text
stringlengths
14
6.51M
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, System.ImageList, FMX.ImgList, FMX.Layouts; type TForm2 = class(TForm) TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; TabItem5: TTabItem; TabItem6: TTabItem; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Rectangle1: TRectangle; ImageList1: TImageList; Layout1: TLayout; Button1: TButton; Button2: TButton; Button3: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} uses FMX.Helpers; procedure TForm2.Button1Click(Sender: TObject); var R :TRectangle; begin R := TRectangle.Create(Self); Layout1.AnimaCard(R); end; procedure TForm2.Button2Click(Sender: TObject); var R :TRectangle; begin R := TRectangle.Create(Self); Layout1.AnimaCard(R,'left'); end; procedure TForm2.Button3Click(Sender: TObject); var R :TRectangle; begin R := TRectangle.Create(Self); Layout1.AnimaCard(R,''); end; procedure TForm2.FormCreate(Sender: TObject); begin ImageList := ImageList1; TabControl1.BarButtons(TAlignLayout.Bottom); end; end.
unit uGlobal; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, ExtCtrls, Graphics, Forms; const LIVE_DATA = './data/live/'; IN_DATA = './data/in/'; OUT_DATA = './data/out/'; type TImageArray = array of TImage; TWordList = array of String; function HexToColor(WebColor: string): TColor; procedure AnchorToParent(var Obj: TControl; Anc: TAnchors); function CardBorder(WC: TWinControl; Kind: String): TImageArray; function ImageBorder(WC: TWinControl; Kind: String): TImageArray; function DSV(Text, Delimiter: String): TWordList; function CSV(Text: String): TWordList; function PSV(Text: String): TWordList; function PartitionWords(Text: String): TWordList; function Basename(Path: String): String; implementation uses FileUtil; function Basename(Path: String): String; begin Result := ExtractFileNameWithoutExt(ExtractFileName(Path)); end; function PartitionWords(Text: String): TWordList; var L: TWordList; K: Integer; Word: String; begin SetLength(L, 0); Word:= ''; for K:= 1 to Length(Text) do begin Word:= Word + Text[K]; if ((Text[K] = ' ') or (Text[K] = '.') or (Text[K] = ',') or (Text[K] = ';')) then begin SetLength(L, Length(L) + 1); L[Length(L) - 1]:= Word; Word:= ''; end; end; SetLength(L, Length(L) + 1); L[Length(L) - 1]:= Word; Result:= L; end; function DSV(Text, Delimiter: String): TWordList; var L: TWordList; K: Integer; Word: String; begin SetLength(L, 0); Word:= ''; for K:= 1 to Length(Text) do begin if not (Text[K] = Delimiter) then Word:= Word + Text[K] else begin SetLength(L, Length(L) + 1); L[Length(L) - 1]:= Word; Word:= ''; end; end; SetLength(L, Length(L) + 1); L[Length(L) - 1]:= Word; Result:= L; end; function CSV(Text: String): TWordList; begin Result := DSV(Text, ','); end; function PSV(Text: String): TWordList; begin Result := DSV(Text, '|'); end; function CardBorder(WC: TWinControl; Kind: String): TImageArray; var Border: array of TImage; Path: String; k: Integer; begin SetLength(Border, 8); for k := 0 to 7 do begin Border[k] := TImage.Create(Nil); with Border[k] do begin Parent := WC; Width := 4; Height := 4; Stretch := True; if k > 4 then Path := './src/icons/card_' + k.ToString + Kind + '.png' else Path := './src/icons/card_' + k.ToString + '.png'; Picture.LoadFromFile(Path); case k of 0: begin AnchorToParent(TControl(Border[k]), [akLeft, akTop, akRight]); BorderSpacing.Left := 4; BorderSpacing.Right := 4; end; 1: begin AnchorToParent(TControl(Border[k]), [akTop, akRight]); end; 2: begin AnchorToParent(TControl(Border[k]), [akBottom, akTop, akRight]); BorderSpacing.Top := 4; BorderSpacing.Bottom := 4; end; 3: begin AnchorToParent(TControl(Border[k]), [akBottom, akRight]); end; 4: begin AnchorToParent(TControl(Border[k]), [akLeft, akBottom, akRight]); BorderSpacing.Left := 4; BorderSpacing.Right := 4; end; 5: begin AnchorToParent(TControl(Border[k]), [akBottom, akLeft]); end; 6: begin AnchorToParent(TControl(Border[k]), [akBottom, akTop, akLeft]); BorderSpacing.Top := 4; BorderSpacing.Bottom := 4; end; 7: begin AnchorToParent(TControl(Border[k]), [akTop, akLeft]); end; end; end; end; Result := Border; end; function ImageBorder(WC: TWinControl; Kind: String): TImageArray; var Border: array of TImage; Path: String; k: Integer; begin SetLength(Border, 8); for k := 0 to 7 do begin Border[k] := TImage.Create(Nil); with Border[k] do begin Parent := WC; Width := 4; Height := 4; Stretch := True; Path := './src/icons/' + Kind + '_' + k.ToString + '.png'; Picture.LoadFromFile(Path); case k of 0: begin AnchorToParent(TControl(Border[k]), [akLeft, akTop, akRight]); BorderSpacing.Left := 4; BorderSpacing.Right := 4; end; 1: begin AnchorToParent(TControl(Border[k]), [akTop, akRight]); end; 2: begin AnchorToParent(TControl(Border[k]), [akBottom, akTop, akRight]); BorderSpacing.Top := 4; BorderSpacing.Bottom := 4; end; 3: begin AnchorToParent(TControl(Border[k]), [akBottom, akRight]); end; 4: begin AnchorToParent(TControl(Border[k]), [akLeft, akBottom, akRight]); BorderSpacing.Left := 4; BorderSpacing.Right := 4; end; 5: begin AnchorToParent(TControl(Border[k]), [akBottom, akLeft]); end; 6: begin AnchorToParent(TControl(Border[k]), [akBottom, akTop, akLeft]); BorderSpacing.Top := 4; BorderSpacing.Bottom := 4; end; 7: begin AnchorToParent(TControl(Border[k]), [akTop, akLeft]); end; end; end; end; Result := Border; end; function RGB(r, g, b: Byte): TColor; begin Result:= (Integer(r) or (Integer(g) shl 8) or (Integer(b) shl 16)); end; function HexToColor(WebColor: string): TColor; begin if (Length(WebColor) <> 7) then Result:= clWhite else if (WebColor[1] <> '#') then Result:= clWhite else Result:= RGB( StrToInt('$' + Copy(WebColor, 2, 2)), StrToInt('$' + Copy(WebColor, 4, 2)), StrToInt('$' + Copy(WebColor, 6, 2)) ); end; procedure AnchorToParent(var Obj: TControl; Anc: TAnchors); begin with Obj do begin Anchors:= Anc; if akLeft in Anc then begin AnchorSide[akLeft].Side:= asrLeft; AnchorSide[akLeft].Control:= Parent; end; if akTop in Anc then begin AnchorSide[akTop].Side:= asrTop; AnchorSide[akTop].Control:= Parent; end; if akBottom in Anc then begin AnchorSide[akBottom].Side:= asrBottom; AnchorSide[akBottom].Control:= Parent; end; if akRight in Anc then begin AnchorSide[akRight].Side:= asrRight; AnchorSide[akRight].Control:= Parent; end; end; end; end.
unit UnitHelp; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DmMemo, ExtCtrls, Menus, clipbrd, Dmitry.Controls.ImButton, Dmitry.Graphics.Types, uMemory, uThemesUtils, uTranslate, Types; type TCanHelpCloseProcedure = procedure(Sender: TObject; var CanClose: Boolean) of object; type THelpPopup = class(TForm) MemText: TDmMemo; ImbClose: TImButton; DestroyTimer: TTimer; ImbNext: TImButton; Label1: TLabel; PmCopy: TPopupMenu; Copy1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure ColorFill(var image : tbitmap); procedure ImbCloseClick(Sender: TObject); procedure SetPos(P : TPoint); procedure ReCreateRGN; procedure DestroyTimerTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDeactivate(Sender: TObject); procedure ImbNextClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Copy1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); private FActivePoint: TPoint; FText: TStrings; FSimpleText : String; Bitmap : TBitmap; Dw, Dh: Integer; FNextButtonVisible: Boolean; FCallBack: TNotifyEvent; FNextText: String; FOnHelpClose: TNotifyEvent; FCanHelpClose: TCanHelpCloseProcedure; FOnCanCloseMessage : Boolean; FHelpCaption: String; procedure SetActivePoint(const Value: TPoint); procedure SetText(const Value: String); procedure SetNextButtonVisible(const Value: Boolean); procedure SetCallBack(const Value: TNotifyEvent); procedure SetNextText(const Value: String); procedure SetOnHelpClose(const Value: TNotifyEvent); procedure SetCanHelpClose(const Value: TCanHelpCloseProcedure); procedure SetHelpCaption(const Value: String); { Private declarations } public property ActivePoint: TPoint read FActivePoint write SetActivePoint; property HelpText: string read FSimpleText write SetText; property NextButtonVisible: Boolean read FNextButtonVisible write SetNextButtonVisible; property CallBack: TNotifyEvent read FCallBack write SetCallBack; property OnHelpClose: TNotifyEvent read FOnHelpClose write SetOnHelpClose; property NextText: string read FNextText write SetNextText; property CanHelpClose: TCanHelpCloseProcedure read FCanHelpClose write SetCanHelpClose; property HelpCaption: string read FHelpCaption write SetHelpCaption; procedure Refresh; procedure DoDelp(HelpMessage: string; Point: TPoint); { Public declarations } end; procedure DoHelpHint(Caption, HelpText: string; MyPoint: TPoint; Control: TControl); procedure DoHelpHintCallBack(Caption, HelpText: string; MyPoint: TPoint; Control: TControl; CallBack: TNotifyEvent; Text: string); procedure DoHelpHintCallBackOnCanClose(Caption, HelpText: string; MyPoint: TPoint; Control: TControl; CallBack: TNotifyEvent; Text: string; OnCanClose: TCanHelpCloseProcedure); implementation {$R *.dfm} procedure DoHelpHint(Caption, HelpText: string; MyPoint: TPoint; Control: TControl); var HelpPopup: THelpPopup; begin Application.CreateForm(THelpPopup, HelpPopup); HelpPopup.NextButtonVisible := False; HelpPopup.HelpCaption := Caption; if Control <> nil then MyPoint := Control.ClientToScreen(Point(Control.ClientWidth div 2, Control.Clientheight div 2)); HelpPopup.DoDelp(HelpText, MyPoint); end; procedure DoHelpHintCallBack(Caption, HelpText: string; MyPoint: TPoint; Control: TControl; CallBack: TNotifyEvent; Text: string); var HelpPopup: THelpPopup; begin Application.CreateForm(THelpPopup, HelpPopup); HelpPopup.NextButtonVisible := True; HelpPopup.NextText := Text; HelpPopup.CallBack := CallBack; HelpPopup.HelpCaption := Caption; if Control <> nil then MyPoint := Control.ClientToScreen(Point(Control.ClientWidth div 2, Control.Clientheight div 2)); HelpPopup.DoDelp(HelpText, MyPoint); end; procedure DoHelpHintCallBackOnCanClose(Caption, HelpText: string; MyPoint: TPoint; Control: TControl; CallBack: TNotifyEvent; Text: string; OnCanClose: TCanHelpCloseProcedure); var HelpPopup: THelpPopup; begin Application.CreateForm(THelpPopup, HelpPopup); HelpPopup.NextButtonVisible := True; HelpPopup.NextText := Text; HelpPopup.CallBack := CallBack; HelpPopup.CanHelpClose := OnCanClose; HelpPopup.HelpCaption := Caption; if Control <> nil then MyPoint := Control.ClientToScreen(Point(Control.ClientWidth div 2, Control.Clientheight div 2)); HelpPopup.DoDelp(HelpText, MyPoint); end; function CreateBitmapRgn(Bitmap: TBitmap; TransClr: TColorRef): hRgn; var // bmInfo: TBitmap; //структура BITMAP WinAPI W, H: Integer; // высота и ширина растра BmDIB: HBitmap; // дискрептор независимого растра BmiInfo: BITMAPINFO; // структура BITMAPINFO WinAPI LpBits, LpOldBits: PRGBTriple; // указатели на структуры RGBTRIPLE WinAPI LpData: PRgnData; // указатель на структуру RGNDATA WinAPI X, Y, C, F, I: Integer; // переменные циклов Buf: Pointer; // указатель BufSize: Integer; // размер указателя RdhInfo: TRgnDataHeader; // структура RGNDATAHEADER WinAPI LpRect: PRect; // указатель на TRect (RECT WinAPI) MemDC: HDC; begin Result := 0; if Bitmap = nil then Exit; // если растр не задан, выходим // GetObject(Bitmap, SizeOf(bmInfo), @bmInfo); //узнаем размеры растра W := Bitmap.Width; // используя структуру BITMAP H := Bitmap.Height; I := (W * 3) - ((W * 3) div 4) * 4; // определяем смещение в байтах if I <> 0 then I := 4 - I; // Пояснение: растр Windows Bitmap читается снизу вверх, причем каждая строка // дополняется нулевыми байтами до ее кратности 4. // для 32-х битный растров такой сдвиг делать не надо. // заполняем BITMAPINFO для передачи в CreateDIBSection MemDC := CreateCompatibleDC(0); bmiInfo.bmiHeader.biWidth := W; //ширина bmiInfo.bmiHeader.biHeight := H; //высота bmiInfo.bmiHeader.biPlanes := 1; //всегда 1 bmiInfo.bmiHeader.biBitCount := 24; //три байта на пиксель bmiInfo.bmiHeader.biCompression := BI_RGB; //без компрессии BmiInfo.BmiHeader.BiSizeImage := 0; // размер не знаем, ставим в ноль BmiInfo.BmiHeader.BiXPelsPerMeter := 2834; // пикселей на метр, гор. BmiInfo.BmiHeader.BiYPelsPerMeter := 2834; // пикселей на метр, верт. BmiInfo.BmiHeader.BiClrUsed := 0; // палитры нет, все в ноль BmiInfo.BmiHeader.BiClrImportant := 0; // то же BmiInfo.BmiHeader.BiSize := SizeOf(BmiInfo.BmiHeader); // размер структруы BmDIB := CreateDIBSection(MemDC, BmiInfo, DIB_RGB_COLORS, Pointer(LpBits), 0, 0); // создаем независимый растр WxHx24, без палитры, в указателе lpBits получаем // адрес первого байта этого растра. bmDIB - дискрептор растра // заполняем первые шесть членов BITMAPINFO для передачи в GetDIBits BmiInfo.BmiHeader.BiWidth := W; // ширина BmiInfo.BmiHeader.BiHeight := H; // высота BmiInfo.BmiHeader.BiPlanes := 1; // всегда 1 BmiInfo.BmiHeader.BiBitCount := 24; // три байта на пиксель BmiInfo.BmiHeader.BiCompression := BI_RGB; // без компресси BmiInfo.BmiHeader.BiSize := SizeOf(BmiInfo.BmiHeader); // размер структуры GetDIBits(MemDC, Bitmap.Handle, 0, H - 1, LpBits, BmiInfo, DIB_RGB_COLORS); // конвертируем исходный растр в наш с его копированием по адресу lpBits LpOldBits := LpBits; // запоминаем адрес lpBits // первый проход - подсчитываем число прямоугольников, необходимых для // создания региона C := 0; // сначала ноль for Y := H - 1 downto 0 do // проход снизу вверх begin X := 0; while X < W do // от 0 до ширины-1 begin // пропускаем прзрачный цвет, увеличивая координату и указатель while (RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) = TransClr) and (X < W) do begin Inc(LpBits); X := X + 1; end; // если нашли не прозрачный цвет, то считаем, сколько точек в ряду он идет if RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) <> TransClr then begin while (RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) <> TransClr) and (X < W) do begin Inc(LpBits); X := X + 1; end; C := C + 1; // увиличиваем счетчик прямоугольников end; end; // ряд закончился, необходимо увеличить указатель до кратности 4 PChar(LpBits) := PChar(LpBits) + I; end; LpBits := LpOldBits; // восстанавливаем значение lpBits // Заполняем структуру RGNDATAHEADER RdhInfo.IType := RDH_RECTANGLES; // будем использовать прямоугольники RdhInfo.NCount := C; // их количество RdhInfo.NRgnSize := 0; // размер выделяем памяти не знаем RdhInfo.RcBound := Rect(0, 0, W, H); // размер региона RdhInfo.DwSize := SizeOf(RdhInfo); // размер структуры // выделяем память для струтуры RGNDATA: // сумма RGNDATAHEADER и необходимых на прямоугольников BufSize := SizeOf(RdhInfo) + SizeOf(TRect) * C; GetMem(Buf, BufSize); LpData := Buf; // ставим указатель на выделенную память LpData.Rdh := RdhInfo; // заносим в память RGNDATAHEADER // Заполдяенм память прямоугольниками LpRect := @LpData.Buffer; // первый прямоугольник for Y := H - 1 downto 0 do begin X := 0; while X < W do begin while (RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) = TransClr) and (X < W) do begin Inc(LpBits); X := X + 1; end; if RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) <> TransClr then begin F := X; while (RGB(LpBits.RgbtRed, LpBits.RgbtGreen, LpBits.RgbtBlue) <> TransClr) and (X < W) do begin Inc(LpBits); X := X + 1; end; LpRect^ := Rect(F, Y - 1, X, Y); // заносим координаты Inc(LpRect); // переходим к следующему end; end; PChar(LpBits) := PChar(LpBits) + I; end; // после окночания заполнения структуры RGNDATA можно создавать регион. // трансформации нам не нужны, ставим в nil, указываем размер // созданной структуры и ее саму. Result := ExtCreateRegion(nil, BufSize, LpData^); // создаем регион FreeMem(Buf, BufSize); // теперь структура RGNDATA больше не нужна, удаляем DeleteObject(BmDIB); // созданный растр тоже удаляем end; function BitmapToRegion(HBmp: TBitmap; TransColor: TColor): HRGN; begin Result := CreateBitmapRgn(HBmp, TransColor); end; procedure THelpPopup.ColorFill(var Image: TBitmap); var I, J: Integer; P: PARGB; begin for I := 0 to Image.Height - 1 do begin P := Image.ScanLine[I]; for J := 0 to Image.Width - 1 do begin P[J].B := P[J].B div 2; P[J].R := P[J].R div 2 + 128; P[J].G := P[J].G div 2 + 128; end; end; end; procedure THelpPopup.DoDelp(HelpMessage: string; Point: TPoint); begin HelpText := HelpMessage; ActivePoint := Point; Show; Refresh; end; procedure THelpPopup.FormCreate(Sender: TObject); begin Color := Theme.HighlightColor; MemText.Color := Theme.HighlightColor; MemText.Font.Color := Theme.HighlightTextColor; ImbClose.Color := Theme.HighlightColor; Copy1.Caption := TA('Copy', 'Help'); FCallBack := nil; FOnCanCloseMessage := True; FNextButtonVisible := False; FText := TStringList.Create; ImbClose.Filter := ColorFill; ImbClose.Refresh; Bitmap := TBitmap.Create; Bitmap.PixelFormat := Pf24bit; Dh := 100; Dw := 220; FOnHelpClose := nil; ImbNext.Filter := ColorFill; ImbNext.Refresh; ImbNext.Caption := 'Ok'; ImbNext.ShowCaption := False; end; procedure THelpPopup.FormPaint(Sender: TObject); begin Canvas.Draw(0, -1, Bitmap); end; procedure THelpPopup.ImbCloseClick(Sender: TObject); begin Close; end; procedure THelpPopup.ReCreateRGN; var RGN: HRGN; Dx, Dy: Integer; PP: array [0 .. 3] of TPoint; HintColor: TColor; begin HintColor := Theme.HighlightColor; //$00FFFF Bitmap.Width := Width; Bitmap.Height := Height; Bitmap.Canvas.Brush.Color := $FFFFFF; Bitmap.Canvas.Pen.Color := $FFFFFF; Bitmap.Canvas.Rectangle(0, 0, Bitmap.Width, Bitmap.Height); Bitmap.Canvas.Brush.Color := HintColor; Bitmap.Canvas.Pen.Color := $0; Dx := 50; Dy := 50; Bitmap.Canvas.RoundRect(0+dx,0+dy,dw+dx,dh+dy,10,10); if (Left-FActivePoint.X>=0) and (Top-FActivePoint.y>=0) then begin PP[0]:=Point(dx+20,dy); PP[1]:=Point(dx+40,dy); PP[2]:=Point(0, 0); PP[3] := Point(Dx + 20, Dy); Bitmap.Canvas.Polygon(PP); Bitmap.Canvas.Brush.Color := HintColor; Bitmap.Canvas.Pen.Color := HintColor; Bitmap.Canvas.MoveTo(Dx + 20, Dy); Bitmap.Canvas.LineTo(Dx + 40, Dy); end; if (Left - FActivePoint.X >= 0) and (Top-FActivePoint.y<0) then begin PP[0]:=Point(dx+20,dy+dh-1); PP[1]:=Point(dx+40,dy+dh-1); PP[2]:=Point(0, Height - 1); PP[3] := Point(Dx + 20, Dy + Dh - 1); Bitmap.Canvas.Polygon(PP); Bitmap.Canvas.Brush.Color := HintColor; Bitmap.Canvas.Pen.Color := HintColor; Bitmap.Canvas.MoveTo(Dx + 20, Dy + Dh - 1); Bitmap.Canvas.LineTo(Dx + 40, Dy + Dh - 1); end; if (Left - FActivePoint.X < 0) and (Top - FActivePoint.Y < 0) then begin PP[0] := Point(Dx - 20 + Dw, Dy + Dh - 1); PP[1] := Point(Dx - 40 + Dw, Dy + Dh - 1); PP[2] := Point(Width - 1, Height - 1); PP[3] := Point(Dx - 20 + Dw, Dy + Dh - 1); Bitmap.Canvas.Polygon(PP); Bitmap.Canvas.Brush.Color:=HintColor; Bitmap.Canvas.Pen.Color:=HintColor; Bitmap.Canvas.MoveTo(dx+dw- 20, Dy + Dh - 1); Bitmap.Canvas.LineTo(Dx + Dw - 40, Dy + Dh - 1); end; if (Left - FActivePoint.X < 0) and (Top - FActivePoint.Y >= 0) then begin PP[0] := Point(Dx - 20 + Dw, Dy); PP[1] := Point(Dx - 40 + Dw, Dy); PP[2] := Point(Width - 1, 0); PP[3] := Point(Dx - 20 + Dw, Dy); Bitmap.Canvas.Polygon(PP); Bitmap.Canvas.Brush.Color := HintColor; Bitmap.Canvas.Pen.Color := HintColor; Bitmap.Canvas.MoveTo(Dx - 20 + Dw, Dy); Bitmap.Canvas.LineTo(Dx - 40 + Dw, Dy); end; RGN := BitmapToRegion(Bitmap, $FFFFFF); SetWindowRGN(Handle, RGN, False); FormPaint(Self); end; procedure THelpPopup.Refresh; begin FormPaint(Self); MemText.Invalidate; end; procedure THelpPopup.SetActivePoint(const Value: TPoint); begin FActivePoint := Value; SetPos(Value); ReCreateRGN; end; procedure THelpPopup.SetPos(P: TPoint); var FTop, FLeft: Integer; begin FTop := P.Y + 1; FLeft := P.X + 1; if FTop + Height > Screen.Height then FTop := P.Y - Height-1; if FLeft+Width>Screen.Width then FLeft := P.X - Width-1; Top:=FTop; Left:=FLeft; end; procedure THelpPopup.SetText(const Value: String); begin FText.Text := Value; MemText.Lines.Assign(FText); MemText.Height := Abs((MemText.Lines.Count + 1 ) * MemText.Font.Height); dh := Abs((MemText.Lines.Count + 1) * MemText.Font.Height) + 10 + ImbClose.Height + 5; ImbNext.Top := MemText.Top + MemText.Height + 3; if ImbNext.Visible then dh := dh + ImbNext.Height + 5; Height := 50 + dh + 50; FSimpleText := Value; end; procedure THelpPopup.DestroyTimerTimer(Sender: TObject); begin DestroyTimer.Enabled := False; Release; end; procedure THelpPopup.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(FOnHelpClose) then FOnHelpClose(self); DestroyTimer.Enabled := True; end; procedure THelpPopup.FormDeactivate(Sender: TObject); begin FOnCanCloseMessage := False; if not DestroyTimer.Enabled then Close; end; procedure THelpPopup.FormDestroy(Sender: TObject); begin F(Bitmap); F(FText); end; procedure THelpPopup.SetNextButtonVisible(const Value: Boolean); begin FNextButtonVisible := Value; ImbNext.Visible:=Value; SetText(HelpText); end; procedure THelpPopup.SetCallBack(const Value: TNotifyEvent); begin FCallBack := Value; end; procedure THelpPopup.ImbNextClick(Sender: TObject); begin FOnCanCloseMessage := False; if Assigned(FCallBack) then FCallBack(Self); Close; end; procedure THelpPopup.SetNextText(const Value: string); begin FNextText := Value; ImbNext.Caption := FNextText; ImbNext.ShowCaption := False; ImbNext.ShowCaption := True; end; procedure THelpPopup.SetOnHelpClose(const Value: TNotifyEvent); begin FOnHelpClose := Value; end; procedure THelpPopup.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if FOnCanCloseMessage then if Assigned(CanHelpClose) then CanHelpClose(Sender, CanClose); end; procedure THelpPopup.SetCanHelpClose(const Value: TCanHelpCloseProcedure); begin FCanHelpClose := Value; end; procedure THelpPopup.SetHelpCaption(const Value: String); begin FHelpCaption := Value; Label1.Caption:=Value; end; procedure THelpPopup.Copy1Click(Sender: TObject); begin ClipBoard.SetTextBuf(PChar(MemText.Text)); end; procedure THelpPopup.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; end.
//============================================================================= // sgAudio.pas //============================================================================= // // The Audio unit is responsible for managing SDL audio for music and sound // effects. This includes initialisation, loading, freeing, playing, and // checking if music or sound is playing. // //============================================================================= /// SwinGame's Audio is responsible for loading and playing music and sound /// effects. The main functionality exists in `LoadMusic`, `PlayMusic`, /// `LoadSoundEffect`, and `PlaySoundEffect`. Associated with these are the /// `Music` and `SoundEffect` types. /// /// @module Audio /// @static /// /// @doc_types SoundEffect, Music unit sgAudio; //============================================================================= interface uses sgTypes; //============================================================================= //---------------------------------------------------------------------------- // Opening and Closing Audio support //---------------------------------------------------------------------------- /// `TryOpenAudio` attempts to open the audio device for SwinGame to use. /// If this fails `TryOpenAudio` returns false to indicate that the audio /// device has not opened correctly and audio cannot be played. /// /// @lib function TryOpenAudio(): Boolean; /// `OpenAudio` is used to initialise the SwinGame audio code. This should be /// called at the start of your programs code, and is usually coded into the /// starting project templates. After initialising the audio code you can /// load and play `Music` using `LoadMusic` and `PlayMusic`, load and play /// `SoundEffect`s using `LoadSoundEffect` and `PlaySoundEffect`. At the end /// of the program you need to call `CloseAudio` to ensure that the audio /// code is correctly terminated. /// /// @lib procedure OpenAudio(); /// `AudioReady` indicates if SwinGame's audio has been opened. Sound effects /// and Music can only be played with the audio is "ready". /// /// @lib function AudioReady(): Boolean; /// `CloseAudio` is used to clean up the resources used by SwinGame audio. If /// `OpenAudio` is called, this must be called to return the resources used /// before the program terminates. /// /// @lib procedure CloseAudio(); //---------------------------------------------------------------------------- // Loading & Releasing Sound Effects //---------------------------------------------------------------------------- /// Loads the `SoundEffect` from the supplied filename. The sound will be loaded /// from the Resources/sounds folder unless a full path to the file is passed /// in. If you are passing in the full path and you want to ensure that your game /// is able to work across multiple platforms correctly then use /// `PathToResource` to get the full path to the files in the projects /// resources folder. /// /// LoadSoundEffect can load wav and ogg audio files. /// /// `FreeSoundEffect` should be called to free the resources used by the /// `SoundEffect` data once the resource is no longer needed. /// /// @param filename the filename of the sound effect file to load. /// /// @lib /// /// @class SoundEffect /// @constructor /// @csn initFromFile:%s function LoadSoundEffect(const filename: String): SoundEffect; /// Loads and returns a sound effect. The supplied ``filename`` is used to /// locate the sound effect to load. The supplied ``name`` indicates the /// name to use to refer to this SoundEffect. The `SoundEffect` can then be /// retrieved by passing this ``name`` to the `SoundEffectNamed` function. /// /// @lib /// @sn loadSoundEffectNamed:%s fromFile:%s /// /// @class SoundEffect /// @constructor /// @csn initWithName:%s fromFile:%s function LoadSoundEffectNamed(const name, filename: String): SoundEffect; /// Determines if SwinGame has a sound effect loaded for the supplied name. /// This checks against all sounds loaded, those loaded without a name /// are assigned the filename as a default /// /// @lib function HasSoundEffect(const name: String): Boolean; /// Returns the `SoundEffect` that has been loaded with the specified name, /// see `LoadSoundEffectNamed`. /// /// @lib function SoundEffectNamed(const name: String): SoundEffect; /// Releases the SwinGame resources associated with the sound effect of the /// specified ``name``. /// /// @lib procedure ReleaseSoundEffect(const name: String); /// Releases all of the sound effects that have been loaded. /// /// @lib procedure ReleaseAllSoundEffects(); /// Frees the resources used by a `SoundEffect` resource. All loaded /// `SoundEffect`s should be freed once they are no longer needed. /// /// @lib /// /// @class SoundEffect /// @dispose procedure FreeSoundEffect(var effect: SoundEffect); //---------------------------------------------------------------------------- // Loading & Releasing Music //---------------------------------------------------------------------------- /// Loads and returns a music value. The supplied ``filename`` is used to /// locate the music file to load. The supplied ``name`` indicates the /// name to use to refer to this Music value. The `Music` can then be /// retrieved by passing this ``name`` to the `MusicNamed` function. /// /// @lib /// @sn loadMusicNamed:%s fromFile:%s /// /// @class Music /// @constructor /// @csn initWithName:%s fromFile:%s function LoadMusicNamed(const name, filename: String): Music; /// Determines if SwinGame has a music value loaded for the supplied name. /// This checks against all music values loaded using `LoadMusicNamed`. /// /// @lib function HasMusic(const name: String): Boolean; /// Returns the `Music` that has been loaded with the specified name. /// This works with music data loaded using `LoadMusicNamed`. /// /// @lib function MusicNamed(const name: String): Music; /// Releases the music that have been loaded with the supplied name. /// /// @lib procedure ReleaseMusic(const name: String); /// Releases all of the music data that have been loaded. /// /// @lib procedure ReleaseAllMusic(); /// Loads the `Music` from the supplied filename. The music will be loaded /// from the Resources/sounds folder unless a full path to the file is passed /// in. If you are passing in the full path and you want toensure that your game /// is able to work across multiple platforms correctly ensure that you use /// `PathToResource` to get the full path to the files in the projects /// resources folder. /// /// LoadMusic can load mp3, wav and ogg audio files. /// /// `FreeMusic` should be called to free the resources used by the /// `Music` data once the resource is no longer needed. /// /// @param filename the filename to the music file to load. /// /// @lib /// /// @class Music /// @constructor /// @csn initFromFile:%s function LoadMusic(const filename: String): Music; /// Frees the resources used by a `Music` resource. All loaded /// `Music` should be freed once it is no longer needed. /// /// @lib /// /// @class Music /// @dispose procedure FreeMusic(var mus: Music); //---------------------------------------------------------------------------- // Playing Sound Effects //---------------------------------------------------------------------------- /// There are several versions of PlaySoundEffect that can be used to control /// the way the sound effect plays, allowing you to control its volume and /// the number of times the code loops. In all cases the started sound effect /// is mixed with the currently playing sound effects and music. /// /// With this version of PlaySoundEffect, the started sound effect will be /// played at full volume. /// /// @param effect The effect indicates which sound effect to start playing. This /// effect is played once at its full volume. /// /// @lib PlaySoundEffectWithLoopAndVolume(effect,1,1.0) /// @uname PlaySoundEffect /// /// @class SoundEffect /// @method Play /// /// @doc_idx 1 procedure PlaySoundEffect(effect: SoundEffect); overload; /// This version of PlaySoundEffect allows you to indicate the number of times /// the sound effect is repeated. Setting the loops parameter to -1 will cause /// the sound effect to be looped infinitely, setting it to a value larger than /// 0 plays the sound effect the number of times indicated, calling with a /// value of 0 means the sound effect is not played. /// /// @param effect The effect indicates which sound effect to start playing. This /// effect is played once at its full volume. /// /// @param loops Controls the number of times the sound effect is played. -1 /// means the sound effect is repeated infinitely. /// /// @lib PlaySoundEffectWithLoopAndVolume(effect, loops, 1.0) /// @uname PlaySoundEffectWithLoop /// @sn playSoundEffect:%s looped:%s /// /// @class SoundEffect /// @overload Play PlayWithLoops /// @csn playLooped:%s /// /// @doc_details procedure PlaySoundEffect(effect: SoundEffect; loops: Longint); overload; /// This version of PlaySoundEffect allows you to control the volume of the /// sounds playback. The vol parameter will take a value between 0 and 1 /// indicating the percentage of full volume to play at. /// For example, 0.1 plays the sound effect at 10% of its original volume. /// /// @param effect The effect indicates which sound effect to start playing. /// @param vol Indicates the percentage of the original volume to play the /// `SoundEffect` at. This must be between 0 and 1. /// /// @lib PlaySoundEffectWithLoopAndVolume(effect, 1, vol) /// @uname PlaySoundEffectWithVolume /// @sn playSoundEffect:%s atVolume:%s /// @version 2.1 /// /// @class SoundEffect /// @overload Play PlayWithVolume /// @csn playVolume:%s /// /// @doc_details procedure PlaySoundEffect(effect: SoundEffect; vol: Single); overload; /// This version of PlaySoundEffect allows you to control both the number /// of times the `SoundEffect` is repeated, and its playback volume. /// /// @param effect The effect indicates which sound effect to start playing. /// @param loops Controls the number of times the sound effect is played. /// @param vol Indicates the percentage of the original volume to play the /// `SoundEffect` at. This must be between 0 and 1. /// /// @lib PlaySoundEffectWithLoopAndVolume /// @sn playSoundEffect:%s looped:%s atVolume:%s /// @version 2.0 /// /// @class SoundEffect /// @overload Play PlayWithLoopsAndVolume /// @csn playLooped:%s vol:%s /// /// @doc_details procedure PlaySoundEffect(effect: SoundEffect; loops: Longint; vol: Single); overload; /// This version of PlaySoundEffect allows you to control both the number /// of times the `SoundEffect` is repeated, and its playback volume. /// /// @param name The name of the sound effect to start playing. /// @param loops Controls the number of times the sound effect is played. /// @param vol Indicates the percentage of the original volume to play the /// `SoundEffect` at. This must be between 0 and 1. /// /// @lib PlaySoundEffectNamedWithLoopAndVolume /// @sn playSoundEffectNamed:%s looped:%s atVolume:%s /// /// @doc_details procedure PlaySoundEffect(const name: String; loops: Longint; vol: Single); overload; /// This version of PlaySoundEffect allows you to indicate the number of times /// the sound effect is repeated. Setting the loops parameter to -1 will cause /// the sound effect to be looped infinitely, setting it to a value larger than /// 0 plays the sound effect the number of times indicated, calling with a /// value of 0 means the sound effect is not played. /// /// @param name The name of the sound effect to start playing. /// /// @param loops Controls the number of times the sound effect is played. -1 /// means the sound effect is repeated infinitely. /// /// @lib PlaySoundEffectNamedWithLoopAndVolume(name, loops, 1.0) /// @uname PlaySoundEffectNamedWithLoop /// @sn playSoundEffectNamed:%s looped:%s /// /// @doc_details procedure PlaySoundEffect(const name: String; loops: Longint); overload; /// There are several versions of PlaySoundEffect that can be used to control /// the way the sound effect plays, allowing you to control its volume and /// the number of times the code loops. In all cases the started sound effect /// is mixed with the currently playing sound effects and music. /// /// With this version of PlaySoundEffect, the started sound effect will be /// played at full volume. /// /// @param name The name of the sound effect to play /// /// @lib PlaySoundEffectNamedWithLoopAndVolume(name,1,1.0) /// @uname PlaySoundEffectNamed procedure PlaySoundEffect(const name: String); overload; /// This version of PlaySoundEffect allows you to control the volume of the /// sounds playback. The vol parameter will take a value between 0 and 1 /// indicating the percentage of full volume to play at. /// For example, 0.1 plays the sound effect at 10% of its original volume. /// /// @param name The name of the sound effect to play. /// @param vol Indicates the percentage of the original volume to play the /// `SoundEffect` at. This must be between 0 and 1. /// /// @lib PlaySoundEffectNamedWithLoopAndVolume(name, 1, vol) /// @uname PlaySoundEffectNamedWithVolume /// @sn playSoundEffectNamed:%s atVolume:%s /// /// @doc_details procedure PlaySoundEffect(const name: String; vol: Single); overload; //---------------------------------------------------------------------------- // Playing Music //---------------------------------------------------------------------------- /// PlayMusic starts playing a `Music` resource. SwinGame only allows one /// music resource to be played at a time. Starting to play a new music /// resource will stop the currently playing music track. You can also stop /// the music by calling `StopMusic`. /// /// By default SwinGame starts playing music at its full volume. This can be /// controlled by calling `SetMusicVolume`. The current volume can be checked /// with `MusicVolume`. /// /// To test if a `Music` resource is currently playing you can use the /// `MusicPlaying` function. /// /// This version of PlayMusic can be used to play background music that is /// looped infinitely. The currently playing music is stopped and the new /// music resource will start playing, and will repeat until `StopMusic` is /// called, or another resource is played. /// /// @param mus The `Music` resource to play. /// /// @lib PlayMusicWithLoops(mus, -1) /// @uname PlayMusic /// /// @class Music /// @method Play procedure PlayMusic(mus: Music); overload; /// This version of PlayMusic allows you to control the number of times the /// `Music` resource is repeated. It starts playing the supplied `Music` /// resource, repeating it the numder of times specified in the loops /// parameter. Setting loops to -1 repeats the music infinitely, other values /// larger than 0 indicate the number of times that the music should be /// played. /// /// @param mus The `Music` resource to be played. /// @param loops The number of times that the music should be played, -1 for /// repeat infinitely /// /// @lib PlayMusicWithLoops /// @sn playMusic:%s looped:%s /// /// @class Music /// @overload Play PlayWithLoops procedure PlayMusic(mus: Music; loops: Longint); overload; /// Fades the music in over a number of milliseconds, and then continues to /// play the music repeatedly until the program ends or the music is stopped. /// The music fades from 0 volume up to the currently set music volume. /// /// @param mus The `Music` resource to be played. /// @param ms The number of milliseconds over which to fade the music in to // the current music volume. /// /// @lib FadeMusicIn /// @sn playMusic:%s fadeIn:%s /// /// @class Music /// @method FadeIn /// @csn playFadeIn:%s procedure FadeMusicIn(mus: Music; ms: Longint); overload; /// This version of FadeMusicIn fades the music in then plays the 'Music' /// for a given number of loops.Setting loops to -1 repeats the music /// infinitely, other values larger than 0 indicate the number of times that /// the music should be played. /// /// @param mus The `Music` resource to be played. /// @param loops The number of times that the music should be played, -1 for /// repeat infinitely /// @param ms The number of milliseconds over which to fade the music in to /// the current music volume. /// /// @lib FadeMusicInWithLoops /// @sn playMusic:%s looped:%s fadeIn:%s /// /// @class Music /// @overload FadeIn FadeInWithLoops /// @csn playLooped:%s fadeIn:%s procedure FadeMusicIn(mus: Music; loops, ms: Longint); overload; /// This version of PlayMusic allows you to control the number of times the /// `Music` resource is repeated. It starts playing the supplied `Music` /// resource, repeating it the numder of times specified in the loops /// parameter. Setting loops to -1 repeats the music infinitely, other values /// larger than 0 indicate the number of times that the music should be /// played. /// /// @param name The name of the `Music` resource to be played. /// @param loops The number of times that the music should be played, -1 for /// repeat infinitely /// /// @lib PlayMusicNamedWithLoops /// @sn playMusicNamed:%s looped:%s procedure PlayMusic(const name: String; loops: Longint); overload; /// PlayMusic starts playing a `Music` resource. SwinGame only allows one /// music resource to be played at a time. Starting to play a new music /// resource will stop the currently playing music track. You can also stop /// the music by calling `StopMusic`. /// /// By default SwinGame starts playing music at its full volume. This can be /// controlled by calling `SetMusicVolume`. The current volume can be checked /// with `MusicVolume`. /// /// To test if a `Music` resource is currently playing you can use the /// `MusicPlaying` function. /// /// This version of PlayMusic can be used to play background music that is /// looped infinitely. The currently playing music is stopped and the new /// music resource will start playing, and will repeat until `StopMusic` is /// called, or another resource is played. /// /// @param name The name of the `Music` resource to play. /// /// @lib PlayMusicNamedWithLoops(name, -1) /// @uname PlayMusicNamed procedure PlayMusic(const name: String); overload; /// This version of FadeMusicIn fades the music in then plays the 'Music' /// for a given number of loops.Setting loops to -1 repeats the music /// infinitely, other values larger than 0 indicate the number of times that /// the music should be played. /// /// @param name The name of the `Music` resource to be played. /// @param loops The number of times that the music should be played, -1 for /// repeat infinitely /// @param ms The number of milliseconds over which to fade the music in to /// the current music volume. /// /// @lib FadeMusicNamedInWithLoops /// @sn playMusicNamed:%s looped:%s fadeIn:%s procedure FadeMusicIn(const name: String; loops, ms: Longint); overload; /// Fades the music in over a number of milliseconds, and then continues to /// play the music repeatedly until the program ends or the music is stopped. /// The music fades from 0 volume up to the currently set music volume. /// /// @param name The name of the `Music` resource to be played. /// @param ms The number of milliseconds over which to fade the music in to // the current music volume. /// /// @lib FadeMusicNamedIn /// @sn playMusicNamed:%s fadeIn:%s procedure FadeMusicIn(const name: String; ms: Longint); overload; /// Pauses the currently playing music. See `ResumeMusic`. /// /// @lib procedure PauseMusic(); /// Resume currently paused music. See `PauseMusic`. /// /// @lib procedure ResumeMusic(); //---------------------------------------------------------------------------- // Query music //---------------------------------------------------------------------------- /// This procedure allows you to set the volume of the currently playing /// music. The vol parameter indicates the percentage of the original volume, /// for example, 0.1 sets the playback volume to 10% of its full volume. /// /// @param value Indicates the percentage of the original volume to play the /// `Music` at. This must be between 0 and 1, e.g. 0.1 is 10%. /// /// @lib SetMusicVolume /// /// @class Music /// @static /// @setter Volume procedure SetMusicVolume(value: Single); /// This function returns the current volume of the music. This will be a /// value between 0 and 1, with 1 indicating 100% of the `Music` resources /// volume. /// /// @returns The volume of the currently playing music. /// /// @lib MusicVolume /// /// @class Music /// @static /// @getter Volume function MusicVolume(): Single; /// This function indicates if music is currently playing. As only one music /// resource can be playing at a time this does not need to be told which /// music resource to check for. /// /// @returns true if the music is playing /// /// @lib MusicPlaying /// /// @class Music /// @static /// @method IsPlaying function MusicPlaying(): Boolean; /// Returns the name that SwinGame uses to refer to this music data. This /// name can be used to fetch and release this music resource. /// /// @lib /// /// @class Music /// @getter Name function MusicName(mus: Music): String; /// Returns the filename that SwinGame uses to load to this music data. /// /// @lib /// /// @class Music /// @getter Filename function MusicFilename(mus: Music): String; //---------------------------------------------------------------------------- // Query Sound Effects //---------------------------------------------------------------------------- /// This function can be used to check if a sound effect is currently /// playing. /// /// @param effect The sound effect to check. /// @returns true if the effect `SoundEffect` is playing. /// /// @lib SoundEffectPlaying /// /// @class SoundEffect /// @method IsPlaying function SoundEffectPlaying(effect: SoundEffect): Boolean; overload; /// This function can be used to check if a sound effect is currently /// playing. /// /// @param name The name of the sound effect to check. /// @returns true if the effect `SoundEffect` is playing. /// /// @lib SoundEffectNamedPlaying function SoundEffectPlaying(const name: String): Boolean; overload; /// Returns the name that SwinGame uses to refer to this sound effect. This /// name can be used to fetch and release this sound effect resource. /// /// @lib /// /// @class SoundEffect /// @getter Name function SoundEffectName(effect: SoundEffect): String; /// Returns the filename that SwinGame used to load to this sound effect. /// /// @lib /// /// @class SoundEffect /// @getter Filename function SoundEffectFilename(effect: SoundEffect): String; //---------------------------------------------------------------------------- // Stop Music & Sound Effects //---------------------------------------------------------------------------- /// Stops all occurances of the effect `SoundEffect` that is currently playing. /// /// @param effect The sound to stop. /// /// @lib StopSoundEffect /// /// @class SoundEffect /// @method Stop procedure StopSoundEffect(effect: SoundEffect); /// Stops all occurances of the named `SoundEffect` that are currently playing. /// /// @param name The name of the sound effect to stop. /// /// @lib StopSoundEffectNamed procedure StopSoundEffect(const name: String); /// Stops playing the current music resource. /// /// @lib StopMusic /// /// @class Music /// @static /// @method Stop procedure StopMusic(); /// Fades the currently playing music out over a number of milli seconds. /// /// @param ms The number of milliseconds over which to fade the music to 0 volume. /// /// @lib FadeMusicOut /// /// @class Music /// @static /// @method FadeOut procedure FadeMusicOut(ms: Longint); //============================================================================= implementation uses SysUtils, Classes, stringhash, // libsrc sgShared, sgResources, sgTrace, sgDriverAudio, sgBackendTypes; //============================================================================= var _SoundEffects: TStringHash; _Music: TStringHash; _firstLoad: Boolean = false; function TryOpenAudio(): Boolean; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'TryOpenAudio', ''); {$ENDIF} sgShared.AudioOpen := AudioDriver.OpenAudio(); result := sgShared.AudioOpen; {$IFDEF TRACE} TraceExit('sgAudio', 'TryOpenAudio', BoolToStr(result, true)); {$ENDIF} end; procedure OpenAudio(); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'OpenAudio', ''); {$ENDIF} if not TryOpenAudio() then RaiseException('Error opening audio device: ' + string(AudioDriver.GetError())); {$IFDEF TRACE} TraceExit('sgAudio', 'OpenAudio'); {$ENDIF} end; function AudioReady(): Boolean; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'AudioReady', ''); {$ENDIF} if not _firstLoad then begin OpenAudio(); _firstLoad := true; end; result := sgShared.AudioOpen; {$IFDEF TRACE} TraceExit('sgAudio', 'AudioReady', BoolToStr(result, true)); {$ENDIF} end; procedure CloseAudio(); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'CloseAudio', ''); {$ENDIF} AudioOpen := False; AudioDriver.CloseAudio(); {$IFDEF TRACE} TraceExit('sgAudio', 'CloseAudio'); {$ENDIF} end; procedure SetMusicVolume(value: Single); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'SetMusicVolume', FloatToStr(value)); {$ENDIF} if (value < 0) then value := 0 else if value > 1 then value := 1; AudioDriver.SetMusicVolume(value); {$IFDEF TRACE} TraceExit('sgAudio', 'SetMusicVolume'); {$ENDIF} end; function MusicVolume(): Single; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'MusicVolume', ''); {$ENDIF} result := AudioDriver.GetMusicVolume(); {$IFDEF TRACE} TraceExit('sgAudio', 'MusicVolume', FloatToStr(result)); {$ENDIF} end; //---------------------------------------------------------------------------- // Private: // Called by LoadSoundEffectNamed function DoLoadSoundEffect(const filename, name: String): SoundEffect; var fn: String; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'DoLoadSoundEffect', name + ' = ' + filename); {$ENDIF} fn := filename; if not FileExists(fn) then begin fn := PathToResource(fn, SoundResource); if not FileExists(fn) then begin RaiseWarning('Unable to locate ' + name + ' sound effect file at ' + fn); result := nil; exit; end; end; result := AudioDriver.LoadSoundEffect(fn, name); {$IFDEF TRACE} TraceExit('sgAudio', 'DoLoadSoundEffect', HexStr(result)); {$ENDIF} end; function LoadSoundEffect(const filename: String): SoundEffect; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'LoadSoundEffect', filename); {$ENDIF} result := LoadSoundEffectNamed(filename, filename); {$IFDEF TRACE} TraceExit('sgAudio', 'LoadSoundEffect'); {$ENDIF} end; function LoadSoundEffectNamed(const name, filename: String): SoundEffect; var obj: tResourceContainer; snd: SoundEffect; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'LoadSoundEffectNamed', name + ' = ' + filename); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'LoadSoundEffectNamed', 'Audio Closed'); {$ENDIF} result := nil; exit; end; if _SoundEffects.containsKey(name) then begin result := SoundEffectNamed(name); exit; end; snd := DoLoadSoundEffect(filename, name); if not assigned(snd) then begin result := nil; exit; end; obj := tResourceContainer.Create(snd); if not _SoundEffects.setValue(name, obj) then begin RaiseWarning('** Leaking: Caused by Sound Effect resource loading twice, ' + name); result := nil; exit; end; result := snd; {$IFDEF TRACE} TraceExit('sgAudio', 'LoadSoundEffectNamed'); {$ENDIF} end; // private: // Called to actually free the resource procedure DoFreeSoundEffect(var effect: SoundEffect); var s: SoundEffectPtr; begin s := ToSoundEffectPtr(effect); {$IFDEF TRACE} TraceEnter('sgAudio', 'DoFreeSoundEffect', 'effect = ' + HexStr(effect)); {$ENDIF} if assigned(s) then begin CallFreeNotifier(effect); AudioDriver.FreeSoundEffect(effect); Dispose(s); end; effect := nil; {$IFDEF TRACE} TraceExit('sgAudio', 'DoFreeSoundEffect'); {$ENDIF} end; procedure FreeSoundEffect(var effect: SoundEffect); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'FreeSoundEffect', 'effect = ' + HexStr(effect)); {$ENDIF} if(assigned(effect)) then begin ReleaseSoundEffect(SoundEffectPtr(effect^)^.name); end; effect := nil; {$IFDEF TRACE} TraceExit('sgAudio', 'FreeSoundEffect'); {$ENDIF} end; procedure ReleaseSoundEffect(const name: String); var snd: SoundEffect; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'ReleaseSoundEffect', 'effect = ' + name); {$ENDIF} snd := SoundEffectNamed(name); if (assigned(snd)) then begin _SoundEffects.remove(name).Free(); DoFreeSoundEffect(snd); end; {$IFDEF TRACE} TraceExit('sgAudio', 'ReleaseSoundEffect'); {$ENDIF} end; procedure ReleaseAllSoundEffects(); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'ReleaseAllSoundEffects', ''); {$ENDIF} ReleaseAll(_SoundEffects, @ReleaseSoundEffect); {$IFDEF TRACE} TraceExit('sgAudio', 'ReleaseAllSoundEffects'); {$ENDIF} end; //---------------------------------------------------------------------------- function DoLoadMusic(const filename, name: String): Music; var fn: String; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'DoLoadMusic', name + ' = ' + filename); {$ENDIF} fn := filename; if not FileExists(fn) then begin fn := PathToResource(fn, SoundResource); if not FileExists(fn) then begin RaiseWarning('Unable to locate ' + name + ' music file at ' + fn); result := nil; exit; end; end; result := AudioDriver.LoadMusic(fn, name); {$IFDEF TRACE} TraceExit('sgAudio', 'DoLoadMusic'); {$ENDIF} end; function LoadMusic(const filename: String): Music; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'LoadMusic', filename); {$ENDIF} result := LoadMusicNamed(filename, filename); {$IFDEF TRACE} TraceExit('sgAudio', 'LoadMusic'); {$ENDIF} end; function LoadMusicNamed(const name, filename: String): Music; var obj: tResourceContainer; mus: Music; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'LoadMusicNamed', name + ' = ' + filename); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'LoadMusicNamed', 'Audio Closed'); {$ENDIF} result := nil; exit; end; if _Music.containsKey(name) then begin RaiseWarning('Error loaded Music resource twice, ' + name); result := nil; exit; end; mus := DoLoadMusic(filename, name); if not assigned(mus) then begin result := nil; exit; end; obj := tResourceContainer.Create(mus); if not _Music.setValue(name, obj) then begin RaiseWarning('** Leaking due to loading Music resource twice, ' + name); exit; end; result := mus; {$IFDEF TRACE} TraceExit('sgAudio', 'LoadMusicNamed'); {$ENDIF} end; procedure DoFreeMusic(var mus: Music); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'DoFreeMusic', 'mus = ' + HexStr(mus)); {$ENDIF} if assigned(mus) then begin CallFreeNotifier(mus); AudioDriver.FreeMusic(mus); end; mus := nil; {$IFDEF TRACE} TraceExit('sgAudio', 'DoFreeMusic'); {$ENDIF} end; procedure FreeMusic(var mus: Music); var m: MusicPtr; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'FreeMusic', 'mus = ' + HexStr(mus)); {$ENDIF} m := ToMusicPtr(mus); if assigned(mus) then ReleaseMusic(m^.name); mus := nil; {$IFDEF TRACE} TraceExit('sgAudio', 'FreeMusic'); {$ENDIF} end; procedure ReleaseMusic(const name: String); var mus: Music; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'ReleaseMusic', name); {$ENDIF} mus := MusicNamed(name); if (assigned(mus)) then begin _Music.remove(name).Free(); DoFreeMusic(mus); end; {$IFDEF TRACE} TraceExit('sgAudio', 'ReleaseMusic'); {$ENDIF} end; procedure ReleaseAllMusic(); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'ReleaseAllMusic', ''); {$ENDIF} ReleaseAll(_Music, @ReleaseMusic); {$IFDEF TRACE} TraceExit('sgAudio', 'ReleaseAllMusic'); {$ENDIF} end; //---------------------------------------------------------------------------- procedure PlaySoundEffect(const name: String; loops: Longint; vol: Single); overload; begin PlaySoundEffect(SoundEffectNamed(name), loops, vol); end; procedure PlaySoundEffect(effect: SoundEffect; loops: Longint; vol: Single); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlaySoundEffect', HexStr(effect) + ' loops = ' + IntToStr(loops) + ' vol = ' + FloatToStr(vol)); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect', 'Audio Closed'); {$ENDIF} exit; end; if not Assigned(effect) then begin {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect', 'No sound effect supplied.'); {$ENDIF} RaiseWarning('No sound effect supplied to PlaySoundEffect'); exit; end; //dont play if loops = 0 if loops = 0 then exit; //correct volume to be between 0 and 1 if (vol < 0) then vol := 0 else if vol > 1 then vol := 1; //alter repeats for multiple loops if loops >= 1 then loops := loops- 1; //play the effect, seaching for a channel if (not AudioDriver.PlaySoundEffect(effect, loops, vol)) then RaiseWarning('Error playing sound effect' + AudioDriver.GetError()); {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect'); {$ENDIF} end; procedure PlaySoundEffect(const name: String; loops: Longint); overload; begin PlaySoundEffect(SoundEffectNamed(name), loops); end; procedure PlaySoundEffect(effect: SoundEffect; loops: Longint); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlaySoundEffect', HexStr(effect) + ' loops = ' + IntToStr(loops)); {$ENDIF} PlaySoundEffect(effect, loops, 1.0); {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect'); {$ENDIF} end; procedure PlaySoundEffect(const name: String); overload; begin PlaySoundEffect(SoundEffectNamed(name)); end; procedure PlaySoundEffect(effect: SoundEffect); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlaySoundEffect', HexStr(effect)); {$ENDIF} PlaySoundEffect(effect, 1, 1.0); {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect'); {$ENDIF} end; procedure PlaySoundEffect(const name: String; vol: Single); overload; begin PlaySoundEffect(SoundEffectNamed(name), vol); end; procedure PlaySoundEffect(effect: SoundEffect; vol: Single); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlaySoundEffect', HexStr(effect) + ' vol = ' + FloatToStr(vol)); {$ENDIF} PlaySoundEffect(effect, 1, vol); {$IFDEF TRACE} TraceExit('sgAudio', 'PlaySoundEffect'); {$ENDIF} end; //---------------------------------------------------------------------------- procedure PlayMusic(const name: String; loops: Longint); overload; begin PlayMusic(MusicNamed(name), loops); end; procedure PlayMusic(mus: Music; loops: Longint); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlayMusic', HexStr(mus) + ' loops = ' + IntToStr(loops)); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'PlayMusic', 'Audio Closed'); {$ENDIF} exit; end; if not Assigned(mus) then begin RaiseWarning('Music not supplied to PlayMusic'); exit; end; AudioDriver.PlayMusic(mus, loops); {$IFDEF TRACE} TraceExit('sgAudio', 'PlayMusic'); {$ENDIF} end; procedure PlayMusic(const name: String); overload; begin PlayMusic(MusicNamed(name)); end; procedure PlayMusic(mus: Music); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'PlayMusic', HexStr(mus)); {$ENDIF} PlayMusic(mus, -1); {$IFDEF TRACE} TraceExit('sgAudio', 'PlayMusic'); {$ENDIF} end; procedure FadeMusicIn(const name: String; loops, ms: Longint); overload; begin FadeMusicIn(MusicNamed(name), loops, ms); end; procedure FadeMusicIn(mus: Music; loops, ms: Longint); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'FadeMusicIn', HexStr(mus) + ' loops = ' + IntToStr(loops) + ' ms = ' + IntToStr(ms)); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'FadeMusicIn', 'Audio Closed'); {$ENDIF} exit; end; if not Assigned(mus) then begin RaiseWarning('Music not supplied to FadeMusicIn'); exit; end; AudioDriver.FadeMusicIn(mus, loops, ms); {$IFDEF TRACE} TraceExit('sgAudio', 'FadeMusicIn'); {$ENDIF} end; procedure FadeMusicIn(const name: String; ms: Longint); overload; begin FadeMusicIn(MusicNamed(name), ms); end; procedure FadeMusicIn(mus: Music; ms: Longint); overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'FadeMusicIn', HexStr(mus) + ' ms = ' + IntToStr(ms)); {$ENDIF} FadeMusicIn(mus, -1, ms); {$IFDEF TRACE} TraceExit('sgAudio', 'FadeMusicIn'); {$ENDIF} end; procedure FadeMusicOut(ms: Longint); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'FadeMusicOut', IntToStr(ms)); {$ENDIF} if not AudioReady() then begin {$IFDEF TRACE} TraceExit('sgAudio', 'FadeMusicOut', 'Audio Closed'); {$ENDIF} exit; end; AudioDriver.FadeMusicOut(ms); {$IFDEF TRACE} TraceExit('sgAudio', 'FadeMusicOut'); {$ENDIF} end; function SoundEffectPlaying(const name: String): Boolean; overload; begin result := SoundEffectPlaying(SoundEffectNamed(name)); end; function SoundEffectPlaying(effect: SoundEffect): Boolean; overload; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'SoundEffectPlaying', HexStr(effect)); {$ENDIF} result := false; if AudioReady() then begin result := AudioDriver.SoundEffectPlaying(effect); end; {$IFDEF TRACE} TraceExit('sgAudio', 'SoundEffectPlaying', BoolToStr(result, true)); {$ENDIF} end; function MusicPlaying(): Boolean; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'MusicPlaying', ''); {$ENDIF} if AudioReady() then result := AudioDriver.MusicPlaying() else result := false; {$IFDEF TRACE} TraceExit('sgAudio', 'MusicPlaying', BoolToStr(result, true)); {$ENDIF} end; procedure PauseMusic(); begin AudioDriver.PauseMusic(); end; procedure ResumeMusic(); begin AudioDriver.ResumeMusic(); end; //---------------------------------------------------------------------------- function HasSoundEffect(const name: String): Boolean; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'HasSoundEffect', name); {$ENDIF} result := _SoundEffects.containsKey(name); {$IFDEF TRACE} TraceExit('sgAudio', 'HasSoundEffect', BoolToStr(result, true)); {$ENDIF} end; function SoundEffectNamed(const name: String): SoundEffect; var tmp : TObject; filename: String; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'SoundEffectNamed', name); {$ENDIF} tmp := _SoundEffects.values[name]; if assigned(tmp) then result := SoundEffect(tResourceContainer(tmp).Resource) else begin filename := PathToResource(name, SoundResource); if FileExists(name) or FileExists(filename) then begin result := LoadSoundEffectNamed(name, name); end else begin result := nil; end; end; {$IFDEF TRACE} TraceExit('sgAudio', 'SoundEffectNamed', HexStr(result)); {$ENDIF} end; function SoundEffectName(effect: SoundEffect): String; var s: SoundEffectPtr; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'SoundEffectName', HexStr(effect)); {$ENDIF} s := ToSoundEffectPtr(effect); if Assigned(s) then result := s^.name else result := ''; {$IFDEF TRACE} TraceExit('sgAudio', 'SoundEffectName', result); {$ENDIF} end; function SoundEffectFilename(effect: SoundEffect): String; var s: SoundEffectPtr; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'SoundEffectFilename', HexStr(effect)); {$ENDIF} s := ToSoundEffectPtr(effect); if Assigned(s) then result := s^.filename else result := ''; {$IFDEF TRACE} TraceExit('sgAudio', 'SoundEffectFilename', result); {$ENDIF} end; //---------------------------------------------------------------------------- function HasMusic(const name: String): Boolean; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'HasMusic', name); {$ENDIF} result := _Music.containsKey(name); {$IFDEF TRACE} TraceExit('sgAudio', 'HasMusic', BoolToStr(result, true)); {$ENDIF} end; function MusicNamed(const name: String): Music; var tmp : TObject; filename: String; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'MusicNamed', name); {$ENDIF} tmp := _Music.values[name]; if Assigned(tmp) then result := Music(tResourceContainer(tmp).Resource) else begin filename := PathToResource(name, SoundResource); if FileExists(name) or FileExists(filename) then begin result := LoadMusicNamed(name, name); end else result := nil; end; {$IFDEF TRACE} TraceExit('sgAudio', 'MusicNamed', HexStr(result)); {$ENDIF} end; function MusicName(mus: Music): String; var m: MusicPtr; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'MusicName', HexStr(mus)); {$ENDIF} m := ToMusicPtr(mus); if Assigned(m) then result := m^.name else result := ''; {$IFDEF TRACE} TraceExit('sgAudio', 'MusicName', result); {$ENDIF} end; function MusicFilename(mus: Music): String; var m: MusicPtr; begin {$IFDEF TRACE} TraceEnter('sgAudio', 'MusicFilename', HexStr(mus)); {$ENDIF} m := ToMusicPtr(mus); if Assigned(m) then result := m^.filename else result := ''; {$IFDEF TRACE} TraceExit('sgAudio', 'MusicFilename', result); {$ENDIF} end; //---------------------------------------------------------------------------- procedure StopMusic(); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'StopMusic', ''); {$ENDIF} if AudioReady() then AudioDriver.StopMusic(); {$IFDEF TRACE} TraceExit('sgAudio', 'StopMusic'); {$ENDIF} end; procedure StopSoundEffect(const name: String); begin StopSoundEffect(SoundEffectNamed(name)); end; procedure StopSoundEffect(effect: SoundEffect); begin {$IFDEF TRACE} TraceEnter('sgAudio', 'StopSoundEffect', HexStr(effect)); {$ENDIF} if not AudioReady() then exit; AudioDriver.StopSoundEffect(effect); {$IFDEF TRACE} TraceExit('sgAudio', 'StopSoundEffect'); {$ENDIF} end; //============================================================================= initialization begin {$IFDEF TRACE} TraceEnter('sgAudio', 'Initialise', ''); {$ENDIF} InitialiseSwinGame(); _SoundEffects := TStringHash.Create(False, 1024); _Music := TStringHash.Create(False, 1024); {$IFDEF TRACE} TraceExit('sgAudio', 'Initialise'); {$ENDIF} end; finalization begin ReleaseAllMusic(); ReleaseAllSoundEffects(); FreeAndNil(_SoundEffects); FreeAndNil(_Music); end; end.
unit ThJavaScript; interface uses SysUtils, Classes, ThAttributeList, ThComponent; type TThJavaScript = class(TThComponent) private FScript: TStringList; protected function GetScript: TStrings; procedure SetScript(const Value: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //procedure Publish(inPage: TThHtmlPage); override; published property Script: TStrings read GetScript write SetScript; end; // TThJavaScriptEventRegistry = class(TStringList) constructor Create; end; // TThJavaScriptEventItem = class(TCollectionItem) private FEventName: string; FCode: TStringList; FFunctionName: string; protected function GetTrimmedName: string; procedure SetCode(const Value: TStringList); procedure SetEventName(const Value: string); procedure SetFunctionName(const Value: string); protected function GetDisplayName: string; override; public constructor Create(inCollection: TCollection); override; destructor Destroy; override; published property FunctionName: string read FFunctionName write SetFunctionName; property EventName: string read FEventName write SetEventName; property Code: TStringList read FCode write SetCode; property TrimmedName: string read GetTrimmedName; end; // TThJavaScriptEvents = class(TCollection) private FOwner: TComponent; protected function GetEvent(inIndex: Integer): TThJavaScriptEventItem; function GetOwner: TPersistent; override; public constructor Create(AOwner: TComponent); procedure CreateDefaultEvents; function AddEvent: TThJavaScriptEventItem; function FindEvent(inName: string): TThJavaScriptEventItem; procedure GenerateFuncs(const inJavaName: string); procedure ListAttributes(const inJavaName: string; inList: TThAttributeList; inIndex: Integer = 0); public property Event[inIndex: Integer]: TThJavaScriptEventItem read GetEvent; default; end; var ThJavaScriptEventRegistry: TThJavaScriptEventRegistry; implementation const cThJsNumEventNames = 22; cThJsEventNames: array[0..Pred(cThJsNumEventNames)] of string = ( 'onKeyDown', 'onKeyPress', 'onKeyUp', 'onMouseDown', 'onMouseUp', 'onMouseMove', 'onMouseOver', 'onMouseOut', 'onClick', 'onDblClick', 'onLoad', 'onAbort', 'onError', 'onMove','onResize', 'onScroll', 'onReset', 'onSubmit', 'onBlur', 'onChange', 'onFocus', 'onSelect' ); { TThJavaScript } constructor TThJavaScript.Create(AOwner: TComponent); begin inherited; FScript := TStringList.Create; end; destructor TThJavaScript.Destroy; begin FScript.Free; inherited; end; function TThJavaScript.GetScript: TStrings; begin Result := FScript; end; { procedure TThJavaScript.Publish(inPage: TThHtmlPage); begin with inPage do begin if Script.Count > 0 then Code.AddContent(Script.Text); if ScriptOnLoad.Count > 0 then CodeBodyLoad.AddContent(ScriptOnLoad.Text); if ScriptOnUnload.Count > 0 then CodeBodyUnload.AddContent(ScriptOnUnload.Text); end; end; } procedure TThJavaScript.SetScript(const Value: TStrings); begin FScript.Assign(Value); end; { TThJavaScriptEventRegistry } constructor TThJavaScriptEventRegistry.Create; var i: Integer; begin for i := 0 to Pred(cThJsNumEventNames) do Add(cThJsEventNames[i]); end; { TThJavaScriptEventItem } constructor TThJavaScriptEventItem.Create(inCollection: TCollection); begin inherited; FCode := TStringList.Create; end; destructor TThJavaScriptEventItem.Destroy; begin FCode.Free; inherited; end; function TThJavaScriptEventItem.GetDisplayName: string; begin Result := EventName; end; procedure TThJavaScriptEventItem.SetEventName(const Value: string); begin FEventName := Value; end; procedure TThJavaScriptEventItem.SetCode(const Value: TStringList); begin FCode.Assign(Value); end; procedure TThJavaScriptEventItem.SetFunctionName(const Value: string); begin FFunctionName := Value; end; function TThJavaScriptEventItem.GetTrimmedName: string; begin Result := Copy(EventName, 3, MAXINT); end; { TThJavaScriptEvents } constructor TThJavaScriptEvents.Create(AOwner: TComponent); begin inherited Create(TThJavaScriptEventItem); FOwner := AOwner; CreateDefaultEvents; end; function TThJavaScriptEvents.AddEvent: TThJavaScriptEventItem; begin Result := TThJavaScriptEventItem(Add); end; function TThJavaScriptEvents.FindEvent(inName: string): TThJavaScriptEventItem; var i: Integer; begin for i := 0 to Pred(Count) do if Event[i].EventName = inName then begin Result := Event[i]; exit; end; Result := nil; end; procedure TThJavaScriptEvents.CreateDefaultEvents; var i: Integer; begin for i := 0 to Pred(ThJavaScriptEventRegistry.Count) do AddEvent.EventName := ThJavaScriptEventRegistry[i]; end; function TThJavaScriptEvents.GetOwner: TPersistent; begin Result := FOwner; end; function TThJavaScriptEvents.GetEvent( inIndex: Integer): TThJavaScriptEventItem; begin Result := TThJavaScriptEventItem(Items[inIndex]); end; procedure TThJavaScriptEvents.GenerateFuncs(const inJavaName: string); var i: Integer; c: string; begin for i := 0 to Pred(Count) do with Event[i] do if Code.Count > 0 then begin if FunctionName <> '' then c := Format('function %s(inSender, inIndex) {'#10, [ FunctionName ]) else c := Format('function %s%s(inSender, inIndex) {'#10, [ inJavaName, TrimmedName ]); c := c + Code.Text + '}'#10; end; end; procedure TThJavaScriptEvents.ListAttributes(const inJavaName: string; inList: TThAttributeList; inIndex: Integer = 0); var i: Integer; n: string; begin for i := 0 to Count - 1 do with Event[i] do if (Code.Text <> '') or (FunctionName <> '') then begin if FunctionName <> '' then n := Format('return %s(this, %d);', [ FunctionName, inIndex ]) else n := Format('return %s%s(this, %d);', [ inJavaName, TrimmedName, inIndex ]); inList.Add(EventName, n); end; end; initialization ThJavaScriptEventRegistry := TThJavaScriptEventRegistry.Create; finalization ThJavaScriptEventRegistry.Free; end.
unit Chapter08._05_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils, DeepStar.DSA.Linear.ArrayList; /// 77. Combinations /// https://leetcode.com/problems/combinations/description/ /// 时间复杂度: O(n^k) /// 空间复杂度: O(k) type TList_TList_int = specialize TArrayList<TList_int>; TSolution = class public function combine(n, k: integer): TList_TList_int; end; procedure Main; implementation procedure Main; var res: TList_TList_int; r: TList_int; i: integer; begin with TSolution.Create do begin res := combine(4, 2); for i := 0 to res.Count - 1 do begin r := res[i]; TArrayUtils_int.Print(r.ToArray); r.Free; end; res.Free; Free; end; end; { TSolution } function TSolution.combine(n, k: integer): TList_TList_int; var res: TList_TList_int; c: TList_int; // 求解 c(n,k), 当前已经找到的组合存储在c中, 需要从start开始搜索新的元素 procedure __combine__(start: integer); var i: integer; begin if c.Count = k then begin res.AddLast(TList_int.Create(c.ToArray)); Exit; end; // 还有k - c.size()个空位, 所以, [i...n] 中至少要有 k - c.size() 个元素 // i最多为 n - (k - c.size()) + 1 for i := start to n - (k - c.Count) + 1 do begin c.AddLast(i); __combine__(start + 1); c.RemoveLast; end; end; begin res := TList_TList_int.Create; c := TList_int.Create; __combine__(1); Result := res; c.Free; end; end.
unit ZFConst; {$I ZFVer.Inc} interface const InternalCurrentVersion = 6.50; // current version of the engine (for visual property) var internalCurrentVersionText: string = ''; const DefaultSearchAttr = 63 + $2000 + $800 + $80; ZF_MAX_IVECTOR_SIZE = 16; ZF_MAX_SAVED_IVECTOR_SIZE = 16; resourcestring SConfirmOverwrite = 'Overwrite file "%s" with "%s"'; SPasswordTitle = 'Password for "%s"'; SPasswordPrompt = 'Enter password: '; SOnRequestBlankDisk = 'Please insert a blank disk #%d'; SOnRequestFirstDisk = 'Please insert the first disk'; SOnRequestLastDisk = 'Please insert the last disk'; SOnRequestMiddleDisk = 'Please insert disk #%d'; SOnDiskFull = 'Disk is full. Required free space: %d bytes, but available only: %d bytes. Clean the disk or find another blank disk'; SOnProcessFileFailure = '%s. File processing error, possibly disk is full'; SWrongDiskRequestLastDisk = 'File ''%s'' not found on inserted disk. Please insert last disk with required file'; const ErUnknownError = 0; ErIndexOutOfBounds = 1; ErInvalidCompressionMode = 2; ErUnexpectedNil = 3; ErInvalidCheckSum = 4; ErBlankFileName = 5; ErFileNotFound = 6; ErArchiveIsNotOpen = 7; ErStubNotSpecified = 8; ErCannotCreateFile = 9; ErCannotCreateDir = 10; ErNotInUpdate = 11; ErCannotOpenFile = 12; ErInUpdate = 13; ErCannotDeleteFile = 14; ErInMemoryArchiveCanBeCreatedOnly = 15; ErFileIsInReadonlyMode = 16; ErInvalidCompressedSize = 17; ErInvalidFormat = 18; ErCannotCreateOutputFile = 19; ErArchiveIsOpen = 20; ErUnableToCreateDirectory = 21; ErUnableToFindZip64DirEnd = 22; ErHugeFileModeIsNotEnabled = 23; ErCannotOpenArchiveFile = 24; ErCannotWriteToStream = 25; ErCannotFitSFXStubOnVolume = 26; ErDamagedArchive = 27; ErMakeSFXIsNotAllowed = 28; ErArchiveAlreadyHasSFXStub = 29; ErMultiVolumeArchiveIsNotAllowed = 30; ErSpanningModificationIsNotAllowed = 31; ErDeflate64NotSupported = 32; ErMakeSFXError = 33; ErInvalidHashedNamesList = 34; ErCannotDeleteFolder = 35; ErFileNameTooLong = 36; ErMultipleTransactionsNotAllowedForMutlivolumeArchives = 37; ErInvalidIVIndex = 38; ErDiskFull = 39; ErInvalidPassword = 40; ZFMaxError = 40; ZFErrorMessages: array[0..ZFMaxError] of string = ( 'Unknown error', 'Index out of bounds', 'Invalid compression mode. Mode must be in [0-9] range', 'Unexpected nil pointer', 'Invalid size or check sum of file or unsupported compression format', 'File name is blank. Specify appropriate file name', 'File "%s" not found', 'Archive is not open', 'SFXStub property is not specified', 'Cannot create file "%s"', 'Cannot create directory "%s"', 'Internal error. Update is not started', 'Cannot open file "%s"', 'Cannot proceed when update is not ended. Preceding EndUpdate call is required.', 'Cannot delete file "%s"', 'In-memory archive can be created only', 'File is open in read-only mode', 'Invalid compressed size, rfs.size = %d, count = %d', 'Invalid archive file.', 'Cannot create output file. Probably file is locked by another process. FileName = ''%s''.', 'Archive is open. You should close it beore performing this operation.', 'Unable to create directory', 'Cannot find 64-bit directory end record', 'Cannot compress file ''%s''. Zip64 mode is not enabled', 'Cannot open archive file. Opening aborted or invalid file', 'Write to stream error', 'Cannot place SFX stub on volume. Volume size limit is too small', 'Archive is damaged. Open failed', 'MakeSFX is not allowed for splitted or spanned archives. Set SFXStub before archive creation instead of MakeSFX', 'Archive already has SFX stub', 'Multi-volume archive is not allowed for custom stream', 'Multi-spanned archive is not allowed for modification. Use BeginUpdate/EndUpdate methods to add files several times', 'Deflate64 compression method is not supported', 'MakeSFX error', 'Hashed list of file names is invalid', 'Cannot delete folder "%s"', 'File name is too long: ' + #13#10 + '"%s"', 'Multiple transactions are not supported for multi-volume archives', 'Invalid InitVector index = %d. Index should be >= 0 and < %d', 'Disk is full. There is not enough free space on disk.', 'Invalid password. Cannot decompress encrypted file.' ); ZFMaxNativeError = 67; ZFNativeToErrorCode: array[0..ZFMaxNativeError, 0..1] of integer = ( (00000, ErUnknownError), (00001, ErIndexOutOfBounds), (00002, ErIndexOutOfBounds), (00003, ErIndexOutOfBounds), (00004, ErIndexOutOfBounds), (00005, ErInvalidCompressionMode), (00006, ErUnexpectedNil), (00007, ErIndexOutOfBounds), (00008, ErInvalidCheckSum), (00009, ErBlankFileName), (00010, ErBlankFileName), (00011, ErFileNotFound), (00012, ErFileNotFound), (00013, ErArchiveIsNotOpen), (00014, ErArchiveIsNotOpen), (00015, ErFileNotFound), (00016, ErIndexOutOfBounds), (00017, ErStubNotSpecified), (00018, ErFileNotFound), (00019, ErCannotCreateFile), (00020, ErCannotCreateDir), (00021, ErIndexOutOfBounds), (00022, ErNotInUpdate), (00023, ErCannotCreateFile), (00024, ErIndexOutOfBounds), (00025, ErNotInUpdate), (00026, ErInUpdate), (00027, ErCannotDeleteFile), (00028, ErInMemoryArchiveCanBeCreatedOnly), (00029, ErBlankFileName), (00030, ErFileNotFound), (00031, ErFileNotFound), (00032, ErFileIsInReadonlyMode), (00033, ErCannotOpenFile), (00034, ErInvalidCompressedSize), (00035, ErInvalidFormat), (00036, ErCannotCreateOutputFile), (00037, ErArchiveIsOpen), (00038, ErFileNotFound), (00039, ErUnableToCreateDirectory), (00040, ErUnableToFindZip64DirEnd), (00041, ErHugeFileModeIsNotEnabled), (00042, ErFileNotFound), (00043, ErHugeFileModeIsNotEnabled), (00044, ErCannotOpenArchiveFile), (00045, ErCannotOpenArchiveFile), (00046, ErCannotWriteToStream), (00047, ErCannotFitSFXStubOnVolume), (00048, ErDamagedArchive), (00049, ErMakeSFXIsNotAllowed), (00050, ErArchiveAlreadyHasSFXStub), (00051, ErMultiVolumeArchiveIsNotAllowed), (00052, ErSpanningModificationIsNotAllowed), (00053, ErFileNotFound), (00054, ErFileNotFound), (00055, ErDeflate64NotSupported), (00056, ErMakeSFXError), (00057, ErDamagedArchive), (00058, ErInvalidHashedNamesList), (00059, ErInvalidHashedNamesList), (00060, ErCannotDeleteFolder), (00061, ErFileNameTooLong), (00062, ErMultipleTransactionsNotAllowedForMutlivolumeArchives), (00063, ErInvalidIVIndex), (00064, ErInvalidIVIndex), (00065, ErDiskFull), (00066, ErDiskFull), (00067, ErInvalidPassword) ); const CRC32_TABLE: array[0..255] of longword = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d ); implementation end.
unit OTFEE4M_U; // Description: Delphi E4M Component // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // TRUE if integer<>0 // FALSE if integer=0 interface uses Classes, SysUtils, Windows, forms, controls, OTFE_U, OTFEE4MStructures_U; type TOTFEE4M = class(TOTFE) private hE4MVxD : THandle; FPasswordPrompt: string; FSupportScramDisk: boolean; FHidePasswordsEnteredCk: boolean; FMountDeviceDlg9xStyle: boolean; mtdVolInfoLst: TList; procedure AddVolumeToHistory(volumeFilename: string); procedure UpdateVolInfoList(); function GetHashType(hashID: integer): E4M_HASH_TYPE; function GetCipherType(cipherID: integer): E4M_CIPHER_TYPE; function ld(driveNum: integer; mode: integer): boolean; function CloseSlot(driveNum: integer; brutal: boolean): boolean; function locklogdrive(drivenum: integer; mode: integer): boolean; function ioctllock(nDrive: cardinal; permissions: integer; func: integer): integer; function DoDeviceClose(driveNum: integer): boolean; function EjectStop(driveLetter: Ansichar; func: boolean): boolean; function GetNextUnusedDrvLtr(afterDrv: Ansichar): Ansichar; function GetUnusedDriveLetters(): Ansistring; protected E4MDriverName: string; E4MDriverVersion: cardinal; CurrentOS: integer; function Connect(): boolean; function Disconnect(): boolean; procedure SetActive(AValue : Boolean); override; function GetDisksMounted(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean; function GetWordFromHeader(buffer: array of byte; var posInBuffer: integer): cardinal; function GetCipherName(cipherID: integer): string; function GetVolumeInfo(volumeFilename: ansistring; info: pTOTFEE4MVolumeInfo): boolean; // Property settings (read/written to INI file) function GetCachePasswordInDriver(): boolean; procedure SetCachePasswordInDriver(cache: boolean); function GetSaveHistory(): boolean; procedure SetSaveHistory(save: boolean); function GetMountWarning(): boolean; procedure SetMountWarning(mountWarning: boolean); function GetDefaultDrive(): Ansichar; procedure SetDefaultDrive(dfltDrive: Ansichar); procedure SetSupportScramDisk(support: boolean); function IsE4MorSFSEncryptedVolFile(volumeFilename: string): boolean; overload; function IsE4MorSFSEncryptedVolFile(volumeFilename: string; var cancelled: boolean): boolean; overload; function GetScramDiskPasswords(dlgTitle: string; var passwordDigest: Ansistring; var driveLetter: ansichar): boolean; function GetAvailableRemovables(dispNames: TStringList; deviceNames: TStringList): integer; function GetAvailableFixedDisks(dispNames: TStringList; deviceNames: TStringList): integer; function OpenDevice(device: string): boolean; procedure ShortArrayToString(theArray: array of short; var theString: string); procedure StringToShortArray(theString: string; var theArray: array of short); function IsFilePartition(volumeFilename: string): boolean; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; // TOTFE functions... function Title(): string; overload; override; function Mount(volumeFilename: ansistring; readonly: boolean = FALSE): ansichar; override; function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; override; function MountDevices(): ansistring; override; function CanMountDevice(): boolean; override; function Dismount(driveLetter: ansichar; emergency: boolean = FALSE): boolean; overload; override; function Dismount(volumeFilename: String; emergency: boolean = FALSE): boolean; overload; override; function DrivesMounted(): ANsiString; override; function GetVolFileForDrive(driveLetter: ansichar): string; override; function GetDriveForVolFile(volumeFilename: string): Ansichar; override; function Version(): cardinal; override; function VersionStr(): string; override; function IsEncryptedVolFile(volumeFilename: string): boolean; override; function GetMainExe(): string; override; function GetDriveInfo(driveLetter: Ansichar): TOTFEE4MVolumeInfo; function VersionCanSupportScramDiskVols(): boolean; function ClearPasswords(driveLetter: Ansichar): boolean; function GetAvailableRawDevices(dispNames: TStringList; deviceNames: TStringList): boolean; published property SupportScramDisk: Boolean read FSupportScramDisk write SetSupportScramDisk default FALSE; property PasswordPrompt: string read FPasswordPrompt write FPasswordPrompt; property SaveHistory: boolean read GetSaveHistory write SetSaveHistory default TRUE; property CachePasswordInDriver: boolean read GetCachePasswordInDriver write SetCachePasswordInDriver default FALSE; property MountWarning: boolean read GetMountWarning write SetMountWarning default FALSE; property DefaultDrive: Ansichar read GetDefaultDrive write SetDefaultDrive; property HidePasswordsEnteredCk: boolean read FHidePasswordsEnteredCk write FHidePasswordsEnteredCk default TRUE; property MountDeviceDlg9xStyle: boolean read FMountDeviceDlg9xStyle write FMountDeviceDlg9xStyle default FALSE; end; procedure Register; implementation uses ShellAPI, dialogs, Registry, RegStr, INIFiles, Math, OTFEConsts_U, OTFEE4MPasswordEntry_U, SDUGeneral, HashValue_U, HashAlg_U, // required for the SHA1 function HashAlgSHA1_U, // required for the SHA1 function OTFEE4MScramDiskPasswordEntry_U, // Part of the ScramDisk component; the ScramDisk password entry dialog OTFEE4MMountDevice_U, OTFEE4MMountDevice9x_U, OTFEE4MMountDeviceNT_U; procedure Register; begin RegisterComponents('OTFE', [TOTFEE4M]); end; constructor TOTFEE4M.Create(AOwner : TComponent); var os: OSVERSIONINFO; begin inherited create(AOwner); // Pull down the windows version os.dwOSVersionInfoSize := sizeof(OSVERSIONINFO); if (GetVersionEx(os) = FALSE) then begin raise EE4MError.Create('Unable to determine OS'); end else if (os.dwPlatformId = VER_PLATFORM_WIN32_NT) then begin CurrentOS := E4M_OS_WIN_NT; end else if ((os.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) and (os.dwMajorVersion = 4) and (os.dwMinorVersion = 0)) then begin CurrentOS := E4M_OS_WIN_95; end else if ((os.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) and (os.dwMajorVersion = 4) and (os.dwMinorVersion = 10)) then begin CurrentOS := E4M_OS_WIN_98; end else begin // raise EE4MError('Unable to determine OS'); CurrentOS := E4M_OS_WIN_98; end; FActive := False; E4MDriverVersion := $FFFFFFFF; mtdVolInfoLst := TList.Create(); FPasswordPrompt := 'Enter password for %s'; end; destructor TOTFEE4M.Destroy; var i: integer; begin for i:=0 to (mtdVolInfoLst.count-1) do begin dispose(mtdVolInfoLst.items[i]); end; mtdVolInfoLst.Free(); if FActive then CloseHandle(hE4MVxD); inherited Destroy; end; function TOTFEE4M.Connect(): boolean; var OSVersion: TOSVersionInfo; dwResult: DWORD; begin Result := Active; if not(Active) then begin hE4MVxD := INVALID_HANDLE_VALUE; if CurrentOS = E4M_OS_WIN_NT then begin // See if v2.10 is installed E4MDriverName := E4M_WIN32_ROOT_PREFIX; hE4MVxD := CreateFile(PChar(E4MDriverName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if hE4MVxD=INVALID_HANDLE_VALUE then begin // v2.10 isn't installed, fallback to v2.00 E4MDriverName := E4M_WIN32_ROOT_PREFIX_v200; end; end else begin E4MDriverName := E4M_WIN9X_DRIVER_NAME; end; if hE4MVxD=INVALID_HANDLE_VALUE then begin hE4MVxD := CreateFile(PChar(E4MDriverName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); end; if hE4MVxD = INVALID_HANDLE_VALUE then begin raise EE4MVxdNotFound.Create('E4M device driver not found'); end else begin OSVersion.dwOSVersionInfoSize := SizeOf(OSVersion); GetVersionEx(OSVersion); FActive := TRUE; if (Version()>=$201) AND (CurrentOS=E4M_OS_WIN_98) then begin // We're runninng E4M v2.0.1 under w98 DeviceIoControl(hE4MVxD, ALLOW_FAST_SHUTDOWN, nil, 0, nil, 0, dwResult, nil); end; Result := TRUE; end; end; end; function TOTFEE4M.Disconnect(): boolean; begin if Active then begin CloseHandle(hE4MVxD); end; Result := TRUE; end; procedure TOTFEE4M.SetActive(AValue : Boolean); var allOK: boolean; begin allOK := FALSE; if AValue <> Active then begin if AValue then begin allOK := Connect(); end else begin allOK := Disconnect(); end; end; if allOK then begin inherited; if Active then begin E4MDriverVersion := Version(); end; end; end; // Note that the emergency parameter is IGNORED function TOTFEE4M.Dismount(driveLetter: Ansichar; emergency: boolean = FALSE): boolean; var query: TOTFEE4M_UNMOUNT; allOK: boolean; inbuf: array [1..80] of char; outbuf: array [1..80] of char; bytesRead: DWORD; serviceCmd: string; i: integer; begin CheckActive(); Result := FALSE; if pos(driveLetter, DrivesMounted())<1 then begin FLastErrCode := OTFE_ERR_INVALID_DRIVE; exit; end; query.nDosDriveNo := ord(upcase(driveLetter))-ord('A'); query.nReturnCode := 0; if CurrentOS = E4M_OS_WIN_NT then begin // Unmount the volume using the e4mservice, this is done to allow // non-administrators to unmount volumes // Doing it with the DeviceIOControl DISMOUNT is a bad idea as we would need // to lock the volume first, which non-administrators can't do serviceCmd := 'unmount '+inttostr(ord(upcase(driveLetter))-ord('A')); for i:=1 to length(serviceCmd) do begin outbuf[i] := serviceCmd[i]; end; outbuf[length(serviceCmd)+1] := #0; allOK := CallNamedPipe(E4M_PIPE_SERVICE, @outbuf, sizeof(outbuf), @inbuf, sizeof(inbuf), bytesRead, NMPWAIT_WAIT_FOREVER); if allOK then begin Result := (inbuf[1]<>'-'); if not(Result) then begin if pos(inttostr(E4M_ERR_FILES_OPEN_LOCK), inbuf)>0 then begin FLastErrCode := OTFE_ERR_FILES_OPEN; end; end; end; end // if CurrentOS = E4M_OS_WIN_NT then else begin Result := CloseSlot(query.nDosDriveNo, emergency); end; // if not(if CurrentOS = E4M_OS_WIN_NT) then end; function TOTFEE4M.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; begin // Don't need to convert volumeFilename to SFN/LFN, this is done in // GetDriveForVolFile(...) Result := Dismount(GetDriveForVolFile(volumeFilename), emergency); end; function TOTFEE4M.Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar; var stlVolumes: TStringList; mountedAs: AnsiString; begin CheckActive(); Result := #0; stlVolumes:= TStringList.Create(); try stlVolumes.Add(volumeFilename); if Mount(stlVolumes, mountedAs, readonly) then begin Result := mountedAs[1]; end; finally stlVolumes.Free(); end; end; function TOTFEE4M.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; var query200: TOTFEE4M_200_MOUNT; query201: TOTFEE4M_201_MOUNT; dwBytesReturned: DWORD; volumeLoop: integer; i: integer; driveLetter: ansichar; thePassword: AnsiString; oneOK: boolean; targetPath: string; dosName: string; volInfo: pTOTFEE4MVolumeInfo; passwordDlg: TOTFEE4MPasswordEntry_F; currAllOK: boolean; mountedDrvLetter: Ansichar; currVolFilename: string; drvLtrsFree: Ansistring; pwEntryDlgTitle: string; currFileValid: boolean; isPartition: boolean; begin CheckActive(); Result := FALSE; oneOK := FALSE; mountedAs := ''; pwEntryDlgTitle := Format(FPasswordPrompt, [volumeFilenames[0]]); // Get the password/starting drive if IsE4MorSFSEncryptedVolFile(volumeFilenames[0]) then begin query200.bSD := FALSE; // v2.00 only passwordDlg:= TOTFEE4MPasswordEntry_F.Create(nil); try passwordDlg.ckHidePassword.visible := not(FHidePasswordsEnteredCk); // The user should be prompted for the drive letter, and offered the // default drvLtrsFree := GetUnusedDriveLetters(); driveLetter := DefaultDrive; if driveLetter=#0 then begin driveLetter := GetNextUnusedDrvLtr(driveLetter); // If we're on A or B, skip this drive if (driveLetter='A') or (driveLetter='B') then begin driveLetter := GetNextUnusedDrvLtr(driveLetter); end; // If we're on B, skip this drive if (driveLetter='B') then begin driveLetter := GetNextUnusedDrvLtr(driveLetter); end; end else if pos(driveLetter, drvLtrsFree)<1 then begin driveLetter := GetNextUnusedDrvLtr(driveLetter); end; passwordDlg.DrivesAllowed := drvLtrsFree; passwordDlg.Drive := driveLetter; passwordDlg.caption := pwEntryDlgTitle; if passwordDlg.ShowModal()=mrCancel then begin passwordDlg.ClearEnteredPassword(); // Result already = FALSE, so just set the error and exit FLastErrCode := OTFE_ERR_USER_CANCEL; exit; end; thePassword := passwordDlg.mePassword.text; { TODO 1 -otdk -cbug : alert user if use unicode } passwordDlg.ClearEnteredPassword(); driveLetter := passwordDlg.Drive; finally passwordDlg.Free(); end; end else begin // It's a ScramDisk volume if (SupportScramDisk) AND (VersionCanSupportScramDiskVols()) then begin query200.bSD := TRUE; // v2.00 only // Get the 4 passwords SHA1'd GetScramDiskPasswords(pwEntryDlgTitle, thePassword, driveLetter); end else begin // driveLetter already = FALSE, so just set the error and exit FLastErrCode:= OTFE_ERR_FILE_NOT_ENCRYPTED_VOLUME; Result := FALSE; exit; end; end; if driveLetter=#0 then begin // Result already = FALSE, so just set the error and exit FLastErrCode := OTFE_ERR_INVALID_DRIVE; Result := FALSE; exit; end; DefaultDrive := driveLetter; for i:=1 to length(thePassword) do begin query200.szPassword[i] := thePassword[i]; query201.szPassword[i] := thePassword[i]; thePassword[i] := Ansichar(Random(256)); end; query200.szPassword[length(thePassword)+1] := #0; query201.szPassword[length(thePassword)+1] := #0; query200.nPasswordLen := length(thePassword); query201.nPasswordLen := length(thePassword); query200.bCache := CachePasswordInDriver; // looked up from the INI file query201.bCache := CachePasswordInDriver; // looked up from the INI file // NOTE: THESE VALUES SHOULD *NOT* NEED TO BE SET TO ANYTHING // xxx - is this really needed? query200.dummy1[1] := $00; query200.dummy1[2] := $8a; query200.dummy1[3] := $01; query200.dummy1[1] := $00; query200.dummy1[2] := $00; query200.dummy1[3] := $00; // v2.0.1 doesn't seem to need these... // query201.dummy1[1] := $00; // query201.dummy1[2] := $8a; // query201.dummy1[3] := $01; query200.dummy2[1] := $00; query200.dummy2[2] := $00; query200.dummy2[3] := $00; query201.dummy2[1] := $00; query201.dummy2[2] := $00; query201.dummy2[3] := $00; query200.dummy3[1] := $00; // v2.00 only query200.dummy3[2] := $00; // v2.00 only query200.dummy3[3] := $00; // v2.00 only for volumeLoop:=0 to (volumeFilenames.count-1) do begin mountedDrvLetter := #0; query200.nDosDriveNo := ord(upcase(driveLetter))-ord('A'); query201.nDosDriveNo := ord(upcase(driveLetter))-ord('A'); currVolFilename := volumeFilenames[volumeLoop]; isPartition := IsFilePartition(currVolFilename); currFileValid := isPartition; if not(isPartition) then begin currVolFilename := SDUConvertSFNToLFN(volumeFilenames[volumeLoop]); currFileValid := IsEncryptedVolFile(currVolFilename); end; AddVolumeToHistory(currVolFilename); if currFileValid OR isPartition then begin // We must get info on the volume *before* we mount it, just in case it // mounts correctly and we need to store this information new(volInfo); GetVolumeInfo(currVolFilename, volInfo); for i:=1 to length(currVolFilename) do begin query200.wszVolume[i] := WCHAR(currVolFilename[i]); end; query200.wszVolume[length(currVolFilename)+1] := #0; StringToShortArray(currVolFilename, query201.wszVolume); query201.time := DateTimeToFileDate(now); query201.time := DateTimeToFileDate(now); query200.nReturnCode := 0; query201.nReturnCode := 0; if E4MDriverVersion=$200 then begin currAllOK := DeviceIoControl(hE4MVxD, E4M_MOUNT, @query200, sizeof(query200), @query200, sizeof(query200), dwBytesReturned, nil); currAllOK := currAllOK AND (query200.nReturnCode=0); end else begin currAllOK := DeviceIoControl(hE4MVxD, E4M_MOUNT, @query201, sizeof(query201), @query201, sizeof(query201), dwBytesReturned, nil); currAllOK := currAllOK AND (query201.nReturnCode=0); end; if not(currAllOK) then begin FLastErrCode:= OTFE_ERR_WRONG_PASSWORD; end; if currAllOK AND (CurrentOS = E4M_OS_WIN_NT) then begin dosName := driveLetter + ':'; if E4MDriverVersion=$200 then begin targetPath := E4M_NT_MOUNT_PREFIX_v200; end else begin targetPath := E4M_NT_MOUNT_PREFIX; end; targetPath := targetPath+driveLetter; currAllOK := DefineDosDevice(DDD_RAW_TARGET_PATH, PWideChar(dosName), PWideChar(targetPath)); end; if currAllOK then begin volInfo^.mountedAs := driveLetter; volInfo^.readonly := IsDriveReadonly(driveLetter); mtdVolInfoLst.Add(volInfo); mountedDrvLetter := driveLetter; oneOK := TRUE; end else begin dispose(volInfo); end; end; // if IsEncryptedVolFile(currVolFilename) then if volumeLoop<(volumeFilenames.count-1) then begin driveLetter := GetNextUnusedDrvLtr(driveLetter); if driveLetter=#0 then begin FLastErrCode := OTFE_ERR_INVALID_DRIVE; break; end; end; mountedAs := mountedAs + mountedDrvLetter; end; // Pad out the string with #0, if needed while length(mountedAs)<volumeFilenames.count do begin mountedAs := mountedAs + #0; end; Result := oneOK; end; function TOTFEE4M.DrivesMounted(): Ansistring; var output: Ansistring; begin GetDisksMounted(output, nil); Result := SortString(output); end; // !! WARNING !! // Under NT, the E4M driver won't tell us the full filename if it's more than // 64 chars long, it will only return the first 60 followed by "..." function TOTFEE4M.GetDisksMounted(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean; var dwBytesReturned : DWORD; query200: TOTFEE4M_200_MOUNT_LIST; query201: TOTFEE4M_201_MOUNT_LIST; i: integer; j: integer; currBit: cardinal; currVolFilename: string; begin CheckActive(); // Cleared query.ulMountedDrives now so we can can use either later... query200.ulMountedDrives := 0; query201.ulMountedDrives := 0; if E4MDriverVersion=$200 then begin DeviceIoControl(hE4MVxD, E4M_MOUNT_LIST, @query200, sizeof(query200), @query200, sizeof(query200), dwBytesReturned, nil); end else begin DeviceIoControl(hE4MVxD, E4M_MOUNT_LIST, @query201, sizeof(query201), @query201, sizeof(query201), dwBytesReturned, nil); end; mountedDrives := ''; if volumeFilenames<>nil then begin volumeFilenames.Clear(); end; currBit := 1; for i:=1 to 26 do begin // We cleared the query.ulMountedDrives earlier, so we can do this if ((query200.ulMountedDrives AND currBit)>0) OR ((query201.ulMountedDrives AND currBit)>0) then begin mountedDrives := mountedDrives + AnsiChar(ord('A')+i-1); if volumeFilenames<>nil then begin currVolFilename := ''; if E4MDriverVersion=$200 then begin j := 1; while query200.wszVolume[i][j]<>#0 do begin currVolFilename := currVolFilename + query200.wszVolume[i][j]; inc(j); end; end else begin ShortArrayToString(query201.wszVolume[i], currVolFilename); end; if CurrentOS=E4M_OS_WIN_NT then begin // If we're running under NT, and it's a file that's mounted, we need // to strip off the "/??/" at the start of the filename returned if not(IsFilePartition(currVolFilename)) then begin delete(currVolFilename, 1, 4); end; end else begin // If we're running under 95/98, we need to do this to prevent problems // with E4M returning only the first 60 chars followed by "..." if // the volume filename length is >64 currVolFilename := GetVolFileForDrive(AnsiChar(ord('A')+i-1)); end; if IsFilePartition(currVolFilename) then begin volumeFilenames.Add(currVolFilename); end else begin // The file may not exist if we only have the first 60 chars of the // filename followed by "..." if FileExists(currVolFilename) then begin volumeFilenames.Add(SDUConvertSFNToLFN(currVolFilename)); end else begin volumeFilenames.Add(currVolFilename); end; end; end; end; currBit := currBit * 2; end; Result := TRUE; end; // !! WARNING !! // Under NT, the E4M driver won't tell us the full filename if it's more than // 64 chars long, it will only return the first 60 followed by "..." function TOTFEE4M.GetVolFileForDrive(driveLetter: Ansichar): string; var mountedFilenames: TStringList; mountedDrives: Ansistring; mountListN98: TOTFEE4M_9x_MOUNT_LIST_N_STRUCT; dwBytes: DWORD; volFilename: string; begin Result := ''; driveLetter := upcase(driveLetter); if CurrentOS = E4M_OS_WIN_NT then begin // We're running under NT, so use GetDisksMounted(...) to get the // filenames mountedFilenames:= TStringList.Create(); try // xxx - hang on... GetDisksMounted will call us if it's under w98... // That's not a problem, but it's not particularly nice, is it? GetDisksMounted(mountedDrives, mountedFilenames); if Pos(driveLetter, mountedDrives)>0 then begin Result := mountedFilenames[Pos(driveLetter, mountedDrives)-1]; end; finally mountedFilenames.Free(); end; end else begin // Running under w98, we need to use MOUNT_LIST_N because otherwise if we // used MOUNT_LIST, if the length of a volume filename is >64 chars, E4M // would return the first 60 chars of the filename, followed by "..." // - Arrrrgh!! mountListN98.nDosDriveNo := ord(upcase(driveLetter))-ord('A'); if DeviceIoControl(hE4MVxD, E4M_9x_MOUNT_LIST_N, @mountListN98, sizeof(mountListN98), nil, 0, dwBytes, nil) then begin if mountListN98.nReturnCode=0 then begin volFilename := ''; ShortArrayToString(mountListN98.wszVolume, volFilename); if IsFilePartition(volFilename) then begin Result := volFilename; end else begin Result := SDUConvertSFNToLFN(volFilename); end; end; // if mountListN98.nReturnCode=0 then end; end; end; // !! WARNING !! // If running under NT, then if the lanegth of "volumeFilename" is >64, this // function may FAIL as the E4M driver only gives us the first 60 chars // followed by "..." to work with function TOTFEE4M.GetDriveForVolFile(volumeFilename: string): Ansichar; var mountedFilenames: TStringList; mountedDrives: Ansistring; numChars: integer; begin Result := #0; if not(IsFilePartition(volumeFilename)) then begin volumeFilename := SDUConvertSFNToLFN(volumeFilename); end; if (CurrentOS=E4M_OS_WIN_NT) AND (length(volumeFilename)>63) then begin numChars := 60; if not(IsFilePartition(volumeFilename)) then begin dec(numChars, 4); end; volumeFilename := Copy(volumeFilename, 1, numChars); volumeFilename := volumeFilename + '...'; end; mountedFilenames:= TStringList.Create(); try GetDisksMounted(mountedDrives, mountedFilenames); if mountedFilenames.IndexOf(volumeFilename)>-1 then begin Result := mountedDrives[mountedFilenames.IndexOf(volumeFilename)+1]; end; finally mountedFilenames.Free(); end; end; function TOTFEE4M.GetVolumeInfo(volumeFilename: Ansistring; info: pTOTFEE4MVolumeInfo): boolean; var buffer: array [1..(22 * 512)] of byte; posInBuffer: integer; tmpFile: TFileStream; vtid: E4M_VOLUME_FILE_TYPE; j: integer; matchFound: boolean; packetID: integer; packetLength: integer; k: integer; remainingInPkt: integer; nKeyLen: integer; begin Result := FALSE; info^.volumeFilename := volumeFilename; info^.cipherID := cphrUNKNOWN; info^.cipherName := E4M_CIPHER_NAMES[info^.cipherID]; info^.hashID := hashUnknown; info^.hashName := E4M_HASH_NAMES[info^.hashID]; info^.volumeTypeID := vtidUnknown; info^.volumeTypeName := E4M_VOLUME_FILE_TYPE_NAMES[info^.volumeTypeID]; // We can't return any information on partitions... if IsFilePartition(volumeFilename) then begin info^.volumeTypeID := vtidE4MSDSDevice; info^.volumeTypeName := E4M_VOLUME_FILE_TYPE_NAMES[info^.volumeTypeID]; end else begin volumeFilename := SDUConvertSFNToLFN(volumeFilename); try tmpFile := TFileStream.Create(volumeFilename, fmOpenRead OR fmShareDenyNone); try tmpFile.Seek(0, soFromBeginning); tmpFile.Read(buffer[1], sizeof(buffer)); finally tmpFile.Free(); end; except on E:EFOpenError do begin exit; end; end; posInBuffer := 1; if FSupportScramDisk AND VersionCanSupportScramDiskVols() then begin info^.volumeTypeID := vtidScramDisk; // Default to ScramDisk end; for vtid:=low(E4M_VOLUME_FILE_TYPE) to high(E4M_VOLUME_FILE_TYPE) do begin matchFound := TRUE; for j:=1 to length(E4M_VOLUME_SIGNATURES[vtid]) do begin matchFound := matchFound AND ((E4M_VOLUME_SIGNATURES[vtid])[j]=char(buffer[posInBuffer+j-1])); end; if matchFound then begin info^.volumeTypeID := vtid; end; end; info^.volumeTypeName := E4M_VOLUME_FILE_TYPE_NAMES[info^.volumeTypeID]; inc(posInBuffer, 4); if (info^.volumeTypeID=vtidSFS) OR (info^.volumeTypeID=vtidOldE4M) OR (info^.volumeTypeID=vtidE4M) then begin packetID := GetWordFromHeader(buffer, posInBuffer); packetLength := GetWordFromHeader(buffer, posInBuffer); while (posInBuffer<high(buffer)) AND (packetID<>0) do begin case packetID of 1: begin // Nothing atm, just reposition the buffer pointer inc(posInBuffer, packetLength); end; 2: begin remainingInPkt := packetLength; info^.cipherID := GetCipherType(GetWordFromHeader(buffer, posInBuffer)); dec(remainingInPkt, 2); GetWordFromHeader(buffer, posInBuffer); // The key setup iteration count dec(remainingInPkt, 2); for k:=1 to 20 do // that 20 is hardcoded in voltest; according to the SFS docs, it should be the blocksize of the encryption algorithm (20 for SFS) begin GetWordFromHeader(buffer, posInBuffer); // The disk key IV (salt) dec(remainingInPkt, 2); end; if (info^.volumeTypeID=vtidE4M) then begin nKeyLen := E4M_DISKKEY_SIZE; end else begin nKeyLen := SFS_DISKKEY_SIZE; end; dec(remainingInPkt, nKeyLen); for k:=1 to (nKeyLen div 2) do begin GetWordFromHeader(buffer, posInBuffer); // The encrypted disk key end; GetWordFromHeader(buffer, posInBuffer); // Key check value dec(remainingInPkt, 2); if (info^.volumeTypeID=vtidE4M) then begin info^.hashID := GetHashType(GetWordFromHeader(buffer, posInBuffer)); dec(remainingInPkt, 2); end; // Reposition the position in the buffer to skip anything else in this // packet inc(posInBuffer, remainingInPkt); end; end; // case packetID of packetID := GetWordFromHeader(buffer, posInBuffer); packetLength := GetWordFromHeader(buffer, posInBuffer); end; // while (posInBuffer<high(buffer)) AND (packetID<>0) do end; // if info^.volumeType<>VOLUME_FILE_TYPE[high(VOLUME_FILE_TYPE)] then info^.hashName := E4M_HASH_NAMES[info.hashID]; info^.cipherName := E4M_CIPHER_NAMES[info^.cipherID]; info^.volumeFilename := volumeFilename; end; Result := TRUE; end; function TOTFEE4M.GetWordFromHeader(buffer: array of byte; var posInBuffer: integer): cardinal; begin Result := (buffer[posInBuffer-1] * 256) + buffer[posInBuffer]; inc(posInBuffer, 2); end; function TOTFEE4M.GetCipherName(cipherID: integer): string; var i: E4M_CIPHER_TYPE; begin Result := ''; for i:=low(E4M_CIPHER_IDS) to high(E4M_CIPHER_IDS) do begin if E4M_CIPHER_IDS[i]=cipherID then begin Result := E4M_CIPHER_NAMES[i]; end; end; end; function TOTFEE4M.GetDriveInfo(driveLetter: Ansichar): TOTFEE4MVolumeInfo; var i: integer; currInfo: pTOTFEE4MVolumeInfo; begin driveLetter := upcase(driveLetter); UpdateVolInfoList(); for i:=0 to (mtdVolInfoLst.count-1) do begin currInfo := mtdVolInfoLst.Items[i]; if currInfo^.mountedAs = driveLetter then begin Result := currInfo^; end; end; end; function TOTFEE4M.ClearPasswords(driveLetter: AnsiChar): boolean; var dwResult: DWORD; begin Result := DeviceIoControl(hE4MVxD, E4M_WIPE_CACHE, nil, 0, nil, 0, dwResult, nil); { TODO 1 -otdk -cinvestigate : doesnt use drive letter } end; function TOTFEE4M.IsEncryptedVolFile(volumeFilename: string): boolean; begin CheckActive(); Result := FSupportScramDisk AND VersionCanSupportScramDiskVols(); if not(Result) then begin Result := IsE4MorSFSEncryptedVolFile(volumeFilename); end; end; // Return TRUE if the volume file specified is a E4M or SFS volume, otherwise // FALSE function TOTFEE4M.IsE4MorSFSEncryptedVolFile(volumeFilename: string): boolean; var junk: boolean; begin Result := IsE4MorSFSEncryptedVolFile(volumeFilename, junk); end; function TOTFEE4M.IsE4MorSFSEncryptedVolFile(volumeFilename: string; var cancelled: boolean): boolean; var info: pTOTFEE4MVolumeInfo; begin cancelled := FALSE; if IsFilePartition(volumeFilename) then begin Result := TRUE; end else begin volumeFilename := SDUConvertSFNToLFN(volumeFilename); new(info); if GetVolumeInfo(volumeFilename, info) then begin Result := not((info^.volumeTypeID = vtidUnknown) OR (info^.volumeTypeID = vtidScramDisk)); end else begin Result := (GetDriveForVolFile(volumeFilename)<>#0); end; dispose(info); end; end; // Remove any drive entries that are no longer mounted, and add records for any // drives that have been mounted, but don't yet have a record procedure TOTFEE4M.UpdateVolInfoList(); var i: integer; mtdDrives: Ansistring; currInfo: pTOTFEE4MVolumeInfo; volFilenames: TStringList; posInStr: integer; begin volFilenames:= TStringList.Create(); try GetDisksMounted(mtdDrives, volFilenames); for i:=(mtdVolInfoLst.count-1) downto 0 do begin currInfo := mtdVolInfoLst.Items[i]; posInStr := pos(currInfo^.mountedAs, mtdDrives); if posInStr=0 then begin mtdVolInfoLst.Delete(i); dispose(currInfo); end else begin delete(mtdDrives, posInStr, 1); volFilenames.Delete(posInStr-1); end; end; for i:=1 to length(mtdDrives) do begin new(currInfo); currInfo^.volumeFilename := volFilenames[i-1]; currInfo^.mountedAs := mtdDrives[i]; currInfo^.cipherID := cphrUnknown; currInfo^.cipherName := E4M_CIPHER_NAMES[currInfo^.cipherID]; currInfo^.hashID := hashUnknown; currInfo^.hashName := E4M_HASH_NAMES[currInfo^.hashID]; if IsFilePartition(currInfo^.volumeFilename) then begin currInfo^.volumeTypeID := vtidE4MSDSDevice; currInfo^.volumeTypeName := E4M_VOLUME_FILE_TYPE_NAMES[currInfo^.volumeTypeID]; end else begin currInfo^.volumeTypeID := vtidUnknown; currInfo^.volumeTypeName := E4M_VOLUME_FILE_TYPE_NAMES[currInfo^.volumeTypeID]; end; currInfo^.readonly := IsDriveReadonly(mtdDrives[i]); mtdVolInfoLst.Add(currInfo); end; finally volFilenames.Free(); end; end; function TOTFEE4M.GetHashType(hashID: integer): E4M_HASH_TYPE; var hashLoop: E4M_HASH_TYPE; begin Result := high(E4M_HASH_IDS); for hashLoop:=low(E4M_HASH_IDS) to high(E4M_HASH_IDS) do begin if E4M_HASH_IDS[hashLoop]=hashID then begin Result := hashLoop; end; end; end; function TOTFEE4M.GetCipherType(cipherID: integer): E4M_CIPHER_TYPE; var cipherLoop: E4M_CIPHER_TYPE; begin Result := high(E4M_CIPHER_IDS); for cipherLoop:=low(E4M_CIPHER_IDS) to high(E4M_CIPHER_IDS) do begin if E4M_CIPHER_IDS[cipherLoop]=cipherID then begin Result := cipherLoop; end; end; end; function TOTFEE4M.Title(): string; begin Result := 'E4M'; end; function TOTFEE4M.Version(): cardinal; var driverVers: TOTFEE4M_VERSION; dwResult: DWORD; begin CheckActive(); if E4MDriverVersion=$FFFFFFFF then begin if DeviceIoControl(hE4MVxD, E4M_DRIVER_VERSION, @driverVers, sizeof(driverVers), @driverVers, sizeof(driverVers), dwResult, nil) then begin E4MDriverVersion := driverVers.version; end else begin // v2.00 didn't support getting the driver version, so it must be that // version if E4MDriverVersion=$FFFFFFFF then begin E4MDriverVersion := $200; end; end; end; Result := E4MDriverVersion; end; function TOTFEE4M.CloseSlot(driveNum: integer; brutal: boolean): boolean; begin if (ld(driveNum, 1)) then begin Result := FALSE; // xxx - Setup error code here // *err = ERR_FILES_OPEN_LOCK; end else begin Result := DoDeviceClose(driveNum); ld(driveNum, 0); end; end; function TOTFEE4M.ld(driveNum: integer; mode: integer): boolean; var a: boolean; drivelett: integer; begin a:= TRUE; drivelett := driveNum + 1; if ((drivelett > 1) AND (drivelett<27)) then begin a := (locklogdrive(drivelett, mode)); end; Result := a; end; // Returns TRUE if error function TOTFEE4M.locklogdrive(drivenum: integer; mode: integer): boolean; var a: integer; begin if (mode<>0) then begin ioctllock(drivenum, 0, 1); a := ioctllock(drivenum, 4, 1); end else begin a := 0; ioctllock(drivenum, 0, 0); ioctllock(drivenum, 0, 0); end; Result := (a<>0); end; function TOTFEE4M.ioctllock(nDrive: cardinal; permissions: integer; func: integer): integer; var hDevice: THANDLE; reg: TDeviceIOControlRegisters; cb: DWORD; lockfunc: integer; begin if (func<>0) then begin lockfunc := $4a; end else begin lockfunc := $6a; end; hDevice := CreateFile('\\.\vwin32', 0, 0, nil, 0, FILE_FLAG_DELETE_ON_CLOSE, 0); reg.reg_EAX := $440D; reg.reg_EBX := nDrive; reg.reg_ECX := $0800 OR lockfunc; reg.reg_EDX := permissions; reg.reg_Flags := $0001; DeviceIoControl(hDevice, VWIN32_DIOC_DOS_IOCTL, @reg, sizeof(reg), @reg, sizeof(reg), cb, nil); CloseHandle (hDevice); Result := (reg.reg_Flags AND 1); // error if carry flag is set end; function TOTFEE4M.DoDeviceClose(driveNum: integer): boolean; var mount_list: TOTFEE4M_9x_MOUNT_LIST_N_STRUCT; unmount: TOTFEE4M_UNMOUNT; tries: integer; c: integer; dwBytes: DWORD; volFilename: string; begin mount_list.nDosDriveNo := driveNum; if (DeviceIoControl(hE4MVxD, E4M_9x_MOUNT_LIST_N, @mount_list, sizeof(mount_list), nil, 0, dwBytes, nil) = FALSE) then begin // xxx - Setup error code here // *err = ERR_OS_ERROR; Result := FALSE; exit; end else begin if (mount_list.nReturnCode<>0) then begin // xxx - Setup error code here // *err = mount_list.nReturnCode; Result := TRUE; exit; end; end; if (mount_list.mountfilehandle<>0) then begin ShortArrayToString(mount_list.wszVolume, volFilename); EjectStop(AnsiChar(upcase(volFilename[1])), FALSE); end; unmount.nDosDriveNo := driveNum; if (DeviceIoControl (hE4MVxD, E4M_UNMOUNT_PENDING, @unmount, sizeof(unmount), nil, 0, dwBytes, nil) = FALSE) then begin // xxx - Setup error code here //*err = ERR_OS_ERROR; Result := FALSE; exit; end else begin if (mount_list.nReturnCode<>0) then begin // xxx - Setup error code here //*err = mount_list.nReturnCode; Result := TRUE; exit; end; end; for c:=0 to 19 do begin DeviceIoControl(hE4MVxD, RELEASE_TIME_SLICE, nil, 0, nil, 0, dwBytes, nil); end; for tries:=0 to 31 do begin DeviceIoControl (hE4MVxd, RELEASE_TIME_SLICE, nil, 0, nil, 0, dwBytes, nil); if (DeviceIoControl (hE4MVxd, E4M_UNMOUNT, @unmount, sizeof(UNMOUNT), nil, 0, dwBytes, nil) = FALSE) then begin // xxx - Setup error code here // *err = ERR_OS_ERROR; Result := FALSE; exit; end else begin if (mount_list.nReturnCode=0) then begin // xxx - Setup error code here // *err = 0; Result := TRUE; exit; end; end; end; // xxx - Setup error code here // *err = ERR_FILES_OPEN_LOCK; Result := TRUE; end; function TOTFEE4M.EjectStop(driveLetter: Ansichar; func: boolean): boolean; var hDevice: THANDLE; reg: TDeviceIOControlRegisters; cb: DWORD; lockfunc: integer; p: TPARAMBLOCK; driveNum: integer; begin if (driveletter = #0) then begin Result := FALSE; exit; end; driveNum := ord('A') - ord(driveLetter) + 1; lockfunc := $48; if (func = TRUE) then begin p.Operation := 0; // lock end else begin p.Operation := 1; end; hDevice := CreateFile('\\.\vwin32', 0, 0, nil, 0, FILE_FLAG_DELETE_ON_CLOSE, 0); reg.reg_EAX := $440D; reg.reg_EBX := driveNum; reg.reg_ECX := $0800 OR lockfunc; reg.reg_EDX := Cardinal(@p); // xxx - Not sure if this will work OK? reg.reg_Flags := $0001; DeviceIoControl(hDevice, VWIN32_DIOC_DOS_IOCTL, @reg, sizeof(reg), @reg, sizeof(reg), cb, nil); CloseHandle (hDevice); Result := (reg.reg_Flags AND 1)>0; // error if carry flag is set */ end; function TOTFEE4M.GetCachePasswordInDriver(): boolean; var iniFile: TIniFile; begin iniFile := TIniFile.Create(E4M_INI_FILE); try Result := iniFile.ReadBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_CACHEINDRIVER, FALSE); finally iniFile.Free(); end; end; procedure TOTFEE4M.SetCachePasswordInDriver(cache: boolean); var iniFile: TIniFile; begin if SaveHistory then begin iniFile := TIniFile.Create(E4M_INI_FILE); try iniFile.WriteBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_CACHEINDRIVER, cache); finally iniFile.Free(); end; end; end; function TOTFEE4M.GetMountWarning(): boolean; var iniFile: TIniFile; begin iniFile := TIniFile.Create(E4M_INI_FILE); try Result := iniFile.ReadBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_NOMOUNTWARNING, FALSE); finally iniFile.Free(); end; end; procedure TOTFEE4M.SetMountWarning(mountWarning: boolean); var iniFile: TIniFile; begin // This setting is not affected by the no history switch iniFile := TIniFile.Create(E4M_INI_FILE); try iniFile.WriteBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_NOMOUNTWARNING, mountWarning); finally iniFile.Free(); end; end; function TOTFEE4M.GetDefaultDrive(): Ansichar; var iniFile: TIniFile; dfltDrvColon: string; begin Result := #0; iniFile := TIniFile.Create(E4M_INI_FILE); try dfltDrvColon := iniFile.ReadString(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_DRIVELETTER, ''); if dfltDrvColon<>'' then begin Result := AnsiChar( dfltDrvColon[1]); end; finally iniFile.Free(); end; end; procedure TOTFEE4M.SetDefaultDrive(dfltDrive: Ansichar); var iniFile: TIniFile; begin if SaveHistory then begin iniFile := TIniFile.Create(E4M_INI_FILE); try iniFile.WriteString(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_DRIVELETTER, upcase(dfltDrive)+':'); finally iniFile.Free(); end; end; end; function TOTFEE4M.GetSaveHistory(): boolean; var iniFile: TIniFile; begin iniFile := TIniFile.Create(E4M_INI_FILE); try Result := not(iniFile.ReadBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_NEVERSAVEHISTORY, TRUE)); finally iniFile.Free(); end; end; procedure TOTFEE4M.SetSaveHistory(save: boolean); var iniFile: TIniFile; begin iniFile := TIniFile.Create(E4M_INI_FILE); try iniFile.WriteBool(E4M_INI_SECTION_LASTRUN, E4M_INI_KEY_NEVERSAVEHISTORY, save); finally iniFile.Free(); end; end; procedure TOTFEE4M.AddVolumeToHistory(volumeFilename: string); var i: integer; key: string; iniFile: TIniFile; lastVol: string; historyMRU: TStringList; begin if SaveHistory then begin iniFile := TIniFile.Create(E4M_INI_FILE); try historyMRU:= TStringList.Create(); try for i:=1 to E4M_SIZEOF_MRU_LIST do begin key := E4M_INI_KEY_LASTVOLUMEn + inttostr(i); historyMRU.Add(iniFile.ReadString(E4M_INI_SECTION_LASTRUN, key, '')); end; // if volumeFilename does not exist in the list, add it. If it does // exist, move it to the head of the list. if historyMRU.IndexOf(volumeFilename)<0 then begin historyMRU.Add(lastVol); end else begin historyMRU.Delete(historyMRU.IndexOf(volumeFilename)); historyMRU.Insert(0, volumeFilename); end; for i:=1 to E4M_SIZEOF_MRU_LIST do begin key := E4M_INI_KEY_LASTVOLUMEn + inttostr(i); iniFile.WriteString(E4M_INI_SECTION_LASTRUN, key, historyMRU[i-1]); end; finally historyMRU.Free(); end; finally iniFile.Free(); end; end; end; function TOTFEE4M.GetNextUnusedDrvLtr(afterDrv: Ansichar): Ansichar; var finished: boolean; unusedDrvs: Ansistring; begin Result := #0; finished := FALSE; unusedDrvs := GetUnusedDriveLetters(); while not(finished) do begin afterDrv := AnsiChar(ord(afterDrv)+1); { TODO 1 -otdk -cinvestigate : why isnt this just using chars? } if ord(afterDrv)>ord('Z') then begin finished := TRUE; end else begin if pos(afterDrv, unusedDrvs)>0 then begin Result := afterDrv; finished := TRUE; end; end; end; end; // Returns a string containing the drive letters of "unallocated" drives function TOTFEE4M.GetUnusedDriveLetters(): Ansistring; var driveLetters: Ansistring; DriveNum: Integer; DriveBits: set of 0..25; begin driveLetters := ''; Integer(DriveBits) := GetLogicalDrives; for DriveNum := 0 to 25 do begin if not(DriveNum in DriveBits) then begin driveLetters := driveLetters + AnsiChar(DriveNum + Ord('A')); end; end; Result := driveLetters; end; function TOTFEE4M.VersionStr(): string; var verNo: cardinal; majorVer : integer; minorVer1: integer; minorVer2: integer; begin verNo:= Version(); majorVer := (verNo AND $FF00) div $FF; minorVer1 := (verNo AND $F0) div $F; minorVer2 := (verNo AND $F); Result := Format('v%d.%d.%d', [majorVer, minorVer1, minorVer2]); end; // For ScramDisk volumes, get the 4 passwords and SHA1 them together function TOTFEE4M.GetScramDiskPasswords(dlgTitle: string; var passwordDigest: Ansistring; var driveLetter: Ansichar): boolean; var hashObj: THashAlgSHA1; tempPasswordDigest: THashArray; tempPasswordString: string; passwordEntryDlg: TOTFEE4MScramDiskPasswordEntry_F; i: integer; j: integer; drvLtrsFree: Ansistring; tempDriveLetter: Ansichar; begin Result := FALSE; passwordEntryDlg := TOTFEE4MScramDiskPasswordEntry_F.create(nil); try passwordEntryDlg.ckHidePasswords.visible := not(FHidePasswordsEnteredCk); // The user should be prompted for the drive letter, and offered the // default drvLtrsFree := GetUnusedDriveLetters(); tempDriveLetter := DefaultDrive; if pos(tempDriveLetter, drvLtrsFree)<1 then begin tempDriveLetter := GetNextUnusedDrvLtr(driveLetter); end; passwordEntryDlg.DrivesAllowed := drvLtrsFree; passwordEntryDlg.Drive := tempDriveLetter; passwordEntryDlg.caption := dlgTitle; if (passwordEntryDlg.showmodal=mrOK) then begin tempPasswordString := Format('%160s', ['x']); tempPasswordString := passwordEntryDlg.mePassword1.text + Format('%'+inttostr(40-length(passwordEntryDlg.mePassword1.text))+'s', [#0]) + passwordEntryDlg.mePassword2.text + Format('%'+inttostr(40-length(passwordEntryDlg.mePassword2.text))+'s', [#0]) + passwordEntryDlg.mePassword3.text + Format('%'+inttostr(40-length(passwordEntryDlg.mePassword3.text))+'s', [#0]) + passwordEntryDlg.mePassword4.text + Format('%'+inttostr(40-length(passwordEntryDlg.mePassword4.text))+'s', [#0]); // Clear down the dialog's passwords passwordEntryDlg.ClearEnteredPasswords(); hashObj := THashAlgSHA1.Create(nil); try tempPasswordDigest := hashObj.HashString(tempPasswordString); // Destroy copy of the passwords for i:=1 to 160 do begin tempPasswordString[i] := char(Random(256)); end; tempPasswordString := ''; // OK, because the driver effectively expects the hashed passwords to // be passed to it as a set of 4 DWORDs, we need to setup the digest // in the format: // byte# 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16 passwordDigest := ''; for i:=0 to 4 do begin for j:=0 to 3 do begin passwordDigest := passwordDigest + Ansichar(tempPasswordDigest[(i*4)+(3-j)]); tempPasswordDigest[(i*4)+(3-j)] := Random(256); end; end; finally hashObj.Free(); end; driveLetter := passwordEntryDlg.Drive; Result := TRUE; end // if (passwordEntryDlg.showmodal=mrOK) then else begin passwordEntryDlg.ClearEnteredPasswords(); FLastErrCode := OTFE_ERR_USER_CANCEL; end; finally passwordEntryDlg.free; end; end; procedure TOTFEE4M.SetSupportScramDisk(support: boolean); begin if not(support) then begin FSupportScramDisk := FALSE; end else begin CheckActive(); if VersionCanSupportScramDiskVols() then begin FSupportScramDisk := support; end else begin FSupportScramDisk := FALSE; end; end; end; function TOTFEE4M.VersionCanSupportScramDiskVols(): boolean; begin Result := (Version() = $200); end; function TOTFEE4M.GetMainExe(): string; var registry: TRegistry; keyName: string; appPath: string; exeLocation: string; begin Result := ''; FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE; registry := TRegistry.create(); try registry.RootKey := HKEY_CLASSES_ROOT; keyName := E4M_REGISTRY_ENTRY_PATH; if registry.OpenKeyReadOnly(keyName) then begin appPath := registry.ReadString(''); exeLocation := ExtractFilePath(appPath) + E4M_APP_EXE_NAME; if FileExists(exeLocation) then begin Result := exeLocation end; registry.CloseKey; end; finally registry.Free(); end; if Result<>'' then begin FLastErrCode:= OTFE_ERR_SUCCESS; end; end; function TOTFEE4M.GetAvailableRemovables(dispNames: TStringList; deviceNames: TStringList): integer; var cnt: integer; szTmp: array [0..E4M_MAX_PATH-1] of char; begin cnt := 0; if CurrentOS=E4M_OS_WIN_NT then begin if (QueryDosDevice('A:', @szTmp[0], sizeof(szTmp))<>0) then begin dispNames.Add('Floppy (A:)'); deviceNames.Add('\Device\Floppy0'); inc(cnt); end; if (QueryDosDevice('B:', @szTmp[0], sizeof(szTmp))<>0) then begin dispNames.Add('Floppy (B:)'); deviceNames.Add('\Device\Floppy1'); inc(cnt); end; end; Result := cnt; end; function TOTFEE4M.GetAvailableFixedDisks(dispNames: TStringList; deviceNames: TStringList): integer; var i: integer; n: integer; cnt: integer; strTmp: string; begin cnt := 0; i := 0; while (i<64) do begin for n:=1 to E4M_HDD_MAX_PARTITIONS do begin strTmp := Format(E4M_HDD_PARTITION_DEVICE_NAME_FORMAT, [i, n]); if OpenDevice(strTmp) then begin dispNames.Add(strTmp); deviceNames.Add(strTmp); inc(cnt); end else begin if n=1 then begin i := 64; break; end; end; end; inc(i); end; Result := cnt; end; function TOTFEE4M.OpenDevice(device: string): boolean; var driver200: TOTFEE4M_200_OPEN_TEST; driver201: TOTFEE4M_201_OPEN_TEST; dwResult: DWORD; currAllOK: boolean; i: integer; begin CheckActive(); for i:=1 to length(device) do begin driver200.wszFileName[i] := WCHAR(device[i]); end; driver200.wszFileName[length(device)+1] := #0; StringToShortArray(device, driver201.wszFileName); { // xxx - is this needed? if CurrentOS=E4M_OS_WIN_NT then begin ToUNICODE ((char *) &driver->wszFileName[0]); end; } if E4MDriverVersion=$200 then begin currAllOK := DeviceIoControl(hE4MVxD, E4M_OPEN_TEST, @driver200, sizeof(driver200), @driver200, sizeof(driver200), dwResult, nil); Result := currAllOK; if not(currAllOK) then begin dwResult := GetLastError (); Result := (dwResult = ERROR_SHARING_VIOLATION); end; end else begin currAllOK := DeviceIoControl(hE4MVxD, E4M_OPEN_TEST, @driver201, sizeof(driver201), @driver201, sizeof(driver201), dwResult, nil); if not(currAllOK) then begin dwResult := GetLastError(); Result := (dwResult = ERROR_SHARING_VIOLATION); end else begin if CurrentOS=E4M_OS_WIN_NT then begin Result := TRUE; end else if (driver201.nReturnCode = 0) then begin Result := TRUE; end else begin // xxx - Setup error code here // SetLastError(ERROR_FILE_NOT_FOUND); Result := FALSE; end; end; end; end; function TOTFEE4M.GetAvailableRawDevices(dispNames: TStringList; deviceNames: TStringList): boolean; var stlTempDisp: TStringList; stlTempDevice: TStringList; begin CheckActive(); dispNames.Clear(); deviceNames.Clear(); GetAvailableRemovables(dispNames, deviceNames); stlTempDisp:= TStringList.Create(); try stlTempDevice:= TStringList.Create(); try GetAvailableFixedDisks(stlTempDisp, stlTempDevice); dispNames.AddStrings(stlTempDisp); deviceNames.AddStrings(stlTempDevice); finally stlTempDevice.Free(); end; finally stlTempDisp.Free(); end; Result := TRUE; end; // This function is required as v2.0.1's short arrays are used: // Under NT to store WCHARs // Under 95/98 to store chars // as a result of this, we need to extract data from these arrays with in the // correct way, depending on the OS being used... // i.e. This function will take an E4M array of short and convert it back into // a string procedure TOTFEE4M.ShortArrayToString(theArray: array of short; var theString: string); var i: integer; hiNotLo: boolean; shortChar: short; begin theString := ''; if CurrentOS<>E4M_OS_WIN_NT then begin i:=0; hiNotLo:= TRUE; shortChar := (theArray[0] AND $FF); while shortChar<>0 do begin theString := theString + chr(shortChar); hiNotLo := not(hiNotLo); shortChar := theArray[i]; if hiNotLo then begin shortChar := shortChar AND $FF; end else begin shortChar := (shortChar AND $FF00) shr 8; inc(i); end; end; end else begin i:=0; shortChar := theArray[0]; while shortChar<>0 do begin theString := theString + char(shortChar); inc(i); shortChar := theArray[i];; end; end; end; // This function is required as v2.0.1's short arrays are used: // Under NT to store WCHARs // Under 95/98 to store chars // as a result of this, we need to fill in these arrays with correctly packed // data, depending on the OS being used // i.e. This function will take a string and put it into an E4M array of short procedure TOTFEE4M.StringToShortArray(theString: string; var theArray: array of short); var i: integer; hiNotLo: boolean; arrPos: integer; begin theString := theString + #0; if CurrentOS<>E4M_OS_WIN_NT then begin hiNotLo:= TRUE; arrPos := 0; theArray[arrPos] := 0; for i:=1 to length(theString) do begin if hiNotLo then begin theArray[arrPos] := ord(theString[i]); end else begin theArray[arrPos] := theArray[arrPos] OR ord(theString[i]) shl 8; inc(arrPos); theArray[arrPos] := 0; end; hiNotLo := not(hiNotLo); end; end else begin for i:=1 to length(theString) do begin theArray[i-1] := short(WCHAR(theString[i])); end; end; end; function TOTFEE4M.IsFilePartition(volumeFilename: string): boolean; begin Result := (pos('\DEVICE\', uppercase(volumeFilename))=1); end; // ----------------------------------------------------------------------------- // Prompt the user for a device (if appropriate) and password (and drive // letter if necessary), then mount the device selected // Returns the drive letter of the mounted devices on success, #0 on failure function TOTFEE4M.MountDevices(): Ansistring; var mntDeviceDlg: TOTFEE4MMountDevice_F; finished: boolean; begin Result := ''; if MountDeviceDlg9xStyle then begin mntDeviceDlg := TOTFEE4MMountDevice9x_F.Create(nil); end else begin mntDeviceDlg := TOTFEE4MMountDeviceNT_F.Create(nil); end; try mntDeviceDlg.E4MComponent := self; if mntDeviceDlg.ShowModal()=mrOK then begin finished:=FALSE; while not(finished) do begin Result := Mount(mntDeviceDlg.PartitionDevice, FALSE); finished := (Result<>#0); if not(finished) then begin finished := (LastErrorCode<>OTFE_ERR_WRONG_PASSWORD); if not(finished) then begin MessageDlg('Wrong passsword entered; try again', mtError, [mbOK], 0); end; end; end; end; finally mntDeviceDlg.Free(); end; end; // ----------------------------------------------------------------------------- // Determine if OTFE component can mount devices. // Returns TRUE if it can, otherwise FALSE function TOTFEE4M.CanMountDevice(): boolean; begin // Supported... Result := TRUE; end; // ----------------------------------------------------------------------------- END.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type TTextItem = class(TCustomControl) private procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS; procedure WMImeChar(var Msg: TMessage); message WM_IME_CHAR; procedure WMImeComposition(var Msg: TMessage); message WM_IME_COMPOSITION; procedure WMImeNotify(var Msg: TMessage); message WM_IME_NOTIFY; procedure WMChar(var Msg: TWMChar); message WM_CHAR; procedure WMGetText(var Msg: TWMGetText); message WM_GETTEXT; procedure WMGetTextLength(var Msg: TWMGetTextLength); message WM_GETTEXTLENGTH; procedure WMSetText(var Msg: TWMSetText); message WM_SETTEXT; procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY; private FMyText: string; procedure InitializeCaret; procedure Process(Value: WideString); protected procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TForm3 = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } FTextItem: TTextItem; public { Public declarations } end; var Form3: TForm3; implementation uses Winapi.Imm, System.WideStrUtils; // Winapi.Windows; {$R *.dfm} procedure TForm3.FormCreate(Sender: TObject); begin FTextItem := TTextItem.Create(Self); FTextItem.Parent := Self; FTextItem.Left := 100; FTextItem.Top := 100; // FTextItem.Text := 'test'; end; { TTextItem } constructor TTextItem.Create(AOwner: TComponent); begin inherited; Height := 150; Width := 200; Cursor := crIBeam; Color := clDefault; ControlStyle := ControlStyle + [csOpaque, csSetCaption]; ParentFont := False; ParentColor := False; TabStop := True; end; procedure TTextItem.CreateParams(var Params: TCreateParams); begin StrDispose(WindowText); WindowText := nil; inherited CreateParams(Params); // // with Params do // begin // Style := Style or WS_BORDER or WS_CLIPCHILDREN; // // if NewStyleControls and Ctl3D then // begin // Style := Style and not WS_BORDER; // ExStyle := ExStyle or WS_EX_CLIENTEDGE; // // avoid flicker while scrolling or resizing // if not (csDesigning in ComponentState) and CheckWin32Version(5, 1) then // ExStyle := ExStyle or WS_EX_COMPOSITED; // end; // end; end; destructor TTextItem.Destroy; begin inherited Destroy; end; procedure TTextItem.InitializeCaret; begin CreateCaret(Handle, 0, 2, 14); SetCaretPos(10, 10); ShowCaret(Handle); end; procedure TTextItem.Paint; begin inherited; Canvas.TextOut(10, 10, FMyText); end; procedure TTextItem.Process(Value: WideString); begin OutputDebugString(PChar(Value)); end; procedure TTextItem.WMChar(var Msg: TWMChar); var C: Char; begin C := Char(Msg.CharCode); Text := Text + C; end; procedure TTextItem.WMDestroy(var Message: TWMDestroy); begin // if WindowText = nil then // WindowText := 'test'; inherited; end; procedure TTextItem.WMGetText(var Msg: TWMGetText); begin WStrLCopy(PWideChar(Msg.Text), PWideChar(Text), Msg.TextMax - 1); Msg.Result := WStrLen(PWideChar(Msg.Text)); end; procedure TTextItem.WMGetTextLength(var Msg: TWMGetTextLength); begin // if csDocking in ControlState then // Msg.Result := 0 // else // Msg.Result := Length(Text); end; procedure TTextItem.WMImeChar(var Msg: TMessage); begin end; procedure TTextItem.WMImeComposition(var Msg: TMessage); var imc: HIMC; PW: PWideChar; PA: PAnsiChar; PWLength: Integer; ImeCount: Integer; begin if (Msg.LParam and GCS_RESULTSTR) <> 0 then begin imc := ImmGetContext(Handle); try ImeCount := ImmGetCompositionStringW(imc, GCS_RESULTSTR, nil, 0); // ImeCount is always the size in bytes, also for Unicode GetMem(PW, ImeCount + sizeof(WideChar)); try ImmGetCompositionStringW(imc, GCS_RESULTSTR, PW, ImeCount); PW[ImeCount div sizeof(WideChar)] := #0; Process(PW); // CommandProcessor(ecImeStr, #0, PW); finally FreeMem(PW); end; finally ImmReleaseContext(Handle, imc); end; end; inherited; end; procedure TTextItem.WMImeNotify(var Msg: TMessage); var imc: HIMC; LogFontW: TLogFontW; LogFontA: TLogFontA; begin with Msg do begin case WParam of IMN_SETOPENSTATUS: begin imc := ImmGetContext(Handle); if imc <> 0 then begin GetObjectW(Font.Handle, SizeOf(TLogFontW), @LogFontW); ImmSetCompositionFontW(imc, @LogFontW); ImmReleaseContext(Handle, imc); end; end; end; end; inherited; end; procedure TTextItem.WMSetFocus(var Msg: TWMSetFocus); begin InitializeCaret; end; procedure TTextItem.WMSetText(var Msg: TWMSetText); begin Msg.Result := 1; try FMyText := FMyText + PChar(Msg.Text); InvaliDate; except Msg.Result := 0; raise end end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Editor for a vector. } unit FVectorEditor; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Objects, VXS.VectorGeometry, VXS.VectorTypes, VXS.Utils; type TVXVectorEditorForm = class(TForm) SBPlusX: TSpeedButton; SBPlusY: TSpeedButton; SBPlusZ: TSpeedButton; SBMinusX: TSpeedButton; SBMinusY: TSpeedButton; SBMinusZ: TSpeedButton; SBNull: TSpeedButton; SBUnit: TSpeedButton; SBNormalize: TSpeedButton; SBInvert: TSpeedButton; EdZ: TEdit; EdY: TEdit; EdX: TEdit; Label3: TLabel; Label2: TLabel; Label1: TLabel; ButtonOK: TButton; ButtonCancel: TButton; ImX: TImage; ImY: TImage; ImZ: TImage; ImageOK: TImage; ImageCancel: TImage; procedure SBPlusXClick(Sender: TObject); procedure SBPlusYClick(Sender: TObject); procedure SBPlusZClick(Sender: TObject); procedure SBNullClick(Sender: TObject); procedure SBNormalizeClick(Sender: TObject); procedure SBMinusXClick(Sender: TObject); procedure SBMinusYClick(Sender: TObject); procedure SBMinusZClick(Sender: TObject); procedure SBUnitClick(Sender: TObject); procedure SBInvertClick(Sender: TObject); private vx, vy, vz: Single; procedure TestInput(edit: TEdit; imError: TImage; var dest: Single); public function Execute(var x, y, z: Single): Boolean; end; var vVectorEditorForm: TVXVectorEditorForm; function GLVectorEditorForm: TVXVectorEditorForm; procedure ReleaseVectorEditorForm; implementation {$R *.fmx} function GLVectorEditorForm: TVXVectorEditorForm; begin if not Assigned(vVectorEditorForm) then vVectorEditorForm := TVXVectorEditorForm.Create(nil); Result := vVectorEditorForm; end; procedure ReleaseVectorEditorForm; begin if Assigned(vVectorEditorForm) then begin vVectorEditorForm.Free; vVectorEditorForm := nil; end; end; { TVectorEditorForm } function TVXVectorEditorForm.Execute(var x, y, z: Single): Boolean; begin // setup dialog fields vx := x; vy := y; vz := z; EDx.Text := FloatToStr(vx); EDy.Text := FloatToStr(vy); EDz.Text := FloatToStr(vz); // show the dialog Result := (ShowModal = mrOk); if Result then begin x := vx; y := vy; z := vz; end; end; procedure TVXVectorEditorForm.SBPlusXClick(Sender: TObject); begin EDx.Text := '1'; EDy.Text := '0'; EDz.Text := '0'; end; procedure TVXVectorEditorForm.SBPlusYClick(Sender: TObject); begin EDx.Text := '0'; EDy.Text := '1'; EDz.Text := '0'; end; procedure TVXVectorEditorForm.SBPlusZClick(Sender: TObject); begin EDx.Text := '0'; EDy.Text := '0'; EDz.Text := '1'; end; procedure TVXVectorEditorForm.SBUnitClick(Sender: TObject); begin EDx.Text := '1'; EDy.Text := '1'; EDz.Text := '1'; end; procedure TVXVectorEditorForm.SBInvertClick(Sender: TObject); var v: TAffineVector; begin SetVector(v, VXS.Utils.StrToFloatDef(EDx.Text, 0), VXS.Utils.StrToFloatDef(EDy.Text, 0), VXS.Utils.StrToFloatDef(EDz.Text, 0)); NegateVector(v); EDx.Text := FloatToStr(v.x); EDy.Text := FloatToStr(v.y); EDz.Text := FloatToStr(v.z); end; procedure TVXVectorEditorForm.SBMinusXClick(Sender: TObject); begin EDx.Text := '-1'; EDy.Text := '0'; EDz.Text := '0'; end; procedure TVXVectorEditorForm.SBMinusYClick(Sender: TObject); begin EDx.Text := '0'; EDy.Text := '-1'; EDz.Text := '0'; end; procedure TVXVectorEditorForm.SBMinusZClick(Sender: TObject); begin EDx.Text := '0'; EDy.Text := '0'; EDz.Text := '-1'; end; procedure TVXVectorEditorForm.SBNormalizeClick(Sender: TObject); var v: TAffineVector; begin SetVector(v, VXS.Utils.StrToFloatDef(EDx.Text, 0), VXS.Utils.StrToFloatDef(EDy.Text, 0), VXS.Utils.StrToFloatDef(EDz.Text, 0)); if VectorLength(v) = 0 then v := NullVector else NormalizeVector(v); EDx.Text := FloatToStr(v.x); EDy.Text := FloatToStr(v.y); EDz.Text := FloatToStr(v.z); end; procedure TVXVectorEditorForm.SBNullClick(Sender: TObject); begin EDx.Text := '0'; EDy.Text := '0'; EDz.Text := '0'; end; procedure TVXVectorEditorForm.TestInput(edit: TEdit; imError: TImage; var dest: Single); begin if Visible then begin try dest := StrToFloat(edit.Text); imError.Visible := False; except imError.Visible := True; end; ButtonOk.Enabled := not(IMx.Visible or IMy.Visible or IMz.Visible); end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ finalization ReleaseVectorEditorForm; end.
{------------------------------------------------------------------------------- Unit Name: frmGeosimGrid Author: HochwimmerA Purpose: Used to enter data for a geothermal simulation grid (e.g. TOUGH) History: -------------------------------------------------------------------------------} unit frmGeosimGrid; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Grids, DBGrids, ComCtrls, ExtCtrls, ActnList, DB, {kbmMemTable,} XPStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, geImportFile, ImgList,cGLSimulationGrids,cUtilities; type TGridMode =(gmTOUGH,gmTETRAD); TformGeoGrid = class(TForm) pcGridInformation: TPageControl; pnlBottom: TPanel; tsVertices: TTabSheet; dbgVertices: TDBGrid; bOK: TBitBtn; ActionManager: TActionManager; dsVertices: TDataSource; GEImportFile: TGEImportFile; ImageList: TImageList; tsLayers: TTabSheet; dbgLayers: TDBGrid; dsLayers: TDataSource; tsBlocks: TTabSheet; acImport: TAction; dbgBlocks: TDBGrid; dsBlocks: TDataSource; tsVertexOrder: TTabSheet; dbgVertexOrder: TDBGrid; dsVertexOrder: TDataSource; tsRocks: TTabSheet; dbgRocks: TDBGrid; dsRocks: TDataSource; tsRockDist: TTabSheet; dsRockDistribution: TDataSource; dbgRockDist: TDBGrid; tsPartial: TTabSheet; dsPartialLayers: TDataSource; dbgPartialLayers: TDBGrid; ColorDialog: TColorDialog; BitBtn1: TBitBtn; ActionToolBar: TActionToolBar; acOK: TAction; tsPTS: TTabSheet; dsPTS: TDataSource; dbgPTS: TDBGrid; tsTETRAD: TTabSheet; dbgTETRADGrid: TDBGrid; dsTETRAD: TDataSource; tsTETRADRocks: TTabSheet; dbgTETRADRocks: TDBGrid; dsTETRADRocks: TDataSource; tsTETRADPTS: TTabSheet; dsTETRADPTS: TDataSource; dbgTETRADPTS: TDBGrid; ///kbmTETRAD: TkbmMemTable; ///kbmTETRADRocks: TkbmMemTable; ///kbmTETRADPTS: TkbmMemTable; ///kbmBlocks: TkbmMemTable; ///kbmVertices: TkbmMemTable; ///kbmLayers: TkbmMemTable; ///kbmVertexOrder: TkbmMemTable; ///kbmRocks: TkbmMemTable; ///kbmRockDist: TkbmMemTable; ///kbmPartialLayers: TkbmMemTable; ///kbmPTS: TkbmMemTable; procedure FormShow(Sender: TObject); procedure pcGridInformationChange(Sender: TObject); procedure acImportExecute(Sender: TObject); procedure dbgRocksDblClick(Sender: TObject); procedure dbgRocksDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); private public gm: TGridMode; iRow,iCol : integer; procedure SaveGrid(aGrid:TGLSimulationGrid;var bl:TStringlist); end; implementation {$R *.dfm} // ----- TformGeoGrid.SaveGrid ------------------------------------------------- // populates aGrid with data from the memory tables} procedure TformGeoGrid.SaveGrid(aGrid:TGLSimulationGrid;var bl:TStringList); var sBlock,sRock,sVertex,sLayer,slayerType,sTemp:string; x,y,dElevation,dThickness:double; i : integer; sl : TStringList; bActive:boolean; begin (* // importing a TOUGH/MULKOM style grid if (gm = gmTOUGH) then begin // Vertices with kbmVertices do begin First; while not eof do begin sVertex:=FieldByName('Vertex').AsString; x := FieldByName('Location E').AsFloat; y := FieldByName('Location N').AsFloat; aGrid.AddVertex(sVertex,x,y); Next; end; end; // Layers with kbmLayers do begin SortOn('Elevation',[]); // order descending First; while not eof do begin sLayer := FieldByName('Layer').AsString; sLayerType := FieldByName('Layer Type').AsString; dElevation := FieldByName('Elevation').AsFloat; dThickness := FieldByName('Thickness').AsFloat; aGrid.GridLayers.AddLayer(sLayer,sLayerType,dElevation,dThickness); Next; end; end; // rocks with kbmRocks do begin First; while not eof do begin aGrid.AddRockType( FieldByName('Rock Code').AsString, FieldByName('Permeability-X').AsFloat, FieldByName('Permeability-Y').AsFloat, FieldByName('Permeability-Z').AsFloat, FieldByName('Porosity').AsFloat, FieldByName('Thermal Conductivity').AsFloat, FieldByName('Specific Heat').AsFloat, FieldByName('Colour Code').AsString); Next; end; end; // adding blocks bl.clear; with kbmBlocks do begin First; while not eof do begin sBlock := FieldByName('Grid Block').AsString; if (bl.IndexOf(sBlock)=-1) then bl.Add(sBlock); x := FieldByName('Location E').AsFloat; y := FieldByName('Location N').AsFloat; // loop over layers; for i:=0 to aGrid.GridLayers.LayerList.Count-1 do begin sLayer := aGrid.GridLayers.GLLayer[i].LayerName; if (agrid.GridLayers.GLLayer[i].LayerType <> 'P') then agrid.GridLayers.GLLayer[i].AddBlock(sBlock,x,y) end; Next; end; end; // partial layers with kbmPartialLayers do begin First; while not eof do begin sLayer := FieldByName('Grid Layer').AsString; sBlock := FieldByName('Grid Block').AsString; if kbmBlocks.Locate('Grid Block',sBlock,[]) then begin TGLGridLayer(aGrid.GridLayers.GetGLLayerByName(slayer)).AddBlock( sBlock, kbmBlocks.FieldByName('Location E').AsFloat, kbmBlocks.FieldByName('Location N').AsFloat); end; Next; end; end; // grid rock types with kbmRockDist do begin First; while not eof do begin sLayer := FieldByName('Grid Layer').AsString; sBlock := FieldByName('Grid Block').AsString; sRock := FieldByName('Rock Type').AsString; // get the right layer + block - needs safety check with aGrid.GridLayers.GetGLLayerByName(sLayer) do begin if (GetBlockByName(sBlock) <> nil) then GetBlockByname(sBlock).RockTypeCode := sRock; end; Next; end; end; // PTS? with kbmPTS do begin First; while not eof do begin sLayer := FieldByName('Grid Layer').AsString; sBlock := FieldByName('Grid Block').AsString; // obtain the correct layer and the correct blockn with aGrid.GridLayers.GetGLLayerByName(sLayer) do begin if (GetBlockByName(sBlock) <> nil) then with GetBlockByName(sBlock) do begin Pr := FieldByName('Pressure').AsFloat; Te := FieldByName('Temperature').AsFloat; Sv := FieldByName('Saturation').AsFloat; end; end; Next; end; end; sl := TStringList.Create; with kbmVertexOrder do begin First; sBlock := ''; while not eof do begin if (sBlock <> FieldByName('Grid Block').AsString) then begin if sl.Count>0 then begin for i:=0 to agrid.GRidLayers.LayerList.Count-1 do begin if (LowerCase(agrid.GridLayers.GLLayer[i].LayerType) <> 'p') then TGLGridLayer(agrid.GridLayers.GLLayer[i]).AddVertexOrder(sBlock,sl) else begin if (TGLGridLayer(agrid.GridLayers.GLLayer[i]).GetBlockByName(sBlock) <> nil) then TGLGridLayer(agrid.GridLayers.GLLayer[i]).AddVertexOrder(sBlock,sl) end; end; end; sl.Clear; sBlock := FieldByName('Grid Block').AsString; end; sl.Add(FieldByName('Grid Vertex').AsString); Next; if eof then begin for i:=0 to agrid.GRidLayers.LayerList.Count-1 do begin with TGLGridLayer(aGrid.GridLayers.GLLayer[i]) do begin if (LowerCase(LayerType) <> 'p') then AddVertexOrder(sBlock,sl) else if (GetBlockByName(sBlock) <> nil) then AddVertexOrder(sBlock,sl) end; end; end; end; end; sl.Free; end else if (gm = gmTETRAD) then begin with kbmTETRAD do begin i := -1; iRow := 0; iCol := 0; DisableControls; First; sLayer := ''; while not eof do begin sTemp := FieldByName('Layer').AsString; if (sTemp <> sLayer) then begin Inc(i); sLayer := sTemp; aGrid.GridLayers.AddTETRADLayer(sLayer); end; bActive := true; if kbmTETRADPTS.Locate('Block',VarArrayOf( [FieldByName('Block').AsString]),[]) then bActive := (kbmTETRADPTS.FieldByName('Active Block').AsInteger = 1); if FieldByName('Row').AsInteger > iRow then iRow := FieldByName('Row').AsInteger; if FieldByName('Column').AsInteger > iCol then iCol := FieldByName('Column').AsInteger; TGLGridLayer(aGrid.GridLayers.GetGLLayerByName(slayer)).AddTETRADBlock( FieldByName('Block').AsString, FieldByName('Location E').AsFloat, FieldByName('Location N').AsFloat, FieldByName('Elevation').AsFloat, FieldByName('Thickness').AsFloat, FieldByName('dX').AsFloat, FieldByName('dY').AsFloat, FieldByName('Row').AsInteger, FieldByName('Column').AsInteger, bActive); if kbmTETRADRocks.Locate('Block',VarArrayOf([FieldByName('Block').AsString]),[]) then begin aGrid.AddRockType(kbmTETRADRocks.FieldByName('Block').AsString, kbmTETRADRocks.FieldByName('Permeability-X').AsFloat, kbmTETRADRocks.FieldByName('Permeability-Y').AsFloat, kbmTETRADRocks.FieldByName('Permeability-Z').AsFloat, kbmTETRADRocks.FieldByName('Porosity').AsFloat, 0.0,0.0,'ff0000'); end; if kbmTETRADPTS.Locate('Block',VarArrayOf( [FieldByName('Block').AsString]),[]) then begin with aGrid.GridLayers.GLLayer[i] do begin if (GetBlockByName(FieldByName('Block').AsString) <> nil) then with GetBlockByName(FieldByName('Block').AsString) do begin Pr := kbmTETRADPTS.FieldByName('Pressure').AsFloat; Te := kbmTETRADPTS.FieldByName('Temperature').AsFloat; Sv := kbmTETRADPTS.FieldByName('Vapour Saturation').AsFloat; end; end; end; with aGrid.GridLayers.GetGLLayerByName(sLayer) do begin if (GetBlockByName(FieldByName('Block').AsString) <> nil) then GetBlockByname(FieldByName('Block').AsString).RockTypeCode := FieldByName('Block').AsString; end; Next; end; EnableControls; end; end; *) end; // ----- TformGeoGrid.FormShow ------------------------------------------------- procedure TformGeoGrid.FormShow(Sender: TObject); begin (* // assumes that the gridmode (GM) has been set prior: if (gm = gmTOUGH) then begin GEImportFile.Identifier := 'vertices'; GEImportFile.Destination := kbmVertices; // show and hide tabs tsVertices.TabVisible := true; tsLayers.TabVisible := true; tsBlocks.TabVisible := true; tsVertexOrder.TabVisible := true; tsRocks.TabVisible := true; tsRockDist.TabVisible := true; tsPartial.TabVisible := true; tsPTS.TabVisible := true; tsTETRAD.TabVisible := false; tsTETRADRocks.TabVisible := false; tsTETRADPTS.TabVisible := false; pcGridInformation.ActivePage := tsVertices; end else if (gm = gmTETRAD) then begin GEImportFile.Identifier := 'tetrad'; GEImportFile.Destination := kbmTETRAD; // show and hide tabs tsVertices.TabVisible := false; tsLayers.TabVisible := false; tsBlocks.TabVisible := false; tsVertexOrder.TabVisible := false; tsRocks.TabVisible := false; tsRockDist.TabVisible := false; tsPartial.TabVisible := false; tsPTS.TabVisible := false; tsTETRAD.TabVisible := true; tsTETRADRocks.TabVisible := true; tsTETRADPTS.TabVisible := true; pcGRidInformation.ActivePage := tsTETRAD; end; *) end; // ----- TformGeoGrid.pcGridInformationChange ---------------------------------- procedure TformGeoGrid.pcGridInformationChange(Sender: TObject); begin (* if (pcGridInformation.ActivePage=tsVertices) then begin GEImportFile.Identifier := 'vertices'; GEImportFile.Destination := kbmVertices; end else if (pcGridInformation.ActivePage=tsLayers) then begin GEImportFile.Identifier := 'layers'; GEImportFile.Destination := kbmLayers; end else if (pcGridInformation.ActivePage = tsBlocks) then begin GEImportFile.Identifier := 'blocks'; GEImportFile.Destination := kbmBlocks; end else if (pcGridInformation.ActivePage = tsVertexOrder) then begin GEImportFile.Identifier := 'vertexorder'; GEImportFile.Destination := kbmVertexOrder; end else if (pcGridInformation.ActivePage = tsRocks) then begin GEImportFile.Identifier := 'rocks'; GEImportFile.Destination := kbmRocks; end else if (pcGridInformation.ActivePage = tsRockDist) then begin GEImportFile.Identifier := 'rockdistribution'; GEImportFIle.Destination := kbmRockDist; end else if (pcGridInformation.ActivePage = tsPartial) then begin GEImportFile.Identifier := 'partiallayers'; GEImportFile.Destination := kbmPartialLayers; end else if (pcGridInformation.ActivePage = tsPTS) then begin GEImportFile.Identifier := 'pts'; GEImportFile.Destination := kbmPTS; end else if (pcGridInformation.ActivePage = tsTETRAD) then begin GEImportFile.Identifier := 'tetrad'; GEImportFile.Destination := kbmTETRAD; end else if (pcGridInformation.ActivePage = tsTETRADRocks) then begin GEImportFile.Identifier := 'tetradrocks'; GEImportFile.Destination := kbmTETRADRocks; end else if (pcGridInformation.ActivePage = tsTETRADPTS) then begin GEImportFile.Identifier := 'tetradpts'; GEImportFile.Destination := kbmTETRADPTS; end; *) end; // ----- TformGeoGrid.acImportBlocksExecute ------------------------------------ procedure TformGeoGrid.acImportExecute(Sender: TObject); begin GEImportFile.Execute; end; // ----- TformGeoGrid.dbgRocksDblClick ----------------------------------------- procedure TformGeoGrid.dbgRocksDblClick(Sender:TObject); begin (* if (dbgRocks.Columns.Items[dbgRocks.SelectedIndex].FieldName = 'Colour Code') then begin ColorDialog.Color := HexToColor(kbmRocks.FieldByName('Colour Code').AsString); if ColorDialog.Execute then begin kbmRocks.Edit; kbmRocks.FieldByName('Colour Code').AsString := ColorToHex(ColorDialog.Color); kbmRocks.Post; end; end; *) end; // ----- TformGeoGrid.dbgRocksDrawColumnCell ----------------------------------- procedure TformGeoGrid.dbgRocksDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if (Column.Field.FieldName <> 'Colour Code') then dbgRocks.DefaultDrawColumnCell(Rect,DataCol,Column,State) else {** Colour} begin if (Column.Field.DisplayText = '') then dbgRocks.Canvas.Brush.Color := clWhite else try dbgRocks.Canvas.Brush.Color := HexToColor(Column.Field.DisplayText); except dbgRocks.Canvas.Brush.Color := clWhite; end; dbgRocks.DefaultDrawColumnCell(Rect,DataCol,Column,State); end; end; // ============================================================================= end.
unit Chapter06._01_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils, DeepStar.UString; // 20. Valid Parentheses // https://leetcode.com/problems/valid-parentheses/description/ // 时间复杂度: O(n) // 空间复杂度: O(n) type TSolution = class(TObject) public function isValid(s: UString): boolean; end; procedure Main; implementation procedure Main; begin with TSolution.Create do begin WriteLn(isValid('()')); WriteLn(isValid('()[]{}')); WriteLn(isValid('(]')); WriteLn(isValid('([)]')); Free; end; end; { TSolution } function TSolution.isValid(s: UString): boolean; var stack: TStack_chr; i: integer; match, c: UChar; begin stack := TStack_chr.Create; try for i := 0 to Length(s) - 1 do begin if (s.Chars[i] = '(') or (s.Chars[i] = '[') or (s.Chars[i] = '{') then stack.Push(s.Chars[i]) else begin if stack.IsEmpty then Exit(false); if s.Chars[i] = ')' then match := '(' else if s.Chars[i] = ']' then match := '[' else match := '{'; c := stack.Pop; if c <> match then Exit(false); end; end; Result := stack.IsEmpty; finally stack.Free; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CONTABIL_PARAMETRO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ContabilParametroVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TContabilParametroVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FMASCARA: String; FNIVEIS: Integer; FINFORMAR_CONTA_POR: String; FCOMPARTILHA_PLANO_CONTA: String; FCOMPARTILHA_HISTORICOS: String; FALTERA_LANCAMENTO_OUTRO: String; FHISTORICO_OBRIGATORIO: String; FPERMITE_LANCAMENTO_ZERADO: String; FGERA_INFORMATIVO_SPED: String; FSPED_FORMA_ESCRIT_DIARIO: String; FSPED_NOME_LIVRO_DIARIO: String; FASSINATURA_DIREITA: String; FASSINATURA_ESQUERDA: String; FCONTA_ATIVO: String; FCONTA_PASSIVO: String; FCONTA_PATRIMONIO_LIQUIDO: String; FCONTA_DEPRECIACAO_ACUMULADA: String; FCONTA_CAPITAL_SOCIAL: String; FCONTA_RESULTADO_EXERCICIO: String; FCONTA_PREJUIZO_ACUMULADO: String; FCONTA_LUCRO_ACUMULADO: String; FCONTA_TITULO_PAGAR: String; FCONTA_TITULO_RECEBER: String; FCONTA_JUROS_PASSIVO: String; FCONTA_JUROS_ATIVO: String; FCONTA_DESCONTO_OBTIDO: String; FCONTA_DESCONTO_CONCEDIDO: String; FCONTA_CMV: String; FCONTA_VENDA: String; FCONTA_VENDA_SERVICO: String; FCONTA_ESTOQUE: String; FCONTA_APURA_RESULTADO: String; FCONTA_JUROS_APROPRIAR: String; FID_HIST_PADRAO_RESULTADO: Integer; FID_HIST_PADRAO_LUCRO: Integer; FID_HIST_PADRAO_PREJUIZO: Integer; //Transientes published property Id: Integer read FID write FID; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property Mascara: String read FMASCARA write FMASCARA; property Niveis: Integer read FNIVEIS write FNIVEIS; property InformarContaPor: String read FINFORMAR_CONTA_POR write FINFORMAR_CONTA_POR; property CompartilhaPlanoConta: String read FCOMPARTILHA_PLANO_CONTA write FCOMPARTILHA_PLANO_CONTA; property CompartilhaHistoricos: String read FCOMPARTILHA_HISTORICOS write FCOMPARTILHA_HISTORICOS; property AlteraLancamentoOutro: String read FALTERA_LANCAMENTO_OUTRO write FALTERA_LANCAMENTO_OUTRO; property HistoricoObrigatorio: String read FHISTORICO_OBRIGATORIO write FHISTORICO_OBRIGATORIO; property PermiteLancamentoZerado: String read FPERMITE_LANCAMENTO_ZERADO write FPERMITE_LANCAMENTO_ZERADO; property GeraInformativoSped: String read FGERA_INFORMATIVO_SPED write FGERA_INFORMATIVO_SPED; property SpedFormaEscritDiario: String read FSPED_FORMA_ESCRIT_DIARIO write FSPED_FORMA_ESCRIT_DIARIO; property SpedNomeLivroDiario: String read FSPED_NOME_LIVRO_DIARIO write FSPED_NOME_LIVRO_DIARIO; property AssinaturaDireita: String read FASSINATURA_DIREITA write FASSINATURA_DIREITA; property AssinaturaEsquerda: String read FASSINATURA_ESQUERDA write FASSINATURA_ESQUERDA; property ContaAtivo: String read FCONTA_ATIVO write FCONTA_ATIVO; property ContaPassivo: String read FCONTA_PASSIVO write FCONTA_PASSIVO; property ContaPatrimonioLiquido: String read FCONTA_PATRIMONIO_LIQUIDO write FCONTA_PATRIMONIO_LIQUIDO; property ContaDepreciacaoAcumulada: String read FCONTA_DEPRECIACAO_ACUMULADA write FCONTA_DEPRECIACAO_ACUMULADA; property ContaCapitalSocial: String read FCONTA_CAPITAL_SOCIAL write FCONTA_CAPITAL_SOCIAL; property ContaResultadoExercicio: String read FCONTA_RESULTADO_EXERCICIO write FCONTA_RESULTADO_EXERCICIO; property ContaPrejuizoAcumulado: String read FCONTA_PREJUIZO_ACUMULADO write FCONTA_PREJUIZO_ACUMULADO; property ContaLucroAcumulado: String read FCONTA_LUCRO_ACUMULADO write FCONTA_LUCRO_ACUMULADO; property ContaTituloPagar: String read FCONTA_TITULO_PAGAR write FCONTA_TITULO_PAGAR; property ContaTituloReceber: String read FCONTA_TITULO_RECEBER write FCONTA_TITULO_RECEBER; property ContaJurosPassivo: String read FCONTA_JUROS_PASSIVO write FCONTA_JUROS_PASSIVO; property ContaJurosAtivo: String read FCONTA_JUROS_ATIVO write FCONTA_JUROS_ATIVO; property ContaDescontoObtido: String read FCONTA_DESCONTO_OBTIDO write FCONTA_DESCONTO_OBTIDO; property ContaDescontoConcedido: String read FCONTA_DESCONTO_CONCEDIDO write FCONTA_DESCONTO_CONCEDIDO; property ContaCmv: String read FCONTA_CMV write FCONTA_CMV; property ContaVenda: String read FCONTA_VENDA write FCONTA_VENDA; property ContaVendaServico: String read FCONTA_VENDA_SERVICO write FCONTA_VENDA_SERVICO; property ContaEstoque: String read FCONTA_ESTOQUE write FCONTA_ESTOQUE; property ContaApuraResultado: String read FCONTA_APURA_RESULTADO write FCONTA_APURA_RESULTADO; property ContaJurosApropriar: String read FCONTA_JUROS_APROPRIAR write FCONTA_JUROS_APROPRIAR; property IdHistPadraoResultado: Integer read FID_HIST_PADRAO_RESULTADO write FID_HIST_PADRAO_RESULTADO; property IdHistPadraoLucro: Integer read FID_HIST_PADRAO_LUCRO write FID_HIST_PADRAO_LUCRO; property IdHistPadraoPrejuizo: Integer read FID_HIST_PADRAO_PREJUIZO write FID_HIST_PADRAO_PREJUIZO; //Transientes end; TListaContabilParametroVO = specialize TFPGObjectList<TContabilParametroVO>; implementation initialization Classes.RegisterClass(TContabilParametroVO); finalization Classes.UnRegisterClass(TContabilParametroVO); end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clHttpUtils; interface {$I clVer.inc} uses Classes; const cDefaultHttpPort = 80; cDefaultHttpProxyPort = 8080; type TclAuthenticationType = (atBasic, atAutoDetect); TclHttpVersion = (hvHttp1_0, hvHttp1_1); TclHttpProxySettings = class(TPersistent) protected FAuthenticationType: TclAuthenticationType; FUserName: string; FPassword: string; FServer: string; FPort: Integer; public constructor Create; procedure Assign(Source: TPersistent); override; procedure Clear; published property AuthenticationType: TclAuthenticationType read FAuthenticationType write FAuthenticationType default atAutoDetect; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Server: string read FServer write FServer; property Port: Integer read FPort write FPort default cDefaultHttpProxyPort; end; resourcestring cInternetAgent = 'Mozilla/4.0 (compatible; Clever Internet Suite 6.2)'; implementation { TclHttpProxySettings } procedure TclHttpProxySettings.Assign(Source: TPersistent); var Src: TclHttpProxySettings; begin if (Source is TclHttpProxySettings) then begin Src := (Source as TclHttpProxySettings); AuthenticationType := Src.AuthenticationType; UserName := Src.UserName; Password := Src.Password; Server := Src.Server; Port := Src.Port; end else begin inherited Assign(Source); end; end; procedure TclHttpProxySettings.Clear; begin FAuthenticationType := atAutoDetect; FPort := cDefaultHttpProxyPort; FUserName := ''; FPassword := ''; FServer := ''; end; constructor TclHttpProxySettings.Create; begin inherited Create; Clear(); end; end.
unit uGeneral; interface uses JsonDataObjects, Ils.Json.Names, Ils.Json.Utils, Geo.Hash.Search, System.SysUtils, System.Generics.Collections, System.Classes, Ils.Logger, UFiles, System.IniFiles, AStar64.Files, AStar64.Areas, AStar64.Extra, Geo.Pos, Ils.Redis.Conf, Redis.Client, Geo.Hash, AStar64.FileStructs, System.Types; const CDateTimeFormat : string = 'yyyy"."mm"."dd" "hh":"nn":"ss"."zzz'; C1KmLongitude = 0.01595863; C1KmLatitude = 0.008993216; CSAVE_ROUTE_NAME_ACCESS_DENIED = 12; CSAVE_ROUTE_FILE_ACCESS_DENIED = 13; CSAVE_ALL_ZONE_FILES_ERROR = 14; CREDIS_ERROR = 15; CLOAD_ROUTE_NAME_ACCESS_DENIED = 16; COTHER_ERROR = 17; CAllErrors = 17; //типы эксепшенов, которые пишутся в редис CErrorNames : array [1..CAllErrors] of string = ('ASTAR_REQUEST_TOO_SHORT_BUFFER', //-1 'ASTAR_REQUEST_NOT_ASSIGNED', //-2 'ASTAR_REQUEST_WRONG_VERSION', //-3 'ASTAR_HAS_WRONG_FILE_VERSION', //-4 'ASTAR_TIMEOUT', //-5 'ASTAR_NOT_ENOUGH_MEMORY', //-6 'ASTAR_FILE_NOT_FOUND', //-7 'ASTAR_NO_WAY_FOUND', //-8 'ASTAR_NEAR_EDGE_NOT_FOUND', //-9 'ASTAR_ERROR_UNKNOWN_ERROR', //-10 'ASTAR_ZONE_FILE_WRONG_SIZE', //-11 'SAVE_ROUTE_NAME_ACCESS_DENIED', 'SAVE_ROUTE_FILE_ACCESS_DENIED', 'SAVE_ALL_ZONE_FILES_ERROR', 'REDIS_CONNECTION_ERROR', 'LOAD_ROUTE_NAME_ACCESS_DENIED', 'OTHER_ERROR'); type TChangeBorder = packed record LastChange: TDateTime; TopLeft: TGeoPos; BottomRight: TGeoPos; end; TAccountChangeBorder = TDictionary<Integer,TChangeBorder>; //Архитектура зависимостей для аккаунтов TAccountsArch = TDictionary<Integer, TIntegerDynArray>; TErrArray = array [1..CAllErrors] of Integer; TGeneral = class private public class var Ffs: TFormatSettings; class var FPort: Integer; class var FRedisPostPeriod: Integer; class var FTimerInterval: Cardinal; class var FTimerRedisInterval: Cardinal; class var FRedisConf: TRedisConf; class var FUseAStarDll: boolean; class var FRedisConnected: boolean; class var FRedisCli: TRedisClient; class var FMinRealRouteLengthM: Integer; class var FMinDistToLineM: Integer; class var FAStarTimeout: Integer; class var FDetailLog: Boolean; class var FRadius: Integer; class var FSuffix: string; class var FRedisInstanceName: string; class var FRedisInstance: string; class var FRedisWatchdogInstanceName: string; class var FRedisWatchdogInstance: string; class var FLandMarkMaxDist: Double; class var FCountCPUForLandMarkCalc: Integer; class var FLandMarkCalcTimeout: Integer; class var FStop: Boolean; class var FAccountsArch: TAccountsArch; class var FAccountChangeBorder: TAccountChangeBorder; class var FRedisBorderIncKm: Integer; //счетчик эксепшенов, которые пишутся в редис class var FRedisWatchdogArr, FTempArr: TErrArray; class var FBorderValues: array of string; class procedure Start(AIniFileName: string = ''); class procedure Stop; class procedure ClearWatchdog(var AArr: TErrArray); class function GetJsonForRedis(const AAccounts: TIntegerDynArray;TopLeft, BottomRight: TGeoPos): TJsonObject; class function GetJsonForWatchdog(AArray: TErrArray): TJsonObject; class function GetForWatchdog(ARedisCli: TRedisClient; var AArray: TErrArray): Boolean; class procedure IncWatchdog(ANum: integer); class procedure SendJsonForWatchdog(AJson: TJsonObject; ARedisCli: TRedisClient); class procedure SendWatchdog; class procedure SendAccountBorder(const AAccounts: TIntegerDynArray; ARedisCli: TRedisClient); class function IntArrToString(AArr: array of Integer): string; class function GetCorrectBorder(ABorder: TGeoPosArray): TGeoPosArray; end; implementation { TGeneral } class procedure TGeneral.ClearWatchdog(var AArr: TErrArray); var i: Integer; begin for I := Low(AArr) to High(AArr) do AArr[i] := 0; end; class function TGeneral.GetCorrectBorder(ABorder: TGeoPosArray): TGeoPosArray; begin Result := ABorder; if Length(ABorder)<>2 then Exit; if ABorder[0].Latitude < ABorder[1].Latitude then begin Result[0].Latitude := ABorder[1].Latitude; Result[1].Latitude := ABorder[0].Latitude; end; if ABorder[0].Longitude > ABorder[1].Longitude then begin Result[0].Longitude := ABorder[1].Longitude; Result[1].Longitude := ABorder[0].Longitude; end; end; class function TGeneral.GetForWatchdog(ARedisCli: TRedisClient; var AArray: TErrArray): Boolean; var sValue, sKey: string; Json: TJsonObject; i: Integer; begin Result := False; sKey := FRedisWatchdogInstance+'_'+FRedisWatchdogInstanceName; // ToLog('TGeneral.GetForWatchdog'); if FRedisConf.Enabled and Assigned(FRedisCli) then begin try FRedisCli.Disconnect; FRedisCli.Connect; if FRedisConf.Password <> '' then FRedisCli.AUTH(FRedisConf.Password); if not ARedisCli.EXISTS(sKey) then begin Exit(True); end; if ARedisCli.GET(sKey, sValue) then begin // ToLog('ARedisCli.GET='+sValue+ ' key='+skey); FRedisConnected := True; Result := True; if FDetailLog then ToLog('Get from Redis' + ' Key = ' + sKey + ' Value =' + sValue); Json := TJsonObject(TJsonObject.Parse(sValue)); for I := Low(AArray) to High(AArray) do AArray[i] := Json.I[CErrorNames[i]]; // ToLog('GetForWatchdog. AArray='+IntArrToString(AArray)); end else if FDetailLog then ToLog('Not get from Redis' + ' Key = ' + sKey + ' Value =' + sValue); except on E : Exception do begin TGeneral.IncWatchdog(CREDIS_ERROR); FRedisConnected := False; ToLog('TGeneral.GetForWatchdog. Redis client NOT connected '+FRedisConf.Host+':'+IntToStr(FRedisConf.Port)+'. '+E.Message); end; end; end; end; class function TGeneral.GetJsonForRedis(const AAccounts: TIntegerDynArray; TopLeft, BottomRight: TGeoPos): TJsonObject; var PointsArr1: TGeoPathPointArray; sBorder: string; i: Integer; begin Result := TJsonObject.Create; //расширяем прямоугольник TopLeft.Latitude := TopLeft.Latitude + C1KmLatitude * FRedisBorderIncKm; TopLeft.Longitude := TopLeft.Longitude - C1KmLongitude * FRedisBorderIncKm; BottomRight.Latitude := BottomRight.Latitude - C1KmLatitude * FRedisBorderIncKm; BottomRight.Longitude := BottomRight.Longitude + C1KmLongitude * FRedisBorderIncKm; SetLength(PointsArr1,2); PointsArr1[0].p := TopLeft; PointsArr1[1].p := BottomRight; sBorder := TGeoHash.EncodeArrayAnyFormat(PointsArr1, 12, gfPath); Result.S['Operation'] := 'ReCalc'; for I := High(AAccounts) downto Low(AAccounts) do Result.A['Accounts'].Add(AAccounts[i]); Result.S['Border'] := sBorder; end; class function TGeneral.GetJsonForWatchdog(AArray: TErrArray): TJsonObject; var i: Integer; begin Result := TJsonObject.Create; Result.S['LastTime'] := FormatDateTime(CDateTimeFormat, Now()); for I := Low(AArray) to High(AArray) do Result.I[CErrorNames[i]] := AArray[i]; end; class procedure TGeneral.IncWatchdog(ANum: integer); begin if ANum in [Low(FRedisWatchdogArr)..High(FRedisWatchdogArr)] then Inc(FRedisWatchdogArr[ANum]); end; class function TGeneral.IntArrToString(AArr: array of Integer): string; var i: Integer; begin Result := ''; for I := Low(AArr) to High(AArr) do Result := Result + IntToStr(AArr[i]) + ','; Delete(Result, Length(Result),1); end; class procedure TGeneral.SendAccountBorder(const AAccounts: TIntegerDynArray; ARedisCli: TRedisClient); var Border: TChangeBorder; sValue, sKey: string; iRPUSH, i: Integer; begin sKey := FRedisInstance+'_'+FRedisInstanceName; if FAccountChangeBorder.TryGetValue(AAccounts[0], Border) then begin if Border.LastChange <> 0 then begin sValue := GetJsonForRedis(AAccounts, Border.TopLeft, Border.BottomRight).ToString; SetLength(FBorderValues, Length(FBorderValues) + 1); FBorderValues[High(FBorderValues)] := sValue; ToLog('Length FBorderValues='+IntToStr(Length(FBorderValues))+ ', LastVal='+FBorderValues[High(FBorderValues)]); end; if FRedisConf.Enabled and Assigned(FRedisCli) and (Length(FBorderValues) > 0) then try FRedisCli.Disconnect; FRedisCli.Connect; if FRedisConf.Password <> '' then FRedisCli.AUTH(FRedisConf.Password); FRedisConnected := True; iRPUSH := ARedisCli.RPUSH(sKey, FBorderValues); if iRPUSH > 0 then begin // if FDetailLog then begin sValue := ''; for I := Low(FBorderValues) to High(FBorderValues) do sValue := sValue + FBorderValues[i] + ','; Delete(sValue, Length(sValue), 1); if FDetailLog then ToLog('Send to Redis'+' Res='+IntToStr(iRPUSH) + ' Key = ' + sKey+ ' Value =' + sValue ); end; SetLength(FBorderValues, 0); end else if FDetailLog then ToLog('Not send to Redis' + ' Res='+IntToStr(iRPUSH)+ ' Key = ' + sKey); except on E: Exception do begin FRedisConnected := False; TGeneral.IncWatchdog(CREDIS_ERROR); ToLog('TGeneral.SendAccountBorder. Redis client NOT connected '+FRedisConf.Host+':'+IntToStr(FRedisConf.Port)+'. '+E.Message); end; end; { Border.LastChange := 0; Border.TopLeft.Latitude := 0; Border.TopLeft.Longitude := 180; Border.BottomRight.Latitude := 90; Border.BottomRight.Longitude := 0; FAccountChangeBorder.AddOrSetValue(AAccounts[0], Border);} end; end; class procedure TGeneral.SendJsonForWatchdog(AJson: TJsonObject; ARedisCli: TRedisClient); var sValue, sKey: string; // sValues: array of string; begin sValue := AJson.ToString; sKey := FRedisWatchdogInstance+'_'+FRedisWatchdogInstanceName; // SetLength(sValues, 1); // sValues[0] := sValue; if FRedisConf.Enabled and Assigned(FRedisCli) then try FRedisCli.Disconnect; FRedisCli.Connect; FRedisConnected := True; if FRedisConf.Password <> '' then FRedisCli.AUTH(FRedisConf.Password); if ARedisCli.&SET(sKey, sValue) then begin ClearWatchdog(FRedisWatchdogArr); // ToLog('SendJsonForWatchdog. FRedisWatchdogArr = ' +IntArrToString(FRedisWatchdogArr)); // ToLog('SendJsonForWatchdog. FTempArr = ' +IntArrToString(FTempArr)); if FDetailLog then ToLog('Send to Redis'+ ' Value =' + sValue + ' Key = ' + sKey) end else if FDetailLog then ToLog('Not send to Redis' + ' Value =' + sValue + ' Key = ' + sKey); except on E: Exception do begin TGeneral.IncWatchdog(CREDIS_ERROR); FRedisConnected := False; ToLog('TGeneral.SendJsonForWatchdog. Redis client NOT connected '+FRedisConf.Host+':'+IntToStr(FRedisConf.Port)+'. '+E.Message); end; end; end; class procedure TGeneral.SendWatchdog; var i: Integer; begin //получаем текущее значение // ToLog('TGeneral.SendWatchdog'); ClearWatchdog(FTempArr); if GetForWatchdog(FRedisCli, FTempArr) then begin // ToLog('TGeneral.SendWatchdog FRedisWatchdogArr = ' +IntArrToString(FRedisWatchdogArr)); // ToLog('TGeneral.SendWatchdog FTempArr = ' +IntArrToString(FTempArr)); //складываем с имеющимися for i := Low(FTempArr) to High(FTempArr) do FTempArr[i] := FTempArr[i] + FRedisWatchdogArr[i]; //отправляем сумму SendJsonForWatchdog(GetJsonForWatchdog(FTempArr), FRedisCli); end; end; class procedure TGeneral.Start(AIniFileName: string); var Ini: TIniFile; FileName: string; begin FStop := False; FileName := GetModuleName(HInstance); Ffs := TFormatSettings.Create; Ffs.DecimalSeparator := '.'; if AIniFileName = '' then ini := TIniFile.Create(ChangeFileExt(FileName, '.ini')) else ini := TIniFile.Create(AIniFileName); ToLog('Load ini ' + Ini.FileName); try ClearWatchdog(FRedisWatchdogArr); SetLength(FBorderValues, 0); FRedisInstanceName := ini.ReadString('redis', 'instance_name', 'release'); FRedisInstance := ini.ReadString('redis', 'instance', 'ProjectDistancesTasks'); FRedisWatchdogInstanceName := ini.ReadString('redis', 'watchdog_instance_name', 'watchdog_release'); FRedisWatchdogInstance := ini.ReadString('redis', 'watchdog_instance', 'watchdog'); FTimerInterval := ini.ReadInteger('main', 'timerinterval', 1000); FTimerRedisInterval := ini.ReadInteger('main', 'timerredisinterval', 60); FRedisPostPeriod := ini.ReadInteger('main', 'redispostperiod', 60); FMinRealRouteLengthM := ini.ReadInteger('main', 'minrealroutelengthm', 50); FMinDistToLineM := ini.ReadInteger('main', 'mindisttolinem', 5); FCountCPUForLandMarkCalc := ini.ReadInteger('main', 'cpuforlandmarkcalc', 1); FAStarTimeout := ini.ReadInteger('main', 'astartimeout', 30); FDetailLog := ini.ReadBool('main', 'detaillog', false); FUseAStarDll := ini.ReadBool('main', 'useastardll', false); FRadius := ini.ReadInteger('main', 'radius', 5); FPort := ini.ReadInteger('web', 'port', 7653); FLandMarkMaxDist := ini.ReadFloat('main', 'landmarkmaxdist', 10); FLandMarkCalcTimeout := ini.ReadInteger('main', 'landmarkcalctimeout', 30); FAccountChangeBorder := TDictionary<Integer, TChangeBorder>.Create; FAccountsArch := TDictionary<Integer, TIntegerDynArray>.Create; FRedisConf := TRedisConf.Create(ini); FRedisCli := TRedisClient.Create(FRedisConf.Host, FRedisConf.Port, FRedisConf.SSL); FRedisConnected := False; SetLength(FBorderValues, 0); if FRedisConf.Enabled then try FRedisCli.Connect; FRedisConnected := True; ToLog('Redis client connected '+FRedisConf.Host+':'+IntToStr(FRedisConf.Port)); if FRedisConf.Password <> '' then FRedisCli.AUTH(FRedisConf.Password); except on E: Exception do begin TGeneral.IncWatchdog(CREDIS_ERROR); FRedisConnected := False; ToLog('TGeneral.Start. Redis client NOT connected '+FRedisConf.Host+':'+IntToStr(FRedisConf.Port)); end; end; // GetForWatchdog(FRedisCli); finally Ini.Free; end; end; class procedure TGeneral.Stop; begin FStop := True; FAccountChangeBorder.Free; FAccountsArch.Free; if Assigned(FRedisCli) then FRedisCli.Free; end; end.
program ActivateSidekick; function Sidekick: Boolean; const SKactOffset = $012D; SKverOffset = $012A; type RegPack = record case Integer of 1: (AX,BX,CX,DX,BP,SI,DI,DS,ES,Flags: Integer); 2: (AL,AH,BL,BH,CL,CH,DL,DH : Byte); end; Address = record Offset : Integer; Segment: Integer; end; SKstr = array[1..2] of Char; SKstrPtr = ^SKstr; var SKbios08Trap: Address absolute $0000:$0020 { Sidekick timer tick trap }; SKbios25Trap: Address absolute $0000:$0094 { Sidekick DOS int 25 trap }; SKfound : Boolean; SKstrCheck : SKstrPtr; R : RegPack; begin with SKbios25Trap do SKstrCheck:=Ptr(Segment, Offset-2); SKfound:=(SKstrCheck^ = 'SK'); if not SKfound then begin with SKbios08Trap do SKstrCheck:=Ptr(Segment, Offset-4); SKfound:=(SKstrCheck^ = 'SK'); end; { Check Sidekick version number (must be >= 1.50) } SKfound:=(SKfound and (Mem[Seg(SKstrCheck^): SKverOffset] >= 1) and (Mem[Seg(SKstrCheck^): SKverOffset+1] >= 50)); if SKfound then begin Mem[Seg(SKstrCheck^): SKactOffset]:=1; { Set Sidekick activate flag } Intr($28, R); { Turn control over to Sidekick } end; Sidekick:=SKfound; end { Sidekick }; begin if not Sidekick then Writeln('Sidekick 1.50 or later not loaded'); end.
(* Compute the arithmetic mean of the difference between two matrices using untyped parameters. Test it on two matrices with random numbers. XXX: This solution doesn't use untyped parameters because I couldn't make it work with FPC. *) {$ASSERTIONS ON} type Matrix = array of array of Real; function matRows(mat: Matrix): Integer; begin Result := Length(mat); end; function matCols(mat: Matrix): Integer; begin Assert(matRows(mat) > 0); Result := Length(mat[0]); end; function matInit(mat: Matrix; rows, cols: Integer): Matrix; var irow: Integer; begin Assert(rows > 0); Assert(cols > 0); SetLength(mat,rows); for irow := 0 to (rows-1) do SetLength(mat[irow],cols); Result := mat; end; function matSum(mat: Matrix): Real; var irow, icol: Integer; var rows, cols: Integer; var res: Real; begin res := 0; rows := matRows(mat); cols := matCols(mat); for irow := 0 to (rows-1) do for icol := 0 to (cols-1) do res := res + mat[irow,icol]; Result := res; end; function matLength(mat: Matrix): Real; begin Result := matRows(mat) * matCols(mat); end; function matMean(mat: Matrix): Real; begin Result := matSum(mat) / matLength(mat); end; function matSub(x, y: Matrix): Matrix; var irow, icol: Integer; var rows, cols: Integer; var res: Matrix; begin Assert(matRows(x) = matRows(y)); Assert(matCols(x) = matCols(y)); rows := matRows(x); cols := matCols(x); res := matInit(res, rows, cols); for irow := 0 to (rows-1) do for icol := 0 to (cols-1) do res[irow,icol] := x[irow,icol] - y[irow,icol]; Result := res; end; procedure matPrint(mat: Matrix); var irow, icol: Integer; var rows, cols: Integer; begin rows := matRows(mat); cols := matCols(mat); for irow := 0 to (rows-1) do for icol := 0 to (cols-1) do begin Write(mat[irow,icol]:4:2); if (icol <> (cols-1)) then Write(', ') else WriteLn(''); end; end; var x, y: Matrix; var irow, icol: Integer; var rows, cols: Integer; var i: Integer; begin rows := 5; cols := 4; x := matInit(x, rows, cols); y := matInit(y, rows, cols); i := 0; for irow := 0 to (rows-1) do for icol := 0 to (cols-1) do begin x[irow,icol] := i; i := i + 1; y[irow,icol] := i; end; WriteLn('x:'); matPrint(x); WriteLn(''); WriteLn('y:'); matPrint(y); WriteLn(''); WriteLn('y - x:'); matPrint(matSub(y, x)); WriteLn(''); WriteLn('mean(y - x):'); WriteLn(matMean(matSub(y, x)):4:2); end.
unit FPWinTime; interface uses Global, ArContain; function SortingTime(Sort: TProc): longint; implementation uses Windows; {Для точного измерения времени под Windows в Free PASCAL используется функция QueryPerformanceCounter} function SortTime(Sort: TProc): longint; var start, finish, res: int64; begin QueryPerformanceCounter(res); {Вызывается один раз в начале программы} QueryPerformanceCounter(start); Sort(A); {Участок программы, для которого будет замеряться время выполнения} QueryPerformanceCounter(finish); {примечание: поскольку используются переменные валюты, возвращаются значения в 10000 раз меньше чем фактические показания счетчиков } {http://support.microsoft.com/kb/172338/ru} SortTime := 100*10000 * (finish - start) div res; end; function SortingTime(Sort: TProc): longint; var CurTime: array [1..count] of word; i, min, max: word; begin SortTime(Sort); SortTime(Sort); for i := 1 to count do CurTime[i] := SortTime(Sort); min := 1; max := 1; for i := 2 to count do begin if CurTime[i] < CurTime[min] then min := i else if CurTime[i] > CurTime[max] then max := i; end; CurTime[min] := 0; CurTime[max] := 0; for i := 2 to count do CurTime[1] := CurTime[1] + CurTime[i]; SortingTime := CurTime[1] div (Count - 2); end; end.
unit InflatablesList_Item_IO_00000008; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, Graphics, AuxTypes, InflatablesList_Item_IO; type TILItem_IO_00000008 = class(TILItem_IO) protected fFNSaveToStreamPlain: procedure(Stream: TStream) of object; fFNLoadFromStreamPlain: procedure(Stream: TStream) of object; fFNSaveToStreamProc: procedure(Stream: TStream) of object; fFNLoadFromStreamProc: procedure(Stream: TStream) of object; fFNDeferredLoadProc: procedure(Stream: TStream) of object; fDeferredLoadProcNum: UInt32; procedure SetDeferredLoadProcNum(Value: UInt32); virtual; // special functions Function GetFlagsWord: UInt32; virtual; procedure SetFlagsWord(FlagsWord: UInt32); virtual; // normal IO funtions procedure InitSaveFunctions(Struct: UInt32); override; procedure InitLoadFunctions(Struct: UInt32); override; procedure SaveItem_00000008(Stream: TStream); virtual; procedure LoadItem_00000008(Stream: TStream); virtual; procedure SavePicture_00000008(Stream: TStream; Pic: TBitmap); virtual; procedure LoadPicture_00000008(Stream: TStream; out Pic: TBitmap); virtual; procedure SaveItem_Plain_00000008(Stream: TStream); virtual; procedure LoadItem_Plain_00000008(Stream: TStream); virtual; procedure SaveItem_Processed_00000008(Stream: TStream); virtual; procedure LoadItem_Processed_00000008(Stream: TStream); virtual; procedure Initialize; override; public property DeferredLoadProcNum: UInt32 read fDeferredLoadProcNum write SetDeferredLoadProcNum; end; implementation uses SysUtils, BinaryStreaming, BitOps, MemoryBuffer, InflatablesList_Types, InflatablesList_Utils, InflatablesList_Encryption, InflatablesList_ItemPictures_Base, InflatablesList_ItemShop, InflatablesList_Manager_IO; procedure TILItem_IO_00000008.SetDeferredLoadProcNum(Value: UInt32); begin If fEncrypted and not fDataAccessible then InitLoadFunctions(Value); end; //------------------------------------------------------------------------------ Function TILItem_IO_00000008.GetFlagsWord: UInt32; begin Result := 0; SetFlagStateValue(Result,IL_ITEM_FLAG_BITMASK_ENCRYPTED,fEncrypted); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.SetFlagsWord(FlagsWord: UInt32); begin fEncrypted := GetFlagState(FlagsWord,IL_ITEM_FLAG_BITMASK_ENCRYPTED); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.InitSaveFunctions(Struct: UInt32); begin If Struct = IL_ITEM_STREAMSTRUCTURE_00000008 then begin fFNSaveToStream := SaveItem_00000008; fFNSavePicture := SavePicture_00000008; fFNSaveToStreamPlain := SaveItem_Plain_00000008; fFNSaveToStreamProc := SaveItem_Processed_00000008; end else raise Exception.CreateFmt('TILItem_IO_00000008.InitSaveFunctions: Invalid stream structure (%.8x).',[Struct]); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.InitLoadFunctions(Struct: UInt32); begin If Struct = IL_ITEM_STREAMSTRUCTURE_00000008 then begin fFNLoadFromStream := LoadItem_00000008; fFNLoadPicture := LoadPicture_00000008; fFNLoadFromStreamPlain := LoadItem_Plain_00000008; fFNLoadFromStreamProc := LoadItem_Processed_00000008; fFNDeferredLoadProc := LoadItem_Plain_00000008; fDeferredLoadProcNum := Struct; end else raise Exception.CreateFmt('TILItem_IO_00000008.InitLoadFunctions: Invalid stream structure (%.8x).',[Struct]); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.SaveItem_00000008(Stream: TStream); begin Stream_WriteUInt32(Stream,GetFlagsWord); If fEncrypted then fFNSaveToStreamProc(Stream) else fFNSaveToStreamPlain(Stream); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.LoadItem_00000008(Stream: TStream); begin SetFlagsWord(Stream_ReadUInt32(Stream)); If fEncrypted then fFNLoadFromStreamProc(Stream) else fFNLoadFromStreamPlain(Stream); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.SavePicture_00000008(Stream: TStream; Pic: TBitmap); var TempStream: TMemoryStream; begin If Assigned(Pic) then begin TempStream := TMemoryStream.Create; try Pic.SaveToStream(TempStream); Stream_WriteUInt32(Stream,TempStream.Size); Stream.CopyFrom(TempStream,0); finally TempStream.Free; end; end else Stream_WriteUInt32(Stream,0); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.LoadPicture_00000008(Stream: TStream; out Pic: TBitmap); var Size: UInt32; TempStream: TMemoryStream; begin Size := Stream_ReadUInt32(Stream); If Size > 0 then begin TempStream := TMemoryStream.Create; try TempStream.CopyFrom(Stream,Size); TempStream.Seek(0,soBeginning); Pic := TBitmap.Create; try Pic.LoadFromStream(TempStream); except FreeAndNil(Pic); end; finally TempStream.Free; end; end else Pic := nil; end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.SaveItem_Plain_00000008(Stream: TStream); var i: Integer; begin Stream_WriteBuffer(Stream,fUniqueID,SizeOf(fUniqueID)); Stream_WriteFloat64(Stream,fTimeOfAddition); // pictures If fPictures.CheckIndex(fPictures.IndexOfItemPicture) then fFNSavePicture(Stream,fPictures[fPictures.IndexOfItemPicture].Thumbnail) else fFNSavePicture(Stream,nil); If fPictures.CheckIndex(fPictures.CurrentSecondary) then fFNSavePicture(Stream,fPictures[fPictures.CurrentSecondary].Thumbnail) else fFNSavePicture(Stream,nil); If fPictures.CheckIndex(fPictures.IndexOfPackagePicture) then fFNSavePicture(Stream,fPictures[fPictures.IndexOfPackagePicture].Thumbnail) else fFNSavePicture(Stream,nil); // basic specs Stream_WriteInt32(Stream,IL_ItemTypeToNum(fItemType)); Stream_WriteString(Stream,fItemTypeSpec); Stream_WriteUInt32(Stream,fPieces); Stream_WriteString(Stream,fUserID); Stream_WriteInt32(Stream,IL_ItemManufacturerToNum(fManufacturer)); Stream_WriteString(Stream,fManufacturerStr); Stream_WriteString(Stream,fTextID); Stream_WriteInt32(Stream,fNumID); // flags Stream_WriteUInt32(Stream,IL_EncodeItemFlags(fFlags)); Stream_WriteString(Stream,fTextTag); Stream_WriteInt32(Stream,fNumTag); // extended specs Stream_WriteUInt32(Stream,fWantedLevel); Stream_WriteString(Stream,fVariant); Stream_WriteString(Stream,fVariantTag); Stream_WriteInt32(Stream,IL_ItemMaterialToNum(fMaterial)); Stream_WriteUInt32(Stream,fSizeX); Stream_WriteUInt32(Stream,fSizeY); Stream_WriteUInt32(Stream,fSizeZ); Stream_WriteUInt32(Stream,fUnitWeight); Stream_WriteUInt32(Stream,fThickness); // others Stream_WriteString(Stream,fNotes); Stream_WriteString(Stream,fReviewURL); // pictures If fPictures.CheckIndex(fPictures.IndexOfItemPicture) then Stream_WriteString(Stream, IL_PathRelative(fStaticSettings.ListPath, fPictures.StaticSettings.PicturesPath + fPictures[fPictures.IndexOfItemPicture].PictureFile)) else Stream_WriteString(Stream,''); If fPictures.CheckIndex(fPictures.CurrentSecondary) then Stream_WriteString(Stream, IL_PathRelative(fStaticSettings.ListPath, fPictures.StaticSettings.PicturesPath + fPictures[fPictures.CurrentSecondary].PictureFile)) else Stream_WriteString(Stream,''); If fPictures.CheckIndex(fPictures.IndexOfPackagePicture) then Stream_WriteString(Stream, IL_PathRelative(fStaticSettings.ListPath, fPictures.StaticSettings.PicturesPath + fPictures[fPictures.IndexOfPackagePicture].PictureFile)) else Stream_WriteString(Stream,''); Stream_WriteUInt32(Stream,fUnitPriceDefault); Stream_WriteUInt32(Stream,fRating); // shop avail and prices Stream_WriteUInt32(Stream,fUnitPriceLowest); Stream_WriteUInt32(Stream,fUnitPriceHighest); Stream_WriteUInt32(Stream,fUnitPriceSelected); Stream_WriteInt32(Stream,fAvailableLowest); Stream_WriteInt32(Stream,fAvailableHighest); Stream_WriteInt32(Stream,fAvailableSelected); // shops Stream_WriteUInt32(Stream,ShopCount); For i := ShopLowIndex to ShopHighIndex do fShops[i].SaveToStream(Stream); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.LoadItem_Plain_00000008(Stream: TStream); var i: Integer; ItemPictureThumb: TBitmap; SecondaryPictureThumb: TBitmap; PackagePictureThumb: TBitmap; ItemPictureFile: String; SecondaryPictureFile: String; PackagePictureFile: String; AutomationInfo: TILPictureAutomationInfo; begin ItemPictureThumb := nil; SecondaryPictureThumb := nil; PackagePictureThumb := nil; try Stream_ReadBuffer(Stream,fUniqueID,SizeOf(fUniqueID)); fTimeOfAddition := TDateTime(Stream_ReadFloat64(Stream)); // pictures - load into temporaries fFNLoadPicture(Stream,ItemPictureThumb); fFNLoadPicture(Stream,SecondaryPictureThumb); fFNLoadPicture(Stream,PackagePictureThumb); // basic specs fItemType := IL_NumToItemType(Stream_ReadInt32(Stream)); fItemTypeSpec := Stream_ReadString(Stream); fPieces := Stream_ReadUInt32(Stream); fUserID := Stream_ReadString(Stream); fManufacturer := IL_NumToItemManufacturer(Stream_ReadInt32(Stream)); fManufacturerStr := Stream_ReadString(Stream); fTextID := Stream_ReadString(Stream); fNumID := Stream_ReadInt32(Stream); // flags fFlags := IL_DecodeItemFlags(Stream_ReadUInt32(Stream)); fTextTag := Stream_ReadString(Stream); fNumTag := Stream_ReadInt32(Stream); // extended specs fWantedLevel := Stream_ReadUInt32(Stream); fVariant := Stream_ReadString(Stream); fVariantTag := Stream_ReadString(Stream); fMaterial := IL_NumToItemMaterial(Stream_ReadInt32(Stream)); fSizeX := Stream_ReadUInt32(Stream); fSizeY := Stream_ReadUInt32(Stream); fSizeZ := Stream_ReadUInt32(Stream); fUnitWeight := Stream_ReadUInt32(Stream); fThickness := Stream_ReadUInt32(Stream); // other info fNotes := Stream_ReadString(Stream); fReviewURL := Stream_ReadString(Stream); // picture files - load into temporaries and expand them ItemPictureFile := Stream_ReadString(Stream); SecondaryPictureFile := Stream_ReadString(Stream); PackagePictureFile := Stream_ReadString(Stream); ItemPictureFile := IL_ExpandFileName(fStaticSettings.ListPath + ItemPictureFile); SecondaryPictureFile := IL_ExpandFileName(fStaticSettings.ListPath + SecondaryPictureFile); PackagePictureFile := IL_ExpandFileName(fStaticSettings.ListPath + PackagePictureFile); fUnitPriceDefault := Stream_ReadUInt32(Stream); fRating := Stream_ReadUInt32(Stream); // shop avail and prices fUnitPriceLowest := Stream_ReadUInt32(Stream); fUnitPriceHighest := Stream_ReadUInt32(Stream); fUnitPriceSelected := Stream_ReadUInt32(Stream); fAvailableLowest := Stream_ReadInt32(Stream); fAvailableHighest := Stream_ReadInt32(Stream); fAvailableSelected := Stream_ReadInt32(Stream); // shops SetLength(fShops,Stream_ReadUInt32(Stream)); fShopCount := Length(fShops); For i := ShopLowIndex to ShopHighIndex do begin fShops[i] := TILItemShop.Create; fShops[i].StaticSettings := fStaticSettings; fShops[i].LoadFromStream(Stream); fShops[i].AssignInternalEvents( ShopClearSelectedHandler, ShopUpdateOverviewHandler, ShopUpdateShopListItemHandler, ShopUpdateValuesHandler, ShopUpdateAvailHistoryHandler, ShopUpdatePriceHistoryHandler); end; // convert pictures fPictures.BeginInitialization; try If Length(ItemPictureFile) > 0 then If fPictures.AutomatePictureFile(ItemPictureFile,AutomationInfo) then begin i := fPictures.Add(AutomationInfo); fPictures.SetThumbnail(i,ItemPictureThumb,True); fPictures.SetItemPicture(i,True); end; If Length(PackagePictureFile) > 0 then If fPictures.AutomatePictureFile(PackagePictureFile,AutomationInfo) then begin i := fPictures.Add(AutomationInfo); fPictures.SetThumbnail(i,PackagePictureThumb,True); fPictures.SetPackagePicture(i,True); end; If Length(SecondaryPictureFile) > 0 then If fPictures.AutomatePictureFile(SecondaryPictureFile,AutomationInfo) then begin i := fPictures.Add(AutomationInfo); fPictures.SetThumbnail(i,SecondaryPictureThumb,True); end; finally fPictures.EndInitialization; end; finally If Assigned(ItemPictureThumb) then FreeAndNil(ItemPictureThumb); If Assigned(SecondaryPictureThumb) then FreeAndNil(SecondaryPictureThumb); If Assigned(PackagePictureThumb) then FreeAndNil(PackagePictureThumb); end; end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.SaveItem_Processed_00000008(Stream: TStream); var TempStream: TMemoryStream; Password: String; begin // in current implementation, if we are here, we are writing encrypted item... If fDataAccessible then begin { data are not encrypted, encrypt them and then save the resulting stream if the item is marked for encryption and the data are decrypted, this means the password is valid since it was already put in (item was either marked for encryption - in that case thee manager prompted for the password, or the item was decrypted and in that case the password was entered for that to happen) } TempStream := TMemoryStream.Create; try // preallocate TempStream.Size := Int64(IL_LISTFILE_PREALLOC_BYTES_ITEM + (fPictures.Count * IL_LISTFILE_PREALLOC_BYTES_THUMB)); TempStream.Seek(0,soBeginning); // write plain data fFNSaveToStreamPlain(TempStream); TempStream.Size := TempStream.Position; // encrypt the stream If RequestItemsPassword(Password) then InflatablesList_Encryption.EncryptStream_AES256(TempStream,Password,IL_ITEM_DECRYPT_CHECK) else raise Exception.Create('TILItem_IO_00000008.SaveItem_Processed_00000006: Unable to obtain password for saving, cannot continue.'); // save the encrypted stream Stream_WriteUInt64(Stream,UInt64(TempStream.Size)); // write size of encrypted data Stream_WriteBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size)); // TempStream contains unencrypted size finally TempStream.Free; end; end else begin { data are still stored in encrypted state, do nothing, just take the encrypted data buffer and save it as is (expects fEncryptedData to contain the data :O) } Stream_WriteUInt64(Stream,UInt64(fEncryptedData.Size)); // encrypted size Stream_WriteBuffer(Stream,fEncryptedData.Memory^,fEncryptedData.Size); // encrypted data end; end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.LoadItem_Processed_00000008(Stream: TStream); begin { the item is marked as encrypted - do not decrypt it here, just load it into fEncryptedData buffer and set fDataAccessible to false } fDataAccessible := False; ReallocBuffer(fEncryptedData,TMemSize(Stream_ReadUInt64(Stream))); Stream_ReadBuffer(Stream,fEncryptedData.Memory^,fEncryptedData.Size); end; //------------------------------------------------------------------------------ procedure TILItem_IO_00000008.Initialize; begin inherited; fDeferredLoadProcNum := UInt32(-1); end; end.
unit DiffuseDebugTextureGeneratorCommand; interface uses ControllerDataTypes, ActorActionCommandBase, Actor; {$INCLUDE source/Global_Conditionals.inc} type TDiffuseDebugTextureGeneratorCommand = class (TActorActionCommandBase) const C_DEFAULT_SIZE = 1024; C_DEFAULT_MATERIAL = 0; C_DEFAULT_TEXTURE = 0; protected FSize: longint; FMaterialID: longint; FTextureID: longint; public constructor Create(var _Actor: TActor; var _Params: TCommandParams); override; procedure Execute; override; end; implementation uses StopWatch, TextureGeneratorBase, DiffuseDebugTextureGenerator, GlobalVars, SysUtils; constructor TDiffuseDebugTextureGeneratorCommand.Create(var _Actor: TActor; var _Params: TCommandParams); begin FCommandName := 'Diffuse Debug Texture Generation'; ReadAttributes3Int(_Params,FSize,FMaterialID,FTextureID,C_DEFAULT_SIZE,C_DEFAULT_MATERIAL,C_DEFAULT_TEXTURE); inherited Create(_Actor,_Params); end; procedure TDiffuseDebugTextureGeneratorCommand.Execute; var TexGenerator : CTextureGeneratorBase; {$ifdef SPEED_TEST} StopWatch : TStopWatch; {$endif} begin {$ifdef SPEED_TEST} StopWatch := TStopWatch.Create(true); {$endif} TexGenerator := CDiffuseDebugTextureGenerator.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD],FSize,FMaterialID,FTextureID); TexGenerator.Execute(); TexGenerator.Free; {$ifdef SPEED_TEST} StopWatch.Stop; GlobalVars.SpeedFile.Add('Diffuse (debug) texture generation for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.'); StopWatch.Free; {$endif} end; end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit LPCdecode; {$MODE Delphi} interface uses iLBC_define, helpfun, lsf, constants,C2Delphi_header; {---------------------------------------------------------------* * interpolation of lsf coefficients for the decoder *--------------------------------------------------------------} procedure LSFinterpolate2a_dec( a:pareal; { (o) lpc coefficients for a sub-frame } lsf1:pareal; { (i) first lsf coefficient vector } lsf2:pareal; { (i) second lsf coefficient vector } coef:real; { (i) interpolation weight } length:integer { (i) length of lsf vectors } ); procedure SimplelsfDEQ( lsfdeq:pareal; { (o) dequantized lsf coefficients } index:painteger; { (i) quantization index } lpc_n:integer { (i) number of LPCs } ); procedure DecoderInterpolateLSF( syntdenum:pareal; { (o) synthesis filter coefficients } weightdenum:pareal; { (o) weighting denumerator coefficients } lsfdeq:pareal; { (i) dequantized lsf coefficients } length:integer; { (i) length of lsf coefficient vector } iLBCdec_inst:piLBC_Dec_Inst_t { (i) the decoder state structure } ); implementation procedure LSFinterpolate2a_dec( a:pareal; { (o) lpc coefficients for a sub-frame } lsf1:pareal; { (i) first lsf coefficient vector } lsf2:pareal; { (i) second lsf coefficient vector } coef:real; { (i) interpolation weight } length:integer { (i) length of lsf vectors } ); var lsftmp:array [0..LPC_FILTERORDER] of real; begin interpolate(@lsftmp, lsf1, lsf2, coef, length); lsf2a(a, @lsftmp); end; {---------------------------------------------------------------* * obtain dequantized lsf coefficients from quantization index *--------------------------------------------------------------} procedure SimplelsfDEQ( lsfdeq:pareal; { (o) dequantized lsf coefficients } index:painteger; { (i) quantization index } lpc_n:integer { (i) number of LPCs } ); var i, j, pos, cb_pos:integer; begin { decode first LSF } pos := 0; cb_pos := 0; for i := 0 to LSF_NSPLIT-1 do begin for j := 0 to dim_lsfCbTbl[i]-1 do begin lsfdeq[pos + j] := lsfCbTbl[cb_pos +(index[i])*dim_lsfCbTbl[i] + j]; end; pos :=pos + dim_lsfCbTbl[i]; cb_pos :=cb_pos + size_lsfCbTbl[i]*dim_lsfCbTbl[i]; end; if (lpc_n>1) then begin { decode last LSF } pos := 0; cb_pos := 0; for i := 0 to LSF_NSPLIT-1 do begin for j := 0 to dim_lsfCbTbl[i]-1 do begin lsfdeq[LPC_FILTERORDER + pos + j] := lsfCbTbl[cb_pos +(index[LSF_NSPLIT + i])*dim_lsfCbTbl[i] + j]; end; pos :=pos + dim_lsfCbTbl[i]; cb_pos :=cb_pos + size_lsfCbTbl[i]*dim_lsfCbTbl[i]; end; end; end; {----------------------------------------------------------------* * obtain synthesis and weighting filters form lsf coefficients *---------------------------------------------------------------} procedure DecoderInterpolateLSF( syntdenum:pareal; { (o) synthesis filter coefficients } weightdenum:pareal; { (o) weighting denumerator coefficients } lsfdeq:pareal; { (i) dequantized lsf coefficients } length:integer; { (i) length of lsf coefficient vector } iLBCdec_inst:piLBC_Dec_Inst_t { (i) the decoder state structure } ); var i, pos, lp_length:integer; lp:array [0..LPC_FILTERORDER ] of real; lsfdeq2:pareal; begin lsfdeq2 := @lsfdeq [ length]; lp_length := length + 1; if (iLBCdec_inst^.mode=30) then begin { sub-frame 1: Interpolation between old and first } LSFinterpolate2a_dec(@lp, @iLBCdec_inst^.lsfdeqold, lsfdeq, lsf_weightTbl_30ms[0], length); move (lp,syntdenum[0],lp_length*sizeof(real)); bwexpand(@weightdenum[0], @lp, LPC_CHIRP_WEIGHTDENUM, lp_length); { sub-frames 2 to 6: interpolation between first and last LSF } pos := lp_length; for i := 1 to 5 do begin LSFinterpolate2a_dec(@lp, lsfdeq, lsfdeq2, lsf_weightTbl_30ms[i], length); move(lp,syntdenum[pos],lp_length*sizeof(real)); bwexpand(@weightdenum [pos], @lp, LPC_CHIRP_WEIGHTDENUM, lp_length); pos :=pos + lp_length; end; end else begin pos := 0; for i := 0 to iLBCdec_inst^.nsub-1 do begin LSFinterpolate2a_dec(@lp, @iLBCdec_inst^.lsfdeqold, lsfdeq, lsf_weightTbl_20ms[i], length); move(lp,syntdenum[pos],lp_length*sizeof(real)); bwexpand(@weightdenum[pos], @lp, LPC_CHIRP_WEIGHTDENUM, lp_length); pos :=pos + lp_length; end; end; { update memory } if (iLBCdec_inst^.mode=30) then move( lsfdeq2[0],iLBCdec_inst^.lsfdeqold,length*sizeof(real)) else move( lsfdeq[0],iLBCdec_inst^.lsfdeqold,length*sizeof(real)); end; end.
unit UCnaeVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO; type [TEntity] [TTable('Cnae')] TCnaeVO = class(TGenericVO) private FidCnae: Integer; FcodigoCnae : String; Fdescricao: String; public [TId('idCnae')] [TGeneratedValue(sAuto)] property idCnae: Integer read FidCnae write FidCnae; [TColumn('CODIGOCNAE','Cnae',80,[ldGrid], False)] [TFormatter(ftCnae, taLeftJustify)] property codigoCnae: String read FcodigoCnae write FcodigoCnae; [TColumn('DESCRICAO','Descrição',500,[ldGrid], False)] property descricao: String read Fdescricao write Fdescricao; function ValidarCamposObrigatorios:boolean; end; implementation { TCnaeVO } function TCnaeVO.ValidarCamposObrigatorios: boolean; begin Result := true; if (Self.FcodigoCnae = '') then begin raise Exception.Create('O campo Cnae é obrigatório!'); Result := false; end else if (Self.Fdescricao = '') then begin raise Exception.Create('O campo Descrição é obrigatório!'); Result := false; end; end; end.
unit ufrmCreateSO; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMaster, StdCtrls, ExtCtrls, ufraFooter5Button, Mask, Math, System.Actions, cxStyles, cxClasses, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ufraFooter4Button, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxGridCustomView, cxGrid, cxButtons, Vcl.Menus, Vcl.ActnList, Vcl.Grids, cxDBExtLookupComboBox; type TThreadSOType = (tpCreateSO,tpSearchSO,tpAddPOTrader,tpAvgSales); TfrmCreateSO = class(TfrmMaster) fraFooter5Button1: TfraFooter5Button; pnlTop: TPanel; edtNoSO: TEdit; lbl1: TLabel; lbl2: TLabel; dtTgl: TcxDateEdit; pnlContent: TPanel; lbl3: TLabel; cbbMerchanGroup: TComboBox; actlst1: TActionList; actCreateSO: TAction; actShowHistorySO: TAction; pnl1: TPanel; lbl4: TLabel; actAddOthersProdSO: TAction; actAddPOTrader: TAction; Button1: TButton; Button2: TButton; Edit1: TEdit; actToExcel: TAction; gridTemp: TStringGrid; sgBarangNotForSo: TStringGrid; cxGrid: TcxGrid; cxGridView: TcxGridDBTableView; cxColNo: TcxGridDBColumn; cxColStatus: TcxGridDBColumn; cxGridViewColumn3: TcxGridDBColumn; cxGridViewColumn4: TcxGridDBColumn; cxGridViewColumn5: TcxGridDBColumn; cxGridViewColumn6: TcxGridDBColumn; cxGridViewColumn7: TcxGridDBColumn; cxGridViewColumn8: TcxGridDBColumn; cxGridViewColumn9: TcxGridDBColumn; cxGridViewColumn10: TcxGridDBColumn; cxGridViewColumn11: TcxGridDBColumn; cxGridViewColumn12: TcxGridDBColumn; cxGridViewColumn13: TcxGridDBColumn; cxGridViewColumn14: TcxGridDBColumn; cxGridViewColumn15: TcxGridDBColumn; cxGridViewColumn16: TcxGridDBColumn; cxGridViewColumn17: TcxGridDBColumn; cxGridViewColumn18: TcxGridDBColumn; cxGridViewColumn19: TcxGridDBColumn; cxGridViewColumn20: TcxGridDBColumn; cxGridViewColumn21: TcxGridDBColumn; cxGridViewColumn22: TcxGridDBColumn; cxGridViewColumn23: TcxGridDBColumn; cxGridViewColumn24: TcxGridDBColumn; cxGridViewColumn25: TcxGridDBColumn; cxGridViewColumn26: TcxGridDBColumn; cxGridViewColumn27: TcxGridDBColumn; cxGridViewColumn28: TcxGridDBColumn; cxGridViewColumn29: TcxGridDBColumn; cxGridViewColumn30: TcxGridDBColumn; cxGridViewColumn31: TcxGridDBColumn; cxGridViewColumn32: TcxGridDBColumn; cxlvMaster: TcxGridLevel; btnShow: TcxButton; bStop: TcxButton; btnTesting: TcxButton; btnAddOthersProdSO: TcxButton; btnToExcel: TcxButton; btnAddFromPOTrader: TcxButton; pmPMGrid: TPopupMenu; pmiHapusItem: TMenuItem; pmiHapusSemua: TMenuItem; N1: TMenuItem; pmiCheckAll: TMenuItem; pmiUncheckAll: TMenuItem; pmiCheckAnalisis: TMenuItem; pmiCheckPSL: TMenuItem; N2: TMenuItem; pmiValFromBiggest: TMenuItem; pmiValFromAnalisis: TMenuItem; pmiValFromPSL: TMenuItem; pmiValToZero: TMenuItem; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actCreateSOExecute(Sender: TObject); procedure actShowHistorySOExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure strgGrid1CanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); procedure strgGrid1ComboChange(Sender: TObject; ACol, ARow, AItemIndex: Integer; ASelection: String); procedure cbbSoForChange(Sender: TObject); procedure FormActivate(Sender: TObject); procedure actAddOthersProdSOExecute(Sender: TObject); procedure actAddPOTraderExecute(Sender: TObject); procedure btnShowClick(Sender: TObject); procedure fraFooter5Button1btnUpdateClick(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure cbbMerchanGroupChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure fraFooter5Button1btnDeleteClick(Sender: TObject); procedure StrgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); procedure CustomItem2Click(Sender: TObject); procedure CustomItem1Click(Sender: TObject); procedure StrgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); procedure StrgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); procedure pnlTopDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure StrgGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure fraFooter5Button1btnCloseClick(Sender: TObject); procedure bStopClick(Sender: TObject); procedure btnTestingClick(Sender: TObject); procedure pmiHapusItemClick(Sender: TObject); procedure pmiHapusSemuaClick(Sender: TObject); procedure pmiCheckAllClick(Sender: TObject); procedure pmiUncheckAllClick(Sender: TObject); procedure pmiCheckAnalisisClick(Sender: TObject); procedure pmiCheckPSLClick(Sender: TObject); procedure pmiValFromBiggestClick(Sender: TObject); procedure pmiValFromAnalisisClick(Sender: TObject); procedure pmiValFromPSLClick(Sender: TObject); procedure pmiValToZeroClick(Sender: TObject); procedure actToExcelExecute(Sender: TObject); procedure btnAddOthersProdSOClick(Sender: TObject); procedure btnAddFromPOTraderClick(Sender: TObject); procedure btnToExcelClick(Sender: TObject); private isAdaData: Boolean; isAfterPOTrader: Boolean; DataCmbStrG: TDataSet; ThreadType: TThreadSOType; // FBarang : TNewBarang; // FSO : TSO; // FSupMerchan : TNewSupplierMerGroup; // FBarangSuplier : TBarangSupplier; FIsCancel: Boolean; FIsInsert: Boolean; // FSatuan : TKonversiSatuan; IsManual: Boolean; FIsEdit : Boolean; FIsSudahLoadDataStock: Boolean; FnewId: Integer; FxGen: Integer; procedure AddNewRow; procedure DoSkenarioSO; procedure DoTestingLoadDataPLU; function GetLastGrQty(aBrgCode: string; aUnitId: Integer): string; //function GetIBQueryCekBHJ(aUnitID : Integer): TFDQuery; function GetQUK(aBrgCode : String; aLeadTime : Integer;aSafetyStock : Double; aPKMAverage : Double; aKonversiSatuanPSL : Double; aKonversiSatuanPurch : Double; aMinor : Double; aMaxor : Double; var aOnHand : Double; var aStockUOMPurchase : Double; var aOnOrder : Double; var aAvgPKM : Double): Double; function GetSQLItem4SO(aBrgCode: string=''): string; function GetSQLLoadDataPLUForSO(aUnitID : Integer; aMerchandizeID : Integer; aTgl : TDateTime): string; procedure LoadDataStock2Temp; //function GetStockQty(aBrgCode: string; aUnitId: Integer; aIsBonus: integer): // Double; //function IsSudahPunyaHargaToko(aQueryCekBHJ : TFDQuery; aBrgCode : String): // Boolean; procedure ShowStockCard(); procedure ParseHeaderGrid; procedure SetArowInGrid(Strings:Tstrings; aBaris: integer = -1); public intHari: Integer; procedure DoTestingIsiQtyOrder; procedure DoTestingSimpan; procedure DoTestQtyStockDanQtyStockPurchase; function SetFilterDay(aToday : TDateTime): string; function getValueOnHand(aBrgKode: String): Double; procedure LoaDataToGridTemp(aDate: TDateTime; aUnitID : Integer); function getValueOnOrder(aKodeBarang : String): Double; procedure LoadDataToCbbMerchanGrup; procedure LoadDataToGrid; procedure SettingGrid; procedure SettingLebarKolom; function getBarisKosong: Integer; function isAdaKomaNonValid: Boolean; function IsAdaPLUKosong: Boolean; function isAdaQtyKurang: Boolean; function isAdaQtyLebih: Boolean; function isAdaQtyNol: Boolean; function IsAdaUOMKosong: Boolean; function IsBarangForSO(aKodeBarang : String): Boolean; function IsBaraSudahAda(aBrgCode : String ): Boolean; procedure LoadDataBarangNotForSO(aUnitID : Integer); procedure LoadDataSO(aNoSO : String; aUnitID : Integer); end; var frmCreateSO: TfrmCreateSO; implementation uses uTSCommonDlg, ufrmHistorySO, ufrmDialogAddProductForSO, uConstanta, uAppUtils, {ufrmDialogStockCard, ufraStockCard, uRegionalSettingUtils,} uRetnoUnit, uFormProperty, ufrmSplash; const _kolQTY2 = 3; _kolTempKodeBarang2 = 2; _kolTempQTY = 1; _kolTempKodeBrg = 0; _kolIsDecimal : Integer = 31; _kolPKMAverage : Integer = 30; _kolIsSat : Integer = 29; _kolIsFri : Integer = 28; _kolIsThu : Integer = 27; _kolIsWed : Integer = 26; _kolIsTue : Integer = 25; _kolIsMon : Integer = 24; _kolIsSun : Integer = 23; _kolIsBKP : Integer = 22; _kolBrgSupID : Integer = 21; _kolDisc3 : Integer = 20; _kolDisc2 : Integer = 19; _kolDisc1 : Integer = 18; _kolHargaBeli : Integer = 17; _KolLeadTime : Integer = 16; _kolSuplierName : Integer = 15; _kolSuplierCode : Integer = 14; _kolMaxOrder : Integer = 13; _kolQtyOrder : Integer = 12; _kolLastGrNo : Integer = 11; _kolQtyPSL : Integer = 10; _kolQtyAnalisis : Integer = 9; _kolQTYUOMPurchase : Integer = 8; _kolQtyUOMStock : Integer = 7; _kolStockMin : Integer = 6; _kolPLUPurchase : Integer = 5; _kolUOM : Integer = 4; _kolProdukName : Integer = 3; _kolPLU : Integer = 2; _kolStatus : Integer = 1; _KolNo : Integer = 0; _fixedRow : Integer = 1; _colCount : Integer = 30; _rowCount : integer = 2; MaxGen : Integer = 5; { _kolQTYOrder = 11; _kolSatuan = 3; _kolKodeBarang = 1; _kolIsReguler = 24; _kolIsOrdered = 11; _kolIsBKP = 28; _kolHarga = 15; _kolDisc3 = 18; _kolDisc2 = 17; _kolDisc1 = 16; _kolBRGSUP_ID = 22; } {$R *.dfm} procedure TfrmCreateSO.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; // frmMain.DestroyMenu((Sender as TForm)); Action := caFree; end; procedure TfrmCreateSO.FormDestroy(Sender: TObject); begin inherited; frmCreateSO := nil; end; procedure TfrmCreateSO.FormCreate(Sender: TObject); begin inherited; SetIDCurrencyRegionalSetting; lblHeader.Caption := 'CREATE SUGGESTION ORDER'; // FSO := TSO.Create(Self); // FBarang := TNewBarang.Create(Self); // FSupMerchan := TNewSupplierMerGroup.Create(Self); // FBarangSuplier := TBarangSupplier.Create(Self); // FSatuan := TKonversiSatuan.Create(Self); SettingGrid; end; procedure TfrmCreateSO.actCreateSOExecute(Sender: TObject); var ssQL: string; //fValQtyOrder: Double; aUOMUnit_ID: Integer; aSOUnit_ID: Integer; aQty: Double; aNewUOM: string; aNewUnit_ID: Integer; aNewBarangKode: string; aIsReguler: Integer; aIsOrdered: Integer; aIsBKP: Integer; aID: Integer; aHarga: Double; aDisc3: Double; aDisc2: Double; aDisc1: Double; aBarangUnit_ID: Integer; aBarangSupplierUnit_ID: Integer; aBarangSupplier_ID: Integer; aMerchandizeID: Integer; aNoBukti: string; aTglBukti: TDateTime; aMerchandizeUnit_ID: Integer; state : Boolean; i: Integer; begin if dtTgl.Date = 0 then begin CommonDlg.ShowMessage('Tanggal SO Dibuat Masih Kosong'); dtTgl.SetFocus; Exit; end; if Trim(edtNoSO.Text) = '' then begin CommonDlg.ShowMessage('Nomor SO Dibuat Masih Kosong'); edtNoSO.SetFocus; Exit; end; if not IsManual then begin // if FSO.IsMerchandizeIniSudahAdaSO(dtTgl.Date, cGetIDfromCombo(cbbMerchanGroup), MasterNewUnit.ID, edtNoSO.Text) then begin CommonDlg.ShowMessage('SO Untuk Merchandize ' + cbbMerchanGroup.Text + ' Sudah Dibuat'); cbbMerchanGroup.SetFocus; Exit; end; end; // IF (Trim(StrgGrid.Cells[_kolPLU,1]) = '') then begin CommonDlg.ShowMessage('Tidak Ada Data Yang Diproses'); Exit; end; if IsAdaPLUKosong then Exit; if IsAdaUOMKosong then Exit; if isAdaQtyNol then Exit; if isAdaQtyKurang then Exit; if isAdaQtyLebih then Exit; //if isAdaKomaNonValid then // Exit; // if not IsValidDateKarenaEOD(Trim(edtNoSO.Text),MasterNewUnit.ID,dtTgl.Date,TTSO,FMasterIsStore) then // Exit; try Self.Enabled := False; { aMerchandizeUnit_ID := MasterNewUnit.ID ; aMErchandizeID := cGetIDfromCombo(cbbMerchanGroup); aNewUnit_ID := MasterNewUnit.ID; aNoBukti := edtNoSO.Text ; aTglBukti := dtTgl.Date; FSO.UpdateData( aMerchandizeUnit_ID, aMErchandizeID, aNewUnit_ID, aNoBukti, aTglBukti, FLoginId, FLoginUnitId ); FSO.SOItems.Clear; try for i := 1 to strgGrid.RowCount-1 do begin strgGrid.GetCheckBoxState(_kolStatus,i,state); if state then begin if strgGrid.cells[_kolQTYOrder,i] = '' then strgGrid.cells[_kolQTYOrder,i] := '0'; if strgGrid.cells[_kolQTYOrder,i] <> '0' then begin //Input to SO Detil aBarangSupplier_ID := StrToInt(strgGrid.Cells[_kolBrgSupID,i]); aBarangSupplierUnit_ID := MasterNewUnit.ID; aBarangUnit_ID := MasterNewUnit.ID; aDisc1 := (strgGrid.Floats[_kolDisc1,i]); aDisc2 := (strgGrid.Floats[_kolDisc2,i]); aDisc3 := (strgGrid.Floats[_kolDisc3,i]); aHarga := strgGrid.Floats[_kolHargaBeli,i]; aID := 0 ; aIsBKP := StrToInt(strgGrid.Cells[_kolIsBKP,i]); aIsOrdered := 0; aIsReguler := 1; aNewBarangKode := strgGrid.Cells[_kolPLU,i]; aNewUnit_ID := MasterNewUnit.ID; aNewUOM:= strgGrid.Cells[_kolUOM, i]; aQty := (strgGrid.Floats[_kolQTYOrder,i]); aSOUnit_ID := MasterNewUnit.ID; aUOMUnit_ID := MasterNewUnit.ID; cShowWaitWindow(StrgGrid.Cells[_kolPLU, i], Self); FSO.UpdateSOItems( aBarangSupplier_ID, aBarangSupplierUnit_ID, aBarangUnit_ID, aDisc1, aDisc2, aDisc3, aHarga, aID, aIsBKP, aIsOrdered, aIsReguler, aNewBarangKode, aNewUnit_ID, aNewUOM, aNoBukti, aQty, aSOUnit_ID, aUOMUnit_ID, FLoginId ); end ; //if (not IsManual) and frmMain.IsTesting then // DoTestQtyStockDanQtyStockPurchase; end; end; finally cCloseWaitWindow; end; try //FIsInsert := True; FxGen := FxGen + 1; try FSO.ExecuteGenerateSQL(FIsInsert); cCommitTrans; //set generator dengan old value + 1 ssQL := 'SET GENERATOR GEN_SO TO '+ IntToStr(FnewId); cExecSQL(ssQL, True, FSO.GetHeaderFlag); ClearByTag(Self,[0]); ClearAdvStringGrid(strgGrid); CommonDlg.ShowMessage('Data SO Berhasil dibuat'); fraFooter5Button1.btnAdd.Enabled := False; fraFooter5Button1.btnDelete.Enabled := True; except on E: EIBError do begin cRollbackTrans; if e.IBErrorCode = 335544665 then begin if FxGen > MaxGen then begin CommonDlg.ShowError('Data SO Gagal dibuat ' + #13 +' Cek Generator !!'); exit; end; FnewId := cGetID('GEN_SO') + 1; edtNoSO.Text:=StrPadLeft(IntToStr(FnewId),10,'0'); actCreateSOExecute(Sender); end; end; end; finally cRollbackTrans; end; } finally Self.Enabled := True; end; end; procedure TfrmCreateSO.actShowHistorySOExecute(Sender: TObject); var aFormProperty : TFormProperty; begin aFormProperty := TFormProperty.Create; // if not assigned(frmHistorySO) then // frmHistorySO := TfrmHistorySO.Create(Application); aFormProperty.FMasterIsStore := Self.FMasterIsStore; aFormProperty.FLoginFullname := Self.FLoginFullname; aFormProperty.FLoginRole := Self.FLoginRole; aFormProperty.FLoginUsername := Self.FLoginUsername; aFormProperty.FLoginId := Self.FLoginId; aFormProperty.FLoginUnitId := Self.FLoginUnitId; aFormProperty.FLoginIsStore := Self.FLoginIsStore; aFormProperty.FFilePathReport := Self.FFilePathReport; aFormProperty.FHostClient := Self.FHostClient; aFormProperty.FIpClient := Self.FIpClient; aFormProperty.FSelfCompanyID := Self.MasterCompany.ID; // aFormProperty.FSelfUnitId := Self.MasterNewUnit.ID; frmHistorySO:= TfrmHistorySO.CreateWithUser(Application, aFormProperty); // frmHistorySO.Show; end; procedure TfrmCreateSO.FormShow(Sender: TObject); begin inherited; // if IsModeTesting then // begin // btnTesting.Visible := True // end else // btnTesting.Visible := False; fraFooter5Button1.btnAdd.Enabled := False; fraFooter5Button1.btnDelete.Enabled := True; // dtTgl.Date := cGetServerTime; edtNoSO.Clear; fraFooter5Button1.btnDelete.SetFocus; LoadDataToCbbMerchanGrup; FIsSudahLoadDataStock := False; //set prosedur untuk alighment dan format grid ya, ketentuannya dibwh ini. { if ACol in [_kolQtyPSL, _kolQtyAnalisis, _KolLeadTime, _kolMaxOrder, _kolStockMin, _kolHargaBeli, _kolPKMAverage, _kolDisc3, _kolDisc2, _kolDisc1, _kolQtyOrder, _kolQTYUOMPurchase, _kolQtyUOMStock, _kolLastGrNo] then HAlign := taRightJustify else HAlign := taLeftJustify; } end; procedure TfrmCreateSO.strgGrid1CanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); //var state: Boolean; begin inherited; if(ACol in[0,8,12])then begin CanEdit:= True; end else CanEdit:=False; end; procedure TfrmCreateSO.strgGrid1ComboChange(Sender: TObject; ACol, ARow, AItemIndex: Integer; ASelection: String); begin inherited; { with strgGrid do begin DataCmbStrG.RecNo:= AItemIndex + 1; cells[13,ARow] := DataCmbStrG.fieldbyname('SUP_NAME').AsString; cells[14,ARow] := IntToStr(DataCmbStrG.fieldbyname('SUPMG_LEAD_TIME').AsInteger); cells[15,ARow] := FloatToStr(DataCmbStrG.fieldbyname('BRGSUP_BUY_PRICE').AsFloat); strgGrid.Alignments[15,ARow]:= taRightJustify; cells[16,ARow] := FloatToStr(DataCmbStrG.fieldbyname('BRGSUP_DISC1').AsFloat); strgGrid.Alignments[16,ARow]:= taRightJustify; cells[17,ARow] := FloatToStr(DataCmbStrG.fieldbyname('BRGSUP_DISC2').AsFloat); strgGrid.Alignments[17,ARow]:= taRightJustify; cells[18,ARow] := FloatToStr(DataCmbStrG.fieldbyname('BRGSUP_DISC3').AsFloat); strgGrid.Alignments[18,ARow]:= taRightJustify; cells[22,ARow] := IntToStr(DataCmbStrG.fieldbyname('BRGSUP_ID').AsInteger); end; } end; procedure TfrmCreateSO.ShowStockCard; begin { if not assigned(frmDialogStockCard) then frmDialogStockCard := TfrmDialogStockCard.Create(Application); frmDialogStockCard.ShowModal; frmDialogStockCard.Free; try if assigned(fraStockCard) then fraStockCard.Parent := nil; except end; if not assigned(fraStockCard) then fraStockCard := TfraStockCard.Create(Application); fraStockCard.FormMode := fmSO; fraFooter5Button1.btnClose.Cancel:= False; fraStockCard.Parent := pnlBody; fraStockCard.Align := alBottom; fraStockCard.ProductCode := strgGrid.cells[21,strgGrid.Row]; fraStockCard.ShowStockCard(strgGrid.cells[21,strgGrid.Row]); //CloseLoading; } end; procedure TfrmCreateSO.cbbSoForChange(Sender: TObject); begin inherited; ThreadType:= tpAvgSales; if not assigned(frmSplash) then frmSplash := TfrmSplash.Create(Application); frmSplash.Show; // frmMain.Enabled:= False; TThreadSO.Create(False); end; procedure TfrmCreateSO.FormActivate(Sender: TObject); begin inherited; frmCreateSO.Caption := 'CREATE SUGGESTION ORDER'; // frmMain.CreateMenu((Sender as TForm)); end; function TfrmCreateSO.getBarisKosong: Integer; var i: Integer; begin Result := 0; {for i := 0 to strgGrid.RowCount - 1 do begin if strgGrid.Cells[2, i] = '' then begin Result := i; Exit; end; end; if (Result = 0) then begin strgGrid.AddRow; Result := strgGrid.RowCount - 1; end; } end; procedure TfrmCreateSO.actAddOthersProdSOExecute(Sender: TObject); var aSS: TStrings; sSQL: string; begin inherited; LoadDataStock2Temp; sSQL := GetSQLItem4SO; { with cLookUp('Daftar Barang',sSQL, 50, 1, False ) do begin try if Strings[0] <> '' then IsManual := True; if Strings[0] = '' then begin Exit; end else begin aSS := TStringList.Create; try aSS.Append(Strings[0]); aSS.Append(Strings[1]); aSS.Append(Strings[2]); aSS.Append(Strings[3]); aSS.Append(Strings[4]); aSS.Append(Strings[5]); SetArowInGrid(aSS); finally aSS.Free; end; end; finally Free; end; end; } end; procedure TfrmCreateSO.actAddPOTraderExecute(Sender: TObject); begin inherited; if isAfterPOTrader then Exit; if cbbMerchanGroup.ItemIndex=0 then begin CommonDlg.ShowMessage(1,'Information','Please select merchandise group first.', mtInformation); cbbMerchanGroup.SetFocus; Exit; end; ThreadType:= tpAddPOTrader; if not assigned(frmSplash) then frmSplash := TfrmSplash.Create(Application); frmSplash.Show; // frmMain.Enabled:= False; TThreadSO.Create(False); end; procedure TfrmCreateSO.AddNewRow; begin if getBarisKosong = 0 then begin // LoadDataStock2Temp; // StrgGrid.AddRow; // StrgGrid.AddCheckBox(_kolStatus,StrgGrid.RowCount-1,True,True); // StrgGrid.Row := getBarisKosong; end; end; procedure TfrmCreateSO.btnShowClick(Sender: TObject); var ITickCountAkhir: Integer; ITickCountAwal: Integer; begin inherited; FIsCancel := False; if cbbMerchanGroup.Text = '' then begin CommonDlg.ShowMessage('Merchandise Kosong'); cbbMerchanGroup.SetFocus; Exit; end; // frmMain.DisableEnableAllMainMenu(False); btnShow.Enabled:=False; ITickCountAwal := GetTickCount; try cShowWaitWindow('Load Data SO', Self); IsManual := False; // LoadDataBarangNotForSO(MasterNewUnit.ID); // LoaDataToGridTemp(dtTgl.Date,MasterNewUnit.ID); LoadDataToGrid; finally cCloseWaitWindow; btnShow.Enabled:=True; ITickCountAkhir := GetTickCount; Edit1.Text := FloatToStr((ITickCountAkhir - ITickCountAwal) / 1000); end; end; procedure TfrmCreateSO.fraFooter5Button1btnUpdateClick(Sender: TObject); var sSQL: string; begin inherited; sSQL := 'select so_no as NoBukti,so_date as Tanggal, b.merchan_name as Merchandize' + ' from so a,REF$MERCHANDISE b' + ' where a.so_merchangrup_id = b.merchan_id' + ' and a.SO_UNT_ID = ' + IntToStr(MasterNewUnit); {with cLookUp('Daftar SO', sSQL,200,1,True) do begin try if Strings[0] = '' then Exit; LoadDataSO(Strings[0], MasterNewUnit.ID); finally Free; end; end; } end; procedure TfrmCreateSO.FormDeactivate(Sender: TObject); begin inherited; // end; procedure TfrmCreateSO.ParseHeaderGrid; begin {with strgGrid do begin Clear; Cells[_KolNo, 0] := 'NO'; Cells[_kolStatus, 0] := '[V]'; Cells[_kolPLU, 0] := 'PLU'; Cells[_kolProdukName, 0] := 'NAMA'; Cells[_kolUOM, 0] := 'UOM'; Cells[_kolPLUPurchase, 0] := 'PLU BELI'; Cells[_kolStockMin, 0] := 'MINOR'; Cells[_kolQtyUOMStock, 0] := 'QTY UOM STOCK'; Cells[_kolQTYUOMPurchase, 0] := 'QTY UOM PURC'; Cells[_kolQtyPSL, 0] := 'QTY PSL'; Cells[_kolQtyAnalisis, 0] := 'QTY Analisis'; Cells[_kolLastGrNo, 0] := 'LAST GR QTY'; Cells[_kolQtyOrder, 0] := 'ORDER'; Cells[_kolMaxOrder, 0] := 'MAXOR'; Cells[_kolSuplierCode, 0] := 'SUP.CODE'; Cells[_kolSuplierName, 0] := 'SUP.NAME'; Cells[_KolLeadTime, 0] := 'LT'; Cells[_kolHargaBeli, 0] := 'PRICE'; Cells[_kolDisc1, 0] := 'DISC1(%)'; Cells[_kolDisc2, 0] := 'DISC2(%)'; Cells[_kolDisc3, 0] := 'DISC3(Rp)'; Cells[_kolBrgSupID, 0] := 'BRGSUP_ID'; Cells[_kolIsBKP, 0] := 'IS BKP'; Cells[_kolIsSun, 0] := 'IS SUN'; Cells[_kolIsMon, 0] := 'IS MON'; Cells[_kolIsTue, 0] := 'IS_TUE'; Cells[_kolIsWed, 0] := 'IS_WED'; Cells[_kolIsThu, 0] := 'IS_THU'; Cells[_kolIsFri, 0] := 'IS_FRI'; Cells[_kolIsSat, 0] := 'IS_SAT'; Cells[_kolPKMAverage, 0] := 'PKM AVERAGE'; Cells[_kolIsDecimal, 0] := 'ISDEC'; RowCount := _rowCount; FixedRows := _fixedRow; ColCount := _colCount; AutoSize := True; end; } end; procedure TfrmCreateSO.cbbMerchanGroupChange(Sender: TObject); begin inherited; // ParseHeaderGrid; // ClearAdvStringGrid(strgGrid) end; function TfrmCreateSO.SetFilterDay(aToday : TDateTime): string; var iToday: Integer; begin Result := ''; iToday := DayOfWeek(aToday); if iToday = 1 then Result := ' and a.SUPMG_IS_SUN = 1 ' else if iToday = 2 then Result := ' and a.SUPMG_IS_MON = 1 ' else if iToday = 3 then Result := ' and a.SUPMG_IS_TUE = 1 ' else if iToday = 4 then Result := ' and a.SUPMG_IS_WED = 1 ' else if iToday = 5 then Result := ' and a.SUPMG_IS_THU = 1 ' else if iToday = 6 then Result := ' and a.SUPMG_IS_FRI = 1 ' else if iToday = 7 then Result := ' and a.SUPMG_IS_SAT = 1 '; end; function TfrmCreateSO.getValueOnHand(aBrgKode: String): Double; var i: Integer; begin Result := 0; for i := 1 to gridTemp.RowCount - 1 do begin if Trim(gridTemp.Cells[_koltempKodeBrg,i]) = aBrgKode then begin // Result := gridTemp.Floats[_kolTempQTY,i]; end; end; end; procedure TfrmCreateSO.LoaDataToGridTemp(aDate: TDateTime; aUnitID : Integer); var i: Integer; sSQL: string; begin { cClearGrid(gridTemp, False); sSQL := 'select a.KODE_BARANG,SUM(a.QTY) as Qty' // ini sdh UOM Stock + ' from SP_MUTASI_BARANG(' + QuotD(StartOfTheYear(aDate)) + ',' + QuotD(aDate) + ',' + IntToStr(aUnitID) + ') a' + ' , barang b where a.KODE_BARANG=B.BRG_CODE and a.IS_BONUS_FOR_BONUS = 0 AND BRG_MERCHAN_ID = ' + IntToStr(cGetIDfromCombo(cbbMerchanGroup)) + ' group by KODE_BARANG'; with cOpenQuery(sSQL) do begin try // cShowWaitWindow('Load Data Stock Dan PO On Order', Self); i := 0; while not Eof do begin if FIsCancel then Exit; Inc(i); if (i mod 10 = 0) then begin // cShowWaitWindow(FieldByName('KODE_BARANG').AsString, Self); Application.ProcessMessages; end; gridtemp.Cells[_kolTempKodeBrg,i] := FieldByName('KODE_BARANG').AsString; gridTemp.Cells[_kolTempQTY, i] := FieldByName('QTY').AsString; gridTemp.AddRow; Next; end; finally Free; // cCloseWaitWindow; end; end; sSQL := 'select BRG_CODE, SUM(QTY) as Qty from ' // ini dalam UOM Beli + ' SP_HITUNG_ORDER_PO(' + QuotD(aDate) + ',' + IntToStr(aUnitID)+ ')' + ' group by BRG_CODE' ; with cOpenQuery(sSQL) do begin try while not Eof do begin if FIsCancel then Exit; Inc(i); if (i mod 10 = 0) then cShowWaitWindow(FieldByName('BRG_CODE').AsString, Self); if (i mod 100 = 0) then Application.ProcessMessages; gridtemp.Cells[_kolTempKodeBarang2,i] := FieldByName('BRG_CODE').AsString; gridTemp.Cells[_kolQTY2, i] := FieldByName('QTY').AsString; gridTemp.AddRow; Next; end; finally // cCloseWaitWindow; Free; end; end; } end; function TfrmCreateSO.getValueOnOrder(aKodeBarang : String): Double; var i : Integer; begin Result := 0; for i := 1 to gridTemp.RowCount - 1 do begin if Trim(gridTemp.Cells[_kolTempKodeBarang2,i]) = aKodeBarang then begin // Result := gridTemp.Floats[_kolQTY2,i]; Exit; end; end; end; procedure TfrmCreateSO.LoadDataToCbbMerchanGrup; var sSQL: string; begin sSQL := ' select merchan_id , merchan_name ' + ' from ref$merchandise '; // cQueryToComboObject(cbbMerchanGroup,sSQL); end; procedure TfrmCreateSO.LoadDataToGrid; var dMaximalOrder: Double; iCounter: Integer; // QJumlahBHJ: TFDQuery; //dMaximalOrder : Double; i : integer; sSQL : string; dAvgPKM : Double; //dPKMStandar : Double; //iLeadTime, //iJadwalOrder, //iSafetyStock : Integer; //dMinimalOrder : Double; //dPKMToko : Double; //iLevelOtorisasi : Integer; //dPKMExist : Double; //iN1,iUPBPlus, //iN2 : Integer; dOnOrder : Double; dStockUOMPurchase, dQUK, dOnHand : Double; dQAnalisis, dQPSL : Double; begin { sSQL := GetSQLLoadDataPLUForSO(MasterNewUnit.ID, cGetIDfromCombo(cbbMerchanGroup), dtTgl.Date); with cOpenQuery(sSQL) do begin try iCounter := 0; i := 0; while not Eof do begin if FIsCancel then Exit; /// tampilkan tiap 100 aj Inc(iCounter); if (iCounter mod 100 = 0) then begin cShowWaitWindow('Analisa Kode Barang ' + fieldbyName('brg_code').AsString, Self); Application.ProcessMessages; end; if IsBaraSudahAda(FieldByName('brg_code').AsString) then begin Next; Continue; end; if not IsBarangForSO(fieldbyName('brg_code').AsString) then begin Next; Continue; end; dQUK := GetQUK(fieldbyName('brg_code').AsString, fieldbyName('SUPMG_LEAD_TIME').AsInteger, fieldbyName('safety_stock').AsFloat, fieldbyName('BRG_PKM_AVERAGE').AsFloat, fieldbyName('ScalePsl').AsFloat, fieldbyName('ScaleBuy').AsFloat, fieldbyName('BRGSUP_MIN_ORDER').AsFloat, fieldbyName('BRGSUP_MAX_ORDER').AsFloat, dOnHand, dStockUOMPurchase, dOnOrder, dAvgPKM); dMaximalOrder := FieldByName('BRGSUP_MAX_ORDER').AsFloat; dQPSL := FieldByName('QtyBeli').AsFloat;// - dStockUOMPurchase - dOnOrder; if dQPSL > dMaximalOrder then dQPSL := dMaximalOrder; if (dQPSL - Floor(dQPSL)) >= 0.75 then dQPSL := Ceil(dQPSL) else dQPSL := Floor(dQPSL); if dQPSL < 0 then dQPSL := 0; dQAnalisis := dQUK; if (dQPSL - dStockUOMPurchase - dOnOrder) > dQAnalisis then dQUK := dQPSL - dStockUOMPurchase - dOnOrder; if (dQUK > 0) or (dQPSL > 0) or (dQAnalisis > 0) or (not FieldByName('PSS_QTY').IsNull) then begin Inc(i); with strgGrid do begin Cells[_KolNo, i] := IntToStr(i); AddCheckBox(_kolStatus,i,True,True); SetCheckBoxState(_kolStatus,i,True); Cells[_kolPLU, i] := fieldbyName('brg_code').AsString; Cells[_kolProdukName,i] := FieldByName('brg_alias').AsString; Cells[_kolUOM, i] := FieldByName('BRGSUP_SAT_CODE_BUY').AsString; Cells[_kolPLUPurchase, i] := FieldByName('BRG_CODE_PURCHASE').AsString; Floats[_kolStockMin, i] := FieldByName('BRGSUP_MIN_ORDER').AsFloat; Floats[_kolMaxOrder, i] := dMaximalOrder; Floats[_kolQtyUOMStock, i] := dOnhand + dOnOrder; Cells[_kolLastGrNo,i] := GetLastGrQty(Cells[_kolPLU, i], MasterNewUnit.ID); Floats[_kolQTYUOMPurchase,i]:= dStockUOMPurchase; Floats[_kolQtyOrder, i] := dQUK; Floats[_kolQtyAnalisis, i] := (dQAnalisis); Floats[_kolQtyPSL, i] := (dQPSL); Cells[_kolSuplierCode,i] := FieldByName('sup_code').AsString; Cells[_kolSuplierName, i] := FieldByName('sup_name').AsString; Ints[_KolLeadTime, i] := FieldByName('SUPMG_LEAD_TIME').AsInteger; Floats[_kolHargaBeli, i] := FieldByName('BRGSUP_BUY_PRICE').AsFloat; Floats[_kolDisc1, i] := FieldByName('brgsup_disc1').AsFloat; Floats[_kolDisc2,i] := FieldByName('brgsup_disc2').AsFloat; Floats[_kolDisc3,i] := FieldByName('brgsup_disc3').AsFloat; Cells[_kolIsBKP,i] := FieldByName('BRGSUP_IS_BKP').AsString; Cells[_kolBrgSupID, i] := fieldByName('brgsup_id').AsString; Cells[_kolIsSun, i] := FieldByName('SUPMG_IS_SUN').AsString; Cells[_kolIsMon, i] := FieldByName('SUPMG_IS_MON').AsString; Cells[_kolIsTue, i] := FieldByName('SUPMG_IS_TUE').AsString; Cells[_kolIsWed, i] := FieldByName('SUPMG_IS_WED').AsString; Cells[_kolIsThu, i] := FieldByName('SUPMG_IS_THU').AsString; Cells[_kolIsFri, i] := FieldByName('SUPMG_IS_FRI').AsString; Cells[_kolIsSat, i] := FieldByName('SUPMG_IS_SAT').AsString; Floats[_kolPKMAverage, i] := dAvgPKM; Cells[_kolIsDecimal, i] := FieldByName('BRG_IS_DECIMAL').AsString; if not EOF then AddRow; end; end; Next; end; finally Free; cCloseWaitWindow; SettingLebarKolom; FreeAndNil(QJumlahBHJ); end; HapusBarisKosong(StrgGrid,_kolPLU); end; } end; procedure TfrmCreateSO.SettingGrid; begin // with StrgGrid do begin //Columns[_kolQtyOrder].ReadOnly := False; //Columns[_kolStatus].ReadOnly := False; end; ParseHeaderGrid; SettingLebarKolom; end; procedure TfrmCreateSO.SettingLebarKolom; begin { with StrgGrid do begin AutoSizeColumns(True, 5); Columns[_kolIsBKP].Width := 0; Columns[_kolBrgSupID].Width := 0; Columns[_kolIsSun].Width := 0; Columns[_kolIsMon].Width := 0; Columns[_kolIsTue].Width := 0; Columns[_kolIsWed].Width := 0; Columns[_kolIsThu].Width := 0; Columns[_kolIsFri].Width := 0; Columns[_kolIsSat].Width := 0; end; } end; procedure TfrmCreateSO.Button1Click(Sender: TObject); begin inherited; gridTemp.Visible := not gridTemp.Visible; sgBarangNotForSo.Visible := gridTemp.Visible; end; function TfrmCreateSO.IsBarangForSO(aKodeBarang : String): Boolean; var i: Integer; begin Result := True; for i := 1 to sgBarangNotForSo.RowCount - 1 do begin if aKodeBarang = sgBarangNotForSo.Cells[1,i] then begin Result := False; Exit; end; end; end; procedure TfrmCreateSO.LoadDataBarangNotForSO(aUnitID : Integer); var sSQL: string; begin try sSQL := 'select b.BRGSUP_BRG_CODE' + ' from SO_BARANG_BLACKLIST a, BARANG_SUPLIER b' + ' where a.SOBB_BRGSUP_ID = b.BRGSUP_ID' + ' and a.SOBB_UNT_ID = ' + IntToStr(aUnitID) + ' order by brgsup_brg_code'; // cQueryToGrid(sSQL, sgBarangNotForSo); // sgBarangNotForSo.AutoSizeColumns(True, 5); finally end; end; procedure TfrmCreateSO.Button2Click(Sender: TObject); var i: Integer; iPKMAverage: Integer; SS: TStrings; sSQL: String; begin inherited; sSQL := 'select * from barang'; SS := TStringList.Create; {with cOpenQuery(sSQL) do begin try while not eof do begin i := 1; if (i mod 100=0) then Application.ProcessMessages; /// tampilkan tiap 100 aj cShowWaitWindow(Fields[0].AsString, Self); Randomize; iPKMAverage := RandomRange(1 ,50); sSQL := 'update barang set brg_pkm_average = ' + IntToStr(iPKMAverage) + ' where brg_code = ' + Quot(Fields[0].AsString); cExecSQLSelfCommit(sSQL); //inc(i); Next; end; finally cCloseWaitWindow; Free; SS.Free; cRollbackTrans; end; end; } end; procedure TfrmCreateSO.fraFooter5Button1btnDeleteClick(Sender: TObject); begin inherited; FxGen := 0; // FnewId := cGetID('GEN_SO') + 1; edtNoSO.Text := TAppUtils.StrPadLeft(IntToStr(FnewId),10,'0'); fraFooter5Button1.btnAdd.Enabled := True; fraFooter5Button1.btnDelete.Enabled := False; FIsInsert := True; end; procedure TfrmCreateSO.LoadDataSO(aNoSO : String; aUnitID : Integer); var IdSatuan: Integer; iBaris: Integer; i: Integer; begin {with TSO.Create(Self) do begin try cShowWaitWindow('Load Data SO', Self); cClearGrid(StrgGrid,False); if LoadByCode(aNoSO, aUnitID) then begin FIsEdit := True; fraFooter5Button1.btnAdd.Enabled := not IsSudahPO; fraFooter5Button1.btnDelete.Enabled := not IsSudahPO; FIsInsert := False; cSetItemAtComboObject(cbbMerchanGroup,Merchandize.ID); edtNoSO.Text := NoBukti; dtTgl.Date := TglBukti; iBaris := 0; for i := 0 to SOItems.Count - 1 do begin if (i mod 100=0) then begin cShowWaitWindow('Produk : ' + IntToStr(i + 1) + ' dari ' + IntToStr(SOItems.Count), Self); Application.ProcessMessages; end; /// tampilkan tiap 100 aj Inc(iBaris); StrgGrid.Ints[_kolIsSat,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsSat; StrgGrid.Ints[_kolIsFri,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsFri; StrgGrid.Ints[_kolIsThu,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsThu; StrgGrid.Ints[_kolIsWed,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsWed; StrgGrid.Ints[_kolIsTue,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsTue; StrgGrid.Ints[_kolIsMon,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsMon; StrgGrid.Ints[_kolIsSun,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.IsSun; StrgGrid.Ints[_kolBrgSupID,iBaris] := SOItems[i].BarangSupplier.ID; StrgGrid.Ints[_kolIsBKP,iBaris] := SOItems[i].BarangSupplier.IsBKP; StrgGrid.Floats[_kolDisc3,iBaris] := SOItems[i].Disc3; StrgGrid.Floats[_kolDisc2,iBaris] := SOItems[i].Disc2; StrgGrid.Floats[_kolDisc1,iBaris] := SOItems[i].Disc1; StrgGrid.Floats[_kolHargaBeli,iBaris] := SOItems[i].Harga; StrgGrid.Ints[_KolLeadTime,iBaris] := SOItems[i].BarangSupplier.NewSupplierMerGroup.LeadTime; StrgGrid.Cells[_kolSuplierName,iBaris] := SOItems[i].BarangSupplier.NewSupplier.Nama; StrgGrid.Cells[_kolSuplierCode,iBaris] := SOItems[i].BarangSupplier.NewSupplier.Kode; StrgGrid.Floats[_kolQtyOrder,iBaris] := SOItems[i].Qty; StrgGrid.Cells[_kolPLUPurchase,iBaris] := SOItems[i].NewBarang.KodePurchase; StrgGrid.Floats[_kolQTYUOMPurchase,iBaris]:= SOItems[i].Qty; StrgGrid.Cells[_kolUOM,iBaris] := SOItems[i].NewUOM.UOM; StrgGrid.Cells[_kolProdukName,iBaris] := SOItems[i].NewBarang.Nama; StrgGrid.Cells[_kolPLU,iBaris] := SOItems[i].NewBarang.Kode; StrgGrid.Ints[_kolIsDecimal,iBaris] := SOItems[i].NewBarang.IsDecimal; StrgGrid.Cells[_kolLastGrNo,iBaris] := GetLastGrQty(StrgGrid.Cells[_kolPLU, iBaris], MasterNewUnit.ID); with TKonversiSatuan.Create(nil) do begin try IdSatuan := GetId(SOItems[i].NewBarang.Kode, SOItems[i].BarangSupplier.KodeSatuanBeli, SOItems[i].NewBarang.KodeSatuanStock.UOM); if LoadByID(IdSatuan) then begin if SkalaKonversi <> 0 then begin StrgGrid.Floats[_kolPKMAverage, iBaris] := SOItems[i].NewBarang.GetPKMAVG / SkalaKonversi; end; end; finally Free; end; end; StrgGrid.Floats[_kolMaxOrder,iBaris] := SOItems[i].BarangSupplier.MaxOrder; StrgGrid.Floats[_kolStockMin,iBaris] := SOItems[i].BarangSupplier.MinOrder; StrgGrid.AddCheckBox(_kolStatus, iBaris,True,True); StrgGrid.SetCheckBoxState(_kolStatus,iBaris,True); SOItems[i].FreeAndNilObjectProperti; if i < SOItems.Count - 1 then StrgGrid.AddRow; StrgGrid.Row := StrgGrid.RowCount - 1; end; end else begin edtNoSO.Text := ''; end; finally Free; cCloseWaitWindow; IsiNomorGrid(StrgGrid, 0); end; end;} end; procedure TfrmCreateSO.StrgGridCanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); begin inherited; if ACol in [_kolQtyOrder, _kolStatus, _kolPLU] then CanEdit := True else CanEdit := False; end; procedure TfrmCreateSO.CustomItem2Click(Sender: TObject); begin inherited; // cClearGrid(StrgGrid, False); end; procedure TfrmCreateSO.CustomItem1Click(Sender: TObject); begin inherited; // StrgGrid.Rows[StrgGrid.Row].Clear; // if StrgGrid.RowCount > 2 then // begin // StrgGrid.RemoveSelectedRows; // cGetServerTime // end; end; function TfrmCreateSO.isAdaKomaNonValid: Boolean; var iValIsDecimal: Integer; // boolValidInteger : boolean; // iValQtyOrder: Integer; iCheckQtyOrder: Integer; i: Integer; begin Result := False; { for i := 1 to StrgGrid.RowCount -1 do begin iValIsDecimal := StrToInt(StrgGrid.Cells[_kolIsDecimal,i]); if ((iValIsDecimal = 0) and (not TryStrToInt(StrgGrid.Cells[_kolQtyOrder,i],iCheckQtyOrder) = True)) then begin Result := True; CommonDlg.ShowError('Qty Order baris ke ' + IntToStr(i) + ' tidak boleh desimal !'); Exit; end; end; } end; function TfrmCreateSO.isAdaQtyKurang: Boolean; var // fValQtyMin: Double; // fValQtyOrder: Double; i: Integer; begin Result := False; { for i := 1 to StrgGrid.RowCount -1 do begin if (TryStrToFloat(StrgGrid.Cells[_kolQtyOrder,i],fValQtyOrder) = False) and (i<>0) then begin Result := True; CommonDlg.ShowError('Qty Order Baris ke : ' + IntToStr(i) + ' tidak valid !'); Exit; end; if (not (TryStrToFloat(StrgGrid.Cells[_kolStockMin,i],fValQtyMin))) and (i<>0) then begin Result := True; CommonDlg.ShowError('Qty Min Baris ke : ' + IntToStr(i) + ' tidak valid !'); Exit; end; TryStrToFloat(StrgGrid.Cells[_kolStockMin,i],fValQtyMin); if (fValQtyOrder < fValQtyMin) and (i <>0) then begin Result := True; CommonDlg.ShowError('Qty Order baris ke ' + IntToStr(i) + ' tidak boleh < Qty Min !'); Exit; end; end; } end; function TfrmCreateSO.isAdaQtyLebih: Boolean; var fValQtyMax: Double; fValQtyOrder: Double; i: Integer; begin Result := False; {for i := 1 to StrgGrid.RowCount -1 do begin fValQtyOrder := StrgGrid.Floats[_kolQtyOrder,i]; fValQtyMax := StrgGrid.Floats[_kolMaxOrder,i]; if (fValQtyOrder > fValQtyMax) and (i<>0) then begin Result := True; CommonDlg.ShowError('Qty Order baris ke ' + IntToStr(i) + ' tidak boleh > Qty Max !'); Exit; end; end; } end; function TfrmCreateSO.isAdaQtyNol: Boolean; var IsChecked: Boolean; i: Integer; begin {Result := False; for i := 1 to StrgGrid.RowCount -1 do begin StrgGrid.GetCheckBoxState(_kolStatus,i,IsChecked); //dulunya sgBarangNotForSo if not IsChecked then Continue; if ((StrgGrid.Cells[_kolQtyOrder,i]) = '') then begin Result := True; CommonDlg.ShowError('Qty Order Baris ke : ' + IntToStr(i) + ' belum diisi !'); Exit; end else if ((StrgGrid.Floats[_kolQtyOrder,i]) = 0) then begin Result := True; CommonDlg.ShowError('Qty Order Baris ke : ' + IntToStr(i) + ' masih nol !'); Exit; end; end;} end; function TfrmCreateSO.IsAdaUOMKosong: Boolean; var i: Integer; begin Result := False; {for i := 1 to StrgGrid.RowCount - 1 do begin if (StrgGrid.Cells[_kolUOM,i] = '') and (i <> 0) then begin Result := True; CommonDlg.ShowError('UOM Baris ke : ' + IntToStr(i) + ' belum diisi !'); Exit; end; end;} end; procedure TfrmCreateSO.StrgGridCellValidate(Sender: TObject; ACol, ARow: Integer; var Value: String; var Valid: Boolean); var aSS: TStrings; dNilai: Double; iNilai: Integer; begin inherited; { if ACol in [_kolQtyOrder] then begin if StrgGrid.Cells[_kolIsDecimal,ARow] = '0' then begin Valid := TryStrToInt(Value, iNilai); if Valid then Begin if (iNilai > StrgGrid.Floats[_kolMaxOrder,ARow]) or (iNilai < StrgGrid.Floats[_kolStockMin,ARow]) then Valid := False; end; end else begin Valid := TryStrToFloat(Value, dNilai); if Valid then Begin if (dNilai > StrgGrid.Floats[_kolMaxOrder,ARow]) or (dNilai < StrgGrid.Floats[_kolStockMin,ARow]) then Valid := False; end; end; end else if ACol in [_kolPLU] then begin if Value='' then Exit; if Length(Value)< igProd_Code_Length then begin Value := StrPadLeft(Value,igProd_Code_Length,'0'); end; with cOpenQuery(GetSQLItem4SO(Value)) do begin try if not Eof then begin aSS := TStringList.Create; try aSS.Append(Fields[0].AsString); aSS.Append(Fields[1].AsString); aSS.Append(Fields[2].AsString); aSS.Append(Fields[3].AsString); aSS.Append(Fields[4].AsString); aSS.Append(Fields[5].AsString); SetArowInGrid(aSS, ARow); finally aSS.Free; end; end else Valid := False; finally Free; end; end; end; } end; procedure TfrmCreateSO.StrgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String); begin inherited; FloatFormat := '%.0n'; if (ACol in [_kolMaxOrder,_kolStockMin,_kolQtyOrder, _kolQTYUOMPurchase, _kolQtyUOMStock]) and (ARow > 0) then IsFloat := True else if (ACol in [_kolHargaBeli, _kolPKMAverage, _kolDisc3, _kolDisc2, _kolDisc1]) and (ARow > 0) then begin FloatFormat := '%.2n'; IsFloat := True; end else IsFloat := False; end; procedure TfrmCreateSO.pnlTopDblClick(Sender: TObject); begin inherited; Button2.Visible := not Button2.Visible; end; procedure TfrmCreateSO.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var isChecked: Boolean; i: Integer; begin // inherited; { if (Key = VK_F5) then ShowStockCard() else if (Key = 88) then begin for i := 1 to strgGrid.RowCount do begin strgGrid.GetCheckBoxState(_kolStatus,i,isChecked); if isChecked then strgGrid.SetCheckBoxState(_kolStatus,i,False) else strgGrid.SetCheckBoxState(_kolStatus,i,True); end; end else if (Key = Ord('R')) and (ssctrl in Shift) then //Delete Row begin if StrgGrid.RowCount>2 then begin StrgGrid.ClearRows(StrgGrid.Row, 1); StrgGrid.RemoveSelectedRows; isiNomorGrid(StrgGrid, 0); end; end else if(Key = Ord('T')) and (ssctrl in Shift) then begin AddNewRow; StrgGrid.Col := _kolPLU; StrgGrid.Row := StrgGrid.RowCount-1; end else if(Key = Ord('F')) and (ssctrl in Shift) then grdSearch.Execute else if(Key = Ord('A')) and (ssctrl in Shift) then btn1.Click else if(Key = VK_RETURN) and (ssctrl in Shift) then actCreateSOExecute(sender) else if(Key = Ord('D')) and (ssctrl in Shift) then //History PO actShowHistorySOExecute(sender) else if (Key = Ord('E')) and (ssctrl in Shift) then //Edit SO fraFooter5Button1btnUpdateClick(sender) else if (Key = Ord('C')) and (ssctrl in Shift) then //New fraFooter5Button1btnDeleteClick(sender); } end; function TfrmCreateSO.GetLastGrQty(aBrgCode: string; aUnitId: Integer): string; var sSQL : string; begin // Result := ''; sSQL := 'select dod.DOD_QTY_ORDER_RECV, dod.DOD_DO_NO, dod.DATE_CREATE' + ' from do_detil dod' + ' where dod.DOD_BRG_CODE = '+ QuotedStr(aBrgCode) + ' and DOD_UNT_ID= '+ inttoStr(aUnitId) + ' order by dod.DATE_MODIFY, dod.DATE_CREATE desc'; { with cOpenQuery(ssQL) do begin try if not eof then Result := FloatToStr(Fields[0].AsFloat) else Result := ''; finally Free; end; end; } end; function TfrmCreateSO.IsAdaPLUKosong: Boolean; var i: Integer; begin Result := False; {for i := 1 to StrgGrid.RowCount - 1 do begin if (StrgGrid.Cells[_kolPLU,i] = '') then begin Result := True; if (CommonDlg.Confirm('PLU Baris ke : ' + IntToStr(i) + ' belum diisi !' + #13 + 'Apakah akan dihapus ?') = mrYes) then Begin StrgGrid.SelectRows(i,1); strgGrid.Rows[i].Clear; strgGrid.RemoveSelectedRows; End; Exit; end; end; } end; procedure TfrmCreateSO.StrgGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; {if FIsInsert or FIsEdit then begin if Key = vk_return then begin if StrgGrid.Col = _kolPLU then begin StrgGrid.Col := _kolQtyOrder; StrgGrid.SelectedCells[_kolQtyOrder, StrgGrid.row ] := True; StrgGrid.EditMode := True; end; end else if key = vk_f5 then begin if StrgGrid.Col = _kolPLU then actAddOthersProdSOExecute(Self); end else if (key = vk_down) and (ssCtrl in Shift) then begin if (StrgGrid.Cells[_kolPLU, StrgGrid.RowCount - 1] <> '') then StrgGrid.AddRow; end else if (key = vk_UP) and (ssCtrl in Shift) then begin if StrgGrid.RowCount > StrgGrid.FixedRows then begin if StrgGrid.RowCount > StrgGrid.FixedRows + 1 then begin StrgGrid.RemoveRows(StrgGrid.row , 1); end else begin StrgGrid.Rows[StrgGrid.row].Clear; end; end; end; end;} end; procedure TfrmCreateSO.fraFooter5Button1btnCloseClick(Sender: TObject); begin inherited; FIsCancel := True; fraFooter5Button1.btnCloseClick(Sender); end; procedure TfrmCreateSO.bStopClick(Sender: TObject); begin inherited; FIsCancel := True; end; function TfrmCreateSO.GetQUK(aBrgCode : String; aLeadTime : Integer; aSafetyStock : Double; aPKMAverage : Double; aKonversiSatuanPSL : Double; aKonversiSatuanPurch : Double; aMinor : Double; aMaxor : Double; var aOnHand : Double; var aStockUOMPurchase : Double; var aOnOrder : Double; var aAvgPKM : Double): Double; var dPKMStandar: Double; iJadwalOrder: Integer; dPKMToko: Double; iLevelOtorisasi: Integer; dPKMExist: Double; iN1: Integer; iUPBPlus: Integer; iN2: Integer; begin {with TNewSupplierMerGroup.Create(self) do begin try aAvgPKM := 0; if (aKonversiSatuanPSL <> 0) and (aKonversiSatuanPurch <> 0) then aAvgPKM := aPKMAverage * aKonversiSatuanPSL / aKonversiSatuanPurch; iLevelOtorisasi := 1; iN1 := 0; iN2 := 0; iUPBPlus := 0; iJadwalOrder := GetJadwalOrder(DayOfWeek(dtTgl.Date)); finally Free; end; end; } if aLeadTime > iJadwalOrder then dPKMStandar := (aLeadTime + aSafetyStock) * aAvgPKM + aMinor else dPKMStandar := (iJadwalOrder + aSafetyStock) * aAvgPKM + aMinor; dPKMToko := dPKMStandar * iLevelOtorisasi; dPKMExist := dPKMToko + iN1 + iUPBPlus + iN2; aOnHand := getValueOnHand(aBrgCode); aOnOrder := getValueOnOrder(aBrgCode); Result := dPKMExist - aOnHand - aOnOrder; aStockUOMPurchase := 0; if (aKonversiSatuanPSL <> 0) and (aKonversiSatuanPurch <> 0) then aStockUOMPurchase := (aOnHand + aOnOrder) * aKonversiSatuanPSL / aKonversiSatuanPurch; if Result > aMaxor then Result := aMaxor; if (Result - Floor(Result)) >= 0.75 then Result := Ceil(Result) else Result := Floor(Result); if Result < aMinor then Result := 0; end; function TfrmCreateSO.GetSQLLoadDataPLUForSO(aUnitID : Integer; aMerchandizeID : Integer; aTgl : TDateTime): string; begin Result := 'select b.BRG_CODE, b.SAT_CODE, c.BRGSUP_SAT_CODE_BUY, d.BRG_SAT_CODE_STOCK,' + ' a.PSS_QTY, e.KONVSAT_SCALE as ScalePsl, e1.KONVSAT_SCALE as ScaleBuy,' + ' a.PSS_QTY * e.KONVSAT_SCALE / e1.KONVSAT_SCALE as QtyBeli,' + ' d.brg_code, d.brg_alias, d.BRG_SAT_CODE_STOCK,' + ' d.BRG_CODE_PURCHASE, d.safety_stock, d.safety_stock,' + ' d.BRG_PKM_AVERAGE, d.BRG_IS_DECIMAL,' + ' d.BRG_PKM_AVERAGE, d.BRG_IS_DECIMAL,' + ' c.BRGSUP_SAT_CODE_BUY, c.BRGSUP_MIN_ORDER,' + ' c.BRGSUP_MAX_ORDER, c.BRGSUP_BUY_PRICE,' + ' c.brgsup_disc1, c.brgsup_disc2, c.brgsup_disc3,' + ' c.brgsup_id, c.BRGSUP_IS_BKP, c.BRGSUP_IS_PRIMARY,' + ' j.sup_name, j.sup_code,' + ' k.SUPMG_LEAD_TIME, k.SUPMG_LEAD_TIME, k.SUPMG_IS_SUN,' + ' k.SUPMG_IS_MON, k.SUPMG_IS_TUE, k.SUPMG_IS_WED,' + ' k.SUPMG_IS_THU, k.SUPMG_IS_FRI, k.SUPMG_IS_SAT' + ' from TPSSTORE a' + ' inner join TPURCHASESUGESTIONITEM b on a.PS_ID = b.PS_ID' + ' and a.PSI_ID = b.PSI_ID' + ' and a.UNT_ID = b.UNT_ID' + ' and a.PSS_UNT_ID = '+ IntToStr(aUnitID) + ' inner join tPurchaseSugestion m on (m.ps_id = b.ps_id' + ' and m.unt_id = b.unt_id' + ' and EXTRACTDATE(m.ps_tgljatuhtempo) = '+ TAppUtils.QuotD(aTgl) + ' )' + ' inner join barang d on b.BRG_CODE = d.BRG_CODE' + ' inner join ref$konversi_satuan e on d.BRG_CODE = e.KONVSAT_BRG_CODE' + ' and e.KONVSAT_SAT_CODE_FROM = b.SAT_CODE' + ' and d.BRG_SAT_CODE_STOCK = e.KONVSAT_SAT_CODE_TO' + ' left join barang_suplier c on b.BRG_CODE = c.BRGSUP_BRG_CODE' + ' left join ref$konversi_satuan e1 on d.BRG_CODE = e1.KONVSAT_BRG_CODE' + ' and e1.KONVSAT_SAT_CODE_FROM = c.BRGSUP_SAT_CODE_BUY' + ' and d.BRG_SAT_CODE_STOCK = e1.KONVSAT_SAT_CODE_TO' + ' left join suplier j on (j.sup_code = c.BRGSUP_SUP_CODE)' + ' left join suplier_merchan_grup k on (k.supmg_sub_code = c.brgsup_supmg_sub_code)' + ' where d.brg_merchan_id = '+ IntToStr(aMerchandizeID) + ' and d.BRG_IS_STOCK = 1' + ' and d.BRG_IS_ACTIVE = 1' + ' and d.BRG_TPBRG_ID <> '+ Trim(getGlobalVar('TIPE_BARANG_JB')) + ' order by d.brg_code asc, c.BRGSUP_IS_PRIMARY desc' end; function TfrmCreateSO.IsBaraSudahAda(aBrgCode : String ): Boolean; var i: Integer; begin Result := False; {for i := 1 to StrgGrid.RowCount - 1 do begin if (StrgGrid.Cells[_kolPLU, i] = aBrgCode) Then begin Result := True; Exit; end; end; } end; procedure TfrmCreateSO.btnTestingClick(Sender: TObject); var i: Integer; iJmlItem: Integer; begin inherited; Randomize; iJmlItem := RandomRange(1,20); for i := 1 to iJmlItem do DoSkenarioSO; end; procedure TfrmCreateSO.DoSkenarioSO; begin // frmMain.IsTesting := True; try DoTestingLoadDataPLU; DoTestingIsiQtyOrder; DoTestQtyStockDanQtyStockPurchase; DoTestingSimpan; finally // frmMain.IsTesting := False; end; end; procedure TfrmCreateSO.DoTestingIsiQtyOrder; var i: Integer; begin Randomize; // for i := 1 to StrgGrid.RowCount - 1 do begin // if Trim(StrgGrid.Cells[_kolPLU,i]) <> '' then // StrgGrid.Ints[_kolQtyOrder,i] := RandomRange(Floor(StrgGrid.Floats[_kolStockMin,i]), Floor(StrgGrid.Floats[_kolMaxOrder,i])) end; end; procedure TfrmCreateSO.DoTestingLoadDataPLU; var iJmlItem: Integer; i: Integer; begin Randomize; iJmlItem := RandomRange(1,15); for i := 1 to iJmlItem do actAddOthersProdSOExecute(nil); end; procedure TfrmCreateSO.DoTestingSimpan; begin fraFooter5Button1btnDeleteClick(nil); actCreateSOExecute(nil); end; procedure TfrmCreateSO.DoTestQtyStockDanQtyStockPurchase; var sStatus: string; dTotal: Double; dQtyPOOrder: Double; dQtyStock: Double; i: Integer; begin {for i := StrgGrid.RowCount - 1 downto 1 do begin if Trim(StrgGrid.Cells[_kolPLU,i]) = '' then Continue; dQtyStock := DoTestingGetQtyStock(StrgGrid.Cells[_KolPLU,i],StartOfTheYear(dtTgl.Date), dtTgl.Date, MasterNewUnit.ID); dQtyPOOrder := DoTestingGetQtyPOOrder(StrgGrid.Cells[_KolPLU,i], MasterNewUnit.ID, dtTgl.Date); dTotal := dQtyPOOrder + dQtyStock; sStatus := 'NOK'; if StrgGrid.Columns[_kolQtyUOMStock].Floats[i] = dTotal then sStatus := 'OK'; DoTestingSaveLog(edtNoSO.Text + ' ' + StrgGrid.Columns[_kolPLU].Rows[i], 'QTY STOCK', StrgGrid.Columns[_kolQtyUOMStock].Rows[i], FloatToStr(dTotal), sStatus, 'SO'); dTotal := dTotal / GetQtyConv(StrgGrid.Cells[_KolUOM,i],StrgGrid.Cells[_KolPLU,i]); sStatus := 'NOK'; if StrgGrid.Columns[_kolQtyUOMStock].Floats[i] = dTotal then sStatus := 'OK'; DoTestingSaveLog(edtNoSO.Text + ' ' + StrgGrid.Columns[_kolPLU].Rows[i], 'QTY STOCK ON PURCHASE', StrgGrid.Columns[_kolQTYUOMPurchase].Rows[i], FloatToStr(dTotal), sStatus, 'SO'); end; } end; function TfrmCreateSO.GetSQLItem4SO(aBrgCode: string=''): string; var sSQL: string; begin sSQL := 'select '+ ' br.brg_code as "Kode Barang", '+ ' br.brg_alias as "Alias Barang", '+ ' sp.sup_code as "Kode Suplier", '+ ' sp.sup_name as "Nama Suplier", '+ ' smg.supmg_sub_code as " Kode Suplier MerchanGroup", '+ ' bs.brgsup_id as "Id Barang Suplier", '+ ' br.BRG_PKM_AVERAGE '+ 'from '+ ' barang br '+ ' left join barang_suplier bs on bs.brgsup_brg_code=br.brg_code '+ ' left join suplier sp on sp.sup_code=bs.BRGSUP_SUP_CODE '+ ' left join suplier_merchan_grup smg on smg.supmg_sub_code=bs.brgsup_supmg_sub_code '+ 'where '+ ' br.BRG_IS_ACTIVE = 1 '+ // ' and br.BRG_MERCHAN_ID = ' + IntToStr(cGetIDfromCombo(cbbMerchanGroup)) + ' '+ ' and BR.BRG_TPBRG_ID <> '+ Trim(getGlobalVar('TIPE_BARANG_JB')); if aBrgCode <> '' then sSQL := sSQL + ' and br.BRG_CODE = '+ QuotedStr(aBrgCode); result := sSQL; end; procedure TfrmCreateSO.LoadDataStock2Temp; begin FIsCancel := False; try cShowWaitWindow('Load Data',Self); if not FIsSudahLoadDataStock then begin LoaDataToGridTemp(dtTgl.Date, MasterNewUnit); FIsSudahLoadDataStock := True; end; finally cCloseWaitWindow; end; end; procedure TfrmCreateSO.pmiHapusItemClick(Sender: TObject); begin inherited; // StrgGrid.Rows[StrgGrid.Row].Clear; // if StrgGrid.RowCount > 2 then // begin // StrgGrid.RemoveSelectedRows; // cGetServerTime // end; end; procedure TfrmCreateSO.pmiHapusSemuaClick(Sender: TObject); begin inherited; // cClearGrid(StrgGrid, False); end; procedure TfrmCreateSO.pmiCheckAllClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // StrgGrid.SetCheckBoxState(_kolStatus,i,True); // end; end; procedure TfrmCreateSO.pmiUncheckAllClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // StrgGrid.SetCheckBoxState(_kolStatus,i,False); // end; end; procedure TfrmCreateSO.pmiCheckAnalisisClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // if StrgGrid.Floats[_kolQtyAnalisis,i] > 0 then // StrgGrid.SetCheckBoxState(_kolStatus,i,True) // else // StrgGrid.SetCheckBoxState(_kolStatus,i,False); // end; end; procedure TfrmCreateSO.pmiCheckPSLClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // if StrgGrid.Floats[_kolQtyPSL,i] > 0 then // StrgGrid.SetCheckBoxState(_kolStatus,i,True) // else // StrgGrid.SetCheckBoxState(_kolStatus,i,False); // end; end; procedure TfrmCreateSO.pmiValFromBiggestClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // if StrgGrid.Floats[_kolQtyPSL,i] > StrgGrid.Floats[_kolQtyAnalisis,i] then // StrgGrid.Floats[_kolQtyOrder,i] := StrgGrid.Floats[_kolQtyPSL,i] // else // StrgGrid.Floats[_kolQtyOrder,i] := StrgGrid.Floats[_kolQtyAnalisis,i]; // end; end; procedure TfrmCreateSO.pmiValFromAnalisisClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // if StrgGrid.Floats[_kolQtyAnalisis,i] > 0 then // if StrgGrid.Floats[_kolQtyAnalisis,i] > StrgGrid.Floats[_kolStockMin,i] then // StrgGrid.Floats[_kolQtyOrder,i] := StrgGrid.Floats[_kolQtyAnalisis,i] // end; end; procedure TfrmCreateSO.pmiValFromPSLClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // if StrgGrid.Floats[_kolQtyPSL,i] > 0 then // if StrgGrid.Floats[_kolQtyPSL,i] > StrgGrid.Floats[_kolStockMin,i] then // StrgGrid.Floats[_kolQtyOrder,i] := StrgGrid.Floats[_kolQtyPSL,i] // end; end; procedure TfrmCreateSO.pmiValToZeroClick(Sender: TObject); var i :Integer; begin inherited; // for i:= StrgGrid.FixedRows+StrgGrid.FixedFooters to StrgGrid.RowCount - StrgGrid.FixedRows - StrgGrid.FixedFooters do // begin // StrgGrid.Floats[_kolQtyOrder,i] := 0; // end; end; procedure TfrmCreateSO.SetArowInGrid(Strings:Tstrings; aBaris: integer = -1); var aBarangSatuanBeli : string; IdSatuan : Integer; Kode : string; dStockUOMPurchase : Double; iOnHand : Double; i, iBaris : Integer; begin LoadDataStock2Temp; { for i := 1 to StrgGrid.RowCount do begin if (StrgGrid.Cells[_kolPLU, i] = Strings[0]) and (StrgGrid.Cells[_kolSuplierCode, i] = Strings[2]) and (StrgGrid.Cells[_kolProdukName,i] = Strings[1]) then begin CommonDlg.ShowError('Data ' + Strings[1] + ' Sudah Ada'); // StrgGrid.RemoveRows(iBaris,StrgGrid.Row); Exit; end; end; if aBaris < 0 then iBaris := getBarisKosong else iBaris := aBaris; if iBaris = 0 then begin strgGrid.AddRow; iBaris := strgGrid.RowCount - 1; end; iOnHand := getValueOnHand(Trim(Strings[0])) + getValueOnOrder(Trim(Strings[0])); StrgGrid.AddCheckBox(_kolStatus,iBaris,True,True); StrgGrid.SetCheckBoxState(_kolStatus,iBaris,True); StrgGrid.Cells[_kolPLU, iBaris] := Strings[0]; StrgGrid.Cells[_kolProdukName,iBaris] := Strings[1]; StrgGrid.Floats[_kolQtyUOMStock, iBaris] := iOnHand; StrgGrid.Cells[_kolSuplierCode,iBaris] := Strings[2]; StrgGrid.Cells[_kolSuplierName, iBaris] := Strings[3]; StrgGrid.Floats[_kolQtyOrder, iBaris] := 0; //------------------Load Data Barang-------------------------- Kode := Strings[0]; if FBarang.LoadByKode(Kode) then begin StrgGrid.Cells[_kolPLUPurchase, iBaris] := FBarang.KodePurchase; StrgGrid.Ints[_kolIsDecimal,iBaris] := FBarang.IsDecimal; end; //------------------ Load Data Suplier Merchan grup --------------- if FSupMerchan.LoadByKode(Strings[4]) then begin StrgGrid.Cells[_KolLeadTime, iBaris] := IntToStr(FSupMerchan.LeadTime); StrgGrid.Cells[_kolIsSun, iBaris] := IntToStr(FSupMerchan.IsSun); StrgGrid.Cells[_kolIsMon, iBaris] := IntToStr(FSupMerchan.IsMon); StrgGrid.Cells[_kolIsTue, iBaris] := IntToStr(FSupMerchan.IsTue); StrgGrid.Cells[_kolIsWed, iBaris] := IntToStr(FSupMerchan.IsWed); StrgGrid.Cells[_kolIsThu, iBaris] := IntToStr(FSupMerchan.IsThu); StrgGrid.Cells[_kolIsFri, iBaris] := IntToStr(FSupMerchan.IsFri); StrgGrid.Cells[_kolIsSat, iBaris] := IntToStr(FSupMerchan.IsSat); end; //------------------------Laod Data Barang Suplier ----------------------- if FBarangSuplier.LoadByID(StrToInt(Strings[5])) then begin aBarangSatuanBeli := FBarangSuplier.KodeSatuanBeli; StrgGrid.Cells[_kolUOM, iBaris] := aBarangSatuanBeli; StrgGrid.Floats[_kolQTYUOMPurchase, iBaris] := iOnHand / GetQtyConv(aBarangSatuanBeli, Strings[0]); strgGrid.Floats[_kolHargaBeli, iBaris] := FBarangSuplier.HargaBeli; StrgGrid.Cells[_kolBrgSupID, iBaris] := IntToStr(FBarangSuplier.ID); StrgGrid.Floats[_kolDisc1,iBaris] := FBarangSuplier.Disc1; StrgGrid.Floats[_kolDisc2,iBaris] := FBarangSuplier.Disc2; StrgGrid.Floats[_kolDisc3,iBaris] := FBarangSuplier.Disc3; StrgGrid.Cells[_kolIsBKP,iBaris] := IntToStr(FBarangSuplier.IsBKP); end; //------------------------Load Data Satuan----------------------------- IdSatuan := FSatuan.GetId(Kode, aBarangSatuanBeli, FBarang.KodeSatuanStock.UOM); dStockUOMPurchase := 0; if FSatuan.LoadByID(IdSatuan) then begin if FSatuan.SkalaKonversi <> 0 then begin dStockUOMPurchase := iOnHand / FSatuan.SkalaKonversi; StrgGrid.Floats[_kolPKMAverage, iBaris] := FBarang.GetPKMAVG / FSatuan.SkalaKonversi; end; end; StrgGrid.Floats[_kolMaxOrder,iBaris] := FBarangSuplier.MaxOrder; StrgGrid.Floats[_kolStockMin,iBaris] := FBarangSuplier.MinOrder; StrgGrid.Floats[_kolQTYUOMPurchase,iBaris] := dStockUOMPurchase; StrgGrid.Cells[_kolLastGrNo,iBaris] := GetLastGrQty(Strings[0], MasterNewUnit.ID); IsiNomorGrid(StrgGrid, 0); StrgGrid.SetFocus; StrgGrid.Col := _kolQtyOrder; StrgGrid.Row := iBaris; } end; procedure TfrmCreateSO.actToExcelExecute(Sender: TObject); begin inherited; // SaveDataGrid2Excel(StrgGrid); end; procedure TfrmCreateSO.btnAddOthersProdSOClick(Sender: TObject); begin inherited; actAddOthersProdSOExecute(Sender); end; procedure TfrmCreateSO.btnAddFromPOTraderClick(Sender: TObject); begin inherited; actAddPOTraderExecute(Sender); end; procedure TfrmCreateSO.btnToExcelClick(Sender: TObject); begin inherited; actToExcelExecute(Sender); end; end.
unit htPersistBase; interface uses Classes; type ThtPersistBase = class(TPersistent) private FOnChange: TNotifyEvent; protected procedure Change; virtual; public //:$ OnChange event is fired when a style property is changed. property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { ThtPersistBase } procedure ThtPersistBase.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; end.
unit uJSONUtils; interface uses System.JSON, System.JSON.Builders, System.JSON.Types, System.JSON.Writers, uModApp, System.TypInfo, System.StrUtils, System.SysUtils, System.Rtti, Data.DB; type TJSONUtils = class(TObject) protected public class function JSONToModel(AJSON: TJSONObject; AModAppClass: TModAppClass): TModApp; class function ModelToJSON(AObject: TModApp): TJSONObject; overload; class function ModelToJSON(AObject: TModApp; FilterProperties: Array Of String): TJSONObject; overload; class function GetProperty(AObject: TModApp; APropName: String; ShowException: Boolean = True): TRttiProperty; class function DataSetToJSON(ADataSet: TDataSet): TJSONArray; overload; class function GetValue(AJSON: TJSONObject; APairName: String): TJSONValue; end; implementation uses System.Variants; class function TJSONUtils.JSONToModel(AJSON: TJSONObject; AModAppClass: TModAppClass): TModApp; var ctx: TRttiContext; i: Integer; lAppClass: TModAppClass; lAppObject: TModApp; lAppObjectItem: TModApp; lExtVal: Extended; lIntVal: Integer; LJSONArr: TJSONArray; lJSONObj: TJSONObject; lJSONVal: TJSONValue; lObjectList: TObject; LPair: TJSONPair; prop: TRttiProperty; meth: TRttiMethod; rtItem: TRttiType; sGenericItemClassName: string; begin Result := AModAppClass.Create; prop := nil; for i := 0 to AJSON.Count-1 do begin Try LPair := AJSON.Pairs[i]; if UpperCase(LPair.JsonString.Value) = 'CLASSNAME' then continue; prop := GetProperty(Result, LPair.JsonString.Value); if not prop.IsWritable then continue; case prop.PropertyType.TypeKind of tkInteger, tkInt64 : if LPair.JsonValue.TryGetValue<Integer>(lIntVal) then prop.SetValue(Result, lIntVal); tkFloat : if LPair.JsonValue.TryGetValue<Extended>(lExtVal) then prop.SetValue(Result, lExtVal); tkUString, tkString, tkWideString : prop.SetValue(Result, LPair.JsonValue.Value); tkClass : begin meth := prop.PropertyType.GetMethod('ToArray'); if Assigned(meth) then //obj list begin lObjectList := prop.GetValue(Result).AsObject; if lObjectList = nil then continue; LJSONArr := TJSONArray(LPair.JsonValue); sGenericItemClassName := StringReplace(lObjectList.ClassName, 'TOBJECTLIST<','', [rfIgnoreCase]); sGenericItemClassName := StringReplace(sGenericItemClassName, '>','', [rfIgnoreCase]); rtItem := ctx.FindType(sGenericItemClassName); meth := prop.PropertyType.GetMethod('Add'); if Assigned(meth) and Assigned(rtItem) then begin //sayangny utk akses rtti object harus ada dulu, jadi create dulu if not rtItem.AsInstance.MetaclassType.InheritsFrom(TModApp) then continue; lAppClass := TModAppClass( rtItem.AsInstance.MetaclassType ); for lJSONVal in LJSONArr do begin lJSONObj := TJSONObject.ParseJSONValue(lJSONVal.ToString) as TJSONObject; lAppObjectItem := JSONToModel(lJSONObj, lAppClass); meth.Invoke(lObjectList,[lAppObjectItem]); FreeAndNil(LJSONObj); end; end; end else begin if not prop.PropertyType.AsInstance.MetaclassType.InheritsFrom(TModApp) then continue; lAppClass := TModAppClass( prop.PropertyType.AsInstance.MetaclassType ); lJSONObj := TJSONObject.ParseJSONValue(LPair.JSONValue.ToString) as TJSONObject; lAppObject := JSONToModel(lJSONObj, lAppClass); lAppObject.ObjectState := 3; prop.SetValue(Result, lAppObject); FreeAndNil(LJSONObj); end; end; else prop.SetValue(Result, LPair.JsonValue.Value); end; Result.ObjectState := 0; except on E:Exception do begin if prop <> nil then E.Message := 'Error at Object ' + Result.ClassName + ' Property ' + prop.Name + #13 + E.Message; Raise; end; End; end; end; class function TJSONUtils.ModelToJSON(AObject: TModApp): TJSONObject; begin Result := ModelToJSON(AObject, []) end; class function TJSONUtils.ModelToJSON(AObject: TModApp; FilterProperties: Array Of String): TJSONObject; var ctx : TRttiContext; i: Integer; // lDate: TDatetime; lModItem: TModApp; lObj: TObject; lObjectList: TObject; lJSOArr: TJSONArray; lJSONItem: TJSONObject; lVal: Extended; meth: TRttiMethod; pairName: string; rt : TRttiType; prop : TRttiProperty; // sGenericItemClassName: string; value: TValue; function CheckFilter(aPropName: String): Boolean; var lFilter: string; begin Result := Length(FilterProperties) = 0; if Result then exit; for lFilter in FilterProperties do begin if LowerCase(aPropName) = LowerCase(lFilter) then Result := True; end; end; begin AObject.ObjectState := 0; Result := TJSONObject.Create; rt := ctx.GetType(AObject.ClassType); for prop in rt.GetProperties do begin pairName := LowerCase(prop.Name); if not CheckFilter(pairName) then continue; If prop.Visibility = mvPublished then begin case prop.PropertyType.TypeKind of tkInteger, tkInt64, tkFloat : begin lVal := prop.GetValue(AObject).AsExtended; // if CompareText('TDateTime', prop.PropertyType.Name)=0 then // begin // lDate := lVal; // Result.AddPair(pairName, TJSONString.Create(DateToStr(lDate))); // end else Result.AddPair(pairName, TJSONNumber.Create(lVal)); end; tkUString, tkString, tkWideString : Result.AddPair(pairName, TJSONString.Create(prop.GetValue(AObject).AsString)); tkClass : begin lObj := prop.GetValue(AObject).AsObject; if lObj = nil then Result.AddPair(pairName, TJSONNull.Create) else if lObj.InheritsFrom(TModApp) then Result.AddPair(pairName, Self.ModelToJSON(TModApp(lObj), ['ID'])); end; else Result.AddPair(pairName, TJSONString.Create(VarToStr(prop.GetValue(AObject).AsVariant))); end; end else begin if prop.PropertyType.TypeKind = tkClass then begin meth := prop.PropertyType.GetMethod('ToArray'); if Assigned(meth) then begin lObjectList := prop.GetValue(AOBject).AsObject; if lObjectList = nil then begin Result.AddPair(pairName, TJSONNull.Create); continue; end else begin value := meth.Invoke(prop.GetValue(AObject), []); Assert(value.IsArray); lJSOArr := TJSONArray.Create; Result.AddPair(pairName, lJSOArr); for i := 0 to value.GetArrayLength - 1 do begin lObj := value.GetArrayElement(i).AsObject; If not lObj.ClassType.InheritsFrom(TModApp) then continue; //bila ada generic selain class ini lModItem := TModApp(lObj); lJSONItem := Self.ModelToJSON(lModItem); lJSOArr.AddElement(lJSONItem); end; end; end; end; end; end; end; class function TJSONUtils.GetProperty(AObject: TModApp; APropName: String; ShowException: Boolean = True): TRttiProperty; var ctx : TRttiContext; rt : TRttiType; prop : TRttiProperty; begin Result := nil; rt := ctx.GetType(AObject.ClassType); for prop in rt.GetProperties do begin // If not prop.Visibility in [mvPublished, mvPublic] then continue; if LowerCase(prop.Name) = LowerCase(APropName) then Result := prop; if Result <> nil then break; end; if (Result = nil) and (ShowException) then raise Exception.Create( 'Property : ' + APropName + ' can''t be found in ' + AObject.ClassName ); end; class function TJSONUtils.DataSetToJSON(ADataSet: TDataSet): TJSONArray; var i: Integer; // lJSOArr: TJSONArray; lJSRow: TJSONObject; begin // Result := TJSONObject.Create; Result := TJSONArray.Create; // Result.AddPair('Data', lJSOArr); ADataSet.First; while not ADataSet.Eof do begin lJSRow := TJSONObject.Create; for i := 0 to ADataSet.FieldCount-1 do lJSROw.AddPair(ADataSet.Fields[i].FieldName, ADataSet.Fields[i].Value); Result.AddElement(lJSROw); ADataSet.Next; end; end; class function TJSONUtils.GetValue(AJSON: TJSONObject; APairName: String): TJSONValue; var i: Integer; begin Result := nil; for i := 0 to AJSON.Count-1 do begin if UpperCase(AJSON.Pairs[i].JsonString.Value) = UpperCase(APairName) then Result := AJSON.Pairs[i].JsonValue; end; end; end.
unit ExtGUI.ListBox.Books; interface uses System.Classes, Vcl.StdCtrls, Vcl.Controls, System.Types, Vcl.Graphics, Winapi.Windows, System.JSON, System.Generics.Collections, DataAccess.Books, Model.Book, Model.BookCollection; type { TODO 4: Too many responsibilities. Separate GUI from structures } // Split into 2 classes TBooksContainer TListBoxesForBooks // Add new unit: Model.Books.pas TBooksListBoxConfigurator = class(TComponent) private FAllBooks: TBookCollection; FListBoxOnShelf: TListBox; FListBoxAvaliable: TListBox; FBooksOnShelf: TBookCollection; FBooksAvaliable: TBookCollection; DragedIdx: integer; procedure EventOnStartDrag(Sender: TObject; var DragObject: TDragObject); procedure EventOnDragDrop(Sender, Source: TObject; X, Y: integer); procedure EventOnDragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: Boolean); procedure EventOnDrawItem(Control: TWinControl; Index: integer; Rect: TRect; State: TOwnerDrawState); procedure AddBookToAvaliableOrOnShelfLits(b: TBook); procedure ConfigureBookListBox(ABookList: TBookCollection; AListBox: TListBox); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { TODO 3: Introduce 3 properties: ListBoxOnShelf, ListBoxAvaliable, Books } procedure PrepareListBoxes(lbxOnShelf, lbxAvaliable: TListBox); function GetBookList(kind: TBookListKind): TBookCollection; function FindBook(isbn: string): TBook; procedure InsertNewBook(b: TBook); end; implementation uses System.SysUtils, DataAccess.Books.FireDAC, Utils.General, Data.Main; constructor TBooksListBoxConfigurator.Create(AOwner: TComponent); var b: TBook; BooksDAO: IBooksDAO; begin inherited; // --------------------------------------------------- FAllBooks := TBookCollection.Create(); { TODO 5: Discuss how to remove this dependency. Check implentation uses } BooksDAO := GetBooks_FireDAC(DataModMain.dsBooks); FAllBooks.LoadDataSet(BooksDAO); // --------------------------------------------------- FBooksOnShelf := TBookCollection.Create(false); FBooksAvaliable := TBookCollection.Create(false); for b in FAllBooks do AddBookToAvaliableOrOnShelfLits(b); end; destructor TBooksListBoxConfigurator.Destroy; begin FAllBooks.Free; FBooksOnShelf.Free; FBooksAvaliable.Free; inherited; end; function TBooksListBoxConfigurator.GetBookList(kind: TBookListKind) : TBookCollection; begin case kind of blkAll: Result := FAllBooks; blkOnShelf: Result := FBooksOnShelf; blkAvaliable: Result := FBooksAvaliable else raise Exception.Create('Not supported collection type'); end; end; procedure TBooksListBoxConfigurator.InsertNewBook(b: TBook); begin FAllBooks.Add(b); AddBookToAvaliableOrOnShelfLits(b); FListBoxAvaliable.AddItem(b.title, b); end; procedure TBooksListBoxConfigurator.ConfigureBookListBox (ABookList: TBookCollection; AListBox: TListBox); var b: TBook; begin for b in ABookList do AListBox.AddItem(b.title, b); AListBox.OnDragDrop := EventOnDragDrop; AListBox.OnDragOver := EventOnDragOver; AListBox.OnStartDrag := EventOnStartDrag; AListBox.OnDrawItem := EventOnDrawItem; AListBox.Style := lbOwnerDrawFixed; AListBox.DragMode := dmAutomatic; AListBox.ItemHeight := 50; end; procedure TBooksListBoxConfigurator.AddBookToAvaliableOrOnShelfLits(b: TBook); begin if b.status = 'on-shelf' then FBooksOnShelf.Add(b) else if b.status = 'avaliable' then FBooksAvaliable.Add(b); end; function TBooksListBoxConfigurator.FindBook(isbn: string): TBook; begin Result := FAllBooks.FindByISBN(isbn); end; procedure TBooksListBoxConfigurator.PrepareListBoxes(lbxOnShelf, lbxAvaliable: TListBox); begin FListBoxOnShelf := lbxOnShelf; FListBoxAvaliable := lbxAvaliable; ConfigureBookListBox(FBooksOnShelf, lbxOnShelf); ConfigureBookListBox(FBooksAvaliable, lbxAvaliable); end; procedure TBooksListBoxConfigurator.EventOnStartDrag(Sender: TObject; var DragObject: TDragObject); var lbx: TListBox; begin lbx := Sender as TListBox; DragedIdx := lbx.ItemIndex; end; procedure TBooksListBoxConfigurator.EventOnDragDrop(Sender, Source: TObject; X, Y: integer); var lbx2: TListBox; lbx1: TListBox; b: TBook; srcList: TBookCollection; dstList: TBookCollection; begin lbx1 := Source as TListBox; lbx2 := Sender as TListBox; b := lbx1.Items.Objects[DragedIdx] as TBook; if lbx1 = FListBoxOnShelf then begin srcList := FBooksOnShelf; dstList := FBooksAvaliable; end else begin srcList := FBooksAvaliable; dstList := FBooksOnShelf; end; dstList.Add(srcList.Extract(b)); lbx1.Items.Delete(DragedIdx); lbx2.AddItem(b.title, b); end; procedure TBooksListBoxConfigurator.EventOnDragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: Boolean); begin Accept := (Source is TListBox) and (DragedIdx >= 0) and (Sender <> Source); end; procedure TBooksListBoxConfigurator.EventOnDrawItem(Control: TWinControl; Index: integer; Rect: TRect; State: TOwnerDrawState); var s: string; ACanvas: TCanvas; b: TBook; r2: TRect; lbx: TListBox; colorTextTitle: integer; colorTextAuthor: integer; colorBackground: integer; colorGutter: integer; begin // TOwnerDrawState = set of (odSelected, odGrayed, odDisabled, odChecked, // odFocused, odDefault, odHotLight, odInactive, odNoAccel, odNoFocusRect, // odReserved1, odReserved2, odComboBoxEdit); lbx := Control as TListBox; // if (odSelected in State) and (odFocused in State) then if (odSelected in State) then begin colorGutter := $F0FFD0; colorTextTitle := clHighlightText; colorTextAuthor := $FFFFC0; colorBackground := clHighlight; end else begin colorGutter := $A0FF20; colorTextTitle := lbx.Font.Color; colorTextAuthor := $909000; colorBackground := lbx.Color; end; b := lbx.Items.Objects[Index] as TBook; s := b.title; ACanvas := lbx.Canvas; ACanvas.Brush.Color := colorBackground; r2 := Rect; r2.Left := 0; ACanvas.FillRect(r2); ACanvas.Brush.Color := colorGutter; r2 := Rect; r2.Left := 0; InflateRect(r2, -3, -5); r2.Right := r2.Left + 6; ACanvas.FillRect(r2); ACanvas.Brush.Color := colorBackground; Rect.Left := Rect.Left + 13; ACanvas.Font.Color := colorTextAuthor; ACanvas.Font.Size := lbx.Font.Size; ACanvas.TextOut(13, Rect.Top + 2, b.author); r2 := Rect; r2.Left := 13; r2.Top := r2.Top + ACanvas.TextHeight('Ag'); ACanvas.Font.Color := colorTextTitle; ACanvas.Font.Size := lbx.Font.Size + 2; InflateRect(r2, -2, -1); DrawText(ACanvas.Handle, PChar(s), Length(s), r2, // DT_LEFT or DT_WORDBREAK or DT_CALCRECT); DT_LEFT or DT_WORDBREAK); end; end.
unit Xplat.Utils; interface uses System.SysUtils, AnonThread, System.Generics.Collections, System.Classes, Xplat.Services; type EAsyncException = class(Exception); TAsyncProgress<T> = class public class procedure Execute(AFunc: TFunc<T>; AOnFinished: TProc<T>; AOnError: TProc<Exception>); end; function PleaseWaitService: IPleaseWaitService; procedure ProgressProc(AProc: TProc); procedure StartWait; procedure StopWait; implementation uses FMX.Platform; procedure ProgressProc(AProc: TProc); begin StartWait; try AProc; finally StopWait; end; end; { TAsyncProgress<T> } class procedure TAsyncProgress<T>.Execute(AFunc: TFunc<T>; AOnFinished: TProc<T>; AOnError: TProc<Exception>); var lThread: TAnonymousThread<T>; begin StartWait; lThread := TAnonymousThread<T>.Create( //Method called in TThread.Execute AFunc, //Method called in TThread.OnTerminate if there was no exception raised in //the running thread. Will run in main thread. procedure(AResult: T) begin StopWait; if Assigned(AOnFinished) then AOnFinished(AResult); end, //Method called in TThread.OnTerminate if there was an exception raised in //the running thread. Will run in main thread. procedure(AError: Exception) begin StopWait; if Assigned(AOnError) then AOnError(AError); end); end; function PleaseWaitService: IPleaseWaitService; begin if TPlatformServices.Current.SupportsPlatformService(IPleaseWaitService) then Result := TPlatformServices.Current.GetPlatformService(IPleaseWaitService) as IPleaseWaitService else Result := nil; end; procedure ToggleWait(AStart: Boolean); var lSvc: IPleaseWaitService; begin lSvc := PleaseWaitService; if Assigned(lSvc) then if AStart then lSvc.StartWait else lSvc.StopWait; end; procedure StartWait; begin ToggleWait(True); end; procedure StopWait; begin ToggleWait(False); end; end.
{: This form showcases runtime object creation and framerate independant motion.<p> We start with an almost empty scene. The dummy cube is used as a convenient way to orient the camera (using its TargetObject property). Planes are programmatically added to the scene in FormCreate and spinned in the GLCadencer1Progress event.<p> Framerate independance motion is obtained by using a clock reference (in this sample, it is given by the TGLCadencer, which uses the high performance precision counter as reference). You can check it by resizing the window : whatever the framerate, the spin speed is the same.<br> In this sample, it is extremely simply done, but with more complex scenes and movements the same rule applies : for framerate independant motion, you need a clock measurement.<p> Using the TGLCadencer is the standard way for animating under GLScene, it offers various option and can drive animation automatically or just act as a manual trigger. Basic use just involves dropping a cadencer and adjusting its "Scene" property.<p> Note that measured framerates are 1 sec averages, a TTimer is used to refresh and reset FPS counter. } unit Unit1; interface {$MODE Delphi} uses Forms, GLScene, GLObjects, GLTexture, Classes, Controls, ExtCtrls, StdCtrls, GLCadencer, GLLCLViewer, GLColor, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; DummyCube1: TGLDummyCube; StaticText1: TStaticText; Timer1: TTimer; GLCadencer1: TGLCadencer; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); private { Déclarations privées } public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.lfm} uses GLVectorGeometry, SysUtils; const cNbPlanes = 30; cStackHeight = 8; procedure TForm1.FormCreate(Sender: TObject); var i: integer; plane: TGLPlane; begin // our column is just a stack of planes for i := 0 to cNbPlanes - 1 do begin // create planes as child of the dummycube plane := TGLPlane(DummyCube1.AddNewChild(TGLPlane)); // default plane size is 1x1, we want bigger planes ! plane.Width := 2; plane.Height := 2; // orient and position then planes in the stack plane.Position.Y := cStackHeight * (0.5 - i / cNbPlanes); plane.Direction.AsVector := YHmgVector; // we use the emission color, since there is no light in the scene // (allows 50+ FPS with software opengl on <400 Mhz CPUs ;) plane.Material.FrontProperties.Emission.Color := VectorLerp(clrBlue, clrYellow, i / cNbPlanes); end; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); var i: integer; begin // for all planes (all childs of the dummycube) for i := 0 to DummyCube1.Count - 1 do // roll them accordingly to our time reference and position in the stack (DummyCube1.Children[i] as TGLPlane).RollAngle := 90 * cos(newTime + i * PI / cNbPlanes); end; procedure TForm1.Timer1Timer(Sender: TObject); begin // update FPS and reset counter for the next second StaticText1.Caption := Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
unit UMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UBookList, UVisitorList, UBorrowList, Menus, ActnList, ComCtrls, ExtCtrls, StdCtrls, Buttons; resourcestring sCODE = 'Код'; sTITLE = 'Название'; sAUTHOR = 'Автор'; sPUBLISH_YEAR = 'Год издания'; sPUBLISH_LANG = 'Язык публикации'; sNAME = 'ФИО'; sADDRESS = 'Адрес проживания'; sPHONE = 'Телефон'; sBOOK_TITLE = 'Название книги'; sBORROW_DATE = 'Дата выдачи'; sEXP_RETURN_DATE = 'Дата возврата'; sREAL_RETURN_DATE = 'Возврат'; sALL_BOOKS = 'Все книги'; sNOT_BORROWED_BOOKS = 'Невзятые книги'; sBORROWED_BOOKS = 'Взятые книги'; sADD_BOOK = 'Добавить книгу'; sDELETE_BOOK = 'Удалить книгу'; sCHANGE_BOOK = 'Изменить информацию о книге'; sSHOW_ALL_BOOKS = 'Показать все книги'; sSHOW_BORROWED_BOOKS = 'Показать взятые книги'; sSHOW_NOT_BORROWED_BOOKS = 'Показать невзятые книги'; sALL_VISITORS = 'Все посетители'; sDEBTS = 'Должники'; sBAD_VISITORS = 'Недоверенные'; sADD_VISITOR = 'Добавить посетителя'; sDELETE_VISITOR = 'Удалить посетителя'; sCHANGE_VISITOR = 'Изменить информацию о посетителе'; sSHOW_ALL_VISITORS = 'Показать всех посетителей'; sSHOW_DEBTS = 'Показать должников'; sSHOW_BAD_VISITORS = 'Показать недоверенных'; sALL_BORROWS = 'Все записи'; sOPEN_BORROWS = 'Открытые записи'; sCLOSED_BORROWS = 'Закрытые записи'; sADD_BORROW = 'Записать книгу на посетителя'; sCHANGE_BORROW = 'Изменить запись'; sCLOSE_BORROW = 'Закрыть запись'; sSHOW_ALL_BORROWS = 'Показать все записи'; sSHOW_OPEN_BORROWS = 'Показать открытые записи'; sSHOW_CLOSED_BORROWS = 'Показать закрытые записи'; sINCORRECT_VISITOR_ID = 'Вы выбрали несуществующего посетителя'; sINCORRECT_BOOK_CODE = 'Вы выбрали несуществующую книгу'; sINCORRECT_BORROW_CODE = 'Вы выбрали несуществующую запись'; sFIELD_MUST_BE_FILLED = 'Поле должно быть заполнено'; sENTER_CORRECT_DATA = 'Введите корректные данные'; sENTER_HOUSE_NUMBER = 'Введите номер дома'; sENTER_PUBLISH_YEAR = 'Введите год публикации'; sENTER_BOOK_TITLE = 'Введите название книги'; sENTER_BOOK_AUTHOR = 'Введите фамилию автора'; sENTER_VISITOR_NAME = 'Введите имя посетителя'; sENTER_CODE = 'Введите код'; sTITLE_BOOK_SEARCH = 'Поиск книг по названию'; sAUTHOR_BOOK_SEARCH = 'Поиск книг по автору'; sNAME_VISITOR_SEARCH = 'Поиск посетителей по фамилии'; sFIND_BOOKS_BY_AUTHOR = 'Найти книги по автору'; sFIND_BOOKS_BY_TITLE = 'Найти книги по названию'; sFIND_VISITORS_BY_NAME = 'Найти посетителей по имени'; sERROR = 'Ошибка'; sSELECT = 'Выбрать'; sLANG_RU = 'Русский'; sLANG_EN = 'Английский'; sLANG_CH = 'Китайский'; sLANG_BY = 'Белорусский'; sLANG_JP = 'Японский'; sLANG_SP = 'Испанский'; sCITY_SHORT = 'г.'; sHOUSE_SHORT = 'д.'; sFLAT_SHORT = 'кв.'; sBOOK_CODE = 'Код книги'; sVISITOR_ID = 'Код посетителя'; sRETURN_PERIOD = 'Срок возврата (дней)'; sFIRST_NAME = 'Имя'; sMIDDLE_NAME = 'Отчество'; sLAST_NAME = 'Фамилия'; sSTREET = 'Улица'; sCITY = 'Город'; sHOUSE = 'Дом'; sFLAT = 'Квартира'; type TListType = (cBOOKS, cVISITORS, cBORROWS); TListAttribute = (cFULL, cOPEN, cCLOSE, cTITLE, cNAME); TDialogType = (cADD, cCHANGE, cDELETE); TfrmMain = class(TForm) alMain: TActionList; aAddBook: TAction; aDeleteBook: TAction; aChangeBook: TAction; aAddVisitor: TAction; aDeleteVisitor: TAction; aChangeVisitor: TAction; aAddBorrow: TAction; aChangeBorrow: TAction; menuMain: TMainMenu; miBooks: TMenuItem; miVisitors: TMenuItem; miBorrows: TMenuItem; msiAddBook: TMenuItem; msiAddVisitor: TMenuItem; msiAddBorrow: TMenuItem; pnlControls: TPanel; btnShowBadVisitors: TBitBtn; aShowDebts: TAction; aShowBadVisitors: TAction; aShowBorrowedBooks: TAction; aFindBooksByAuthor: TAction; aFindBooksByTitle: TAction; btnShowDebts: TButton; btnShowBorrowedBooks: TButton; btnFindBooksByAuthor: TButton; editBooksAuthor: TEdit; editBooksTitle: TEdit; btnFindBooksByTitle: TButton; btnShowAllBooks: TButton; aShowAllBooks: TAction; btnShowAllVisitors: TButton; aShowAllVisitors: TAction; editVisitorsName: TEdit; btnFindVisitorsByName: TButton; aFindVisitorsByName: TAction; bevelLineTop: TBevel; btnShowNotBorrowedBooks: TButton; aShowNotBorrowedBooks: TAction; bevelLineBottom: TBevel; btnShowAllBorrows: TButton; btnShowOpenBorrows: TButton; btnShowClosedBorrows: TButton; aShowAllBorrows: TAction; aShowOpenBorrows: TAction; aShowClosedBorrows: TAction; pnlLists: TPanel; labelCurrentList: TLabel; lvCurrentList: TListView; msiChangeBook: TMenuItem; msiChangeVisitor: TMenuItem; msiDeleteVisitor: TMenuItem; msiDeleteBook: TMenuItem; msiChangeBorrow: TMenuItem; aCloseBorrow: TAction; msiCloseBorrow: TMenuItem; msiBookSplitter: TMenuItem; msiShowAllBooks: TMenuItem; msiShowBorrowedBooks: TMenuItem; msiShowNotBorrowedBooks: TMenuItem; msiVisitorSplitter: TMenuItem; msiShowAllVisitors: TMenuItem; msiShowDebts: TMenuItem; msiShowBadVisitors: TMenuItem; msiBorrowSplitter: TMenuItem; msiShowAllBorrows: TMenuItem; msiShowOpenBorrows: TMenuItem; msiShowClosedBorrows: TMenuItem; procedure FormCreate(Sender: TObject); procedure aAddBookExecute(Sender: TObject); procedure aShowAllVisitorsExecute(Sender: TObject); procedure aShowAllBooksExecute(Sender: TObject); procedure aShowAllBorrowsExecute(Sender: TObject); procedure aAddVisitorExecute(Sender: TObject); procedure aAddBorrowExecute(Sender: TObject); procedure aFindBooksByTitleExecute(Sender: TObject); procedure aFindBooksByAuthorExecute(Sender: TObject); procedure aFindVisitorsByNameExecute(Sender: TObject); procedure aShowOpenBorrowsExecute(Sender: TObject); procedure aShowClosedBorrowsExecute(Sender: TObject); procedure aShowNotBorrowedBooksExecute(Sender: TObject); procedure aShowBorrowedBooksExecute(Sender: TObject); procedure aShowDebtsExecute(Sender: TObject); procedure aShowBadVisitorsExecute(Sender: TObject); procedure aChangeBookExecute(Sender: TObject); procedure aDeleteBookExecute(Sender: TObject); procedure aDeleteVisitorExecute(Sender: TObject); procedure aChangeVisitorExecute(Sender: TObject); procedure aChangeBorrowExecute(Sender: TObject); procedure aCloseBorrowExecute(Sender: TObject); private // Тип текущего выведенного списка currentListType: TListType; // Определяет какие записи требуется вывести currentListAttribute: TListAttribute; // Устанавливает заголовки компонентов procedure setCaptions; // Заполняет столбцы listView procedure setColumnsBooks; procedure setColumnsVisitors; procedure setColumnsBorrows; // Выводит список procedure showBooksList; procedure showVisitorsList; procedure showBorrowsList; public // Тип вызываемого диалога dialogType: TDialogType; //Определяет, какой список необходимо вывести procedure showList; end; var frmMain: TfrmMain; implementation uses DateUtils, UAddBook, UAddVisitor, UAddBorrow; {$R *.dfm} procedure TfrmMain.setCaptions; begin editBooksAuthor.Text := sENTER_BOOK_AUTHOR; editBooksTitle.Text := sENTER_BOOK_TITLE; editVisitorsName.Text := sENTER_VISITOR_NAME; aAddBook.Caption := sADD_BOOK; aDeleteBook.Caption := sDELETE_BOOK; aChangeBook.Caption := sCHANGE_BOOK; aAddVisitor.Caption := sADD_VISITOR; aDeleteVisitor.Caption := sDELETE_VISITOR; aChangeVisitor.Caption := sCHANGE_VISITOR; aAddBorrow.Caption := sADD_BORROW; aChangeBorrow.Caption := sCHANGE_BORROW; aCloseBorrow.Caption := sCLOSE_BORROW; aShowAllVisitors.Caption := sSHOW_ALL_VISITORS; aShowDebts.Caption := sSHOW_DEBTS; aShowBadVisitors.Caption := sSHOW_BAD_VISITORS; aShowAllBooks.Caption := sSHOW_ALL_BOOKS; aShowBorrowedBooks.Caption := sSHOW_BORROWED_BOOKS; aShowNotBorrowedBooks.Caption := sSHOW_NOT_BORROWED_BOOKS; aShowAllBorrows.Caption := sSHOW_ALL_BORROWS; aShowOpenBorrows.Caption := sSHOW_OPEN_BORROWS; aShowClosedBorrows.Caption := sSHOW_CLOSED_BORROWS; aFindBooksByAuthor.Caption := sFIND_BOOKS_BY_AUTHOR; aFindBooksByTitle.Caption := sFIND_BOOKS_BY_TITLE; aFindVisitorsByName.Caption := sFIND_VISITORS_BY_NAME; end; // Заполняет столбцы listView procedure TfrmMain.setColumnsBooks; var listColumn: TListColumn; begin listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sCODE; listColumn.Width := 50; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sTITLE; listColumn.Width := 150; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sAUTHOR; listColumn.Width := 150; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sPUBLISH_YEAR; listColumn.Width := 125; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sPUBLISH_LANG; listColumn.Width := 125; end; // Заполняет столбцы listView procedure TfrmMain.setColumnsVisitors; var listColumn: TListColumn; begin listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sCODE; listColumn.Width := 50; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sNAME; listColumn.Width := 200; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sADDRESS; listColumn.Width := 200; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sPHONE; listColumn.Width := 125; end; // Заполняет столбцы listView procedure TfrmMain.setColumnsBorrows; var listColumn: TListColumn; begin listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sCODE; listColumn.Width := 40; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sBOOK_TITLE; listColumn.Width := 150; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sNAME; listColumn.Width := 200; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sBORROW_DATE; listColumn.Width := 100; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sEXP_RETURN_DATE; listColumn.Width := 100; listColumn := lvCurrentList.Columns.Add; listColumn.Caption := sREAL_RETURN_DATE; listColumn.Width := 100; end; // Выводит список книг procedure TfrmMain.showBooksList; var book: TBooks; borrow: TBorrows; i, j: Integer; listItem: TListItem; error: Boolean; begin SetLength(book, 0); SetLength(borrow, 0); error := false; case currentListAttribute of // Вывод всех книг cFULL: begin labelCurrentList.Caption := sALL_BOOKS; book := returnAllBooks; end; // Вывод невзятых книг cOPEN: begin labelCurrentList.Caption := sNOT_BORROWED_BOOKS; book := returnAllBooks; borrow := returnOpenBorrows; for i := 0 to length(book) - 1 do begin error := false; for j := 0 to length(borrow) - 1 do begin if book[i].code = borrow[j].bookCode then error := true; end; if not error then book[i].code := -1; end; error := false; end; // Вывод взятых книг cCLOSE: begin labelCurrentList.Caption := sBORROWED_BOOKS; book := returnAllBooks; borrow := returnOpenBorrows; for i := 0 to length(book) - 1 do begin error := false; for j := 0 to length(borrow) - 1 do begin if book[i].code = borrow[j].bookCode then error := true; end; if error then book[i].code := -1; end; error := false; end; // Поиск по названию cTITLE: begin labelCurrentList.Caption := sTITLE_BOOK_SEARCH; if editBooksTitle.Text <> sENTER_BOOK_TITLE then begin book := findByTitle(editBooksTitle.Text); end else begin error := true; MessageBox(Handle, PChar(sENTER_BOOK_TITLE), PChar(sERROR), MB_OK or MB_ICONWARNING); end; end; // Поиск по автору cNAME: begin labelCurrentList.Caption := sAUTHOR_BOOK_SEARCH; if editBooksAuthor.Text <> sENTER_BOOK_AUTHOR then begin book := findByAuthor(editBooksAuthor.Text); end else begin error := true; MessageBox(Handle, PChar(sENTER_BOOK_AUTHOR), PChar(sERROR), MB_OK or MB_ICONWARNING); end; end; end; if not error then begin // Очистка listView lvCurrentList.Clear; lvCurrentList.Columns.Clear; setColumnsBooks; // Вывод элементов for i := 0 to length(book) - 1 do begin if book[i].code <> -1 then begin listItem := lvCurrentList.Items.Add; listItem.Caption := IntToStr(book[i].code); listItem.SubItems.Add(book[i].bookTitle); listItem.SubItems.Add(book[i].authorSurname); listItem.SubItems.Add(IntToStr(book[i].publishYear)); listItem.SubItems.Add(langToStr(book[i].publishLang)); end; end; end; end; // Выводит список посетителей procedure TfrmMain.showVisitorsList; var visitor: TVisitors; borrow: TBorrows; i, j: Integer; listItem: TListItem; error: Boolean; today: TDateTime; begin error := false; SetLength(visitor, 0); SetLength(borrow, 0); case currentListAttribute of // Вывод всех посетителей cFULL: begin labelCurrentList.Caption := sALL_VISITORS; visitor := returnAllVisitors; end; // Вывод должников cOPEN: begin labelCurrentList.Caption := sDEBTS; today := date; visitor := returnAllVisitors; borrow := returnOpenBorrows; for i := 0 to length(visitor) - 1 do begin error := false; for j := 0 to length(borrow) - 1 do if borrow[j].visitorID = visitor[i].ID then if borrow[j].expReturnDate + 10 < today then error := true; if not error then visitor[i].ID := -1; end; error := false; end; cCLOSE: // Вывод недоверенных begin labelCurrentList.Caption := sBAD_VISITORS; today := date; visitor := returnAllVisitors; borrow := returnAllBorrows; for i := 0 to length(visitor) - 1 do begin error := false; for j := 0 to length(borrow) - 1 do begin if borrow[j].visitorID = visitor[i].ID then begin if borrow[j].realReturnDate = -1 then begin if borrow[j].expReturnDate + 10 < today then error := true; end else begin if borrow[j].expReturnDate + 10 < borrow[j].realReturnDate then error := true; end; end; end; if not error then visitor[i].ID := -1; end; error := false; end; // Поиск по фамилии cNAME: begin labelCurrentList.Caption := sNAME_VISITOR_SEARCH; if editVisitorsName.Text <> sENTER_VISITOR_NAME then begin visitor := findByName(toName('', '', editVisitorsName.Text)); end else begin error := true; MessageBox(Handle, PChar(sENTER_VISITOR_NAME), PChar(sERROR), MB_OK or MB_ICONWARNING); end; end; end; if not error then begin // Очистка listView lvCurrentList.Clear; lvCurrentList.Columns.Clear; setColumnsVisitors; // Вывод элементов for i := 0 to length(visitor) - 1 do begin if visitor[i].ID <> -1 then begin listItem := lvCurrentList.Items.Add; listItem.Caption := IntToStr(visitor[i].ID); listItem.SubItems.Add(nameToStr(visitor[i].name)); listItem.SubItems.Add(addressToStr(visitor[i].address)); listItem.SubItems.Add(visitor[i].phoneNumber); end; end; end; end; // Выводит список записей о взятии книг procedure TfrmMain.showBorrowsList; var borrow: TBorrows; i: Integer; listItem: TListItem; begin SetLength(borrow, 0); case currentListAttribute of cFULL: begin labelCurrentList.Caption := sALL_BORROWS; borrow := returnAllBorrows; end; cOPEN: begin labelCurrentList.Caption := sOPEN_BORROWS; borrow := returnOpenBorrows; end; cCLOSE: begin labelCurrentList.Caption := sCLOSED_BORROWS; borrow := returnClosedBorrows; end; end; // Очистка listView lvCurrentList.Clear; lvCurrentList.Columns.Clear; setColumnsBorrows; // Вывод элементов for i := 0 to length(borrow) - 1 do begin listItem := lvCurrentList.Items.Add; listItem.Caption := IntToStr(borrow[i].code); listItem.SubItems.Add(findByCode(borrow[i].bookCode).bookTitle); listItem.SubItems.Add(nameToStr(findByID(borrow[i].visitorID).name)); listItem.SubItems.Add(DateToStr(borrow[i].borrowDate)); listItem.SubItems.Add(DateToStr(borrow[i].expReturnDate)); if borrow[i].realReturnDate = -1 then listItem.SubItems.Add('') else listItem.SubItems.Add(DateToStr(borrow[i].realReturnDate)); end; end; // Определяет, какой список необходимо вывести procedure TfrmMain.showList; begin case currentListType of cBOOKS: showBooksList; cVISITORS: showVisitorsList; cBORROWS: showBorrowsList; end; end; // При создании формы выводит полный список книг procedure TfrmMain.FormCreate(Sender: TObject); begin setCaptions; Caption := Application.Title; currentListType := cBOOKS; currentListAttribute := cFULL; showList; end; // Вывод полного списка книг procedure TfrmMain.aShowAllBooksExecute(Sender: TObject); begin currentListType := cBOOKS; currentListAttribute := cFULL; showList; end; // Вывод невзятых книг procedure TfrmMain.aShowNotBorrowedBooksExecute(Sender: TObject); begin currentListType := cBOOKS; currentListAttribute := cCLOSE; showList; end; // Вывод взятых книг procedure TfrmMain.aShowBorrowedBooksExecute(Sender: TObject); begin currentListType := cBOOKS; currentListAttribute := cOPEN; showList; end; // Вывод всех посетителей procedure TfrmMain.aShowAllVisitorsExecute(Sender: TObject); begin currentListType := cVISITORS; currentListAttribute := cFULL; showList; end; // Вывод списка должников procedure TfrmMain.aShowDebtsExecute(Sender: TObject); begin currentListType := cVISITORS; currentListAttribute := cOPEN; showList; end; // Вывод списка недоверенных procedure TfrmMain.aShowBadVisitorsExecute(Sender: TObject); begin currentListType := cVISITORS; currentListAttribute := cCLOSE; showList; end; // Вывод всех записей procedure TfrmMain.aShowAllBorrowsExecute(Sender: TObject); begin currentListType := cBORROWS; currentListAttribute := cFULL; showList; end; // Вывод открытых записей procedure TfrmMain.aShowOpenBorrowsExecute(Sender: TObject); begin currentListType := cBORROWS; currentListAttribute := cOPEN; showList; end; // Вывод закрытых записей procedure TfrmMain.aShowClosedBorrowsExecute(Sender: TObject); begin currentListType := cBORROWS; currentListAttribute := cCLOSE; showList; end; // Поиск книги по заголовку procedure TfrmMain.aFindBooksByTitleExecute(Sender: TObject); begin currentListType := cBOOKS; currentListAttribute := cTITLE; showList; end; // Поиск книги по автору procedure TfrmMain.aFindBooksByAuthorExecute(Sender: TObject); begin currentListType := cBOOKS; currentListAttribute := cNAME; showList; end; // Поиск посетителя по фамилии procedure TfrmMain.aFindVisitorsByNameExecute(Sender: TObject); begin currentListType := cVISITORS; currentListAttribute := cNAME; showList; end; // Добавление книги procedure TfrmMain.aAddBookExecute(Sender: TObject); begin dialogType := cADD; if (Assigned(frmAddBook)) then frmAddBook.Close; frmAddBook:=TfrmAddBook.Create(Self); end; // Изменение книги procedure TfrmMain.aChangeBookExecute(Sender: TObject); begin dialogType := cCHANGE; if (Assigned(frmAddBook)) then frmAddBook.Close; frmAddBook:=TfrmAddBook.Create(Self); end; // Удаление книги procedure TfrmMain.aDeleteBookExecute(Sender: TObject); begin dialogType := cDELETE; if (Assigned(frmAddBook)) then frmAddBook.Close; frmAddBook:=TfrmAddBook.Create(Self); end; // Добавление посетителя procedure TfrmMain.aAddVisitorExecute(Sender: TObject); begin dialogType := cADD; if (Assigned(frmAddVisitor)) then frmAddVisitor.Close; frmAddVisitor:=TfrmAddVisitor.Create(Self); end; // Изменение посетителя procedure TfrmMain.aChangeVisitorExecute(Sender: TObject); begin dialogType := cCHANGE; if (Assigned(frmAddVisitor)) then frmAddVisitor.Close; frmAddVisitor:=TfrmAddVisitor.Create(Self); end; // Удаление посетителя procedure TfrmMain.aDeleteVisitorExecute(Sender: TObject); begin dialogType := cDELETE; if (Assigned(frmAddVisitor)) then frmAddVisitor.Close; frmAddVisitor:=TfrmAddVisitor.Create(Self); end; // Добавление записи procedure TfrmMain.aAddBorrowExecute(Sender: TObject); begin dialogType := cADD; if (Assigned(frmAddBorrow)) then frmAddBorrow.Close; frmAddBorrow:=TfrmAddBorrow.Create(Self); end; // Изменение записи procedure TfrmMain.aChangeBorrowExecute(Sender: TObject); begin dialogType := cCHANGE; if (Assigned(frmAddBorrow)) then frmAddBorrow.Close; frmAddBorrow:=TfrmAddBorrow.Create(Self); end; // Закрытие записи procedure TfrmMain.aCloseBorrowExecute(Sender: TObject); begin dialogType := cDELETE; if (Assigned(frmAddBorrow)) then frmAddBorrow.Close; frmAddBorrow:=TfrmAddBorrow.Create(Self); end; end.
{******************************************************************************* * uTableSignCheck * * * * Проверка табеля перед подписью (все ли приказы переданы в зарплату) * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uTableSignCheck; interface uses RxMemDs, uTableGroup, uMovingTable, IBase, pFIBDatabase, Classes, uTableData, DB, SysUtils, DateUtils; type TTableSignCheck = class(TObject) private DM: TTableData; public constructor Create(DM: TTableData); function Check(TableGroup: TTableGroup): Boolean; end; implementation constructor TTableSignCheck.Create(DM: TTableData); begin inherited Create; Self.DM := DM; end; function TTableSignCheck.Check(TableGroup: TTableGroup): Boolean; var i, Year, Month: Integer; begin DM.OrdersCheck.EmptyTable; for i := 0 to TableGroup.Count - 1 do begin Year := TableGroup[i].Year; Month := TableGroup[i].Month; DM.MovingCheck.Close; DM.MovingCheck.ParamByName('Id_Man_Moving').AsInteger := TableGroup[i].Id_Man_Moving; DM.MovingCheck.ParamByName('Month_Beg').AsDate := EncodeDate(Year, Month, 1); DM.MovingCheck.ParamByName('Month_End').AsDate := EncodeDate(Year, Month, DaysInAMonth(Year, Month)); DM.MovingCheck.Open; DM.OrdersCheck.Open; DM.MovingCheck.First; while not DM.MovingCheck.Eof do begin if not DM.OrdersCheck.Locate('Id_Order', DM.MovingCheck['Id_Order'], []) then begin DM.OrdersCheck.Append; DM.OrdersCheck['Id_Order'] := DM.MovingCheck['Id_Order']; DM.OrdersCheck['Num_Order'] := DM.MovingCheck['Num_Order']; DM.OrdersCheck['Note'] := DM.MovingCheck['Note']; DM.OrdersCheck.Post; end; DM.MovingCheck.Next; end; end; Result := DM.OrdersCheck.IsEmpty; end; end.
unit untRequest; interface uses System.Classes; type TRequest = class public function PostSync(pJson: TStringStream; pUrl: string): string; end; implementation uses IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, System.SysUtils; { TRequest } function TRequest.PostSync(pJson: TStringStream; pUrl: string): string; var retorno: string; HTTP: TIdHTTP; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; begin try HTTP := TIdHTTP.Create(nil); try HTTP.Request.ContentType := 'application/json'; //Abre SSL IdSSLIOHandlerSocketOpenSSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil); HTTP.IOHandler := IdSSLIOHandlerSocketOpenSSL1; //Avisa o uso de UTF-8 HTTP.Request.ContentEncoding := 'UTF-8'; //Faz o envio por POST do json para a url retorno := HTTP.Post(pUrl, pJson); finally HTTP.Free(); end; except on E: EIdHTTPProtocolException do retorno := e.ErrorMessage; on E: Exception do retorno := E.message; end; //Devolve o json de retorno da API Result := retorno; end; end.
unit NewFrontiers.Validation.Vcl; interface uses NewFrontiers.Validation, Vcl.StdCtrls, Generics.Collections, Vcl.Controls, NewFrontiers.GUI.PropertyChanged; type /// <summary> /// Der ValidationManager kann verwendet werden, um mehrere Validator /// gleichzeitig zu testen und ein Gesamtergebnis zu erhalten. Für jedes /// Control können beliebig viele Validator registriert werden /// </summary> TValidationManager = class(TPropertyChangedObject) private procedure setIsValid(const Value: boolean); protected _validators: TObjectDictionary<TWinControl, TObjectlist<TValidator>>; _isValid: boolean; public property IsValid: boolean read _isValid write setIsValid; constructor Create; destructor Destroy; override; /// <summary> /// Fügt einen Validator für ein Control hinzu /// </summary> procedure add(aControl: TWinControl; aValidator: TValidator); /// <summary> /// Validiert alle registrierten Validator und gibt das /// Gesamtergebnis zurück. /// </summary> function validate: boolean; end; implementation uses Vcl.Graphics, Vcl.ExtCtrls, NewFrontiers.Validation.VclHelper, Vcl.Dialogs; { TValidationManager } procedure TValidationManager.add(aControl: TWinControl; aValidator: TValidator); begin if (not _validators.ContainsKey(aControl)) then _validators.Add(aControl, TObjectlist<TValidator>.Create(true)); _validators.Items[aControl].Add(aValidator); end; constructor TValidationManager.Create; begin _validators := TObjectDictionary<TWinControl, TObjectlist<TValidator>>.Create([doOwnsValues]); end; destructor TValidationManager.Destroy; begin _validators.Free; inherited; end; procedure TValidationManager.setIsValid(const Value: boolean); begin _isValid := Value; propertyChanged('IsValid'); end; function TValidationManager.validate: boolean; var control: TWinControl; validator: TValidator; controlIsValid: boolean; begin result := true; for control in _validators.Keys do begin controlIsValid := true; for validator in _validators.Items[control] do begin // Das hier kann man sicher noch überarbeiten // Aktuell verwenden wir hier einen Hack. Durch das casten nach TEdit // stehen dessen Class Helper zur Verfügung. TLabeldEdit verwendet // die gleiochen Felder, so dass man an dieser Stelle den Helper // mitbenutzen kann. // Ggf. hier keine Class Helper sondern das Adapter Pattern nutzen if ((control is TEdit) or (control is TLabeledEdit)) then begin controlIsValid := controlIsValid and validator.validate(TEdit(control).getValidationText); end; end; if (controlIsValid) then TEdit(control).valid else begin TEdit(control).invalid; result := false; end; end; // Noch was tun? Vielleicht ein Event? IsValid := result; end; end.
unit StrTbl; interface uses SysUtils, StrVec, StrIntDictCS; type TStrId = type Integer; TStrIdArray = array of TStrId; TStringTable = class(TObject) private FItems: IStrVector; FIndex: IStrIntDict; function GetItem(Id: TStrId): string; function GetCount: Integer; procedure AddDefaults; public constructor Create; function AddItem(S: string): TStrId; procedure Clear; function EmptyStrId: TStrId; function PrototypeStrId: TStrId; function ThisStrId: TStrId; function SuperStrId: TStrId; function ArgumentsStrId: TStrId; function GlobalStrId: TStrId; function ObjectStrId: TStrId; property Items[Id: TStrId]: string read GetItem; default; property Count: Integer read GetCount; end; const UndefinedStrId = -1; NullStrId = -2; FalseStrId = -3; TrueStrId = -4; implementation { TStringTable } constructor TStringTable.Create; begin inherited Create; FItems := TStrVector.Create; FIndex := TStrIntHash.Create(113); AddDefaults; end; procedure TStringTable.AddDefaults; begin AddItem(''); AddItem('this'); AddItem('prototype'); AddItem('super'); AddItem('arguments'); AddItem('_global'); AddItem('Object'); end; function TStringTable.GetCount: Integer; begin Result := FItems.Count; end; function TStringTable.GetItem(Id: TStrId): string; begin Result := FItems[Id]; end; function TStringTable.AddItem(S: string): TStrId; var Pair: StrIntDictCS.PPair; begin Pair := FIndex.Find(S); if Pair <> nil then Result := Pair^.Value else begin Result := FItems.Count; FIndex[S] := Result; FItems.Add(S); end; end; procedure TStringTable.Clear; begin FItems.Clear; FIndex.Clear; AddDefaults; end; function TStringTable.EmptyStrId: TStrId; begin Result := AddItem(''); end; function TStringTable.PrototypeStrId: TStrId; begin Result := AddItem('prototype'); end; function TStringTable.ThisStrId: TStrId; begin Result := AddItem('this'); end; function TStringTable.SuperStrId: TStrId; begin Result := AddItem('super'); end; function TStringTable.ArgumentsStrId: TStrId; begin Result := AddItem('arguments'); end; function TStringTable.GlobalStrId: TStrId; begin Result := AddItem('_global'); end; function TStringTable.ObjectStrId: TStrId; begin Result := AddItem('Object'); end; end.
unit fos_locking; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl FirmOS Business Solutions GmbH New Style BSD Licence (OSI) Copyright (c) 2001-2009, FirmOS Business Solutions GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$mode objfpc} {$codepage utf8} {$H+} {$modeswitch nestedprocvars} interface uses Sysutils,SyncObjs, FOS_TOOL_INTERFACES; type TFOS_E=class; { TFOS_LOCK } TFOS_LOCK=class(TObject,IFOS_LOCK) private CS:SyncObjs.TCriticalSection; public constructor Create; destructor Destroy;override; procedure Acquire;virtual; function Release:QWord;virtual; procedure Finalize; end; { TFOS_TIMED_LOCK } TFOS_TIMED_LOCK=class(TFOS_LOCK) private FStartTime : QWord; public procedure Acquire;override; function Release:QWord;override; end; TFOS_RW_LOCK=class(TInterfacedObject,IFOS_RW_LOCK) // If you lock multiple -> you are Dead locked private rc,wc:integer; x,y,z,wsem,rsem:TFOS_E; // Stallings (Reader/Writer Problem) public constructor Create; destructor Destroy;override; procedure AcquireRead; procedure ReleaseRead; procedure AcquireWrite; procedure ReleaseWrite; end; { TFOS_TE } TFOS_TE=class(TInterfacedObject,IFOS_TE) private FSig:PRTLEvent; public constructor Create; destructor Destroy; override; procedure WaitFor(timeout:integer); function SetEvent:boolean; procedure Finalize; end; TFOS_DATA_TE=class(TFOS_TE,IFOS_DATA_TE) private FData:String; FData2:String; FData3:String; FData4:String; public procedure SetData(const data:string); procedure SetData2(const data:string); procedure SetData3(const data:string); procedure SetData4(const data:string); function GetData:string; function GetData2:string; function GetData3:string; function GetData4:string; end; { TFOS_E } TFOS_E=class(TInterfacedObject,IFOS_E) private FSig : PRTLEvent; FData : Pointer; public constructor Create; destructor Destroy;override; procedure WaitFor; procedure SetEvent; procedure SetEventWithData (const data:Pointer); function GetData : Pointer; procedure Finalize; end; implementation { TFOS_TIMED_LOCK } procedure TFOS_TIMED_LOCK.Acquire; begin FStartTime := GFRE_BT.Get_Ticks_us; inherited Acquire; end; function TFOS_TIMED_LOCK.Release: QWord; begin inherited; Result := GFRE_BT.Get_Ticks_us-FStartTime; end; { TFOS_TE } constructor TFOS_TE.Create; begin inherited; FSig:=RTLEventCreate; end; destructor TFOS_TE.Destroy; begin RTLeventdestroy(FSig); inherited; end; function TFOS_TE.SetEvent: boolean; begin result:=true; RTLeventSetEvent(FSig); end; procedure TFOS_TE.Finalize; begin Free; end; procedure TFOS_TE.WaitFor(timeout: integer); begin if timeout=0 then begin RTLeventWaitFor(FSig); end else begin RTLeventWaitFor(FSig,timeout); end; end; { TFOS_E } constructor TFOS_E.Create; begin FSig := RTLEventCreate; end; destructor TFOS_E.Destroy; begin RTLeventdestroy(FSig); inherited Destroy; end; procedure TFOS_E.SetEvent; begin RTLeventSetEvent(FSig); end; procedure TFOS_E.SetEventWithData(const data: Pointer); begin FData := data; SetEvent; end; function TFOS_E.GetData: Pointer; begin result := FData; end; procedure TFOS_E.Finalize; begin free; end; procedure TFOS_E.WaitFor; begin RTLeventWaitFor(FSig); end; { TFOS_RW_LOCK } procedure TFOS_RW_LOCK.AcquireRead; begin z.WaitFor; rsem.WaitFor; x.WaitFor; inc(RC); if rc=1 then begin wsem.WaitFor; end; x.SetEvent; rsem.SetEvent; z.SetEvent; end; procedure TFOS_RW_LOCK.AcquireWrite; begin y.WaitFor; inc(wc); if wc=1 then begin rsem.WaitFor; end; y.SetEvent; wsem.WaitFor; end; constructor TFOS_RW_LOCK.Create; begin x:=TFOS_E.Create; y:=TFOS_E.Create; z:=TFOS_E.Create; RSEM:=TFOS_E.Create; WSEM:=TFOS_E.Create; WC:=0; RC:=0; end; destructor TFOS_RW_LOCK.Destroy; begin x.Free; y.Free; z.free; rsem.Free; wsem.free; inherited; end; procedure TFOS_RW_LOCK.ReleaseRead; begin x.WaitFor; dec(rc); if rc=0 then begin wsem.SetEvent; end; x.SetEvent; end; procedure TFOS_RW_LOCK.ReleaseWrite; begin wsem.SetEvent; y.WaitFor; dec(wc); if wc=0 then begin rsem.SetEvent; end; y.SetEvent; end; { TFOS_LOCK } procedure TFOS_LOCK.Acquire; begin CS.Acquire; end; constructor TFOS_LOCK.Create; begin CS:=SyncObjs.TCriticalSection.Create; end; destructor TFOS_LOCK.Destroy; begin CS.Free; inherited; end; function TFOS_LOCK.Release:QWord; begin if assigned(CS) then begin try CS.Release; except CS:=nil; end; end else begin CS:=nil; end; end; procedure TFOS_LOCK.Finalize; begin Free; end; { TFOS_DATA_TE } function TFOS_DATA_TE.GetData: string; begin result:=FData; end; function TFOS_DATA_TE.GetData2: string; begin result:=FData2; end; function TFOS_DATA_TE.GetData3: string; begin result:=FData3; end; function TFOS_DATA_TE.GetData4: string; begin result:=FData4; end; procedure TFOS_DATA_TE.SetData(const data: string); begin FData:=Data; end; procedure TFOS_DATA_TE.SetData2(const data: string); begin FData2:=Data; end; procedure TFOS_DATA_TE.SetData3(const data: string); begin FData3:=Data; end; procedure TFOS_DATA_TE.SetData4(const data: string); begin FData4:=Data; end; end.
unit Core.Articles.Gen; interface uses System.SysUtils, System.Classes, Data.API.Google; type IArticle = interface ['{C81436AF-BC56-45BC-910F-ECCDE35B32E6}'] function GetCaption: String; function GetText: String; function GetCategories(const AIndex: Integer): String; function GetCategoryCount: Integer; property Caption: String read GetCaption; property Text: String read GetCaption; property Categories[const AIndex: Integer]: String read GetCategories; property CategoryCount: Integer read GetCategoryCount; end; TArticle = class(TInterfacedObject, IArticle) private FCaption: String; FText: String; FCategories: TStrings; function GetCaption: String; function GetText: String; function GetCategories(const AIndex: Integer): String; function GetCategoryCount: Integer; protected procedure LoadFromGoogleArticle(const AGoogleArticle: IGoogleArticle); public constructor Create(const AGoogleArticle: IGoogleArticle); destructor Destroy; override; end; implementation { TArticle } constructor TArticle.Create(const AGoogleArticle: IGoogleArticle); begin inherited Create; FCategories := TStringList.Create; LoadFromGoogleArticle(AGoogleArticle); end; destructor TArticle.Destroy; begin FCategories.Free; inherited; end; function TArticle.GetCaption: String; begin Result := FCaption; end; function TArticle.GetCategories(const AIndex: Integer): String; begin Result := FCategories[AIndex]; end; function TArticle.GetCategoryCount: Integer; begin Result := FCategories.Count; end; function TArticle.GetText: String; begin Result := FText; end; procedure TArticle.LoadFromGoogleArticle(const AGoogleArticle: IGoogleArticle); var Article: IGoogleArticle absolute AGoogleArticle; Index: Integer; function FindTokens(const ADependency: IToken; const ALabel: TLabel) : TArray<IToken>; var TokenIndex: Integer; begin for TokenIndex := 0 to Pred(Article.Sentences[Index].TokenCount) do begin if (Article.Sentences[Index].Tokens[TokenIndex].Dependency = ADependency) and (Article.Sentences[Index].Tokens[TokenIndex].&Label = ALabel) then begin Result := Concat(Result, [Article.Sentences[Index].Tokens[TokenIndex]]); end; end; end; function Build(const ATokens: TArray<IToken>): String; var Current: IToken; begin for Current in ATokens do begin case Current.&Label of laNSUBJ, laDOBJ, laPOBJ, laATTR: // Articles + Adverbs Result := Concat(Build(FindTokens(Current, laDET)), Build(FindTokens(Current, laAMOD)), Current.Text); laROOT: // Subjects + Adverbs + D.Objects + Attribs + Punctations Result := Concat(Build(FindTokens(Current, laNSUBJ)), Build(FindTokens(Current, laADVMOD)), Current.Text, Build(FindTokens(Current, laDOBJ)), Build(FindTokens(Current, laATTR)), Build(FindTokens(Current, laP))); laPREP: // P.Objects Result := Concat(Current.Text, Build(FindTokens(Current, laPOBJ))); laP, laDET, laADVMOD: Result := Current.Text; laAMOD: // Adverbs Result := Concat(Build(FindTokens(Current, laADVMOD)), Current.Text); end; end; if not Result.IsEmpty then begin Result := Concat(Result, ' '); end; end; var Category: TArray<String>; begin FCaption := Article.Caption; for Index := 0 to Pred(Article.CategoryCount) do begin Category := Article.Categories[Index].Split(['/'], '"'); FCategories.Add(Category[Low(Category)]); end; for Index := 0 to Pred(Article.SentenceCount) do begin FText := Concat(FText, Build(FindTokens(nil, laROOT))); end; FText[Low(FText)] := UpCase(FText[Low(FText)]); end; end.
unit uFrmImput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SuperEdit, SuperEditCurrency; type TFrmImput = class(TForm) Selecionar: TButton; edtInput: TEdit; lbInput: TLabel; btnAbort: TButton; edtCurrency: TSuperEditCurrency; btnVoltar: TButton; procedure SelecionarClick(Sender: TObject); procedure btnAbortClick(Sender: TObject); procedure edtCurrencyPressEnter(Sender: TObject); procedure btnVoltarClick(Sender: TObject); private FResult : String; FValue : Double; FMin: Integer; FStartType : Integer; FValidarSenha : Boolean; FComando: Integer; FTipoCampo: Integer; function SenhaValida : Boolean; function ValidateInput: Boolean; public function Start(Texto : String; AMin, Max : Integer; ValidarSenha : Boolean; const Comando, TipoCampo: Integer):String; function StartDouble(Texto : String; AMin, Max : Integer):Double; end; implementation uses uMsgBox, uDM, DBClient, DB, uSystemConst; {$R *.dfm} function TFrmImput.Start(Texto: String; AMin, Max: Integer; ValidarSenha : Boolean; const Comando, TipoCampo: Integer): String; begin lbInput.Caption := Texto; edtInput.MaxLength := Max; FMin := AMin; edtInput.Clear; FStartType := 0; edtCurrency.Visible := False; edtInput.Visible := True; FValidarSenha := ValidarSenha; FComando := Comando; FTipoCampo := TipoCampo; if FValidarSenha then edtInput.PasswordChar := '*' else edtInput.PasswordChar := #0; ShowModal; Result := FResult; end; function TFrmImput.StartDouble(Texto: String; AMin, Max: Integer): Double; begin lbInput.Caption := Texto; edtCurrency.MaxLength := Max; FMin := AMin; edtInput.Clear; FStartType := 1; edtCurrency.Visible := True; edtInput.Visible := False; ShowModal; Result := FValue; end; function TFrmImput.ValidateInput: Boolean; begin Result := False; if (FComando = 30) and (FTipoCampo = 513) then if Trim(edtInput.Text) = '' then Exit; Result := True; end; procedure TFrmImput.SelecionarClick(Sender: TObject); begin if not ValidateInput then Exit; if FStartType = 0 then begin {if Length(Trim(edtInput.Text)) < FMin then begin MessageBeep($FFFFFFFF); Exit; end;} if FValidarSenha and (not SenhaValida) then begin edtInput.Clear; Exit; end; FResult := edtInput.Text; end else begin try StrToCurr(edtCurrency.Text); Except MsgBox('Formatação inválida', vbCritical + vbOKOnly); Exit; end; FValue := StrToCurr(edtCurrency.Text); end; Close; end; procedure TFrmImput.btnAbortClick(Sender: TObject); begin if FStartType = 0 then FResult := '-1' else FValue := -1; Close; end; procedure TFrmImput.edtCurrencyPressEnter(Sender: TObject); begin SelecionarClick(self); end; function TFrmImput.SenhaValida: Boolean; begin Result := False; with DM.cdsSystemUser do begin if not Active then Open; if Locate('PW', edtInput.Text, []) then begin Result := (FieldByName('UserTypeID').AsInteger in [USER_TYPE_ADMINISTRATOR, USER_TYPE_MANAGER]); if not Result then MsgBox('Você não tem acesso para esta operaçao', vbInformation + vbOKOnly); end else MsgBox('Senha inválida', vbInformation + vbOKOnly); end; end; procedure TFrmImput.btnVoltarClick(Sender: TObject); begin if FStartType = 0 then FResult := '-2' else FValue := -2; Close; end; end.
{*******************************************************} { } { Borland Delphi Test Server } { } { Copyright (c) 2001 Borland Software Corporation } { } { Русификация: 2001 Polaris Software } { http://polesoft.da.ru } {*******************************************************} unit SvrConst; interface resourcestring sWebAppDebugger = 'Отладчик Web-приложений'; sStopServer = 'Стоп'; sStartServer = 'Старт'; sCouldNotOpenRegKey = 'Не могу открыть ключ реестра: %s'; sUnauthorizedString = '<HTML><HEAD><TITLE>Несанкционировано</TITLE></HEAD>' + '<BODY><H1>Несанкционировано</H1>' + 'Правильная авторизация требуется для этой области. ' + 'Либо Ваш браузер не поддерживает авторизацию, ' + 'либо Ваша авторизация - неверная.' + '</BODY></HTML>'#13#10; sForbiddenString = '<HTML><TITLE>Требуемый URL запрещен</TITLE>' + '<BODY>' + '<H1>Требуемый URL запрещен</H1>' + '<P>Код статуса HTTP: 403' + '</BODY></HTML>'#13#10; sNoDirBrowseString = '<HTML><TITLE>Просмотр каталогов запрещен</TITLE>' + '<BODY>' + '<H1>Требуемый URL запрещен</H1>' + '<P>Код статуса HTTP: 403' + '</BODY></HTML>'#13#10; sBadRequest = '<HTML><TITLE>Неверный HTTP запрос: Метод не допускается для HTTP/1.0</TITLE>' + '<BODY>' + '<H1>Неверный HTTP запрос: Метод не допускается для HTTP/1.0</H1>' + '<P>Код статуса HTTP: 400' + '</BODY></HTML>'#13#10; sNotFound = '<TITLE>Требуемый URL не найден</TITLE>' + '<BODY>' + '<H1>Требуемый URL не найден</H1>' + '<P>Код статуса HTTP: 404' + '</BODY>'; sInternalServerError = '<TITLE>Внутренняя ошибка сервера</TITLE>' + '<BODY>' + '<H1>Внутренняя ошибка сервера</H1>' + '<P>Код статуса HTTP: 500' + '<P>Сообщение об ошибке HTTP: %s' + '</BODY>'; SInvalidActionRegistration = 'Неверная регистрация действия (action)'; sErrorEvent = 'ERROR'; sResponseEvent = 'RESPONSE'; sEvent = 'Event'; sTime = 'Time'; sDate = 'Date'; sElapsed = 'Elapsed'; sPath = 'Path'; sCode = 'Code'; sContentLength = 'Content Length'; sContentType = 'Content Type'; sThread = 'Thread'; sNoDefaultURL = '(нет)'; sLogTab = 'Log(%d)'; sSend = 'Send'; sReceive = 'Receive'; sLogStrTemplate = '%s %s Ошибка: (%d)%s'; UnauthorizedString = '<HTML><HEAD><TITLE>Несанкционировано</TITLE></HEAD>' + '<BODY><H1>Несанкционировано</H1>' + 'Правильная авторизация требуется для этой области. ' + 'Либо Ваш браузер не поддерживает авторизацию, ' + 'либо Ваша авторизация - неверная.' + '</BODY></HTML>'#13#10; ForbiddenString = '<HTML><TITLE>Требуемый URL запрещен</TITLE>' + '<BODY>' + '<H1>Требуемый URL запрещен</H1>' + '<P>Код статуса HTTP: 403' + '</BODY></HTML>'#13#10; NoDirBrowseString = '<HTML><TITLE>Просмотр каталогов запрещен</TITLE>' + '<BODY>' + '<H1>Требуемый URL запрещен</H1>' + '<P>Код статуса HTTP: 403' + '</BODY></HTML>'#13#10; BadRequest = '<HTML><TITLE>Неверный HTTP запрос: Метод не допускается для HTTP/1.0</TITLE>' + '<BODY>' + '<H1>Неверный HTTP запрос: Метод не допускается для HTTP/1.0</H1>' + '<P>Код статуса HTTP: 400' + '</BODY></HTML>'#13#10; NotFound = '<TITLE>Требуемый URL не найден</TITLE>' + '<BODY>' + '<H1>Требуемый URL не найден</H1>' + '<P>Код статуса HTTP: 404' + '</BODY>'; DateFormat = 'ddd, dd mmm yyyy hh:mm:ss'; sBuild = 'Build'; sDirHeader = '<HTML><HEAD><TITLE>Каталог %s</TITLE></HEAD>' + '<BODY><H1>Каталог %0:s</H1>'#13#10; sDirParent = 'Up to <A HREF="%s">%0:s</A>'#13#10'<UL>'; sDirRoot = 'Вверх в <A HREF="%s">корневой каталог</A>'#13#10'<UL>'; sDirEntry = '<LI>[ <A HREF="%s">%s</A> ]'#13#10; sFileEntry = '<LI><A HREF="%s">%s</A> (%d байт)'#13#10; sListStart = '<UL>'#13#10; sDirFooter = '</UL></BODY></HTML>'#13#10; implementation end.
unit CCriptografiaCutre; interface (******* CLASE: TCriptografiaCutre Encargada de, dada una cadena, hacer un conjunto de operaciones a nivel de byte y devolver una cadena de código, que necesita un contracódigo para terminar la autenticación. Si cabe, el contracódigo es más chorra aún. *******) type TCutreCriptoEngine = class( TObject ) public function getCodeA( const strWorking: String ): String; function getCodeB( const codeA: String ): String; function isCodeBValid( const codeA, codeB: String ): boolean; end; (******* VARIABLES GLOBALES DEL MÓDULO. *******) var theCutreCriptoEngine: TCutreCriptoEngine; implementation (****** CONSTANTES PRIVADAS ******) const kBaseTrabajoCriptoEngine = 11; kTablaConversion: array [0..(kBaseTrabajoCriptoEngine-1)] of char = ( 'Z', 'Y', 'A', '4', 'M', '0', 'Q', 'S', 'P', '7', 'L' ); // ** cuando la base es 19 = ( 'Z', 'Y', 'A', '4', 'M', '0', 'Q', 'S', 'P', '7', 'L', 'W', 'X', '3', 'K', 'T', '1', 'E', 'B' ); kNumOfRepeatsOfWorkStr = 100; kLenOfCodeA = 6; kStrXORCodeA: String[ kLenOfCodeA ] = '%$#@&?'; // al hacer un XOR con esta cadena, se supone que obtendremos el códigoB (****** IMPLEMENTACIÓN: Clase TCutreCriptoEngine ******) // se encarga de, a partir una cadena y sumando los valores de los caracteres, obtener una ristra (código A) de varios caracteres. Luego, esta ristra se normaliza a base 19, que se representa según una tabla de conversión particular // Hay que hacer notar que, previamente, a los bytes de la cadena se les resta un valor para normalizar (anterior al espacio en blanco), pero que si su valor es menor que 32 automáticamente se colocan a 0 (no influyen en el valor final) function TCutreCriptoEngine.getCodeA( const strWorking: String ): String; const klBaseNormalizaCadena = 16; var cadenaBytes: array [0..100] of byte; currentChar: integer; numRep: integer; // para controlar el número de veces que se repite la cadena de trabajo ( de esta forma se incrementa el código A) strWorkAux: String; // normaliza los caracteres de la cadena de trabajo. Para ello les resta el valor indicado como constante. function normalizaCaracterBase( theChar: char ): byte; var tmpResult: integer; begin tmpResult := ord(theChar) - klBaseNormalizaCadena; if tmpResult < 0 then result := 0 else result := tmpResult; end; // borra los bytes de la suma procedure resetBytes; var i: integer; begin for i:=0 to 100 do cadenaBytes[i] := 0; end; // suma un byte a la cadena de bytes en la base especificada procedure addByte( sumando: byte ) ; var acarreo: byte; byteTrabajo: integer; begin cadenaBytes[0] := cadenaBytes[0] + sumando ; byteTrabajo := 0; while cadenaBytes[ byteTrabajo ] >= kBaseTrabajoCriptoEngine do begin acarreo := cadenaBytes[ byteTrabajo ] div kBaseTrabajoCriptoEngine ; cadenaBytes[ byteTrabajo ] := cadenaBytes[ byteTrabajo ] mod kBaseTrabajoCriptoEngine ; inc( byteTrabajo ); cadenaBytes[ byteTrabajo ] := cadenaBytes[ byteTrabajo ] + acarreo ; end; end; // convierte la cadena de bytes en una cadena de caracteres según la tabla de conversión indicada function bytesToString: String; var curByte: integer; begin result := ''; for curByte:= 0 to kLenOfCodeA - 1 do result := kTablaConversion[ cadenaBytes[ curByte ] ] + result ; end; // getCodeA begin resetBytes; // se repite la cadena de trabajo el nº de veces que se indica strWorkAux := ''; for numRep:= 1 to kNumOfRepeatsOfWorkStr do strWorkAux := strWorkAux + strWorking ; // se procesa la cadena de trabajo (auxiliar) for currentChar := 1 to length( strWorkAux ) do addByte( normalizaCaracterBase( strWorkAux[ currentChar ] ) ) ; // se devuelve la cadena normalizada a nuestra tabla de códigos particular result := bytesToString; end; // TCutreCriptoEngine.getCodeA() // esta es una función auxiliar para obtener un código B a partir de uno A function TCutreCriptoEngine.getCodeB( const codeA: String ): string; const klNormalizaCadenaBInf = 40; klNormalizaCadenaBSup = 127; var curChar: integer; ordCharB: integer; begin result := ' '; setLength( result, kLenOfCodeA ); for curChar := 1 to kLenOfCodeA do begin ordCharB := ord( codeA[ curChar ] ) xor ( ord( kStrXORCodeA[ curChar ] ) * ord( codeA[ ( curChar + 2 ) mod kLenOfCodeA ] ) ); if ordCharB >= klNormalizaCadenaBSup then ordCharB := ordCharB mod klNormalizaCadenaBSup; if ordCharB < klNormalizaCadenaBInf then ordCharB := ordCharB + klNormalizaCadenaBInf ; result[ curChar ] := UpCase( Chr( ordCharB ) ); end; end; // TCutreCriptoEngine.getCodeB() // comprueba que el código B es la contrapartida del código A function TCutreCriptoEngine.isCodeBValid( const codeA, codeB: String ): boolean ; begin result := (getCodeB( codeA ) = codeB) ; end; // TCutreCriptoEngine.isCodeBValid() initialization // se crea la instancia del criptografiador theCutreCriptoEngine := TCutreCriptoEngine.Create ; finalization // se debe destruir la instancia del criptografiador theCutreCriptoEngine.Free ; end.
// // Generated by JavaToPas v1.5 20171018 - 171148 //////////////////////////////////////////////////////////////////////////////// unit java.io.WriteAbortedException; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JWriteAbortedException = interface; JWriteAbortedExceptionClass = interface(JObjectClass) ['{C6D25309-19BA-492B-B217-CBC320231479}'] function _Getdetail : JException; cdecl; // A: $1 function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1 function init(s : JString; ex : JException) : JWriteAbortedException; cdecl;// (Ljava/lang/String;Ljava/lang/Exception;)V A: $1 procedure _Setdetail(Value : JException) ; cdecl; // A: $1 property detail : JException read _Getdetail write _Setdetail; // Ljava/lang/Exception; A: $1 end; [JavaSignature('java/io/WriteAbortedException')] JWriteAbortedException = interface(JObject) ['{2306D29B-A3D6-45F0-BB51-9BDFA6E7173F}'] function _Getdetail : JException; cdecl; // A: $1 function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure _Setdetail(Value : JException) ; cdecl; // A: $1 property detail : JException read _Getdetail write _Setdetail; // Ljava/lang/Exception; A: $1 end; TJWriteAbortedException = class(TJavaGenericImport<JWriteAbortedExceptionClass, JWriteAbortedException>) end; implementation end.
unit SlistView1; interface uses classes,ovcViewR,ovcBordr, util1; { TStringListViewer se comporte comme un mémo en mode ReadOnly. Son intérêt est d'affecter des couleurs pour chaque ligne de texte. } type TStringListViewer= class(TovcBaseViewer) private list:TstringList; Colors:Tlist; function GetLinePtr(LineNum : LongInt; var Len : integer) : PAnsiChar;override; function getLineColor(line:integer):integer; public property Borders; property BorderStyle; property Caret; property ExpandTabs; property FixedFont; property HighlightColors; property MarginColor; property ScrollBars; property ShowBookmarks; property ShowCaret; property TabSize; {events} property OnShowStatus; property OnTopLineChanged; property OnUserCommand; constructor create(owner:Tcomponent); destructor destroy;override; procedure AddLine(st:string;col:integer); procedure Clear; end; implementation { TStringListViewer } procedure TStringListViewer.AddLine(st: string; col: integer); begin list.add(st); colors.Add(pointer(col)); lineCount:=List.count; end; constructor TStringListViewer.create(owner: Tcomponent); begin list:=TstringList.Create; Colors:=Tlist.create; getUserColor:=getLineColor; inherited; end; destructor TStringListViewer.destroy; begin inherited; list.free; colors.free; end; function TStringListViewer.GetLinePtr(LineNum: Integer; var Len: integer): PAnsiChar; const st:string=''; begin if (lineNum>=0) and (lineNum<list.count) then st:=list[lineNum] else st:=''; len:=length(st); if len=0 then st:=#0; result:=@st[1]; end; function TStringListViewer.getLineColor(line: integer): integer; begin if (line>=0) and (line<list.count) then result:=integer(colors[line]) else result:=0; end; procedure TStringListViewer.Clear; begin list.clear; colors.clear; lineCount:=0; end; end.
EXTERN {=================================================================} FUNCTION arctan (x : real) : real; CONST half_pi = 1.5707963267948; sixth_pi = 0.52359877559828; twelfth_pi = 0.26179938779914; sqrt3 = 1.7320508075689; VAR flag2, flag3, i : integer; result : real; sign : char; {=================================================================} PROCEDURE compute; VAR flip, power, x2, odd1, result2 : real; i, j : integer; BEGIN (* compute *) flip := 1.0; power := x; x2 := sqr(power); odd1 := 1.0; j := 0; i := 0; result := 0.0; REPEAT result2 := result; result := result + flip * (power / odd1); odd1 := odd1 + 2.0; flip := - flip; power := power * x2; j := j + 1; i := i + 1; IF i > 5 THEN BEGIN i := 0; IF abs(result - result2) < (1e-12 * result) THEN result2 := result; END; UNTIL result = result2; END; (* compute *) BEGIN (* arctan *) IF x = 0.0 THEN arctan := 0.0 ELSE BEGIN IF x < 0.0 THEN BEGIN x := - x; sign := '-' END ELSE sign := '+'; IF x > 1.0 THEN BEGIN x := 1.0 / x; flag2 := 1; END ELSE flag2 := 0; IF x > twelfth_pi THEN BEGIN x := (sqrt3 * x - 1.0) / (x + sqrt3); flag3 := 1; END ELSE flag3 := 0; IF (abs(x) <= 1.0e-08) THEN result := x ELSE compute; IF flag3 = 1 THEN result := result + sixth_pi; IF flag2 = 1 THEN result := half_pi - result; IF sign = '-' THEN arctan := - result ELSE arctan := result; END; (* else *) END; (* arctan *) . 
unit FHIRValueSetChecker; interface uses SysUtils, Classes, AdvObjects, AdvStringObjectMatches, FHIRTypes, FHIRComponents, FHIRResources, FHIRUtilities, TerminologyServices, TerminologyServerStore; Type TValueSetChecker = class (TAdvObject) private FStore : TTerminologyServerStore; FOthers : TAdvStringObjectMatch; // checkers or code system providers fvs : TFHIRValueSet; FId: String; function check(system, code : String; displays : TStringList) : boolean; overload; function findCode(code: String; list : TFhirValueSetDefineConceptList; displays : TStringList): boolean; function checkConceptSet(cs: TCodeSystemProvider; cset : TFhirValueSetComposeInclude; code : String; displays : TStringList) : boolean; function rule(op : TFhirOperationOutcome; severity : TFhirIssueSeverity; test : boolean; code, msg : string):boolean; procedure check(coding: TFhirCoding; op : TFhirOperationOutcome); overload; public constructor create(store : TTerminologyServerStore; id : String); overload; destructor destroy; override; property id : String read FId; procedure prepare(vs : TFHIRValueSet); function check(system, code : String) : boolean; overload; function check(coding : TFhirCoding) : TFhirOperationOutcome; overload; function check(coded : TFhirCodeableConcept) : TFhirOperationOutcome; overload; end; implementation { TValueSetChecker } constructor TValueSetChecker.create(store : TTerminologyServerStore; id : string); begin Create; FStore := store; FId := id; FOthers := TAdvStringObjectMatch.create; FOthers.PreventDuplicates; end; destructor TValueSetChecker.destroy; begin FVs.Free; FOthers.Free; FStore.Free; inherited; end; procedure TValueSetChecker.prepare(vs: TFHIRValueSet); var i, j : integer; checker : TValueSetChecker; cs : TCodeSystemProvider; other : TFHIRValueSet; begin FVs := vs.link; if fvs.define <> nil then FOthers.Add(fvs.define.systemST, TValueSetProvider.create(FVs.Link)); if (fvs.compose <> nil) then begin for i := 0 to fvs.compose.importList.Count - 1 do begin other := FStore.getValueSetByIdentifier(fvs.compose.importList[i].value); try if other = nil then raise exception.create('Unable to find value set '+fvs.compose.importList[i].value); checker := TValueSetChecker.create; try checker.prepare(other); FOthers.Add(fvs.compose.importList[i].value, checker.Link); finally checker.free; end; finally other.free; end; end; for i := 0 to fvs.compose.includeList.Count - 1 do begin if not FOthers.ExistsByKey(fvs.compose.includeList[i].systemST) then FOthers.Add(fvs.compose.includeList[i].systemST, FStore.getProvider(fvs.compose.includeList[i].systemST)); cs := TCodeSystemProvider(FOthers.matches[fvs.compose.includeList[i].systemST]); for j := 0 to fvs.compose.includeList[i].filterList.count - 1 do if not (('concept' = fvs.compose.includeList[i].filterList[j].property_ST) and (fvs.compose.includeList[i].filterList[j].OpST = FilterOperatorIsA)) then if not cs.doesFilter(fvs.compose.includeList[i].filterList[j].property_ST, fvs.compose.includeList[i].filterList[j].OpST, fvs.compose.includeList[i].filterList[j].valueST) then raise Exception.create('The filter "'+fvs.compose.includeList[i].filterList[j].property_ST +' '+ CODES_TFhirFilterOperator[fvs.compose.includeList[i].filterList[j].OpST]+ ' '+fvs.compose.includeList[i].filterList[j].valueST+'" was not understood in the context of '+cs.system); end; for i := 0 to fvs.compose.excludeList.Count - 1 do begin if not FOthers.ExistsByKey(fvs.compose.excludeList[i].systemST) then FOthers.Add(fvs.compose.excludeList[i].systemST, FStore.getProvider(fvs.compose.excludeList[i].systemST)); cs := TCodeSystemProvider(FOthers.matches[fvs.compose.excludeList[i].systemST]); for j := 0 to fvs.compose.excludeList[i].filterList.count - 1 do if not (('concept' = fvs.compose.excludeList[i].filterList[j].property_ST) and (fvs.compose.excludeList[i].filterList[j].OpST = FilterOperatorIsA)) then if not cs.doesFilter(fvs.compose.excludeList[i].filterList[j].property_ST, fvs.compose.excludeList[i].filterList[j].OpST, fvs.compose.excludeList[i].filterList[j].valueST) then raise Exception.create('The filter "'+fvs.compose.excludeList[i].filterList[j].property_ST +' '+ CODES_TFhirFilterOperator[fvs.compose.excludeList[i].filterList[j].OpST]+ ' '+fvs.compose.excludeList[i].filterList[j].valueST+'" was not understood in the context of '+cs.system); end; end; end; function TValueSetChecker.rule(op: TFhirOperationOutcome; severity: TFhirIssueSeverity; test: boolean; code, msg: string): boolean; var issue : TFhirOperationOutcomeIssue; begin result := test; if not test then begin issue := op.issueList.Append; issue.severityST := severity; issue.type_ := TFhirCoding.Create; issue.type_.systemST := 'http://hl7.org/fhir/issue-type'; issue.type_.codeST := code; issue.detailsST := msg; end; end; function TValueSetChecker.findCode(code: String; list : TFhirValueSetDefineConceptList; displays : TStringList): boolean; var i : integer; begin result := false; for i := 0 to list.count - 1 do begin if (code = list[i].codeST) and not list[i].abstractST then begin result := true; displays.Add(list[i].displayST); exit; end; if findCode(code, list[i].conceptList, displays) then begin result := true; exit; end; end; end; function TValueSetChecker.check(system, code: String): boolean; var list : TStringList; begin list := TStringList.Create; try result := check(system, code, list); finally list.Free; end; end; function TValueSetChecker.check(system, code : String; displays : TStringList) : boolean; var checker : TValueSetChecker; cs : TCodeSystemProvider; i : integer; begin result := false; if (fvs.define <> nil) and (system = fvs.define.systemST) then begin result := FindCode(code, fvs.define.conceptList, displays); if result then exit; end; if (fvs.compose <> nil) then begin for i := 0 to fvs.compose.importList.Count - 1 do begin if not result then begin checker := TValueSetChecker(FOthers.matches[fvs.compose.importList[i].value]); result := checker.check(system, code, displays); end; end; for i := 0 to fvs.compose.includeList.Count - 1 do begin if not result then begin cs := TCodeSystemProvider(FOthers.matches[fvs.compose.includeList[i].systemST]); result := (cs.system = system) and checkConceptSet(cs, fvs.compose.includeList[i], code, displays); end; end; for i := 0 to fvs.compose.excludeList.Count - 1 do begin if result then begin cs := TCodeSystemProvider(FOthers.matches[fvs.compose.excludeList[i].systemST]); result := not ((cs.system = system) and checkConceptSet(cs, fvs.compose.excludeList[i], code, displays)); end; end; end; end; procedure TValueSetChecker.check(coding: TFhirCoding; op : TFhirOperationOutcome); var list : TStringList; begin list := TStringList.Create; try if rule(op, IssueSeverityError, check(coding.systemST, coding.codeST, list), 'code-unknown', 'The system/code "'+coding.systemST+'"/"'+coding.codeST+'" is not in the value set') then rule(op, IssueSeverityWarning, (coding.displayST = '') or (list.IndexOf(coding.displayST) >= 0), 'value', 'The display "'+coding.displayST+'" is not a valid display for the code'); finally list.Free; end; end; function TValueSetChecker.check(coding: TFhirCoding): TFhirOperationOutcome; begin result := TFhirOperationOutcome.Create; try check(coding, result); BuildNarrative(result, 'Code Validation'); result.Link; finally result.free; end; end; function TValueSetChecker.check(coded: TFhirCodeableConcept): TFhirOperationOutcome; begin end; Function FreeAsBoolean(cs : TCodeSystemProvider; ctxt : TCodeSystemProviderContext) : boolean; overload; begin result := ctxt <> nil; if result then cs.Close(ctxt); end; Function FreeAsBoolean(cs : TCodeSystemProvider; ctxt : TCodeSystemProviderFilterContext) : boolean; overload; begin result := ctxt <> nil; if result then cs.Close(ctxt); end; function TValueSetChecker.checkConceptSet(cs: TCodeSystemProvider; cset : TFhirValueSetComposeInclude; code: String; displays : TStringList): boolean; var i : integer; fc : TFhirValueSetComposeIncludeFilter; ctxt : TCodeSystemProviderFilterContext; loc : TCodeSystemProviderContext; prep : TCodeSystemProviderFilterPreparationContext; filters : Array of TCodeSystemProviderFilterContext; begin result := false; if (cset.codeList.count = 0) and (cset.filterList.count = 0) then begin loc := cs.locate(code); try result := loc <> nil; if result then begin cs.displays(loc, displays); exit; end; finally cs.Close(loc); end; end; for i := 0 to cset.codeList.count - 1 do if (code = cset.codeList[i].value) and (cs.locate(code) <> nil) then begin cs.displays(code, displays); result := true; exit; end; if cset.filterList.count > 0 then begin SetLength(filters, cset.filterList.count); prep := cs.getPrepContext; try for i := 0 to cset.filterList.count - 1 do begin fc := cset.filterList[i]; if ('concept' = fc.property_ST) and (fc.OpST = FilterOperatorIsA) then filters[i] := cs.filter(fc.property_ST, fc.OpST, fc.valueST, prep); end; if cs.prepare(prep) then // all are together, just query the first filter begin ctxt := filters[0]; loc := cs.filterLocate(ctxt, code); try result := loc <> nil; if result then cs.displays(loc, displays); finally cs.Close(loc); end; end else begin for i := 0 to cset.filterList.count - 1 do begin fc := cset.filterList[i]; if ('concept' = fc.property_ST) and (fc.OpST = FilterOperatorIsA) then begin loc := cs.locateIsA(code, fc.valueST); try result := loc <> nil; if result then cs.displays(loc, displays); finally cs.Close(loc); end; end else begin ctxt := filters[i]; loc := cs.filterLocate(ctxt, code); try result := loc <> nil; if result then cs.displays(loc, displays); finally cs.Close(loc); end; end; if result then break; end; end; finally for i := 0 to cset.filterList.count - 1 do cs.Close(filters[i]); cs.Close(prep); end; end; end; end.
{ ***************************************************************************** * * * See the file COPYING.modifiedLGPL, 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. * * * ***************************************************************************** Original Author: Graeme Geldenhuys Makes all *Unix library loading functions emulate the Windows API names. Makes porting and cross platform development much easier. } unit dllfuncs; {$MODE objfpc} {$H+} interface uses SysUtils; function LoadLibrary(Name: PChar): PtrInt; function GetProcAddress(Lib: PtrInt; ProcName: PChar): Pointer; function FreeLibrary(Lib: PtrInt): Boolean; function GetLastdlerror: pchar; implementation const RTLD_LAZY = $001; RTLD_NOW = $002; RTLD_BINDING_MASK = $003; {$IFDEF LINUX} function dlopen(Name: PChar; Flags: LongInt) : Pointer; cdecl; external 'dl'; function dlsym(Lib: Pointer; Name: PChar) : Pointer; cdecl; external 'dl'; function dlclose(Lib: Pointer): LongInt; cdecl; external 'dl'; function dlerror: pchar; cdecl; external 'dl'; {$ELSE} function dlopen(Name: PChar; Flags: LongInt) : Pointer; cdecl; external 'c'; function dlsym(Lib: Pointer; Name: PChar) : Pointer; cdecl; external 'c'; function dlclose(Lib: Pointer): LongInt; cdecl; external 'c'; function dlerror: pchar; cdecl; external 'c'; {$ENDIF} function getlastdlerror: pchar; begin getlastdlerror := dlerror; end; function LoadLibrary(Name: PChar): PtrInt; begin Result := PtrInt(dlopen(Name, RTLD_LAZY)); end; function GetProcAddress(Lib: PtrInt; ProcName: PChar): Pointer; begin Result := dlsym(Pointer(Lib), ProcName); end; function FreeLibrary(Lib: PtrInt): Boolean; begin if Lib = 0 then Result := False else Result := dlClose(Pointer(Lib)) = 0; end; end.
program test; function factorial(a: integer): integer; begin if a < 0 then begin write('Wrong input'); Result := -1; end else if a = 0 then Result := 1 else Result := a * factorial(a - 1); end; begin write(factorial(-1)); write(factorial(8)); end.
unit LrComponentIterator; interface uses Classes, Controls, LrIterator; type TLrComponentIterator = class(TLrIterator) private FContainer: TComponent; protected function GetComponent: TComponent; virtual; procedure SetContainer(const Value: TComponent); virtual; public constructor Create(inContainer: TComponent = nil); function Eof: Boolean; override; function Next(inClass: TClass): Boolean; overload; property Component: TComponent read GetComponent; property Container: TComponent read FContainer write SetContainer; end; // TLrSortedComponentIterator = class(TLrComponentIterator) private FComponents: TList; FSortFunc: TListSortCompare; protected function GetComponent: TComponent; override; function GetComponents(inIndex: Integer): TComponent; procedure SetContainer(const Value: TComponent); override; protected procedure ListComponents; procedure SortComponents; public constructor Create(inContainer: TComponent = nil; inSortFunction: TListSortCompare = nil); destructor Destroy; override; function Eof: Boolean; override; property Components[inIndex: Integer]: TComponent read GetComponents; end; implementation { TLrComponentIterator } constructor TLrComponentIterator.Create(inContainer: TComponent); begin Container := inContainer; end; function TLrComponentIterator.Eof: Boolean; begin Result := (Index >= Container.ComponentCount); end; function TLrComponentIterator.GetComponent: TComponent; begin Result := Container.Components[Index - 1]; end; function TLrComponentIterator.Next(inClass: TClass): Boolean; begin Result := true; while Next do if Component is inClass then exit; Result := false; end; procedure TLrComponentIterator.SetContainer(const Value: TComponent); begin FContainer := Value; end; { TLrSortedComponentIterator } constructor TLrSortedComponentIterator.Create(inContainer: TComponent; inSortFunction: TListSortCompare); begin FComponents := TList.Create; FSortFunc := inSortFunction; Container := inContainer; end; destructor TLrSortedComponentIterator.Destroy; begin FComponents.Free; inherited; end; function TLrSortedComponentIterator.Eof: Boolean; begin Result := (Index >= FComponents.Count); end; function TLrSortedComponentIterator.GetComponents( inIndex: Integer): TComponent; begin Result := FComponents[inIndex - 1]; end; function TLrSortedComponentIterator.GetComponent: TComponent; begin Result := Components[Index]; end; procedure TLrSortedComponentIterator.ListComponents; var i: Integer; begin FComponents.Clear; if Container <> nil then for i := 0 to Pred(Container.ComponentCount) do if not (Container.Components[i] is TControl) then FComponents.Add(Container.Components[i]); end; procedure TLrSortedComponentIterator.SortComponents; begin FComponents.Sort(FSortFunc); end; procedure TLrSortedComponentIterator.SetContainer( const Value: TComponent); begin inherited; ListComponents; SortComponents; end; end.
unit AutoUpdater; interface uses Windows, Internet, Classes, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls, Dialogs, SysUtils, ActiveX, ExtCtrls, Forms; type TAutoUpdater = class(TThread) private FMmReport: TMemo; FLbFilename: TLabel; FForceRepair: Boolean; procedure DoMemoRefresh; procedure DoLabelRefresh; protected procedure Execute(); override; public Finished: boolean; RepairDone: boolean; constructor Create(const _MMReport: TMemo; const _LbFilename: TLabel; _ForceRepair: boolean); end; implementation constructor TAutoUpdater.Create(const _MMReport: TMemo; const _LbFilename: TLabel; _ForceRepair: boolean); begin inherited Create(true); Finished := false; Priority := TpHighest; FMmReport := _MMReport; FLbFilename := _LbFilename; FForceRepair := _ForceRepair; RepairDone := false; Resume; end; procedure TAutoUpdater.DoMemoRefresh; begin Application.ProcessMessages; FMMReport.Refresh; FMMReport.Repaint; end; procedure TAutoUpdater.DoLabelRefresh; begin Application.ProcessMessages; FLbFileName.Refresh; FLbFileName.Repaint; end; procedure TAutoUpdater.Execute; var FileStructureString : string; StructureFile: System.Text; StructureFilename,BaseDir,Filename: string; Node: IXMLNode; XMLDocument: IXMLDocument; Web : TWebFileDownloader; begin // Ok, first let's get the file structure document. FMMReport.Lines.Clear; FLbFilename.Caption := 'Loading File Structure'; try FileStructureString := GetWebContent('http://vxlse.ppmsite.com/structure.xml'); except ShowMessage('Warning: Internet Connection Failed. Try again later.'); ReturnValue := 0; Finished := true; exit; end; if Length(FileStructureString) = 0 then begin ReturnValue := 0; Finished := true; exit; end; FLbFilename.Caption := 'File Structure Downloaded'; BaseDir := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))); StructureFilename := BaseDir + 'structure.xml'; AssignFile(StructureFile,StructureFilename); Rewrite(StructureFile); Write(StructureFile,FileStructureString); CloseFile(StructureFile); FMMReport.Lines.Add('File structure data acquired. Starting procedure to repair the program.'); FMMReport.Refresh; // Now, let's read it. CoInitialize(nil); XMLDocument := TXMLDocument.Create(nil); XMLDocument.Active := true; XMLDocument.LoadFromFile(StructureFilename); // check each item Node := XMLDocument.DocumentElement.ChildNodes.FindNode('file'); repeat Filename := BaseDir + Node.Attributes['in']; FLbFilename.Caption := Filename; Synchronize(DoLabelRefresh); if not FileExists(Filename) or FForceRepair then begin Web := TWebFileDownloader.Create(Node.Attributes['out'],Filename); Sleep(20); if Web.WaitFor > 0 then begin FMMReport.Lines.Add(Filename + ' downloaded.'); Synchronize(DoMemoRefresh); end else begin FMMReport.Lines.Add(Filename + ' failed.'); Synchronize(DoMemoRefresh); end; Web.Free; end else begin FMMReport.Lines.Add(Filename + ' skipped.'); Synchronize(DoMemoRefresh); end; Node := Node.NextSibling; until Node = nil; XMLDocument.Active := false; DeleteFile(StructureFilename); FMMReport.Lines.Add('Repairing procedure has been finished.'); Synchronize(DoMemoRefresh); ReturnValue := 1; RepairDone := true; Finished := true; end; end.
// ***************************************************************************// // MODEL ACCESS // Jeziel Ribeiro Lago - 24/03/2017 // ***************************************************************************// unit Model.Access; interface uses System.Classes, System.Generics.Collections, ZDataSet, Model.Mapper, DataModuleDB; type TBaseModel = class(TInterfacedObject, IReadable, IWritable) published /// <summary>Ler os dados de um READER e passa os dados para um objeto</summary> procedure Read(Reader: IReader); Virtual; Abstract; /// <summary>Escreve os dados de um objeto para um WRITER</summary> procedure Write(Writer: IWriter); Virtual; Abstract; end; TModelAccess = class(TComponent) private FTableName: string; published ///<summary>Retorna um objeto conforme a query e os parâmetros informados</summary> class function QuerySingle<T: TBaseModel>(const AQueryText: string; Parameters: TMapValues = nil): T; ///<summary>Retorna uma lista de objetos conforme a query e os parâmetros informados</summary> class function QueryList<T: TBaseModel>(const AQueryText: string; Parameters: TMapValues = nil): TObjectList<T>; ///<summary>Retorna um TZQuery conforme a query e os parâmetros informados</summary> class function RawQuery(const TextQuery: string; Parameters: TMapValues = nil): TZQuery; function Insert(MapValues: TMapValues): Boolean; function Update(MapValues: TMapValues; Where: string): Boolean; function Delete(Where: string): Boolean; ///<summary>Informa a tabela para acesso aos dados</summary> procedure SetTable(ATableName: string); ///<summary>Insere os parâmetros no TZQuery informado</summary> procedure SetParams(MapValues: TMapValues; Query: TZQuery); end; implementation uses System.SysUtils, System.Variants, System.TypInfo, Winapi.Windows; { TModelAccess } function TModelAccess.Insert(MapValues: TMapValues): Boolean; var Query: TZQuery; i: Integer; begin if FTableName = '' then raise Exception.Create('TableName is empty!'); Query := TZQuery.Create(Self); Query.Connection := DataDB.Connection; with Query do begin SQL.Add('INSERT INTO ' + FTableName + '('); for i := 0 to MapValues.Count - 1 do begin if i = 0 then SQL.Add(MapValues[i].Key) else SQL.Add(',' + MapValues[i].Key); end; SQL.Add(') VALUES('); for i := 0 to MapValues.Count - 1 do begin if i = 0 then SQL.Add(':_' + MapValues[i].Key) else SQL.Add(',:_' + MapValues[i].Key); end; SQL.Add(')'); SetParams(MapValues, Query); try ExecSql; Close; except on E: Exception do raise Exception.Create('Insert in ' + FTableName + ': ' + E.Message); end; end; Query.Free; end; class function TModelAccess.QueryList<T>(const AQueryText: string; Parameters: TMapValues = nil): TObjectList<T>; var Lista: TObjectList<T>; ValuesReader: TValuesReader; Obj: T; begin if AQueryText = '' then raise Exception.Create('QueryText is empty!'); Lista := TObjectList<T>.Create; ValuesReader := TValuesReader.Create; ValuesReader.Query := TZQuery.Create(nil); ValuesReader.Query.Connection := DataDB.Connection; with ValuesReader.Query do begin try SQL.Add(AQueryText); if (Parameters <> nil) and (Parameters.Count > 0) then begin TModelAccess.Create(ValuesReader.Query).SetParams(Parameters, ValuesReader.Query); end; try Open; while not Eof do begin Obj := T(GetTypeData(PTypeInfo(TypeInfo(T)))^.ClassType.Create); Obj.Read(ValuesReader); Lista.Add(Obj); Next; end; Result := Lista; except on E: Exception do raise Exception.Create('QueryList in ' + E.Message); end; finally Close; Free; end; end; end; class function TModelAccess.QuerySingle<T>(const AQueryText: string; Parameters: TMapValues = nil): T; var ValuesReader: TValuesReader; Obj: T; begin if AQueryText = '' then raise Exception.Create('QueryText is empty!'); ValuesReader := TValuesReader.Create; ValuesReader.Query := TZQuery.Create(nil); ValuesReader.Query.Connection := DataDB.Connection; with ValuesReader.Query do begin try SQL.Text := AQueryText; if (Parameters <> nil) and (Parameters.Count > 0) then begin TModelAccess.Create(ValuesReader.Query).SetParams(Parameters, ValuesReader.Query); end; try Open; First; if not Eof then begin Obj := T(GetTypeData(PTypeInfo(TypeInfo(T)))^.ClassType.Create); Obj.Read(ValuesReader); Result := Obj; end; except on E: Exception do raise Exception.Create('QueryList in ' + E.Message); end; finally Close; Free; end; end; end; class function TModelAccess.RawQuery(const TextQuery: string; Parameters: TMapValues): TZQuery; var Query: TZQuery; begin if TextQuery = '' then raise Exception.Create('TextQuery is empty!'); Query := TZQuery.Create(nil); Query.Connection := DataDB.Connection; with Query do begin SQL.Text := TextQuery; if (Parameters <> nil) and (Parameters.Count > 0) then TModelAccess.Create(Query).SetParams(Parameters, Query); try Open; if not Eof then Result := Query; except on E: Exception do raise Exception.Create('RawQuery in: ' + E.Message); end; end; end; function TModelAccess.Update(MapValues: TMapValues; Where: string): Boolean; var Query: TZQuery; i: Integer; begin if FTableName = '' then raise Exception.Create('TableName is empty!'); if Where = '' then raise Exception.Create('Where is empty!'); Query := TZQuery.Create(Self); Query.Connection := DataDB.Connection; with Query do begin SQL.Add('UPDATE ' + FTableName + ' SET '); for i := 0 to MapValues.Count - 1 do begin if i = 0 then SQL.Add(MapValues[i].Key + ' = :_' + MapValues[i].Key) else SQL.Add(',' + MapValues[i].Key + ' = :_' + MapValues[i].Key); end; SQL.Add(' WHERE ' + Where); SetParams(MapValues, Query); try ExecSql; Close; except on E: Exception do raise Exception.Create('Insert in ' + FTableName + ': ' + E.Message); end; end; Query.Free; end; function TModelAccess.Delete(Where: string): Boolean; var Query: TZQuery; begin if FTableName = '' then raise Exception.Create('TableName is empty!'); if Where = '' then raise Exception.Create('Where is empty!'); Query := TZQuery.Create(Self); Query.Connection := DataDB.Connection; with Query do begin SQL.Add('DELETE FROM ' + FTableName + ' WHERE ' + Where); try try ExecSql; except on E: Exception do raise Exception.Create('Delete in ' + FTableName + ': ' + E.Message); end; finally Close; end; end; Query.Free; end; procedure TModelAccess.SetParams(MapValues: TMapValues; Query: TZQuery); var i: Integer; begin if (MapValues <> nil) and (MapValues.Count > 0) then begin for i := 0 to MapValues.Count - 1 do begin if VarIsType(MapValues[i].Value, varInteger) then Query.ParamByName('_' + MapValues[i].Key).AsInteger := MapValues[i].Value else if VarIsStr(MapValues[i].Value) then Query.ParamByName('_' + MapValues[i].Key).AsString := MapValues[i].Value else if VarIsFloat(MapValues[i].Value) then Query.ParamByName('_' + MapValues[i].Key).AsFloat := MapValues[i].Value else if VarIsType(MapValues[i].Value, varDate) then Query.ParamByName('_' + MapValues[i].Key).AsDateTime := MapValues[i].Value else raise Exception.Create('Tipo não suportado'); end; end; end; procedure TModelAccess.SetTable(ATableName: string); begin if ATableName = '' then raise Exception.Create('SetTable: TableName is empty!'); FTableName := ATableName; end; end.
unit Menu; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Registry, ShellAPI, Vcl.Buttons; type TForm1 = class(TForm) Theme: TComboBox; Change: TButton; Header: TImage; Maximizar: TImage; Fechar: TImage; Minimizar: TImage; Footer: TImage; Version: TLabel; WindowsLogo: TImage; Preview: TButton; ImagePreview: TImage; SystemSettings: TSpeedButton; procedure ChangeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ThemeChange(Sender: TObject); procedure PreviewClick(Sender: TObject); procedure SystemSettingsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} //== Função da Versão do Aplicativo ============================================ Function VersaoExe: String; type PFFI = ^vs_FixedFileInfo; var F : PFFI; Handle : Dword; Len : Longint; Data : Pchar; Buffer : Pointer; Tamanho : Dword; Parquivo: Pchar; Arquivo : String; begin Arquivo := Application.ExeName; Parquivo := StrAlloc(Length(Arquivo) + 1); StrPcopy(Parquivo, Arquivo); Len := GetFileVersionInfoSize(Parquivo, Handle); Result := ''; if Len > 0 then begin Data:=StrAlloc(Len+1); if GetFileVersionInfo(Parquivo,Handle,Len,Data) then begin VerQueryValue(Data, '',Buffer,Tamanho); F := PFFI(Buffer); Result := Format('%d.%d.%d.%d', [HiWord(F^.dwFileVersionMs), LoWord(F^.dwFileVersionMs), HiWord(F^.dwFileVersionLs), Loword(F^.dwFileVersionLs)] ); end; StrDispose(Data); end; StrDispose(Parquivo); end; //============================================================================== //=== Função para verificar o tema ============================================= Function ThemeChecker:string; var reg: TRegistry; begin reg := TRegistry.Create;//Criar e Escolher o caminho reg.RootKey:=HKEY_CURRENT_USER; //Criar o registro e abrir reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize',True); //Light Theme if reg.ReadInteger('AppsUseLightTheme')=1 then Result:='Light Theme'; //Dark Theme if reg.ReadInteger('AppsUseLightTheme')=0 then Result:='Dark Theme'; reg.CloseKey(); //Liberar reg.Free; end; //============================================================================== //=== Abrir Configurações ====================================================== procedure TForm1.SystemSettingsClick(Sender: TObject); begin winexec('explorer.exe shell:Appsfolder\windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel',SW_SHOW); end; //=== Trocar Tema ============================================================== procedure TForm1.ChangeClick(Sender: TObject); var reg: TRegistry; begin reg := TRegistry.Create;//Criar e Escolher o caminho reg.RootKey:=HKEY_CURRENT_USER; //Criar o registro e abrir reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize',True); //Light Theme if Theme.Text='Windows 10 Light Theme' then begin reg.WriteInteger('AppsUseLightTheme',1); reg.WriteInteger('SystemUseLightTheme',1); end; //Dark Theme if Theme.Text='Windows 10 Dark Theme' then begin reg.WriteInteger('AppsUseLightTheme',0); reg.WriteInteger('SystemUseLightTheme',0); end; reg.CloseKey(); //Liberar reg.Free; //verificar tema Version.Caption:=ThemeChecker+' | ['+VersaoExe+' ]'; end; //=== Criação do Form ========================================================== procedure TForm1.FormCreate(Sender: TObject); begin //verificar tema Version.Caption:=ThemeChecker+' | ['+VersaoExe+' ]'; if ThemeChecker='Dark Theme' then Theme.ItemIndex:=1; if ThemeChecker='Light Theme' then Theme.ItemIndex:=0; ThemeChange(Self); end; //=== Botão Preview ============================================================ procedure TForm1.PreviewClick(Sender: TObject); begin if (Form1.Height=190)and(Form1.Width=370) then begin Form1.Height:=555; Form1.Width:=1176; Preview.Caption:='<'; end else begin Form1.Height:=190; Form1.Width :=370; Preview.Caption:='>'; end; end; //=== Efeitos visuais e imagem ao trocar de tema =============================== procedure TForm1.ThemeChange(Sender: TObject); begin //Light Theme if Theme.Text='Windows 10 Light Theme' then begin Form1.Color:=ClBtnFace; ImagePreview.Picture.LoadFromFile(ExtractFilePath(ParamStr(0))+'Preview\Light Theme.PNG'); end; //Dark Theme if Theme.Text='Windows 10 Dark Theme' then begin Form1.Color:=$353535; ImagePreview.Picture.LoadFromFile(ExtractFilePath(ParamStr(0))+'Preview\Dark Theme.PNG'); end; end; end.
unit Invoice.Controller.DataModule; interface uses System.SysUtils, System.Classes, Data.DB, System.ImageList, Vcl.ImgList, Vcl.Controls, Vcl.AppEvnts, Invoice.Controller.Interfaces; type TDataModuleLocal = class(TDataModule) ApplicationEvents: TApplicationEvents; ImageList32_D: TImageList; ImageList32_E: TImageList; ImageListTabs: TImageList; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure ApplicationEventsException(Sender: TObject; E: Exception); private { Private declarations } FConnectionLocal: iModelConnection; FSQLServerName: String; FSQLDatabaseName: String; FSQLUserName: String; FSQLPassword: String; FSystemidUser: Integer; FSystemUsername: String; // procedure SetConfig; procedure SetInitialValues; function ConnectDatabase: Boolean; public { Public declarations } function Connected: Boolean; function GetConnection: iModelConnection; function GetidUser: Integer; procedure SetidUser(Value: Integer); function GetUsername: String; procedure SetUsername(Value: String); end; var DataModuleLocal: TDataModuleLocal; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses Vcl.Dialogs, Invoice.Controller.IniFile.Factory, Invoice.Controller.Connection.Factory, Invoice.Controller.Security.Factory; {$R *.dfm} procedure TDataModuleLocal.DataModuleCreate(Sender: TObject); begin SetInitialValues; // SetConfig; // ConnectDatabase; end; procedure TDataModuleLocal.DataModuleDestroy(Sender: TObject); begin FConnectionLocal.Connection.Close; end; function TDataModuleLocal.GetConnection: iModelConnection; begin Result := FConnectionLocal; end; function TDataModuleLocal.GetidUser: Integer; begin Result := FSystemidUser; end; function TDataModuleLocal.GetUsername: String; begin Result := FSystemUsername; end; procedure TDataModuleLocal.ApplicationEventsException(Sender: TObject; E: Exception); begin MessageDlg(E.Message, mtError, [mbOk], 0); // TControllerSecurityFactory.New.Default.AddLog(E.Message); end; function TDataModuleLocal.ConnectDatabase; begin FConnectionLocal := TControllerConnectionFactory.New.ConnectionFiredac.Parametros .DriverID('MSSQL') .Server(FSQLServerName) .Database(FSQLDatabaseName) .UserName(FSQLUserName) .Password(FSQLPassword) .EndParametros; // FConnectionLocal.Connection.Open; end; function TDataModuleLocal.Connected: Boolean; begin Result := FConnectionLocal.Connection.Connected; end; procedure TDataModuleLocal.SetConfig; begin FSQLServerName := TControllerIniFileFactory.New.Default.InputKey('Server', 'ServerName', '<Server Name>', False); FSQLDatabaseName := TControllerIniFileFactory.New.Default.InputKey('Server', 'DatabaseName', '<Database Name>', False); FSQLUserName := TControllerIniFileFactory.New.Default.InputKey('Server', 'UserName', '<User Name>', False); FSQLPassword := TControllerIniFileFactory.New.Default.InputKey('Server', 'UserPassword', '<User Password>', True); end; procedure TDataModuleLocal.SetidUser(Value: Integer); begin FSystemidUser := Value; end; procedure TDataModuleLocal.SetInitialValues; begin FSQLServerName := ''; FSQLDatabaseName := ''; FSQLUserName := ''; FSQLPassword := ''; // FSystemidUser := 0; FSystemUsername := ''; end; procedure TDataModuleLocal.SetUsername(Value: String); begin FSystemUsername := Value; end; end.
{****************************************************************************** lazbbscrollcontrols : Label and Button with scrolling caption Added to lazbbComponents palette bb - sdtp - january 2023 TbbScrollButton : Speedbutton with scrolling caption TbbScrollLabel ;: Label with scrolling caption Scrolling (boolean): Enable or disable caption scrolling. When caption is shorter than button width, scrolling is always disabled. ScrollInterval (ms): Set the scroolling speed. A low interval means a high scrolling speed. ScrollAutoString (string): String added between caption text during scrolling. Default is '...' ScrollGraph (boolean): Enable or disable smooth scrolling (pixel by pixel instead char by char). ScrollStep (integer): Increment scrolling step. default 1 ScrollDirection (sdLeftToRight, sdRightToLeft) ********************************************************************************} unit lazbbscrollcontrols; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons, fpTimer, ExtCtrls, StdCtrls, LMessages; type TScrollDirection= (sdLeftToRight, sdRightToLeft); TBidiMod = (Disabled); TbbScrollButton = class(TSpeedButton) private FCaption: String; FScrolling: boolean; FScrollInterval: integer; FScrollAutoString:string; FScrollGraph: Boolean; FScrollStep: Integer; FScrollDirection: TSCrollDirection; FMargin: Integer; FBidiMode: TBidiMOd; FSpacing: Integer; CaptionBmp: Tbitmap; CaptionRect: TRect; FTimerScroll: TTimer; TimerGlyph:TTimer; PrevGlyphwidth: Integer; ScrollText: String; txtHeight, txtWidth: Integer; ScrollBmp: TBitMap; ScrollRect:Trect; BkGndBmp:Tbitmap; BkGndRect: Trect; ScrollIndex: Integer; BordersWidth:Integer; procedure ReInit; procedure OnTimerScrollL(Sender: TObject); // Left to right procedure OnTimerScrollR(Sender: TObject); // Right to left procedure OnTimerGlyph(Sender: TObject); procedure SetCaption(AValue: string); procedure SetMargin(AValue: integer); procedure SetSpacing(AValue: integer); procedure SetScrolling(AValue: Boolean); procedure SetScrollInterval(AValue:integer); procedure SetScrollAutoString(AValue:string); procedure SetScrollGraph(aValue: Boolean); procedure SetScrollStep(aValue:Integer); procedure SetScrollDirection(aValue: TSCrollDirection); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Caption: string read FCaption write SetCaption; property Margin: integer read FMargin write SetMargin default 4; property Spacing: integer read FSpacing write SetSpacing default 4; property BidiMode: TBiDiMod read FBidiMode default disabled; property Scrolling: Boolean read FScrolling write SetScrolling default false; property ScrollInterval: Integer read FScrollInterval write SetScrollInterval default 50; property ScrollAutoString: string read FScrollAutoString write SetScrollAutoString; property ScrollGraph: Boolean read FScrollGraph write SetScrollGraph default true; property ScrollStep: Integer read FScrollStep write SetScrollStep default 1; property ScrollDirection: TScrollDirection read FScrollDirection write SetScrollDirection default sdLeftToRight; end; TbbScrollLabel = class(TCustomLabel) private FScrollAutoString: String; FScrollDirection: TSCrollDirection; FSCrollGraph: Boolean; FScrolling: Boolean; FSCrollInterval: Integer; FScrollStep: Integer; CaptionRect: TRect; TxtHeight, TxtWidth, CaptionWidth: Integer; ScrollBmp: TBitmap; ScrollIndex: Integer; bkColor: TColor; ScrollText: String; TextScroll: String; TimerScroll:TFPTimer; xOff, yOff: Integer; ReInit: Boolean; function GetAlignment: TAlignment; procedure SetAlignment(al: TAlignment); function GetCaption: String; procedure SetCaption(s: String); function GetLayout: TTextLayout; procedure SetLayout(tl: TTextLayout); function GetParentColor: Boolean; procedure SetParentColor(b: Boolean); procedure SetScrollAutoString(s: String); procedure SetScrollDirection(sd: TScrollDirection); procedure SetScrollGraph(b: Boolean); procedure SetSCrolling(b: Boolean); procedure SetSCrollInterval(i: Integer); procedure SetScrollStep(i: Integer); procedure OnTimerScrollLG(Sender: TObject); // Graphic mode Left to Right procedure OnTimerScrollRG(Sender: TObject); // Right to left procedure OnTimerScrollLT(Sender: TObject); // Text mode Left to Right procedure OnTimerScrollRT(Sender: TObject); // Right to left procedure Init; procedure ScrollTimerEvent; protected procedure CMColorChanged( Var Msg :TLMessage ); Message CM_COLORCHANGED; procedure CMParentColorChanged(var Msg: TLMessage); message CM_PARENTCOLORCHANGED; procedure FontChanged(Sender: TObject); override; public constructor Create(aOwner: Tcomponent); override; destructor Destroy; override; procedure Paint; override; published property Align; property Alignment: TAlignment read GetAlignment write SetAlignment default taLeftJustify; property Anchors; property AutoSize; property BidiMode; property BorderSpacing; property Caption: String read GetCaption write SetCaption; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; property FocusControl; property Font; //: TFont read GetTheFont write SetTheFont; property Layout: TTextLayout read GetLayout write SetLayout default tlTop; property ParentBidiMode; property ParentColor: Boolean read GetParentColor write SetParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property Transparent; property Visible; property WordWrap; property OnChangeBounds; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnMouseWheelHorz; property OnMouseWheelLeft; property OnMouseWheelRight; property OnResize; property OnStartDrag; property OptimalFill; // Scrolling properties property ScrollAutoString: String read FScrollAutoString write SetScrollAutoString; property ScrollDirection: TSCrollDirection read FScrollDirection write SetScrollDirection default sdLeftToRight; property SCrollGraph: Boolean read FSCrollGraph write SetSCrollGraph default True; property Scrolling: Boolean read FScrolling write SetScrolling default True; property ScrollInterval: Integer read FSCrollInterval write SetSCrollInterval default 50; property ScrollStep: Integer read FScrollStep write SetScrollStep default 1; end; procedure Register; implementation procedure Register; begin {$I lazbbscrollcontrols_icon.lrs} RegisterComponents('lazbbComponents',[TbbScrollButton]); RegisterComponents('lazbbComponents',[TbbScrollLabel]); end; // TbbScrollButton creation constructor TbbScrollButton.Create(AOwner: TComponent); begin inherited Create(AOwner); Parent:= TWinControl(aOwner); FCaption:='ScrollButton'; FScrolling:= true; AutoSize:= False; Width:= 75; FMargin:= 4; inherited Margin:= FMargin; FSpacing:= 4; inherited Spacing:= FSpacing; BordersWidth:= 3; // Arbitrary value for proper scrolling centering FScrollInterval:=50; FScrollAutoString:= '...'; FScrollGraph:= true; FScrollStep:= 1; TimerGlyph:= TTimer.Create(self); TimerGlyph.Enabled:= True; TimerGlyph.OnTimer:= @OnTimerGlyph; TimerGlyph.Interval:= 100; FTimerSCroll:= TTimer.Create(self); FTimerScroll.Enabled:= False; FTimerScroll.OnTimer:= @OnTimerScrollL; FTimerScroll.Interval:= FScrollInterval; ScrollIndex:= 0; inherited Layout:= Layout; inherited Caption:= FCaption; if csDesigning in ComponentState then begin Inherited Margin:= -1; Exit; end; ScrollText:= ''; ScrollBmp:= Tbitmap.Create; ScrollBmp.PixelFormat:= pf8bit; BkGndBmp:= Tbitmap.Create; BkGndBmp.PixelFormat:= pf8bit; CaptionBmp:= Tbitmap.Create; PrevGlyphwidth:= Glyph.width; FBidiMode:= Disabled; inherited BiDiMode:= bdLeftToRight; end; procedure TbbScrollButton.SetCaption(AValue: string); begin if fCaption=AValue then exit; FCaption:=AValue; //if csDesigning in ComponentState then inherited Caption:=FCaption; ReInit; end; procedure TbbScrollButton.SetMargin(AValue: integer); begin if FMargin=AValue then exit; FMargin:=AValue; inherited Margin:= AValue; ReInit; end; procedure TbbScrollButton.SetSpacing(AValue: integer); begin if FSpacing=AValue then exit; FSpacing:=AValue; inherited Spacing:= AValue; ReInit; end; procedure TbbScrollButton.SetSCrolling(AValue: Boolean); begin if FScrolling= AValue then exit; FSCrolling:= AValue; ReInit; end; procedure TbbScrollButton.SetScrollInterval(AValue:integer); begin if FScrollInterval= AValue then exit; FScrollInterval:= AValue; FTimerScroll.Interval:= AValue; //ReInit; //Not needed, will be updated next timer tick end; procedure TbbScrollButton.SetSCrollAutoString(AValue:string); begin if FSCrollAutoString= AValue then exit; FSCrollAutoString:= AValue; ReInit; end; procedure TbbScrollButton.SetSCrollGraph(AValue:Boolean); begin if fScrollGraph= AValue then exit; fsCrollGraph:= AValue; Reinit; end; procedure TbbScrollButton.SetSCrollStep(AValue:Integer); begin if fScrollStep=aValue then exit; fSCrollStep:= AValue; //ReInit; //Not needed, will be updated next timer tick end; procedure TbbScrollButton.SetSCrollDirection(aValue: TSCrollDirection); begin if FScrollDirection=aValue then exit; FScrollDirection:= aValue; if aValue=sdLeftToRight then FTimerScroll.OnTimer:= @OnTimerScrollL else FTimerScroll.OnTimer:= @OnTimerScrollR ; //ReInit; //Not needed, will be updated next timer tick end; destructor TbbScrollButton.Destroy; begin if assigned(BkGndBmp) then BkGndBmp.Free; if assigned(ScrollBmp) then ScrollBmp.Free; if assigned(CaptionBmp) then CaptionBmp.Free; if assigned(FTimerScroll) then FTimerSCroll.free; if assigned(TimerGlyph) then TimerGlyph.free; Inherited Destroy; end; procedure TbbScrollButton.ReInit; var BegTxt: integer; begin if csDesigning in ComponentState then exit; inherited Caption:= ''; // avoid some flickering inherited margin:= FMargin; // if it was previously changed // Scroll d�sactiv� FTimerScroll.enabled:= false; if (Glyph.width=0) or (layout=blGlyphTop) or (layout=blGlyphBottom) // if FCaption shorter than button free space, then exit. then BegTxt:= FMargin else BegTxt:= (Glyph.Width div NumGlyphs)+FSpacing+FMargin; Canvas.Font.Assign(Font); if (Canvas.TextWidth(FCaption) <= ClientWidth-BegTxt-FMargin-BordersWidth) or not FScrolling then begin Inherited Margin:= -1; Inherited Caption:= FCaption; Exit; end ; if csDesigning in ComponentState then exit; // So, we scroll ! ScrollText:= FCaption+FScrollAutoString; TxtHeight:= Canvas.TextHeight(ScrollText); TxtWidth:= Canvas.TextWidth(ScrollText); CaptionRect.Top:= (height-TxtHeight) div 2; CaptionRect.Bottom:= CaptionRect.Top+TxtHeight; BkGndBmp.Width:= 1; BkGndBmp.Height:= TxtHeight; BkGndRect:= Rect(0, 0, 1, TxtHeight); if (Glyph.width=0) then begin CaptionRect.Left:= FMargin+1; CaptionRect.Right:= CaptionRect.Left+ClientWidth-FMargin*2-BordersWidth; BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Top+1)); end else Case Layout of blGlyphLeft: begin CaptionRect.Left:= FMargin+Fspacing+(glyph.width div NumGlyphs)+FMargin; CaptionRect.Right:= ClientWidth+1-FMargin*2; BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Bottom)); end; blGlyphRight:begin CaptionRect.Left:= FMargin+1; CaptionRect.Right:= ClientWidth-Fspacing-FMargin*2-(glyph.width div NumGlyphs); BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Right, CaptionRect.top, CaptionRect.Right+1, CaptionRect.Bottom)); end; blGlyphTop : begin CaptionRect.Left:= FMargin+1; CaptionRect.Right:= CaptionRect.Left+ClientWidth-FMargin*3; CaptionRect.Top:=FMargin+glyph.height+ (ClientHeight-FMargin-glyph.height-Canvas.TextHeight(ScrollText) ) div 2; CaptionRect.Bottom:= FMargin+glyph.height+ (ClientHeight-FMargin-glyph.height+Canvas.TextHeight(ScrollText) ) div 2; BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Bottom)); end; blGlyphBottom: begin CaptionRect.Left:= FMargin+1; CaptionRect.Right:= CaptionRect.Left+ClientWidth-FMargin*3; CaptionRect.Top:=(ClientHeight-FMargin-glyph.height-Canvas.TextHeight(ScrollText)) div 2; CaptionRect.Bottom:=(ClientHeight-FMargin-glyph.height+Canvas.TextHeight(ScrollText) ) div 2; BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Bottom)); end; end; If fScrollGraph then begin ScrollBmp.Canvas.Font.Assign(Font); ScrollBmp.width:= 2*txtWidth; ScrollBmp.Height:= txtHeight; ScrollRect:= Rect(0,0,2*txtWidth,txtHeight); ScrollBmp.Canvas.StretchDraw(ScrollRect, BkGndBmp); ScrollBmp.Canvas.Brush.Style:= bsClear; ScrollBmp.Canvas.TextOut(0,0, ScrollText+ScrollText); end; FTimerScroll.Enabled:= FScrolling; end; // This timer detect if glyph size has changed and reinit. procedure TbbScrollButton.OnTimerGlyph(Sender: TObject); begin if csDesigning in ComponentState then exit; if PrevGlyphwidth=Glyph.width then exit else begin PrevGlyphwidth:=Glyph.width; ReInit; end; end; // Timer procedure for left to right // separate procedures to reduce processing time in the timer event procedure TbbScrollButton.OnTimerScrollL(Sender: TObject); begin if fSCrollGraph then // pixel by pixel begin if (ScrollIndex=0) then ReInit; if ScrollIndex < (ScrollBmp.Width div 2)-1 then Inc(ScrollIndex, FSCrollStep) else ScrollIndex:= 0; // Background change when button has focus BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Bottom)); ScrollBmp.Canvas.StretchDraw(ScrollRect, BkGndBmp); ScrollBmp.Canvas.TextOut(0,0, ScrollText+ScrollText); Canvas.CopyRect(CaptionRect, ScrollBmp.Canvas, Rect(ScrollIndex,0,ScrollIndex+CaptionRect.Right-CaptionRect.left , txtHeight)); end else // scroll char by char begin ScrollText:= Copy(ScrollText, 2, Length(ScrollText) - 1) + Copy(ScrollText,1,1) ; inherited Caption:= scrolltext; end; end; // Timer procedure for right to left // separate procedures to reduce processing time in the timer event procedure TbbScrollButton.OnTimerScrollR(Sender: TObject); begin if fSCrollGraph then begin if (ScrollIndex=0) then ReInit; if ScrollIndex >0 then Dec(ScrollIndex, FSCrollStep) else ScrollIndex:= (ScrollBmp.Width div 2); // Background change when button has focus BkGndBmp.Canvas.CopyRect(BkGndRect, Canvas, Rect(CaptionRect.Left-1, CaptionRect.top, CaptionRect.Left, CaptionRect.Bottom)); ScrollBmp.Canvas.StretchDraw(ScrollRect, BkGndBmp); ScrollBmp.Canvas.TextOut(0,0, ScrollText+ScrollText); Canvas.CopyRect(CaptionRect, ScrollBmp.Canvas, Rect(ScrollIndex,0,ScrollIndex+CaptionRect.Right-CaptionRect.left , txtHeight)); end else // scroll char by char begin ScrollText:=Copy(ScrollText,Length(ScrollText),1)+Copy(ScrollText, 1, Length(ScrollText)-1); inherited Caption:= scrolltext; end; end; // TbbScrollLabel procedures function TbbScrollLabel.GetAlignment: TAlignment; begin result:= Inherited Alignment; end; procedure TbbScrollLabel.SetAlignment(al: TAlignment); begin if Alignment=al then exit; Inherited Alignment:= al; Init; Invalidate; end; function TbbScrollLabel.GetCaption: String; begin result:= Inherited Caption; end; procedure TbbScrollLabel.SetCaption(s: String); begin if Caption=s then exit; Inherited Caption:= s; TextScroll:= Caption+FScrollAutoString; ScrollText:= Caption+FScrollAutoString; ScrollIndex:= 0; Init; Invalidate; end; function TbbScrollLabel.GetLayout: TTextLayout; begin result:= Inherited Layout; end; procedure TbbScrollLabel.SetLayout(tl: TTextLayout); begin if Layout=tl then exit; Inherited Layout:= tl; Init; Invalidate; end; function TbbScrollLabel.GetParentColor: Boolean; begin result:= Inherited ParentColor; end; procedure TbbScrollLabel.SetParentColor(b: Boolean); begin if ParentColor= b then exit; inherited ParentColor:= b; if ParentColor then color:= Parent.Color; init; Invalidate; end; procedure TbbScrollLabel.SetScrollAutoString(s: String); begin if FScrollAutoString=s then exit; FScrollAutoString:=s; TextScroll:= Caption+FScrollAutoString; ScrollText:= Caption+FScrollAutoString;; Init; Invalidate; end; procedure TbbScrollLabel.ScrollTimerEvent; begin if FSCrollGraph then begin if FScrollDirection= sdLeftToRight then TimerScroll.OnTimer:= @OnTimerScrollLG else TimerScroll.OnTimer:= @OnTimerScrollRG; end else begin if FScrollDirection= sdLeftToRight then TimerScroll.OnTimer:= @OnTimerScrollLT else TimerScroll.OnTimer:= @OnTimerScrollRT; end; end; procedure TbbScrollLabel.SetScrollDirection(sd: TScrollDirection); begin if FScrollDirection= sd then exit; FScrollDirection:= sd; ScrollTimerEvent; Init; Invalidate; end; procedure TbbScrollLabel.SetScrollGraph(b: Boolean); begin if FSCrollGraph= b then exit; FSCrollGraph:= b; ScrollTimerEvent; Init; Invalidate; end; procedure TbbScrollLabel.SetSCrolling(b: Boolean); begin if FScrolling= b then exit; FSCrolling:= b; Init; Invalidate; end; procedure TbbScrollLabel.SetSCrollInterval(i: Integer); begin if FSCrollInterval=i then exit; FSCrollInterval:= i; TimerSCroll.Interval:= i; Init; Invalidate; end; procedure TbbScrollLabel.SetScrollStep(i: Integer); begin if FScrollStep=i then exit; FScrollStep:= i; Init; Invalidate; end; procedure TbbScrollLabel.CMColorChanged(Var Msg :TLMessage ); begin Inherited CMVisiblechanged(Msg); Init; Invalidate; end; procedure TbbScrollLabel.CMParentColorChanged(Var Msg :TLMessage ); begin Inherited CMVisiblechanged(Msg); Init; Invalidate; end; procedure TbbSCrollLabel.FontChanged(Sender: TObject); begin inherited FontChanged(Sender); Init; Invalidate; end; constructor TbbScrollLabel.Create(aOwner: Tcomponent); begin inherited; parent:= TwinControl(aOwner); ScrollBmp:= TBitmap.Create; ScrollBmp.PixelFormat:= pf24bit; TimerScroll:= TFPTimer.Create(self); TimerScroll.UseTimerThread:= true; Height:= 15; Width:= 50; Alignment:= taLeftJustify; Layout:= tlTop; AutoSize:= false; ParentFont:= False; FScrollAutoString:= '...'; FScrollDirection:= sdLeftToRight; FScrolling:= True; FSCrollGraph:= True; FScrollStep:= 1; FScrollInterval:= 50; ScrollText:= Caption+FScrollAutoString; TextScroll:= Caption+FScrollAutoString; TimerScroll.Interval:= FScrollInterval; TimerScroll.OnTimer:= @OnTimerScrollLG; TimerScroll.Enabled:= True; end; destructor TbbScrollLabel.Destroy; begin if Assigned(TimerSCroll) then begin TimerScroll.Enabled:= False; TimerScroll.Free; end; if assigned(ScrollBmp) then ScrollBmp.Free; Inherited Destroy; end; // Procedure called when any property change to properly set metrics variables procedure TbbScrollLabel.Init; begin CaptionRect.Top:= BorderSpacing.Top; CaptionRect.Left:= BorderSpacing.Left; CaptionRect.Right:= ClientWidth-BorderSpacing.Right; CaptionRect.Bottom:= Height-BorderSpacing.Bottom; if (color=cldefault) or (color=clnone) then bkcolor:= clForm else bkColor:= color; if Assigned(SCrollBmp) then begin ScrollBmp.SetSize(Width, Height); ScrollBmp.Canvas.Font.Assign(Font); TxtWidth:= ScrollBmp.Canvas.TextWidth(ScrollText); TxtHeight:= ScrollBmp.Canvas.TextHeight(ScrollText); ScrollBmp.Width:= txtWidth*2; ScrollBmp.Canvas.Brush.Style:= bssolid; ScrollBmp.Canvas.Brush.color:= bkColor; ScrollBmp.Canvas.pen.color:= Font.Color; CaptionWidth:= ScrollBmp.Canvas.TextWidth(Caption); ScrollBmp.Canvas.FillRect(0,0,ScrollBmp.Width, ScrollBmp.Height); Case Layout of tlCenter: yOff:= (Height-txtHeight) div 2; tlBottom: yOff:= Height-txtHeight; else yOff:= 0; end; Case Alignment of taRightJustify: xOff:= Width-CaptionWidth; taCenter: xOff:= (Width-CaptionWidth) div 2; else xOff:= 0; end; //Write the scrolltext (Caption+ScrollAutostring+Caption+SCrollAutostring) on ScrollBmp ScrollBmp.Canvas.TextOut(xOff,yOff, ScrollText+ScrollText); end; ReInit:= True; end; // Paint the component procedure TbbScrollLabel.Paint; begin // Reinit set at true in Init procedure when some properties changes, // need to reload canvas related variables here //if ReInit then //begin // ReInit:= False; { CaptionWidth:= Canvas.TextWidth(Caption); TxtWidth:= Canvas.TextWidth(ScrollText); TxtHeight:= Canvas.TextHeight(ScrollText); Case Layout of tlCenter: yOff:= (Height-txtHeight) div 2; tlBottom: yOff:= Height-txtHeight; else yOff:= 0; end; Case Alignment of taRightJustify: xOff:= Width-CaptionWidth; taCenter: xOff:= (Width-CaptionWidth) div 2; else xOff:= 0; end; } Canvas.Brush.Style:= bssolid; Canvas.Brush.color:= bkColor; { ScrollBmp.Width:= txtWidth*2; ScrollBmp.Height:= Height; ScrollBmp.Canvas.Font.Assign(Font); ScrollBmp.Canvas.Brush.Style:= bssolid; ScrollBmp.Canvas.Brush.color:= bkColor; ScrollBmp.Canvas.pen.color:= Font.Color; ScrollBmp.Canvas.FillRect(0,0,ScrollBmp.Width, ScrollBmp.Height); } //end; if (not FSCrolling) or (CaptionWidth<Clientwidth) or (csDesigning in ComponentState) then begin inherited Paint; exit; end; if FSCrollGraph then begin // Write the scrolltext (Caption+ScrollAutostring+Caption+SCrollAutostring) on ScrollBmp //ScrollBmp.Canvas.TextOut(xOff,yOff, ScrollText+ScrollText); // Copy part of ScrollBMP on the component canvas, timer increment part position Canvas.CopyRect(CaptionRect, ScrollBmp.Canvas, Rect(ScrollIndex,0, ScrollIndex+CaptionRect.Right-CaptionRect.left, Height)); end else begin Canvas.TextOut(xOff, yOff, TextScroll); end; end; // Timer procedure for left to right // separate procedures to reduce processing time in the timer event procedure TbbScrollLabel.OnTimerScrollLG(Sender: TObject); begin if ScrollIndex < (ScrollBmp.Width div 2)-1 then Inc(ScrollIndex, FSCrollStep) else ScrollIndex:= 0; Invalidate; end; procedure TbbScrollLabel.OnTimerScrollLT(Sender: TObject); begin TextScroll:= Copy(TextScroll, 2, Length(TextScroll) - 1) + Copy(TextScroll,1,1) ; Invalidate; end; // Timer procedure for right to left procedure TbbScrollLabel.OnTimerScrollRG(Sender: TObject); begin if ScrollIndex >0 then Dec(ScrollIndex, FSCrollStep) else ScrollIndex:= (ScrollBmp.Width div 2); Invalidate; end; procedure TbbScrollLabel.OnTimerScrollRT(Sender: TObject); begin TextScroll:=Copy(TextScroll,Length(TextScroll),1)+Copy(TextScroll, 1, Length(TextScroll)-1); Invalidate; end; end.
unit uMain; {******************************************************************************* * * * Название модуля : * * * * uMain * * * * Назначение модуля : * * * * Поиск и выполнение скриптов. Отображение результатов тестирования. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls, Menus, IniFiles, uTypes, FileUtil, ShellApi; type TfmMain = class(TForm) stbMain : TStatusBar; mnuMain : TMainMenu; lvwOutput : TListView; OpenDialog : TOpenDialog; mnuTest : TMenuItem; mnuExit : TMenuItem; mnuStart : TMenuItem; mnuOptions : TMenuItem; mnuCreateTestList : TMenuItem; procedure mnuExitClick (Sender: TObject); procedure mnuStartClick (Sender: TObject); procedure mnuOptionsClick (Sender: TObject); procedure mnuCreateTestListClick (Sender: TObject); procedure FormActivate (Sender: TObject); procedure FormShortCut (var Msg: TWMKey; var Handled: Boolean); private FAppMode : TAppMode; FFileName : TFileName; function GetAppMode : TAppMode; function GetFileName: TFileName; procedure SetAppMode ( aValue: TAppMode ); procedure SetFileName( aValue: TFileName ); public Params: TStringList; Property AppMode : TAppMode read GetAppMode write SetAppMode; Property FileName : TFileName read GetFileName write SetFileName; end; var fmMain: TfmMain; implementation uses uUtils, DateUtils; {$R *.dfm} function TfmMain.GetAppMode: TAppMode; begin Result := FAppMode; end; function TfmMain.GetFileName: TFileName; begin Result := FFileName; end; procedure TfmMain.SetAppMode(aValue: TAppMode); begin FAppMode := aValue; end; procedure TfmMain.SetFileName(aValue: TFileName); begin FFileName := aValue; end; //Выходим из приложения procedure TfmMain.mnuExitClick(Sender: TObject); var MsgRes : TModalResult; begin MsgRes := MessageDlg( cQUIT_QUESTION, mtConfirmation, [mbYes, mbNo], 0 ); if MsgRes = mrYes then Close; end; Function WinCopyFile(FromFile, ToDir : string) : boolean; var F : TShFileOpStruct; begin //showmessage(FromFile+'|'+ToDir); F.Wnd := 0; F.wFunc := FO_COPY; FromFile:=FromFile+#0; F.pFrom:=pchar(FromFile); ToDir:=ToDir+#0; F.pTo:=pchar(ToDir); F.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION; result:=ShFileOperation(F) = 0; end; //Обрабатываем горячие клавищи procedure TfmMain.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin case Msg.CharCode of VK_ESCAPE : begin mnuExit.Click; end; VK_F9 : begin mnuStart.Click; end; VK_F2 : begin mnuCreateTestList.Click; end; 115 : begin Close; end; end; Handled := True; end; //Пытаемся использовать для тестирования настройки из ini-файла procedure TfmMain.FormActivate(Sender: TObject); var MsgRes : TModalResult; begin try FileName := ExtractFilePath( Application.ExeName ) + cINI_FILE_NAME; //Прячем приложение if AppMode = amCmd then begin ShowWindow( Handle, SW_HIDE ); ShowWindow( Application.Handle, SW_HIDE ); end; //Проверяем: существует ли файл настроек? if not( FileExists( FileName ) ) then begin MsgRes := MessageDlg( cINI_FILE_NOT_FOUND, mtError, [mbYes, mbNo], 0 ); //Указываем путь к ini-файлу вручную if MsgRes = mrYes then begin if OpenDialog.Execute then begin FileName := OpenDialog.FileName; mnuStart.Enabled := True; if AppMode in [amCmd, amWin] then mnuStart.Click; end else begin MessageDlg( cAPP_EXIT, mtWarning, [mbOK], 0 ); if AppMode = amCmd then Close; end; end else begin MessageDlg( cAPP_EXIT, mtWarning, [mbOK], 0 ); if AppMode = amCmd then Close; end; end else begin mnuStart.Enabled := True; if AppMode in [amCmd, amWin] then mnuStart.Click; end; except LogException( ExtractFilePath( Application.ExeName ) + cERROR_FILE_NAME ); end; end; //Копируем на локальную станцию все необходимые файлы для тестирования, //тестируем скрипты, переименовываем их + применяем к удалённым версиям БД procedure TfmMain.mnuStartClick(Sender: TObject); const HighBound = 99; var i, j, n : Integer; Index : Integer; Result : Boolean; IsValid : Boolean; IniFile : TIniFile; StrList : TStringList; FileRec : TSearchRec; TmpPath : String; CurIndex : Integer; CurrItem : TListItem; DBParams : TStringList; ScrStatus : TScriptStatus; DBResult : TAppResult; AppResult : Boolean; DateBackUp : TDate; CurrResult : Boolean; FullRename : Boolean; TestParams : TStringList; ScrOnlyExec : TStringList; IsValidExec : Boolean; DBResultMsg : String; ErrFileName : TFileName; AllSecNames : TStringList; FmtSettings : TFormatSettings; AllExecScrOK : Boolean; ExecSysScrMsg : String; ErrScriptChar : String; ScrTestAndExec : TStringList; TmpErrFileName : TFileName; UselessSecNames : TStringList; ExecSysScrResult : Boolean; begin try try try lvwOutput.Clear; lvwOutput.Color := clWhite; if FileExists( FileName ) then begin IniFile := TIniFile.Create( FileName ); AllSecNames := TStringList.Create; UselessSecNames := TStringList.Create; //Получаем имена ВСЕХ секций ini-файла IniFile.ReadSections( AllSecNames ); //Получаем имена только служебных секций ini-файла IniFile.ReadSectionValues( cUSELESS_SECTION, UselessSecNames ); //Формируем список названий значащих секций n := UselessSecNames.Count - 1; for i := 0 to n do begin Index := AllSecNames.IndexOf( UselessSecNames.ValueFromIndex[i] ); AllSecNames.Delete( Index ); end; //Получаем параметры тестирования для локальной станции TestParams := TStringList.Create; with TestParams do begin BeginUpdate; Values[cUSER ] := IniFile.ReadString( cTEST_PARAMS, cUSER, cDEF_USER ); Values[cSERVER ] := IniFile.ReadString( cTEST_PARAMS, cSERVER, cDEF_SERVER ); Values[cPASSWORD ] := IniFile.ReadString( cTEST_PARAMS, cPASSWORD, cDEF_PASSWORD ); Values[cERROR_LOG_DIR ] := IniFile.ReadString( cTEST_PARAMS, cERROR_LOG_DIR, cDEF_ERROR_LOG_DIR ); Values[cSEPARATOR_CHAR ] := IniFile.ReadString( cTEST_PARAMS, cSEPARATOR_CHAR, cDEF_SEPARATOR_CHAR ); Values[cERROR_SCRIPT_CHAR ] := IniFile.ReadString( cTEST_PARAMS, cERROR_SCRIPT_CHAR, cDEF_ERROR_SCRIPT_CHAR ); Values[cPREFIX_CHAR_COUNT ] := IniFile.ReadString( cTEST_PARAMS, cPREFIX_CHAR_COUNT, cDEF_PREFIX_CHAR_COUNT ); Values[cARCHIVATOR_PATH ] := IniFile.ReadString( cTEST_PARAMS, cARCHIVATOR_PATH, cDEF_ARCHIVATOR_PATH ); Values[cIBESCRIPT_PATH ] := IniFile.ReadString( cTEST_PARAMS, cIBESCRIPT_PATH, cDEF_IBESCRIPT_PATH ); Values[cDB_ARCHIVE_FILE_NAME_PART] := IniFile.ReadString( cTEST_PARAMS, cDB_ARCHIVE_FILE_NAME_PART, cDEF_DB_ARCHIVE_FILE_NAME_PART ); Values[cDB_PATH_COPY_TO ] := IniFile.ReadString( cTEST_PARAMS, cDB_PATH_COPY_TO, cDEF_DB_PATH_COPY_TO ); Values[cSCRIPTS_PATH_COPY_FROM ] := IniFile.ReadString( cTEST_PARAMS, cSCRIPTS_PATH_COPY_FROM, cDEF_SCRIPTS_PATH_COPY_FROM ); EndUpdate; end; //Корректируем пути для локальной станции с учётом завершающего слеша TmpPath := TestParams.Values[cERROR_LOG_DIR]; SetDirEndDelimiter( TmpPath ); TestParams.Values[cERROR_LOG_DIR] := TmpPath; TmpPath := TestParams.Values[cDB_PATH_COPY_TO]; SetDirEndDelimiter( TmpPath ); TestParams.Values[cDB_PATH_COPY_TO] := TmpPath; TmpPath := TestParams.Values[cSCRIPTS_PATH_COPY_FROM]; SetDirEndDelimiter( TmpPath ); TestParams.Values[cSCRIPTS_PATH_COPY_FROM] := TmpPath; ScrOnlyExec := TStringList.Create; ScrTestAndExec := TStringList.Create; DbParams := TStringList.Create; //Выполняем тестирование скриптов DBResult := arNone; AppResult := True; n := AllSecNames.Count - 1; ErrScriptChar := TestParams.Values[cERROR_SCRIPT_CHAR]; for i := 0 to n do begin //Получаем параметры тестирования для конкретного файла БД with DBParams do begin BeginUpdate; Values[cUSER ] := IniFile.ReadString( AllSecNames.Strings[i], cUSER, '' ); Values[cPATH ] := IniFile.ReadString( AllSecNames.Strings[i], cPATH, '' ); Values[cSERVER ] := IniFile.ReadString( AllSecNames.Strings[i], cSERVER, '' ); Values[cRENAME ] := IniFile.ReadString( AllSecNames.Strings[i], cRENAME, cDEF_RENAME ); Values[cEXECUTE ] := IniFile.ReadString( AllSecNames.Strings[i], cEXECUTE, cDEF_EXECUTE ); Values[cPASSWORD ] := IniFile.ReadString( AllSecNames.Strings[i], cPASSWORD, '' ); Values[cKEY_EXPR ] := IniFile.ReadString( AllSecNames.Strings[i], cKEY_EXPR, '' ); Values[cFULL_RENAME ] := IniFile.ReadString( AllSecNames.Strings[i], cFULL_RENAME, cDEF_FULL_RENAME ); Values[cSYSTEM_SCRIPT ] := IniFile.ReadString( AllSecNames.Strings[i], cSYSTEM_SCRIPT, '' ); Values[cDB_PATH_BACKUP ] := IniFile.ReadString( AllSecNames.Strings[i], cDB_PATH_BACKUP, '' ); Values[cDEFAULT_DB_FILE_NAME] := IniFile.ReadString( AllSecNames.Strings[i], cDEFAULT_DB_FILE_NAME, cDEF_DEFAULT_DB_FILE_NAME ); EndUpdate; end; //Получаем полный путь к архиву файла БД с учётом завершающего слеша TmpPath := DBParams.Values[cDB_PATH_BACKUP]; SetDirEndDelimiter( TmpPath ); DBParams.Values[cDB_PATH_BACKUP] := TmpPath; //Получаем полный путь к каталогу, содержащему самый "свежий" архив файла БД j := 0; FmtSettings.DateSeparator := cDATE_SEPARATOR; FmtSettings.ShortDateFormat := cFORMAT_DATE_TO_STR; repeat DateBackUp := Now - j; Inc(j); TmpPath := DBParams.Values[cDB_PATH_BACKUP] + DateToStr( DateBackUp, FmtSettings ) + cSEPARATOR_FOLDER_WIN; TmpPath := TmpPath + '*' + TestParams.Values[cDB_ARCHIVE_FILE_NAME_PART] + '*.*'; until ( FileExists( TmpPath ) OR ( j > HighBound ) ); //Проверяем существованиe скриптов и актуального архива файла БД if not( FileExists( TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + cSCRIPTS_MASK ) ) OR ( not FileExists( TmpPath ) AND ( j > HighBound ) ) then begin if AppMode = amWin then MessageDlg( cDB_FILE_NOT_FOUND1 + #13#10 + cDB_FILE_NOT_FOUND2, mtError, [mbOK], 0 ); Continue; end else begin try FindFirst( TmpPath, faAnyFile, FileRec ); DBParams.Values[cDB_PATH_BACKUP] := ExtractFilePath( TmpPath ) + FileRec.Name; finally FindClose( FileRec ); end; end; //Получаем путь к актуальной копии файла БД TmpPath := TestParams.Values[cDB_PATH_COPY_TO] + DBParams.Values[cDEFAULT_DB_FILE_NAME]; if not( FileExists( TmpPath ) ) then begin //Копируем архив файла БД на локальную станцию TmpPath := TestParams.Values[cDB_PATH_COPY_TO] + ExtractFileName( DBParams.Values[cDB_PATH_BACKUP] ); if not( FileExists( TmpPath ) ) then begin stbMain.SimpleText := cCOPYING_FILES; WinCopyFile( DBParams.Values[cDB_PATH_BACKUP], PChar(TmpPath)); stbMain.SimpleText := cSPACE; end; //Раскручиваем файл архива c помощью WinRar.exe Cursor := crHourGlass; stbMain.SimpleText := cEXTRACTING_FILES; CreateMyProcess( PAnsiChar( TestParams.Values[cARCHIVATOR_PATH] ), PAnsiChar( cCOMMAND_LINE_ARCHIVATOR + TmpPath + ' ' + TestParams.Values[cDB_PATH_COPY_TO] ), SW_HIDE ); TmpPath := ExtractFileName( DBParams.Values[cDB_PATH_BACKUP] ); Delete( TmpPath, Pos( ExtractFileExt( TmpPath ), TmpPath ), Length( ExtractFileExt( TmpPath ) ) ); DBParams.Values[cDEFAULT_DB_FILE_NAME] := TmpPath + cSEPARATOR_FOLDER_WIN + DBParams.Values[cDEFAULT_DB_FILE_NAME]; stbMain.SimpleText := cSPACE; Cursor := crDefault; end; //Получаем список имён файлов скриптов, подлежащих только тестированию GetScriptNamesExt ( TestParams.Values[cSCRIPTS_PATH_COPY_FROM], TestParams.Values[cSEPARATOR_CHAR], DBParams.Values[cKEY_EXPR], StrToInt( TestParams.Values[cPREFIX_CHAR_COUNT] ), DateBackUp, ScrOnlyExec ); //Получаем список имён файлов скриптов, подлежащих тестированию и применению GetScriptNames ( TestParams.Values[cSCRIPTS_PATH_COPY_FROM], TestParams.Values[cSEPARATOR_CHAR], DBParams.Values[cKEY_EXPR], StrToInt( TestParams.Values[cPREFIX_CHAR_COUNT] ), ScrTestAndExec ); //Проверяем: существует ли каталог для хранения файлов-отчётов ошибок выполнения скриптов? if not DirExists( TestParams.Values[cERROR_LOG_DIR] ) then ForceDirectories( TestParams.Values[cERROR_LOG_DIR] ); try //Инициализируем переменные AllExecScrOK := True; Cursor := crHourGlass; DBResult := arPrepareSuccess; StrList := TStringList.Create; stbMain.SimpleText := cEXECUTING_SCRIPTS; n := ScrOnlyExec.Count - 1; //Только применяем скрипты for j := 0 to n do begin //Отбрасываем расширение в имени файла скрипта ErrFileName := ExtractFileName( ScrOnlyExec.Strings[j] ); CurIndex := Pos( ExtractFileExt( ErrFileName ), ErrFileName ); Delete( ErrFileName, CurIndex, Length( ExtractFileExt( ErrFileName ) ) ); TmpErrFileName := ErrFileName + '.log'; //Получаем уникальное имя файла-отчёта ошибок применения данного скрипта ErrFileName := ErrScriptChar + DBParams.Values[cKEY_EXPR] + ErrScriptChar + cTEST_EXPR + ErrScriptChar + TmpErrFileName; ErrFileName := TestParams.Values[cERROR_LOG_DIR] + ErrFileName; //Применяем скрипт с помощью утилиты IBEScript.exe к локальной БД CreateMyProcess( PAnsiChar( TestParams.Values[cIBESCRIPT_PATH] ), PAnsiChar( cSCRIPT_EXECUTER_NAME + '"' + TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + ScrOnlyExec.Strings[j] + '"' + cCOMMAND_LINE_SCRIPT_EXEC + '"' + ErrFileName + '"' + ' -D' + TestParams.Values[cSERVER] + ':' + '"' + TestParams.Values[cDB_PATH_COPY_TO] + DBParams.Values[cDEFAULT_DB_FILE_NAME] + '"' + ' -P' + TestParams.Values[cPASSWORD] + ' -U' + TestParams.Values[cUSER] + ' -C' + cCHAR_SET ), SW_HIDE ); StrList.LoadFromFile( ErrFileName ); //Анализируем результат применения скрипта if Pos( cSUCCESS_EXEC_RESULT, StrList.Text ) = 0 then begin DBResult := arPrepareError; AppResult := False; AllExecScrOK := False; Break; end else begin //Удаляем лог-файл для успешно примененённого скрипта DeleteFile( ErrFileName ); end; StrList.Clear; end; //Переходим к тестированию и применению скриптов if AllExecScrOK then begin //Инициализируем переменные Index := 0; Result := True; StrList.Clear; DBResultMsg := ''; FullRename := StrToBool( DBParams.Values[cFULL_RENAME] ); n := ScrTestAndExec.Count - 1; //Выводим на экран строку, расшифровывающую куда применяются скрипты if n >= 0 then begin DBResult := arTestSuccess; with lvwOutput do begin Items.BeginUpdate; Items.Add; CurrItem := Items.Add; CurrItem.SubItems.Add( cDESCRIPTION_STR + DBParams.Values[cPATH] + ' ''' ); Items.Add; Items.EndUpdate; end; end else begin DBResult := arScrNotFound; end; //Тестируем и применяем скрипты for j := 0 to n do begin //Отбрасываем расширение в имени файла скрипта ErrFileName := ExtractFileName( ScrTestAndExec.Strings[j] ); CurIndex := Pos( ExtractFileExt( ErrFileName ), ErrFileName ); Delete( ErrFileName, CurIndex, Length( ExtractFileExt( ErrFileName ) ) ); TmpErrFileName := ErrFileName + '.log'; //Получаем уникальное имя файла-отчёта ошибок тестирования данного скрипта ErrFileName := ErrScriptChar + DBParams.Values[cKEY_EXPR] + ErrScriptChar + cTEST_EXPR + ErrScriptChar + TmpErrFileName; ErrFileName := TestParams.Values[cERROR_LOG_DIR] + ErrFileName; //Тестируем скрипт с помощью утилиты IBEScript.exe на локальной БД CreateMyProcess( PAnsiChar( TestParams.Values[cIBESCRIPT_PATH] ), PAnsiChar( cSCRIPT_EXECUTER_NAME + '"' + TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + ScrTestAndExec.Strings[j] + '"' + cCOMMAND_LINE_SCRIPT_EXEC + '"' + ErrFileName + '"' + ' -D' + TestParams.Values[cSERVER] + ':' + '"' + TestParams.Values[cDB_PATH_COPY_TO] + DBParams.Values[cDEFAULT_DB_FILE_NAME] + '"' + ' -P' + TestParams.Values[cPASSWORD] + ' -U' + TestParams.Values[cUSER] + ' -C' + cCHAR_SET ), SW_HIDE ); StrList.LoadFromFile( ErrFileName ); //Анализируем результат тестирования скрипта if Pos( cSUCCESS_EXEC_RESULT, StrList.Text ) = 0 then begin Result := False; DBResult := arTestError; AppResult := False; CurrResult := False; ScrStatus := scsTestErr; end else begin //Удаляем лог-файл для успешно протестированного скрипта DeleteFile( ErrFileName ); CurrResult := True; ScrStatus := scsTestSucc; end; StrList.Clear; TmpPath := TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + ScrTestAndExec.Strings[j]; //Выполняем скрипт if AllExecScrOK AND StrToBool( DBParams.Values[cEXECUTE] ) then begin if Result then begin //Получаем уникальное имя файла-отчёта ошибок применения данного скрипта ErrFileName := ErrScriptChar + DBParams.Values[cKEY_EXPR] + ErrScriptChar + cEXECUTE_EXPR + ErrScriptChar + TmpErrFileName; ErrFileName := TestParams.Values[cERROR_LOG_DIR] + ErrFileName; //Применяем скрипт CreateMyProcess( PAnsiChar( TestParams.Values[cIBESCRIPT_PATH] ), PAnsiChar( cSCRIPT_EXECUTER_NAME + '"' + TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + ScrTestAndExec.Strings[j] + '"' + cCOMMAND_LINE_SCRIPT_EXEC + '"' + ErrFileName + '"' + ' -D' + DBParams.Values[cSERVER] + ':' + '"' + DBParams.Values[cPATH] + '"' + ' -P' + DBParams.Values[cPASSWORD] + ' -U' + DBParams.Values[cUSER] + ' -C' + cCHAR_SET ), SW_HIDE ); StrList.LoadFromFile( ErrFileName ); //Анализируем результат применения скрипта if Pos( cSUCCESS_EXEC_RESULT, StrList.Text ) = 0 then begin DBResult := arExecError; AppResult := False; ScrStatus := scsExecErr; end else begin //Удаляем лог-файл для успешно применённого скрипта ScrStatus := scsExecSucc; DeleteFile( ErrFileName ); end; StrList.Clear; Index := j; end; //Переименовываем файл скрипта if StrToBool( DBParams.Values[cRENAME] ) AND ( ( Index + 1 ) >= j ) then begin if not Result then FullRename := False; RenameScript( TmpPath, DBParams.Values[cKEY_EXPR], TestParams.Values[cSEPARATOR_CHAR], TestParams.Values[cERROR_SCRIPT_CHAR], Result, FullRename, StrToInt( TestParams.Values[cPREFIX_CHAR_COUNT] ) ); RenameFile( TestParams.Values[cSCRIPTS_PATH_COPY_FROM] + ScrTestAndExec.Strings[j], TmpPath ); end; end; //Выводим отчёт о применении отдельного скрипта на экран with lvwOutput do begin Items.BeginUpdate; CurrItem := Items.Add; CurrItem.Caption := IntToStr( j + 1 ); CurrItem.SubItems.Add( ExtractFileName( TmpPath ) ); CurrItem.SubItems.Add( GetScriptStatus( ScrStatus ) ); Items.EndUpdate; end; end; end; //Получаем сообщение о результатах тестирования и применения скриптов для данной БД case DBResult of arPrepareError : begin DBResultMsg := cPREPARE_SCRIPT_ERR; end; arScrNotFound : begin DBResultMsg := cSCRIPTS_NOT_FOUND; end; arTestSuccess : begin if StrToBool( DBParams.Values[cEXECUTE] ) then begin DBResultMsg := cEXECUTE_SCRIPT_STR; ExecSysScrResult := False; //Вливаем системный скрипт, не выполнив предварительно КАКИХ-ЛИБО проверок{Личное указание Смоктия К.В.} if FileExists( DBParams.Values[cSYSTEM_SCRIPT] ) then begin ErrFileName := TestParams.Values[cERROR_LOG_DIR] + ErrScriptChar + DBParams.Values[cKEY_EXPR] + ErrScriptChar + cSYSTEM_SCRIPT_ERROR_FILE_NAME; CreateMyProcess( PAnsiChar( TestParams.Values[cIBESCRIPT_PATH] ), PAnsiChar( cSCRIPT_EXECUTER_NAME + '"' + DBParams.Values[cSYSTEM_SCRIPT] + '"' + cCOMMAND_LINE_SCRIPT_EXEC + '"' + ErrFileName + '"' + ' -D' + TestParams.Values[cSERVER] + ':' + '"' + TestParams.Values[cDB_PATH_COPY_TO] + DBParams.Values[cDEFAULT_DB_FILE_NAME] + '"' + ' -P' + TestParams.Values[cPASSWORD] + ' -U' + TestParams.Values[cUSER] + ' -C' + cCHAR_SET ), SW_HIDE ); StrList.Clear; StrList.LoadFromFile( ErrFileName ); //Анализируем результат применения системного скрипта if Pos( cSUCCESS_EXEC_RESULT, StrList.Text ) = 0 then begin ExecSysScrMsg := cEXEC_SYS_SCRIPT_STR_ERR; end else begin //Удаляем лог-файл для успешно применённого системного скрипта ExecSysScrMsg := cEXEC_SYS_SCRIPT_STR_SUCC; ExecSysScrResult := True; DeleteFile( ErrFileName ); end; end else begin ExecSysScrMsg := cEXEC_SYS_SCRIPT_STR_ERR + #13 + 'File ''' + DBParams.Values[cSYSTEM_SCRIPT] + ''' not found!'; end; end else begin DBResultMsg := cTEST_SCRIPT_STR; ExecSysScrMsg := cDONT_EXEC_SYS_SCRIPT_STR; ExecSysScrResult := True; end; end; arTestError, arExecError : begin if DBResult = arTestError then DBResultMsg := cTEST_SCRIPT_STR_ERR else DBResultMsg := cEXECUTE_SCRIPT_STR_ERR; end; end; //Оповещаем пользователя о результатах тестирования и применения скриптов для данной БД with lvwOutput do begin Items.BeginUpdate; Items.Add; CurrItem := Items.Add; CurrItem.SubItems.Add( DBResultMsg ); Items.Add; Items.EndUpdate; end; finally StrList.Free; end; stbMain.SimpleText := cSPACE; Cursor := crDefault; ScrOnlyExec.Clear; ScrTestAndExec.Clear; DBParams.Clear; end; //Оповещаем пользователя о результатах работы приложения if AppResult then begin MessageDlg( cAPP_RESULT_OK_MSG, mtInformation, [mbOK], 0 ); end else begin lvwOutput.Color := clRed; MessageDlg( cAPP_RESULT_ERR_MSG, mtError, [mbOK], 0 ); end; //Оповещаем пользователя о результатах применения системного скрипта if DBResult = arTestSuccess then begin if ExecSysScrResult then begin MessageDlg( ExecSysScrMsg, mtInformation, [mbOK], 0 ); end else begin MessageDlg( ExecSysScrMsg, mtError, [mbOK], 0 ); end; end; //Завершаем работу приложения в режиме коммандной строки if AppMode = amCmd then Close; end else begin if AppMode = amCmd then Close else mnuStart.Enabled := False; MessageDlg( cINI_FILE_WAS_REMOVED, mtWarning, [mbOK], 0 ); end; finally IniFile.Free; ScrOnlyExec.Free; ScrTestAndExec.Free; DbParams.Free; TestParams.Free; AllSecNames.Free; UselessSecNames.Free; stbMain.SimpleText := cSPACE; end; except LogException( ExtractFilePath( Application.ExeName ) + cERROR_FILE_NAME ); Raise; end; except on E: EInOutError do begin MessageDlg( E.Message + ' ' + SysErrorMessage( E.ErrorCode ), mtError, [mbOK], 0 ); if AppMode = amCmd then Close; end; on E: EConvertError do begin MessageDlg( cCONVERT_ERROR + E.Message, mtError, [mbOK], 0 ); if AppMode = amCmd then Close; end; else begin ShowException( ExceptObject, ExceptAddr ); if AppMode = amCmd then Close; end; end; end; procedure TfmMain.mnuCreateTestListClick(Sender: TObject); begin MessageDlg( 'Coming soon...', mtInformation, [mbOK], 0 ); end; procedure TfmMain.mnuOptionsClick(Sender: TObject); begin MessageDlg( 'Coming soon...', mtInformation, [mbOK], 0 ); end; end.
unit rtti_serializer_uManager; interface uses SysUtils, rtti_broker_iBroker, rtti_broker_uData, fgl, rtti_serializer_uFactory, rtti_serializer_uSerialObject; //type { TSerialManager } //TSerialManager = class(TInterfacedObject, ISerialManager) //private // const // cCounterID = 0; //private type // // { TCounter } // // TCounter = class(TRBCustomIDObject) // private // fIDCounter: integer; // function GetIDCounter: integer; // procedure SetIDCounter(AValue: integer); // public // constructor Create; override; // function NewID: integer; // published // property IDCounter: integer read GetIDCounter write SetIDCounter; // end; // //private // fFactory: ISerialFactory; // fStore: ISerialStore; // fCounter: TCounter; //protected // procedure Save(AData: TObject); // function Load(const AClass: string; const AID: integer; ACanCreate: Boolean = True): TObject; overload; // function Load(const AClass: TClass; const AID: integer; ACanCreate: Boolean = True): TObject; overload; // function New(const AClass: string): TObject; overload; // function New(const AClass: TClass): TObject; overload; // function New(const AClass: string; const AID: integer): TObject; overload; // function New(const AClass: TClass; const AID: integer): TObject; overload; // function Exists(const AID: integer): Boolean; // function LoadList(const AClass: string): ISerialList; // function NewID: integer; // procedure Flush; // procedure RegisterClass(const AClass: TClass); //public // constructor Create(const AConnection: string); // destructor Destroy; override; //end; implementation type { ESerialException } ESerialException = class(Exception) public class procedure ClassNotRegistered(const AClassName: string); class procedure ClassAlreadyRegistered(const AClassName: string); class procedure ObjectAlreadyExistsInCache(const AClass, AName: string; AID: integer); class procedure TryLoadObjectWithNotExistsID(const AClass: string; AID: integer); class procedure TryCreateObjectWhichDoNotHaveID(const AClass: string; AID: integer); end; { ESerialException } class procedure ESerialException.ClassNotRegistered(const AClassName: string); begin raise ESerialException.CreateFmt('Cannot create object - class %s is not registered', [AClassName]); end; class procedure ESerialException.ClassAlreadyRegistered(const AClassName: string); begin raise ESerialException.CreateFmt('Class %s is already registered', [AClassName]); end; class procedure ESerialException.ObjectAlreadyExistsInCache(const AClass, AName: string; AID: integer); begin raise ESerialException.CreateFmt('Object %s.%s (ID=%d) already exists in cache', [AClass, AName, AID]); end; class procedure ESerialException.TryLoadObjectWithNotExistsID(const AClass: string; AID: integer); begin raise ESerialException.CreateFmt('Try load not exists object of %s with ID=%d', [AClass, AID]); end; class procedure ESerialException.TryCreateObjectWhichDoNotHaveID( const AClass: string; AID: integer); begin raise ESerialException.CreateFmt('Try create object of %s with ID=%d, but %s do not have ID property', [AClass, AID, AClass]); end; //{ TSerialManager.TCounter } // //function TSerialManager.TCounter.GetIDCounter: integer; //begin // Result := fIDCounter; //end; // //procedure TSerialManager.TCounter.SetIDCounter(AValue: integer); //begin // fIDCounter := AValue; //end; // //constructor TSerialManager.TCounter.Create; //begin // fIDCounter := 0; // ID := cCounterID; //end; // //function TSerialManager.TCounter.NewID: integer; //begin // inc(fIDCounter); // Result := fIDCounter; //end; // //{ TSerialManager } // //procedure TSerialManager.Save(AData: TObject); //begin // fStore.Save(AData as IRBData); //end; // //function TSerialManager.Load(const AClass: string; const AID: integer; // ACanCreate: Boolean = True): TObject; //begin // if fFactory.Exists(AID) then begin // Result := fFactory.Get(AID); // end else if fStore.Exists(AID) then begin // Result := fFactory.New(AClass, AID); // fStore.Load(Result as IRBData); // end else if ACanCreate then begin // Result := fFactory.New(AClass, AID); // end else begin // ESerialException.TryLoadObjectWithNotExistsID(AClass, AID); // end; //end; // //function TSerialManager.Load(const AClass: TClass; const AID: integer; // ACanCreate: Boolean = True): TObject; //begin // Result := Load(AClass.ClassName, AID, ACanCreate); //end; // //function TSerialManager.New(const AClass: string): TObject; //begin // if fFactory.IsIDClass(AClass) then // Result := fFactory.New(AClass, NewID) // else // Result := fFactory.New(AClass); //end; // //function TSerialManager.New(const AClass: TClass): TObject; //begin // Result := New(AClass.ClassName); //end; // //function TSerialManager.New(const AClass: string; const AID: integer): TObject; //begin // if not fFactory.IsIDClass(AClass) then // ESerialException.TryCreateObjectWhichDoNotHaveID(AClass, AID); // Result := fFactory.New(AClass, AID); //end; // //function TSerialManager.New(const AClass: TClass; const AID: integer): TObject; //begin // Result := New(AClass.ClassName, AID); //end; // //function TSerialManager.Exists(const AID: integer): Boolean; //begin // Result := fFactory.Exists(AID); // if not Result then // Result := fStore.Exists(AID); //end; // //function TSerialManager.LoadList(const AClass: string): ISerialList; //begin // Result := TSerialList.Create(AClass); // fStore.LoadList(Result); //end; // //function TSerialManager.NewID: integer; //begin // if fCounter = nil then // Result := -1 // else // Result := fCounter.NewID; //end; // //procedure TSerialManager.Flush; //begin // fStore.Flush; //end; // //procedure TSerialManager.RegisterClass(const AClass: TClass); //begin // fFactory.RegisterClass(AClass); //end; // //constructor TSerialManager.Create(const AConnection: string); //begin // fFactory := TSerialFactory.Create; // fStore := TXmlStore.Create(fFactory, AConnection); // //counter will not registry // fCounter := TCounter.Create; // fCounter.ID := cCounterID; // fStore.Load(fCounter as IRBData); //end; // //destructor TSerialManager.Destroy; //begin // fStore.Save(fCounter as IRBData); // fStore := nil; // FreeAndNil(fCounter); // not in cache // inherited Destroy; //end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Menus, Dialogs, ExtDlgs, LrProject, ImgList, PngImageList; type TMainForm = class(TForm) TreePopup: TPopupMenu; NewFolder1: TMenuItem; AddItem1: TMenuItem; OpenPictureDialog: TOpenPictureDialog; TreeImages: TPngImageList; N1: TMenuItem; AddServer1: TMenuItem; AddDatabase1: TMenuItem; procedure FormCreate(Sender: TObject); procedure NewFolder1Click(Sender: TObject); procedure AddItem1Click(Sender: TObject); procedure AddServer1Click(Sender: TObject); procedure AddDatabase1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } function GetFolderItem(inItem: TLrProjectItem): TLrProjectItem; function GetSelectedFolderItem: TLrProjectItem; procedure ProjectCanDrag(inItem: TLrProjectItem; var inAllowed: Boolean); procedure ProjectCanDrop(inDragItem, inDropItem: TLrProjectItem; inShift: TShiftState; var inAccept: Boolean); procedure ProjectCanEdit(inItem: TLrProjectItem; var inAllowed: Boolean); procedure ProjectDragDrop(inDragItem, inDropItem: TLrProjectItem; inShift: TShiftState); procedure ProjectNewText(inItem: TLrProjectItem; const inNewText: WideString); public { Public declarations } procedure BuildSampleProject; end; var MainForm: TMainForm; implementation uses JPEG, LrVclUtils, LrTreeData, LrProjectView, Servers; {$R *.dfm} type TVirtualItem = class(TLrProjectItem) end; // TCustomItem = class(TLrProjectItem) private FItem: TVirtualItem; protected function GetCount: Integer; override; function GetItems(inIndex: Integer): TLrTreeLeaf; override; public constructor Create; override; destructor Destroy; override; end; // TCustomProject = class(TLrProject) protected procedure CreateNodes; procedure SaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); override; public Dbs: TLrProjectItem; Servers: TLrProjectItem; constructor Create; override; procedure LoadFromFile(const inFilename: string); override; procedure SaveToFile(const inFilename: string); override; end; { TCustomItem } constructor TCustomItem.Create; begin inherited; FItem := TVirtualItem.Create; end; destructor TCustomItem.Destroy; begin FItem.Free; inherited; end; function TCustomItem.GetCount: Integer; begin Result := 3; end; function TCustomItem.GetItems(inIndex: Integer): TLrTreeLeaf; begin FItem.ImageIndex := ImageIndex; FItem.DisplayName := 'Custom Item #' + IntToStr(inIndex + 1); Result := FItem; end; { TCustomProject } constructor TCustomProject.Create; begin inherited; Items.OnSaveItem := SaveItem; CreateNodes; end; procedure TCustomProject.CreateNodes; begin Servers := TLrProjectItem.Create; Items.Add(Servers); Servers.ImageIndex := 4; Servers.DisplayName := 'Servers'; Servers.ComponentIndex := 0; // Dbs := TLrProjectItem.Create; Items.Add(Dbs); Dbs.ImageIndex := 6; Dbs.DisplayName := 'Databases'; Dbs.ComponentIndex := 1; end; procedure TCustomProject.LoadFromFile(const inFilename: string); begin // Servers.Free; // Dbs.Free; inherited; // Servers := TLrProjectItem(Items[0]); // Dbs := TLrProjectItem(Items[1]); CreateNodes; Servers.LoadFromFile(inFilename + 'servers'); Dbs.LoadFromFile(inFilename + 'dbs'); end; procedure TCustomProject.SaveItem(inSender: TLrTreeLeaf; inIndex: Integer; var inAllow: Boolean); begin inAllow := (inSender <> Items) or (inIndex > 1); end; procedure TCustomProject.SaveToFile(const inFilename: string); begin inherited; Servers.SaveToFile(inFilename + 'servers'); Dbs.SaveToFile(inFilename + 'dbs'); end; var Project: TCustomProject; function GetProjectFilename: string; begin Result := ExtractFilePath(Application.ExeName) + 'Sample.project.txt'; end; { TMainForm } procedure TMainForm.FormCreate(Sender: TObject); begin Project := TCustomProject.Create; // if not FileExists(GetProjectFilename) then BuildSampleProject else Project.LoadFromFile(GetProjectFilename); // LrAddForm(LrProjectForm, TLrProjectForm, Self); LrProjectForm.Project := Project; LrProjectForm.Tree.Images := TreeImages; LrProjectForm.Tree.PopupMenu := TreePopup; LrProjectForm.OnCanDrag := ProjectCanDrag; LrProjectForm.OnCanDrop := ProjectCanDrop; LrProjectForm.OnDragDrop := ProjectDragDrop; LrProjectForm.OnCanEdit := ProjectCanEdit; LrProjectForm.OnNewText := ProjectNewText; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Project.SaveToFile(GetProjectFilename); end; procedure TMainForm.BuildSampleProject; var folder: TLrFolderItem; item: TLrProjectItem; begin Project := TCustomProject.Create; // folder := TLrFolderItem.Create; folder.Source := 'C:\Program Files\RemObjects Software\Chrome\Samples\ClassRefs'; Project.Items.Add(folder); // item := TLrProjectItem.Create; item.Source := 'C:\Program Files\RemObjects Software\Chrome\Samples\ClassRefs\ClassRefs.chrome'; item.ImageIndex := 1; folder.Add(item); // item := TLrProjectItem.Create; item.Source := 'C:\Program Files\RemObjects Software\Chrome\Samples\ClassRefs\AssemblyInfo.pas'; item.ImageIndex := 1; folder.Add(item); // item := TCustomItem.Create; item.Source := 'Custom Node'; item.ImageIndex := 3; Project.Items.Add(item); // folder := TLrFolderItem.Create; folder.Source := 'D:\Pictures\Named\Andrea'; Project.Items.Add(folder); // item := TLrProjectItem.Create; item.Source := 'D:\Pictures\Named\Andrea\028.jpg'; item.ImageIndex := 2; folder.Add(item); // item := TLrProjectItem.Create; item.Source := 'D:\Pictures\Named\Andrea\075.jpg'; item.ImageIndex := 2; folder.Add(item); end; function TMainForm.GetFolderItem(inItem: TLrProjectItem): TLrProjectItem; begin Result := inItem; while (Result <> nil) and not (Result is TLrFolderItem) do Result := TLrProjectItem(Result.Parent); if Result = nil then Result := Project.Items; end; function TMainForm.GetSelectedFolderItem: TLrProjectItem; begin Result := GetFolderItem(LrProjectForm.SelectedItem); end; procedure TMainForm.ProjectCanDrag(inItem: TLrProjectItem; var inAllowed: Boolean); begin inAllowed := not (inItem is TVirtualItem); end; procedure TMainForm.ProjectCanDrop(inDragItem, inDropItem: TLrProjectItem; inShift: TShiftState; var inAccept: Boolean); begin inAccept := (inDropItem = nil) or not (inDropItem is TVirtualItem); end; procedure TMainForm.ProjectDragDrop(inDragItem, inDropItem: TLrProjectItem; inShift: TShiftState); var folder: TLrProjectItem; begin Project.Items.BeginUpdate; try folder := GetFolderItem(TLrProjectItem(inDragItem.Parent)); folder.Remove(inDragItem); folder := GetFolderItem(inDropItem); folder.Add(inDragItem); finally Project.Items.EndUpdate; end; end; procedure TMainForm.ProjectCanEdit(inItem: TLrProjectItem; var inAllowed: Boolean); begin inAllowed := (inItem is TLrFolderItem); end; procedure TMainForm.ProjectNewText(inItem: TLrProjectItem; const inNewText: WideString); begin inItem.Source := inNewText; end; procedure TMainForm.NewFolder1Click(Sender: TObject); var folder: TLrFolderItem; begin folder := TLrFolderItem.Create; folder.Source := 'New Folder'; GetSelectedFolderItem.Add(folder); end; procedure TMainForm.AddItem1Click(Sender: TObject); var item: TLrProjectItem; begin if OpenPictureDialog.Execute then begin item := TLrProjectItem.Create; item.Source := OpenPictureDialog.Filename; item.ImageIndex := 2; GetSelectedFolderItem.Add(item); end; end; function GetGuid: string; var guid: TGUID; begin CreateGUID(guid); Result := GUIDToString(guid); end; procedure TMainForm.AddServer1Click(Sender: TObject); var item: TServerItem; begin item := TServerItem.Create; item.ImageIndex := 5; item.Host := GetGuid; item.Name := Project.Servers.GetUniqueName('server'); Project.Servers.Add(item); end; procedure TMainForm.AddDatabase1Click(Sender: TObject); var item: TServerItem; begin item := TServerItem.Create; item.ImageIndex := 7; item.Host := GetGuid; Project.Dbs.Add(item); end; initialization RegisterClass(TVirtualItem); RegisterClass(TCustomItem); end.
//====================================================================================================================// //======================================= THE COMMON PASCAL AST PARSER CLASS =========================================// //====================================================================================================================// unit AST.Pascal.Parser; interface {$I compilers.inc} uses SysUtils, Math, Classes, StrUtils, Types, IOUtils, Generics.Collections, AST.Lexer.Delphi, AST.Delphi.Classes, AST.Delphi.DataTypes, AST.Lexer, AST.Delphi.Operators, AST.Parser.Utils, AST.Parser.Messages, AST.Parser.Contexts, AST.Delphi.Contexts, AST.Classes, AST.Parser.Options, AST.Intf, AST.Pascal.Intf; type TPascalUnit = class; TUnitSection = (usInterface, usImplementation); {parse members context - контекст парсинга выражений вид a.b.c или a[1, 2, 3].b...} TPMContext = record private FCnt: Integer; // кол-во элементов в выражении FItems: TIDExpressions; // элементы цепочки function GetLast: TIDExpression; inline; public ID: TIdentifier; // текущий идентификатор ItemScope: TScope; // текущий scope DataType: TIDType; // результатирующий тип цепочки выражений property Items: TIDExpressions read FItems; property Count: Integer read FCnt; property Last: TIDExpression read GetLast; procedure Init; inline; procedure Add(const Expr: TIDExpression); procedure Clear; end; TUnits = TList<TObject>; TTypes = TList<TIDType>; TIDDeclarationList = TList<TIDDeclaration>; TCondIFValue = (condIFFalse, condIfTrue, condIFUnknown); TASTArgMatchLevel = ( MatchNone, // doesn't match at all MatchImplicitCallAndDataLoss, // matches using implicit operator call and possible data loss MatchImplicitAndDataLoss, // matches using implicit cast and possible data loss MatchImplicitCall, // matches using implicit operator call MatchImplicit, // matches using implicit cast (minimally matches) MatchGeneric, // matches strictly using generic instantiation MatchStrict // matches strictly ); TASTArgMatchInfo = record Level: TASTArgMatchLevel; Rate: TASTArgMatchRate; end; PASTArgMatchInfo = ^TASTArgMatchInfo; TASTArgsMachItems = array of TASTArgMatchInfo; TASTProcMatchItem = record ArgsInfo: TASTArgsMachItems; Decl: TIDProcedure; TotalRate: Integer; end; PASTProcMatchItem = ^TASTProcMatchItem; TUnitState = ( UnitNotCompiled, UnitIntfCompiled, UnitAllCompiled, UnitCompileFailed ); TASTProcMachArray = array of TASTProcMatchItem; TPascalUnit = class(TASTModule) type TVarModifyPlace = (vmpAssignment, vmpPassArgument); TIdentifiersPool = TPool<TIdentifier>; private fID: Integer; // ID модуля в пакете fLexer: TDelphiLexer; fIntfScope: TScope; // interface scope fImplScope: TScope; // implementation scope fIntfImportedUnits: TUnitList; fImplImportedUnits: TUnitList; fMessages: ICompilerMessages; fVarSpace: TVarSpace; fProcSpace: TProcSpace; fTypeSpace: TTypeSpace; fConsts: TConstSpace; // список нетривиальных констант (массивы, структуры) function GetMessagesText: string; protected fCompiled: TCompilerResult; fUnitState: TUnitState; fUnitName: TIdentifier; // the Unit declaration name fSysUnit: TASTModule; fProcMatches: TASTProcMachArray; ////////////////////////////////////////////////////////////////////////////////////////////////////////// function FindPublicDecl(const Name: string): TIDDeclaration; function GetPublicClass(const Name: string): TIDClass; function GetPublicType(const Name: string): TIDType; function GetModuleName: string; override; procedure SetUnitName(const Name: string); public //====================================================================================================================================== procedure AddType(const Decl: TIDType); inline; procedure AddConstant(const Decl: TIDConstant); inline; property Lexer: TDelphiLexer read fLexer; property SysUnit: TASTModule read fSysUnit; //////////////////////////////////////////////////////////////////////////// constructor Create(const Project: IASTProject; const FileName: string; const Source: string = ''); override; constructor CreateFromFile(const Project: IASTProject; const FileName: string); override; destructor Destroy; override; //////////////////////////////////////////////////////////////////////////// procedure SaveConstsToStream(Stream: TStream); // сохраняет сложные константы модуля procedure SaveMethodBodies(Stream: TStream); // сохраняет тела всех методов модуля procedure SaveDeclToStream(Stream: TStream); // сохраняет все декларации модуля procedure SaveBodyToStream(Stream: TStream); // сохраняет тела всех глобальных процедур модуля procedure SaveTypesToStream(Stream: TStream); // сохраняет все типы модуля function Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean = True): TCompilerResult; virtual; function CompileIntfOnly: TCompilerResult; virtual; function UsedUnit(const UnitName: string): Boolean; function GetDefinesAsString: string; property _ID: TIdentifier read FUnitName; property UnitID: Integer read FID write FID; property Messages: ICompilerMessages read FMessages; property MessagesText: string read GetMessagesText; property IntfScope: TScope read FIntfScope; // Interface section scope property ImplScope: TScope read FImplScope; // Implementation section scope property IntfImportedUnits: TUnitList read fIntfImportedUnits; property ImplImportedUnits: TUnitList read fImplImportedUnits; property Compiled: TCompilerResult read FCompiled; property TypeSpace: TTypeSpace read FTypeSpace; property VarSpace: TVarSpace read FVarSpace; property ProcSpace: TProcSpace read FProcSpace; property ConstSpace: TConstSpace read FConsts; property UnitState: TUnitState read fUnitState; end; implementation { TCompiler } uses AST.Delphi.System, AST.Parser.Errors, AST.Pascal.Project, AST.Pascal.ConstCalculator; procedure TPascalUnit.SetUnitName(const Name: string); begin FUnitName.Name := Name; end; function TPascalUnit.Compile(ACompileIntfOnly: Boolean; RunPostCompile: Boolean = True): TCompilerResult; begin Result := TCompilerResult.CompileInProgress; FCompiled := Result; fSysUnit := (Project as IASTPascalProject).SysUnit; // add system unit implicitly if Assigned(fSysUnit) and (Self <> fSysUnit) then fIntfImportedUnits.AddObject('system', fSysUnit); end; function TPascalUnit.CompileIntfOnly: TCompilerResult; begin Result := TCompilerResult.CompileFail; end; constructor TPascalUnit.Create(const Project: IASTProject; const FileName: string; const Source: string = ''); begin inherited Create(Project, FileName, Source); fSysUnit := (Project as IASTPascalProject).SysUnit; fLexer := TDelphiLexer.Create(Source); FMessages := TCompilerMessages.Create; //FVisibility := vPublic; var AUnitName := StringReplace(ExtractFileName(FileName), '.pas', '', []); FIntfImportedUnits := TUnitList.Create; FImplImportedUnits := TUnitList.Create; FIntfScope := TInterfaceScope.Create(Self, @FVarSpace, @FProcSpace); {$IFDEF DEBUG}FIntfScope.Name := AUnitName + '$intf_scope';{$ENDIF} FImplScope := TImplementationScope.Create(FIntfScope); {$IFDEF DEBUG}FImplScope.Name := AUnitName + '$impl_scope';{$ENDIF} //FBENodesPool := TBENodesPool.Create(16); // pre allocate 8 items by 8 args SetLength(fProcMatches, 8); for var i := 0 to Length(fProcMatches) - 1 do SetLength(fProcMatches[i].ArgsInfo, 8); // FOptions := TCompilerOptions.Create(Package.Options); // // fCondStack := TSimpleStack<Boolean>.Create(0); // fCondStack.OnPopError := procedure begin ERROR_INVALID_COND_DIRECTIVE() end; end; constructor TPascalUnit.CreateFromFile(const Project: IASTProject; const FileName: string); var Stream: TStringStream; begin Stream := TStringStream.Create(); try Stream.LoadFromFile(FileName); Create(Project, FileName, Stream.DataString); finally Stream.Free; end; end; destructor TPascalUnit.Destroy; begin FIntfScope.Free; FImplScope.Free; fLexer.Free; FIntfImportedUnits.Free; FImplImportedUnits.Free; inherited; end; function TPascalUnit.FindPublicDecl(const Name: string): TIDDeclaration; begin Result := fIntfScope.FindID(Name); end; function TPascalUnit.UsedUnit(const UnitName: string): Boolean; var i: Integer; begin i := FIntfImportedUnits.IndexOf(UnitName); if i > 0 then Exit(True); i := FImplImportedUnits.IndexOf(UnitName); if i > 0 then Exit(True) else Exit(False); end; procedure TPascalUnit.AddConstant(const Decl: TIDConstant); var Item: TIDConstant; begin Item := FConsts.First; while Assigned(Item) do begin if Item = Decl then Exit else Break; Item := TIDConstant(Item.NextItem); end; FConsts.Add(Decl); end; procedure TPascalUnit.AddType(const Decl: TIDType); begin if not (Decl is TIDAliasType) and not Decl.IsPooled then begin FTypeSpace.Add(Decl); Decl.IsPooled := True; end; end; function TPascalUnit.GetMessagesText: string; begin Result := FMessages.GetAsString; end; function TPascalUnit.GetModuleName: string; begin Result := fUnitName.Name; if Result = '' then Result := ChangeFileExt(inherited GetModuleName(), ''); end; function TPascalUnit.GetPublicClass(const Name: string): TIDClass; var Res: TIDDeclaration; begin Res := FindPublicDecl(Name); Result := Res as TIDClass; end; function TPascalUnit.GetPublicType(const Name: string): TIDType; var Res: TIDDeclaration; begin Res := FindPublicDecl(Name); Result := Res as TIDType; end; {parser methods} procedure TPascalUnit.SaveConstsToStream(Stream: TStream); begin Assert(False); end; procedure TPascalUnit.SaveMethodBodies(Stream: TStream); begin Assert(False); end; procedure TPascalUnit.SaveTypesToStream(Stream: TStream); begin Assert(False); end; procedure TPascalUnit.SaveDeclToStream(Stream: TStream); begin Assert(False); end; procedure TPascalUnit.SaveBodyToStream(Stream: TStream); begin Assert(False); end; { TPMContext } procedure TPMContext.Add(const Expr: TIDExpression); begin SetLength(FItems, FCnt + 1); FItems[FCnt] := Expr; Inc(FCnt); end; procedure TPMContext.Clear; begin FItems := nil; FCnt := 0; end; function TPMContext.GetLast: TIDExpression; begin if FCnt > 0 then Result := FItems[FCnt - 1] else Result := nil; end; procedure TPMContext.Init; begin FCnt := 0; DataType := nil; end; function TPascalUnit.GetDefinesAsString: string; begin // Result := FDefines.Text; end; initialization FormatSettings.DecimalSeparator := '.'; end.
(* ╔═══════════════════════════════════════════════════════════════════════════════════════════════════════╗ ║ This is a custom wrapper for DOM manipulation. This library utilizes most edge and high-performance ║ ║ methods for DOM manipulation. You don't need to learn something new, its usage is very simple because ║ ║ it has the same syntax as well known jQuery library with support of the most popular and widely used ║ ║ methods and jQuery-like chaining. ║ ║ by warleyalex ║ ╚═══════════════════════════════════════════════════════════════════════════════════════════════════════╝ } *) unit uDOM; {$MODE objfpc} {$MODESWITCH externalclass} interface uses Types, Web, JS, Classes, SysUtils {, libjquery}; type JDom7TopLeft = class external name 'Dom7TopLeft' top, left: integer; end; type JDom7 = class; //TCallback = Procedure (args : JSValue); //TCallbackEvent = Procedure (args : JSValue); (* type TCallbacks = class external name 'Callbacks' Public function add(aCallBack : TCallBack) : TCallbacks; function add(aCallBack : Array of TCallBack) : TCallbacks; function add(aCallBack : TCallBackEvent) : TCallbacks; function add(aCallBack : Array of TCallBackEvent) : TCallbacks; function disable : TCallBacks; function disabled : Boolean; function empty : TCallBacks; function fire(arguments : JSValue) : TCallbacks; varargs; function fired : Boolean; function fireWith(context : JSValue; arguments : JSValue) : TCallbacks; function has(aCallBack : TCallBack) : Boolean; function has(aCallBack : TCallBackEvent) : Boolean; function lock : TCallBacks; function locked : boolean; function remove(aCallBack : TCallBack) : TCallbacks; function remove(aCallBack : Array of TCallBack) : TCallbacks; function remove(aCallBack : TCallBackEvent) : TCallbacks; function remove(aCallBack : Array of TCallBackEvent) : TCallbacks; end;*) { JDom7 } JDom7AddClassHandler = reference to function(aIndex: Integer; AClass: string): string; JDom7AttrHandler = reference to function(aIndex: Integer; aAttr: string): JSValue; JDom7CSSHandler = reference to function(aIndex: Integer; AClass: string): JSValue; JDom7EachHandler = reference to function(aIndex: Integer; AElement: TJSElement): Boolean; JDom7FilterHandler = reference to function(aIndex: Integer; AElement: TJSElement): Boolean; JDom7HeightHandler = reference to function(aIndex: Integer; AHeight: jsValue): JSValue; JDom7HTMLHandler = reference to function(aIndex: Integer; aHTML: string): string; //JDom7MapHandler = Reference to Function (aIndex : Integer; AElement : TJSElement) : TJSObject; JDom7OffsetHandler = reference to function(aIndex: Integer; aCoords: JDom7TopLeft): JDom7TopLeft; JDom7PropHandler = reference to function(aIndex: Integer; oldProp: JSValue): JSValue; //JDom7QueueHandler = Reference to procedure; JDom7TextHandler = reference to function(aIndex: Integer; aString: string): string; JDom7ToggleClassHandler = reference to function(aIndex: Integer; aClassName: string; AState: Boolean): string; JDom7ValHandler = reference to function(aIndex: integer; aValue: string): string; JDom7WidthHandler = reference to function(aIndex: Integer; AHeight: jsValue): JSValue; JDom7DeQueueFunction = reference to procedure; //JDom7AddQueueHandler = Reference to Procedure (aFunc : JDom7DeQueueFunction); //TAjaxEvent = class external name 'AjaxEvent' (TJSEvent); TDeferredDoneHandler = reference to function: Boolean; JDom7Deferred = class external name 'Deferred'(TJSObject) public function done(aHandler: TDeferredDoneHandler): JDom7Deferred; overload; function done(aHandlers: array of TDeferredDoneHandler): JDom7Deferred; overload; end; TJQXHR = class; TJQXHRDoneHandler = reference to function(aData: jsValue; textStatus: string; aJQXHR: TJQXHR): boolean; TJQXHRFailHandler = reference to function(aJQXHR: TJQXHR; textStatus: string; AErrorThrown: jsValue): boolean; TJQXHRAlwaysHandler = reference to function(arg1: TJSObject; textStatus: string; arg2: TJSObject): boolean; TJQXHR = class external name 'jqXHR'(JDom7Deferred) private FReadyState: NativeInt; external name 'readyState'; //FResponse: JSValue; external name 'response'; FResponseText: string; external name 'responseText'; FresponseXML: TJSDocument; external name 'responseXML'; //FUpload: TJSXMLHttpRequestUpload; external name 'upload'; FStatus: NativeInt; external name 'status'; FStatusText: string; external name 'statustext'; public function getResponseHeader(aName: string): string; function getAllResponseHeaders: string; procedure overrideMimeType(aType: string); procedure setRequestHeader(aName, AValue: string); procedure done(aHandler: TJQXHRDoneHandler); overload; procedure always(aHandler: TJQXHRAlwaysHandler); overload; procedure fail(aHandler: TJQXHRFailHandler); overload; procedure _then(aSuccess: TJQXHRDoneHandler; aFail: TJQXHRFailHandler); overload; procedure abort; procedure abort(AStatusText: string); property readyState: NativeInt read FReadyState; property ResponseHeaders[aName: string]: string read getResponseHeader; property responseXML: TJSDocument read FresponseXML; property responseText: string read FResponseText; property status: NativeInt read FStatus; property statusText: string read FStatusText; end; TJSAjaxSettings = class; JDom7AjaxSettingsHandler = reference to function(aHXR: TJQXHR; aOptions: TJSAjaxSettings): Boolean; JDom7AjaxSettingsDataFilter = reference to function(aData: string; aType: string): JSValue; JDom7AjaxSettingsErrorHandler = reference to function(aHXR: TJQXHR; aOptions: TJSAjaxSettings; aStatus, aError: string): Boolean; JDom7AjaxSettingsSuccessHandler = reference to function(data: JSValue; aStatus: string; aHXR: TJQXHR): Boolean; JDom7AjaxSettsingsXHRHandler = reference to function: JSValue; TJSAjaxSettings = class external name 'Object'(TJSObject) accepts: TJSObject; async: boolean; beforeSend: JDom7AjaxSettingsHandler; cache: boolean; complete: JDom7AjaxSettingsHandler; contents: TJSObject; contentType: string; context: TJSObject; converters: TJSObject; crossDomain: boolean; data: JSValue; dataFilter: JDom7AjaxSettingsDataFilter; dataType: string; error: JDom7AjaxSettingsErrorHandler; global: boolean; headers: TJSObject; ifModified: Boolean; isLocal: Boolean; json: string; jsonpCallback: string; method: string; mimeType: string; password: string; processData: Boolean; scriptCharset: string; statusCode: TJSObject; success: JDom7AjaxSettingsSuccessHandler; timeout: NativeInt; traditional: boolean; url: string; username: string; xhr: JDom7AjaxSettsingsXHRHandler; xhrFields: TJSObject; end; JDom7AjaxTransportCompleteHandler = function(aStatus: NativeInt; aStatusText: string; responses, Headers: TJSObject): Boolean; JDom7AjaxTransportSendHandler = reference to function(headers: TJSObject; onComplete: JDom7AjaxTransportCompleteHandler): boolean; JDom7AjaxTransportAbortHandler = reference to function(): Boolean; JDom7AjaxTransport = record send: JDom7AjaxTransportSendHandler; abort: JDom7AjaxTransportAbortHandler; end; //JDom7AjaxTransportHandler = reference to Function (aOptions,aOriginalOptions : TJSObject; aXHR : TJQXHR) : JDom7AjaxTransport; //JDom7AjaxPrefilterHandler = reference to procedure (aOptions,aOriginalOptions : TJSObject; aXHR : TJQXHR); //JDom7AjaxEventHandler = Reference to Function (aEvent : TAjaxEvent; aHXR : TJQXHR; aOptions : TJSAjaxSettings) : Boolean; //JDom7AjaxErrorHandler = Reference to Function (aEvent : TAjaxEvent; aHXR : TJQXHR; aOptions : TJSAjaxSettings; aError : String) : Boolean; JDom7AjaxSuccessHandler = reference to function(aData: TJSObject; aStatus: string; aXHR: TJQXHR): Boolean; //JDom7AjaxLoadHandler = Reference to function (aResponseText,aStatus : String; aXHR : TJQXHR) : Boolean; //JDom7AjaxScriptHandler = Reference to function (aScript,aStatus : String; aXHR : TJQXHR) : Boolean; //JDom7AjaxHandler = Reference to procedure; TProcedure = procedure of object; JEvent = class external name 'Event'(TJSEvent); JBaseEventObject = class external name 'Object'(JEvent); JEventObject = class external name 'Object'(JBaseEventObject); JFunction_on_handler = function(eventObject: JEventObject): JSValue of object; JProcEvent = procedure(event: TJSEvent {JEvent}) of object; JProcEventJS = procedure(event: JSValue); eachCallBack = procedure(index, value: JSValue); eachCallBackProc = procedure(index: Double; element: JSValue); JDomFilterHandlerFunc = function(index: Double; element: JSValue): Boolean; { ╔════════════════════════════════════════════════╗ ║ DOM7 Library ║ ╚════════════════════════════════════════════════╝ } JDom7 = class external name 'window.Dom7'(TJSObject) private FCSSHooks: TJSObject; external name 'cssHooks'; FCSSNumber: TJSObject; external name 'cssNumber'; FReady: TJSPromise; external name 'ready'; function getEl(aIndex: Integer): TJSElement; external name 'get'; public //-------- Classes --------// //function item(aIndex : NativeInt) : TJSNode; //TJSHTMLElement; //Property Nodes [aIndex : NativeInt] : TJSNode Read item; default; function addClass(const aClass: string): JDom7; overload; function addClass(const aClassFunction: JDom7AddClassHandler): JDom7; overload; function removeClass(const aClass: string): JDom7; overload; function removeClass(const aClassFunction: JDom7AddClassHandler): JDom7; overload; function hasClass(const aClassName: string): Boolean; function toggleClass(const aClass: string): JDom7; overload; function toggleClass(const aClass: string; aState: Boolean): JDom7; overload; function toggleClass(const aHandler: JDom7ToggleClassHandler): JDom7; overload; function toggleClass(const aHandler: JDom7ToggleClassHandler; AState: Boolean): JDom7; overload; //-------- Attributes and properties --------// function prop(const aPropertyName: string): JDom7; {JSValue;} overload; function prop(const aPropertyName: string; AValue: JSValue): JDom7; overload; function prop(const aPropertyName: string; propValue: boolean): JDom7; overload; function prop(const aPropertyName: string; propValue: string): JDom7; overload; function prop(const TJSObject): JDom7; overload; function prop(const propertiesObject: JSValue): JDom7; overload; function prop(const aPropertyName: string; aHandler: JDom7PropHandler): JDom7; overload; { function attr(Const attributeName : string) : JDom7; overload; } function attr(const attributeName: string): string; overload; function attr(const attributeName: string; const Value: string): JDom7; overload; function attr(const attributes: TJSObject): JDom7; overload; function attr(const attributes: JSValue): JDom7; overload; function attr(const attributeName: string; aHandler: JDom7AttrHandler): JDom7; overload; function removeAttr(const attributeName: string): JDom7; function val: JSValue; overload; {function val : JDom7; overload;} function val(const aValue: string): JDom7; overload; function val(newValue: JSValue): JDom7; overload; function val(const aValue: Integer): JDom7; overload; function val(const aValue: array of string): JDom7; overload; function val(aHandler: JDom7ValHandler): JDom7; overload; //-------- Data storage --------// class function data(aElement: TJSElement; const aKey: string; aValue: jsValue): TJSObject; overload; class function data(aElement: TJSElement; const aKey: string): TJSObject; overload; class function data(aElement: TJSElement): TJSObject; overload; function data(aKey: string; aValue: JSValue): JDom7; overload; function data(aObj: TJSObject): JDom7; overload; function data(aKey: string): TJSObject; overload; function data: TJSObject; overload; class function removeData(aElement: TJSElement; const aName: string): JDom7; overload; class function removeData(aElement: TJSElement): JDom7; overload; function removeData(const aName: string): JDom7; overload; function removeData(const aNames: array of string): JDom7; overload; function removeData: JDom7; overload; //-------- Data Set --------// function dataset(): JDom7; overload; //-------- CSS transform, transitions --------// function transform(CSSTransformString: string): JDom7; overload; function transition(transitionDuration: double): JDom7; overload; //-------- Events --------// function on(eventName: string; handler: JProcEventJS): JDom7; overload; function on(eventName: string; handler: JProcEvent): JDom7; overload; function on(eventName: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function on(eventName: string; delegatedTarget: string; handler: JProcEvent): JDom7; overload; function on(eventName: string; delegatedTarget: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function on(objParams: TJSObject): JDom7; overload; function on(eventName: string; handler: JFunction_on_handler = nil): JDom7; overload; {function on(const eventName: JSValue; delegatedTarget: JSValue = undefined; handler: TFunction_on_handler = nil): JDom7; overload;} // function on(const eventName: JSValue; delegatedTarget: JSValue; const handler: JFunction_on_handler = nil): JDom7; overload; function on(const eventName: JSValue; const delegatedTarget: JSValue; const handler: JFunction_on_handler = nil): JDom7; overload; function once(eventName: string; handler: JProcEvent): JDom7; overload; function once(eventName: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function once(eventName: string; delegatedTarget: string; handler: JProcEvent): JDom7; overload; function once(eventName: string; delegatedTarget: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function once(eventName: string; handler: JFunction_on_handler = nil): JDom7; overload; {function once(eventName: JSValue; delegatedTarget: JSValue = undefined; handler: JFunction_on_handler = nil): JDom7; overload;} function once(eventName: JSValue; const delegatedTarget: JSValue; handler: JFunction_on_handler = nil): JDom7; overload; function off(eventName: string; handler: JProcEvent): JDom7; overload; function off(eventName: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function off(eventName: string; delegatedTarget: string; handler: JProcEvent): JDom7; overload; function off(eventName: string; delegatedTarget: string; handler: JProcEvent; useCapture: Boolean): JDom7; overload; function off(eventName: string): JDom7; overload; function off(eventName: string; handler: TProcedure): JDom7; overload; {function off(eventName: JSValue; delegatedTarget: JSValue = undefined; handler: TProcedure = nil): JDom7; overload;} function &off(eventName: string; delegatedTarget: JSValue; handler: TProcedure = nil): JDom7; overload; function trigger(eventName: string; eventData: JSValue): JDom7; overload; function transitionEnd(callback: TProcedure; permanent: Boolean): JDom7; overload; function transitionEnd(callback: TProcedure): JDom7; overload; function animationEnd(callback: TProcedure): JDom7; overload; //-------- Styles --------// function Width: Integer; overload; function Width(aValue: Integer): JDom7; overload; function Width(aValue: string): JDom7; overload; function width(value: JSValue {String or Float}): JDom7; overload; function Width(aHandler: JDom7WidthHandler): JDom7; overload; function height: Integer; function height(aValue: Integer): JDom7; function height(aValue: string): JDom7; function height(aValue: JSValue): JDom7; function height(aHandler: JDom7HeightHandler): JDom7; function outerHeight(IncludeMargin: Boolean): Integer; overload; function outerHeight: Integer; overload; function outerHeight(aValue: Integer): JDom7; overload; function outerHeight(aValue: string): JDom7; overload; function outerHeight(aValue: JSValue): JDom7; overload; function outerHeight(aHandler: JDom7HeightHandler): JDom7; overload; function outerWidth(IncludeMargin: Boolean): Integer; overload; function outerWidth: Integer; overload; function outerWidth(aValue: Integer): JDom7; overload; function outerWidth(aValue: string): JDom7; overload; function outerWidth(aHandler: JDom7WidthHandler): JDom7; overload; //function offset: Double; overload; function offset: JDom7TopLeft; overload; function offset(const aOffset: JSValue{String or Float}): JDom7; overload; function offset(const aOffset: JDom7TopLeft): JDom7; overload; function offset(aHandler: JDom7OffsetHandler): JDom7; overload; function offsetParent: JDom7; function hide(): JDom7; overload; function show(): JDom7; overload; function css(const aPropertyName: TJSObject): string; overload; function css(const aPropertyName: string): string; overload; function css(const aPropertyNames: array of string): string; overload; function css(const aPropertyName, Avalue: string): JDom7; overload; function css(const aPropertyName: string; Avalue: Integer): JDom7; overload; function css(const aPropertyName: string; AHandler: JDom7CSSHandler): JDom7; overload; {function css(Const aProperty: String): JSValue {String or Float}; overload; } function css(const aProperty: string; value: JSValue {String or Float}): JDom7; overload; function css(const aPropertiesObject: JSValue): JDom7; overload; //-------- Scroll --------// function scrollLeft: Integer; overload; function scrollLeft(aValue: Integer): JDom7; overload; function scrollLeft(position: Integer; duration: Double): JDom7; overload; function scrollLeft(position: Integer; duration: Double; callback: TProcedure): JDom7; overload; function scrollLeft(position: integer; duration: integer; callback: TProcedure): JDom7; overload; function scrollTop: Integer; overload; function scrollTop(aValue: Integer): JDom7; overload; function scrollTop(position: Double; duration: Double): JDom7; overload; function scrollTop(position: Double; duration: Double; callback: TProcedure): JDom7; overload; function scrollTop(position: integer; duration: integer; callback: TProcedure): JDom7; overload; function scrollTo(left: Double; top: Double): JDom7; overload; function scrollTo(left: Double; top: Double; duration: Double): JDom7; overload; function scrollTo(left: Double; top: Double; duration: Double; callback: TProcedure): JDom7; overload; function scrollTo(left, top, duration: integer; callback: TProcedure): JDom7; overload; //-------- Dom Manipulation --------// function add(const aSelector: string): JDom7; overload; function add(const aSelector: string; AContext: TJSElement): JDom7; overload; function add(const aElement: TJSElement): JDom7; overload; function add(const aElement: array of TJSElement): JDom7; overload; function add(const aQuery: JDom7): JDom7; overload; function add(const aElement: JSValue): JDom7; overload; function add(const aElement: TJSArray): JDom7; overload; function each(aHandler: JDom7EachHandler): JDom7; function each(obj: JSValue; callback: eachCallBack): JDom7; overload; function each(callback: TProcedure): JDom7; overload; function each(callback: eachCallBackProc): JDom7; overload; function html: string; overload; function html(const aHTML: string): JDom7; overload; function html(const aHTML: JSValue): JDom7; overload; function html(const aHandler: JDom7HTMLHandler): JDom7; overload; function text: string; overload; function text(const aText: string): JDom7; overload; function text(const aText: Integer): JDom7; overload; function text(const aText: Double): JDom7; overload; function text(const aText: Boolean): JDom7; overload; function text(aHandler: JDom7TextHandler): JDom7; overload; function text(newTextContent: JSValue): JDom7; overload; function &is(const aSelector: string): JDom7; external name 'is'; function &is(const aQuery: JDom7): JDom7; external name 'is'; function &is(aHandler: JDom7FilterHandler): JDom7; external name 'is'; function &is(const aElement: TJSElement): JDom7; external name 'is'; function &is(const aElements: array of TJSElement): JDom7; external name 'is'; function &is(CSSSelector: JSValue): JDom7; overload; external name 'is'; (* Dom7.isArray(obj) - Determine whether the argument is an array obj - object - Object to test whether or not it is an array returns a Boolean indicating whether the object is a JavaScript array *) { function isArray(obj: JSValue): JDom7; overload; } function isArray(target: JSValue): Boolean; overload; function index: Boolean; (* Dom7.dataset(el) - Get element's data set (set of data- attributes) as plain Object el - HTMLElement or string (with CSS selector) - element with data- attributes to get dataset from returns a new plain object with dataset *) //function dataset(el: variant): JDom7; overload function dataset(target: string {String or JHTMLElement or JDom7}): JSValue; overload; function dataset(target: TJSElement {String or JHTMLElement or JDom7}): JDom7; overload; function dataset(target: JSValue {String or JHTMLElement or JDom7}): JDom7; overload; function eq(AIndex: Integer): JDom7; overload; function eq(index: JSValue): JDom7; overload; function eq(index: Double): Boolean; overload; function append(HTMLString: string): JDom7; overload; function append(HTMLElement: JSValue): JDom7; overload; function appendTo(element: string {String or JElement or JDom7}): JDom7; function appendTo(element: TJSElement {String or JElement or JDom7}): JDom7; (* Dom7.parseUrlQuery(url) - parse url query get parameters url - string - url with GET parameters. Required. Method returns object with query parameters *) function parseUrlQuery(url: string): JDom7; overload; function prepend(HTMLString: string): JDom7; overload; function prepend(HTMLElement: JSValue): JDom7; overload; function prependTo(element: string {String or JElement or JDom7}): JDom7; function prependTo(element: TJSElement {String or JElement or JDom7}): JDom7; function prependTo(element: JSValue {String or JElement or JDom7}): JDom7; function insertBefore(element: JSValue {String or JElement or JDom7}): JDom7; function insertBefore(element: TJSElement {String or JElement or JDom7}): JDom7; function insertBefore(element: string {String or JElement or JDom7}): JDom7; function insertAfter(element: JSValue {String or JElement or JDom7}): JDom7; function insertAfter(element: TJSElement {String or JElement or JDom7}): JDom7; function insertAfter(element: string {String or JElement or JDom7}): JDom7; function next: JDom7; overload; function next(const aSelector: string): JDom7; overload; function nextAll: JDom7; overload; function nextAll(const aSelector: string): JDom7; overload; function nextAll(const aSelector: JSValue): JDom7; overload; function nextUntil: JDom7; overload; function nextUntil(const aSelector: string): JDom7; overload; function nextUntil(const aSelector, aFilter: string): JDom7; overload; function nextUntil(const aElement: TJSElement): JDom7; overload; function nextUntil(const aElement: TJSElement; aFilter: string): JDom7; overload; function nextUntil(const aQuery: JDom7): JDom7; overload; function nextUntil(const aQuery: JDom7; aFilter: string): JDom7; overload; function prev: JDom7; overload; function prev(const aSelector: string): JDom7; overload; function prev(const aSelector: JSValue): JDom7; overload; function prevAll: JDom7; overload; function prevAll(const aSelector: string): JDom7; overload; function prevAll(const aSelector: JSValue): JDom7; overload; (*function prevUntil : JDom7; overload; function prevUntil(const aSelector : String) : JDom7; overload; function prevUntil(const aSelector,aFilter : String) : JDom7; overload; function prevUntil(const aElement : TJSElement) : JDom7; overload; function prevUntil(const aElement : TJSElement; aFilter : String) : JDom7; overload; function prevUntil(const aQuery : JDom7) : JDom7; overload; function prevUntil(const aQuery : JDom7; aFilter : String) : JDom7; overload;*) function parent: JDom7; function parent(const ASelector: string): JDom7; function parent(const ASelector: JSValue): JDom7; function parents: JDom7; function parents(const ASelector: string): JDom7; function parents(const ASelector: JSValue): JDom7; (*function parentsUntil : JDom7; function parentsUntil(const aSelector : String) : JDom7; function parentsUntil(const aSelector,aFilter : String) : JDom7; function parentsUntil(const aElement : TJSElement) : JDom7; function parentsUntil(const aElement : TJSElement; aFilter : String) : JDom7; function parentsUntil(const aQuery : JDom7) : JDom7; function parentsUntil(const aQuery : JDom7; aFilter : String) : JDom7; *) function find(const aSelector: string): JDom7; overload; function find(const aSelector: JSValue): JDom7; overload; function find(const aQuery: JDom7): JDom7; overload; function find(const aElement: TJSElement): JDom7; overload; function children(selector: JSValue): JDom7; overload; function children(const aSelector: string): JDom7; overload; function children: JDom7; overload; function filter(callback: TProcedure): JDom7; overload; function filter(callback: JDomFilterHandlerFunc): JDom7; overload; function filter(const aSelector: string): JDom7; overload; function filter(aHandler: JDom7FilterHandler): JDom7; overload; function filter(const aQuery: JDom7): JDom7; overload; function filter(const aElement: TJSElement): JDom7; overload; function filter(const aElements: array of TJSElement): JDom7; overload; function remove(): JDom7; overload; (* function removeProp(Const aPropertyName : string) : JDom7; *) (* Dom7.requestAnimationFrame(callback) - Cross-browser implementation on requestAnimationFrame callback - function - A parameter specifying a function to call when it's time to update your animation for the next repaint returns animation request id, that uniquely identifies the entry in the callback list *) (* function requestAnimationFrame(callback: TProcedure): JDom7; overload; *) function requestAnimationFrame(callback: TProcedure): Integer; overload; (* Dom7.cancelAnimationFrame(requestID) - Cancels an animation frame request requestID - number - The ID value returned by the call to $$.requestAnimationFrame() that requested the callback *) function cancelAnimationFrame(requestID: integer): JDom7; overload; (* Dom7.serializeObject(object) - Create a serialized representation of a plain object suitable for use in a URL query string object - object - Object to serialize returns a new unique array *) //function serializeObject(obj: variant): JDom7; overload; function serializeObject(target: JSValue): string; overload; (* Dom7.toCamelCase(string) - Convert hypens-case string to camelCase string string - string - hypens-case string returns a new camelCase string *) //function toCamelCase(str: string): JDom7; overload; function toCamelCase(aStr: string): string; overload; (* Dom7.unique(array) - Remove duplicates in passed array obj - array - Array to remove duplicates returns a new unique array *) function unique(arr: JSValue): JDom7; overload; function unique(target: TJSValueDynArray): TJSValueDynArray; overload; //-------- Shortcuts --------// function click: JDom7; overload; function click(handler: JProcEvent): JDom7; overload; function click(handler: TProcedure): JDom7; overload; function blur(): JDom7; overload; function blur(handler: TProcedure): JDom7; overload; function blur(handler: JProcEvent): JDom7; overload; function focus(): JDom7; overload; function focus(handler: TProcedure): JDom7; overload; function focus(handler: JProcEvent): JDom7; overload; function focusin(): JDom7; overload; function focusin(handler: TProcedure): JDom7; overload; function focusin(handler: JProcEvent): JDom7; overload; function focusout(): JDom7; overload; function focusout(handler: TProcedure): JDom7; overload; function focusout(handler: JProcEvent): JDom7; overload; function keyup(): JDom7; overload; function keyup(handler: TProcedure): JDom7; overload; function keyup(handler: JProcEvent): JDom7; overload; function keydown(): JDom7; overload; function keydown(handler: TProcedure): JDom7; overload; function keydown(handler: JProcEvent): JDom7; overload; function keypress(): JDom7; overload; function keypress(handler: TProcedure): JDom7; overload; function keypress(handler: JProcEvent): JDom7; overload; function submit(): JDom7; overload; function submit(handler: TProcedure): JDom7; overload; function submit(handler: JProcEvent): JDom7; overload; function change(): JDom7; overload; function change(handler: TProcedure): JDom7; overload; function change(handler: JProcEvent): JDom7; overload; function mousedown(): JDom7; overload; function mousedown(handler: TProcedure): JDom7; overload; function mousedown(handler: JProcEvent): JDom7; overload; function mousemove(): JDom7; overload; function mousemove(handler: TProcedure): JDom7; overload; function mousemove(handler: JProcEvent): JDom7; overload; function mouseup(): JDom7; overload; function mouseup(handler: TProcedure): JDom7; overload; function mouseup(handler: JProcEvent): JDom7; overload; function mouseenter(): JDom7; overload; function mouseenter(handler: TProcedure): JDom7; overload; function mouseenter(handler: JProcEvent): JDom7; overload; function mouseleave(): JDom7; overload; function mouseleave(handler: TProcedure): JDom7; overload; function mouseleave(handler: JProcEvent): JDom7; overload; function mouseout(): JDom7; overload; function mouseout(handler: TProcedure): JDom7; overload; function mouseout(handler: JProcEvent): JDom7; overload; function mouseover(): JDom7; overload; function mouseover(handler: TProcedure): JDom7; overload; function mouseover(handler: JProcEvent): JDom7; overload; function touchstart(): JDom7; overload; function touchstart(handler: TProcedure): JDom7; overload; function touchstart(handler: JProcEvent): JDom7; overload; function touchend(): JDom7; overload; function touchend(handler: TProcedure): JDom7; overload; function touchend(handler: JProcEvent): JDom7; overload; function touchmove(): JDom7; overload; function touchmove(handler: TProcedure): JDom7; overload; function touchmove(handler: JProcEvent): JDom7; overload; function resize(handler: TProcedure): JDom7; overload; function resize(handler: JProcEvent): JDom7; overload; function scroll(handler: JProcEvent): JDom7; overload; function scroll(handler: TProcedure): JDom7; overload; //-------- Ajax --------// (* $$.ajax(parameters) - Load data from the server parameters - object - Request parameters returns plain XHR object *) //function ajax(parameters: JAjaxSettings): JDom7; overload; //function ajax(parameters: JAjaxSettings): JDom7XHR; overload; class function ajax(aURL: string; aSettings: TJSObject): tJQXHR; overload; class function ajax(aSettings: TJSObject): TJQXHR; overload; class function ajax(aSettings: TJSAjaxSettings): TJQXHR; overload; (* $$.get(url, data, success) - Load data from the server using a HTTP GET request url - string - Request url data - object - A plain object or string that is sent to the server with the request. Optional success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional returns plain XHR object *) //function get(url: string; data: JSValue; success: aCallBack): JDom7; overload; //function get(url: String; data: JSValue; success: procedure(data: JSValue; status: Double; xhr: JDom7XHR)): JDom7XHR; overload; function get(aIndex: Integer): TJSElement; overload; class function get: TJQXHR; overload; class function get(url: string): TJQXHR; overload; class function get(url, Data: string): TJQXHR; overload; class function get(url: string; Data: TJSObject): TJQXHR; overload; class function get(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function get(url, Data: string; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function get(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; class function get(url, Data: string; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; class function get(aSettings: TJSAjaxSettings): TJQXHR; overload; class function get(aSettings: TJSObject): TJQXHR; overload; (* $$.post(url, data, success) - Load data from the server using a HTTP POST request url - string - Request url data - object - A plain object or FormData or string that is sent to the server with the request. Optional success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional returns plain XHR object *) //function post(url: string; data: variant; success: aCallBack): JDom7; overload; //function post(url: String; data: Variant; success: procedure(data: Variant; status: Float; xhr: JDom7XHR)): JDom7XHR; overload; class function post(url: string): TJQXHR; overload; class function post(url, Data: string): TJQXHR; overload; class function post(url: string; Data: TJSObject): TJQXHR; overload; class function post(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function post(url, Data: string; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function post(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; class function post(url, Data: string; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; class function post(aSettings: TJSAjaxSettings): TJQXHR; overload; class function post(aSettings: TJSObject): TJQXHR; overload; (* $$.getJSON(url, data, success) - Load JSON-encoded data from the server using a GET HTTP request url - string - Request url data - object - A plain object or FormData or string that is sent to the server with the request. Optional success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional returns plain XHR object *) //function getJSON(url: string; data: variant=undefined; success: variant=undefined): JDom7; overload; //function getJSON(url: String; data: Variant; success: procedure(data: Variant; status: Float; xhr: JDom7XHR)): JDom7XHR; overload; class function getJSON(url: string): TJQXHR; overload; class function getJSON(url, Data: string): TJQXHR; overload; class function getJSON(url: string; Data: TJSObject): TJQXHR; overload; class function getJSON(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function getJSON(url, Data: string; success: JDom7AjaxSuccessHandler): TJQXHR; overload; class function getJSON(url: string; Data: TJSObject; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; class function getJSON(url, Data: string; success: JDom7AjaxSuccessHandler; aDataType: string): TJQXHR; overload; (* function addBack(Const aSelector : String) : JDom7; overload; function addBack : JDom7; overload; function ajaxComplete(aHandler : JDom7AjaxEventHandler) : JDom7; function ajaxError(aHandler : JDom7AjaxEventHandler) : JDom7; function ajaxSend(aHandler : JDom7AjaxEventHandler) : JDom7; function ajaxStart(aHandler : JDom7AjaxHandler) : JDom7; function ajaxStop(aHandler : JDom7AjaxHandler) : JDom7; function ajaxSuccess(aHandler : JDom7AjaxEventHandler) : JDom7; class procedure ajaxPrefilter(dataTypes : string; aHandler : JDom7AjaxPrefilterHandler); overload; class procedure ajaxSetup(aSettings : TJSAjaxSettings); overload; class procedure ajaxSetup(aSettings : TJSObject); overload; class procedure ajaxTransport(aDataType : string; AHandler : JDom7AjaxTransportHandler); class function Callbacks : TCallbacks; overload; class function Callbacks(const aFlags : string) : TCallbacks; overload; function clearQueue : JDom7; overload; function clearQueue(const aQueueName : String) : JDom7; overload; function closest(Const aSelector : String) : JDom7; overload; function closest(Const aSelector : String; AContext : TJSElement) : JDom7; overload; function closest(Const aQuery : JDom7) : JDom7; overload; function closest(Const aElement : TJSElement) : JDom7; overload; function contents : JDom7; function dequeue : JDom7; overload; function dequeue(const aQueueName : String) : JDom7; overload; class function dequeue(aElement : TJSElement) : JDom7; overload; class function dequeue(aElement : TJSElement; const aQueueName : String) : JDom7; overload; function _end : JDom7; external name 'end'; class function escapeSelector(const S : String) : String; function first : JDom7; class function getScript(url : String) : TJQXHR; overload; class function getScript(url : String; aSuccess : JDom7AjaxScriptHandler) : TJQXHR; overload; function has(Const aSelector : String) : JDom7; function has(Const aQuery : JDom7) : JDom7; class function hasData(aElement : TJSElement) : Boolean; function innerHeight: Integer; function innerHeight(aValue: Integer) : JDom7; function innerHeight(aValue: String) : JDom7; function innerHeight(aHandler: JDom7HeightHandler) : JDom7; function innerWidth: Integer; function innerWidth(aValue: Integer) : JDom7; function innerWidth(aValue: String) : JDom7; function innerWidth(aHandler: JDom7WidthHandler) : JDom7; function last : JDom7; class function load(url : String) : TJQXHR; overload; class function load(url,Data : String) : TJQXHR; overload; class function load(url : String; Data : TJSObject) : TJQXHR; overload; class function load(url : String; Data : TJSObject; success : JDom7AjaxLoadHandler) : TJQXHR; overload; class function load(url,Data : String; success : JDom7AjaxLoadHandler) : TJQXHR; overload; function map(aHandler : JDom7MapHandler) : JDom7; function &not(const aSelector : String) : JDom7; external name 'not'; overload; function &not(const aSelector : TJSElement) : JDom7; external name 'not'; overload; function &not(const aSelector : Array of TJSElement) : JDom7; external name 'not'; overload; function &not(const aSelector : JDom7) : JDom7; external name 'not'; overload; function &not(const aSelector : JDom7FilterHandler) : JDom7;external name 'not'; overload; function noConflict : TJSObject; overload; function noConflict(removeAll: Boolean) : TJSObject; overload; class function param (aObject : String) : String; overload; class function param (aObject : TJSObject) : String; overload; class function param (aObject : JDom7) : String; overload; class function param (aObject : String; traditional : Boolean) : String; overload; class function param (aObject : TJSObject; traditional : Boolean) : String; overload; class function param (aObject : JDom7; traditional : Boolean) : String; overload; function position : JDom7TopLeft; class function queue(element : TJSElement) : TJSarray; overload; class function queue(element : TJSElement; const aQueueName : String) : TJSarray; overload; class function queue(element : TJSElement; const aQueueName : string; anewQueue : TJSarray) : JDom7; overload; class function queue(element : TJSElement; const aQueueName : String ; aHandler : JDom7QueueHandler) : JDom7; overload; function queue : TJSarray; overload; function queue(aQueueName : string) : TJSarray; overload; function queue(anArray : TJSArray) : JDom7; overload; function queue(aQueueName : string; anArray : TJSarray) : JDom7; overload; function queue(aQueueName : string; aHandler : JDom7AddQueueHandler) : JDom7; overload; function serialize : string; function serializeArray : TJSObjectDynArrayArray; Function siblings : JDom7; overload; Function siblings(Const aSelector : String) : JDom7; overload; Function slice(aStart : integer) : JDom7; overload; Function slice(aStart,aEnd : integer) : JDom7; overload; Function sub : JDom7; Function when(APromise : TJSPromise) : TJSPromise; overload; Function when : TJSPromise; overload; Property ready : TJSPromise Read FReady; // These should actually be class properties ? property cssHooks : TJSObject Read FCSSHooks; property cssNumber : TJSObject read FCSSNumber; Property Elements[AIndex : Integer] : TJSElement read getEl; default; *) end; { ╔════════════════════════════════════════════════╗ ║ External Global Functions ║ ╚════════════════════════════════════════════════╝ } function _(const aSelector: TJSDocument): JDom7; external name 'window._'; function _(const aSelector: string): JDom7; external name 'window._'; function _(const aSelector: string; Context: TJSElement): JDom7; external name 'window._'; function _(const aElement: TJSElement): JDom7; external name 'window._'; function _(const aElement: array of TJSElement): JDom7; external name 'window._'; function _(const aElement: TJSObject): JDom7; external name 'window._'; function _(const aQuery: JDom7): JDom7; external name 'window._'; function _(): JDom7; external name 'window._'; //Function _(Const aSelector: JSValue) : TJSHTMLElement; external name 'window.Dom7'; var g_: JDom7; external name 'window._'; var this: TJSElement; external name 'this'; implementation end.
unit UFourier; (************************************************************************** ************************* UFourier *************************************** * Purpose: Implements Fast Fourier Transform and InverseFastFourierTrans * * * * * * procedures * * FFT(_NumSamples : Integer; * * _InValues, _OutValues : TComplex1DArray); * * * * IFFT(_NumSamples : Integer; * * _InValues, _OutValues : TComplex1DArray); * * * * Note: * * Based on the DMath Package by Jean Debord * * (http://www.unilim.fr/pages_perso/jean.debord/index.htm) * * * * Adapted to use TComplex and TComplex1DArrays - 06.09.2004 * * ---------------------------------------------------------------------- * * (c) W.Blecher 2004 - ITMC RWTH Aachen * ************************************************************************** **************************************************************************) interface uses SysUtils, UGlobalTools; procedure FFT(_NumSamples : Integer; _InValues : TComplex1DArray; var _OutValues : TComplex1DArray); procedure IFFT(_NumSamples : Integer; _InValues : TComplex1DArray; var _OutValues : TComplex1DArray); implementation const MaxPowerOfTwo : integer = 25; (*************************************************************** ************************** IsPowerOfTwo *********************** * Purpose: Checks if an Integer is a Power of Two * * * * Input: _X : Integer * * * * Number to check * * Output: True/False * * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) function IsPowerOfTwo(_X : Integer) : Boolean; var I, Y : Integer; begin Y := 2; for I := 1 to Pred(MaxPowerOfTwo) do begin if _X = Y then begin IsPowerOfTwo := True; Exit; end; Y := Y shl 1; end; IsPowerOfTwo := False; end; (*************************************************************** ************************** NumberOfBitsNeeded ***************** * Purpose: How much Bits are needed to store the max value * * * * Input: _PowerOfTwo : Integer * * Max Array Index * * Output: Integer * * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) function NumberOfBitsNeeded(_PowerOfTwo : Integer) : Integer; var I : Integer; begin for I := 0 to MaxPowerOfTwo do begin if (_PowerOfTwo and (1 shl I)) <> 0 then begin NumberOfBitsNeeded := I; Exit; end; end; NumberOfBitsNeeded := 0; end; (*************************************************************** ************************ ReverseBits ************************** * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) function ReverseBits(_Index, _NumBits : Integer) : Integer; var I, Rev : Integer; begin Rev := 0; for I := 0 to _NumBits - 1 do begin Rev := (Rev shl 1) or (_Index and 1); _Index := _Index shr 1; end; ReverseBits := Rev; end; (*************************************************************** ************************* FourierTransform ******************** * Purpose: Calculate the Fourier Transform of _ValsIn * * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) procedure FourierTransform(_AngleNumerator : Single; _NumSamples : Integer; _ValsIn : TComplex1DArray; var _ValsOut : TComplex1DArray); var NumBits, I, J, K, N, BlockSize, BlockEnd : Integer; Delta_angle, Delta_ar : Single; Alpha, Beta : Single; Tr, Ti, Ar, Ai : Single; begin if not IsPowerOfTwo(_NumSamples) or (_NumSamples < 2) then begin raise Exception.Create('Error in procedure Fourier: NumSamples=' + IntToStr(_NumSamples)+ ' is not a positive integer power of 2'); end; NumBits := NumberOfBitsNeeded(_NumSamples); for I := 0 to _NumSamples - 1 do begin J := ReverseBits(I, NumBits); _ValsOut[J].Re := _ValsIn[I].Re; _ValsOut[J].img := _ValsIn[I].Img; end; BlockEnd := 1; BlockSize := 2; while BlockSize <= _NumSamples do begin Delta_angle := _AngleNumerator / BlockSize; Alpha := Sin(0.5 * Delta_angle); Alpha := 2.0 * Alpha * Alpha; Beta := Sin(Delta_angle); I := 0; while I < _NumSamples do begin Ar := 1.0; (* cos(0) *) Ai := 0.0; (* sin(0) *) J := I; for N := 0 to BlockEnd - 1 do begin K := J + BlockEnd; Tr := Ar * _ValsOut[K].Re - Ai * _ValsOut[K].Img; Ti := Ar * _ValsOut[K].Img + Ai * _ValsOut[K].Re; _ValsOut[K].Re := _ValsOut[J].Re - Tr; _ValsOut[K].Img := _ValsOut[J].Img - Ti; _ValsOut[J].Re := _ValsOut[J].Re + Tr; _ValsOut[J].Img := _ValsOut[J].Img + Ti; Delta_ar := Alpha * Ar + Beta * Ai; Ai := Ai - (Alpha * Ai - Beta * Ar); Ar := Ar - Delta_ar; Inc(J); end; I := I + BlockSize; end; BlockEnd := BlockSize; BlockSize := BlockSize shl 1; end; end; (*************************************************************** ************************* FFT ********************************* * Purpose: Caller for calculation of Fast Fourier Transform * * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) procedure FFT(_NumSamples : Integer; _InValues : TComplex1DArray; var _OutValues : TComplex1DArray); begin FourierTransform(2 * PI, _NumSamples, _InValues, _OutValues); end; (*************************************************************** ************************ IFFT ********************************* * Purpose: Caller of Iverse Fast Fourier Transform * * ----------------------------------------------------------- * * http://www.unilim.fr/pages_perso/jean.debord/index.htm * *************************************************************** ***************************************************************) procedure IFFT(_NumSamples : Integer; _InValues : TComplex1DArray; var _OutValues : TComplex1DArray); var I : Integer; begin FourierTransform(- 2 * PI, _NumSamples, _InValues, _OutValues); { Normalize the resulting time samples } for I := 0 to _NumSamples - 1 do begin _OutValues[I].Re := _OutValues[I].Re / _NumSamples; _OutValues[I].Img := _OutValues[I].Img / _NumSamples; end; end; end.
namespace com.example.android.jetboy; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface // Android JET demonstration code: // All inline comments related to the use of the JetPlayer class are preceded by "JET info:" uses android.content, android.os, android.util, android.view, android.widget; type JetBoyView = public class(SurfaceView, SurfaceHolder.Callback) private // The thread that actually draws the animation var thread: JetBoyThread; var mTimerView: TextView; var mButtonRetry: Button; // var mButtonRestart: Button; var mTextView: TextView; public const TAG = 'JetBoy'; // the number of asteroids that must be destroyed const mSuccessThreshold = 50; // used to calculate level for mutes and trigger clip var mHitStreak: Integer := 0; // total number asteroids you need to hit. var mHitTotal: Integer := 0; // which music bed is currently playing? var mCurrentBed: Integer := 0; // have we already started up var mGameIsRunning: Boolean := false; public constructor(ctx: Context; attrs: AttributeSet); method onWindowFocusChanged(hasWindowFocus: Boolean); override; method setTimerView(tv: TextView); method getThread: JetBoyThread; method SetButtonView(_buttonRetry: Button); method SetTextView(textView: TextView); // SurfaceHolder.Callback methods method surfaceCreated(arg0: SurfaceHolder); method surfaceChanged(holder: SurfaceHolder; format, width, height: Integer); method surfaceDestroyed(arg0: SurfaceHolder); end; implementation /// <summary> /// The constructor called from the main JetBoy activity /// </summary> /// <param name="ctx"></param> /// <param name="attrs"></param> constructor JetBoyView(ctx: Context; attrs: AttributeSet); begin inherited; // register our interest in hearing about changes to our surface var surfHolder: SurfaceHolder := Holder; surfHolder.addCallback(self); if not isInEditMode then begin // create thread only; it's started in surfaceCreated() thread := new JetBoyThread(self, surfHolder, ctx, new Handler( new interface Handler.Callback(handleMessage := method (m: Message); begin mTimerView.Text := m.Data.String['text']; if m.Data.String['STATE_LOSE'] <> nil then begin // mButtonRestart.Visibility := View.VISIBLE; mButtonRetry.Visibility := View.VISIBLE; mTimerView.Visibility := View.INVISIBLE; mTextView.Visibility := View.VISIBLE; Log.d(TAG, 'the total was ' + mHitTotal); if mHitTotal >= mSuccessThreshold then mTextView.Text := R.string.winText else mTextView.Text := 'Sorry, You Lose! You got ' + mHitTotal + '. You need 50 to win.'; mTimerView.Text := ctx.String[R.string.timer]; mTextView.Height := 20 end end))) end; Focusable := true; // make sure we get key events Log.d(TAG, '@@@ done creating view!') end; /// <summary> /// Pass in a reference to the timer view widget so we can update it from here. /// </summary> /// <param name="tv"></param> method JetBoyView.setTimerView(tv: TextView); begin mTimerView := tv end; /// <summary> /// Standard window-focus override. Notice focus lost so we can pause on /// focus lost. e.g. user switches to take a call. /// </summary> /// <param name="hasWindowFocus"></param> method JetBoyView.onWindowFocusChanged(hasWindowFocus: Boolean); begin if not hasWindowFocus then if thread <> nil then thread.pause end; /// <summary> /// Fetches the animation thread corresponding to this LunarView. /// </summary> /// <returns>the animation thread</returns> method JetBoyView.getThread: JetBoyThread; begin exit thread end; method JetBoyView.surfaceCreated(arg0: SurfaceHolder); begin // start the thread here //NOTE: mGameIsRunning will remain true if the user //switches away from and back to the app if not mGameIsRunning then begin thread.start; mGameIsRunning := true end else thread.unPause; end; /// <summary> /// Callback invoked when the surface dimensions change. /// </summary> /// <param name="holder"></param> /// <param name="format"></param> /// <param name="width"></param> /// <param name="height"></param> method JetBoyView.surfaceChanged(holder: SurfaceHolder; format, width, height: Integer); begin thread.setSurfaceSize(width, height) end; method JetBoyView.surfaceDestroyed(arg0: SurfaceHolder); begin //NOTE: thread management code change //We no longer try and encourage the thread to exit here //Instead it gets paused and resumed end; /// <summary> /// A reference to the button to start game over. /// </summary> /// <param name="_buttonRetry"></param> method JetBoyView.SetButtonView(_buttonRetry: Button); begin mButtonRetry := _buttonRetry end; /// <summary> /// we reuse the help screen from the end game screen. /// </summary> /// <param name="textView"></param> method JetBoyView.SetTextView(textView: TextView); begin mTextView := textView end; end.
unit uWorkerThread; interface uses Classes, SysUtils, Windows, uHelpers, IdGlobal, IdUDPClient, IdException, Variants, ActiveX, ComObj, StrUtils, ThreadUtilities; type TWorkerThread = class(TObject) //class(TThread) strict private FFormHandle: THandle; FThreadPool: TThreadPool; private procedure PrepareThreadVars; procedure ExecuteWork(Data: Pointer; AThread: TThread); procedure UpdateCaption; // function ExecuteCommand(CommandLine: string): string; function HostAlive(sAddress: string): Boolean; procedure PrepareCommandLine; // function GetConsoleOutput(const Command: string; // var Output: TStringList): Boolean; procedure ReadTempFile(var slOutput: TStringList; sTempFilename: string); procedure WmiDeleteFile(const FileName, WbemComputer, WbemUser, WbemPassword: string); function WmiGetWindowsFolder(const WbemComputer, WbemUser, WbemPassword: string): string; procedure WmiStopAndDeleteService(const sService, WbemComputer, WbemUser, WbemPassword: string); { Private declarations } public procedure BeginWork(athrdtask: PWorkerThreadTask); constructor Create(formHandle: THandle); destructor Destroy; override; end; threadvar FCurThreadTask : PWorkerThreadTask; FHostname : string; FPsexecCmd : string; FCommandOutput : string; FSuccess : string; FErrorCode : string; mOutputs, mCommand : string; implementation procedure TWorkerThread.PrepareThreadVars(); begin FHostname := ''; end; constructor TWorkerThread.Create(formHandle: THandle); begin FFormHandle := formHandle; FThreadPool := TThreadPool.Create(ExecuteWork, MAX_THREADS); //MAX_PV_THREADS); inherited Create; end; destructor TWorkerThread.Destroy; begin FThreadPool.Free; inherited; end; procedure TWorkerThread.ReadTempFile(var slOutput: TStringList; sTempFilename: string); var fsReadOutput : TFileStream; begin //ExecuteCommand(FPsexecCmd); //GetConsoleOutput(FPsexecCmd, slOutput); //FCommandOutput := slOutput.Text; if FileExists(sTempFilename) then begin fsReadOutput := TFileStream.Create(sTempFilename, fmShareDenyNone); try slOutput.LoadFromStream(fsReadOutput); finally FreeAndNil(fsReadOutput); end; end; end; procedure TWorkerThread.BeginWork(athrdtask: PWorkerThreadTask); begin FThreadPool.Add(athrdtask); end; procedure TWorkerThread.WmiStopAndDeleteService(const sService, WbemComputer, WbemUser, WbemPassword: string); var FSWbemLocator : OLEVariant; FWMIService : OLEVariant; FWbemObjectSet : OLEVariant; FOutParams : OLEVariant; begin FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword); FWbemObjectSet := FWMIService.Get('Win32_Service.Name="' + sService + '"'); FWbemObjectSet.StopService(); Sleep(500); Sleep(500); Sleep(500); Sleep(500); Sleep(500); Sleep(500); FWbemObjectSet.Delete(); end; function TWorkerThread.WmiGetWindowsFolder(const WbemComputer, WbemUser, WbemPassword: string): string; var FSWbemLocator : OLEVariant; FWMIService : OLEVariant; FWbemObject : OLEVariant; begin Result := ''; //default FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword); FWbemObject := FWMIService.Get('Win32_OperatingSystem=@'); Result := ExcludeTrailingPathDelimiter(Format('%s', [string(FWbemObject.WindowsDirectory)])); // Result := ''; //default // FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); // FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, // WbemPassword); // FWbemObjectSet := // FWMIService.ExecQuery('SELECT WindowsDirectory FROM Win32_OperatingSystem', 'WQL', // wbemFlagForwardOnly); // oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant; // while oEnum.Next(1, FWbemObject, iValue) = 0 do // begin // Result := ExcludeTrailingPathDelimiter(Format('%s', // [string(FWbemObject.WindowsDirectory)])); // // String // // FWbemObject := Unassigned; // end; end; procedure TWorkerThread.WmiDeleteFile(const FileName, WbemComputer, WbemUser, WbemPassword: string); var FSWbemLocator : OLEVariant; FWMIService : OLEVariant; FWbemObjectSet : OLEVariant; FOutParams : OLEVariant; begin FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword); FWbemObjectSet := FWMIService.Get(Format('CIM_DataFile.Name="%s"', [StringReplace(FileName, '\', '\\', [rfReplaceAll])])); FOutParams := FWbemObjectSet.Delete(); end; procedure TWorkerThread.UpdateCaption(); var msg_prm : PWMUCommand; begin New(msg_prm); msg_prm.sComputer := FHostname; msg_prm.sResult := FCommandOutput; msg_prm.sErrorCode := FErrorCode; msg_prm.sSuccess := FSuccess; // + ' --- ' + BoolToStr(Length(FCommandOutput) > 0); if not PostMessage(FFormHandle, WM_POSTED_MSG, WM_THRD_MSG, integer(msg_prm)) then begin Sleep(35); PostMessage(FFormHandle, WM_POSTED_MSG, WM_THRD_MSG, integer(msg_prm)); if not PostMessage(FFormHandle, WM_POSTED_MSG, WM_THRD_MSG, integer(msg_prm)) then begin Sleep(35); PostMessage(FFormHandle, WM_POSTED_MSG, WM_THRD_MSG, integer(msg_prm)); end; end; end; function TWorkerThread.HostAlive(sAddress: string): Boolean; const NB_REQUEST = #$A2#$48#$00#$00#$00#$01#$00#$00 + #$00#$00#$00#$00#$20#$43#$4B#$41 + #$41#$41#$41#$41#$41#$41#$41#$41 + #$41#$41#$41#$41#$41#$41#$41#$41 + #$41#$41#$41#$41#$41#$41#$41#$41 + #$41#$41#$41#$41#$41#$00#$00#$21 + #$00#$01; NB_PORT = 137; NB_BUFSIZE = 8192; var Buffer : TIdBytes; UDPClient : TIdUDPClient; bResult : boolean; begin if (sAddress = '127.0.0.1') or (SameText(sAddress, 'localhost')) then begin Result := True; Exit; end; bResult := False; UDPClient := nil; try UDPClient := TIdUDPClient.Create(nil); UDPClient.Host := Trim(sAddress); UDPClient.Port := NB_PORT; SetLength(Buffer, NB_BUFSIZE); UDPClient.Send(NB_REQUEST); if (0 < UDPClient.ReceiveBuffer(Buffer, 5000)) then begin bResult := True; end; except on E: EIdSocketHandleError do begin // do nothing end; on E: Exception do begin begin FCommandOutput := StringToHex(E.Message); Result := False; end; end; end; if Assigned(UDPClient) then FreeAndNil(UDPClient); Result := bResult; end; procedure TWorkerThread.PrepareCommandLine; var sWorkDir : string; sFile : string; sEscapedPass : string; bFileAdded : boolean; idx : integer; begin // bFileAdded := False; FPsexecCmd := '\\' + FCurThreadTask.sComputer; if FCurThreadTask.bAlternateUser then begin //lets add CMD supported escape character (^) for every character in password for idx := 1 to Length(FCurThreadTask.sPass) do begin sEscapedPass := sEscapedPass + '^' + FCurThreadTask.sPass[idx]; end; FPsexecCmd := FPsexecCmd + ' -u ' + FCurThreadTask.sUser + ' -p ' + sEscapedPass; end; if FCurThreadTask.bSetConnectionTimeout then FPsexecCmd := FPsexecCmd + ' -n ' + IntToStr(FCurThreadTask.iConnectTimeout); if FCurThreadTask.bRunAsSystem then FPsexecCmd := FPsexecCmd + ' -s'; if FCurThreadTask.bDoNotLoadProfile then FPsexecCmd := FPsexecCmd + ' -e'; sWorkDir := ExtractFilePath(FCurThreadTask.sFileWithPath); sFile := ExtractFileName(FCurThreadTask.sFileWithPath); //FPsexecCmd := FPsexecCmd + ' -w ' + sWorkDir; if FCurThreadTask.bInteractDesktop then FPsexecCmd := FPsexecCmd + ' -i'; if FCurThreadTask.bCopyFileToRemote then begin if FCurThreadTask.bOverwriteExisting then FPsexecCmd := FPsexecCmd + ' -f' else if FCurThreadTask.bCopyOnlyIfNewer then FPsexecCmd := FPsexecCmd + ' -v'; FPsexecCmd := FPsexecCmd + ' -c ' + FCurThreadTask.sFileWithPath; bFileAdded := True; end; if FCurThreadTask.bDontWaitForTermination then FPsexecCmd := FPsexecCmd + ' -d'; if TPriority(FCurThreadTask.iThreadPriority) <> tpnormal then begin case TPriority(FCurThreadTask.iThreadPriority) of tplow: FPsexecCmd := FPsexecCmd + ' -low'; tpbelownormal: FPsexecCmd := FPsexecCmd + ' -belownormal'; tpabovenormal: FPsexecCmd := FPsexecCmd + ' -abovenormal'; tphigh: FPsexecCmd := FPsexecCmd + ' -high'; tprealtime: FPsexecCmd := FPsexecCmd + ' -realtime'; end; end; { -priority Specifies -low, -belownormal, -abovenormal, -high or -realtime to run the process at a different priority. Use -background to run at low memory and I/O priority on Vista. } //if FCurThreadTask.bRunExistingRemoteCmd then //begin if Length(FCurThreadTask.sCmdLine) > 0 then begin if not bFileAdded then FPsexecCmd := FPsexecCmd + ' ' + FCurThreadTask.sFileWithPath + ' ' + FCurThreadTask.sCmdLine else FPsexecCmd := FPsexecCmd + ' ' + FCurThreadTask.sCmdLine end else begin if not bFileAdded then FPsexecCmd := FPsexecCmd + ' ' + FCurThreadTask.sFileWithPath; end; end; procedure TWorkerThread.ExecuteWork(Data: Pointer; AThread: TThread); var FoundMatch : Boolean; slOutput : TStringList; sTempFilename : string; iResult : Cardinal; sWinFolder : string; bTryAgain : boolean; //Regex : TPerlRegEx; begin { Place thread code here } bTryAgain := False; // New(FCurThreadTask); try PrepareThreadVars(); FCurThreadTask.bAlternateUser := TWorkerThreadTask(Data^).bAlternateUser; FCurThreadTask.sUser := TWorkerThreadTask(Data^).sUser; FCurThreadTask.sPass := TWorkerThreadTask(Data^).sPass; FCurThreadTask.sFileWithPath := Trim(TWorkerThreadTask(Data^).sFileWithPath); FCurThreadTask.sCmdLine := Trim(TWorkerThreadTask(Data^).sCmdLine); FCurThreadTask.bCheckIfOnline := TWorkerThreadTask(Data^).bCheckIfOnline; FCurThreadTask.bRunExistingRemoteCmd := TWorkerThreadTask(Data^).bRunExistingRemoteCmd; FCurThreadTask.bCopyFileToRemote := TWorkerThreadTask(Data^).bCopyFileToRemote; FCurThreadTask.bOverwriteExisting := TWorkerThreadTask(Data^).bOverwriteExisting; FCurThreadTask.bCopyOnlyIfNewer := TWorkerThreadTask(Data^).bCopyOnlyIfNewer; FCurThreadTask.bDoNotLoadProfile := TWorkerThreadTask(Data^).bDoNotLoadProfile; FCurThreadTask.bInteractDesktop := TWorkerThreadTask(Data^).bInteractDesktop; FCurThreadTask.bRunAsSystem := TWorkerThreadTask(Data^).bRunAsSystem; FCurThreadTask.iThreadPriority := TWorkerThreadTask(Data^).iThreadPriority; FCurThreadTask.bDontWaitForTermination := TWorkerThreadTask(Data^).bDontWaitForTermination; FCurThreadTask.bSetConnectionTimeout := TWorkerThreadTask(Data^).bSetConnectionTimeout; FCurThreadTask.iConnectTimeout := TWorkerThreadTask(Data^).iConnectTimeout; FCurThreadTask.sComputer := TWorkerThreadTask(Data^).sComputer; FHostname := FCurThreadTask.sComputer; FCommandOutput := StringToHex('-'); //default FErrorCode := '-'; //default FSuccess := 'False'; //default if FCurThreadTask.bCheckIfOnline then begin if not HostAlive(FHostname) then begin FCommandOutput := StringToHex('Host offline'); UpdateCaption; Exit; end; end; PrepareCommandLine(); if not FCurThreadTask.bAlternateUser then begin UninstallPsexecService(FHostname); end; sTempFilename := MgGetTempFileName('psexec', ''); FPsexecCmd := ReplaceText(FPsexecCmd, '"', '"""'); FPsexecCmd := 'cmd.exe /c "psexec ' + FPsexecCmd + ' >' + sTempFilename + '"'; slOutput := TStringList.Create; try iResult := StartApp(FPsexecCmd, '', True); if iResult = 0 then begin FSuccess := 'Success: ' + SysErrorMessage(iResult); end else begin FSuccess := 'Error: ' + SysErrorMessage(iResult); if ContainsText(FSuccess, 'The handle is invalid') then begin // FSuccess := FSuccess + ' --- Make sure that the default admin$ share is enabled'; end; if ContainsText(FSuccess, 'requires a newer version of Windows') then begin try CoInitialize(nil); try try begin sWinFolder := WmiGetWindowsFolder(FHostname, FCurThreadTask.sUser, FCurThreadTask.sPass); if Length(sWinFolder) > 0 then begin WmiStopAndDeleteService('psexesvc', FHostname, FCurThreadTask.sUser, FCurThreadTask.sPass); WmiDeleteFile(sWinFolder + '\psexesvc.exe', FHostname, FCurThreadTask.sUser, FCurThreadTask.sPass); end; end; except on E: EOleException do FSuccess := FSuccess + ' --- ' + (Format('%s %x', [E.Message, E.ErrorCode])); on E: Exception do FSuccess := FSuccess + ' --- ' + (E.Classname + ':' + E.Message); end; finally CoUninitialize; end; except on E: EOleException do OutputDebugString(PChar(Format('EOleException %s %x', [E.Message, E.ErrorCode]))); on E: Exception do OutputDebugString(PChar(E.Classname + ':' + E.Message)); end; bTryAgain := True; end; if bTryAgain then begin iResult := StartApp(FPsexecCmd, '', True); if iResult = 0 then begin FSuccess := 'Success: ' + SysErrorMessage(iResult); end else begin FSuccess := 'Error: ' + SysErrorMessage(iResult); end; end; end; //MgExecute(FPsexecCmd, SW_NORMAL, '', True); ReadTempFile(slOutput, sTempFilename); FCommandOutput := StringToHex(slOutput.Text); finally FreeAndNil(slOutput); end; if FileExists(sTempFilename) then begin DeleteFile(PChar(sTempFilename)); end; UpdateCaption; finally Dispose(FCurThreadTask); end; end; end.
unit UPais; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, UPaisVo, UController, Generics.Collections, UPaisController; type TFTelaCadastroPais = class(TFTelaCadastro) LabelEditNome: TLabeledEdit; GroupBox2: TGroupBox; RadioButtonNome: TRadioButton; function MontaFiltro: string; procedure FormCreate(Sender: TObject); function DoSalvar: boolean; override; procedure DoConsultar; override; function DoExcluir: boolean; override; procedure CarregaObjetoSelecionado; override; procedure BitBtnNovoClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; function EditsToObject(Pais: TPaisVo): TPaisVo; end; var FTelaCadastroPais: TFTelaCadastroPais; ControllerPais: TPaisController; implementation {$R *.dfm} procedure TFTelaCadastroPais.BitBtnNovoClick(Sender: TObject); begin inherited; LabelEditNome.SetFocus; end; procedure TFTelaCadastroPais.CarregaObjetoSelecionado; begin if not CDSGrid.IsEmpty then begin ObjetoRetornoVO := TPaisVo.Create; TPaisVo(ObjetoRetornoVO).idPais := CDSGrid.FieldByName('IDPAIS').AsInteger; TPaisVo(ObjetoRetornoVO).NomePais := CDSGrid.FieldByName('NOMEPAIS').AsString; end; end; procedure TFTelaCadastroPais.DoConsultar; var listaPais: TObjectList<TPaisVo>; filtro: string; begin filtro := MontaFiltro; listaPais := ControllerPais.Consultar(filtro); PopulaGrid<TPaisVo>(listaPais); end; function TFTelaCadastroPais.DoExcluir: boolean; var Pais: TPaisVo; begin try try Pais := TPaisVo.Create; Pais.idPais := CDSGrid.FieldByName('IDPAIS').AsInteger; ControllerPais.Excluir(Pais); except on E: Exception do begin ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 + E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroPais.DoSalvar: boolean; var Pais: TPaisVo; begin Pais:=EditsToObject(TPaisVo.Create); try try if (Pais.ValidarCamposObrigatorios()) then begin if (StatusTela = stInserindo) then begin ControllerPais.Inserir(Pais); Result := true; end else if (StatusTela = stEditando) then begin Pais := ControllerPais.ConsultarPorId(CDSGrid.FieldByName('IDPAIS') .AsInteger); Pais := EditsToObject(Pais); ControllerPais.Alterar(Pais); Result := true; end; end else Result := false; except on E: Exception do begin ShowMessage(E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroPais.EditsToObject(Pais: TPaisVo): TPaisVo; begin Pais.NomePais := LabelEditNome.Text; Result := Pais; end; procedure TFTelaCadastroPais.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(ControllerPais); end; procedure TFTelaCadastroPais.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TPaisVo; RadioButtonNome.Checked := true; ControllerPais := TPaisCOntroller.Create; inherited; end; procedure TFTelaCadastroPais.GridParaEdits; var Pais: TPaisVo; begin inherited; if not CDSGrid.IsEmpty then Pais := ControllerPais.ConsultarPorId(CDSGrid.FieldByName('IDPAIS') .AsInteger); if Assigned(Pais) then begin LabelEditNome.Text := Pais.NomePais; end; end; function TFTelaCadastroPais.MontaFiltro: string; begin Result := ''; if (editBusca.Text <> '') then Result := '(UPPER(NOMEPAIS) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end; end.
unit DDMIFinder; interface uses Classes, stdctrls, sysutils; type tDDMI = record nr: integer; depart_id: variant; dem_id: variant; shift_id: variant; end; // pointer to structure pDDMI = ^tDDMI; TDDMIFinder = class(TObject) rowList: array of TList; fRowCount: integer; private procedure AddElement (nRow: integer; aElement: pDDMI); function GetElementCount (nRow: integer): integer; function GetFirstElement (nRow: integer; var aElement: pDDMI):boolean; function GetElementAtIndex (nRow: integer; idx: integer): pDDMI; public constructor Create; destructor Destroy; procedure Init (nRows: integer); function GetRowCount: integer; procedure AddDDMI (aRi, aDDMI: integer); function ContainsDDMI (aRi, aDDMI: integer):boolean; procedure ListAllDDMI (aRi: integer; aMemo: TMemo); end; implementation constructor TDDMIFinder.Create; begin end; destructor TDDMIFinder.Destroy; var i: integer; begin inherited; for i:= 0 to fRowCount - 1 do begin rowList[i].Free; end; SetLength (rowList, 0); end; procedure TDDMIFinder.Init(nRows: integer); var i: integer; aList: TList; begin SetLength (rowList, nRows); fRowCount := nRows; for i:= 0 to nRows - 1 do begin aLIst := TList.Create; rowList[i]:= aList; end; end; procedure TDDMIFinder.AddElement (nRow: integer; aElement: pDDMI); begin rowList[nRow].Add(aElement); end; function TDDMIFinder.GetFirstElement (nRow: integer; var aElement: pDDMI):boolean; begin if rowList[nRow].Count > 0 then begin aElement := rowList[nRow].First; GetFirstElement := true; end else GetFirstElement := false; end; function TDDMIFinder.GetElementAtIndex (nRow: integer; idx: integer): pDDMI; begin if rowList[nRow].Count >= idx then GetElementAtIndex := rowList[nRow].Items[idx] else GetElementAtIndex := nil; end; // PUBLIC methods function TDDMIFinder.GetElementCount (nRow: integer): integer; begin GetElementCount := rowList[nRow].Count; end; function TDDMIFinder.GetRowCount: integer; begin GetRowCount := fRowCount; end; procedure TDDMIFinder.AddDDMI (aRi, aDDMI: integer); var aPtr: pDDMI; begin new (aPtr); aPtr^.nr := aDDMI; AddElement(aRi, aPtr); end; function TDDMIFinder.ContainsDDMI (aRi, aDDMI: integer):boolean; var i: integer; ptd: pDDMI; begin for i:=0 to GetElementCount (aRi) -1 do begin ptd := GetElementAtIndex (aRi, i); if ptd <> nil then begin if ptd^.nr = aDDMI then begin Result := true; exit; end; end; end; Result := false; end; procedure TDDMIFinder.ListAllDDMI (aRi: integer; aMemo: TMemo); var i: integer; ptd: pDDMI; aLine: string; begin aLine := ''; for i:=0 to GetElementCount (aRi) -1 do begin ptd := GetElementAtIndex (aRi, i); if ptd <> nil then begin aLine := aLine + IntToStr(ptd^.nr) + ', '; end; end; aMemo.Lines.Add(aLine); end; end.
unit uBitmap; interface uses system.classes, system.types, vcl.imaging.jpeg, vcl.imaging.pngimage, vcl.graphics, idhttp, system.sysutils; type TBmpHlp = class helper for TBitmap public procedure loadImgFromUrl(url:string); end; implementation { TBmpHlp } procedure TBmpHlp.loadImgFromUrl(url: string); var nhc: TIdHttp; strm : TMemoryStream; jpg :TJPEGImage; ext: string; png: TPngImage; begin ext := url.Substring(url.Length-3,3); nhc:=tidhttp.Create(nil); strm:=TMemoryStream.Create; try nhc.Get(url,strm); if strm.Size >0 then begin strm.Position:=0; if ext='jpg' then begin jpg := tjpegimage.create; try jpg.loadFromStream(strm); assign(jpg); finally jpg.Free; end; end else if ext='png' then begin png := TPngImage.Create; try png.LoadFromStream(strm); assign(png); finally png.Free; end; end; end; finally nhc.Free; strm.Free; end; end; end.
unit AnidbConsts; interface //File states const STATE_UNKNOWN = 0; STATE_HDD = 1; STATE_CD = 2; STATE_DELETED = 3; const // POSITIVE 2XX LOGIN_ACCEPTED = 200; //a LOGIN_ACCEPTED_NEW_VER = 201; //a LOGGED_OUT = 203; //a RESOURCE = 205; //d STATS = 206; //b TOP = 207; //b UPTIME = 208; //b ENCRYPTION_ENABLED = 209; //c MYLIST_ENTRY_ADDED = 210; //a MYLIST_ENTRY_DELETED = 211; //a ADDED_FILE = 214; //e ADDED_STREAM = 215; //e ENCODING_CHANGED = 219; //c C_FILE = 220; //a MYLIST = 221; //a MYLIST_STATS = 222; //b ANIME = 230; //b ANIME_BEST_MATCH = 231; //b RANDOMANIME = 232; //b EPISODE = 240; //b PRODUCER = 245; //b GROUP = 250; //b BUDDY_LIST = 253; //c BUDDY_STATE = 254; //c BUDDY_ADDED = 255; //c BUDDY_DELETED = 256; //c BUDDY_ACCEPTED = 257; //c BUDDY_DENIED = 258; //c VOTED = 260; //b VOTE_FOUND = 261; //b VOTE_UPDATED = 262; //b VOTE_REVOKED = 263; //b NOTIFICATION_ENABLED = 270; //a NOTIFICATION_NOTIFY = 271; //a NOTIFICATION_MESSAGE = 272; //a NOTIFICATION_BUDDY = 273; //c NOTIFICATION_SHUTDOWN = 274; //c PUSHACK_CONFIRMED = 280; //a NOTIFYACK_SUCCESSFUL_M = 281; //a NOTIFYACK_SUCCESSFUL_N = 282; //a NOTIFICATION = 290; //a NOTIFYLIST = 291; //a NOTIFYGET_MESSAGE = 292; //a NOTIFYGET_NOTIFY = 293; //a SENDMSG_SUCCESSFUL = 294; //a USER = 295; //d // AFFIRMATIVE/NEGATIVE 3XX PONG = 300; //a AUTHPONG = 301; //c NO_SUCH_RESOURCE = 305; //d API_PASSWORD_NOT_DEFINED = 309; //c FILE_ALREADY_IN_MYLIST = 310; //a MYLIST_ENTRY_EDITED = 311; //a MULTIPLE_MYLIST_ENTRIES = 312; //e SIZE_HASH_EXISTS = 314; //c INVALID_DATA = 315; //c STREAMNOID_USED = 316; //c NO_SUCH_FILE = 320; //a NO_SUCH_ENTRY = 321; //a MULTIPLE_FILES_FOUND = 322; //b NO_SUCH_ANIME = 330; //b NO_SUCH_EPISODE = 340; //b NO_SUCH_PRODUCER = 345; //b NO_SUCH_GROUP = 350; //b BUDDY_ALREADY_ADDED = 355; //c NO_SUCH_BUDDY = 356; //c BUDDY_ALREADY_ACCEPTED = 357; //c BUDDY_ALREADY_DENIED = 358; //c NO_SUCH_VOTE = 360; //b INVALID_VOTE_TYPE = 361; //b INVALID_VOTE_VALUE = 362; //b PERMVOTE_NOT_ALLOWED = 363; //b ALREADY_PERMVOTED = 364; //b NOTIFICATION_DISABLED = 370; //a NO_SUCH_PACKET_PENDING = 380; //a NO_SUCH_ENTRY_M = 381; //a NO_SUCH_ENTRY_N = 382; //a NO_SUCH_MESSAGE = 392; //a NO_SUCH_NOTIFY = 393; //a NO_SUCH_USER = 394; //a // NEGATIVE 4XX NOT_LOGGED_IN = 403; //a NO_SUCH_MYLIST_FILE = 410; //a NO_SUCH_MYLIST_ENTRY = 411; //a // CLIENT SIDE FAILURE 5XX LOGIN_FAILED = 500; //a LOGIN_FIRST = 501; //a ACCESS_DENIED = 502; //a CLIENT_VERSION_OUTDATED = 503; //a CLIENT_BANNED = 504; //a ILLEGAL_INPUT_OR_ACCESS_DENIED = 505; //a INVALID_SESSION = 506; //a NO_SUCH_ENCRYPTION_TYPE = 509; //c ENCODING_NOT_SUPPORTED = 519; //c BANNED = 555; //a UNKNOWN_COMMAND = 598; //a // SERVER SIDE FAILURE 6XX INTERNAL_SERVER_ERROR = 600; //a ANIDB_OUT_OF_SERVICE = 601; //a SERVER_BUSY = 602; //d API_VIOLATION = 666; //a type //File information that is stored in Anidb TAnidbFileState = record State: integer; State_set: boolean; Viewed: boolean; Viewed_set: boolean; ViewDate: TDatetime; ViewDate_set: boolean; Source: string; Source_set: boolean; Storage: string; Storage_set: boolean; Other: string; Other_set: boolean; end; //True if at least one field is set function AfsSomethingIsSet(afs: TAnidbFileState): boolean; //Updates afs fields with new data (only the parts that were changed) procedure AfsUpdate(var afs: TAnidbFileState; newData: TAnidbFileState); implementation function AfsSomethingIsSet(afs: TAnidbFileState): boolean; begin Result := afs.State_set or afs.Viewed_set or afs.ViewDate_set or afs.Source_set or afs.Storage_set or afs.Other_set; end; procedure AfsUpdate(var afs: TAnidbFileState; newData: TAnidbFileState); begin if newData.State_set then begin afs.State := newData.State; afs.State_set := true; end; if newData.Viewed_set then begin afs.Viewed := newData.Viewed; afs.Viewed_set := true; end; if newData.ViewDate_set then begin afs.ViewDate := newData.ViewDate; afs.ViewDate_set := true; end; if newData.Source_set then begin afs.Source := newData.Source; afs.Source_set := true; end; if newData.Storage_set then begin afs.Storage := newData.Storage; afs.Storage_set := true; end; if newData.Other_set then begin afs.Other := newData.Other; afs.Other_set := true; end; end; end.
{*******************************************************} { } { 软件名称 W.MIS CLIENT MODEL } { 版权所有 (C) 2003, 2004 Esquel.IT } { 单元名称 frmBase.pas } { 创建日期 2004-8-3 9:36:30 } { 创建人员 wuwj } { } {*******************************************************} unit frmBase; {* 所有MDIChild窗体的基窗体单元;} interface uses UShowMessage, Windows, Messages, SysUtils, Variants, Classes, Controls, Forms; type TActionTypeList=(atQuery,atPrint,atPrintPreview,atExportData,atSave); TActionTypeChangedEvent = procedure (Sender: TObject; actionType:TActionTypeList) of object; TBaseForm = class (TForm) {* 基窗体} procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); private FActionType: TActionTypeList; FOnActionTypeChanged:TActionTypeChangedEvent; function GetActionType: TActionTypeList; procedure SetActionType(Value: TActionTypeList); protected procedure DoOnActionChanged(Sender:TObject;actionType:TActionTypeList); procedure ShowMsg(sMsg: string; cursor:TCursor=crDefault); procedure ActionChanged(Sender: TObject;actionType:TActionTypeList); Public Procedure PublicQuery;Virtual; Procedure PublicExport;Virtual; Procedure PublicSave;Virtual; Procedure PublicPrintPreview;Virtual; Procedure PublicPrint;Virtual; published property ActionType: TActionTypeList read GetActionType write SetActionType; property OnActionTypeChanged: TActionTypeChangedEvent read FOnActionTypeChanged write FOnActionTypeChanged ; end; var BaseForm: TBaseForm; implementation {$R *.dfm} procedure TBaseForm.DoOnActionChanged(Sender: TObject; actionType: TActionTypeList); begin if Assigned(FOnActionTypeChanged) then FOnActionTypeChanged(Sender,actionType); end; procedure TBaseForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TBaseForm.FormDestroy(Sender: TObject); begin BaseForm:=nil; end; procedure TBaseForm.FormKeyPress(Sender: TObject; var Key: Char); var s:string; begin if key=#27 then//如果用户按的是ESC键,则向后移动焦点; begin Key:=#0; PerForm(WM_NEXTDLGCTL,1,0); end; if key=#13 then//如果用户按的是Enter键,则向前移动焦点; begin if not ((ActiveControl.ClassNameIs('TDBGrid')) or (ActiveControl.ClassNameIs('TMemo')) or (ActiveControl.ClassNameIs('TdxTreeList')) or (ActiveControl.ClassNameIs('TdxDBGrid')) or (ActiveControl.ClassNameIs('TcxGridSite')) or (ActiveControl.ClassNameIs('TDBMemo')) or (ActiveControl.ClassNameIs('TcxCustomInnerMemo'))or (ActiveControl.ClassNameIs('TListBox')) or (ActiveControl.ClassNameIs('TValueListEditor')) or (ActiveControl.ClassNameIs('TListView'))) then begin Key:=#0; PerForm(WM_NEXTDLGCTL,0,0); end; end; end; function TBaseForm.GetActionType: TActionTypeList; begin Result := FActionType; end; procedure TBaseForm.SetActionType(Value: TActionTypeList); begin FActionType := Value; DoOnActionChanged(self,value); end; procedure TBaseForm.FormCreate(Sender: TObject); begin BaseForm:=self; Self.Position :=poDefault; self.OnActionTypeChanged :=ActionChanged; end; procedure TBaseForm.ActionChanged(Sender: TObject;actionType:TActionTypeList); begin case actionType of atQuery: PublicQuery ; atExportData: PublicExport; atSave: PublicSave; atPrintPreview: PublicPrintPreview; atPrint: PublicPrint; end; end; Procedure TBaseForm.PublicQuery; begin end; Procedure TBaseForm.PublicExport; begin end; Procedure TBaseForm.PublicSave; begin end; Procedure TBaseForm.PublicPrintPreview; begin end; Procedure TBaseForm.PublicPrint; begin end; procedure TBaseForm.ShowMsg(sMsg: string; cursor: TCursor); begin ShowStatusMessage(sMsg,cursor); //TStatusBarMessage.ShowMessageOnMainStatsusBar(sMsg,cursor); end; end.
program DarwinDynlibTestExecutable; {$APPTYPE CONSOLE} {$mode objfpc}{$H+} uses DynLibs, {$IFDEF UNIX} cthreads, {$ENDIF} Classes, SysUtils, CustApp; type { TMyApplication } TMyApplication = class(TCustomApplication) private procedure Test(AFilename, AFunctionName: string); protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; end; var Application: TMyApplication; {$IF DEFINED(MSWindows)} const SLibName = 'DarwinDynlibTestLibrary.dll'; {$ELSEIF DEFINED(Darwin)} SLibName: string = 'libdarwindynlibtestlibrary.dylib'; {$IFEND} { TMyApplication } procedure TMyApplication.Test(AFilename, AFunctionName: string); var h: TLibHandle; sFilename: string; p: Pointer; begin sFilename := ExtractFilePath(Application.ExeName) + AFilename; WriteLn('[i] ', sFilename); h := LoadLibrary(sFilename); if (h = NilHandle) then begin WriteLn('[-] LoadLibrary(); GetLastOSError = ', SysErrorMessage(GetLastOSError), '; GetLoadErrorStr = ', GetLoadErrorStr); Exit; end else begin WriteLn('[+] LoadLibrary() = ', IntToStr(h), '; GetLoadErrorStr = ', GetLoadErrorStr); end; p := GetProcedureAddress(h, AFunctionName); if not Assigned(p) then begin WriteLn('[-] GetProcAddress(', AFunctionName, '); GetLastOSError = ', SysErrorMessage(GetLastOSError), '; GetLoadErrorStr = ', GetLoadErrorStr); end else begin WriteLn('[+] GetProcAddress(', AFunctionName, ')'); end; p := nil; p := GetProcedureAddress(h, '_' + AFunctionName); if not Assigned(p) then begin WriteLn('[-] GetProcAddress(_', AFunctionName, '); GetLastOSError = ', SysErrorMessage(GetLastOSError), '; GetLoadErrorStr = ', GetLoadErrorStr); end else begin WriteLn('[+] GetProcAddress(_', AFunctionName, ')'); end; end; procedure TMyApplication.DoRun; begin WriteLn('[i] Test Version 2'); Test(SLibName, 'FourtyTwo'); Terminate; end; constructor TMyApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; end; destructor TMyApplication.Destroy; begin inherited Destroy; end; begin Application := TMyApplication.Create(nil); Application.Title := 'My Application'; Application.Run; Application.Free; end.
unit uRepositorySystemPostgreSQL; interface uses Dialogs, uDM_RepositoryPostgreSQL, uiRepoSystem, uCustomers, uUsers, uProducts, System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TDM_RepositorySystemPostgreSQL = class(TDataModule, iRepoSystem) QryCustomerPostgreSQL: TFDQuery; QryUserPostgreSQL: TFDQuery; QryProductPostgreSQL: TFDQuery; private { Private declarations } public { Public declarations } function ReturnCustomer(id: Integer): TCustomer; function ReturnProduct(id: Integer): TProducts; function ReturnUser(id: Integer): TUser; end; var DM_RepositorySystemPostgreSQL: TDM_RepositorySystemPostgreSQL; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDM_RepositorySystemPostgreSQL } function TDM_RepositorySystemPostgreSQL.ReturnCustomer(id: Integer): TCustomer; begin Try QryCustomerPostgreSQL.Close; QryCustomerPostgreSQL.ParamByName('id').Value := id; QryCustomerPostgreSQL.Open; if not QryCustomerPostgreSQL.IsEmpty then begin Result := TCustomer.Create; Result.id := QryCustomerPostgreSQL.FieldByName('id_customer').AsInteger; Result.name := QryCustomerPostgreSQL.FieldByName('customer_name').AsString; Result.status := QryCustomerPostgreSQL.FieldByName('customer_status').AsInteger; end else Result := nil; Except On E : Exception do ShowMessage(E.Message); End; end; function TDM_RepositorySystemPostgreSQL.ReturnProduct(id: Integer): TProducts; begin Try QryProductPostgreSQL.Close; QryProductPostgreSQL.ParamByName('id').Value := id; QryProductPostgreSQL.Open; if not QryProductPostgreSQL.IsEmpty then begin Result := TProducts.Create; Result.id := QryProductPostgreSQL.FieldByName('id_product').AsInteger; Result.code := QryProductPostgreSQL.FieldByName('code').AsString; Result.descr := QryProductPostgreSQL.FieldByName('descr').AsString; Result.list_price := QryProductPostgreSQL.FieldByName('list_price').AsFloat; Result.tax := QryProductPostgreSQL.FieldByName('tax').AsFloat; Result.quantity := QryProductPostgreSQL.FieldByName('quantity').AsFloat; end else Result := nil; Except On E : Exception do ShowMessage(E.Message); End; end; function TDM_RepositorySystemPostgreSQL.ReturnUser(id: Integer): TUser; begin Try QryUserPostgreSQL.Close; QryUserPostgreSQL.ParamByName('id').Value := id; QryUserPostgreSQL.Open; if not QryUserPostgreSQL.IsEmpty then begin Result := TUser.Create; Result.id := QryUserPostgreSQL.FieldByName('id_user').AsInteger; Result.login := QryUserPostgreSQL.FieldByName('login').AsString; Result.password := QryUserPostgreSQL.FieldByName('password').AsString; end else Result := nil; Except On E : Exception do ShowMessage(E.Message); End; end; end.
{******************************************************************************* Title: T2TiPDV Description: Lista as NFC-e. The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: alberteije@gmail.com @author T2Ti.COM @version 1.0 *******************************************************************************} unit UListaNfce; {$mode objfpc}{$H+} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, StdCtrls, Buttons, ExtCtrls, LabeledCtrls, DB, FMTBcd, ZAbstractRODataset, ZAbstractDataset, ZDataset, ACBrBase, ACBrEnterTab, UBase, Tipos; type TCustomDBGridCracker = class(TCustomDBGrid); { TFListaNfce } TFListaNfce = class(TFBase) ACBrEnterTab1: TACBrEnterTab; ComboBoxProcedimento: TLabeledComboBox; Image1: TImage; botaoConfirma: TBitBtn; botaoCancela: TBitBtn; GridPrincipal: TDBGrid; Image2: TImage; Panel1: TPanel; Label1: TLabel; EditLocaliza: TEdit; SpeedButton1: TSpeedButton; DSNFCe: TDataSource; Label2: TLabel; procedure botaoCancelaClick(Sender: TObject); procedure ComboBoxProcedimentoChange(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure Localiza; procedure Confirma; procedure SpeedButton1Click(Sender: TObject); procedure FormActivate(Sender: TObject); procedure GridPrincipalKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure botaoConfirmaClick(Sender: TObject); procedure EditLocalizaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure EditLocalizaKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); private { Private declarations } public { Public declarations } Operacao: String; Confirmou: Boolean; QNFCe: TZQuery; end; var FListaNfce: TFListaNfce; implementation uses UDataModule, VendaController, UCaixa; {$R *.lfm} {$REGION 'Infra'} procedure TFListaNfce.FormActivate(Sender: TObject); begin Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); Confirmou := False; ComboBoxProcedimento.Clear; if Operacao = 'RecuperarVenda' then begin ComboBoxProcedimento.Items.Add('Recuperar Venda'); end else if Operacao = 'CancelaInutiliza' then begin ComboBoxProcedimento.Items.Add('Cancelar NFC-e'); ComboBoxProcedimento.Items.Add('Inutilizar Número'); end; ComboBoxProcedimento.ItemIndex := 0; end; procedure TFListaNfce.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin FCaixa.editCodigo.SetFocus; CloseAction := caFree; end; procedure TFListaNfce.EditLocalizaKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if (Key = VK_RETURN) or (Key = VK_UP) or (Key = VK_DOWN) then GridPrincipal.SetFocus; end; procedure TFListaNfce.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if Key = VK_F2 then Localiza; if Key = VK_F12 then Confirma; if key = VK_ESCAPE then botaoCancela.Click; end; procedure TFListaNfce.GridPrincipalKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if Key = VK_RETURN then EditLocaliza.SetFocus; end; procedure TFListaNfce.botaoCancelaClick(Sender: TObject); begin Close; end; {$ENDREGION 'Infra'} {$REGION 'Pesquisa e Confirmação'} procedure TFListaNfce.SpeedButton1Click(Sender: TObject); begin Localiza; end; procedure TFListaNfce.botaoConfirmaClick(Sender: TObject); begin if GridPrincipal.DataSource.DataSet.Active then begin if GridPrincipal.DataSource.DataSet.RecordCount > 0 then Confirma else begin Application.MessageBox('Não existem registros selecionados!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditLocaliza.SetFocus; end; end else begin Application.MessageBox('Não existem registros selecionados!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditLocaliza.SetFocus; end; end; procedure TFListaNfce.ComboBoxProcedimentoChange(Sender: TObject); begin if ComboBoxProcedimento.Text <> 'Recuperar Venda' then Localiza; end; procedure TFListaNfce.Confirma; begin Confirmou := True; Close; end; procedure TFListaNfce.EditLocalizaKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); begin if Length(trim(EditLocaliza.Text)) > 1 then Localiza; end; procedure TFListaNfce.localiza; var ProcurePor, Filtro: string; begin ProcurePor := '%' + EditLocaliza.Text + '%'; if ComboBoxProcedimento.Text = 'Recuperar Venda' then Filtro := 'STATUS_NOTA < 4 AND NUMERO LIKE '+ QuotedStr(ProcurePor) else if ComboBoxProcedimento.Text = 'Cancelar NFC-e' then Filtro := 'STATUS_NOTA = 4 AND NUMERO LIKE '+ QuotedStr(ProcurePor) else if ComboBoxProcedimento.Text = 'Inutilizar Número' then Filtro := 'STATUS_NOTA < 4 AND NUMERO LIKE '+ QuotedStr(ProcurePor); QNFCe := TVendaController.Consulta(Filtro, '-1'); QNFCe.Active := True; DSNFCe.DataSet := QNFCe; end; {$ENDREGION 'Pesquisa e Confirmação'} end.
unit Rows.Title.Config; interface uses Interfaces, Injection; Type TModelHTMLRowsTitleConfig = class(TInterfacedObject, IModelRowsTitleConfig) private FParent : iModelHTMLRowsTitle; FH1 : String; FH2 : String; FH3 : String; FH4 : String; FH5 : String; public constructor Create(Parent : iModelHTMLRowsTitle); destructor Destroy; override; class function New(Parent : iModelHTMLRowsTitle) : IModelRowsTitleConfig; function H1(Value: String): IModelRowsTitleConfig; overload; function H1: String; overload; function H2(Value: String): IModelRowsTitleConfig; overload; function H2: String; overload; function H3(Value: String): IModelRowsTitleConfig; overload; function H3: String; overload; function H4(Value: String): IModelRowsTitleConfig; overload; function H4: String; overload; function H5(Value: String): IModelRowsTitleConfig; overload; function H5: String; overload; function &End: iModelHTMLRowsTitle; end; implementation { TModelHTMLRowsTitleConfig } function TModelHTMLRowsTitleConfig.&End: iModelHTMLRowsTitle; begin Result := FParent; end; constructor TModelHTMLRowsTitleConfig.Create(Parent : iModelHTMLRowsTitle); begin TInjection.Weak(@FParent, IInterface(Parent)); end; destructor TModelHTMLRowsTitleConfig.Destroy; begin inherited; end; function TModelHTMLRowsTitleConfig.H1: String; begin Result := FH1; end; function TModelHTMLRowsTitleConfig.H1( Value: String): IModelRowsTitleConfig; begin Result := Self; FH1 := Value; end; function TModelHTMLRowsTitleConfig.H2: String; begin Result := FH2; end; function TModelHTMLRowsTitleConfig.H2( Value: String): IModelRowsTitleConfig; begin Result := Self; FH2 := Value; end; function TModelHTMLRowsTitleConfig.H3( Value: String): IModelRowsTitleConfig; begin Result := Self; FH3 := Value; end; function TModelHTMLRowsTitleConfig.H3: String; begin Result := FH3; end; function TModelHTMLRowsTitleConfig.H4( Value: String): IModelRowsTitleConfig; begin Result := Self; FH4 := Value; end; function TModelHTMLRowsTitleConfig.H4: String; begin Result := FH4; end; function TModelHTMLRowsTitleConfig.H5( Value: String): IModelRowsTitleConfig; begin Result := Self; FH5 := Value; end; function TModelHTMLRowsTitleConfig.H5: String; begin Result := FH5; end; class function TModelHTMLRowsTitleConfig.New(Parent : iModelHTMLRowsTitle): IModelRowsTitleConfig; begin Result := Self.Create(Parent); end; end.
(* Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED Original name: 0021.PAS Description: A source code mangler Author: SWAG SUPPORT TEAM Date: 07-16-93 06:11 *) { Here is a VERY simple source-code mangler that I just made. It simply: 1) Removes whitespace, 2) Removes comments (but not Compiler-directives!), 3) Makes everything upper-Case. 4) Make lines max. 127 Chars wide (max. For Turbo Pascal), 5) Doesn't mess up literal Strings :-) I don't imagine that this is anything Near perfect - but it's better than nothing... } Program Mangler; Const Alpha : Set of Char = ['a'..'z', 'A'..'Z', '0'..'9']; Var F, F2 : Text; R, S : String; X : Byte; InString : Boolean; Function NumChar(C : Char; S : String; Max : Byte) : Byte; Var N, Y : Byte; begin N := 0; For Y := 1 to Max do if S[Y] = C then Inc(N); NumChar := N; end; Function TrimF(T : String) : String; Var T2 : String; begin T2 := T; While (Length(T2) > 0) and (T2[1] = ' ') do Delete(T2, 1, 1); TrimF := T2; end; Function Trim(T : String) : String; Var T2 : String; begin T2 := TrimF(T); While (Length(T2) > 0) and (T2[Length(T2)] = ' ') do Delete(T2, Length(T2), 1); Trim := T2; end; Procedure StripComments(Var T : String); Var Y : Byte; Rem : Boolean; begin Rem := True; if Pos('(*', T) > 0 then begin For Y := Pos('(*', T) to Pos('*)', T) do if (T[Y] = '$') or (T[Y] = '''') then Rem := False; if (Rem) and (not Odd(NumChar('''', T, Pos('(*', T)))) then Delete(T, Pos('(*', T), Pos('*)', T)+2-Pos('(*', T)); end; if Pos('{', T) > 0 then begin For Y := Pos('{', T) to Pos('}', T) do if (T[Y] = '$') or (T[Y] = '''') then Rem := False; if (Rem) and (not Odd(NumChar('''', T, Pos('(*', T)))) then Delete(T, Pos('{', T), Pos('}', T)+1-Pos('{', T)); end; end; begin Write('Enter file name: '); ReadLn(S); Assign(F, S); Reset(F); ReadLn(S); Assign(F2, S); ReWrite(F2); R := ''; S := ''; While not EoF(F) do begin ReadLn(F, R); StripComments(R); R := Trim(R); X := 1; InString := false; While X <= Length(R) do begin InString := (R[X] = '''') xor InString; if not InString then begin if R[X] = #9 then R[X] := ' '; if ((R[X] = ' ') and (R[X+1] = ' ')) then begin Delete(R, X, 1); if X > 1 then Dec(X); end; if ((R[X] = ' ') and not(R[X+1] in Alpha)) then Delete(R, X, 1); if ((R[X+1] = ' ') and not(R[X] in Alpha)) then Delete(R, X+1, 1); R[X] := UpCase(R[X]); end; Inc(X); end; if (Length(R) > 0) and (R[Length(R)] <> ';') then R := R+' '; if Length(R)+Length(S) <= 127 then S := TrimF(S+R) else begin WriteLn(F2, Trim(S)); S := TrimF(R); end; end; WriteLn(F2, S); Close(F); Close(F2); end. { > 1) Remove whitespace. Just removes indentation now. > 2) Put lines together (max. length approx. 120 Chars). This is going to be one of the harder parts. > 3) Make everything lower-Case (or upper-Case). No need.. see 4. 4. Convert all Types, Consts, and VarS to an encypted name, like so: IIl0lll1O0lI1 5. Convert all Procedures, and Functions like #4 6. On Objects, Convert all "data" fields. Leave alone all others except For the "ConstRUCtoR" and on that, only check to see if any Types are being used. Constructors are the only ones that can change from the ancestor. 7. on Records, When Typed like this: aRec.Name:='Rob Green'; check to see if arec is in the list, if not, skip. if like this: With arec do name:='Rob Green'; do the same as above, but check For begin and end. 8. Leave externals alone. 9. Also mangle the Includes. 10. Leave Any Interface part alone, and only work With the Implementation. This is what my mangler currently does.(all except For #7 and #10, havent got that Far yet.) Any ways it works pretty good. im happy With the results i am getting With it. It makes it "VERY" hard to read. The only thing i see having trouble With down the line, is the "Compressing" of mulitiple lines. Anyways, heres a small Program, and then what PAM(Pascal automatic mangler) did to it: } Program test; Type pstr30 = ^str30; str30 = String[30]; Var b : Byte; s : pstr30; Function hex(b : Byte) : String; Const Digits : Array [0..15] of Char = '0123456789ABCDEF'; Var s:String; begin s:=''; s[0] := #2; s[1] := Digits [b shr 4]; s[2] := Digits [b and $F]; hex:=s; end; begin new(s); s^:='Hello world'; Writeln(s^); Writeln('Enter a Byte to convert to hex:'); readln(b); s^:=hex(b); Writeln('Byte :',b,' = $',s^); dispose(s); end. Program test; Type IO1II0IO00O = ^II0lOl1011I; II0lOl1011I = String[30]; Var III0O1ll10l:Byte; I11110I11Il0:IO1II0IO00O; Function Il00O011IO0I(III0O1ll10l:Byte):String; Const Illl1OOOO0I : Array [0..15] of Char = '0123456789ABCDEF'; Var I11110I11Il0:String; begin I11110I11Il0:=''; I11110I11Il0[0] := #2; I11110I11Il0[1] := Illl1OOOO0I [III0O1ll10l shr 4]; I11110I11Il0[2] := Illl1OOOO0I [III0O1ll10l and $F]; Il00O011IO0I:=I11110I11Il0; end; begin new(I11110I11Il0); I11110I11Il0^:='Hello world'; Writeln(I11110I11Il0^); Writeln('Enter a Byte to convert to hex:'); readln(III0O1ll10l); I11110I11Il0^:=Il00O011IO0I(III0O1ll10l); Writeln('Byte :',III0O1ll10l,' = $',I11110I11Il0^); dispose(I11110I11Il0); end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Components and functions that abstract file I/O access for an application. Allows re-routing file reads to reads from a single archive file f.i. } unit VXS.ApplicationFileIO; interface {$I VXScene.inc} uses Winapi.Windows, System.Classes, System.SysUtils, FMX.Dialogs, VXS.BaseClasses; const VXS_RC_DDS_Type = RT_RCDATA; VXS_RC_JPG_Type = RT_RCDATA; VXS_RC_XML_Type = RT_RCDATA; VXS_RC_String_Type = RT_RCDATA; type TVXApplicationResource = ( aresNone, aresSplash, aresTexture, aresMaterial, aresSampler, aresFont, aresMesh); TAFIOCreateFileStream = function(const fileName: string; mode: Word): TStream; TAFIOFileStreamExists = function(const fileName: string): Boolean; TAFIOFileStreamEvent = procedure (const fileName : String; mode : Word; var Stream : TStream) of object; TAFIOFileStreamExistsEvent = function(const fileName: string): Boolean of object; { Allows specifying a custom behaviour for CreateFileStream. The component should be considered a helper only, you can directly specify a function via the vAFIOCreateFileStream variable. If multiple ApplicationFileIO components exist in the application, the last one created will be the active one. } TVXApplicationFileIO = class(TComponent) private FOnFileStream: TAFIOFileStreamEvent; FOnFileStreamExists: TAFIOFileStreamExistsEvent; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Event that allows you to specify a stream for the file. Destruction of the stream is at the discretion of the code that invoked CreateFileStream. Return nil to let the default mechanism take place (ie. attempt a regular file system access). } property OnFileStream: TAFIOFileStreamEvent read FOnFileStream write FOnFileStream; { Event that allows you to specify if a stream for the file exists. } property OnFileStreamExists: TAFIOFileStreamExistsEvent read FOnFileStreamExists write FOnFileStreamExists; end; TVXDataFileCapability = (dfcRead, dfcWrite); TVXDataFileCapabilities = set of TVXDataFileCapability; { Abstract base class for data file formats interfaces. This class declares base file-related behaviours, ie. ability to load/save from a file or a stream. It is highly recommended to overload ONLY the stream based methods, as the file-based one just call these, and stream-based behaviours allow for more enhancement (such as other I/O abilities, compression, cacheing, etc.) to this class, without the need to rewrite subclasses. } TVXDataFile = class(TVXUpdateAbleObject) private FResourceName: string; procedure SetResourceName(const AName: string); public { Describes what the TVXDataFile is capable of. Default value is [dfcRead]. } class function Capabilities: TVXDataFileCapabilities; virtual; { Duplicates Self and returns a copy. Subclasses should override this method to duplicate their data. } function CreateCopy(AOwner: TPersistent): TVXDataFile; virtual; procedure LoadFromFile(const fileName: string); virtual; procedure SaveToFile(const fileName: string); virtual; procedure LoadFromStream(stream: TStream); virtual; procedure SaveToStream(stream: TStream); virtual; procedure Initialize; virtual; { Optionnal resource name. When using LoadFromFile/SaveToFile, the filename is placed in it, when using the Stream variants, the caller may place the resource name in it for parser use. } property ResourceName: string read FResourceName write SetResourceName; end; TVXDataFileClass = class of TVXDataFile; TVXResourceStream = TResourceStream; // Returns true if an ApplicationFileIO has been defined function ApplicationFileIODefined: Boolean; (*Creates a file stream corresponding to the fileName. If the file does not exists, an exception will be triggered. Default mechanism creates a regular TFileStream, the 'mode' parameter is similar to the one for TFileStream. *) function CreateFileStream(const fileName: string; mode: Word = fmOpenRead + fmShareDenyNone): TStream; // Queries is a file stream corresponding to the fileName exists. function FileStreamExists(const fileName: string): Boolean; function CreateResourceStream(const ResName: string; ResType: PChar): TVXResourceStream; function StrToGLSResType(const AStrRes: string): TVXApplicationResource; var vAFIOCreateFileStream: TAFIOCreateFileStream = nil; vAFIOFileStreamExists: TAFIOFileStreamExists = nil; // --------------------------------------------------------------------- implementation // --------------------------------------------------------------------- var vAFIO: TVXApplicationFileIO = nil; function ApplicationFileIODefined: Boolean; begin Result := (Assigned(vAFIOCreateFileStream) and Assigned(vAFIOFileStreamExists)) or Assigned(vAFIO); end; function CreateFileStream(const fileName: string; mode: Word = fmOpenRead + fmShareDenyNone): TStream; begin if Assigned(vAFIOCreateFileStream) then Result := vAFIOCreateFileStream(fileName, mode) else begin Result:=nil; if Assigned(vAFIO) and Assigned(vAFIO.FOnFileStream) then vAFIO.FOnFileStream(fileName, mode, Result); if not Assigned(Result) then begin if ((mode and fmCreate)=fmCreate) or FileExists(fileName) then Result := TFileStream.Create(fileName, mode) else raise Exception.Create('File not found: "'+fileName+'"'); end; end; end; function FileStreamExists(const fileName: string): Boolean; begin if Assigned(vAFIOFileStreamExists) then Result := vAFIOFileStreamExists(fileName) else begin if Assigned(vAFIO) and Assigned(vAFIO.FOnFileStreamExists) then Result := vAFIO.FOnFileStreamExists(fileName) else Result := FileExists(fileName); end; end; function CreateResourceStream(const ResName: string; ResType: PChar): TVXResourceStream; var InfoBlock: HRSRC; begin Result := nil; InfoBlock := FindResource(HInstance, PChar(ResName), ResType); if InfoBlock <> 0 then Result := TResourceStream.Create(HInstance, ResName, ResType) else ShowMessage(Format('Can''t create stream of application resource "%s"', [ResName])); end; // ------------------ // ------------------ TVXApplicationFileIO ------------------ // ------------------ constructor TVXApplicationFileIO.Create(AOwner: TComponent); begin inherited Create(AOwner); vAFIO := Self; end; destructor TVXApplicationFileIO.Destroy; begin vAFIO := nil; inherited Destroy; end; // ------------------ // ------------------ TVXDataFile ------------------ // ------------------ class function TVXDataFile.Capabilities: TVXDataFileCapabilities; begin Result := [dfcRead]; end; function TVXDataFile.CreateCopy(AOwner: TPersistent): TVXDataFile; begin if Self <> nil then Result := TVXDataFileClass(Self.ClassType).Create(AOwner) else Result := nil; end; procedure TVXDataFile.LoadFromFile(const fileName: string); var fs: TStream; begin ResourceName := ExtractFileName(fileName); fs := CreateFileStream(fileName, fmOpenRead + fmShareDenyNone); try LoadFromStream(fs); finally fs.Free; end; end; procedure TVXDataFile.SaveToFile(const fileName: string); var fs: TStream; begin ResourceName := ExtractFileName(fileName); fs := CreateFileStream(fileName, fmCreate); try SaveToStream(fs); finally fs.Free; end; end; procedure TVXDataFile.LoadFromStream(stream: TStream); begin Assert(False, 'Import for ' + ClassName + ' to ' + stream.ClassName + ' not available.'); end; procedure TVXDataFile.SaveToStream(stream: TStream); begin Assert(False, 'Export for ' + ClassName + ' to ' + stream.ClassName + ' not available.'); end; procedure TVXDataFile.Initialize; begin end; procedure TVXDataFile.SetResourceName(const AName: string); begin FResourceName := AName; end; function StrToGLSResType(const AStrRes: string): TVXApplicationResource; begin if AStrRes = '[SAMPLERS]' then begin Result := aresSampler; end else if AStrRes = '[TEXTURES]' then begin Result := aresTexture; end else if AStrRes = '[MATERIALS]' then begin Result := aresMaterial; end else if AStrRes = '[STATIC MESHES]' then begin Result := aresMesh; end else if AStrRes = '[SPLASH]' then begin Result := aresSplash; end else if AStrRes = '[FONTS]' then begin Result := aresFont; end else Result := aresNone; end; end.
unit ibSHTool; interface uses SysUtils, Classes, SHDesignIntf, SHOptionsIntf, ibSHDesignIntf, ibSHConsts, ibSHComponent; type TibBTTool = class(TibBTComponent, IibSHTool) private protected FBTCLServerIntf: IibSHServer; FBTCLDatabaseIntf: IibSHDatabase; function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; function GetBTCLServer: IibSHServer; function GetBTCLDatabase: IibSHDatabase; function GetBranchIID: TGUID; override; function GetCaption: string; override; function GetCaptionExt: string; override; function GetCaptionPath: string; override; procedure SetOwnerIID(Value: TGUID); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetHintClassFnc: string; override; class function GetAssociationClassFnc: string; override; { properties } property BTCLServer: IibSHServer read GetBTCLServer; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; end; TibBTToolFactory = class(TibBTComponentFactory) private procedure CheckStart(const AOwnerIID, AClassIID: TGUID); function GetWantedOwnerIID(const AClassIID: TGUID): TGUID; protected procedure DoBeforeChangeNotification(var ACallString: string; AComponent: TSHComponent); virtual; public function SupportComponent(const AClassIID: TGUID): Boolean; override; function CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; override; end; implementation uses ibSHValues, ibSHMessages; { TibBTTool } constructor TibBTTool.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TibBTTool.Destroy; begin inherited Destroy; end; class function TibBTTool.GetHintClassFnc: string; begin Result := inherited GetHintClassFnc; if Supports(Self, IibSHSQLEditor) then Result := SClassHintSQLEditor else if Supports(Self, IibSHDMLHistory) then Result := SClassHintDMLHistory else if Supports(Self, IibSHDDLHistory) then Result := SClassHintDDLHistory else if Supports(Self, IibSHSQLPerformance) then Result := SClassHintSQLPerformance else if Supports(Self, IibSHSQLPlan) then Result := SClassHintSQLPlan else if Supports(Self, IibSHSQLPlayer) then Result := SClassHintSQLPlayer else if Supports(Self, IibSHDMLExporter) then Result := SClassHintDMLExporter else if Supports(Self, IibSHFIBMonitor) then Result := SClassHintFIBMonitor else if Supports(Self, IibSHIBXMonitor) then Result := SClassHintIBXMonitor else if Supports(Self, IibSHDDLGrantor) then Result := SClassHintDDLGrantor else if Supports(Self, IibSHUserManager) then Result := SClassHintUserManager else if Supports(Self, IibSHDDLCommentator) then Result := SClassHintDDLCommentator else if Supports(Self, IibSHDDLDocumentor) then Result := SClassHintDDLDocumentor else if Supports(Self, IibSHDDLFinder) then Result := SClassHintDDLFinder else if Supports(Self, IibSHDDLExtractor) then Result := SClassHintDDLExtractor else if Supports(Self, IibSHTXTLoader) then Result := SClassHintTXTLoader else if Supports(Self, IibSHBlobEditor) then Result := SClassHintBlobEditor else if Supports(Self, IibSHDDLDocumentor) then Result := SClassHintDDLDocumentor else if Supports(Self, IibSHReportManager) then Result := SClassHintReportManager else if Supports(Self, IibSHDataGenerator) then Result := SClassHintDataGenerator else if Supports(Self, IibSHDBComparer) then Result := SClassHintDBComparer else if Supports(Self, IibSHSecondaryFiles) then Result := SClassHintSecondaryFiles else if Supports(Self, IibSHCVSExchanger) then Result := SClassHintCVSExchanger else if Supports(Self, IibSHDBDesigner) then Result := SClassHintDBDesigner else if Supports(Self, IibSHPSQLDebugger) then Result := SClassHintPSQLDebugger else // Services if Supports(Self, IibSHServerProps) then Result := SClassHintServerProps else if Supports(Self, IibSHServerLog) then Result := SClassHintServerLog else if Supports(Self, IibSHServerConfig) then Result := SClassHintServerConfig else if Supports(Self, IibSHServerLicense) then Result := SClassHintServerLicense else if Supports(Self, IibSHDatabaseShutdown) then Result := SClassHintDatabaseShutdown else if Supports(Self, IibSHDatabaseOnline) then Result := SClassHintDatabaseOnline else if Supports(Self, IibSHDatabaseBackup) then Result := SClassHintDatabaseBackup else if Supports(Self, IibSHDatabaseRestore) then Result := SClassHintDatabaseRestore else if Supports(Self, IibSHDatabaseStatistics) then Result := SClassHintDatabaseStatistics else if Supports(Self, IibSHDatabaseValidation) then Result := SClassHintDatabaseValidation else if Supports(Self, IibSHDatabaseSweep) then Result := SClassHintDatabaseSweep else if Supports(Self, IibSHDatabaseMend) then Result := SClassHintDatabaseMend else if Supports(Self, IibSHTransactionRecovery) then Result := SClassHintTransactionRecovery else if Supports(Self, IibSHDatabaseProps) then Result := SClassHintDatabaseProps; end; class function TibBTTool.GetAssociationClassFnc: string; begin Result := inherited GetAssociationClassFnc; if Supports(Self, IibSHSQLEditor) then Result := SClassAssocSQLEditor; if Supports(Self, IibSHDMLHistory) then Result := SClassAssocDMLHistory; if Supports(Self, IibSHDDLHistory) then Result := SClassAssocDDLHistory; if Supports(Self, IibSHSQLPerformance) then Result := SClassAssocSQLPerformance; if Supports(Self, IibSHSQLPlan) then Result := SClassAssocSQLPlan; if Supports(Self, IibSHSQLPlayer) then Result := SClassAssocSQLPlayer; if Supports(Self, IibSHDMLExporter) then Result := SClassAssocDMLExporter; if Supports(Self, IibSHFIBMonitor) then Result := SClassAssocFIBMonitor; if Supports(Self, IibSHIBXMonitor) then Result := SClassAssocIBXMonitor; if Supports(Self, IibSHDDLGrantor) then Result := SClassAssocDDLGrantor; if Supports(Self, IibSHUserManager) then Result := SClassAssocUserManager; if Supports(Self, IibSHDDLCommentator) then Result := SClassAssocDDLCommentator; if Supports(Self, IibSHDDLDocumentor) then Result := SClassAssocDDLDocumentor; if Supports(Self, IibSHDDLFinder) then Result := SClassAssocDDLFinder; if Supports(Self, IibSHDDLExtractor) then Result := SClassAssocDDLExtractor; if Supports(Self, IibSHTXTLoader) then Result := SClassAssocTXTLoader; if Supports(Self, IibSHBlobEditor) then Result := SClassAssocBlobEditor; if Supports(Self, IibSHDDLDocumentor) then Result := SClassAssocDDLDocumentor; if Supports(Self, IibSHReportManager) then Result := SClassAssocReportManager; if Supports(Self, IibSHDataGenerator) then Result := SClassAssocDataGenerator; if Supports(Self, IibSHDBComparer) then Result := SClassAssocDBComparer; if Supports(Self, IibSHSecondaryFiles) then Result := SClassAssocSecondaryFiles; if Supports(Self, IibSHCVSExchanger) then Result := SClassAssocCVSExchanger; if Supports(Self, IibSHDBDesigner) then Result := SClassAssocDBDesigner; if Supports(Self, IibSHPSQLDebugger) then Result := SClassAssocPSQLDebugger; // Services if Supports(Self, IibSHServerProps) then Result := SClassAssocServerProps; if Supports(Self, IibSHServerLog) then Result := SClassAssocServerLog; if Supports(Self, IibSHServerConfig) then Result := SClassAssocServerConfig; if Supports(Self, IibSHServerLicense) then Result := SClassAssocServerLicense; if Supports(Self, IibSHDatabaseShutdown) then Result := SClassAssocDatabaseShutdown; if Supports(Self, IibSHDatabaseOnline) then Result := SClassAssocDatabaseOnline; if Supports(Self, IibSHDatabaseBackup) then Result := SClassAssocDatabaseBackup; if Supports(Self, IibSHDatabaseRestore) then Result := SClassAssocDatabaseRestore; if Supports(Self, IibSHDatabaseStatistics) then Result := SClassAssocDatabaseStatistics; if Supports(Self, IibSHDatabaseValidation) then Result := SClassAssocDatabaseValidation; if Supports(Self, IibSHDatabaseSweep) then Result := SClassAssocDatabaseSweep; if Supports(Self, IibSHDatabaseMend) then Result := SClassAssocDatabaseMend; if Supports(Self, IibSHTransactionRecovery) then Result := SClassAssocTransactionRecovery; if Supports(Self, IibSHDatabaseProps) then Result := SClassAssocDatabaseProps; end; function TibBTTool.QueryInterface(const IID: TGUID; out Obj): HResult; begin if IsEqualGUID(IID, IibSHDatabase) then begin IInterface(Obj) := FBTCLDatabaseIntf; if Pointer(Obj) <> nil then Result := S_OK else Result := E_NOINTERFACE; end else Result := inherited QueryInterface(IID, Obj); end; function TibBTTool.GetBTCLServer: IibSHServer; begin Result := FBTCLServerIntf; end; function TibBTTool.GetBTCLDatabase: IibSHDatabase; begin Result := FBTCLDatabaseIntf; end; function TibBTTool.GetBranchIID: TGUID; begin Result := inherited GetBranchIID; if not Assigned(BTCLDatabase) then begin if Assigned(Designer.FindComponent(OwnerIID)) then Result := Designer.FindComponent(OwnerIID).BranchIID; end else Result := BTCLDatabase.BranchIID; end; function TibBTTool.GetCaption: string; begin Result := inherited GetCaption; end; { begin if Assigned(BTCLDatabase) and not SHSystemOptions.UseWorkspaces then Result := Format('%s : %s', [Caption, BTCLDatabase.Alias]); } function TibBTTool.GetCaptionExt: string; var SHSystemOptions: ISHSystemOptions; begin Result := Format('%s', [Caption]); Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, SHSystemOptions); if Assigned(BTCLDatabase) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then Result := Format('%s : %s', [Result, BTCLDatabase.Alias]); // if Supports(Self, IibSHUserManager) then // begin // if Assigned(BTCLServer) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then // Result := Format('%s : %s', [Caption, BTCLServer.Alias]); // if Assigned(BTCLDatabase) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then // Result := Format('%s : %s', [Result, BTCLDatabase.Alias]); // end; // if Supports(Self, IibSHService) then // if Assigned(BTCLServer) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then // Result := Format('%s : %s', [Caption, BTCLServer.Alias]); if Supports(Self, IibSHSQLPlayer) then begin if Assigned(BTCLDatabase) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then Result := Format('%s : %s', [Caption, BTCLDatabase.Alias]); // if Assigned(BTCLServer) and Assigned(SHSystemOptions) and not SHSystemOptions.UseWorkspaces then // Result := Format('%s : %s', [Caption, BTCLServer.Alias]); end; SHSystemOptions := nil; end; function TibBTTool.GetCaptionPath: string; var BranchName, ServerAlias, DatabaseAlias: string; begin if IsEqualGUID(BranchIID, IibSHBranch) then BranchName := SSHInterBaseBranch else if IsEqualGUID(BranchIID, IfbSHBranch) then BranchName := SSHFirebirdBranch; ServerAlias := 'ServerAlias'; DatabaseAlias := 'DatabaseAlias'; if not (Supports(Self, IibSHFIBMonitor) or Supports(Self, IibSHIBXMonitor) or Supports(Self, IibSHSQLPlayer)) then begin if Assigned(BTCLDatabase) then begin DatabaseAlias := BTCLDatabase.Alias; if Assigned(BTCLDatabase.BTCLServer) then ServerAlias := BTCLDatabase.BTCLServer.Alias; end; Result := Format('%s\%s\%s\%s', [BranchName, ServerAlias, DatabaseAlias, Self.Caption]); if Supports(Self, IibSHUserManager) then begin if Assigned(BTCLServer) then ServerAlias := BTCLServer.Alias; if not Assigned(BTCLDatabase) then Result := Format('%s\%s\%s', [BranchName, ServerAlias, Self.Caption]); end; if Supports(Self, IibSHService) then begin if Assigned(BTCLServer) then ServerAlias := BTCLServer.Alias; if not Assigned(BTCLDatabase) then Result := Format('%s\%s\%s', [BranchName, ServerAlias, Self.Caption]); end; end else if Supports(Self, IibSHSQLPlayer) then begin if Assigned(BTCLDatabase) then begin DatabaseAlias := BTCLDatabase.Alias; if Assigned(BTCLDatabase.BTCLServer) then ServerAlias := BTCLDatabase.BTCLServer.Alias; Result := Format('%s\%s\%s\%s', [BranchName, ServerAlias, DatabaseAlias, Self.Caption]); end else if Assigned(BTCLServer) then begin ServerAlias := BTCLServer.Alias; Result := Format('%s\%s\%s', [BranchName, ServerAlias, Self.Caption]); end else Result := Format('%s', [Caption]); end else Result := Format('%s\%s', [BranchName, Self.Caption]); end; procedure TibBTTool.SetOwnerIID(Value: TGUID); begin if not (Supports(Self, IibSHFIBMonitor) or Supports(Self, IibSHIBXMonitor) or Supports(Self, IibSHSQLPlayer)) then begin if not IsEqualGUID(OwnerIID, Value) then Supports(Designer.FindComponent(Value), IibSHDatabase, FBTCLDatabaseIntf); if Supports(Self, IibSHUserManager) then begin if Assigned(FBTCLDatabaseIntf) then FBTCLServerIntf := FBTCLDatabaseIntf.BTCLServer else Supports(Designer.FindComponent(Value), IibSHServer, FBTCLServerIntf) end; if Supports(Self, IibSHService) then Supports(Designer.FindComponent(Value), IibSHServer, FBTCLServerIntf) end; inherited SetOwnerIID(Value); end; { TibBTToolFactory } procedure TibBTToolFactory.CheckStart(const AOwnerIID, AClassIID: TGUID); var BTCLServer: IibSHServer; BTCLDatabase: IibSHDatabase; begin if IsEqualGUID(AClassIID, IibSHFIBMonitor) or IsEqualGUID(AClassIID, IibSHIBXMonitor) then begin end else if IsEqualGUID(AClassIID, IibSHSQLPlayer) then begin if Assigned(Designer.CurrentServer) then Supports(Designer.CurrentServer, IibSHServer, BTCLServer) else Supports(Designer.CurrentServer, IibSHServer, BTCLServer); Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase); if (not Assigned(BTCLServer)) and (not Assigned(BTCLDatabase)) and IsEqualGUID(AOwnerIID, IUnknown) then Designer.AbortWithMsg(Format('%s', [SServerIsNotInterBase])); end else if IsEqualGUID(AClassIID, IibSHUserManager) or // Services IsEqualGUID(AClassIID, IibSHServerProps) or IsEqualGUID(AClassIID, IibSHServerLog) or IsEqualGUID(AClassIID, IibSHServerConfig) or IsEqualGUID(AClassIID, IibSHServerLicense) or IsEqualGUID(AClassIID, IibSHDatabaseShutdown) or IsEqualGUID(AClassIID, IibSHDatabaseOnline) or IsEqualGUID(AClassIID, IibSHDatabaseBackup) or IsEqualGUID(AClassIID, IibSHDatabaseRestore) or IsEqualGUID(AClassIID, IibSHDatabaseStatistics) or IsEqualGUID(AClassIID, IibSHDatabaseValidation) or IsEqualGUID(AClassIID, IibSHDatabaseSweep) or IsEqualGUID(AClassIID, IibSHDatabaseMend) or IsEqualGUID(AClassIID, IibSHTransactionRecovery) or IsEqualGUID(AClassIID, IibSHDatabaseProps) then begin if Assigned(Designer.CurrentServer) then Supports(Designer.CurrentServer, IibSHServer, BTCLServer) else Supports(Designer.CurrentServer, IibSHServer, BTCLServer); if not Assigned(BTCLServer) and IsEqualGUID(AOwnerIID, IUnknown) then Designer.AbortWithMsg(Format('%s', [SServerIsNotInterBase])); end; if IsEqualGUID(AClassIID, IibSHSQLEditor) or IsEqualGUID(AClassIID, IibSHDMLExporter) or IsEqualGUID(AClassIID, IibSHDDLGrantor) or IsEqualGUID(AClassIID, IibSHDDLCommentator) or IsEqualGUID(AClassIID, IibSHDDLDocumentor) or IsEqualGUID(AClassIID, IibSHDDLFinder) or IsEqualGUID(AClassIID, IibSHDDLExtractor) or IsEqualGUID(AClassIID, IibSHTXTLoader) or IsEqualGUID(AClassIID, IibSHPSQLDebugger) then begin Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase); if not Assigned(BTCLDatabase) and IsEqualGUID(AOwnerIID, IUnknown) then Designer.AbortWithMsg(Format('%s', [SDatabaseIsNotInterBase])); end; end; function TibBTToolFactory.GetWantedOwnerIID(const AClassIID: TGUID): TGUID; begin Result := Designer.CurrentBranch.InstanceIID; if IsEqualGUID(AClassIID, IibSHFIBMonitor) or IsEqualGUID(AClassIID, IibSHIBXMonitor) then begin end else if IsEqualGUID(AClassIID, IibSHSQLPlayer) then begin if Assigned(Designer.CurrentDatabase) and Designer.CurrentDatabaseInUse then begin Result := Designer.CurrentDatabase.InstanceIID end else begin if Assigned(Designer.CurrentServer) then Result := Designer.CurrentServer.InstanceIID; end; end else if IsEqualGUID(AClassIID, IibSHSQLEditor) or IsEqualGUID(AClassIID, IibSHDMLHistory) or IsEqualGUID(AClassIID, IibSHDMLExporter) or IsEqualGUID(AClassIID, IibSHDDLGrantor) or IsEqualGUID(AClassIID, IibSHDDLCommentator) or IsEqualGUID(AClassIID, IibSHDDLDocumentor) or IsEqualGUID(AClassIID, IibSHDDLFinder) or IsEqualGUID(AClassIID, IibSHDDLExtractor) or IsEqualGUID(AClassIID, IibSHTXTLoader) or IsEqualGUID(AClassIID, IibSHPSQLDebugger) then begin Result := Designer.CurrentDatabase.InstanceIID; end; // Services if IsEqualGUID(AClassIID, IibSHUserManager) or IsEqualGUID(AClassIID, IibSHServerProps) or IsEqualGUID(AClassIID, IibSHServerLog) or IsEqualGUID(AClassIID, IibSHServerConfig) or IsEqualGUID(AClassIID, IibSHServerLicense) or IsEqualGUID(AClassIID, IibSHDatabaseShutdown) or IsEqualGUID(AClassIID, IibSHDatabaseOnline) or IsEqualGUID(AClassIID, IibSHDatabaseBackup) or IsEqualGUID(AClassIID, IibSHDatabaseRestore) or IsEqualGUID(AClassIID, IibSHDatabaseStatistics) or IsEqualGUID(AClassIID, IibSHDatabaseValidation) or IsEqualGUID(AClassIID, IibSHDatabaseSweep) or IsEqualGUID(AClassIID, IibSHDatabaseMend) or IsEqualGUID(AClassIID, IibSHTransactionRecovery) or IsEqualGUID(AClassIID, IibSHDatabaseProps) then begin // if Assigned(Designer.CurrentDatabase) then // Result := Designer.CurrentDatabase.OwnerIID // else // Result := Designer.CurrentServer.InstanceIID; if Assigned(Designer.CurrentServer) then Result := Designer.CurrentServer.InstanceIID; // else // if Assigned(Designer.CurrentServer) then // Result := Designer.CurrentServer.InstanceIID; end; end; procedure TibBTToolFactory.DoBeforeChangeNotification( var ACallString: string; AComponent: TSHComponent); begin // Do nothing end; function TibBTToolFactory.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHSQLEditor) or // IsEqualGUID(AClassIID, IibSHSQLHistory) or IsEqualGUID(AClassIID, IibSHSQLPerformance) or IsEqualGUID(AClassIID, IibSHSQLPlan) or IsEqualGUID(AClassIID, IibSHSQLPlayer) or // IsEqualGUID(AClassIID, IibSHDMLExporter) or IsEqualGUID(AClassIID, IibSHFIBMonitor) or IsEqualGUID(AClassIID, IibSHIBXMonitor) or IsEqualGUID(AClassIID, IibSHDDLGrantor) or IsEqualGUID(AClassIID, IibSHUserManager) or IsEqualGUID(AClassIID, IibSHDDLCommentator) or IsEqualGUID(AClassIID, IibSHDDLDocumentor) or IsEqualGUID(AClassIID, IibSHDDLFinder) or IsEqualGUID(AClassIID, IibSHDDLExtractor) or IsEqualGUID(AClassIID, IibSHTXTLoader) or IsEqualGUID(AClassIID, IibSHPSQLDebugger) or IsEqualGUID(AClassIID, IibSHBlobEditor) or IsEqualGUID(AClassIID, IibSHDDLDocumentor) or IsEqualGUID(AClassIID, IibSHReportManager) or IsEqualGUID(AClassIID, IibSHDataGenerator) or IsEqualGUID(AClassIID, IibSHDBComparer) or IsEqualGUID(AClassIID, IibSHSecondaryFiles) or IsEqualGUID(AClassIID, IibSHCVSExchanger) or IsEqualGUID(AClassIID, IibSHDBDesigner) or // Services IsEqualGUID(AClassIID, IibSHServerProps) or IsEqualGUID(AClassIID, IibSHServerLog) or IsEqualGUID(AClassIID, IibSHServerConfig) or IsEqualGUID(AClassIID, IibSHServerLicense) or IsEqualGUID(AClassIID, IibSHDatabaseShutdown) or IsEqualGUID(AClassIID, IibSHDatabaseOnline) or IsEqualGUID(AClassIID, IibSHDatabaseBackup) or IsEqualGUID(AClassIID, IibSHDatabaseRestore) or IsEqualGUID(AClassIID, IibSHDatabaseStatistics) or IsEqualGUID(AClassIID, IibSHDatabaseValidation) or IsEqualGUID(AClassIID, IibSHDatabaseSweep) or IsEqualGUID(AClassIID, IibSHDatabaseMend) or IsEqualGUID(AClassIID, IibSHTransactionRecovery) or IsEqualGUID(AClassIID, IibSHDatabaseProps); end; function TibBTToolFactory.CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; var I: Integer; OldCaption, NewCaption, CallString: string; begin if Length(ACaption) = 0 then CheckStart(AOwnerIID, AClassIID); Result := inherited CreateComponent(AOwnerIID, AClassIID, ACaption); if Assigned(Result) then begin // получение названия if Length(ACaption) = 0 then begin if not IsEqualGUID(AOwnerIID, IUnknown) then Result.OwnerIID := AOwnerIID else Result.OwnerIID := GetWantedOwnerIID(AClassIID); I := 1; OldCaption := {GetHintLeftPart(}Designer.GetComponent(AClassIID).GetHintClassFnc{)}; NewCaption := Format('%s %d', [OldCaption, I]); while Assigned(Designer.FindComponent(Result.OwnerIID, AClassIID, NewCaption)) do begin Inc(I); NewCaption := Format('%s %d', [OldCaption, I]); end; Result.Caption := NewCaption; end else begin Result.OwnerIID := AOwnerIID; Result.Caption := ACaption; end; // подготовка к отправке в IDE if Supports(Result, IibSHSQLEditor) then CallString := SCallSQLText; if Supports(Result, IibSHSQLPlayer) then CallString := SCallSQLStatements; if Supports(Result, IibSHDMLExporter) then CallString := SCallTargetScript; if Supports(Result, IibSHFIBMonitor) then CallString := SCallFIBTrace; if Supports(Result, IibSHIBXMonitor) then CallString := SCallIBXTrace; if Supports(Result, IibSHDDLGrantor) then CallString := SCallPrivileges; if Supports(Result, IibSHUserManager) then CallString := SCallUsers; if Supports(Result, IibSHDDLCommentator) then CallString := SCallDescriptions; if Supports(Result, IibSHDDLDocumentor) then CallString:= SCallDescriptions; if Supports(Result, IibSHDDLFinder) then CallString := SCallSearchResults; if Supports(Result, IibSHDDLExtractor) then CallString := SCallTargetScript; if Supports(Result, IibSHTXTLoader) then CallString := SCallDMLStatement; if Supports(Result, IibSHPSQLDebugger) then CallString := SCallTracing; // Services if Supports(Result, IibSHServerProps) then CallString := SCallServiceOutputs; if Supports(Result, IibSHServerLog) then CallString := SCallServiceOutputs; if Supports(Result, IibSHServerConfig) then CallString := SCallServiceOutputs; if Supports(Result, IibSHServerLicense) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseShutdown) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseOnline) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseBackup) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseRestore) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseStatistics) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseValidation) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseSweep) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseMend) then CallString := SCallServiceOutputs; if Supports(Result, IibSHTransactionRecovery) then CallString := SCallServiceOutputs; if Supports(Result, IibSHDatabaseProps) then CallString := SCallServiceOutputs; if Length(CallString) = 0 then CallString := SCallUnknown; DoBeforeChangeNotification(CallString, Result); if Designer.ExistsComponent(Result) then Designer.ChangeNotification(Result, opInsert) else Designer.ChangeNotification(Result, CallString, opInsert); end; end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Time based events mannager using the Cadencer can be useful to make animations } unit VXS.TimeEventsMgr; interface uses System.Classes, System.SysUtils, VXS.Cadencer, VXS.BaseClasses; type TVXTimeEvent = class; TVXTimeEvents = class; TVXTimeEventsMGR = class(TVXUpdateAbleComponent) private FCadencer: TVXCadencer; FEnabled: boolean; FFreeEventOnEnd: boolean; FEvents: TVXTimeEvents; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetCadencer(const val: TVXCadencer); procedure SetEvents(const val: TVXTimeEvents); public constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure DoProgress(const progressTime: TVXProgressTimes); override; procedure Reset(); published property Cadencer: TVXCadencer read FCadencer write SetCadencer; property Enabled: boolean read FEnabled write FEnabled default True; property FreeEventOnEnd: boolean read FFreeEventOnEnd write FFreeEventOnEnd default False; property Events: TVXTimeEvents read FEvents write SetEvents; end; TVXTimeEvents = class(TCollection) protected Owner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TVXTimeEvent); function GetItems(index: Integer): TVXTimeEvent; public constructor Create(aOwner: TComponent); function Add: TVXTimeEvent; function FindItemID(ID: Integer): TVXTimeEvent; function EventByName(name: String): TVXTimeEvent; property Items[index: Integer]: TVXTimeEvent read GetItems write SetItems; default; end; TVXTimeEventType = (etOneShot, etContinuous, etPeriodic); TVXTimeEventProc = procedure(event: TVXTimeEvent) of object; TVXTimeEvent = class(TCollectionItem) private FName: String; FStartTime, FEndTime, FElapsedTime: Double; FPeriod: Double; FEventType: TVXTimeEventType; FOnEvent: TVXTimeEventProc; FEnabled: boolean; FTickCount: Cardinal; procedure SetEnabled(const Value: boolean); protected function GetDisplayName: String; override; procedure SetName(val: String); procedure DoEvent(const curTime: Double); public constructor Create(Collection: TCollection); override; destructor Destroy; override; // Number of times the event was triggered since activation property TickCount: Cardinal read FTickCount; // Elapsed time since the event was activated property ElapsedTime: Double read FElapsedTime; published property Name: String read FName write SetName; property StartTime: Double read FStartTime write FStartTime; property EndTime: Double read FEndTime write FEndTime; property Period: Double read FPeriod write FPeriod; property EventType: TVXTimeEventType read FEventType write FEventType default etOneShot; property OnEvent: TVXTimeEventProc read FOnEvent write FOnEvent; property Enabled: boolean read FEnabled write SetEnabled default True; end; //--------------------------------------------------------- implementation //--------------------------------------------------------- // ------------------ // ------------------ TVXTimeEventsMGR ------------------ // ------------------ constructor TVXTimeEventsMGR.Create(aOwner: TComponent); begin inherited; FEnabled := True; FFreeEventOnEnd := False; FEvents := TVXTimeEvents.Create(self); end; destructor TVXTimeEventsMGR.Destroy; begin Cadencer := nil; FEvents.Free; inherited Destroy; end; procedure TVXTimeEventsMGR.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = Cadencer) then FCadencer := nil; inherited; end; procedure TVXTimeEventsMGR.SetCadencer(const val: TVXCadencer); begin if FCadencer <> val then begin if Assigned(FCadencer) then FCadencer.UnSubscribe(self); FCadencer := val; if Assigned(FCadencer) then FCadencer.Subscribe(self); end; end; procedure TVXTimeEventsMGR.SetEvents(const val: TVXTimeEvents); begin FEvents.Assign(val); end; procedure TVXTimeEventsMGR.DoProgress(const progressTime: TVXProgressTimes); var i: Integer; begin if not Enabled then Exit; i := 0; with progressTime do while i <= Events.Count - 1 do with Events.Items[i] do begin if Enabled and Assigned(FOnEvent) then begin case EventType of etOneShot: if (newTime >= StartTime) and (TickCount = 0) then DoEvent(newTime); etContinuous: if (newTime >= StartTime) and ((newTime <= EndTime) or (EndTime <= 0)) then DoEvent(newTime); etPeriodic: if (newTime >= StartTime + TickCount * Period) and ((newTime <= EndTime) or (EndTime <= 0)) then DoEvent(newTime); else Assert(False); end; end; if FreeEventOnEnd and (((EventType <> etOneShot) and (newTime > EndTime) and (EndTime >= 0)) or ((EventType = etOneShot) and (TickCount > 0))) then Events[i].Free else begin // if we delete current event, the next will have same index // so increment only if we don't delete Inc(i); end; end; end; procedure TVXTimeEventsMGR.Reset; var i: Integer; begin if FEvents.Count <> 0 then for i := 0 to FEvents.Count - 1 do FEvents[i].FTickCount := 0; end; // ------------------ // ------------------ TVXTimeEvents ------------------ // ------------------ constructor TVXTimeEvents.Create(aOwner: TComponent); begin Owner := aOwner; inherited Create(TVXTimeEvent); end; function TVXTimeEvents.GetOwner: TPersistent; begin Result := Owner; end; procedure TVXTimeEvents.SetItems(index: Integer; const val: TVXTimeEvent); begin inherited Items[index] := val; end; function TVXTimeEvents.GetItems(index: Integer): TVXTimeEvent; begin Result := TVXTimeEvent(inherited Items[index]); end; function TVXTimeEvents.Add: TVXTimeEvent; begin Result := (inherited Add) as TVXTimeEvent; end; function TVXTimeEvents.FindItemID(ID: Integer): TVXTimeEvent; begin Result := (inherited FindItemID(ID)) as TVXTimeEvent; end; function TVXTimeEvents.EventByName(name: String): TVXTimeEvent; var i: Integer; begin i := 0; while (i < Count) and (Items[i].FName <> name) do Inc(i); if i = Count then Result := nil else Result := Items[i]; end; // ------------------ // ------------------ TVXTimeEvent ------------------ // ------------------ constructor TVXTimeEvent.Create(Collection: TCollection); begin inherited Create(Collection); FEventType := etOneShot; FName := Format('Event%d', [index]); // give a default name different for each event FEnabled := True; end; destructor TVXTimeEvent.Destroy; begin inherited Destroy; end; function TVXTimeEvent.GetDisplayName: String; begin case EventType of etOneShot: Result := Name + Format(' (OneShot ST=%g)', [StartTime]); etContinuous: Result := Name + Format(' (Continuous ST=%g ET=%g)', [StartTime, EndTime]); etPeriodic: Result := Name + Format(' (Periodic ST=%g ET=%g P=%g)', [StartTime, EndTime, Period]); end; end; procedure TVXTimeEvent.SetName(val: String); var i: Integer; ok: boolean; begin ok := True; with self.Collection as TVXTimeEvents do // we mustn't have 2 events with the same name (for EventByName) for i := 0 to Count - 1 do if Items[i].FName = val then ok := False; if ok and (val <> '') then FName := val; end; procedure TVXTimeEvent.DoEvent(const curTime: Double); begin if Assigned(FOnEvent) then begin FElapsedTime := curTime - StartTime; FOnEvent(self); end; Inc(FTickCount); end; procedure TVXTimeEvent.SetEnabled(const Value: boolean); begin FEnabled := Value; FStartTime := ((GetOwner as TVXTimeEvents).Owner as TVXTimeEventsMGR).Cadencer.CurrentTime; end; end.
unit Dmitry.Graphics.BitmapCache; interface uses Generics.Collections, System.Classes, System.SysUtils, Vcl.Graphics, Dmitry.Memory; type TGraphicCachedObject = class(TObject) protected procedure SaveToCache; virtual; abstract; procedure LoadFromCache; virtual; abstract; end; TCachedGraphic<T: TGraphic, constructor> = class(TGraphicCachedObject) private FGraphic: T; FMemory: TMemoryStream; FGraphicInMemory: Boolean; function GetGraphic: T; procedure SetGraphic(const Value: T); protected procedure SaveToCache; override; procedure LoadFromCache; override; public constructor Create; destructor Destroy; override; property Graphic: T read GetGraphic write SetGraphic; end; TGraphicCacheManager = class(TObject) private FUseList: TList<TGraphicCachedObject>; protected procedure UsedItem(Item: TGraphicCachedObject); procedure RemoveItem(Item: TGraphicCachedObject); public constructor Create; destructor Destroy; override; end; var GraphicObjectsLimit: Integer = 100; GraphicsSwapAtTime: Integer = 10; function GraphicCacheManager: TGraphicCacheManager; implementation var FGraphicCacheManager: TGraphicCacheManager = nil; function GraphicCacheManager: TGraphicCacheManager; begin if FGraphicCacheManager = nil then FGraphicCacheManager := TGraphicCacheManager.Create; Result := FGraphicCacheManager; end; { TCachedGraphic } constructor TCachedGraphic<T>.Create; begin FGraphic := nil; FMemory := nil; FGraphicInMemory := False; end; destructor TCachedGraphic<T>.Destroy; begin F(FGraphic); F(FMemory); inherited; end; function TCachedGraphic<T>.GetGraphic: T; begin GraphicCacheManager.UsedItem(Self); LoadFromCache; Result := FGraphic; end; procedure TCachedGraphic<T>.LoadFromCache; begin if FMemory = nil then Exit; FMemory.Seek(0, soFromBeginning); FGraphic := T.Create; FGraphic.LoadFromStream(FMemory); F(FMemory); end; procedure TCachedGraphic<T>.SaveToCache; begin if (FGraphic = nil) then Exit; if FMemory <> nil then Exit; FMemory := TMemoryStream.Create; if FGraphic <> nil then FGraphic.SaveToStream(FMemory); F(FGraphic); end; procedure TCachedGraphic<T>.SetGraphic(const Value: T); begin LoadFromCache; F(FGraphic); FGraphic := Value; end; { TGraphicCacheManager } constructor TGraphicCacheManager.Create; begin FUseList := TList<TGraphicCachedObject>.Create; end; destructor TGraphicCacheManager.Destroy; begin F(FUseList); inherited; end; procedure TGraphicCacheManager.RemoveItem(Item: TGraphicCachedObject); begin FUseList.Remove(Item); end; procedure TGraphicCacheManager.UsedItem(Item: TGraphicCachedObject); var I: Integer; begin RemoveItem(Item); FUseList.Add(Item); if FUseList.Count > GraphicObjectsLimit then begin for I := GraphicsSwapAtTime - 1 downto 0 do begin FUseList[I].SaveToCache; FUseList.Delete(I); end; end; end; initialization finalization F(FGraphicCacheManager); end.
unit LA.LinearSystem; interface uses System.SysUtils, LA.Matrix, LA.Vector, LA.ArrayList, LA.Globals; type TLinearSystem = class(TObject) type TVectorArr = TArray<TVector>; TList = TArrayList<integer>; private __row, __col: integer; procedure __forward; procedure __backward; function __max_row(index_i, index_j: integer): integer; procedure __swapRow(var a, b: TVector); public Ab: TVectorArr; Pivots: TList; constructor Create(mtx: TMatrix); overload; constructor Create(mtxA: TMatrix; mtxB: TMatrix); overload; constructor Create(mtx: TMatrix; vec: TVector); overload; destructor Destroy; override; /// <summary> 高斯约旦消元法 </summary> function Gauss_Jordan_Elimination: boolean; function ToString: string; override; end; /// <summary> 返回逆矩阵 </summary> function Inv(mtx: TMatrix): PMatrix; /// <summary> 返回矩阵的秩 </summary> function Rank(mtx: TMatrix): integer; implementation function Inv(mtx: TMatrix): PMatrix; var ls: TLinearSystem; n, i, j: integer; invMtx: TList2D; begin if mtx.Row_num <> mtx.Col_num then Exit(nil); n := mtx.Row_num; ls := TLinearSystem.Create(mtx, TMatrix.Identity(n)); if not ls.Gauss_Jordan_Elimination then Exit(nil); SetLength(invMtx, n, n); for i := 0 to n - 1 do begin for j := 0 to n - 1 do begin invMtx[i, j] := ls.Ab[i][j + n]; end; end; new(Result); Result^ := TMatrix.Create(invMtx); end; function Rank(mtx: TMatrix): integer; var ls: TLinearSystem; zeroVec, row: TVector; Count: integer; begin ls := TLinearSystem.Create(mtx); zeroVec := TVector.Zero(mtx.Col_num); Count := 0; for row in ls.Ab do begin if row <> zeroVec then Inc(Count); end; Result := Count; end; { TLinearSystem } constructor TLinearSystem.Create(mtx: TMatrix; vec: TVector); var tmpList: TLists; tmpVecArr: TVectorArr; i: integer; begin if mtx.Row_num <> vec.Len then raise Exception.Create ('row number of Matrix must be equal to the length of Vector'); __row := mtx.Row_num; __col := mtx.Col_num; // if __row <> __col then //TODO : no this restriction // raise Exception.Create('Error Message'); SetLength(tmpVecArr, __row); for i := 0 to __row - 1 do begin tmpList := Copy(mtx.Get_Row_vector(i).UnderlyingList); tmpList := Concat(tmpList, [vec[i]]); tmpVecArr[i] := TVector.Create(tmpList); end; Ab := tmpVecArr; Pivots := TList.Create; end; constructor TLinearSystem.Create(mtxA: TMatrix; mtxB: TMatrix); var tmpList: TLists; tmpVecArr: TVectorArr; i: integer; begin if mtxA.Row_num <> mtxB.Row_num then raise Exception.Create ('row number of Matrix must be equal to the length of Row'); __row := mtxA.Row_num; __col := mtxA.Col_num; SetLength(tmpVecArr, __row); for i := 0 to __row - 1 do begin tmpList := Copy(mtxA.Get_Row_vector(i).UnderlyingList); tmpList := Concat(tmpList, mtxB.Get_Row_vector(i).UnderlyingList); tmpVecArr[i] := TVector.Create(tmpList); end; Ab := tmpVecArr; Pivots := TList.Create; end; constructor TLinearSystem.Create(mtx: TMatrix); var tmpList: TLists; tmpVecArr: TVectorArr; i: integer; begin __row := mtx.Row_num; SetLength(tmpVecArr, __row); for i := 0 to __row - 1 do begin tmpList := Copy(mtx.Get_Row_vector(i).UnderlyingList); tmpVecArr[i] := TVector.Create(tmpList); end; Ab := tmpVecArr; end; destructor TLinearSystem.Destroy; begin FreeAndNil(Pivots); inherited Destroy; end; function TLinearSystem.Gauss_Jordan_Elimination: boolean; var i: integer; begin // 如果有解,返回True;如果没有解,返回False __forward; __backward; Result := True; for i := Pivots.GetSize to __row - 1 do begin if not Is_zero(Ab[i][Ab[i].Len - 1]) then begin Result := False; Exit; end; end; end; function TLinearSystem.ToString: string; var sb: TStringBuilder; i, j: integer; begin sb := TStringBuilder.Create; try for i := 0 to __row - 1 do begin for j := 0 to __col - 1 do begin sb.Append(Ab[i][j]).Append(#9); end; sb.Append(' |'#9).Append(Ab[i][__col]).Append(#10); end; Result := sb.ToString; finally FreeAndNil(sb); end; end; procedure TLinearSystem.__backward; var i, j, n, k: integer; begin n := Pivots.GetSize; for i := n - 1 downto 0 do begin k := Pivots[i]; // Ab[i][k]为主元 for j := i - 1 downto 0 do Ab[j] := Ab[j] - Ab[j][k] * Ab[i]; end; end; procedure TLinearSystem.__forward; var i, j, k, max_row: integer; begin i := 0; k := 0; while (i < __row) and (k < __col) do begin // Ab[i][k]位置是否可以是主元 max_row := __max_row(i, k); __swapRow(Ab[i], Ab[max_row]); if Is_zero(Ab[i][k]) then Inc(k) else begin // 将主元归为一 Ab[i] := Ab[i] / Ab[i][k]; for j := i + 1 to __row - 1 do Ab[j] := Ab[j] - Ab[j][k] * Ab[i]; Pivots.AddLast(k); Inc(i); end; end; end; function TLinearSystem.__max_row(index_i, index_j: integer): integer; var best: double; ret, i: integer; begin best := Ab[index_i][index_j]; ret := index_i; for i := index_i + 1 to __row - 1 do begin if Ab[i][index_j] > best then begin best := Ab[i][index_j]; ret := i; end; end; Result := ret; end; procedure TLinearSystem.__swapRow(var a, b: TVector); var tmp: TVector; begin tmp := a; a := b; b := tmp; end; end.
unit UMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Generics.Collections, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Control1, Vcl.ExtCtrls, UList, UListItem, UnitNewItem, Math; type TForm1 = class(TForm) Panel1: TPanel; Panel2: TPanel; RadioButton2: TRadioButton; RadioButton1: TRadioButton; Panel3: TPanel; ButtonAddAfter: TButton; ButtonAddBefore: TButton; ButtonDelete: TButton; Edit1: TEdit; ButtonCreate: TButton; ButtonNext: TButton; Label1: TLabel; ButtonAdd: TButton; ScrollBox1: TScrollBox; FlowPanel1: TPanel; Memo1: TMemo; procedure ButtonCreateClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonClearClick(Sender: TObject); procedure RadioButton1Click(Sender: TObject); procedure RadioButton2Click(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure ButtonAddAfterClick(Sender: TObject); procedure ButtonAddClick(Sender: TObject); procedure RedrawPanel(); procedure ButtonAddBeforeClick(Sender: TObject); procedure ButtonAppendClick(Sender: TObject); procedure ButtonNextClick(Sender: TObject); procedure ButtonRefreshClick(Sender: TObject); // Обработчик события MyEvent для объектов, принадлежащих типу TMyClass. procedure OnThreadSyspended(Sender: TObject); procedure ButtonInsertClick(Sender: TObject); procedure ButtonDeleteClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; ListControl: TList<TListControl>; // контейнер списка List: TList; implementation {$R *.dfm} uses Logger; // обновляем состояние кнопок procedure UpdateButtonState; begin with Form1 do begin case List.State of lsNormal: begin if List.Getcount > 0 then begin ButtonAdd.Enabled := false; ButtonAddAfter.Enabled := true; ButtonAddBefore.Enabled := true; RadioButton1.Enabled := false; ButtonCreate.Enabled := false; RadioButton2.Enabled := false; Edit1.Enabled := false; // удалять первый элемент пока нельзя if List.Getcount > 1 then ButtonDelete.Enabled := true else ButtonDelete.Enabled := false; end else begin ButtonAdd.Enabled := true; ButtonAddAfter.Enabled := false; ButtonAddBefore.Enabled := false; ButtonDelete.Enabled := false; RadioButton1.Enabled := true; RadioButton2.Enabled := true; ButtonCreate.Enabled := true; Edit1.Enabled := true; end; ButtonNext.Enabled := false; end; lsAddbefore, lsAddAfter, lsDelete: begin ButtonAdd.Enabled := false; ButtonAddAfter.Enabled := false; ButtonAddBefore.Enabled := false; ButtonDelete.Enabled := false; ButtonNext.Enabled := true; end; end; end; end; // перемещает все контролы в ряд по порядку procedure ReplaceControlItems(); var i: integer; width: integer; begin width := 0; for i := 0 to ListControl.Count - 1 do begin ListControl.Items[i].Left := width; ListControl[i].Refresh; if (i = 0) and (ListControl.Items[i].State = new) then width := 0 else case ListControl.Items[i].State of addAfter: width := width + ListControl.Items[i].width - (ListControl.Items[i].ItemWidth + ListControl.Items[i].ArrowWidth); normal: width := width + ListControl.Items[i].width - (ListControl.Items[i].ItemWidth + ListControl.Items[i].ArrowWidth + Round(1 / 5 * ListControl.Items[i].ItemWidth) + Round(ListControl.Items[i].ArrowHeadWidth / 2)); new: width := width + ListControl.Items[i].width; end; end; end; // перерисовывает панель с компонентами, предварительно ее очищая procedure TForm1.RedrawPanel(); var temp: TListItem; ListControlItem, NewListControlItem: TListControl; begin ButtonClearClick(Self); case List.State of lsNormal: begin temp := List.GetFirst; while temp <> nil do begin ListControlItem := TListControl.Create(FlowPanel1); ListControlItem.ItemMain.TitleMain := temp.GetInfo; ListControlItem.ItemMain.TitleNext := temp.GetNextInfo; ListControlItem.ItemMain.TitlePrev := temp.GetPrevInfo; ListControlItem.IsLast := temp.IsLast; ListControlItem.IsFirst := temp.IsFirst; ListControlItem.ItemMain.ArrowHeader.visible := temp.IsFirst; ListControl.Add(ListControlItem); temp := temp.GetNext; end; end; lsAddbefore: begin end; lsAddAfter: begin temp := List.GetFirst; while temp <> nil do begin ListControlItem := TListControl.Create(FlowPanel1); ListControlItem.ItemMain.TitleMain := temp.GetInfo; ListControlItem.ItemMain.TitleNext := temp.GetNextInfo; ListControlItem.ItemMain.TitlePrev := temp.GetPrevInfo; ListControlItem.ItemMain.ArrowHeader.visible := temp.IsFirst; ListControlItem.IsLast := temp.IsLast; ListControlItem.IsFirst := temp.IsFirst; ListControlItem.IsAddAfter := temp.IsAddAfter; ListControl.Add(ListControlItem); if temp.IsAddAfter then begin NewListControlItem := TListControl.Create(FlowPanel1); NewListControlItem.ItemMain.TitleMain := List.NewItem.GetInfo; NewListControlItem.ItemMain.TitleNext := List.NewItem.GetNextInfo; NewListControlItem.ItemMain.TitlePrev := List.NewItem.GetPrevInfo; NewListControlItem.State := new; NewListControlItem.IsLast := List.NewItem.IsLast; NewListControlItem.IsFirst := List.NewItem.IsFirst; NewListControlItem.ItemMain.color := clGreen; // стрелочки ListControlItem.ItemMain.ArrowRight.visible := (temp.GetNext = List.NewItem) and (temp.IsLast); // стрелочки при добавлении в середину для нового элемента if temp.GetNext <> nil then begin NewListControlItem.ItemMain.ArrowUpRight.visible := (temp.GetNext = List.NewItem.GetNext); NewListControlItem.ItemMain.ArrowDownRight.visible := (List.NewItem = temp.GetNext.GetPrev); ListControlItem.ItemMain.ArrowDownLeft.visible := (temp.GetNext = List.NewItem); ListControlItem.ItemMain.ArrowUpLeft.visible := (temp = List.NewItem.GetPrev); // длинные ListControlItem.ItemMain.ArrowLongLeft.visible := (temp.GetNext <> List.NewItem) and (temp.GetNext.GetPrev = temp); ListControlItem.ItemMain.ArrowLongRight.visible := (temp.GetNext <> List.NewItem) and (temp.GetNext <> nil); end; if temp.IsLast then begin ListControlItem.IsLast := false; NewListControlItem.State := normal; ListControlItem.ItemMain.ArrowRight.visible := (temp.GetNext <> nil); ListControlItem.ItemMain.ArrowLeft.visible := (List.NewItem.GetPrev <> nil); end else begin NewListControlItem.State := new; ListControlItem.State := addAfter; end; ListControl.Add(NewListControlItem); end; // закрашивание temp if temp = List.TempItem then begin ListControlItem.ItemMain.color := clBlue; end; temp := temp.GetNext; end; end; lsDelete: begin temp := List.GetFirst; while temp <> nil do begin ListControlItem := TListControl.Create(FlowPanel1); ListControlItem.ItemMain.TitleMain := temp.GetInfo; ListControlItem.ItemMain.TitleNext := temp.GetNextInfo; ListControlItem.ItemMain.TitlePrev := temp.GetPrevInfo; ListControlItem.ItemMain.ArrowHeader.visible := temp.IsFirst; ListControlItem.IsLast := temp.IsLast; ListControlItem.IsFirst := temp.IsFirst; ListControl.Add(ListControlItem); // закрашивание удяляемого if temp.IsDelete then begin ListControlItem.ItemMain.color := clRed; end; // закрашивание temp if temp = List.TempItem then begin ListControlItem.ItemMain.color := clBlue; end; // непосредственно визуализация удаления элемента if Assigned(List.DeleteItem) then begin // если удаляем с начала списка (первый элемент) if List.DeleteItem = List.GetFirst then begin if temp = List.DeleteItem then if temp.GetNext.GetPrev <> temp then ListControlItem.ItemMain.ArrowLeft.cross.visible := true; end; // если удаляем с конца (последний элеменет) if List.DeleteItem.GetNext = nil then begin // крестик вправо if (List.DeleteItem.GetPrev = temp) and (temp.GetNext <> List.DeleteItem) then begin ListControlItem.ItemMain.ArrowRight.cross.visible := true; end; end else // удаление из середины begin // длинная стрелочка вперед + крестик if (List.DeleteItem.GetPrev = temp) and (temp.GetNext <> List.DeleteItem) then begin ListControlItem.ItemMain.ArrowRightPolygon.visible := true; ListControlItem.ItemMain.ArrowRight.cross.visible := true; end; // длинная стрелочка назад if (List.DeleteItem.GetNext = temp.GetNext) and (temp.GetNext <> List.DeleteItem) and (temp <> List.DeleteItem) and (temp.GetNext.GetPrev = temp) then begin ListControlItem.ItemMain.ArrowLeftPolygon.visible := true; end; // крестик if (temp = List.DeleteItem) and (List.DeleteItem.GetNext.GetPrev = List.DeleteItem.GetPrev) then begin ListControlItem.ItemMain.ArrowLeft.cross.visible := true; end; end; end; // обработка прохода по списку с учетом удаляемного элемента if Assigned(List.DeleteItem) then begin if List.DeleteItem.GetPrev = temp then temp := List.DeleteItem else temp := temp.GetNext; end else temp := temp.GetNext; end; end; end; ReplaceControlItems; UpdateButtonState; end; // Обработчик события ThreadSyspended для объектов, принадлежащих типу TList. procedure TForm1.OnThreadSyspended(Sender: TObject); begin if not(Sender is TList) then Exit; RedrawPanel; end; procedure TForm1.ButtonCreateClick(Sender: TObject); var ListItem: TListItem; i, Count: integer; begin // переводим режим программы в обычный - без управления потоком List.Mode := lmNormal; // выключаем логгирование Logger.Enabled := false; Count := Min(3, StrToInt(Edit1.Text) - 1); if RadioButton1.Checked = true then for i := 0 to Count do begin if i = 0 then begin ListItem := TListItem.Create('item' + IntToStr(i)); List.AddAfter('item', ListItem); WaitForSingleObject(List.ThreadId, INFINITE); end else begin ListItem := TListItem.Create('item' + IntToStr(i)); List.AddAfter('item' + IntToStr(i - 1), ListItem); WaitForSingleObject(List.ThreadId, INFINITE); end; end; // перерисовываем панель RedrawPanel(); // возвращаем программу в режим управления Logger.Enabled := true; List.Mode := lmControl; end; // удаление procedure TForm1.ButtonDeleteClick(Sender: TObject); var searchItem: string; begin searchItem := InputBox('Удаление', 'Введите элемент, который нужно удалить :', 'item1'); List.Delete(searchItem); end; procedure TForm1.ButtonAppendClick(Sender: TObject); var temp: TListItem; begin if List.Getcount = 0 then begin temp := TListItem.Create('item' + IntToStr(List.Getcount)); List.AddAfter('', temp); end else begin temp := TListItem.Create('item' + IntToStr(List.Getcount)); List.AddAfter('item' + IntToStr(List.Getcount - 1), temp); end; end; // добавление первого элемента в список procedure TForm1.ButtonAddClick(Sender: TObject); var ListItem: TListItem; info: string; begin Form2.ShowModal; info := Form2.Edit1.Text; ListItem := TListItem.Create(info); List.AddAfter('', ListItem); end; // возобновление работы procedure TForm1.ButtonNextClick(Sender: TObject); begin List.NextStep; end; procedure TForm1.ButtonRefreshClick(Sender: TObject); begin ButtonClearClick(Sender); // FlowPanel1.Components.DestroyComponents; { TODO пересмоттреть очистку списка, т.к. панель не очищается } ReplaceControlItems(); end; procedure TForm1.ButtonInsertClick(Sender: TObject); var temp: TListItem; searchItem: string; begin if List.Getcount = 0 then begin temp := TListItem.Create('item' + IntToStr(List.Getcount)); List.AddAfter('', temp); end else begin searchItem := InputBox('Новый элемент', 'Введите элемент, после которого добавить новый :', 'item1'); temp := TListItem.Create('itemNew'); List.AddAfter(searchItem, temp); end; end; // добавление после procedure TForm1.ButtonAddAfterClick(Sender: TObject); var ListItem: TListItem; searchItem: string; info: string; begin if List.Getcount <> 0 then Form2.ShowModal; info := Form2.Edit1.Text; ListItem := TListItem.Create(info); searchItem := InputBox('Добавление после заданного', 'Введите элемент, после которого добавить новый :', 'item1'); List.AddAfter(searchItem, ListItem); end; // добавление перед procedure TForm1.ButtonAddBeforeClick(Sender: TObject); var ListItem: TListControl; k: integer; begin k := StrToInt(InputBox('Новый элемент', 'Введите номер элемента,ПОСЛЕ которого хотите добавить новый элемент:', '1')) - 1; ListItem := TListControl.Create(FlowPanel1); ListItem.ItemMain.TitleMain := 'new'; ListItem.ItemMain.TitleNext := 'nul'; ListItem.ItemMain.TitlePrev := 'nul'; if ListControl[k].IsLast then begin ListItem.State := normal; ListItem.IsLast := true; end else begin ListItem.State := new; ListControl[k].State := addBefore; end; if k > 0 then begin ListControl[k - 1].State := addAfter; end else begin ListControl.Items[k].PaddingLeft := ListControl.Items[k].PaddingLeft + ListControl.Items[k].ArrowWidth; end; ListControl.Insert(k, ListItem); RedrawPanel(); end; procedure TForm1.ButtonClearClick(Sender: TObject); var i: integer; begin for i := 1 to FlowPanel1.ComponentCount do FlowPanel1.Controls[0].DisposeOf; for i := 1 to ListControl.Count do begin ListControl.Delete(0); end; end; procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin If not CharInSet(Key, ['0' .. '9', #8]) then Key := #0; end; // обработчик создания формы procedure TForm1.FormCreate(Sender: TObject); begin List := TList.Create; // Для OnThreadSyspended назначаем обработчики события ThreadSyspended. List.OnThreadSyspended := OnThreadSyspended; ListControl := TList<TListControl>.Create; UpdateButtonState; end; procedure TForm1.RadioButton1Click(Sender: TObject); begin if RadioButton1.Checked = true then begin Edit1.ReadOnly := false; ButtonCreate.Enabled := true; end; end; procedure TForm1.RadioButton2Click(Sender: TObject); begin if RadioButton2.Checked = true then begin ButtonAdd.Enabled := true; Edit1.ReadOnly := false; end; UpdateButtonState; end; end.
function ArredontaFloat(x : Real): Real; {Arredonda um número float para convertê-lo em String} Begin if x > 0 Then begin if Frac(x) > 0.5 Then begin x := x + 1 - Frac(x); end else begin x := x - Frac(x); end; end else begin x := x - Frac(x); end; result := x end;
unit API_DBases; interface uses System.Classes ,FireDAC.Stan.Def ,FireDAC.Stan.Async ,FireDAC.Phys.MySQL ,FireDAC.Comp.Client ,FireDAC.DApt ,FireDAC.VCLUI.Wait ,API_Files; type TDBEngine = class abstract private FDConnection: TFDConnection; FConnectParams: TStringList; procedure SetConnectParams; virtual; abstract; public procedure OpenConnection; overload; procedure OpenConnection(aFileName: String); overload; procedure OpenQuery(aQuery: TFDQuery); overload; procedure OpenQuery(aQuery: TFDQuery; aSQL: string); overload; procedure ExecQuery(aQuery: TFDQuery); property Connection: TFDConnection read FDConnection; end; TMySQLEngine = class(TDBEngine) private procedure SetConnectParams; override; public function GetLastInsertedId: integer; end; implementation procedure TDBEngine.OpenQuery(aQuery: TFDQuery; aSQL: string); begin aQuery.SQL.Text:=aSQL; OpenQuery(aQuery); end; function TMySQLEngine.GetLastInsertedId: integer; var dsQuery: TFDQuery; begin Result:=0; dsQuery:=TFDQuery.Create(nil); try OpenQuery(dsQuery, 'select LAST_INSERT_ID()'); Result:=dsQuery.Fields[0].AsInteger; finally dsQuery.Free; end; end; procedure TDBEngine.ExecQuery(aQuery: TFDQuery); begin aQuery.Close; aQuery.Connection := FDConnection; aQuery.ExecSQL; end; procedure TDBEngine.OpenQuery(aQuery: TFDQuery); begin aQuery.Connection:=FDConnection; aQuery.Open; aQuery.FetchAll; end; procedure TDBEngine.OpenConnection(aFileName: String); begin FConnectParams := TStringList.Create; try FConnectParams.Text := TFilesEngine.GetTextFromFile(aFileName); OpenConnection; finally FConnectParams.Free; end; end; procedure TMySQLEngine.SetConnectParams; begin FDConnection.Params.Values['DriverID'] := 'MySQL'; FDConnection.Params.Values['Server'] := FConnectParams.Values['Host']; FDConnection.Params.Values['Database'] := FConnectParams.Values['DataBase']; FDConnection.Params.Values['User_Name'] := FConnectParams.Values['Login']; FDConnection.Params.Values['Password'] := FConnectParams.Values['Password']; FDConnection.Params.Values['CharacterSet'] := FConnectParams.Values['CharacterSet']; end; procedure TDBEngine.OpenConnection; begin FDConnection := TFDConnection.Create(nil); SetConnectParams; FDConnection.LoginPrompt := False; FDConnection.Connected := True; end; end.
unit TestThCanvasZoom; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, BaseTestUnit, System.Types, System.SysUtils, FMX.Types, FMX.Objects, System.UIConsts; type // Test methods for class TThInterfacedObject TestTThCanvasZoom = class(TThCanvasBaseTestUnit) published // #191 지정된 비율로 캔버스가 확대/축소 되어야 한다. procedure TestZoomBasic; // #192 Zoom 되도 ResizeSpot 및 Highlight의 크기는 변경되지 않아야 한다. procedure TestZoomAndSpotSizeMaintain; {$IFDEF ON_HIGHLIGHT} procedure TestZoomAndHighlightSizeMaintain; {$ENDIF} // #196 명령을 통한 확대 축소는 중심점을 기준으로 Zoom 되어야 한다. procedure TestZoomCenterPosition; // #190 위치 중심으로 확대/축소 되어야 한다. procedure TestZoomAtPoint; // #189 캔버스 선택(클릭) 후 마우스 휠을 올리면 확대, 내리면 축소가 되어야 한다. procedure TestZoomWithWheel; // #201 한곳에서 Zoom처리 하면 포인트에 맞게 처리되지만 마우스를 다른데로 옮겨가면 시도 시 처리되지 않음 procedure BugTestZoomPointAnotherPoint; // #199 이동 후에도 마우스 위치에 따른 Zoom이 가능해야 한다. procedure TestZoomPositionCheckAfterMove; // #198 Zoom이후 마우스로 아이템 추가 시 Zoom이 적용되지 않고 그려짐 procedure BugTestZoomAfterDrawCenter; procedure BugTestZoomAfterDraw25; procedure BugTestZoomAfterDraw75; // #193 아이템 크기조정(또는 그릴때)시 Zoom에 따른 최소크기가 적용되야 한다. procedure TestMinSizeWithZoomOfDrawing; procedure TestMinSizeWithZoomOfResizing; // #204 확대 시 직선 주위를 선택해도 선택되는 버그 procedure BugTestAfterZoomingOverRangeLineSelection; // #214 H 버튼 클릭 시 현재 보이는 캔버스 영역의 중앙으로 맞추어져야 한다. procedure BugZoomGoHome; end; implementation uses FMX.TestLib, ThItem, ThShapeItem, ThItemFactory, ThConsts, UITypes, FMX.Forms, DebugUtils; { TestTThCanvasZoom } procedure TestTThCanvasZoom.TestZoomBasic; begin DrawRectangle(50, 50, 150, 150); FCanvas.ZoomIn; Check(FCanvas.ZoomScale > CanvasZoomScaleDefault, Format('ZoomIn: %f', [FCanvas.ZoomScale])); FCanvas.ZoomHome; FCanvas.ZoomOut; Check(FCanvas.ZoomScale < CanvasZoomScaleDefault, Format('ZoomOt: %f', [FCanvas.ZoomScale])); end; procedure TestTThCanvasZoom.TestZoomAndSpotSizeMaintain; var AC: TAlphaColor; begin DrawRectangle(50, 50, 150, 150); AC := TestLib.GetControlPixelColor(FCanvas, 50-ItemResizeSpotRadius+1, 50); Check(AC = ItemResizeSpotOutColor, Format('Not matching color Orginal(%d, %d)', [AC, ItemResizeSpotOutColor])); FCanvas.ZoomOutAtPoint(50, 50); FCanvas.ZoomOutAtPoint(50, 50); AC := TestLib.GetControlPixelColor(FCanvas, 50-ItemResizeSpotRadius+1, 50); Check(AC = ItemResizeSpotOutColor, Format('[Left] Not matching color ZoomOut(%d, %d)', [AC, ItemResizeSpotOutColor])); end; {$IFDEF ON_HIGHLIGHT} procedure TestTThCanvasZoom.TestZoomAndHighlightSizeMaintain; var l, c: single; AC: TAlphaColor; begin DrawRectangle(50, 50, 150, 150); TestLib.RunMouseMove(MousePath.New.Add(100, 100).Path); AC := TestLib.GetControlPixelColor(FCanvas, 150+ItemHighlightSize-1, 100); Check(AC = ItemHighlightColor, Format('Not matching color Orginal(%d, %d)', [AC, ItemHighlightColor])); FCanvas.ZoomOutAtPoint(0, 0); FCanvas.ZoomOutAtPoint(0, 0); // 구현은 되었으나 테스트에서 오류 l := 1500 * FCanvas.ZoomScale; c := 1000 * FCanvas.ZoomScale; AC := TestLib.GetControlPixelColor(FCanvas, Trunc(l)+ItemHighlightSize-1, Trunc(c)); Check(AC = ItemHighlightColor, Format('[Left: %f] Not matching color ZoomOut(%d, %d)', [l, AC, ItemHighlightColor])); end; {$ENDIF} procedure TestTThCanvasZoom.TestZoomCenterPosition; begin DrawRectangle(150, 150, 250, 250); FCanvas.ZoomAnimated := False; FCanvas.ZoomOut; FCanvas.ZoomOut; FCanvas.ZoomOut; FCanvas.ClearSelection; TestLib.RunMouseClick(149, 149); CheckNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.TestZoomAtPoint; begin DrawRectangle(100, 100, 250, 250); FCanvas.ZoomAnimated := False; FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ClearSelection; TestLib.RunMouseClick(99, 99); CheckNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.TestZoomWithWheel; var ZS: Single; begin DrawRectangle(150, 150, 250, 250); ZS := FCanvas.ZoomScale; TestLib.RunMouseWheelUp(150, 150); TestLib.Delay(100); Check(FCanvas.ZoomScale < ZS, 'Up'); ZS := FCanvas.ZoomScale; TestLib.RunMouseWheelDown(150, 150); TestLib.Delay(100); Check(FCanvas.ZoomScale > ZS, 'Down'); end; procedure TestTThCanvasZoom.BugTestZoomPointAnotherPoint; begin FCanvas.ZoomOutAtPoint(75, 75); DrawRectangle(75, 75, 150, 150); FCanvas.ClearSelection; FCanvas.ZoomOutAtPoint(75, 75); DrawRectangle(75, 200, 150, 150); DrawRectangle(200, 75, 150, 150); FCanvas.ClearSelection; TestLib.RunMouseClick(76, 76); CheckNotNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.TestZoomPositionCheckAfterMove; begin FCanvas.TrackAnimated := False; MousePath.New .Add(50, 50) .Add(100, 100) .Add(100, 150) .Add(150, 150) .Add(200, 200); TestLib.RunMousePath(MousePath.Path); FCanvas.ZoomOutAtPoint(75, 75); FCanvas.ZoomOutAtPoint(75, 75); FCanvas.ZoomOutAtPoint(75, 75); DrawRectangle(75, 75, 150, 150); FCanvas.ClearSelection; FCanvas.ZoomOutAtPoint(75, 75); DrawRectangle(75, 200, 150, 150); DrawRectangle(200, 75, 150, 150); FCanvas.ClearSelection; TestLib.RunMouseClick(76, 76); CheckNotNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.BugTestZoomAfterDrawCenter; begin FForm.Left := 10; FForm.Top := 10; FForm.Width := 1020; FForm.Height := 920; FCanvas.BoundsRect := RectF(10,10,1010,910); TestLib.SetInitialMousePoint(GetInitialPoint); Application.ProcessMessages; FCanvas.ZoomOut; FCanvas.ZoomOut; FCanvas.ZoomOut; DrawRectangle(100, 100, 200, 200); FCanvas.ClearSelection; TestLib.RunMouseClick(101, 101); CheckNotNull(FCanvas.SelectedItem, 'TopLeft'); FCanvas.ClearSelection; TestLib.RunMouseClick(199, 199); CheckNotNull(FCanvas.SelectedItem, 'BottomRight'); FCanvas.ClearSelection; TestLib.RunMouseClick(99, 99); CheckNull(FCanvas.SelectedItem); // CheckNull(FCanvas.SelectedItem, Format('TopLeft Null %f, %f', [FCanvas.SelectedItem.Position.X, FCanvas.SelectedItem.Position.Y])); FCanvas.ClearSelection; TestLib.RunMouseClick(201, 201); CheckNull(FCanvas.SelectedItem); // CheckNull(FCanvas.SelectedItem, Format('BottomRight Null %f, %f', [FCanvas.SelectedItem.Position.X, FCanvas.SelectedItem.Position.Y])); end; procedure TestTThCanvasZoom.BugTestZoomAfterDraw25; begin FForm.Left := 10; FForm.Top := 10; FForm.Width := 1020; FForm.Height := 920; FCanvas.BoundsRect := RectF(10,10,1010,910); TestLib.SetInitialMousePoint(GetInitialPoint); Application.ProcessMessages; FCanvas.ZoomOutAtPoint(FCanvas.Width / 4, FCanvas.Height / 4); FCanvas.ZoomOutAtPoint(FCanvas.Width / 4, FCanvas.Height / 4); FCanvas.ZoomOutAtPoint(FCanvas.Width / 4, FCanvas.Height / 4); DrawRectangle(100, 100, 200, 200); FCanvas.ClearSelection; TestLib.RunMouseClick(101, 101); CheckNotNull(FCanvas.SelectedItem, 'TopLeft'); FCanvas.ClearSelection; TestLib.RunMouseClick(199, 199); CheckNotNull(FCanvas.SelectedItem, 'BottomRight'); FCanvas.ClearSelection; TestLib.RunMouseClick(99, 99); CheckNull(FCanvas.SelectedItem); FCanvas.ClearSelection; TestLib.RunMouseClick(201, 201); CheckNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.BugTestZoomAfterDraw75; begin FForm.Left := 10; FForm.Top := 10; FForm.Width := 1020; FForm.Height := 920; FCanvas.BoundsRect := RectF(10,10,1010,910); TestLib.SetInitialMousePoint(GetInitialPoint); Application.ProcessMessages; FCanvas.ZoomOutAtPoint(FCanvas.Width / 4 * 3, FCanvas.Height / 4 * 3); FCanvas.ZoomOutAtPoint(FCanvas.Width / 4 * 3, FCanvas.Height / 4 * 3); FCanvas.ZoomOutAtPoint(FCanvas.Width / 4 * 3, FCanvas.Height / 4 * 3); DrawRectangle(100, 100, 200, 200); FCanvas.ClearSelection; TestLib.RunMouseClick(101, 101); CheckNotNull(FCanvas.SelectedItem, 'TopLeft'); FCanvas.ClearSelection; TestLib.RunMouseClick(199, 199); CheckNotNull(FCanvas.SelectedItem, 'BottomRight'); FCanvas.ClearSelection; TestLib.RunMouseClick(99, 99); CheckNull(FCanvas.SelectedItem); FCanvas.ClearSelection; TestLib.RunMouseClick(201, 201); CheckNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.TestMinSizeWithZoomOfDrawing; begin FCanvas.ZoomOut; FCanvas.ZoomOut; DrawRectangle(10, 10, 20, 20); FCanvas.ClearSelection; TestLib.RunMouseClick(10 + ItemMinimumSize - 1, 10 + ItemMinimumSize - 1); CheckNotNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.TestMinSizeWithZoomOfResizing; begin FCanvas.ZoomOut; FCanvas.ZoomOut; DrawRectangle(10, 10, 100, 100); MousePath.New .Add(100, 100) .Add(20, 20); TestLib.RunMousePath(MousePath.Path); FCanvas.ClearSelection; TestLib.RunMouseClick(10 + ItemMinimumSize - 1, 10 + ItemMinimumSize - 1); CheckNotNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.BugTestAfterZoomingOverRangeLineSelection; var I: Integer; begin DrawLine(100, 100, 200, 200); FCanvas.ClearSelection; for I := 0 to 100 do FCanvas.ZoomInAtPoint(100, 100); TestLib.RunMouseClick(50, 50); CheckNull(FCanvas.SelectedItem); end; procedure TestTThCanvasZoom.BugZoomGoHome; var R: TRectF; begin R := FCanvas.BoundsRect; DrawRectangle(R.CenterPoint.X - 50, R.CenterPoint.Y - 50, R.CenterPoint.X + 50, R.CenterPoint.Y + 50); FCanvas.SetBounds(FCanvas.Position.X, FCanvas.Position.Y, 500, 500); FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ZoomOutAtPoint(100, 100); FCanvas.ZoomHome; FCanvas.ClearSelection; TestLib.RunMouseClick(FCanvas.BoundsRect.CenterPoint.X, FCanvas.BoundsRect.CenterPoint.Y); Check(FCanvas.ZoomScale = CanvasZoomScaleDefault, Format('ZoomScale: %f(<> %f)', [FCanvas.ZoomScale, CanvasZoomScaleDefault])); CheckNotNull(FCanvas.SelectedItem); // FCanvas.c // Check(FCanvas.CenterPoint.X * FCanvas.ZoomScale = FCanvas.BoundsRect.CenterPoint.X); end; initialization // Register any test cases with the test runner RegisterTest(TestTThCanvasZoom.Suite); end.
program HowToDetectShapeCollision; uses SwinGame, sgTypes; procedure BouncingCircle(var cPoint : Point2D; c : Circle; l : LinesArray); var random : Integer; begin random := Rnd(8); if CircleLinesCollision(c, l) = false then begin case random of 0: begin // Top cPoint.x += 0; cPoint.y -= 1; end; 1: begin // Bottom cPoint.x += 0; cPoint.y += 1; end; 2: begin // Left cPoint.x -= 1; cPoint.y += 0; end; 3: begin // Right cPoint.x += 1; cPoint.y += 0; end; 4: begin // Top Left cPoint.x -= 1; cPoint.y -= 1; end; 5: begin // Top Right cPoint.x += 1; cPoint.y -= 1; end; 6: begin // Bottom Left cPoint.x -= 1; cPoint.y += 1; end; 7: begin // Bottom Right cPoint.x += 1; cPoint.y += 1; end; end; end; end; procedure Main(); var c : Color; c1 : Circle; lineArray : Array[0..3] of LineSegment; begin OpenGraphicsWindow('Shape Collision Movement', 800, 600); LoadDefaultColors(); c := ColorGreen; c1 := CircleAt(400, 300, 15); // return a circle lineArray[0] := LineFrom(300, 200, 300, 400); lineArray[1] := LineFrom(500, 200, 500, 400); lineArray[2] := LineFrom(300, 200, 500, 200); lineArray[3] := LineFrom(300, 400, 500, 400); repeat // The game loop... ProcessEvents(); ClearScreen(ColorWhite); FillCircle(c, c1); DrawLine(ColorGreen, lineArray[0]); DrawLine(ColorGreen, lineArray[1]); DrawLine(ColorGreen, lineArray[2]); DrawLine(ColorGreen, lineArray[3]); BouncingCircle(c1.center, c1, lineArray); RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
unit uAddModifAdr3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uAddModifForm, uInvisControl, uSpravControl, uFormControl, StdCtrls, Buttons, uFControl, uLabeledFControl, uCharControl, DB, FIBDataSet, pFIBDataSet, uAdr_DataModule; type TAddModifAdrForm3 = class(TAddModifForm) qFCC_Korpus: TqFCharControl; qFCC_House: TqFCharControl; qFCC_Flat: TqFCharControl; qFCC_Zip: TqFCharControl; OkButton: TBitBtn; qFFC_Adress: TqFFormControl; CancelButton: TBitBtn; qFSC_CArea: TqFSpravControl; qFSC_Street: TqFSpravControl; qFIC_AdrPK: TqFInvisControl; qFSC_Country: TqFSpravControl; qFSC_Region: TqFSpravControl; qFSC_District: TqFSpravControl; qFSC_Place: TqFSpravControl; procedure qFSC_DistrictOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_CountryOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_RegionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_PlaceOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_StreetOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_CAreaOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure qFSC_PlaceChange(Sender: TObject); procedure qFSC_CountryChange(Sender: TObject); procedure qFSC_RegionChange(Sender: TObject); procedure qFSC_DistrictChange(Sender: TObject); procedure OkButtonClick(Sender: TObject); private Mode: TFormMode; DM: TAdrDM; { Private declarations } public constructor Create(AOwner:TComponent; DMod: TAdrDM; Mode: TFormMode; Where: Variant; id_PK:Variant); end; var AddModifAdrForm3: TAddModifAdrForm3; implementation {$R *.dfm} uses RxMemDS, uUnivSprav; constructor TAddModifAdrForm3.Create(AOwner:TComponent; DMod: TAdrDM; Mode: TFormMode; Where: Variant; id_PK:Variant); begin inherited Create(AOwner); Self.Mode := Mode; Self.DM := TAdrDM.Create(Self); Self.DM := DMod; DBHandle:=Integer(DM.pFIBDB_Adr.Handle); qFIC_AdrPK.SetValue(id_PK); qFFC_Adress.Prepare(DM.pFIBDB_Adr,Mode,Where,Null); qFIC_AdrPK.SetValue(id_PK); end; procedure TAddModifAdrForm3.qFSC_CountryOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник країн'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Country_Form'; Params.ModifFormClass:='TAdd_Country_Form'; Params.TableName:='adr_country'; Params.Fields:='Name_country,id_country'; Params.FieldsName:='Назва'; Params.KeyField:='id_country'; Params.ReturnFields:='Name_country,id_country'; Params.DeleteSQL:='execute procedure adr_country_d(:id_country);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin value:=output['id_country']; DisplayText:=VarToStr(output['Name_country']); end; end; procedure TAddModifAdrForm3.qFSC_RegionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; begin if VarIsNull(qFSC_Country.Value) then begin ShowMessage('Спочатку оберіть країну!'); Exit; end; Params.FormCaption:='Довідник регіонів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Region_Form'; Params.ModifFormClass:='TAdd_Region_Form'; Params.TableName:='ADR_REGION_SELECT('+IntToStr(qFSC_Country.Value)+');'; Params.Fields:='Name_region,id_region'; Params.FieldsName:='Назва'; Params.KeyField:='id_region'; Params.ReturnFields:='Name_region,id_region'; Params.DeleteSQL:='execute procedure adr_region_d(:id_region);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin // ShowInfo(output); value:=output['id_region']; DisplayText:=VarToStr(output['Name_region']); end; end; procedure TAddModifAdrForm3.qFSC_DistrictOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; begin if VarIsNull(qFSC_Region.Value) then begin ShowMessage('Спочатку оберіть регіон!'); Exit; end; Params.FormCaption:='Довідник районів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_District_Form'; Params.ModifFormClass:='TAdd_District_Form'; Params.TableName:='adr_district_select('+IntToStr(qFSC_Region.Value)+');'; Params.Fields:='Name_district,id_district'; Params.FieldsName:='Район'; Params.KeyField:='id_district'; Params.ReturnFields:='Name_district,id_district'; Params.DeleteSQL:='execute procedure adr_district_d(:id_district);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin // ShowInfo(output); value:=output['id_district']; DisplayText:=VarToStr(output['Name_district']); end; end; procedure TAddModifAdrForm3.qFSC_PlaceOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; id_distr: string; begin if VarIsNull(qFSC_Region.Value) then begin ShowMessage('Спочатку оберіть регіон!'); Exit; end; if not VarIsNull(qFSC_District.Value) then id_distr:=IntToStr(qFSC_District.Value) else id_distr:='null'; Params.FormCaption:='Довідник міст'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Place_Form'; Params.ModifFormClass:='TAdd_Place_Form'; Params.TableName:='ADR_PLACE_SELECT('+IntToStr(qFSC_Region.Value)+','+id_distr+')'; Params.Fields:='Name_place,id_place'; Params.FieldsName:='Назва'; Params.KeyField:='id_place'; Params.ReturnFields:='Name_place,id_place'; Params.DeleteSQL:='execute procedure adr_place_d(:id_place);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin value:=output['id_place']; DisplayText:=VarToStr(output['Name_place']); end; end; procedure TAddModifAdrForm3.qFSC_StreetOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; begin if VarIsNull(qFSC_Place.Value) then begin ShowMessage('Спочатку оберіть місто!'); Exit; end; Params.FormCaption:='Довідник вулиць'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit]; Params.AddFormClass:='TAdd_Street_Form'; Params.ModifFormClass:='TAdd_Street_Form'; Params.TableName:='ADR_STREET_SELECT('+IntToStr(qFSC_Place.Value)+');'; Params.Fields:='Name_street,id_street'; Params.FieldsName:='Вулиця'; Params.KeyField:='id_street'; Params.ReturnFields:='Name_street,id_street'; Params.DeleteSQL:='execute procedure adr_street_d(:id_street);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin // ShowInfo(output); value:=output['id_street']; DisplayText:=VarToStr(output['Name_street']); end; end; procedure TAddModifAdrForm3.qFSC_CAreaOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var Params:TUnivParams; OutPut : TRxMemoryData; begin if VarIsNull(qFSC_Place.Value) then begin ShowMessage('Спочатку оберіть місто!'); Exit; end; Params.FormCaption:='Довідник міських районів'; Params.ShowMode:=fsmSelect; Params.ShowButtons:=[fbAdd,fbModif,fbDelete,fbExit]; Params.AddFormClass:='TAddCityArea'; Params.ModifFormClass:='TAddCityArea'; Params.TableName:='adr_city_area_select('+IntToStr(qFSC_Place.Value)+')'; Params.Fields:='Name_CITY_AREA,id_CITY_AREA'; Params.FieldsName:='Назва'; Params.KeyField:='id_CITY_AREA'; Params.ReturnFields:='Name_CITY_AREA,id_CITY_AREA'; Params.DeleteSQL:='execute procedure adr_CITY_AREA_d(:id_CITY_AREA);'; Params.DBHandle:=DBHandle; OutPut:=TRxMemoryData.Create(self); if GetUnivSprav(Params,OutPut) then begin value:=output['id_CITY_AREA']; DisplayText:=VarToStr(output['Name_CITY_AREA']); end; end; procedure TAddModifAdrForm3.qFSC_CountryChange(Sender: TObject); begin if not Visible then Exit; qFSC_Region.Clear; end; procedure TAddModifAdrForm3.qFSC_RegionChange(Sender: TObject); begin if not Visible then Exit; qFSC_District.Clear; end; procedure TAddModifAdrForm3.qFSC_DistrictChange(Sender: TObject); begin if not Visible then Exit; qFSC_Place.Clear; end; procedure TAddModifAdrForm3.qFSC_PlaceChange(Sender: TObject); begin if not Visible then Exit; qFSC_Street.Clear; qFSC_CArea.Clear; end; procedure TAddModifAdrForm3.OkButtonClick(Sender: TObject); begin qFFC_Adress.Ok; end; initialization RegisterClass(TAddModifAdrForm3); end.
unit Memory_Editor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, StdCtrls, Grids, MaskEdit, Types; type { TMemoryEditor } TMemoryEditor = class(TForm) editMemoryCell: TEdit; gridSystemMemory: TDrawGrid; statusBar: TStatusBar; procedure editMemoryCellEditingDone(Sender: TObject); procedure editMemoryCellKeyPress(Sender: TObject; var Key: char); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormShow(Sender: TObject); procedure gridSystemMemoryDblClick(Sender: TObject); procedure gridSystemMemoryDrawCell(Sender: TObject; aCol, aRow: integer; aRect: TRect; aState: TGridDrawState); procedure gridSystemMemorySelectEditor(Sender: TObject; aCol, aRow: integer; var Editor: TWinControl); procedure statusBarResize(Sender: TObject); private CpuProgrammCounter: DWord; public procedure showMemoryData; procedure memoryChanged; end; var MemoryEditor: TMemoryEditor; implementation {$R *.lfm} { TMemoryEditor } uses LCLIntf, LCLType, UscaleDPI, System_Settings, strutils, System_Memory, Z180_CPU; // -------------------------------------------------------------------------------- procedure TMemoryEditor.FormShow(Sender: TObject); begin with gridSystemMemory do begin BeginUpdate; ColCount := 17; Font.Name := 'Droid Sans Mono'; Font.Size := 10; Canvas.Font.Style := [fsBold]; DefaultRowHeight := Canvas.TextExtent('X').Height + Canvas.TextExtent('|').Width; DefaultColWidth := Canvas.TextExtent('XXX').Width; ColWidths[0] := Canvas.TextExtent('XXXXXX').Width; EndUpdate(); end; editMemoryCell.Font.Name := 'Droid Sans Mono'; editMemoryCell.Font.Size := 10; Width := gridSystemMemory.ColWidths[0] + (16 * gridSystemMemory.DefaultColWidth) + GetSystemMetrics(SM_CYHSCROLL) + 2; Height := (17 * gridSystemMemory.DefaultRowHeight) + statusBar.Height + 2; Constraints.MinWidth := Width; Constraints.MaxWidth := Width; Constraints.MinHeight := Height; Constraints.MaxHeight := Height; SystemSettings.restoreFormState(TForm(self)); ScaleDPI(self, 96); memoryChanged; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.gridSystemMemoryDblClick(Sender: TObject); var cellRect: TRect; begin cellRect := gridSystemMemory.CellRect(gridSystemMemory.Col, gridSystemMemory.Row); cellRect.Left := cellRect.Left + gridSystemMemory.Left; cellRect.Right := cellRect.Right + gridSystemMemory.Left; cellRect.Top := cellRect.Top + gridSystemMemory.Top; cellRect.Bottom := cellRect.Bottom + gridSystemMemory.Top; if ((gridSystemMemory.Col > 0) and (gridSystemMemory.Row > 0)) then begin with editMemoryCell do begin Left := cellRect.Left + 1; Top := cellRect.Top + 1; Width := cellRect.Right - cellRect.Left - 1; Height := cellRect.Bottom - cellRect.Top - 1; Text := IntToHex(SystemMemory.Read(((gridSystemMemory.Row - 1) shl 4) + (gridSystemMemory.Col - 1)), 2); SelectAll; Visible := True; SetFocus; end; end else begin editMemoryCell.Visible := False; end; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin SystemSettings.saveFormState(TForm(self)); CloseAction := caFree; MemoryEditor := nil; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.editMemoryCellKeyPress(Sender: TObject; var Key: char); begin if not (Key in ['0'..'9', 'a'..'f', 'A'..'F', #8]) then begin Key := #0; end; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.editMemoryCellEditingDone(Sender: TObject); begin SystemMemory.Write((((gridSystemMemory.Row - 1) shl 4) + (gridSystemMemory.Col - 1)), Hex2Dec(editMemoryCell.Text)); editMemoryCell.Visible := False; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.gridSystemMemoryDrawCell(Sender: TObject; aCol, aRow: integer; aRect: TRect; aState: TGridDrawState); var CellText: string; TextWidth, TextHeight: integer; TextTop, TextLeft: integer; memAddr: DWord; begin if (aCol >= 1) and (aCol <= 16) and (aRow = 0) then begin CellText := IntToHex(aCol - 1, 2); gridSystemMemory.Canvas.Font.Style := [fsBold]; end else if (aCol = 0) and (aRow >= 1) then begin CellText := IntToHex((aRow - 1) * 16, 4); gridSystemMemory.Canvas.Font.Style := [fsBold]; end else if (aCol >= 1) and (aRow >= 1) then begin memAddr := ((aRow - 1) shl 4) + (aCol - 1); CellText := IntToHex(SystemMemory.Read(memAddr), 2); gridSystemMemory.Canvas.Font.Style := []; if (SystemMemory.IsRomEnabled = True) and (memAddr < SystemMemory.GetBootRomSize) then begin gridSystemMemory.Canvas.Brush.Color := $BABAFF; end else begin gridSystemMemory.Canvas.Brush.Color := clDefault; end; if (memAddr = CpuProgrammCounter) then begin gridSystemMemory.Canvas.Brush.Color := $A5FF9D; end; //if (gdFocused in aState) then begin // gridSystemMemory.Canvas.Brush.Color := clDefault; //end; end; gridSystemMemory.Canvas.FillRect(aRect); gridSystemMemory.Canvas.GetTextSize(CellText, TextWidth, TextHeight); TextTop := aRect.Top + ((aRect.Height - TextHeight) div 2); TextLeft := aRect.Left + ((aRect.Width - TextWidth) div 2); gridSystemMemory.Canvas.TextOut(TextLeft, TextTop, CellText); end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.gridSystemMemorySelectEditor(Sender: TObject; aCol, aRow: integer; var Editor: TWinControl); begin if ((aCol > 0) and (aRow > 0)) then begin editMemoryCell.BoundsRect := gridSystemMemory.CellRect(aCol, aRow); editMemoryCell.Text := IntToHex(SystemMemory.Read(((aRow - 1) shl 4) + (aCol - 1)), 2); Editor := editMemoryCell; end; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.statusBarResize(Sender: TObject); begin statusBar.Panels[0].Width := self.Width div 2; statusBar.Panels[1].Width := self.Width div 2; end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.showMemoryData; begin CpuProgrammCounter := Z180Cpu.getCoreData().PCmmu; gridSystemMemory.BeginUpdate; gridSystemMemory.Row := 0; gridSystemMemory.Row := (CpuProgrammCounter div 16) + 8; gridSystemMemory.EndUpdate(); end; // -------------------------------------------------------------------------------- procedure TMemoryEditor.memoryChanged; begin gridSystemMemory.RowCount := (SystemMemory.GetSystemMemorySize div 16) + 1; statusBar.Panels[0].Text := ' System-Memory Size : ' + IntToStr(SystemMemory.GetSystemMemorySize div 1024) + 'KB'; statusBar.Panels[1].Text := ' Boot-ROM Size : ' + IntToStr(SystemMemory.GetBootRomSize div 1024) + 'KB'; end; // -------------------------------------------------------------------------------- end.
{ 6.11.2002 10:53:07 (GMT+1:00) > [shmia on SHMIA01] checked in } {---------------------------------------------------} { Copyright (c)2000 by Przemyslaw Jankowski } { e-mail: pjank@pjank.pl } {---------------------------------------------------} { } { Thanks to: } { - Harald Bender <bender@nt-newton.fho-emden.de> } { for helping me with WinNT support } { and German error messages } { } {---------------------------------------------------} unit RAWPrinting; {$B-,H+,X+} interface uses SysUtils, Printers; type ERAWPrintError = class(EPrinter); ERAWPrintErrorPrinterName = class(ERAWPrintError); procedure RAWPrint(PrinterName:string;const DocumentTitle, DocumentData: string); // PrinterName - the name of the printer you want to use // to use the default printer - leave this blank // DocumentTitle - the text that is listed in the Print Manager // DocumentData - the text you want to send to the printer function GetDefaultPrinter:string; implementation uses WinSpool, Windows, Consts; const // English // //errOpenPrinter = 'The printer "%s" is not available.'; //errPrintError = 'Error printing the document "%s".'; // German // errOpenPrinter = 'Der Drucker "%s" ist nicht verfügbar.'; errPrintError = 'Fehler beim Drucken von Dokument "%s".'; // Polish // //errOpenPrinter = 'Drukarka "%s" jest niedostępna.'; //errPrintError = 'Błąd przy drukowaniu "%s".'; function GetDefaultPrinter:string; var str: array[0..79]of Char; function FetchStr(s:string):string; var i: Integer; begin s:= TrimLeft(s); i:= Pos(',',s); if i=0 then Result:= s else Result:= Copy(s, 1, i-1); end; begin GetProfileString('windows', 'device', '', str, SizeOf(str)-1); Result:= FetchStr(str); if Result='' then raise EPrinter.Create(SNoDefaultPrinter); end; procedure RAWPrint(PrinterName:string;const DocumentTitle, DocumentData: string); var hPrinter: NativeUInt; DocInfo: TDocInfo1; dwJob: Integer; dwBytesWritten: DWord; procedure PrintError; begin raise ERAWPrintError.Create(Format(errPrintError, [DocumentTitle])); end; begin if PrinterName='' then PrinterName:= GetDefaultPrinter; if not OpenPrinter(PChar(PrinterName), hPrinter, nil) then raise ERAWPrintErrorPrinterName.Create(Format(errOpenPrinter, [PrinterName])); try DocInfo.pOutputFile:= nil; DocInfo.pDatatype:= 'RAW'; DocInfo.pDocName:= PChar(DocumentTitle); dwJob:= StartDocPrinter(hPrinter, 1, @DocInfo); if (dwJob=0) then PrintError; try if not StartPagePrinter(hPrinter) then PrintError; try if not WritePrinter(hPrinter, Pointer(DocumentData), Length(DocumentData), dwBytesWritten) then PrintError; if (LongInt(dwBytesWritten)<Length(DocumentData)) then PrintError; finally if not EndPagePrinter(hPrinter) then PrintError; end; finally if not EndDocPrinter(hPrinter) then PrintError; end; finally ClosePrinter(hPrinter); end; end; end.
(* Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES Original name: 0001.PAS Description: BITS1.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:53 *) { Sean Palmer > What if I want to just access a bit? Say I have a Byte, to store > Various access levels (if it does/doesn't have this, that, or the > other). How can I > 1) Access, say, bit 4? > 2) Give, say, bit 4, a value of 1? > I have a simple routine that does "GetBit:= Value SHR 1;" to return > a value, but how can I *SET* a value? And is the above a good > method? I only have TP5.5, so I can't do the Asm keyWord (yet..). You COULD use TP sets to do it... } Type tByte = set of 0..7; Var b : Byte; {to get: Write('Bit 0 is ',Boolean(0 in tByte(b))); to set: tByte(b):=tByte(b)+[1,3,4]-[0,2]; } Type bitNum = 0..7; bit = 0..1; Function getBit(b : Byte; n : bitNum) : bit; begin getBit := bit(odd(b shr n)); end; Function setBit( b : Byte; n : bitNum) : Byte; begin setBit := b or (1 shl n); end; Function clrBit(b : Byte; n : bitNum) : Byte; begin clrBit := b and hi($FEFF shl n); end; begin WriteLn('Bit 2 of number 4 is: ', getBit(4, 2)); WriteLn('Bit 5 of number 4 is: ', getBit(4, 5)); b := 4; b := setBit(b, 5); WriteLn('After setting bit 5, it becomes: ', b); end. { OR.....using Inline() code (the fastest) These are untested but I'm getting fairly good at assembling by hand...8) } (* Function getBit(b : Byte; n : bitNum) : bit; Inline( $59/ {pop cx} $58/ {pop ax} $D2/$E8/ {shr al,cl} $24/$01); {and al,1} Function setBit(b : Byte; n : bitNum) : Byte; Inline( $59/ {pop cx} $58/ {pop ax} $B3/$01/ {mov bl,1} $D2/$E3/ {shl bl,cl} $0A/$C3); {or al,bl} Function clrBit(b : Byte; n : bitNum) : Byte; Inline( $59/ {pop cx} $58/ {pop ax} $B3/$FE/ {mov bl,$FE} $D2/$C3/ {rol bl,cl} $22/$C3); {or al,bl} *)
unit ConfigurationUnit; interface Uses SysUtils,Classes,Windows; Type TStringArray = Array Of String; Type TConfiguration = Class RootPath : String; QuarantinePathes : TStringArray; DeniedExt : TStringArray; Procedure ImportSetting(_Setting:String); Function ExportSetting() : String; Procedure Configure(); Constructor Create(); End; implementation Uses GlobalFunctionsUnit; { TConfiguration } procedure TConfiguration.Configure; Var TempStrList : TStringList; ConfigFilePath : String; begin WaitForSingleObject(Mutex, INFINITE); Try SetLength(QuarantinePathes,0); SetLength(DeniedExt,0); ConfigFilePath := ApplicationPath + 'Config.txt'; TempStrList := TStringList.Create; Try if Not FileExists(ConfigFilePath) then Begin SetLength(QuarantinePathes,1); SetLength(DeniedExt,1); TempStrList.Text := ExportSetting(); TempStrList.SaveToFile(ConfigFilePath); SetLength(QuarantinePathes,0); SetLength(DeniedExt,0); End else Begin TempStrList.LoadFromFile(ConfigFilePath); ImportSetting(TempStrList.Text); End; Finally TempStrList.Free; End; Finally ReleaseMutex(Mutex); End; end; constructor TConfiguration.Create; begin Configure(); end; function TConfiguration.ExportSetting: String; Var I:Integer; begin Result := ''; Result := AddXmlStyle('Inboxes Root Path',RootPath)+sLineBreak; Result := Result + sLineBreak + '<Quarantine Pathes>'+ sLineBreak; for I := 0 to High(QuarantinePathes) do Begin Result := Result + AddXmlStyle(Format('Quarantine Path No %d',[I]),QuarantinePathes[I])+sLineBreak; End; Result := Result + sLineBreak + '</Quarantine Pathes>' + sLineBreak + sLineBreak; Result := Result + sLineBreak + '<Denied Extentions>'+ sLineBreak; for I := 0 to High(DeniedExt) do Begin Result := Result + AddXmlStyle(Format('Denied Extention No %d',[I]),DeniedExt[I])+sLineBreak; End; Result := Result + sLineBreak + '</Denied Extentions>' + sLineBreak + sLineBreak; end; procedure TConfiguration.ImportSetting(_Setting: String); Var TempStr : String; TempItem : String; ItemFound : Boolean; I : Integer; begin RootPath := Trim(GetNodeFromXml('Inboxes Root Path',_Setting)); TempStr := Trim(GetNodeFromXml('Quarantine Pathes',_Setting)); SetLength(QuarantinePathes,0); ItemFound := True; I := 0; while ItemFound do Begin TempItem := Trim(GetNodeFromXml(Format('Quarantine Path No %d',[I]),TempStr)); if TempItem <> '' then Begin SetLength(QuarantinePathes,Length(QuarantinePathes)+1); QuarantinePathes[High(QuarantinePathes)] := TempItem; Inc(I); End else ItemFound := False; End; TempStr := Trim(GetNodeFromXml('Denied Extentions',_Setting)); SetLength(DeniedExt,0); ItemFound := True; I := 0; while ItemFound do Begin TempItem := Trim(GetNodeFromXml(Format('Denied Extention No %d',[I]),TempStr)); if TempItem <> '' then Begin SetLength(DeniedExt,Length(DeniedExt)+1); DeniedExt[High(DeniedExt)] := TempItem; Inc(I); End else ItemFound := False; End; end; end.
unit ibSHPSQLDebugger; interface uses SysUtils, Classes, StrUtils, SHDesignIntf, SHEvents, SHOptionsIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHComponent, ibSHTool, ibSHConsts, ibSHDebuggerIntf; type TibSHPSQLDebugger = class(TibBTTool, IibSHPSQLDebugger, IibSHDDLInfo, IibSHBranch, IfbSHBranch) private FDebugComponent: TSHComponent; FParentDebugger: IibSHPSQLDebugger; FDRVTransactionComponent: TSHComponent; FDRVTransaction: IibSHDRVTransaction; FDebugDDL: TStrings; protected { IibSHPSQLDebugger } function GetDebugComponent: TSHComponent; function GetDRVTransaction: IibSHDRVTransaction; function GetParentDebugger: IibSHPSQLDebugger; procedure Debug(AParentDebugger: IibSHPSQLDebugger; AClassIID: TGUID; ACaption: string); { End of IibSHPSQLDebugger } { IibSHDDLInfo } function GetDDL: TStrings; function GetBTCLDatabase: IibSHDatabase; function GetState: TSHDBComponentState; procedure CreateDRV; procedure FreeDRV; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property DebugComponent: TSHComponent read GetDebugComponent; property DRVTransaction: IibSHDRVTransaction read GetDRVTransaction; property ParentDebugger: IibSHPSQLDebugger read GetParentDebugger; end; TibSHPSQLDebuggerFactory = class(TibBTToolFactory) end; procedure Register; implementation uses ibSHPSQLDebuggerActions; procedure Register; begin SHRegisterImage(GUIDToString(IibSHPSQLDebugger), 'PSQLDebugger.bmp'); SHRegisterImage(SCallTracing, 'Form_PSQLDebugger.bmp'); SHRegisterImage(TibSHPSQLDebuggerFormAction.ClassName, 'Form_PSQLDebugger.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_SetParameters.ClassName, 'Button_SetParameters.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_TraceInto.ClassName, 'Button_TraceInto.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_StepOver.ClassName, 'Button_StepOver.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_SkipStatement.ClassName, 'Button_SkipStatement.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_RunToCursor.ClassName, 'Button_RunToCursor.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_ToggleBreakpoint.ClassName, 'Button_Breakpoint.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_AddWatch.ClassName, 'Button_AddWatch.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_Reset.ClassName, 'Button_Reset.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_Pause.ClassName, 'Button_Stop.bmp'); SHRegisterImage(TibSHPSQLDebuggerToolbarAction_ModifyVarValues.ClassName, 'Button_Evaluate.bmp'); SHRegisterImage(TibSHSendToPSQLDebuggerToolbarAction.ClassName, 'PSQLDebugger.bmp'); SHRegisterComponents([ TibSHPSQLDebugger, TibSHPSQLDebuggerFactory]); SHRegisterActions([ // Palette //TibSHPSQLDebuggerPaletteAction - на хуй не нужен типа // Forms TibSHPSQLDebuggerFormAction, // Toolbar TibSHPSQLDebuggerToolbarAction_SetParameters, TibSHPSQLDebuggerToolbarAction_TraceInto, TibSHPSQLDebuggerToolbarAction_StepOver, TibSHPSQLDebuggerToolbarAction_SkipStatement, TibSHPSQLDebuggerToolbarAction_RunToCursor, TibSHPSQLDebuggerToolbarAction_ToggleBreakpoint, TibSHPSQLDebuggerToolbarAction_AddWatch, TibSHPSQLDebuggerToolbarAction_ModifyVarValues, TibSHPSQLDebuggerToolbarAction_Reset, TibSHPSQLDebuggerToolbarAction_Run, TibSHPSQLDebuggerToolbarAction_Pause, TibSHSendToPSQLDebuggerToolbarAction // Editors ]); end; { TibSHDebugger } constructor TibSHPSQLDebugger.Create(AOwner: TComponent); begin inherited Create(AOwner); FDebugComponent := nil; FDebugDDL := TStringList.Create; end; destructor TibSHPSQLDebugger.Destroy; begin FDebugDDL.Free; if Assigned(FDebugComponent) then FreeAndNil(FDebugComponent); // FDebugComponent.Free; inherited; end; function TibSHPSQLDebugger.GetDebugComponent: TSHComponent; begin Result := FDebugComponent; end; function TibSHPSQLDebugger.GetDRVTransaction: IibSHDRVTransaction; begin Result := FDRVTransaction; end; function TibSHPSQLDebugger.GetParentDebugger: IibSHPSQLDebugger; begin Result := FParentDebugger; end; procedure TibSHPSQLDebugger.Debug(AParentDebugger: IibSHPSQLDebugger; AClassIID: TGUID; ACaption: string); var vPSQLDebuggerForm: IibSHPSQLDebuggerForm; begin if not Assigned(FDebugComponent) and (Length(ACaption) > 0) and ( IsEqualGUID(AClassIID, IibSHProcedure) or IsEqualGUID(AClassIID, IibSHTrigger) ) then begin // FDebugComponent := Designer.CreateComponent(OwnerIID, AClassIID, ACaption); if Assigned(AParentDebugger) then begin if Assigned(FParentDebugger) then begin FreeDRV; ReferenceInterface(FParentDebugger, opRemove); end; FParentDebugger := AParentDebugger; ReferenceInterface(FParentDebugger, opInsert); FDRVTransaction := FParentDebugger.DRVTransaction; end else CreateDRV; FDebugComponent := Designer.GetComponent(AClassIID).Create(nil); Designer.Components.Remove(FDebugComponent); FDebugComponent.OwnerIID := OwnerIID; FDebugComponent.Caption := ACaption; (FDebugComponent as IibSHDBObject).State := csSource; if not GetComponentFormIntf(IibSHPSQLDebuggerForm, vPSQLDebuggerForm) then Designer.ChangeNotification(Self, SCallTracing, opInsert); if GetComponentFormIntf(IibSHPSQLDebuggerForm, vPSQLDebuggerForm) then vPSQLDebuggerForm.ChangeNotification; Designer.UpdateActions; end; end; function TibSHPSQLDebugger.GetDDL: TStrings; begin Result := FDebugDDL; end; function TibSHPSQLDebugger.GetBTCLDatabase: IibSHDatabase; begin Result := BTCLDatabase; end; function TibSHPSQLDebugger.GetState: TSHDBComponentState; begin Result := csSource; end; procedure TibSHPSQLDebugger.CreateDRV; var vComponentClass: TSHComponentClass; begin vComponentClass := Designer.GetComponent(BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVTransaction)); if Assigned(vComponentClass) then begin FDRVTransactionComponent := vComponentClass.Create(Self); Supports(FDRVTransactionComponent, IibSHDRVTransaction, FDRVTransaction); DRVTransaction.Params.Text := TransactionParamsSnapshot; DRVTransaction.Database := BTCLDatabase.DRVQuery.Database; end; Assert(DRVTransaction <> nil, 'DRVTransaction = nil'); end; procedure TibSHPSQLDebugger.FreeDRV; begin if Assigned(FDRVTransactionComponent) then begin FDRVTransaction := nil; FreeAndNil(FDRVTransactionComponent); end; end; procedure TibSHPSQLDebugger.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if Assigned(FParentDebugger) and AComponent.IsImplementorOf(FParentDebugger) then begin FParentDebugger := nil; if Assigned(FDRVTransaction) then FDRVTransaction := nil; end; end; inherited Notification(AComponent, Operation); end; initialization Register; end.
unit ideSHMegaEditor; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, ComCtrls, CommCtrl, ExtCtrls, Types, Menus, Contnrs, Dialogs, SHDesignIntf, SHEvents, ideSHDesignIntf; type TideBTMegaEditor = class(TComponent, IideBTMegaEditor) private FActive: Boolean; FMultiLine: Boolean; FFilterMode: Boolean; FEditorList: TObjectList; function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetMultiLine: Boolean; procedure SetMultiLine(Value: Boolean); function GetFilterMode: Boolean; procedure SetFilterMode(Value: Boolean); function CreatePage(AComponent: TSHComponent): Boolean; function ShowPage(AIndex: Integer): Boolean; function DestroyPage(AIndex: Integer): Boolean; procedure PageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); function CreateEditor(AComponent: TSHComponent): Integer; procedure CreateSingleEditor; procedure DestroySingleEditor; function IndexOfEditor(AComponent: TSHComponent): Integer; function ExistsEditor(AComponent: TSHComponent): Boolean; function AddEditor(AComponent: TSHComponent): Boolean; function RemoveEditor(AComponent: TSHComponent): Boolean; private procedure GetCaptionList(APopupMenu: TPopupMenu); procedure DoOnClikCaptionItem(Sender: TObject); function Exists(AComponent: TSHComponent; const CallString: string): Boolean; function Add(AComponent: TSHComponent; const CallString: string): Boolean; function Remove(AComponent: TSHComponent; const CallString: string): Boolean; procedure Toggle(AIndex: Integer); function Close: Boolean; function CloseAll: Boolean; function ShowEditor(AComponent: TSHComponent): Boolean; overload; function ShowEditor(const AIndex: Integer): Boolean; overload; function DestroyEditor(const AIndex: Integer): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses ideSHMainFrm, ideSHConsts, ideSHSystem, ideSHSysUtils, ideSHObjectEditor; { TideBTMegaEditor } constructor TideBTMegaEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); FEditorList := TObjectList.Create; FActive := True; end; destructor TideBTMegaEditor.Destroy; begin FreeAndNil(FEditorList); inherited Destroy; end; function TideBTMegaEditor.GetActive: Boolean; begin Result := FActive; end; procedure TideBTMegaEditor.SetActive(Value: Boolean); begin if FActive <> Value then begin FActive := Value; if Value then begin MainForm.pnlHost.Color := clBtnFace; MainForm.pnlHost.BevelInner := bvNone; MainForm.PageControl1.Font.Style := [fsBold]; MainForm.PageControl1.OnMouseDown := PageMouseDown; MainForm.PageControl1.OnDrawTab := DrawTab; MainForm.PageControl1.OwnerDraw := True; if Assigned(SystemOptionsIntf) and SystemOptionsIntf.UseWorkspaces then MainForm.PageControl1.Visible := True; end else begin MainForm.pnlHost.Color := clBtnFace; // clAppWorkSpace; MainForm.pnlHost.BevelInner := bvLowered; MainForm.PageControl1.OnChange := nil; MainForm.PageControl1.OnDrawTab := nil; MainForm.PageControl1.OwnerDraw := False; MainForm.PageControl1.Visible := False; end; end; end; function TideBTMegaEditor.GetMultiLine: Boolean; begin Result := FMultiLine; end; procedure TideBTMegaEditor.SetMultiLine(Value: Boolean); var I: Integer; vObjectEditorIntf: IideSHObjectEditor; begin FMultiLine := Value; for I := 0 to Pred(FEditorList.Count) do if Supports(FEditorList[I], IideSHObjectEditor, vObjectEditorIntf) then vObjectEditorIntf.MultiLine := FMultiLine; end; function TideBTMegaEditor.GetFilterMode: Boolean; begin Result := FFilterMode; end; procedure TideBTMegaEditor.SetFilterMode(Value: Boolean); var I: Integer; vObjectEditorIntf: IideSHObjectEditor; begin FFilterMode := Value; MainForm.TabSet1.Visible := FFilterMode; for I := 0 to Pred(FEditorList.Count) do if Supports(FEditorList[I], IideSHObjectEditor, vObjectEditorIntf) then vObjectEditorIntf.FilterMode := FFilterMode; end; function TideBTMegaEditor.CreatePage(AComponent: TSHComponent): Boolean; var NewIndex: Integer; PageControl: TPageControl; Page: TTabSheet; begin PageControl := MainForm.PageControl1; Result := Assigned(AComponent); if Result then begin NewIndex := Pred(PageControl.PageCount) + 1{ActivePageIndex}; Page := TTabSheet.Create(PageControl); if Supports(AComponent, ISHDatabase) then begin // Page.Caption := Format('%s\%s\..', [(DesignerIntf.FindComponent(AComponent.OwnerIID) as ISHServer).Alias, AComponent.Caption]) Page.Caption := Format('%s', [AComponent.Caption]); Page.ImageIndex := IMG_DATABASE; //DesignerIntf.GetImageIndex(AComponent.ClassIID); end else begin Page.Caption := Format('%s ', [AComponent.Caption]); Page.ImageIndex := IMG_SERVER; //DesignerIntf.GetImageIndex(AComponent.ClassIID); end; Page.Parent := PageControl; Page.PageControl := PageControl; Page.Font := PageControl.Font; Page.PageIndex := NewIndex; Page.Tag := Integer(AComponent); PageControl.ActivePageIndex := Page.PageIndex; end; end; function TideBTMegaEditor.ShowPage(AIndex: Integer): Boolean; begin Result := Pred(MainForm.PageControl1.PageCount) >= AIndex; if Result then begin MainForm.PageControl1.ActivePageIndex := AIndex; MainForm.PageControl1.Width := MainForm.PageControl1.Width + 1; // хак перерисовки MainForm.PageControl1.Width := MainForm.PageControl1.Width - 1; // хак перерисовки if Supports(TSHComponent(MainForm.PageControl1.ActivePage.Tag), ISHDatabase) and Assigned(NavigatorIntf) then NavigatorIntf.ActivateConnection(TSHComponent(MainForm.PageControl1.ActivePage.Tag)); end; end; function TideBTMegaEditor.DestroyPage(AIndex: Integer): Boolean; begin Result := Pred(MainForm.PageControl1.PageCount) >= AIndex; if Result then begin MainForm.PageControl1.Pages[AIndex].Free; end; // MainForm.PageControl1.ActivePage.Free; end; procedure TideBTMegaEditor.PageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NewIndex: Integer; P: TPoint; begin P.X := X; P.Y := Y; if Button = mbLeft then begin NewIndex := MainForm.PageControl1.IndexOfTabAt(X, Y); if NewIndex > -1 then ShowEditor(NewIndex); end; if (Button = mbRight) or (Button = mbMiddle) then begin NewIndex := MainForm.PageControl1.IndexOfTabAt(X, Y); if (NewIndex > -1) and (NewIndex <> MainForm.PageControl1.ActivePageIndex) then begin MainForm.PageControl1.ActivePageIndex := NewIndex; if MainForm.PageControl1.PageCount > 0 then ShowEditor(NewIndex); end; P := MainForm.PageControl1.ClientToScreen(P); if Button = mbRight then MainForm.PopupMenuOE0.Popup(P.X, P.Y); if Button = mbMiddle then Close; end; end; procedure TideBTMegaEditor.DrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); var S: string; I: Integer; begin S := MainForm.PageControl1.Pages[TabIndex].Caption; I := MainForm.PageControl1.Pages[TabIndex].ImageIndex; with Control.Canvas do begin FillRect(Rect); DesignerIntf.ImageList.Draw(Control.Canvas, Rect.Left + 2, Rect.Top, I); if Active then Font.Style := [fsBold] else Font.Style := []; if I <> -1 then TextOut(Rect.Left + 24, (Rect.Top + Rect.Bottom - TextHeight(S)) div 2, S) else TextOut((Rect.Left + Rect.Right - TextWidth(S)) div 2, (Rect.Top + Rect.Bottom - TextHeight(S)) div 2, S) end; end; function TideBTMegaEditor.CreateEditor(AComponent: TSHComponent): Integer; var vObjectEditorIntf: IideSHObjectEditor; begin Result := FEditorList.Add(TideSHObjectEditor.Create(nil)); if (FEditorList[Result] is TComponent) then TComponent(FEditorList[Result]).Tag := Integer(AComponent); if Supports(FEditorList[Pred(FEditorList.Count)], IideSHObjectEditor, vObjectEditorIntf) then begin vObjectEditorIntf.CreateEditor; vObjectEditorIntf.MultiLine := FMultiLine; CreatePage(AComponent); end; end; procedure TideBTMegaEditor.CreateSingleEditor; var WindowLocked: Boolean; begin if FEditorList.Count = 0 then begin FEditorList.Add(TideSHObjectEditor.Create(nil)); if Supports(FEditorList[0], IideSHObjectEditor, ObjectEditorIntf) then begin ObjectEditorIntf.CreateEditor; ObjectEditorIntf.MultiLine := FMultiLine; WindowLocked := LockWindowUpdate(GetDesktopWindow); try ObjectEditorIntf.PageCtrl.BringToFront; finally if WindowLocked then LockWindowUpdate(0); end; ObjectEditorIntf.ChangeEditor; SetActive(True); end; end; end; procedure TideBTMegaEditor.DestroySingleEditor; begin if FEditorList.Count = 1 then begin ObjectEditorIntf := nil; FEditorList.Delete(0); SetActive(False); end; end; function TideBTMegaEditor.IndexOfEditor(AComponent: TSHComponent): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(FEditorList.Count) do if (FEditorList[I] is TComponent) and (TComponent(FEditorList[I]).Tag = Integer(AComponent)) then begin Result := I; Break; end; end; function TideBTMegaEditor.ExistsEditor(AComponent: TSHComponent): Boolean; begin Result := IndexOfEditor(AComponent) <> -1; end; function TideBTMegaEditor.AddEditor(AComponent: TSHComponent): Boolean; var I: Integer; begin I := IndexOfEditor(AComponent); Result := I = -1; if Result then begin I := CreateEditor(AComponent); ShowEditor(I); end; if (FEditorList.Count > 0) and (TSHComponent(MainForm.PageControl1.ActivePage.Tag) <> AComponent) then ShowEditor(I); if FEditorList.Count > 0 then SetActive(True); end; function TideBTMegaEditor.RemoveEditor(AComponent: TSHComponent): Boolean; var I: Integer; begin I := IndexOfEditor(AComponent); Result := I <> -1; if Result then DestroyEditor(I); if FEditorList.Count > 0 then ShowEditor(GetNextItem(I, FEditorList.Count)); if FEditorList.Count = 0 then SetActive(False); end; procedure TideBTMegaEditor.GetCaptionList(APopupMenu: TPopupMenu); var I: Integer; PageControl: TPageControl; NewItem: TMenuItem; begin PageControl := MainForm.PageControl1; while APopupMenu.Items.Count > 0 do APopupMenu.Items.Delete(0); if Assigned(SystemOptionsIntf) and SystemOptionsIntf.UseWorkspaces then for I := 0 to Pred(PageControl.PageCount) do begin NewItem := TMenuItem.Create(nil); NewItem.Caption := PageControl.Pages[I].Caption; NewItem.OnClick := DoOnClikCaptionItem; NewItem.ImageIndex := PageControl.Pages[I].ImageIndex; NewItem.Tag := I; NewItem.Default := PageControl.ActivePageIndex = I; NewItem.ImageIndex := 85; APopupMenu.Items.Add(NewItem); end; end; procedure TideBTMegaEditor.DoOnClikCaptionItem(Sender: TObject); begin ShowEditor(TMenuItem(Sender).Tag); end; function TideBTMegaEditor.Exists(AComponent: TSHComponent; const CallString: string): Boolean; var I: Integer; vObjectEditorIntf: IideSHObjectEditor; begin Result := False; for I := 0 to Pred(FEditorList.Count) do begin Result := Supports(FEditorList[I], IideSHObjectEditor, vObjectEditorIntf) and vObjectEditorIntf.Exists(AComponent, CallString); if Result then Break; end; end; function TideBTMegaEditor.Add(AComponent: TSHComponent; const CallString: string): Boolean; var vComponent: TSHComponent; begin Result := Assigned(AComponent); if Result then begin if Assigned(SystemOptionsIntf) and SystemOptionsIntf.UseWorkspaces then begin vComponent := DesignerIntf.FindComponent(AComponent.OwnerIID); // -> добавлено для сбора NonDatabaseContext в сепаратный редактор if not Supports(vComponent, ISHDatabase) then vComponent := DesignerIntf.FindComponent(IUnknown, AComponent.BranchIID); // <- if Assigned(vComponent) then AddEditor(vComponent); end else CreateSingleEditor; if Assigned(ObjectEditorIntf) then begin Result := ObjectEditorIntf.Add(AComponent, CallString); end; end; end; function TideBTMegaEditor.Remove(AComponent: TSHComponent; const CallString: string): Boolean; var vComponent: TSHComponent; begin vComponent := nil; Result := Assigned(AComponent); if Result then begin if Assigned(SystemOptionsIntf) and SystemOptionsIntf.UseWorkspaces then begin vComponent := DesignerIntf.FindComponent(AComponent.OwnerIID); // -> добавлено для сбора NonDatabaseContext в сепаратный редактор if not Supports(vComponent, ISHDatabase) then vComponent := DesignerIntf.FindComponent(IUnknown, AComponent.BranchIID); // <- if Assigned(vComponent) then AddEditor(vComponent); end; if Assigned(ObjectEditorIntf) then begin Result := ObjectEditorIntf.Remove(AComponent, CallString); if (ObjectEditorIntf.PageCtrl.PageCount = 0) then begin if Assigned(SystemOptionsIntf) and SystemOptionsIntf.UseWorkspaces then begin if ExistsEditor(vComponent) then RemoveEditor(vComponent); end else DestroySingleEditor; end; end; end; end; procedure TideBTMegaEditor.Toggle(AIndex: Integer); begin ShowEditor(AIndex); end; function TideBTMegaEditor.Close: Boolean; var I: Integer; begin Result := True; I := MainForm.PageControl1.PageCount; while Assigned(ObjectEditorIntf) and (ObjectEditorIntf.PageCtrl.PageCount <> 0) and (I = MainForm.PageControl1.PageCount) do if not ComponentFactoryIntf.DestroyComponent(ObjectEditorIntf.CurrentComponent) then begin Result := False; Break; end; end; function TideBTMegaEditor.CloseAll: Boolean; begin while Assigned(ObjectEditorIntf) and (ObjectEditorIntf.PageCtrl.PageCount <> 0) do if not ComponentFactoryIntf.DestroyComponent(ObjectEditorIntf.CurrentComponent) then Break; Result := FEditorList.Count = 0; end; function TideBTMegaEditor.ShowEditor(AComponent: TSHComponent): Boolean; begin Result := ExistsEditor(AComponent); if Result then AddEditor(AComponent); end; function TideBTMegaEditor.ShowEditor(const AIndex: Integer): Boolean; var WindowLocked: Boolean; begin Result := Pred(FEditorList.Count) >= AIndex; if Result and Supports(FEditorList[AIndex], IideSHObjectEditor, ObjectEditorIntf) then begin ShowPage(AIndex); WindowLocked := LockWindowUpdate(GetDesktopWindow); try ObjectEditorIntf.PageCtrl.BringToFront; finally if WindowLocked then LockWindowUpdate(0); end; ObjectEditorIntf.ChangeEditor; end; end; function TideBTMegaEditor.DestroyEditor(const AIndex: Integer): Boolean; begin Result := Pred(FEditorList.Count) >= AIndex; if Result then begin DestroyPage(AIndex); ObjectEditorIntf := nil; FEditorList.Delete(AIndex); end; end; end.
{ SuperMaximo GameLibrary : Shader class unit by Max Foster License : http://creativecommons.org/licenses/by/3.0/ } unit ShaderClass; {$mode objfpc}{$H+} interface uses dglOpenGL; const //Shader attribute constants VERTEX_ATTRIBUTE = 0; NORMAL_ATTRIBUTE = 1; COLOR0_ATTRIBUTE = 2; COLOR1_ATTRIBUTE = 3; COLOR2_ATTRIBUTE = 4; TEXTURE0_ATTRIBUTE = 5; EXTRA0_ATTRIBUTE = 6; EXTRA1_ATTRIBUTE = 7; EXTRA2_ATTRIBUTE = 8; EXTRA3_ATTRIBUTE = 9; EXTRA4_ATTRIBUTE = 10; //Shader uniform location constants MODELVIEW_LOCATION = 0; PROJECTION_LOCATION = 1; TEXSAMPLER_LOCATION = 2; EXTRA0_LOCATION = 3; EXTRA1_LOCATION = 4; EXTRA2_LOCATION = 5; EXTRA3_LOCATION = 6; EXTRA4_LOCATION = 7; EXTRA5_LOCATION = 8; EXTRA6_LOCATION = 9; EXTRA7_LOCATION = 10; EXTRA8_LOCATION = 11; EXTRA9_LOCATION = 12; TEXCOMPAT_LOCATION = 13; type matrix4d = array[0..15] of GLfloat; matrix3d = array[0..8] of GLfloat; PShader = ^TShader; TShader = object strict private program_ : GLhandle; uniformLocation_ : array[0..TEXCOMPAT_LOCATION] of GLint; name_ : string; public //Load a shader from the files provided, with arrays of attributes used in the shader constructor create(newName, vertexShaderFile, fragmentShaderFile : string; enums : array of integer; attributeNames : array of string); destructor destroy; function name : string; procedure bind; //Bind the shader to be used when an object is drawn procedure use; //Binds the shader right now so that we can send down uniform data to it function getProgram : GLhandle; //Get the OpenGL handle for the program to be used in OpenGL functions function setUniformLocation(dstLocation : integer; locationName : string) : GLint; //Tells the shader about uniform variables in the shader function uniformLocation(location : integer) : GLint; //Returns the OpenGL location of the uniform variable in the shader //Use these procedures to pass data to the shaders. Use the shader uniform location constants for the 'location' parameter procedure setUniform16(location : integer; data : matrix4d); //Sends down a 4x4 matrix uniform to the shader procedure setUniform9(location : integer; data : matrix3d); //Sends down a 3x3 matrix uniform to the shader procedure setUniform1(location, data : integer); //Sends down a single integer to the shader procedure setUniform1(location : integer; data : GLfloat); //Sends down a single GLfloat (which is equivalent to a Single) to the shader procedure setUniform4(location : integer; data1, data2, data3, data4 : GLfloat); //Sends down a GLSL vec4 to the shader with four GLfloats end; function shader(searchName : string) : PShader; function addShader(newName, vertexShaderFile, fragmentShaderFile : string; enums : array of integer; attributeNames : array of string) : PShader; procedure destroyShader(searchName : string); procedure destroyAllShaders; implementation uses SysUtils, Classes, Display; var allShaders : array['a'..'z'] of TList; constructor TShader.create(newName, vertexShaderFile, fragmentShaderFile : string; enums : array of integer; attributeNames : array of string); var i, success, null : integer; shaderText, tempStr : string; shaderFile : text; vertexShader, fragmentShader : GLhandle; log : array[0..1023] of char; arr : array[0..0] of PGLChar; begin name_ := newName; program_ := GLuint(nil); for i := 0 to EXTRA9_LOCATION do uniformLocation_[i] := -1; //Load up the vertex shader file shaderText := ''; vertexShaderFile := setDirSeparators(vertexShaderFile); fragmentShaderFile := setDirSeparators(fragmentShaderFile); assign(shaderFile, vertexShaderFile); reset(shaderFile); repeat readln(shaderFile, tempStr); shaderText += tempStr+#13#10; until Eof(shaderFile); shaderText += #0; close(shaderFile); //Create the vertex shader vertexShader := glCreateShader(GL_VERTEX_SHADER); arr[0] := PGLChar(pchar(shaderText)); //Very awkward but its the only way I got it to work glShaderSource(vertexShader, 1, PPGLchar(arr), nil); glCompileShader(vertexShader); //Check if our vertex shader compiled, otherwise throw an error and exit glGetShaderiv(vertexShader, GL_COMPILE_STATUS, @success); if (success = GL_FALSE) then begin writeln('Error with compiling vertex shader ('+vertexShaderFile+')'); glGetShaderInfoLog(vertexShader, 1024, null, @log); writeln(log); glDeleteShader(vertexShader); exit; end; //Load the fragment shader file, tell OpenGL about it and error check it, as before shaderText := ''; assign(shaderFile, fragmentShaderFile); reset(shaderFile); repeat readln(shaderFile, tempStr); shaderText += tempStr+#13#10; until Eof(shaderFile); shaderText += #0; close(shaderFile); fragmentShader := glCreateShader(GL_FRAGMENT_SHADER); arr[0] := PGLChar(pchar(shaderText)); glShaderSource(fragmentShader, 1, PPGLchar(arr), nil); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, @success); if (success = GL_FALSE) then begin writeln('Error with compiling fragment shader ('+fragmentShaderFile+')'); glGetShaderInfoLog(fragmentShader, 1024, null, @log); writeln(log); glDeleteShader(fragmentShader); glDeleteShader(vertexShader); exit; end; //Create a GLSL program and attach the shaders to be processed program_ := glCreateProgram(); glAttachShader(program_, vertexShader); glAttachShader(program_, fragmentShader); //Tell the program about the attributes that have been passed in for i := 0 to length(enums)-1 do glBindAttribLocation(program_, enums[i], pchar(attributeNames[i])); //Link the program and delete the shaders that are no longer needed glLinkProgram(program_); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); //Error check glGetProgramiv(program_, GL_LINK_STATUS, @success); if (success = GL_FALSE) then begin writeln('Error with linking shader program ('+vertexShaderFile+', '+fragmentShaderFile+')'); glGetProgramInfoLog(program_, 1024, null, @log); writeln(log); glDeleteProgram(program_); exit; end; end; destructor TShader.destroy; begin glDeleteProgram(program_); end; function TShader.name : string; begin result := name_; end; procedure TShader.bind; begin globalBindShader(@self); end; procedure TShader.use; begin glUseProgram(program_); end; function TShader.getProgram : GLhandle; begin result := program_; end; function TShader.setUniformLocation(dstLocation : integer; locationName : string) : GLint; begin uniformLocation_[dstLocation] := glGetUniformLocation(program_, pchar(locationName)); result := uniformLocation_[dstLocation]; end; function TShader.uniformLocation(location : integer) : GLint; begin result := uniformLocation_[location]; end; procedure TShader.setUniform16(location : integer; data : matrix4d); begin glUniformMatrix4fv(uniformLocation_[location], 1, false, @data); end; procedure TShader.setUniform9(location : integer; data : matrix3d); begin glUniformMatrix3fv(uniformLocation_[location], 1, false, @data); end; procedure TShader.setUniform1(location, data : integer); begin glUniform1i(uniformLocation_[location], data); end; procedure TShader.setUniform1(location : integer; data : GLFloat); begin glUniform1f(uniformLocation_[location], data); end; procedure TShader.setUniform4(location : integer; data1, data2, data3, data4 : GLfloat); begin glUniform4f(uniformLocation_[location], data1, data2, data3, data4); end; function shader(searchName : string) : PShader; var letter : char; i : word; tempShader : PShader; begin letter := searchName[1]; result := nil; if (allShaders[letter].count > 0) then begin for i := 0 to allShaders[letter].count-1 do begin tempShader := PShader(allShaders[letter][i]); if (tempShader^.name = searchName) then result := tempShader; end; end; end; function addShader(newName, vertexShaderFile, fragmentShaderFile : string; enums : array of integer; attributeNames : array of string) : PShader; var letter : char; begin letter := newName[1]; allShaders[letter].add(new(PShader, create(newName, vertexShaderFile, fragmentShaderFile, enums, attributeNames))); result := allShaders[letter].last; end; procedure destroyShader(searchName : string); var letter : char; i : word; tempShader : PShader; begin letter := searchName[1]; if (allShaders[letter].count > 0) then begin for i := 0 to allShaders[letter].count-1 do begin tempShader := PShader(allShaders[letter][i]); if (tempShader^.name = searchName) then begin dispose(tempShader, destroy); allShaders[letter].delete(i); break; end; end; end; end; procedure destroyAllShaders; var i : char; j : integer; tempShader : PShader; begin for i := 'a' to 'z' do begin if (allShaders[i].count > 0) then begin for j := 0 to allShaders[i].count-1 do begin tempShader := PShader(allShaders[i][j]); dispose(tempShader, destroy); end; allShaders[i].clear; end; end; end; procedure initializeAllShaders; var i : char; begin for i := 'a' to 'z' do begin allShaders[i] := TList.create; end; end; procedure finalizeAllShaders; var i : char; begin for i := 'a' to 'z' do begin allShaders[i].destroy; end; end; initialization initializeAllShaders; finalization finalizeAllShaders; end.
unit SDUEndianIntegers; interface uses Windows; // Required for DWORD; type // 32 bit big endian numbers TSDUBigEndian32 = array [0..(4-1)] of byte; // 32 bit big endian numbers TSDULittleEndian32 = array [0..(4-1)] of byte; function SDUBigEndian32ToDWORD(number: TSDUBigEndian32): DWORD; function SDUBigEndian32ToString(number: TSDUBigEndian32): Ansistring; { TODO 1 -otdk -cclean : use byte areays } function SDUDWORDToBigEndian32(number: DWORD): TSDUBigEndian32; implementation // Convert from big-endian to DWORD function SDUBigEndian32ToDWORD(number: TSDUBigEndian32): DWORD; begin Result := (number[0] * $01000000) + (number[1] * $00010000) + (number[2] * $00000100) + (number[3] * $00000001); end; function SDUBigEndian32ToString(number: TSDUBigEndian32): Ansistring; begin Result := Ansichar(number[0] * $01000000) + Ansichar(number[1] * $00010000) + Ansichar(number[2] * $00000100) + Ansichar(number[3] * $00000001); end; function SDUDWORDToBigEndian32(number: DWORD): TSDUBigEndian32; begin Result[0] := (number and $FF000000) shr 24; Result[1] := (number and $00FF0000) shr 16; Result[2] := (number and $0000FF00) shr 8; Result[3] := (number and $000000FF); end; END.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Grids, UR_K_method; type TForm1 = class(TForm) Label1: TLabel; Panel1: TPanel; Label2: TLabel; Label3: TLabel; Panel2: TPanel; Label4: TLabel; StringGrid1: TStringGrid; Panel3: TPanel; Label5: TLabel; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Panel4: TPanel; Label10: TLabel; StringGrid2: TStringGrid; Button1: TButton; procedure get_data(var kin_par, comp_conc:TArrOfDouble; var tk, h: double); procedure show_result(comp_conc_profile: TArrOfArrOfDouble; tk, h: double); function kinetic_model(c, kin_par: TArrOfDouble; react_count: integer): TArrOfDouble; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; const react_count = 2; comp_count = 4; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.get_data(var kin_par, comp_conc:TArrOfDouble; var tk, h: double); var i: Integer; begin SetLength(kin_par, react_count); SetLength(comp_conc, comp_count); kin_par[0]:= StrToFloat(Edit1.Text); kin_par[1]:= StrToFloat(Edit2.Text); for i := 0 to comp_count - 1 do comp_conc[i]:= StrToFloat(StringGrid1.Cells[i+1, 1]); tk:= StrToFloat(Edit3.Text); h:= StrToFloat(Edit4.Text); end; procedure TForm1.show_result(comp_conc_profile: TArrOfArrOfDouble; tk, h: double); var i, j: integer; begin with StringGrid2 do for i := 0 to Trunc(tk / h)-1 do begin RowCount := RowCount + 1; cells[0, i+1] := FloatToStrF((i * h + h), fffixed, 4, 1); for j := 0 to comp_count-1 do cells [j+1, i+1] := FloatToStrF(comp_conc_profile[i, j], fffixed, 8, 4); end; end; function TForm1.kinetic_model(c, kin_par: TArrOfDouble; react_count: integer): TArrOfDouble; begin SetLength(result, comp_count); result[0] := - kin_par[0] * c[0]; result[1] := kin_par[0] * c[0] - kin_par[1] * c[1]; result[2] := kin_par[1] * c[1]; result[3] := kin_par[0] * c[0] + kin_par[1] * c[1]; end; procedure TForm1.Button1Click(Sender: TObject); var kin_par, comp_conc:TArrOfDouble; tk, h: double; comp_conc_profile: TArrOfArrOfDouble; begin StringGrid2.RowCount := 1; get_data(kin_par, comp_conc, tk, h); comp_conc_profile := RK(kinetic_model, comp_count, react_count, h, tk, comp_conc, kin_par); show_result(comp_conc_profile, tk, h) end; procedure TForm1.FormCreate(Sender: TObject); begin with StringGrid1 do begin StringGrid1.ColWidths[0]:= 260; Cells[0, 1]:= '»сходные концентрации, моль / л'; Cells[0, 2]:= 'Ёкспериментальные концентрации, моль / л'; Cells[1, 0]:= 'C9H20'; Cells[2, 0]:= 'C9H18'; Cells[3, 0]:= 'C9H16'; Cells[4, 0]:= 'H2'; Cells[1, 1]:= '1,0'; Cells[2, 1]:= '0,0'; Cells[3, 1]:= '0,0'; Cells[4, 1]:= '0,0'; Cells[1, 2]:= '0,1653'; Cells[2, 2]:= '0,4481'; Cells[3, 2]:= '0,3866'; Cells[4, 2]:= '1,2213'; end; with StringGrid2 do begin Cells[0, 0]:= '¬рем€, ч'; Cells[1, 0]:= 'C9H20'; Cells[2, 0]:= 'C9H18'; Cells[3, 0]:= 'C9H16'; Cells[4, 0]:= 'H2'; end; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Sensors, System.Sensors.Components, Vcl.ExtCtrls; type TForm5 = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; lsLocation: TLocationSensor; msAccelerometr: TMotionSensor; osCompass: TOrientationSensor; osInclinometer: TOrientationSensor; tOrientation: TTimer; lCompass: TLabel; lInclinometr: TLabel; Button1: TButton; GroupBox4: TGroupBox; Panel1: TPanel; bSwitch: TButton; lCoordinates: TLabel; lAddress: TLabel; lGeoCoordinates: TLabel; tMotion: TTimer; lAccel: TLabel; procedure osCompassSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); procedure osInclinometerSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); procedure tOrientationTimer(Sender: TObject); procedure bSwitchClick(Sender: TObject); procedure lsLocationLocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure msAccelerometrSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); procedure tMotionTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FGeocoder : TGeocoder; procedure OnGeocodeReverseEvent(const Address: TCivicAddress); procedure OnGeocodeEvent(const Coords: TArray<TLocationCoord2D>); public { Public declarations } end; var Form5: TForm5; implementation {$R *.dfm} procedure TForm5.bSwitchClick(Sender: TObject); begin if bSwitch.Caption = 'Turn On' then begin bSwitch.Caption := 'Turn off'; lsLocation.Active := True; msAccelerometr.Active := True; osCompass.Active := True; osInclinometer.Active := True; end else begin bSwitch.Caption := 'Turn On'; lsLocation.Active := False; msAccelerometr.Active := False; osCompass.Active := False; osInclinometer.Active := False; end; end; procedure TForm5.FormCreate(Sender: TObject); begin FGeocoder := TGeocoder.Current.Create; FGeocoder.OnGeocodeReverse := OnGeocodeReverseEvent; FGeocoder.OnGeocode := OnGeocodeEvent; end; procedure TForm5.lsLocationLocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); begin lCoordinates.Caption := Format('Latitude : %2.7f; Longitude : %2.7f', [NewLocation.Latitude, NewLocation.Longitude]); if FGeocoder <> nil then begin lAddress.Caption := 'Start geocoding'; if FGeocoder.Supported then FGeocoder.GeocodeReverse(NewLocation) else lAddress.Caption := 'Geocoding not supporting'; end else lAddress.Caption := 'Geocoder not found'; end; procedure TForm5.msAccelerometrSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); var I : integer; begin for I := 0 to Length(Sensors) - 1 do if (Sensors[I] as TCustomMotionSensor).SensorType = TMotionSensorType.Accelerometer3D then begin ChoseSensorIndex := I; Break; end; end; procedure TForm5.OnGeocodeEvent(const Coords: TArray<TLocationCoord2D>); begin if Length(Coords) > 0 then lGeoCoordinates.Caption := Format('After geocoding address. Lat : %2.7f, Long : %2.7f',[Coords[0].Latitude, Coords[0].Longitude]); end; procedure TForm5.OnGeocodeReverseEvent(const Address: TCivicAddress); begin if Address <> nil then begin lAddress.Caption := 'After geocoding coords:' + Address.ToString; if FGeocoder <> nil then FGeocoder.Geocode(Address); end else lAddress.Caption := 'not found'; end; procedure TForm5.osCompassSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); var I : integer; begin for I := 0 to Length(Sensors) - 1 do if (Sensors[I] as TCustomOrientationSensor).SensorType = TOrientationSensorType.Compass3D then begin ChoseSensorIndex := I; Break; end; end; procedure TForm5.osInclinometerSensorChoosing(Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer); var I : integer; begin for I := 0 to Length(Sensors) - 1 do if (Sensors[I] as TCustomOrientationSensor).SensorType = TOrientationSensorType.Inclinometer3D then begin ChoseSensorIndex := I; Break; end; end; procedure TForm5.tMotionTimer(Sender: TObject); begin if msAccelerometr.Sensor <> nil then lAccel.Caption := Format('AccelX : %-1.5f'#13#10'AccelY : %-1.5f'#13#10'AccelZ : %-1.5f', [msAccelerometr.Sensor.AccelerationX, msAccelerometr.Sensor.AccelerationY, msAccelerometr.Sensor.AccelerationZ] ) else lAccel.Caption := ''; end; procedure TForm5.tOrientationTimer(Sender: TObject); begin if osCompass.Sensor <> nil then lCompass.Caption := Format('Heading : %3.1f',[osCompass.Sensor.CompMagHeading]) else lCompass.Caption := ''; if osInclinometer.Sensor <> nil then lInclinometr.Caption := Format('TiltX : %-3.5f '#13#10'TiltY : %-3.5f '#13#10'TiltZ : %-3.5f ', [osInclinometer.Sensor.TiltX, osInclinometer.Sensor.TiltY, osInclinometer.Sensor.TiltZ]) else lInclinometr.Caption := ''; end; end.
unit uDMImportPet; interface uses SysUtils, Classes, variants, ADODB, uPetClasses, uContentClasses, uObjectServices; type TDMImportPet = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FSQLConnection: TADOConnection; FLog: TStringList; function ImportPet(AAnimal : TAnimal) : Boolean; function GetPropertyDomain(AProperty: String): Variant; public function ImportPetInfo(APetImportInfo: TPetImportInfo): Boolean; property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection; property Log: TStringList read FLog write FLog; end; implementation {$R *.dfm} procedure TDMImportPet.DataModuleCreate(Sender: TObject); begin FLog := TStringList.Create; end; procedure TDMImportPet.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FLog); end; function TDMImportPet.GetPropertyDomain(AProperty: String): Variant; var FQuery : TADOQuery; begin try FQuery := TADOQuery.Create(Self); FQuery.Connection := FSQLConnection; FQuery.SQL.Add('SELECT PropertyValue'); FQuery.SQL.Add('FROM Sis_PropertyDomain'); FQuery.SQL.Add('WHERE Property = :Property'); FQuery.Parameters.ParamByName('Property').Value := AProperty; FQuery.Open; Result := FQuery.FieldByName('PropertyValue').Value; finally FQuery.Close; FreeAndNil(FQuery); end; end; function TDMImportPet.ImportPet(AAnimal: TAnimal): Boolean; var FMRAnimalService : TMRAnimalService; begin FMRAnimalService := TMRAnimalService.Create; try FMRAnimalService.SQLConnection := FSQLConnection; FMRAnimalService.InsertOrUpdate(AAnimal); finally FreeAndNil(FMRAnimalService); end; end; function TDMImportPet.ImportPetInfo(APetImportInfo: TPetImportInfo): Boolean; var FAnimal : TAnimal; FSpecies : TSpecies; FBreed : TBreed; FAnimalColor : TAnimalColor; FEntity : TEntity; FMicrochip : TMicrochip; FAnimalWeight : TAnimalWeight; FAnimalRegistry : TAnimalRegistry; begin FAnimal := nil; FSpecies := nil; FBreed := nil; FEntity := nil; FAnimalColor := nil; FMicrochip := nil; FAnimalWeight := nil; FAnimalRegistry := nil; try if (APetImportInfo.Species <> '') or (APetImportInfo.IDSpecies <> Null) then begin FSpecies := TSpecies.Create; FSpecies.Species := APetImportInfo.Species; FSpecies.IDSpecies := APetImportInfo.IDSpecies; end; if (APetImportInfo.Breed <> '') or (APetImportInfo.IDBreed <> Null) then begin FBreed := TBreed.Create; FBreed.Breed := APetImportInfo.Breed; FBreed.IDBreed := APetImportInfo.IDBreed; end; if (APetImportInfo.Breeder <> '') or (APetImportInfo.IDBreeder <> Null) then begin FEntity := TEntity.Create; FEntity.IDPessoa := APetImportInfo.IDBreeder; FEntity.Pessoa := APetImportInfo.Breeder; FEntity.Endereco := APetImportInfo.BreederAddress; FEntity.Cidade := APetImportInfo.BreederCity; FEntity.CEP := APetImportInfo.BreederZip; FEntity.Juridico := True; FEntity.IDTipoPessoa := StrToIntDef(GetPropertyDomain('PctBreederDefaultEntityType'), 2); FEntity.IDTipoPessoaRoot := StrToIntDef(GetPropertyDomain('PctBreederDefaultEntityType'), 2); if APetImportInfo.BreederState <> '' then begin FEntity.State := TState.Create; FEntity.State.StateName := APetImportInfo.BreederState; end; end; if (APetImportInfo.Color <> '') or (APetImportInfo.IDColor <> Null) then begin FAnimalColor := TAnimalColor.Create; FAnimalColor.Color := APetImportInfo.Color; FAnimalColor.IDColor := APetImportInfo.IDColor; end; if (APetImportInfo.Microchip <> '') then begin FMicrochip := TMicrochip.Create; FMicrochip.MicrochipNum := APetImportInfo.Microchip; FMicrochip.Brand := APetImportInfo.MicrochipBrand; end; if (APetImportInfo.Weight <> 0) and (APetImportInfo.WeightDate <> 0) then begin FAnimalWeight := TAnimalWeight.Create; FAnimalWeight.Weight := APetImportInfo.Weight; FAnimalWeight.EntryDate := APetImportInfo.WeightDate; end; if (APetImportInfo.Registry <> '') then begin FAnimalRegistry := TAnimalRegistry.Create; FAnimalRegistry.Registry := APetImportInfo.Registry; if APetImportInfo.RegistryNumber <> '' then FAnimalRegistry.RegistrationNum := APetImportInfo.RegistryNumber; end; FAnimal := TAnimal.Create; with FAnimal do begin IDStore := StrToIntDef(GetPropertyDomain('PctDefaultStore'), 1); IDStatus := PET_STATUS_AVAILABLE; SKU := APetImportInfo.SKU; Sex := APetImportInfo.Sex; PenNum := APetImportInfo.PenNumber; USDA := APetImportInfo.USDA; Collar := APetImportInfo.Collar; Sire := APetImportInfo.Sire; Dam := APetImportInfo.Dam; Notes := APetImportInfo.Notes; VendorCost := APetImportInfo.VendorCost; MSRP := APetImportInfo.MSRP; SalePrice := APetImportInfo.SalePrice; PromoPrice := APetImportInfo.PromoPrice; WhelpDate := APetImportInfo.Whelpdate; PurchaseDate := APetImportInfo.PurchaseDate; Desativado := False; Species := FSpecies; Breed := FBreed; Breeder := FEntity; AnimalColor := FAnimalColor; Microchip := FMicrochip; AnimalWeight := FAnimalWeight; AnimalRegistry := FAnimalRegistry; TreatmentList := APetImportInfo.TreatmentList; end; ImportPet(FAnimal); finally if Assigned(FAnimalColor) then FreeAndNil(FAnimalColor); if Assigned(FEntity) then FreeAndNil(FEntity); if Assigned(FBreed) then FreeAndNil(FBreed); if Assigned(FSpecies) then FreeAndNil(FSpecies); if Assigned(FAnimalWeight) then FreeAndNil(FAnimalWeight); if Assigned(FMicrochip) then FreeAndNil(FMicrochip); if Assigned(FAnimalRegistry) then FreeAndNil(FAnimalRegistry); FreeAndNil(FAnimal); end; end; end.
{ *********************************************************************** } { } { GUI Hangman } { Version 1.0 - First release of program } { Last Revised: 27nd of July 2004 } { Copyright (c) 2004 Chris Alley } { } { *********************************************************************** } unit UGameLogic; interface uses UConstantsAndTypes; type TGameLogic = class(TObject) private MysteryWord: string; WordListFile: textfile; GuessesLeft: integer; AvailableLetters: TLetterSet; UsedLetters: TLetterSet; GuessedLetter: char; CheatMode: boolean; function GetAmountOfWordsInTextFile: integer; procedure SetGuessesLeftToDefault; procedure SetAvailableLettersToDefault; procedure SetUsedLettersToDefault; procedure AddVowelsToUsedLetters; procedure DecrementGuessesLeftByOne; procedure UpdateLetterSets; public procedure SetCheatModeToTrue; procedure GetRandomMysteryWord(DifficultyLevel: string); procedure PrepareGame; function UpdateCurrentStateOfMysteryWord: string; function CheckIfGuessedLetterIsWrong(ALetter: char): boolean; function GetGuessesLeft: integer; function CheckIfPlayerHasLost: boolean; function CheckIfPlayerHasWon: boolean; function GetMysteryWord: string; end; implementation procedure TGameLogic.AddVowelsToUsedLetters; { Carries out a cheat that gives the player all the vowels at the start of a new game. } begin if Self.CheatMode = True then Self.UsedLetters := Self.UsedLetters + ['A', 'E', 'I', 'O', 'U', 'Y']; end; function TGameLogic.GetAmountOfWordsInTextFile: integer; begin Result := 0; reset(Self.WordListFile); while not eof(Self.WordListFile) do begin readln(Self.WordListFile); Result := Result + 1; end; closefile(Self.WordListFile); end; procedure TGameLogic.GetRandomMysteryWord(DifficultyLevel: string); { Gets a random mystery word from a text file, depending on the difficulty level. } var Count, RandomNumber: integer; begin Count := 0; if DifficultyLevel = Easy then assignfile(WordListFile, EasyWordListFilePath); if DifficultyLevel = Normal then assignfile(WordListFile, NormalWordListFilePath); if DifficultyLevel = Hard then assignfile(WordListFile, HardWordListFilePath); Randomize; RandomNumber := Random(Self.GetAmountOfWordsInTextFile); reset(Self.WordListFile); while not eof(Self.WordListFile) do begin Count := Count + 1; readln(Self.WordListFile, Self.MysteryWord); if Count = RandomNumber then break; end; closefile(Self.WordListFile); end; procedure TGameLogic.PrepareGame; { Sets various game settings to default, before a new game is started. } begin Self.SetGuessesLeftToDefault; Self.SetAvailableLettersToDefault; Self.SetUsedLettersToDefault; Self.AddVowelsToUsedLetters; Self.UpdateLetterSets; Self.CheckIfPlayerHasLost; end; procedure TGameLogic.SetAvailableLettersToDefault; begin Self.AvailableLetters := ['A' .. 'Z']; end; procedure TGameLogic.SetGuessesLeftToDefault; begin Self.GuessesLeft := 10; end; procedure TGameLogic.SetUsedLettersToDefault; begin Self.UsedLetters := []; end; function TGameLogic.UpdateCurrentStateOfMysteryWord: string; { Returns the current state of the mystery word, only showing the letters in it that have been guessed. } var Count: integer; begin Result := ''; for Count := 1 to length(Self.MysteryWord) do begin if Self.MysteryWord[Count] in Self.UsedLetters then Result := Result + Self.MysteryWord[Count] else Result := Result + MysteryLetter; end; end; procedure TGameLogic.UpdateLetterSets; { Adds the guessed letter to the used letters set, and subtracts it from the avaliable letters set. } begin Self.AvailableLetters := Self.AvailableLetters - [Self.GuessedLetter]; Self.UsedLetters := Self.UsedLetters + [Self.GuessedLetter]; end; procedure TGameLogic.DecrementGuessesLeftByOne; begin Self.GuessesLeft := Self.GuessesLeft - 1; end; function TGameLogic.CheckIfGuessedLetterIsWrong(ALetter: char): boolean; { Returns true only if GuessedLetter is in AvailableLetters and is also in the mystery word. } var Count: integer; begin Result := True; Self.GuessedLetter := ALetter; if (Self.GuessedLetter in Self.AvailableLetters) then begin for Count := 1 to length(Self.MysteryWord) do begin if Self.GuessedLetter = Self.MysteryWord[Count] then Result := False; end; if Result = True then begin Self.DecrementGuessesLeftByOne; Result := True; end; end else Result := False; Self.UpdateLetterSets; end; function TGameLogic.GetGuessesLeft: integer; begin Result := Self.GuessesLeft; end; function TGameLogic.CheckIfPlayerHasLost: boolean; begin Result := False; if Self.GuessesLeft = 0 then Result := True; end; function TGameLogic.CheckIfPlayerHasWon: boolean; begin Result := False; if Self.UpdateCurrentStateOfMysteryWord = Self.MysteryWord then Result := True; end; function TGameLogic.GetMysteryWord: string; begin Result := Self.MysteryWord; end; procedure TGameLogic.SetCheatModeToTrue; { Turns cheat mode on. } begin Self.CheatMode := True; end; end.
unit uDBManager; interface {$WARN SYMBOL_PLATFORM OFF} uses Generics.Defaults, Generics.Collections, Winapi.Windows, Winapi.CommCtrl, System.Classes, System.SyncObjs, System.SysUtils, Data.DB, Vcl.Forms, Vcl.Controls, Vcl.ImgList, Vcl.Imaging.Jpeg, UnitDBDeclare, UnitINI, Dmitry.CRC32, Dmitry.Utils.Files, Dmitry.Utils.System, uMemory, uShellIntegration, uLogger, uConstants, uTime, uCollectionEvents, uShellUtils, uAppUtils, uTranslate, uDBForm, uDBConnection, uDBScheme, uDBContext, uDBEntities, uRuntime, uStringUtils, uSettings, uCollectionUtils, uProgramStatInfo, uVCLHelpers; type TDBManager = class(TObject) private { Private declarations } FDBContext: IDBContext; class procedure HandleError(E: Exception); public { Public declarations } constructor Create; destructor Destroy; override; class function CreateDBbyName(FileName: string): Boolean; function SetDataBase(DatabaseFileName: string): IDBContext; function LoadDefaultCollection: Boolean; function CreateSampleDefaultCollection: IDBContext; function SelectDB(Caller: TDBForm; CollectionFileName: string): Boolean; class function CreateExampleDB(FileName: string): Boolean; class procedure ReadUserCollections(Collections: TList<TDatabaseInfo>); class procedure SaveUserCollections(Collections: TList<TDatabaseInfo>); class procedure UpdateUserCollection(Collection: TDatabaseInfo; SortOrder: Integer = -1); class function UpdateDatabaseQuery(FileName: string): Boolean; property DBContext: IDBContext read FDBContext; end; function DBManager: TDBManager; implementation var FDBManager: TDBManager = nil; function DBManager: TDBManager; begin if FDBManager = nil then FDBManager := TDBManager.Create; Result := FDBManager; end; class function TDBManager.UpdateDatabaseQuery(FileName: string): Boolean; var Msg: string; begin Msg := FormatEx(TA('Collection "{0}" should be updated to work with this program version. After updating this collection may not work with previous program versions. Update now?', 'Explorer'), [FileName]); Result := ID_YES = MessageBoxDB(Screen.ActiveFormHandle, Msg, TA('Warning'), '', TD_BUTTON_YESNO, TD_ICON_WARNING); end; class procedure TDBManager.ReadUserCollections(Collections: TList<TDatabaseInfo>); var Reg: TBDRegistry; List: TStrings; I: Integer; Icon, FileName, Description: string; begin List := TStringList.Create; try Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try Reg.OpenKey(RegRoot + 'dbs', True); Reg.GetKeyNames(List); for I := 0 to List.Count - 1 do begin Reg.CloseKey; Reg.OpenKey(RegRoot + 'dbs\' + List[I], True); if Reg.ValueExists('Icon') and Reg.ValueExists('FileName') then begin Icon := Reg.ReadString('Icon'); FileName := Reg.ReadString('FileName'); Description := Reg.ReadString('Description'); Collections.Add(TDatabaseInfo.Create(List[I], FileName, Icon, Description, Reg.ReadInteger('Order'))); end; end; finally F(Reg); end; finally F(List); end; Collections.Sort(TComparer<TDatabaseInfo>.Construct( function (const L, R: TDatabaseInfo): Integer begin Result := L.Order - R.Order; end )); end; class procedure TDBManager.UpdateUserCollection(Collection: TDatabaseInfo; SortOrder: Integer = -1); var Reg: TBDRegistry; Settings: TSettings; Context: IDBContext; SettingsRepository: ISettingsRepository; EventValue: TEventValues; begin Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try if SortOrder = -1 then Reg.DeleteKey(RegRoot + 'dbs\' + Collection.OldTitle); Reg.OpenKey(RegRoot + 'dbs\' + Collection.Title, True); Reg.WriteString('FileName', Collection.Path); Reg.WriteString('Icon', Collection.Icon); Reg.WriteString('Description', Collection.Description); if SortOrder > -1 then Reg.WriteInteger('Order', SortOrder) else Reg.WriteInteger('Order', Collection.Order); if FileExistsSafe(Collection.Path) then begin if TDBScheme.IsOldColectionFile(Collection.Path) then begin if UpdateDatabaseQuery(Collection.Path) then TDBScheme.UpdateCollection(Collection.Path, 0, True); end; if TDBScheme.IsValidCollectionFile(Collection.Path) then begin Context := TDBContext.Create(Collection.Path); SettingsRepository := Context.Settings; Settings := SettingsRepository.Get; try Settings.Name := Collection.Title; Settings.Description := Collection.Description; SettingsRepository.Update(Settings); finally F(Settings); end; end; if SortOrder = -1 then begin EventValue.NewName := Collection.Title; CollectionEvents.DoIDEvent(nil, 0, [EventID_CollectionInfoChanged], EventValue); end; end; finally F(Reg); end; end; class procedure TDBManager.SaveUserCollections(Collections: TList<TDatabaseInfo>); var Reg: TBDRegistry; List: TStrings; I: Integer; DB: TDatabaseInfo; EventValue: TEventValues; begin List := TStringList.Create; try Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try Reg.OpenKey(RegRoot + 'dbs', True); Reg.GetKeyNames(List); for I := 0 to List.Count - 1 do Reg.DeleteKey(List[I]); for DB in Collections do UpdateUserCollection(DB, Collections.IndexOf(DB)); EventValue.NewName := ''; CollectionEvents.DoIDEvent(nil, 0, [EventID_CollectionInfoChanged], EventValue); finally F(Reg); end; finally F(List); end; end; { TDBManager } constructor TDBManager.Create; begin inherited; FDBContext := nil; end; class function TDBManager.CreateDBbyName(FileName: string): Boolean; begin Result := False; CreateDirA(ExtractFileDir(FileName)); try if FileExistsSafe(FileName) then begin if ID_YES <> MessageBoxDB(Screen.ActiveFormHandle, FormatEx(TA('Collection "{0}" already exists! Delete this collection file?', 'Explorer'), [FileName]), TA('Warning'), '', TD_BUTTON_YESNO, TD_ICON_WARNING) then Exit; DeleteFile(FileName); end; if FileExistsSafe(FileName) then Exit; TDBScheme.CreateCollection(FileName); Result := True; except on E: Exception do begin HandleError(E); EventLog(':TDBKernel::CreateDBbyName() throw exception: ' + E.message); Exit; end; end; ProgramStatistics.DBUsed; end; class function TDBManager.CreateExampleDB(FileName: string): Boolean; var NewGroup: TGroup; ImagesDir: string; DBContext: IDBContext; GroupsRepository: IGroupsRepository; begin Result := False; if not CreateDBbyName(FileName) then Exit; DBContext := TDBContext.Create(FileName); GroupsRepository := DBContext.Groups; ImagesDir := ExtractFilePath(Application.ExeName) + 'Images\'; if FileExists(ImagesDir + 'Me.jpg') then begin NewGroup := TGroup.Create; try NewGroup.GroupName := GetWindowsUserName; NewGroup.GroupCode := TGroup.CreateNewGroupCode; NewGroup.GroupImage := TJPEGImage.Create; NewGroup.GroupImage.LoadFromFile(ImagesDir + 'Me.jpg'); NewGroup.GroupDate := Now; NewGroup.GroupComment := ''; NewGroup.GroupFaces := ''; NewGroup.GroupAccess := 0; NewGroup.GroupKeyWords := NewGroup.GroupName; NewGroup.AutoAddKeyWords := True; NewGroup.RelatedGroups := ''; NewGroup.IncludeInQuickList := True; GroupsRepository.Add(NewGroup); finally F(NewGroup); end; end; if FileExists(ImagesDir + 'Friends.jpg') then begin NewGroup := TGroup.Create; try NewGroup.GroupName := TA('Friends', 'Setup'); NewGroup.GroupCode := TGroup.CreateNewGroupCode; NewGroup.GroupImage := TJPEGImage.Create; NewGroup.GroupImage.LoadFromFile(ImagesDir + 'Friends.jpg'); NewGroup.GroupDate := Now; NewGroup.GroupComment := ''; NewGroup.GroupFaces := ''; NewGroup.GroupAccess := 0; NewGroup.GroupKeyWords := TA('Friends', 'Setup'); NewGroup.AutoAddKeyWords := True; NewGroup.RelatedGroups := ''; NewGroup.IncludeInQuickList := True; GroupsRepository.Add(NewGroup); finally F(NewGroup); end; end; if FileExists(ImagesDir + 'Family.jpg') then begin NewGroup := TGroup.Create; try NewGroup.GroupName := TA('Family', 'Setup'); NewGroup.GroupCode := TGroup.CreateNewGroupCode; NewGroup.GroupImage := TJPEGImage.Create; NewGroup.GroupImage.LoadFromFile(ImagesDir + 'Family.jpg'); NewGroup.GroupDate := Now; NewGroup.GroupComment := ''; NewGroup.GroupFaces := ''; NewGroup.GroupAccess := 0; NewGroup.GroupKeyWords := TA('Family', 'Setup'); NewGroup.AutoAddKeyWords := True; NewGroup.RelatedGroups := ''; NewGroup.IncludeInQuickList := True; GroupsRepository.Add(NewGroup); finally F(NewGroup); end; end; Result := True; end; destructor TDBManager.Destroy; begin FDBContext := nil; inherited; end; function TDBManager.SelectDB(Caller: TDBForm; CollectionFileName: string): Boolean; var EventInfo: TEventValues; begin if not FileExists(CollectionFileName) then raise Exception.Create(FormatEx(TA('Can''t find collection file: {0}!', 'Errors'), [CollectionFileName])); if not TDBScheme.IsValidCollectionFile(CollectionFileName) then begin if TDBManager.UpdateDatabaseQuery(CollectionFileName) then TDBScheme.UpdateCollection(CollectionFileName, 0, True); end; if TDBScheme.IsValidCollectionFile(CollectionFileName) then begin SetDataBase(CollectionFileName); CollectionEvents.DoIDEvent(Caller, 0, [EventID_Param_DB_Changed], EventInfo); Result := True; Exit; end else raise Exception.Create(FormatEx(TA('Can''t select old version of collection file!', 'Errors'), [CollectionFileName])); end; function TDBManager.SetDataBase(DatabaseFileName: string): IDBContext; var Reg: TBDRegistry; begin if not FileExistsSafe(DatabaseFileName) then Exit; Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER); try Reg.OpenKey(RegRoot, True); Reg.WriteString('DBDefaultName', DatabaseFileName); FDBContext := TDBContext.Create(DatabaseFileName); Result := FDBContext; finally F(Reg); end; end; function TDBManager.LoadDefaultCollection: Boolean; var CollectionFileName: string; begin FDBContext := nil; if FolderView then begin CollectionFileName := ExtractFilePath(Application.ExeName) + 'FolderDB.photodb'; if FileExistsSafe(ExtractFilePath(Application.ExeName) + AnsiLowerCase(GetFileNameWithoutExt(Application.ExeName)) + '.photodb') then CollectionFileName := ExtractFilePath(Application.ExeName) + AnsiLowerCase(GetFileNameWithoutExt(Application.ExeName)) + '.photodb'; end else begin CollectionFileName := AppSettings.DataBase; if not FileExistsSafe(CollectionFileName) then FDBContext := CreateSampleDefaultCollection; end; if FDBContext = nil then FDBContext := TDBContext.Create(CollectionFileName); Result := FDBContext.IsValid; end; function TDBManager.CreateSampleDefaultCollection: IDBContext; var Collections: TList<TDatabaseInfo>; CollectionFile: string; SettingsRepository: ISettingsRepository; Settings: TSettings; function IsCollectionFile(FileName: string): Boolean; begin Result := TDBScheme.GetCollectionVersion(FileName) > 0; end; begin //if program was uninstalled with registered databases - restore database or create new database CollectionFile := IncludeTrailingBackslash(GetMyDocumentsPath) + TA('My collection', 'CollectionSettings') + '.photodb'; if not (FileExistsSafe(CollectionFile) and IsCollectionFile(CollectionFile)) then begin CollectionFile := IncludeTrailingBackslash(GetMyDocumentsPath) + FormatEx(TA('Photos - {0}', 'CollectionSettings'), [GetWindowsUserName]) + '.photodb'; if not (FileExistsSafe(CollectionFile) and IsCollectionFile(CollectionFile)) then CreateExampleDB(CollectionFile); end; Collections := TList<TDatabaseInfo>.Create; try ReadUserCollections(Collections); Collections.Add(TDatabaseInfo.Create(FormatEx(TA('Photos - {0}', 'CollectionSettings'), [GetWindowsUserName]), CollectionFile, Application.ExeName + ',0', '', Collections.Count)); SaveUserCollections(Collections); Result := SetDataBase(CollectionFile); if Result <> nil then begin SettingsRepository := Result.Settings; Settings := SettingsRepository.Get; try if Settings.Name = '' then begin Settings.Name := TA('Photos - {0}', 'CollectionSettings'); Settings.Description := TA('My collection', 'CollectionSettings'); SettingsRepository.Update(Settings); end; finally F(Settings); end; CheckDefaultSyncDirectoryForCollection(CollectionFile); end; finally FreeList(Collections); end; end; class procedure TDBManager.HandleError(E: Exception); begin TThread.Synchronize(nil, procedure begin MessageBoxDB(0, E.Message, TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR); NotifyOleException(E); end ); EventLog(E); end; initialization finalization F(FDBManager); end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.Logger.ExceptionHook Description : Log raised Exceptions Author : Kike Pérez Version : 1.20 Created : 12/10/2017 Modified : 28/03/2019 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Logger.ExceptionHook; {$i QuickLib.inc} interface implementation uses SysUtils, System.TypInfo, Quick.Logger; //var //RealRaiseExceptObject: Pointer; type EExceptionHack = class public FMessage: string; FHelpContext: Integer; FInnerException: Exception; FStackInfo: Pointer; FAcquireInnerException: Boolean; end; procedure RaiseExceptObject(pExRec: PExceptionRecord); type TRaiseExceptObjectProc = procedure(pExRec: PExceptionRecord); begin if TObject(pExRec^.ExceptObject) is Exception then EExceptionHack(pExRec^.ExceptObject).FAcquireInnerException := True; //throw event in Quick Logger to log it if Assigned(GlobalLoggerHandledException) then begin {$IFDEF DELPHILINUX} GlobalLoggerHandledException(Pointer(pExRec^.ExceptObject)); {$ELSE} GlobalLoggerHandledException(pExRec^.ExceptObject); {$ENDIF} end; //throw real exception //if Assigned(RealRaiseExceptObject) then TRaiseExceptObjectProc(RealRaiseExceptObject)(pExRec); end; initialization //RealRaiseExceptObject := RaiseExceptObjProc; RaiseExceptObjProc := @RaiseExceptObject; //raised exceptions end.
unit Sort.StringList; interface uses Classes; type TStringListSort = record private class var FCaseSensitive: Boolean; FAsc: Boolean; class function CompareStrings(List: TStringList; Index1, Index2: Integer): Integer; static; public class procedure Sort( AStringList: TStringList; ACaseSensitive, AAsc: Boolean ); static; end; implementation uses Sort.StringCompare; { TStringListSort } class procedure TStringListSort.Sort(AStringList: TStringList; ACaseSensitive, AAsc: Boolean); begin FCaseSensitive := ACaseSensitive; FAsc := AAsc; AStringList.CustomSort( CompareStrings ); end; class function TStringListSort.CompareStrings(List: TStringList; Index1, Index2: Integer): Integer; begin Result := NaturalOrderCompareString( List.Strings[Index1], List.Strings[Index2], FCaseSensitive ); if FAsc = False then Result := -Result; end; end.
unit HashAlgSHA512_U; // Description: SHA-512 Hash (Wrapper for the SHA-512 Hashing Engine) // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, HashAlg_U, HashValue_U, HashAlgSHA512Engine_U; type THashAlgSHA512 = class(THashAlg) private shaXXXEngine: THashAlgSHA512Engine; context: SHA512_CTX; protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Init(); override; procedure Update(const input: array of byte; const inputLen: cardinal); override; procedure Final(digest: THashValue); override; function PrettyPrintHashValue(const theHashValue: THashValue): string; override; published { Published declarations } end; procedure Register; implementation uses SysUtils; // needed for fmOpenRead procedure Register; begin RegisterComponents('Hash', [THashAlgSHA512]); end; constructor THashAlgSHA512.Create(AOwner: TComponent); begin inherited; shaXXXEngine:= THashAlgSHA512Engine.Create(); fTitle := 'SHA-512'; fHashLength := 512; fBlockLength := 1024; end; destructor THashAlgSHA512.Destroy(); begin // Nuke any existing context before freeing off the engine... shaXXXEngine.SHA512Init(context); shaXXXEngine.Free(); inherited; end; procedure THashAlgSHA512.Init(); begin shaXXXEngine.SHA512Init(context); end; procedure THashAlgSHA512.Update(const input: array of byte; const inputLen: cardinal); begin shaXXXEngine.SHA512Update(context, input, inputLen); end; procedure THashAlgSHA512.Final(digest: THashValue); begin shaXXXEngine.SHA512Final(digest, context); end; function THashAlgSHA512.PrettyPrintHashValue(const theHashValue: THashValue): string; var retVal: string; begin retVal := inherited PrettyPrintHashValue(theHashValue); insert(' ', retVal, 113); insert(' ', retVal, 97); insert(' ', retVal, 81); insert(' ', retVal, 65); insert(' ', retVal, 49); insert(' ', retVal, 33); insert(' ', retVal, 17); Result := retVal; end; END.
{$mode objfpc} {$include pyopts.inc} //for define PYTHON_DYNAMIC {$assertions on} {$ifdef win32} {$define cpux86} {$endif} {$ifdef fpc} {$ifdef cpu64} {$define cpux64} {$endif cpu64} {$ifdef cpu32} {$define cpux86} {$endif cpu32} {$ifdef darwin} {$define macos} {$define align_stack} {$ifdef cpu32} {$define macos32} {$endif cpu32} {$endif darwin} {$endif fpc} {$modeswitch cvar} unit Python3Core; interface uses {$IFDEF windows} Windows, {$ELSE} Types, {$ENDIF} CTypes, Classes, SysUtils, SyncObjs, Variants, TinyWideStrings ; //####################################################### //## ## //## PYTHON specific constants ## //## ## //####################################################### type {$IFNDEF UNICODE} UnicodeString = WideString; TUnicodeStringList = TWideStringList; {$ELSE} TUnicodeStringList = TStringList; {$ENDIF} {$IFNDEF FPC} {$IF CompilerVersion < 21} NativeInt = integer; NativeUInt = Cardinal; {$IFEND} PNativeInt = ^NativeInt; {$ELSE} {$IF DEFINED(FPC_FULLVERSION) and (FPC_FULLVERSION >= 20500)} {$ELSE} NativeInt = integer; NativeUInt = Cardinal; {$IFEND} PNativeInt = ^NativeInt; {$ENDIF} const PYT_METHOD_BUFFER_INCREASE = 10; PYT_MEMBER_BUFFER_INCREASE = 10; PYT_GETSET_BUFFER_INCREASE = 10; METH_VARARGS = $0001; METH_KEYWORDS = $0002; // Masks for the co_flags field of PyCodeObject CO_OPTIMIZED = $0001; CO_NEWLOCALS = $0002; CO_VARARGS = $0004; CO_VARKEYWORDS = $0008; // Rich comparison opcodes introduced in version 2.1 Py_LT = 0; Py_LE = 1; Py_EQ = 2; Py_NE = 3; Py_GT = 4; Py_GE = 5; type // Delphi equivalent used by TPyObject TRichComparisonOpcode = (pyLT, pyLE, pyEQ, pyNE, pyGT, pyGE); const {Type flags (tp_flags) introduced in version 2.0 These flags are used to extend the type structure in a backwards-compatible fashion. Extensions can use the flags to indicate (and test) when a given type structure contains a new feature. The Python core will use these when introducing new functionality between major revisions (to avoid mid-version changes in the PYTHON_API_VERSION). Arbitration of the flag bit positions will need to be coordinated among all extension writers who publically release their extensions (this will be fewer than you might expect!).. Python 1.5.2 introduced the bf_getcharbuffer slot into PyBufferProcs. Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value. Code can use PyType_HasFeature(type_ob, flag_value) to test whether the given type object has a specified feature. } // PyBufferProcs contains bf_getcharbuffer Py_TPFLAGS_HAVE_GETCHARBUFFER = (1 shl 0); // PySequenceMethods contains sq_contains Py_TPFLAGS_HAVE_SEQUENCE_IN = (1 shl 1); // Objects which participate in garbage collection (see objimp.h) Py_TPFLAGS_GC = (1 shl 2); // PySequenceMethods and PyNumberMethods contain in-place operators Py_TPFLAGS_HAVE_INPLACEOPS = (1 shl 3); // PyNumberMethods do their own coercion */ Py_TPFLAGS_CHECKTYPES = (1 shl 4); Py_TPFLAGS_HAVE_RICHCOMPARE = (1 shl 5); // Objects which are weakly referencable if their tp_weaklistoffset is >0 // XXX Should this have the same value as Py_TPFLAGS_HAVE_RICHCOMPARE? // These both indicate a feature that appeared in the same alpha release. Py_TPFLAGS_HAVE_WEAKREFS = (1 shl 6); // tp_iter is defined Py_TPFLAGS_HAVE_ITER = (1 shl 7); // New members introduced by Python 2.2 exist Py_TPFLAGS_HAVE_CLASS = (1 shl 8); // Set if the type object is dynamically allocated Py_TPFLAGS_HEAPTYPE = (1 shl 9); // Set if the type allows subclassing Py_TPFLAGS_BASETYPE = (1 shl 10); // Set if the type is 'ready' -- fully initialized Py_TPFLAGS_READY = (1 shl 12); // Set while the type is being 'readied', to prevent recursive ready calls Py_TPFLAGS_READYING = (1 shl 13); // Objects support garbage collection (see objimp.h) Py_TPFLAGS_HAVE_GC = (1 shl 14); Py_TPFLAGS_DEFAULT = Py_TPFLAGS_HAVE_GETCHARBUFFER or Py_TPFLAGS_HAVE_SEQUENCE_IN or Py_TPFLAGS_HAVE_INPLACEOPS or Py_TPFLAGS_HAVE_RICHCOMPARE or Py_TPFLAGS_HAVE_WEAKREFS or Py_TPFLAGS_HAVE_ITER or Py_TPFLAGS_HAVE_CLASS or Py_TPFLAGS_BASETYPE ; // See function PyType_HasFeature below for testing the flags. // Delphi equivalent used by TPythonType type TPFlag = (tpfHaveGetCharBuffer, tpfHaveSequenceIn, tpfGC, tpfHaveInplaceOps, tpfCheckTypes, tpfHaveRichCompare, tpfHaveWeakRefs ,tpfHaveIter, tpfHaveClass, tpfHeapType, tpfBaseType, tpfReady, tpfReadying, tpfHaveGC ); TPFlags = set of TPFlag; const TPFLAGS_DEFAULT = [tpfHaveGetCharBuffer, tpfHaveSequenceIn, tpfHaveInplaceOps, tpfHaveRichCompare, tpfHaveWeakRefs, tpfHaveIter, tpfHaveClass, tpfBaseType ]; //------- Python opcodes ----------// Const single_input = 256; file_input = 257; eval_input = 258; p4d_funcdef = 259; p4d_parameters = 260; p4d_varargslist = 261; p4d_fpdef = 262; p4d_fplist = 263; p4d_stmt = 264; p4d_simple_stmt = 265; p4d_small_stmt = 266; p4d_expr_stmt = 267; p4d_augassign = 268; p4d_print_stmt = 269; p4d_del_stmt = 270; p4d_pass_stmt = 271; p4d_flow_stmt = 272; p4d_break_stmt = 273; p4d_continue_stmt = 274; p4d_return_stmt = 275; p4d_raise_stmt = 276; p4d_import_stmt = 277; p4d_import_as_name = 278; p4d_dotted_as_name = 279; p4d_dotted_name = 280; p4d_global_stmt = 281; p4d_exec_stmt = 282; p4d_assert_stmt = 283; p4d_compound_stmt = 284; p4d_if_stmt = 285; p4d_while_stmt = 286; p4d_for_stmt = 287; p4d_try_stmt = 288; p4d_except_clause = 289; p4d_suite = 290; p4d_test = 291; p4d_and_test = 291; p4d_not_test = 293; p4d_comparison = 294; p4d_comp_op = 295; p4d_expr = 296; p4d_xor_expr = 297; p4d_and_expr = 298; p4d_shift_expr = 299; p4d_arith_expr = 300; p4d_term = 301; p4d_factor = 302; p4d_power = 303; p4d_atom = 304; p4d_listmaker = 305; p4d_lambdef = 306; p4d_trailer = 307; p4d_subscriptlist = 308; p4d_subscript = 309; p4d_sliceop = 310; p4d_exprlist = 311; p4d_testlist = 312; p4d_dictmaker = 313; p4d_classdef = 314; p4d_arglist = 315; p4d_argument = 316; p4d_list_iter = 317; p4d_list_for = 318; p4d_list_if = 319; // structmember.h const //* Types */ T_SHORT = 0; T_INT = 1; T_LONG = 2; T_FLOAT = 3; T_DOUBLE = 4; T_STRING = 5; T_OBJECT = 6; //* XXX the ordering here is weird for binary compatibility */ T_CHAR = 7; //* 1-character string */ T_BYTE = 8; //* 8-bit signed int */ //* unsigned variants: */ T_UBYTE = 9; T_USHORT = 10; T_UINT = 11; T_ULONG = 12; //* Added by Jack: strings contained in the structure */ T_STRING_INPLACE= 13; T_OBJECT_EX = 16;{* Like T_OBJECT, but raises AttributeError when the value is NULL, instead of converting to None. *} //* Flags */ READONLY = 1; RO = READONLY; //* Shorthand */ READ_RESTRICTED = 2; WRITE_RESTRICTED = 4; RESTRICTED = (READ_RESTRICTED or WRITE_RESTRICTED); type TPyMemberType = (mtShort, mtInt, mtLong, mtFloat, mtDouble, mtString, mtObject, mtChar, mtByte, mtUByte, mtUShort, mtUInt, mtULong, mtStringInplace, mtObjectEx); TPyMemberFlag = (mfDefault, mfReadOnly, mfReadRestricted, mfWriteRestricted, mfRestricted); //####################################################### //## ## //## Non-Python specific constants ## //## ## //####################################################### const ErrInit = -300; CR = #13; LF = #10; TAB = #09; CRLF = CR+LF; //####################################################### //## ## //## Global declarations, nothing Python specific ## //## ## //####################################################### type TPAnsiChar = array[0..16000] of PAnsiChar; TPWideChar = array[0..16000] of PWideChar; PPAnsiChar = ^TPAnsiChar; PPWideChar = ^TPWideChar; PInt = ^Integer; PDouble = ^Double; PFloat = ^Real; PLong = ^LongInt; PShort = ^ShortInt; //####################################################### //## ## //## Python specific interface ## //## ## //####################################################### type PP_frozen = ^P_frozen; P_frozen = ^_frozen; PPyObject = ^PyObject; PPPyObject = ^PPyObject; PPPPyObject = ^PPPyObject; PPyIntObject = ^PyIntObject; PPyTypeObject = ^PyTypeObject; PPySliceObject = ^PySliceObject; AtExitProc = procedure; PyCFunction = function( self, args:PPyObject): PPyObject; cdecl; PyCFunctionWithKW = function( self, args, keywords:PPyObject): PPyObject; cdecl; unaryfunc = function( ob1 : PPyObject): PPyObject; cdecl; binaryfunc = function( ob1,ob2 : PPyObject): PPyObject; cdecl; ternaryfunc = function( ob1,ob2,ob3 : PPyObject): PPyObject; cdecl; inquiry = function( ob1 : PPyObject): integer; cdecl; lenfunc = function( ob1 : PPyObject): NativeInt; cdecl; coercion = function( ob1,ob2 : PPPyObject): integer; cdecl; ssizeargfunc = function( ob1 : PPyObject; i: NativeInt): PPyObject; cdecl; ssizessizeargfunc = function( ob1 : PPyObject; i1, i2: NativeInt): PPyObject; cdecl; ssizeobjargproc = function( ob1 : PPyObject; i: NativeInt; ob2 : PPyObject): integer; cdecl; ssizessizeobjargproc = function( ob1: PPyObject; i1, i2: NativeInt; ob2: PPyObject): integer; cdecl; objobjargproc = function( ob1,ob2,ob3 : PPyObject): integer; cdecl; pydestructor = procedure(ob: PPyObject); cdecl; printfunc = function( ob: PPyObject; var f: file; i: integer): integer; cdecl; getattrfunc = function( ob1: PPyObject; name: PAnsiChar): PPyObject; cdecl; setattrfunc = function( ob1: PPyObject; name: PAnsiChar; ob2: PPyObject): integer; cdecl; cmpfunc = function( ob1,ob2: PPyObject): integer; cdecl; reprfunc = function( ob: PPyObject): PPyObject; cdecl; hashfunc = function( ob: PPyObject): NativeInt; cdecl; // !! in 2.x it is still a LongInt getattrofunc = function( ob1,ob2: PPyObject): PPyObject; cdecl; setattrofunc = function( ob1,ob2,ob3: PPyObject): integer; cdecl; /// jah 29-sep-2000 : updated for python 2.0 /// added from object.h getreadbufferproc = function ( ob1: PPyObject; i: NativeInt; ptr: Pointer): NativeInt; cdecl; getwritebufferproc= function ( ob1: PPyObject; i: NativeInt; ptr: Pointer): NativeInt; cdecl; getsegcountproc = function ( ob1: PPyObject; i: NativeInt): NativeInt; cdecl; getcharbufferproc = function ( ob1: PPyObject; i: NativeInt; const pstr: PAnsiChar): NativeInt; cdecl; objobjproc = function ( ob1, ob2: PPyObject): integer; cdecl; visitproc = function ( ob1: PPyObject; ptr: Pointer): integer; cdecl; traverseproc = function ( ob1: PPyObject; proc: visitproc; ptr: Pointer): integer; cdecl; richcmpfunc = function ( ob1, ob2 : PPyObject; i : Integer) : PPyObject; cdecl; getiterfunc = function ( ob1 : PPyObject) : PPyObject; cdecl; iternextfunc = function ( ob1 : PPyObject) : PPyObject; cdecl; descrgetfunc = function ( ob1, ob2, ob3 : PPyObject) : PPyObject; cdecl; descrsetfunc = function ( ob1, ob2, ob3 : PPyObject) : Integer; cdecl; initproc = function ( self, args, kwds : PPyObject) : Integer; cdecl; newfunc = function ( subtype: PPyTypeObject; args, kwds : PPyObject) : PPyObject; cdecl; allocfunc = function ( self: PPyTypeObject; nitems : NativeInt) : PPyObject; cdecl; PyNumberMethods = {$IFNDEF CPUX64}packed{$ENDIF} record nb_add : binaryfunc; nb_substract : binaryfunc; nb_multiply : binaryfunc; nb_divide : binaryfunc; nb_remainder : binaryfunc; nb_divmod : binaryfunc; nb_power : ternaryfunc; nb_negative : unaryfunc; nb_positive : unaryfunc; nb_absolute : unaryfunc; nb_nonzero : inquiry; nb_invert : unaryfunc; nb_lshift : binaryfunc; nb_rshift : binaryfunc; nb_and : binaryfunc; nb_xor : binaryfunc; nb_or : binaryfunc; nb_coerce : coercion; nb_int : unaryfunc; nb_long : unaryfunc; nb_float : unaryfunc; nb_oct : unaryfunc; nb_hex : unaryfunc; /// jah 29-sep-2000 : updated for python 2.0 /// added from .h nb_inplace_add : binaryfunc; nb_inplace_subtract : binaryfunc; nb_inplace_multiply : binaryfunc; nb_inplace_divide : binaryfunc; nb_inplace_remainder : binaryfunc; nb_inplace_power : ternaryfunc; nb_inplace_lshift : binaryfunc; nb_inplace_rshift : binaryfunc; nb_inplace_and : binaryfunc; nb_inplace_xor : binaryfunc; nb_inplace_or : binaryfunc; // Added in release 2.2 // The following require the Py_TPFLAGS_HAVE_CLASS flag nb_floor_divide : binaryfunc; nb_true_divide : binaryfunc; nb_inplace_floor_divide : binaryfunc; nb_inplace_true_divide : binaryfunc; end; PPyNumberMethods = ^PyNumberMethods; PySequenceMethods = {$IFNDEF CPUX64}packed{$ENDIF} record sq_length : lenfunc; sq_concat : binaryfunc; sq_repeat : ssizeargfunc; sq_item : ssizeargfunc; sq_slice : ssizessizeargfunc; sq_ass_item : ssizeobjargproc; sq_ass_slice : ssizessizeobjargproc; /// jah 29-sep-2000 : updated for python 2.0 /// added from .h sq_contains : objobjproc; sq_inplace_concat : binaryfunc; sq_inplace_repeat : ssizeargfunc; end; PPySequenceMethods = ^PySequenceMethods; PyMappingMethods = {$IFNDEF CPUX64}packed{$ENDIF} record mp_length : lenfunc; mp_subscript : binaryfunc; mp_ass_subscript : objobjargproc; end; PPyMappingMethods = ^PyMappingMethods; /// jah 29-sep-2000 : updated for python 2.0 /// added from .h PyBufferProcs = {$IFNDEF CPUX64}packed{$ENDIF} record bf_getreadbuffer : getreadbufferproc; bf_getwritebuffer : getwritebufferproc; bf_getsegcount : getsegcountproc; bf_getcharbuffer : getcharbufferproc; end; PPyBufferProcs = ^PyBufferProcs; Py_complex = {$IFNDEF CPUX64}packed{$ENDIF} record real : double; imag : double; end; PyObject = {$IFNDEF CPUX64}packed{$ENDIF} record ob_refcnt: NativeInt; ob_type: PPyTypeObject; end; PyIntObject = {$IFNDEF CPUX64}packed{$ENDIF} record ob_refcnt : NativeInt; ob_type : PPyTypeObject; ob_ival : LongInt; end; _frozen = {$IFNDEF CPUX64}packed{$ENDIF} record name : PAnsiChar; code : PByte; size : Integer; end; PySliceObject = {$IFNDEF CPUX64}packed{$ENDIF} record ob_refcnt: NativeInt; ob_type: PPyTypeObject; start, stop, step: PPyObject; end; PPyMethodDef = ^PyMethodDef; PyMethodDef = {$IFNDEF CPUX64}packed{$ENDIF} record ml_name: PAnsiChar; ml_meth: PyCFunction; ml_flags: Integer; ml_doc: PAnsiChar; end; // structmember.h PPyMemberDef = ^PyMemberDef; PyMemberDef = {$IFNDEF CPUX64}packed{$ENDIF} record name : PAnsiChar; _type : integer; offset : NativeInt; flags : integer; doc : PAnsiChar; end; // descrobject.h // Descriptors getter = function ( obj : PPyObject; context : Pointer) : PPyObject; cdecl; setter = function ( obj, value : PPyObject; context : Pointer) : integer; cdecl; PPyGetSetDef = ^PyGetSetDef; PyGetSetDef = {$IFNDEF CPUX64}packed{$ENDIF} record name : PAnsiChar; get : getter; _set : setter; doc : PAnsiChar; closure : Pointer; end; wrapperfunc = function (self, args: PPyObject; wrapped : Pointer) : PPyObject; cdecl; pwrapperbase = ^wrapperbase; wrapperbase = {$IFNDEF CPUX64}packed{$ENDIF} record name : PAnsiChar; wrapper : wrapperfunc; doc : PAnsiChar; end; // Various kinds of descriptor objects {#define PyDescr_COMMON \ PyObject_HEAD \ PyTypeObject *d_type; \ PyObject *d_name } PPyDescrObject = ^PyDescrObject; PyDescrObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object d_type : PPyTypeObject; d_name : PPyObject; end; PPyMethodDescrObject = ^PyMethodDescrObject; PyMethodDescrObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of PyDescr_COMMON // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object d_type : PPyTypeObject; d_name : PPyObject; // End of PyDescr_COMMON d_method : PPyMethodDef; end; PPyMemberDescrObject = ^PyMemberDescrObject; PyMemberDescrObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of PyDescr_COMMON // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object d_type : PPyTypeObject; d_name : PPyObject; // End of PyDescr_COMMON d_member : PPyMemberDef; end; PPyGetSetDescrObject = ^PyGetSetDescrObject; PyGetSetDescrObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of PyDescr_COMMON // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object d_type : PPyTypeObject; d_name : PPyObject; // End of PyDescr_COMMON d_getset : PPyGetSetDef; end; PPyWrapperDescrObject = ^PyWrapperDescrObject; PyWrapperDescrObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of PyDescr_COMMON // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object d_type : PPyTypeObject; d_name : PPyObject; // End of PyDescr_COMMON d_base : pwrapperbase; d_wrapped : Pointer; // This can be any function pointer end; PPyModuleDef_Base = ^PyModuleDef_Base; PyModuleDef_Base = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object m_init : function( ) : PPyObject; cdecl; m_index : NativeInt; m_copy : PPyObject; end; PPyModuleDef = ^PyModuleDef; PyModuleDef = {$IFNDEF CPUX64}packed{$ENDIF} record m_base : PyModuleDef_Base; m_name : PAnsiChar; m_doc : PAnsiChar; m_size : NativeInt; m_methods : PPyMethodDef; m_reload : inquiry; m_traverse : traverseproc; m_clear : inquiry; m_free : inquiry; end; // object.h PyTypeObject = {$IFNDEF CPUX64}packed{$ENDIF} record ob_refcnt: NativeInt; ob_type: PPyTypeObject; ob_size: NativeInt; // Number of items in variable part tp_name: PAnsiChar; // For printing tp_basicsize, tp_itemsize: NativeInt; // For allocation // Methods to implement standard operations tp_dealloc: pydestructor; tp_print: printfunc; tp_getattr: getattrfunc; tp_setattr: setattrfunc; tp_compare: cmpfunc; tp_repr: reprfunc; // Method suites for standard classes tp_as_number: PPyNumberMethods; tp_as_sequence: PPySequenceMethods; tp_as_mapping: PPyMappingMethods; // More standard operations (here for binary compatibility) tp_hash: hashfunc; tp_call: ternaryfunc; tp_str: reprfunc; tp_getattro: getattrofunc; tp_setattro: setattrofunc; /// jah 29-sep-2000 : updated for python 2.0 // Functions to access object as input/output buffer tp_as_buffer: PPyBufferProcs; // Flags to define presence of optional/expanded features tp_flags: LongInt; tp_doc: PAnsiChar; // Documentation string // call function for all accessible objects tp_traverse: traverseproc; // delete references to contained objects tp_clear: inquiry; // rich comparisons tp_richcompare: richcmpfunc; // weak reference enabler tp_weaklistoffset: NativeInt; // Iterators tp_iter : getiterfunc; tp_iternext : iternextfunc; // Attribute descriptor and subclassing stuff tp_methods : PPyMethodDef; tp_members : PPyMemberDef; tp_getset : PPyGetSetDef; tp_base : PPyTypeObject; tp_dict : PPyObject; tp_descr_get : descrgetfunc; tp_descr_set : descrsetfunc; tp_dictoffset : NativeInt; tp_init : initproc; tp_alloc : allocfunc; tp_new : newfunc; tp_free : pydestructor; // Low-level free-memory routine tp_is_gc : inquiry; // For PyObject_IS_GC tp_bases : PPyObject; tp_mro : PPyObject; // method resolution order tp_cache : PPyObject; tp_subclasses : PPyObject; tp_weaklist : PPyObject; tp_del : PyDestructor; tp_version_tag : NativeUInt; // Type attribute cache version tag. Added in version 2.6 tp_finalize : PyDestructor; //More spares tp_xxx1 : NativeInt; tp_xxx2 : NativeInt; tp_xxx3 : NativeInt; tp_xxx4 : NativeInt; tp_xxx5 : NativeInt; tp_xxx6 : NativeInt; tp_xxx7 : NativeInt; tp_xxx8 : NativeInt; tp_xxx9 : NativeInt; tp_xxx10 : NativeInt; end; PPyMethodChain = ^PyMethodChain; PyMethodChain = {$IFNDEF CPUX64}packed{$ENDIF} record methods: PPyMethodDef; link: PPyMethodChain; end; PPyClassObject = ^PyClassObject; PyClassObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object cl_bases : PPyObject; // A tuple of class objects cl_dict : PPyObject; // A dictionary cl_name : PPyObject; // A string // The following three are functions or NULL cl_getattr : PPyObject; cl_setattr : PPyObject; cl_delattr : PPyObject; end; PPyInstanceObject = ^PyInstanceObject; PyInstanceObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object in_class : PPyClassObject; // The class object in_dict : PPyObject; // A dictionary end; { Instance method objects are used for two purposes: (a) as bound instance methods (returned by instancename.methodname) (b) as unbound methods (returned by ClassName.methodname) In case (b), im_self is NULL } PPyMethodObject = ^PyMethodObject; PyMethodObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object im_func : PPyObject; // The function implementing the method im_self : PPyObject; // The instance it is bound to, or NULL im_class : PPyObject; // The class that defined the method end; // Bytecode object, compile.h PPyCodeObject = ^PyCodeObject; PyCodeObject = {$IFNDEF CPUX64}packed{$ENDIF} record ob_refcnt : NativeInt; ob_type : PPyTypeObject; co_argcount : Integer; // #arguments, except *args co_nlocals : Integer; // #local variables co_stacksize : Integer; // #entries needed for evaluation stack co_flags : Integer; // CO_..., see below co_code : PPyObject; // instruction opcodes (it hides a PyStringObject) co_consts : PPyObject; // list (constants used) co_names : PPyObject; // list of strings (names used) co_varnames : PPyObject; // tuple of strings (local variable names) co_freevars : PPyObject; // tuple of strings (free variable names) co_cellvars : PPyObject; // tuple of strings (cell variable names) // The rest doesn't count for hash/cmp co_filename : PPyObject; // string (where it was loaded from) co_name : PPyObject; // string (name, for reference) co_firstlineno : Integer; // first source line number co_lnotab : PPyObject; // string (encoding addr<->lineno mapping) end; // from pystate.h PPyInterpreterState = ^PyInterpreterState; PPyThreadState = ^PyThreadState; PPyFrameObject = ^PyFrameObject; // Interpreter environments PyInterpreterState = {$IFNDEF CPUX64}packed{$ENDIF} record next : PPyInterpreterState; tstate_head : PPyThreadState; // The strucure has changed between versions beyond this point. // Not safe to use members // modules : PPyObject; // sysdict : PPyObject; // builtins : PPyObject; //Spares is_xxx1 : NativeInt; is_xxx2 : NativeInt; is_xxx3 : NativeInt; is_xxx4 : NativeInt; is_xxx5 : NativeInt; is_xxx6 : NativeInt; is_xxx7 : NativeInt; is_xxx8 : NativeInt; is_xxx9 : NativeInt; end; // Thread specific information PyThreadState = {$IFNDEF CPUX64}packed{$ENDIF} record {prev : PPyThreadState; introduced in python 3.4} next : PPyThreadState; interp : PPyInterpreterState; interp34 : PPyInterpreterState; // The strucure has changed between versions beyond this point. // Not safe to use members // // frame : PPyFrameObject; // recursion_depth: integer; // ticker : integer; // tracing : integer; // // sys_profilefn : Pointer; // c-functions for profile/trace // sys_tracefn : Pointer; // sys_profilefunc: PPyObject; // sys_tracefunc : PPyObject; // // curexc_type : PPyObject; // curexc_value : PPyObject; // curexc_traceback: PPyObject; // // exc_type : PPyObject; // exc_value : PPyObject; // exc_traceback : PPyObject; // // dict : PPyObject; // tick_counter :Integer; // gilstate_counter :Integer; // // async_exc :PPyObject; { Asynchronous exception to raise } // thread_id :LongInt; { Thread id where this tstate was created } //Spares ts_xxx1 : NativeInt; ts_xxx2 : NativeInt; ts_xxx3 : NativeInt; ts_xxx4 : NativeInt; ts_xxx5 : NativeInt; ts_xxx6 : NativeInt; ts_xxx7 : NativeInt; ts_xxx8 : NativeInt; ts_xxx9 : NativeInt; ts_xxx10 : NativeInt; ts_xxx11 : NativeInt; ts_xxx12 : NativeInt; ts_xxx13 : NativeInt; ts_xxx14 : NativeInt; ts_xxx15 : NativeInt; ts_xxx16 : NativeInt; ts_xxx17 : NativeInt; ts_xxx18 : NativeInt; ts_xxx19 : NativeInt; { XXX signal handlers should also be here } end; // from frameobject.h PPyTryBlock = ^PyTryBlock; PyTryBlock = {$IFNDEF CPUX64}packed{$ENDIF} record b_type : Integer; // what kind of block this is b_handler : Integer; // where to jump to find handler b_level : Integer; // value stack level to pop to end; CO_MAXBLOCKS = 0..19; PyFrameObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the VAR_HEAD of an object. ob_refcnt : NativeInt; ob_type : PPyTypeObject; ob_size : NativeInt; // Number of items in variable part // End of the Head of an object f_back : PPyFrameObject; // previous frame, or NULL f_code : PPyCodeObject; // code segment f_builtins : PPyObject; // builtin symbol table (PyDictObject) f_globals : PPyObject; // global symbol table (PyDictObject) f_locals : PPyObject; // local symbol table (PyDictObject) f_valuestack : PPPyObject; // points after the last local (* Next free slot in f_valuestack. Frame creation sets to f_valuestack. Frame evaluation usually NULLs it, but a frame that yields sets it to the current stack top. *) f_stacktop : PPPyObject; f_trace : PPyObject; // Trace function f_exc_type, f_exc_value, f_exc_traceback: PPyObject; f_tstate : PPyThreadState; f_lasti : Integer; // Last instruction if called f_lineno : Integer; // Current line number f_iblock : Integer; // index in f_blockstack f_blockstack : array[CO_MAXBLOCKS] of PyTryBlock; // for try and loop blocks f_localsplus : array[0..0] of PPyObject; // locals+stack, dynamically sized end; // From traceback.c PPyTraceBackObject = ^PyTraceBackObject; PyTraceBackObject = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object tb_next : PPyTraceBackObject; tb_frame : PPyFrameObject; tb_lasti : Integer; tb_lineno : Integer; end; // Parse tree node interface PNode = ^node; node = {$IFNDEF CPUX64}packed{$ENDIF} record n_type : smallint; n_str : PAnsiChar; n_lineno : integer; n_col_offset: integer; n_nchildren : integer; n_child : PNode; end; PPyCompilerFlags = ^PyCompilerFlags; PyCompilerFlags = {$IFNDEF CPUX64}packed{$ENDIF} record flags : integer; end; // From weakrefobject.h PPyWeakReference = ^PyWeakReference; PyWeakReference = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object wr_object : PPyObject; wr_callback : PPyObject; hash : NativeInt; wr_prev : PPyWeakReference; wr_next : PPyWeakReference; end; // from datetime.h {* Fields are packed into successive bytes, each viewed as unsigned and * big-endian, unless otherwise noted: * * byte offset * 0 year 2 bytes, 1-9999 * 2 month 1 byte, 1-12 * 3 day 1 byte, 1-31 * 4 hour 1 byte, 0-23 * 5 minute 1 byte, 0-59 * 6 second 1 byte, 0-59 * 7 usecond 3 bytes, 0-999999 * 10 *} const { # of bytes for year, month, and day. } _PyDateTime_DATE_DATASIZE = 4; { # of bytes for hour, minute, second, and usecond. } _PyDateTime_TIME_DATASIZE = 6; { # of bytes for year, month, day, hour, minute, second, and usecond. } _PyDateTime_DATETIME_DATASIZE = 10; type PyDateTime_Delta = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; // -1 when unknown days : Integer; // -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS seconds : Integer; // 0 <= seconds < 24*3600 is invariant microseconds: Integer; // 0 <= microseconds < 1000000 is invariant end; PPyDateTime_Delta = ^PyDateTime_Delta; PyDateTime_TZInfo = {$IFNDEF CPUX64}packed{$ENDIF} record // a pure abstract base clase // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object end; PPyDateTime_TZInfo = ^PyDateTime_TZInfo; { /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ #define _PyTZINFO_HEAD \ PyObject_HEAD \ long hashcode; \ char hastzinfo; /* boolean flag */ } {* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects * starting with _PyTZINFO_HEAD. *} _PyDateTime_BaseTZInfo = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD end; _PPyDateTime_BaseTZInfo = ^_PyDateTime_BaseTZInfo; {* All time objects are of PyDateTime_TimeType, but that can be allocated * in two ways, with or without a tzinfo member. Without is the same as * tzinfo == None, but consumes less memory. _PyDateTime_BaseTime is an * internal struct used to allocate the right amount of space for the * "without" case. *} {#define _PyDateTime_TIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_TIME_DATASIZE]; } _PyDateTime_BaseTime = {$IFNDEF CPUX64}packed{$ENDIF} record // hastzinfo false // Start of _PyDateTime_TIMEHEAD // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD data : array[0..Pred(_PyDateTime_TIME_DATASIZE)] of Byte; // End of _PyDateTime_TIMEHEAD end; _PPyDateTime_BaseTime = ^_PyDateTime_BaseTime; PyDateTime_Time = {$IFNDEF CPUX64}packed{$ENDIF} record // hastzinfo true // Start of _PyDateTime_TIMEHEAD // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD data : array[0..Pred(_PyDateTime_TIME_DATASIZE)] of Byte; // End of _PyDateTime_TIMEHEAD tzinfo : PPyObject; end; PPyDateTime_Time = ^PyDateTime_Time; {* All datetime objects are of PyDateTime_DateTimeType, but that can be * allocated in two ways too, just like for time objects above. In addition, * the plain date type is a base class for datetime, so it must also have * a hastzinfo member (although it's unused there). *} PyDateTime_Date = {$IFNDEF CPUX64}packed{$ENDIF} record // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD data : array[0..Pred(_PyDateTime_DATE_DATASIZE)] of Byte; end; PPyDateTime_Date = ^PyDateTime_Date; { #define _PyDateTime_DATETIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_DATETIME_DATASIZE]; } _PyDateTime_BaseDateTime = {$IFNDEF CPUX64}packed{$ENDIF} record // hastzinfo false // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD data : array[0..Pred(_PyDateTime_DATETIME_DATASIZE)] of Byte; end; _PPyDateTime_BaseDateTime = ^_PyDateTime_BaseDateTime; PyDateTime_DateTime = {$IFNDEF CPUX64}packed{$ENDIF} record // hastzinfo true // Start of _PyDateTime_DATETIMEHEAD // Start of _PyTZINFO_HEAD // Start of the Head of an object ob_refcnt : NativeInt; ob_type : PPyTypeObject; // End of the Head of an object hashcode : Integer; hastzinfo : Char; // boolean flag // End of _PyTZINFO_HEAD data : array[0..Pred(_PyDateTime_DATETIME_DATASIZE)] of Byte; // End of _PyDateTime_DATETIMEHEAD tzinfo : PPyObject; end; PPyDateTime_DateTime = ^PyDateTime_DateTime; //####################################################### //## ## //## GIL state ## //## ## //####################################################### PyGILState_STATE = (PyGILState_LOCKED, PyGILState_UNLOCKED); var {$ifdef PYTHON_DYNAMIC} {$include DynamicTypes} {$else} {$include StaticTypes} {$endif} {$ifdef PYTHON_DYNAMIC} procedure LoadLibrary(path: ansistring; loadAll: boolean = true); {$endif} implementation uses Dynlibs; {$ifdef PYTHON_DYNAMIC} procedure LoadLibrary(path: ansistring; loadAll: boolean = true); var handle: TLibHandle; function Import(name: string): CodePointer; begin result := GetProcAddress(handle, name); Assert(result <> nil, 'failed to load function '+name); end; begin handle := Dynlibs.LoadLibrary(path); Assert(handle <> NilHandle, 'python library '+path+' failed to load.'); if loadAll then begin {$include DynamicImports} end; end; {$endif} end.
unit Common; interface type //代理的结构 TDLUserInfo = record //返回给客户端的 sAccount: string[12];//账号 sUserQQ: string[20]; //QQ sName: string[20]; //真实姓名 CurYuE: Currency; //帐户余额 CurXiaoShouE: Currency; //帐户销售额 SAddrs: string[50]; //上次登陆地址 dTimer: TDateTime; //上次登陆时间 end; pTDLUserInfo = ^TDLUserInfo; TUserEntry1 = record //添加用户的机构 sAccount: string[12];//账号 sUserQQ: string[20]; //QQ sGameListUrl: string[120]; sBakGameListUrl: string[120]; sPatchListUrl: string[120]; sGameMonListUrl: string[120]; sGameESystemUrl: string[120]; sGatePass: string[30]; end; //公用结构 TUserSession = record sAccount: string[12]; //帐号 sPassword: string[20]; //密码 boLogined: Boolean; end; //普通用户的结构 TUserInfo = record sAccount: string[12];//账号 sUserQQ: string[20]; //QQ nDayMakeNum: Byte; //今日生成次数 nMaxDayMakeNum: Byte; //最大生成次数 sAddrs: string[50]; //上次登陆地址 dTimer: TDateTime; //上次登陆时间 end; const ///////////////////////////授权相关///////////////////////////////////////////// //代理相关 GM_LOGIN = 118; SM_LOGIN_SUCCESS = 119; SM_LOGIN_FAIL = 120; GM_GETUSER = 121; //检测用户名是否存在 SM_GETUSER_SUCCESS = 122; SM_GETUSER_FAIL = 123; GM_ADDUSER = 124; SM_ADDUSER_SUCCESS = 125; SM_ADDUSER_FAIL = 126; GM_CHANGEPASS = 127; //修改密码 SM_CHANGEPASS_SUCCESS = 128; SM_CHANGEPASS_FAIL = 129; //用户相关 GM_USERLOGIN = 200; //用户登陆 SM_USERLOGIN_SUCCESS = 201; SM_USERLOGIN_FAIL = 202; GM_USERCHANGEPASS = 203; //修改密码 SM_USERCHANGEPASS_SUCCESS = 204; SM_USERCHANGEPASS_FAIL = 205; GM_USERCHECKMAKEKEYANDDAYMAKENUM = 206; //验证密钥匙和今日生成次数 SM_USERCHECKMAKEKEYANDDAYMAKENUM_SUCCESS = 207; SM_USERCHECKMAKEKEYANDDAYMAKENUM_FAIL = 208; GM_USERMAKELOGIN = 209; //生成登陆器 SM_USERMAKELOGIN_SUCCESS = 210; SM_USERMAKELOGIN_FAIL = 211; GM_USERMAKEGATE = 212; //生成网关 SM_USERMAKEGATE_SUCCESS = 213; SM_USERMAKEGATE_FAIL = 214; SM_USERMAKEONETIME_FAIL = 215; //超过服务器最大用户同时生成人数 //////////////////////////////////////////////////////////////////////////////// GS_QUIT = 2000; //关闭 SG_FORMHANDLE = 1000; //服务器HANLD SG_STARTNOW = 1001; //正在启动服务器... SG_STARTOK = 1002; //服务器启动完成... implementation end.
unit feli_validation; {$mode objfpc} interface type FeliValidation = class(TObject) private public class function emailCheck(email: ansiString): boolean; static; class function fixedValueCheck(targetString: ansiString; const checkStrings: array of ansiString): boolean; static; class function lengthCheck(target: ansiString; min, max: integer; inclusive: boolean = true): boolean; static; class function rangeCheck(target, min, max: integer; inclusive: boolean = true): boolean; static; class function rangeCheck(target, min, max: real; inclusive: boolean = true): boolean; static; class procedure debug; static; end; implementation uses feli_logger, feli_stack_tracer, sysutils, regExpr; class function FeliValidation.emailCheck(email: ansiString): boolean; static; var re: TRegExpr; begin FeliStackTrace.trace('begin', 'class function FeliValidation.emailCheck(email: ansiString): boolean; static;'); re := TRegExpr.create('^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+$'); result := re.exec(email); FeliStackTrace.trace('end', 'class function FeliValidation.emailCheck(email: ansiString): boolean; static;'); end; class function FeliValidation.fixedValueCheck(targetString: ansiString; const checkStrings: array of ansiString): boolean; static; var currentString: ansiString; found: boolean; begin FeliStackTrace.trace('begin', 'class function FeliValidation.fixedValueCheck(targetString: ansiString; const checkStrings: array of ansiString): boolean; static;'); found := false; for currentString in checkStrings do begin if targetString = currentString then begin found := true; break; end; end; result := found; FeliStackTrace.trace('end', 'class function FeliValidation.fixedValueCheck(targetString: ansiString; const checkStrings: array of ansiString): boolean; static;'); end; class function FeliValidation.lengthCheck(target: ansiString; min, max: integer; inclusive: boolean = true): boolean; static; begin FeliStackTrace.trace('begin', 'class function FeliValidation.lengthCheck(target: ansiString; min, max: integer; inclusive: boolean = true): boolean; static;'); result := FeliValidation.rangeCheck(length(target), min, max, inclusive); FeliStackTrace.trace('end', 'class function FeliValidation.lengthCheck(target: ansiString; min, max: integer; inclusive: boolean = true): boolean; static;'); end; class function FeliValidation.rangeCheck(target, min, max: integer; inclusive: boolean = true): boolean; static; begin FeliStackTrace.trace('begin', 'class function FeliValidation.rangeCheck(target, min, max: integer; inclusive: boolean = true): boolean; static;'); if (min <= target) and (target <= max) then if inclusive then result := true else if (min = target) or (max = target) then result := false else result := true else result := false; FeliStackTrace.trace('end', 'class function FeliValidation.rangeCheck(target, min, max: integer; inclusive: boolean = true): boolean; static;'); end; class function FeliValidation.rangeCheck(target, min, max: real; inclusive: boolean = true): boolean; static; begin FeliStackTrace.trace('begin', 'class function FeliValidation.rangeCheck(target, min, max: real; inclusive: boolean = true): boolean; static;'); // Checks if min <= target <= max if (min <= target) and (target <= max) then if inclusive then result := true else // Checks if min < target < max if (min = target) or (max = target) then result := false else result := true else result := false; FeliStackTrace.trace('end', 'class function FeliValidation.rangeCheck(target, min, max: real; inclusive: boolean = true): boolean; static;'); end; class procedure FeliValidation.debug; static; begin FeliStackTrace.trace('begin', 'class procedure FeliValidation.debug; static;'); FeliLogger.info(format('[FeliValidation.debug]', [])); FeliStackTrace.trace('end', 'class procedure FeliValidation.debug; static;'); end; end.
unit nsProjectFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, nsTypes, nsGlobals, DateUtils, System.UITypes, tsTaskman, tsSettings, StrUtils, ImgList, Spin, System.ImageList; type TfrmProjectProperties = class(TForm) PageControl: TPageControl; TS1: TTabSheet; TS2: TTabSheet; edtTitle: TEdit; Label7: TLabel; Label8: TLabel; lblSize: TLabel; lblContains: TLabel; TS3: TTabSheet; Label1: TLabel; OpenDialog: TOpenDialog; btnSecurity: TButton; grpSchedules: TGroupBox; grpLog: TGroupBox; chkWriteLog: TCheckBox; lblIncluded: TLabel; lblExcluded: TLabel; edtInclude: TEdit; edtExclude: TEdit; lblEncType: TLabel; lblEncryption: TLabel; btnEditSchedule: TButton; lblSchedule: TLabel; ImageList1: TImageList; Label16: TLabel; GroupBox3: TGroupBox; Label17: TLabel; edExtApp1: TEdit; btBrowseExtApp1: TButton; ckbWaitExtApp1: TCheckBox; Label18: TLabel; edExtApp2: TEdit; btBrowseExtApp2: TButton; ckbWaitExtApp2: TCheckBox; odExtExecutable: TOpenDialog; lvVolumes: TListView; btnAddVolume: TButton; btnEdit: TButton; btnDelete: TButton; seTimeOutBefore: TSpinEdit; Label10: TLabel; Label11: TLabel; seTimeOutAfter: TSpinEdit; Label12: TLabel; Label13: TLabel; lblSyncMode: TLabel; cbSyncMode: TComboBox; Label9: TLabel; cbDefAction: TComboBox; cbSendMail: TComboBox; cbSendMailContent: TComboBox; lblSendMail: TLabel; lblSendMailContent: TLabel; btnEditIncluded: TButton; btnEditExcluded: TButton; lblComression: TLabel; cbCompression: TComboBox; cbFileFormat: TComboBox; Label33: TLabel; Bevel1: TBevel; Bevel4: TBevel; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; Bevel5: TBevel; Bevel2: TBevel; Bevel3: TBevel; Bevel6: TBevel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSecurityClick(Sender: TObject); procedure edtMaxSizeKeyPress(Sender: TObject; var Key: char); procedure btnEditScheduleClick(Sender: TObject); procedure cbSchedulesKeyPress(Sender: TObject; var Key: char); procedure btnHelpClick(Sender: TObject); procedure btBrowseExtApp1Click(Sender: TObject); procedure btnAddVolumeClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure lvVolumesDblClick(Sender: TObject); procedure chkWriteLogClick(Sender: TObject); procedure btnEditIncludedClick(Sender: TObject); procedure btnEditExcludedClick(Sender: TObject); procedure cbFileFormatChange(Sender: TObject); procedure cbDefActionChange(Sender: TObject); private { Private declarations } FThread: TThread; FProject: TNSProject; FTask: TTaskItem; TaskDialog: TfrmTaskSettings; FPasswordSet: Boolean; FDisableTask: Boolean; procedure CheckPassword; procedure GetTaskProperties(AProject: TNSProject); procedure SetTaskProperties(AProject: TNSProject); procedure UpdateTask; procedure GetProperties(AProject: TNSProject); procedure SetProperties(AProject: TNSProject); protected procedure UpdateActions; override; procedure FillVolumes; procedure UpdateListItem(const AItem: TListItem); public { Public declarations } end; TScanThread = class(TThread) private FSize: int64; FFolderCount: integer; FFileCount: integer; FForm: TfrmProjectProperties; FProject: TNSProject; procedure Update; public constructor Create(AForm: TfrmProjectProperties; AProject: TNSProject); destructor Destroy; override; procedure Execute; override; end; function DisplayProjectPropertiesDialog(const AProject: TNSProject; DisableTask: Boolean = True): Boolean; implementation {$R *.dfm} uses nsSecSettingsFrm, nsUtils, nsActions, nsTaskPassword, nsMediaSettings, abMasksDlg, nsMainFrm; function DisplayProjectPropertiesDialog(const AProject: TNSProject; DisableTask: Boolean = True): Boolean; var dlg: TfrmProjectProperties; begin dlg := TfrmProjectProperties.Create(nil); try dlg.FDisableTask := DisableTask; dlg.GetTaskProperties(AProject); dlg.GetProperties(AProject); Result := dlg.ShowModal = mrOk; if Result then dlg.SetProperties(AProject); if Result then dlg.SetTaskProperties(AProject); finally FreeAndNil(dlg); end; end; { TProjectForm } procedure TfrmProjectProperties.GetProperties(AProject: TNSProject); var da: TDefaultAction; sm: TSyncMode; begin PageControl.ActivePageIndex := 0; // FProject := AProject; FProject := TNSProject.Create(nil); AssignVolumes(AProject, FProject); FThread := TScanThread.Create(Self, AProject); Caption := Format(sProperties, [AProject.DisplayName]); edtTitle.Text := AProject.DisplayName; lblEncryption.Caption := Encryptions[AProject.EncryptionMethod]^; chkWriteLog.Checked := AProject.WriteLog; edtInclude.Text := AProject.IncMasks.GetMask; edtExclude.Text := AProject.ExcMasks.GetMask; for da := Low(TDefaultAction) to High(TDefaultAction) do cbDefAction.Items.Add(ActionNames[da]^); cbDefAction.ItemIndex := Ord(AProject.DefaultAction); for sm := Low(TSyncMode) to High(TSyncMode) do cbSyncMode.Items.Add(SyncModeNames[sm]^); cbSyncMode.ItemIndex := Ord(AProject.SyncMode); cbSendMail.ItemIndex := Ord(AProject.SendLog); cbSendMailContent.ItemIndex := Ord(AProject.SendMailContect); chkWriteLogClick(Self); cbFileFormat.ItemIndex := Ord(AProject.FileFormat); cbCompression.ItemIndex := AProject.CompressionLevel; cbFileFormatChange(Self); edExtApp1.Text := AProject.ExtAppBefore; ckbWaitExtApp1.Checked := AProject.WaitForExtAppBefore; edExtApp2.Text := AProject.ExtAppAfter; ckbWaitExtApp2.Checked := AProject.WaitForExtAppAfter; seTimeOutBefore.Value := AProject.TimeOutBefore; seTimeOutAfter.Value := AProject.TimeOutAfter; FillVolumes; end; procedure TfrmProjectProperties.SetProperties(AProject: TNSProject); begin AssignVolumes(FProject, AProject); AProject.DisplayName := edtTitle.Text; AProject.Kind := AProject.Kind; AProject.WriteLog := chkWriteLog.Checked; AProject.IncMasks.SetMask(edtInclude.Text); AProject.IncMasks := AProject.IncMasks; AProject.ExcMasks.SetMask(edtExclude.Text); AProject.ExcMasks := AProject.ExcMasks; AProject.ReInitCrypting; // AProject.ProjPwd := AProject.ProjPwd; // AProject.EncryptionMethod := FProject.EncryptionMethod; if AProject.Items.Count = 0 then AProject.DefaultAction := TDefaultAction(cbDefAction.ItemIndex) else if AProject.DefaultAction <> TDefaultAction(cbDefAction.ItemIndex) then begin if MessageDlg(Format(sConfirmApplyDefAction, [ActionNames[TDefaultAction(cbDefAction.ItemIndex)]^]), mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin AProject.DefaultAction := TDefaultAction(cbDefAction.ItemIndex); ChangeDefAction(nil, AProject.DefaultAction); end; end; AProject.SendLog := TSendMail(cbSendMail.ItemIndex); AProject.SendMailContect := TSendMailContent(cbSendMailContent.ItemIndex); AProject.CompressionLevel := cbCompression.ItemIndex; AProject.ExtAppBefore := edExtApp1.Text; AProject.WaitForExtAppBefore := ckbWaitExtApp1.Checked; AProject.ExtAppAfter := edExtApp2.Text; AProject.WaitForExtAppAfter := ckbWaitExtApp2.Checked; AProject.TimeOutBefore := seTimeOutBefore.Value; AProject.TimeOutAfter := seTimeOutAfter.Value; if AProject.VolumeCount > 1 then AProject.SyncMode := TSyncMode(cbSyncMode.ItemIndex) else AProject.SyncMode := smIndependent; // AProject.FileFormat := TFileFormat(cbFileFormat.ItemIndex); end; procedure TfrmProjectProperties.UpdateTask; begin try lblSchedule.Caption := FTask.TriggerText; except on E: Exception do lblSchedule.Caption := E.Message; end; end; procedure TfrmProjectProperties.GetTaskProperties(AProject: TNSProject); var sTaskAccount: string; begin if not frmMain.TaskManager.Active then Exit; FTask := frmMain.TaskManager.ActivateTask(AProject.DisplayName); if FTask <> nil then begin FPasswordSet := True; try sTaskAccount := FTask.Account; except FPasswordSet := False; end; end else try FTask := frmMain.TaskManager.CreateTask(AProject.DisplayName); FTask.AppName := Application.ExeName; except FPasswordSet := False; end; UpdateTask; end; procedure TfrmProjectProperties.SetTaskProperties(AProject: TNSProject); begin if (FTask <> nil) then begin if FTask.Triggers.Count > 0 then begin FTask.AppName := Application.ExeName; FTask.WorkDir := g_ProjectsDir; FTask.Creator := Application.Title; if FDisableTask then FTask.Flags := FTask.Flags - [tfEnabled]; FTask.Arguments := sUpdate + #34 + AProject.FileName + #34; FTask.SaveTask; end else begin FTask.SaveTask; FTask := nil; end; end; end; procedure TfrmProjectProperties.CheckPassword; var Accnt: WideString; Pwd: WideString; begin if SysUtils.Win32Platform <> VER_PLATFORM_WIN32_NT then Exit; if not FPasswordSet and (FTask.Triggers.Count > 0) then begin FPasswordSet := SetTaskPassword(Accnt, Pwd); if FPasswordSet then begin FTask.SetAccount(Accnt, Pwd); end; end; end; procedure TfrmProjectProperties.FillVolumes; var Project: TNSProject; Index: integer; Item: TListItem; begin lvVolumes.Items.Clear; for Index := 0 to FProject.VolumeCount - 1 do begin Project := FProject.Volumes[Index]; Item := lvVolumes.Items.Add; Item.Data := Project; UpdateListItem(Item); end; if lvVolumes.CanFocus then lvVolumes.SetFocus; Self.Update; end; procedure TfrmProjectProperties.UpdateListItem(const AItem: TListItem); var Project: TNSProject; begin Project := TNSProject(AItem.Data); AItem.Caption := Format(sVolume, [Project.VolumeIndex]); AItem.SubItems.Text := #13#10#13#10; AItem.SubItems[0] := BackupMediaNames[Project.BackupMedia]^; AItem.SubItems[1] := Project.GetVolumeString(False); end; procedure TfrmProjectProperties.UpdateActions; begin inherited UpdateActions; btnEdit.Enabled := lvVolumes.Selected <> nil; btnDelete.Enabled := (lvVolumes.Selected <> nil) and (lvVolumes.Selected.Index > 0); seTimeOutBefore.Enabled := ckbWaitExtApp1.Checked; seTimeOutAfter.Enabled := ckbWaitExtApp2.Checked; cbSyncMode.Enabled := lvVolumes.Items.Count > 1; lblSyncMode.Enabled := cbSyncMode.Enabled; btnEditSchedule.Enabled := FTask <> nil; end; { TScanThread } constructor TScanThread.Create(AForm: TfrmProjectProperties; AProject: TNSProject); begin inherited Create(True); FForm := AForm; FProject := AProject; Priority := tpLower; FreeOnTerminate := True; Execute; // FIX // Resume; end; destructor TScanThread.Destroy; begin FForm.FThread := nil; inherited Destroy; end; procedure TScanThread.Execute; var Index: integer; Volume: TNSProject; procedure ScanSubItems(const AItem: TPersistent); var Index: integer; CurItem: TNSItem; Collection: TNSCollection; begin if AItem is TNSProject then Collection := TNSProject(AItem).Items else Collection := TNSItem(AItem).SubItems; Synchronize(Update); for Index := 0 to Collection.Count - 1 do begin CurItem := Collection[Index]; if CurItem.IsFolder then begin Inc(FFolderCount); ScanSubItems(CurItem); end else begin Inc(FFileCount); FSize := FSize + CurItem.SizeOnMedia; end; end; end; begin FSize := 0; for Index := 0 to FProject.VolumeCount - 1 do begin Volume := FProject.Volumes[Index]; ScanSubItems(Volume); Synchronize(Update); end; end; procedure TScanThread.Update; begin with FForm do begin lblSize.Caption := FormatSize(FSize, True); lblContains.Caption := Format(sFFInfo, [FFileCount, FFolderCount]); end; end; procedure TfrmProjectProperties.FormDestroy(Sender: TObject); begin if Assigned(FProject) then FreeAndNil(FProject); if Assigned(FThread) then FThread.Terminate; end; procedure TfrmProjectProperties.btnSecurityClick(Sender: TObject); begin if DisplaySecSettingsDialog(Self, FProject) then lblEncryption.Caption := Encryptions[FProject.EncryptionMethod]^; // lblKind.Caption := ProjectKindNames[FProject.Kind]^; end; procedure TfrmProjectProperties.edtMaxSizeKeyPress(Sender: TObject; var Key: char); begin if not CharInSet(Key, [Chr(VK_BACK), '0'..'9']) then Key := #0; end; procedure TfrmProjectProperties.btnEditScheduleClick(Sender: TObject); begin if FTask = nil then Exit; try TaskDialog.TaskItem := FTask; if TaskDialog.Execute then begin UpdateTask; CheckPassword; end; except end; end; procedure TfrmProjectProperties.FormCreate(Sender: TObject); begin TaskDialog := TfrmTaskSettings.Create(Self); TaskDialog.TaskScheduler := frmMain.TaskManager; grpSchedules.Visible := True; end; procedure TfrmProjectProperties.cbSchedulesKeyPress(Sender: TObject; var Key: char); begin Key := #0; end; procedure TfrmProjectProperties.btnHelpClick(Sender: TObject); begin Application.HelpSystem.ShowContextHelp(PageControl.ActivePage.HelpContext, Application.HelpFile); end; procedure TfrmProjectProperties.btBrowseExtApp1Click(Sender: TObject); begin Self.Enabled := False; try if TComponent(Sender).Tag = 0 then odExtExecutable.FileName := edExtApp1.Text else odExtExecutable.FileName := edExtApp2.Text; if not FileExists(odExtExecutable.FileName) then odExtExecutable.FileName := EmptyStr; if not odExtExecutable.Execute then Exit; if TComponent(Sender).Tag = 0 then edExtApp1.Text := odExtExecutable.FileName else edExtApp2.Text := odExtExecutable.FileName; finally Self.Enabled := True; end; end; procedure TfrmProjectProperties.btnAddVolumeClick(Sender: TObject); var NewProject: TNSProject; Item: TListItem; begin NewProject := FProject.AddVolume; if EditMediaSettingsDlg(NewProject) then begin Item := lvVolumes.Items.Add; Item.Data := NewProject; UpdateListItem(Item); end else begin NewProject.Free; end; end; procedure TfrmProjectProperties.btnEditClick(Sender: TObject); var Project: TNSProject; begin if (lvVolumes.Selected = nil) or (lvVolumes.Selected.Data = nil) then Exit; Project := TNSProject(lvVolumes.Selected.Data); if EditMediaSettingsDlg(Project, True) then UpdateListItem(lvVolumes.Selected); end; procedure TfrmProjectProperties.btnDeleteClick(Sender: TObject); var Item: TListItem; Project: TNSProject; begin Item := lvVolumes.Selected; if (Item = nil) or (Item.Data = nil) or (Item.Index = 0) then Exit; Project := TNSProject(Item.Data); if MessageDlg(Format(sConfirmDeleteVolume, [Project.GetVolumeString]), mtWarning, [mbYes, mbNo], 0) = mrYes then begin Project.Free; FillVolumes; end; // lvVolumes.Items.Delete(Item.Index); end; procedure TfrmProjectProperties.lvVolumesDblClick(Sender: TObject); begin btnEdit.Click; end; procedure TfrmProjectProperties.chkWriteLogClick(Sender: TObject); begin if chkWriteLog.Checked then begin lblSendMail.Enabled := True; cbSendMail.Enabled := True; lblSendMailContent.Enabled := True; cbSendMailContent.Enabled := True; end else begin lblSendMail.Enabled := False; cbSendMail.Enabled := False; lblSendMailContent.Enabled := False; cbSendMailContent.Enabled := False; end; end; procedure TfrmProjectProperties.btnEditIncludedClick(Sender: TObject); var S: string; begin S := edtInclude.Text; if EditMasksDlg(lblIncluded.Caption, S) then edtInclude.Text := S; end; procedure TfrmProjectProperties.btnEditExcludedClick(Sender: TObject); var S: string; begin S := edtExclude.Text; if EditMasksDlg(lblExcluded.Caption, S) then edtExclude.Text := S; end; procedure TfrmProjectProperties.cbFileFormatChange(Sender: TObject); begin lblEncType.Enabled := cbFileFormat.ItemIndex = 0; lblEncryption.Enabled := cbFileFormat.ItemIndex = 0; btnSecurity.Enabled := cbFileFormat.ItemIndex = 0; lblComression.Enabled := cbFileFormat.ItemIndex = 0; cbCompression.Enabled := cbFileFormat.ItemIndex = 0; end; procedure TfrmProjectProperties.cbDefActionChange(Sender: TObject); begin if cbFileFormat.ItemIndex = 1 then // As Is if cbDefAction.ItemIndex = 2 then cbDefAction.ItemIndex := 1; end; end.
unit MVVM.CommandFactory; interface uses System.Rtti, System.Classes, Spring.Collections, MVVM.Rtti, MVVM.Interfaces, MVVM.Types; type TCommandsFactory = class {$REGION 'Internal Declarations'} private FRegisteredActionMembers: IDictionary<String, RActionMember>; FRegisteredCommands: IList<RCommand>; protected //Actions procedure CheckMethodIsRightActionMemberType(const AActionMemberType: EActionMemberType; const AMethod: TRttiMethod); //basic test procedure RegisterActionMember(const AName: string; const ACaption: String; const AActionMemberType: EActionMemberType; const AMethod: TRttiMethod; const AOwner: TObject); function TryGetActionMember(const AName: string; out AData: RActionMember): Boolean; //Commands procedure RegisterCommand(const AExecuteName: string; const ACanExecuteName: String; const AParamsName: string; const AOwner: TObject; const AField: TRttiField); public //class destructor Destroy; {$ENDREGION 'Internal Declarations'} public constructor Create; destructor Destroy; override; procedure LoadCommandsAndActionsFrom(const AObject: TObject); procedure BindView(const AView: TComponent); end; implementation uses System.TypInfo, System.SysUtils, MVVM.Utils, MVVM.Attributes; { TCommandFactory } procedure TCommandsFactory.BindView(const AView: TComponent); var LCommand : RCommand; LExecute : RActionMember; LCanExecute: RActionMember; LParams : RActionMember; LUseCanExecute : Boolean; LUseParams : Boolean; LBindableAction: IBindableAction; LObject : TObject; begin for LCommand in FRegisteredCommands do begin if (LCommand.Owner = AView) then //if the View is the good one begin LUseCanExecute:= False; LUseParams := False; // Execute if not TryGetActionMember(LCommand.ExecuteName, LExecute) then raise ExceptionActionMemberNotFound.Create('Action Member not found: ' + LCommand.ExecuteName); // CanExecute if not LCommand.CanExecuteName.IsEmpty then begin if not TryGetActionMember(LCommand.CanExecuteName, LCanExecute) then raise ExceptionActionMemberNotFound.Create('Action Member not found: ' + LCommand.CanExecuteName); LUseCanExecute := True; end; // Params if not LCommand.ParamsName.IsEmpty then begin if not TryGetActionMember(LCommand.ParamsName, LParams) then raise ExceptionActionMemberNotFound.Create('Action Member not found: ' + LCommand.ParamsName); LUseParams := True; end; LObject := LCommand.Field.GetValue(LCommand.Owner).AsType<TObject>; if Supports(LObject, IBindableAction, LBindableAction) then begin LBindableAction.Bind(LExecute.Method, LExecute.Owner, Utils.iif<TRttiMethod>(LUseCanExecute, LCanExecute.Method, nil), Utils.iif<TObject>(LUseCanExecute, LCanExecute.Owner, nil), Utils.iif<TRttiMethod>(LUseParams, LParams.Method, nil), Utils.iif<TObject>(LUseParams, LParams.Owner, nil)); end; end; end; end; procedure TCommandsFactory.CheckMethodIsRightActionMemberType(const AActionMemberType: EActionMemberType; const AMethod: TRttiMethod); begin (* case AActionMemberType of OnExecute: begin if AMethod.MethodKind <> TMethodKind.mkProcedure then raise ExceptionActionMemberTypeError.Create('The member type or the method are wrong'); end; OnUpdate: begin if AMethod.MethodKind <> TMethodKind.mkFunction then raise ExceptionActionMemberTypeError.Create('The member type or the method are wrong'); end; OnAsyncExecutionFinished: begin if AMethod.MethodKind <> TMethodKind.mkProcedure then raise ExceptionActionMemberTypeError.Create('The member type or the method are wrong'); end; OnParams: begin if AMethod.MethodKind <> TMethodKind.mkFunction then raise ExceptionActionMemberTypeError.Create('The member type or the method are wrong'); end; end; *) end; constructor TCommandsFactory.Create; begin inherited; FRegisteredActionMembers := TCollections.CreateDictionary<String, RActionMember>; FRegisteredCommands := TCollections.CreateList<RCommand>; end; destructor TCommandsFactory.Destroy; begin FRegisteredActionMembers := nil; FRegisteredCommands := nil; inherited; end; function TCommandsFactory.TryGetActionMember(const AName: string; out AData: RActionMember): Boolean; var LName: string; begin if AName.IsEmpty then raise ExceptionActionMemberNameCannotBeEmpty.Create('Member name cannot be empty'); LName := AName.ToUpper; Result := FRegisteredActionMembers.TryGetValue(LName, AData); end; procedure TCommandsFactory.LoadCommandsAndActionsFrom(const AObject: TObject); var Ctx: TRttiContext; Typ: TRttiType; LMethod: TRttiMethod; LField: TRttiField; LProperty: TRttiProperty; LAttr: TCustomAttribute; LActionMember: ActionMember; LCommand: Command; // LTValueMethod: TValue; begin Ctx := TRttiContext.Create; try //for Typ in Ctx.GetTypes do //begin // Loop for Method attributes (* for LMethod in Typ.GetMethods do begin for LAttr in LMethod.GetAttributes do begin case Utils.AttributeToCaseSelect(LAttr, [ActionMember]) of 0: // ActionMember begin LActionMember := LAttr as ActionMember; LConverted := Ctx.GetType(TypeInfo(LMethod.CodeAddress)) as TRttiInvokableType; if LTmp is TRttiInvokableType then ; //LConverted := LMethod as TRttiInvokableType; // LTValueMethod := LMethod. as //RegisterActionMember(LActionMember.Name, LActionMember.Caption, LActionMember.MemberType, LMethod, AObject); end; end; end; end; *) Typ := ctx.GetType(AObject.ClassInfo); //ClassType // Loop for Properties attributes for LProperty in Typ.GetProperties do begin for LAttr in LProperty.GetAttributes do begin case Utils.AttributeToCaseSelect(LAttr, [ActionMember]) of 0: // ActionMember begin LActionMember := LAttr as ActionMember; LMethod := LProperty.GetterMethod(AObject); if Assigned(LMethod) then RegisterActionMember(LActionMember.Name, LActionMember.Caption, LActionMember.MemberType, LMethod, AObject); end; end; end; end; // Loop for Method attributes for LMethod in Typ.GetMethods do begin for LAttr in LMethod.GetAttributes do begin case Utils.AttributeToCaseSelect(LAttr, [ActionMember]) of 0: // ActionMember begin LActionMember := LAttr as ActionMember; RegisterActionMember(LActionMember.Name, LActionMember.Caption, LActionMember.MemberType, LMethod, AObject); end; end; end; end; // Loop for Field attributes for LField in Typ.GetFields do begin for LAttr in LField.GetAttributes do begin case Utils.AttributeToCaseSelect(LAttr, [Command, ActionMember]) of 0: // Command begin LCommand := LAttr as Command; RegisterCommand(LCommand.ExecuteName, LCommand.CanExecuteName, LCommand.ParamsName, AObject, LField); end; end; end; end; finally Ctx.Free; end; end; procedure TCommandsFactory.RegisterActionMember(const AName, ACaption: String; const AActionMemberType: EActionMemberType; const AMethod: TRttiMethod; const AOwner: TObject); var LName: string; LData: RActionMember; begin LName := AName.ToUpper; //Utils.IdeDebugMsg('<TCommandsFactory.RegisterActionMember> ' + AName); if LName.IsEmpty then begin LName := AMethod.Name.ToUpper; // For future uses end; if FRegisteredActionMembers = nil then FRegisteredActionMembers := TCollections.CreateDictionary<String, RActionMember>; if FRegisteredActionMembers.ContainsKey(LName) then raise ExceptionActionMemberTypeDuplicated.Create('The Name is already used: ' + AName); LData.Name := LName; LData.Caption := ACaption; LData.MemberType := AActionMemberType; LData.Method := AMethod; LData.Owner := AOwner; //Integrity Checking CheckMethodIsRightActionMemberType(AActionMemberType, AMethod); FRegisteredActionMembers[LName] := LData; end; procedure TCommandsFactory.RegisterCommand(const AExecuteName, ACanExecuteName, AParamsName: string; const AOwner: TObject; const AField: TRttiField); var LCommand: RCommand; begin LCommand.ExecuteName := AExecuteName; LCommand.CanExecuteName := ACanExecuteName; LCommand.ParamsName := AParamsName; LCommand.Owner := AOwner; LCommand.Field := AField; if FRegisteredCommands = nil then FRegisteredCommands := TCollections.CreateList<RCommand>; FRegisteredCommands.Add(LCommand); end; end.