text
stringlengths
14
6.51M
unit notifieru; interface uses Windows, Messages, Classes, SysUtils, Forms, declu; type _Notifier = class private hWnd: uint; FWndInstance: TFarProc; FPrevWndProc: TFarProc; FActivating: boolean; x: integer; y: integer; need_x: integer; need_y: integer; awidth: integer; aheight: integer; showtime: uint; active: boolean; alert: boolean; timeout: cardinal; monitor: integer; current_text: string; procedure err(where: string; e: Exception); public texts: TStrings; constructor Create; destructor Destroy; override; function GetMonitorRect(monitor: integer): Windows.TRect; procedure Message(Text: string; monitor: integer = 0; alert: boolean = false; silent: boolean = false); procedure Message_Internal(Caption, Text: string; monitor: integer; animate: boolean = True); procedure Close; procedure Timer; procedure WindowProc(var msg: TMessage); end; var Notifier: _Notifier; implementation uses GDIPAPI, gdip_gfx, toolu, dwm_unit; //------------------------------------------------------------------------------ constructor _Notifier.Create; begin inherited; active := False; texts := TStringList.Create; current_text := ''; // create window // hWnd := 0; try hWnd := CreateWindowEx(ws_ex_layered or ws_ex_toolwindow, WINITEM_CLASS, nil, ws_popup, 0, 0, 0, 0, 0, 0, hInstance, nil); if IsWindow(hWnd) then begin SetWindowLong(hWnd, GWL_USERDATA, cardinal(self)); FWndInstance := MakeObjectInstance(WindowProc); FPrevWndProc := Pointer(GetWindowLong(hWnd, GWL_WNDPROC)); SetWindowLong(hWnd, GWL_WNDPROC, LongInt(FWndInstance)); end else err('Notifier.Create.CreateWindowEx failed', nil); except on e: Exception do err('Notifier.Create.CreateWindow', e); end; end; //------------------------------------------------------------------------------ destructor _Notifier.Destroy; begin try // restore window proc if assigned(FPrevWndProc) then SetWindowLong(hWnd, GWL_WNDPROC, LongInt(FPrevWndProc)); DestroyWindow(hWnd); if assigned(texts) then texts.Free; inherited; except on e: Exception do err('Notifier.Destroy', e); end; end; //------------------------------------------------------------------------------ function _Notifier.GetMonitorRect(monitor: integer): Windows.TRect; begin result.Left := 0; result.Top := 0; result.Right := screen.Width; result.Bottom := screen.Height; if monitor >= screen.MonitorCount then monitor := screen.MonitorCount - 1; if monitor >= 0 then Result := screen.Monitors[monitor].WorkareaRect; end; //------------------------------------------------------------------------------ procedure _Notifier.Message(Text: string; monitor: integer = 0; alert: boolean = false; silent: boolean = false); begin if alert then AddLog('!' + text) else AddLog(text); try texts.add('[' + formatdatetime('dd/MM/yyyy hh:nn:ss', now) + '] ' + Text); self.alert := self.alert or alert; if not silent or alert then begin timeout := 8000; if length(Text) > 50 then timeout := 15000 else if length(Text) > 30 then timeout := 11000; if current_text = '' then current_text := Text else current_text := current_text + #13#10#13#10 + Text; Message_Internal('Terry', current_text, monitor, true); end; except on e: Exception do err('Notifier.Message', e); end; end; //------------------------------------------------------------------------------ procedure _Notifier.Message_Internal(Caption, Text: string; monitor: integer; animate: boolean = True); var hgdip, path, hbrush, hpen: Pointer; caption_font, message_font, caption_font_family, message_font_family: Pointer; caption_rect, text_rect: TRectF; message_margin, wa: Windows.TRect; bmp: _SimpleBitmap; h_split, radius: integer; rgn: HRGN; alpha: uint; acoeff: integer; begin if FActivating then exit; self.monitor := monitor; FActivating := True; radius := 3; h_split := 3; awidth := 240; message_margin.left := radius * 2 div 3 + 3; message_margin.right := radius * 2 div 3 + 3; message_margin.top := radius * 2 div 3 + 3; message_margin.bottom := radius * 2 div 3 + 3; // context // try bmp.dc := CreateCompatibleDC(0); if bmp.dc = 0 then begin err('Notifier.Message_Internal'#10#13'Unable to create device context', nil); FActivating := False; exit; end; hgdip := CreateGraphics(bmp.dc, 0); if not assigned(hgdip) then begin err('Notifier.Message_Internal.Context CreateGraphics failed', nil); exit; end; except on e: Exception do begin err('Notifier.Message_Internal.Context', e); FActivating := False; exit; end; end; // context // try GdipCreateFontFamilyFromName(PWideChar(WideString(GetFont)), nil, caption_font_family); GdipCreateFontFamilyFromName(PWideChar(WideString(GetContentFont)), nil, message_font_family); GdipCreateFont(caption_font_family, 16, 1, 2, caption_font); GdipCreateFont(message_font_family, 14, 0, 2, message_font); except on e: Exception do begin err('Notifier.Message_Internal.Fonts', e); FActivating := False; exit; end; end; // measure // try caption_rect.x := 0; caption_rect.y := 0; caption_rect.Width := awidth - message_margin.left - message_margin.right; caption_rect.Height := 0; GdipMeasureString(hgdip, PWideChar(WideString(Caption)), -1, caption_font, @caption_rect, nil, @caption_rect, nil, nil); caption_rect.Height := caption_rect.Height + 1; text_rect.x := 0; text_rect.y := 0; text_rect.Width := awidth - message_margin.left - message_margin.right; text_rect.Height := 0; GdipMeasureString(hgdip, PWideChar(WideString(Text)), -1, message_font, @text_rect, nil, @text_rect, nil, nil); text_rect.Height := text_rect.Height + 1; caption_rect.x := message_margin.left; caption_rect.y := message_margin.top; text_rect.x := message_margin.left; text_rect.y := caption_rect.y + caption_rect.Height + h_split; if assigned(hgdip) then GdipDeleteGraphics(hgdip); if bmp.dc > 0 then DeleteDC(bmp.dc); aheight := message_margin.top + trunc(caption_rect.Height) + h_split + trunc(text_rect.Height) + message_margin.bottom; // calc position // wa := GetMonitorRect(monitor); need_x := wa.right - awidth - 2; x := wa.right - awidth div 2 - 2; need_y := wa.bottom - aheight - 2; y := need_y; if not animate then begin x := need_x; y := need_y; end; except on e: Exception do begin err('Notifier.Message_Internal.Measure', e); FActivating := False; exit; end; end; // prepare drawing // try bmp.topleft.x := x; bmp.topleft.y := y; bmp.Width := awidth; bmp.Height := aheight; if not gdip_gfx.CreateBitmap(bmp) then begin err('Notifier.Message_Internal.Prepare CreateBitmap failed', nil); exit; end; hgdip := CreateGraphics(bmp.dc, 0); if not assigned(hgdip) then begin err('Notifier.Message_Internal.Prepare CreateGraphics failed', nil); exit; end; GdipSetTextRenderingHint(hgdip, TextRenderingHintAntiAlias); GdipSetSmoothingMode(hgdip, SmoothingModeAntiAlias); except on e: Exception do begin err('Notifier.Message_Internal.Prepare', e); FActivating := False; exit; end; end; // background // try GdipCreatePath(FillModeAlternate, path); GdipStartPathFigure(path); GdipAddPathLine(path, radius, 0, awidth - radius - 1, 0); GdipAddPathArc(path, awidth - radius * 2 - 1, 0, radius * 2, radius * 2, 270, 90); GdipAddPathLine(path, awidth - 1, radius, awidth - 1, aheight - radius - 1); GdipAddPathArc(path, awidth - radius * 2 - 1, aheight - radius * 2 - 1, radius * 2, radius * 2, 0, 90); GdipAddPathLine(path, awidth - radius - 1, aheight - 1, radius, aheight - 1); GdipAddPathArc(path, 0, aheight - radius * 2 - 1, radius * 2, radius * 2, 90, 90); GdipAddPathLine(path, 0, aheight - radius - 1, 0, radius); GdipAddPathArc(path, 0, 0, radius * 2, radius * 2, 180, 90); GdipClosePathFigure(path); if dwm.CompositingEnabled then alpha := $40000000 else alpha := $ff101010; GdipCreateSolidFill(alpha, hbrush); GdipFillPath(hgdip, hbrush, path); GdipDeleteBrush(hbrush); GdipCreatePen1($50ffffff, 1, UnitPixel, hpen); GdipDrawPath(hgdip, hpen, path); GdipDeletePen(hpen); GdipDeletePath(path); except on e: Exception do begin err('Notifier.Message_Internal.Backgroud', e); FActivating := False; exit; end; end; // message caption and text // try if alert then GdipCreateSolidFill($ffff5000, hbrush) else GdipCreateSolidFill($ffffffff, hbrush); GdipDrawString(hgdip, PWideChar(WideString(Caption)), -1, caption_font, @caption_rect, nil, hbrush); GdipDeleteBrush(hbrush); if alert then GdipCreateSolidFill($ffff5000, hbrush) else GdipCreateSolidFill($ffffffff, hbrush); GdipDrawString(hgdip, PWideChar(WideString(Text)), -1, message_font, @text_rect, nil, hbrush); GdipDeleteBrush(hbrush); except on e: Exception do begin err('Notifier.Message_Internal.MessageCaptionAndText', e); FActivating := False; exit; end; end; // show // try acoeff := 255; if animate then begin acoeff := 255 - (abs(x - need_x) * 510 div awidth); if acoeff < 0 then acoeff := 0; if acoeff > 255 then acoeff := 255; end; gdip_gfx.UpdateLWindow(hWnd, bmp, acoeff); SetWindowPos(hWnd, $ffffffff, 0, 0, 0, 0, swp_noactivate + swp_nomove + swp_nosize + swp_showwindow); if dwm.CompositingEnabled then begin rgn := CreateRoundRectRgn(0, 0, awidth, aheight, radius * 2, radius * 2); DWM.EnableBlurBehindWindow(hWnd, rgn); DeleteObject(rgn); end else DWM.DisableBlurBehindWindow(hWnd); except on e: Exception do begin err('Notifier.Message_Internal.Show', e); FActivating := False; exit; end; end; // cleanup // try GdipDeleteFont(caption_font); GdipDeleteFont(message_font); GdipDeleteFontFamily(caption_font_family); GdipDeleteFontFamily(message_font_family); GdipDeleteGraphics(hgdip); gdip_gfx.DeleteBitmap(bmp); except on e: Exception do begin err('Notifier.Message_Internal.Cleanup', e); FActivating := False; exit; end; end; showtime := gettickcount; if not active then SetTimer(hWnd, ID_TIMER, 10, nil); active := True; FActivating := False; end; //------------------------------------------------------------------------------ procedure _Notifier.Timer; var delta: integer; set_pos: boolean; acoeff: integer; begin if active then try acoeff := 255 - (abs(x - need_x) * 510 div awidth); if acoeff < 0 then acoeff := 0; if acoeff > 255 then acoeff := 255; set_pos := boolean(need_x - x + need_y - y <> 0); delta := abs(need_x - x) div 6; if delta < 1 then delta := 1; if x > need_x then Dec(x, delta); if x < need_x then Inc(x, delta); delta := abs(need_y - y) div 6; if delta < 1 then delta := 1; if y > need_y then Dec(y, delta); if y < need_y then Inc(y, delta); if set_pos then UpdateLWindowPosAlpha(hWnd, x, y, acoeff); if (x <> need_x) or (y <> need_y) then showtime := gettickcount else if not alert then if gettickcount - showtime > timeout then Close; except on e: Exception do err('Notifier.Timer', e); end; end; //------------------------------------------------------------------------------ procedure _Notifier.Close; begin try DWM.DisableBlurBehindWindow(hWnd); KillTimer(hWnd, ID_TIMER); ShowWindow(hWnd, 0); active := False; alert := False; current_text := ''; except on e: Exception do err('Notifier.Close', e); end; end; //------------------------------------------------------------------------------ procedure _Notifier.WindowProc(var msg: TMessage); begin msg.Result := 0; if (msg.msg = wm_lbuttondown) or (msg.msg = wm_rbuttonup) then begin Close; exit; end else if msg.msg = WM_TIMER then begin Timer; exit; end; msg.Result := DefWindowProc(hWnd, msg.msg, msg.wParam, msg.lParam); end; //------------------------------------------------------------------------------ procedure _Notifier.err(where: string; e: Exception); begin if assigned(e) then begin AddLog(where + #10#13 + e.message); messagebox(hWnd, PChar(where + #10#13 + e.message), 'Terry', MB_ICONERROR) end else begin AddLog(where); messagebox(hWnd, PChar(where), 'Terry', MB_ICONERROR); end; end; //------------------------------------------------------------------------------ end.
unit FileAPI; interface procedure CreatePath(EndDir: string); { Создаёт иерархию каталогов до конечного каталога включительно. Допускаются разделители: "\" и "/" } function ExtractFileDir(Path: string): string; { Извлекает путь к файлу. Допускаются разделители: "\" и "/" } function ExtractFileName(Path: string): string; { Извлекает имя файла. Допускаются разделители: "\" и "/" } function ExtractHost(Path: string): string; { Извлекает имя хоста из сетевого адреса. http://site.ru/folder/script.php --> site.ru } function ExtractObject(Path: string): string; { Извлекает имя объекта из сетевого адреса: http://site.ru/folder/script.php --> folder/script.php } implementation function CreateDirectory( PathName: PChar; lpSecurityAttributes: Pointer ): LongBool; stdcall; external 'kernel32.dll' name 'CreateDirectoryA'; // Процедуры работы с файловой системой и адресами: // Допускаются разделители "\" и "/" // Создаёт иерархию папок до конечной указанной папки включительно: procedure CreatePath(EndDir: string); var I: LongWord; PathLen: LongWord; TempPath: string; begin PathLen := Length(EndDir); if (EndDir[PathLen] = '\') or (EndDir[PathLen] = '/') then Dec(PathLen); TempPath := Copy(EndDir, 0, 3); for I := 4 to PathLen do begin if (EndDir[I] = '\') or (EndDir[I] = '/') then CreateDirectory(PAnsiChar(TempPath), nil); TempPath := TempPath + EndDir[I]; end; CreateDirectory(PAnsiChar(TempPath), nil); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Получает каталог, в котором лежит файл: function ExtractFileDir(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := PathLen; while (I <> 0) and (Path[I] <> '\') and (Path[I] <> '/') do Dec(I); Result := Copy(Path, 0, I); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Получает имя файла: function ExtractFileName(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := PathLen; while (Path[I] <> '\') and (Path[I] <> '/') and (I <> 0) do Dec(I); Result := Copy(Path, I + 1, PathLen - I); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Извлекает имя хоста: // http://site.ru/folder/script.php --> site.ru function ExtractHost(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := 8; // Длина "http://" while (I <= PathLen) and (Path[I] <> '\') and (Path[I] <> '/') do Inc(I); Result := Copy(Path, 8, I - 8); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Извлекает имя объекта: // http://site.ru/folder/script.php --> folder/script.php function ExtractObject(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := 8; while (I <= PathLen) and (Path[I] <> '\') and (Path[I] <> '/') do Inc(I); Result := Copy(Path, I + 1, PathLen - I); end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvFullColorListFrm.pas, released on 2004-09-27. The Initial Developer of the Original Code is Florent Ouchet [ouchet dott florent att laposte dott net] Portions created by Florent Ouchet are Copyright (C) 2004 Florent Ouchet. All Rights Reserved. Contributor(s): - You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id$ unit JvFullColorListForm; {$mode objfpc}{$H+} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ActnList, Buttons, ImgList, JvFullColorSpaces, JvFullColorDialogs, JvFullColorCtrls; type { TJvFullColorListFrm } TJvFullColorListFrm = class(TForm) ImageList: TImageList; JvFullColorDialog: TJvFullColorDialog; ListBoxColors: TListBox; ActionList: TActionList; ActionNew: TAction; ActionModify: TAction; ActionDelete: TAction; ButtonNew: TButton; ButtonModify: TButton; ButtonDelete: TButton; ButtonCancel: TButton; ButtonOK: TButton; BitBtnMoveUp: TBitBtn; ActionMoveUp: TAction; ActionMoveDown: TAction; BitBtnMoveDown: TBitBtn; ButtonApply: TButton; ButtonClear: TButton; ActionClear: TAction; ButtonInsert: TButton; ActionInsert: TAction; procedure ActionNewUpdate(Sender: TObject); procedure ActionModifyUpdate(Sender: TObject); procedure ActionDeleteUpdate(Sender: TObject); procedure ActionMoveUpUpdate(Sender: TObject); procedure ActionMoveDownUpdate(Sender: TObject); procedure ActionNewExecute(Sender: TObject); procedure ActionClearUpdate(Sender: TObject); procedure ActionModifyExecute(Sender: TObject); procedure ActionInsertUpdate(Sender: TObject); procedure ActionClearExecute(Sender: TObject); procedure ActionDeleteExecute(Sender: TObject); procedure ActionInsertExecute(Sender: TObject); procedure ActionMoveUpExecute(Sender: TObject); procedure ActionMoveDownExecute(Sender: TObject); procedure ButtonApplyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure JvFullColorDialogApply(Sender: TObject; AFullColor: TJvFullColor); procedure ListBoxColorsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); private FColorList: TJvFullColorList; FOnApply: TNotifyEvent; procedure SetColorList(const Value: TJvFullColorList); function GetColorList: TJvFullColorList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; property ColorList: TJvFullColorList read GetColorList write SetColorList; property OnApply: TNotifyEvent read FOnApply write FOnApply; end; var JvFullColorListFrm: TJvFullColorListFrm; implementation uses Math, LCLType, LCLIntf, LCLVersion, JvDsgnConsts; {$R *.lfm} constructor TJvFullColorListFrm.Create(AOwner: TComponent); begin inherited Create(AOwner); FColorList := TJvFullColorList.Create; end; destructor TJvFullColorListFrm.Destroy; begin FColorList.Free; inherited Destroy; end; procedure TJvFullColorListFrm.ActionClearExecute(Sender: TObject); begin ListBoxColors.Clear; end; procedure TJvFullColorListFrm.ActionClearUpdate(Sender: TObject); begin (Sender as TAction).Enabled := ListBoxColors.Items.Count > 0; end; procedure TJvFullColorListFrm.ActionDeleteExecute(Sender: TObject); begin ListBoxColors.DeleteSelected; end; procedure TJvFullColorListFrm.ActionDeleteUpdate(Sender: TObject); begin (Sender as TAction).Enabled := ListBoxColors.SelCount >= 1; end; procedure TJvFullColorListFrm.ActionInsertExecute(Sender: TObject); begin JvFullColorDialog.Options := JvFullColorDialog.Options - [foShowApply]; if JvFullColorDialog.Execute then ListBoxColors.Items.InsertObject(ListBoxColors.ItemIndex, '', TObject(PtrInt(JvFullColorDialog.FullColor))); end; procedure TJvFullColorListFrm.ActionInsertUpdate(Sender: TObject); begin (Sender as TAction).Enabled := ListBoxColors.SelCount = 1; end; procedure TJvFullColorListFrm.ActionModifyExecute(Sender: TObject); begin JvFullColorDialog.Options := JvFullColorDialog.Options + [foShowApply]; JvFullColorDialog.FullColor := TJvFullColor(PtrInt(ListBoxColors.Items.Objects[ListBoxColors.ItemIndex])); if JvFullColorDialog.Execute then ListBoxColors.Items.Objects[ListBoxColors.ItemIndex] := TObject(PtrInt(JvFullColorDialog.FullColor)); end; procedure TJvFullColorListFrm.ActionModifyUpdate(Sender: TObject); begin (Sender as TAction).Enabled := ListBoxColors.SelCount = 1; end; procedure TJvFullColorListFrm.ActionMoveDownExecute(Sender: TObject); var OldIndex: Integer; begin with ListBoxColors do begin OldIndex := ItemIndex; Items.Move(ItemIndex, ItemIndex + 1); Selected[OldIndex + 1] := True; end; end; procedure TJvFullColorListFrm.ActionMoveDownUpdate(Sender: TObject); begin with ListBoxColors do (Sender as TAction).Enabled := (SelCount = 1) and (ItemIndex < (Items.Count - 1)); end; procedure TJvFullColorListFrm.ActionMoveUpExecute(Sender: TObject); var OldIndex: Integer; begin with ListBoxColors do begin OldIndex := ItemIndex; Items.Move(ItemIndex, ItemIndex - 1); Selected[OldIndex - 1] := True; end; end; procedure TJvFullColorListFrm.ActionMoveUpUpdate(Sender: TObject); begin with ListBoxColors do (Sender as TAction).Enabled := (SelCount = 1) and (ItemIndex > 0); end; procedure TJvFullColorListFrm.ActionNewExecute(Sender: TObject); begin JvFullColorDialog.Options := JvFullColorDialog.Options - [foShowApply]; if JvFullColorDialog.Execute then begin ListBoxColors.Items.AddObject('', TObject(PtrInt(JvFullColorDialog.FullColor))); ListBoxColors.ItemIndex := ListBoxColors.Items.Count-1; end; end; procedure TJvFullColorListFrm.ActionNewUpdate(Sender: TObject); begin (Sender as TAction).Enabled := True; end; function TJvFullColorListFrm.Execute: Boolean; begin Result := (ShowModal = mrOK); end; procedure TJvFullColorListFrm.FormCreate(Sender: TObject); begin BitBtnMoveUp.Width := BitBtnMoveUp.Height; BitBtnMoveDown.Width := BitBtnMoveDown.Height; {$IF LCL_FullVersion >= 2000000} BitBtnMoveUp.Images := ImageList; BitBtnMoveUp.ImageIndex := 0; BitBtnMoveDown.Images := ImageList; BitBtnMoveDown.ImageIndex := 1; {$ELSE} ImageList.GetBitmap(0, BitBtnMoveUp.Glyph); ImageList.GetBitmap(1, BitBtnMoveDown.Glyph); {$IFEND} end; procedure TJvFullColorListFrm.FormShow(Sender: TObject); var i, w: Integer; s: string; begin w := 0; ListBoxColors.Canvas.Font.Assign(ListboxColors.Font); for i := 0 to ColorSpaceManager.Count-1 do begin; with ColorSpaceManager.ColorSpaceByIndex[i] do if ID <> csDEF then begin s := Format('%s: %s = $FF; %s = $FF; %s = $FF', [ Name, AxisName[axIndex0], AxisName[axIndex1], AxisName[axIndex2] ]); w := Max(w, ListBoxColors.Canvas.TextWidth(s)); end; end; ListBoxColors.ClientWidth := w + ListBoxColors.ItemHeight + GetSystemMetrics(SM_CXVSCROLL) + 8; end; function TJvFullColorListFrm.GetColorList: TJvFullColorList; var Index: Integer; begin FColorList.BeginUpdate; FColorList.Clear; for Index := 0 to ListBoxColors.Items.Count - 1 do FColorList.Add(TJvFullColor(PtrInt(ListBoxColors.Items.Objects[Index]))); FColorList.EndUpdate; Result := FColorList; end; procedure TJvFullColorListFrm.SetColorList(const Value: TJvFullColorList); var I: Integer; begin with ListBoxColors.Items, ColorSpaceManager do begin BeginUpdate; for I := 0 to Value.Count - 1 do AddObject('', TObject(PtrInt(Value.Items[I]))); EndUpdate; end; end; procedure TJvFullColorListFrm.ButtonApplyClick(Sender: TObject); begin if Assigned(FOnApply) then FOnApply(Self); end; procedure TJvFullColorListFrm.JvFullColorDialogApply(Sender: TObject; AFullColor: TJvFullColor); begin ListBoxColors.Items.Objects[ListBoxColors.ItemIndex] := TObject(PtrInt(JvFullColorDialog.FullColor)); end; procedure TJvFullColorListFrm.ListBoxColorsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var AFullColor: TJvFullColor; AText: string; ColorIndex: Integer; AColor: TColor; AColorSpace: TJvColorSpace; begin with TListBox(Control), Canvas do begin Pen.Style := psSolid; Pen.Color := Brush.Color; Brush.Style := bsSolid; Rectangle(Rect); AFullColor := TJvFullColor(PtrInt(Items.Objects[Index])); with ColorSpaceManager do begin AColorSpace := ColorSpace[GetColorSpaceID(AFullColor)]; if AColorSpace.ID = csDEF then with TJvDEFColorSpace(AColorSpace) do begin AColor := ConvertToColor(AFullColor); AText := Format(RsUnnamedColorFmt, [Name, AFullColor]); for ColorIndex := 0 to ColorCount - 1 do if AColor = ColorValue[ColorIndex] then begin AText := Format(RsUnnamedColorFmt, [Name, ColorName[ColorIndex], ColorPrettyName[ColorIndex]]); Break; end; end else with AColorSpace do AText := Format('%s: %s = $%.2x; %s = $%.2x; %s = $%.2x', [Name, AxisName[axIndex0], GetAxisValue(AFullColor, axIndex0), AxisName[axIndex1], GetAxisValue(AFullColor, axIndex1), AxisName[axIndex2], GetAxisValue(AFullColor, axIndex2)]); TextOut(Rect.Left + Rect.Bottom - Rect.Top + 2, Rect.Top + 2, AText); end; Brush.Color := ColorSpaceManager.ConvertToColor(AFullColor); Pen.Color := clBlack; Rectangle(Rect.Left + 2, Rect.Top + 2, Rect.Left + Rect.Bottom - Rect.Top - 2, Rect.Bottom - 2); end; end; end.
unit exereader; {$mode objfpc}{$H+} interface uses SysUtils, Math, dosheader; type TExeFileKind = ( fkUnknown, fkDOS, fkExe16, fkExe32, fkExe64, fkExeArm, fkDll16, fkDll32, fkDll64, fkDllArm, fkVXD ); PLongword = ^Longword; TExeFile = class; TImportFuncEntry = record case IsOrdinal: Boolean of true: ( Ordinal: Word; ); false: ( Hint: Word; Name: PAnsiChar; ); end; { TExeImportDLL } TExeImportDLL = class private FHandle: THandle; FParent: TExeFile; FDLLName: PChar; FDescriptor: PIMAGE_IMPORT_DESCRIPTOR; FEntries: array of TImportFuncEntry; function GetCount: Integer; function GetDLLName: string; function GetEntry(Index: Integer): TImportFuncEntry; public constructor Create(AParent: TExeFile; DLL: PIMAGE_IMPORT_DESCRIPTOR); function Read: Boolean; function Read64: Boolean; property Descriptor: PIMAGE_IMPORT_DESCRIPTOR read FDescriptor; property DLLName: string read GetDLLName; property Count: Integer read GetCount; property Entries[Index: Integer]: TImportFuncEntry read GetEntry; property Handle: THandle read FHandle write FHandle; end; TExeExportFunc = record Name: PChar; Ordinal: Word; EntryPoint: longword; end; TDWordArray = array[0..0] of DWord; PDWordArray = ^TDWordArray; TExeRelocTable = record VirtualAddress: UInt64; Count: Integer; Items: PWordarray; end; { TExeFile } TExeFile = class private FDataSize: longword; FData: PByteArray; FDOSHeader: PIMAGE_DOS_HEADER; FNTHeaders64: PIMAGE_NT_HEADERS64; FNTHeaders: PIMAGE_NT_HEADERS; FSections: array of PIMAGE_SECTION_HEADER; FImports: array of TExeImportDLL; FExports: array of TExeExportFunc; FRelocations: array of TExeRelocTable; FDOSFileSize: longword; FStatus: string; FExportName: PChar; FFileType: TExeFileKind; function GetExport(Index: Integer): TExeExportFunc; function GetExportCount: Integer; function GetImport(Index: Integer): TExeImportDLL; function GetImportCount: Integer; function GetRelocation(Index: Integer): TExeRelocTable; function GetRelocationCount: Integer; function GetSection(Index: Integer): PIMAGE_SECTION_HEADER; function GetSectionCount: Integer; protected function ResolveVirtualAddress32(VirtualAddress: UInt64): UInt64; procedure ReadImports(VirtualAddress: UInt64; is64Bit: Boolean); procedure ReadExports(VirtualAddress: UInt64); procedure ReadRelocations(VirtualAddress: UInt64); function ReadDOSHeader: Boolean; function ReadWin32Header: Boolean; function ReadWin64Header: Boolean; public constructor Create; destructor Destroy; override; procedure Clear; function LoadFile(aFilename: string; ReadFull: Boolean = True): Boolean; function GetRawAddress(Address: UInt64): Pointer; function GetVirtualAddress(VirtualAddress: UInt64): Pointer; function IsValidVirtualAddress(VirtualAddress: UInt64): Boolean; property Status: string read FStatus; property FileType: TExeFileKind read FFileType; property DOSHeader: PIMAGE_DOS_HEADER read FDOSHeader; property NTHeader: PIMAGE_NT_HEADERS read FNTHeaders; property NTHeader64: PIMAGE_NT_HEADERS64 read FNTHeaders64; property SectionCount: Integer read GetSectionCount; property Sections[Index: Integer]: PIMAGE_SECTION_HEADER read GetSection; property ImportCount: Integer read GetImportCount; property Imports[Index: Integer]: TExeImportDLL read GetImport; property ExportName: PChar read FExportName; property ExportCount: Integer read GetExportCount; property ExportFuncs[Index: Integer]: TExeExportFunc read GetExport; property RelocationCount: Integer read GetRelocationCount; property Relocations[Index: Integer]: TExeRelocTable read GetRelocation; end; implementation { TExeImportDLL } function TExeImportDLL.GetDLLName: string; begin result:=FDLLName; end; function TExeImportDLL.GetCount: Integer; begin result:=Length(FEntries); end; function TExeImportDLL.GetEntry(Index: Integer): TImportFuncEntry; begin if(Index>=0)and(Index<Length(FEntries)) then result:=FEntries[Index] else begin result.IsOrdinal:=False; result.Hint:=0; result.Name:=nil; end; end; constructor TExeImportDLL.Create(AParent: TExeFile; DLL: PIMAGE_IMPORT_DESCRIPTOR); begin FParent:=AParent; FDescriptor:=DLL; end; function TExeImportDLL.Read: Boolean; var p: Pointer; ThunkData: PIMAGE_IMPORT_BY_NAME; ThunkRef: PDWord; ACount: Integer; begin result:=False; if FDescriptor^.Name = 0 then raise Exception.Create('Invalid Image Import Descriptor!'); try FDLLName:=PChar(FParent.GetVirtualAddress(FDescriptor^.Name)); except result:=False; Exit; end; if FDescriptor^.OriginalFirstThunk <> 0 then p := FParent.GetVirtualAddress(FDescriptor^.OriginalFirstThunk) else p := FParent.GetVirtualAddress(FDescriptor^.FirstThunk); ACount:=0; ThunkRef:=p; while ThunkRef^ <> 0 do begin Inc(ACount); Inc(ThunkRef); end; Setlength(FEntries, ACount); ThunkRef:=p; ACount:=0; while ThunkRef^ <> 0 do begin if (ThunkRef^ and IMAGE_ORDINAL_FLAG32 = IMAGE_ORDINAL_FLAG32) then begin FEntries[ACount].IsOrdinal:=True; FEntries[ACount].Ordinal:=ThunkRef^ and $FFFF; end else begin FEntries[ACount].IsOrdinal:=False; ThunkData:=FParent.GetVirtualAddress(ThunkRef^); FEntries[ACount].Name:=PChar(@ThunkData^.Name[0]); FEntries[ACount].Hint:=ThunkData^.Hint; end; Inc(ACount); Inc(ThunkRef); end; result:=True; end; function TExeImportDLL.Read64: Boolean; var p: Pointer; ThunkData: PIMAGE_IMPORT_BY_NAME; ThunkRef: PQWord; ACount: Integer; begin result:=False; if FDescriptor^.Name = 0 then //raise Exception.Create('Invalid Image Import Descriptor!'); Exit; FDLLName:=PChar(FParent.GetVirtualAddress(FDescriptor^.Name)); if FDescriptor^.OriginalFirstThunk <> 0 then p := FParent.GetVirtualAddress(FDescriptor^.OriginalFirstThunk) else p := FParent.GetVirtualAddress(FDescriptor^.FirstThunk); ACount:=0; ThunkRef:=p; while ThunkRef^ <> 0 do begin Inc(ACount); Inc(ThunkRef); end; Setlength(FEntries, ACount); ThunkRef:=p; ACount:=0; while ThunkRef^ <> 0 do begin if (ThunkRef^ and IMAGE_ORDINAL_FLAG64 = IMAGE_ORDINAL_FLAG64) then begin FEntries[ACount].IsOrdinal:=True; FEntries[ACount].Ordinal:=ThunkRef^ and $FFFFFFFF; end else begin FEntries[ACount].IsOrdinal:=False; ThunkData:=FParent.GetVirtualAddress(ThunkRef^); FEntries[ACount].Name:=PChar(@ThunkData^.Name[0]); FEntries[ACount].Hint:=ThunkData^.Hint; end; Inc(ACount); Inc(ThunkRef); end; result:=True; end; { TExeFile } function TExeFile.GetSection(Index: Integer): PIMAGE_SECTION_HEADER; begin if (Index>=0)and(Index<Length(FSections)) then result:=FSections[Index] else result:=nil; end; function TExeFile.GetImport(Index: Integer): TExeImportDLL; begin if (Index>=0)and(Index<Length(FImports)) then result:=FImports[Index] else result:=nil; end; function TExeFile.GetExport(Index: Integer): TExeExportFunc; begin if(Index>=0)and(Index<Length(FExports)) then result:=FExports[Index] else begin result.EntryPoint:=0; result.Name:=nil; result.Ordinal:=0; end; end; function TExeFile.GetExportCount: Integer; begin result:=Length(FExports); end; function TExeFile.GetImportCount: Integer; begin result:=Length(FImports); end; function TExeFile.GetRelocation(Index: Integer): TExeRelocTable; begin if (Index>=0)and(Index<Length(FRelocations)) then result:=FRelocations[Index] else begin result.Count:=0; result.Items:=nil; result.VirtualAddress:=0; end; end; function TExeFile.GetRelocationCount: Integer; begin result:=Length(FRelocations); end; function TExeFile.GetSectionCount: Integer; begin result:=Length(FSections); end; function TExeFile.IsValidVirtualAddress(VirtualAddress: UInt64): Boolean; var i: Integer; begin result:=False; if VirtualAddress = 0 then Exit; for i:=0 to Length(FSections)-1 do if (VirtualAddress >= FSections[i]^.VirtualAddress) and (VirtualAddress < FSections[i]^.VirtualAddress + UInt64(FSections[i]^.PhysicalAddress)) // PhysicalAddress == VirtualSize! then begin result:= ((VirtualAddress - FSections[i]^.VirtualAddress) + FSections[i]^.PointerToRawData) < FDataSize; Exit; end; if VirtualAddress<FDataSize then result:=True; end; function TExeFile.ResolveVirtualAddress32(VirtualAddress: UInt64): UInt64; var i: Integer; begin result:=0; if VirtualAddress = 0 then Exit; for i:=0 to Length(FSections)-1 do if (VirtualAddress >= FSections[i]^.VirtualAddress) and (VirtualAddress < UInt64(FSections[i]^.VirtualAddress) + UInt64(FSections[i]^.PhysicalAddress)) // PhysicalAddress == VirtualSize! then begin result:= ((VirtualAddress - FSections[i]^.VirtualAddress) + FSections[i]^.PointerToRawData); if result>=FDataSize then raise Exception.Create('Virtual address out of bounds'); Exit; end; // not sure if this is right behaviour, but it'srequired for some versions // of kkrunchy result:=VirtualAddress; if result>=FDataSize then raise Exception.Create('Virtual address out of bounds'); end; procedure TExeFile.ReadImports(VirtualAddress: UInt64; is64Bit: Boolean); var ImportDesc: PIMAGE_IMPORT_DESCRIPTOR_ARRAY; i: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; ImportDesc:=GetVirtualAddress(VirtualAddress); i:=0; while (ImportDesc^[i].Name<>0) do begin Setlength(FImports, i + 1); FImports[i]:=TExeImportDLL.Create(Self, @ImportDesc^[i]); if is64Bit then FImports[i].Read64 else FImports[i].Read; Inc(i); end; end; procedure TExeFile.ReadExports(VirtualAddress: UInt64); var ExportDesc: PIMAGE_EXPORT_DIRECTORY; expInfo: PDWord; ordInfo: PWord; addrInfo: PDWord; j: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; ExportDesc:=GetVirtualAddress(VirtualAddress); if ExportDesc^.Name <> 0 then begin FExportName:=GetVirtualAddress(ExportDesc^.Name); expInfo:=GEtVirtualAddress(ExportDesc^.AddressOfNames); ordInfo:=GEtVirtualAddress(ExportDesc^.AddressOfNameOrdinals); addrInfo:=GetVirtualAddress(ExportDesc^.AddressOfFunctions); Setlength(FExports, ExportDesc^.NumberOfNames); for j:=0 to ExportDesc^.NumberOfNames -1 do begin FExports[j].Name:=GetVirtualAddress(expInfo^); FExports[j].Ordinal:=OrdInfo^; FExports[j].EntryPoint:=AddrInfo^; inc(expInfo); inc(ordInfo); inc(addrInfo); end; end; end; procedure TExeFile.ReadRelocations(VirtualAddress: UInt64); var Reloc:PIMAGE_BASE_RELOCATION; i: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; reloc:=GetVirtualAddress(VirtualAddress); while reloc^.VirtualAddress>0 do begin if reloc^.SizeOfBlock>0 then begin i:=Length(FRelocations); Setlength(FRelocations, i+1); FRelocations[i].VirtualAddress:=reloc^.VirtualAddress; FRelocations[i].Count:=(reloc^.SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) div 2; FRelocations[i].Items:=Pointer((Reloc)+ IMAGE_SIZEOF_BASE_RELOCATION); end; reloc:=Pointer(UInt64(reloc)+reloc^.SizeOfBlock); end; end; function TExeFile.ReadDOSHeader: Boolean; var HeaderOFfset: longword; NEFlags: Byte; begin FStatus:='Invalid file'; FFileType:=fkUnknown; result:=False; if not Assigned(FData) then Exit; if FDataSize<SizeOf(IMAGE_DOS_HEADER) then Exit; FDOSHeader:=@FData[0]; if FDOSHeader^.e_magic <> cDOSMagic then begin FStatus:='Not an executable file'; Exit; end; // DOS files have length >= size indicated at offset $02 and $04 // (offset $02 indicates length of file mod 512 and offset $04 // indicates no. of 512 pages in file) if FDOSHeader^.e_cblp = 0 then FDOSFileSize:=512 * FDOSHeader^.e_cp else FDOSFileSize:=512 * (FDOSHeader^.e_cp - 1) + FDOSHeader^.e_cblp; // DOS file relocation offset must be within DOS file size. if FDOSHeader^.e_lfarlc > FDOSFileSize then Exit; FFileType:=fkDOS; FSTatus:=''; result:=True; if FDataSize <= cWinHeaderOffset + SizeOf(LongInt) then Exit; HeaderOffset:=FDOSHeader^.e_lfanew; if FDataSize< HeaderOffset + SizeOf(IMAGE_NT_HEADERS) then Exit; FNTHeaders:=@FData^[HeaderOffset]; case FNTHeaders^.Signature of cPEMagic: begin // 32 bit/64 bit if FDataSize>=HeaderOffset + SizeOf(FNTHeaders^) then begin case FNTHeaders^.FileHeader.Machine of $01c4: begin // arm 32 bit if (FNTHeaders^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDllArm else FFileType:=fkExeArm; end; $014c: begin // 32 bit if (FNTHeaders^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDll32 else FFileType:=fkExe32; end; $8664: begin // 64 bit FNTHeaders64:=PIMAGE_NT_HEADERS64(FNTHeaders); FNTHeaders:=nil; if (FNTHeaders64^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDll64 else FFileType:=fkExe64; end; else begin result:=False; FFileType:=fkUnknown; FStatus:='Unknown Machine Type '+IntToHex(FNTHeaders^.FileHeader.Machine, 4); FNTHeaders:=nil; end; end; end; end; cNEMagic: begin // 16 bit FNTHeaders:=nil; if FDataSize>=HeaderOffset + cNEAppTypeOffset + SizeOf(NEFlags) then begin NEFlags:=FData^[HeaderOffset + cNEAppTypeOffset]; if (NEFlags and cNEDLLFlag) = cNEDLLFlag then FFileType:=fkDll16 else FFileType:=fkExe16; end; Exit; end; cLEMagic: begin FNTHeaders:=nil; FFileType:=fkVXD; end; else begin FStatus:='Unknown NT Header Signature'; Exit; end; end; end; function TExeFile.ReadWin32Header: Boolean; var i: Integer; p: longword; begin result:=False; if FNTHeaders^.OptionalHeader.Magic <> $10b then begin FStatus:='OptionalHeader Magic is not Win32'; Exit; end; // read sections if FNTHeaders^.FileHeader.NumberOfSections<=96 then begin Setlength(FSections, FNTHeaders^.FileHeader.NumberOfSections); p:=FDOSHeader^.e_lfanew + SizeOf(FNTHeaders^); for i:=0 to FNTHeaders^.FileHeader.NumberOfSections-1 do begin FSections[i]:=@FData^[p]; p:=p+SizeOf(FSections[i]^); end; end else begin FStatus:='Number of sections exceeds maximum'; Exit; end; if FNTHeaders^.OptionalHeader.DataDirectory[0].VirtualAddress <> 0 then ReadExports(FNTHeaders^.OptionalHeader.DataDirectory[0].VirtualAddress); if FNTHeaders^.OptionalHeader.DataDirectory[1].VirtualAddress <> 0 then ReadImports(FNTHeaders^.OptionalHeader.DataDirectory[1].VirtualAddress, false); if FNTHeaders^.OptionalHeader.DataDirectory[5].Size >= SizeOf(IMAGE_BASE_RELOCATION) then ReadRelocations(FNTHeaders^.OptionalHeader.DataDirectory[5].VirtualAddress); result:=True; end; function TExeFile.ReadWin64Header: Boolean; var i: Integer; p: longword; begin result:=False; if FNTHeaders64^.OptionalHeader.Magic <> $20b then begin FStatus:='Not Win32/x86'; Exit; end; // read sections if FNTHeaders64^.FileHeader.NumberOfSections<=96 then begin Setlength(FSections, FNTHeaders64^.FileHeader.NumberOfSections); p:=FDOSHeader^.e_lfanew + SizeOf(FNTHeaders64^); for i:=0 to FNTHeaders64^.FileHeader.NumberOfSections-1 do begin FSections[i]:=@FData^[p]; p:=p+SizeOf(FSections[i]^); end; end else begin FStatus:='Number of sections exceeds maximum'; Exit; end; if FNTHeaders64^.OptionalHeader.DataDirectory[0].Size <> 0 then ReadExports(FNTHeaders64^.OptionalHeader.DataDirectory[0].VirtualAddress); if FNTHeaders64^.OptionalHeader.DataDirectory[1].Size <> 0 then ReadImports(FNTHeaders64^.OptionalHeader.DataDirectory[1].VirtualAddress, true); if FNTHeaders64^.OptionalHeader.DataDirectory[5].Size >= SizeOf(IMAGE_BASE_RELOCATION) then ReadRelocations(FNTHeaders64^.OptionalHeader.DataDirectory[5].VirtualAddress); result:=True; end; constructor TExeFile.Create; begin FData:=nil; end; destructor TExeFile.Destroy; begin Clear; inherited Destroy; end; function TExeFile.GetVirtualAddress(VirtualAddress: UInt64): Pointer; begin result:=@FData^[ResolveVirtualAddress32(VirtualAddress)]; end; function TExeFile.LoadFile(aFilename: string; ReadFull: Boolean): Boolean; var f: File; begin result:=False; Clear; Assignfile(f, aFilename); Filemode:=0; {$i-}reset(f,1);{$i+} if ioresult=0 then begin FDataSize := Filesize(f); if not ReadFull then FDataSize := Min(4 * 1024, FdataSize); Getmem(FData, FDataSize); Blockread(f, FData^, FDataSize); CloseFile(f); end else begin FStatus:='Could not open file'; Exit; end; result:=ReadDOSHeader; case FFileType of fkExe32, fkExeArm, fkDll32, fkDllArm: ReadWin32Header; fkExe64, fkDLL64: ReadWin64Header; end; end; function TExeFile.GetRawAddress(Address: UInt64): Pointer; begin result:=@FData^[Address]; end; procedure TExeFile.Clear; var i: Integer; begin for i:=0 to Length(FImports)-1 do FImports[i].Free; Setlength(FImports, 0); Setlength(FExports, 0); Setlength(FSections, 0); FDOSHeader:=nil; FNTHeaders:=nil; FNTHeaders64:=nil; FExportName:=nil; if Assigned(FData) then Freemem(FData); FDataSize:=0; FData:=nil; end; end.
{$R-} {$Q-} unit ncEncMd5; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2; type TncEnc_md5 = class(TncEnc_hash) protected LenHi, LenLo: longword; Index: DWord; CurrentHash: array [0 .. 3] of DWord; HashBuffer: array [0 .. 63] of byte; procedure Compress; public class function GetAlgorithm: string; override; class function GetHashSize: integer; override; class function SelfTest: boolean; override; procedure Init; override; procedure Burn; override; procedure Update(const Buffer; Size: longword); override; procedure Final(var Digest); override; end; { ****************************************************************************** } { ****************************************************************************** } implementation uses ncEncryption; function LRot32(a, b: longword): longword; begin Result := (a shl b) or (a shr (32 - b)); end; procedure TncEnc_md5.Compress; var Data: array [0 .. 15] of DWord; a, b, C, D: DWord; begin Move(HashBuffer, Data, Sizeof(Data)); a := CurrentHash[0]; b := CurrentHash[1]; C := CurrentHash[2]; D := CurrentHash[3]; a := b + LRot32(a + (D xor (b and (C xor D))) + Data[0] + $D76AA478, 7); D := a + LRot32(D + (C xor (a and (b xor C))) + Data[1] + $E8C7B756, 12); C := D + LRot32(C + (b xor (D and (a xor b))) + Data[2] + $242070DB, 17); b := C + LRot32(b + (a xor (C and (D xor a))) + Data[3] + $C1BDCEEE, 22); a := b + LRot32(a + (D xor (b and (C xor D))) + Data[4] + $F57C0FAF, 7); D := a + LRot32(D + (C xor (a and (b xor C))) + Data[5] + $4787C62A, 12); C := D + LRot32(C + (b xor (D and (a xor b))) + Data[6] + $A8304613, 17); b := C + LRot32(b + (a xor (C and (D xor a))) + Data[7] + $FD469501, 22); a := b + LRot32(a + (D xor (b and (C xor D))) + Data[8] + $698098D8, 7); D := a + LRot32(D + (C xor (a and (b xor C))) + Data[9] + $8B44F7AF, 12); C := D + LRot32(C + (b xor (D and (a xor b))) + Data[10] + $FFFF5BB1, 17); b := C + LRot32(b + (a xor (C and (D xor a))) + Data[11] + $895CD7BE, 22); a := b + LRot32(a + (D xor (b and (C xor D))) + Data[12] + $6B901122, 7); D := a + LRot32(D + (C xor (a and (b xor C))) + Data[13] + $FD987193, 12); C := D + LRot32(C + (b xor (D and (a xor b))) + Data[14] + $A679438E, 17); b := C + LRot32(b + (a xor (C and (D xor a))) + Data[15] + $49B40821, 22); a := b + LRot32(a + (C xor (D and (b xor C))) + Data[1] + $F61E2562, 5); D := a + LRot32(D + (b xor (C and (a xor b))) + Data[6] + $C040B340, 9); C := D + LRot32(C + (a xor (b and (D xor a))) + Data[11] + $265E5A51, 14); b := C + LRot32(b + (D xor (a and (C xor D))) + Data[0] + $E9B6C7AA, 20); a := b + LRot32(a + (C xor (D and (b xor C))) + Data[5] + $D62F105D, 5); D := a + LRot32(D + (b xor (C and (a xor b))) + Data[10] + $02441453, 9); C := D + LRot32(C + (a xor (b and (D xor a))) + Data[15] + $D8A1E681, 14); b := C + LRot32(b + (D xor (a and (C xor D))) + Data[4] + $E7D3FBC8, 20); a := b + LRot32(a + (C xor (D and (b xor C))) + Data[9] + $21E1CDE6, 5); D := a + LRot32(D + (b xor (C and (a xor b))) + Data[14] + $C33707D6, 9); C := D + LRot32(C + (a xor (b and (D xor a))) + Data[3] + $F4D50D87, 14); b := C + LRot32(b + (D xor (a and (C xor D))) + Data[8] + $455A14ED, 20); a := b + LRot32(a + (C xor (D and (b xor C))) + Data[13] + $A9E3E905, 5); D := a + LRot32(D + (b xor (C and (a xor b))) + Data[2] + $FCEFA3F8, 9); C := D + LRot32(C + (a xor (b and (D xor a))) + Data[7] + $676F02D9, 14); b := C + LRot32(b + (D xor (a and (C xor D))) + Data[12] + $8D2A4C8A, 20); a := b + LRot32(a + (b xor C xor D) + Data[5] + $FFFA3942, 4); D := a + LRot32(D + (a xor b xor C) + Data[8] + $8771F681, 11); C := D + LRot32(C + (D xor a xor b) + Data[11] + $6D9D6122, 16); b := C + LRot32(b + (C xor D xor a) + Data[14] + $FDE5380C, 23); a := b + LRot32(a + (b xor C xor D) + Data[1] + $A4BEEA44, 4); D := a + LRot32(D + (a xor b xor C) + Data[4] + $4BDECFA9, 11); C := D + LRot32(C + (D xor a xor b) + Data[7] + $F6BB4B60, 16); b := C + LRot32(b + (C xor D xor a) + Data[10] + $BEBFBC70, 23); a := b + LRot32(a + (b xor C xor D) + Data[13] + $289B7EC6, 4); D := a + LRot32(D + (a xor b xor C) + Data[0] + $EAA127FA, 11); C := D + LRot32(C + (D xor a xor b) + Data[3] + $D4EF3085, 16); b := C + LRot32(b + (C xor D xor a) + Data[6] + $04881D05, 23); a := b + LRot32(a + (b xor C xor D) + Data[9] + $D9D4D039, 4); D := a + LRot32(D + (a xor b xor C) + Data[12] + $E6DB99E5, 11); C := D + LRot32(C + (D xor a xor b) + Data[15] + $1FA27CF8, 16); b := C + LRot32(b + (C xor D xor a) + Data[2] + $C4AC5665, 23); a := b + LRot32(a + (C xor (b or (not D))) + Data[0] + $F4292244, 6); D := a + LRot32(D + (b xor (a or (not C))) + Data[7] + $432AFF97, 10); C := D + LRot32(C + (a xor (D or (not b))) + Data[14] + $AB9423A7, 15); b := C + LRot32(b + (D xor (C or (not a))) + Data[5] + $FC93A039, 21); a := b + LRot32(a + (C xor (b or (not D))) + Data[12] + $655B59C3, 6); D := a + LRot32(D + (b xor (a or (not C))) + Data[3] + $8F0CCC92, 10); C := D + LRot32(C + (a xor (D or (not b))) + Data[10] + $FFEFF47D, 15); b := C + LRot32(b + (D xor (C or (not a))) + Data[1] + $85845DD1, 21); a := b + LRot32(a + (C xor (b or (not D))) + Data[8] + $6FA87E4F, 6); D := a + LRot32(D + (b xor (a or (not C))) + Data[15] + $FE2CE6E0, 10); C := D + LRot32(C + (a xor (D or (not b))) + Data[6] + $A3014314, 15); b := C + LRot32(b + (D xor (C or (not a))) + Data[13] + $4E0811A1, 21); a := b + LRot32(a + (C xor (b or (not D))) + Data[4] + $F7537E82, 6); D := a + LRot32(D + (b xor (a or (not C))) + Data[11] + $BD3AF235, 10); C := D + LRot32(C + (a xor (D or (not b))) + Data[2] + $2AD7D2BB, 15); b := C + LRot32(b + (D xor (C or (not a))) + Data[9] + $EB86D391, 21); Inc(CurrentHash[0], a); Inc(CurrentHash[1], b); Inc(CurrentHash[2], C); Inc(CurrentHash[3], D); Index := 0; FillChar(HashBuffer, Sizeof(HashBuffer), 0); end; class function TncEnc_md5.GetHashSize: integer; begin Result := 128; end; class function TncEnc_md5.GetAlgorithm: string; begin Result := 'MD5'; end; class function TncEnc_md5.SelfTest: boolean; const Test1Out: array [0 .. 15] of byte = ($90, $01, $50, $98, $3C, $D2, $4F, $B0, $D6, $96, $3F, $7D, $28, $E1, $7F, $72); Test2Out: array [0 .. 15] of byte = ($C3, $FC, $D3, $D7, $61, $92, $E4, $00, $7D, $FB, $49, $6C, $CA, $67, $E1, $3B); var TestHash: TncEnc_md5; TestOut: array [0 .. 19] of byte; begin TestHash := TncEnc_md5.Create(nil); TestHash.Init; TestHash.UpdateStr('abc'); TestHash.Final(TestOut); Result := CompareMem(@TestOut, @Test1Out, Sizeof(Test1Out)); TestHash.Init; TestHash.UpdateStr('abcdefghijklmnopqrstuvwxyz'); TestHash.Final(TestOut); Result := CompareMem(@TestOut, @Test2Out, Sizeof(Test2Out)) and Result; TestHash.Free; end; procedure TncEnc_md5.Init; begin Burn; CurrentHash[0] := $67452301; CurrentHash[1] := $EFCDAB89; CurrentHash[2] := $98BADCFE; CurrentHash[3] := $10325476; fInitialized := true; end; procedure TncEnc_md5.Burn; begin LenHi := 0; LenLo := 0; Index := 0; FillChar(HashBuffer, Sizeof(HashBuffer), 0); FillChar(CurrentHash, Sizeof(CurrentHash), 0); fInitialized := false; end; procedure TncEnc_md5.Update(const Buffer; Size: longword); var PBuf: ^byte; begin if not fInitialized then raise EncEnc_hash.Create('Hash not initialized'); Inc(LenHi, Size shr 29); Inc(LenLo, Size * 8); if LenLo < (Size * 8) then Inc(LenHi); PBuf := @Buffer; while Size > 0 do begin if (Sizeof(HashBuffer) - Index) <= DWord(Size) then begin Move(PBuf^, HashBuffer[Index], Sizeof(HashBuffer) - Index); Dec(Size, Sizeof(HashBuffer) - Index); Inc(PBuf, Sizeof(HashBuffer) - Index); Compress; end else begin Move(PBuf^, HashBuffer[Index], Size); Inc(Index, Size); Size := 0; end; end; end; procedure TncEnc_md5.Final(var Digest); begin if not fInitialized then raise EncEnc_hash.Create('Hash not initialized'); HashBuffer[Index] := $80; if Index >= 56 then Compress; PDWord(@HashBuffer[56])^ := LenLo; PDWord(@HashBuffer[60])^ := LenHi; Compress; Move(CurrentHash, Digest, Sizeof(CurrentHash)); Burn; end; end.
{=============================================================================== 通讯基类 ===============================================================================} unit xCommBase; interface uses System.Types, xTypes, System.Classes, xFunction, System.SysUtils; type TCommBase = class private FOnSendRevPack: TSendRevPack; FOnError: TGetStrProc; FCommBusy: Boolean; FActive: Boolean; FOnRevPacks: TEnventPack; FOnLog: TGetStrProc; protected /// <summary> /// 通讯错误 /// </summary> procedure CommError( sError : string ); virtual; /// <summary> /// 连接之前函数 /// </summary> procedure BeforeConn; virtual; /// <summary> /// 连接之后函数 /// </summary> procedure AfterConn; virtual; /// <summary> /// 断开连接之前函数 /// </summary> procedure BeforeDisConn; virtual; /// <summary> /// 断开连接之后函数 /// </summary> procedure AfterDisConn; virtual; /// <summary> /// 发送之前函数 /// </summary> procedure BeforeSend; virtual; /// <summary> /// 发送之后函数 /// </summary> procedure AfterSend; virtual; /// <summary> /// 接收之前函数 /// </summary> procedure BeforeRev; virtual; /// <summary> /// 接收之后函数 /// </summary> procedure AfterRev; virtual; /// <summary> /// 接收数据 /// </summary> procedure RevPacksData(aPacks: TArray<Byte>); overload; virtual; procedure RevStrData(sStr: string); overload; virtual; /// <summary> ///真实发送 串口或以太网发送 /// 第一个参数为IP地址,第二个参数为端口 /// </summary> function RealSend(APacks: TArray<Byte>; sParam1: string = ''; sParam2 : string=''): Boolean; virtual; /// <summary> /// 真实连接 /// </summary> function RealConnect : Boolean; virtual; /// <summary> /// 真实断开连接 /// </summary> procedure RealDisconnect; virtual; procedure Log(s : string); public constructor Create; virtual; destructor Destroy; override; /// <summary> /// 发送数据 /// </summary> function SendPacksDataBase(APacks: TArray<Byte>; sParam1,sParam2 : string): Boolean; overload; virtual; function SendPacksDataBase(sStr: string; sParam1,sParam2 : string): Boolean; overload; virtual; /// <summary> /// 连接 /// </summary> procedure Connect; /// <summary> /// 断开连接 /// </summary> procedure Disconnect; public /// <summary> /// 是否忙 /// </summary> property CommBusy : Boolean read FCommBusy write FCommBusy; /// <summary> /// 串口是否打开 TCP是否连接上 /// </summary> property Active : Boolean read FActive; /// <summary> /// 接收数据包事件 /// </summary> property OnRevPacks : TEnventPack read FOnRevPacks write FOnRevPacks; /// <summary> /// 收发数据包事件 /// </summary> property OnSendRevPack : TSendRevPack read FOnSendRevPack write FOnSendRevPack; /// <summary> /// 错误事件 /// </summary> property OnError: TGetStrProc read FOnError write FOnError; /// <summary> /// 事件记录 /// </summary> property OnLog : TGetStrProc read FOnLog write FOnLog; end; implementation { TCommBase } procedure TCommBase.AfterConn; begin end; procedure TCommBase.AfterDisConn; begin end; procedure TCommBase.AfterRev; begin end; procedure TCommBase.AfterSend; begin FCommBusy := False; end; procedure TCommBase.BeforeConn; begin end; procedure TCommBase.BeforeDisConn; begin end; procedure TCommBase.BeforeRev; begin end; procedure TCommBase.BeforeSend; begin FCommBusy := True; end; procedure TCommBase.CommError(sError: string); begin if Assigned(FOnError) then FOnError(sError); end; procedure TCommBase.Connect; begin BeforeConn; try FActive := RealConnect; except end; AfterConn; end; constructor TCommBase.Create; begin FCommBusy := False; FActive := False; end; destructor TCommBase.Destroy; begin inherited; end; procedure TCommBase.Disconnect; begin BeforeDisConn; RealDisconnect; AfterDisConn; end; procedure TCommBase.Log(s: string); begin if Assigned(FOnLog) then FOnLog(s); end; function TCommBase.RealConnect : Boolean; begin Result := True; end; procedure TCommBase.RealDisconnect; begin FActive := False; end; function TCommBase.RealSend(APacks: TArray<Byte>; sParam1, sParam2 : string): Boolean; begin Result := True; end; procedure TCommBase.RevPacksData(aPacks: TArray<Byte>); begin if Assigned(FOnSendRevPack) then FOnSendRevPack(APacks, False); if Assigned(FOnLog) then FOnLog(FormatDateTime('hh:mm:ss:zzz', Now) + ' 接收 ' + BCDPacksToStr(aPacks)); if Assigned(FOnRevPacks) then FOnRevPacks(aPacks); end; procedure TCommBase.RevStrData(sStr: string); begin end; function TCommBase.SendPacksDataBase(sStr: string; sParam1,sParam2 : string): Boolean; begin Result := SendPacksDataBase(StrToPacks(sStr),sParam1,sParam2); end; function TCommBase.SendPacksDataBase(APacks: TArray<Byte>; sParam1,sParam2 : string): Boolean; begin BeforeSend; Result := RealSend(APacks, sParam1, sParam2); if Result and Assigned(FOnSendRevPack) then FOnSendRevPack(APacks, True); if Assigned(FOnLog) then FOnLog(FormatDateTime('hh:mm:ss:zzz', Now) + ' 发送 ' + BCDPacksToStr(aPacks)); AfterSend; end; end.
unit BInt; interface {const numlen = 102;} uses BigInt, Math; type BigInteger = class private a: number;//array [1..numlen] of byte; s: ShortInt; l: Byte; public constructor Create(num: Int64); overload; constructor Create(abs: number; sign: ShortInt); overload; function GetAbsoluteValue: number; function GetSign: ShortInt; function Copy: BigInteger; procedure InvertSign; function Add(b: BigInteger): BigInteger; function Multiply(b: BigInteger): BigInteger; overload; function Multiply(b: Int64): BigInteger; overload; function SubStract(b: BigInteger): BigInteger; overload; function SubStract(b: Int64): BigInteger; overload; function Sqrt: BigInteger; function SqrtRough: BigInteger; function SqrtCeil: BigInteger; function SqrtFloor: BigInteger; function toExt: Extended; procedure BigInc; procedure BigDec; procedure readFromFile(var f: TextFile); procedure writeToFile(var f: TextFile); function getLen: Byte; end; implementation { BigInteger } function BigInteger.Add(b: BigInteger): BigInteger; var x: number; bs: ShortInt; begin bs := b.GetSign(); if bs = 0 then begin Result := self; Exit; end; x := b.GetAbsoluteValue; if s = 0 then begin a := x; s := bs; Result := self; Exit; end; if s * bs > 0 then begin BigInt.add(a, x); s := 1; end else if (cmp(a, x) = 0) then begin s := 0; set0(a); end else if (cmp(a, x) = 1) then BigInt.subStract(a, x) else begin BigInt.subStract(x, a); a := x; InvertSign; end; Result := self; end; function BigInteger.Copy: BigInteger; begin Result := BigInteger.Create(a, s) end; constructor BigInteger.Create(num: Int64); begin if (num = 0) then s := 0 else if (num > 0) then s := 1 else s := -1; setn(a, abs(num)); end; constructor BigInteger.Create(abs: number; sign: ShortInt); begin a := abs; s := sign; end; procedure BigInteger.BigDec; begin SubStract(BigInteger.Create(1)); end; function BigInteger.GetAbsoluteValue: number; begin Result := a; end; function BigInteger.getLen: Byte; begin Result := len(a); end; function BigInteger.GetSign: ShortInt; begin Result := s; end; procedure BigInteger.BigInc; begin Add(BigInteger.Create(1)); end; procedure BigInteger.InvertSign; begin s := -s; end; function BigInteger.Multiply(b: Int64): BigInteger; begin mulShort(a, b); Result := Self; end; function BigInteger.Multiply(b: BigInteger): BigInteger; var res: number; begin mul(a, b.a, res); Result := BigInteger.Create(res, 1); end; procedure BigInteger.readFromFile(var f: TextFile); var s: String; i, j: Byte; e: Integer; begin Readln(f, s); set0(a); l := 0; for i := 1 to Length(s) do begin Val(s[i], j, E); if (E = 0) then begin a[i] := j; Inc(l); end else break; end; end; function BigInteger.SqrtRough: BigInteger; var l, n: Byte; x: number; begin l := len(a); n := Ceil(l/2); set0(x); if Odd(l) then x[n] := 2 else x[n] := 6; Result := BigInteger.create(x, 1); end; function BigInteger.SubStract(b: Int64): BigInteger; begin Result := SubStract(BigInteger.Create(b)) end; function BigInteger.Sqrt: BigInteger; var r: BigInteger; x, sqx: number; begin r := SqrtRough; x := r.GetAbsoluteValue; sqx := Sq(x); if cmp(sqx, a) = 0 then begin Result := r; Exit; end; end; function BigInteger.SqrtCeil: BigInteger; var b, c: BigInteger; zero: number; begin b := BigInteger.Create(1); c := BigInteger.Create(0); set0(zero); repeat Substract(b); b.Add(BigInteger.Create(2)); c.biginc; until s < 1; if cmp(a, zero) = 1 then c.bigInc; Result := c; end; function BigInteger.SqrtFloor: BigInteger; var b, c: BigInteger; zero: number; begin b := BigInteger.Create(1); c := BigInteger.Create(0); set0(zero); repeat Substract(b); b.Add(BigInteger.Create(2)); c.biginc; until s < 1; if (s < 0) and (cmp(a, zero) = 1) then c.bigDec; Result := c; end; function BigInteger.SubStract(b: BigInteger): BigInteger; var c: BigInteger; begin c := b.Copy; c.InvertSign; Result := Add(c); end; function BigInteger.toExt: Extended; begin Result := s * toExtended(a); end; procedure BigInteger.writeToFile(var f: TextFile); begin showf(f, a); end; end.
unit efatt.dbmodel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, mssqlconn, sqlite3conn, sqldb, FileUtil; type { TdmMain } TdmMain = class(TDataModule) cnSqlLite3: TSQLite3Connection; tbMeta: TSQLQuery; SQLTransaction1: TSQLTransaction; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FLog: TStringList; procedure SaveLog; public function ConnectDatabase: boolean; procedure CheckDbSchema; end; var dmMain: TdmMain; implementation {$R *.lfm} { TdmMain } procedure TdmMain.DataModuleCreate(Sender: TObject); begin FLog:=TStringList.Create; end; procedure TdmMain.DataModuleDestroy(Sender: TObject); begin SaveLog; FLog.Free; end; procedure TdmMain.SaveLog; begin FLog.SaveToFile( 'eFatt_dbmodel.log' ); end; function TdmMain.ConnectDatabase: boolean; begin result:=False; FLog.Add('ConnectDatabase: connecting...'); try cnSqlLite3.Open; result:=True; FLog.Add('ConnectDatabase: connected'); except on e: exception do begin FLog.Add('ConnectDatabase: *** ERROR ***'); FLog.Add(e.Message); end; end; SaveLog; end; procedure TdmMain.CheckDbSchema; var sSql: string; begin tbMeta.Close; sSql:='SELECT count(*) FROM sqlite_master WHERE type=''table'''; FLog.Add('CheckDbSchema: SQL : ' + sSql); tbMeta.SQL.Add(sSql); tbMeta.Open; tbMeta.Last; tbMeta.First; FLog.Add('CheckDbSchema: Table count = ' + IntToStr(tbMeta.RecordCount)); // log tables if tbMeta.RecordCount > 0 then while not tbMeta.EOF do begin FLog.Add(Format('%10.10s %50.50s', [ tbMeta.FieldByName('type').AsString, tbMeta.FieldByName('name').AsString])); tbMeta.Next; end; SaveLog; // create end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Analytics.AppAnalytics; interface uses System.Types, System.Classes, System.SysUtils, System.Math, System.Analytics; type /// <summary>An implementation of IApplicationActivityListener for use with the Embarcadero AppAnalytics service.</summary> TAppAnalyticsListener = class(TInterfacedObject, IApplicationActivityListener) private FOptions: TAppActivityOptions; FAppVersion: string; FCacheManager: IApplicationActivityCacheManager; FPreviousControlClassname: string; FPreviousControlName: string; FPreviousFormClassname: string; FPreviousFormName: string; { IApplicationActivityListener } procedure TrackAppStart(const TimeStamp: TDateTime); procedure TrackAppExit(const TimeStamp: TDateTime); procedure TrackControlFocused(const TimeStamp: TDateTime; const Sender: TObject); procedure TrackWindowActivated(const TimeStamp: TDateTime; const Sender: TObject); procedure TrackEvent(const TimeStamp: TDateTime; const Sender, Context: TObject); procedure TrackException(const TimeStamp: TDateTime; const E: Exception); procedure SetOptions(const Value: TAppActivityOptions); function GetTimestamp: string; public /// <summary>Creates an instance of TAppAnalyticsListener which can be registered with the application's Analytics /// Manager.</summary> constructor Create(const CacheManager: IApplicationActivityCacheManager; const AppVersion: string; const Options: TAppActivityOptions); /// <summary>Sets or retrieves the set of TAppActivity types which will be recorded.</summary> property Options: TAppActivityOptions read FOptions write SetOptions; end; /// <summary>An implementation of IApplicationActivityCacheManager which stores application events in a temporary /// cache and uploads the data to an AppAnalytics server for analysis.</summary> TAppAnalyticsCacheManager = class(TInterfacedObject, IApplicationActivityCacheManager, IAppAnalyticsStartupDataRecorder) private FDataCache: TStringList; FMaxCacheSize: Integer; FUserID: string; // Must be an anonymous ID to track this user through across sessions FSessionID: string; FApplicationID: string; FEventCount: Cardinal; FServerAddress: string; FServerPort: Integer; FOnDataCacheFull: TNotifyEvent; FCPUInfo: string; FAppVersion: string; FOSVersion: string; { IApplicationActivityCacheManager } function GetCacheCount: Integer; procedure PersistData(const Wait: Boolean); procedure ClearData; procedure Log(const AMessage: string); procedure RemoveEventAtIndex(const Index: Integer); function GetEventAtIndex(const Index: Integer): string; procedure SetOnDataCacheFull(const AValue: TNotifyEvent); function GetOnDataCacheFull: TNotifyEvent; procedure SetMaxCacheSize(const AValue: Integer); function GetMaxCacheSize: Integer; class procedure SendData(const ContentString, ServerAddress: string; const ServerPort: Integer); { IAppAnalyticsStartupDataRecorder } procedure AddEnvironmentField(const AKey, AValue: string); public /// <summary>Creates an instance of this cache manager. The AppID and UserID are GUID strings which uniquely /// identify this application and user to the AppAnalytics service. ServerAddress is the URL of the AppAnalytics /// server which should receive the collected data. ServerPort is the port number on the specified server which /// will receive the data.</summary> constructor Create(const AppID, UserID, ServerAddress: string; const ServerPort: Integer); /// <summary>Destroys this object.</summary> destructor Destroy; override; /// <summary>Returns the number of events in the temporary data cache.</summary> property CacheCount: Integer read GetCacheCount; /// <summary>Sets or retrieves the maximum size of the memory data cache. When the cache is full, the data should /// be sent to the AppAnalytics service.</summary> property MaxCacheSize: Integer read GetMaxCacheSize write SetMaxCacheSize; /// <summary>Returns the event at the specified index from the temporary data cache.</summary> property Event[const Index: Integer]: string read GetEventAtIndex; /// <summary>Sets or retrieves an event handler which will be fired when the memory data cache is full. When this /// event is fired, the data should be sent to the AppAnalytics service.</summary> property OnDataCacheFull: TNotifyEvent read GetOnDataCacheFull write SetOnDataCacheFull; end; /// <summary>Class used for storing context data for tracking a custom event with TAppActivity.Custom.</summary> TCustomEventContext = class private FCategory: string; FAction: string; FText: string; FValue: Double; public /// <summary>Conveninience constructor that sets the values of the fields.</summary> constructor Create(const ACategory, AAction, AText: string; const AValue: Double); /// <summary>String data indicating a category for the event.</summary> property Category: string read FCategory write FCategory; /// <summary>String data indicating the action for the event.</summary> property Action: string read FAction write FAction; /// <summary>String data of descriptive information about the event.</summary> property Text: string read FText write FText; /// <summary>A floating point value associated with the event.</summary> property Value: Double read FValue write FValue; end; implementation uses System.SyncObjs, System.DateUtils, System.SysConst, System.NetEncoding, System.Net.HttpClient, System.Character, System.Net.URLClient, System.NetConsts {$IFDEF MSWINDOWS} , System.Win.Registry, Winapi.Windows {$ENDIF MSWINDOWS} {$IFDEF MACOS} , Posix.SysSysctl {$ENDIF MACOS} {$IFDEF ANDROID} , Androidapi.JNI.Os, Androidapi.Helpers, Androidapi.JNI.JavaTypes {$ENDIF ANDROID} ; constructor TAppAnalyticsListener.Create(const CacheManager: IApplicationActivityCacheManager; const AppVersion: string; const Options: TAppActivityOptions); begin inherited Create; FOptions := Options; FAppVersion := AppVersion; FCacheManager := CacheManager; end; function TAppAnalyticsListener.GetTimestamp: string; const TimestampFormat = 'yyyy-mm-dd hh:nn:ss.zzz'; // do not localize var UTC: TDateTime; begin UTC := TTimeZone.Local.ToUniversalTime(Now); DateTimeToString(Result, TimestampFormat, UTC); end; procedure TAppAnalyticsListener.SetOptions(const Value: TAppActivityOptions); begin FOptions := Value; end; procedure TAppAnalyticsListener.TrackAppExit(const TimeStamp: TDateTime); begin if (TAppActivity.AppExit in FOptions) and (FCacheManager <> nil) then FCacheManager.Log('AppExit|' + GetTimestamp); // do not localize; end; procedure TAppAnalyticsListener.TrackAppStart(const TimeStamp: TDateTime); function GetCPUName: string; {$IFDEF MSWINDOWS} var Reg: TRegistry; {$ENDIF} {$IFDEF MACOS} var Buffer: TArray<Byte>; BufferLength: LongWord; {$ENDIF} begin {$IFDEF MSWINDOWS} Result := ''; Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('Hardware\Description\System\CentralProcessor\0', False) then // do not localize Result := Reg.ReadString('ProcessorNameString') // do not localize else Result := '(CPU Unidentified)'; // do not localize finally Reg.Free; end; {$ENDIF} {$IFDEF MACOS} {$IFDEF IOS} SysCtlByName(MarshaledAString('hw.machine'), nil, @BufferLength, nil, 0); // do not localize SetLength(Buffer, BufferLength); try SysCtlByName(MarshaledAString('hw.machine'), @Buffer[0], @BufferLength, nil, 0); // do not localize Result := 'APPLE ' + string(MarshaledAString(@Buffer[0])); // do not localize finally SetLength(Buffer, 0); end; {$ELSE} SysCtlByName(MarshaledAString('machdep.cpu.brand_string'), nil, @BufferLength, nil, 0); // do not localize SetLength(Buffer, BufferLength); try SysCtlByName(MarshaledAString('machdep.cpu.brand_string'), @Buffer[0], @BufferLength, nil, 0); // do not localize Result := string(MarshaledAString(@Buffer[0])); finally SetLength(Buffer, 0); end; {$ENDIF IOS} {$ENDIF MACOS} {$IFDEF ANDROID} Result := JStringToString(TJBuild.JavaClass.MANUFACTURER).ToUpper + ' ' + JStringToString(TJBuild.JavaClass.MODEL); {$ENDIF} end; function GetOSFamily: string; begin case TOSVersion.Platform of TOSVersion.TPlatform.pfWindows: Result := 'WIN'; // do not localize TOSVersion.TPlatform.pfMacOS: Result := 'MAC'; // do not localize TOSVersion.TPlatform.pfiOS: Result := 'IOS'; // do not localize TOSVersion.TPlatform.pfAndroid: Result := 'ANDROID'; // do not localize else Result := 'UNDEFINED'; // do not localize end; end; var OSVersion: string; CPUName: string; StartupRecorder: IAppAnalyticsStartupDataRecorder; begin if (TAppActivity.AppStart in FOptions) and (FCacheManager <> nil) then begin OSVersion := Format('%s %d.%d' , [GetOSFamily, TOSVersion.Major, TOSVersion.Minor]); CPUName := GetCPUName; if Supports(FCacheManager, IAppAnalyticsStartupDataRecorder, StartupRecorder) then begin StartupRecorder.AddEnvironmentField('OS', OSVersion); // do not localize StartupRecorder.AddEnvironmentField('CPU', CPUName); // do not localize StartupRecorder.AddEnvironmentField('APPVER', FAppVersion); // do not localize end; FCacheManager.Log('AppStart|' + GetTimestamp + '|' + OSVersion + '|' + CPUName + '|' + FAppVersion); // do not localize end; end; procedure TAppAnalyticsListener.TrackControlFocused(const TimeStamp: TDateTime; const Sender: TObject); begin if (TAppActivity.ControlFocused in FOptions) and (Sender is TComponent) and (FCacheManager <> nil) and (TComponent(Sender).ClassName <> FPreviousControlClassname) and (TComponent(Sender).Name <> FPreviousControlName) then begin FCacheManager.Log('ControlFocus|' + GetTimestamp + '|' + TComponent(Sender).ClassName + '|' + TComponent(Sender).Name + '|' + FPreviousControlClassname + '|' + FPreviousControlName); // do not localize FPreviousControlClassname := TComponent(Sender).ClassName; FPreviousControlName := TComponent(Sender).Name; end; end; procedure TAppAnalyticsListener.TrackException(const TimeStamp: TDateTime; const E: Exception); begin if (TAppActivity.Exception in FOptions) and (E <> nil) and (FCacheManager <> nil) then FCacheManager.Log('AppCrash|' + GetTimestamp + '|' + E.ClassName + '|' + E.Message); // do not localize end; procedure TAppAnalyticsListener.TrackEvent(const TimeStamp: TDateTime; const Sender, Context: TObject); var Builder: TStringBuilder; begin if (TAppActivity.Custom in FOptions) and (Context is TCustomEventContext) and (FCacheManager <> nil) then begin Builder := TStringBuilder.Create; try Builder.Append(TCustomEventContext(Context).Category); if TCustomEventContext(Context).Action <> '' then begin Builder.Append('|'); Builder.Append(TCustomEventContext(Context).Action); if TCustomEventContext(Context).Text <> '' then begin Builder.Append('|'); Builder.Append(TCustomEventContext(Context).Text); Builder.Append('|'); Builder.Append(FloatToStr(TCustomEventContext(Context).Value)); end; end; FCacheManager.Log('TrackEvent|' + GetTimestamp + '|' + Builder.ToString(True)); // do not localize finally Builder.Free; end; end; end; procedure TAppAnalyticsListener.TrackWindowActivated(const TimeStamp: TDateTime; const Sender: TObject); begin if (TAppActivity.WindowActivated in FOptions) and (Sender is TComponent) and (FCacheManager <> nil) and (TComponent(Sender).ClassName <> FPreviousFormClassname) and (TComponent(Sender).Name <> FPreviousFormName) then begin FCacheManager.Log('FormActivate|' + GetTimestamp + '|' + TComponent(Sender).ClassName + '|' + TComponent(Sender).Name + '|' + FPreviousFormClassname + '|' + FPreviousFormName); // do not localize FPreviousFormClassname := TComponent(Sender).ClassName; FPreviousFormName := TComponent(Sender).Name; end; end; { TCustomEventContext } constructor TCustomEventContext.Create(const ACategory, AAction, AText: string; const AValue: Double); begin inherited Create; FCategory := ACategory; FAction := AAction; FText := AText; FValue := AValue; end; { TAppAnalyticsCacheManager } constructor TAppAnalyticsCacheManager.Create(const AppID, UserID, ServerAddress: string; const ServerPort: Integer); begin inherited Create; FApplicationID := AppID; FUserID := UserID; FServerAddress := ServerAddress; FServerPort := ServerPort; FEventCount := 0; FDataCache := TStringList.Create; FMaxCacheSize := 500; end; destructor TAppAnalyticsCacheManager.Destroy; begin FDataCache.Free; inherited; end; procedure TAppAnalyticsCacheManager.AddEnvironmentField(const AKey, AValue: string); begin if AKey = 'OS' then FOSVersion := AValue else if AKey = 'CPU' then FCPUInfo := AValue else if AKey = 'APPVER' then FAppVersion := AValue; end; procedure TAppAnalyticsCacheManager.ClearData; begin FDataCache.Clear; end; function TAppAnalyticsCacheManager.GetCacheCount: Integer; begin Result := FDataCache.Count; end; function TAppAnalyticsCacheManager.GetEventAtIndex(const Index: Integer): string; begin if (Index >= 0) and (Index < FDataCache.Count) then Result := FDataCache[Index] else raise ERangeError.Create(SRangeError); end; function TAppAnalyticsCacheManager.GetMaxCacheSize: Integer; begin Result := FMaxCacheSize; end; function TAppAnalyticsCacheManager.GetOnDataCacheFull: TNotifyEvent; begin Result := FOnDataCacheFull; end; procedure TAppAnalyticsCacheManager.Log(const AMessage: string); begin TMonitor.Enter(FDataCache); try FDataCache.Add(IntToStr(FEventCount) + '|' + AMessage); Inc(FEventCount); finally TMonitor.Exit(FDataCache); end; if FDataCache.Count > FMaxCacheSize then if Assigned(FOnDataCacheFull) then FOnDataCacheFull(Self) else FDataCache.Clear; end; procedure CheckServerCertificate(const Sender: TObject; const ARequest: TURLRequest; const Certificate: TCertificate; var Accepted: Boolean); begin Accepted := True; end; class procedure TAppAnalyticsCacheManager.SendData(const ContentString, ServerAddress: string; const ServerPort: Integer); const URLTemplate = 'https://%s:%u/d.php'; // do not localize var HttpClient: THttpClient; DataStream: TStringStream; Header: TNetHeader; begin DataStream := TStringStream.Create(ContentString); HttpClient := THttpClient.Create; try HttpClient.ValidateServerCertificateCallback := CheckServerCertificate; Header := TNetHeader.Create(sContentType, 'application/x-www-form-urlencoded; charset=UTF8'); // do not localize try HttpClient.Post(Format(URLTemplate, [ServerAddress, ServerPort]), DataStream, nil, [Header]); except end; finally DataStream.Free; HttpClient.Free; end; end; procedure TAppAnalyticsCacheManager.PersistData(const Wait: Boolean); function BuildString: string; var I: Integer; DataCount: Integer; ContentBuilder: TStringBuilder; begin DataCount := FDataCache.Count; ContentBuilder := TStringBuilder.Create; try ContentBuilder.Append(Format('I=%s', [TNetEncoding.URL.Encode(FApplicationID)])); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('U=%s', [TNetEncoding.URL.Encode(FUserID)])); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('S=%s', [TNetEncoding.URL.Encode(FSessionID)])); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('N=%s', [TNetEncoding.URL.Encode(IntToStr(DataCount))])); // do not loalize ContentBuilder.Append('&'); { v2 data header } ContentBuilder.Append('V=2'); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('OS=%s', [TNetEncoding.URL.Encode(FOSVersion)])); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('CPU=%s', [TNetEncoding.URL.Encode(FCPUInfo)])); // do not localize ContentBuilder.Append('&'); ContentBuilder.Append(Format('APPVER=%s', [TNetEncoding.URL.Encode(FAppVersion)])); // do not localize ContentBuilder.Append('&'); { end v2} for I := 0 to DataCount - 1 do begin ContentBuilder.Append(Format('L%d=%s',[I, TNetEncoding.URL.Encode(Event[0])])); // do not localize RemoveEventAtIndex(0); if I < DataCount - 1 then ContentBuilder.Append('&'); end; Result := ContentBuilder.ToString(True); finally ContentBuilder.Free; end; end; var TransferThread: TThread; DataString: string; LServerAddress: string; LServerPort: Integer; begin if FDataCache.Count > 0 then begin DataString := BuildString; LServerAddress := FServerAddress; LServerPort := FServerPort; if Wait then TAppAnalyticsCacheManager.SendData(DataString, LServerAddress, LServerPort) else begin TransferThread := TThread.CreateAnonymousThread(procedure begin TAppAnalyticsCacheManager.SendData(DataString, LServerAddress, LServerPort); end); TransferThread.Start; end; end; end; procedure TAppAnalyticsCacheManager.RemoveEventAtIndex(const Index: Integer); begin if (Index >= 0) and (Index < FDataCache.Count) then begin TMonitor.Enter(FDataCache); try FDataCache.Delete(Index); finally TMonitor.Exit(FDataCache); end; end else raise ERangeError.Create(SRangeError); end; procedure TAppAnalyticsCacheManager.SetMaxCacheSize(const AValue: Integer); begin FMaxCacheSize := AValue; if FDataCache.Count >= AValue then if Assigned(FOnDataCacheFull) then FOnDataCacheFull(Self) else FDataCache.Clear; end; procedure TAppAnalyticsCacheManager.SetOnDataCacheFull(const AValue: TNotifyEvent); begin FOnDataCacheFull := AValue; end; end.
program integral3angle(output); {$F+} const a12 = 0.1; b12 = 0.4; a13 = -1.9; {Диапазоны выбрал самые маленькие} b13 = -1.8; a23 = -1.3; b23 = -1.0; eps1 = 0.0001; {Не включал eps как параметры функций, зачем?} eps2 = 0.0001; type func = function(x: real): real; var x12, x13, x23, s: real; function f1(x: real): real; begin f1 := 0.35 * sqr(x) - 0.95 * x + 2.7; end; function f2(x: real): real; begin f2 := exp(x * ln(3)) + 1; end; function f3(x: real): real; begin f3 := 1 / (x + 2); end; function df1(x: real): real; begin df1 := 0.7 * x - 0.95; end; function df2(x: real): real; begin df2 := exp(x * ln(3)) * ln(3); end; function df3(x: real): real; begin df3 := (-1) / sqr(x + 2); end; function fmg(f, g: func; a: real): real; begin fmg := f(a) - g(a); end; function cond(f, g: func; a, b: real): boolean; begin cond := (fmg(f, g, a) > 0) xor (fmg(f, g, (a + b) / 2) < (fmg(f, g, a) + fmg(f, g, b)) / 2); end; procedure root(f, g, df, dg: func; a, b: real; var x: real); var c1, c2, d, eps: real; ok: boolean; begin ok := cond(f, g, a, b); if ok then begin c1 := a; eps := eps1; end else begin c1 := b; b := a; eps := -eps1; end; d := b; repeat c1 := (c1 * fmg(f, g, b) - b * fmg(f, g, c1)) / (fmg(f, g, b) - fmg(f, g, c1)); c2 := d - fmg(f, g, d) / fmg(df, dg, d); d := c2; until (fmg(f, g, c2) * fmg(f, g, c2 - eps) < 0) or (fmg(f, g, c1) * fmg(f, g, c1 + eps) < 0); if fmg(f, g, c2) * fmg(f, g, c2 - eps1) < 0 then x := c2 else x := c1; end; function integral(f: func; a, b: real; var k: integer): real; var s1, s2n, sn, s2, h, x: real; i, n: integer; begin k := 0; n := 2; s1 := 0; s2n := 0; s2 := 2 * f(b - a) / 2; repeat inc(k); sn := s2n; n := n * 2; h := (b - a) / n; s2 := s2 + s1 / 2; s1 := 0; x := a - h; for i := 1 to n div 2 do begin x := x + 2 * h; s1 := s1 + f(x); end; s1 := s1 * 4; s2n := h / 3 * (s1 + s2 + f(a) + f(b)); until abs(sn - s2n) / 15 < eps2; integral := s2n; end; function max(a, b, c: real): real; begin if a > b then if a > c then max := a else max := c else if b > c then max := b else max := c; end; var i1, i2, i3: integer; s1, s2, s3: real; begin writeln('_________________________________________________________'); writeln('Puchkin Daniel, group 112, Computing of definite integral'); writeln('_________________________________________________________'); root(f1, f2, df1, df2, a12, b12, x12); root(f2, f3, df2, df3, a23, b23, x23); root(f1, f3, df1, df3, a13, b13, x13); if x13 < x12 then s1 := integral(f1, x13, x12, i1) {Условия для того,} else {чтобы не менять параметры функций} s1 := integral(f1, x12, x13, i1); {при изменении функций} if x23 < x12 then s2 := integral(f2, x23, x12, i2) else s2 := integral(f2, x12, x23, i2); if x13 < x23 then s3 := integral(f3, x13, x23, i3) else s3 := integral(f3, x23, x13, i3); s := s1 - s2 - s3; {Необходимо изменять знаки при изменении функций} writeln('Roots of equations:'); writeln('f1(x) = f2(x): ', x12); writeln('f2(x) = f3(x): ', x23); writeln('f1(x) = f3(x): ', x13); writeln('Definite integral: ', s); writeln('Number of iterations: ', i1 + i2 + i3); readln; end.
unit Rx.Observable.Defer; interface uses Rx, Rx.Implementations; type TDefer<T> = class(TObservableImpl<T>) type TFactory = Rx.TDefer<T>; strict private FFactory: TFactory; protected procedure OnSubscribe(Subscriber: ISubscriber<T>); override; public constructor Create(const Factory: TFactory); destructor Destroy; override; end; implementation { TDefer<T> } constructor TDefer<T>.Create(const Factory: TFactory); begin inherited Create; FFactory := Factory; end; destructor TDefer<T>.Destroy; begin FFactory := nil; inherited; end; procedure TDefer<T>.OnSubscribe(Subscriber: ISubscriber<T>); var O: TObservable<T>; begin O := FFactory(); O.Subscribe(Subscriber); end; end.
unit fNotesBP; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ExtCtrls, VA508AccessibilityManager; type TfrmNotesBP = class(TfrmAutoSz) Label1: TStaticText; btnPanel: TPanel; cmdPreview: TButton; cmdClose: TButton; grpOptions: TGroupBox; radReplace: TRadioButton; radAppend: TRadioButton; radIgnore: TRadioButton; procedure cmdPreviewClick(Sender: TObject); procedure cmdCloseClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure grpOptionsEnter(Sender: TObject); procedure radIgnoreExit(Sender: TObject); procedure radAppendExit(Sender: TObject); procedure radReplaceExit(Sender: TObject); procedure FormShow(Sender: TObject); private FBPText: TStrings; public { Public declarations } end; function QueryBoilerPlate(BPText: TStrings): Integer; implementation {$R *.DFM} uses ORFn, fRptBox, VAUtils; function QueryBoilerPlate(BPText: TStrings): Integer; var frmNotesBP: TfrmNotesBP; radIndex: integer; begin frmNotesBP := TfrmNotesBP.Create(Application); try ResizeFormToFont(TForm(frmNotesBP)); with frmNotesBP do begin Result := 0; FBPText := BPText; ShowModal; radIndex:= 0; //radIgnore.checked if radAppend.checked then radIndex := 1; if radReplace.checked then radIndex := 2; Result := radIndex; end; finally frmNotesBP.Release; end; end; procedure TfrmNotesBP.cmdPreviewClick(Sender: TObject); begin inherited; ReportBox(FBPText, 'Boilerplate Text Preview', False); end; procedure TfrmNotesBP.cmdCloseClick(Sender: TObject); begin inherited; Close; end; procedure TfrmNotesBP.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_ESCAPE then begin Key := 0; radIgnore.Checked := true; //Ignore Close; end; end; procedure TfrmNotesBP.FormShow(Sender: TObject); begin inherited; radIgnore.SetFocus; end; procedure TfrmNotesBP.grpOptionsEnter(Sender: TObject); begin inherited; if TabisPressed then begin if radReplace.Checked then radReplace.SetFocus; if radAppend.Checked then radAppend.SetFocus; if radIgnore.Checked then radIgnore.SetFocus; end; end; procedure TfrmNotesBP.radAppendExit(Sender: TObject); begin inherited; if ShiftTabisPressed then cmdClose.SetFocus; end; procedure TfrmNotesBP.radIgnoreExit(Sender: TObject); begin inherited; if ShiftTabisPressed then cmdClose.SetFocus; end; procedure TfrmNotesBP.radReplaceExit(Sender: TObject); begin inherited; if ShiftTabisPressed then cmdClose.SetFocus; end; end.
unit XfpGUIFrame; {$mode objfpc}{$H+} interface uses { FCL RTL } Classes, { X Stuff } X, XLib, { fpGUI units} fpg_base, fpg_main, fpg_x11, fpg_form, fpg_widget, fpg_label,fpg_button, ctypes, { program units } BaseWM, XfpGUIWM, XFrames, xfpwmwidgets, XRootWindow, xfpguiwindow; type { TfpGUIFrame } TfpGUIFrame = class(TXFrame) procedure FormPaint(Sender: TObject); private FOrigXY: TPoint; FStartDragPos: TPoint; FMouseIsDown: Boolean; FForm: TfpguiWindow; FTitleBar: TXfpgWMTitleBar; FfpgClientWindow: TfpgClientWindow; procedure FormResize(Sender: TObject); procedure CloseClick(Sender: TObject); procedure SetCaption(const AValue: String); override; procedure TitleBarMouseDown(Sender: TObject; AButton: TMouseButton; AShift: TShiftState; const AMousePos: TPoint); procedure TitleBarMouseUp(Sender: TObject; AButton: TMouseButton; AShift: TShiftState; const AMousePos: TPoint); procedure TitleBarMouseMove(Sender: TObject; AShift: TShiftState; const AMousePos: TPoint); procedure MoveWindow(APosition: TPoint); override; procedure ResizeWindow(Var AWidth, AHeight: Integer); override; public constructor Create(AOwner: TBaseWindowManager; AClientWindow: TWindow; AFrameWindow: TWindow; ARootWindow: TWindow; AX,AY,AW,AH: Integer); override; destructor Destroy; override; property Form: TfpguiWindow read FForm; end; implementation { TfpGUIFrame } procedure TfpGUIFrame.FormPaint ( Sender: TObject ) ; begin with FForm do fpgStyle.DrawControlFrame(Canvas, 0, 0, Width, Height ); end; procedure TfpGUIFrame.FormResize ( Sender: TObject ) ; begin FTitleBar.Width := FForm.Width; FTitleBar.UpdateWindowPosition; end; procedure TfpGUIFrame.CloseClick(Sender: TObject); begin CloseWindowNice; end; procedure TfpGUIFrame.SetCaption(const AValue: String); begin inherited SetCaption(AValue); FTitleBar.Title := AValue; end; procedure TfpGUIFrame.TitleBarMouseDown ( Sender: TObject; AButton: TMouseButton; AShift: TShiftState; const AMousePos: TPoint ) ; var WM: TfpGUIWindowManager; RootX, RootY: cint; CW: TWindow; CWX, CWY: cint; RW: TWindow; mask: cuint; begin WM := TfpGUIWindowManager(Owner); FMouseIsDown := True; //FOrigXY:= Point(FForm.Top, FForm.Left); //WriteLn('MOuse is down'); XQueryPointer(Display, RootWindow, @RW, @CW, @RootX, @RootY, @CWx, @CWy, @mask); FOrigXY := Point(RootX, RootY); FStartDragPos := Point(FForm.Left, FForm.Top); FTitleBar.MouseCursor := mcMove; BringWindowToFront; FocusWindow; end; procedure TfpGUIFrame.TitleBarMouseUp ( Sender: TObject; AButton: TMouseButton; AShift: TShiftState; const AMousePos: TPoint ) ; begin FMouseIsDown := False; FTitleBar.MouseCursor := mcArrow; //WriteLn('MOuse is UP'); end; procedure TfpGUIFrame.TitleBarMouseMove ( Sender: TObject; AShift: TShiftState; const AMousePos: TPoint ) ; var NewPos: TPoint; RootX, RootY: cint; CW: TWindow; CWX, CWY: cint; RW: TWindow; mask: cuint; begin if Not FMouseIsDown then Exit; XQueryPointer(Display, RootWindow, @RW, @CW, @RootX, @RootY, @CWx, @CWy, @mask); NewPos := FStartDragPos; NewPos.X := NewPos.X + (RootX-FOrigXY.X); NewPos.Y := NewPos.Y + (RootY-FOrigXY.Y); MoveWindow(NewPos); end; procedure TfpGUIFrame.MoveWindow ( APosition: TPoint ) ; begin FForm.Top := APosition.Y; FForm.Left := APosition.X; FForm.UpdateWindowPosition; ClientLeft := APosition.X; ClientTop := APosition.Y; Include(FFrameInitialProps, xfpMoved); //WriteLn('Moving Window ',APosition.x,':', APosition.y); end; procedure TfpGUIFrame.ResizeWindow ( var AWidth, AHeight: Integer ) ; begin if MinSize.Width >= 0 then AWidth := Max(MinSize.Width, AWidth); if MinSize.Height >= 0 then AHeight := Max(MinSize.Height, AHeight); if AWidth < (FTitleBar.Height*4)+FrameLeftWidth+FrameRightWidth then AWidth := (FTitleBar.Height*4)+FrameLeftWidth+FrameRightWidth; if AHeight < FTitleBar.Height+FrameBottomHeight+FrameTopHeight then AHeight := FTitleBar.Height+FrameBottomHeight+FrameTopHeight; FrameWidth := AWidth+FrameLeftWidth+FrameRightWidth; FrameHeight := AHeight+FrameTopHeight+FrameBottomHeight; // resize the client to fit in the frame window XResizeWindow(Display, ClientWindow, AWidth, AHeight); // resize the Frame to fit the client's wanted size // it's important to resize this window after FForm.Width := FrameWidth; FForm.Height := FrameHeight; FForm.UpdateWindowPosition; Include(FFrameInitialProps, xfpResized); WriteLn('ResizeWindow ', AWidth,';',AHeight); ClientHeight := AHeight; ClientWidth := AWidth; end; type TFPWMFormAccess = class(TfpgForm); constructor TfpGUIFrame.Create(AOwner: TBaseWindowManager; AClientWindow: TWindow; AFrameWindow: TWindow; ARootWindow: TWindow; AX,AY,AW,AH: Integer); begin // consider all buttons and labels in this routine as just the shortest route // to have the basic things a window needs. These must be changed later to be prettier. FForm := TfpguiWindow.Create(fpgApplication); FForm.OnResize := @FormResize; FForm.OnPaint := @FormPaint; FForm.Visible:=True; FfpgClientWindow := TfpgClientWindow.Create(FForm, AClientWindow); FTitleBar := TXfpgWMTitleBar.Create(FForm); FTitleBar.OnCloseButtonClick := @CloseClick; FTitleBar.Top := 0; FTitleBar.Left := 0; FTitleBar.Visible := True; FTitleBar.OnStartDrag := @TitleBarMouseDown; FTitleBar.OnMouseMove := @TitleBarMouseMove; FTitleBar.OnEndDrag := @TitleBarMouseUp; // create the TWindow that is the frame //Caption := TfpGUIWindowManager(AOwner).WindowGetTitle(AClientWindow); inherited Create(AOwner, AClientWindow, TWindow(fForm.Window.WinHandle), ARootWindow, AX,AY,AW,AH); end; destructor TfpGUIFrame.Destroy; begin fpgPostMessage(nil, FForm, FPGM_KILLME); inherited Destroy; end; end.
unit IFinanceGlobal; interface uses SysUtils, User, Vcl.Graphics, Location; type TFirstPayment = class strict private FMaxDaysHalf: byte; FHalfInterestRate: currency; FMinDaysHalf: byte; public property MinDaysHalfInterest: byte read FMinDaysHalf write FMinDaysHalf; property MaxDaysHalfInterest: byte read FMaxDaysHalf write FMaxDaysHalf; end; TRules = class strict private FFirstPayment: TFirstPayment; public property FirstPayment: TFirstPayment read FFirstPayment write FFirstPayment; constructor Create; end; TIFinance = class(TObject) private FAppName: string; FAppDescription: string; FAppDate: TDate; FLocationCode: string; FLocationPrefix: string; FUser: TUser; FPhotoPath: string; FPhotoUtility: string; FControlDisabledColor: TColor; FMaxComakeredLoans: byte; FAppImagesPath: string; FVersion: string; FLocations: array of TLocation; FDaysInAMonth: byte; FRules: TRules; FBacklogEntryEnabled: boolean; FCutoffDate: TDate; function GetLocation(const i: integer): TLocation; function GetLocationCount: integer; function GetHalfMonth: byte; function GetRequiredConfigEmpty: boolean; public procedure AddLocation(const loc: TLocation); function GetLocationNameByCode(const code: string): string; property AppDate: TDate read FAppDate write FAppDate; property LocationCode: string read FLocationCode write FLocationCode; property LocationPrefix: string read FLocationPrefix write FLocationPrefix; property User: TUser read FUser write FUser; property PhotoPath: string read FPhotoPath write FPhotoPath; property PhotoUtility: string read FPhotoUtility write FPhotoUtility; property ControlDisabledColor: TColor read FControlDisabledColor write FControlDisabledColor; property MaxComakeredLoans: byte read FMaxComakeredLoans write FMaxComakeredLoans; property AppImagesPath: string read FAppImagesPath write FAppImagesPath; property Version: string read FVersion write FVersion; property AppName: string read FAppName write FAppName; property AppDescription: string read FAppDescription write FAppDescription; property Locations[const i: integer]: TLocation read GetLocation; property LocationCount: integer read GetLocationCount; property DaysInAMonth: byte read FDaysInAMonth write FDaysInAMonth; property Rules: TRules read FRules write FRules; property HalfMonth: byte read GetHalfMonth; property BacklogEntryEnabled: boolean read FBacklogEntryEnabled write FBacklogEntryEnabled; property RequiredConfigEmpty: boolean read GetRequiredConfigEmpty; property CutoffDate: TDate read FCutoffDate write FCutoffDate; constructor Create; destructor Destroy; override; end; var ifn: TIFinance; implementation { TIFinance } constructor TIFinance.Create; begin if ifn <> nil then Abort else begin FAppName := 'i-Finance'; FAppDescription := 'Integrated Financial Management Information System'; FPhotoUtility := 'PhotoUtil.exe.'; FControlDisabledColor := clWhite; FMaxComakeredLoans := 3; FDaysInAMonth := 30; FUser := TUser.Create; FRules := TRules.Create; ifn := self; end; end; destructor TIFinance.Destroy; begin if ifn = self then ifn := nil; inherited Destroy; end; procedure TIFinance.AddLocation(const loc: TLocation); begin SetLength(FLocations,Length(FLocations) + 1); FLocations[Length(FLocations) - 1] := loc; end; function TIFinance.GetHalfMonth: byte; begin Result := 15; end; function TIFinance.GetLocation(const i: Integer): TLocation; begin Result := FLocations[i]; end; function TIFinance.GetLocationNameByCode(const code: string): string; var loc: TLocation; begin Result := 'Unknown'; for loc in FLocations do if code = Trim(loc.LocationCode) then begin Result := loc.LocationName; Exit; end; end; function TIFinance.GetRequiredConfigEmpty: boolean; begin Result := (FLocationCode = '') or (FLocationPrefix = ''); end; function TIFinance.GetLocationCount: integer; begin Result := Length(FLocations); end; { TRules } constructor TRules.Create; begin FFirstPayment := TFirstPayment.Create; FFirstPayment.MinDaysHalfInterest := 5; FFirstPayment.MaxDaysHalfInterest := 15; end; end.
unit uDB; interface uses System.SysUtils, System.Classes, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.Client, FireDAC.DApt; type TDB = class private class var FDBInstance: TDB; FConexao: TFDConnection; FDriverLink: TFDPhysFBDriverLink; FWaitCursor: TFDGUIxWaitCursor; constructor CreatePrivate; procedure DestroyPrivate; procedure onBeforeConnect(Sender: TObject); public constructor Create; destructor Destroy; override; function Conexao: TFDConnection; class function getInstance: TDB; end; implementation { TDB } function TDB.Conexao: TFDConnection; begin Result := FConexao; end; constructor TDB.Create; begin raise Exception.Create('Deve ser usado o getInstance()'); end; constructor TDB.CreatePrivate; begin FConexao := TFDConnection.Create(nil); FConexao.BeforeConnect := onBeforeConnect; FDriverLink := TFDPhysFBDriverLink.Create(nil); FWaitCursor := TFDGUIxWaitCursor.Create(nil); end; destructor TDB.Destroy; begin FConexao.Close; FreeAndNil(FConexao); FreeAndNil(FDriverLink); FreeAndNil(FWaitCursor); inherited; end; procedure TDB.DestroyPrivate; begin if Assigned(FDBInstance) then FreeAndNil(FDBInstance); end; class function TDB.getInstance: TDB; begin if not Assigned(FDBInstance) then FDBInstance := TDB.CreatePrivate; Result := FDBInstance; end; procedure TDB.onBeforeConnect(Sender: TObject); const Servidor_BD = '127.0.0.1'; Porta_BD = '3050'; DataBaseName = 'D:\Users\jperi\Documents\Embarcadero\Studio\Projects\OOPMVCAlexandre\DB\BANCO.fdb'; Usuario_BD = 'SYSDBA'; Senha_BD = 'masterkey'; begin FConexao.Params.Clear; FConexao.Params.Add('DriverID=FB'); FConexao.Params.Add('Server=' + Servidor_BD); FConexao.Params.Add('Port=' + Porta_BD); FConexao.Params.Add('Database=' + DataBaseName); FConexao.Params.Add('User_Name=' + Usuario_BD); FConexao.Params.Add('Password=' + Senha_BD); FConexao.Params.Add('Protocol=TCPIP'); FConexao.DriverName := 'FB'; FConexao.LoginPrompt := False; FConexao.UpdateOptions.CountUpdatedRecords := False; end; initialization finalization TDB.getInstance.DestroyPrivate; end.
unit Player.AudioOutput.PCMU; interface uses Windows,SysUtils,Classes,Types,Player.AudioOutput.Base,MediaProcessing.Definitions, ULaw; type TAudioOutputDecoder_PCMU= class (TAudioOutputDecoder) private FDecodeBuffer: TWordDynArray; public function IsDataValid(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal):boolean; override; function DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; override; end; TPlayerAudioOutput_PCMU= class (TPlayerAudioOutputWaveOut) public constructor Create; override; end; implementation { TAudioOutputDecoder_PCMU } function TAudioOutputDecoder_PCMU.DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; var i: integer; begin Assert(aFormat.AudioBitsPerSample=8); if cardinal(Length(FDecodeBuffer))<aDataSize then SetLength(FDecodeBuffer,aDataSize); for i:=0 to aDataSize-1 do FDecodeBuffer[i]:=ULaw.audio_u2s(PByte(aData)[i]); aPcmData:=@FDecodeBuffer[0]; aPcmDataSize:=aDataSize*2; aPcmFormat.Channels:=aFormat.AudioChannels; aPcmFormat.BitsPerSample:=16; aPcmFormat.SamplesPerSec:=aFormat.AudioSamplesPerSec; result:=true; end; { TPlayerAudioOutput_PCM } constructor TPlayerAudioOutput_PCMU.Create; begin inherited Create; RegisterDecoderClass(stPCMU,TAudioOutputDecoder_PCMU); SetStreamType(stPCMU); end; function TAudioOutputDecoder_PCMU.IsDataValid( const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal): boolean; begin result:=inherited IsDataValid(aFormat,aData,aDataSize,aInfo,aInfoSize); if result then result:=aFormat.AudioBitsPerSample=8; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------} unit untTvDirectoryOper; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, untEasyEdit, untEasySpinEdit, untEasyEditExt, untEasyGroupBox, untEasyButtons, untEasyPlateManager, untEasyLabel, unEasyComboBox, ImgList, untEasyClassPluginDirectory, ExtCtrls, untEasyMemo; type TfrmTvDirectoryOper = class(TForm) edtCName: TEasyLabelEdit; speOrder: TEasySpinEdit; edtImage1: TEasyButtonEdit; edtImage2: TEasyButtonEdit; rbDirectory: TEasyRadioButton; rbModules: TEasyRadioButton; btnSave: TEasyBitButton; btnCancel: TEasyBitButton; lblParentNode: TEasyLabel; ImageList1: TImageList; rgShowModal: TEasyRadioGroup; rgModuleEnable: TEasyRadioGroup; edtFileName: TEasyButtonEdit; dlgBpl: TOpenDialog; edtEName: TEasyLabelEdit; mmRemark: TEasyMemo; procedure btnCancelClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edtImage1ButtonClick(Sender: TObject); procedure edtImage2ButtonClick(Sender: TObject); procedure rbDirectoryClick(Sender: TObject); procedure rbModulesClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtFileNameButtonClick(Sender: TObject); private { Private declarations } FAData: TEasysysPluginsDirectory; function CheckNotNullControl: Boolean; public { Public declarations } end; var frmTvDirectoryOper: TfrmTvDirectoryOper; procedure ShowfrmTvDirectoryOper(var AData: TEasysysPluginsDirectory; AFlag: string; ParentCName: string = ''); implementation uses untEasyUtilMethod, untEasyImageSelect; {$R *.dfm} const Remark_NULL = '暂无说明'; procedure ShowfrmTvDirectoryOper(var AData: TEasysysPluginsDirectory; AFlag: string; ParentCName: string = ''); begin try frmTvDirectoryOper := TfrmTvDirectoryOper.Create(Application); frmTvDirectoryOper.lblParentNode.Caption := ''; if AFlag = 'Add' then begin frmTvDirectoryOper.Caption := frmTvDirectoryOper.Caption + '-[新增]'; if ParentCName <> '' then frmTvDirectoryOper.lblParentNode.Caption := '上级节点: 【' + ParentCName +'】'; end else if AFlag = 'Edit' then begin frmTvDirectoryOper.Caption := frmTvDirectoryOper.Caption + '-[编辑]'; with frmTvDirectoryOper do begin edtCName.Text := AData.PluginCName; edtEName.Text := AData.PluginEName; speOrder.Value := AData.iOrder; edtImage1.Text := IntToStr(AData.ImageIndex); edtImage2.Text := IntToStr(AData.SelectedImageIndex); if AData.IsDirectory then rbDirectory.Checked := True else begin rbModules.Checked := True; edtFileName.Text := AData.PluginFileName; end; if AData.ShowModal then rgShowModal.ItemIndex := 0; if AData.IsEnable then rgModuleEnable.ItemIndex := 0; if Trim(AData.Remark) = '' then mmRemark.Text := Remark_NULL; end; end; //引出交换数据 frmTvDirectoryOper.FAData := AData; frmTvDirectoryOper.ShowModal; finally FreeAndNil(frmTvDirectoryOper); end; end; procedure TfrmTvDirectoryOper.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmTvDirectoryOper.btnSaveClick(Sender: TObject); begin if CheckNotNullControl then Exit; if trim(FAData.PluginGUID) = '' then //新增时生成GUID FAData.PluginGUID := GenerateGUID; FAData.PluginCName := Trim(edtCName.Text); FAData.PluginEName := Trim(edtEName.Text); FAData.iOrder := StrToInt(speOrder.Text); FAData.ImageIndex := StrToInt(edtImage1.Text); FAData.SelectedImageIndex := StrToInt(edtImage2.Text); if mmRemark.Lines.Text <> Remark_NULL then FAData.Remark := mmRemark.Lines.Text; //先设置模块是否目录属性,后面有使用 if rbDirectory.Checked then FAData.IsDirectory := True else FAData.IsDirectory := False; //模态显示 if rgShowModal.ItemIndex = 0 then FAData.ShowModal := True else FAData.ShowModal := False; if not rbDirectory.Checked then // FAData.PluginFileName := edtFileName.Text; FAData.PluginFileName := ExtractFileName(edtFileName.Text); //目录不能被停用 if FAData.IsDirectory then FAData.IsEnable := True else begin if rgModuleEnable.ItemIndex = 0 then FAData.IsEnable := True else FAData.IsEnable := False; end; Close; end; procedure TfrmTvDirectoryOper.FormCreate(Sender: TObject); begin edtImage1.Text := '-1'; edtImage2.Text := '-1'; end; procedure TfrmTvDirectoryOper.edtImage1ButtonClick(Sender: TObject); begin edtImage1.Text := IntToStr(EasySelectImage); end; procedure TfrmTvDirectoryOper.edtImage2ButtonClick(Sender: TObject); begin edtImage2.Text := IntToStr(EasySelectImage); end; procedure TfrmTvDirectoryOper.rbDirectoryClick(Sender: TObject); begin if rbDirectory.Checked then begin edtFileName.Enabled := False; rgShowModal.Enabled := False; if Pos('新增', Caption) > 0 then begin edtImage1.Text := '0'; edtImage2.Text := '1'; end; end else begin edtFileName.Enabled := True; rgShowModal.Enabled := True; end; end; procedure TfrmTvDirectoryOper.rbModulesClick(Sender: TObject); begin if rbModules.Checked then begin edtFileName.Enabled := True; rgShowModal.Enabled := True; if Pos('新增', Caption) > 0 then begin edtImage1.Text := '2'; edtImage2.Text := '2'; end; end else begin edtFileName.Enabled := False; rgShowModal.Enabled := False; end; end; function TfrmTvDirectoryOper.CheckNotNullControl: Boolean; begin Result := False; if Trim(edtCName.Text) = '' then begin Application.MessageBox('模块中文名称不能为空!', '提示', MB_OK + MB_ICONWARNING); Result := True; Exit; end; if Trim(speOrder.Text) = '' then begin Application.MessageBox('模块序号不能为空!', '提示', MB_OK + MB_ICONWARNING); Result := True; Exit; end; if not rbDirectory.Checked then begin if Trim(edtFileName.Text) = '' then begin Application.MessageBox('模块文件不能为空!', '提示', MB_OK + MB_ICONWARNING); Result := True; Exit; end; end; end; procedure TfrmTvDirectoryOper.FormShow(Sender: TObject); begin edtCName.EditLabel.Font.Color := clBlue; speOrder.EditLabel.Font.Color := clBlue; edtFileName.EditLabel.Font.Color := clBlue; edtCName.EditLabel.Transparent := True; speOrder.EditLabel.Transparent := True; edtFileName.EditLabel.Transparent := True; //默认选中目录 置文件选择框不可用 edtFileName.Enabled := False; rbDirectoryClick(Sender); end; procedure TfrmTvDirectoryOper.edtFileNameButtonClick(Sender: TObject); begin if rbModules.Checked then begin dlgBpl.InitialDir := ExtractFilePath(Application.ExeName) + 'plugins\'; if dlgBpl.Execute then edtFileName.Text := dlgBpl.FileName; end; end; end.
unit ClienteServidor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Datasnap.DBClient, Data.DB,System.zip,System.Threading, Data.FMTBcd, Data.SqlExpr ; type TServidor = class private NArquivo: Integer; FPath: AnsiString; public constructor Create; procedure SalvarArquivos(AData: OleVariant); procedure SalvarArquivosParalelo(AData: OleVariant); procedure ApagarArquivos; end; TfClienteServidor = class(TForm) ProgressBar: TProgressBar; btEnviarSemErros: TButton; btEnviarComErros: TButton; btEnviarParalelo: TButton; SQLTable1: TSQLTable; procedure FormCreate(Sender: TObject); procedure btEnviarSemErrosClick(Sender: TObject); procedure btEnviarComErrosClick(Sender: TObject); procedure btEnviarParaleloClick(Sender: TObject); private FPath: AnsiString; FServidor: TServidor; QtThreadEnvio: Integer; function InitDataset: TClientDataset; public end; var fClienteServidor: TfClienteServidor; const QTD_ARQUIVOS_ENVIAR = 100; implementation uses IOUtils; {$R *.dfm} procedure TfClienteServidor.btEnviarComErrosClick(Sender: TObject); var cds: TClientDataset; i: Integer; begin try FServidor.ApagarArquivos; with ProgressBar do begin position:=0; max:=QTD_ARQUIVOS_ENVIAR; visible:=true; end; cds := InitDataset; for i := 0 to QTD_ARQUIVOS_ENVIAR do begin ProgressBar.position:=i; application.ProcessMessages; cds.Append; TBlobField(cds.FieldByName('Arquivo')).LoadFromFile(String(FPath)); cds.Post; {$REGION Simulação de erro, não alterar} if i = (QTD_ARQUIVOS_ENVIAR/2) then FServidor.SalvarArquivos(NULL); {$ENDREGION} end; FServidor.SalvarArquivos(cds.Data); except FServidor.ApagarArquivos; end; end; procedure TfClienteServidor.btEnviarParaleloClick(Sender: TObject); begin try QtThreadEnvio:=0; FServidor.ApagarArquivos; with ProgressBar do begin position:=0; max:=QTD_ARQUIVOS_ENVIAR-1; visible:=true; end; TTask.Run( procedure begin TParallel.For(0,QTD_ARQUIVOS_ENVIAR-1, procedure (Index: Integer) begin TThread.Queue(TThread.CurrentThread, procedure var cds: TClientDataset; begin try Inc(fClienteServidor.QtThreadEnvio); cds := fClienteServidor.InitDataset; fClienteServidor.Progressbar.position:=fClienteServidor.ProgressBar.position+1; cds.Append; TBlobField(cds.FieldByName('Arquivo')).LoadFromFile(String(FPath)); cds.Post; fClienteServidor.Fservidor.SalvarArquivosParalelo(cds.Data); cds.EmptyDataSet; cds.close; cds.free; finally Dec(fClienteServidor.QtThreadEnvio); end; end); end); end); finally end; end; procedure TfClienteServidor.btEnviarSemErrosClick(Sender: TObject); var cds: TClientDataset; i: Integer; begin try with ProgressBar do begin position:=0; max:=QTD_ARQUIVOS_ENVIAR-1; visible:=true; end; FServidor.ApagarArquivos; cds := InitDataset; for i := 0 to QTD_ARQUIVOS_ENVIAR - 1 do begin ProgressBar.position:=i; application.ProcessMessages; cds.Append; TBlobField(cds.FieldByName('Arquivo')).LoadFromFile(String(FPath)); cds.Post; FServidor.SalvarArquivos(cds.Data); cds.EmptyDataSet; end; finally with ProgressBar do begin visible:=false; position:=0; end; end; end; procedure TfClienteServidor.FormCreate(Sender: TObject); begin inherited; FPath := AnsiString(ExtractFilePath(ParamStr(0)) + 'pdf.pdf'); FServidor := TServidor.Create; QtThreadEnvio:=0; end; function TfClienteServidor.InitDataset: TClientDataset; begin Result := TClientDataset.Create(nil); Result.FieldDefs.Add('Arquivo', ftBlob); Result.CreateDataSet; end; { TServidor } procedure TServidor.ApagarArquivos; var i: integer; sr: TSearchRec; begin try i := FindFirst(string(FPath)+'*.*', faAnyFile, sr); while i = 0 do begin DeleteFile(string(FPath)+sr.name); i := Findnext(sr); end; finally NArquivo := 0; end; end; constructor TServidor.Create; begin FPath := AnsiString(ExtractFilePath(string(ParamStr(0))) + 'Servidor\'); end; procedure TServidor.SalvarArquivos(AData: OleVariant); var cds: TClientDataSet; FileName: string; begin try if not DirectoryExists(string(FPath)) then if not CreateDir(string(FPath)) then ForceDirectories(string(FPath)); cds := TClientDataset.Create(nil); cds.Data := AData; {$REGION Simulação de erro, não alterar} if cds.RecordCount = 0 then Exit; {$ENDREGION} cds.First; while not cds.Eof do begin inc(NArquivo); FileName := string(FPath) + inttostr(NArquivo) + '.pdf'; if TFile.Exists(FileName) then TFile.Delete(FileName); TBlobField(cds.FieldByName('Arquivo')).SaveToFile(FileName); cds.delete; end; cds.EmptyDataSet; cds.close; cds.Free; except raise; end; end; procedure TServidor.SalvarArquivosParalelo(AData: OleVariant); var cds: TClientDataSet; FileName: string; begin try if not DirectoryExists(string(FPath)) then if not CreateDir(string(FPath)) then ForceDirectories(string(FPath)); TThread.Queue(TThread.CurrentThread, procedure var NArquivoThread:integer; begin cds := TClientDataset.Create(nil); cds.Data := AData; NArquivoThread:=NArquivo; NArquivo:=NArquivo+cds.recordcount; {$REGION Simulação de erro, não alterar} if cds.RecordCount = 0 then Exit; {$ENDREGION} cds.First; while not cds.Eof do begin inc(NArquivoThread); FileName := String(FPath) + inttostr(NArquivoThread) + '.pdf'; if TFile.Exists(String(FileName)) then TFile.Delete(String(FileName)); TBlobField(cds.FieldByName('Arquivo')).SaveToFile(FileName); cds.delete; end; cds.EmptyDataSet; cds.close; end); except raise; end; end; end.
unit FormHlavneOkno; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ScktComp, StdCtrls; type THlavneOkno = class(TForm) ButtonPripojit: TButton; ClientSocket: TClientSocket; Memo: TMemo; procedure ButtonPripojitClick(Sender: TObject); procedure ClientSocketConnecting(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocketConnect(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocketError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); private { Private declarations } public { Public declarations } end; var HlavneOkno: THlavneOkno; implementation {$R *.DFM} procedure THlavneOkno.ButtonPripojitClick(Sender: TObject); begin if ClientSocket.Active then begin ButtonPripojit.Caption := '&Pripojiť'; ClientSocket.Close; end else begin ButtonPripojit.Caption := '&Odpojiť'; ClientSocket.Address := 'http://www.zoznam.sk/'; ClientSocket.Open; end; end; procedure THlavneOkno.ClientSocketConnecting(Sender: TObject; Socket: TCustomWinSocket); begin Memo.Lines.Add('Conecting ...'); end; procedure THlavneOkno.ClientSocketConnect(Sender: TObject; Socket: TCustomWinSocket); begin Memo.Lines.Add('Connected.'); end; procedure THlavneOkno.ClientSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin Memo.Lines.Add('Disconnected.'); end; procedure THlavneOkno.ClientSocketError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin Memo.Lines.Add('Error'); end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit BindCompReg; interface uses System.Classes, System.SysUtils, Data.Bind.Components, DesignEditors, DesignIntf, ColnEdit, Vcl.ActnList, System.Generics.Collections, Data.Bind.ObjectScope, ValueEdit, StringsEdit; type TDataBindingFactory = class(TInterfacedObject, IBindCompFactory) private protected FCategory: string; FClass: TContainedBindCompClass; function Enabled(AContext: IBindCompFactoryContext): Boolean; virtual; function GetCommandText(AContext: IBindCompFactoryContext): string; virtual; procedure Execute(AContext: IBindCompFactoryExecuteContext); virtual; public constructor Create(ACategory: string; AClass: TContainedBindCompClass); end; TRttiUnitSelectionEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; TCustomBindCompListSelectionEditor = class(TSelectionEditor) public procedure RequiresUnits(Proc: TGetStrProc); override; end; TBaseDataGeneratorSelectionEditor = class(TSelectionEditor) protected function GetDataGenerator(AComponent: TComponent): TCustomDataGeneratorAdapter; virtual; public procedure RequiresUnits(Proc: TGetStrProc); override; end; TDataGeneratorSelectionEditor = TBaseDataGeneratorSelectionEditor; TPrototypeBindSourceDataGeneratorSelectionEditor = class(TBaseDataGeneratorSelectionEditor) protected function GetDataGenerator(AComponent: TComponent): TCustomDataGeneratorAdapter; override; end; TBindCompExpressionEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindingComponentPropertyEditor = class(TStringProperty) protected function GetBindComponent: TContainedBindComponent; function GetComponentProperty(const AName: string): TComponent; function GetStringProperty(const AName: string): string; public procedure GetValueList(List: TStrings); virtual; abstract; function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TSourceMemberNamePropertyEditor = class(TBindingComponentPropertyEditor) private function GetSourceComponent: TComponent; protected procedure GetMemberNames(ASourceComponent: TComponent; List: TStrings); virtual; function GetSourceComponentName: string; virtual; public procedure GetValueList(List: TStrings); override; end; TFieldNamePropertyEditor = class(TSourceMemberNamePropertyEditor) protected function GetSourceComponentName: string; override; end; TLinkFillControlToFieldFieldNamePropertyEditor = class(TSourceMemberNamePropertyEditor) protected function GetSourceComponentName: string; override; end; TFillFieldNamePropertyEditor = class(TFieldNamePropertyEditor) // protected // function GetSourceComponentName: string; override; end; TEditorNamePropertyEditor = class(TBindingComponentPropertyEditor) private function GetControlComponent: TComponent; protected procedure GetEditorNames(AControlComponent: TComponent; List: TStrings); virtual; function GetControlComponentName: string; virtual; public function GetValue: string; override; procedure SetValue(const Value: string); override; procedure GetValueList(List: TStrings); override; end; TLinkingControlPropertyEditor = class(TComponentProperty) private FProc: TGetStrProc; procedure InternalStrProc(const S: string); protected function IsValidControl(AComponent: TComponent): Boolean; virtual; public procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TLinkingFillControlPropertyEditor = class(TLinkingControlPropertyEditor) protected function IsValidControl(AComponent: TComponent): Boolean; override; end; TFillCustomFormatPropertyEditor = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TControlMembersPropertyEditor = class(TBindingComponentPropertyEditor) private function GetControlComponent: TComponent; function GetEditorName: string; protected function GetEditor(AControlComponent: TComponent; const AEditor: string): IInterface; virtual; procedure GetItemMemberNames(AControlComponent: TComponent; const AEditor: string; AList: TStrings); virtual; function GetControlComponentName: string; virtual; function GetEditorPropertyName: string; virtual; public procedure GetValueList(List: TStrings); override; end; TLookupFieldNamePropertyEditor = class(TSourceMemberNamePropertyEditor) protected function GetSourceComponentName: string; override; end; TLookupKeyFieldNamePropertyEditor = class(TLookupFieldNamePropertyEditor) protected procedure GetMemberNames(ASourceComponent: TComponent; List: TStrings); override; end; TGeneratorNamePropertyEditor = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; function GetValueList: TArray<string>; virtual; procedure GetValues(Proc: TGetStrProc); override; end; TFormatExpressionSourceMemberEditor = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; function GetValueList: TArray<string>; virtual; procedure GetValues(Proc: TGetStrProc); override; end; TUseDataGeneratorPropertyEditor = class(TBoolProperty) const sName = 'UseDataGenerator'; public procedure SetValue(const Value: string); override; end; TAdapterPropertyEditor = class(TComponentProperty) const sName = 'Adapter'; public procedure SetValue(const Value: string); override; end; TLinkingBindScopePropertyEditor = class(TComponentProperty) public procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TLBComponentFilterFunc = TFunc<TComponent,string,Boolean>; TLBVisualizationPropertyManager = class private class var FInstance: TLBVisualizationPropertyManager; private FProcs: TList<TLBComponentFilterFunc>; class function Instance: TLBVisualizationPropertyManager; public constructor Create; destructor Destroy; override; class procedure AddComponentFilter(AFilterFunc: TLBComponentFilterFunc); class procedure RemoveComponentFilter(AFilterFunc: TLBComponentFilterFunc); class function GetComponentFiltersFuncArray: TArray<TLBComponentFilterFunc>; end; TLBVisualizationPropertyFilter = class(TSelectionEditor, ISelectionPropertyFilter) protected { ISelectionPropertyFilter } procedure FilterProperties(const ASelection: IDesignerSelections; const ASelectionProperties: IInterfaceList); end; TAddDataBindingsPropertyFilter = class(TSelectionEditor, ISelectionPropertyFilter) protected { ISelectionPropertyFilter } procedure FilterProperties(const ASelection: IDesignerSelections; const ASelectionProperties: IInterfaceList); end; TBindCompFactorySelectionEditor = class(TSelectionEditor) private FTempStringList: TStrings; FActions: TList<TCustomAction>; class procedure AddDataBindingAction(AFactory: IBindCompFactory; Info: Pointer); procedure AddFactoryActions(AList: TList<TCustomAction>); procedure AddTempString(const S: string); procedure CreateDataBindingFactoryContext(Sender: TObject; ABindCompList: TCustomBindingsList; out AContext: IBindCompFactoryContext); procedure CreateNewDataBindingFactory(Sender: TObject; DataBindingFactory: IBindCompFactory; BindingsList: TCustomBindingsList); function CreateDataBindingFactoryExecuteContext( ABindCompList: TCustomBindingsList): IBindCompFactoryExecuteContext; public function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure ExecuteVerb(Index: Integer; const List: IDesignerSelections); override; constructor Create(const ADesigner: IDesigner); override; destructor Destroy; override; procedure RequiresUnits(Proc: TGetStrProc); override; end; TAddBindScopeSelectionEditor = class(TSelectionEditor) private function CanHaveBindScope(AComponent: TComponent): Boolean; procedure CreateBindScope(AComponent: TComponent); public function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure ExecuteVerb(Index: Integer; const List: IDesignerSelections); override; end; TComponentPropertyNamesProperty = class(TStringProperty) public class function GetComponentPropertyNames(AComponent: TComponent): TArray<string>; overload; static; class function HasComponentPropertyName(AComponent: TComponent; const AName: string): Boolean; overload; static; function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; function GetPropertyComponent: TComponent; virtual; function GetValueList: TArray<string>; virtual; end; TLinkControlToPropertyNamesEditor = class(TComponentPropertyNamesProperty) public function GetPropertyComponent: TComponent; override; end; TLinkPropertyToFieldPropertyNamesEditor = class(TComponentPropertyNamesProperty) public function GetPropertyComponent: TComponent; override; end; TBaseLinkingBindScopeEditor = class(TComponentEditor) public procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TScopeAdapterFieldsEditor = class(TBaseLinkingBindScopeEditor) private function GetCollection: TCollection; function GetPropertyName: string; public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TGetDesignerComponents = class type TComponentPropertyClass = class(TComponent) private FComponent: TComponent; published property Component: TComponent read FComponent write FComponent; end; private class var FCounter: Integer; private var FDesigner: IDesigner; FComponentProc: TProc<TComponent, string>; procedure ComponentNameProc(const RootName: string); public constructor Create(const ADesigner: IDesigner); function IsExternalComponent(AComponent: TComponent): Boolean; procedure GetDesignerComponents(AProc: TProc<TComponent, string>); end; type TPersistentPair = TPair<string, TPersistent>; function GetDataSourceMemberNames(AComponent: TComponent; AList: TStrings): Boolean; overload; function GetDataSourceMemberNames(AComponent: TComponent): TArray<TPersistentPair>; overload; function IsDataSourceMemberName(AComponent: TComponent; const AMemberName: string): Boolean; function IsDataSourceComponent(AComponent: TComponent): Boolean; function CreateBindingsList(AOwner: TComponent): TBindingsList; function FindBindingsList(AOwner: TComponent): TBindingsList; procedure GetComponentPropertyNames(AComponent: TComponent; AList: TList<string>); procedure GetBindComponentsOfControl(AComponent: TComponent; AFunc: TFunc<TContainedBindComponent, Boolean>); procedure GetBindComponentsOfComponentProperty(AComponent: TComponent; const AProperty: string; AFunc: TFunc<TContainedBindComponent, Boolean>); function FindBindComponentsLinkToControl(const AControl: TComponent): TArray<TContainedBindComponent>; function ConfirmDeleteBindComponents(const ADesigner: IDesigner; AComponents: TArray<TContainedBindComponent>; ANewClass: TComponentClass = nil): Boolean; procedure DeleteBindComponents(const ADesigner: IDesigner; AComponents: TArray<TContainedBindComponent>); function FindBindComponentsLinkToComponentProperty(const AComponent: TComponent; const APropertyName: string): TArray<TContainedBindComponent>; function DefaultTrackControl(AControl: TComponent): Boolean; function ShowLiveBindingsWizard: Boolean; function BindScopeOfDataSourceComponent(const ADesigner: IDesigner; AComponent: TComponent): TComponent; function CreateUniqueComponentName(AOwner: TComponent; const APrefix, AMemberName: string): string; procedure GetOwnedAndLinkedComponents(ADesigner: IDesigner; AProc: TProc<TComponent, string>); function GetOwnedAndLinkedComponentsList(ADesigner: IDesigner): TArray<TComponent>; function IntroducedInAncestor(AComponent: TComponent): Boolean; procedure Register; implementation uses DsnConst, Vcl.Forms, Winapi.Windows,Vcl.Controls, Vcl.Themes, Winapi.UxTheme, VisualizationServicesAPI, BindCompEdit, BindCompDsnResStrs, Vcl.Graphics, Vcl.ComCtrls, Vcl.Menus, System.Math, ComponentDesigner, Vcl.GraphUtil,System.TypInfo, DesignConst, TreeIntf, BindCompBasePropEditor, System.StrUtils, System.Types, ToolsAPI, PropInspApi, BindCompProperties, BindMethodsFormU, BindOutputConvertersFormU, System.Bindings.EvalProtocol, System.Bindings.Methods, System.Bindings.Outputs, BindCompExprEdit, Data.Bind.Consts, Data.Bind.DBLinks, System.Bindings.ObjEval, // initialization Data.Bind.DBScope, Data.Bind.EngExt, Vcl.Dialogs, Proxies, System.Rtti, Data.Db, BindNewFieldDlg, BindAdapterFieldColnEdit, Data.Bind.Grid, LiveBindingsGenOptFrame, StdConst, Data.Bind.GenData, System.RTLConsts, System.Character; // Register { TBindCompListEditor } type TBindCompListEditor = class(TComponentEditor) private procedure ExecuteNewBindingsDlg; public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindFillListExpressionEditor = class(TBindCompExpressionEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindFillGridLinkExpressionEditor = class(TBindCompExpressionEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindFillGridListExpressionEditor = class(TBindCompExpressionEditor) private function GetBindList: TCustomBindGridList; public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindEvaluateExpressionEditor = class(TBindCompExpressionEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TBindEvaluateExprItemsEditor = class(TBindCompExpressionEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TAddActionInfo = record FContext: IBindCompFactoryContext; FBindingsList: TCustomBindingsList; FList: TList<TCustomAction>; end; PAddActionInfo = ^TAddActionInfo; TFactoryAction = class(TCustomAction) private FBindingsList: TCustomBindingsList; FFactory: IBindCompFactory; public constructor Create(const ACaption: string; ABindingsList: TCustomBindingsList; AFactory: IBindCompFactory); reintroduce; function Execute: Boolean; override; end; TVerbAction = class(TCustomAction) private FVerb: Integer; FDesigner: IDesigner; FComponent: TComponent; public constructor Create(const ACaption: string; AComponent: TComponent; AVerb: integer; ADesigner: IDesigner); reintroduce; function Execute: Boolean; override; end; TDataBindingFactoryContext = class(TInterfacedObject, IBindCompFactoryContext) private FBindCompList: TCustomBindingsList; FControlComponent: TComponent; FDesigner: IDesigner; protected function GetOwner: TComponent; function GetBindingsList: TCustomBindingsList; function GetControlComponent: TComponent; function GetDesigner: IInterface; public constructor Create(ADesigner: IDesigner; ABindCompList: TCustomBindingsList; AControlComponent: TComponent); end; TDataBindingFactoryExecuteContext = class(TDataBindingFactoryContext, IBindCompFactoryExecuteContext) protected function UniqueName(const ABaseName: string): string; virtual; procedure BindCompCreated(AComponent: TComponent); virtual; end; TDataLinkProperty = class(TObject) protected function GetOwner: TComponent; virtual; abstract; public property Owner: TComponent read GetOwner; end; { TBindCompListView } TNewDataBindingEvent = procedure(Sender: TObject; const Category: string; DataBindingClass: TContainedBindCompClass; BindingsList: TCustomBindingsList) of object; TNewDataBindingFactoryEvent = procedure(Sender: TObject; DataBindingFactory: IBindCompFactory; BindingsList: TCustomBindingsList) of object; TCreateDataBindingFactoryContext = procedure(Sender: TObject; BindingsList: TCustomBindingsList; var AContext: IBindCompFactoryContext) of object; TSelectDataBindingEvent = procedure(Sender: TObject; DataBinding: TContainedBindComponent) of object; TBindCompListViewOption = (dblvSelect, dblvDelete, dblvCreateNew, dblvCreateNewFactory, dblvSelectExisting); TBindCompListViewOptions = set of TBindCompListViewOption; TBindCompListView = class(TCustomListView) private const FDefItemHeight = 17; private FSelectComponentItem: TListItem; FDeleteComponentItem: TListItem; FActionsDictionary: TDictionary<TListItem, TCustomAction>; FDesigner: IDesigner; FImageList: TImageList; FTempStringList: TStrings; FOnNewDataBinding: TNewDataBindingEvent; FOnNewDataBindingFactory: TNewDataBindingFactoryEvent; FOnSelectDataBindingProperty: TSelectDataBindingEvent; FOnSelectDataBindingComponent: TNotifyEvent; FOnDeleteDataBinding: TNotifyEvent; FOptions: TBindCompListViewOptions; FDataBindingComponentName: string; FCreateDataBindingFactoryContext: TCreateDataBindingFactoryContext; FControlComponent: TComponent; FCustomActions: TArray<TCustomAction>; procedure AddTempString(const S: string); procedure RebuildListView; procedure SetDesigner(const Value: IDesigner); procedure AddFactoryActions(AList: TList<TCustomAction>); class procedure AddDataBindingAction(AFactory: IBindCompFactory; Info: Pointer); class procedure AddVerbActions(AComponent: TComponent; AList: TList<TCustomAction>; ADesigner: IDesigner); protected procedure CreateWnd; override; function CustomDrawItem(Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; override; function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Click; override; property CustomActions: TArray<TCustomAction> read FCustomActions write FCustomActions; property ControlComponent: TComponent read FControlComponent write FControlComponent; property Options: TBindCompListViewOptions read FOptions write FOptions; property DataBindingComponentName: string read FDataBindingComponentName write FDataBindingComponentName; property Designer: IDesigner read FDesigner write SetDesigner; property OnNewDataBinding: TNewDataBindingEvent read FOnNewDataBinding write FOnNewDataBinding; property OnNewDataBindingFactory: TNewDataBindingFactoryEvent read FOnNewDataBindingFactory write FOnNewDataBindingFactory; property OnCreateDataBindingFactoryContext: TCreateDataBindingFactoryContext read FCreateDataBindingFactoryContext write FCreateDataBindingFactoryContext; property OnDeleteDataBinding: TNotifyEvent read FOnDeleteDataBinding write FOnDeleteDataBinding; property OnSelectDataBindingProperty: TSelectDataBindingEvent read FOnSelectDataBindingProperty write FOnSelectDataBindingProperty; property OnSelectDataBindingComponent: TNotifyEvent read FOnSelectDataBindingComponent write FOnSelectDataBindingComponent; end; TProxyComponent = class; TBindArtifactsPropertyEditor = class(TClassProperty) protected procedure ShowForm(AComponent: TComponent; AMethods: TBindArtifacts); virtual; abstract; public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TMethodsPropertyEditor = class(TBindArtifactsPropertyEditor) protected procedure ShowForm(AComponent: TComponent; AArtifacts: TBindArtifacts); override; end; TOutputConvertersPropertyEditor = class(TBindArtifactsPropertyEditor) protected procedure ShowForm(AComponent: TComponent; AArtifacts: TBindArtifacts); override; end; TCustomBindCompListSprig = class(TComponentSprig) end; TCustomDataBindingSprig = class(TComponentSprig) public procedure FigureParent; override; function DragDropTo(AItem: TSprig): Boolean; override; function DragOverTo(AItem: TSprig): Boolean; override; function ItemIndex: Integer; override; end; TCustomAssociatedDataBindingSprig = class(TComponentSprig) public procedure FigureParent; override; function DragDropTo(AItem: TSprig): Boolean; override; function DragOverTo(AItem: TSprig): Boolean; override; function ItemIndex: Integer; override; end; TDataBindingCategorySprig = class(TTransientCollectionSprig) private FBindCompList: TCustomBindingsList; FCategory: string; public function UniqueName: string; override; function Caption: string; override; procedure FigureParent; override; function SortByIndex: Boolean; override; end; TComponentDataBindingsSprig = class(TTransientCollectionSprig) private FComponent: TComponent; public function UniqueName: string; override; function Caption: string; override; procedure FigureParent; override; function SortByIndex: Boolean; override; end; TVGSyntheticPropertyGroup = class; TVGSyntheticProperty = class(TCustomSyntheticProperty) private var FGroup: TVGSyntheticPropertyGroup; public property Group: TVGSyntheticPropertyGroup read FGroup write FGroup; end; TVGVisibleSyntheticProperty = class(TVGSyntheticProperty, IProperty, IProperty80) protected procedure SetValue(const Value: string); override; procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; end; TVGLayersNodeSyntheticProperty = class(TVGSyntheticProperty, IProperty, IProperty80) const sMixedCollection = '(Collection)'; private FNodeId: Integer; protected procedure SetId(AId: Integer); procedure GetProperties(Proc: TGetPropProc); override; procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; public constructor Create(const ADesigner: IDesigner; APropCount: Integer); override; end; TVGSyntheticPropertyGroup = class(TCustomSyntheticProperty, IProperty80) private var FRoot: TComponent; FComponents: TArray<TComponent>; function GetComponents: TArray<TComponent>; procedure SetComponents(const Values: TArray<TComponent>); protected procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetProperties(Proc: TGetPropProc); override; public constructor Create(const ADesigner: IDesigner; APropCount: Integer); override; property SelectedComponents: TArray<TComponent> read GetComponents write SetComponents; end; TDataBindingSyntheticProperty = class(TCustomSyntheticProperty, IProperty80, IShowReferenceProperty) private const sName = 'LiveBindings'; private var FComponent: TComponent; FBindCompListView: TBindCompListView; FHost: IPropertyHost; procedure CreateDataBindingFactoryContext(Sender: TObject; ABindCompList: TCustomBindingsList; var AContext: IBindCompFactoryContext); function CreateDataBindingFactoryExecuteContext( ABindCompList: TCustomBindingsList): IBindCompFactoryExecuteContext; procedure CreateNewDataBindingFactory(Sender: TObject; DataBindingFactory: IBindCompFactory; BindingsList: TCustomBindingsList); procedure SelectDataBindingProperty(Sender: TObject; DataBinding: TContainedBindComponent); protected // IShowReferenceProperty (show events) function ShowReferenceProperty: Boolean; // IProperty80 procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure SetValue(const Value: string); override; procedure GetProperties(Proc: TGetPropProc); override; property ControlComponent: TComponent read FComponent; public property Component: TComponent read FComponent write FComponent; destructor Destroy; override; end; // Provide published property which can be used to dynamicall add DataBinding components under a // DataBindingsPropery TProxyComponent = class(TComponent) private // List of databinding components that will get deleted class var FPendingFreeList: TList<TComponent>; class constructor Create; var FComponent: TComponent; FDesigner: IDesigner; //FFreeComponent: Boolean; public class destructor Destroy; published property ComponentProperty: TComponent read FComponent; constructor Create(AOwner: TComponent; ADesigner: IDesigner); reintroduce; destructor Destroy; override; end; TBindVisuallyViewFactory = class(TInterfacedObject, IBindCompFactory) private protected function Enabled(AContext: IBindCompFactoryContext): Boolean; function GetCommandText(AContext: IBindCompFactoryContext): string; procedure Execute(AContext: IBindCompFactoryExecuteContext); end; TNewBindCompWizardFactory = class(TInterfacedObject, IBindCompFactory) private protected function GetCategory: string; function Enabled(AContext: IBindCompFactoryContext): Boolean; function GetCommandText(AContext: IBindCompFactoryContext): string; procedure Execute(AContext: IBindCompFactoryExecuteContext); end; procedure GetOwnedAndLinkedComponents(ADesigner: IDesigner; AProc: TProc<TComponent, string>); begin with TGetDesignerComponents.Create(ADesigner) do try // Support data modules GetDesignerComponents( procedure(ADesignerComponent: TComponent; ARootName: string) begin AProc(ADesignerComponent, ARootName); end); finally Free; end; end; function GetOwnedAndLinkedComponentsList(ADesigner: IDesigner): TArray<TComponent>; var LList: TList<TComponent>; begin LList := TList<TComponent>.Create; try GetOwnedAndLinkedComponents(ADesigner, procedure (AComponent: TComponent; AName: string) begin Assert(not LList.Contains(AComponent)); LList.Add(AComponent); end); Result := LList.ToArray; finally LList.Free; end; end; // Get components owned by this form, including components in frames procedure GetOwnedComponents(AOwner: TComponent; AProc: TProc<TComponent>); var I: Integer; LComponent: TComponent; begin for I := 0 to AOwner.ComponentCount - 1 do // Find components under a root begin LComponent := AOwner.Components[I]; AProc(LComponent); if csInline in LComponent.ComponentState then GetOwnedComponents(LComponent, AProc); end; end; function GetRootOwner(AComponent: TComponent): TComponent; forward; procedure GetBindComponentsOfControlOwner(AOwner: TComponent; AComponent: TComponent; AFunc: TFunc<TContainedBindComponent, Boolean>); begin if AOwner <> nil then GetOwnedComponents(AOwner, procedure(AOwnedComponent: TComponent) begin if csDestroying in AOwnedComponent.ComponentState then begin // Skip end else if AOwnedComponent is TContainedBindComponent then if TContainedBindComponent(AOwnedComponent).ControlComponent = AComponent then if not AFunc(TContainedBindComponent(AOwnedComponent)) then Exit; end); end; procedure GetBindComponentsOfControl(AComponent: TComponent; AFunc: TFunc<TContainedBindComponent, Boolean>); var LRoot: TComponent; begin GetBindComponentsOfControlOwner(AComponent.Owner, AComponent, AFunc); LRoot := GetRootOwner(AComponent); if LRoot <> AComponent.Owner then GetBindComponentsOfControlOwner(LRoot, AComponent, AFunc); end; procedure GetBindComponentsOfComponentPropertyOwner(AOwner: TComponent; AComponent: TComponent; const AProperty: string; AFunc: TFunc<TContainedBindComponent, Boolean>); var C: TRttiContext; T: TRttiType; P: TRttiProperty; begin AOwner := GetRootOwner(AComponent); if AOwner <> nil then GetOwnedComponents(AOwner, procedure(AOwnedComponent: TComponent) begin if csDestroying in AOwnedComponent.ComponentState then begin // Skip end else if AOwnedComponent is TContainedBindComponent then begin try T := C.GetType(AOwnedComponent.ClassInfo); if Assigned(T) then begin P := T.GetProperty('ComponentProperty'); if Assigned(P) and (P.PropertyType.TypeKind = tkUString) then if P.GetValue(AOwnedComponent).ToString = AProperty then begin P := T.GetProperty('Component'); if Assigned(P) and (P.PropertyType.IsInstance) then if P.GetValue(AOwnedComponent).AsObject = AComponent then if not AFunc(TContainedBindComponent(AOwnedComponent)) then Exit; end; end; except // Ignore RTTI exceptions end; end; end); end; procedure GetBindComponentsOfComponentProperty(AComponent: TComponent; const AProperty: string; AFunc: TFunc<TContainedBindComponent, Boolean>); var LRoot: TComponent; begin GetBindComponentsOfComponentPropertyOwner(AComponent.Owner, AComponent, AProperty, AFunc); LRoot := GetRootOwner(AComponent); if LRoot <> AComponent.Owner then GetBindComponentsOfComponentPropertyOwner(LRoot, AComponent, AProperty, AFunc); end; function FindBindComponentsLinkToControl(const AControl: TComponent): TArray<TContainedBindComponent>; var LList: TList<TContainedBindComponent>; begin LList := TList<TContainedBindComponent>.Create; try GetBindComponentsOfControl(AControl, function(ABindComponent: TContainedBindComponent): Boolean begin LList.Add(ABindComponent); Result := True; end); Result := LList.ToArray; finally LList.Free; end; end; resourcestring sDeleteBindComponents = 'Delete %s?'; sDeleteCreateBindComponents = 'Delete %0:s and create new %1:s?'; function ConfirmDeleteBindComponents(const ADesigner: IDesigner; AComponents: TArray<TContainedBindComponent>; ANewClass: TComponentClass): Boolean; var LComponent: TComponent; LMessage: string; // S: string; begin if Length(AComponents) = 0 then Exit(True); LMessage := ''; for LComponent in AComponents do begin if LComponent <> nil then if LMessage = '' then LMessage := LComponent.Name else LMessage := LMessage + ', ' + LComponent.Name; end; if LMessage = '' then Exit(True); if ANewClass <> nil then LMessage := Format(sDeleteCreateBindComponents, [LMessage, ANewClass.ClassName]) else LMessage := Format(sDeleteBindComponents, [LMessage]); Result := MessageDlg(LMessage, mtConfirmation, mbYesNoCancel, 0) = idYes; end; function IntroducedInAncestor(AComponent: TComponent): Boolean; begin Assert(AComponent <> nil); Result := ((AComponent.Owner <> nil) and (csInline in AComponent.Owner.ComponentState)) or (csAncestor in AComponent.ComponentState); end; procedure DeleteBindComponents(const ADesigner: IDesigner; AComponents: TArray<TContainedBindComponent>); var LComponent: TContainedBindComponent; LBindActivate: IBindActivate; LDesignerSelections: IDesignerSelections; begin LDesignerSelections := CreateSelectionList; for LComponent in AComponents do if LComponent <> nil then begin if IntroducedInAncestor(LComponent) then raise EDesignPropertyError.CreateRes(@SCantDeleteAncestor); // NonAirException try Assert(LComponent.Owner = ADesigner.Root); LDesignerSelections.Add(LComponent); if Supports(LComponent, IBindActivate, LBindActivate) then begin LBindActivate.SetActive(False); LBindActivate := nil; end; except // Ignore errors deactivating end; end; AComponents := nil; if LDesignerSelections.Count > 0 then begin ADesigner.SetSelections(LDesignerSelections); ADesigner.DeleteSelection(True); end; end; function FindBindComponentsLinkToComponentProperty(const AComponent: TComponent; const APropertyName: string): TArray<TContainedBindComponent>; var LList: TList<TContainedBindComponent>; begin LList := TList<TContainedBindComponent>.Create; try GetBindComponentsOfComponentProperty(AComponent, APropertyName, function(ABindComponent: TContainedBindComponent): Boolean begin LList.Add(ABindComponent); Result := True; end); Result := LList.ToArray; finally LList.Free; end; end; function IsDataSourceComponent(AComponent: TComponent): Boolean; begin Result := False; if AComponent is TBindSourceAdapter then Result := True else if Supports(AComponent, IScopeMemberNames) then Result := True else if TCustomBindSourceDB.IsDataComponent(AComponent) then Result := True; end; function IsDataSourceMemberName(AComponent: TComponent; const AMemberName: string): Boolean; var LList: TStrings; begin Result := False; if IsDataSourceComponent(AComponent) then if AMemberName <> '' then begin LList := TStringList.Create; try GetDataSourceMemberNames(AComponent, LList); Result := LList.IndexOf(AMemberName) >= 0; finally LList.Free; end; end; end; function CreateBindingsList(AOwner: TComponent): TBindingsList; begin Result := TBindingsList.Create(nil); if Assigned(AOwner) then begin //Place BindingsList in top left corner of parent (Low Word = Left, High Word = Top) Result.DesignInfo := (5 shl 16) + 20; AOwner.InsertComponent(Result); end; end; function FindBindingsList(AOwner: TComponent): TBindingsList; var I: Integer; begin Result := nil; for I := 0 to AOwner.ComponentCount - 1 do // Ignores components in frames begin if AOwner.Components[I] is TBindingsList then begin Result := TBindingsList(AOwner.Components[I]); break; end; end; end; function BindScopeOfDataComponent(const ADesigner: IDesigner; AComponent: TComponent): TCustomBindSourceDB; var LResult: TCustomBindSourceDB; begin LResult := nil; with TGetDesignerComponents.Create(ADesigner) do try // Support data modules GetDesignerComponents( procedure(ADesignerComponent: TComponent; ARootName: string) begin if LResult <> nil then Exit; if ADesignerComponent is TCustomBindSourceDB then begin with TCustomBindSourceDB(ADesignerComponent) do begin if AComponent = DataComponent then LResult := TCustomBindSourceDB(ADesignerComponent); end; end; end); finally Free; end; Result := LResult; end; function BindScopeOfAdapter(const ADesigner: IDesigner; AComponent: TComponent): TBaseObjectBindSource; var LResult: TBaseObjectBindSource; begin LResult := nil; with TGetDesignerComponents.Create(ADesigner) do try // Support data modules GetDesignerComponents( procedure(ADesignerComponent: TComponent; ARootName: string) begin if LResult <> nil then Exit; if ADesignerComponent is TBaseObjectBindSource then begin with TBaseObjectBindSource(ADesignerComponent) do begin if InternalAdapter <> nil then if InternalAdapter = AComponent then LResult := TBaseObjectBindSource(ADesignerComponent); end; end end); finally Free; end; Result := LResult; end; function BindScopeOfDataSourceComponent(const ADesigner: IDesigner; AComponent: TComponent): TComponent; begin Result := nil; if AComponent is TBindSourceAdapter then begin Result := BindScopeOfAdapter(ADesigner, AComponent); end; if TCustomBindSourceDB.IsDataComponent(AComponent) then begin Result := BindScopeOfDataComponent(ADesigner, AComponent); end; end; type TDBScope = TBindSourceDB; function GetDataSourceMemberNames(AComponent: TComponent): TArray<TPersistentPair>; function GetMemberNames(AScope: TComponent): TArray<TPersistentPair>; var LMemberNames: IScopeMemberNames; LList: TStrings; LArray: TList<TPersistentPair>; I: Integer; LObject: TObject; begin Result := nil; LList := nil; try if Supports(AScope, IScopeMemberNames, LMemberNames) then begin LList := TStringList.Create; LMemberNames.GetMemberNames(LList); LMemberNames := nil; end; if LList <> nil then begin LArray := TList<TPersistentPair>.Create; try for I := 0 to LList.Count - 1 do begin LObject := LList.Objects[I]; if not (LObject is TPersistent) then LObject := nil else if (LObject is TComponent) and (TComponent(LObject).Name = '') then // Don't reference components with no name, such as non persistent TFields in an active TDataSet LObject := nil; LArray.Add(TPair<string, TPersistent>.Create(LList[I], TPersistent(LObject))); end; Result := LArray.ToArray; finally LArray.Free; end; end; finally LList.Free; end; end; var LBindScope: TCustomAdapterBindSource; LBindScopeDB: TCustomBindSourceDB; begin Result := nil; if AComponent is TBindSourceAdapter then begin begin LBindScope := TAdapterBindSource.Create(nil); try LBindScope.Adapter := TBindSourceAdapter(AComponent); Result := GetMemberNames(LBindScope); finally LBindScope.Free; end; end end else if Supports(AComponent, IScopeMemberNames) then begin Result := GetMemberNames(AComponent) end else if TCustomBindSourceDB.IsDataComponent(AComponent) then begin LBindScopeDB := TDBScope.Create(nil); try LBindScopeDB.DataComponent := AComponent; Result := GetMemberNames(LBindScopeDB); finally LBindScopeDB.Free; end; end; end; function GetDataSourceMemberNames(AComponent: TComponent; AList: TStrings): Boolean; procedure GetMemberNames(AScope: TComponent); var LMemberNames: IScopeMemberNames; begin if Supports(AScope, IScopeMemberNames, LMemberNames) then begin LMemberNames.GetMemberNames(AList); LMemberNames := nil; end; end; var LBindScope: TCustomAdapterBindSource; LBindScopeDB: TCustomBindSourceDB; begin Result := False; if AComponent is TBindSourceAdapter then begin Result := True; LBindScope := TAdapterBindSource.Create(nil); try LBindScope.Adapter := TBindSourceAdapter(AComponent); GetMemberNames(LBindScope); finally LBindScope.Free; end; end else if Supports(AComponent, IScopeMemberNames) then begin Result := True; GetMemberNames(AComponent) end else if TCustomBindSourceDB.IsDataComponent(AComponent) then begin Result := True; LBindScopeDB := TDBScope.Create(nil); try LBindScopeDB.DataComponent := AComponent; GetMemberNames(LBindScopeDB); finally LBindScopeDB.Free; end; end; end; function GenerateComponentName(const APrefix, AMemberName: string; Number: Integer): string; function Alpha(C: Char): Boolean; inline; begin Result := C.IsLetter or (C = '_'); end; function AlphaNumeric(C: Char): Boolean; inline; begin Result := C.IsLetterOrDigit or (C = '_'); end; function CrunchFieldName(const AMemberName: string): string; var I: Integer; begin Result := AMemberName; I := 1; while I <= Length(Result) do begin if AlphaNumeric(Result[I]) then Inc(I) else Delete(Result, I, 1); end; end; var LFmt: string; LMemberName: string; begin LMemberName := CrunchFieldName(APrefix + AMemberName); if (LMemberName = '') or not Alpha(LMemberName[1]) then LMemberName := CrunchFieldName(APrefix + 'Field' + AMemberName); if Number < 2 then LFmt := '%s' else LFmt := '%s%d'; Result := Format(LFmt, [LMemberName, Number]); end; function CreateUniqueComponentName(AOwner: TComponent; const APrefix, AMemberName: string): string; var I: Integer; function IsUnique(const AName: string): Boolean; var I: Integer; begin Result := False; with AOwner do for I := 0 to ComponentCount - 1 do // ignores components in frames if CompareText(AName, Components[I].Name) = 0 then Exit; Result := True; end; begin for I := 1 to MaxInt do begin Result := GenerateComponentName(APrefix, AMemberName, I); if IsUnique(Result) then Exit; end; end; { TBindCompListEditor } procedure TBindCompListEditor.ExecuteVerb(Index: Integer); begin case Index of 0: ShowBindCompListDesigner(Designer, (Component as TBindingsList)); 1: ExecuteNewBindingsDlg; else Assert(False); end; end; procedure TBindCompListEditor.ExecuteNewBindingsDlg; var LBindingsList: TBindingsList; begin LBindingsList := Component as TBindingsList; with TExecuteNewDataBinding.Create(LBindingsList, Designer) do begin Execute( procedure begin end, procedure(ACategory: string; ADataBinding: TContainedBindComponent) begin ADataBinding.Name := Designer.UniqueName(System.Copy(ADataBinding.ClassName, 2, MaxInt)); ADataBinding.Category := ACategory; ADataBinding.BindingsList := LBindingsList; Designer.Modified; Designer.SelectComponent(ADataBinding); end, procedure begin //FocusDataBinding(LDataBinding) end, function(AClass: TContainedBindCompClass): Boolean begin Result := True; end); end; end; function TBindCompListEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := SBindCompListEdit; 1: Result := SNewBindingDlgCommand; else Assert(False); end; end; function TBindCompListEditor.GetVerbCount: Integer; begin Result := 2; end; { TAddBindComponentEditor } constructor TBindCompFactorySelectionEditor.Create(const ADesigner: IDesigner); begin inherited; end; destructor TBindCompFactorySelectionEditor.Destroy; begin FActions.Free; inherited; end; procedure TBindCompFactorySelectionEditor.ExecuteVerb(Index: Integer; const List: IDesignerSelections); var LFactoryAction: TFactoryAction; begin // Create actions on demand rather than in constructor to improve // performance of code insite AddFactoryActions(FActions); LFactoryAction := FActions[Index] as TFactoryAction; CreateNewDataBindingFactory(LFactoryAction, LFactoryAction.FFactory, LFactoryAction.FBindingsList); // Reselect to update verbs // DesignNotificationSelectionChanged(Designer, CreateSelectionList); // DesignNotificationSelectionChanged(Designer, List); end; function TBindCompFactorySelectionEditor.GetVerb(Index: Integer): string; begin // Create actions on demand rather than in constructor to improve // performance of code insite AddFactoryActions(FActions); Result := FActions[Index].Caption; end; procedure TBindCompFactorySelectionEditor.CreateNewDataBindingFactory(Sender: TObject; DataBindingFactory: IBindCompFactory; BindingsList: TCustomBindingsList); var LContext: IBindCompFactoryExecuteContext; LBindCompList: TBindingsList; begin LBindCompList := nil; LContext := CreateDataBindingFactoryExecuteContext(BindingsList); Assert(LContext <> nil); if LContext.BindingsList = nil then begin LBindCompList := BindCompReg.CreateBindingsList(LContext.Owner); LBindCompList.Name := LContext.UniqueName(LBindCompList.ClassType.ClassName ); (LContext as TDataBindingFactoryExecuteContext).FBindCompList := LBindCompList; end; if LContext <> nil then DataBindingFactory.Execute(LContext); if LBindCompList <> nil then begin if LBindCompList.BindCompCount = 0 then // Free compononent we've create because no binding components created LBindCompList.Free; end; end; class procedure TBindCompFactorySelectionEditor.AddDataBindingAction( AFactory: IBindCompFactory; Info: Pointer); var LInfo: PAddActionInfo; LAction: TFactoryAction; begin LInfo := PAddActionInfo(Info); if AFactory.Enabled(LInfo.FContext) then begin LAction := TFactoryAction.Create( AFactory.GetCommandText(LInfo.FContext), LInfo.FBindingsList, AFactory); LInfo.FList.Add(LAction); end; end; function TBindCompFactorySelectionEditor.GetVerbCount: Integer; begin // Create actions on demand rather than in constructor to improve // performance of code insite AddFactoryActions(FActions); Result := FActions.Count; end; procedure TBindCompFactorySelectionEditor.RequiresUnits(Proc: TGetStrProc); var I: Integer; LService: TDataSource; begin for I := 0 to Designer.Root.ComponentCount - 1 do begin if Designer.Root.Components[I] is TCustomBindSourceDB then begin LService := TBindSourceDB(Designer.Root.Components[I]).DataSource; if (LService <> nil) and Assigned(GetMethodProp(LService, 'OnDataChange').Code) then begin Proc(TDataSource.UnitName); break; end; end; end; end; procedure TBindCompFactorySelectionEditor.CreateDataBindingFactoryContext(Sender: TObject; ABindCompList: TCustomBindingsList; out AContext: IBindCompFactoryContext); var LComponent: TComponent; List: IDesignerSelections; begin AContext := nil; List := CreateSelectionList; Designer.GetSelections(List); if (List.Count > 0) and (List[0] is TComponent) then LComponent := TComponent(List[0]) else LComponent := nil; if LComponent <> nil then begin AContext := TDataBindingFactoryContext.Create(Designer, ABindCompList, LComponent); //FComponent); end else AContext := nil; end; type TBindCompFactorySelectionEditorExecuteContext = class(TDataBindingFactoryExecuteContext) public procedure BindCompCreated(AComponent: TComponent); override; end; function TBindCompFactorySelectionEditor.CreateDataBindingFactoryExecuteContext(ABindCompList: TCustomBindingsList): IBindCompFactoryExecuteContext; var LComponent: TComponent; List: IDesignerSelections; begin Result := nil; List := CreateSelectionList; Designer.GetSelections(List); if (List.Count > 0) and (List[0] is TComponent) then LComponent := TComponent(List[0]) else LComponent := nil; if LComponent <> nil then begin Result := TBindCompFactorySelectionEditorExecuteContext.Create(Designer, ABindCompList, LComponent); //FComponent); end; end; procedure TBindCompFactorySelectionEditor.AddTempString(const S: string); begin FTempStringList.Add(S); end; procedure TBindCompFactorySelectionEditor.AddFactoryActions(AList: TList<TCustomAction>); var LBindCompList: TCustomBindingsList; I: Integer; LBindCompLists: TList<TCustomBindingsList>; LDataBindingFactoryContext: IBindCompFactoryContext; LInfo: TAddActionInfo; begin // Create actions on demand rather than in constructor to improve // performance of code insite // Don't need parameter anymore, but for updates must not change signature Assert(AList = FActions); if FActions <> nil then Exit; FActions := TObjectList<TCustomAction>.Create; AList := FActions; LBindCompLists := TList<TCustomBindingsList>.Create; try // Build list of ActionLists FTempStringList := TStringList.Create; try Designer.GetComponentNames(GetTypeData(TypeInfo(TBindingsList)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin Assert(Designer.GetComponent(FTempStringList[I]) is TBindingsList); LBindCompLists.Add(TBindingsList(Designer.GetComponent(FTempStringList[I]))); end; finally FreeAndNil(FTempStringList); end; // Build menus even if no databinding list, factory will create one if LBindCompLists.Count = 0 then LBindCompLists.Add(nil); // Build popupmenus for actionlists and standard actions for LBindCompList in LBindCompLists do begin CreateDataBindingFactoryContext(Self, nil, LDataBindingFactoryContext); if LDataBindingFactoryContext <> nil then begin Assert(LDataBindingFactoryContext <> nil); LInfo.FContext := LDataBindingFactoryContext; LInfo.FBindingsList := LBindCompList; LInfo.FList := AList; if Assigned(EnumRegisteredBindCompFactoriesProc) then EnumRegisteredBindCompFactories(AddDataBindingAction, @LInfo); end; // Note: only create one verb for the first bindings list... break; end; finally LBindCompLists.Free; end; end; { TBindCompExpressionEditor } procedure TBindCompExpressionEditor.ExecuteVerb(Index: Integer); begin ShowBindCompExprDesigner(Designer, (Component as TContainedBindComponent)); end; function TBindCompExpressionEditor.GetVerb(Index: Integer): string; begin Result := SBindCompExpressionEdit; end; function TBindCompExpressionEditor.GetVerbCount: Integer; begin Result := 1; end; //{ TBaseLinkingBindScopeEditor } resourcestring SAddNavigator = 'Add Navigator'; SAddBindScope = 'Add BindSource'; { TBindFillListExpressionEditor } procedure TBindFillListExpressionEditor.ExecuteVerb(Index: Integer); var I: Integer; LList: TCustomBindList; begin LList := Component as TCustomBindList; Assert(LList <> nil); I := inherited GetVerbCount; if Index < I then inherited else if LList <> nil then case Index - I of 0: LList.FillList; 1: LList.ClearList; end; end; function TBindFillListExpressionEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited else case Index - I of 0: Result := SBindFillList; 1: Result := SBindClearList; end; end; function TBindFillListExpressionEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 2; end; { TBindEvaluateExpressionEditor } procedure TBindEvaluateExpressionEditor.ExecuteVerb(Index: Integer); var I: Integer; begin I := inherited GetVerbCount; if Index < I then inherited else case Index - I of 0: (Component as TCustomBindExpression).EvaluateFormat; end; end; function TBindEvaluateExpressionEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited else case Index - I of 0: Result := SEvaluate; end; end; function TBindEvaluateExpressionEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 1; end; { TBindEvaluateExprItemsEditor } procedure TBindFillGridLinkExpressionEditor.ExecuteVerb(Index: Integer); var I: Integer; begin Assert(Component is TCustomBindGridLink); I := inherited GetVerbCount; if Index < I then inherited else case Index - I of 0: (Component as TCustomBindGridLink).FillGrid; 1: (Component as TCustomBindGridLink).ClearGrid; end; end; function TBindFillGridLinkExpressionEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited else case Index - I of 0: Result := SBindFillGrid; 1: Result := SBindClearGrid; end; end; function TBindFillGridLinkExpressionEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 2; end; { TBindFillGridListExpressionEditor } function TBindFillGridListExpressionEditor.GetBindList: TCustomBindGridList; var LBindComponent: TCommonBindComponent; begin Result := nil; if Component is TCustomBindGridList then Result := TCustomBindGridList(Component) else if Component is TBindComponentDelegate then begin for LBindComponent in TBindComponentDelegate(Component).GetDelegates do if LBindComponent is TCustomBindGridList then begin Result := TCustomBindGridList(LBindComponent); break; end; end; end; procedure TBindFillGridListExpressionEditor.ExecuteVerb(Index: Integer); var I: Integer; LList: TCustomBindGridList; begin I := inherited GetVerbCount; LList := GetBindList; Assert(LList <> nil); if Index < I then inherited else if LList <> nil then case Index - I of 0: LList.FillList; 1: LList.ClearList; end; end; function TBindFillGridListExpressionEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited else case Index - I of 0: Result := SBindFillList; 1: Result := SBindClearList; end; end; function TBindFillGridListExpressionEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 2; end; { TBindEvaluateExprItemsEditor } procedure TBindEvaluateExprItemsEditor.ExecuteVerb(Index: Integer); var I: Integer; begin I := inherited GetVerbCount; if Index < I then inherited else case Index - I of 0: (Component as TCustomBindExprItems).EvaluateFormat; 1: (Component as TCustomBindExprItems).EvaluateClear; end; end; function TBindEvaluateExprItemsEditor.GetVerb(Index: Integer): string; var I: Integer; begin I := inherited GetVerbCount; if Index < I then Result := inherited else case Index - I of 0: Result := SEvaluateFormat; 1: Result := SEvaluateClear; end; end; function TBindEvaluateExprItemsEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount + 2; end; { TBindCompListView } constructor TBindCompListView.Create(AOwner: TComponent); begin inherited; FActionsDictionary := TDictionary<TListItem, TCustomAction>.Create; FImageList := TImageList.Create(nil); FTempStringList := TStringList.Create; BorderStyle := bsNone; Columns.Add; Height := FDefItemHeight; ReadOnly := True; RowSelect := True; ShowColumnHeaders := False; SmallImages := FImageList; ViewStyle := vsReport; Width := 200; end; destructor TBindCompListView.Destroy; begin FreeAndNil(FImageList); FreeAndNil(FActionsDictionary); inherited; end; procedure TBindCompListView.AddTempString(const S: string); begin FTempStringList.Add(S); end; procedure TBindCompListView.Click; var P: TPoint; Item: TListItem; LAction: TCustomAction; begin GetCursorPos(P); P := ScreenToClient(P); Item := GetItemAt(P.X, P.Y); if Item <> nil then begin if (Item.Data = Self) then begin if Assigned(FOnSelectDataBindingProperty) then FOnSelectDataBindingProperty(Self, TContainedBindComponent(Item.Data)); end else if (Item.Data <> nil) then begin if Assigned(FOnSelectDataBindingProperty) then FOnSelectDataBindingProperty(Self, TContainedBindComponent(Item.Data)) end else begin if Item = FSelectComponentItem then begin if Assigned(FOnSelectDataBindingComponent) then FOnSelectDataBindingComponent(Self) end else if Item = FDeleteComponentItem then begin if Assigned(FOnDeleteDataBinding) then FOnDeleteDataBinding(Self) end else if FActionsDictionary.TryGetValue(Item, LAction) then if LAction is TFactoryAction then begin if Assigned(FOnNewDataBindingFactory) then FOnNewDataBindingFactory(Self, TFactoryAction(LAction).FFactory, TFactoryAction(LAction).FBindingsList) end else LAction.Execute; end end else if Assigned(FOnSelectDataBindingProperty) then FOnSelectDataBindingProperty(Self, nil); end; procedure TBindCompListView.CreateWnd; begin inherited; if Designer.Root <> nil then RebuildListView; end; function TBindCompListView.CustomDrawItem(Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var LRect: TRect; begin Result := True; Canvas.Brush.Style := bsClear; LRect := Item.DisplayRect(drLabel); case Stage of cdPrePaint: // Draw separator if Item.Caption = '' then begin Canvas.Pen.Color := clSilver; Canvas.MoveTo(LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); Canvas.LineTo(LRect.Right - LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); Result := False; // Prevent default drawing of highlight bar end; cdPostPaint: // Draw arrow for New Action and New Standard Action items // if ((Item.Index <= 1) and (FNewStdActnPopupMenu.Items.Count > 1)) and // (((Item.Index = 0) and (FNewActnPopupMenu.Items.Count > 1)) or // ((Item.Index = 1) and (FNewStdActnPopupMenu.Items.Count > 1))) then // if Item.Data = FNewStdActnPopupMenu then // // begin // LRect.Left := LRect.Right - 20; // if ThemeServices.ThemesEnabled and (Win32MajorVersion >= 6) then // DrawThemeBackground(ThemeServices.Theme[teMenu], Canvas.Handle, // MENU_POPUPSUBMENU, MSM_NORMAL, LRect, nil) // else // DrawArrow(Canvas, sdRight, Point(LRect.Right - 15, // LRect.Top + ((LRect.Bottom - LRect.Top - 8) div 2)), 4); // end; end; end; function TBindCompListView.IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; begin Result := (Stage = cdPrePaint) or (Stage = cdPostPaint); end; procedure TBindCompListView.KeyDown(var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: if (Selected <> nil) then begin if Selected.Data <> nil then begin if Assigned(FOnSelectDataBindingProperty) then FOnSelectDataBindingProperty(Self, TContainedBindComponent(Selected.Data)); end else if Assigned(FOnDeleteDataBinding) then FOnDeleteDataBinding(Self); end; VK_RIGHT: if Selected <> nil then begin // if Selected.Data = FNewStdActnPopupMenu then // ShowPopupMenu(Selected, FNewStdActnPopupMenu); end; else inherited; end; end; procedure TBindCompListView.RebuildListView; var LRect: TRect; ListItem: TListItem; LDataBinding: TContainedBindComponent; I, LWidth, MinWidth: Integer; LItemIndex: Integer; LExistingDataBindingCount: Integer; LAction: TCustomAction; begin FDeleteComponentItem := nil; FSelectComponentItem := nil; FActionsDictionary.Clear; LExistingDataBindingCount := 0; begin Items.BeginUpdate; try Items.Clear; FImageList.Clear; // Set initial max width MinWidth := 0; // Max(Width, Canvas.TextWidth(SCreateNewDataBinding) + 25); if TBindCompListViewOption.dblvSelectExisting in FOptions then begin // Find all actions FTempStringList.Clear; Designer.GetComponentNames(GetTypeData(TypeInfo(TContainedBindComponent)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin LDataBinding := TContainedBindComponent(Designer.GetComponent(FTempStringList[I])); if LDataBinding.ControlComponent <> Self.ControlComponent then Continue; ListItem := Items.Add; ListItem.Caption := FTempStringList[I]; ListItem.Data := LDataBinding; ListItem.ImageIndex := -1; Inc(LExistingDataBindingCount); MinWidth := Max(MinWidth, Canvas.TextWidth(ListItem.Caption)); end; // Sort list items before adding "special" items CustomSort(nil, 0); end; LItemIndex := 0; if TBindCompListViewOption.dblvDelete in FOptions then begin // Delete data binding item ListItem := Items.Insert(LItemIndex); FDeleteComponentItem := ListItem; ListItem.Caption := Format(SDeleteDataBinding, [FDataBindingComponentName]); ListItem.ImageIndex := -1; ListItem.Data := nil; MinWidth := Max(MinWidth, Canvas.TextWidth(ListItem.Caption)); Inc(LItemIndex); end; if TBindCompListViewOption.dblvSelect in FOptions then begin // Delete data binding item ListItem := Items.Insert(LItemIndex); FSelectComponentItem := ListItem; ListItem.Caption := Format(SSelectDataBinding, [FDataBindingComponentName]); ListItem.ImageIndex := -1; ListItem.Data := nil; MinWidth := Max(MinWidth, Canvas.TextWidth(ListItem.Caption)); Inc(LItemIndex); end; if LExistingDataBindingCount > 0 then if TBindCompListViewOption.dblvSelectExisting in FOptions then begin // Add dummy item for divider line //if LItemIndex > 2 then begin // Add existing DataBinding instances ListItem := Items.Insert(LItemIndex); ListItem.ImageIndex := -1; end; end; if Length(FCustomActions) > 0 then for LAction in FCustomActions do begin if LAction.Enabled and LAction.Visible then begin ListItem := Items.Insert(LItemIndex); ListItem.Caption := LAction.Caption; ListItem.ImageIndex := -1; ListItem.Data := nil; FActionsDictionary.Add(ListItem, LAction); MinWidth := Max(MinWidth, Canvas.TextWidth(ListItem.Caption) + FImageList.Width); Inc(LItemIndex); end; end; finally Items.EndUpdate; end; LWidth := 0; // if LExistingDataBindingCount > 0 then // if TBindCompListViewOption.dblvSelectExisting in FOptions then begin // Set Height to fit 14 items if Items.Count > 14 then begin I := 14; LWidth := GetSystemMetrics(SM_CXVSCROLL); end else I := Items.Count; if Items.Count > 0 then begin LRect := Items[0].DisplayRect(drBounds); Height := LRect.Bottom * I; end else Height := FDefItemHeight end; // Set width to widest + space gutters (20 pixels each side) Self.Width := MinWidth + LWidth + 40; //+ FImageList.Width; Columns[0].Width := Width - LWidth; end // else // Height := FDefItemHeight; end; class procedure TBindCompListView.AddDataBindingAction( AFactory: IBindCompFactory; Info: Pointer); var LInfo: PAddActionInfo; LAction: TFactoryAction; begin LInfo := PAddActionInfo(Info); if AFactory.Enabled(LInfo.FContext) then begin LAction := TFactoryAction.Create( AFactory.GetCommandText(LInfo.FContext), LInfo.FBindingsList, AFactory); LInfo.FList.Add(LAction); end; end; procedure TBindCompListView.AddFactoryActions(AList: TList<TCustomAction>); var LBindCompList: TCustomBindingsList; I: Integer; LBindCompLists: TList<TCustomBindingsList>; LDataBindingFactoryContext: IBindCompFactoryContext; LInfo: TAddActionInfo; begin LBindCompLists := TList<TCustomBindingsList>.Create; try // Build list of ActionLists FTempStringList.Clear; Designer.GetComponentNames(GetTypeData(TypeInfo(TBindingsList)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin Assert(Designer.GetComponent(FTempStringList[I]) is TBindingsList); LBindCompLists.Add(TBindingsList(Designer.GetComponent(FTempStringList[I]))); end; // Build menus even if no databinding list, factory will create one if LBindCompLists.Count = 0 then LBindCompLists.Add(nil); // Build popupmenus for actionlists and standard actions for LBindCompList in LBindCompLists do begin FCreateDataBindingFactoryContext(Self, nil, LDataBindingFactoryContext); Assert(LDataBindingFactoryContext <> nil); LInfo.FContext := LDataBindingFactoryContext; LInfo.FBindingsList := LBindCompList; LInfo.FList := AList; if Assigned(EnumRegisteredBindCompFactoriesProc) then EnumRegisteredBindCompFactories(AddDataBindingAction, @LInfo); end; finally LBindCompLists.Free; end; end; class procedure TBindCompListView.AddVerbActions(AComponent: TComponent; AList: TList<TCustomAction>; ADesigner: IDesigner); var LAction: TVerbAction; LEditor: IComponentEditor; I: Integer; LText: string; begin LEditor := GetComponentEditor(AComponent, ADesigner); if LEditor <> nil then begin for I := 0 to LEditor.GetVerbCount - 1 do begin LText := LEditor.GetVerb(I); LText := ReplaceStr(LText, '&', ''); LAction := TVerbAction.Create( LText, AComponent, I, ADesigner); AList.Add(LAction); end; end; end; procedure TBindCompListView.SetDesigner(const Value: IDesigner); begin if Value <> FDesigner then begin FDesigner := Value; // Set initial height based on default item height FTempStringList.Clear; Designer.GetComponentNames(GetTypeData(TypeInfo(TContainedBindComponent)), AddTempString); if FTempStringList.Count > 0 then Height := (Min(FTempStringList.Count, 11) + 3) * FDefItemHeight else Height := FDefItemHeight; // Rebuild popup menus and listview //RebuildPopupMenus; if HandleAllocated then RebuildListView; end; end; { TCustomDataBindingSprig } function TCustomDataBindingSprig.DragDropTo(AItem: TSprig): Boolean; begin Result := False; // if AItem is TActionCategorySprig then // begin // Result := not AnsiSameText(TActionCategorySprig(AItem).FCategory, TContainedAction(Item).Category); // if Result then // TContainedAction(Item).Category := TActionCategorySprig(AItem).FCategory; // end // // else if AItem is TContainedActionSprig then // begin // Result := True; // TContainedAction(Item).Index := TContainedAction(AItem.Item).Index; // if not AnsiSameText(TContainedAction(Item).Category, TContainedAction(AItem.Item).Category) then // TContainedAction(Item).Category := TContainedAction(AItem.Item).Category; // Parent.SetIndexOf(AItem, TContainedAction(AItem.Item).Index); // end; end; function TCustomDataBindingSprig.DragOverTo(AItem: TSprig): Boolean; begin Result := False; // Result := ((AItem is TActionCategorySprig) and // (TActionCategorySprig(AItem).FActionList = TContainedAction(Item).ActionList)) or // ((AItem is TContainedActionSprig) and // (TContainedAction(AItem.Item).ActionList = TContainedAction(Item).ActionList)); end; const CDataBindingCategoryPrefix = '<DataBindingCategory>'; function DataBindingCategorySprigName(const ACategory: string): string; begin Result := Format('%s.%s', [CDataBindingCategoryPrefix, ACategory]); end; function ComponentDataBindingsSprigName: string; begin Result := 'LiveBindings'; end; procedure TCustomDataBindingSprig.FigureParent; var LListSprig, LCatSprig: TSprig; begin with TContainedBindComponent(Item) do begin LListSprig := SeekParent(BindingsList, False); if Assigned(LListSprig) then begin LCatSprig := LListSprig.Find(DataBindingCategorySprigName(Category), False); if not Assigned(LCatSprig) then begin LCatSprig := LListSprig.Add(TDataBindingCategorySprig.Create(nil)); TDataBindingCategorySprig(LCatSprig).FBindCompList := BindingsList; TDataBindingCategorySprig(LCatSprig).FCategory := Category; end; LCatSprig.Add(Self); end; end; end; function TCustomDataBindingSprig.ItemIndex: Integer; begin Result := TContainedBindComponent(Item).Index; end; { TCustomAssociatedDataBindingSprig } function TCustomAssociatedDataBindingSprig.DragDropTo(AItem: TSprig): Boolean; begin Result := False; end; function TCustomAssociatedDataBindingSprig.DragOverTo(AItem: TSprig): Boolean; begin Result := False; end; procedure TCustomAssociatedDataBindingSprig.FigureParent; var LListSprig, LCatSprig: TSprig; begin with TContainedBindComponent(Item) do begin if ControlComponent <> nil then begin LListSprig := SeekParent(ControlComponent, False); if Assigned(LListSprig) then begin LCatSprig := LListSprig.Find(ComponentDataBindingsSprigName, False); if not Assigned(LCatSprig) then begin LCatSprig := LListSprig.Add(TComponentDataBindingsSprig.Create(nil)); TComponentDataBindingsSprig(LCatSprig).FComponent := ControlComponent; end; LCatSprig.Add(Self); //LListSprig.Add(Self); end; end; end; end; function TCustomAssociatedDataBindingSprig.ItemIndex: Integer; begin //Result := TContainedBindComponent(Item).Index; Result := inherited; end; { TDataBindingCategorySprig } function TDataBindingCategorySprig.Caption: string; begin Result := FCategory; if Result = '' then Result := SDataBindingCategoryNone; end; procedure TDataBindingCategorySprig.FigureParent; begin SeekParent(FBindCompList, False); end; function TDataBindingCategorySprig.SortByIndex: Boolean; begin Result := True; end; function TDataBindingCategorySprig.UniqueName: string; begin Result := DataBindingCategorySprigName(FCategory); end; { TComponentDataBindingsSprig } function TComponentDataBindingsSprig.Caption: string; begin // Result := FCategory; // if Result = '' then // Result := SDataBindingCategoryNone; Result := ComponentDataBindingsSprigName; end; procedure TComponentDataBindingsSprig.FigureParent; begin SeekParent(FComponent, False); end; function TComponentDataBindingsSprig.SortByIndex: Boolean; begin // Result := True; Result := inherited; end; function TComponentDataBindingsSprig.UniqueName: string; begin // Result := DataBindingCategorySprigName(FCategory); Result := ComponentDataBindingsSprigName; end; type TPrototypeBindSourceFactory = class(TBindScopeFactory) public function GetEnabled: Boolean; override; function BindScopeClass: TComponentClass; override; function CreateNewBindScopeManager(AOwner: TComponent): INewBindScopeManager; override; function CreateBindScopeEditor(AOwner: TComponent; AScope: TComponent): IBindScopeEditor; override; end; TDataGeneratorAdapterFactory = class(TBindScopeFactory) public function GetEnabled: Boolean; override; function CanCreate: Boolean; override; function BindScopeClass: TComponentClass; override; function CreateNewBindScopeManager(AOwner: TComponent): INewBindScopeManager; override; function CreateBindScopeEditor(AOwner: TComponent; AScope: TComponent): IBindScopeEditor; override; end; TBaseNewGeneratorScopeManager = class(TNewBindScopeManager) private FOwner: TComponent; FDesigner: IDesigner; procedure ValidateNewField(Sender: TObject; var AValid: Boolean); function FieldExists(const AFieldName: string): Boolean; procedure ExistingFieldName(Sender: TObject; const AFieldName: string; var AExists: Boolean); protected function GetAdapter: TCustomDataGeneratorAdapter; virtual; abstract; //function InternalDataSource: TComponent; override; function AddField: string; override; function CanAddFields: Boolean; override; function CanRemoveField(const AFieldName: string): Boolean; override; function RemoveField(const AFieldName: string): Boolean; override; //function CreateScope: TBaseLinkingBindSource; override; public constructor Create(AOwner: TComponent; const ADesigner: IDesigner); destructor Destroy; override; end; TNewPrototypeBindSourceManager = class(TBaseNewGeneratorScopeManager) private FDataSource: TCustomPrototypeBindSource; protected function InternalDataSource: TComponent; override; function CreateScope: TBaseLinkingBindSource; override; function GetAdapter: TCustomDataGeneratorAdapter; override; public destructor Destroy; override; end; TDataGeneratorAdapterEditor = class(TBindScopeEditor) private FDataSource: TCustomDataGeneratorAdapter; FOwner: TComponent; FDesigner: IDesigner; FNewFields: TList<TGeneratorFieldDef>; function FindNewField(const AFieldName: string): Integer; procedure ValidateNewField(Sender: TObject; var AValid: Boolean); function FieldExists(const AFieldName: string): Boolean; procedure ExistingFieldName(Sender: TObject; const AFieldName: string; var AExists: Boolean); protected function CanAddFields: Boolean; override; function AddField: TArray<string>; override; function CanRemoveField(const AFieldName: string): Boolean; override; function RemoveField(const AFieldName: string): Boolean; override; procedure GetMembers(AList: TStrings); override; function Changed: Boolean; override; function ApplyChanges: TArray<TPersistentPair>; override; public constructor Create(AOwner: TComponent; ADataSource: TCustomDataGeneratorAdapter; const ADesigner: IDesigner); destructor Destroy; override; end; TPrototypeBindSourceEditor = class(TDataGeneratorAdapterEditor) private FDataSource: TCustomPrototypeBindSource; protected constructor Create(AOwner: TComponent; ADataSource: TCustomPrototypeBindSource; const ADesigner: IDesigner); end; TGeneratorFieldDefsPropertyEditor = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; procedure TGeneratorFieldDefsPropertyEditor.Edit; begin ShowCollectionEditorClass(Designer, TBindAdapterColumnsEditor, GetComponent(0) as TComponent, TCollection(GetOrdValue), GetName); end; function TGeneratorFieldDefsPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly{$IFDEF LINUX}, paVCL{$ENDIF}]; end; { TDataGeneratorAdapterFactory } function TDataGeneratorAdapterFactory.CanCreate: Boolean; begin Result := False; end; function TDataGeneratorAdapterFactory.CreateBindScopeEditor( AOwner: TComponent; AScope: TComponent): IBindScopeEditor; begin Assert(AScope is TCustomDataGeneratorAdapter); Result := TDataGeneratorAdapterEditor.Create(AOwner, AScope as TCustomDataGeneratorAdapter, Designer); end; function TDataGeneratorAdapterFactory.CreateNewBindScopeManager(AOwner: TComponent): INewBindScopeManager; begin Assert(False); Result := nil; end; function TDataGeneratorAdapterFactory.GetEnabled: Boolean; begin Result := True; end; function TDataGeneratorAdapterFactory.BindScopeClass: TComponentClass; begin Result := TDataGeneratorAdapter; end; { TPrototypeBindSourceFactory } function TPrototypeBindSourceFactory.CreateBindScopeEditor( AOwner: TComponent; AScope: TComponent): IBindScopeEditor; begin Assert(AScope is TCustomPrototypeBindSource); Result := TPrototypeBindSourceEditor.Create(AOwner, AScope as TCustomPrototypeBindSource, Designer); end; function TPrototypeBindSourceFactory.CreateNewBindScopeManager(AOwner: TComponent): INewBindScopeManager; begin Result := TNewPrototypeBindSourceManager.Create(AOwner, Designer); end; function TPrototypeBindSourceFactory.GetEnabled: Boolean; begin Result := True; end; function TPrototypeBindSourceFactory.BindScopeClass: TComponentClass; begin Result := TPrototypeBindSource; end; { TDataGeneratorAdapterEditor } resourcestring sEnterAFieldName = 'Enter a field name'; sDuplicateFieldName = 'Field name is not unique'; const sFieldName = 'Field%d'; procedure TDataGeneratorAdapterEditor.ValidateNewField(Sender: TObject; var AValid: Boolean); var LDialog: TNewObjectBindScopeField; LFieldName: string; LFieldNames: TArray<string>; begin LDialog := Sender as TNewObjectBindScopeField; if LDialog.AllowMultiSelect then LFieldNames := LDialog.FieldNames else LFieldNames := TArray<string>.Create(LDialog.FieldName); for LFieldName in LFieldNames do begin if LFieldName = '' then begin AValid := False; MessageDlg(sEnterAFieldName, mtError, [mbOK], 0); end; if FieldExists(LFieldName) then begin AValid := False; MessageDlg(sDuplicateFieldName, mtError, [mbOK], 0); end; end; end; procedure TDataGeneratorAdapterEditor.ExistingFieldName(Sender: TObject; const AFieldName: string; var AExists: Boolean); begin AExists := FieldExists(AFieldName); end; function TDataGeneratorAdapterEditor.FieldExists(const AFieldName: string): Boolean; begin Result := False; if FDataSource <> nil then begin if (FindNewField(AFieldName) <> -1) or (FDataSource.FindField(AFieldName) <> nil) then begin Result := True; end; end; end; function TDataGeneratorAdapterEditor.AddField: TArray<string>; var LDialog: TNewObjectBindScopeField; LBindFieldDef: TGeneratorFieldDef; I: Integer; LFieldNames: TArray<string>; LResult: TList<string>; begin LResult := TList<string>.Create; try Assert(FDataSource <> nil); if FDataSource <> nil then begin LDialog := TNewObjectBindScopeField.Create(FOwner); try I := 1; while FieldExists(Format(sFieldName, [I])) do Inc(I); LDialog.FieldName := Format(sFieldName, [I]); LDialog.OnValidate := ValidateNewField; LDialog.OnExistingFieldName := ExistingFieldName; LDialog.Initialize; LDialog.AllowMultiSelect := True; if LDialog.ShowModal = mrOK then begin LFieldNames := LDialog.FieldNames; for I := 0 to Length(LFieldNames) - 1 do begin LBindFieldDef := TGeneratorFieldDef.Create(nil, LFieldNames[I], 0); LBindFieldDef.Name := LFieldNames[I]; LBindFieldDef.FieldType := LDialog.FieldTypes[I]; LBindFieldDef.Options := LDialog.Options; LBindFieldDef.Generator := LDialog.Generators[I]; FNewFields.Add(LBindFieldDef); LResult.Add(LBindFieldDef.Name); end; end; finally LDialog.Free; end; end; Result := LResult.ToArray; finally LResult.Free; end; end; function TDataGeneratorAdapterEditor.CanAddFields: Boolean; begin Result := FDataSource <> nil; end; function TDataGeneratorAdapterEditor.CanRemoveField( const AFieldName: string): Boolean; begin Result := (FDataSource <> nil) and (FindNewField(AFieldName) <> -1) end; constructor TDataGeneratorAdapterEditor.Create(AOwner: TComponent; ADataSource: TCustomDataGeneratorAdapter; const ADesigner: IDesigner); begin FOwner := AOwner; FDataSource := ADatasource; FDesigner := ADesigner; FNewFields := TObjectList<TGeneratorFieldDef>.Create; end; function TDataGeneratorAdapterEditor.Changed: Boolean; begin Result := FNewFields.Count > 0; end; function TDataGeneratorAdapterEditor.ApplyChanges: TArray<TPersistentPair>; var LFieldDef: TGeneratorFieldDef; LBindFieldDef: TGeneratorFieldDef; LAdapter: TCustomDataGeneratorAdapter; LResult: TList<TPersistentPair>; LActive: Boolean; begin LResult := TList<TPersistentPair>.Create; try if FDataSource <> nil then begin for LFieldDef in FNewFields do begin LAdapter := TCustomDataGeneratorAdapter(FDataSource); LActive := LAdapter.Active; LAdapter.Active := False; LBindFieldDef := LAdapter.FieldDefs.AddFieldDef; LBindFieldDef.Assign(LFieldDef); LResult.Add(TPersistentPair.Create(LBindFieldDef.Name, LBindFieldDef)); try LAdapter.Active := LActive; except // Conversion exceptions may occur when activate Application.HandleException(Self); end; end; FNewFields.Clear; FDesigner.Modified; end else Assert(False); Result := LResult.ToArray; finally LResult.Free; end; end; destructor TDataGeneratorAdapterEditor.Destroy; begin inherited; FNewFields.Free; end; function TDataGeneratorAdapterEditor.RemoveField(const AFieldName: string): Boolean; var I: Integer; begin Result := False; I := FindNewField(AFieldName); if I <> -1 then begin FNewFields.Delete(I); Exit(True); end else Assert(False); // Not found end; function TDataGeneratorAdapterEditor.FindNewField(const AFieldName: string): Integer; var I: Integer; begin for I := 0 to FNewFields.Count - 1 do begin if FNewFields[I].Name = AFieldName then begin Exit(I); end; end; Result := -1; end; procedure TDataGeneratorAdapterEditor.GetMembers(AList: TStrings); var LBindFieldDef: TGeneratorFieldDef; LItem: TCollectionItem; begin AList.Clear; for LItem in FDataSource.FieldDefs do AList.Add(TGeneratorFieldDef(LItem).Name); for LBindFieldDef in FNewFields do AList.Add(LBindFieldDef.Name); end; { TPrototypeBindSourceEditor } constructor TPrototypeBindSourceEditor.Create(AOwner: TComponent; ADataSource: TCustomPrototypeBindSource; const ADesigner: IDesigner); begin FDataSource := ADataSource; inherited Create(AOwner, FDataSource.DataGenerator as TCustomDataGeneratorAdapter, ADesigner); end; { TNewPrototypeBindSourceManager } procedure TBaseNewGeneratorScopeManager.ValidateNewField(Sender: TObject; var AValid: Boolean); var LDialog: TNewObjectBindScopeField; LFieldNames: TArray<string>; LFieldName: string; begin LDialog := Sender as TNewObjectBindScopeField; if LDialog.AllowMultiSelect then LFieldNames := LDialog.FieldNames else LFieldNames := TArray<string>.Create(LDialog.FieldName); for LFieldName in LFieldNames do begin if LFieldName = '' then begin AValid := False; MessageDlg(sEnterAFieldName, mtError, [mbOK], 0); end; if FieldExists(LFieldName) then begin AValid := False; MessageDlg(sDuplicateFieldName, mtError, [mbOK], 0); end; end; end; procedure TBaseNewGeneratorScopeManager.ExistingFieldName(Sender: TObject; const AFieldName: string; var AExists: Boolean); begin AExists := FieldExists(AFieldName); end; function TBaseNewGeneratorScopeManager.FieldExists(const AFieldName: string): Boolean; begin Result := False; if GetAdapter is TCustomDataGeneratorAdapter then begin if (GetAdapter.FindField(AFieldName) <> nil) then begin Result := True; end; end; end; function TBaseNewGeneratorScopeManager.AddField: string; var LDialog: TNewObjectBindScopeField; LBindFieldDef: TGeneratorFieldDef; LAdapter: TCustomDataGeneratorAdapter; I: Integer; LFieldNames: TArray<string>; begin Result := ''; LDialog := TNewObjectBindScopeField.Create(FOwner); try I := 1; Assert(Format(sFieldName,[1]) <> Format(sFieldName, [2])); while FieldExists(Format(sFieldName, [I])) do Inc(I); LDialog.FieldName := Format(sFieldName, [I]); LDialog.OnValidate := ValidateNewField; LDialog.OnExistingFieldName := ExistingFieldName; LDialog.AllowMultiSelect := True; LDialog.Initialize; if LDialog.ShowModal = mrOK then begin InternalDataSource; if GetAdapter is TCustomDataGeneratorAdapter then begin LAdapter := TCustomDataGeneratorAdapter(GetAdapter); LFieldNames := LDialog.FieldNames; for I := 0 to Length(LFieldNames) - 1 do begin LBindFieldDef := LAdapter.FieldDefs.AddFieldDef; LBindFieldDef.Name := LFieldNames[I]; LBindFieldDef.FieldType := LDialog.FieldTypes[I]; LBindFieldDef.Options := LDialog.Options; LBindFieldDef.Generator := LDialog.Generators[I]; Result := LBindFieldDef.Name; end; end else Assert(False); end; finally LDialog.Free; end; end; function TBaseNewGeneratorScopeManager.CanAddFields: Boolean; begin InternalDataSource; Result := GetAdapter is TCustomDataGeneratorAdapter; end; function TBaseNewGeneratorScopeManager.CanRemoveField( const AFieldName: string): Boolean; begin InternalDataSource; Result := GetAdapter is TCustomDataGeneratorAdapter; end; constructor TBaseNewGeneratorScopeManager.Create(AOwner: TComponent; const ADesigner: IDesigner); begin FOwner := AOwner; FDesigner := ADesigner; end; destructor TBaseNewGeneratorScopeManager.Destroy; begin inherited; end; function TBaseNewGeneratorScopeManager.RemoveField(const AFieldName: string): Boolean; var LBindFieldDef: TGeneratorFieldDef; LAdapter: TCustomDataGeneratorAdapter; begin Result := False; InternalDataSource; if GetAdapter is TCustomDataGeneratorAdapter then begin LAdapter := TCustomDataGeneratorAdapter(GetAdapter); LBindFieldDef := LAdapter.FieldDefs.Find(AFieldName); if LBindFieldDef <> nil then begin LAdapter.FieldDefs.Delete(LBindFieldDef.Index); Exit(True); end; end else Assert(False); end; { TNewPrototypeBindSourceManager } function TNewPrototypeBindSourceManager.GetAdapter: TCustomDataGeneratorAdapter; begin Assert(FDataSource <> nil); Result := TCustomPrototypeBindSource(FDataSource).DataGenerator; end; function TNewPrototypeBindSourceManager.CreateScope: TBaseLinkingBindSource; var LInternalScope: TCustomPrototypeBindSource; LNewScope: TCustomPrototypeBindSource; begin LNewScope := FDesigner.CreateComponent(TPrototypeBindSource, FDesigner.Root, 0, 0, 0, 0) as TCustomPrototypeBindSource; try LInternalScope := FDataSource; if LInternalScope <> nil then begin TCustomDataGeneratorAdapter(LNewScope.DataGenerator).FieldDefs.Assign( TCustomDataGeneratorAdapter(LInternalScope.DataGenerator).FieldDefs); end; Result := LNewScope; except LNewScope.Free; raise; end; end; destructor TNewPrototypeBindSourceManager.Destroy; begin inherited; FDataSource.Free; end; function TNewPrototypeBindSourceManager.InternalDataSource: TComponent; var LScope: TPrototypeBindSource; begin if FDataSource = nil then begin LScope := TPrototypeBindSource.Create(nil); FDataSource := LScope; end; Result := FDataSource; end; { TGetDesignerComponents } procedure TGetDesignerComponents.ComponentNameProc(const RootName: string); var LComponent: TComponent; begin LComponent := FDesigner.GetComponent(RootName); Assert(Assigned(FComponentProc)); if Assigned(FComponentProc) then FComponentProc(LComponent, RootName); end; // Get components available to a designer, even from linked data modules constructor TGetDesignerComponents.Create(const ADesigner: IDesigner); begin FDesigner := ADesigner; end; procedure TGetDesignerComponents.GetDesignerComponents(AProc: TProc<TComponent, string>); var PropInfo: PPropInfo; begin Assert(FCounter = 0); // Make sure we don't reenter Inc(FCounter); try PropInfo := System.TypInfo.GetPropInfo(TypeInfo(TComponentPropertyClass), 'Component'); Assert(PropInfo <> nil); Assert(not Assigned(FComponentProc)); FComponentProc := AProc; try FDesigner.GetComponentNames(PropInfo.PropType^.TypeData, ComponentNameProc); finally FComponentProc := nil; end; finally Dec(FCounter); end; end; function GetRootOwner(AComponent: TComponent): TComponent; begin Result := AComponent.Owner; while (Result <> nil) and (csInline in Result.ComponentState) do Result := Result.Owner; end; function TGetDesignerComponents.IsExternalComponent( AComponent: TComponent): Boolean; var LResult: Boolean; begin if GetRootOwner(AComponent) = FDesigner.Root then // Short circuit Exit(False); LResult := False; GetDesignerComponents( procedure(ADesignerComponent: TComponent; AName: string) begin if ADesignerComponent = AComponent then if Pos('.', AName) > 1 then begin LResult := True; end; end); Result := LResult; end; procedure Register; const sSourceMemberName = 'SourceMemberName'; begin RegisterNoIcon([TBindExpression, TBindExprItems, TBindLink, TBindList, TBindGridLink, TBindListLink, TBindGridList, TBindPosition]); RegisterNoIcon([TBindControlValue]); RegisterNoIcon([TLinkListControlToField, TLinkControlToField, TLinkControlToProperty, TLinkPropertyToField, TLinkFillControlToField, TLinkFillControlToProperty]); RegisterClasses([TBindExpression, TBindExprItems, TBindLink, TBindList, TBindGridLink, TBindListLink, TBindGridList, TBindPosition, TBindControlValue]); RegisterClasses([TBindControlValue]); RegisterClasses([TLinkListControlToField, TLinkControlToField, TLinkControlToProperty, TLinkPropertyToField, TLinkFillControlToField, TLinkFillControlToProperty]); RegisterBindComponents(SDataBindingsCategory_BindingExpressions, [TBindExpression, TBindExprItems]); RegisterBindComponents(SDataBindingsCategory_Links, [TBindLink, TBindListLink, TBindGridLink, TBindPosition, TBindControlValue]); RegisterBindComponents(SDataBindingsCategory_Lists, [TBindList, TBindGridList]); RegisterBindComponents(SQuickBindingsCategory, [TLinkListControlToField, TLinkControlToField, TLinkControlToProperty, TLinkPropertyToField, TLinkFillControlToField, TLinkFillControlToProperty]); RegisterComponents(SBindingComponentsMiscCategory, [TBindingsList]); RegisterComponents(SBindingComponentsMiscCategory, [TDataGeneratorAdapter]); RegisterComponents(SBindingComponentsCategory, [TPrototypeBindSource]); RegisterComponents(SBindingComponentsMiscCategory, [TAdapterBindSource]); RegisterComponentEditor(TCustomBindingsList, TBindCompListEditor); RegisterSelectionEditor(TComponent, TLBVisualizationPropertyFilter); // Verbs to add data bindings RegisterSelectionEditor(TBaseLinkingBindSource, TBindCompFactorySelectionEditor); RegisterSelectionEditor(TBindSourceAdapter, TBindCompFactorySelectionEditor); RegisterSelectionEditor(TDataSource, TBindCompFactorySelectionEditor); RegisterSelectionEditor(TDataSet, TBindCompFactorySelectionEditor); // RegisterSelectionEditor(TBaseLinkingBindSource, TAddNavigatorSelectionEditor); RegisterSelectionEditor(TDataSet, TAddBindScopeSelectionEditor); RegisterSelectionEditor(TBindSourceAdapter, TAddBindScopeSelectionEditor); RegisterComponentEditor(TContainedBindComponent, TBindCompExpressionEditor); // RegisterComponentEditor(TBaseLinkingBindSource, TBaseLinkingBindScopeEditor); RegisterComponentEditor(TCustomBindList, TBindFillListExpressionEditor); RegisterComponentEditor(TCustomBindGridLink, TBindFillGridLinkExpressionEditor); RegisterComponentEditor(TCustomBindGridLIst, TBindFillGridListExpressionEditor); RegisterComponentEditor(TCustomLinkFillControlToField, TBindFillGridListExpressionEditor); RegisterComponentEditor(TCustomLinkFillControlToProperty, TBindFillGridListExpressionEditor); RegisterComponentEditor(TCustomBindExpression, TBindEvaluateExpressionEditor); RegisterComponentEditor(TCustomBindExprItems, TBindEvaluateExprItemsEditor); RegisterPropertyEditor(TypeInfo(TMethods), nil, '', TMethodsPropertyEditor); RegisterPropertyEditor(TypeInfo(TOutputConverters), nil, '', TOutputConvertersPropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCommonBindComponent, sSourceMemberName, TSourceMemberNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TColumnLinkExpressionItem, sSourceMemberName, TSourceMemberNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TColumnFormatExpressionItem, sSourceMemberName, TSourceMemberNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkControlToProperty, 'ComponentProperty', TLinkControlToPropertyNamesEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkPropertyToField, 'ComponentProperty', TLinkPropertyToFieldPropertyNamesEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkPropertyToField, 'FieldName', TFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkListControlToField, 'FieldName', TFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkControlToField, 'FieldName', TFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FieldName', TLinkFillControlToFieldFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FillValueFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FillDisplayFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FillHeaderCustomFormat', TFillCustomFormatPropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FillBreakFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'FillHeaderFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'FillValueFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'FillDisplayFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'FillHeaderCustomFormat', TFillCustomFormatPropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'FillBreakFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'FillHeaderFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TLinkListControlToField, 'FillHeaderCustomFormat', TFillCustomFormatPropertyEditor); RegisterPropertyEditor(TypeInfo(string), TLinkListControlToField, 'FillBreakFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TLinkListControlToField, 'FillHeaderFieldName', TFillFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkPropertyToField, 'LookupKeyFieldName', TLookupKeyFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkPropertyToField, 'LookupValueFieldName', TLookupFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkControlToField, 'LookupKeyFieldName', TLookupKeyFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkControlToField, 'LookupValueFieldName', TLookupFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TGeneratorFieldDef , 'Generator', TGeneratorNamePropertyEditor); RegisterPropertyEditor(TypeInfo(TGeneratorFieldDefs), nil, '', TGeneratorFieldDefsPropertyEditor); RegisterComponentEditor(TDataGeneratorAdapter, TScopeAdapterFieldsEditor); RegisterComponentEditor(TPrototypeBindSource, TScopeAdapterFieldsEditor); RegisterComponentEditor(TBaseLinkingBindSource, TBaseLinkingBindScopeEditor); // Default component editor RegisterPropertyEditor(TypeInfo(TBaseLinkingBindSource), TLinkControlToFieldDelegate, 'DataSource', TLinkingBindScopePropertyEditor); RegisterPropertyEditor(TypeInfo(TBaseLinkingBindSource), TLinkPropertyToFieldDelegate, 'DataSource', TLinkingBindScopePropertyEditor); RegisterPropertyEditor(TypeInfo(TBaseLinkingBindSource), TBaseLinkToDataSource, 'DataSource', TLinkingBindScopePropertyEditor); RegisterSprigType(TCustomBindingsList, TCustomBindCompListSprig); RegisterSprigType(TContainedBindComponent, TCustomDataBindingSprig); RegisterSprigType(TContainedBindComponent, TCustomAssociatedDataBindingSprig); RegisterPropertyEditor(TypeInfo(string), TFormatExpressionItem , sSourceMemberName, TFieldNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TFormatExpressionItem , 'ControlMemberName', TControlMembersPropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToField, 'ListItemStyle', TEditorNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkFillControlToProperty, 'ListItemStyle', TEditorNamePropertyEditor); RegisterPropertyEditor(TypeInfo(string), TCustomLinkListControlToField, 'ListItemStyle', TEditorNamePropertyEditor); RegisterPropertyEditor(TypeInfo(TComponent), TCustomLinkControlToField, 'Control', TLinkingControlPropertyEditor); RegisterPropertyEditor(TypeInfo(TComponent), TCustomLinkControlToProperty, 'Control', TLinkingControlPropertyEditor); // List controls only RegisterPropertyEditor(TypeInfo(TComponent), TCustomLinkListControlToField, 'Control', TLinkingFillControlPropertyEditor); RegisterPropertyEditor(TypeInfo(TComponent), TCustomLinkFillControlToField, 'Control', TLinkingFillControlPropertyEditor); RegisterPropertyEditor(TypeInfo(TComponent), TCustomLinkFillControlToProperty, 'Control', TLinkingFillControlPropertyEditor); RegisterBindCompFactory(TNewBindCompWizardFactory.Create); // Do not show "New LiveBindings component" in object inspector or menu // RegisterBindCompFactory(TNewBindCompDialogFactory.Create); RegisterBindCompFactory(TBindVisuallyViewFactory.Create); // Add 'Live Bindings' property to components // RegisterSelectionEditor(TComponent, TAddDataBindingsPropertyFilter); // Add RTTI unit to uses list RegisterSelectionEditor(TCommonBindComponent, TRttiUnitSelectionEditor); RegisterSelectionEditor(TBindComponentDelegate, TRttiUnitSelectionEditor); // Add BindingsList used methods/converters required units to the uses list RegisterSelectionEditor(TCustomBindingsList, TCustomBindCompListSelectionEditor); RegisterSelectionEditor(TCustomBindingsList, TBindCompFactorySelectionEditor); // Add "DataBindings" property to object inspector RegisterBoundComponents([TComponent], [dbcoptAddDataBindingsProperty, dbcoptApplyToDescendents]); // RegisterControlFrameFactory(TObjectBindScopeFactory); RegisterControlFrameFactory(TPrototypeBindSourceFactory); RegisterControlFrameFactory(TDataGeneratorAdapterFactory); RegisterSelectionEditor(TCustomDataGeneratorAdapter, TDataGeneratorSelectionEditor); // RegisterSelectionEditor(TCustomObjectBindScope, TObjectBindScopeDataGeneratorSelectionEditor); RegisterSelectionEditor(TCustomPrototypeBindSource, TPrototypeBindSourceDataGeneratorSelectionEditor); end; function GetDataBindingComponents(AControlComponent: TComponent): TArray<TContainedBindComponent>; var LOwner: TComponent; LDataBindingComponent: TContainedBindComponent; LDesigner: IBindCompDesigner; LResult: TArray<TContainedBindComponent>; begin SetLength(LResult, 0); LOwner := AControlComponent.Owner; if LOwner <> nil then GetOwnedComponents(LOwner, procedure(LOwnedComponent: TComponent) begin // Exclude components that are being deleted if LOwnedComponent is TContainedBindComponent then begin LDataBindingComponent := TContainedBindComponent(LOwnedComponent); if TProxyComponent.FPendingFreeList.Contains(LDataBindingComponent) then begin // Skip end else begin LDesigner := GetBindCompDesigner(TContainedBindCompClass(LDataBindingComponent.ClassType)); if LDesigner <> nil then begin if LDesigner.BindsComponent(LDataBindingComponent, AControlComponent) then begin SetLength(LResult, Length(LResult) + 1); LResult[Length(LResult)-1] := TContainedBindComponent(LOwnedComponent); end; end; end; end; end); Result := LResult; end; type // Wrapper around a DataBinding component to make it appear in the object inspector under // the DataBindingsProperty TDataBindingComponentProperty = class(TComponentProperty, IPropertyKind, IProperty, IProperty80) private FComponentReference: TContainedBindComponent; FProxyComponent: TProxyComponent; FActionListView: TBindCompListView; FHost: IPropertyHost; FDataBindingsPropertyNamePath: string; FFilterFuncDesigner: IBindCompDesigner; protected function GetComponentReference: TComponent; override; function GetAttributes: TPropertyAttributes; override; private procedure SetComponent(ACustomDataBinding: TContainedBindComponent); { IPropertyKind } function GetName: string; override; procedure DeleteDataBinding(Sender: TObject); procedure SelectDataBindingComponent(Sender: TObject); procedure SelectDataBindingsProperty(ADesigner: IDesigner); function FilterFunc(const ATestEditor: IProperty): Boolean; protected // IProperty80 procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; overload; public destructor Destroy; override; procedure GetProperties(Proc: TGetPropProc); override; end; function TDataBindingComponentProperty.GetName: string; var LComponent: TComponent; begin LComponent := GetComponentReference; if LComponent <> nil then Result := LComponent.Name else Result := inherited; // Name of TProxyComponent property end; function TDataBindingComponentProperty.GetComponentReference; begin Result := FComponentReference; end; procedure TDataBindingComponentProperty.SelectDataBindingsProperty(ADesigner: IDesigner); begin (BorlandIDEServices as IOTAPropInspServices).Expand; ADesigner.SelectItemName(FDataBindingsPropertyNamePath); end; function TDataBindingComponentProperty.FilterFunc(const ATestEditor: IProperty): Boolean; begin Result := not (paNotNestable in ATestEditor.GetAttributes); if Result then begin if FFilterFuncDesigner <> nil then begin // Hide property use to specify the bound component if FFilterFuncDesigner.BindsComponentPropertyName(FComponentReference, ATestEditor.GetName) then Result := False; end; end; end; procedure TDataBindingComponentProperty.DeleteDataBinding(Sender: TObject); begin FHost.CloseDropDown; if (idYes <> MessageDlg( Format(sConfirmDelete, [FProxyComponent.FComponent.Name]), mtConfirmation, mbYesNoCancel, 0)) then Exit; TProxyComponent.FPendingFreeList.Add(FProxyComponent.FComponent); SelectDataBindingsProperty(FActionListView.Designer); // Deep modify, which will handle volatile properties (BorlandIDEServices as IOTAPropInspServices).VolatileModified; end; procedure TDataBindingComponentProperty.SelectDataBindingComponent(Sender: TObject); var LSelection: IDesignerSelections; begin FHost.CloseDropDown; LSelection := TDesignerSelections.Create as IDesignerSelections; LSelection.Add(FProxyComponent.FComponent); Designer.SetSelections(LSelection); end; destructor TDataBindingComponentProperty.Destroy; begin if FActionListView <> nil then FreeAndNil(FActionListView); FProxyComponent.Free; inherited; end; function TDataBindingComponentProperty.GetAttributes: TPropertyAttributes; begin Result := inherited + [paCustomDropDown] - [paValueList, paSortList]; end; procedure TDataBindingComponentProperty.GetProperties(Proc: TGetPropProc); var LComponents: IDesignerSelections; LDesigner: IDesigner; begin LComponents := GetSelections; if LComponents <> nil then begin if not Supports(FindRootDesigner(LComponents[0]), IDesigner, LDesigner) then LDesigner := Designer; FFilterFuncDesigner := GetBindCompDesigner(TContainedBindCompClass(Self.FComponentReference.ClassType)); try GetComponentProperties(LComponents, tkAny, LDesigner, Proc, FilterFunc); finally FFilterFuncDesigner := nil; end; end; end; procedure TDataBindingComponentProperty.SetComponent(ACustomDataBinding: TContainedBindComponent); var PropInfo: PPropInfo; begin FProxyComponent := TProxyComponent.Create(nil, Self.Designer); FProxyComponent.FComponent := ACustomDataBinding; FComponentReference := ACustomDataBinding; PropInfo := System.TypInfo.GetPropInfo(FProxyComponent, 'ComponentProperty'); Self.SetPropEntry(0, FProxyComponent, PropInfo); Self.Initialize; end; function GetDesignerModel(ADesigner: IDesigner): IVGModel; var LGraph: IVGHandler; LModules: TArray<IVGModule>; LModule: IVGModule; begin Result := nil; if VisualizationService = nil then Exit; LGraph := VisualizationService.ActiveGraph; if LGraph = nil then Exit; LModules := LGraph.GetModules; for LModule in LModules do if LModule.Designer = ADesigner then Exit(LModule.GetModel); end; { TLBVisualizationPropertyFilter } procedure TLBVisualizationPropertyFilter.FilterProperties( const ASelection: IDesignerSelections; const ASelectionProperties: IInterfaceList); var I, J: Integer; LComponents: TList<TComponent>; LNewProperty: TVGSyntheticPropertyGroup; LProperty: IProperty; LIndex: Integer; LModel: IVGModel; begin LModel := GetDesignerModel(Designer); if LModel = nil then Exit; LComponents := TList<TComponent>.Create; try for I := 0 to ASelection.Count - 1 do begin if (ASelection.Items[I] is TComponent) and not ( ASelection.Items[I] is TContainedBindComponent) then LComponents.Add(ASelection.Items[I] as TComponent); end; if LComponents.Count > 0 then begin LNewProperty := TVGSyntheticPropertyGroup.Create(Designer, 1); LNewProperty.SelectedComponents := LComponents.ToArray; LIndex := -1; for J := 0 to ASelectionProperties.Count - 1 do begin if Supports(ASelectionProperties[J], IProperty, LProperty) then begin if CompareText(LNewProperty.GetName, LProperty.GetName) <= 0 then begin LIndex := J; break; end; end; end; if LIndex <> -1 then ASelectionProperties.Insert(LIndex, LNewProperty as IProperty) else ASelectionProperties.Add(LNewProperty); end; finally LComponents.Free; end; end; { TAddDataBindingsPropertyFilter } procedure TAddDataBindingsPropertyFilter.FilterProperties( const ASelection: IDesignerSelections; const ASelectionProperties: IInterfaceList); var I, J: Integer; LSelectedItem: TPersistent; LNewProperty: TDataBindingSyntheticProperty; LProperty: IProperty; LIndex: Integer; LComponent: TComponent; LOptions: TBoundComponentOptions; begin if ASelection.Count > 1 then // Don't show property if multiple selection Exit; for I := 0 to ASelection.Count - 1 do begin LSelectedItem := ASelection[I]; if (LSelectedItem is TComponent) then begin LComponent := TComponent(LSelectedItem); LOptions := GetBoundComponentOptions(TComponentClass(LComponent.ClassType)); if not (TBoundComponentOption.dbcoptAddDataBindingsProperty in LOptions) then continue; LNewProperty := TDataBindingSyntheticProperty.Create(Designer, 1); LNewProperty.Component := LComponent; LIndex := 0; for J := 0 to ASelectionProperties.Count - 1 do begin if Supports(ASelectionProperties[J], IProperty, LProperty) then begin if CompareText(LNewProperty.GetName, LProperty.GetName) <= 0 then begin LIndex := J; break; end; end; end; ASelectionProperties.Insert(LIndex, LNewProperty as IProperty); end; end; end; procedure TDataBindingComponentProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var LHost20: IPropertyHost20; LCustomActions: TList<TCustomAction>; begin FHost := Host; if FActionListView <> nil then begin FActionListView.Free; end; LCustomActions := TObjectList<TCustomAction>.Create; try FActionListView := TBindCompListView.Create(nil); FActionListView.Options := [dblvDelete, dblvSelect]; FActionListView.DataBindingComponentName := FProxyComponent.FComponent.Name; if Supports(FHost, IPropertyHost20, LHost20) then FActionListView.Width := LHost20.GetDropDownWidth; FActionListView.OnDeleteDataBinding := DeleteDataBinding; FActionListView.OnSelectDataBindingComponent := SelectDataBindingComponent; FActionListView.AddVerbActions(FProxyComponent.FComponent, LCustomActions, Designer); FActionListView.CustomActions := LCustomActions.ToArray; FActionListView.Designer := Designer; FActionListView.Visible := True; FHost.DropDownControl(FActionListView); finally LCustomActions.Free; end; end; { TDataBindingSyntheticProperty } function TDataBindingSyntheticProperty.GetAttributes: TPropertyAttributes; begin // Not nestible so that it won't appear inside expanded component references Result := [paSubProperties, paVolatileSubProperties, paCustomDropDown, paReadOnly, paNotNestable]; end; function TDataBindingSyntheticProperty.GetName: string; begin Result := sName end; procedure TDataBindingSyntheticProperty.GetProperties(Proc: TGetPropProc); var LComponents: TArray<TContainedBindComponent>; LComponent: TContainedBindComponent; LComponentProperty: TDataBindingComponentProperty; begin LComponents := GetDataBindingComponents(FComponent); for LComponent in LComponents do begin LComponentProperty := TDataBindingComponentProperty.Create(Designer, 1); LComponentProperty.SetComponent(LComponent); //LComponentProperty.FDataBindingsProperty := Self; LComponentProperty.FDataBindingsPropertyNamePath := GetName; Proc(LComponentProperty as IProperty); end; end; function TDataBindingSyntheticProperty.GetValue: string; begin Result := GetName; // ReverseString(Component.Name); end; procedure TDataBindingSyntheticProperty.SetValue(const Value: string); begin Component.Name := ReverseString(Value); Designer.Modified; end; function TDataBindingSyntheticProperty.ShowReferenceProperty: Boolean; begin Result := True; end; destructor TDataBindingSyntheticProperty.Destroy; begin FBindCompListView.Free; FHost := nil; inherited; end; procedure TDataBindingSyntheticProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var LHost20: IPropertyHost20; LCustomActions: TList<TCustomAction>; begin FHost := Host; if FBindCompListView <> nil then FBindCompListView.Free; LCustomActions := TObjectList<TCustomAction>.Create; try FBindCompListView := TBindCompListView.Create(nil); FBindCompListView.Options := [dblvCreateNewFactory, dblvSelectExisting]; FBindCompListView.ControlComponent := ControlComponent; if Supports(FHost, IPropertyHost20, LHost20) then FBindCompListView.Width := LHost20.GetDropDownWidth; //FBindCompListView.OnNewDataBinding := CreateNewDataBinding; FBindCompListView.OnNewDataBindingFactory := CreateNewDataBindingFactory; FBindCompListView.OnCreateDataBindingFactoryContext := CreateDataBindingFactoryContext; FBindCompListView.OnSelectDataBindingProperty := SelectDataBindingProperty; FBindCompListView.Designer := Designer; FBindCompListView.AddFactoryActions(LCustomActions); //FBindCompListView.AddVerbActions(ControlComponent, LCustomActions); FBindCompListView.CustomActions := LCustomActions.ToArray; FBindCompListView.Visible := True; FHost.DropDownControl(FBindCompListView); finally LCustomActions.Free; end; end; procedure TDataBindingSyntheticProperty.SelectDataBindingProperty(Sender: TObject; DataBinding: TContainedBindComponent); begin // if DataBinding <> nil then // SetValue(DataBinding.Owner.Name + DotSep + DataBinding.Name) // else // SetValue(''); // Select under Databindings FHost.CloseDropDown; (BorlandIDEServices as IOTAPropInspServices).Expand; if DataBinding <> nil then Designer.SelectItemName(GetName + '.' + DataBinding.Name); end; function TDataBindingSyntheticProperty.CreateDataBindingFactoryExecuteContext(ABindCompList: TCustomBindingsList): IBindCompFactoryExecuteContext; var LComponent: TComponent; begin Result := nil; LComponent := ControlComponent; if LComponent <> nil then begin Result := TDataBindingFactoryExecuteContext.Create(Designer, ABindCompList, LComponent); //FComponent); end; end; procedure TDataBindingSyntheticProperty.CreateDataBindingFactoryContext(Sender: TObject; ABindCompList: TCustomBindingsList; var AContext: IBindCompFactoryContext); var LComponent: TComponent; begin AContext := nil; LComponent := ControlComponent; if LComponent <> nil then begin AContext := TDataBindingFactoryContext.Create(Designer, ABindCompList, LComponent); //FComponent); end; end; procedure TDataBindingSyntheticProperty.CreateNewDataBindingFactory(Sender: TObject; DataBindingFactory: IBindCompFactory; BindingsList: TCustomBindingsList); var LContext: IBindCompFactoryExecuteContext; LBindCompList: TBindingsList; begin LBindCompList := nil; LContext := CreateDataBindingFactoryExecuteContext(BindingsList); Assert(LContext <> nil); if LContext.BindingsList = nil then begin LBindCompList := BindCompReg.CreateBindingsList(LContext.Owner); // TBindingsList.Create(LContext.Owner); // if Assigned(LContext.Owner) then // begin // //Place BindingsList in top left corner of parent (Low Word = Left, High Word = Top) // LBindCompList.DesignInfo := (5 shl 16) + 20; // LContext.Owner.InsertComponent(LBindCompList); // end; LBindCompList.Name := LContext.UniqueName(LBindCompList.ClassType.ClassName ); (LContext as TDataBindingFactoryExecuteContext).FBindCompList := LBindCompList; end; if FHost <> nil then FHost.CloseDropDown; if LContext <> nil then DataBindingFactory.Execute(LContext); if LBindCompList <> nil then begin if LBindCompList.BindCompCount = 0 then // Free compononent we've create because no binding components created LBindCompList.Free; end; end; { TProxyComponent } class constructor TProxyComponent.Create; begin FPendingFreeList := TList<TComponent>.Create; end; constructor TProxyComponent.Create(AOwner: TComponent; ADesigner: IDesigner); begin inherited Create(AOwner); FDesigner := ADesigner; end; destructor TProxyComponent.Destroy; begin if FPendingFreeList.Contains(FComponent) then begin FPendingFreeList.Remove(FComponent); FComponent.Free; if FDesigner <> nil then FDesigner.Modified; end; inherited; end; class destructor TProxyComponent.Destroy; begin FPendingFreeList.Free; end; { TDataBindingFactory } constructor TDataBindingFactory.Create(ACategory: string; AClass: TContainedBindCompClass); begin FCategory := ACategory; FClass := AClass; end; function TDataBindingFactory.Enabled( AContext: IBindCompFactoryContext): Boolean; begin Result := True; end; procedure TDataBindingFactory.Execute( AContext: IBindCompFactoryExecuteContext); var LNewDataBinding: TContainedBindComponent; begin LNewDataBinding := CreateBindComponent(AContext.Owner, FClass); LNewDataBinding.Name := AContext.UniqueName(LNewDataBinding.ClassType.ClassName); LNewDataBinding.Category := FCategory; LNewDataBinding.BindingsList := AContext.BindingsList; LNewDataBinding.ControlComponent := AContext.ControlComponent; AContext.BindCompCreated(LNewDataBinding); end; function TDataBindingFactory.GetCommandText( AContext: IBindCompFactoryContext): string; begin Result := FClass.ClassName; end; { TDataBindingFactoryContext } constructor TDataBindingFactoryContext.Create(ADesigner: IDesigner; ABindCompList: TCustomBindingsList; AControlComponent: TComponent); begin FDesigner := ADesigner; FBindCompList := ABindCompList; FControlComponent := AControlComponent; end; function TDataBindingFactoryContext.GetControlComponent: TComponent; begin Result := FControlComponent; end; function TDataBindingFactoryContext.GetDesigner: IInterface; begin Result := FDesigner; end; function TDataBindingFactoryContext.GetBindingsList: TCustomBindingsList; begin Result := FBindCompList; end; function TDataBindingFactoryContext.GetOwner: TComponent; begin if FBindCompList = nil then Result := FDesigner.Root else Result := FBindCompList.Owner; end; { TDataBindingFactoryExecuteContext } procedure TDataBindingFactoryExecuteContext.BindCompCreated(AComponent: TComponent); begin FDesigner.Modified; (BorlandIDEServices as IOTAPropInspServices).VolatileModified; (BorlandIDEServices as IOTAPropInspServices).Expand; // Select under Databindings FDesigner.SelectItemName(TDataBindingSyntheticProperty.sName + '.' + AComponent.Name); end; function TDataBindingFactoryExecuteContext.UniqueName(const ABaseName: string): string; var LRoot: IRoot; begin if (FBindCompList = nil) or (FBindCompList.Owner = FDesigner.Root) then Result := FDesigner.UniqueName(ABaseName) else begin LRoot := ActiveDesigner.FindRoot(FBindCompList.Owner); if LRoot <> nil then Result := LRoot.GetDesigner.UniqueName(ABaseName) else raise Exception.CreateResFmt(@SUnableToFindComponent, [FBindCompList.Owner.Name]); end; end; { TBindingComponentPropertyEditor } function TBindingComponentPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList]; end; procedure TBindingComponentPropertyEditor.SetValue(const Value: string); begin try inherited; except // Call modified even if error in expression evaluation Modified; raise; end; end; function TBindingComponentPropertyEditor.GetBindComponent: TContainedBindComponent; var Component: TPersistent; begin Result := nil; Component := GetComponent(0); if Component is TContainedBindComponent then Result := TContainedBindComponent(Component) else if Component is TCollectionItem then begin while Component is TCollectionItem do begin Component := TCollectionItem(Component).Collection.Owner; end; if Component is TContainedBindComponent then Result := TContainedBindComponent(Component); end; end; procedure TBindingComponentPropertyEditor.GetValues(Proc: TGetStrProc); var I: Integer; Values: TStringList; begin Values := TStringList.Create; try GetValueList(Values); for I := 0 to Values.Count - 1 do Proc(Values[I]); finally Values.Free; end; end; function TBindingComponentPropertyEditor.GetComponentProperty(const AName: string): TComponent; var PropInfo: PPropInfo; LBindComponent: TContainedBindComponent; begin Result := nil; LBindComponent := GetBindComponent; if LBindComponent = nil then Exit; PropInfo := System.TypInfo.GetPropInfo(LBindComponent.ClassInfo, AName); // Do not localize Assert(PropInfo <> nil); if (PropInfo <> nil) and (PropInfo^.PropType^.Kind = tkClass) then Result := TObject(GetOrdProp(LBindComponent, PropInfo)) as TComponent; end; function TBindingComponentPropertyEditor.GetStringProperty(const AName: string): string; var PropInfo: PPropInfo; LBindComponent: TContainedBindComponent; begin Result := ''; LBindComponent := GetBindComponent; if LBindComponent = nil then Exit; PropInfo := System.TypInfo.GetPropInfo(LBindComponent.ClassInfo, AName); // Do not localize Assert(PropInfo <> nil); if (PropInfo <> nil) and (PropInfo^.PropType^.Kind = tkUString) then Result := GetStrProp(LBindComponent, PropInfo); end; { TSourceMemberNamePropertyEditor } function TSourceMemberNamePropertyEditor.GetSourceComponent: TComponent; begin Result := GetComponentProperty(GetSourceComponentName); end; function TSourceMemberNamePropertyEditor.GetSourceComponentName: string; begin Result := 'SourceComponent'; end; procedure TSourceMemberNamePropertyEditor.GetMemberNames(ASourceComponent: TComponent; List: TStrings); var LScopeMemberNames: IScopeMemberNames; begin if Supports(ASourceComponent, IScopeMemberNames, LScopeMemberNames) then LScopeMemberNames.GetMemberNames(List); end; procedure TSourceMemberNamePropertyEditor.GetValueList(List: TStrings); var LSourceComponent: TComponent; begin LSourceComponent := GetSourceComponent; GetMemberNames(LSourceComponent, List); end; { TEditorNamePropertyEditor } resourcestring sDefault = '(default)'; procedure TEditorNamePropertyEditor.SetValue(const Value: string); begin if SameText(Value, sDefault) then inherited SetValue('') else inherited SetValue(Value); end; function TEditorNamePropertyEditor.GetControlComponent: TComponent; begin Result := GetComponentProperty(GetControlComponentName); end; function TEditorNamePropertyEditor.GetControlComponentName: string; begin Result := 'Control'; end; procedure TEditorNamePropertyEditor.GetEditorNames(AControlComponent: TComponent; List: TStrings); var S: string; begin for S in Data.Bind.Components.GetBindEditorNames(AControlComponent, IBindListEditorCommon) do List.Add(S); end; function TEditorNamePropertyEditor.GetValue: string; begin Result := inherited GetValue; if Result = '' then Result := sDefault; end; procedure TEditorNamePropertyEditor.GetValueList(List: TStrings); var LControlComponent: TComponent; begin LControlComponent := GetControlComponent; GetEditorNames(LControlComponent, List); Assert(List.IndexOf('') = -1); List.Insert(0, sDefault); end; { TControlMembersPropertyEditor } function TControlMembersPropertyEditor.GetControlComponent: TComponent; begin Result := GetComponentProperty(GetControlComponentName); end; function TControlMembersPropertyEditor.GetEditorName: string; begin Result := GetStringProperty(GetEditorPropertyName); end; function TControlMembersPropertyEditor.GetControlComponentName: string; begin Result := 'Control'; end; function TControlMembersPropertyEditor.GetEditor(AControlComponent: TComponent; const AEditor: string): IInterface; begin Result := GetBindEditor(AControlComponent, IBindListEditorCommon, AEditor); end; function TControlMembersPropertyEditor.GetEditorPropertyName: string; begin Result := 'ListItemStyle'; end; procedure TControlMembersPropertyEditor.GetItemMemberNames(AControlComponent: TComponent; const AEditor: string; AList: TStrings); var LBindFillControlMembers: IBindFillControlMembers; begin AList.Clear; if Supports(GetEditor(AControlComponent, AEditor), IBindFillControlMembers, LBindFillControlMembers) then LBindFillControlMembers.GetItemMemberNames(AList) end; procedure TControlMembersPropertyEditor.GetValueList(List: TStrings); var LControlComponent: TComponent; LEditor: string; begin LControlComponent := GetControlComponent; LEditor := GetEditorName; GetItemMemberNames(LControlComponent, LEditor, List); end; { TRttiUnitSelectionEditor } procedure TRttiUnitSelectionEditor.RequiresUnits(Proc: TGetStrProc); begin Proc('System.Rtti'); Proc('System.Bindings.Outputs'); end; { TMethodsProperty } type TPersistentCracker = class(TPersistent); procedure TBindArtifactsPropertyEditor.Edit; var LObj: TPersistent; LArtifacts: TBindArtifacts; begin LObj := GetComponent(0); while (LObj <> nil) and not (LObj is TComponent) do LObj := TPersistentCracker(LObj).GetOwner; LArtifacts := TBindArtifacts(GetOrdValue); Assert(LArtifacts is TBindArtifacts); ShowForm(TComponent(LObj), LArtifacts); end; function TBindArtifactsPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly, paVCL]; end; { TMethodsPropertyEditor } procedure TMethodsPropertyEditor.ShowForm(AComponent: TComponent; AArtifacts: TBindArtifacts); var LForm: TBindMethodsForm; begin LForm := TBindMethodsForm.Create(Application); with LForm do try LForm.DesignerIntf := Self.Designer; LForm.BindArtifacts := AArtifacts; if ShowModal = mrOk then begin LForm.ApplyChanges; Self.Designer.Modified; end; except Free; end; end; { TOutputConvertersProperty } procedure TOutputConvertersPropertyEditor.ShowForm(AComponent: TComponent; AArtifacts: TBindArtifacts); var LForm: TBindOutputConvertersForm; begin LForm := TBindOutputConvertersForm.Create(Application); with LForm do try LForm.DesignerIntf := Self.Designer; LForm.BindArtifacts := AArtifacts; if ShowModal = mrOK then begin ApplyChanges; Self.Designer.Modified; end; except Free; end; end; { TCustomBindCompListSelectionEditor } // This method must be fast or it will slow down code insite. procedure TCustomBindCompListSelectionEditor.RequiresUnits(Proc: TGetStrProc); var LActiveClassGroup: TPersistentClass; function IsActiveFramework(AFrameworkClass: TPersistentClass): Boolean; var LClassGroup: TPersistentClass; begin if AFrameworkClass = nil then Exit(True); LClassGroup := System.Classes.ClassGroupOf(AFrameworkClass); Result := LActiveClassGroup.InheritsFrom(LClassGroup); end; // Detect units with DB dependencies function IsDBUnit(const AUnitName: string): Boolean; const cDB = 'Data.Bind.DB'; begin Result := SameText(cDB, Copy(AUnitName, 1, Length(cDB))); end; function CanUseUnit(const AUnitName: string): Boolean; begin Result := (AUnitName <> '') and (not IsDBUnit(AUnitName)); end; var BindingsList: TCustomBindingsList; UseUnits, ExcludedList: TStringList; CurUnitName: string; MethodDesc: TMethodDescription; ConverterDesc: TConverterDescription; I, CompNum: Integer; LFrameworkClass: TPersistentClass; begin LActiveClassGroup := Designer.ActiveClassGroup; UseUnits := TStringList.Create; UseUnits.CaseSensitive := True; // Improve IndexOf performance ExcludedList := TStringList.Create; ExcludedList.CaseSensitive := True; try for CompNum := 0 to Designer.Root.ComponentCount - 1 do // Ignore components in frames begin if Designer.Root.Components[CompNum] is TCustomBindingsList then begin BindingsList := TCustomBindingsList(Designer.Root.Components[CompNum]); //check for method units ExcludedList.Clear; for I := 0 to BindingsList.Methods.Count - 1 do begin if BindingsList.Methods.Items[I].State = eaInclude then begin CurUnitName := TBindingMethodsFactory.GetMethodUnitName(BindingsList.Methods.Items[I].ID); if (CurUnitName <> '') and (UseUnits.IndexOf(CurUnitName) = -1) then begin LFrameworkClass := TBindingMethodsFactory.GetMethodFrameworkClass(BindingsList.Methods.Items[I].ID); if CanUseUnit(CurUnitName) and IsActiveFramework(LFrameworkClass) then UseUnits.Add(CurUnitName); end; end else ExcludedList.Add(BindingsList.Methods.Items[I].ID); end; //now add methods enabled by default unless explicitly excluded for MethodDesc in TBindingMethodsFactory.GetRegisteredMethods do if (MethodDesc.UnitName <> '') and (UseUnits.IndexOf(MethodDesc.UnitName) = -1) then if MethodDesc.DefaultEnabled and (ExcludedList.IndexOf(MethodDesc.ID) = -1) then if CanUseUnit(MethodDesc.UnitName) and IsActiveFramework(MethodDesc.FrameworkClass) then UseUnits.Add(MethodDesc.UnitName); //check for output converter units ExcludedList.Clear; for I := 0 to BindingsList.OutputConverters.Count - 1 do begin if BindingsList.OutputConverters.Items[I].State = eaInclude then begin CurUnitName := TValueRefConverterFactory.GetConverterUnitName(BindingsList.OutputConverters.Items[I].ID); if (CurUnitName <> '') and (UseUnits.IndexOf(CurUnitName) = -1) then begin LFrameworkClass := TValueRefConverterFactory.GetConverterFrameworkClass(BindingsList.OutputConverters.Items[I].ID); if CanUseUnit(CurUnitName) and IsActiveFramework(LFrameworkClass) then UseUnits.Add(CurUnitName); end; end else ExcludedList.Add(BindingsList.OutputConverters.Items[I].ID); end; //now add converters enabled by default unless explicitly excluded for ConverterDesc in TValueRefConverterFactory.GetConverterDescriptions do if (ConverterDesc.UnitName <> '') and (UseUnits.IndexOf(ConverterDesc.UnitName) = -1) then if ConverterDesc.DefaultEnabled and (ExcludedList.IndexOf(ConverterDesc.ID) = -1) then if CanUseUnit(ConverterDesc.UnitName) and IsActiveFramework(ConverterDesc.FrameworkClass) then UseUnits.Add(ConverterDesc.UnitName); end; end; for I := 0 to UseUnits.Count - 1 do Proc(UseUnits[I]); finally ExcludedList.Free; UseUnits.Free; end; end; function TBaseDataGeneratorSelectionEditor.GetDataGenerator(AComponent: TComponent): TCustomDataGeneratorAdapter; begin Result := nil; if AComponent is TCustomDataGeneratorAdapter then Result := TCustomDataGeneratorAdapter(AComponent) end; procedure TBaseDataGeneratorSelectionEditor.RequiresUnits(Proc: TGetStrProc); function DesignerSupportsExtension(const AExt: string): Boolean; const sDfm = 'DFM'; sFmx = 'FMX'; sVCL = 'VCL'; var LClassGroup: TPersistentClass; LUnitScope: string; begin Assert(AExt <> ''); LClassGroup := Designer.ActiveClassGroup; if LClassGroup <> nil then begin // Designer.DesignerExtension is .dfm for TDataModule so look at activeclassgroup LUnitScope := LClassGroup.UnitScope; if SameText(AExt, sDfm) then Result := LClassGroup.UnitScope.StartsWith(sVcl, True) else if SameText(AExt, sFmx) then Result := LClassGroup.UnitScope.StartsWith(sFmx, True) else Result := False; end else Result := SameText(AExt, Designer.DesignerExtention); end; var I: Integer; LDataGenerator: TCustomDataGeneratorAdapter; LComponent: TComponent; LFieldDef: TGeneratorFieldDef; LDescriptions: TArray<TPair<string, TValueGeneratorDescription>>; LPair: TPair<string, TValueGeneratorDescription>; begin for I := 0 to Designer.Root.ComponentCount - 1 do // Ignore components in frames begin LComponent := Designer.Root.Components[I]; LDataGenerator := GetDataGenerator(LComponent); if LDataGenerator <> nil then begin for LFieldDef in LDataGenerator.FieldDefs do begin if LFieldDef.Generator <> '' then begin LDescriptions := FindRegisteredValueGenerators(LFieldDef.Generator, LFieldDef.FieldType); for LPair in LDescriptions do begin if LPair.Value.UnitName <> '' then if (LPair.Key = '') or //(SameText(LPair.Key, Designer.DesignerExtention) and DesignerSupportsExtension(LPair.Key) then begin Proc(LPair.Value.UnitName); break; end; end; end; end; end; end; end; { TFieldNamePropertyEditor } function TFieldNamePropertyEditor.GetSourceComponentName: string; const sFillDataSource = 'FillDataSource'; sDataSource = 'DataSource'; begin if System.TypInfo.GetPropInfo(GetBindComponent.ClassInfo, 'FillDataSource') <> nil then Result := sFillDataSource else Result := sDataSource; end; { TNewBindCompWizardFactory } function TNewBindCompWizardFactory.Enabled( AContext: IBindCompFactoryContext): Boolean; begin //Result := True; Result := ShowLiveBindingsWizard; end; procedure TNewBindCompWizardFactory.Execute( AContext: IBindCompFactoryExecuteContext); var LDataBinding: TContainedBindComponent; begin with TExecuteNewDataBindingWizard.Create(AContext) do begin Execute( // BeforeCreate procedure begin //SelectNone(False) end, // Created procedure(ACategory: string; ADataBinding: TContainedBindComponent; ANewControl: TComponent) begin if ADatabinding <> nil then begin LDataBinding := ADataBinding; if LDataBinding.Name = '' then LDataBinding.Name := AContext.UniqueName(LDataBinding.ClassType.ClassName + AContext.ControlComponent.Name); LDataBinding.Category := ACategory; LDataBinding.BindingsList := AContext.BindingsList; //LDataBinding.ControlComponent := AContext.ControlComponent; AContext.BindCompCreated(LDataBinding); end; end, // After create procedure begin //FocusDataBinding(LDataBinding) end, // Allow class function(AClass: TContainedBindCompClass): Boolean begin Result := True; // LDesigner := GetBindCompDesigner(AClass); // if LDesigner <> nil then // // Allow class // Result := LDesigner.CanBindComponent(AClass, // AContext.ControlComponent, AContext.Designer) // else // Result := False; end); end; end; function TNewBindCompWizardFactory.GetCategory: string; begin Result := ''; end; function TNewBindCompWizardFactory.GetCommandText( AContext: IBindCompFactoryContext): string; begin Result := SNewBindingWizard; end; { TFactoryAction } constructor TFactoryAction.Create(const ACaption: string; ABindingsList: TCustomBindingsList; AFactory: IBindCompFactory); begin inherited Create(nil); Caption := ACaption; FBindingsList := ABindingsList; FFactory := AFactory; end; function TFactoryAction.Execute: Boolean; begin Assert(False); Result := True; end; { TVerbAction } constructor TVerbAction.Create(const ACaption: string; AComponent: TComponent; AVerb: integer; ADesigner: IDesigner); begin inherited Create(nil); Caption := ACaption; FDesigner := ADesigner; FComponent := AComponent; FVerb := AVerb; end; function TVerbAction.Execute: Boolean; var LEditor: IComponentEditor; begin LEditor := GetComponentEditor(FComponent, FDesigner); if LEditor <> nil then begin if FVerb < LEditor.GetVerbCount then begin LEditor.ExecuteVerb(FVerb); end; end; Result := True; end; { TBindCompFactorySelectionEditorExecuteContext } procedure TBindCompFactorySelectionEditorExecuteContext.BindCompCreated( AComponent: TComponent); begin FDesigner.Modified; (BorlandIDEServices as IOTAPropInspServices).VolatileModified; // (BorlandIDEServices as IOTAPropInspServices).Expand; // Select under Databindings FDesigner.SelectComponent(AComponent); end; procedure GetComponentPropertyNames(AComponent: TComponent; AList: TList<string>); var LPropertyNames: TDataBindingComponentPropertyNames; begin LPropertyNames := TDataBindingComponentPropertyNames.Create(AComponent); try AList.AddRange(LPropertyNames.PropertyNames); finally LPropertyNames.Free; end; end; function DefaultTrackControl(AControl: TComponent): Boolean; var LOptions: TObservableMemberOptions; begin Result := GetControlValuePropertyOptions(AControl, LOptions) and (TObservableMemberOption.moTrack in LOptions); end; function ShowLiveBindingsWizard: Boolean; begin Result := LiveBindingsGenOptFrame.IsOptionEnabled(TLBRegNames.EnableWizardVerb); end; { TPropertyNameProperty } function TComponentPropertyNamesProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TComponentPropertyNamesProperty.GetValueList: TArray<string>; var LComponent: TComponent; begin LComponent := GetPropertyComponent; if LComponent <> nil then Result := Self.GetComponentPropertyNames(LComponent) else Result := TArray<string>.Create(); end; procedure TComponentPropertyNamesProperty.GetValues(Proc: TGetStrProc); var S: string; Values: TArray<string>; begin Values := GetValueList; for s in Values do Proc(S); end; function TComponentPropertyNamesProperty.GetPropertyComponent: TComponent; begin Assert(False); Result := nil; end; class function TComponentPropertyNamesProperty.GetComponentPropertyNames(AComponent: TComponent): TArray<string>; var LList: TList<string>; begin LList := TList<string>.Create; try BindCompReg.GetComponentPropertyNames(AComponent, LList); Result := LList.ToArray; finally LList.Free; end; end; class function TComponentPropertyNamesProperty.HasComponentPropertyName(AComponent: TComponent; const AName: string): Boolean; var LList: TList<string>; begin LList := TList<string>.Create; try BindCompReg.GetComponentPropertyNames(AComponent, LList); Result := LList.IndexOf(AName) >= 0; finally LList.Free; end; end; { TLinkControlToPropertyNamesEditor } function TLinkControlToPropertyNamesEditor.GetPropertyComponent: TComponent; var LSelected: TCustomLinkControlToProperty; begin LSelected := GetComponent(0) as TCustomLinkControlToProperty; if Assigned(LSelected) then Result := LSelected.Component else Result := nil; end; { TLinkPropertyToFieldPropertyNamesEditor } function TLinkPropertyToFieldPropertyNamesEditor.GetPropertyComponent: TComponent; var LSelected: TCustomLinkPropertyToField; begin LSelected := GetComponent(0) as TCustomLinkPropertyToField; if Assigned(LSelected) then Result := LSelected.Component else Result := nil; end; { TVisualizationSyntheticProperty } constructor TVGSyntheticPropertyGroup.Create(const ADesigner: IDesigner; APropCount: Integer); begin inherited Create(ADesigner, APropCount); if ADesigner = nil then FRoot := nil else FRoot := ADesigner.Root; end; procedure TVGSyntheticPropertyGroup.Edit(const Host: IPropertyHost; DblClick: Boolean); begin end; function TVGSyntheticPropertyGroup.GetAttributes: TPropertyAttributes; begin // Not nestible so that it won't appear inside expanded component references Result := [paSubProperties, paVolatileSubProperties, paReadOnly, paNotNestable]; end; function TVGSyntheticPropertyGroup.GetComponents: TArray<TComponent>; begin Result := FComponents; end; function TVGSyntheticPropertyGroup.GetName: string; begin Result := sVisualizationGroup; end; procedure TVGSyntheticPropertyGroup.GetProperties(Proc: TGetPropProc); var LProperty: TVGSyntheticProperty; LComponent: TComponent; LModel: IVGModel; LNodesOnly: Boolean; LId: Integer; LElementIDS: TArray<Integer>; LShowVisibleProperty, LShowLayersProperty: Boolean; LFilterFunc: TLBComponentFilterFunc; begin LModel := GetDesignerModel(Designer); if LModel <> nil then begin // Node Visibility property (only valid for nodes, so only show if selected components contain nothing but nodes) LNodesOnly := True; LShowVisibleProperty := True; LShowLayersProperty := True; for LComponent in FComponents do begin if LComponent = FRoot then begin LShowVisibleProperty := False; LShowLayersProperty := False; end else for LFilterFunc in TLBVisualizationPropertyManager.GetComponentFiltersFuncArray do begin if (not LShowVisibleProperty) and (not LShowLayersProperty) then break; if LShowVisibleProperty then LShowVisibleProperty := LFilterFunc(LComponent, TVGVisibleSyntheticProperty.ClassName); if LShowLayersProperty then LShowLayersProperty := LFilterFunc(LComponent, TVGLayersNodeSyntheticProperty.ClassName); end; LElementIDS := LModel.FindElementIDs(LComponent); if Length(LElementIDS) > 0 then begin LNodesOnly := False; for LId in LElementIDS do if LModel.FindElement(LId).IsNode then begin // This component has a node LNodesOnly := True; break; end; end; if not LNodesOnly then break; end; if LNodesOnly then begin if LShowVisibleProperty then begin LProperty := TVGVisibleSyntheticProperty.Create(Designer, 1); LProperty.Group := Self; Proc(LProperty); end; if LShowLayersProperty then begin LProperty := TVGLayersNodeSyntheticProperty.Create(Designer, 1); LProperty.Group := Self; Proc(LProperty); end; end; end; end; function TVGSyntheticPropertyGroup.GetValue: string; begin Result := sVisualizationGroup end; procedure TVGSyntheticPropertyGroup.SetComponents(const Values: TArray<TComponent>); begin FComponents := Values; end; { TVisualizationVisibleSyntheticProperty } procedure TVGVisibleSyntheticProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var LOrigValue: string; begin if DblClick then begin LOrigValue := GetValue; if LOrigValue = '' then // mixed results - set all to enabled LOrigValue := BoolToStr(False, True); SetValue(BoolToStr(not StrToBool(LOrigValue), True)); end; end; function TVGVisibleSyntheticProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paMultiSelect, paNotNestable, paValueEditable]; end; function TVGVisibleSyntheticProperty.GetName: string; begin Result := sNodeVisibility; end; function TVGVisibleSyntheticProperty.GetValue: string; var LModel: IVGModel; LComponent: TComponent; LId: Integer; LFirst, LLast: Boolean; LList: TArray<Integer>; begin LFirst := True; LLast := False; LModel := GetDesignerModel(Designer); if LModel <> nil then begin for LComponent in Group.SelectedComponents do begin LList := LModel.FindElementIDs(LComponent); for LId in LList do begin if LFirst then begin LLast := LModel.IsElementVisible(LId); LFirst := False; end else if LLast <> LModel.IsElementVisible(LId) then Exit(''); end; end; end; Result := BoolToStr(LLast, True); end; procedure TVGVisibleSyntheticProperty.GetValues(Proc: TGetStrProc); begin Proc('True'); Proc('False'); Proc('Default'); // Do not localize end; procedure TVGVisibleSyntheticProperty.SetValue(const Value: string); var LValue: Boolean; LModel: IVGModel; LComponent: TComponent; LList: TArray<Integer>; LId: Integer; LDefault: Boolean; begin LDefault := SameText(Value, 'Default'); // Do not localize if LDefault or TryStrToBool(Value, LValue) then begin LModel := GetDesignerModel(Designer); if LModel <> nil then begin for LComponent in Group.SelectedComponents do begin LList := LModel.FindElementIds(LComponent); for LId in LList do begin if LDefault then LModel.RestoreDefaultVisibility(LId) else if LValue then LModel.ShowElement(LId, True) else LModel.HideElement(LId, True); end; end; end; end; end; { TGeneratorNamePropertyEditor } function TGeneratorNamePropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList]; end; function TGeneratorNamePropertyEditor.GetValueList: TArray<string>; var LFieldType: TGeneratorFieldType; LComponent: TPersistent; begin Result := nil; LComponent := GetComponent(0); if LComponent is TGeneratorFieldDef then begin LFieldType := TGeneratorFieldDef(LComponent).FieldType; Result := Data.Bind.ObjectScope.GetRegisteredValueGenerators(LFieldType); end; end; procedure TGeneratorNamePropertyEditor.GetValues(Proc: TGetStrProc); var Values: TArray<string>; S: string; begin Values := GetValueList; for S in Values do Proc(S); end; { TFormatExpressionSourceMemberEditor } function TFormatExpressionSourceMemberEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList]; end; function TFormatExpressionSourceMemberEditor.GetValueList: TArray<string>; var LFieldType: TGeneratorFieldType; LComponent: TPersistent; begin Result := nil; LComponent := GetComponent(0); if LComponent is TGeneratorFieldDef then begin LFieldType := TGeneratorFieldDef(LComponent).FieldType; Result := Data.Bind.ObjectScope.GetRegisteredValueGenerators(LFieldType); end; end; procedure TFormatExpressionSourceMemberEditor.GetValues(Proc: TGetStrProc); var Values: TArray<string>; S: string; begin Values := GetValueList; for S in Values do Proc(S); end; { TScopeAdapterFieldsEditor } function CreateBindScopeEditor(AOwner: TComponent; const ADesigner: IDesigner; AComponent: TComponent): IBindScopeEditor; var LBindScopeFactory: TBindScopeFactory; LFactories: TArray<TBindScopeFactory>; begin Result := nil; LFactories := BindCompEdit.CreateAdapterFactories(ADesigner); for LBindScopeFactory in LFactories do begin if AComponent.InheritsFrom(LBindScopeFactory.BindScopeClass) then begin if LBindScopeFactory.CanEdit then Result := LBindScopeFactory.CreateBindScopeEditor(AOwner, AComponent) else Result := nil; Exit; end; end; end; procedure TScopeAdapterFieldsEditor.ExecuteVerb(Index: Integer); var LEditor: IBindScopeEditor; LFields: TArray<TPersistentPair>; LField: TPersistentPair; LDesignerSelections: IDesignerSelections; begin case Index - inherited GetVerbCount of 0: if GetCollection <> nil then ShowCollectionEditorClass(Designer, TBindAdapterColumnsEditor, Component, GetCollection, GetPropertyName); 1: begin LEditor := CreateBindScopeEditor(nil, Designer, Component); if (LEditor <> nil) and (LEditor.CanAddFields) then begin if Length(LEditor.AddField) > 0 then begin LFields := LEditor.ApplyChanges; LDesignerSelections := CreateSelectionList; for LField in LFields do if LField.Value <> nil then LDesignerSelections.Add(LField.Value); if LDesignerSelections.Count > 0 then Designer.SetSelections(LDesignerSelections); end; end; end else inherited ExecuteVerb(Index); end; end; function TScopeAdapterFieldsEditor.GetCollection: TCollection; begin Result := nil; if Component is TBaseObjectBindSource then if TBaseObjectBindSource(Component).InternalAdapter is TCustomDataGeneratorAdapter then Result := TCustomDataGeneratorAdapter(TBaseObjectBindSource(Component).InternalAdapter).FieldDefs; if Component is TCustomDataGeneratorAdapter then Result := TCustomDataGeneratorAdapter(Component).FieldDefs; end; function TScopeAdapterFieldsEditor.GetPropertyName: string; begin Result := 'FieldDefs'; // Do not localize end; resourcestring sAdapterFieldsEditor = 'Fields Editor...'; sAddFields = 'Add Field...'; function TScopeAdapterFieldsEditor.GetVerb(Index: Integer): string; begin case Index - inherited GetVerbCount of 0: Result := sAdapterFieldsEditor; 1: Result := sAddFields; else Result := inherited GetVerb(Index); end end; function TScopeAdapterFieldsEditor.GetVerbCount: Integer; var LEditor: IBindScopeEditor; begin if GetCollection <> nil then begin Result := inherited GetVerbCount + 1; LEditor := CreateBindScopeEditor(nil, Designer, Component); if (LEditor <> nil) and (LEditor.CanAddFields) then Result := Result + 1; end else Result := inherited; end; procedure UpdateHotCommands(ADesigner: IDesigner; const APropertyName: string); var LList: IDesignerSelections; begin // Force update of hot commands LList := CreateSelectionList; ADesigner.GetSelections(LList); ADesigner.SetSelections(CreateSelectionList); ADesigner.SetSelections(LList); ADesigner.SelectItemName(APropertyName); end; { TUseGeneratorPropertyEditor } procedure TUseDataGeneratorPropertyEditor.SetValue(const Value: string); begin try inherited; except Application.HandleException(Self); end; // Force update of hot commands UpdateHotCommands(Designer, 'UseDataGenerator'); end; procedure TAdapterPropertyEditor.SetValue(const Value: string); begin try inherited; except Application.HandleException(Self); end; // Force update of hot commands UpdateHotCommands(Designer, 'Adapter'); end; { TVGLayersNodeSyntheticProperty } constructor TVGLayersNodeSyntheticProperty.Create(const ADesigner: IDesigner; APropCount: Integer); begin inherited; FNodeId := -1; end; procedure TVGLayersNodeSyntheticProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var LDrawing: IVGDrawing; LModel: IVGModel; LElement: IVGElement; I, LNodeId: Integer; LComponent: TComponent; LValue: string; begin LModel := GetDesignerModel(Designer); if LModel = nil then Exit; with TStringsEditDlg.Create(Application) do try CodeEditorItem.Visible := False; CodeWndBtn.Visible := False; LValue := GetValue; if LValue <> sMixedCollection then Lines.DelimitedText := LValue; repeat I := Lines.IndexOf(''); if I <> -1 then Lines.Delete(I); until I = -1; case ShowModal of mrOk, mrYes: begin LDrawing := VisualizationService.GetDrawingControl; if LDrawing <> nil then begin if FNodeId = -1 then for LComponent in Group.SelectedComponents do begin LNodeId := LModel.FindNodeId(LComponent); if LNodeId <> -1 then begin LModel.FindElement(LNodeId).SetLayerNames(Lines.ToStringArray); LModel.ElementChanged(LComponent); LModel.GetModule.Designer.Modified; //? end; end else begin LElement := LModel.FindElement(FNodeId); if LElement <> nil then begin LElement.SetLayerNames(Lines.ToStringArray); LModel.ElementChanged(LElement.Component); LModel.GetModule.Designer.Modified; //? end; end; LDrawing.RefreshLayers; end; end; end; finally Free; end; end; function TVGLayersNodeSyntheticProperty.GetAttributes: TPropertyAttributes; begin Result := [paReadOnly, paVCL, paDialog, paMultiSelect, paNotNestable, paValueEditable]; if FNodeId = -1 then Result := Result + [paSubProperties, paVolatileSubProperties]; end; function TVGLayersNodeSyntheticProperty.GetName: string; var LModel: IVGModel; LElement: IVGElement; begin Result := sNodeLayerNames; if FNodeId <> -1 then begin LModel := GetDesignerModel(Designer); if LModel = nil then Result := '' else begin LElement := LModel.FindElement(FNodeId); Assert(LElement <> nil); if LElement <> nil then Result := Format('%s', [LElement.Name]) else Result := ''; end; end; end; procedure TVGLayersNodeSyntheticProperty.GetProperties(Proc: TGetPropProc); var LModel: IVGModel; LNodeId: Integer; LProperty: IProperty; LComponent: TComponent; begin assert(FNodeId = -1); LModel := GetDesignerModel(Designer); if (LModel <> nil) then begin for LComponent in Group.SelectedComponents do begin LNodeId := LModel.FindNodeId(LComponent); Assert(LNodeId <> -1); if LNodeId = -1 then continue; LProperty := TVGLayersNodeSyntheticProperty.Create(Designer, 1); TVGLayersNodeSyntheticProperty(LProperty).Group := Group; TVGLayersNodeSyntheticProperty(LProperty).SetId(LNodeId); Proc(LProperty); end; end; end; function TVGLayersNodeSyntheticProperty.GetValue: string; var LModel: IVGModel; LNodeId: Integer; LStr: string; LElement: IVGElement; begin Result := ''; LModel := GetDesignerModel(Designer); if LModel <> nil then begin if (FNodeId <> -1) or (Length(Group.SelectedComponents) = 1) then begin if FNodeId = -1 then LNodeId := LModel.FindNodeId(Group.SelectedComponents[0]) else LNodeId := FNodeId; if LNodeId = -1 then Exit; LElement := LModel.FindElement(LNodeId); if LElement = nil then Exit; for LStr in LElement.LayerNames do begin if Result = '' then Result := LStr else Result := Format('%s;%s', [LStr, Result]); end; end else Result := sMixedCollection; end; end; procedure TVGLayersNodeSyntheticProperty.SetId(AId: Integer); begin FNodeId := AId; end; { TLookupFieldNamePropertyEditor } function TLookupFieldNamePropertyEditor.GetSourceComponentName: string; begin Result := 'LookupDataSource'; // Do not localize end; { TLookupKeyFieldNamePropertyEditor } procedure TLookupKeyFieldNamePropertyEditor.GetMemberNames( ASourceComponent: TComponent; List: TStrings); var LScopeLookup: IScopeLookup; begin if Supports(ASourceComponent, IScopeLookup, LScopeLookup) then LScopeLookup.GetLookupMemberNames(List); end; { TBaseLinkingBindScopeEditor } procedure TBaseLinkingBindScopeEditor.Edit; begin if CanCreateNavigator(Designer) and (not DataSourceHasNavigator(Designer, Component)) then // Create navigator is not default command ExecuteVerb(1) else inherited; end; procedure TBaseLinkingBindScopeEditor.ExecuteVerb(Index: Integer); begin case Index - inherited GetVerbCount of 0: if CanCreateNavigator(Designer) and (not DataSourceHasNavigator(Designer, Component)) then // Redundant check in case object inspector shows a disable verb CreateNavigator(Designer, Component as TBaseLinkingBindSource); else inherited; end; end; function TBaseLinkingBindScopeEditor.GetVerb(Index: Integer): string; begin case Index - inherited GetVerbCount of 0: Result := SAddNavigator; else Result := inherited; end; end; function TBaseLinkingBindScopeEditor.GetVerbCount: Integer; begin if (Component is TBaseLinkingBindSource) and CanCreateNavigator(Designer) and (not DataSourceHasNavigator(Designer, Component)) then Result := inherited + 1 else Result := inherited; end; { TAddBindScopeSelectionEditor } procedure TAddBindScopeSelectionEditor.ExecuteVerb(Index: Integer; const List: IDesignerSelections); var LComponent: TComponent; begin case Index of 0: begin if (List.Count > 0) and (List[0] is TComponent) and CanHaveBindScope(TComponent(List[0])) then LComponent := TComponent(List[0]) else LComponent := nil; if LComponent <> nil then CreateBindScope(LComponent); end else inherited; end; end; procedure TAddBindScopeSelectionEditor.CreateBindScope(AComponent: TComponent); procedure SetUniqueName(const ADesigner: IDesigner; AScopeComponent: TComponent); var LSuffix: string; LName: string; begin LName := AComponent.Name; if StartsStr(AComponent.ClassName.Substring(1), LName) then LSuffix := LName.SubString(AComponent.ClassName.Length-1); if LSuffix.Length > 0 then begin AScopeComponent.Name := BindCompReg.CreateUniqueComponentName(ADesigner.Root, AScopeComponent.ClassName.Substring(1), LSuffix); end; end; var LScopeComponent: TBaseLinkingBindSource; LDesigner: IDesigner; begin if AComponent is TBindSourceAdapter then begin LDesigner := Designer; // Selection editor gets destroyed when create a component LScopeComponent := Designer.CreateComponent(TAdapterBindSource, Designer.Root, 0, 0, 0, 0) as TBaseLinkingBindSource; SetUniqueName(LDesigner, LScopeComponent); TAdapterBindSource(LScopeComponent).Adapter := TBindSourceAdapter(AComponent); LDesigner.Modified; end else if TDBScope.IsDataComponent(AComponent) then begin LDesigner := Designer; // Selection editor gets destroyed when create a component LScopeComponent := Designer.CreateComponent(TDBScope, Designer.Root, 0, 0, 0, 0) as TBaseLinkingBindSource; SetUniqueName(LDesigner, LScopeComponent); TDBScope(LScopeComponent).DataComponent := AComponent; LDesigner.Modified; end else Assert(False); end; function TAddBindScopeSelectionEditor.CanHaveBindScope(AComponent: TComponent): Boolean; var LResult: Boolean; begin Result := False; if AComponent is TBindSourceAdapter then begin LResult := True; GetOwnedComponents(Designer.Root, procedure(AOwnedComponent: TComponent) begin if AOwnedComponent is TBaseObjectBindSource then if TBaseObjectBindSource(AOwnedComponent).InternalAdapter = AComponent then LResult := False; end); Result := LResult; end else if TDBScope.IsDataComponent(AComponent) then begin LResult := True; GetOwnedComponents(Designer.Root, procedure(AOwnedComponent: TComponent) begin if AOwnedComponent is TCustomBindSourceDB then if (TCustomBindSourceDB(AOwnedComponent).DataComponent = AComponent) then LResult := False; end); Result := LResult; end; end; function TAddBindScopeSelectionEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := SAddBindScope; else Result := inherited; end; end; function TAddBindScopeSelectionEditor.GetVerbCount: Integer; var LComponent: TComponent; List: IDesignerSelections; begin Result := 0; List := CreateSelectionList; Designer.GetSelections(List); if (List.Count > 0) and (List[0] is TComponent) and CanHaveBindScope(TComponent(List[0])) then LComponent := TComponent(List[0]) else LComponent := nil; if LComponent <> nil then Result := 1 end; { TLinkingBindScopePropertyEditor } procedure TLinkingBindScopePropertyEditor.GetValues(Proc: TGetStrProc); var LDataSources: TList<TComponent>; LComponent: TComponent; LAllComponents: TArray<TComponent>; begin inherited; LDataSources := TList<TComponent>.Create; try LAllComponents := GetOwnedAndLinkedComponentsList(Designer); for LComponent in LAllComponents do begin if TDBScope.IsDataComponent(LComponent) or (LComponent is TBindSourceAdapter) then LDataSources.Add(LComponent); end; for LComponent in LAllComponents do begin if LComponent is TBaseObjectBindSource then LDataSources.Remove(TBaseObjectBindSource(LComponent).InternalAdapter) else if LComponent is TCustomBindSourceDB then LDataSources.Remove(TCustomBindSourceDB(LComponent).DataComponent); end; for LComponent in LDataSources do Proc(LComponent.Name); finally LDataSources.Free; end; end; procedure TLinkingBindScopePropertyEditor.SetValue(const Value: string); var Component: TComponent; LScopeComponent: TComponent; begin if Value = '' then Component := nil else Component := Designer.GetComponent(Value); if Component = nil then inherited SetValue('') else if Component is TBaseLinkingBindSource then inherited SetValue(Value) else if TDBScope.IsDataComponent(Component) then begin LScopeComponent := Designer.CreateComponent(TDBScope, Designer.Root, 0, 0, 0, 0) as TBaseLinkingBindSource; TDBScope(LScopeComponent).DataComponent := Component; inherited SetValue(LScopeComponent.Name); end else if Component is TBindSourceAdapter then begin LScopeComponent := Designer.CreateComponent(TAdapterBindSource, Designer.Root, 0, 0, 0, 0) as TBaseLinkingBindSource; TAdapterBindSource(LScopeComponent).Adapter := TBindSourceAdapter(Component); inherited SetValue(LScopeComponent.Name); end else Assert(False); end; { TBindVisuallyViewFactory } function TBindVisuallyViewFactory.Enabled( AContext: IBindCompFactoryContext): Boolean; begin Result := VisualizationService <> nil; end; procedure TBindVisuallyViewFactory.Execute( AContext: IBindCompFactoryExecuteContext); var LDrawing: IVGDrawing; LModel: IVGModel; LNodeId: Integer; begin if VisualizationService <> nil then begin VisualizationService.FocusDrawing; LDrawing := VisualizationService.GetDrawingControl; LModel := VisualizationService.ActiveModel; if LModel <> nil then begin LNodeId := LModel.FindNodeId(AContext.ControlComponent); if LNodeId <> -1 then begin try LModel.ShowElement(LNodeId, True); LModel.InitNewLink(LNodeId, True); if LDrawing <> nil then LDrawing.ScrollToElement(LNodeId); finally if LDrawing <> nil then LDrawing.RecolorModel(nil); end; end; end; end; end; function TBindVisuallyViewFactory.GetCommandText( AContext: IBindCompFactoryContext): string; begin Result := SBindVisuallyCommand; end; { TPrototypeBindSourceDataGeneratorSelectionEditor } function TPrototypeBindSourceDataGeneratorSelectionEditor.GetDataGenerator( AComponent: TComponent): TCustomDataGeneratorAdapter; begin Result := inherited; if Result = nil then if AComponent is TCustomPrototypeBindSource then Result := TCustomPrototypeBindSource(AComponent).DataGenerator end; { TLinkingControlPropertyEditor } procedure TLinkingControlPropertyEditor.GetValues(Proc: TGetStrProc); begin FProc := Proc; try Designer.GetComponentNames(GetTypeData(GetPropType), InternalStrProc); finally FProc := nil; end; end; function TLinkingControlPropertyEditor.IsValidControl(AComponent: TComponent): Boolean; var LPropertyName: string; LWritable: Boolean; begin Result := Data.Bind.Components.GetControlValuePropertyName(AComponent, LPropertyName, LWritable) and LWritable; end; procedure TLinkingControlPropertyEditor.SetValue(const Value: string); var LComponent: TComponent; begin if Value <> '' then begin LComponent := Designer.GetComponent(Value); if LComponent <> nil then if not IsValidControl(LComponent) then raise EDesignPropertyError.CreateRes(@SInvalidPropertyValue); end; inherited SetValue(Value); end; procedure TLinkingControlPropertyEditor.InternalStrProc(const S: string); var LComponent: TComponent; begin LComponent := Designer.GetComponent(S); if LComponent <> nil then if IsValidControl(LComponent) then FProc(S); end; { TLBVisualizationPropertyManager } constructor TLBVisualizationPropertyManager.Create; begin inherited Create; FProcs := TList<TLBComponentFilterFunc>.Create; end; destructor TLBVisualizationPropertyManager.Destroy; begin FProcs.Free; inherited; end; class function TLBVisualizationPropertyManager.GetComponentFiltersFuncArray: TArray<TLBComponentFilterFunc>; begin Result := Instance.FProcs.ToArray; end; class function TLBVisualizationPropertyManager.Instance: TLBVisualizationPropertyManager; begin if FInstance = nil then FInstance := TLBVisualizationPropertyManager.Create; Result := FInstance; end; class procedure TLBVisualizationPropertyManager.AddComponentFilter( AFilterFunc: TLBComponentFilterFunc); begin if not Instance.FProcs.Contains(AFilterFunc) then Instance.FProcs.Add(AFilterFunc); end; class procedure TLBVisualizationPropertyManager.RemoveComponentFilter( AFilterFunc: TLBComponentFilterFunc); begin if Instance.FProcs.Contains(AFilterFunc) then Instance.FProcs.Remove(AFilterFunc); end; { TLinkFillCustomFormatPropertyEditor } procedure TFillCustomFormatPropertyEditor.GetValues(Proc: TGetStrProc); begin Proc('LowerCase(%s)'); Proc('SubString(%s, 0, 1)'); Proc('UpperCase(%s)'); end; function TFillCustomFormatPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueEditable, paValueList, paSortList]; end; { TLinkingFillControlPropertyEditor } function TLinkingFillControlPropertyEditor.IsValidControl( AComponent: TComponent): Boolean; begin Result := inherited IsValidControl(AComponent) and (GetBindEditor(AComponent, IBindListEditorCommon, '') <> nil) end; { TLinkFillControlToFieldFieldNamePropertyEditor } function TLinkFillControlToFieldFieldNamePropertyEditor.GetSourceComponentName: string; const sDataSource = 'DataSource'; begin Result := sDataSource; end; initialization System.Bindings.ObjEval.IsProxyClassProc := Proxies.IsProxyClass; finalization System.Bindings.ObjEval.IsProxyClassProc := nil; TLBVisualizationPropertyManager.FInstance.Free; TLBVisualizationPropertyManager.FInstance := nil; end.
{=============================== Program Header ================================ PROGRAM-NAME : 구성원평가결과 FeedBack - PEA1073A1 SYSTEM-NAME : 평가 SUBSYSTEM-NAME : 평가결과 조회 Programmer : Version : ver 1.0 Date : 2013.11.20 Update Contents 버전 수정일 수정자 수정내용 관련근거 1.00 2013.11.20 이희용 신규개발 HR팀 요청 ================================================================================} unit PEA1073A1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl, OnTmaxPersonEdit, OnShapeLabel, ComCtrls, OnRadioBtn, OnEditMemo, StdCtrls, OnLineLabel, OnFocusButton, Db, Tmax_DataSetText, Tmax_session, printers, OnPopupEdit, TmaxFunc, Pass, OnInsaCommon, OnSkinBtn, OnScheme; type TFM_Main = class(TForm) TMaxDataSet: TTMaxDataSet; L_Deptname: TOnShapeLabel; L_payraname: TOnShapeLabel; OnSectionLabel3: TOnSectionLabel; OnSectionLabel1: TOnSectionLabel; L_korname: TOnShapeLabel; SB_1: TOnSkinButton; SB_2: TOnSkinButton; SB_3: TOnSkinButton; P_OpinionO: TPanel; E_Opinion2: TOnMemo; E_Opinion4: TOnMemo; E_Opinion3: TOnMemo; E_Opinion1: TOnMemo; OnMemo4: TOnMemo; OnMemo7: TOnMemo; BT_Exit: TOnFocusButton; BT_ScrPrint: TOnFocusButton; E_Empno: TOnWinPopupEdit; E_LoginEmp: TOnEdit; Panel3: TPanel; L_NowBand: TOnShapeLabel; L_NextBand: TOnShapeLabel; FINALGRADE: TOnShapeLabel; VN_PAYRA: TOnShapeLabel; VN_DEPTNAME: TOnShapeLabel; RESULTSCRGRADE: TOnShapeLabel; Memo_E2: TOnMemo; Panel6: TPanel; lable12: TLabel; lable23: TLabel; Memo_E1: TOnMemo; Panel4: TPanel; lable22: TLabel; lable11: TLabel; P_OpinionN: TPanel; MERIT_JVN: TOnMemo; MERIT_JCN: TOnMemo; MERIT_JRN: TOnMemo; MERIT_JAN: TOnMemo; Memo_E0: TOnMemo; MERIT_JAY: TOnMemo; MERIT_JRY: TOnMemo; MERIT_JCY: TOnMemo; MERIT_JVY: TOnMemo; OnMemo6: TOnMemo; OnMemo5: TOnMemo; OnMemo2: TOnMemo; SF_Main: TOnSchemeForm; TMaxSession: TTMaxSession; procedure BT_ExitClick(Sender: TObject); procedure BT_ScrPrintClick(Sender: TObject); procedure E_EmpnoInitPopup(Sender: TObject); procedure FormShow(Sender: TObject); procedure OpinionViewO(v_Year : String); //Old procedure OpinionViewN(v_Year : String); //New procedure OpinionViewF(v_Year : String); //공통 procedure FormCHG(v_Year : String); //2013년 기준으로 화면 분류 procedure E_EmpnoCloseUp(Sender: TObject; var Text: String; var Accept: Boolean); procedure E_LoginEmpKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure SB_1Click(Sender: TObject); procedure E_EmpnoKeyPress(Sender: TObject; var Key: Char); private { Private declarations } vParamSQL : String; procedure EmpnoFind(vEmp : String); public { Public declarations } vRabasdate : String; Workemp1 : String; Workemp2 : String; Workemp3 : String; Workemp4 : String; Workemp5 : String; v_YEAR1 : String; v_YEAR2 : String; v_YEAR3 : String; v_empno : String; end; var FM_Main: TFM_Main; implementation uses UEmpForm; {$R *.DFM} procedure TFM_Main.FormCreate(Sender: TObject); begin Application.ProcessMessages; // SB_Help.Panels[1].Text := '종합인사 시스템에 접속 중입니다...'; TMaxSession.EnvFileName := FM_Tmax.GetHomeDir+'\newhana.env'; TMaxSession.LabelName := 'HANAROHPER'; TMaxSession.Connect := False; TMaxSession.Host := Passemp(cmdline,10); TMaxSession.Port := '9999'; try TMaxSession.Connect := True; except Application.MessageBox(PChar('APP서버 접속 실패'),'에러',mb_ok); Application.Terminate; Exit; end; //2013.11. Add FM_Tmax := TFM_Tmax.Create(Self); FM_Tmax.T_Session := TMaxSession; if FM_Tmax.PassWordChk(Hinsa_Param(cmdline,1), Hinsa_Param(cmdline,3)) = 0 then Application.Terminate; E_empno.Text := Passemp(cmdline,1); // SB_Help.Panels[1].Text := ' '; E_LoginEmp.Visible := False; BT_ScrPrint.Visible := False; end; procedure TFM_Main.FormShow(Sender: TObject); var vSysdate, vPAYRAYN : String; begin with TMaxDataSet do begin //평가기준일 불러오기 vParamSQL := 'SELECT Value1, TO_CHAR(SYSDATE,''YYYYMMDDHH24MI''), ''3'', ''4'', ''5'' '+ ' FROM pehrebas '+ ' WHERE rabasdate = ''00000000'' '+ ' AND gubun = ''00'' '+ ' AND sgubun = ''0001'' '; ServiceName := 'HINSA_select'; ClearFieldInfo; AddField('Field1' , ftString, 100); AddField('Field2' , ftString, 100); AddField('Field3' , ftString, 100); AddField('Field4' , ftString, 100); AddField('Field5' , ftString, 100); Close; SQl.Clear; SQL.Text := vParamSQL; Open; vRabasdate := Fields[0].AsString; // 현평가기준일 //평가결과완료 및 평가연도(3년) vParamSQL := 'SELECT Value1, Value2, Value3, Value4, Value5 '+ ' FROM pehrebas '+ ' WHERE rabasdate = '''+ vRabasdate +''' '+ ' AND gubun = ''11'' '+ ' AND sgubun = ''0008'' '; ServiceName := 'HINSA_select'; ClearFieldInfo; AddField('Field1' , ftString, 100); AddField('Field2' , ftString, 100); AddField('Field3' , ftString, 100); AddField('Field4' , ftString, 100); AddField('Field5' , ftString, 100); Close; SQl.Clear; SQL.Text := vParamSQL; Open; (* If (Fields[0].AsString = 'N') Then Begin ShowMessage('평가결과 준비중입니다.'+#13#13+'프로그램을 종료합니다'); Application.Terminate; Exit; End; *) v_YEAR1 := Fields[1].AsString; v_YEAR2 := Fields[2].AsString; v_YEAR3 := Fields[3].AsString; SB_1.Caption := v_YEAR1 + '평가'; SB_2.Caption := v_YEAR2 + '평가'; SB_3.Caption := v_YEAR3 + '평가'; //팀장 여부 확인 vParamSQL := 'SELECT NVL(jobpayrayn, ''N'') PAYRAYN, ' + ' '''' F2, '''' F3, '''' F4, '''' F5 ' + ' FROM PIMPMAS '+ ' WHERE EMPNO = '''+ Passemp(cmdline,1) +''' ' + ' and pstate < ''80'' '; ServiceName := 'HINSA_select'; ClearFieldInfo; AddField('PAYRAYN' , ftString, 100); AddField('F2' , ftString, 100); AddField('F3' , ftString, 100); AddField('F4' , ftString, 100); AddField('F5' , ftString, 100); Close; SQl.Clear; SQL.Text := vParamSQL; Open; vPAYRAYN := Fields[0].AsString; If vPAYRAYN = 'Y' Then Begin E_empno.Enabled := True; E_Empno.ReadOnly := False; E_empno.Perform(WM_KEYDOWN, VK_F2, 0); End Else Begin E_empno.Enabled := False; E_Empno.ReadOnly := True; End; //평가담당자 vParamSQL := 'SELECT Value1, Value2, Value3, Value4, '+ ' TO_CHAR(SYSDATE,''YYYYMMDDHH24MI'') '+ ' FROM pehrebas '+ ' WHERE rabasdate = '''+ vRabasdate +''' '+ ' AND gubun = ''11'' '+ ' AND sgubun = ''0005'' '; ServiceName := 'HINSA_select'; ClearFieldInfo; AddField('Field1' , ftString, 100); AddField('Field2' , ftString, 100); AddField('Field3' , ftString, 100); AddField('Field4' , ftString, 100); AddField('Field5' , ftString, 100); Close; SQl.Clear; SQL.Text := vParamSQL; Open; Workemp1 := Fields[0].AsString; Workemp2 := Fields[1].AsString; Workemp3 := Fields[2].AsString; Workemp4 := Fields[3].AsString; vSysdate := Fields[4].AsString; // 현 시간. if (Passemp(cmdline,1) = Workemp1) or (Passemp(cmdline,1) = Workemp2) or //관리자 (Passemp(cmdline,1) = Workemp3) or (Passemp(cmdline,1) = Workemp4) or (Copy(Passemp(cmdline,1),1,1) = 'D') then begin E_Empno.Enabled := True; E_Empno.ReadOnly := False; E_LoginEmp.Visible := True; BT_ScrPrint.Visible := True; v_empno := Passemp(cmdline,1); end Else Begin //2014.12.29 김현순M 요청으로 31일까지는 팀장만 조회 //2015년 부터 구성원 조회 가능 하도록 임시 사용 (* If (vPAYRAYN = 'N') Then Begin ShowMessage('평가결과 준비중입니다.'+#13#13+'프로그램을 종료합니다'); Application.Terminate; Exit; End; *) v_empno := (Passemp(cmdline,1)); End; EmpnoFind(v_empno); FormCHG(v_YEAR1); SB_1.BtnDown := True; SB_2.BtnDown := False; SB_3.BtnDown := False; end; end; procedure TFM_Main.FormCHG(v_Year : String); Begin If (v_Year >= '2013') Then //2013년이후 평가 장단점 입력. Begin P_OpinionN.Visible := True; P_OpinionO.Visible := False; OpinionViewN(Copy(v_Year,1,4)+'1130'); End Else Begin P_OpinionO.Visible := True; P_OpinionN.Visible := False; OpinionViewO(Copy(v_Year,1,4)+'1130'); End; OpinionViewF(v_Year+'1130'); End; procedure TFM_Main.OpinionViewO(v_Year : String); begin //평가의견 Read... 2012년 이전 with TMaxDataSet do begin vParamSQL := 'SELECT Opinion1, Opinion2, Opinion3, Opinion4, ''5'' '+ ' FROM PEHREMAS '+ ' WHERE rabasdate = '''+ v_Year +''' '+ ' AND empno = '''+ E_empno.Text +''' '; ServiceName := 'HINSA_select3'; ClearFieldInfo; AddField('Field1' , ftString, 2000); AddField('Field2' , ftString, 2000); AddField('Field3' , ftString, 2000); AddField('Field4' , ftString, 2000); AddField('Field5' , ftString, 2000); Close; SQl.Clear; SQL.Text := vParamSQL; Open; E_Opinion1.Text := Fields[0].AsString; E_Opinion2.Text := Fields[1].AsString; E_Opinion3.Text := Fields[2].AsString; E_Opinion4.Text := Fields[3].AsString; end; end; procedure TFM_Main.OpinionViewN(v_Year : String); begin //평가의견 Read...2013년 이후 with TMaxDataSet do begin ServiceName := 'HINSA_select12'; vParamSQL := ' SELECT MERIT_JVY, MERIT_JVN, MERIT_JCY, MERIT_JCN, '+ ' MERIT_JRY, MERIT_JRN, MERIT_JAY, MERIT_JAN, E1PERVIEW, ''F10'' '+ ' FROM PEHREMER A '+ ' where rabasdate = ''' + v_Year +''' ' + ' AND empno = ''' + E_empno.Text +''' ' ; ClearFieldInfo; AddField('MERIT_JVY' ,ftString, 2000); AddField('MERIT_JVN' ,ftString, 2000); AddField('MERIT_JCY' ,ftString, 2000); AddField('MERIT_JCN' ,ftString, 2000); AddField('MERIT_JRY' ,ftString, 2000); AddField('MERIT_JRN' ,ftString, 2000); AddField('MERIT_JAY' ,ftString, 2000); AddField('MERIT_JAN' ,ftString, 2000); AddField('E1PERVIEW' ,ftString, 2000); AddField('F10' ,ftString, 2000); Close; SQl.Clear; SQL.Text := vParamSQL; Open; MERIT_JVY.Text := Fields[0].AsString; MERIT_JVN.Text := Fields[1].AsString; MERIT_JCY.Text := Fields[2].AsString; MERIT_JCN.Text := Fields[3].AsString; MERIT_JRY.Text := Fields[4].AsString; MERIT_JRN.Text := Fields[5].AsString; MERIT_JAY.Text := Fields[6].AsString; MERIT_JAN.Text := Fields[7].AsString; Memo_E0.Text := Fields[8].AsString; //업적의견 end; end; procedure TFM_Main.OpinionViewF(v_Year : String); begin with TMaxDataSet do begin //종합의견/팀장이면 PETREMAS에서 가져옴(2014.12.01) vParamSQL := 'SELECT E1VALVIEW, E2VALVIEW, '+ ' '''' Field3, '''' Field4, '''' Field5 '+ ' FROM PETREMAS '+ ' WHERE rabasdate = '''+ v_Year +''' '+ ' AND empno = '''+ E_empno.Text +''' '; Close; ServiceName := 'HINSA_select3'; ClearFieldInfo; AddField('E1VALVIEW', ftString, 2000); AddField('E2VALVIEW', ftString, 2000); AddField('Field1' , ftString, 2000); AddField('Field2' , ftString, 2000); AddField('Field3' , ftString, 2000); Close; ClearParamInfo; SQL.Text := vParamSQL; Open; if RecordCount = 0 then begin vParamSQL := 'SELECT E1VALVIEW, E2VALVIEW, '+ ' '''' Field3, '''' Field4, '''' Field5 '+ ' FROM PEHREMAS '+ ' WHERE rabasdate = '''+ v_Year +''' '+ ' AND empno = '''+ E_empno.Text +''' '; Close; ServiceName := 'HINSA_select3'; ClearFieldInfo; AddField('E1VALVIEW', ftString, 2000); AddField('E2VALVIEW', ftString, 2000); AddField('Field1' , ftString, 2000); AddField('Field2' , ftString, 2000); AddField('Field3' , ftString, 2000); Close; ClearParamInfo; SQL.Text := vParamSQL; Open; End; Memo_E1.text := FieldByName('E1VALVIEW').AsString; Memo_E2.text := FieldByName('E2VALVIEW').AsString; (* 등급 *) vParamSQL := 'SELECT Substr(RESULTSCRGRADE,1,1), Substr(FINALGRADE,1,1), '+ //G+ G-를 G등급으로 통일. ' (Select codename from pyccode '+ ' where codeid = ''I112'' and codeno = a.paycl) NOWBAND, '+ ' (Select codename from pyccode '+ ' where codeid = ''I112'' and codeno = a.npaycl) NEXTBAND, '+ ' To_Char(To_Number(rabasyear)+1) NEXTYEAR, '+ ' (select codename from pyccode where codeid = ''I113'' and codeno=A.payra) PAYRA , '+ ' (select deptname from pycdept where orgnum = A.orgnum and deptcode=A.deptcode) DEPTNAME, '+ ' '''' F8, '''' F9, '''' F10 '+ ' FROM pehevhis a '+ ' WHERE rabasyear = '''+ copy(v_Year,1,4) +''''+ ' AND empno = '''+ E_empno.Text +''''; ServiceName := 'HINSA_select10'; ClearFieldInfo; AddField('RESULTSCRGRADE' , ftString, 100); AddField('FINALGRADE' , ftString, 100); AddField('NOWBAND' , ftString, 100); AddField('NEXTBAND' , ftString, 100); AddField('NEXTYEAR' , ftString, 100); AddField('PAYRA' , ftString, 100); AddField('DEPTNAME' , ftString, 100); AddField('F8' , ftString, 100); AddField('F9' , ftString, 100); AddField('F10' , ftString, 100); Close; ClearParamInfo; SQL.Text := vParamSQL; Open; RESULTSCRGRADE.ValueCaption := FieldByName('RESULTSCRGRADE').AsString; FINALGRADE.ValueCaption := FieldByName('FINALGRADE').AsString; if FieldByName('FINALGRADE').AsString = 'Y' then RESULTSCRGRADE.ValueCaption := '평가제외자'; if FieldByName('FINALGRADE').AsString = 'Y' then FINALGRADE.ValueCaption := '평가제외자'; if FieldByName('FINALGRADE').AsString = 'Z' then RESULTSCRGRADE.ValueCaption := '평가보류자'; if FieldByName('FINALGRADE').AsString = 'Z' then FINALGRADE.ValueCaption := '평가보류자'; L_NowBand.ValueCaption := FieldByName('NOWBAND').AsString; L_NowBand.LabelCaption := copy(v_Year,1,4) +'년 BAND'; L_NextBand.LabelCaption := FieldByName('NEXTYEAR').AsString+'년 BAND'; VN_DEPTNAME.LabelCaption := copy(v_Year,1,4) +'년 부서'; VN_PAYRA.LabelCaption := copy(v_Year,1,4) +'년 직책'; VN_DEPTNAME.ValueCaption := FieldByName('DEPTNAME').AsString; VN_PAYRA.ValueCaption := FieldByName('PAYRA').AsString; if FieldByName('NEXTBAND').AsString = '' then L_NextBand.ValueCaption := FieldByName('NOWBAND').AsString else L_NextBand.ValueCaption := FieldByName('NEXTBAND').AsString; end; end; procedure TFM_Main.E_EmpnoInitPopup(Sender: TObject); begin Fm_EmpForm.Edit := TOnWinPopupEdit(Sender); Fm_EmpForm.empno := E_empno.Text; Fm_EmpForm.SqlOpen; TOnWinPopupEdit(Sender).PopupControl := Fm_EmpForm ; end; procedure TFM_Main.SB_1Click(Sender: TObject); var vYYear : String; begin SB_1.BtnDown := False; SB_2.BtnDown := False; SB_3.BtnDown := False; TOnSkinButton(Sender).BtnDown := True; vYYear := (Sender as TOnSkinButton).Caption; FormCHG(Copy(vYYear,1,4)); end; procedure TFM_Main.E_EmpnoKeyPress(Sender: TObject; var Key: Char); begin if (Length(E_Empno.Text) >= 4) and (key = #13) then begin EmpnoFind(E_Empno.Text); FormCHG(Copy(SB_1.Caption,1,4)); SB_1.BtnDown := True; SB_2.BtnDown := False; SB_3.BtnDown := False; end; end; procedure TFM_Main.E_EmpnoCloseUp(Sender: TObject; var Text: String; var Accept: Boolean); begin if E_Empno.Text <> '' then begin FormCHG(Copy(SB_1.Caption,1,4)); end; end; procedure TFM_Main.E_LoginEmpKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin v_Empno := ''; v_Empno := E_LoginEmp.Text; E_Empno.Enabled := True; E_Empno.ReadOnly := False; E_empno.Perform(WM_KEYDOWN, VK_F2, 0); end; end; procedure TFM_Main.EmpnoFind(vEmp : String); begin with TMaxDataSet do begin vParamSQL := 'SELECT empno, korname, '+ ' (select codename from pyccode where codeid=''I112'' and codeno=A.paycl) , '+ ' (select codename from pyccode where codeid=''I113'' and codeno=A.payra) , '+ ' (select deptname from pycdept where orgnum=A.orgnum and deptcode=A.deptcode) '+ ' FROM Pimpmas A '+ ' WHERE (empno like '''+ vEmp +'''||''%'' OR korname like '''+ vEmp +'''||''%'') '; ServiceName := 'HINSA_select'; ClearFieldInfo; AddField('Field1' , ftString, 100); AddField('Field2' , ftString, 100); AddField('Field3' , ftString, 100); AddField('Field4' , ftString, 100); AddField('Field5' , ftString, 100); Close; SQl.Clear; SQL.Text := vParamSQL; //Memo1.Text := Sql.Text; Open; if RecordCount > 0 then begin v_Empno := Fields[0].AsString; E_Empno.Text := Fields[0].AsString; L_korname.ValueCaption := Fields[1].AsString; L_payraname.ValueCaption := Fields[3].AsString; L_Deptname.ValueCaption := Fields[4].AsString; end else ShowMessage('평가 내역이 없습니다'); end; end; procedure TFM_Main.BT_ScrPrintClick(Sender: TObject); begin if MessageDlg('현재 화면 그대로 프린터로 출력이 됩니다. '+#13+#13 + '진행하시겠습니까? ', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin BT_ScrPrint.SetFocus; Printer.Orientation := poLandscape; FM_Main.PrintScale := poPrintToFit; FM_Main.Print; end; end; procedure TFM_Main.BT_ExitClick(Sender: TObject); begin Close; end; end.
unit uEventLog; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.EventLog; type TfrmEventLog = class(TForm) btnCreateEventSource: TButton; CnEventLog1: TCnEventLog; btnRaiseOnEntryWrittenEvent: TButton; CnEventLog2: TCnEventLog; btnWriteEntry: TButton; btnStopEvent: TButton; procedure btnCreateEventSourceClick(Sender: TObject); procedure CnEventLog2EntryWritten(Sender: TObject; E: _EntryWrittenEventArgs); procedure btnRaiseOnEntryWrittenEventClick(Sender: TObject); procedure btnStopEventClick(Sender: TObject); procedure btnWriteEntryClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmEventLog: TfrmEventLog; implementation {$R *.dfm} // The following example creates the event source MySource if it doesn't already // exist, and writes an entry to the event log MyNewLog. procedure TfrmEventLog.btnCreateEventSourceClick(Sender: TObject); begin // Create the source, if it does not already exist. if not TCnEventLog.SourceExists('MySource') then begin //An event log source should not be created and immediately used. //There is a latency time to enable the source, it should be created //prior to executing the application that uses the source. //Execute this sample a second time to use the new source. TCnEventLog.CreateEventSource('MySource', 'MyNewLog'); TClrMessageBox.Show('Exiting, execute the application a second time to use the source.', 'CreatedEventSource'); // The source is created. Exit the application to allow it to be registered. Exit; end; // Assign a source to the instance of TCnEventLog. CnEventLog1.Source := 'MySource'; // Write an informational entry to the event log. CnEventLog1.WriteEntry('Writing to event log.'); TClrMessageBox.Show('Informational entry has been written to the event log'); end; //==== // The following example handles an EntryWritten event. procedure TfrmEventLog.btnRaiseOnEntryWrittenEventClick(Sender: TObject); begin CnEventLog2.EnableRaisingEvents := True; btnWriteEntry.Enabled := True; btnStopEvent.Enabled := True; btnRaiseOnEntryWrittenEvent.Enabled := False; end; //==== procedure TfrmEventLog.btnStopEventClick(Sender: TObject); begin CnEventLog2.EnableRaisingEvents := False; btnWriteEntry.Enabled := False; btnStopEvent.Enabled := False; btnRaiseOnEntryWrittenEvent.Enabled := True; end; procedure TfrmEventLog.btnWriteEntryClick(Sender: TObject); begin CnEventLog1.WriteEntry('Writing to event log.'); end; procedure TfrmEventLog.CnEventLog2EntryWritten(Sender: TObject; E: _EntryWrittenEventArgs); begin TClrMessageBox.Show('Written: '+ E.Entry.Message); end; end.
unit ufrmBaseInput; interface {$I ThsERP.inc} uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Dialogs, System.Variants, Vcl.Samples.Spin, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Graphics, Vcl.AppEvnts, Vcl.Menus, System.StrUtils, System.Rtti, Data.DB, FireDAC.Stan.Option, FireDAC.Stan.Intf, FireDAC.Comp.Client, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Ths.Erp.Helper.BaseTypes, Ths.Erp.Helper.Edit, Ths.Erp.Helper.Memo, Ths.Erp.Helper.ComboBox, ufrmBase, Ths.Erp.Database, Ths.Erp.Database.Table, Ths.Erp.Functions; type TfrmBaseInput = class(TfrmBase) pmLabels: TPopupMenu; mniAddLanguageContent: TMenuItem; mniEditFormTitleByLang: TMenuItem; pgcMain: TPageControl; tsMain: TTabSheet; procedure btnCloseClick(Sender: TObject); override; procedure FormCreate(Sender: TObject); override; procedure mniAddLanguageContentClick(Sender: TObject); procedure RefreshData(); virtual; procedure mniEditFormTitleByLangClick(Sender: TObject); private protected public procedure SetControlsDisabledOrEnabled(pPanelGroupboxPagecontrolTabsheet: TWinControl = nil; pIsDisable: Boolean = True); procedure SetCaptionFromLangContent(); procedure SetLabelPopup(Sender: TControl = nil); published procedure FormShow(Sender: TObject); override; procedure FormDestroy(Sender: TObject); override; end; implementation uses Ths.Erp.Database.Singleton, Ths.Erp.Constants, Ths.Erp.Database.Table.SysLangGuiContent, ufrmSysLangGuiContent; {$R *.dfm} procedure TfrmBaseInput.btnCloseClick(Sender: TObject); begin if (FormMode = ifmRewiev) then inherited else begin if (CustomMsgDlg( TranslateText('Are you sure you want to exit? All changes will be canceled!!!', FrameworkLang.MessageCloseWindow, LngMsgData, LngSystem), mtConfirmation, mbYesNo, [TranslateText('Yes', FrameworkLang.GeneralYesLower, LngGeneral, LngSystem), TranslateText('No', FrameworkLang.GeneralNoLower, LngGeneral, LngSystem)], mbNo, TranslateText('Confirmation', FrameworkLang.GeneralConfirmationLower, LngGeneral, LngSystem)) = mrYes) then inherited; end; end; procedure TfrmBaseInput.FormCreate(Sender: TObject); begin inherited; pmLabels.Images := TSingletonDB.GetInstance.ImageList16; mniAddLanguageContent.ImageIndex := IMG_ADD_DATA; if Assigned(Table) then TSingletonDB.GetInstance.HaneMiktari.SelectToList('', False, False); pnlBottom.Visible := False; stbBase.Visible := True; pnlBottom.Visible := True; end; procedure TfrmBaseInput.FormDestroy(Sender: TObject); begin // inherited; end; procedure TfrmBaseInput.FormShow(Sender: TObject); var n1: Integer; begin inherited; stbBase.Panels.Add; for n1 := 0 to stbBase.Panels.Count - 1 do stbBase.Panels.Items[n1].Style := psOwnerDraw; //Kalite standartlarına göre uygulama pencerelerinde Form Numarası //olması isteniyorsa bu durumda // if TSingletonDB.GetInstance.DataBase.Connection.Connected then begin if TSingletonDB.GetInstance.ApplicationSettings.IsUseQualityFormNumber.Value then begin stbBase.Panels.Items[STATUS_SQL_SERVER].Text := TSingletonDB.GetInstance.GetQualityFormNo(Table.TableName, True); stbBase.Panels.Items[STATUS_SQL_SERVER].Width := stbBase.Width; end; end; SetCaptionFromLangContent(); //form ve page control page 0 caption bilgisini dil dosyasına göre doldur //page control page 0 için isternise miras alan formda değişiklik yapılabilir. if Assigned(Table) then begin Self.Caption := getFormCaptionByLang(Self.Name, Self.Caption); pgcMain.Pages[0].Caption := Self.Caption; end; if Self.FormMode = ifmRewiev then begin //eğer başka pencerede açık transaction varsa güncelleme moduna hiç girilmemli if (Table.Database.TranscationIsStarted) then begin btnAccept.Visible := False; btnDelete.Visible := False; btnAccept.OnClick := nil; btnDelete.OnClick := nil; end; if ParentForm <> nil then begin btnSpin.Visible := True; end; //Burada inceleme modunda olduğu için bütün kontrolleri kapatmak gerekiyor. SetControlsDisabledOrEnabled(pgcMain, True); end else begin //Burada yeni kayıt, kopya yeni kayıt veya güncelleme modunda olduğu için bütün kontrolleri açmak gerekiyor. SetControlsDisabledOrEnabled(pgcMain, False); end; mniAddLanguageContent.Visible := False; if (TSingletonDB.GetInstance.User.IsSuperUser.Value) and (FormMode = ifmRewiev) then begin //yeni kayıtta transactionlardan dolayı sorun oluyor. Düzeltmek için uğralılmadı SetLabelPopup(); mniAddLanguageContent.Visible := True; end; // if (FormMode <> ifmNewRecord ) then // RefreshData; //ferhat buraya bak normal input db formlarda iki kere refreshdata yapıyor. Bunu engelle //detaylı formlarda da refresh yapmalı fakat input db formlarından gelmediği için burada yapıldı. //yapıyı gözden geçir Application.ProcessMessages; end; procedure TfrmBaseInput.mniAddLanguageContentClick(Sender: TObject); var vSysLangGuiContent: TSysLangGuiContent; vCode, vValue, vContentType, vTableName: string; begin if pmLabels.PopupComponent.ClassType = TLabel then begin vCode := StringReplace(pmLabels.PopupComponent.Name, PREFIX_LABEL, '', [rfReplaceAll]); vContentType := LngLabelCaption; vTableName := ReplaceRealColOrTableNameTo(Table.TableName); vValue := TLabel(pmLabels.PopupComponent).Caption; end else if pmLabels.PopupComponent.ClassType = TTabSheet then begin vCode := StringReplace(pmLabels.PopupComponent.Name, PREFIX_TABSHEET, '', [rfReplaceAll]); vContentType := LngTab; vTableName := ReplaceRealColOrTableNameTo(Table.TableName); vValue := TTabSheet(pmLabels.PopupComponent).Caption; end; vSysLangGuiContent := TSysLangGuiContent.Create(TSingletonDB.GetInstance.DataBase); vSysLangGuiContent.Lang.Value := TSingletonDB.GetInstance.DataBase.ConnSetting.Language; vSysLangGuiContent.Code.Value := vCode; vSysLangGuiContent.ContentType.Value := vContentType; vSysLangGuiContent.TableName1.Value := vTableName; vSysLangGuiContent.Val.Value := vValue; TfrmSysLangGuiContent.Create(Self, nil, vSysLangGuiContent, True, ifmCopyNewRecord, fomNormal, ivmSort).ShowModal; SetCaptionFromLangContent(); end; procedure TfrmBaseInput.mniEditFormTitleByLangClick(Sender: TObject); begin // CreateLangGuiContentFormforFormCaption; end; procedure TfrmBaseInput.RefreshData; begin // end; procedure TfrmBaseInput.SetLabelPopup(Sender: TControl); var n1: Integer; n2: Integer; begin if Sender = nil then begin Sender := pnlMain; SetLabelPopup(Sender); end; for n1 := 0 to TWinControl(Sender).ControlCount-1 do begin if TWinControl(Sender).Controls[n1].ClassType = TPageControl then begin for n2 := 0 to TPageControl(TWinControl(Sender).Controls[n1]).PageCount-1 do begin TPageControl(TWinControl(Sender).Controls[n1]).Pages[n2].PopupMenu := pmLabels; end; SetLabelPopup(TWinControl(Sender).Controls[n1]); end else if TWinControl(Sender).Controls[n1].ClassType = TTabSheet then begin TTabSheet(TWinControl(Sender).Controls[n1]).PopupMenu := pmLabels; SetLabelPopup(TWinControl(Sender).Controls[n1]); end else if TWinControl(Sender).Controls[n1].ClassType = TLabel then begin TLabel(TWinControl(Sender).Controls[n1]).PopupMenu := pmLabels; end; end; end; procedure TfrmBaseInput.SetCaptionFromLangContent; procedure SubSetLabelCaption(); var vCtx1: TRttiContext; vRtf1: TRttiField; vRtt1: TRttiType; vLabel: TLabel; n1: Integer; vLabelNames, vLabelName, vFilter: string; vSysLangGuiContent: TSysLangGuiContent; begin //label component isimleri lbl + db_field_name olacak şekilde verileceği varsayılarak bu kod yazildi. örnek: lblcountry_code vLabelNames := ''; vCtx1 := TRttiContext.Create; vRtt1 := vCtx1.GetType(Self.ClassType); for vRtf1 in vRtt1.GetFields do if vRtf1.FieldType.Name = TLabel.ClassName then begin vLabel := TLabel(FindComponent(vRtf1.Name)); if Assigned(vLabel) then vLabelNames := vLabelNames + QuotedStr(StringReplace(TLabel(vLabel).Name, PREFIX_LABEL, '', [rfReplaceAll])) + ', '; end; vLabelNames := Trim(vLabelNames); if Length(vLabelNames) > 0 then vLabelNames := LeftStr(vLabelNames, Length(vLabelNames)-1); vSysLangGuiContent := TSysLangGuiContent.Create(TSingletonDB.GetInstance.DataBase); try if Assigned(Table) then vFilter := ' AND ' + vSysLangGuiContent.TableName1.FieldName + '=' + QuotedStr(ReplaceRealColOrTableNameTo(Table.TableName)) else vFilter := ' AND ' + vSysLangGuiContent.FormName.FieldName + '=' + QuotedStr(ReplaceRealColOrTableNameTo(Self.Name)); vSysLangGuiContent.SelectToList( ' AND ' + vSysLangGuiContent.Lang.FieldName + '=' + QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language) + ' AND ' + vSysLangGuiContent.Code.FieldName + ' IN (' + vLabelNames + ')' + ' AND ' + vSysLangGuiContent.ContentType.FieldName + '=' + QuotedStr(LngLabelCaption) + vFilter, False, False); for n1 := 0 to vSysLangGuiContent.List.Count-1 do begin if not VarIsNull(TSysLangGuiContent(vSysLangGuiContent.List[n1]).Code.Value) then begin vLabelName := VarToStr(TSysLangGuiContent(vSysLangGuiContent.List[n1]).Code.Value); vLabel := TLabel(FindComponent(PREFIX_LABEL + vLabelName)); if not VarIsNull(TSysLangGuiContent(vSysLangGuiContent.List[n1]).Val.Value) then TLabel(vLabel).Caption := VarToStr(TSysLangGuiContent(vSysLangGuiContent.List[n1]).Val.Value); end; end; finally vSysLangGuiContent.Free; end; end; procedure SubSetTabSheetCaption(); var vCtx1: TRttiContext; vRtf1: TRttiField; vRtt1: TRttiType; vTabSheet: TTabSheet; begin if Assigned(Table) then begin //TAB SHEET Captionları düzenle vCtx1 := TRttiContext.Create; vRtt1 := vCtx1.GetType(Self.ClassType); for vRtf1 in vRtt1.GetFields do if vRtf1.FieldType.Name = TTabSheet.ClassName then begin vTabSheet := TTabSheet(FindComponent(vRtf1.Name)); if Assigned(vTabSheet) then TTabSheet(vTabSheet).Caption := TranslateText(TTabSheet(vTabSheet).Caption, StringReplace(TTabSheet(vTabSheet).Name, PREFIX_TABSHEET, '', [rfReplaceAll]), LngTab, ReplaceRealColOrTableNameTo(Table.TableName)); end; end; end; begin if TSingletonDB.GetInstance.DataBase.Connection.Connected then begin SubSetTabSheetCaption; SubSetLabelCaption; end; end; procedure TfrmBaseInput.SetControlsDisabledOrEnabled(pPanelGroupboxPagecontrolTabsheet: TWinControl; pIsDisable: Boolean); var nIndex: Integer; PanelContainer: TWinControl; begin PanelContainer := nil; if pPanelGroupboxPagecontrolTabsheet = nil then PanelContainer := pnlMain else begin if pPanelGroupboxPagecontrolTabsheet.ClassType = TPanel then PanelContainer := pPanelGroupboxPagecontrolTabsheet as TPanel else if pPanelGroupboxPagecontrolTabsheet.ClassType = TGroupBox then PanelContainer := pPanelGroupboxPagecontrolTabsheet as TGroupBox else if pPanelGroupboxPagecontrolTabsheet.ClassType = TPageControl then PanelContainer := pPanelGroupboxPagecontrolTabsheet as TPageControl else if pPanelGroupboxPagecontrolTabsheet.ClassType = TTabSheet then PanelContainer := pPanelGroupboxPagecontrolTabsheet as TTabSheet; end; for nIndex := 0 to PanelContainer.ControlCount-1 do begin if PanelContainer.Controls[nIndex].ClassType = TPanel then SetControlsDisabledOrEnabled(PanelContainer.Controls[nIndex] as TPanel, pIsDisable) else if PanelContainer.Controls[nIndex].ClassType = TGroupBox then SetControlsDisabledOrEnabled(PanelContainer.Controls[nIndex] as TGroupBox, pIsDisable) else if PanelContainer.Controls[nIndex].ClassType = TPageControl then SetControlsDisabledOrEnabled(PanelContainer.Controls[nIndex] as TPageControl, pIsDisable) else if PanelContainer.Controls[nIndex].ClassType = TTabSheet then SetControlsDisabledOrEnabled(PanelContainer.Controls[nIndex] as TTabSheet, pIsDisable) else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TEdit) then TEdit(PanelContainer.Controls[nIndex]).ReadOnly := pIsDisable else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TComboBox) then TComboBox(PanelContainer.Controls[nIndex]).Enabled := (pIsDisable = False) else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TMemo) then TMemo(PanelContainer.Controls[nIndex]).ReadOnly := pIsDisable else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TCheckBox) then TCheckBox(PanelContainer.Controls[nIndex]).Enabled := (pIsDisable = False) else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TRadioGroup) then TRadioGroup(PanelContainer.Controls[nIndex]).Enabled := (pIsDisable = False) else if (TControl(PanelContainer.Controls[nIndex]).ClassType = TRadioButton) then TRadioButton(PanelContainer.Controls[nIndex]).Enabled := (pIsDisable = False); end; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXMessageHandlerJSonCommon; interface uses System.JSON, Data.DBXCommon, Data.DBXCommonTable, Data.DBXMessageHandlerCommon, Data.DBXStream, Data.DBXStreamPlatform; type TDBXJSonConnectionHandler = class abstract(TDBXConnectionHandler) public constructor Create(const ADbxContext: TDBXContext; const AUsesDbxParameters: Boolean; const ADbxStreamReader: TDBXJSonStreamReader; const ADbxStreamWriter: TDBXJSonStreamWriter; const ARowBuffer: TDBXRowBuffer; const AOwnsStreamers: Boolean); destructor Destroy; override; function GetActiveTableReaderItem(const ActiveStreamerRowList: TDBXActiveTableReaderList; const CommandHandle: Integer; const RowHandle: Integer): TDBXActiveTableReaderItem; function CreateJSonRow(const CommandHandle: Integer; const OwnsRow: Boolean): TDBXJSonRow; function ReadDBXReader: TDBXReader; function ReadDBXReaderMetaData: TDBXJSonReader; procedure HandleMetadataData; /// <summary> Parse part past "metadata" from: {"metadata":{data}} /// /// </summary> /// <returns>JSONObject</returns> function ReadMetadataData: TJSONObject; /// <summary> Parse part past "data" from: {"data":[LEN,JSONVALUE]}. If the callback failed /// </summary> /// <remarks> If the callback failed /// with exception a DBXError is raised. /// /// </remarks> /// <returns>JSONValue</returns> function ReadCallbackData: TJSONValue; procedure WriteFirst(const CommandHandle: Integer; const RowHandle: Integer; const DbxRow: TDBXJSonRow; const Value: TDBXReader; const BcdFormat: Integer); function WriteNext(const CommandHandle: Integer; const DbxStreamerRow: TDBXJSonRow; const Value: TDBXReader; const FirstRows: Boolean): Boolean; procedure WriteDBXReader(const CommandHandle: Integer; const Item: TDBXActiveTableReaderItem); function ReadParameter: TDBXParameter; procedure ReadParameters(const Message: TDBXCommandMessage); procedure WriteParameters(const Message: TDBXCommandMessage; const SomethingWritten: Boolean); /// <summary> Writes the JSON value into the output stream. May or may not flush the /// </summary> /// <remarks> May or may not flush the /// data depending on argument. /// /// </remarks> /// <param name="data">- JSON value to be serialized and stored into the output stream</param> /// <param name="flush">- controls the flush operation</param> procedure WriteCallbackData(const Data: TJSONValue; const Flush: Boolean); /// <summary> Writes the Metadata value into the output stream. May or may not flush the /// </summary> /// <remarks> May or may not flush the /// data depending on argument. /// /// </remarks> /// <param name="data">- JSON object of metadata to be serialized and stored into the output stream</param> /// <param name="flush">- controls the flush operation</param> procedure WriteMetadataData(const Data: TJSONObject; const Flush: Boolean); protected function IsNoDBXReaderParameterReturn(const Parameters: TDBXParameterList): Boolean; function IsOutputDBXReader(const Parameter: TDBXParameter): Boolean; function IsConnectionLost: Boolean; private function CreateRowBuffer(const CommandHandle: Integer): TDBXRowBuffer; function ReadValueTypes(const Context: TDBXContext; const Row: TDBXRow; const ColumnCount: Integer; const UseDbxFlags: Boolean): TDBXWritableValueArray; procedure FlushStreamWriterIfNeeded; procedure WriteParameter(const Parameter: TDBXParameter); protected FDbxStreamReader: TDBXJSonStreamReader; FDbxStreamWriter: TDBXJSonStreamWriter; FDbxRowBuffer: TDBXRowBuffer; FUsesDbxParameters: Boolean; FOwnsStreamers: Boolean; public property ConnectionLost: Boolean read IsConnectionLost; end; implementation uses Data.DBXPlatform, System.SysUtils, Data.DBXClientResStrs, Data.DBXMetadataCommon; constructor TDBXJSonConnectionHandler.Create(const ADbxContext: TDBXContext; const AUsesDbxParameters: Boolean; const ADbxStreamReader: TDBXJSonStreamReader; const ADbxStreamWriter: TDBXJSonStreamWriter; const ARowBuffer: TDBXRowBuffer; const AOwnsStreamers: Boolean); begin inherited Create(ADbxContext); FDbxStreamReader := ADbxStreamReader; FDbxStreamWriter := ADbxStreamWriter; FDbxRowBuffer := ARowBuffer; FUsesDbxParameters := AUsesDbxParameters; FOwnsStreamers := AOwnsStreamers; end; destructor TDBXJSonConnectionHandler.Destroy; begin if FOwnsStreamers then begin FreeAndNil(FDbxStreamReader); FreeAndNil(FDbxStreamWriter); FreeAndNil(FDbxRowBuffer); end; inherited Destroy; end; function TDBXJSonConnectionHandler.IsConnectionLost: Boolean; begin Result := FDbxStreamReader.ConnectionLost or FDbxStreamWriter.ConnectionLost; end; function TDBXJSonConnectionHandler.IsNoDBXReaderParameterReturn(const Parameters: TDBXParameterList): Boolean; var Parameter: TDBXParameter; begin if Parameters.Count = 1 then begin Parameter := Parameters.Parameter[0]; if Parameter.ParameterDirection = TDBXParameterDirections.ReturnParameter then begin if Parameter.DataType = TDBXDataTypes.TableType then Exit(True); end; end; Result := False; end; function TDBXJSonConnectionHandler.IsOutputDBXReader(const Parameter: TDBXParameter): Boolean; begin if Parameter.DataType = TDBXDataTypes.TableType then case Parameter.ParameterDirection of TDBXParameterDirections.ReturnParameter, TDBXParameterDirections.OutParameter, TDBXParameterDirections.InOutParameter: Exit(not Parameter.Value.IsNull); end; Result := False; end; function TDBXJSonConnectionHandler.CreateRowBuffer(const CommandHandle: Integer): TDBXRowBuffer; var RowBuffer: TDBXRowBuffer; Complete: Boolean; Handle: TDBXInt32s; begin Complete := False; RowBuffer := TDBXRowBuffer.Create; try RowBuffer.DbxStreamReader := FDbxStreamReader; RowBuffer.DbxStreamWriter := FDbxStreamWriter; SetLength(Handle,1); Handle[0] := CommandHandle; RowBuffer.CommandHandle := Handle; if (FDbxRowBuffer = nil) or FDbxRowBuffer.Client then RowBuffer.Client := True else RowBuffer.Client := False; RowBuffer.MinBufferSize := FDbxStreamWriter.CalcRowBufferSize; Complete := True; Result := RowBuffer; finally if not Complete then RowBuffer.Free; end; end; function TDBXJSonConnectionHandler.GetActiveTableReaderItem(const ActiveStreamerRowList: TDBXActiveTableReaderList; const CommandHandle: Integer; const RowHandle: Integer): TDBXActiveTableReaderItem; var Row: TDBXJSonRow; Item: TDBXActiveTableReaderItem; begin Item := ActiveStreamerRowList.FindStreamerRowItem(RowHandle); if Item = nil then begin Row := CreateJSonRow(CommandHandle, True); Item := ActiveStreamerRowList.AddDBXStreamerRow(Row, RowHandle, True, False); end; Result := Item; end; function TDBXJSonConnectionHandler.CreateJSonRow(const CommandHandle: Integer; const OwnsRow: Boolean): TDBXJSonRow; begin Result := TDBXJSonRow.Create(DBXContext, FDbxStreamReader, FDbxStreamWriter, CreateRowBuffer(CommandHandle), OwnsRow); end; function TDBXJSonConnectionHandler.ReadDBXReader: TDBXReader; var Reader: TDBXJSonReader; begin Reader := ReadDBXReaderMetaData; Reader.ReadFirstData; Result := Reader; end; function TDBXJSonConnectionHandler.ReadDBXReaderMetaData: TDBXJSonReader; var Reader: TDBXJSonReader; Context: TDBXContext; Updateable: Boolean; Values: TDBXWritableValueArray; Row: TDBXJSonRow; ColumnCount: Integer; RowHandle: Integer; CommandHandle: Integer; BcdFormat: Integer; UseDbxFlags: Boolean; begin Values := nil; RowHandle := 0; Row := nil; Updateable := False; CommandHandle := -1; Context := DBXContext; BcdFormat := TDBXBcdFormat.BinaryRead; UseDbxFlags := False; repeat case FDbxStreamReader.ReadStringCode of TDBXStringCodes.Fields: begin FDbxStreamReader.Next(TDBXTokens.NameSeparatorToken); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); CommandHandle := FDbxStreamReader.ReadInt; FDbxStreamReader.Next(TDBXTokens.ValueSeparatorToken); Updateable := FDbxStreamReader.ReadBoolean; if FDbxStreamReader.Next = TDBXTokens.ValueSeparatorToken then begin RowHandle := FDbxStreamReader.ReadInt; if FDbxStreamReader.Next = TDBXTokens.ValueSeparatorToken then begin BcdFormat := FDbxStreamReader.ReadInt; if FDbxStreamReader.Next = TDBXTokens.ValueSeparatorToken then UseDbxFlags := FDbxStreamReader.ReadBoolean; end; end; end; TDBXStringCodes.Columns: begin FDbxStreamReader.Next(TDBXTokens.NameSeparatorToken); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); ColumnCount := FDbxStreamReader.ReadInt; Row := CreateJSonRow(CommandHandle, False); Row.BcdFormat := BcdFormat; Values := ReadValueTypes(Context, Row, ColumnCount, UseDbxFlags); end; end; FDbxStreamReader.SkipToEndOfObject; until FDbxStreamReader.Next <> TDBXTokens.ValueSeparatorToken; FDbxStreamReader.SkipToEndOfObject; Row.RowHandle := RowHandle; Reader := TDBXJSonReader.Create(Context, Row, RowHandle, CommandHandle, Values, FDbxStreamReader, FDbxStreamWriter, Row.RowBuffer, Updateable); Result := Reader; end; procedure TDBXJSonConnectionHandler.HandleMetadataData; var MetaData: TJSONObject; begin MetaData := ReadMetadataData; {$IFNDEF J2CS} TInvocationMetadataDelegate.StoreMetadata(MetaData); MetaData := nil; {$ENDIF} MetaData.Free; end; function TDBXJSonConnectionHandler.ReadMetadataData: TJSONObject; var Count: Integer; Buffer: TArray<Byte>; MetadataData: TJSONObject; begin MetadataData := nil; FDbxStreamReader.Next(TDBXTokens.NameSeparatorToken); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); Count := FDbxStreamReader.ReadInt; FDbxStreamReader.Next(TDBXTokens.ValueSeparatorToken); SetLength(Buffer,Count); FDbxStreamReader.ReadDataBytes(Buffer, 0, Count); FDbxStreamReader.SkipToEndOfObject; try MetadataData := TJSONObject(TJSONObject.ParseJSONValue(Buffer, 0)); except end; if MetadataData = nil then raise TDBXError.Create(TDBXErrorCodes.InvalidArgument, SMetadataParseError); Result := MetadataData; end; function TDBXJSonConnectionHandler.ReadCallbackData: TJSONValue; var Count: Integer; Buffer: TArray<Byte>; CallbackParam: TJSONValue; begin FDbxStreamReader.Next(TDBXTokens.ObjectStartToken); FDbxStreamReader.Next(TDBXTokens.StringStartToken); case FDbxStreamReader.ReadStringCode of TDBXStringCodes.Data: ; TDBXStringCodes.Error: FDbxStreamReader.ReadErrorBody; else raise TDBXError.Create(TDBXErrorCodes.CallbackError, SInvalidCallbackMessageFormat); end; FDbxStreamReader.Next(TDBXTokens.NameSeparatorToken); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); Count := FDbxStreamReader.ReadInt; FDbxStreamReader.Next(TDBXTokens.ValueSeparatorToken); SetLength(Buffer,Count); FDbxStreamReader.ReadDataBytes(Buffer, 0, Count); FDbxStreamReader.SkipToEndOfObject; CallbackParam := TJSONObject.ParseJSONValue(Buffer, 0); if CallbackParam = nil then raise TDBXError.Create(TDBXErrorCodes.CallbackError, SCallbackArgParseError); Result := CallbackParam; end; function TDBXJSonConnectionHandler.ReadValueTypes(const Context: TDBXContext; const Row: TDBXRow; const ColumnCount: Integer; const UseDbxFlags: Boolean): TDBXWritableValueArray; var Values: TDBXWritableValueArray; ValueType: TDBXValueType; DbxReaderLocal: TDBXJSonStreamReader; DataType, DbxFlags, Flags, Ordinal, SubType: Integer; begin DbxReaderLocal := FDbxStreamReader; if ColumnCount < 1 then Result := nil else begin SetLength(Values,ColumnCount); for Ordinal := 0 to ColumnCount - 1 do begin DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); DbxReaderLocal.Next(TDBXTokens.ArrayStartToken); ValueType := TDBXValueType.Create(Context); ValueType.Ordinal := Ordinal; ValueType.Name := DbxReaderLocal.ReadString; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); DataType := DbxReaderLocal.ReadInt; ValueType.DataType := DataType; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); SubType := DbxReaderLocal.ReadInt; ValueType.SubType := SubType; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); ValueType.Precision := DbxReaderLocal.ReadInt; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); ValueType.Scale := DbxReaderLocal.ReadInt; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); ValueType.Size := DbxReaderLocal.ReadInt; DbxReaderLocal.Next(TDBXTokens.ValueSeparatorToken); Flags := DbxReaderLocal.ReadInt; if UseDbxFlags then ValueType.ValueTypeFlags := Flags else begin DbxFlags := TDBXValueTypeFlags.ExtendedType; if (Flags and TDBXSQLColumnFlags.FlagReadonly) <> 0 then DbxFlags := DbxFlags or TDBXValueTypeFlags.ReadOnly; if (Flags and TDBXSQLColumnFlags.FlagSearchable) <> 0 then DbxFlags := DbxFlags or TDBXValueTypeFlags.Searchable; if (Flags and TDBXSQLColumnFlags.FlagNullable) <> 0 then DbxFlags := DbxFlags or TDBXValueTypeFlags.Nullable; if (Flags and TDBXSQLColumnFlags.FlagAutoincrement) <> 0 then DbxFlags := DbxFlags or TDBXValueTypeFlags.Autoincrement; ValueType.ValueTypeFlags := DbxFlags; end; if DbxReaderLocal.Next <> TDBXTokens.ArrayEndToken then begin ValueType.ParameterDirection := DbxReaderLocal.ReadInt; DbxReaderLocal.SkipToEndOfArray; end; Values[Ordinal] := TDBXValue.CreateValue(Context, ValueType, Row, True); end; Result := Values; end; end; procedure TDBXJSonConnectionHandler.WriteFirst(const CommandHandle: Integer; const RowHandle: Integer; const DbxRow: TDBXJSonRow; const Value: TDBXReader; const BcdFormat: Integer); var Table: TDBXReader; Count: Integer; Ordinal: Integer; ValueType: TDBXValueType; begin Table := Value; Count := Table.ColumnCount; DbxRow.NeedsNext := False; FDbxStreamWriter.WriteTableObjectStart; FDbxStreamWriter.WriteFieldsObjectStart; FDbxStreamWriter.WriteInt(CommandHandle); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteBoolean(Table.Updateable); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(RowHandle); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(BcdFormat); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteBoolean(True); FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteColumnsObjectStart; FDbxStreamWriter.WriteInt(Count); if Count > 0 then begin FDbxStreamWriter.WriteValueSeparator; Ordinal := 0; while True do begin ValueType := Table.ValueType[Ordinal]; FDbxStreamWriter.WriteArrayStart; FDbxStreamWriter.WriteString(ValueType.Name); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.DataType); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.SubType); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteLong(ValueType.Precision); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.Scale); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.Size); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.ValueTypeFlags); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteInt(ValueType.ParameterDirection); FDbxStreamWriter.WriteArrayEnd; Inc(Ordinal); if Ordinal < Count then FDbxStreamWriter.WriteValueSeparator else break; end; end; FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; end; procedure TDBXJSonConnectionHandler.FlushStreamWriterIfNeeded; var Buffer: TArray<Byte>; SizeOff: Integer; begin Buffer := FDbxStreamWriter.Buffer; SizeOff := FDbxStreamWriter.BufferPosition; if (Length(Buffer) - SizeOff) < 128 then FDbxStreamWriter.Flush; end; function TDBXJSonConnectionHandler.WriteNext(const CommandHandle: Integer; const DbxStreamerRow: TDBXJSonRow; const Value: TDBXReader; const FirstRows: Boolean): Boolean; var HasRows: Boolean; Table: TDBXReader; RowBuffer: TDBXRowBuffer; MinBufSize: Integer; ColumnCount: Integer; Ordinal: Integer; BytesWritten: Integer; begin HasRows := True; Table := Value; RowBuffer := DbxStreamerRow.RowBuffer; MinBufSize := RowBuffer.MinBufferSize; if FirstRows and not Table.Next then begin FDbxStreamWriter.WriteDataObjectStart; FDbxStreamWriter.WriteInt(0); FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; Exit(True); end; FlushStreamWriterIfNeeded; RowBuffer.Post; if DbxStreamerRow.NeedsNext then begin DbxStreamerRow.NeedsNext := False; HasRows := Table.Next; end; ColumnCount := Table.ColumnCount; try while HasRows and (RowBuffer.offset < MinBufSize) do begin for ordinal := 0 to ColumnCount - 1 do TDBXDriverHelp.CopyRowValue(Table.Value[Ordinal], DbxStreamerRow); if RowBuffer.offset < MinBufSize then HasRows := Table.Next else DbxStreamerRow.NeedsNext := True; end; except on Ex: Exception do begin RowBuffer.Cancel; raise TDBXError.Create(TDBXErrorCodes.InvalidOperation, Ex.Message, Ex); end; end; if FDbxStreamWriter <> nil then begin BytesWritten := RowBuffer.offset; FDbxStreamWriter.WriteDataObjectStart; if HasRows then FDbxStreamWriter.WriteInt(BytesWritten) else FDbxStreamWriter.WriteInt(-BytesWritten); FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteDataBytes(RowBuffer.buf, 0, RowBuffer.offset); RowBuffer.Post; FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; end; Result := not HasRows; end; procedure TDBXJSonConnectionHandler.WriteDBXReader(const CommandHandle: Integer; const Item: TDBXActiveTableReaderItem); var DbxJSonRow: TDBXJSonRow; begin DbxJSonRow := TDBXJSonRow(Item.StreamerRow); WriteFirst(CommandHandle, DbxJSonRow.RowHandle, DbxJSonRow, Item.Reader, DbxJSonRow.BcdFormat); Item.ReaderEos := WriteNext(CommandHandle, DbxJSonRow, Item.Reader, True); end; function TDBXJSonConnectionHandler.ReadParameter: TDBXParameter; var Parameter: TDBXParameter; begin Parameter := TDBXParameter.Create(DBXContext); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); Parameter.DataType := FDbxStreamReader.ReadInt; FDbxStreamReader.NextValueSeparator; Parameter.SubType := FDbxStreamReader.ReadInt; FDbxStreamReader.NextValueSeparator; Parameter.ParameterDirection := FDbxStreamReader.ReadInt; FDbxStreamReader.NextValueSeparator; Parameter.Precision := FDbxStreamReader.ReadLong; FDbxStreamReader.NextValueSeparator; Parameter.Scale := FDbxStreamReader.ReadInt; FDbxStreamReader.NextValueSeparator; Parameter.Name := FDbxStreamReader.ReadString; FDbxStreamReader.NextValueSeparator; Parameter.ChildPosition := FDbxStreamReader.ReadInt; FDbxStreamReader.NextValueSeparator; Parameter.Size := FDbxStreamReader.ReadInt; //Size of 0 is never valid for string types. //Use precision as the size value if it is nonzero in this case to prevent invalid memory writes if (Parameter.Size = 0) and (Parameter.DataType in [TDBXDataTypes.AnsiStringType, TDBXDataTypes.WideStringType]) then begin if (Parameter.ParameterDirection in [TDBXParameterDirections.OutParameter, TDBXParameterDirections.InOutParameter, TDBXParameterDirections.ReturnParameter ]) then begin if Parameter.Precision <> 0 then Parameter.Size := Parameter.Precision; end; end; if FDbxStreamReader.Next = TDBXTokens.ValueSeparatorToken then begin Parameter.ValueTypeFlags := FDbxStreamReader.ReadInt; if Parameter.Literal then begin FDbxStreamReader.NextValueSeparator; Parameter.Value.SetWideString(FDbxStreamReader.ReadString); end; ; FDbxStreamReader.SkipToEndOfArray; end; ; Parameter.ValueTypeFlags := Parameter.ValueTypeFlags or TDBXValueTypeFlags.ExtendedType; Result := Parameter; end; procedure TDBXJSonConnectionHandler.ReadParameters(const Message: TDBXCommandMessage); var ParameterCount: Integer; Ordinal: Integer; Parameter: TDBXParameter; Parameters: TDBXParameterList; ExistingParameterCount: Integer; begin Parameters := Message.Parameters; if Parameters = nil then Parameters := Message.ExplicitParameters; FDbxStreamReader.Next(TDBXTokens.NameSeparatorToken); FDbxStreamReader.Next(TDBXTokens.ArrayStartToken); try ParameterCount := FDbxStreamReader.ReadInt; if ParameterCount > 0 then begin ExistingParameterCount := Parameters.Count; if ExistingParameterCount = 0 then Parameters.Count := ParameterCount; if FDbxStreamReader.Next = TDBXTokens.ValueSeparatorToken then for ordinal := 0 to ParameterCount - 1 do begin if Ordinal <> 0 then FDbxStreamReader.NextValueSeparator; Parameter := ReadParameter; if ExistingParameterCount = 0 then begin Parameters.SetParameter(Ordinal, Parameter); if FUsesDbxParameters then TDBXDriverHelp.UpdateParameterType(Parameter); end else Parameter.Free; end; if ExistingParameterCount = 0 then Message.ParameterTypeChanged := False; end; finally FDbxStreamReader.SkipToEndOfObject; end; end; procedure TDBXJSonConnectionHandler.WriteParameter(const Parameter: TDBXParameter); var StreamWriter: TDBXJSonStreamWriter; begin StreamWriter := FDbxStreamWriter; StreamWriter.WriteValueSeparator; StreamWriter.WriteArrayStart; StreamWriter.WriteInt(Parameter.DataType); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.SubType); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.ParameterDirection); StreamWriter.WriteValueSeparator; StreamWriter.WriteLong(Parameter.Precision); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.Scale); StreamWriter.WriteValueSeparator; StreamWriter.WriteString(Parameter.Name); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.ChildPosition); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.Size); StreamWriter.WriteValueSeparator; StreamWriter.WriteInt(Parameter.ValueTypeFlags); if Parameter.Literal then begin StreamWriter.WriteValueSeparator; StreamWriter.WriteString(Parameter.Value.GetWideString); end; StreamWriter.WriteArrayEnd; end; procedure TDBXJSonConnectionHandler.WriteParameters(const Message: TDBXCommandMessage; const SomethingWritten: Boolean); var Parameters: TDBXParameterList; ParamListCount: Integer; Ordinal: Integer; begin Parameters := Message.Parameters; ParamListCount := Parameters.Count; if ParamListCount > 0 then begin if SomethingWritten then FDbxStreamWriter.WriteValueSeparator; FDbxStreamWriter.WriteParametersObjectStart(ParamListCount); if Parameters.Parameter[0] <> nil then for ordinal := 0 to ParamListCount - 1 do WriteParameter(Parameters.Parameter[Ordinal]); FDbxStreamWriter.WriteArrayEnd; FDbxStreamWriter.WriteObjectEnd; Message.ParameterTypeChanged := False; end; end; procedure TDBXJSonConnectionHandler.WriteCallbackData(const Data: TJSONValue; const Flush: Boolean); begin FDbxStreamWriter.WriteCallback(Data); if Flush then FDbxStreamWriter.Flush; end; procedure TDBXJSonConnectionHandler.WriteMetadataData(const Data: TJSONObject; const Flush: Boolean); begin FDbxStreamWriter.WriteMetadata(Data); if Flush then FDbxStreamWriter.Flush; end; end.
{$MODE OBJFPC} const InputFile = 'TURTLE.INP'; OutputFile = 'TURTLE.OUT'; var a: array[1..4] of Integer; res: Integer; f: TextFile; i, j: Integer; temp: Integer; begin AssignFile(f, InputFile); Reset(f); ReadLn(f, a[1], a[2], a[3], a[4]); CloseFile(f); for i := 1 to 4 do for j := i + 1 to 4 do if a[i] > a[j] then begin temp := a[i]; a[i] := a[j]; a[j] := temp; end; AssignFile(f, OutputFile); Rewrite(f); WriteLn(f, Int64(a[1]) * a[3]); CloseFile(f); end.
unit ncEnvioCaixa; interface uses sysutils, classes, IdHTTP, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdMultipartFormData; function httpPost( aParams: TStrings; aArq, aHost, aUrl : String): String; implementation uses uLogs; function httpPost(aParams: TStrings; aArq, aHost, AUrl : String): String; var h: TIdHTTP; ms : TIdMultiPartFormDataStream; i : integer; s : string; begin { o post pode ser feito para esta url: http://emailcaixanextar.herokuapp.com/ se acessar pelo browser, conseguem testar o envio no enderešo: http://emailcaixanextar.herokuapp.com/test } result := ''; h := TIdHTTP.create(nil); ms := TIdMultiPartFormDataStream.Create; try h.HandleRedirects := True; try for i := 0 to aParams.Count-1 do ms.AddFormField(aParams.Names[i], aParams.ValueFromIndex[i]); ms.AddFile('pdf', aArq, 'application/pdf'); ms.Seek(0,0); result := h.Post(aUrl, ms); glog.Log(nil, [lcTrace], 'httpPost: '+result); except on e:exception do begin glog.Log(nil, [lcExcept], 'httpPost - Exception: '+e.Message); result := e.Message; end; end; finally h.free; ms.Free; end; end; end.
unit HexToInt_1; interface implementation function TryHexToInt(const Hex: string; out Value: Int32): Boolean; function Multiplier(Position: UInt32): Int32; inline; var I: Int32; begin Result := 1; for I := 1 to Position do Result := 16 * Result; end; var A, B, I: Int32; M: Int32; begin B := 0; Value := 0; for I := High(Hex) downto Low(Hex) do begin A := Ord(Hex[I]); M := Multiplier(B); case A of 48: ; // '0' -- Do nothing. 49..57: Value := Value + (A - 48) * M; // '1'..'9' 65..70: Value := Value + (A - 55) * M; // 'A'..'F' 97..102: Value := Value + (A - 87) * M; // 'a'..'f' else Exit(False); end; Inc(B); end; Result := True; end; var G0, G1, G2, G3, G4, G5, G6, G7: Int32; procedure Test; begin TryHexToInt('a', G0); TryHexToInt('a0', G1); TryHexToInt('a0b', G2); TryHexToInt('a0b0', G3); TryHexToInt('a0b0c', G4); TryHexToInt('a0b0c0', G5); TryHexToInt('a0b0c0d', G6); TryHexToInt('a0b0c0d0', G7); end; initialization Test(); finalization Assert(G0 = $a); Assert(G1 = $a0); Assert(G2 = $a0b); Assert(G3 = $a0b0); Assert(G4 = $a0b0c); Assert(G5 = $a0b0c0); Assert(G6 = $a0b0c0d); Assert(G7 = $a0b0c0d0); end.
{************************************************** llPDFLib Version 6.4.0.1389, 09.07.2016 Copyright (c) 2002-2016 Sybrex Systems Copyright (c) 2002-2016 Vadim M. Shakun All rights reserved mailto:em-info@sybrex.com **************************************************} unit llPDFFont; {$i pdf.inc} interface uses {$ifndef USENAMESPACE} Windows, SysUtils, Classes, Graphics, {$else} WinAPI.Windows, System.SysUtils, System.Classes, Vcl.Graphics, {$endif} llPDFTrueType,llPDFEngine, llPDFMisc, llPDFTypes; type TPDFANSICharacterWidth = array [ 0..127 ] of Integer; PPDFANSICharacterWidth = ^TPDFANSICharacterWidth; TGlyphData = record Unicode: Word; Width: Word; BaseWidth:Word; AddWidth: Word; Used: Boolean; NewIdx: Word; FontID:Word; Size: Word; DataOffset:Integer; end; TPDFFont = class(TPDFObject) private FAlias: AnsiString; FUsed: Boolean; function GetAscent: Integer; virtual; abstract; function GetDescent: Integer; virtual; abstract; function GetWidth(Index:Word): Integer; virtual; abstract; public procedure FillUsed(s:AnsiString); virtual; procedure UsedChar(Ch:Byte); virtual; procedure SetAllASCII; virtual; property Ascent: Integer read GetAscent; property AliasName: AnsiString read FAlias; property Descent: Integer read GetDescent; property FontUsed: Boolean read FUsed write FUsed; property Width[Index:Word]: Integer read GetWidth; end; TPDFStandardFont = class(TPDFFont) private FStyle: TPDFStdFont; function GetAscent: Integer; override; function GetDescent: Integer; override; function GetWidth(Index: Word): Integer; override; public constructor Create(Engine: TPDFEngine; Style: TPDFStdFont); procedure Save; override; end; TPDFTrueTypeFont = class; TPDFTrueTypeSubsetFont = class (TPDFFont) private FParent: TPDFTrueTypeFont; FLast :Integer; FIndexes: array[32..127] of integer; FUnicodes: array[32..127] of Word; procedure GetToUnicodeStream(Alias: AnsiString; Stream: TStream; AliasName:AnsiString); protected procedure Save;override; function GetAscent: Integer; override; function GetDescent: Integer; override; function GetWidth(Index: Word): Integer; override; public constructor Create(Engine:TPDFEngine; AParent: TPDFTrueTypeFont); destructor Destroy;override; property Parent: TPDFTrueTypeFont read FParent; end; TPDFTrueTypeFont = class(TPDFFont) private FIsEmbedded: Boolean; FFirstChar: Integer; FLastChar: Integer; FFontName: String; FFontNameAddon:AnsiString; FFontStyle: TFontStyles; FASCIIList: array [ 32..127 ] of Integer; FUsedList: array [32.. 127] of Boolean; FExtendedFonts: array of TPDFTrueTypeSubsetFont; FCurrentIndex:Integer; FCurrentChar: Integer; FManager: TTrueTypeManager; function GetAscent: Integer; override; function GetDescent: Integer; override; function GetWidth(Index: Word): Integer; override; function GetSubset(Index: Integer): TPDFFont; function GetNewCharByIndex(Index: Integer): PNewCharInfo; function GetNewCharByUnicode(Index: Word): PNewCharInfo; public constructor Create(Engine:TPDFEngine;FontName:String; FontStyle: TFontStyles;IsEmbedded:Boolean); destructor Destroy; override; procedure Save; override; procedure FillUsed(s:AnsiString); override; procedure UsedChar(Ch:Byte); override; procedure SetAllASCII; override; procedure MarkAsUsed(Glyph:PGlyphInfo;Unicode:Word); property Name: String read FFontName; property Style: TFontStyles read FFontStyle; property SubsetFont[Index: Integer]:TPDFFont read GetSubset; property CharByIndex[Index: Integer]: PNewCharInfo read GetNewCharByIndex; property CharByUnicode[Index: Word]: PNewCharInfo read GetNewCharByUnicode; end; TPDFFonts = class (TPDFManager) private FNonEmbeddedFonts: TStringList; function GetTrueTypeFont(FontName: String; Style: TFontStyles): TPDFFont; procedure SetNonEmbeddedFonts(const Value: TStringList); protected procedure Save;override; procedure Clear;override; function GetCount:Integer; override; public constructor Create(PDFEngine: TPDFEngine); destructor Destroy; override; function GetFontByInfo(StdFont:TPDFStdFont): TPDFFont;overload; function GetFontByInfo(FontName: String; Style: TFontStyles): TPDFFont; overload; property NonEmbeddedFonts: TStringList read FNonEmbeddedFonts write SetNonEmbeddedFonts; end; implementation uses llPDFResources, {$ifdef WIN64} System.ZLib, System.ZLibConst, {$else} llPDFFlate, {$endif} llPDFSecurity, llPDFCrypt; const PDFStandardFontNames: array [ 0..13 ] of AnsiString = ( 'Helvetica', 'Helvetica-Bold', 'Helvetica-Oblique', 'Helvetica-BoldOblique', 'Times-Roman', 'Times-Bold', 'Times-Italic', 'Times-BoldItalic', 'Courier', 'Courier-Bold', 'Courier-Oblique', 'Courier-BoldOblique', 'Symbol', 'ZapfDingbats' ); const StdFontAliases : array[0..13] of AnsiString = ( 'Helv','HeBo','HeOb','HeBO','TiRo','TiBo','TiIt','TiBI','Cour','CoBo','CoOb','CoBO','Symb','ZaDb'); StWidth: array [ 0..13, 0..268 ] of word = ( ( 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 350, 558, 350, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 350, 611, 350, 350, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 350, 500, 667, 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, 333, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, 556, 333, 333, 333, 278, 500, 500, 167, 333, 222, 584, 333, 400 ), ( 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 350, 558, 350, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 350, 611, 350, 350, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 350, 500, 667, 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, 333, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, 611, 333, 333, 333, 278, 611, 611, 167, 333, 278, 584, 333, 400 ), ( 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 350, 558, 350, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 350, 611, 350, 350, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 350, 500, 667, 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, 333, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, 556, 333, 333, 333, 278, 500, 500, 167, 333, 222, 584, 333, 400 ), ( 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 350, 558, 350, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 350, 611, 350, 350, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 350, 500, 667, 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, 333, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, 611, 333, 333, 333, 278, 611, 611, 167, 333, 278, 584, 333, 400 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 350, 500, 350, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 350, 611, 350, 350, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 350, 444, 722, 250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333, 333, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444, 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500, 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500, 611, 333, 333, 333, 278, 556, 556, 167, 333, 278, 564, 333, 400 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 350, 500, 350, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 350, 667, 350, 350, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 350, 444, 722, 250, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 333, 747, 333, 333, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750, 750, 500, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389, 389, 389, 722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722, 611, 556, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500, 556, 500, 667, 333, 333, 333, 278, 556, 556, 167, 333, 278, 570, 333, 400 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 350, 500, 350, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 350, 556, 350, 350, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 350, 389, 556, 250, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 333, 760, 333, 333, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750, 750, 500, 611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, 722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556, 611, 500, 500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444, 500, 444, 556, 333, 333, 333, 278, 500, 500, 167, 333, 278, 675, 333, 400 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 350, 500, 350, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 350, 611, 350, 350, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 350, 389, 611, 250, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 333, 747, 333, 333, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750, 750, 500, 667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389, 389, 389, 722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611, 611, 500, 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444, 500, 444, 611, 333, 333, 333, 278, 556, 556, 167, 333, 278, 606, 333, 400 ), ( 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600 ), ( 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600 ), ( 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600 ), ( 600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, 0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ), ( 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, 0, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) ); StdFontAscent: array [ 0..13 ] of Integer = ( 728, 728, 728, 728, 613, 633, 613, 633, 693, 677, 694, 677, 1000, 1000 ); StdFontDescent: array [ 0..13 ] of Integer = ( -210, -210, -208, -210, -188, -209, -188, -216, -216, -216, -216, -217, 0, 0 ); type TFontInfo = record FontName: String; Style: TFontStyles; Error: Boolean; DefItalic: Boolean; DefBold: Boolean; Step: Integer; end; function FontTestBack ( const Enum: ENUMLOGFONTEX; Nop:Pointer; FT: DWORD; var FI: TFontInfo ): Integer; stdcall; var Bold, Italic: Boolean; Er: Boolean; begin if FT <> TRUETYPE_FONTTYPE then begin Result := 1; Exit; end; if StrComp(PChar(fi.FontName) ,Enum.elfLogFont.lfFaceName)<>0 then fi.FontName := Enum.elfLogFont.lfFaceName; Bold := Enum.elfLogFont.lfWeight >= 600; Italic := Enum.elfLogFont.lfItalic <> 0; if FI.Step = 0 then begin FI.DefItalic := Italic; FI.DefBold := Bold; end; Inc ( FI.Step ); Er := False; if ( fsbold in FI.Style ) <> Bold then Er := True; if ( fsItalic in FI.Style ) <> Italic then Er := True; FI.Error := Er; if Er then Result := 1 else Result := 0; end; function FontTest ( var FontName: String; var FontStyle: TFontStyles ): Boolean; var LogFont: TLogFont; DC: HDC; ST: TFontStyles; FI: TFontInfo; begin FI.FontName := FontName; FI.Style := FontStyle; FillChar ( LogFont, SizeOf ( LogFont ), 0 ); LogFont.lfCharSet := DEFAULT_CHARSET; StrPCopy( LogFont.lfFaceName, FI.FontName ); FI.Step := 0; FI.Error := True; ST := FI.Style; DC := GetDC ( 0 ); try EnumFontFamiliesEx ( DC, LogFont, @FontTestBack, FInt ( @FI ), 0 ); if FI.Step <> 0 then if FI.Error then begin if fsItalic in FI.Style then begin FI.Style := FontStyle - [ fsItalic ]; EnumFontFamiliesEx ( DC, LogFont, @FontTestBack, FInt ( @FI ), 0 ); end; if FI.Error then if fsBold in FontStyle then begin FI.Style := FI.Style - [ fsBold ]; EnumFontFamiliesEx ( DC, LogFont, @FontTestBack, FInt ( @FI ), 0 ); end; if FI.Error then begin FI.Style := [ ]; EnumFontFamiliesEx ( DC, LogFont, @FontTestBack, FInt ( @FI ), 0 ); end; if FI.Error then begin FI.Style := [ ]; if FI.DefItalic then FI.Style := FI.Style + [ fsItalic ]; if FI.DefBold then FI.Style := FI.Style + [ fsBold ]; EnumFontFamiliesEx ( DC, LogFont, @FontTestBack, FInt ( @FI ), 0 ); end; end; finally ReleaseDC ( 0, DC ); end; Result := not FI.Error; if FI.FontName <> FontName then FontName := FI.FontName; if not FI.Error then FontStyle := FI.Style; end; { TPDFTrueTypeFont } constructor TPDFTrueTypeFont.Create(Engine:TPDFEngine;FontName:String; FontStyle: TFontStyles;IsEmbedded:Boolean); var i: Integer; begin inherited Create( Engine); FFontName := FontName; FFontStyle := FontStyle; FIsEmbedded := IsEmbedded; FManager := TTrueTypeManager.Create(FontName,FontStyle); FCurrentIndex := 0; FCurrentChar := 128; FFirstChar := 128; FLastChar := 31; for I := 1 to 6 do FFontNameAddon := FFontNameAddon + AnsiChar(Random(26)+65); for i:= 32 to 127 do FASCIIList[i] := FManager.GetIdxByUnicode(i); end; destructor TPDFTrueTypeFont.Destroy; var i: integer; begin for i := 0 to length(FExtendedFonts) -1 do if FExtendedFonts[i]<> nil then FExtendedFonts[i].Free; FManager.Free; inherited; end; procedure TPDFTrueTypeFont.FillUsed(s:AnsiString); var I: Integer; B: Byte; begin FUsed := True; for I := 1 to Length ( s ) do begin b := Ord ( s [ i ] ); if (B> 31 ) and (B < 128) then begin if not FUsedList[B] then begin FUsedList[B] := True; if B > FLastChar then FLastChar := B; if B < FFirstChar then FFirstChar := B; end; end; end; end; function TPDFTrueTypeFont.GetAscent: Integer; begin Result := FManager.Ascent; end; function TPDFTrueTypeFont.GetDescent: Integer; begin Result := FManager.Descent; end; function TPDFTrueTypeFont.GetWidth(Index: Word): Integer; var C: PGlyphInfo; begin if (Index < 128) and (Index > 31) and (FASCIIList[Index] > 0) then C := FManager.Glyphs[FASCIIList[Index]] else C := FManager.GlyphByUnicode[Index]; Result := C^.CharInfo.Width; end; procedure TPDFTrueTypeFont.Save; var I: Integer; Wid: AnsiString; MS, MS1: TMemoryStream; CS: TCompressionStream; RS: Integer; FFN: AnsiString; FontDescriptorID: Integer; FontFileID: Integer; UsedArray:array [0..127] of byte; begin for i := 0 to Length(FExtendedFonts) -1 do FExtendedFonts[i].Save; if FFirstChar > FLastChar then Exit; FontFileID := -1; if FIsEmbedded then begin MS := TMemoryStream.Create; try FillChar(UsedArray,Length(UsedArray),0); for i := 32 to 127 do if FUsedList[i] then UsedArray[i] := 1; FManager.PrepareASCIIFont(@UsedArray,MS); RS := MS.Size; MS.Position := 0; MS1 := TMemoryStream.Create; try CS := TCompressionStream.Create ( clMax, MS1 ); try CS.CopyFrom ( MS, MS.Size ); finally CS.Free; end; MS.Clear; FontFileID := Eng.GetNextID; Eng.StartObj ( FontFileID ); Eng.SaveToStream ( '/Filter /FlateDecode /Length ' + IStr ( CalcAESSize(Eng.SecurityInfo.State, MS1.Size ) ) + ' /Length1 ' + IStr ( RS ) ); Eng.StartStream; ms1.Position := 0; CryptStreamToStream(Eng.SecurityInfo, MS1, Eng.Stream, FontFileID); Eng.CloseStream; finally MS1.Free; end; finally MS.Free; end; end; Wid := ''; for I := FFirstChar to FLastChar do begin if FUsedList[i] then Wid := Wid + IStr ( FManager.Glyphs [ FASCIIList[i]].CharInfo.Width ) + ' ' else Wid := Wid + '0 '; if I mod 16 = 0 then Wid := Wid + #13#10; end; FFN := FManager.PostScriptName; if FIsEmbedded then FFN := FFontNameAddon+'+'+FFN; FontDescriptorID := Eng.GetNextID; Eng.StartObj ( FontDescriptorID ); Eng.SaveToStream ( '/Type /FontDescriptor' ); Eng.SaveToStream ( '/Ascent ' + IStr ( FManager.Ascent ) ); Eng.SaveToStream ( '/CapHeight 666' ); Eng.SaveToStream ( '/Descent ' + IStr ( FManager.Descent ) ); Eng.SaveToStream ( '/Flags 32' ); Eng.SaveToStream ( '/FontBBox [' + RectToStr(FManager.FontBox ) + ']' ); Eng.SaveToStream ( '/FontName /' + FFN ); Eng.SaveToStream ( '/ItalicAngle ' + IStr ( FManager.ItalicAngle ) ); Eng.SaveToStream ( '/StemV 87' ); if Eng.PDFACompatibile then Eng.SaveToStream ( '/MissingWidth 0' ); if FIsEmbedded then Eng.SaveToStream ( '/FontFile2 ' + IStr ( FontFileID ) + ' 0 R' ); Eng.CloseObj; Eng.StartObj ( ID ); Eng.SaveToStream ( '/Type /Font' ); Eng.SaveToStream ( '/Subtype /TrueType' ); Eng.SaveToStream ( '/BaseFont /' + FFN ); Eng.SaveToStream ( '/FirstChar ' + IStr ( FFirstChar ) ); Eng.SaveToStream ( '/LastChar ' + IStr ( FLastChar ) ); Eng.SaveToStream ( '/Encoding /WinAnsiEncoding'); Eng.SaveToStream ( '/FontDescriptor ' + IStr ( FontDescriptorID ) + ' 0 R' ); Eng.SaveToStream ( '/Widths [' + Wid + ']' ); Eng.CloseObj; end; procedure TPDFTrueTypeFont.SetAllASCII; var I: Integer; begin FUsed := True; FFirstChar := 32; FLastChar := 127; for I := 32 to 127 do FUsedList[i] := True; end; procedure TPDFTrueTypeFont.UsedChar(Ch:Byte); begin if (Ch < 32) or (Ch >127) then Exit; FUsed := True; FUsedList[Ch] := True; if Ch > FLastChar then FLastChar := Ch; if Ch < FFirstChar then FFirstChar := Ch; end; procedure TPDFTrueTypeFont.MarkAsUsed(Glyph:PGlyphInfo;Unicode:Word); var idx : Integer; begin if Glyph^.ExtUsed then Exit; Glyph^.ExtUsed := true; FUsed := True; idx := (FarInteger(Pointer(Glyph)) - FarInteger(Pointer(FManager.Glyphs[0]))) div sizeof(TGlyphInfo); if (Unicode > 0 ) and (Unicode < 128) then begin Glyph^.CharInfo.NewCharacter := AnsiChar(Unicode); Glyph^.CharInfo.FontIndex := 0; end else begin if FCurrentChar = 128 then begin inc(FCurrentIndex); SetLength(FExtendedFonts,FCurrentIndex); FExtendedFonts[FCurrentIndex - 1] := TPDFTrueTypeSubsetFont.Create(Eng,Self); FExtendedFonts[FCurrentIndex - 1].FAlias := FAlias+'+'+IStr(FCurrentIndex); FCurrentChar := 32; end; Glyph^.CharInfo.NewCharacter := AnsiChar(FCurrentChar); Glyph^.CharInfo.FontIndex := FCurrentIndex; FExtendedFonts[FCurrentIndex - 1].FLast := FCurrentChar; FExtendedFonts[FCurrentIndex - 1].FIndexes[FCurrentChar] := idx; if Unicode > 0 then FExtendedFonts[FCurrentIndex - 1].FUnicodes[FCurrentChar] := Unicode else if Glyph^.Unicode < $FFFF then FExtendedFonts[FCurrentIndex - 1].FUnicodes[FCurrentChar] := Glyph^.Unicode else FExtendedFonts[FCurrentIndex - 1].FUnicodes[FCurrentChar] := 0; inc(FCurrentChar); end; end; function TPDFTrueTypeFont.GetSubset(Index: Integer): TPDFFont; begin if (Index< 0) or (Index >=Length(FExtendedFonts)) then raise EPDFException.Create(SOutOfRange); result := FExtendedFonts[Index]; end; function TPDFTrueTypeFont.GetNewCharByIndex(Index: Integer): PNewCharInfo; var Glyph: PGlyphInfo; begin Glyph := FManager.Glyphs[Index]; MarkAsUsed(Glyph,0); Result := Pointer(Glyph); end; function TPDFTrueTypeFont.GetNewCharByUnicode(Index: Word): PNewCharInfo; var Glyph: PGlyphInfo; begin Glyph := FManager.GlyphByUnicode[Index]; MarkAsUsed(Glyph,Index); Result := Pointer(Glyph); end; { TPDFStandardFont } constructor TPDFStandardFont.Create(Engine: TPDFEngine; Style: TPDFStdFont); begin inherited Create( Engine); FStyle := Style; end; function TPDFStandardFont.GetAscent: Integer; begin Result := StdFontAscent [ Ord(FStyle) ]; end; function TPDFStandardFont.GetDescent: Integer; begin Result := StdFontDescent [ Ord(FStyle) ] end; function TPDFStandardFont.GetWidth(Index: Word): Integer; begin if Word(Index) >= 256 then raise EPDFException.Create(SOutOfRange); Result := stWidth [ Ord(FStyle), Word(Index) ]; end; procedure TPDFStandardFont.Save; begin Eng.StartObj ( ID ); Eng.SaveToStream ( '/Type /Font' ); Eng.SaveToStream ( '/Subtype /Type1' ); Eng.SaveToStream ( '/BaseFont /' + PDFStandardFontNames [ Ord(FStyle) ] ); if FStyle < stdfSymbol then Eng.SaveToStream ( '/Encoding /WinAnsiEncoding' ); Eng.SaveToStream ( '/FirstChar 32' ); Eng.SaveToStream ( '/LastChar 255' ); Eng.CloseObj; end; { TPDFFont } procedure TPDFFont.FillUsed(s:AnsiString); begin end; procedure TPDFFont.SetAllASCII; begin end; procedure TPDFFont.UsedChar(Ch:Byte); begin end; { TPDFFonts } constructor TPDFFonts.Create(PDFEngine: TPDFEngine); begin inherited Create(PDFEngine); FNonEmbeddedFonts := TStringList.Create; end; destructor TPDFFonts.Destroy; begin inherited; FNonEmbeddedFonts.Free; end; procedure TPDFFonts.Clear; var I: Integer; begin for i := 0 to Length(FEngine.Resources.Fonts) -1 do TPDFFont(FEngine.Resources.Fonts[I]).Free; FEngine.Resources.Fonts := nil; inherited; end; function TPDFFonts.GetCount: Integer; begin Result := Length(FEngine.Resources.Fonts); end; function TPDFFonts.GetFontByInfo(StdFont: TPDFStdFont): TPDFFont; var i: Integer; FNT: TPDFStandardFont; begin for i := 0 to Length(FEngine.Resources.Fonts) -1 do if FEngine.Resources.Fonts[i] is TPDFStandardFont then if TPDFStandardFont(FEngine.Resources.Fonts[i]).FStyle = StdFont then begin Result := FEngine.Resources.Fonts[i] as TPDFFont; Exit; end; FNT := TPDFStandardFont.Create(FEngine, StdFont); i := Length(FEngine.Resources.Fonts); SetLength(FEngine.Resources.Fonts, i+1); FEngine.Resources.Fonts[i] := FNT; FEngine.Resources.LastFont := FNT; FNT.FAlias := StdFontAliases[Ord(StdFont)]; Result := FNT; end; function TPDFFonts.GetFontByInfo(FontName: String; Style: TFontStyles): TPDFFont; var FA :String; begin Style := Style - [fsUnderline, fsStrikeOut]; FA:=UpperCase(FontName); Result :=GetTrueTypeFont(FontName, Style); end; function TPDFFonts.GetTrueTypeFont(FontName: String; Style: TFontStyles): TPDFFont; var i: Integer; FS: TFontStyles; FN: String; TT: TPDFFont; IsEmbedded: Boolean; begin FontName := UpperCase(FontName); for i := 0 to Length(FEngine.Resources.Fonts) -1 do if FEngine.Resources.Fonts[i] is TPDFTrueTypeFont then if (TPDFTrueTypeFont(FEngine.Resources.Fonts[i]).Style = Style) and (TPDFTrueTypeFont(FEngine.Resources.Fonts[i]).Name = FontName) then begin Result := FEngine.Resources.Fonts[i] as TPDFFont; Exit; end; FS := Style; FN := FontName; if not FontTest ( FN, FS ) then begin Result := GetFontByInfo ( 'Arial', Style ); Exit; end; if FN <> FontName then FontName := UpperCase(FN); if FS <> Style then for i := 0 to Length(FEngine.Resources.Fonts) - 1 do if FEngine.Resources.Fonts[i] is TPDFTrueTypeFont then if (TPDFTrueTypeFont(FEngine.Resources.Fonts[i]).Style = FS) and (TPDFTrueTypeFont(FEngine.Resources.Fonts[i]).Name = FontName) then begin Result := FEngine.Resources.Fonts[i] as TPDFFont; Exit; end; IsEmbedded := True; for I := 0 to FNonEmbeddedFonts.Count - 1 do if UpperCase(FNonEmbeddedFonts [ I ] ) = FontName then begin IsEmbedded := False; Break; end; TT := TPDFTrueTypeFont.Create(FEngine, FontName, FS, IsEmbedded); i := Length(FEngine.Resources.Fonts); SetLength(FEngine.Resources.Fonts, i+1); FEngine.Resources.Fonts[i] := TT; TT.FAlias := 'TT'+IStr(i); Result := TT; FEngine.Resources.LastFont := TT; end; procedure TPDFFonts.Save; var i: Integer; begin for i := 0 to Length(FEngine.Resources.Fonts) -1 do if TPDFFont(FEngine.Resources.Fonts[i]).FontUsed then FEngine.SaveObject(FEngine.Resources.Fonts[i]); end; procedure TPDFFonts.SetNonEmbeddedFonts(const Value: TStringList); begin FNonEmbeddedFonts.Assign(Value); end; { TPDFTrueTypeSubsetFont } constructor TPDFTrueTypeSubsetFont.Create(Engine:TPDFEngine; AParent: TPDFTrueTypeFont); begin inherited Create(Engine); FParent := AParent; end; destructor TPDFTrueTypeSubsetFont.Destroy; begin inherited; end; function TPDFTrueTypeSubsetFont.GetAscent: Integer; begin Result := FParent.Ascent; end; function TPDFTrueTypeSubsetFont.GetDescent: Integer; begin Result := FParent.Descent; end; function TPDFTrueTypeSubsetFont.GetWidth(Index: Word): Integer; begin Result := FParent.GetWidth(Index); end; procedure TPDFTrueTypeSubsetFont.GetToUnicodeStream ( Alias: AnsiString; Stream: TStream;AliasName:AnsiString); var SS: TAnsiStringList; I: Integer; begin ss := TAnsiStringList.Create ; try ss.Add ( '/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << ' ); ss.Add ( '/Registry (' + AliasName + ') /Ordering ('+AliasName+'+) /Supplement 0 >> def' ); ss.Add ( '/CMapName /' + AliasName + '+0 def' ); ss.Add ( '/CMapType 2 def' ); ss.Add ( '1 begincodespacerange <' + ByteToHex ( 32 ) + '> <' + ByteToHex ( FLast ) + '> endcodespacerange' ); {$ifdef UNICODE} ss.LineBreak :=''; {$endif} ss.Add ( IStr ( FLast -31 ) + ' beginbfchar' ); for i:= 32 to FLast do ss.Add ( '<' + ByteToHex ( i ) + '> <' + WordToHex ( FUnicodes [ i ] ) + '>' ); ss.Add ( 'endbfchar' ); ss.Add ( 'endcmap CMapName currentdict /CMap defineresource pop end end' ); ss.SaveToStream(Stream); finally ss.Free; end; end; procedure TPDFTrueTypeSubsetFont.Save; var I, L: Integer; Wid: AnsiString; MS, MS1: TMemoryStream; CS: TCompressionStream; RS: Integer; FFN: AnsiString; FontDescriptorID: Integer; FontFileID, UnicodeID: Integer; begin FFN := FParent.FFontNameAddon+'+'+FParent.FManager.PostScriptName; UnicodeID := Eng.GetNextID; Eng.StartObj ( UnicodeID ); MS1 := TMemoryStream.Create; try CS := TCompressionStream.Create ( clDefault, MS1 ); try GetToUnicodeStream ( AliasName, CS, FFN ); finally CS.Free; end; Eng.SaveToStream ( '/Filter /FlateDecode /Length ' + IStr ( CalcAESSize( Eng.SecurityInfo.State,MS1.Size ) ) ); Eng.StartStream; ms1.Position := 0; CryptStreamToStream(Eng.SecurityInfo, MS1, Eng.Stream, UnicodeID); Eng.CloseStream; finally MS1.Free; end; Eng.CloseObj; MS := TMemoryStream.Create; try FParent.FManager.PrepareFont(@FIndexes,FLast - 31, MS); RS := MS.Size; MS.Position := 0; MS1 := TMemoryStream.Create; try CS := TCompressionStream.Create ( clMax, MS1 ); try CS.CopyFrom ( MS, MS.Size ); finally CS.Free; end; MS.Clear; FontFileID := Eng.GetNextID; Eng.StartObj ( FontFileID ); Eng.SaveToStream ( '/Filter /FlateDecode /Length ' + IStr ( CalcAESSize( Eng.SecurityInfo.State,MS1.Size ) ) + ' /Length1 ' + IStr ( RS ) ); Eng.StartStream; ms1.Position := 0; CryptStreamToStream(Eng.SecurityInfo, MS1, Eng.Stream, FontFileID); Eng.CloseStream; finally MS1.Free; end; finally MS.Free; end; Wid := ''; L := 1; for I := 32 to FLast do begin Wid := Wid + IStr ( FParent.FManager.Glyphs [ FIndexes[i]].CharInfo.Width ) + ' '; inc(L); if L mod 16 = 0 then Wid := Wid + #13#10; end; FontDescriptorID := Eng.GetNextID; Eng.StartObj ( FontDescriptorID ); Eng.SaveToStream ( '/Type /FontDescriptor' ); Eng.SaveToStream ( '/Ascent ' + IStr ( FParent.FManager.Ascent ) ); Eng.SaveToStream ( '/CapHeight 666' ); Eng.SaveToStream ( '/Descent ' + IStr ( FParent.FManager.Descent ) ); Eng.SaveToStream ( '/Flags 32' ); Eng.SaveToStream ( '/FontBBox [' + RectToStr(FParent.FManager.FontBox ) + ']' ); Eng.SaveToStream ( '/FontName /' + FFN ); Eng.SaveToStream ( '/ItalicAngle ' + IStr ( FParent.FManager.ItalicAngle ) ); Eng.SaveToStream ( '/StemV 87' ); if Eng.PDFACompatibile then Eng.SaveToStream ( '/MissingWidth 0' ); Eng.SaveToStream ( '/FontFile2 ' + IStr ( FontFileID ) + ' 0 R' ); Eng.CloseObj; Eng.StartObj ( ID ); Eng.SaveToStream ( '/Type /Font' ); Eng.SaveToStream ( '/Subtype /TrueType' ); Eng.SaveToStream ( '/BaseFont /' + FFN ); Eng.SaveToStream ( '/FirstChar 32'); Eng.SaveToStream ( '/LastChar ' + IStr ( FLast ) ); Eng.SaveToStream ( '/Encoding /WinAnsiEncoding' ); Eng.SaveToStream ( '/ToUnicode ' + GetRef ( UnicodeID ) ); Eng.SaveToStream ( '/FontDescriptor ' + IStr ( FontDescriptorID ) + ' 0 R' ); Eng.SaveToStream ( '/Widths [' + Wid + ']' ); Eng.CloseObj; end; end.
unit Mock.Getter.TrimBasics.Factory; interface uses Classes, SysUtils, Windows, OSFile; type TTrimProgress = record CurrentPartition: Integer; PartitionCount: Integer; end; TTrimSynchronization = record IsUIInteractionNeeded: Boolean; ThreadToSynchronize: TThread; Progress: TTrimProgress; end; TTrimBasicsToInitialize = record PaddingLBA: Integer; LBAPerCluster: Cardinal; StartLBA: UInt64; end; TTrimBasicsGetter = class(TOSFile) public function IsPartitionMyResponsibility: Boolean; function GetTrimBasicsToInitialize: TTrimBasicsToInitialize; end; TrimBasicsGetterFactory = class public class function GetSuitableTrimBasicsGetter(FileToGetAccess: String): TTrimBasicsGetter; end; EUnknownPartition = class(Exception); implementation function TTrimBasicsGetter.IsPartitionMyResponsibility: Boolean; begin result := true; end; function TTrimBasicsGetter.GetTrimBasicsToInitialize: TTrimBasicsToInitialize; begin result.StartLBA := 0; result.LBAPerCluster := 1; result.PaddingLBA := 0; end; class function TrimBasicsGetterFactory.GetSuitableTrimBasicsGetter( FileToGetAccess: String): TTrimBasicsGetter; begin result := TTrimBasicsGetter.Create(FileToGetAccess); end; end.
unit JAWSCommon; interface uses SysUtils, Windows, Messages, Registry, StrUtils; const DLL_MESSAGE_ID_NAME: PChar = 'VA 508 / Freedom Scientific - JAWS Communication Message ID'; DISPATCHER_WINDOW_CLASS = 'TfrmVA508JawsDispatcherHiddenWindow'; DISPATCHER_WINDOW_TITLE = 'VA 508 JAWS Dispatcher Window'; DISPATCHER_WINDOW_TITLE_LEN = length(DISPATCHER_WINDOW_TITLE); DLL_MAIN_WINDOW_CLASS = 'TfrmVA508HiddenJawsMainWindow'; DLL_WINDOW_TITLE = 'VA 508 JAWS Window'; DLL_WINDOW_TITLE_LEN = length(DLL_WINDOW_TITLE); // format = prefix : varname : <index #> : +/- <data> DLL_WINDOW_DELIM = ':'; DLL_WINDOW_OFFSET = '='; DLL_WINDOW_LENGTH = ','; DLL_CAPTION_MAX = 4090; // max num of chars per title MAX_CHARS_IN_WINDOW_HANDLE = 12; DLL_CAPTION_LIMIT = DLL_CAPTION_MAX - MAX_CHARS_IN_WINDOW_HANDLE; DLL_DATA_WINDOW_CLASS = 'TfrmVA508HiddenJawsDataWindow'; JAWS_MESSAGE_GET_DLL_WITH_FOCUS = 1; var MessageID: UINT = 0; procedure ErrorCheckClassName(obj: TObject; ClassName: string); procedure SendReturnValue(Window: HWND; Value: Longint); implementation uses VAUtils; procedure ErrorCheckClassName(obj: TObject; ClassName: string); begin if obj.ClassName <> ClassName then Raise Exception.Create(obj.ClassName + ' should have been ' + ClassName); end; procedure SendReturnValue(Window: HWND; Value: Longint); var idx1, idx2: integer; header: string; bump: byte; begin header := GetWindowTitle(Window); idx1 := pos(':', header); if idx1 < 1 then idx1 := length(header) + 1; idx2 := posex(':', header, idx1+1); if idx2<=idx1 then idx2 := idx1+1; bump := StrToIntDef(copy(header, idx1+1, idx2 - idx1 - 1), 0); if bump > 254 then bump := 1 else inc(bump); header := copy(header,1,idx1-1) + ':' + inttostr(bump) + ':' + IntToStr(Value); SetWindowText(Window, PChar(header)); end; procedure InitializeCommonData; begin MessageID := RegisterWindowMessage(DLL_MESSAGE_ID_NAME); end; initialization InitializeCommonData; finalization end.
unit Ths.Erp.Database.Table.SysGridColPercent; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TSysGridColPercent = class(TTable) private FTableName: TFieldDB; FColumnName: TFieldDB; FMaxValue: TFieldDB; FColorBar: TFieldDB; FColorBarBack: TFieldDB; FColorBarText: TFieldDB; FColorBarTextActive: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property TableName1: TFieldDB read FTableName write FTableName; Property ColumnName: TFieldDB read FColumnName write FColumnName; property MaxValue: TFieldDB read FMaxValue write FMaxValue; property ColorBar: TFieldDB read FColorBar write FColorBar; property ColorBarBack: TFieldDB read FColorBarBack write FColorBarBack; property ColorBarText: TFieldDB read FColorBarText write FColorBarText; property ColorBarTextActive: TFieldDB read FColorBarTextActive write FColorBarTextActive; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TSysGridColPercent.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_grid_col_percent'; SourceCode := '1'; FTableName := TFieldDB.Create('table_name', ftString, ''); FColumnName := TFieldDB.Create('column_name', ftString, ''); FMaxValue := TFieldDB.Create('max_value', ftFloat, 0); FColorBar := TFieldDB.Create('color_bar', ftInteger, 0); FColorBarBack := TFieldDB.Create('color_bar_back', ftInteger, 0); FColorBarText := TFieldDB.Create('color_bar_text', ftInteger, 0); FColorBarTextActive := TFieldDB.Create('color_bar_text_active', ftInteger, 0); end; procedure TSysGridColPercent.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FTableName.FieldName, TableName + '.' + FColumnName.FieldName, TableName + '.' + FMaxValue.FieldName, TableName + '.' + FColorBar.FieldName, TableName + '.' + FColorBarBack.FieldName, TableName + '.' + FColorBarText.FieldName, TableName + '.' + FColorBarTextActive.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'TABLE NAME'; Self.DataSource.DataSet.FindField(FColumnName.FieldName).DisplayLabel := 'COLUMN NAME'; Self.DataSource.DataSet.FindField(FMaxValue.FieldName).DisplayLabel := 'MAX VALUE'; Self.DataSource.DataSet.FindField(FColorBar.FieldName).DisplayLabel := 'COLOR BAR'; Self.DataSource.DataSet.FindField(FColorBarBack.FieldName).DisplayLabel := 'COLOR BAR BACK'; Self.DataSource.DataSet.FindField(FColorBarText.FieldName).DisplayLabel := 'COLOR BAR TEXT'; Self.DataSource.DataSet.FindField(FColorBarTextActive.FieldName).DisplayLabel := 'COLOR BAR TEXT ACTIVE'; end; end; end; procedure TSysGridColPercent.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FTableName.FieldName, TableName + '.' + FColumnName.FieldName, TableName + '.' + FMaxValue.FieldName, TableName + '.' + FColorBar.FieldName, TableName + '.' + FColorBarBack.FieldName, TableName + '.' + FColorBarText.FieldName, TableName + '.' + FColorBarTextActive.FieldName, ' 40::varchar as test ' ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FTableName.Value := FormatedVariantVal(FieldByName(FTableName.FieldName).DataType, FieldByName(FTableName.FieldName).Value); FColumnName.Value := FormatedVariantVal(FieldByName(FColumnName.FieldName).DataType, FieldByName(FColumnName.FieldName).Value); FMaxValue.Value := FormatedVariantVal(FieldByName(FMaxValue.FieldName).DataType, FieldByName(FMaxValue.FieldName).Value); FColorBar.Value := FormatedVariantVal(FieldByName(FColorBar.FieldName).DataType, FieldByName(FColorBar.FieldName).Value); FColorBarBack.Value := FormatedVariantVal(FieldByName(FColorBarBack.FieldName).DataType, FieldByName(FColorBarBack.FieldName).Value); FColorBarText.Value := FormatedVariantVal(FieldByName(FColorBarText.FieldName).DataType, FieldByName(FColorBarText.FieldName).Value); FColorBarTextActive.Value := FormatedVariantVal(FieldByName(FColorBarTextActive.FieldName).DataType, FieldByName(FColorBarTextActive.FieldName).Value); List.Add(Self.Clone()); Next; end; EmptyDataSet; Close; end; end; end; procedure TSysGridColPercent.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FTableName.FieldName, FColumnName.FieldName, FMaxValue.FieldName, FColorBar.FieldName, FColorBarBack.FieldName, FColorBarText.FieldName, FColorBarTextActive.FieldName ]); NewParamForQuery(QueryOfInsert, FTableName); NewParamForQuery(QueryOfInsert, FColumnName); NewParamForQuery(QueryOfInsert, FMaxValue); NewParamForQuery(QueryOfInsert, FColorBar); NewParamForQuery(QueryOfInsert, FColorBarBack); NewParamForQuery(QueryOfInsert, FColorBarText); NewParamForQuery(QueryOfInsert, FColorBarTextActive); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSysGridColPercent.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FTableName.FieldName, FColumnName.FieldName, FMaxValue.FieldName, FColorBar.FieldName, FColorBarBack.FieldName, FColorBarText.FieldName, FColorBarTextActive.FieldName ]); NewParamForQuery(QueryOfUpdate, FTableName); NewParamForQuery(QueryOfUpdate, FColumnName); NewParamForQuery(QueryOfUpdate, FMaxValue); NewParamForQuery(QueryOfUpdate, FColorBar); NewParamForQuery(QueryOfUpdate, FColorBarBack); NewParamForQuery(QueryOfUpdate, FColorBarText); NewParamForQuery(QueryOfUpdate, FColorBarTextActive); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TSysGridColPercent.Clone():TTable; begin Result := TSysGridColPercent.Create(Database); Self.Id.Clone(TSysGridColPercent(Result).Id); FTableName.Clone(TSysGridColPercent(Result).FTableName); FColumnName.Clone(TSysGridColPercent(Result).FColumnName); FMaxValue.Clone(TSysGridColPercent(Result).FMaxValue); FColorBar.Clone(TSysGridColPercent(Result).FColorBar); FColorBarBack.Clone(TSysGridColPercent(Result).FColorBarBack); FColorBarText.Clone(TSysGridColPercent(Result).FColorBarText); FColorBarTextActive.Clone(TSysGridColPercent(Result).FColorBarTextActive); end; end.
{ Some routines for file and directory handling on a higher level than those provided by the RTS. Copyright (C) 2000-2005 Free Software Foundation, Inc. Author: Frank Heckenbach <frank@pascal.gnu.de> This file is part of GNU Pascal. GNU Pascal is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Pascal is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Pascal; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, if you link this file with files compiled with a GNU compiler to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. } {$gnu-pascal,I-} {$if __GPC_RELEASE__ < 20030412} {$error This unit requires GPC release 20030412 or newer.} {$endif} unit FileUtils; interface uses GPC; type TStringProc = procedure (const s: String); { Finds all files matching the given Mask in the given Directory and all subdirectories of it. The matching is done using all wildcards and brace expansion, like MultiFileNameMatch does. For each file found, FileAction is executed. For each directory found (including `.' and `..' if they match the Mask!), DirAction is executed. If MainDirFirst is True, this happens before processing the files in the directory and below, otherwise afterwards. (The former is useful, e.g., if this is used to copy a directory tree and DirAction does a MkDir, while the latter behaviour is required when removing a directory tree and DirAction does a RmDir.) Both FileAction and DirAction can be nil in which case nothing is done for files or directories found, respectively. (If DirAction is nil, the value of DirsFirst does not matter.) Of course, FileAction and DirAction may also be identical. The procedure leaves InOutRes set in case of any error. If FileAction or DirAction return with InOutRes set, FindFiles recognizes this and returns immediately. } procedure FindFiles (const Directory, Mask: String; MainDirFirst: Boolean; FileAction, DirAction: TStringProc); attribute (iocritical); { Creates the directory given by Path and all directories in between that are necessary. Does not report an error if the directory already exists, but, of course, if it cannot be created because of missing permissions or because Path already exists as a file. } procedure MkDirs (const Path: String); attribute (iocritical); { Removes Path if empty as well as any empty parent directories. Does not report an error if the directory is not empty. } procedure RmDirs (const Path: String); attribute (iocritical); { Copies the file Source to Dest, overwriting Dest if it exists and can be written to. Returns any errors in IOResult. If Mode >= 0, it will change the permissions of Dest to Mode immediately after creating it and before writing any data to it. That's useful, e.g., if Dest is not meant to be world-readable, because if you'd do a ChMod after FileCopy, you might leave the data readable (depending on the umask) during the copying. If Mode < 0, Dest will be set to the same permissions Source has. In any case, Dest will be set to the modification time of Source after copying. On any error, the destination file is erased. This is to avoid leaving partial files in case of full file systems (one of the most common reasons for errors). } procedure FileCopy (const Source, Dest: String; Mode: Integer); attribute (iocritical); { Creates a backup of FileName in the directory BackupDirectory or, if BackupDirectory is empty, in the directory of FileName. Errors are returned in IOResult (and on any error, no partial backup file is left), but if FileName does not exist, this does *not* count as an error (i.e., BackupFile will just return without setting IOResult then). If OnlyUserReadable is True, the backup file will be given only user-read permissions, nothing else. The name chosen for the backup depends on the Simple and Short parameters. The short names will fit into 8+3 characters (whenever possible), while the long ones conform to the conventions used by most GNU tools. If Simple is True, a simple backup file name will be used, and previous backups under the same name will be overwritten (if possible). Otherwise, backups will be numbered, where the number is chosen to be larger than all existing backups, so it will be unique and increasing in chronological order. In particular: Simple Short Backup name True True Base name of FileName plus '.bak' False True Base name of FileName plus '.b' plus a number True False Base name plus extension of FileName plus '~' False False Base name plus extension of FileName plus '.~', a number and '~' } procedure BackupFile (const FileName, BackupDirectory: String; Simple, Short, OnlyUserReadable: Boolean); attribute (iocritical); implementation procedure FindFiles (const Directory, Mask: String; MainDirFirst: Boolean; FileAction, DirAction: TStringProc); var Dir: DirPtr; FileName, FullName: TString; begin Dir := OpenDir (Directory); while InOutRes = 0 do begin FileName := ReadDir (Dir); if FileName = '' then Break; FullName := Directory + DirSeparator + FileName; if DirectoryExists (FullName) then begin if MainDirFirst and (@DirAction <> nil) and MultiFileNameMatch (Mask, FileName) then DirAction (FullName); if (InOutRes = 0) and (FileName <> DirSelf) and (FileName <> DirParent) then FindFiles (FullName, Mask, MainDirFirst, FileAction, DirAction); if not MainDirFirst and (@DirAction <> nil) and MultiFileNameMatch (Mask, FileName) then DirAction (FullName) end else if (@FileAction <> nil) and MultiFileNameMatch (Mask, FileName) then FileAction (FullName) end; CloseDir (Dir) end; procedure MkDirs (const Path: String); var NewPath: TString; begin if InOutRes <> 0 then Exit; NewPath := DirFromPath (RemoveDirSeparator (Path)); if NewPath <> Path then MkDirs (NewPath); if not DirectoryExists (Path) then MkDir (Path) end; procedure RmDirs (const Path: String); var NewPath: TString; begin if InOutRes <> 0 then Exit; RmDir (Path); { We use IOResult which clears the error status because an error here should not be reported to the caller because RmDir will fail for the first non-empty parent directory. } if IOResult = 0 then begin NewPath := DirFromPath (RemoveDirSeparator (Path)); if NewPath <> Path then RmDirs (NewPath) end end; procedure FileCopy (const Source, Dest: String; Mode: Integer); var Buf: array [1 .. $10000] of Byte; BytesRead: SizeType; f, g: File; b: BindingType; i: Integer; begin if InOutRes <> 0 then Exit; SetReturnAddress (ReturnAddress (0)); Assign (f, Source); Reset (f, 1); b := Binding (f); Assign (g, Dest); Rewrite (g, 1); RestoreReturnAddress; if Mode < 0 then Mode := b.Mode; ChMod (g, Mode); while not EOF (f) and (InOutRes = 0) do begin BlockRead (f, Buf, SizeOf (Buf), BytesRead); BlockWrite (g, Buf, BytesRead) end; Close (f); SetFileTime (g, GetUnixTime (Null), b.ModificationTime); Close (g); if InOutRes <> 0 then begin i := IOResult; Erase (g); InOutRes := i end end; procedure BackupFile (const FileName, BackupDirectory: String; Simple, Short, OnlyUserReadable: Boolean); var c, j, nr, r, Mode: Integer; BackupPath, p, p1, p2, n, e, g: TString; Buf: GlobBuffer; begin if (InOutRes <> 0) or not FileExists (FileName) then Exit; if OSDosFlag then Short := True; FSplit (FileName, p, n, e); if BackupDirectory <> '' then p := ForceAddDirSeparator (BackupDirectory); if Short then p := p + n else p := p + n + e; if Simple then if Short then BackupPath := p + '.bak' else BackupPath := p + '~' else begin if Short then begin p1 := p + '.b'; p2 := '' end else begin p1 := p + '.~'; p2 := '~' end; c := 0; Glob (Buf, QuoteFileName (p1, WildCardChars) + '*' + p2); for j := 1 to Buf.Result^.Count do begin g := Buf.Result^[j]^; if IsPrefix (p1, g) then begin Delete (g, 1, Length (p1)); if IsSuffix (p2, g) then begin Delete (g, Length (g) - Length (p2) + 1); Val (g, nr, r); if r = 0 then c := Max (c, nr) end end end; GlobFree (Buf); repeat Inc (c); BackupPath := p1 + StringOfChar ('0', Ord (Short and (c < 10))) + Integer2String (c) + p2 until not FileExists (BackupPath) end; if OnlyUserReadable then Mode := fm_UserReadable else Mode := -1; SetReturnAddress (ReturnAddress (0)); FileCopy (FileName, BackupPath, Mode); RestoreReturnAddress end; end.
unit tr.com.isisbilisim.types; interface uses Generics.Defaults, SysUtils; type Nullable<T> = record private FValue: T; FHasValue: IInterface; function GetValue: T; function GetHasValue: Boolean; public constructor Create(AValue: T); function GetValueOrDefault: T; overload; function GetValueOrDefault(Default: T): T; overload; property HasValue: Boolean read GetHasValue; property Value: T read GetValue; class operator NotEqual(const ALeft, ARight: Nullable<T>): Boolean; class operator Equal(ALeft, ARight: Nullable<T>): Boolean; class operator Implicit(Value: Nullable<T>): T; class operator Implicit(Value: T): Nullable<T>; class operator Explicit(Value: Nullable<T>): T; end; procedure SetFlagInterface(var Intf: IInterface); implementation function NopAddref(inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopRelease(inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopQueryInterface(inst: Pointer; const IID: TGUID; out Obj) : HResult; stdcall; begin Result := E_NOINTERFACE; end; const FlagInterfaceVTable: array [0 .. 2] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease ); FlagInterfaceInstance: Pointer = @FlagInterfaceVTable; procedure SetFlagInterface(var Intf: IInterface); begin Intf := IInterface(@FlagInterfaceInstance); end; { Nullable<T> } constructor Nullable<T>.Create(AValue: T); begin FValue := AValue; SetFlagInterface(FHasValue); end; class operator Nullable<T>.Equal(ALeft, ARight: Nullable<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if ALeft.HasValue and ARight.HasValue then begin Comparer := TEqualityComparer<T>.Default; Result := Comparer.Equals(ALeft.Value, ARight.Value); end else Result := ALeft.HasValue = ARight.HasValue; end; class operator Nullable<T>.Explicit(Value: Nullable<T>): T; begin Result := Value.Value; end; function Nullable<T>.GetHasValue: Boolean; begin Result := FHasValue <> nil; end; function Nullable<T>.GetValue: T; begin if not HasValue then raise Exception.Create('Invalid operation, Nullable type has no value'); Result := FValue; end; function Nullable<T>.GetValueOrDefault: T; begin if HasValue then Result := FValue else Result := Default (T); end; function Nullable<T>.GetValueOrDefault(Default: T): T; begin if not HasValue then Result := Default else Result := FValue; end; class operator Nullable<T>.Implicit(Value: Nullable<T>): T; begin Result := Value.Value; end; class operator Nullable<T>.Implicit(Value: T): Nullable<T>; begin Result := Nullable<T>.Create(Value); end; class operator Nullable<T>.NotEqual(const ALeft, ARight: Nullable<T>): Boolean; var Comparer: IEqualityComparer<T>; begin if ALeft.HasValue and ARight.HasValue then begin Comparer := TEqualityComparer<T>.Default; Result := not Comparer.Equals(ALeft.Value, ARight.Value); end else Result := ALeft.HasValue <> ARight.HasValue; end; end.
unit uCycleCommandHandler; interface uses uCommandHandler, uTokenizer, dmConnection; type TCycleCommandHandler = class(TCommandHandler) function HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; override; end; implementation uses SysUtils, Windows, Forms; { TCycleCommandHandler } function TCycleCommandHandler.HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; var Channel, Reason: string; begin Reason := ''; if ATokenizer.HasMoreTokens then Channel := ATokenizer.NextToken else Channel := ATarget; if Channel[1] <> '#' then Channel := '#' + Channel; Reason := ATokenizer.NextToken; AConnection.Cycle(Channel, Reason); end; initialization TCommandHandlerFactory.GetInstance.RegisterClass('/cycle', TCycleCommandHandler); end.
unit MediaStorage.Transport.Samba; interface uses SysUtils,Classes, Windows, dInterfacesObjectFileStorage,MediaStorage.Transport; type //Транспорт средствами Microsoft Network (samba) TRecordObjectTransport_NetworkPath =class (TRecordObjectTransportBase,IRecordObjectTransport) private FFileName: string; public function TypeCode: byte; //Название транспорта function Name: string; //Доставляет файл и дает на него ссылку function GetReader: IRecordObjectReader; //Создает экземпляр писателя файла function GetWriter: IRecordObjectWriter; function FileExists: boolean; function FileSize: int64; function ConnectionString: string; function NeedCopying: boolean; constructor Create(const aConnectionString: string); end; function IsNetworkPath(const aFileName: string): boolean; implementation uses uTrace,uBaseUtils; const SearchResultTitles: array [boolean] of string = ('Не найден','Найден'); function ExtractHostFromNetAddress(const aNetAddress: string): string; var i: integer; begin if (not (Length(aNetAddress)>2)) or (not (aNetAddress[1]='\')) or (not (aNetAddress[2]='\')) then raise Exception.Create('Указанный адрес не является сетевым'); i:=3; while i<=Length(aNetAddress) do begin if i<Length(aNetAddress) then if aNetAddress[i+1]='\' then break; inc(i); end; result:=Copy(aNetAddress,3,i-3+1); end; function IsNetworkPath(const aFileName: string): boolean; begin result:=(Length(aFileName)>2) and (aFileName[1]='\') and (aFileName[2]='\'); end; type TRecordObjectReader_NetworkPath = class (TRecordObjectFileBase,IRecordObjectReader) private FFileName: string; FStream : TFileStream; public function GetStream: TStream; function GetWholeFile: string; procedure PrepareFromBegin; procedure PrepareFromEnd; constructor Create(const aFileName: string); destructor Destroy; override; end; TRecordObjectWriter_NetworkPath = class (TRecordObjectFileBase,IRecordObjectWriter) private FStream : TFileStream; public procedure WriteAndCommit(const aData; aSize: integer); overload; //Записывает данные из указанного файла в себя и сразу же закрывает сессию. Можно вызывать только 1 раз procedure WriteAndCommit(const aFileName: string); overload; constructor Create(const aFileName: string); destructor Destroy; override; end; TSambaStream = class (TFileStream) public function Read(var Buffer; Count: Longint): Longint; override; end; { TRecordObjectTransport_NetworkPath } function TRecordObjectTransport_NetworkPath.ConnectionString: string; begin result:=FFileName; end; constructor TRecordObjectTransport_NetworkPath.Create(const aConnectionString: string); begin inherited Create; FFileName:=aConnectionString; end; function TRecordObjectTransport_NetworkPath.FileExists: boolean; const aMethodName = 'TRecordObjectTransport_NetworkPath.FileExists'; var aTraceID: cardinal; begin aTraceID:=TraceProcBegin(aMethodName); try result:=SysUtils.FileExists(FFileName); TraceLine('Поиск файла '+FFileName+':'+SearchResultTitles[result]); finally TraceProcEnd(aMethodName,aTraceID); end; end; function TRecordObjectTransport_NetworkPath.FileSize: int64; const aMethodName = 'TRecordObjectTransport_NetworkPath.FileExists'; var aTraceID: cardinal; begin aTraceID:=TraceProcBegin(aMethodName); try result:=fsiBaseUtils.GetFileSize(FFileName); finally TraceProcEnd(aMethodName,aTraceID); end; end; function TRecordObjectTransport_NetworkPath.GetReader: IRecordObjectReader; begin result:=TRecordObjectReader_NetworkPath.Create(FFileName); end; function TRecordObjectTransport_NetworkPath.TypeCode: byte; begin result:=0; end; function TRecordObjectTransport_NetworkPath.GetWriter: IRecordObjectWriter; begin result:=TRecordObjectWriter_NetworkPath.Create(FFileName); end; function TRecordObjectTransport_NetworkPath.NeedCopying: boolean; begin result:=false; end; function TRecordObjectTransport_NetworkPath.Name: string; begin if IsNetworkPath(FFileName) then result:='MS Network (Samba)' else result:='Local File'; end; { TRecordObjectReader_NetworkPath } constructor TRecordObjectReader_NetworkPath.Create(const aFileName: string); begin FFileName:=aFileName; FStream:=TSambaStream.Create(aFileName,fmOpenRead or fmShareDenyNone); end; destructor TRecordObjectReader_NetworkPath.Destroy; begin FreeAndNil(FStream); inherited; end; function TRecordObjectReader_NetworkPath.GetStream : TStream; begin result:=FStream; end; function TRecordObjectReader_NetworkPath.GetWholeFile: string; begin result:=FStream.FileName; end; procedure TRecordObjectReader_NetworkPath.PrepareFromBegin; begin end; procedure TRecordObjectReader_NetworkPath.PrepareFromEnd; begin end; { TRecordObjectWriter_NetworkPath } constructor TRecordObjectWriter_NetworkPath.Create( const aFileName: string); begin FStream:=TFileStream.Create(aFileName,fmCreate); end; destructor TRecordObjectWriter_NetworkPath.Destroy; begin inherited; FreeAndNil(FStream); end; procedure TRecordObjectWriter_NetworkPath.WriteAndCommit(const aFileName: string); var aSourceStream : TFileStream; begin if FStream=nil then raise Exception.Create('Сессия записи закрыта'); aSourceStream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyNone); try FStream.CopyFrom(aSourceStream,0); finally aSourceStream.Free; end; FreeAndNil(FStream); end; procedure TRecordObjectWriter_NetworkPath.WriteAndCommit(const aData; aSize: integer); begin if FStream=nil then raise Exception.Create('Сессия записи закрыта'); FStream.WriteBuffer(aData,aSize); FreeAndNil(FStream); end; { TSambaStream } function TSambaStream.Read(var Buffer; Count: Integer): Longint; begin // if Count<=sizeof(HV_FRAME_HEAD) then // uTrace.TraceLine(Format('12 байт от позиции %d',[Position])); result:=inherited Read(Buffer,Count); end; end.
procedure TForm1.btnGoClick(Sender: TObject); var nums: TList; a, b: integer; r: double; begin nums := TList.Create; for a := 2 to 100 do begin for b := 2 to 100 do begin r := power(a, b); if nums.IndexOf(Pointer(r)) = -1 then nums.Add(Pointer(r)); end; end; MessageDlg('Length', Format('%d', [nums.Count]), mtInformation, [mbOK], -1); end;
unit PreAchatLocDAOU; interface uses PreAchatLocDTOU, System.Generics.Collections; type TListPreAchatLocDTO=TObjectList<TPreAchatLocDTO>; Type TPreAchatLocDAO =class(TObject) function getPreAchatsLoc:TListPreAchatLocDTO; function getNbr:integer; function Saveloc(vpreachatlocDTO:TPreAchatLocDTO): integer; function isExist(vpreachatLocDTO:TPreAchatLocDTO):boolean; Function GetNewId:Integer; function delete(vpreachatLocDTO:TPreAchatLocDTO): integer; function hasDetail(vpreachatDTO: TPreAchatLocDTO): boolean; end; implementation uses FireDAC.Comp.Client, MainU, System.SysUtils, FormatDateSQLiteU, FMX.Dialogs, System.UITypes; { TPreAchatLocDAO } function TPreAchatLocDAO.delete(vpreachatLocDTO: TPreAchatLocDTO): integer; begin if MessageDlg('Voulais vous vraiment supprimer?',TMsgDlgType.mtConfirmation, [TmsgDlgBtn.mbOK,TmsgDlgBtn.mbCancel],0)=mrok then begin if not hasDetail(vpreachatLocDTO) then begin with TFdQuery.Create(nil) do begin try if isExist(vpreachatLocDTO) then begin Connection:=Main.oconnection; SQL.Add('delete from tpreachatloc '); SQL.Add(' where idpreachatloc='+QuotedStr(IntToStr(vpreachatLocDTO.idpreachatloc))); ExecSQL; end; finally DisposeOf; end; end; end else showmessage('Vous devais supprimer les détails'); end; end; function TPreAchatLocDAO.getNbr: integer; begin with TFdQuery.Create(nil) do begin try Connection:=Main.oconnection; SQL.Add('select count(*) as nbr from tpreachatloc '); Active:=true; result:=FieldByName('nbr').AsInteger; Active:=false; finally Active:=false; DisposeOf; end; end; end; function TPreAchatLocDAO.GetNewId: Integer; begin with TFdQuery.Create(nil) do begin try Connection:=Main.oconnection; SQL.Add('select max(idpreachatloc) as id from tpreachatloc '); Active:=true; result:=FieldByName('id').AsInteger+1; Active:=false; finally Active:=false; DisposeOf; end; end; end; function TPreAchatLocDAO.getPreAchatsLoc: TListPreAchatLocDTO; var preachatlist: TListPreAchatLocDTO; i: integer; vNbrLike:integer; vpreachatLocDTO:TPreAchatLocDTO; begin result:=TListPreAchatLocDTO.Create(); with TFDQuery.Create(nil) do begin i:=0; Connection:=Main.oconnection; SQL.Add('select * from tpreachatloc '); Active:=true; First; while not Eof do begin vpreachatLocDTO:=TPreAchatLocDTO.create(FieldByName('idpreachatloc').AsInteger); vpreachatLocDTO.idpreachatloc:=FieldByName('idpreachatloc') .AsInteger; vpreachatLocDTO.despreachatloc:=FieldByName('despreachatloc') .AsString; vpreachatLocDTO.date_:=FieldByName('date_') .AsString; result.Add(vpreachatLocDTO); Next; Inc(i); end; end; end; function TPreAchatLocDAO.hasDetail(vpreachatDTO: TPreAchatLocDTO): boolean; begin with TFdQuery.Create(nil) do begin try Connection:=Main.oconnection; SQL.Add('select count(*) as nbr '+ ' from rpreachatloc where rpreachatloc.idpreachatloc='+ QuotedStr(IntToStr(vpreachatDTO.idpreachatloc))); Active:=true; result:=Fields[0].AsInteger>0; finally Active:=false; DisposeOf; end; end; end; function TPreAchatLocDAO.isExist(vpreachatLocDTO:TPreAchatLocDTO):boolean; begin with TFdQuery.Create(nil) do begin result:=false; try Connection:=Main.oconnection; SQL.Add('select count(*) from tpreachatloc where idpreachatloc='+ QuotedStr(IntToStr(vpreachatLocDTO.idpreachatloc))); Active:=true; result:=Fields[0].AsInteger>0; Active:=false; finally Active:=false; DisposeOf; end; end; end; function TPreAchatLocDAO.Saveloc(vpreachatlocDTO: TPreAchatLocDTO): integer; begin with TFdQuery.Create(nil) do begin try if not isExist(vpreachatlocDTO) then begin Connection:=Main.oconnection; SQL.Add('insert into tpreachatloc(idpreachatloc,despreachatloc,date_)'); SQL.Add( 'values ('); SQL.Add(QuotedStr(IntToStr(vpreachatlocDTO.idpreachatloc))+','); SQL.Add(QuotedStr(vpreachatlocDTO.despreachatloc)+','); SQL.Add(QuotedStr(FormatDateSQLite.Create.FormatDate(Now))+')'); ExecSQL; end else begin Connection:=Main.oconnection; SQL.Add('update tpreachatloc set '); SQL.Add('despreachatloc='+QuotedStr(vpreachatlocDTO.despreachatloc)+','); SQL.Add('date_='+QuotedStr(FormatDateSQLite.Create.FormatDate(Now))); SQL.Add(' where idpreachatloc='+QuotedStr(IntToStr(vpreachatlocDTO.idpreachatloc))); ExecSQL; end; finally DisposeOf; end; end; end; end.
program functions; function Fibonacci(n: integer): longint; var i: integer; p, q, r: longint; begin if n <= 0 then Fibonacci := 0 else begin q := 0; r := 1; for i := 2 to n do begin p := q; q := r; r := p + q end; Fibonacci := r end; end; var x: integer; y: longint; begin write('Enter number: '); read(x); y := Fibonacci(x); writeln(y); end.
{$R-} {$Q-} unit ncEncSha256; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2; type TncEnc_sha256 = class(TncEnc_hash) protected LenHi, LenLo: longword; Index: DWord; CurrentHash: array [0 .. 7] of DWord; HashBuffer: array [0 .. 63] of byte; procedure Compress; public class function GetAlgorithm: string; override; class function GetHashSize: integer; override; class function SelfTest: boolean; override; procedure Init; override; procedure Final(var Digest); override; procedure Burn; override; procedure Update(const Buffer; Size: longword); override; end; { ****************************************************************************** } { ****************************************************************************** } implementation uses ncEncryption; function SwapDWord(a: DWord): DWord; begin Result := ((a and $FF) shl 24) or ((a and $FF00) shl 8) or ((a and $FF0000) shr 8) or ((a and $FF000000) shr 24); end; procedure TncEnc_sha256.Compress; var a, b, c, d, e, f, g, h, t1, t2: DWord; W: array [0 .. 63] of DWord; i: longword; begin Index := 0; a := CurrentHash[0]; b := CurrentHash[1]; c := CurrentHash[2]; d := CurrentHash[3]; e := CurrentHash[4]; f := CurrentHash[5]; g := CurrentHash[6]; h := CurrentHash[7]; Move(HashBuffer, W, Sizeof(HashBuffer)); for i := 0 to 15 do W[i] := SwapDWord(W[i]); for i := 16 to 63 do W[i] := (((W[i - 2] shr 17) or (W[i - 2] shl 15)) xor ((W[i - 2] shr 19) or (W[i - 2] shl 13)) xor (W[i - 2] shr 10)) + W[i - 7] + (((W[i - 15] shr 7) or (W[i - 15] shl 25)) xor ((W[i - 15] shr 18) or (W[i - 15] shl 14)) xor (W[i - 15] shr 3)) + W[i - 16]; { Non-optimised version for i:= 0 to 63 do begin t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + K[i] + W[i]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= g; g:= f; f:= e; e:= d + t1; d:= c; c:= b; b:= a; a:= t1 + t2; end; } t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $428A2F98 + W[0]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $71374491 + W[1]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $B5C0FBCF + W[2]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $E9B5DBA5 + W[3]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $3956C25B + W[4]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $59F111F1 + W[5]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $923F82A4 + W[6]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $AB1C5ED5 + W[7]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $D807AA98 + W[8]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $12835B01 + W[9]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $243185BE + W[10]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $550C7DC3 + W[11]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $72BE5D74 + W[12]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $80DEB1FE + W[13]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $9BDC06A7 + W[14]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $C19BF174 + W[15]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $E49B69C1 + W[16]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $EFBE4786 + W[17]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $0FC19DC6 + W[18]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $240CA1CC + W[19]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $2DE92C6F + W[20]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4A7484AA + W[21]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5CB0A9DC + W[22]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $76F988DA + W[23]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $983E5152 + W[24]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $A831C66D + W[25]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $B00327C8 + W[26]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $BF597FC7 + W[27]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $C6E00BF3 + W[28]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $D5A79147 + W[29]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $06CA6351 + W[30]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $14292967 + W[31]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $27B70A85 + W[32]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $2E1B2138 + W[33]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $4D2C6DFC + W[34]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $53380D13 + W[35]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $650A7354 + W[36]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $766A0ABB + W[37]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $81C2C92E + W[38]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $92722C85 + W[39]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $A2BFE8A1 + W[40]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $A81A664B + W[41]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $C24B8B70 + W[42]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $C76C51A3 + W[43]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $D192E819 + W[44]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $D6990624 + W[45]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $F40E3585 + W[46]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $106AA070 + W[47]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $19A4C116 + W[48]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $1E376C08 + W[49]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $2748774C + W[50]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $34B0BCB5 + W[51]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $391C0CB3 + W[52]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4ED8AA4A + W[53]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5B9CCA4F + W[54]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $682E6FF3 + W[55]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; t1 := h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $748F82EE + W[56]; t2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := t1 + t2; d := d + t1; t1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $78A5636F + W[57]; t2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := t1 + t2; c := c + t1; t1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $84C87814 + W[58]; t2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := t1 + t2; b := b + t1; t1 := e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $8CC70208 + W[59]; t2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e := t1 + t2; a := a + t1; t1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $90BEFFFA + W[60]; t2 := (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d := t1 + t2; h := h + t1; t1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $A4506CEB + W[61]; t2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c := t1 + t2; g := g + t1; t1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $BEF9A3F7 + W[62]; t2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b := t1 + t2; f := f + t1; t1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $C67178F2 + W[63]; t2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := t1 + t2; e := e + t1; CurrentHash[0] := CurrentHash[0] + a; CurrentHash[1] := CurrentHash[1] + b; CurrentHash[2] := CurrentHash[2] + c; CurrentHash[3] := CurrentHash[3] + d; CurrentHash[4] := CurrentHash[4] + e; CurrentHash[5] := CurrentHash[5] + f; CurrentHash[6] := CurrentHash[6] + g; CurrentHash[7] := CurrentHash[7] + h; FillChar(W, Sizeof(W), 0); FillChar(HashBuffer, Sizeof(HashBuffer), 0); end; class function TncEnc_sha256.GetAlgorithm: string; begin Result := 'SHA256'; end; class function TncEnc_sha256.GetHashSize: integer; begin Result := 256; end; class function TncEnc_sha256.SelfTest: boolean; const Test1Out: array [0 .. 31] of byte = ($BA, $78, $16, $BF, $8F, $01, $CF, $EA, $41, $41, $40, $DE, $5D, $AE, $22, $23, $B0, $03, $61, $A3, $96, $17, $7A, $9C, $B4, $10, $FF, $61, $F2, $00, $15, $AD); Test2Out: array [0 .. 31] of byte = ($24, $8D, $6A, $61, $D2, $06, $38, $B8, $E5, $C0, $26, $93, $0C, $3E, $60, $39, $A3, $3C, $E4, $59, $64, $FF, $21, $67, $F6, $EC, $ED, $D4, $19, $DB, $06, $C1); var TestHash: TncEnc_sha256; TestOut: array [0 .. 31] of byte; begin TestHash := TncEnc_sha256.Create(nil); TestHash.Init; TestHash.UpdateStr('abc'); TestHash.Final(TestOut); Result := boolean(CompareMem(@TestOut, @Test1Out, Sizeof(Test1Out))); TestHash.Init; TestHash.UpdateStr('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'); TestHash.Final(TestOut); Result := boolean(CompareMem(@TestOut, @Test2Out, Sizeof(Test2Out))) and Result; TestHash.Free; end; procedure TncEnc_sha256.Init; begin Burn; CurrentHash[0] := $6A09E667; CurrentHash[1] := $BB67AE85; CurrentHash[2] := $3C6EF372; CurrentHash[3] := $A54FF53A; CurrentHash[4] := $510E527F; CurrentHash[5] := $9B05688C; CurrentHash[6] := $1F83D9AB; CurrentHash[7] := $5BE0CD19; fInitialized := true; end; procedure TncEnc_sha256.Burn; begin LenHi := 0; LenLo := 0; Index := 0; FillChar(HashBuffer, Sizeof(HashBuffer), 0); FillChar(CurrentHash, Sizeof(CurrentHash), 0); fInitialized := false; end; procedure TncEnc_sha256.Update(const Buffer; Size: longword); var PBuf: ^byte; begin if not fInitialized then raise EncEnc_hash.Create('Hash not initialized'); Inc(LenHi, Size shr 29); Inc(LenLo, Size * 8); if LenLo < (Size * 8) then Inc(LenHi); PBuf := @Buffer; while Size > 0 do begin if (Sizeof(HashBuffer) - Index) <= DWord(Size) then begin Move(PBuf^, HashBuffer[Index], Sizeof(HashBuffer) - Index); Dec(Size, Sizeof(HashBuffer) - Index); Inc(PBuf, Sizeof(HashBuffer) - Index); Compress; end else begin Move(PBuf^, HashBuffer[Index], Size); Inc(Index, Size); Size := 0; end; end; end; procedure TncEnc_sha256.Final(var Digest); begin if not fInitialized then raise EncEnc_hash.Create('Hash not initialized'); HashBuffer[Index] := $80; if Index >= 56 then Compress; PDWord(@HashBuffer[56])^ := SwapDWord(LenHi); PDWord(@HashBuffer[60])^ := SwapDWord(LenLo); Compress; CurrentHash[0] := SwapDWord(CurrentHash[0]); CurrentHash[1] := SwapDWord(CurrentHash[1]); CurrentHash[2] := SwapDWord(CurrentHash[2]); CurrentHash[3] := SwapDWord(CurrentHash[3]); CurrentHash[4] := SwapDWord(CurrentHash[4]); CurrentHash[5] := SwapDWord(CurrentHash[5]); CurrentHash[6] := SwapDWord(CurrentHash[6]); CurrentHash[7] := SwapDWord(CurrentHash[7]); Move(CurrentHash, Digest, Sizeof(CurrentHash)); Burn; end; end.
unit SelTabla; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGrids, Db, DBTables, LibApp, IniFiles, IB_Components, TB2Dock, TB2Toolbar, TB2ExtItems, TBXExtItems, TBX, IB_Grid, RxPlacemnt, ImgList, IB_NavigationBar, IB_UpdateBar, TB2Item, RzButton; {**************************************************************** Definicion de Objetos que se regresaran ****************************************************************} type TfrmSelTabla = class(TForm) pnlMain: TPanel; pnlTop: TPanel; edtKey: TEdit; idsSelect: TIB_DataSource; Dock971: TTBXDock; Toolbar971: TTBXToolbar; tlbAceptar: TTBXItem; tlbCancelar: TTBXItem; ImageList2: TImageList; IB_Grid1: TIB_Grid; iqrSelect: TIB_Query; TBControlItem1: TTBControlItem; IB_NavigationBar1: TIB_NavigationBar; TBXSeparatorItem1: TTBXSeparatorItem; tlbCodigo: TRzBitBtn; tlbDescri: TRzBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tlbAceptarClick(Sender: TObject); procedure tlbCancelarClick(Sender: TObject); procedure Aceptar; procedure Cancelar; procedure PorCodigo; procedure PorDescri; procedure FormActivate(Sender: TObject); procedure GoPrior; procedure GoNext; procedure tlbCodigoClick(Sender: TObject); procedure tlbDescriClick(Sender: TObject); procedure edtKeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtKeyChange(Sender: TObject); private { Private declarations } fldCodigo:String; fldDescri:String; TablaAnt:String; Codigox:String; Descrix:String; public { Public declarations } Tabla:String; {Tabla de la base de datos} Campo:Integer; {1=Por Codigo, 2=Por Descripcion} Codigo:String; // Valor del codigo (entrada y salida) Descri:String; // Texto de la descripcion (entrada y salida) Valores:array[1..20] of Variant; Param1:String; Param2:String; procedure Open; end; var frmSelTabla: TfrmSelTabla; implementation uses Main, DM_MBA; {$R *.DFM} procedure TfrmSelTabla.FormActivate(Sender: TObject); begin Open; edtKey.SetFocus; end; procedure TfrmSelTabla.Open; begin if Tabla = 'MBA10001' then begin TablaAnt := Tabla; fldCodigo := 'NUMAGENTE'; fldDescri := 'NOMBAGEN'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT NUMAGENTE,NOMBAGEN FROM MBA10001'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10002' then begin TablaAnt := Tabla; fldCodigo := 'CODCTEPROV'; fldDescri := 'RAZSOCIAL'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT CODCTEPROV,RAZSOCIAL,NUMAGENTE,LIMCREDCTE FROM MBA10002 WHERE EDOACTCTE <> 2'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10004' then begin TablaAnt := Tabla; fldCodigo := 'CODPRODSER'; fldDescri := 'DESCRIPPRO'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT CODPRODSER,DESCRIPPRO,PCIOVTA1,PCIOVTA2,PCIOVTA3,PCIOVTA4,PCIOVTA5,PCIOVTA6,PCIOVTA7,PCIOVTA8,PCIOVTA9,PCIOVTA10,CODFAMILIA FROM MBA10004 WHERE EDOACTPROD <> 2'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10006' then begin TablaAnt := Tabla; fldCodigo := 'NumTipoDoc'; fldDescri := 'NombreTipo'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT NumTipoDoc,NombreTipo FROM MBA10006'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10013' then begin TablaAnt := Tabla; fldCodigo := 'CODCTEPROV'; fldDescri := 'NOMBPROVEE'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT CODCTEPROV,NOMBPROVEE FROM MBA10013 WHERE EDOACTPROV <> 2'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10021' then begin TablaAnt := Tabla; fldCodigo := 'NUMTABLA'; fldDescri := 'DESCRIPCIO'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT TIPOTABLA,NUMTABLA,DESCRIPCIO FROM MBA10021 WHERE TIPOTABLA = ?PARAM01'); iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.TIPOTABLA'); iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10040' then begin TablaAnt := Tabla; fldCodigo := 'CODFAM'; fldDescri := 'DESCRIPFAM'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT CODFAM,DESCRIPFAM FROM MBA10040 WHERE EDOACTFAM <> 2'); //Solo activas iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('CODIGO='+fldCodigo+';'); iqrSelect.OrderingItems.Add('DESCRI='+fldDescri+';'); end; if Tabla = 'MBA10050' then begin TablaAnt := Tabla; fldCodigo := 'IDSUCURSAL'; fldDescri := 'NOMBRE'; iqrSelect.SQL.Clear; iqrSelect.sql.add ('SELECT IDSUCURSAL,NOMBRE FROM MBA10050 '); //Solo activas iqrSelect.KeyLinks.Clear; iqrSelect.KeyLinks.Add (Tabla+'.'+fldCodigo); iqrSelect.OrderingItems.Clear; iqrSelect.OrderingItems.Add('IDSUCURSAL='+fldCodigo+';'); iqrSelect.OrderingItems.Add('NOMBRE='+fldDescri+';'); end; iqrSelect.OrderingLinks.Clear; iqrSelect.OrderingLinks.Add('IDSUCURSAL=1'); iqrSelect.OrderingLinks.Add('NOMBRE=2'); iqrSelect.OrderingItemNo := Campo; case Campo of 1: tlbCodigo.Down := True; 2: tlbDescri.down := True; end; Caption := 'Selección de Datos [' + Tabla +']'; iqrSelect.Prepare; if length(Param1) > 0 then begin iqrSelect.ParamByName('PARAM01').AsString := Param1; end; iqrSelect.Open; case Campo of 1: edtKey.Text := Codigo; 2: edtKey.Text := Descri; end; end; procedure TfrmSelTabla.FormClose(Sender: TObject; var Action: TCloseAction); begin iqrSelect.Close; end; procedure TfrmSelTabla.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: Aceptar; VK_ESCAPE: Cancelar; VK_F3: PorCodigo; VK_F4: PorDescri; VK_UP: GoPrior; VK_DOWN: GoNext; end; end; procedure TfrmSelTabla.GoPrior; begin if not (iqrSelect.bof) then iqrSelect.Prior; end; procedure TfrmSelTabla.GoNext; begin if not (iqrSelect.eof) then iqrSelect.Next; end; procedure TfrmSelTabla.Aceptar; var i:Integer; begin if iqrSelect.State in [dssInsert,dssEdit] then iqrSelect.Post; Codigo := iqrSelect.fieldbyname(fldCodigo).AsString; Descri := iqrSelect.fieldbyname(fldDescri).AsString; for i:= 0 to iqrSelect.FieldCount - 1 do begin Valores [i+1] := iqrSelect.Fields[i].AsVariant; end; ModalResult := mrOk; end; procedure TfrmSelTabla.Cancelar; begin Codigo := ''; Descri := ''; ModalResult := mrCancel; end; procedure TfrmSelTabla.PorCodigo; begin if tlbCodigo.Down then begin iqrSelect.OrderingItemNo := 1; Campo := 1; end; end; procedure TfrmSelTabla.PorDescri; begin if tlbDescri.Down then begin iqrSelect.OrderingItemNo := 2; Campo := 2; end; end; procedure TfrmSelTabla.tlbAceptarClick(Sender: TObject); begin Aceptar; end; procedure TfrmSelTabla.tlbCancelarClick(Sender: TObject); begin Cancelar; end; procedure TfrmSelTabla.tlbCodigoClick(Sender: TObject); begin Campo := 1; PorCodigo; end; procedure TfrmSelTabla.tlbDescriClick(Sender: TObject); begin PorDescri; end; procedure TfrmSelTabla.edtKeyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_F3: PorCodigo; VK_F4: PorDescri; end; end; procedure TfrmSelTabla.edtKeyChange(Sender: TObject); var Campox:String; begin case Campo of 1: Campox := fldCodigo; 2: Campox := fldDescri; end; iqrSelect.Locate (Campox, edtKey.Text, [lopCaseInsensitive, lopPartialKey, lopFindNearest] ); end; end.
(* LLVM Triple Class > Author: Aleksey A. Naumov [alexey.naumov@gmail.com] > License: BSD *) unit llvmTriple; interface uses SysUtils; type TArchType = ( atUnknownArch, atARM, atCellSPU, atHexagon, atMIPS, atMIPSel, atMIPS64, atMIPS64el, atMSP430, atPPC, atPPC64, atR600, atSparc, atSparCV9, atTCE, atThumb, atX86, atX86_64, atXCore, atMBlaze, atNVPTX, atNVPTX64, atLE32, atAMDil ); TArchRec = record Name: String; PBW: Cardinal; Alternate: TArchType; end; const CArchType: array [TArchType] of TArchRec = ( (Name: 'UnknownArch'; PBW: 0; Alternate: atUnknownArch), (Name: 'arm'; PBW: 32; Alternate: atARM), (Name: 'cellspu'; PBW: 32; Alternate: atCellSPU), (Name: 'hexagon'; PBW: 32; Alternate: atHexagon), (Name: 'mips'; PBW: 32; Alternate: atMIPS64), (Name: 'mipsel'; PBW: 32; Alternate: atMIPS64el), (Name: 'mips64'; PBW: 64; Alternate: atMIPS), (Name: 'mips64el'; PBW: 64; Alternate: atMIPSel), (Name: 'msp430'; PBW: 16; Alternate: atUnknownArch), (Name: 'ppc'; PBW: 32; Alternate: atPPC64), (Name: 'ppc64'; PBW: 64; Alternate: atPPC), (Name: 'r600'; PBW: 32; Alternate: atR600), (Name: 'sparc'; PBW: 32; Alternate: atSparcV9), (Name: 'sparcv9'; PBW: 64; Alternate: atSparc), (Name: 'tce'; PBW: 32; Alternate: atTCE), (Name: 'thumb'; PBW: 32; Alternate: atThumb), (Name: 'x86'; PBW: 32; Alternate: atX86_64), (Name: 'x86_64'; PBW: 64; Alternate: atX86), (Name: 'xcore'; PBW: 32; Alternate: atXCore), (Name: 'mblaze'; PBW: 32; Alternate: atMBlaze), (Name: 'nvptx'; PBW: 32; Alternate: atNVPTX64), (Name: 'nvptx64'; PBW: 64; Alternate: atNVPTX), (Name: 'le32'; PBW: 32; Alternate: atLE32), (Name: 'amdil'; PBW: 32; Alternate: atAMDil) ); type TVendorType = ( vtUnknownVendor, vtApple, vtPC, vtSCEI, vtBGP, vtBGQ ); const CVendorType: array [TVendorType] of String = ( 'UnknownVendor', 'Apple', 'PC', 'SCEI', 'BGP', 'BGQ' ); type TOSType = ( otUnknownOS, otAuroraUX, otCygwin, otDarwin, otDragonFly, otFreeBSD, otIOS, otKFreeBSD, otLinux, otLv2, otMacOSX, otMinGW32, otNetBSD, otOpenBSD, otSolaris, otWin32, otHaiku, otMinix, otRTEMS, otNativeClient, otCNK ); const COSType: array [TOSType] of String = ( 'UnknownOS', 'AuroraUX', 'Cygwin', 'Darwin', 'DragonFly', 'FreeBSD', 'IOS', 'KFreeBSD', 'Linux', 'Lv2', 'MacOSX', 'MinGW32', 'NetBSD', 'OpenBSD', 'Solaris', 'Win32', 'Haiku', 'Minix', 'RTEMS', 'NativeClient', 'CNK' ); type TEnvironmentType = ( etUnknownEnvironment, etGNU, etGNUEABI, etGNUEABIHF, etEABI, etMachO, etANDROIDEABI ); const CEnvironmentType: array [TEnvironmentType] of String = ( 'UnknownEnvironment', 'GNU', 'GNUEABI', 'GNUEABIHF', 'EABI', 'MachO', 'ANDROIDEABI' ); type TLLVMTriple = class private FArchType: TArchType; FVendorType: TVendorType; FOSType: TOSType; FEnvType: TEnvironmentType; FTriple: String; procedure BuildTriple; procedure ParseTriple; procedure SetArchType(const Value: TArchType); procedure SetEnvType(const Value: TEnvironmentType); procedure SetOSType(const Value: TOSType); procedure SetVendorType(const Value: TVendorType); procedure SetTriple(const Value: String); function GetArchTypeName: String; function GetEnvTypeName: String; function GetOSTypeName: String; function GetVendorTypeName: String; function GetArchPointerBitWidth: Cardinal; public constructor Create; overload; constructor Create(const ATriple: String); overload; constructor Create(AArchType: TArchType; AVendorType: TVendorType; AOSType: TOSType); overload; constructor Create(AArchType: TArchType; AVendorType: TVendorType; AOSType: TOSType; AEnvType: TEnvironmentType); overload; destructor Destroy; override; function IsArch16Bit: Boolean; function IsArch32Bit: Boolean; function IsArch64Bit: Boolean; function HasEnvironment: Boolean; function Get32BitArchVariant: TArchType; function Get64BitArchVariant: TArchType; procedure SwitchTo32BitArchVariant; procedure SwitchTo64BitArchVariant; public property Triple: String read FTriple write SetTriple; property ArchType: TArchType read FArchType write SetArchType; property VendorType: TVendorType read FVendorType write SetVendorType; property OSType: TOSType read FOSType write SetOSType; property EnvType: TEnvironmentType read FEnvType write SetEnvType; property ArchTypeName: String read GetArchTypeName; property VendorTypeName: String read GetVendorTypeName; property OSTypeName: String read GetOSTypeName; property EnvTypeName: String read GetEnvTypeName; property ArchPointerBitWidth: Cardinal read GetArchPointerBitWidth; end; implementation { TLLVMTriple } procedure TLLVMTriple.BuildTriple; begin FTriple := GetArchTypeName + '-' + GetVendorTypeName + '-' + GetOSTypeName; if HasEnvironment then FTriple := FTriple + '-' + GetEnvTypeName; end; constructor TLLVMTriple.Create(AArchType: TArchType; AVendorType: TVendorType; AOSType: TOSType); begin FArchType := AArchType; FVendorType := AVendorType; FOSType := AOSType; FEnvType := etUnknownEnvironment; FTriple := ''; BuildTriple; end; constructor TLLVMTriple.Create(AArchType: TArchType; AVendorType: TVendorType; AOSType: TOSType; AEnvType: TEnvironmentType); begin FArchType := AArchType; FVendorType := AVendorType; FOSType := AOSType; FEnvType := AEnvType; FTriple := ''; BuildTriple; end; constructor TLLVMTriple.Create; begin FArchType := atUnknownArch; FVendorType := vtUnknownVendor; FOSType := otUnknownOS; FEnvType := etUnknownEnvironment; FTriple := ''; BuildTriple; end; constructor TLLVMTriple.Create(const ATriple: String); begin FArchType := atUnknownArch; FVendorType := vtUnknownVendor; FOSType := otUnknownOS; FEnvType := etUnknownEnvironment; FTriple := ATriple; ParseTriple; end; destructor TLLVMTriple.Destroy; begin inherited; end; function TLLVMTriple.Get32BitArchVariant: TArchType; begin Result := FArchType; if (CArchType[FArchType].PBW <> 32) then Result := CArchType[FArchType].Alternate; end; function TLLVMTriple.Get64BitArchVariant: TArchType; begin Result := FArchType; if (CArchType[FArchType].PBW <> 64) then Result := CArchType[FArchType].Alternate; end; function TLLVMTriple.GetArchPointerBitWidth: Cardinal; begin Result := CArchType[FArchType].PBW; end; function TLLVMTriple.GetArchTypeName: String; begin Result := CArchType[FArchType].Name; end; function TLLVMTriple.GetEnvTypeName: String; begin Result := CEnvironmentType[FEnvType]; end; function TLLVMTriple.GetOSTypeName: String; begin Result := COSType[FOSType]; end; function TLLVMTriple.GetVendorTypeName: String; begin Result := CVendorType[FVendorType]; end; function TLLVMTriple.HasEnvironment: Boolean; begin Result := (FEnvType <> etUnknownEnvironment); end; function TLLVMTriple.IsArch16Bit: Boolean; begin Result := (GetArchPointerBitWidth = 16); end; function TLLVMTriple.IsArch32Bit: Boolean; begin Result := (GetArchPointerBitWidth = 32); end; function TLLVMTriple.IsArch64Bit: Boolean; begin Result := (GetArchPointerBitWidth = 64); end; procedure TLLVMTriple.ParseTriple; begin // ToDo: Parse FTriple to Arch/Vendor/OS/Environment raise Exception.Create('[ParseTriple] Not ready yet!'); end; procedure TLLVMTriple.SetArchType(const Value: TArchType); begin if (FArchType <> Value) then begin FArchType := Value; BuildTriple; end; end; procedure TLLVMTriple.SetEnvType(const Value: TEnvironmentType); begin if (FEnvType <> Value) then begin FEnvType := Value; BuildTriple; end; end; procedure TLLVMTriple.SetOSType(const Value: TOSType); begin if (FOSType <> Value) then begin FOSType := Value; BuildTriple; end; end; procedure TLLVMTriple.SetTriple(const Value: String); begin if (FTriple <> Value) then begin FTriple := Value; ParseTriple; end; end; procedure TLLVMTriple.SetVendorType(const Value: TVendorType); begin if (FVendorType <> Value) then begin FVendorType := Value; BuildTriple; end; end; procedure TLLVMTriple.SwitchTo32BitArchVariant; begin SetArchType(Get32BitArchVariant); end; procedure TLLVMTriple.SwitchTo64BitArchVariant; begin SetArchType(Get64BitArchVariant); end; end.
unit UnComissoes; {Verificado -.edit; } interface uses Db, DBTables, classes, sysUtils, UnSistema, UnDadosCR, SQLExpr, Tabela; // funcoes type TFuncoesComissao = class Cadastro, Comissao : TSQL; Tabela : TSQLQuery; private procedure PosicionaComissao(VpaTabela : TDataSet; VpaCodfilial, VpaLanComissao : Integer); procedure PosicionaComisaoCR(VpaTabela : TDataSet; VpaCodFilial,VpLanReceber,VpaNumParcela : Integer); function RPerParcelaSobreValoTotal(VpaValTotal, VpaValParcela : Double):Double; function ExisteSequencialComissao(VpaCodFilial, VpaSeqComissao : Integer):Boolean; public constructor cria(VpaBaseDados : TSQLConnection); destructor Destroy; override; function RSeqComissaoDisponivel(VpaCodFilial : Integer) : Integer; function VerificaComissaoPaga(VpaCodFilial, VpaLanReceber, VpaNumParcela : Integer ) : Boolean;overload; function VerificaComissaoPaga(VpaCodFilial, VpaLanReceber : Integer ) : Boolean;overload; procedure ExcluiTodaComissaoDireto(VpaCodfilial, VpaLanReceber : Integer); function ExcluiUmaComissao(VpaCodFilial, VpaLanReceber,VpaNumParcela : Integer) : string; procedure AlteraVencimentos(VpaCodFilial,VpaLanReceber, VpaNumParcela : integer; VpaNovaData : TDateTime); function EfetuaBaixaPagamento(VpaCodfilial,VpaLanComissao : Integer;VpaDatPagamento : TDateTime):String; function EstornaBaixaPagamento(VpaCodfilial,VpaLanComissao : Integer):String; function EfetuaLiberacao(VpaCodfilial,VpaLanComissao : Integer;VpaDatLiberacao : TDateTime):String; function EstornaLiberacao(VpaCodfilial,VpaLanComissao : Integer):String; procedure AlteraVendedor( VpaCodVendedor, VpaCodFilial, VpaLanComissao: Integer); procedure AlterarPerComissao(VpaCodFilial, VpaNumLancamento, VpaNumLanReceber, VpaNroParcela : Integer;VpaNovoPercentual : Double); procedure GeraParcelasComissao(VpaDNovaCR : TRBDContasCR;VpaDComissao : TRBDComissao); function GravaDComissoes(VpaDComissao : TRBDComissao) : string; function LiberaComissao(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer;VpaDatPagamentoParcela : TDateTime) : String; function EstornaComissao(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer) : string; end; implementation uses constMsg, constantes, funSql, funData, FunObjeto; {############################################################################# TFuncoesComissoes ############################################################################# } { ****************** Na criação da classe ******************************** } constructor TFuncoesComissao.cria(VpaBaseDados : TSQLConnection); begin inherited; Comissao := TSQL.Create(nil); Comissao.ASQLConnection := VpaBaseDados; Cadastro := TSQL.Create(nil); Cadastro.ASQLConnection := VpaBaseDados; Tabela := TSQLQuery.Create(nil); Tabela.SQLConnection := VpaBaseDados; end; { ******************* Quando destroy a classe ****************************** } destructor TFuncoesComissao.Destroy; begin FechaTabela(Comissao); FechaTabela(tabela); Comissao.free; Cadastro.free; Tabela.free; inherited; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( funcoes de carregamento da classe ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) } {******************************************************************************} function TFuncoesComissao.RSeqComissaoDisponivel(VpaCodFilial : Integer) : Integer; begin if varia.TipoBancoDados = bdMatrizSemRepresentante then begin AdicionaSQLAbreTabela(Tabela,'Select max(I_LAN_CON) ULTIMO FROM MOVCOMISSOES '+ ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)); result := Tabela.FieldByname('ULTIMO').AsInteger + 1; Tabela.close; end else begin repeat AdicionaSQLAbreTabela(Tabela,'Select SEQCOMISSAO FROM SEQUENCIALCOMISSAO '+ ' where CODFILIAL = '+IntToStr(VpaCodFilial)+ ' order by SEQCOMISSAO'); result := Tabela.FieldByName('SEQCOMISSAO').AsInteger; if result = 0 then begin aviso('FINAL SEQUENCIAL COMISSÃO!!!'#13'Não existem mais sequenciais de comissão disponiveis, é necessário gerar mais sequenciais ou fazer uma importação de dados.'); break; end; Tabela.Close; ExecutaComandoSql(Tabela,'Delete from SEQUENCIALCOMISSAO ' + ' where CODFILIAL = '+IntToStr(VpaCodFilial)+ ' and SEQCOMISSAO = '+IntToStr(result)); until (not ExisteSequencialComissao(VpaCodFilial,result)); end; end; {(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Exclusao da comissao ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} { ********************* exclui comisssao ************************************} procedure TFuncoesComissao.ExcluiTodaComissaoDireto(VpaCodfilial, VpaLanReceber : Integer); begin Sistema.GravaLogExclusao('MOVCOMISSOES','Select * from MOVCOMISSOES '+ ' where I_EMP_FIL = '+ InttoStr(VpaCodFilial) + ' and I_LAN_REC = ' + IntToStr(VpaLanReceber)); ExecutaComandoSql(Comissao,' Delete from MovComissoes ' + ' where i_emp_fil = '+ InttoStr(VpaCodFilial) + ' and I_LAN_REC = ' + IntToStr(VpaLanReceber)); end; { ********************* exclui uma única comisssao ************************************} function TFuncoesComissao.ExcluiUmaComissao(VpaCodFilial, VpaLanReceber,VpaNumParcela : Integer) : string; begin Result := ''; // Exclui a comissão; if VerificaComissaoPaga(VpaCodFilial, VpalanReceber, VpaNumParcela) then begin if not Confirmacao(CT_CanExcluiComissao) then result := 'COMISSAO PAGA!!!'#13'A comissão referente a esse título foi paga.'; end; if result = '' then begin ExecutaComandoSql(comissao, ' Delete from MOVCOMISSOES '+ ' where I_EMP_FIL = '+ InttoStr(VpaCodFilial) + ' and I_LAN_REC = ' + IntToStr(VpaLanReceber) + ' and I_NRO_PAR = ' + IntToStr(VpaNumParcela)); end; end; {******************************************************************************} function TFuncoesComissao.ExisteSequencialComissao(VpaCodFilial, VpaSeqComissao: Integer): Boolean; begin AdicionaSQLAbreTabela(Tabela,'Select I_EMP_FIL FROM MOVCOMISSOES ' + ' Where I_EMP_FIL = ' +IntToStr(VpaCodFilial)+ ' and I_LAN_CON = ' +IntToStr(VpaSeqComissao)); result := not Tabela.eof; Tabela.Close; end; { *** verifica se a comissão foi paga *** } function TFuncoesComissao.VerificaComissaoPaga(VpaCodFilial, VpaLanReceber, VpaNumParcela : Integer ) : Boolean; begin AdicionaSQLAbreTabela(Tabela, ' select I_EMP_FIL from MOVCOMISSOES ' + ' where I_EMP_FIL = '+ InttoStr(VpaCodFilial) + ' and I_LAN_REC = ' + IntToStr(VpaLanReceber) + ' and I_NRO_PAR = ' + IntToStr(VpaNumParcela) + ' and not D_DAT_PAG is null '); Result := (not Tabela.EOF); FechaTabela(Tabela); end; {******************************************************************************} function TFuncoesComissao.VerificaComissaoPaga(VpaCodFilial, VpaLanReceber : Integer ) : Boolean; begin AdicionaSQLAbreTabela(Tabela, ' select I_EMP_FIL from MOVCOMISSOES ' + ' where I_EMP_FIL = '+ InttoStr(VpaCodFilial) + ' and I_LAN_REC = ' + IntToStr(VpaLanReceber) + ' and not D_DAT_PAG is null '); Result := (not Tabela.EOF); FechaTabela(Tabela); end; {(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Altera o vencimento da comissao ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} { ***** Altera o venvimento da comissao ************************************* } procedure TFuncoesComissao.AlteraVencimentos(VpaCodFilial,VpaLanReceber, VpaNumParcela : integer; VpaNovaData : TDateTime); begin PosicionaComisaoCR(Comissao, VpaCodFilial,VpaLanReceber, VpaNumParcela); if not Comissao.eof then begin Comissao.edit; Comissao.FieldByName('D_DAT_VEN').Value := VpaNovaData; //atualiza a data de alteracao para poder exportar Comissao.FieldByName('D_ULT_ALT').AsDateTime := SISTEMA.RDataServidor; Comissao.post; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; Comissao.close; end; {(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Manutencao de pagamentos ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} procedure TFuncoesComissao.PosicionaComissao(VpaTabela : TDataSet; VpaCodfilial, VpaLanComissao : Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVCOMISSOES MOC ' + ' Where I_EMP_FIL = ' +IntToStr(VpaCodfilial)+ ' and I_LAN_CON = ' +IntToStr(VpaLanComissao)); end; {******************************************************************************} procedure TFuncoesComissao.PosicionaComisaoCR(VpaTabela : TDataSet; VpaCodFilial,VpLanReceber,VpaNumParcela : Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVCOMISSOES MOC ' + ' Where I_EMP_FIL = ' +IntToStr(VpaCodfilial)+ ' and I_LAN_REC = ' +IntToStr(VpLanReceber)+ ' and I_NRO_PAR = ' +IntToStr(VpaNumParcela)); end; {******************************************************************************} function TFuncoesComissao.RPerParcelaSobreValoTotal(VpaValTotal, VpaValParcela : Double) : Double; begin result := 100; if VpaValTotal > 0 then result := (VpaValParcela * 100)/VpaValTotal; end; { ********** efetua baixas de pagamentos de parcelas ou de efetiva ********** } function TFuncoesComissao.EfetuaBaixaPagamento(VpaCodfilial,VpaLanComissao : Integer;VpaDatPagamento : TDateTime):String; begin result := ''; PosicionaComissao(Comissao,VpaCodfilial,VpaLanComissao); Comissao.Edit; Comissao.FieldByName('D_DAT_PAG').AsDateTime := VpaDatPagamento; Comissao.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor; Comissao.post; result := Comissao.AMensagemErroGravacao; comissao.close; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; {******************************************************************************} function TFuncoesComissao.EstornaBaixaPagamento(VpaCodfilial,VpaLanComissao : Integer):String; begin result := ''; PosicionaComissao(Comissao,VpaCodfilial,VpaLanComissao); Comissao.Edit; Comissao.FieldByName('D_DAT_PAG').clear; Comissao.FieldByName('D_ULT_ALT').AsDateTime := SISTEMA.RDataServidor; Comissao.post; result := Comissao.AMensagemErroGravacao; comissao.close; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; {******************************************************************************} function TFuncoesComissao.EfetuaLiberacao(VpaCodfilial,VpaLanComissao : Integer;VpaDatLiberacao : TDateTime):String; begin result := ''; PosicionaComissao(Comissao,VpaCodfilial,VpaLanComissao); Comissao.Edit; Comissao.FieldByName('D_DAT_VAL').AsDateTime := VpaDatLiberacao; Comissao.FieldByName('D_ULT_ALT').AsDateTime := sistema.RDataServidor; Comissao.post; result := comissao.AMensagemErroGravacao; comissao.close; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; {******************************************************************************} function TFuncoesComissao.EstornaLiberacao(VpaCodfilial,VpaLanComissao : Integer):String; begin result := ''; PosicionaComissao(Comissao,VpaCodfilial,VpaLanComissao); Comissao.Edit; Comissao.FieldByName('D_DAT_VAL').clear; Comissao.FieldByName('D_ULT_ALT').AsDateTime := sistema.RDataServidor; Comissao.post; result := Comissao.AMensagemErroGravacao; comissao.close; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; {******************************************************************************} procedure TFuncoesComissao.AlteraVendedor( VpaCodVendedor, VpaCodFilial, VpaLanComissao : Integer); begin PosicionaComissao(Comissao,VpaCodfilial,VpaLanComissao); Comissao.edit; Comissao.FieldByName('I_COD_VEN').AsInteger := VpaCodVendedor; //atualiza a data de alteracao para poder exportar Comissao.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor; Comissao.post; Comissao.close; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); end; {******************************************************************************} procedure TFuncoesComissao.AlterarPerComissao(VpaCodFilial, VpaNumLancamento, VpaNumLanReceber, VpaNroParcela : Integer;VpaNovoPercentual : Double); begin AdicionaSqlAbreTabela(Tabela,'Select (MOV.N_VLR_PAR * MOE.N_VLR_DIA) Valor '+ ' from MOVCONTASARECEBER MOV, CADMOEDAS MOE ' + ' Where MOV.I_EMP_FIL = '+IntTostr(VpaCodFilial)+ ' and MOV.I_LAN_REC = ' + IntToStr(VpaNumLanReceber)+ ' and MOV.I_NRO_PAR = '+ IntToStr(VpaNroParcela)+ ' and MOE.I_COD_MOE = MOV.I_COD_MOE'); AdicionaSQLAbreTabela(Comissao,'Select * from MOVCOMISSOES MOC' + ' Where MOC.I_EMP_FIL = '+IntTostr(VpaCodFilial)+ ' and MOC.I_LAN_CON = ' + IntToStr(VpaNumLancamento)); Comissao.Edit; Comissao.FieldByName('N_VLR_COM').AsFloat := ((Tabela.FieldByName('Valor').AsFloat * VpaNovoPercentual)/100); Comissao.FieldByName('N_PER_COM').AsFloat := VpaNovoPercentual; Comissao.FieldByName('N_VLR_INI').AsFloat := ((Tabela.FieldByName('Valor').AsFloat * VpaNovoPercentual)/100); Comissao.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor; Comissao.post; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); Comissao.close; Tabela.Close; end; {******************************************************************************} procedure TFuncoesComissao.GeraParcelasComissao(VpaDNovaCR : TRBDContasCR;VpaDComissao : TRBDComissao); var VpfDParcela : TRBDMovContasCR; VpfDParcelaComissao : TRBDComissaoItem; VpfLaco : Integer; VpfValTotalComissao, VpfValBaseComissao : Double; begin FreeTObjectsList(VpaDComissao.Parcelas); VpfValTotalComissao := VpaDComissao.ValTotalComissao; if VpaDNovaCR.TipValorComissao = 1 then //50% no faturamento e o restante nas liquidacao; begin VpfDParcelaComissao := VpaDComissao.AddParcela; VpfDParcelaComissao.NumParcela := 1; VpfDParcelaComissao.DatVencimento := VpaDComissao.DatEmissao; VpfValTotalComissao := VpfValTotalComissao / 2; VpfDParcelaComissao.ValComissaoParcela := VpfValTotalComissao; VpfValBaseComissao := VpaDNovaCR.ValBaseComissao / 2; VpfDParcelaComissao.ValBaseComissao := VpfValBaseComissao; VpfDParcelaComissao.DatLiberacao := VpaDComissao.DatEmissao; VpfDParcelaComissao.IndLiberacaoAutomatica := true; end; for VpfLaco := 0 to VpaDNovaCR.Parcelas.Count - 1 do begin VpfDParcela := TRBDMovContasCR(VpaDNovaCR.Parcelas.Items[VpfLaco]); VpfDParcelaComissao := VpaDComissao.AddParcela; VpfDParcelaComissao.IndLiberacaoAutomatica := false; VpfDParcelaComissao.NumParcela := VpfDParcela.NumParcela; VpfDParcelaComissao.DatVencimento := VpfDParcela.DatVencimento; if VpaDComissao.ValTotalComissao < 0 then begin VpfDParcelaComissao.ValComissaoParcela := VpfValTotalComissao; VpfDParcelaComissao.DatLiberacao := date; end else begin VpfDParcelaComissao.ValComissaoParcela := (VpfValTotalComissao * RPerParcelaSobreValoTotal(VpaDNovaCR.ValTotal,VpfDParcela.Valor))/100; VpfDParcelaComissao.ValBaseComissao := (VpfValBaseComissao * RPerParcelaSobreValoTotal(VpaDNovaCR.ValTotal,VpfDParcela.Valor))/100; VpfDParcelaComissao.DatLiberacao := montadata(1,1,1900); end; end; end; {******************************************************************************} function TFuncoesComissao.GravaDComissoes(VpaDComissao : TRBDComissao) : string; Var VpfLaco : Integer; VpfDParcela : TRBDComissaoItem; begin result := ''; if VpaDComissao.SeqComissao <> 0 then ExcluiTodaComissaoDireto(VpaDComissao.CodFilial,VpaDComissao.LanReceber); AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCOMISSOES '+ ' Where I_EMP_FIL = 0 AND I_LAN_CON = 0'); for VpfLaco := 0 to VpaDComissao.Parcelas.count - 1 do begin VpfDParcela := TRBDComissaoItem(VpaDComissao.Parcelas.Items[VpfLaco]); Cadastro.insert; Cadastro.FieldByname('I_EMP_FIL').AsInteger := VpaDComissao.CodFilial; Cadastro.FieldByname('I_LAN_REC').AsInteger := VpaDComissao.LanReceber; Cadastro.FieldByname('I_NRO_PAR').AsInteger := VpfDParcela.NumParcela; Cadastro.FieldByname('I_COD_VEN').AsInteger := VpaDComissao.CodVendedor; Cadastro.FieldByname('D_DAT_VEN').AsDateTime := VpfDParcela.DatVencimento; if VpfDParcela.DatPagamento > montadata(1,1,1900) then Cadastro.FieldByname('D_DAT_PAG').AsDateTime := VpfDParcela.DatPagamento; if VpfDParcela.DatLiberacao > montadata(1,1,1900) then Cadastro.FieldByname('D_DAT_VAL').AsDateTime := VpfDParcela.DatLiberacao; Cadastro.FieldByname('N_VLR_COM').AsFloat := VpfDParcela.ValComissaoParcela; Cadastro.FieldByname('N_VLR_INI').AsFloat := VpfDParcela.ValComissaoParcela; Cadastro.FieldByname('N_BAS_PRO').AsFloat := VpfDParcela.ValBaseComissao; Cadastro.FieldByname('I_TIP_COM').AsInteger := VpaDComissao.TipComissao; if VpaDComissao.PerComissao <> 0 then Cadastro.FieldByname('N_PER_COM').AsFloat := VpaDComissao.PerComissao; Cadastro.FieldByname('L_OBS_COM').AsString := VpaDComissao.DesObservacao; Cadastro.FieldByname('D_DAT_EMI').AsDateTime := VpaDComissao.DatEmissao; Cadastro.FieldByname('D_ULT_ALT').AsDateTime := sistema.RDataServidor; if VpfDParcela.ValComissaoParcela < 0 then Cadastro.FieldByname('C_IND_DEV').AsString := 'S' else Cadastro.FieldByname('C_IND_DEV').AsString := 'N'; if VpfDParcela.IndLiberacaoAutomatica then Cadastro.FieldByname('C_LIB_AUT').AsString := 'S' else Cadastro.FieldByname('C_LIB_AUT').AsString := 'N'; VpaDComissao.SeqComissao := RSeqComissaoDisponivel(VpaDComissao.CodFilial); Cadastro.FieldByname('I_LAN_CON').AsInteger := VpaDComissao.SeqComissao; if varia.TipoBancoDados = bdRepresentante then Cadastro.FieldByName('C_FLA_EXP').AsString := 'N' else Cadastro.FieldByName('C_FLA_EXP').AsString := 'S'; Cadastro.post; result := Cadastro.AMensagemErroGravacao; if Cadastro.AErronaGravacao then break; end; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); Cadastro.close; end; {******************************************************************************} function TFuncoesComissao.LiberaComissao(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer;VpaDatPagamentoParcela : TDateTime) : String; begin result := ''; PosicionaComisaoCR(Comissao,VpaCodfilial,VpaLanReceber,VpaNumParcela); while not Comissao.eof do begin if Comissao.FieldByName('C_LIB_AUT').AsString = 'N' then begin Comissao.Edit; Comissao.FieldByName('D_DAT_VAL').AsDateTime := date; Comissao.FieldByName('D_ULT_ALT').AsDateTime := SISTEMA.RDataServidor; Comissao.FieldByName('D_PAG_REC').AsDateTime := VpaDatPagamentoParcela; Comissao.post; result := Comissao.AMensagemErroGravacao; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); if Comissao.AErronaGravacao then exit; end; Comissao.next; end; comissao.close; end; {******************************************************************************} function TFuncoesComissao.EstornaComissao(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer) : string; begin result := ''; PosicionaComisaoCR(Comissao,VpaCodfilial,VpaLanReceber,VpaNumParcela); while not Comissao.Eof do begin if Comissao.FieldByName('C_LIB_AUT').AsString = 'N' then begin if not Comissao.FieldByname('D_DAT_PAG').IsNull then result := 'COMISSÃO PAGA!!!'#13'Não é possivel concluir a operação pois a comissão já foi paga para o vendedor'; if result = '' then begin Comissao.Edit; Comissao.FieldByName('D_DAT_VAL').clear; Comissao.FieldByName('D_PAG_REC').clear; Comissao.FieldByName('D_ULT_ALT').AsDateTime := Sistema.RDataServidor; Comissao.post; result := Comissao.AMensagemErroGravacao; end; end; Comissao.Next; end; Sistema.MarcaTabelaParaImportar('MOVCOMISSOES'); comissao.close; end; end.
program _demo; Array[0] var State : MinLMState; Rep : MinLMReport; I : AlglibInteger; S : TReal1DArray; X : TReal1DArray; Y : TReal1DArray; FI : Double; N : AlglibInteger; M : AlglibInteger; begin // // Example of solving polynomial approximation task using FJ scheme. // // Data points: // xi are random numbers from [-1,+1], // // Function being fitted: // yi = exp(xi) - sin(xi) - x^3/3 // // Function being minimized: // F(a,b,c) = // (a + b*x0 + c*x0^2 - y0)^2 + // (a + b*x1 + c*x1^2 - y1)^2 + ... // N := 3; SetLength(S, N); I:=0; while I<=N-1 do begin S[I] := RandomReal-0.5; Inc(I); end; M := 100; SetLength(X, M); SetLength(Y, M); I:=0; while I<=M-1 do begin X[I] := AP_Double(2*I)/(M-1)-1; Y[I] := Exp(X[I])-Sin(X[I])-X[I]*X[I]*X[I]/3; Inc(I); end; // // Now S stores starting point, X and Y store points being fitted. // MinLMCreateFJ(N, M, S, State); MinLMSetCond(State, 0.0, 0.0, 0.001, 0); while MinLMIteration(State) do begin if State.NeedF then begin State.F := 0; end; I:=0; while I<=M-1 do begin // // "a" is stored in State.X[0] // "b" - State.X[1] // "c" - State.X[2] // FI := State.X[0]+State.X[1]*X[I]+State.X[2]*AP_Sqr(X[I])-Y[I]; if State.NeedF then begin // // F is equal to sum of fi squared. // State.F := State.F+AP_Sqr(FI); end; if State.NeedFiJ then begin // // Fi // State.Fi[I] := FI; // // dFi/da // State.J[I,0] := 1; // // dFi/db // State.J[I,1] := X[I]; // // dFi/dc // State.J[I,2] := AP_Sqr(X[I]); end; Inc(I); end; end; MinLMResults(State, S, Rep); // // output results // Write(Format('A = %4.2f'#13#10'',[ S[0]])); Write(Format('B = %4.2f'#13#10'',[ S[1]])); Write(Format('C = %4.2f'#13#10'',[ S[2]])); Write(Format('TerminationType = %0d (should be 2 - stopping when step is small enough)'#13#10'',[ Rep.TerminationType])); end.
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Cmp_CSS; {$mode objfpc}{$H+} interface uses ATStrings, ATSynEdit, ATSynEdit_Cmp_CSS_Provider; procedure DoEditorCompletionCss(AEdit: TATSynEdit); type TATCompletionOptionsCss = record Provider: TATCssProvider; FilenameCssList: string; //from CudaText: data/autocompletespec/css_list.ini FilenameCssColors: string; //from CudaText: data/autocompletespec/css_colors.ini FilenameCssSelectors: string; //from CudaText: data/autocompletespec/css_sel.ini PrefixProp: string; PrefixVar: string; PrefixAtRule: string; PrefixPseudo: string; PrefixDir: string; PrefixFile: string; LinesToLookup: integer; NonWordChars: UnicodeString; AppendSemicolon: boolean; FileMaskURL: string; end; var CompletionOpsCss: TATCompletionOptionsCss; implementation uses SysUtils, Classes, Graphics, StrUtils, Math, ATSynEdit_Carets, ATSynEdit_RegExpr, ATSynEdit_Cmp_Filenames, ATSynEdit_Cmp_Form; type TQuoteKind = (qkNone, qkSingle, qkDouble); type { TAcp } TAcp = class private ListSel: TStringList; //CSS at-rules (@) and pseudo elements (:) procedure DoOnGetCompleteProp(Sender: TObject; AContent: TStringList; out ACharsLeft, ACharsRight: integer); procedure DoOnChoose(Sender: TObject; const ASnippetId: string; ASnippetIndex: integer); procedure FindCustomProps(L: TStringList; AMaxLine: integer); public Ed: TATSynEdit; constructor Create; virtual; destructor Destroy; override; end; var Acp: TAcp = nil; type TCompletionCssContext = ( CtxNone, CtxPropertyName, CtxPropertyValue, CtxSelectors, CtxUrl, CtxVar ); function SFindRegex(const SText, SRegex: UnicodeString; NGroup: integer): string; var R: TRegExpr; begin Result:= ''; R:= TRegExpr.Create; try R.ModifierS:= false; R.ModifierM:= true; R.ModifierI:= true; R.Expression:= SRegex; R.InputString:= SText; if R.ExecPos(1) then Result:= Copy(SText, R.MatchPos[NGroup], R.MatchLen[NGroup]); finally R.Free; end; end; function EditorGetCaretInCurlyBrackets(Ed: TATSynEdit; APosX, APosY: integer): boolean; var St: TATStrings; S: UnicodeString; X, Y: integer; begin Result:= false; St:= Ed.Strings; for Y:= APosY downto Max(0, APosY-CompletionOpsCss.LinesToLookup) do begin if not St.IsIndexValid(Y) then Continue; S:= St.Lines[Y]; if Y=APosY then Delete(S, APosX+1, MaxInt); for X:= Length(S) downto 1 do begin if S[X]='{' then exit(true); if S[X]='}' then exit(false); end; end; end; function GetQuoteKind(const S: string): TQuoteKind; begin case S of '''': Result:= qkSingle; '"': Result:= qkDouble; else Result:= qkNone; end; end; procedure EditorGetCssContext(Ed: TATSynEdit; APosX, APosY: integer; out AContext: TCompletionCssContext; out ATag: string; out AQuoteKind: TQuoteKind); const //char class for all chars in css values cRegexChars = '[''"\w\s\.,:/~&%@!=\#\$\^\-\+\(\)\?]'; //regex to catch css property name, before css attribs and before ":", at line end cRegexProp = '([\w\-]+):\s*' + cRegexChars + '*$'; cRegexAtRule = '(@[a-z\-]*)$'; cRegexSelectors = '\w+(:+[a-z\-]*)$'; cRegexGroup = 1; //group 1 in (..) //group 1: quote char, group 2: URL text cRegexUrl = 'url\(\s*([''"]?)(' + '[\w\.%,/~@!=\-\(\)\[\]]*' + ')$'; cRegexUrlEmpty = 'url\(\s*(''|"|)$'; cRegexVar = 'var\(\s*([\w\-]*)$'; var S, S2: UnicodeString; SQuote: string; NPos: integer; begin AContext:= CtxNone; ATag:= ''; AQuoteKind:= qkDouble; S:= Ed.Strings.LineSub(APosY, 1, APosX); //detect 'var()' context NPos:= RPos(' var(', S); if NPos=0 then NPos:= RPos(':var(', S); if NPos>0 then begin S2:= Copy(S, NPos+1, MaxInt); if SFindRegex(S2, cRegexVar, 0)<>'' then begin ATag:= SFindRegex(S2, cRegexVar, 1); AContext:= CtxVar; exit; end; end; //detect 'url()' context NPos:= RPos(' url(', S); if NPos=0 then NPos:= RPos(':url(', S); if NPos>0 then begin S2:= Copy(S, NPos+1, MaxInt); //empty URL before caret? if SFindRegex(S2, cRegexUrlEmpty, 0)<>'' then begin AContext:= CtxUrl; SQuote:= SFindRegex(S2, cRegexUrlEmpty, 1); AQuoteKind:= GetQuoteKind(SQuote); exit; end; //not empty URL? ATag:= SFindRegex(S2, cRegexUrl, 2); if ATag<>'' then begin AContext:= CtxUrl; SQuote:= SFindRegex(S2, cRegexUrl, 1); AQuoteKind:= GetQuoteKind(SQuote); exit; end; end; ATag:= SFindRegex(S, cRegexAtRule, cRegexGroup); if ATag<>'' then begin AContext:= CtxSelectors; exit; end; if EditorGetCaretInCurlyBrackets(Ed, APosX, APosY) then begin AContext:= CtxPropertyName; if S='' then exit; ATag:= SFindRegex(S, cRegexProp, cRegexGroup); if ATag<>'' then AContext:= CtxPropertyValue; end else begin ATag:= SFindRegex(S, cRegexSelectors, cRegexGroup); if ATag<>'' then AContext:= CtxSelectors; end; end; function IsQuoteRight(QuoteKind: TQuoteKind; ch: WideChar): boolean; inline; begin case ch of '"': begin if QuoteKind=qkDouble then Result:= true; end; '''': begin if QuoteKind=qkSingle then Result:= true; end; ')': begin if QuoteKind=qkNone then Result:= true; end; else Result:= false; end; end; function IsQuoteLeftOrSlash(QuoteKind: TQuoteKind; ch: WideChar): boolean; inline; begin case ch of '"': begin if QuoteKind=qkDouble then Result:= true; end; '''': begin if QuoteKind=qkSingle then Result:= true; end; '(': begin if QuoteKind=qkNone then Result:= true; end; '/': Result:= true; else Result:= false; end; end; procedure EditorGetDistanceToQuotes(Ed: TATSynEdit; AQuoteKind: TQuoteKind; out ALeft, ARight: integer); var Caret: TATCaretItem; S: UnicodeString; Len, X, i: integer; begin ALeft:= 0; ARight:= 0; Caret:= Ed.Carets[0]; if not Ed.Strings.IsIndexValid(Caret.PosY) then exit; S:= Ed.Strings.Lines[Caret.PosY]; Len:= Length(S); X:= Caret.PosX+1; i:= X; while (i<=Len) and not IsQuoteRight(AQuoteKind, S[i]) do Inc(i); ARight:= i-X; i:= X; while (i>1) and (i<=Len) and not IsQuoteLeftOrSlash(AQuoteKind, S[i-1]) do Dec(i); ALeft:= Max(0, X-i); end; { TAcp } procedure TAcp.DoOnGetCompleteProp(Sender: TObject; AContent: TStringList; out ACharsLeft, ACharsRight: integer); // procedure GetFileNames(AResult: TStringList; AQuoteKind: TQuoteKind; const AText, AFileMask: string); begin EditorGetDistanceToQuotes(Ed, AQuoteKind, ACharsLeft, ACharsRight); CalculateCompletionFilenames(AResult, ExtractFileDir(Ed.FileName), AText, AFileMask, CompletionOpsCss.PrefixDir, CompletionOpsCss.PrefixFile, true, //AddSlash true //URL encode ); end; // var Caret: TATCaretItem; L: TStringList; s_word, s_NonWordChars: UnicodeString; s_tag, s_item, s_val, s_valsuffix: string; context: TCompletionCssContext; quote: TQuoteKind; ok: boolean; begin AContent.Clear; ACharsLeft:= 0; ACharsRight:= 0; Caret:= Ed.Carets[0]; EditorGetCssContext(Ed, Caret.PosX, Caret.PosY, context, s_tag, quote); s_NonWordChars:= CompletionOpsCss.NonWordChars; if context=CtxVar then s_NonWordChars+= '()'; EditorGetCurrentWord(Ed, Caret.PosX, Caret.PosY, s_NonWordChars, s_word, ACharsLeft, ACharsRight); case context of CtxPropertyValue: begin L:= TStringList.Create; try CompletionOpsCss.Provider.GetValues(s_tag, L); for s_item in L do begin s_val:= s_item; //filter values by cur word (not case sens) if s_word<>'' then begin ok:= StartsText(s_word, s_val); if not ok then Continue; end; //handle values like 'rgb()', 'val()' if EndsStr('()', s_val) then begin SetLength(s_val, Length(s_val)-2); s_valsuffix:= '|()'; end else s_valsuffix:= ''; //CompletionOps.SuffixSep+' '; AContent.Add(CompletionOpsCss.PrefixProp+' "'+s_tag+'"|'+s_val+s_valsuffix); end; finally FreeAndNil(L); end; end; CtxPropertyName: begin //if caret is inside property // back|ground: left; //then we must replace "background: ", ie replace extra 2 chars s_item:= Ed.Strings.LineSub(Caret.PosY, Caret.PosX+ACharsRight+1, 2); if s_item=': ' then Inc(ACharsRight, 2); L:= TStringList.Create; try CompletionOpsCss.Provider.GetProps(L); for s_item in L do begin //filter by cur word (not case sens) if s_word<>'' then begin ok:= StartsText(s_word, s_item); if not ok then Continue; end; AContent.Add(CompletionOpsCss.PrefixProp+'|'+s_item+#1': '); end; finally FreeAndNil(L); end; end; CtxSelectors: begin ACharsLeft:= Length(s_tag); if s_tag[1]='@' then s_val:= CompletionOpsCss.PrefixAtRule else if s_tag[1]=':' then s_val:= CompletionOpsCss.PrefixPseudo else exit; for s_item in ListSel do begin if (s_tag='') or StartsText(s_tag, s_item) then AContent.Add(s_val+'|'+s_item); end; end; CtxUrl: begin GetFileNames(AContent, quote, s_tag, CompletionOpsCss.FileMaskURL); end; CtxVar: begin case Length(s_tag) of 1: begin if not StartsStr('-', s_tag) then exit; end; 2..MaxInt: begin if not StartsStr('--', s_tag) then exit; end; end; L:= TStringList.Create; try FindCustomProps(L, Caret.PosY-1); for s_item in L do begin if s_tag<>'' then begin ok:= StartsText(s_tag, s_item); if not ok then Continue; end; AContent.Add(CompletionOpsCss.PrefixVar+'|'+s_item); end; finally FreeAndNil(L); end; end; end; end; procedure TAcp.DoOnChoose(Sender: TObject; const ASnippetId: string; ASnippetIndex: integer); var St: TATStrings; Caret: TATCaretItem; S: UnicodeString; begin St:= Ed.Strings; if CompletionOpsCss.AppendSemicolon then begin if Ed.Carets.Count=0 then exit; Caret:= Ed.Carets[0]; if not St.IsIndexValid(Caret.PosY) then exit; S:= St.Lines[Caret.PosY]; if S='' then exit; if S[Length(S)]<>';' then begin S+= ';'; St.Lines[Caret.PosY]:= S; Ed.DoEventChange(Caret.PosY); Ed.Update; end; end; end; constructor TAcp.Create; begin inherited; ListSel:= TStringlist.create; end; destructor TAcp.Destroy; begin FreeAndNil(ListSel); inherited; end; procedure TAcp.FindCustomProps(L: TStringList; AMaxLine: integer); // Docs: https://developer.mozilla.org/en-US/docs/Web/CSS/--* const cRegexVar = '^\s*(\-\-[a-z][\w\-]*)\s*:.+$'; cRegexVarGroup = 1; var S: UnicodeString; SId: string; N, iLine: integer; begin L.Clear; L.Sorted:= true; L.CaseSensitive:= true; //TODO: consider CSS comments for iLine:= 0 to Min(Ed.Strings.Count-1, AMaxLine) do begin S:= Ed.Strings.Lines[iLine]; N:= Pos('--', S); if N=0 then Continue; SId:= SFindRegex(S, cRegexVar, cRegexVarGroup); if SId<>'' then L.Add(SId); end; end; //----------------------------- procedure DoEditorCompletionCss(AEdit: TATSynEdit); begin Acp.Ed:= AEdit; if CompletionOpsCss.Provider=nil then begin CompletionOpsCss.Provider:= TATCssBasicProvider.Create( CompletionOpsCss.FilenameCssList, CompletionOpsCss.FilenameCssColors); end; //optional list, load only once if Acp.ListSel.Count=0 then begin if FileExists(CompletionOpsCss.FilenameCssSelectors) then Acp.ListSel.LoadFromFile(CompletionOpsCss.FilenameCssSelectors); end; EditorShowCompletionListbox(AEdit, @Acp.DoOnGetCompleteProp, nil, @Acp.DoOnChoose); end; initialization Acp:= TAcp.Create; with CompletionOpsCss do begin Provider:= nil; FilenameCssList:= ''; FilenameCssColors:= ''; FilenameCssSelectors:= ''; PrefixProp:= 'css'; PrefixVar:= 'var'; PrefixAtRule:= 'at-rule'; PrefixPseudo:= 'pseudo'; PrefixDir:= 'folder'; PrefixFile:= 'file'; LinesToLookup:= 50; NonWordChars:= '#@.{};''"<>'; //don't include ':' because we need to complete :pseudo and ::pseudo //don't include '!' because we need to complete !important thing AppendSemicolon:= true; FileMaskURL:= '*.png;*.gif;*.jpg;*.jpeg;*.ico;*.cur;*.svg;*.woff;*.css'; end; finalization with CompletionOpsCss do if Assigned(Provider) then FreeAndNil(Provider); FreeAndNil(Acp); end.
unit PascalCoin.FMX.Frame.Receive; /// <summary> /// <para> /// For QRCode URL see /// </para> /// <para> /// PIP-0026: a URI scheme for making PascalCoin payments. /// </para> /// <para> /// <see href="https://github.com/PascalCoin/PascalCoin/blob/master/PIP/PIP-0026.md" /><br /> /// </para> /// <para> /// and /// </para> /// <para> /// PIP-0027: E-PASA - Layer 2 Addresses: /// </para> /// <para> /// <see href="https://github.com/PascalCoin/PascalCoin/blob/master/PIP/PIP-0027.md" /> /// </para> /// </summary> interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, PascalCoin.FMX.Frame.Base, FMX.Edit, FMX.EditBox, FMX.NumberBox, FMX.ListBox, FMX.Controls.Presentation, FMX.Layouts, FMX.Objects, PascalCoin.Wallet.Interfaces, PascalCoin.Utils.Interfaces; type TReceiveFrame = class(TBaseFrame) FooterLayout: TLayout; MainLayout: TLayout; AccountLayout: TLayout; AccountLabel: TLabel; PayloadEncryptLayout: TLayout; PayloadEncryptLabel: TLabel; PayloadLayout: TLayout; PayloadLabel: TLabel; AmountLayout: TLayout; AmountLabel: TLabel; AccountNumber: TComboBox; Amount: TNumberBox; PascLabel: TLabel; Payload: TEdit; PayloadEncrypt: TComboBox; QRCodeLayout: TLayout; QRCodeImage: TImage; PayloadEncodeLayout: TLayout; PayloadEncodeLabel: TLabel; PayloadEncode: TComboBox; PayloadPasswordLayout: TLayout; PasswordLabel: TLabel; PayloadPassword: TEdit; PayloadAdvanced: TLayout; procedure AccountNumberChange(Sender: TObject); procedure AmountChange(Sender: TObject); procedure PayloadChange(Sender: TObject); procedure PayloadEncodeChange(Sender: TObject); procedure PayloadEncryptChange(Sender: TObject); procedure PayloadPasswordChange(Sender: TObject); private { Private declarations } FURI: IPascalCoinURI; procedure DataChanged; procedure UpdateQRCode; function CalcURI: string; procedure OnAdvancedOptionsChanged(const AValue: Boolean); public { Public declarations } constructor Create(AComponent: TComponent); override; destructor Destroy; override; end; var ReceiveFrame: TReceiveFrame; implementation {$R *.fmx} uses DelphiZXIngQRCode, PascalCoin.FMX.DataModule, PascalCoin.FMX.Wallet.Shared; // 'pasc:<account>[?amount=<amount>][?label=<label>][?message=<message>]' { TBaseFrame1 } function TReceiveFrame.CalcURI: string; begin result := ''; if AccountNumber.ItemIndex < 0 then Exit; result := 'pasc:' + AccountNumber.Items[AccountNumber.ItemIndex]; end; constructor TReceiveFrame.Create(AComponent: TComponent); var lPE: TPayloadEncryption; lPT: TPayloadEncode; lAccount, tAccount: string; sAccount: Int64; begin inherited; MainDataModule.Settings.OnAdvancedOptionsChange.Add(OnAdvancedOptionsChanged); PascLabel.Text := FormatSettings.CurrencyString; FURI := MainDataModule.Config.Container.Resolve<IPascalCoinURI>; for lPE := Low(TPayloadEncryption) to High(TPayloadEncryption) do PayloadEncrypt.Items.Add(_PayloadEncryptText[lPE]); PayloadEncrypt.ItemIndex := 0; for lPT := Low(TPayloadEncode) to High(TPayloadEncode) do PayloadEncode.Items.Add(_PayloadEncodeText[lPT]); PayloadEncode.ItemIndex := 2; PayloadPasswordLayout.Visible := False; OnAdvancedOptionsChanged(MainDataModule.Settings.AdvancedOptions); sAccount := MainDataModule.AccountsDataAccountNumber.Value; tAccount := ''; MainDataModule.DisableAccountData; try MainDataModule.AccountsData.First; while not MainDataModule.AccountsData.Eof do begin lAccount := MainDataModule.AccountsDataAccountNumChkSum.Value; if MainDataModule.AccountsDataAccountName.Value <> '' then lAccount := lAccount + ' [' + MainDataModule.AccountsDataAccountName. Value + ']'; AccountNumber.Items.Add(lAccount); if MainDataModule.AccountsDataAccountNumber.Value = sAccount then tAccount := lAccount; MainDataModule.AccountsData.Next; end; finally MainDataModule.EnableAccountData; end; if tAccount <> '' then AccountNumber.ItemIndex := AccountNumber.Items.IndexOf(tAccount) else AccountNumber.ItemIndex := 0; QRCodeImage.DisableInterpolation := True; QRCodeImage.WrapMode := TImageWrapMode.Stretch; UpdateQRCode; end; procedure TReceiveFrame.DataChanged; begin if csLoading in Self.ComponentState then Exit; UpdateQRCode; end; destructor TReceiveFrame.Destroy; begin MainDataModule.Settings.OnAdvancedOptionsChange.Remove (OnAdvancedOptionsChanged); inherited; end; procedure TReceiveFrame.OnAdvancedOptionsChanged(const AValue: Boolean); begin PayloadAdvanced.Visible := AValue; end; procedure TReceiveFrame.AccountNumberChange(Sender: TObject); begin DataChanged; end; procedure TReceiveFrame.AmountChange(Sender: TObject); begin DataChanged; end; procedure TReceiveFrame.PayloadChange(Sender: TObject); begin DataChanged; end; procedure TReceiveFrame.PayloadEncodeChange(Sender: TObject); begin DataChanged; end; procedure TReceiveFrame.PayloadEncryptChange(Sender: TObject); begin PayloadPasswordLayout.Visible := TPayloadEncryption(PayloadEncrypt.ItemIndex) = TPayloadEncryption.Password; DataChanged; end; procedure TReceiveFrame.PayloadPasswordChange(Sender: TObject); begin DataChanged; end; procedure TReceiveFrame.UpdateQRCode; var QRC: TDelphiZXingQRCode; QRCodeBitmap: TBitmap; Row, Col: Integer; pixelColor: TAlphaColor; vBitmapData: TBitmapData; rSrc, rDest: TRectF; lAccount: string; begin if AccountNumber.ItemIndex = -1 then Exit; lAccount := AccountNumber.Items[AccountNumber.ItemIndex]; if lAccount.IndexOf(' ') > -1 then lAccount := lAccount.Substring(0, lAccount.IndexOf(' ')); FURI.AccountNumber := lAccount; FURI.Amount := Amount.Value; FURI.Payload := Payload.Text; FURI.PayloadEncode := TPayloadEncode(PayloadEncode.ItemIndex); FURI.PayloadEncrypt := TPayloadEncryption(PayloadEncrypt.ItemIndex); FURI.Password := PayloadPassword.Text; QRCodeBitmap := TBitmap.Create; try QRC := TDelphiZXingQRCode.Create; try QRC.Data := FURI.URI; QRC.Encoding := TQRCodeEncoding.qrAuto; QRC.QuietZone := 4; QRCodeBitmap.SetSize(QRC.Columns, QRC.Rows); for Row := 0 to QRC.Rows - 1 do begin for Col := 0 to QRC.Columns - 1 do begin if QRC.IsBlack[Row, Col] then pixelColor := TAlphaColors.Black else pixelColor := TAlphaColors.White; if QRCodeBitmap.Map(TMapAccess.maWrite, vBitmapData) then begin try vBitmapData.SetPixel(Col, Row, pixelColor); finally QRCodeBitmap.Unmap(vBitmapData); end; end; end; end; QRCodeImage.Bitmap.SetSize(QRCodeBitmap.Width, QRCodeBitmap.Height); rSrc := TRectF.Create(0, 0, QRCodeBitmap.Width, QRCodeBitmap.Height); rDest := TRectF.Create(0, 0, QRCodeImage.Bitmap.Width, QRCodeImage.Bitmap.Height); if QRCodeImage.Bitmap.Canvas.BeginScene then begin try QRCodeImage.Bitmap.Canvas.Clear(TAlphaColors.White); QRCodeImage.Bitmap.Canvas.DrawBitmap(QRCodeBitmap, rSrc, rDest, 1); finally QRCodeImage.Bitmap.Canvas.EndScene; end; end; finally QRC.Free; end; finally QRCodeBitmap.Free; end; end; end.
unit uTestEventModel; interface uses TestFrameWork, SysUtils, uBase, uEventModel; type TTestObjectName = class( TTestCase ) published procedure TestCommon; end; implementation { TTestObjectName } const VAL_OK = 1; VAL_FAIL = 2; EVENT_ID = 'TEST_EVENT_ID'; var EventDataID : string = ''; type TTestSubscriber = class ( TBaseSubscriber ) public Val : integer; procedure ProcessEvent( const aEventID : TEventID; const aEventData : Variant ); override; end; procedure TTestObjectName.TestCommon; var EventModel : TEventModel; Subscriber : TTestSubscriber; EventData : Variant; begin Subscriber := TTestSubscriber.Create; Subscriber.Val := VAL_FAIL; EventData := 111; EventModel := TEventModel.Create; try EventModel.RegisterSubscriber( EVENT_ID, Subscriber ); EventModel.Event( EVENT_ID, EventData ); CheckEquals( Subscriber.Val, VAL_OK, 'Check Event' ); EventModel.UnRegister( EVENT_ID, Subscriber ); Subscriber.Val := VAL_FAIL; EventModel.Event( EVENT_ID, EventData ); CheckNotEquals( Subscriber.Val, VAL_OK, 'Check Event Unregister'); Subscriber := TTestSubscriber.Create; Subscriber.Val := VAL_FAIL; EventModel.RegisterSubscriber( EVENT_ID, Subscriber ); EventModel.UnRegister( Subscriber ); Subscriber.Val := VAL_FAIL; EventModel.Event( EVENT_ID, EventData ); CheckNotEquals( Subscriber.Val, VAL_OK, 'Check Event Unregister V2 '); finally EventModel.Free; end; end; { TTestSubscriber } procedure TTestSubscriber.ProcessEvent(const aEventID: TEventID; const aEventData: Variant ); begin Val := VAL_OK; end; initialization TestFramework.RegisterTest( TTestObjectName.Suite ); end.
unit uQTZHelper; interface uses SysUtils, Classes, IdHttp, IdURI, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, uGlobal; type TQTZHelper = class private public class function HttpGet(url: string): string; class function HttpPost(url: string; stream: TStream): string; static; class function GetVehInfo(hphm, hpzl: string): string; static; class function Surscreen(sbbh,zqmj,clfl,hpzl,hphm,xzqh,wfdd,lddm,ddms,wfdz, wfsj,wfsj1,wfxw,scz,bzz: string; zpsl: integer; zpwjm,zpstr1,zpstr2,zpstr3,wfspdz: string): string; static; class function QVehbus(hphm, hpzl: string): boolean; static; class function WriteVehicleInfo(const kkbh: string; const fxlx: string; const cdh: Int64; const hphm: string; const hpzl: string; const gcsj: string; const clsd: Int64; const clxs: Int64; const wfdm: string; const cwkc: Int64; const hpys: string; const cllx: string; const fzhpzl: string; const fzhphm: string; const fzhpys: string; const clpp: string; const clwx: string; const csys: string; const tplj: string; const tp1: string; const tp2: string; const tp3: string; const tztp: string): integer; static; class var QTZUrl: string; end; implementation { TQTZHelper } class function TQTZHelper.HttpGet(url: string): string; var http: TIdHttp; begin result := ''; http := TIdHttp.Create(nil); http.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'; try result := http.Get(url); except on e: exception do begin logger.Error('[QTZHelper][HttpGet]' + e.Message + url.Substring(0, 50)); end; end; http.Free; end; class function TQTZHelper.HttpPost(url: string; stream: TStream): string; var http: TIdHttp; begin result := ''; http := TIdHttp.Create(nil); try result := http.Post(url, stream); except on e: exception do begin logger.Error('[QTZHelper][HttpGet]' + e.Message + url.Substring(0, 50)); end; end; http.Free; end; class function TQTZHelper.GetVehInfo(hphm, hpzl: string): string; begin result := ''; if QTZUrl = '' then exit; result := HttpGet(QTZUrl + 'GetVehInfo?hphm=' + hphm + '&hpzl=' + hpzl); end; class function TQTZHelper.QVehbus(hphm, hpzl: string): boolean; var response, s: string; i: integer; begin result := false; if QTZUrl = '' then exit; s := HttpGet(QTZUrl + 'QVehbus?hphm=' + hphm + '&hpzl=' + hpzl); i := response.IndexOf('<kycllx>') + 8; if i > 0 then begin s := response.Substring(i, 1); result := (s = '1') or (s = '2'); end; if not result then begin i := response.IndexOf('<sfjbc>') + 7; if i > 0 then begin s := response.Substring(i, 1); result := s = '1'; end; end; end; class function TQTZHelper.Surscreen(sbbh,zqmj,clfl,hpzl,hphm,xzqh,wfdd,lddm,ddms,wfdz, wfsj,wfsj1,wfxw,scz,bzz: string; zpsl: integer; zpwjm,zpstr1,zpstr2,zpstr3, wfspdz: string): string; var s: string; stream: TStringStream; begin result := ''; if QTZUrl = '' then exit; s := QTZUrl + 'Surscreen?sbbh=' + sbbh; if zqmj <> '' then s := s + '&zqmj=' + zqmj; if clfl <> '' then s := s + '&clfl=' + clfl; if hpzl <> '' then s := s + '&hpzl=' + hpzl; if hphm <> '' then s := s + '&hphm=' + hphm; if xzqh <> '' then s := s + '&xzqh=' + xzqh; if wfdd <> '' then s := s + '&wfdd=' + wfdd; if lddm <> '' then s := s + '&lddm=' + lddm; if ddms <> '' then s := s + '&ddms=' + ddms; if wfdz <> '' then s := s + '&wfdz=' + wfdz; if wfsj <> '' then s := s + '&wfsj=' + wfsj; if wfsj1 <> '' then s := s + '&wfsj1=' + wfsj1; if wfxw <> '' then s := s + '&wfxw=' + wfxw; if scz <> '' then s := s + '&scz=' + scz; if bzz <> '' then s := s + '&bzz=' + bzz; s := s + '&zpsl=' + zpsl.ToString; if zpwjm <> '' then s := s + '&zpwjm=' + zpwjm; {s := s + '&zpstr1=' + zpstr1; if zpstr2 <> '' then s := s + '&zpstr2=' + zpstr2; if zpstr3 <> '' then s := s + '&zpstr3=' + zpstr3; } if wfspdz <> '' then s := s + '&wfspdz=' + wfspdz; stream := TStringStream.Create; stream.WriteString('zpstr1=' + zpstr1); if zpstr2 <> '' then stream.WriteString('&zpstr2=' + zpstr2); if zpstr3 <> '' then stream.WriteString('&zpstr3=' + zpstr3); result := HttpPost(s, stream); stream.Free; end; class function TQTZHelper.WriteVehicleInfo(const kkbh, fxlx: string; const cdh: Int64; const hphm, hpzl, gcsj: string; const clsd, clxs: Int64; const wfdm: string; const cwkc: Int64; const hpys, cllx, fzhpzl, fzhphm, fzhpys, clpp, clwx, csys, tplj, tp1, tp2, tp3, tztp: string): integer; var s: string; begin result := 0; if QTZUrl = '' then exit; s := QTZUrl + 'WriteVehicleInfo?kkbh=' + kkbh + '&fxlx=' + fxlx + '&cdh=' + cdh.ToString + '&hphm=' + hphm + '&hpzl=' + hpzl + '&gcsj=' + gcsj + '&clsd=' + clsd.ToString + '&clxs=' + clxs.ToString + '&wfdm=' + wfdm + '&cwkc=' + cwkc.ToString + '&hpys=' + hpys + '&cllx=' + cllx + '&fzhpzl=' +fzhpzl + '&fzhphm=' +fzhphm + '&fzhpys=' +fzhpys + '&clpp=' + clpp + '&clwx=' + clwx + '&csys=' + csys + '&tplj=' + tplj + '&tp1=' + tp1 + '&tp2=' + tp2 + '&tp3=' + tp3 + '&tztp=' + tztp; s := HttpGet(TIdUri.URLEncode(s)); result := StrToIntDef(s, 0); end; end.
unit Vigilante.Controller.Mediator; interface uses Vigilante.Controller.Base, Module.ValueObject.URL; type TTipoController = (tcBuild, tcCompilacao); IControllerMediator = interface(IInterface) ['{5853E4AA-2002-4A65-8452-B2F40693FD02}'] procedure AdicionarController(const AController: IBaseController; const ATipoController: TTipoController); procedure RemoverController(const ATipoController: TTipoController); procedure AdicionarURL(const ATipoController: TTipoController; const AURL: IURL); end; implementation end.
unit ProductSelect; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, DB, ComCtrls, ToolWin; type TProductSelectForm = class(TForm) Panel1: TPanel; CancelButton: TButton; OKButton: TButton; DBGridEh1: TDBGridEh; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; DBGridEh2: TDBGridEh; Splitter1: TSplitter; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var ProductSelectForm: TProductSelectForm; implementation uses StoreDM, ProductItem; var CloseStatus : Boolean; {$R *.dfm} procedure TProductSelectForm.FormCreate(Sender: TObject); var SQLTxt: String; begin with StoreDataModule do begin if ProductSelectQuery.Active = False then ProductSelectQuery.Open; ProductSelectQuery.Locate('ProductID', CurrentProductID, []); //Если енто расход, то подключаем Партии и отключаем Кнопки "F2", "F8" if (CurType = 1) or (CurType = 0) then begin if StoreSelectQuery.Active = True then StoreSelectQuery.Close; //Перезаписывается SQL-запрос для обновления параметров... SQLTxt := StoreSelectQuery.SQL.Text; StoreSelectQuery.SQL.Clear; StoreSelectQuery.SQL.SetText(PChar(SQLTxt)); StoreSelectQuery.DataSource := ProductSelectDataSource; StoreSelectQuery.ParamByName('PriceID').Value := CurPriceID; StoreSelectQuery.ParamByName('DivisionID').Value := CurDivisionID; StoreSelectQuery.Open; StoreSelectQuery.Locate('StoreID', CurStoreID, []); InsertButton.Visible := False; InsertButton.Enabled := False; DeleteButton.Visible := False; DeleteButton.Enabled := False; end else DBGridEh2.Visible := False; end; Caption := 'Выбор Товара'; end; procedure TProductSelectForm.FormClose(Sender: TObject; var Action: TCloseAction); begin with StoreDataModule do try try if ModalResult = mrOk then begin CurrentProductID := ProductSelectQuery['ProductID']; CurProductFullName := ProductSelectQuery['ProductFullName']; CurVATRate := ProductSelectQuery['VATRate']; CurPack := ProductSelectQuery['Pack']; if (CurType = 1) or (CurType = 0) then begin CurStoreID := StoreSelectQuery['StoreID']; CurPrice := StoreSelectQuery['Price']; end; end; except Application.MessageBox('Недопустимые значения данных', 'Ошибка ввода', mb_IconStop); Abort; end; finally if ProductSelectQuery.Active = True then ProductSelectQuery.Close; ProductSelectQuery.SQL.Strings[4] := ''; if StoreSelectQuery.Active = True then StoreSelectQuery.Close; StoreSelectQuery.DataSource := nil; end; {try finally} end; procedure TProductSelectForm.CancelButtonClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TProductSelectForm.OKButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TProductSelectForm.Edit1Change(Sender: TObject); var Find : String; begin Find := AnsiUpperCase(Edit1.Text); with StoreDataModule.ProductSelectQuery do begin Close; SQL.Strings[4] := ' AND ((UPPER("Categories"."CategoryName" || '' '' || "Products"."ProductName") LIKE ''%' + Find + '%''))'; Open; end; end; procedure TProductSelectForm.InsertButtonClick(Sender: TObject); begin if StoreDataModule.ProductDataSet.Active = False then begin CloseStatus := True; StoreDataModule.ProductDataSet.Open; end; StoreDataModule.ProductDataSet.Append; ProductItemForm := TProductItemForm.Create(Self); ProductItemForm.ShowModal; if ProductItemForm.ModalResult = mrOK then begin StoreDataModule.ProductSelectQuery.Close; StoreDataModule.ProductSelectQuery.Open; StoreDataModule.ProductSelectQuery.Locate('ProductID', CurrentProductID, []); end; if CloseStatus = True then begin StoreDataModule.ProductDataSet.Close; CloseStatus := False; end; end; procedure TProductSelectForm.EditButtonClick(Sender: TObject); begin if StoreDataModule.ProductDataSet.Active = False then begin CloseStatus := True; StoreDataModule.ProductDataSet.Open; end; StoreDataModule.ProductDataSet.Locate('ProductID', StoreDataModule.ProductSelectQuery['ProductID'], []); StoreDataModule.ProductDataSet.Edit; ProductItemForm := TProductItemForm.Create(Self); ProductItemForm.ShowModal; if ProductItemForm.ModalResult = mrOK then begin StoreDataModule.ProductSelectQuery.Close; StoreDataModule.ProductSelectQuery.Open; StoreDataModule.ProductSelectQuery.Locate('ProductID', CurrentProductID, []); end; if CloseStatus = True then begin StoreDataModule.ProductDataSet.Close; CloseStatus := False; end; end; procedure TProductSelectForm.DeleteButtonClick(Sender: TObject); var ProductStr : String; begin ProductStr := StoreDataModule.ProductSelectQuery.FieldByName('ProductFullName').AsString; if StoreDataModule.ProductDataSet.Active = False then begin CloseStatus := True; StoreDataModule.ProductDataSet.Open; end; StoreDataModule.ProductDataSet.Locate('ProductID', StoreDataModule.ProductSelectQuery['ProductID'], []); if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' + ProductStr + '"?'), 'Удаление записи', mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then try StoreDataModule.ProductDataSet.Delete; except Application.MessageBox(PChar('Запись "' + ProductStr + '" удалять нельзя.'), 'Ошибка удаления', mb_IconStop); end; if CloseStatus = True then begin StoreDataModule.ProductDataSet.Close; CloseStatus := False; end; StoreDataModule.ProductSelectQuery.Close; StoreDataModule.ProductSelectQuery.Open; end; procedure TProductSelectForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN : OKButton.Click; VK_F2 : if InsertButton.Enabled = true then InsertButton.Click; VK_F3 : if EditButton.Enabled = true then EditButton.Click; VK_F8 : if DeleteButton.Enabled = true then DeleteButton.Click; VK_F4 : Edit1.SetFocus; end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { Misc helpful URLs: Implementing a Custom Download Manager http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/ext/overview/downloadmgr.asp Programming and Reusing the Browser Overviews and Tutorials http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/overview/prog_browser_ovw_entry.asp About Asynchronous Pluggable Protocols http://msdn.microsoft.com/workshop/networking/pluggable/overview/overview.asp Element Behaviors in Internet Explorer 5.5 http://msdn.microsoft.com/msdnmag/issues/1200/cutting/cutting1200.asp Binary Behaviors in Internet Explorer 5.5 http://msdn.microsoft.com/msdnmag/issues/01/01/cutting/cutting0101.asp HOWTO: Handle Script Errors as a WebBrowser Control Host http://support.microsoft.com/default.aspx?scid=KB;EN-US;q261003 WebBrowser Customization http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/hosting/wbcustomization.asp Viva Components! http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndude/html/dude01032000.asp The following is the HTML necessary to have IE instantial an element behavior. <HTML XMLNS:CUSTOM> <HEAD> <OBJECT ID="customFactory" CLASSID="clsid:D979404F-4FDD-465F-86DD-64E1B34AA6BA"></OBJECT> <?IMPORT NAMESPACE="CUSTOM" IMPLEMENTATION="#customFactory" /> </HEAD> <BODY> <CUSTOM:TEST></CUSTOM:TEST> </BODY> </HTML> IElementBehaviorFactory::FindBehavior http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/behaviors/reference/ifaces/elementnamespacefactory2/ielementnamespacefactory2.asp "Specify the case of the bstrBehavior parameter to be all caps when using this method with element behaviors; for attached behaviors specify the bstrBehavior parameter in lower case." Note: After initially browsing to about:blank the format of the document loaded loaded in the browser is unicode. Therefore to change the encoding to ansi you must call LoadFromFile/Stream with ansi data. } unit WebBrowserEx; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Graphics, Vcl.OleCtrls, Winapi.ActiveX, SHDocVw, MSHTML, mshtmcid, idoc, System.Contnrs, Mshtmdid, Winapi.URLMon {$IFDEF EVENTSINKSUBCOMPONENTS} , MSHTMLEvents, SHDocVwEvents; {$ELSE} ; {$ENDIF} const // From mshtml.h SID_SHTMLEditServices: TGUID = '{3050f7f9-98b5-11cf-bb82-00aa00bdce0b}'; // SID_SElementBehaviorFactory = IID_IElementBehaviorFactory; // From downloadmgr.h SID_SDownloadManager: TGUID = '{988934A4-064B-11D3-BB80-00104B35E7F9}'; // SHLGUID.H SID_STopLevelBrowser: TGUID = '{4C96BE40-915C-11CF-99D3-00AA004AE837}'; // From mshtmhst.h (undocumented) CGID_MSHTML: TGUID = '{DE4BA900-59CA-11CF-9592-444553540000}'; CGID_DocHostCommandHandler: TGUID = '{f38bc242-b950-11d1-8918-00c04fc2c836}'; DOCHOSTUIDBLCLK_DEFAULT = 0; DOCHOSTUIDBLCLK_SHOWPROPERTIES = 1; DOCHOSTUIDBLCLK_SHOWCODE = 2; // Constants from mshtml.h (why aren't these in the IDL file!!) ELEMENTNAMESPACEFLAGS_ALLOWANYTAG = 1; ELEMENTNAMESPACEFLAGS_QUERYFORUNKNOWNTAGS = 2; // IID_IHTMLDocument2: TGUID = '{332C4425-26CB-11D0-B483-00C04FD90119}'; CLSID_HTMLDocument: TGUID = '{25336920-03F9-11CF-8FD0-00AA00686F13}'; OLECMDID_OPENNEWWINDOW = 7050; GUID_TriEditCommandGroup: TGUID = '{2582F1C0-084E-11d1-9A0E-006097C9B344}'; type TControlBorder = (cb3D, cbNone); TWebBrowserEx = class; { TCustomWebBrowserComponent } TCustomWebBrowserComponent = class(TComponent) private FWebBrowser: TWebBrowserEx; FOnBrowserChanged: TNotifyEvent; protected procedure CheckWebBrowserAssigned; procedure CheckDocumentAssigned; procedure SetWebBrowser(const Value: TWebBrowserEx); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property WebBrowser: TWebBrowserEx read FWebBrowser write SetWebBrowser; property OnBrowserChanged: TNotifyEvent read FOnBrowserChanged write FOnBrowserChanged; end; { TWebBrowserServiceProvider } TWebBrowserServiceProvider = class(TCustomWebBrowserComponent) protected FServiceGUID: TGUID; procedure SetWebBrowser(const Value: TWebBrowserEx); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ServiceGUID: TGUID read FServiceGUID write FServiceGUID; end; { TEventDispatchEx } TEventDispatchEx = class(TObject, IUnknown, IDispatch) private FActive: Boolean; FConnection: Longint; FInternalCount: Integer; procedure SetActive(const Value: Boolean); protected FIID: TGUID; function GetEventInterface: IInterface; virtual; abstract; { IUnknown } function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HRESULT; virtual; stdcall; { IDispatch } function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount: Integer; LocaleID: Integer; DispIDs: Pointer): HRESULT; stdcall; function GetTypeInfo(Index: Integer; LocaleID: Integer; out TypeInfo): HRESULT; stdcall; function GetTypeInfoCount(out Count: Integer): HRESULT; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult: Pointer; ExcepInfo: Pointer; ArgErr: Pointer): HRESULT; stdcall; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; virtual; public destructor Destroy; override; property Active: Boolean read FActive write SetActive; property IID: TGUID read FIID; end; { THTMLElementEventDispatch } THTMLElementEventDispatch = class(TEventDispatchEx) private FHTMLElement: IHTMLElement; protected function GetEventInterface: IInterface; override; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; override; function QueryInterface(const IID: TGUID; out Obj): HRESULT; override; stdcall; public procedure AfterConstruction; override; property HTMLElement: IHTMLElement read FHTMLElement write FHTMLElement; end; { TWebBrowserEventDispatch } TWebBrowserEventDispatch = class(TEventDispatchEx) protected FWebBrowser: TWebBrowserEx; public property WebBrowser: TWebBrowserEx read FWebBrowser; end; { TDocEventDispatch - HTMLDocumentEvents2 event sink } TDocEventDispatch = class(TWebBrowserEventDispatch) protected function GetEventInterface: IInterface; override; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; override; public procedure AfterConstruction; override; end; { TIFrameDocEventDispatch - used to prevent editing of iframes } TIFrameDocEventDispatch = class(TDocEventDispatch) private FDocument: IHTMLDocument2; protected function GetEventInterface: IInterface; override; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; override; public property Document: IHTMLDocument2 read FDocument write FDocument; end; { TWndEventDispatch - HTMLWindowEvents2 event sink } TWndEventDispatch = class(TWebBrowserEventDispatch) protected function GetEventInterface: IInterface; override; function GetHTMLWindow2: IHTMLWindow2; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; override; public procedure AfterConstruction; override; property HTMLWindow2: IHTMLWindow2 read GetHTMLWindow2; end; { TWebBrowserEvents2Dispatch - DWebBrowserEvents2 event sink } TWebBrowserEvents2Dispatch = class(TWebBrowserEventDispatch) protected function GetEventInterface: IInterface; override; procedure DoStatusTextChange(const Text: WideString); virtual; procedure DoProgressChange(Progress: Integer; ProgressMax: Integer); virtual; procedure DoCommandStateChange(Command: TOleEnum; Enable: WordBool); virtual; procedure DoDownloadBegin; virtual; procedure DoDownloadComplete; virtual; procedure DoTitleChange(const Text: WideString); virtual; procedure DoPropertyChange(const szProperty: WideString); virtual; procedure DoBeforeNavigate2(const pDisp: IDispatch; var URL: OleVariant; var Flags: OleVariant; var TargetFrameName: OleVariant; var PostData: OleVariant; var Headers: OleVariant; var Cancel: WordBool); virtual; procedure DoNewWindow2(var ppDisp: IDispatch; var Cancel: WordBool); virtual; procedure DoNavigateComplete2(const pDisp: IDispatch; var URL: OleVariant); virtual; procedure DoDocumentComplete(const pDisp: IDispatch; var URL: OleVariant); virtual; procedure DoOnQuit; virtual; procedure DoOnVisible(Visible: WordBool); virtual; procedure DoOnToolBar(ToolBar: WordBool); virtual; procedure DoOnMenuBar(MenuBar: WordBool); virtual; procedure DoOnStatusBar(StatusBar: WordBool); virtual; procedure DoOnFullScreen(FullScreen: WordBool); virtual; procedure DoOnTheaterMode(TheaterMode: WordBool); virtual; procedure DoWindowSetResizable(Resizable: WordBool); virtual; procedure DoWindowSetLeft(Left: Integer); virtual; procedure DoWindowSetTop(Top: Integer); virtual; procedure DoWindowSetWidth(Width: Integer); virtual; procedure DoWindowSetHeight(Height: Integer); virtual; procedure DoWindowClosing(IsChildWindow: WordBool; var Cancel: WordBool); virtual; procedure DoClientToHostWindow(var CX: Integer; var CY: Integer); virtual; procedure DoSetSecureLockIcon(SecureLockIcon: Integer); virtual; procedure DoFileDownload(var Cancel: WordBool); virtual; procedure DoNavigateError(const pDisp: IDispatch; var URL: OleVariant; var Frame: OleVariant; var StatusCode: OleVariant; var Cancel: WordBool); virtual; procedure DoPrintTemplateInstantiation(const pDisp: IDispatch); virtual; procedure DoPrintTemplateTeardown(const pDisp: IDispatch); virtual; procedure DoUpdatePageStatus(const pDisp: IDispatch; var nPage: OleVariant; var fDone: OleVariant); virtual; procedure DoPrivacyImpactedStateChange(bImpacted: WordBool); virtual; function DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; override; public procedure AfterConstruction; override; end; { TWebBrowserEx } TCurrentElementType = (cetUndefined, cetNone, cetAtCursor, cetTextRange, cetControlRange); TElementEditableFlag = (efInnerOrOuterRequired, efInnerRequired, efOuterRequired, efSelectableControlRequired); TElementEditableFlags = set of TElementEditableFlag; TCommandState = (csSupported, csEnabled, csChecked); TCommandStates = set of TCommandState; TCommandStateArray = array of _tagOLECMD; TWebBrowserEvent = procedure(Sender: TWebBrowserEx; Event: IHTMLEventObj) of object; TWebBrowserEventWordBool = function(Sender: TWebBrowserEx; Event: IHTMLEventObj): WordBool of object; TWebBrowserNotifyEvent = procedure(Sender: TWebBrowserEx) of object; TWndActivateEvent = procedure(Sender: TWebBrowser; Activate: Boolean; var hr: HRESULT) of object; TCustomWebBrowserCommandUpdater = class; TGetExternalDispatchEvent = procedure (Sender: TObject; out ExternalDisp: IDispatch) of object; TStatusTextChangeEvent = procedure (Sender: TObject; const Text: string) of object; TControlSelectEvent = function(Sender: TWebBrowser; const EventObj: IHTMLEventObj): WordBool of object; TControlMoveEvent = function(Sender: TWebBrowser; const EventObj: IHTMLEventObj; DispID: Integer): WordBool of object; TControlResizeEvent = function(Sender: TWebBrowser; const EventObj: IHTMLEventObj; DispID: Integer): WordBool of object; TResolveRelativePathEvent = procedure(Sender: TWebBrowser; var Path: string) of object; TGetDropTargetEvent = procedure(Sender: TObject; const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget) of object; TShowContextMenuEvent = procedure(Sender: TObject; dwID: UINT; ppt: PtagPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch; var Result: HRESULT) of object; TInitMenuPopupEvent = procedure(Sender: TObject; Menu: HMENU; Pos: SmallInt; SystemMenu: Boolean) of object; TWindowClosingEvent = procedure(Sender: TObject; IsChildWindow: Boolean; var Cancel: WordBool) of object; TGetSelectionObjectEvent = procedure(Sender: TObject; var ppSelectionObject: IHTMLSelectionObject) of object; TGetActiveDocumentEvent = procedure(Sender: TObject; var ppDocumentObject: IHTMLDocument) of object; TGetHostInfoEvent = function(Sender: TObject; var pInfo: _DOCHOSTUIINFO): HRESULT of object; TGetAmbientControlEvent = function(Sender: TObject; var Flags: Integer): HRESULT of object; TPreProcessMessageEvent = procedure(Sender: TObject; var Msg: TMsg; out Handled: Boolean) of object; TInterceptMouseMessageEvent = procedure(Sender: TObject; var Message: TMessage; out Handled: Boolean) of object; TGetElementOfViewLinkDocumentEvent = procedure(Sender: TObject; ADocument: IHTMLDocument; out AElement: IHTMLElement) of object; TGetIsEditableElementEvent = procedure(Sender: TObject; AElement: IHTMLElement; AFlags: TElementEditableFlags; out AIsEditable: Boolean) of object; TGetIsContentPageEvent = procedure(Sender: TObject; out AIsContentPage: Boolean) of object; TGetViewLinkDocumentsEvent = procedure(Sender: TObject; CmdId: TOleEnum; var pDocuments: IInterfaceList) of object; TWebBrowserEx = class(TWebBrowser, IUnknown, IDispatch, IDocHostUIHandler, IDocHostUIHandler2, IDocHostShowUI, IServiceProvider, IOleCommandTarget, IHTMLChangeSink) private FBeforeLoadFromStream: TWebBrowserNotifyEvent; FBeforeDestroy: TWebBrowserNotifyEvent; FUserMode: WordBool; FURL: String; FControlBorder: TControlBorder; FShowScrollBar: Boolean; FFlatScrollBar: Boolean; FHTMLSelectionObject: IHTMLSelectionObject; FHasFocus: Boolean; {$IFDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch: TMSHTMLHTMLDocumentEvents2; FWndEventDispatch: TMSHTMLHTMLWindowEvents2; FWebBrowserEvents2Dispatch: TSHDocVwDWebBrowserEvents2; {$ELSE} FDocEventDispatch: TDocEventDispatch; FWndEventDispatch: TWndEventDispatch; FWebBrowserEvents2Dispatch: TWebBrowserEvents2Dispatch; {$ENDIF} FChangeLog: IHTMLChangeLog; FDocEventDispatchCounter: IUnknown; FWndEventDispatchCounter: IUnknown; FWebBrowserEvents2DispatchCounter: IUnknown; FOnMouseOut: TMouseMoveEvent; FOnMouseOver: TMouseMoveEvent; FAfterUpdate: TNotifyEvent; FBeforeUpdate: TNotifyEvent; FOnError: TNotifyEvent; FOnSelectStart: TNotifyEvent; FOnRowExit: TNotifyEvent; FOnRowEnter: TNotifyEvent; FOnErrorUpdate: TNotifyEvent; FOnLoad: TNotifyEvent; FOnHelp: TNotifyEvent; FOnUnLoad: TNotifyEvent; FOnFocus: TNotifyEvent; FOnBlur: TNotifyEvent; FOnScroll: TNotifyEvent; FOnWndResize: TNotifyEvent; FBeforeUnload: TNotifyEvent; FOnDocWndActivate: TWndActivateEvent; FOnFrameWndActivate: TWndActivateEvent; FServiceProviders: TComponentList; FCommandUpdater: TCustomWebBrowserCommandUpdater; FOnReadyStateChange: TNotifyEvent; FOnGetExternalDispatch: TGetExternalDispatchEvent; FOnStatusTextChange: TStatusTextChangeEvent; FOnSelectionChange: TWebBrowserEvent; FOnUpdateCommands: TNotifyEvent; FOnCancelMode: TNotifyEvent; FOnGetDropTarget: TGetDropTargetEvent; FOnWindowClosing: TWindowClosingEvent; FDisplayServices: IDisplayServices; FCaret: IHTMLCaret; FMarkupServices: IMarkupServices2; FPrimarySelectionServices: ISelectionServices; FDefInetExplorerServerProc: Pointer; FDefShellObjViewProc: Pointer; FShellDocObjViewHandle: THandle; FInetExplorerServerHandle: THandle; FShellDocObjInstance: Pointer; FInetExplorerServerInstance: Pointer; FUseDivBlock: Boolean; FUseTheme: Boolean; FHooksSet: Boolean; FAutoComplete: Boolean; FOnControlSelect: TControlSelectEvent; FOnResolveRelativePath: TResolveRelativePathEvent; FOnShowContextMenu: TShowContextMenuEvent; FOnInitMenuPopup: TInitMenuPopupEvent; FOnOpenNewWindow: TNotifyEvent; FOnReloadDocument: TWebBrowserNotifyEvent; FOnControlMove: TControlMoveEvent; FOnControlResize: TControlResizeEvent; FBaseURL: string; FOnChange: TNotifyEvent; FOnGetSelectionObject: TGetSelectionObjectEvent; FOnGetActiveDocument: TGetActiveDocumentEvent; FOnGetViewLinkDocuments: TGetViewLinkDocumentsEvent; FOnGetElementOfViewLinkDocument: TGetElementOfViewLinkDocumentEvent; FOnGetIsEditableElement: TGetIsEditableElementEvent; FOnGetIsContentPage: TGetIsContentPageEvent; FOnBeforeEditFocus: TWebBrowserEventWordBool; FOnGetHostInfo: TGetHostInfoEvent; FOnGetAmbientControlInfo: TGetAmbientControlEvent; FOnPreProcessMessage: TPreProcessMessageEvent; FOnInterceptMouseMessage: TInterceptMouseMessageEvent; FCurrentElement: IHTMLElement; FCurrentElementType: TCurrentElementType; procedure SetUserMode(const Value: WordBool); function GetTag(Index: Integer): IHTMLElement; function GetDocument2: IHTMLDocument2; procedure SetURL(Value: String); function GetActiveElement: IHTMLElement; function GetCount: Integer; procedure SetControlBorder(const Value: TControlBorder); procedure SetFlatScrollBar(const Value: Boolean); procedure SetShowScrollBar(const Value: Boolean); function GetWindow: IHTMLWindow2; function GetServiceProvider: IServiceProvider; function GetHTMLEditServices: IHTMLEditServices2; function GetCommandTarget: IOleCommandTarget; function GetDocument3: IHTMLDocument3; function GetDisplayServices: IDisplayServices; function GetHighlightRenderingServices: IHighlightRenderingServices; function GetMarkupServices: IMarkupServices2; function GetPrimaryMarkupContainer: IMarkupContainer2; function GetDocument4: IHTMLDocument4; function GetIHTMLNamespaceCollection: IHTMLNamespaceCollection; function GetModified: Boolean; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE; function GetCaret: IHTMLCaret; procedure CMRecreatewnd(var Message: TMessage); message CM_RECREATEWND; procedure SetCommandUpdater(const Value: TCustomWebBrowserCommandUpdater); procedure WMParentNotify(var Message: TWMParentNotify); message WM_PARENTNOTIFY; function GetOverrideCursor: Boolean; procedure SetOverrideCursor(const Value: Boolean); procedure SetModified(const Value: Boolean); function GetActiveDocument: IHTMLDocument; function GetCurrentElement: IHTMLElement; function GetCurrentElementType: TCurrentElementType; procedure ClearCurrentElement; protected FBackEnabled: Boolean; FForwardEnabled: Boolean; procedure ShellWndProc(var Message: TMessage; Wnd: HWnd; WndProc: Pointer); procedure DestroyWindowHandle; override; procedure DoStatusTextChange(const Text: string); procedure DoResolveRelativePath(var Path: string); function DoOnControlSelect(const EventObj: IHTMLEventObj): WordBool; safecall; function DoOnControlMove(const EventObj: IHTMLEventObj; DispID: Integer): WordBool; function DoOnControlResize(const EventObj: IHTMLEventObj; DispID: Integer): WordBool; function DoBeforeEditFocus(const EventObj: IHTMLEventObj; const DispID: Integer): WordBool; procedure DoCommandStateChange(Command: TOleEnum; Enable: WordBool); procedure DoUpdateCommands; procedure Loaded; override; procedure HookChildWindows; procedure UnHookChildWindows; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ShellDocObjWndProc(var Message: TMessage); procedure InetExplorerServerWndProc(var Message: TMessage); { IDispatch } function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; { IDocHostShowUI } function ShowMessage(hwnd: THandle;lpstrText: POLESTR;lpstrCaption: POLESTR; dwType: longint;lpstrHelpFile: POLESTR;dwHelpContext: longint; var plResult: LRESULT): HRESULT; stdcall; function ShowHelp(hwnd: THandle; pszHelpFile: POLESTR; uCommand: UINT; dwData: longint; ptMouse: TPoint; var pDispachObjectHit: IDispatch): HRESULT; stdcall; { IDocHostUIHandler } function EnableModeless(fEnable: Integer): HResult; stdcall; function FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HResult; stdcall; function GetDropTarget(const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HResult; stdcall; function GetExternal(out ppDispatch: IDispatch): HResult; stdcall; function GetHostInfo(var pInfo: _DOCHOSTUIINFO): HResult; stdcall; function GetOptionKeyPath(out pchKey: PWideChar; dw: UINT): HResult; stdcall; function HideUI: HResult; stdcall; function OnDocWindowActivate(fActivate: Integer): HResult; stdcall; function OnFrameWindowActivate(fActivate: Integer): HResult; stdcall; function ResizeBorder(var prcBorder: tagRECT; const pUIWindow: IOleInPlaceUIWindow; fRameWindow: Integer): HResult; stdcall; function ShowUI(dwID: UINT; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HResult; stdcall; function TranslateAccelerator(var lpmsg: tagMSG; var pguidCmdGroup: TGUID; nCmdID: UINT): HResult; stdcall; function TranslateUrl(dwTranslate: UINT; pchURLIn: PWideChar; out ppchURLOut: PWideChar): HResult; stdcall; function UpdateUI: HResult; stdcall; { IDocHostUIHandler2 } function GetOverrideKeyPath(out pchKey: PWideChar; dw: DWORD): HRESULT; stdcall; function OnFocus(fGotFocus: BOOL): HResult; stdcall; { IServiceProvider } function QueryService(const rsid: TGUID; const iid: TGUID; out Obj): HRESULT; stdcall; { IOleCommandTarget } function QueryStatus(CmdGroup: PGUID; cCmds: Cardinal; prgCmds: POleCmd; CmdText: POleCmdText): HResult; stdcall; function Exec(CmdGroup: PGUID; nCmdID, nCmdexecopt: DWORD; const vaIn: OleVariant; var vaOut: OleVariant): HResult; stdcall; { function QueryStatus(const pguidCmdGroup: PGUID; cCmds: UINT; prgCmds: POleCmd; pCmdText: PtagOLECMDTEXT): HResult; stdcall; function Exec(const pguidCmdGroup: PGUID; nCmdID: UINT; nCmdexecopt: UINT; pvaIn: POleVariant; pvaOut: POleVariant): HResult; stdcall;} { IHTMLChangeSink } function Notify: HRESULT; stdcall; { TOleControl } procedure InvokeEvent(DispID: TDispID; var Params: TDispParams); override; procedure MouseOut(Shift: TShiftState; X, Y: Integer); dynamic; procedure MouseOver(Shift: TShiftState; X, Y: Integer); dynamic; procedure DoError; dynamic; procedure DoBeforeUpdate; dynamic; procedure DoAfterUpdate; dynamic; procedure DoReadyStateChange; dynamic; { TWndEventDispatch events } procedure DoWndResize; dynamic; procedure DoScroll; dynamic; procedure DoFocus; dynamic; procedure DoBlur; dynamic; procedure DoHelp; dynamic; procedure DoLoad; dynamic; procedure DoUnLoad; dynamic; procedure DoBeforeUnLoad; dynamic; { TDocEventDispatch } procedure ErrorUpdate; dynamic; procedure RowEnter; dynamic; procedure RowExit; dynamic; procedure SelectStart; dynamic; procedure SelectionChange; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function PreProcessMessage(var Msg: TMsg): Boolean; override; procedure DoCommand(const CmdStr: String); overload; procedure DoCommand(const Cmd: TOleEnum; InParam: OleVariant; OutParam: OleVariant); overload; function CommandState(const CmdID: TOleEnum): TCommandStates; overload; function CommandState(Cmds: TCommandStateArray): TCommandStateArray; overload; function ShowContextMenu(dwID: UINT; ppt: PtagPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HResult; stdcall; procedure ForceSelectionChange; procedure Bold; function Focused: Boolean; override; procedure Italic; procedure Underline; procedure CutToClipBoard; procedure CopyToClipBoard; procedure PasteFromClipBoard; procedure Delete; procedure Undo; procedure Redo; procedure SelectAll; procedure Clear; function SelLength: Integer; function Selection: IHTMLSelectionObject; procedure CreateBookmark; procedure Overwrite; function GetViewLinkDocuments(CmdId: TOleEnum): IInterfaceList; function GetElementOfViewLinkDocument(ADocument: IHTMLDocument): IHTMLElement; function GetIsEditableElement(AElement: IHTMLElement; AFlags: TElementEditableFlags): Boolean; function GetIsContentPage: Boolean; { Print Operations } procedure Print; procedure PageSetup; procedure PrintPreview; { File Operations } procedure ClearDirtyFlag; procedure Open; procedure Save; procedure SaveAs; procedure LoadFromStream(S: TStream); procedure LoadFromFile(const FileName: string); virtual; procedure SaveToStream(S: TStream); procedure SaveToFile(const FileName: string); virtual; procedure ViewSource; function GetSelectionServices: ISelectionServices; procedure RegisterServiceProvider(Provider: TWebBrowserServiceProvider); procedure UnRegisterServiceProvider(Provider: TWebBrowserServiceProvider); property BackEnabled: Boolean read FBackEnabled; property Caret: IHTMLCaret read GetCaret; property CommandUpdater: TCustomWebBrowserCommandUpdater read FCommandUpdater write SetCommandUpdater; property ForwardEnabled: Boolean read FForwardEnabled; property CommandTarget: IOleCommandTarget read GetCommandTarget; property DisplayServices: IDisplayServices read GetDisplayServices; property Document2: IHTMLDocument2 read GetDocument2; property Document3: IHTMLDocument3 read GetDocument3; property Document4: IHTMLDocument4 read GetDocument4; property HTMLEditServices: IHTMLEditServices2 read GetHTMLEditServices; property HighlightRenderingServices: IHighlightRenderingServices read GetHighlightRenderingServices; property MarkupServices: IMarkupServices2 read GetMarkupServices; property Modified: Boolean read GetModified write SetModified; property Namespaces: IHTMLNamespaceCollection read GetIHTMLNamespaceCollection; property OverrideCursor: Boolean read GetOverrideCursor write SetOverrideCursor; property PrimaryMarkupContainer: IMarkupContainer2 read GetPrimaryMarkupContainer; property ServiceProvider: IServiceProvider read GetServiceProvider; property SelectionServices: ISelectionServices read GetSelectionServices; property ShellDocObjViewHandle: THandle read FShellDocObjViewHandle; property InetExplorerServerHandle: THandle read FInetExplorerServerHandle; property ActiveElement: IHTMLElement read GetActiveElement; property Count: Integer read GetCount; property Tags[Index: Integer]: IHTMLElement read GetTag; property Window: IHTMLWindow2 read GetWindow; {$IFNDEF EVENTSINKSUBCOMPONENTS} property DocEvents: TDocEventDispatch read FDocEventDispatch; property WndEvents: TWndEventDispatch read FWndEventDispatch; property WebBrowserEvents: TWebBrowserEvents2Dispatch read FWebBrowserEvents2Dispatch; {$ENDIF} property CurrentElement: IHTMLElement read GetCurrentElement; property CurrentElementType: TCurrentElementType read GetCurrentElementType; published property AutoComplete: Boolean read FAutoComplete write FAutoComplete; property ActiveDocument: IHTMLDocument read GetActiveDocument; property BaseURL: string read FBaseURL write FBaseURL; property BeforeDestroy: TWebBrowserNotifyEvent read FBeforeDestroy write FBeforeDestroy; {$IFDEF EVENTSINKSUBCOMPONENTS} property DocEvents: TMSHTMLHTMLDocumentEvents2 read FDocEventDispatch write FDocEventDispatch; property WndEvents: TMSHTMLHTMLWindowEvents2 read FWndEventDispatch write FWndEventDispatch; property WebBrowserEvents: TSHDocVwDWebBrowserEvents2 read FWebBrowserEvents2Dispatch write FWebBrowserEvents2Dispatch; {$ENDIF} property Constraints; property FlatScrollBar: Boolean read FFlatScrollBar write SetFlatScrollBar default False; property ShowScrollBar: Boolean read FShowScrollBar write SetShowScrollBar default True; property ControlBorder: TControlBorder read FControlBorder write SetControlBorder; property UserMode: WordBool read FUserMode write SetUserMode; property UseDivBlock: Boolean read FUseDivBlock write FUseDivBlock; property UseTheme: Boolean read FUseTheme write FUseTheme; property URL: String read FURL write SetURL; property BeforeLoadFromStream: TWebBrowserNotifyEvent read FBeforeLoadFromStream write FBeforeLoadFromStream; property BeforeUpdate: TNotifyEvent read FBeforeUpdate write FBeforeUpdate; property AfterUpdate: TNotifyEvent read FAfterUpdate write FAfterUpdate; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnDblClick; property OnCancelMode: TNotifyEvent read FOnCancelMode write FOnCancelMode; property OnClick; property OnError: TNotifyEvent read FOnError write FOnError; property OnErrorUpdate: TNotifyEvent read FOnErrorUpdate write FOnErrorUpdate; property OnGetAmbientControlInfo: TGetAmbientControlEvent read FOnGetAmbientControlInfo write FOnGetAmbientControlInfo; property OnGetHostInfo: TGetHostInfoEvent read FOnGetHostInfo write FOnGetHostInfo; property OnReloadDocument: TWebBrowserNotifyEvent read FOnReloadDocument write FOnReloadDocument; property OnResolveRelativePath: TResolveRelativePathEvent read FOnResolveRelativePath write FOnResolveRelativePath; property OnPreprocessMessage: TPreProcessMessageEvent read FOnPreprocessMessage write FOnPreprocessMessage; property OnInterceptMouseMessage: TInterceptMouseMessageEvent read FOnInterceptMouseMessage write FOnInterceptMouseMessage; { IDocHostUIHandler } property OnDocWndActivate: TWndActivateEvent read FOnDocWndActivate write FOnDocWndActivate; property OnFrameWndActivate: TWndActivateEvent read FOnFrameWndActivate write FOnFrameWndActivate; property OnGetExternalDispatch: TGetExternalDispatchEvent read FOnGetExternalDispatch write FOnGetExternalDispatch; property OnStatusTextChange: TStatusTextChangeEvent read FOnStatusTextChange write FOnStatusTextChange; property OnGetDropTarget: TGetDropTargetEvent read FOnGetDropTarget write FOnGetDropTarget; property OnGetSelectionObject: TGetSelectionObjectEvent read FOnGetSelectionObject write FOnGetSelectionObject; property OnGetActiveDocument: TGetActiveDocumentEvent read FOnGetActiveDocument write FOnGetActiveDocument; property OnGetViewLinkDocuments: TGetViewLinkDocumentsEvent read FOnGetViewLinkDocuments write FOnGetViewLinkDocuments; property OnGetElementOfViewLinkDocument: TGetElementOfViewLinkDocumentEvent read FOnGetElementOfViewLinkDocument write FOnGetElementOfViewLinkDocument; property OnGetIsEditableElement: TGetIsEditableElementEvent read FOnGetIsEditableElement write FOnGetIsEditableElement; property OnGetIsContentPage: TGetIsContentPageEvent read FOnGetIsContentPage write FOnGetIsContentPage; property OnShowContextMenu: TShowContextMenuEvent read FOnShowContextMenu write FOnShowContextMenu; property OnInitMenuPopup: TInitMenuPopupEvent read FOnInitMenuPopup write FOnInitMenuPopup; property OnOpenNewWindow: TNotifyEvent read FOnOpenNewWindow write FOnOpenNewWindow; property OnWindowClosing: TWindowClosingEvent read FOnWindowClosing write FOnWindowClosing; { TWndEventDispatch events } property BeforeUnload: TNotifyEvent read FBeforeUnload write FBeforeUnload; property OnBlur: TNotifyEvent read FOnBlur write FOnBlur; // property OnFocus: TNotifyEvent read FOnFocus write FOnFocus; property OnHelp: TNotifyEvent read FOnHelp write FOnHelp; property OnLoad: TNotifyEvent read FOnLoad write FOnLoad; property OnUnLoad: TNotifyEvent read FOnUnLoad write FOnUnLoad; property OnWndResize: TNotifyEvent read FOnWndResize write FOnWndResize; property OnScroll: TNotifyEvent read FOnScroll write FOnScroll; { TDocEventDispatch events } property OnReadyStateChange: TNotifyEvent read FOnReadyStateChange write FOnReadyStateChange; property OnSelectionChange: TWebBrowserEvent read FOnSelectionChange write FOnSelectionChange; property OnBeforeEditFocus: TWebBrowserEventWordBool read FOnBeforeEditFocus write FOnBeforeEditFocus; { WebBrowser Events } property OnUpdateCommands: TNotifyEvent read FOnUpdateCommands write FOnUpdateCommands; property OnControlSelect: TControlSelectEvent read FOnControlSelect write FOnControlSelect; property OnMouseMove; property OnMouseDown; property OnMouseOut: TMouseMoveEvent read FOnMouseOut write FOnMouseOut; property OnMouseOver: TMouseMoveEvent read FOnMouseOver write FOnMouseOver; property OnRowEnter: TNotifyEvent read FOnRowEnter write FOnRowEnter; property OnRowExit: TNotifyEvent read FOnRowExit write FOnRowExit; property OnSelectStart: TNotifyEvent read FOnSelectStart write FOnSelectStart; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnControlMove: TControlMoveEvent read FOnControlMove write FOnControlMove; property OnControlResize: TControlResizeEvent read FOnControlResize write FOnControlResize; end; { TWebBrowserCommandUpdater This class was introduced to minimize the impact of calling QueryStatus multiple times with only a single command ID. This class collects all of the command IDs to be queried and queries them at one time thus saving multiple calls. Actions can simply check CommandUpdater.CommandState to retrieve the state of a registered command. } // So far we only have identifiers for the property changes that affect asp controls TElementProperty = (epWidth, epHeight); TElementProperties = set of TElementProperty; TCommandUpdaterEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; CmdID: Cardinal) of object; TCommandUpdaterBeforeExecuteEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; CmdID: Cardinal; var Executed: Boolean) of object; TSaveActionStateEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; Action: TObject; State: TCommandState; Value: Boolean) of object; TGetActionStateEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; Action: TObject; State: TCommandState; var Value: Boolean; var HaveState: Boolean) of object; TElementPropertiesChangedEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; Element: IHTMLElement; Properties: TElementProperties) of object; TFilterCommandStateEvent = procedure(Sender: TCustomWebBrowserCommandUpdater; CmdID: TOleEnum; var State: TCommandStates) of object; TCustomWebBrowserCommandUpdater = class(TCustomWebBrowserComponent) private FCmds: TCommandStateArray; FOnUpdateCommands: TCommandUpdaterEvent; FBeforeCommand: TCommandUpdaterBeforeExecuteEvent; FAfterCommand: TCommandUpdaterEvent; FOnGetActionState: TGetActionStateEvent; FOnSaveActionState: TSaveActionStateEvent; FOnElementPropertiesChanged: TElementPropertiesChangedEvent; FOnFilterCommandState: TFilterCommandStateEvent; procedure QuickSort(L, R: Integer); function Find(const CmdID: TOleEnum; var Index: Integer): Boolean; protected procedure SetWebBrowser(const Value: TWebBrowserEx); override; public function CommandState(CmdID: TOleEnum): TCommandStates; procedure DoElementPropertiesChanged(Element: IHTMLElement; Properties: TElementProperties); procedure DoAfterCommand(CmdID: Cardinal); procedure DoBeforeCommand(CmdID: Cardinal; var Executed: Boolean); function GetActionState(Action: TObject; State: TCommandState; Value: Boolean): Boolean; procedure RegisterCommand(CmdID: Cardinal); procedure RegisterCommands(CmdIDs: array of Cardinal); procedure SaveActionState(Action: TObject; State: TCommandState; Value: Boolean); procedure UnRegisterCommand(CmdID: Cardinal); procedure UnRegisterCommands(CmdIDs: array of Cardinal); // UpdateCommands can optionally update a single command or all registered // commands, the default is all commands. procedure UpdateCommands(CmdID: Cardinal = 0); property AfterCommand: TCommandUpdaterEvent read FAfterCommand write FAfterCommand; property BeforeCommand: TCommandUpdaterBeforeExecuteEvent read FBeforeCommand write FBeforeCommand; property OnUpdateCommands: TCommandUpdaterEvent read FOnUpdateCommands write FOnUpdateCommands; property OnGetActionState: TGetActionStateEvent read FOnGetActionState write FOnGetActionState; property OnSaveActionState: TSaveActionStateEvent read FOnSaveActionState write FOnSaveActionState; property OnElementPropertiesChanged: TElementPropertiesChangedEvent read FOnElementPropertiesChanged write FOnElementPropertiesChanged; property OnFilterCommandState: TFilterCommandStateEvent read FOnFilterCommandState write FOnFilterCommandState; end; TWebBrowserCommandUpdater = class(TCustomWebBrowserCommandUpdater) published property WebBrowser; property AfterCommand; property BeforeCommand; property OnBrowserChanged; property OnUpdateCommands; property OnGetActionState; property OnSaveActionState; property OnElementPropertiesChanged; end; function SafeCreateRange(WebBrowserEx: TWebBrowserEx): IDispatch; function SafeCreateControlRange(WebBrowserEx: TWebBrowserEx): IHTMLControlRange; implementation uses Vcl.Forms, Vcl.Menus, System.Variants, System.Win.ComObj, ExDispID, Vcl.Dialogs, Winapi.ShlObj, WBComp, IEConst; const // Constants from mshtmhst.h DOCHOSTUIFLAG_DIALOG = $1; DOCHOSTUIFLAG_DISABLE_HELP_MENU = $2; DOCHOSTUIFLAG_NO3DBORDER = $4; DOCHOSTUIFLAG_SCROLL_NO = $8; DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = $10; DOCHOSTUIFLAG_OPENNEWWIN = $20; DOCHOSTUIFLAG_DISABLE_OFFSCREEN = $40; DOCHOSTUIFLAG_FLAT_SCROLLBAR = $80; DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = $100; DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = $200; DOCHOSTUIFLAG_OVERRIDEBEHAVIORFACTORY = $400; DOCHOSTUIFLAG_CODEPAGELINKEDFONTS = $800; DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 = $1000; DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 = $2000; DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE = $4000; DOCHOSTUIFLAG_ENABLE_INPLACE_NAVIGATION = $10000; DOCHOSTUIFLAG_IME_ENABLE_RECONVERSION = $20000; DOCHOSTUIFLAG_THEME = $40000; DOCHOSTUIFLAG_NOTHEME = $80000; DOCHOSTUIFLAG_NOPICS = $100000; DOCHOSTUIFLAG_NO3DOUTERBORDER = $200000; DOCHOSTUIFLAG_DISABLE_EDIT_NS_FIXUP = $400000; DOCHOSTUIFLAG_LOCAL_MACHINE_ACCESS_CHECK = $800000; DOCHOSTUIFLAG_DISABLE_UNTRUSTEDPROTOCOL = $1000000; DOCHOSTUIFLAG_ENABLE_ACTIVEX_BLOCK_MODE = $2000000; DOCHOSTUIFLAG_ENABLE_ACTIVEX_PROMPT_MODE = $4000000; DOCHOSTUIFLAG_ENABLE_ACTIVEX_DEFAULT_MODE = $8000000; procedure OutputDebugString(P: PChar); begin // Windows.OutputDebugString(P); end; procedure BuildPositionalDispIds (pDispIds: PDispIdList; const dps: TDispParams); var i: integer; begin Assert (pDispIds <> nil); { by default, directly arrange in reverse order } for i := 0 to dps.cArgs - 1 do pDispIds^ [i] := dps.cArgs - 1 - i; { check for named args } if (dps.cNamedArgs <= 0) then Exit; { parse named args } for i := 0 to dps.cNamedArgs - 1 do pDispIds^ [dps.rgdispidNamedArgs^ [i]] := i; end; function SafeCreateControlRange(WebBrowserEx: TWebBrowserEx): IHTMLControlRange; var Selection: IHTMLSelectionObject; begin Result := nil; if WebBrowserEx = nil then exit; try Selection := WebBrowserEx.Selection; if Selection <> nil then if Selection.type_ = 'None' then Result := nil else Supports(Selection.createRange, IHTMLControlRange, Result) else Result := nil; except // Silent exceptions that occur when document is // <body><frameset rows="*,5*"/><html></html></body> Result := nil; end; end; function SafeCreateRange(WebBrowserEx: TWebBrowserEx): IDispatch; var Selection: IHTMLSelectionObject; begin Result := nil; if WebBrowserEx = nil then exit; try Selection := WebBrowserEx.Selection; if (Selection <> nil) and (Selection.type_ <> 'None') then Result := Selection.createRange else Result := nil; except // Silent exceptions that occur when document is // <body><frameset rows="*,5*"/><html></html></body> Result := nil; end; end; { TCustomWebBrowserComponent } procedure TCustomWebBrowserComponent.CheckDocumentAssigned; begin CheckWebBrowserAssigned; if WebBrowser.Document = nil then raise Exception.Create(sNoPageLoaded); end; procedure TCustomWebBrowserComponent.CheckWebBrowserAssigned; begin if FWebBrowser = nil then raise Exception.CreateFmt(sWebBrowserNotAssigned, [Name]); end; procedure TCustomWebBrowserComponent.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FWebBrowser) then FWebBrowser := nil; end; procedure TCustomWebBrowserComponent.SetWebBrowser(const Value: TWebBrowserEx); begin if FWebBrowser <> Value then begin if Assigned(FWebBrowser) then FWebBrowser.RemoveFreeNotification(Self); FWebBrowser := Value; if Assigned(FWebBrowser) then FWebBrowser.FreeNotification(Self); if Assigned(FOnBrowserChanged) then FOnBrowserChanged(Self); end; end; { TEventDispatchEx } destructor TEventDispatchEx.Destroy; begin // Don't set active here because this will result in a recursive call to destroy //SetActive(False); inherited; end; function TEventDispatchEx.DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; begin Result := DISP_E_MEMBERNOTFOUND; end; function TEventDispatchEx.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HRESULT; begin Result := E_NOTIMPL; end; function TEventDispatchEx.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HRESULT; begin Pointer(TypeInfo) := nil; Result := E_NOTIMPL; end; function TEventDispatchEx.GetTypeInfoCount(out Count: Integer): HRESULT; begin Count := 0; Result := S_OK; end; function TEventDispatchEx.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; var dps: TDispParams absolute Params; bHasParams: boolean; pDispIds: PDispIdList; iDispIdsSize: integer; begin { validity checks } if (Flags AND DISPATCH_METHOD = 0) then raise Exception.Create(Format(SClassSinkingError, [ClassName])); { build pDispIds array. this maybe a bit of overhead but it allows us to sink named-argument calls such as Excel's AppEvents, etc! } pDispIds := nil; iDispIdsSize := 0; bHasParams := (dps.cArgs > 0); if (bHasParams) then begin iDispIdsSize := dps.cArgs * SizeOf (TDispId); GetMem (pDispIds, iDispIdsSize); end; try { rearrange dispids properly } if (bHasParams) then BuildPositionalDispIds(pDispIds, dps); Result := DoInvoke(DispId, IID, LocaleID, Flags, dps, pDispIds, VarResult, ExcepInfo, ArgErr); finally { free pDispIds array } if (bHasParams) then FreeMem (pDispIds, iDispIdsSize); end; end; function TEventDispatchEx.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin if GetInterface(IID, Obj) then begin Result := S_OK; Exit; end; if IsEqualIID(IID, FIID) then begin GetInterface(IDispatch, Obj); Result := S_OK; Exit; end; Result := E_NOINTERFACE; end; procedure TEventDispatchEx.SetActive(const Value: Boolean); var Intf: IInterface; begin if FActive <> Value then begin FActive := Value; Intf := GetEventInterface; if Intf <> nil then if FActive then InterfaceConnect(Intf, FIID, Self, FConnection) else InterfaceDisconnect(Intf, FIID, FConnection); end; end; function TEventDispatchEx._AddRef: Integer; begin Result := InterlockedIncrement(FInternalCount); end; function TEventDispatchEx._Release: Integer; begin Result := InterlockedDecrement(FInternalCount); if Result = 0 then Destroy; end; { TDocEventDispatch } procedure TDocEventDispatch.AfterConstruction; begin inherited; FIID := DIID_HTMLDocumentEvents2; end; function TDocEventDispatch.GetEventInterface: IInterface; begin Result := nil; if Assigned(WebBrowser) and not (csDestroying in WebBrowser.ComponentState) then Result := WebBrowser.Document2; end; function TDocEventDispatch.DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; function GetShiftState: TShiftState; begin Result := []; if WebBrowser.Window.Event.altKey then Include(Result, ssAlt); if WebBrowser.Window.Event.ctrlKey then Include(Result, ssCtrl); if WebBrowser.Window.Event.shiftKey then Include(Result, ssShift); end; var KeyCh: Char; KeyWord: Word; IsLocked: OleVariant; begin Result := DISP_E_MEMBERNOTFOUND; if not Assigned(WebBrowser) then exit; {$IFDEF DEVELOPERS} // OutputDebugString(PChar(Format('%x', [Dispid]))); with WebBrowser, WebBrowser.Window.Event do case DispID of DISPID_HTMLDOCUMENTEVENTS2_ONHELP: OutputDebugString('HTMLDOCEVENTS2_ONHELP'); DISPID_HTMLDOCUMENTEVENTS2_ONCLICK: OutputDebugString('HTMLDOCEVENTS2_ONCLICK'); DISPID_HTMLDOCUMENTEVENTS2_ONDBLCLICK: OutputDebugString('HTMLDOCEVENTS2_ONDBLCLICK'); DISPID_HTMLDOCUMENTEVENTS2_ONKEYDOWN: OutputDebugString('HTMLDOCEVENTS2_ONKEYDOWN'); DISPID_HTMLDOCUMENTEVENTS2_ONKEYUP: OutputDebugString('HTMLDOCEVENTS2_ONKEYUP'); DISPID_HTMLDOCUMENTEVENTS2_ONKEYPRESS: OutputDebugString('HTMLDOCEVENTS2_ONKEYPRESS'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEDOWN: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEDOWN'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEMOVE: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEMOVE'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEUP: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEUP'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOUT: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEOUT'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOVER: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEOVER'); DISPID_HTMLDOCUMENTEVENTS2_ONREADYSTATECHANGE: OutputDebugString('HTMLDOCEVENTS2_ONREADYSTATECHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREUPDATE: OutputDebugString('HTMLDOCEVENTS2_ONBEFOREUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONAFTERUPDATE: OutputDebugString('HTMLDOCEVENTS2_ONAFTERUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONROWEXIT: OutputDebugString('HTMLDOCEVENTS2_ONROWEXIT'); DISPID_HTMLDOCUMENTEVENTS2_ONROWENTER: OutputDebugString('HTMLDOCEVENTS2_ONROWENTER'); DISPID_HTMLDOCUMENTEVENTS2_ONDRAGSTART: OutputDebugString('HTMLDOCEVENTS2_ONDRAGSTART'); DISPID_HTMLDOCUMENTEVENTS2_ONSELECTSTART: OutputDebugString('HTMLDOCEVENTS2_ONSELECTSTART'); DISPID_HTMLDOCUMENTEVENTS2_ONERRORUPDATE: OutputDebugString('HTMLDOCEVENTS2_ONERRORUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONCONTEXTMENU: OutputDebugString('HTMLDOCEVENTS2_ONCONTEXTMENU'); DISPID_HTMLDOCUMENTEVENTS2_ONSTOP: OutputDebugString('HTMLDOCEVENTS2_ONSTOP'); DISPID_HTMLDOCUMENTEVENTS2_ONROWSDELETE: OutputDebugString('HTMLDOCEVENTS2_ONROWSDELETE'); DISPID_HTMLDOCUMENTEVENTS2_ONROWSINSERTED: OutputDebugString('HTMLDOCEVENTS2_ONROWSINSERTED'); DISPID_HTMLDOCUMENTEVENTS2_ONCELLCHANGE: OutputDebugString('HTMLDOCEVENTS2_ONCELLCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONPROPERTYCHANGE: OutputDebugString('HTMLDOCEVENTS2_ONPROPERTYCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCHANGED: OutputDebugString('HTMLDOCEVENTS2_ONDATASETCHANGED'); DISPID_HTMLDOCUMENTEVENTS2_ONDATAAVAILABLE: OutputDebugString('HTMLDOCEVENTS2_ONDATAAVAILABLE'); DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCOMPLETE: OutputDebugString('HTMLDOCEVENTS2_ONDATASETCOMPLETE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREEDITFOCUS: OutputDebugString('HTMLDOCEVENTS2_ONBEFOREEDITFOCUS'); DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE: OutputDebugString('DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONCONTROLSELECT: OutputDebugString('HTMLDOCEVENTS2_ONCONTROLSELECT'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEWHEEL: OutputDebugString('HTMLDOCEVENTS2_ONMOUSEWHEEL'); DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSIN: OutputDebugString('HTMLDOCEVENTS2_ONFOCUSIN'); DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSOUT: OutputDebugString('HTMLDOCEVENTS2_ONFOCUSOUT'); DISPID_HTMLDOCUMENTEVENTS2_ONACTIVATE: OutputDebugString('HTMLDOCEVENTS2_ONACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONDEACTIVATE: OutputDebugString('HTMLDOCEVENTS2_ONDEACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREACTIVATE: OutputDebugString('HTMLDOCEVENTS2_ONBEFOREACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREDEACTIVATE: OutputDebugString('HTMLDOCEVENTS2_ONBEFOREDEACTIVATE'); else OutputDebugString(PChar('HTMLDOCEVENT = ' + IntToStr(DispID))); end; {$ENDIF} case DispID of DISPID_ONRESIZESTART, DISPID_ONRESIZE, DISPID_ONRESIZEEND: begin OleVariant(VarResult^) := WebBrowser.DoOnControlResize(IUnknown(dps.rgvarg^[pDispIds^[0]].unkval) as IHTMLEventObj, DispID); Result := S_OK; end; DISPID_ONMOVESTART, DISPID_ONMOVE, DISPID_ONMOVEEND: begin OleVariant(VarResult^) := WebBrowser.DoOnControlMove(IUnknown(dps.rgvarg^[pDispIds^[0]].unkval) as IHTMLEventObj, DispID); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONCONTROLSELECT: begin OleVariant(VarResult^) := WebBrowser.DoOnControlSelect(IUnknown(dps.rgvarg^[pDispIds^[0]].unkval) as IHTMLEventObj); Result := S_OK; end; // DISPID_HTMLDOCUMENTEVENTS2_ONHELP:; DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE: begin WebBrowser.ClearCurrentElement; WebBrowser.SelectionChange; Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONCLICK: WebBrowser.Click; DISPID_HTMLDOCUMENTEVENTS2_ONDBLCLICK: WebBrowser.DblClick; DISPID_HTMLDOCUMENTEVENTS2_ONKEYDOWN: try KeyWord := WebBrowser.Window.Event.KeyCode; WebBrowser.KeyDown(KeyWord, GetShiftState); OleVariant (VarResult^) := WebBrowser.Window.Event.KeyCode = KeyWord; except end; DISPID_HTMLDOCUMENTEVENTS2_ONKEYUP: begin KeyWord := WebBrowser.Window.Event.KeyCode; WebBrowser.KeyUp(KeyWord, GetShiftState); // Assigning to the keycode here cause an Access denied error and further problems see bug 165902 // KeyCode := KeyWord; end; DISPID_HTMLDOCUMENTEVENTS2_ONKEYPRESS: begin KeyCh := Chr(WebBrowser.Window.Event.KeyCode); WebBrowser.KeyPress(KeyCh); // KeyCode := Ord(KeyCh); end; DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEDOWN: begin WebBrowser.MouseDown(TMouseButton(WebBrowser.Window.Event.button), GetShiftState, WebBrowser.Window.Event.x, WebBrowser.Window.Event.y); // Prevent elements with the Design_Time_Lock attribute from being dragged if WebBrowser.Window.Event.button = 1 then begin IsLocked := WebBrowser.Window.event.srcElement.getAttribute('Design_Time_Lock', 0); { do not localize } if not VarIsNull(IsLocked) and IsLocked then begin OleVariant(VarResult^) := not WordBool(IsLocked); Result := S_False; end else begin WebBrowser.CommandTarget.Exec(@CGID_MSHTML, IDM_2D_POSITION, OLECMDEXECOPT_DODEFAULT, True, POleVariant(nil)^); Result := S_OK; end; end; end; DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEMOVE: WebBrowser.MouseMove(GetShiftState, WebBrowser.Window.Event.x, WebBrowser.Window.Event.y); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEUP: begin WebBrowser.MouseUp(TMouseButton(WebBrowser.Window.Event.button), GetShiftState, WebBrowser.Window.Event.x, WebBrowser.Window.Event.y); WebBrowser.CommandTarget.Exec(@CGID_MSHTML, IDM_2D_POSITION, OLECMDEXECOPT_DODEFAULT, False, POleVariant(nil)^); end; DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOUT: WebBrowser.MouseOut(GetShiftState, WebBrowser.Window.Event.x, WebBrowser.Window.Event.y); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOVER: WebBrowser.MouseOver(GetShiftState, WebBrowser.Window.Event.x, WebBrowser.Window.Event.y); DISPID_HTMLDOCUMENTEVENTS2_ONREADYSTATECHANGE: WebBrowser.DoReadyStateChange; DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREUPDATE: WebBrowser.DoBeforeUpdate; DISPID_HTMLDOCUMENTEVENTS2_ONAFTERUPDATE: WebBrowser.DoAfterUpdate; DISPID_HTMLDOCUMENTEVENTS2_ONROWEXIT: WebBrowser.RowExit; DISPID_HTMLDOCUMENTEVENTS2_ONROWENTER: WebBrowser.RowEnter; DISPID_HTMLDOCUMENTEVENTS2_ONDRAGSTART: begin // Prevent elements with the Design_Time_Lock attribute from being dragged IsLocked := WebBrowser.Window.event.srcElement.getAttribute('Design_Time_Lock', 0); { do not localize } if not VarIsNull(IsLocked) and IsLocked then begin OleVariant(VarResult^) := not WordBool(IsLocked); Result := S_False; end; end; DISPID_HTMLDOCUMENTEVENTS2_ONSELECTSTART: WebBrowser.SelectStart; DISPID_HTMLDOCUMENTEVENTS2_ONERRORUPDATE: WebBrowser.ErrorUpdate; DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREEDITFOCUS: begin with IUnknown(dps.rgvarg^[pDispIds^[0]].unkval) as IHTMLEventObj do if (WideCompareText(srcElement.tagName, 'input') = 0) or { do not localize } (WideCompareText(srcElement.tagName, 'textarea') = 0) or { do not localize } (WideCompareText(srcElement.tagName, 'select') = 0) then { do not localize } begin with IUnknown(dps.rgvarg^[pDispIds^[0]].unkval) as IHTMLEventObj do cancelBubble := True; OleVariant(VarResult^) := False; Result := S_False; end else Result := inherited DoInvoke(DispID, IID, LocaleID, Flags, dps, pDispIds, VarResult, ExcepInfo, ArgErr); end; else Result := inherited DoInvoke(DispID, IID, LocaleID, Flags, dps, pDispIds, VarResult, ExcepInfo, ArgErr); // if Result <> S_OK then // OutputDebugString(PChar(Format('Doc event not handled %x', [Dispid]))); end; end; { TWndEventDispatch } procedure TWndEventDispatch.AfterConstruction; begin inherited; FIID := DIID_HTMLWindowEvents2; end; function TWndEventDispatch.GetEventInterface: IInterface; begin Result := nil; if Assigned(WebBrowser) and not (csDestroying in WebBrowser.ComponentState) and Assigned(WebBrowser.Document) then Result := WebBrowser.Window; end; function TWndEventDispatch.DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; begin Result := DISP_E_MEMBERNOTFOUND; if not Assigned(WebBrowser) then exit; with WebBrowser do case DispID of DISPID_HTMLWINDOWEVENTS_ONLOAD : DoLoad; DISPID_HTMLWINDOWEVENTS_ONUNLOAD: begin ClearCurrentElement; DoUnload; end; DISPID_HTMLWINDOWEVENTS_ONHELP : DoHelp; DISPID_HTMLWINDOWEVENTS_ONFOCUS : DoFocus; DISPID_HTMLWINDOWEVENTS_ONBLUR : DoBlur; DISPID_HTMLWINDOWEVENTS_ONERROR : DoError;//!!! DISPID_HTMLWINDOWEVENTS_ONRESIZE: DoWndResize; DISPID_HTMLWINDOWEVENTS_ONSCROLL: DoScroll; DISPID_HTMLWINDOWEVENTS_ONBEFOREUNLOAD: DoBeforeUnload; else Result := E_NOTIMPL; // OutputDebugString('TWndEventDispatch.Invoke - Unhandled Event'); end; end; function TWndEventDispatch.GetHTMLWindow2: IHTMLWindow2; begin Result := GetEventInterface as IHTMLWindow2; end; { TWebBrowserEventDispatch } procedure TWebBrowserEvents2Dispatch.AfterConstruction; begin inherited; FIID := DIID_DWebBrowserEvents2; end; function TWebBrowserEvents2Dispatch.GetEventInterface: IInterface; begin Result := WebBrowser.DefaultInterface; end; procedure TWebBrowserEvents2Dispatch.DoBeforeNavigate2( const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool); begin // Check pDisp ID to ensure that it's for the top level document if pDisp <> WebBrowser.ControlInterface as IDispatch then exit; if WebBrowser.Modified then Cancel := True; WebBrowser.FDocEventDispatch.Active := False; WebBrowser.FChangeLog := nil; end; procedure TWebBrowserEvents2Dispatch.DoClientToHostWindow(var CX, CY: Integer); begin {$IFDEF DEVELOPERS} OutputDebugString('DoClientToHostWindow'); {$ENDIF} //!! end; procedure TWebBrowserEvents2Dispatch.DoCommandStateChange(Command: TOleEnum; Enable: WordBool); begin if Command = CSC_UPDATECOMMANDS then WebBrowser.CommandUpdater.UpdateCommands else if Command = CSC_NAVIGATEFORWARD then WebBrowser.FForwardEnabled := Enable else if Command = CSC_NAVIGATEBACK then WebBrowser.FBackEnabled := Enable; end; procedure TWebBrowserEvents2Dispatch.DoDocumentComplete( const pDisp: IDispatch; var URL: OleVariant); begin // Check pDisp ID to ensure that it's for the top level document if pDisp <> (WebBrowser.ControlInterface as IDispatch) then exit; with WebBrowser do begin FDisplayServices := nil; FCaret := nil; FMarkupServices := nil; FPrimarySelectionServices := nil; if (FInetExplorerServerInstance = nil) then if HandleAllocated then begin HookChildWindows; {$IFDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch.Connect(Document2); FWndEventDispatch.Connect(Window); {$ELSE} if PrimaryMarkupContainer <> nil then PrimaryMarkupContainer.CreateChangeLog(WebBrowser as IHTMLChangeSink, FChangeLog, 1, 0); FDocEventDispatch.Active := True; FWndEventDispatch.Active := True; FWebBrowserEvents2Dispatch.Active := True; {$ENDIF} end else if Assigned(FOnReloadDocument) then FOnReloadDocument(WebBrowser); end; end; procedure TWebBrowserEvents2Dispatch.DoDownloadBegin; begin end; procedure TWebBrowserEvents2Dispatch.DoDownloadComplete; begin end; procedure TWebBrowserEvents2Dispatch.DoFileDownload(var Cancel: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoNavigateComplete2( const pDisp: IDispatch; var URL: OleVariant); begin end; procedure TWebBrowserEvents2Dispatch.DoNavigateError( const pDisp: IDispatch; var URL, Frame, StatusCode: OleVariant; var Cancel: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoNewWindow2(var ppDisp: IDispatch; var Cancel: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnFullScreen(FullScreen: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnMenuBar(MenuBar: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnQuit; begin end; procedure TWebBrowserEvents2Dispatch.DoOnStatusBar(StatusBar: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnTheaterMode( TheaterMode: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnToolBar(ToolBar: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoOnVisible(Visible: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoPrintTemplateInstantiation( const pDisp: IDispatch); begin end; procedure TWebBrowserEvents2Dispatch.DoPrintTemplateTeardown( const pDisp: IDispatch); begin end; procedure TWebBrowserEvents2Dispatch.DoPrivacyImpactedStateChange( bImpacted: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoProgressChange(Progress, ProgressMax: Integer); begin end; procedure TWebBrowserEvents2Dispatch.DoPropertyChange( const szProperty: WideString); begin end; procedure TWebBrowserEvents2Dispatch.DoSetSecureLockIcon( SecureLockIcon: Integer); begin end; procedure TWebBrowserEvents2Dispatch.DoStatusTextChange( const Text: WideString); begin WebBrowser.DoStatusTextChange(Text); end; procedure TWebBrowserEvents2Dispatch.DoTitleChange(const Text: WideString); begin end; procedure TWebBrowserEvents2Dispatch.DoUpdatePageStatus( const pDisp: IDispatch; var nPage, fDone: OleVariant); begin end; procedure TWebBrowserEvents2Dispatch.DoWindowClosing( IsChildWindow: WordBool; var Cancel: WordBool); begin with WebBrowser do if Assigned(FOnWindowClosing) then FOnWindowClosing(WebBrowser, IsChildWindow, Cancel); end; procedure TWebBrowserEvents2Dispatch.DoWindowSetHeight(Height: Integer); begin end; procedure TWebBrowserEvents2Dispatch.DoWindowSetLeft(Left: Integer); begin end; procedure TWebBrowserEvents2Dispatch.DoWindowSetResizable( Resizable: WordBool); begin end; procedure TWebBrowserEvents2Dispatch.DoWindowSetTop(Top: Integer); begin end; procedure TWebBrowserEvents2Dispatch.DoWindowSetWidth(Width: Integer); begin end; function TWebBrowserEvents2Dispatch.DoInvoke (DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; type POleVariant = ^OleVariant; begin Result := DISP_E_MEMBERNOTFOUND; case DispId of DISPID_STATUSTEXTCHANGE: begin DoStatusTextChange(dps.rgvarg^ [pDispIds^ [0]].bstrval); Result := S_OK; end; DISPID_PROGRESSCHANGE: begin DoProgressChange(dps.rgvarg^[pDispIds^[0]].lval, dps.rgvarg^[pDispIds^[1]].lval); Result := S_OK; end; DISPID_COMMANDSTATECHANGE: begin DoCommandStateChange(TOleEnum(dps.rgvarg^[pDispIds^[0]].lval), dps.rgvarg^[pDispIds^[1]].vbool); Result := S_OK; end; DISPID_DOWNLOADBEGIN: begin DoDownloadBegin; Result := S_OK; end; DISPID_DOWNLOADCOMPLETE: begin DoDownloadComplete; Result := S_OK; end; DISPID_TITLECHANGE: begin DoTitleChange(dps.rgvarg^[pDispIds^[0]].bstrval); Result := S_OK; end; DISPID_PROPERTYCHANGE: begin DoPropertyChange (dps.rgvarg^[pDispIds^[0]].bstrval); Result := S_OK; end; DISPID_BEFORENAVIGATE2, DISPID_BEFORENAVIGATE: begin {$IFDEF DEVELOPERS} OutputDebugString('DoBeforeNavigate/2'); {$ENDIF} DoBeforeNavigate2(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval), POleVariant(dps.rgvarg^[pDispIds^[1]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[2]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[3]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[4]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[5]].pvarval)^, dps.rgvarg^[pDispIds^[6]].pbool^); Result := S_OK; end; DISPID_NEWWINDOW2: begin DoNewWindow2(IDispatch(dps.rgvarg^[pDispIds^[0]].pdispval^), dps.rgvarg^[pDispIds^[1]].pbool^); Result := S_OK; end; DISPID_NAVIGATECOMPLETE2: begin DoNavigateComplete2(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval), POleVariant(dps.rgvarg^[pDispIds^[1]].pvarval)^); Result := S_OK; end; DISPID_DOCUMENTCOMPLETE: begin DoDocumentComplete(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval), POleVariant(dps.rgvarg^[pDispIds^[1]].pvarval)^); Result := S_OK; end; DISPID_ONQUIT: begin DoOnQuit; Result := S_OK; end; DISPID_ONVISIBLE: begin DoOnVisible(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_ONTOOLBAR: begin DoOnToolBar(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_ONMENUBAR: begin DoOnMenuBar(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_ONSTATUSBAR: begin DoOnStatusBar(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_ONFULLSCREEN: begin DoOnFullScreen(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_ONTHEATERMODE: begin DoOnTheaterMode(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_WINDOWSETRESIZABLE: begin DoWindowSetResizable(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; DISPID_WINDOWSETLEFT: begin DoWindowSetLeft(dps.rgvarg^[pDispIds^[0]].lval); Result := S_OK; end; DISPID_WINDOWSETTOP: begin DoWindowSetTop(dps.rgvarg^[pDispIds^[0]].lval); Result := S_OK; end; DISPID_WINDOWSETWIDTH: begin DoWindowSetWidth(dps.rgvarg^[pDispIds^[0]].lval); Result := S_OK; end; DISPID_WINDOWSETHEIGHT: begin DoWindowSetHeight(dps.rgvarg^[pDispIds^[0]].lval); Result := S_OK; end; DISPID_WINDOWCLOSING: begin DoWindowClosing(dps.rgvarg^[pDispIds^[0]].vbool, dps.rgvarg^ [pDispIds^ [1]].pbool^); Result := S_OK; end; DISPID_CLIENTTOHOSTWINDOW: begin DoClientToHostWindow(dps.rgvarg^[pDispIds^[0]].plval^, dps.rgvarg^ [pDispIds^ [1]].plval^); Result := S_OK; end; DISPID_SETSECURELOCKICON: begin DoSetSecureLockIcon(dps.rgvarg^[pDispIds^[0]].lval); Result := S_OK; end; DISPID_FILEDOWNLOAD: begin DoFileDownload(dps.rgvarg^[pDispIds^[0]].pbool^); Result := S_OK; end; DISPID_NAVIGATEERROR: begin DoNavigateError(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval), POleVariant(dps.rgvarg^[pDispIds^[1]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[2]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[3]].pvarval)^, dps.rgvarg^[pDispIds^[4]].pbool^); Result := S_OK; end; DISPID_PRINTTEMPLATEINSTANTIATION: begin DoPrintTemplateInstantiation(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval)); Result := S_OK; end; DISPID_PRINTTEMPLATETEARDOWN: begin DoPrintTemplateTeardown(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval)); Result := S_OK; end; DISPID_UPDATEPAGESTATUS: begin DoUpdatePageStatus(IDispatch(dps.rgvarg^[pDispIds^[0]].dispval), POleVariant(dps.rgvarg^[pDispIds^[1]].pvarval)^, POleVariant(dps.rgvarg^[pDispIds^[2]].pvarval)^); Result := S_OK; end; DISPID_PRIVACYIMPACTEDSTATECHANGE: begin DoPrivacyImpactedStateChange(dps.rgvarg^[pDispIds^[0]].vbool); Result := S_OK; end; end; end; { TWebBrowserEx } constructor TWebBrowserEx.Create(AOwner: TComponent); begin inherited Create(AOwner); FShowScrollBar := True; {$IFDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch := TMSHTMLHTMLDocumentEvents2.Create(Self); FDocEventDispatch.Name := 'InternalDocEventDispatch'; FDocEventDispatch.SetSubComponent(True); FWndEventDispatch := TMSHTMLHTMLWindowEvents2.Create(Self); FWndEventDispatch.Name := 'InternalWndEventDispatch'; { do not localize } FWndEventDispatch.SetSubComponent(True); FWebBrowserEvents2Dispatch := TSHDocVwDWebBrowserEvents2.Create(Self); FWebBrowserEvents2Dispatch.Name := 'InternalWebBrowserEvents2Dispatch'; { do not localize } FWebBrowserEvents2Dispatch.SetSubComponent(True); FWebBrowserEvents2Dispatch.Connect(DefaultInterface); {$ELSE} FDocEventDispatch := TDocEventDispatch.Create; FDocEventDispatch.FWebBrowser := Self; FWndEventDispatch := TWndEventDispatch.Create; FWndEventDispatch.FWebBrowser := Self; FWebBrowserEvents2Dispatch := TWebBrowserEvents2Dispatch.Create; FWebBrowserEvents2Dispatch.FWebBrowser := Self; FWebBrowserEvents2Dispatch.Active := True; {$ENDIF} FDocEventDispatchCounter := FDocEventDispatch as IUnknown; FWndEventDispatchCounter := FWndEventDispatch as IUnknown; FWebBrowserEvents2DispatchCounter := FWebBrowserEvents2Dispatch as IUnknown; FCommandUpdater := TCustomWebBrowserCommandUpdater.Create(Self); FCommandUpdater.WebBrowser := Self; FCommandUpdater.SetSubComponent(True); FCommandUpdater.Name := 'InternalCommandUpdater'; { do not localize } end; destructor TWebBrowserEx.Destroy; begin FPrimarySelectionServices := nil; inherited Destroy; {$IFNDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch.Active := False; FWndEventDispatch.Active := False; FWebBrowserEvents2Dispatch.Active := False; FDocEventDispatch.FWebBrowser := nil; FWndEventDispatch.FWebBrowser := nil; FWebBrowserEvents2Dispatch.FWebBrowser := nil; {$ENDIF} FreeAndNil(FServiceProviders); end; procedure TWebBrowserEx.Bold; begin DoCommand('Bold'); { do not localize } end; procedure TWebBrowserEx.Clear; begin //!! end; {function TWebBrowserEx.CommandState(const CmdStr: String): TCommandState; var FHTMLSelectionObject: IHTMLSelectionObject; FHTMLRange: IDispatch; FHTMLTxtRange: IHTMLTxtRange; begin Result := False; FHTMLSelectionObject := Document2.Get_Selection; if Assigned(FHTMLSelectionObject) then begin FHTMLRange := FHTMLSelectionObject.createRange; if Assigned(FHTMLRange) then begin FHTMLRange.QueryInterface(IHTMLTxtRange, FHTMLTxtRange); // IHTMLControlRange if Assigned(FHTMLTxtRange) then Result := FHTMLTxtRange.queryCommandState(CmdStr); end; end else Result := False; end;} procedure TWebBrowserEx.CopyToClipBoard; begin DoCommand('Copy'); { do not localize } end; procedure TWebBrowserEx.CreateBookmark; begin //!! end; procedure TWebBrowserEx.CutToClipBoard; begin DoCommand('Cut'); { do not localize } end; procedure TWebBrowserEx.Delete; begin DoCommand('Delete'); { do not localize } end; procedure TWebBrowserEx.DoCommand(const CmdStr: String); var RetVal: OleVariant; LDocument2: IHTMLDocument2; begin LDocument2 := GetActiveDocument as IHTMLDocument2; if LDocument2 <> nil then if LDocument2.QueryCommandSupported(CmdStr) then LDocument2.execCommand(CmdStr, True, RetVal); end; procedure TWebBrowserEx.DoCommand(const Cmd: TOleEnum; InParam: OleVariant; OutParam: OleVariant); begin if CommandTarget <> nil then CommandTarget.Exec(@CGID_MSHTML, Cmd, OLECMDEXECOPT_DODEFAULT, InParam, OutParam); end; function TWebBrowserEx.EnableModeless(fEnable: Integer): HResult; begin Result := S_FALSE; // Result := S_OK; end; function TWebBrowserEx.FilterDataObject(const pDO: IDataObject; out ppDORet: IDataObject): HResult; begin Result := S_FALSE; ppDORet := nil; end; function TWebBrowserEx.GetActiveElement: IHTMLElement; var LDocument2: IHTMLDocument2; begin LDocument2 := Document2; if LDocument2 <> nil then Result := LDocument2.ActiveElement else Result := nil; end; function TWebBrowserEx.GetCount: Integer; var LDocument2: IHTMLDocument2; begin LDocument2 := Document2; if LDocument2 <> nil then Result := LDocument2.All.Length else Result := 0; end; function TWebBrowserEx.GetCurrentElementType: TCurrentElementType; begin if FCurrentElementType = cetUndefined then GetCurrentElement; Result := FCurrentElementType; end; function TWebBrowserEx.GetCurrentElement: IHTMLElement; var Range: IDispatch; TxtRange: IHTMLTxtRange; CtrlRange: IHTMLControlRange; MarkupPointer: IMarkupPointer; begin if (FCurrentElementType = cetUndefined) or (FCurrentElementType = cetNone) then begin Assert((DisplayServices <> nil) and not (csDesigning in ComponentState)); Range := SafeCreateRange(Self); if Supports(Range, IHTMLControlRange, CtrlRange) then begin FCurrentElement := CtrlRange.item(0); FCurrentElementType := cetControlRange; end // Check for Text to work around problem where parent element is block elemement // preceding cursor else if Supports(Range, IHTMLTxtRange, TxtRange) and (TxtRange.Text <> '') then //else if Supports(Range, IHTMLTxtRange, TxtRange) then begin FCurrentElement := TxtRange.parentElement; FCurrentElementType := cetTextRange; end else begin // Very slow OleCheck(MarkupServices.CreateMarkupPointer(MarkupPointer)); Caret.MoveMarkupPointerToCaret(MarkupPointer); MarkupPointer.CurrentScope(FCurrentElement); if FCurrentElement <> nil then FCurrentElementType := cetAtCursor else // This may mean that we are still loading FCurrentElementType := cetNone; end; end; Result := FCurrentElement; end; function TWebBrowserEx.GetDocument2: IHTMLDocument2; begin Supports(Document, IHTMLDocument2, Result); end; function TWebBrowserEx.GetDocument3: IHTMLDocument3; begin Supports(Document, IHTMLDocument3, Result); end; function TWebBrowserEx.GetDocument4: IHTMLDocument4; begin Supports(Document, IHTMLDocument4, Result); end; function TWebBrowserEx.GetIHTMLNamespaceCollection: IHTMLNamespaceCollection; var LDocument4: IHTMLDocument4; begin LDocument4 := Document4; if LDocument4 <> nil then Result := LDocument4.Namespaces as IHTMLNamespaceCollection; end; function TWebBrowserEx.GetDropTarget(const pDropTarget: IDropTarget; out ppDropTarget: IDropTarget): HResult; begin if Assigned(FOnGetDropTarget) then begin ppDropTarget := nil; FOnGetDropTarget(Self, pDropTarget, ppDropTarget); if ppDropTarget <> nil then Result := S_OK else Result := E_NOTIMPL; end else Result := E_NOTIMPL; end; function TWebBrowserEx.GetExternal(out ppDispatch: IDispatch): HResult; begin if Assigned(FOnGetExternalDispatch) then FOnGetExternalDispatch(Self, ppDispatch) else ppDispatch := nil; Result := S_OK; end; function TWebBrowserEx.GetHostInfo(var pInfo: _DOCHOSTUIINFO): HResult; const BorderStyle: array[TControlBorder] of Integer = (0, DOCHOSTUIFLAG_NO3DBORDER); ScrollBarStyle: array[Boolean] of Integer = (DOCHOSTUIFLAG_SCROLL_NO, 0); ThemeStyle: array[Boolean] of Integer = (DOCHOSTUIFLAG_NOTHEME, DOCHOSTUIFLAG_THEME); AutoCompleteOption: array[Boolean] of Integer = (0, DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE); DefaultBlock: array[Boolean] of Integer = (0, DOCHOSTUIFLAG_DIV_BLOCKDEFAULT); begin FillChar(pInfo, SizeOf(pInfo), 0); pInfo.cbSize := SizeOf(_DOCHOSTUIINFO); pInfo.dwFlags := BorderStyle[FControlBorder] or ScrollBarStyle[FShowScrollBar] or ThemeStyle[UseTheme] or AutoCompleteOption[FAutoComplete] or DefaultBlock[UseDivBlock]; pInfo.dwDoubleClick := 0;//DOCHOSTUIDBLCLK_SHOWPROPERTIES; if Assigned(FOnGetHostInfo) then Result := FOnGetHostInfo(Self, pInfo) else Result := S_OK; end; function TWebBrowserEx.GetOptionKeyPath(out pchKey: PWideChar; dw: UINT): HResult; begin pchKey := nil; Result := S_FALSE; // Use the default registry settings end; function TWebBrowserEx.GetTag(Index: Integer): IHTMLElement; var LDocument2: IHTMLDocument2; begin LDocument2 := Document2; if LDocument2 <> nil then Result := Document2.All.Item(null, Index) as IHTMLElement else Result := nil; end; function TWebBrowserEx.HideUI: HResult; begin Result := S_OK; end; function TWebBrowserEx.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; var AmbientControlFlags: Integer; begin Result := inherited Invoke(DispID, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr); if (Flags and DISPATCH_PROPERTYGET <> 0) and (VarResult <> nil) then begin Result := S_OK; case DispID of DISPID_AMBIENT_DLCONTROL: begin Result := DISP_E_MEMBERNOTFOUND; if Assigned(FOnGetAmbientControlInfo) then begin AmbientControlFlags := DLCTL_DLIMAGES or DLCTL_VIDEOS or DLCTL_BGSOUNDS; Result := FOnGetAmbientControlInfo(Self, AmbientControlFlags); PVariant(VarResult)^ := AmbientControlFlags; end end; // DISPID_AMBIENT_USERAGENT = -5513; // DISPID_SECURITYDOMAIN = -5514; // DISPID_AMBIENT_PALETTE: // Result := DISP_E_MEMBERNOTFOUND; DISPID_AMBIENT_USERMODE: PVariant(VarResult)^ := FUserMode; else Result := DISP_E_MEMBERNOTFOUND; (* // AmbientControlFlags := DLCTL_DLIMAGES or DLCTL_VIDEOS or DLCTL_BGSOUNDS; TVarData(PVariant(VarResult)^).VType := VT_I4; // TVarData(PVariant(VarResult)^).VInteger := AmbientControlFlags; if Assigned(FOnGetAmbientControlInfo) then begin Result := FOnGetAmbientControlInfo(Self, AmbientControlFlags); TVarData(PVariant(VarResult)^).VInteger := AmbientControlFlags; end end; // DISPID_AMBIENT_USERAGENT = -5513; // DISPID_SECURITYDOMAIN = -5514; // DISPID_AMBIENT_PALETTE: // Result := DISP_E_MEMBERNOTFOUND; DISPID_AMBIENT_USERMODE: begin TVarData(PVariant(VarResult)^).VType := VT_I4; TVarData(PVariant(VarResult)^).VBoolean := FUserMode; end; else Result := DISP_E_MEMBERNOTFOUND; *) end; end; end; procedure TWebBrowserEx.Italic; begin DoCommand('Italic'); { do not localize } end; function TWebBrowserEx.OnDocWindowActivate(fActivate: Integer): HResult; begin Result := S_OK; { if Assigned(FOnDocWndActivate) then FOnDocWndActivate(Self, fActivate = 1, Result); Result := S_OK;} end; function TWebBrowserEx.OnFrameWindowActivate(fActivate: Integer): HResult; begin Result := S_OK; if Assigned(FOnFrameWndActivate) then FOnFrameWndActivate(Self, fActivate = 1, Result) else Result := S_OK; end; procedure TWebBrowserEx.Open; begin DoCommand(IDM_OPEN, EmptyParam, EmptyParam); end; procedure TWebBrowserEx.Overwrite; begin DoCommand('Overwrite'); { do not localize } end; procedure TWebBrowserEx.PasteFromClipBoard; begin DoCommand('Paste'); { do not localize } end; procedure TWebBrowserEx.Print; begin DoCommand(IDM_PRINT, EmptyParam, EmptyParam); end; procedure TWebBrowserEx.PrintPreview; begin //!! end; procedure TWebBrowserEx.PageSetup; begin DoCommand(IDM_PAGESETUP, EmptyParam, EmptyParam); end; function TWebBrowserEx.ResizeBorder(var prcBorder: tagRECT; const pUIWindow: IOleInPlaceUIWindow; fRameWindow: Integer): HResult; begin Result := S_OK; //!! end; procedure TWebBrowserEx.Save; var AFile: IPersistFile; begin if Supports(Document, IPersistFile, AFile) and (AFile.IsDirty <> S_FALSE) then OleCheck(AFile.Save(nil, True)); end; procedure TWebBrowserEx.SaveAs; begin DoCommand(IDM_SAVEAS, EmptyParam, EmptyParam); end; procedure TWebBrowserEx.SelectAll; begin DoCommand(IDM_SELECTALL, EmptyParam, EmptyParam); end; function TWebBrowserEx.SelLength: Integer; var LDocument2: IHTMLDocument2; FHTMLRange: IDispatch; FHTMLTxtRange: IHTMLTxtRange; begin Result := -1; // if (Document2 = nil) or (FDocEventsConnection = 0) then exit; if FHTMLSelectionObject = nil then begin LDocument2 := Document2; if LDocument2 <> nil then FHTMLSelectionObject := Document2.Get_Selection else Exit; end; if Assigned(FHTMLSelectionObject) then begin FHTMLRange := FHTMLSelectionObject.createRange; if Assigned(FHTMLRange) then begin FHTMLRange.QueryInterface(IHTMLTxtRange, FHTMLTxtRange); if Assigned(FHTMLTxtRange) then Result := Length(FHTMLTxtRange.Get_Text); end; end else Result := -1; end; procedure TWebBrowserEx.SetControlBorder(const Value: TControlBorder); begin FControlBorder := Value; end; procedure TWebBrowserEx.SetFlatScrollBar(const Value: Boolean); begin FFlatScrollBar := Value; end; procedure TWebBrowserEx.SetShowScrollBar(const Value: Boolean); begin FShowScrollBar := Value; end; procedure TWebBrowserEx.SetURL(Value: String); begin FURL := Value; FUserMode := True; if csDesigning in ComponentState then Value := 'about:blank'; { do not localize } if not (csLoading in ComponentState) then Navigate(FURL); end; procedure TWebBrowserEx.SetUserMode(const Value: WordBool); var FOleControl: IOleControl; begin FUserMode := Value; if Supports(DefaultDispatch, IOleControl, FOleControl) then FOleControl.OnAmbientPropertyChange(DISPID_AMBIENT_USERMODE); end; function TWebBrowserEx.ShowContextMenu(dwID: UINT; ppt: PtagPOINT; const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HResult; var LDocument2: IHTMLDocument2; E: IHTMLElement; P: TPoint; S: string; LPopupMenu: TPopupMenu; Handled: Boolean; begin if Supports(pdispReserved, IHTMLElement, E) then S := E.tagName; P := Point(ppt.x, ppt.y); P := ScreenToClient(P); LDocument2 := Document2; if LDocument2 <> nil then E := Document2.elementFromPoint(P.x, P.y); Handled := False; DoContextPopup(Point(ppt.x, ppt.y), Handled); if not Handled then begin LPopupMenu := GetPopupMenu; if (LPopupMenu <> nil) and LPopupMenu.AutoPopup then begin SendCancelMode(nil); LPopupMenu.PopupComponent := Self; PopupMenu.Popup(ppt.x, ppt.y); Result := S_OK; end else begin Result := S_FALSE; if Assigned(FOnShowContextMenu) then FOnShowContextMenu(Self, dwID, ppt, pcmdtReserved, pdispReserved, Result); end; end else Result := S_OK; end; { IDocHostShowUI } function TWebBrowserEx.ShowHelp(hwnd: THandle; pszHelpFile: POLESTR; uCommand: UINT; dwData: longint; ptMouse: TPoint; var pDispachObjectHit: IDispatch): HRESULT; begin Result := S_OK; end; function TWebBrowserEx.ShowMessage(hwnd: THandle;lpstrText: POLESTR; lpstrCaption: POLESTR; dwType: longint; lpstrHelpFile: POLESTR; dwHelpContext: longint; var plResult: LRESULT): HRESULT; stdcall; begin Result := S_FALSE; end; function TWebBrowserEx.ShowUI(dwID: UINT; const pActiveObject: IOleInPlaceActiveObject; const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame; const pDoc: IOleInPlaceUIWindow): HResult; begin Result := S_FALSE; end; function TWebBrowserEx.PreProcessMessage(var Msg: TMsg): Boolean; var KeyMsg: TWMKey; Form: TCustomForm; Handled: Boolean; begin Result := False; if Assigned(FOnPreProcessMessage) then begin FOnPreProcessMessage(Self, Msg, Handled); if Handled then begin Result := True; Exit; end; end; if Msg.message = WM_KEYDOWN then begin Form := GetParentForm(Self); if Assigned(Form) then begin KeyMsg.Msg := Msg.message; KeyMsg.CharCode := Msg.wParam; KeyMsg.KeyData := Msg.lParam; Result := (KeyboardStateToShiftState <> []) and Form.IsShortCut(KeyMsg); end; end; end; function TWebBrowserEx.TranslateAccelerator(var lpmsg: tagMSG; var pguidCmdGroup: TGUID; nCmdID: UINT): HResult; var Form: TCustomForm; // Msg: TWMKey; // ShortCut: TShortCut; Pt: TPoint; begin Result := S_FALSE; case lpMsg.message of WM_CLOSE: exit; WM_SYSKEYDOWN: if (GetAsyncKeyState(VK_MENU) < 0) and (lpMsg.wParam = VK_F10) then if PopupMenu <> nil then begin Pt := ClientToScreen(Point(Left, Top)); PopupMenu.Popup(Pt.X, Pt.Y); end; WM_KEYDOWN: begin // Fix bug 200750 Check the virtual keycode if ((lpMsg.wParam and $FF) = Ord('N')) then if (GetAsyncKeyState(VK_CONTROL) < 0) then begin Result := S_OK; exit; end; end; end; Form := GetParentForm(Self); if Assigned(Form) then begin { Msg.Msg := lpmsg.message; Msg.CharCode := lpmsg.wParam; Msg.KeyData := lpmsg.lParam; if (KeyboardStateToShiftState <> []) and Form.IsShortCut(Msg) then begin lpmsg.message := Msg.Msg; lpmsg.wParam := Msg.CharCode; lpmsg.lParam := Msg.KeyData; Result := S_FALSE; end else} if Form.Perform(lpMsg.message, lpmsg.wParam, lpmsg.lParam) = 0 then Result := S_FALSE else Result := S_OK; end; end; function TWebBrowserEx.TranslateUrl(dwTranslate: UINT; pchURLIn: PWideChar; out ppchURLOut: PWideChar): HResult; begin ppchURLOut := nil; Result := S_FALSE; end; procedure TWebBrowserEx.Underline; begin DoCommand('Underline'); { do not localize } end; procedure TWebBrowserEx.Undo; begin DoCommand(IDM_UNDO, EmptyParam, EmptyParam); end; function TWebBrowserEx.UpdateUI: HResult; begin Result := E_NOTIMPL; end; function TWebBrowserEx.Selection: IHTMLSelectionObject; var LDocument2: IHTMLDocument2; begin LDocument2 := Document2; if LDocument2 <> nil then Result := Document2.Get_Selection else Result := nil; if Assigned(FOnGetSelectionObject) then FOnGetSelectionObject(Self, Result); end; procedure TWebBrowserEx.Redo; begin DoCommand(IDM_REDO, EmptyParam, EmptyParam); end; function TWebBrowserEx.GetOverrideKeyPath(out pchKey: PWideChar; dw: DWORD): HRESULT; {var Key: WideString; Len: Integer;} begin { Key := 'Software\\MyCompany\\MyApp'; Len := Length(Key); pchKey := CoTaskMemAlloc(Len + sizeof(WCHAR)); Move(Key, pchKey, Len + sizeof(WCHAR));} pchKey := nil; // HKEY_CURRENT_USER/Software/YourCompany/YourApp // Result := S_OK; Result := E_NOTIMPL; end; function TWebBrowserEx.GetServiceProvider: IServiceProvider; begin Result := Document2 as IServiceProvider; end; function TWebBrowserEx.GetHTMLEditServices: IHTMLEditServices2; begin Result := nil; if Assigned(ServiceProvider) then OleCheck(ServiceProvider.QueryService(SID_SHTMLEditServices, IID_IHTMLEditServices, Result)); end; function TWebBrowserEx.GetHighlightRenderingServices: IHighlightRenderingServices; begin Result := Document2 as IHighlightRenderingServices; end; procedure TWebBrowserEx.SaveToStream(S: TStream); var Stream: IPersistStreamInit; Adapter: IStream; begin if not Assigned(Document) then raise Exception.Create(sNoPageLoaded); if Supports(Document, IPersistStreamInit, Stream) then begin Adapter := TStreamAdapter.Create(S); OleCheck(Stream.Save(Adapter, false)); // Adapter freed on IInterface.Release end; end; type TStreamLoadMoniker = class(TInterfacedObject, IMoniker) private FStream: TStream; FMoniker: IMoniker; FBaseURL: string; protected function BindToObject(const bc: IBindCtx; const mkToLeft: IMoniker; const iidResult: TGUID; out vResult): HRESULT; stdcall; function BindToStorage(const bc: IBindCtx; const mkToLeft: IMoniker; const iid: TGUID; out vObj): HRESULT; stdcall; function CommonPrefixWith(const mkOther: IMoniker; out mkPrefix: IMoniker): HRESULT; stdcall; function ComposeWith(const mkRight: IMoniker; fOnlyIfNotGeneric: LongBool; out mkComposite: IMoniker): HRESULT; stdcall; function Enum(fForward: LongBool; out enumMoniker: IEnumMoniker): HRESULT; stdcall; function GetClassID(out classID: TGUID): HRESULT; stdcall; function GetDisplayName(const bc: IBindCtx; const mkToLeft: IMoniker; out pszDisplayName: PWideChar): HRESULT; stdcall; function GetSizeMax(out cbSize: Int64): HRESULT; stdcall; function GetTimeOfLastChange(const bc: IBindCtx; const mkToLeft: IMoniker; out filetime: _FILETIME): HRESULT; stdcall; function Hash(out dwHash: Integer): HRESULT; stdcall; function Inverse(out mk: IMoniker): HRESULT; stdcall; function IsDirty: HRESULT; stdcall; function IsEqual(const mkOtherMoniker: IMoniker): HRESULT; stdcall; function IsRunning(const bc: IBindCtx; const mkToLeft: IMoniker; const mkNewlyRunning: IMoniker): HRESULT; stdcall; function IsSystemMoniker(out dwMksys: Integer): HRESULT; stdcall; function Load(const stm: IStream): HRESULT; stdcall; function ParseDisplayName(const bc: IBindCtx; const mkToLeft: IMoniker; pszDisplayName: PWideChar; out chEaten: Integer; out mkOut: IMoniker): HRESULT; stdcall; function Reduce(const bc: IBindCtx; dwReduceHowFar: Integer; mkToLeft: PIMoniker; out mkReduced: IMoniker): HRESULT; stdcall; function RelativePathTo(const mkOther: IMoniker; out mkRelPath: IMoniker): HRESULT; stdcall; function Save(const stm: IStream; fClearDirty: LongBool): HRESULT; stdcall; public constructor Create(AStream: TStream; BaseURL: string); end; procedure TWebBrowserEx.LoadFromStream(S: TStream); var Moniker: IPersistMoniker; BindCtx: IBindCtx; LBaseUrl: string; begin if Assigned(FBeforeLoadFromStream) then FBeforeLoadFromStream(Self); if (Length(Path) > 0) and Supports(Document2, IPersistMoniker, Moniker) then begin OleCheck(CreateBindCtx(0, BindCtx)); LBaseUrl := BaseUrl; if LBaseUrl = '' then LBaseUrl := 'c:'; // prevent invalid parameter OleCheck(Moniker.Load(LongBool(0), TStreamLoadMoniker.Create(S, LBaseURL), BindCtx, STGM_READ)); end; end; procedure TWebBrowserEx.ViewSource; begin // !! end; function TWebBrowserEx.GetActiveDocument: IHTMLDocument; var LDocument: IHTMLDocument; begin if Assigned(FOnGetActiveDocument) then begin FOnGetActiveDocument(Self, LDocument); Result := LDocument as IHTMLDocument2; end else Result := Document2; end; function TWebBrowserEx.GetViewLinkDocuments(CmdId: TOleEnum): IInterfaceList; var LDocuments: IInterfaceList; begin if Assigned(FOnGetViewLinkDocuments) then begin FOnGetViewLinkDocuments(Self, CmdId, LDocuments); Result := LDocuments; end else Result := nil; end; function TWebBrowserEx.GetElementOfViewLinkDocument(ADocument: IHTMLDocument): IHTMLElement; var LElement: IHTMLElement; begin if Assigned(FOnGetElementOfViewLinkDocument) then begin FOnGetElementOfViewLinkDocument(Self, ADocument, LElement); Result := LElement; end else Result := nil; end; function TWebBrowserEx.GetIsEditableElement(AElement: IHTMLElement; AFlags: TElementEditableFlags): Boolean; var LIsEditable: Boolean; begin if Assigned(FOnGetIsEditableElement) then begin FOnGetIsEditableElement(Self, AElement, AFlags,LIsEditable); Result := LIsEditable; end else Result := True; end; function TWebBrowserEx.GetIsContentPage: Boolean; var LIs: Boolean; begin if Assigned(FOnGetIsEditableElement) then begin FOnGetIsContentPage(Self, LIs); Result := LIs; end else Result := False; end; function TWebBrowserEx.GetCommandTarget: IOleCommandTarget; var LDocument2: IHTMLDocument2; begin Result := nil; if not HandleAllocated then exit; LDocument2 := GetActiveDocument as IHTMLDocument2; if LDocument2 <> nil then Result := LDocument2 as IOleCommandTarget; end; function TWebBrowserEx.GetWindow: IHTMLWindow2; var LDocument2: IHTMLDocument2; begin Result := nil; if not HandleAllocated then exit; LDocument2 := Document2; if LDocument2 <> nil then Result := LDocument2.parentWindow; end; procedure TWebBrowserEx.InvokeEvent(DispID: TDispID; var Params: TDispParams); begin inherited InvokeEvent(DispID, Params); if (FWebBrowserEvents2Dispatch = nil) or HandleAllocated and Assigned(FWebBrowserEvents2Dispatch) and FWebBrowserEvents2Dispatch.Active then exit; case DispID of DISPID_DOCUMENTCOMPLETE: begin FDisplayServices := nil; FCaret := nil; FMarkupServices := nil; FPrimarySelectionServices := nil; if (FInetExplorerServerInstance = nil) then if HandleAllocated then begin HookChildWindows; {$IFDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch.Connect(Document2); FWndEventDispatch.Connect(Window); {$ELSE} FDocEventDispatch.Active := True; FWndEventDispatch.Active := True; FWebBrowserEvents2Dispatch.Active := True; {$ENDIF} end else if Assigned(FOnReloadDocument) then FOnReloadDocument(Self); end; DISPID_BEFORENAVIGATE2: begin {$IFDEF EVENTSINKSUBCOMPONENTS} FDocEventDispatch.Disconnect; {$ELSE} FDocEventDispatch.Active := False; {$ENDIF} end; end; end; procedure TWebBrowserEx.MouseOut(Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseOut) then FOnMouseOut(Self, Shift, X, Y); end; procedure TWebBrowserEx.MouseOver(Shift: TShiftState; X, Y: Integer); begin if Assigned(FOnMouseOver) then FOnMouseOver(Self, Shift, X, Y); end; procedure TWebBrowserEx.DoAfterUpdate; begin if Assigned(FAfterUpdate) then FAfterUpdate(Self); end; procedure TWebBrowserEx.DoBeforeUpdate; begin if Assigned(FBeforeUpdate) then FBeforeUpdate(Self); end; procedure TWebBrowserEx.DoError; begin if Assigned(FOnError) then FOnError(Self); end; procedure TWebBrowserEx.ErrorUpdate; begin if Assigned(FOnErrorUpdate) then FOnErrorUpdate(Self); end; procedure TWebBrowserEx.RowEnter; begin if Assigned(FOnRowEnter) then FOnRowEnter(Self); end; procedure TWebBrowserEx.RowExit; begin if Assigned(FOnRowExit) then FOnRowExit(Self); end; procedure TWebBrowserEx.SelectStart; begin if Assigned(FOnSelectStart) then FOnSelectStart(Self); end; { Here are the interfaces that are queries for... Format: Service <(first_8_digits_of_guid)> -> IID <(first_8_digits_of_guid)> SID_STopLevelBrowser -> ??? SID_STopLevelBrowser -> IShellBrowser ??? -> IUnknown ??? -> IShellBrowser ??? -> IUnknown SID_STopWindow -> ISearchContext ??? -> IUnknown SID_STopLevelBrowser -> IOleCommandTarget IShellBrowser -> IShellBrowser SID_STopLevelBrowser -> IServiceProvider SID_STopLevelBrowser -> IServiceProvider IMimeInfo -> IMimeInfo SID_STopLevelBrowser -> IOleCommandTarget ??? -> ??? SID_STopLevelBrowser -> IOleCommandTarget IOleUndoManager -> IOleUndoManager IPersistMoniker -> IPersistMoniker SID_STopLevelBrowser (4c96be40) -> IServiceProvider (6d5140c1) HTMLFrameBase (3050f312) -> HTMLFrameBase (3050f312) ??? -> IUnknown HTMLObjectElement -> HTMLObjectElement ??? -> ??? ??? -> IUnknown ??? -> IUnknown ??? -> IUnknown IElementBehaviorFactory -> IElementBehaviorFactory ??? -> ??? SID_STopLevelBrowser (4c96be40) -> IServiceProvider (6d5140c1) ??? -> IUnknown ??? -> IUnknown ??? -> IUnknown GopherProtocol -> GopherProtocol ??? -> IUnknown ??? -> IUnknown SID_STopLevelBrowser (4c96be40) -> IServiceProvider (6d5140c1) SID_STopLevelBrowser (4c96be40) -> IServiceProvider (6d5140c1) SID_STopLevelBrowser (4c96be40) -> IOleCommandTarget SID_STopLevelBrowser (4c96be40) -> IOleWindow IShellBrowser -> IShellBrowser SID_STopWindow -> ISearchContext ??? -> ??? SID_STopLevelBrowser (4c96be40) -> IOleCommandTarget ??? -> IUnknown ??? -> IUnknown ??? -> IUnknown SID_STopLevelBrowser (4c96be40) -> IUrlHistoryStg SID_STopLevelBrowser (4c96be40) -> IShellBrowser SID_SEditCommandTarget (3050f4b5) -> IOleCommandTarget SID_SEditCommandTarget (3050f4b5) -> IOleCommandTarget SID_STopLevelBrowser (4c96be40) -> IServiceProvider (6d5140c1) } function TWebBrowserEx.QueryService(const rsid: TGUID; const iid: TGUID; out Obj): HRESULT; var I: Integer; Temp: TWebBrowserServiceProvider; begin // OutputDebugString(PChar('Service ' + GUIDToString(rsid))); // OutputDebugString(PChar('iid ' + GUIDToString(iid))); Result := E_NOINTERFACE; if (Result <> S_OK) and Assigned(FServiceProviders) and not (csDesigning in ComponentState) then begin for I := 0 to FServiceProviders.Count - 1 do begin Temp := TWebBrowserServiceProvider(FServiceProviders[I]); // OutputDebugString(PChar(GUIDToString(Temp.ServiceGUID))); if (IsEqualGUID(rsid, Temp.ServiceGUID) or IsEqualGUID(iid, Temp.ServiceGUID)) and Supports(Temp, iid, Obj) then begin Result := S_OK; Break; end; end; end; if (Result <> S_OK) and Supports(Self, rsid) and Supports(Self, iid, Obj) then Result := S_OK end; procedure TWebBrowserEx.DoLoad; begin if Assigned(FOnLoad) then FOnLoad(Self); end; procedure TWebBrowserEx.DoHelp; begin if Assigned(FOnHelp) then FOnHelp(Self); end; procedure TWebBrowserEx.DoUnLoad; begin if Assigned(FOnUnLoad) then FOnUnLoad(Self); end; procedure TWebBrowserEx.DoBlur; begin if Assigned(FOnBlur) then FOnBlur(Self); end; procedure TWebBrowserEx.DoFocus; begin if Assigned(FOnFocus) then FOnFocus(Self); end; procedure TWebBrowserEx.DoWndResize; begin if Assigned(FOnWndResize) then FOnWndResize(Self); end; procedure TWebBrowserEx.DoScroll; begin if Assigned(FOnScroll) then FOnScroll(Self); end; function TWebBrowserEx.DoBeforeEditFocus(const EventObj: IHTMLEventObj; const DispID: Integer): WordBool; begin if Assigned(FOnBeforeEditFocus) then Result := FOnBeforeEditFocus(Self, EventObj) else Result := False; end; procedure TWebBrowserEx.DoBeforeUnLoad; begin if Assigned(FBeforeUnload) then FBeforeUnload(Self); end; procedure TWebBrowserEx.DoCommandStateChange(Command: TOleEnum; Enable: WordBool); begin end; function TWebBrowserEx.CommandState(const CmdID: TOleEnum): TCommandStates; var C: TCommandStateArray; LEditable: Boolean; begin Result := []; if Document2 <> nil then begin SetLength(C, 1); C[0].cmdID := CmdID; C[0].cmdf := 0; CommandState(C); if C[0].cmdf and OLECMDF_ENABLED = OLECMDF_ENABLED then Include(Result, csEnabled); if C[0].cmdf and OLECMDF_SUPPORTED = OLECMDF_SUPPORTED then Include(Result, csSupported); if C[0].cmdf and OLECMDF_LATCHED = OLECMDF_LATCHED then Include(Result, csChecked); if (csEnabled in Result) and CommandUpdater.WebBrowser.GetIsContentPage then begin LEditable := True; case CmdId of IDM_CUT, IDM_PASTE, IDM_DELETE: case CommandUpdater.WebBrowser.CurrentElementType of cetAtCursor, cetTextRange: LEditable := CommandUpdater.WebBrowser.GetIsEditableElement( CommandUpdater.WebBrowser.CurrentElement, [efInnerRequired]); cetControlRange: LEditable := CommandUpdater.WebBrowser.GetIsEditableElement( CommandUpdater.WebBrowser.CurrentElement.parentElement, [efInnerRequired]); end; IDM_SELECTALL: if not CommandUpdater.WebBrowser.GetIsEditableElement( CommandUpdater.WebBrowser.Document2.body, [efInnerRequired]) then begin LEditable := False; end; end; if not LEditable then begin Exclude(Result, csEnabled); Exclude(Result, csChecked); end; end; end; end; function TWebBrowserEx.CommandState(Cmds: TCommandStateArray): TCommandStateArray; begin SetLength(Result, 0); if Assigned(Document2) then CommandTarget.QueryStatus(@CGID_MSHTML, Length(Cmds), @Cmds[0], nil); end; procedure TWebBrowserEx.LoadFromFile(const FileName: string); var AFile: IPersistFile; Stream: TFileStream; begin if Supports(Document, IPersistFile, AFile) and (AFile.IsDirty <> S_FALSE) then case MessageDlg(sSaveCurrentFile, mtConfirmation, mbYesNoCancel, 0) of mrYes: OleCheck(AFile.Save(nil, True)); mrCancel: exit; end; Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try if Trim(BaseURL) = '' then BaseURL := ExtractFilePath(FileName); LoadFromStream(Stream); finally Stream.Free; end; end; procedure TWebBrowserEx.SaveToFile(const FileName: string); var AFile: IPersistFile; wFileName: WideString; begin if Supports(Document, IPersistFile, AFile) then begin wFileName := FileName; AFile.Save(@wFileName, True); end; end; procedure TWebBrowserEx.RegisterServiceProvider( Provider: TWebBrowserServiceProvider); begin if Provider = nil then raise Exception.Create(sNilProvider); if IsEqualGUID(Provider.ServiceGUID, GUID_NULL) then raise Exception.Create(sInvalidServiceProviderGUID); if not Assigned(FServiceProviders) then FServiceProviders := TComponentList.Create(False); if FServiceProviders.IndexOf(Provider) < 0 then FServiceProviders.Add(Provider); end; procedure TWebBrowserEx.UnRegisterServiceProvider( Provider: TWebBrowserServiceProvider); var Idx: Integer; begin if not (csDestroying in ComponentState) then begin Idx := FServiceProviders.IndexOf(Provider); if Idx <> -1 then FServiceProviders.Extract(Provider); end; if FServiceProviders.Count = 0 then FreeAndNil(FServiceProviders); end; function TWebBrowserEx.GetDisplayServices: IDisplayServices; begin if FDisplayServices = nil then FDisplayServices := Document2 as IDisplayServices; Result := FDisplayServices; end; function TWebBrowserEx.GetMarkupServices: IMarkupServices2; begin if FMarkupServices = nil then FMarkupServices := Document as IMarkupServices2; Result := FMarkupServices; end; function TWebBrowserEx.GetPrimaryMarkupContainer: IMarkupContainer2; begin Result := Document as IMarkupContainer2; end; function TWebBrowserEx.GetSelectionServices: ISelectionServices; begin if FPrimarySelectionServices = nil then OleCheck(HTMLEditServices.GetSelectionServices(PrimaryMarkupContainer, FPrimarySelectionServices)); Result := FPrimarySelectionServices; end; function TWebBrowserEx.Exec(CmdGroup: PGUID; nCmdID, nCmdexecopt: DWORD; const vaIn: OleVariant; var vaOut: OleVariant): HResult; var LDocument2: IHTMLDocument2; begin // Used to handle script errors in a custom manner Result := S_OK; if Assigned(CmdGroup) then begin if IsEqualGUID(CmdGroup^, CGID_DocHostCommandHandler) then case nCmdID of OLECMDID_SHOWSCRIPTERROR: begin LDocument2 := Document2; if LDocument2 <> nil then //LDocument2.parentWindow.event.reason; end; OLECMDID_OPENNEWWINDOW: begin if Assigned(FOnOpenNewWindow) then FOnOpenNewWindow(Self) else Result := OLECMDERR_E_NOTSUPPORTED; end; else Result := OLECMDERR_E_NOTSUPPORTED; end else Result := OLECMDERR_E_UNKNOWNGROUP; {else if IsEqualGUID(CmdGroup^, CGID_Explorer) then case nCmdId of 58: begin if @vaOut <> nil then vaOut := ControlInterface as IDispatch; Result := S_OK; end; else Result := OLECMDERR_E_NOTSUPPORTED; end} end else Result := OLECMDERR_E_UNKNOWNGROUP; end; function TWebBrowserEx.QueryStatus(CmdGroup: PGUID; cCmds: Cardinal; prgCmds: POleCmd; CmdText: POleCmdText): HResult; begin // Result := S_OK; Result := E_NOTIMPL; end; procedure TWebBrowserEx.DoReadyStateChange; begin if Assigned(FOnReadyStateChange) then FOnReadyStateChange(Self); end; procedure TWebBrowserEx.DoStatusTextChange(const Text: string); begin if Assigned(FOnStatusTextChange) then FOnStatusTextChange(Self, Text); end; procedure TWebBrowserEx.Loaded; begin inherited; if Length(FURL) > 0 then Navigate(FURL); end; // Call when selection has changed but browser does not notify procedure TWebBrowserEx.ForceSelectionChange; begin ClearCurrentElement; SelectionChange; end; procedure TWebBrowserEx.ClearCurrentElement; begin FCurrentElement := nil; FCurrentElementType := cetUndefined; end; procedure TWebBrowserEx.SelectionChange; begin if Assigned(FOnSelectionChange) then FOnSelectionChange(Self, Window.event); end; procedure TWebBrowserEx.DoUpdateCommands; begin if Assigned(FOnUpdateCommands) then FOnUpdateCommands(Self); end; function TWebBrowserEx.GetModified: Boolean; var AFile: IPersistFile; begin Result := False; if Assigned(Document) and Supports(Document, IPersistFile, AFile) then Result := AFile.IsDirty = S_OK; end; procedure TWebBrowserEx.CMCancelMode(var Message: TCMCancelMode); begin inherited; if Assigned(FOnCancelMode) then FOnCancelMode(Self); end; function TWebBrowserEx.Notify: HRESULT; begin if Assigned(FOnChange) then FOnChange(Self); Result := S_OK; end; function TWebBrowserEx.OnFocus(fGotFocus: BOOL): HResult; begin Result := inherited OnFocus(fGotFocus); // The following code is necessary so that the control properly regains focus // when tabbing into the webbrowser control. if fGotFocus and Assigned(Document2) then Document2.parentWindow.focus; end; function TWebBrowserEx.GetCaret: IHTMLCaret; begin if FCaret = nil then OleCheck(DisplayServices.GetCaret(FCaret)); Result := FCaret; end; procedure TWebBrowserEx.CMRecreatewnd(var Message: TMessage); begin inherited; end; procedure TWebBrowserEx.InetExplorerServerWndProc(var Message: TMessage); var ParentForm: TCustomForm; Handled: Boolean; begin // Prevent a beep when Alt keys are pressed (like for menus) if (Message.Msg = WM_SYSCOMMAND) or ((Message.Msg = WM_SYSKEYDOWN) and (Message.WParam = VK_MENU)) then begin Message.Result := 1; Exit; end; case Message.Msg of WM_SETCURSOR, WM_RBUTTONUP, WM_RBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_LBUTTONDOWN: if Assigned(FOnInterceptMouseMessage) then begin FOnInterceptMouseMessage(Self, Message, Handled); if Handled then begin Exit; end; end; end; Message.Result := CallWindowProc(FDefInetExplorerServerProc, FInetExplorerServerHandle, Message.Msg, Message.WParam, Message.LParam); case Message.Msg of WM_SETFOCUS: begin // Catching this message allows us to set the Active control to the // WebBrowser itself which keeps VCL in sync with the real active control // which makes things like tabbing work correctly. if (csDestroying in ComponentState) or not CanFocus then exit; FHasFocus := True; GetParentForm(Self).ActiveControl := Self; end; WM_KILLFOCUS: FHasFocus := False; WM_SHOWWINDOW: begin if Message.WParam <> 0 then exit; ParentForm := GetParentForm(Self, False); if Assigned(ParentForm) and Assigned(FBeforeDestroy) then FBeforeDestroy(Self); end; WM_NCDESTROY: UnHookChildWindows; WM_INITMENUPOPUP: if Assigned(FOnInitMenuPopup) then with TWMInitMenuPopup(Message) do FOnInitMenuPopup(Self, MenuPopup, Pos, SystemMenu); end; end; procedure TWebBrowserEx.ShellDocObjWndProc(var Message: TMessage); var LDocument: IHTMLDocument; begin // Hooking this wndproc is necessary to allow the WebBrowser control to // properly regain focus when the application loses then regains focus. Message.Result := CallWindowProc(FDefShellObjViewProc, FShellDocObjViewHandle, Message.Msg, Message.WParam, Message.LParam); case Message.Msg of WM_SETFOCUS: begin if (csDestroying in ComponentState) or not CanFocus then exit; GetParentForm(Self).ActiveControl := Self; LDocument := GetActiveDocument; // Try two different calls for setting focus. IHTMLDocument4.focus works when setting // the focus back to the designer after displaying a modal dialog (e.g.; background color). // It doesn't seem to work when activating the designer by clicking a tab. // IHTMLDocument2.parentWindow.focus works when moving between tabs. However, if editing // a template IHTMLDocument2.parentWindow.focus causes the template editor to lose focus // and the body element to receive focus. Situations when this occur include when template editing // include click on the "design" bottom tab and when template editing and click on the webform1.aspx top tab. if Assigned(LDocument) then (LDocument as IHTMLDocument4).focus; if not Focused then // Previous method doesn't always work so try this if Assigned(Document2) then Document2.parentwindow.focus; end; WM_NCDESTROY: UnHookChildWindows; end; end; procedure TWebBrowserEx.DestroyWindowHandle; begin FDocEventDispatch.Active := False; FWndEventDispatch.Active := False; FWebBrowserEvents2Dispatch.Active := False; inherited; FInetExplorerServerHandle := 0; FShellDocObjViewHandle := 0; end; procedure TWebBrowserEx.ShellWndProc(var Message: TMessage; Wnd: HWnd; WndProc: Pointer); begin try with Message do Result := CallWindowProc(WndProc, Wnd, Msg, WParam, LParam); except Vcl.Forms.Application.HandleException(Self); end; end; procedure TWebBrowserEx.SetCommandUpdater( const Value: TCustomWebBrowserCommandUpdater); begin if FCommandUpdater <> Value then begin if Assigned(FCommandUpdater) then FCommandUpdater.RemoveFreeNotification(Self); FCommandUpdater := Value; if Assigned(FCommandUpdater) then FCommandUpdater.FreeNotification(Self); end; end; procedure TWebBrowserEx.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FCommandUpdater) then FCommandUpdater := nil; end; procedure TWebBrowserEx.HookChildWindows; begin if csDesigning in ComponentState then exit; // Hook child windows to catch destroywnd messages if (FShellDocObjViewHandle <> 0) or (FInetExplorerServerHandle <> 0) then raise Exception.Create(SChildWindowsAlreadyHooked); FShellDocObjViewHandle := Winapi.Windows.GetWindow(Handle, GW_CHILD); if (FShellDocObjViewHandle <> 0) and not FHooksSet then begin FInetExplorerServerInstance := System.Classes.MakeObjectInstance(InetExplorerServerWndProc); FHooksSet := True; FShellDocObjInstance := System.Classes.MakeObjectInstance(ShellDocObjWndProc); if IsWindowUnicode(FShellDocObjViewHandle) then begin FDefShellObjViewProc := Pointer(GetWindowLongW(FShellDocObjViewHandle, GWL_WNDPROC)); SetWindowLongW(FShellDocObjViewHandle, GWL_WNDPROC, Longint(FShellDocObjInstance)); end else begin FDefShellObjViewProc := Pointer(GetWindowLong(FShellDocObjViewHandle, GWL_WNDPROC)); SetWindowLong(FShellDocObjViewHandle, GWL_WNDPROC, Longint(FShellDocObjInstance)); end; FInetExplorerServerHandle := Winapi.Windows.GetWindow(FShellDocObjViewHandle, GW_CHILD); if IsWindowUnicode(FInetExplorerServerHandle) then begin FDefInetExplorerServerProc := Pointer(GetWindowLongW(FInetExplorerServerHandle, GWL_WNDPROC)); SetWindowLongW(FInetExplorerServerHandle, GWL_WNDPROC, Longint(FInetExplorerServerInstance)); end else begin FDefInetExplorerServerProc := Pointer(GetWindowLong(FInetExplorerServerHandle, GWL_WNDPROC)); SetWindowLong(FInetExplorerServerHandle, GWL_WNDPROC, Longint(FInetExplorerServerInstance)); end; end; end; procedure TWebBrowserEx.WMParentNotify(var Message: TWMParentNotify); begin inherited; case Message.Event of WM_DESTROY: UnHookChildWindows; end; end; function TWebBrowserEx.GetOverrideCursor: Boolean; var POut: OleVariant; begin POut := False; if Assigned(CommandTarget) then CommandTarget.Exec(@CGID_MSHTML, IDM_OVERRIDE_CURSOR, OLECMDEXECOPT_DONTPROMPTUSER, POleVariant(nil)^, POut); Result := POut; end; procedure TWebBrowserEx.SetOverrideCursor(const Value: Boolean); var PIn: OleVariant; ViewLinkDocuments: IInterfaceList; I: Integer; LCommandTarget: IOleCommandTarget; begin PIn := Value; if Assigned(CommandTarget) then CommandTarget.Exec(@CGID_MSHTML, IDM_OVERRIDE_CURSOR, OLECMDEXECOPT_DONTPROMPTUSER, PIn, POleVariant(nil)^); ViewLinkDocuments := GetViewLinkDocuments(IDM_OVERRIDE_CURSOR); if ViewLinkDocuments <> nil then begin PIn := Value; for I := 0 to ViewLinkDocuments.Count - 1 do begin LCommandTarget := ViewLinkDocuments[I] as IOleCommandTarget; if LCommandTarget <> nil then LCommandTarget.Exec(@CGID_MSHTML, IDM_OVERRIDE_CURSOR, OLECMDEXECOPT_DONTPROMPTUSER, PIn, POleVariant(nil)^); end; end; end; procedure TWebBrowserEx.UnHookChildWindows; begin FDocEventDispatch.Active := False; FWndEventDispatch.Active := False; FWebBrowserEvents2Dispatch.Active := False; if FShellDocObjViewHandle <> 0 then begin SetWindowLongW(FShellDocObjViewHandle, GWL_WNDPROC, IntPtr(FDefShellObjViewProc)); System.Classes.FreeObjectInstance(FShellDocObjInstance); FShellDocObjViewHandle := 0; FShellDocObjInstance := nil; end; if FInetExplorerServerHandle <> 0 then begin SetWindowLongW(FInetExplorerServerHandle, GWL_WNDPROC, IntPtr(FDefInetExplorerServerProc)); System.Classes.FreeObjectInstance(FInetExplorerServerInstance); FInetExplorerServerHandle := 0; FInetExplorerServerInstance := nil; end; FHooksSet := (FInetExplorerServerHandle <> 0) or (FShellDocObjViewHandle <> 0); end; function TWebBrowserEx.DoOnControlSelect( const EventObj: IHTMLEventObj): WordBool; begin Result := True; if Assigned (FOnControlSelect) then Result := OnControlSelect(Self, EventObj); end; function TWebBrowserEx.DoOnControlMove(const EventObj: IHTMLEventObj; DispID: Integer): WordBool; begin Result := True; if Assigned (FOnControlMove) then Result := OnControlMove(Self, EventObj, DispID); end; function TWebBrowserEx.DoOnControlResize(const EventObj: IHTMLEventObj; DispID: Integer): WordBool; begin Result := True; if Assigned (FOnControlResize) then Result := OnControlResize(Self, EventObj, DispID); end; procedure TWebBrowserEx.DoResolveRelativePath(var Path: string); begin Path := ''; if Assigned(FOnResolveRelativePath) then FOnResolveRelativePath(Self, Path); end; function EnumChildProc(hWnd: THandle; lParam: LongInt): Bool; stdcall; export; begin Result := False; if TWebBrowserEx(lParam).FHasFocus then exit; TWebBrowserEx(lParam).FHasFocus := GetForegroundWindow = hWnd; end; function TWebBrowserEx.Focused: Boolean; begin Result := inherited Focused or FHasFocus; end; procedure TWebBrowserEx.ClearDirtyFlag; var AStream: IPersistStreamInit; begin if Supports(Document, IPersistStreamInit, AStream) and (AStream.IsDirty <> S_FALSE) then OleCheck(AStream.Save(nil, True)); end; procedure TWebBrowserEx.SetModified(const Value: Boolean); var PIn: OleVariant; begin PIn := Value; // CommandTarget is nil when loading browser before the designer is shown. if CommandTarget <> nil then CommandTarget.Exec(@CGID_MSHTML, IDM_SETDIRTY, OLECMDEXECOPT_DONTPROMPTUSER, PIn, POleVariant(nil)^); end; { THTMLElementEventDispatch } procedure THTMLElementEventDispatch.AfterConstruction; begin inherited; FIID := DIID_HTMLElementEvents2; end; function THTMLElementEventDispatch.GetEventInterface: IInterface; begin Result := FHTMLElement; end; function THTMLElementEventDispatch.DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; begin Result := E_NOTIMPL; {$IFDEF DEVELOPERS} case DispID of DISPID_HTMLELEMENTEVENTS_ONHELP: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONHELP'); DISPID_HTMLELEMENTEVENTS_ONCLICK: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCLICK'); DISPID_HTMLELEMENTEVENTS_ONDBLCLICK: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDBLCLICK'); DISPID_HTMLELEMENTEVENTS_ONKEYPRESS: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONKEYPRESS'); DISPID_HTMLELEMENTEVENTS_ONKEYDOWN: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONKEYDOWN'); DISPID_HTMLELEMENTEVENTS_ONKEYUP: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONKEYUP'); DISPID_HTMLELEMENTEVENTS_ONMOUSEOUT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEOUT'); DISPID_HTMLELEMENTEVENTS_ONMOUSEOVER: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEOVER'); DISPID_HTMLELEMENTEVENTS_ONMOUSEMOVE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEMOVE'); DISPID_HTMLELEMENTEVENTS_ONMOUSEDOWN: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEDOWN'); DISPID_HTMLELEMENTEVENTS_ONMOUSEUP: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEUP'); DISPID_HTMLELEMENTEVENTS_ONSELECTSTART: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONSELECTSTART'); DISPID_HTMLELEMENTEVENTS_ONFILTERCHANGE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONFILTERCHANGE'); DISPID_HTMLELEMENTEVENTS_ONDRAGSTART: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAGSTART'); DISPID_HTMLELEMENTEVENTS_ONBEFOREUPDATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFOREUPDATE'); DISPID_HTMLELEMENTEVENTS_ONAFTERUPDATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONAFTERUPDATE'); DISPID_HTMLELEMENTEVENTS_ONERRORUPDATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONERRORUPDATE'); DISPID_HTMLELEMENTEVENTS_ONROWEXIT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONROWEXIT'); DISPID_HTMLELEMENTEVENTS_ONROWENTER: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONROWENTER'); DISPID_HTMLELEMENTEVENTS_ONDATASETCHANGED: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDATASETCHANGED'); DISPID_HTMLELEMENTEVENTS_ONDATAAVAILABLE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDATAAVAILABLE'); DISPID_HTMLELEMENTEVENTS_ONDATASETCOMPLETE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDATASETCOMPLETE'); DISPID_HTMLELEMENTEVENTS_ONLOSECAPTURE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONLOSECAPTURE'); DISPID_HTMLELEMENTEVENTS_ONPROPERTYCHANGE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONPROPERTYCHANGE'); DISPID_HTMLELEMENTEVENTS_ONSCROLL: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONSCROLL'); DISPID_HTMLELEMENTEVENTS_ONFOCUS: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONFOCUS'); DISPID_HTMLELEMENTEVENTS_ONBLUR: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBLUR'); DISPID_HTMLELEMENTEVENTS_ONRESIZE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONRESIZE'); DISPID_HTMLELEMENTEVENTS_ONDRAG: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAG'); DISPID_HTMLELEMENTEVENTS_ONDRAGEND: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAGEND'); DISPID_HTMLELEMENTEVENTS_ONDRAGENTER: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAGENTER'); DISPID_HTMLELEMENTEVENTS_ONDRAGOVER: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAGOVER'); DISPID_HTMLELEMENTEVENTS_ONDRAGLEAVE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDRAGLEAVE'); DISPID_HTMLELEMENTEVENTS_ONDROP: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDROP'); DISPID_HTMLELEMENTEVENTS_ONBEFORECUT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFORECUT'); DISPID_HTMLELEMENTEVENTS_ONCUT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCUT'); DISPID_HTMLELEMENTEVENTS_ONBEFORECOPY: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFORECOPY'); DISPID_HTMLELEMENTEVENTS_ONCOPY: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCOPY'); DISPID_HTMLELEMENTEVENTS_ONBEFOREPASTE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFOREPASTE'); DISPID_HTMLELEMENTEVENTS_ONPASTE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONPASTE'); DISPID_HTMLELEMENTEVENTS_ONCONTEXTMENU: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCONTEXTMENU'); DISPID_HTMLELEMENTEVENTS_ONROWSDELETE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONROWSDELETE'); DISPID_HTMLELEMENTEVENTS_ONROWSINSERTED: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONROWSINSERTED'); DISPID_HTMLELEMENTEVENTS_ONCELLCHANGE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCELLCHANGE'); DISPID_HTMLELEMENTEVENTS_ONREADYSTATECHANGE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONREADYSTATECHANGE'); DISPID_HTMLELEMENTEVENTS_ONBEFOREEDITFOCUS: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFOREEDITFOCUS'); DISPID_HTMLELEMENTEVENTS_ONLAYOUTCOMPLETE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONLAYOUTCOMPLETE'); DISPID_HTMLELEMENTEVENTS_ONPAGE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONPAGE'); DISPID_HTMLELEMENTEVENTS_ONBEFOREDEACTIVATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFOREDEACTIVATE'); DISPID_HTMLELEMENTEVENTS_ONBEFOREACTIVATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONBEFOREACTIVATE'); DISPID_HTMLELEMENTEVENTS_ONMOVE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOVE'); DISPID_HTMLELEMENTEVENTS_ONCONTROLSELECT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONCONTROLSELECT'); DISPID_HTMLELEMENTEVENTS_ONMOVESTART: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOVESTART'); DISPID_HTMLELEMENTEVENTS_ONMOVEEND: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOVEEND'); DISPID_HTMLELEMENTEVENTS_ONRESIZESTART: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONRESIZESTART'); DISPID_HTMLELEMENTEVENTS_ONRESIZEEND: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONRESIZEEND'); DISPID_HTMLELEMENTEVENTS_ONMOUSEENTER: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEENTER'); DISPID_HTMLELEMENTEVENTS_ONMOUSELEAVE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSELEAVE'); DISPID_HTMLELEMENTEVENTS_ONMOUSEWHEEL: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONMOUSEWHEEL'); DISPID_HTMLELEMENTEVENTS_ONACTIVATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONACTIVATE'); DISPID_HTMLELEMENTEVENTS_ONDEACTIVATE: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONDEACTIVATE'); DISPID_HTMLELEMENTEVENTS_ONFOCUSIN: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONFOCUSIN'); DISPID_HTMLELEMENTEVENTS_ONFOCUSOUT: OutputDebugString('DISPID_HTMLELEMENTEVENTS_ONFOCUSOUT'); end; {$ENDIF} end; function THTMLElementEventDispatch.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin Result := inherited QueryInterface(IID, Obj); if Result <> S_OK then begin if Supports(Self, IDispatch, Obj) then Result := S_OK; end; end; { TWebBrowserServiceProvider } constructor TWebBrowserServiceProvider.Create(AOwner: TComponent); begin inherited; FServiceGUID := GUID_NULL; end; destructor TWebBrowserServiceProvider.Destroy; begin if Assigned(WebBrowser) then WebBrowser.UnRegisterServiceProvider(Self); inherited; end; procedure TWebBrowserServiceProvider.SetWebBrowser( const Value: TWebBrowserEx); begin if Assigned(WebBrowser) and (Value <> WebBrowser) then WebBrowser.UnRegisterServiceProvider(Self); inherited; if Assigned(Value) then Value.RegisterServiceProvider(Self); end; { TCustomWebBrowserCommandUpdater } function TCustomWebBrowserCommandUpdater.CommandState(CmdID: TOleEnum): TCommandStates; var I: Integer; begin Result := []; if Find(CmdID, I) then if FCmds[I].cmdID = CmdID then begin if FCmds[I].cmdf and OLECMDF_ENABLED = OLECMDF_ENABLED then Include(Result, csEnabled); if FCmds[I].cmdf and OLECMDF_SUPPORTED = OLECMDF_SUPPORTED then Include(Result, csSupported); if FCmds[I].cmdf and OLECMDF_LATCHED = OLECMDF_LATCHED then Include(Result, csChecked); if Assigned(FOnFilterCommandState) then FOnFilterCommandState(Self, CmdID, Result); end; end; procedure TCustomWebBrowserCommandUpdater.DoElementPropertiesChanged(Element: IHTMLElement; Properties: TElementProperties); begin if Assigned(FOnElementPropertiesChanged) then FOnElementPropertiesChanged(Self, Element, Properties); end; procedure TCustomWebBrowserCommandUpdater.DoAfterCommand(CmdID: Cardinal); begin if Assigned(FAfterCommand) then FAfterCommand(Self, CmdID); end; procedure TCustomWebBrowserCommandUpdater.DoBeforeCommand(CmdID: Cardinal; var Executed: Boolean); begin Executed := False; if Assigned(FBeforeCommand) then FBeforeCommand(Self, CmdID, Executed); end; function TCustomWebBrowserCommandUpdater.Find(const CmdID: TOleEnum; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; if not Assigned(WebBrowser) then exit; L := 0; H := Length(FCmds) - 1; while L <= H do begin I := (L + H) shr 1; C := Integer(FCmds[I].cmdID - CmdID); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then Result := True; end; end; Index := L; end; function TCustomWebBrowserCommandUpdater.GetActionState(Action: TObject; State: TCommandState; Value: Boolean): Boolean; begin if Assigned(FOnGetActionState) then FOnGetActionState(Self, Action, State, Value, Result) else Result := False; end; procedure TCustomWebBrowserCommandUpdater.QuickSort(L, R: Integer); var I, J, P: Integer; Temp: _tagOLECMD; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while FCmds[I].cmdID < FCmds[P].cmdID do Inc(I); while FCmds[J].cmdID > FCmds[P].cmdID do Dec(J); if I <= J then begin Temp := FCmds[I]; FCmds[I] := FCmds[J]; FCmds[J] := Temp; if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; procedure TCustomWebBrowserCommandUpdater.RegisterCommand(CmdID: Cardinal); begin if CmdID = 0 then exit; SetLength(FCmds, Length(FCmds) + 1); FCmds[Length(FCmds) - 1].cmdID := CmdID; QuickSort(0, Length(FCmds) - 1); end; procedure TCustomWebBrowserCommandUpdater.RegisterCommands( CmdIDs: array of Cardinal); var I: Integer; begin for I := 0 to Length(CmdIDs) - 1 do RegisterCommand(CmdIDs[I]); end; procedure TCustomWebBrowserCommandUpdater.SaveActionState(Action: TObject; State: TCommandState; Value: Boolean); begin if Assigned(FOnSaveActionState) then FOnSaveActionState(Self, Action, State, Value); end; procedure TCustomWebBrowserCommandUpdater.SetWebBrowser( const Value: TWebBrowserEx); begin inherited; if Assigned(Value) then begin Value.CommandUpdater := Self; Value.FreeNotification(Self); end; end; procedure TCustomWebBrowserCommandUpdater.UnRegisterCommand(CmdID: Cardinal); var idx: Integer; I: Integer; begin idx := 0; while (idx < Length(FCmds)) and (FCmds[idx].cmdID <> CmdID) do Inc(idx); if idx = Length(FCmds) then exit; for I := idx to Length(FCmds) - 2 do FCmds[I] := FCmds[I + 1]; SetLength(FCmds, Length(FCmds) - 1); end; procedure TCustomWebBrowserCommandUpdater.UnRegisterCommands( CmdIDs: array of Cardinal); var I: Integer; begin for I := 0 to Length(CmdIDs) - 1 do UnRegisterCommand(CmdIDs[I]); end; procedure TCustomWebBrowserCommandUpdater.UpdateCommands(CmdID: Cardinal); var CommandTarget: IOleCommandTarget; Idx: Integer; Len: Integer; begin if not Assigned(WebBrowser) or not Assigned(WebBrowser.Document) or (csDestroying in WebBrowser.ComponentState) or (Length(FCmds) = 0) then exit; Idx := 0; if (CmdID = 0) or Find(CmdID, Idx) then begin if CmdID <> 0 then Len := 1 else Len := Length(FCmds); if Supports(WebBrowser.Document2, IOleCommandTarget, CommandTarget) then CommandTarget.QueryStatus(@CGID_MSHTML, Len, @FCmds[Idx], nil); WebBrowser.DoUpdateCommands; end; if Assigned(FOnUpdateCommands) then FOnUpdateCommands(Self, CmdID); end; { TStreamLoadMoniker } function TStreamLoadMoniker.BindToObject(const bc: IBindCtx; const mkToLeft: IMoniker; const iidResult: TGUID; out vResult): HRESULT; begin Result := FMoniker.BindToObject(bc, mkToLeft, iidResult, vResult); end; function TStreamLoadMoniker.BindToStorage(const bc: IBindCtx; const mkToLeft: IMoniker; const iid: TGUID; out vObj): HRESULT; begin Result := MK_E_NOSTORAGE; if IsEqualGUID(iid, IID_IStream) and Supports(TStreamAdapter.Create(FStream), IStream, vObj) then Result := S_OK; end; function TStreamLoadMoniker.CommonPrefixWith(const mkOther: IMoniker; out mkPrefix: IMoniker): HRESULT; begin Result := FMoniker.CommonPrefixWith(mkOther, mkPrefix); end; function TStreamLoadMoniker.ComposeWith(const mkRight: IMoniker; fOnlyIfNotGeneric: LongBool; out mkComposite: IMoniker): HRESULT; begin Result := FMoniker.ComposeWith(mkRight, fOnlyIfNotGeneric, mkComposite); end; constructor TStreamLoadMoniker.Create(AStream: TStream; BaseURL: string); begin FStream := AStream; FBaseURL := BaseURL; Assert(BaseUrl <> ''); OleCheck(CreateURLMoniker(nil, StringToOleStr(FBaseUrl), FMoniker)); { do not localize } end; function TStreamLoadMoniker.Enum(fForward: LongBool; out enumMoniker: IEnumMoniker): HRESULT; begin Result := FMoniker.Enum(fForward, enumMoniker); end; function TStreamLoadMoniker.GetClassID(out classID: TGUID): HRESULT; begin Result := FMoniker.GetClassID(classID); end; function TStreamLoadMoniker.GetDisplayName(const bc: IBindCtx; const mkToLeft: IMoniker; out pszDisplayName: PWideChar): HRESULT; begin Result := FMoniker.GetDisplayName(bc, mkToLeft, pszDisplayName); end; function TStreamLoadMoniker.GetSizeMax(out cbSize: Int64): HRESULT; begin Result := FMoniker.GetSizeMax(cbSize); end; function TStreamLoadMoniker.GetTimeOfLastChange(const bc: IBindCtx; const mkToLeft: IMoniker; out filetime: _FILETIME): HRESULT; begin Result := FMoniker.GetTimeOfLastChange(bc, mkToLeft, filetime); end; function TStreamLoadMoniker.Hash(out dwHash: Integer): HRESULT; begin Result := FMoniker.Hash(dwHash); end; function TStreamLoadMoniker.Inverse(out mk: IMoniker): HRESULT; begin Result := FMoniker.Inverse(mk); end; function TStreamLoadMoniker.IsDirty: HRESULT; begin Result := FMoniker.IsDirty; end; function TStreamLoadMoniker.IsEqual(const mkOtherMoniker: IMoniker): HRESULT; begin Result := FMoniker.IsEqual(mkOtherMoniker); end; function TStreamLoadMoniker.IsRunning(const bc: IBindCtx; const mkToLeft, mkNewlyRunning: IMoniker): HRESULT; begin Result := FMoniker.IsRunning(bc, mkToLeft, mkNewlyRunning); end; function TStreamLoadMoniker.IsSystemMoniker(out dwMksys: Integer): HRESULT; begin Result := FMoniker.IsSystemMoniker(dwMksys); end; function TStreamLoadMoniker.Load(const stm: IStream): HRESULT; begin Result := Load(stm); end; function TStreamLoadMoniker.ParseDisplayName(const bc: IBindCtx; const mkToLeft: IMoniker; pszDisplayName: PWideChar; out chEaten: Integer; out mkOut: IMoniker): HRESULT; begin Result := FMoniker.ParseDisplayName(bc, mkToLeft, pszDisplayName, chEaten, mkOut); end; function TStreamLoadMoniker.Reduce(const bc: IBindCtx; dwReduceHowFar: Integer; mkToLeft: PIMoniker; out mkReduced: IMoniker): HRESULT; begin Result := FMoniker.Reduce(bc, dwReduceHowFar, mkToLeft, mkReduced); end; function TStreamLoadMoniker.RelativePathTo(const mkOther: IMoniker; out mkRelPath: IMoniker): HRESULT; begin Result := FMoniker.RelativePathTo(mkOther, mkRelPath); end; function TStreamLoadMoniker.Save(const stm: IStream; fClearDirty: LongBool): HRESULT; begin Result := FMoniker.Save(stm, fClearDirty); end; { TIFrameDocEventDispatch } function TIFrameDocEventDispatch.DoInvoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var dps: TDispParams; pDispIds: PDispIdList; VarResult, ExcepInfo, ArgErr: Pointer): HRESULT; var EventObj: IHTMLEventObj; begin Result := DISP_E_MEMBERNOTFOUND; case DispID of DISPID_HTMLDOCUMENTEVENTS2_ONCLICK, DISPID_HTMLDOCUMENTEVENTS2_ONDBLCLICK: // DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREEDITFOCUS, // DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOVER: begin OleVariant (VarResult^) := False; if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then with IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal) as IHTMLEventObj do cancelBubble := True; Result := S_OK; end; end; {$IFDEF SAVE_DEVELOPERS} // OutputDebugString(PChar(Format('%x', [Dispid]))); case DispID of DISPID_HTMLDOCUMENTEVENTS2_ONHELP: OutputDebugString('iframe:ONHELP'); DISPID_HTMLDOCUMENTEVENTS2_ONCLICK: begin OleVariant (VarResult^) := False; if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then with IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal) as IHTMLEventObj do cancelBubble := True; OutputDebugString('iframe:ONCLICK'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONDBLCLICK: begin OleVariant (VarResult^) := False; if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then with IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal) as IHTMLEventObj do cancelBubble := True; OutputDebugString('iframe:ONDBLCLICK'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONKEYDOWN: OutputDebugString('iframe:ONKEYDOWN'); DISPID_HTMLDOCUMENTEVENTS2_ONKEYUP: OutputDebugString('iframe:ONKEYUP'); DISPID_HTMLDOCUMENTEVENTS2_ONKEYPRESS: OutputDebugString('iframe:ONKEYPRESS'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEDOWN: OutputDebugString('iframe:ONMOUSEDOWN'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEMOVE: begin // OleVariant (VarResult^) := False; // (IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkval) as IHTMLEventObj).cancelBubble := True; OutputDebugString('iframe:iframe:ONMOUSEMOVE'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEUP: OutputDebugString('iframe:ONMOUSEUP'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOUT: OutputDebugString('iframe:ONMOUSEOUT'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOVER: begin OleVariant (VarResult^) := False; if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then with IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal) as IHTMLEventObj do cancelBubble := True; OutputDebugString('iframe:ONMOUSEOVER'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONREADYSTATECHANGE: OutputDebugString('iframe:ONREADYSTATECHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREUPDATE: OutputDebugString('iframe:ONBEFOREUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONAFTERUPDATE: OutputDebugString('iframe:ONAFTERUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONROWEXIT: OutputDebugString('iframe:ONROWEXIT'); DISPID_HTMLDOCUMENTEVENTS2_ONROWENTER: OutputDebugString('iframe:ONROWENTER'); DISPID_HTMLDOCUMENTEVENTS2_ONDRAGSTART: OutputDebugString('iframe:ONDRAGSTART'); DISPID_HTMLDOCUMENTEVENTS2_ONSELECTSTART: OutputDebugString('iframe:ONSELECTSTART'); DISPID_HTMLDOCUMENTEVENTS2_ONERRORUPDATE: OutputDebugString('iframe:ONERRORUPDATE'); DISPID_HTMLDOCUMENTEVENTS2_ONCONTEXTMENU: OutputDebugString('iframe:ONCONTEXTMENU'); DISPID_HTMLDOCUMENTEVENTS2_ONSTOP: OutputDebugString('iframe:ONSTOP'); DISPID_HTMLDOCUMENTEVENTS2_ONROWSDELETE: OutputDebugString('iframe:ONROWSDELETE'); DISPID_HTMLDOCUMENTEVENTS2_ONROWSINSERTED: OutputDebugString('iframe:ONROWSINSERTED'); DISPID_HTMLDOCUMENTEVENTS2_ONCELLCHANGE: OutputDebugString('iframe:ONCELLCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONPROPERTYCHANGE: OutputDebugString('iframe:ONPROPERTYCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCHANGED: OutputDebugString('iframe:ONDATASETCHANGED'); DISPID_HTMLDOCUMENTEVENTS2_ONDATAAVAILABLE: OutputDebugString('iframe:ONDATAAVAILABLE'); DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCOMPLETE: OutputDebugString('iframe:ONDATASETCOMPLETE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREEDITFOCUS: begin OleVariant (VarResult^) := False; if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then with IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal) as IHTMLEventObj do cancelBubble := True; OutputDebugString('iframe:ONBEFOREEDITFOCUS'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE: OutputDebugString('DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE'); DISPID_HTMLDOCUMENTEVENTS2_ONCONTROLSELECT: OutputDebugString('iframe:ONCONTROLSELECT'); DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEWHEEL: OutputDebugString('iframe:ONMOUSEWHEEL'); DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSIN: begin if Supports(IUnknown(dps.rgvarg^ [pDispIds^ [0]].unkVal), IHTMLEventObj, EventObj) then EventObj.cancelBubble := True; OutputDebugString('iframe:ONFOCUSIN'); Result := S_OK; end; DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSOUT: OutputDebugString('iframe:ONFOCUSOUT'); DISPID_HTMLDOCUMENTEVENTS2_ONACTIVATE: OutputDebugString('iframe:ONACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONDEACTIVATE: OutputDebugString('iframe:ONDEACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREACTIVATE: OutputDebugString('iframe:ONBEFOREACTIVATE'); DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREDEACTIVATE: OutputDebugString('iframe:ONBEFOREDEACTIVATE'); else // Result := inherited DoInvoke(DispID, IID, LocaleID, Flags, dps, pDispIds, // VarResult, ExcepInfo, ArgErr); OutputDebugString(PChar('HTMLDOCEVENT = ' + IntToStr(DispID))); end; {$ENDIF} end; function TIFrameDocEventDispatch.GetEventInterface: IInterface; begin Result := Document; end; initialization // Required for Cut and Copy to work within the MSTHML control OleInitialize(nil); finalization OleUnInitialize; end.
unit ATWinAmpDriver; { Name : ATWinAmpDriver <ATWinAmpDriver.PAS> Version : 1.01 Description : Component to drive/control WinAmp from your Delphi app. Programmer : Sony Arianto Kurniawan Copyright © Nov-Dec, 1998 AriTech Development Indonesia Tools : Borland Delphi 3.0 C/S E-Mail : sony-ak@iname.com Web site : http://www.geocities.com/Pentagon/5900/ Type : Freeware Price : $0.00 Made in Indonesia History : v1.00 - First release to public v1.01 - Init some vars Note : - Latest check with WinAmp v2.03 - This component is FREEWARE if : - You credits me in your app. if you use this component/code - some code portion from WAIPC.PAS by Brendin J. Emslie } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TATWAShowMode = (wamNormal,wamHide,wamMinimize,wamMaximize); TATWinAmpDriver = class(TComponent) private FAuthor,NullValS : string; FWAPath : string; FWASMode : TATWAShowMode; procedure SetWinAmpMode(value:TATWAShowMode); protected procedure ExecuteCmd(cmd:integer); // execute WinAmp commands public constructor Create(AOwner:TComponent); override; destructor Destroy; override; function GetWinAmpHandle:hWnd; // get WinAmp handle function IsWinAmpRunning:boolean; // check if WinAmp is running function GetWinAmpVersionStr:string; // get WinAmp version in string form function GetWinAmpVersionInt:integer; // get WinAmp version in integer form function GetPlayBackStatus:integer; // if it play=1;pause=3 or not_play=0 function GetSongLength:integer; // get song length in seconds function GetSongPos:integer; // get song pos in milliseconds function GetPlayListLength:integer; // get playlist length in tracks function WritePlayList:integer; // write play list to disk // writes to <WinAmpDir>\WinAmp.pl function JumpToTime(newsongpos:integer):integer;// jump to new song position // in milliseconds, // return 0=success // 1=on eof // -1=error // ONLY AVAILABLE IN v1.60+ procedure AddToPlayList(fname:string); // add file name to play list procedure DeletePlayList; // delete play list procedure Play; // start play the music from playlist procedure ChangeDir(newdir:string); // change directory procedure SetPlayListPos(newplpos:integer); // set playlist pos for v2.00+ procedure SetVolume(newvol:integer); // set volume for v2.00+ (0-255) procedure SetPanning(newpan:integer); // set panning for v2.00+ (0-255) procedure EQWindow; // toggle EQ window procedure PlayListWindow; // toggle PlayList window procedure VolumeUp; // set volume up a little procedure VolumeDown; // set volume down a little procedure ForwardFive; // forward 5 seconds procedure RewindFive; // rewind five seconds procedure GoToPrevSong; // go to previous song procedure ShowLoadFile; // show load file(s) box procedure ShowPreferences; // show preferences box procedure SetAOT; // toggle set "Always On Top" option procedure ShowAbout; // show about box (cute) //button related procedures procedure BtnPrevSong; // Button1 click procedure BtnStartList; // Ctrl+Button1 click procedure BtnRewFive; // Shift+Button1 click procedure BtnPlay; // Button2 click procedure BtnOpenLocation; // Ctrl+Button2 click procedure BtnLoadFile; // Shift+Button2 click procedure BtnPause; // Button3 click procedure BtnStop; // Button4 click procedure BtnFadeStop; // Shift+Button4 click procedure BtnFwdSong; // Button5 click procedure BtnEndList; // Ctrl+Button5 click procedure BtnFwdFive; // Shift+Button5 click function LaunchWinAmp:integer; // try to launch WinAmp 0=success;1=fail function ShutdownWinAmp:integer; // try to shutdown WinAmp 0=success;1=fail published property Author : string read FAuthor write NullValS; property WinAmpPath : string read FWAPath write FWAPath; property WinAmpMode : TATWAShowMode read FWASMode write SetWinAmpMode; end; procedure Register; implementation const // List of WinAmp's IPCs IPC_GETVERSION = 0; IPC_PLAYFILE = 100; // add to playlist IPC_DELETE = 101; // delete playlist IPC_STARTPLAY = 102; // start the music IPC_CHDIR = 103; // change directory IPC_ISPLAYING = 104; // is WinAmp playing music? IPC_GETOUTPUTTIME = 105; // get song length & song position IPC_JUMPTOTIME = 106; // jump to new song position IPC_WRITEPLAYLIST = 120; // write playlist to disk IPC_SETPLAYLISTPOS = 121; // set playlist position IPC_SETVOLUME = 122; // set WinAmp volume IPC_SETPANNING = 123; // set WinAmp panning IPC_GETLISTLENGTH = 124; // get playlist length in tracks // List of WinAmp's commands WINAMP_OPTIONS_EQ = 40036; WINAMP_OPTIONS_PLEDIT = 40040; WINAMP_VOLUMEUP = 40058; WINAMP_VOLUMEDOWN = 40059; WINAMP_FFWD5S = 40060; WINAMP_REW5S = 40061; // List of WinAmp's button control WINAMP_BUTTON1 = 40044; WINAMP_BUTTON2 = 40045; WINAMP_BUTTON3 = 40046; WINAMP_BUTTON4 = 40047; WINAMP_BUTTON5 = 40048; WINAMP_BUTTON1_SHIFT = 40144; WINAMP_BUTTON2_SHIFT = 40145; WINAMP_BUTTON3_SHIFT = 40146; WINAMP_BUTTON4_SHIFT = 40147; WINAMP_BUTTON5_SHIFT = 40148; WINAMP_BUTTON1_CTRL = 40154; WINAMP_BUTTON2_CTRL = 40155; WINAMP_BUTTON3_CTRL = 40156; WINAMP_BUTTON4_CTRL = 40157; WINAMP_BUTTON5_CTRL = 40158; // List of WinAmp's additional control WINAMP_PREVSONG = 40198; WINAMP_FILE_PLAY = 40029; WINAMP_OPTIONS_PREFS = 40012; WINAMP_OPTIONS_AOT = 40019; WINAMP_HELP_ABOUT = 40041; function TATWinAmpDriver.ShutdownWinAmp:integer; begin result := 0; if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_CLOSE,0,0) else result := 1; end; procedure TATWinAmpDriver.SetWinAmpMode(value:TATWAShowMode); var mode : integer; begin mode := SW_HIDE; if value = FWASMode then exit; FWASMode := value; if IsWinAmpRunning then begin case value of wamNormal : mode := SW_SHOWNORMAL; wamHide : mode := SW_HIDE; wamMaximize : mode := SW_MAXIMIZE; wamMinimize : mode := SW_MINIMIZE; end; ShowWindow(GetWinAmpHandle,mode); end; end; function TATWinAmpDriver.LaunchWinAmp:integer; var mode : integer; begin result := 0; mode := SW_HIDE; case FWASMode of wamNormal : mode := SW_SHOWNORMAL; wamHide : mode := SW_HIDE; wamMaximize : mode := SW_MAXIMIZE; wamMinimize : mode := SW_MINIMIZE; end; if WinExec(PChar(FWAPath),mode) <= 31 then result := 1; end; procedure TATWinAmpDriver.BtnPrevSong; begin ExecuteCmd(WINAMP_BUTTON1); end; procedure TATWinAmpDriver.BtnStartList; begin ExecuteCmd(WINAMP_BUTTON1_CTRL); end; procedure TATWinAmpDriver.BtnRewFive; begin ExecuteCmd(WINAMP_BUTTON1_SHIFT); end; procedure TATWinAmpDriver.BtnPlay; begin ExecuteCmd(WINAMP_BUTTON2); end; procedure TATWinAmpDriver.BtnOpenLocation; begin ExecuteCmd(WINAMP_BUTTON2_CTRL); end; procedure TATWinAmpDriver.BtnLoadFile; begin ExecuteCmd(WINAMP_BUTTON2_SHIFT); end; procedure TATWinAmpDriver.BtnPause; begin ExecuteCmd(WINAMP_BUTTON3); end; procedure TATWinAmpDriver.BtnStop; begin ExecuteCmd(WINAMP_BUTTON4); end; procedure TATWinAmpDriver.BtnFadeStop; begin ExecuteCmd(WINAMP_BUTTON4_SHIFT); end; procedure TATWinAmpDriver.BtnFwdSong; begin ExecuteCmd(WINAMP_BUTTON5); end; procedure TATWinAmpDriver.BtnEndList; begin ExecuteCmd(WINAMP_BUTTON5_CTRL); end; procedure TATWinAmpDriver.BtnFwdFive; begin ExecuteCmd(WINAMP_BUTTON5_SHIFT); end; procedure TATWinAmpDriver.GoToPrevSong; begin ExecuteCmd(WINAMP_PREVSONG); end; procedure TATWinAmpDriver.ShowLoadFile; begin ExecuteCmd(WINAMP_FILE_PLAY); end; procedure TATWinAmpDriver.ShowPreferences; begin ExecuteCmd(WINAMP_OPTIONS_PREFS); end; procedure TATWinAmpDriver.SetAOT; begin ExecuteCmd(WINAMP_OPTIONS_AOT); end; procedure TATWinAmpDriver.ShowAbout; begin ExecuteCmd(WINAMP_HELP_ABOUT); end; procedure TATWinAmpDriver.VolumeUp; begin ExecuteCmd(WINAMP_VOLUMEUP); end; procedure TATWinAmpDriver.VolumeDown; begin ExecuteCmd(WINAMP_VOLUMEDOWN); end; procedure TATWinAmpDriver.ForwardFive; begin ExecuteCmd(WINAMP_FFWD5S); end; procedure TATWinAmpDriver.RewindFive; begin ExecuteCmd(WINAMP_REW5S); End; procedure TATWinAmpDriver.EQWindow; begin ExecuteCmd(WINAMP_OPTIONS_EQ); end; procedure TATWinAmpDriver.PlayListWindow; begin ExecuteCmd(WINAMP_OPTIONS_PLEDIT); end; procedure TATWinAmpDriver.ExecuteCmd(cmd:integer); begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_COMMAND,cmd,0); end; function TATWinAmpDriver.GetPlayListLength:integer; begin result := 0; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,0,IPC_GETLISTLENGTH); end; procedure TATWinAmpDriver.SetPanning(newpan:integer); begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_USER,newpan,IPC_SETPANNING); end; procedure TATWinAmpDriver.SetVolume(newvol:integer); begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_USER,newvol,IPC_SETVOLUME); end; procedure TATWinAmpDriver.SetPlayListPos(newplpos:integer); begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_USER,newplpos,IPC_SETPLAYLISTPOS); end; function TATWinAmpDriver.WritePlaylist:integer; begin result := -1; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,0,IPC_WRITEPLAYLIST); // result is the index of the current song in the playlist end; function TATWinAmpDriver.JumpToTime(newsongpos:integer):integer; begin result := -1; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,newsongpos,IPC_JUMPTOTIME); end; function TATWinAmpDriver.GetSongPos:integer; begin result := -1; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,0,IPC_GETOUTPUTTIME); end; function TATWinAmpDriver.GetSongLength:integer; begin result := -1; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,1,IPC_GETOUTPUTTIME); end; function TATWinAmpDriver.GetPlayBackStatus:integer; begin result := $0F; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,0,IPC_ISPLAYING); end; procedure TATWinAmpDriver.ChangeDir(newdir:string); var i : integer; begin if IsWinAmpRunning then begin for i:=0 to length(newdir) do PostMessage(GetWinAmpHandle,WM_USER,ord(PChar(newdir)[i]),IPC_CHDIR); PostMessage(GetWinAmpHandle,WM_USER,0,IPC_CHDIR); end; end; procedure TATWinAmpDriver.Play; begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_USER,0,IPC_STARTPLAY); end; procedure TATWinAmpDriver.DeletePlayList; begin if IsWinAmpRunning then SendMessage(GetWinAmpHandle,WM_USER,0,IPC_DELETE); end; procedure TATWinAmpDriver.AddToPlayList(fname:string); var i : integer; begin if IsWinAmpRunning then begin for i:=0 to length(fname) do PostMessage(GetWinAmpHandle,WM_USER,ord(PChar(fname)[i]),IPC_PLAYFILE); PostMessage(GetWinAmpHandle,WM_USER,0,IPC_PLAYFILE); end; end; function TATWinAmpDriver.GetWinAmpVersionStr:string; begin result := 'Unknown Version'; if IsWinAmpRunning then case SendMessage(GetWinAmpHandle,WM_USER,0,IPC_GETVERSION) of $1551 : result := '1.55'; $16A0 : result := '1.6b'; $16AF : result := '1.60'; $16B0 : result := '1.61'; $16B1 : result := '1.62'; $16B3 : result := '1.64'; $16B4 : result := '1.666'; $16B5 : result := '1.69'; $1700 : result := '1.70'; $1702 : result := '1.72'; $1703 : result := '1.73'; $1800 : result := '1.80'; $1801 : result := '1.81'; $1802 : result := '1.82'; $1900 : result := '1.90'; $1901 : result := '1.91'; $2000 : result := '2.00'; $2001 : result := '2.01'; $2002 : result := '2.02'; $2003 : result := '2.03'; $2004 : result := '2.04'; end; end; function TATWinAmpDriver.GetWinAmpVersionInt:integer; begin result := 0; if IsWinAmpRunning then result := SendMessage(GetWinAmpHandle,WM_USER,0,IPC_GETVERSION); end; function TATWinAmpDriver.IsWinAmpRunning:boolean; begin result := false; if GetWinAmpHandle <> 0 then result := true; end; function TATWinAmpDriver.GetWinAmpHandle:hWnd; begin result := FindWindow('Winamp v1.x',nil); // find WinAmp handle end; constructor TATWinAmpDriver.Create(AOwner:TComponent); begin inherited Create(AOwner); FAuthor := 'Sony Arianto Kurniawan [November,1998]'; FWAPath := ''; FWASMode := wamNormal; end; destructor TATWinAmpDriver.Destroy; begin inherited; end; procedure Register; begin RegisterComponents('ActiveX', [TATWinAmpDriver]); end; end.
unit UEmpForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, pegradpanl, StdCtrls, Mask, Grids, DBGrids, Db, DBTables, pegraphic, DBClient, MIDAScon, Tmax_DataSetText, OnDBGrid, OnFocusButton, ComCtrls, OnShapeLabel, OnGrDBGrid, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl, OnPopupEdit; type TFm_EmpForm = class(TForm) ds1: TDataSource; Query1: TTMaxDataSet; Panel2: TPanel; BB_close: TOnFocusButton; Sb_Ok: TOnFocusButton; Sb_Close: TOnFocusButton; Grid1: TOnGrDbGrid; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Sb_CloseClick(Sender: TObject); procedure Sb_OkClick(Sender: TObject); procedure Grid1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } FOrgDept : string; Fempno : string; Fkorname : string; Fdeptname : string; Fpayclname : string; Fpayraname : string; Fe1empno : string; FConyn : string; FFinyn : string; SqlText : string; public Edit : TOnWinPopupEdit; FCloseYn : Boolean; property OrgDeptList : string read FOrgDept write FOrgDept; property empno : string read Fempno write Fempno; property korname : string read Fkorname write Fkorname; property deptname : string read Fdeptname write Fdeptname; property payclname : string read Fpayclname write Fpayclname; property payraname : string read Fpayraname write Fpayraname; property e1empno : string read Fe1empno write Fe1empno; property Conyn : string read FConyn write FConyn; property Finyn : string read FFinyn write FFinyn; procedure SqlOpen; end; var Fm_EmpForm : TFm_EmpForm; implementation uses HMainForm; {$R *.DFM} procedure TFm_EmpForm.FormCreate(Sender: TObject); begin FCloseYn := False; end; procedure TFm_EmpForm.Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssleft in shift then begin Releasecapture; Self.Perform(WM_SYSCOMMAND, $F012, 0); end; end; procedure TFm_EmpForm.Sb_CloseClick(Sender: TObject); begin Fempno := ''; Fkorname := ''; Fdeptname := ''; Fpayclname := ''; Fpayraname := ''; Fe1empno := ''; FCloseYn := True; Edit.PopupForm.ClosePopup(False); FM_MAIN.BT_ExitClick(FM_MAIN.Bt_Exit); end; procedure TFm_EmpForm.Sb_OkClick(Sender: TObject); begin if (FM_MAIN.E_ChangeEmp.Text <> Query1.FieldByName('empno').AsString) And (Query1.FieldByName('Conyn').AsString = 'Y') then begin if Query1.FieldByName('Finyn').AsString = 'Y' then MessageDlg('이미 [팀원 Action Contract 결재]을 완료 하였습니다.' + #13+#13+ '[팀원 Action Contract 결재] 내용 확인만 할수 있습니다.', mtInformation, [mbOK],0); Fempno := Query1.FieldByName('empno').AsString; Fkorname := Query1.FieldByName('korname').AsString; Fdeptname := Query1.FieldByName('deptname').AsString; Fpayclname := Query1.FieldByName('payclname').AsString; Fpayraname := Query1.FieldByName('payraname').AsString; FE1empno := Query1.FieldByName('e1empno').AsString; FConyn := Query1.FieldByName('conyn').AsString; FFinyn := Query1.FieldByName('finyn').AsString; FCloseYn := False; Edit.PopupForm.ClosePopup(False); end else begin MessageDlg('해당 팀원이 아직 등록 작업을 마치지 않았습니다.'+#13 ,mtError,[mbOK],0); end; end; procedure TFm_EmpForm.SqlOpen; var i : integer; Field : TField; SqlText : string; begin SqlText := ' SELECT A.EMPNO, (select KORNAME from pimpmas where empno = a.empno) KORNAME, ' + ' A.ORGNUM,B.DEPTCODE,B.DEPTNAME, ' + ' A.PAYCL, C.CODENAME PAYCLNAME, A.PAYRA, E.CODENAME PAYRANAME, ' + ' (select JOBPAYRAYN from pimpmas where empno = a.empno) JOBPAYRAYN, ' + ' A.E1empno, F.RVALCONYN CONYN, F.E1VALCONYN FINYN, ' + ' decode(F.E1VALCONYN,''R'',''반려'',''Y'',''결재완료'', ' + ' decode(F.RVALCONYN,''Y'',''결재상신중'', ''등록중'')) prog ' + ' FROM PEHREMAS A, PYCDEPT B, PYCCODE C, PYCCODE E, PEACTFILE F ' + ' WHERE A.rabasdate = '''+ FM_MAIN.vRabasdate +''' ' + ' and F.rabasYm(+) = '''+ FM_MAIN.vRabasym +''' ' + ' AND A.DEPTCODE = B.DEPTCODE ' + ' AND A.ORGNUM = B.ORGNUM ' + ' AND A.PAYCL = C.CODENO(+) AND C.CODEID(+) = ''I112'' ' + ' AND A.PAYRA = E.CODENO(+) AND E.CODEID(+) = ''I113'' ' + ' AND SubStr(A.RabasDate,1,4) = SubStr(F.rabasym(+),1,4) ' + ' And A.EMPNO = F.EMPNO(+) ' + ' AND A.E1payra < '''+FM_MAIN.payrafrom+''' ' + ' AND ((A.payra >= '''+FM_MAIN.payrafrom+''') And ' + ' (A.payra <= '''+FM_MAIN.payrato +''') ) ' + ' AND (A.empno not in ('''+FM_MAIN.objemp1+''','''+FM_MAIN.objemp2+''', ' + ' '''+FM_MAIN.objemp3+''','''+FM_MAIN.objemp4+''', ' + ' '''+FM_MAIN.objemp5+''','''+FM_MAIN.objemp6+''', ' + ' '''+FM_MAIN.objemp7+''','''+FM_MAIN.objemp8+''' )) ' + ' AND A.RECONYN = ''Y'' ' + ' AND A.EMPNO <> A.E1EMPNO ' + ' AND SUBSTR(A.EMPNO,1,1) NOT IN (''Q'',''P'',''Y'',''J'') ' + ' AND A.E1EMPNO = '''+ FM_MAIN.E_ChangeEmp.Text +''' ' + ' ORDER BY A.DEPTCODE, A.PAYRA, A.EMPNO ' ; with Query1 do begin Close; ClearFieldInFo; AddField('EMPNO' , ftString, 4 ); AddField('KORNAME' , ftString, 12 ); AddField('ORGNUM' , ftString, 3 ); AddField('DEPTCODE' , ftString, 6 ); AddField('DEPTNAME' , ftString, 60 ); AddField('PAYCL' , ftString, 3 ); AddField('PAYCLNAME' , ftString, 20 ); AddField('PAYRA' , ftString, 3 ); AddField('PAYRANAME' , ftString, 20 ); AddField('JOBPAYRAYN' , ftString, 2 ); AddField('E1EMPNO' , ftString, 20 ); AddField('CONYN' , ftString, 1 ); AddField('FINYN' , ftString, 1 ); AddField('PROG' , ftString, 11 ); Sql.Clear; Sql.Text := SqlText; memo1.text := SqlText; ServiceName := 'PIT1030A_SEL9'; Open; Locate('EMPNO',vararrayof([FM_Main.Ed_empno.Text]),[loCaseInsensitive]); end; for i := 0 to Query1.FieldCount - 1 do begin Field := Query1.Fields[i]; Field.Visible := False; case Field.Index of 0 : begin Field.Visible := True; Field.DisplayWidth := 8; Field.DisplayLabel := '사 번'; end; 1 : begin Field.Visible := True; Field.DisplayWidth := 12; Field.DisplayLabel := '성 명'; end; 8 : begin Field.Visible := True; Field.DisplayWidth := 10; Field.DisplayLabel := '직 책'; end; 4 : begin Field.Visible := True; Field.DisplayWidth := 32; Field.DisplayLabel := '부 서 명'; end; 13: begin Field.Visible := True; Field.DisplayWidth := 16; Field.DisplayLabel := '진행상황'; end; end; end; Width := GetDisplayWidth(Grid1.Canvas,Grid1.Font,87) + 36; end; procedure TFm_EmpForm.Grid1KeyPress(Sender: TObject; var Key: Char); begin if Key = Chr(13) then begin Key := #0; Sb_OkClick(Sender); end; end; end.
unit SearchComponentCategoryQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, Vcl.StdCtrls, DSWrap; type TSearchComponentCategoryW = class(TDSWrap) private FExternalID: TParamWrap; FProductCategoryID: TFieldWrap; FProductID: TFieldWrap; procedure AddNewValue(AIDComponent, AIDCategory: Integer); public constructor Create(AOwner: TComponent); override; property ExternalID: TParamWrap read FExternalID; property ProductCategoryID: TFieldWrap read FProductCategoryID; property ProductID: TFieldWrap read FProductID; end; TQuerySearchComponentCategory = class(TQueryBase) private FW: TSearchComponentCategoryW; function Search(AIDComponent, AIDCategory: Integer): Integer; overload; function Search(AIDComponent: Integer; const ASubGroup: String) : Integer; overload; { Private declarations } public constructor Create(AOwner: TComponent); override; procedure LocateOrAddValue(AIDComponent, AIDCategory: Integer); procedure SearchAndDelete(AIDComponent: Integer; const ASubGroup: String); property W: TSearchComponentCategoryW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper; constructor TQuerySearchComponentCategory.Create(AOwner: TComponent); begin inherited; FW := TSearchComponentCategoryW.Create(FDQuery); end; function TQuerySearchComponentCategory.Search(AIDComponent: Integer; const ASubGroup: String): Integer; var ASQL: string; begin Assert(AIDComponent > 0); // Добавляем соединение таблиц ASQL := SQL; ASQL := ASQL.Replace('/* productCategories', '', [rfReplaceAll]); ASQL := ASQL.Replace('productCategories */', '', [rfReplaceAll]); // Добавляем условие ASQL := ReplaceInSQL(ASQL, Format('%s = :%s', [W.ProductID.FullName, W.ProductID.FieldName]), 0); // Добавляем условие FDQuery.SQL.Text := ReplaceInSQL(ASQL, Format('instr('',''||:%s||'','', '',''||%s||'','') = 0', [W.ExternalID.FieldName, W.ExternalID.FullName]), 1); SetParamType(W.ProductID.FieldName); SetParamType(W.ExternalID.FieldName, ptInput, ftWideString); Result := Search([W.ProductID.FieldName, W.ExternalID.FieldName], [AIDComponent, ASubGroup]); end; procedure TQuerySearchComponentCategory.SearchAndDelete(AIDComponent: Integer; const ASubGroup: String); begin if Search(AIDComponent, ASubGroup) > 0 then W.DeleteAll; end; procedure TQuerySearchComponentCategory.LocateOrAddValue(AIDComponent, AIDCategory: Integer); begin if Search(AIDComponent, AIDCategory) = 0 then W.AddNewValue(AIDComponent, AIDCategory); end; function TQuerySearchComponentCategory.Search(AIDComponent, AIDCategory: Integer): Integer; begin Assert(AIDComponent > 0); Assert(AIDCategory > 0); Result := SearchEx([TParamRec.Create(W.ProductID.FullName, AIDComponent), TParamRec.Create(W.ProductCategoryID.FullName, AIDCategory)]); end; constructor TSearchComponentCategoryW.Create(AOwner: TComponent); begin inherited; FProductCategoryID := TFieldWrap.Create(Self, 'ppc.ProductCategoryID'); FProductID := TFieldWrap.Create(Self, 'ppc.ProductID'); FExternalID := TParamWrap.Create(Self, 'pc.externalID'); end; procedure TSearchComponentCategoryW.AddNewValue(AIDComponent, AIDCategory: Integer); begin Assert(AIDComponent > 0); Assert(AIDCategory > 0); TryAppend; ProductID.F.AsInteger := AIDComponent; ProductCategoryID.F.AsInteger := AIDCategory; TryPost; end; end.
unit Main; interface {$include KControls.inc} uses {$IFDEF FPC} LCLIntf, LResources, LCLProc, {$ELSE} Windows, Messages, {$ENDIF} SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, KGrids, KMemo, KGraphics, KFunctions, ExtCtrls, Grids, StdCtrls, KEditCommon, KSplitter, KControls, KLabels, KDialogs; type { TMainForm } TMainForm = class(TForm) BUtest: TButton; BUPreview: TButton; BUPrint: TButton; PNMain: TPanel; Panel1: TPanel; Panel2: TPanel; BULoad: TButton; Splitter1: TSplitter; KPrintPreviewDialog1: TKPrintPreviewDialog; KPrintSetupDialog1: TKPrintSetupDialog; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure KMemo1DropFiles(Sender: TObject; X, Y: Integer; Files: TStrings); procedure BULoadClick(Sender: TObject); procedure BUPreviewClick(Sender: TObject); procedure BUPrintClick(Sender: TObject); procedure BUTestClick(Sender: TObject); private { Private declarations } KMemo1: TKMemo; KMemo2: TKMemo; procedure LoadFiles; procedure Test1; procedure Test2; procedure Test3; procedure Test4; procedure Test5; procedure Test6; procedure Test7; procedure Test8; procedure Test9; procedure Test10; procedure Test11; procedure Test12; procedure Test13; procedure Test14; procedure Test15; procedure Test16; procedure Test17; procedure Test18; procedure Test19; procedure Test20; procedure Test21; procedure Test22; procedure Test23; procedure Test24; public { Public declarations } end; var MainForm: TMainForm; implementation {$IFDEF FPC} {$R *.lfm} {$ELSE} {$R *.dfm} {$ENDIF} procedure TMainForm.FormCreate(Sender: TObject); begin KMemo1 := TKMemo.Create(Self); KMemo1.ContentPadding.Top := 20; KMemo1.ContentPadding.Left := 20; KMemo1.ContentPadding.Right := 20; KMemo1.ContentPadding.Bottom := 20; KMemo1.Align := alClient; KMemo1.Options := KMemo1.Options + [eoDropFiles, eoShowFormatting, eoWantTab]; KMemo1.OnDropFiles := KMemo1DropFiles; KMemo1.Parent := Panel1; KMemo1.PageSetup.Title := 'test_document'; KMemo1.Clear; KMemo2 := TKMemo.Create(Self); KMemo2.ContentPadding.Top := 20; KMemo2.ContentPadding.Left := 20; KMemo2.ContentPadding.Right := 20; KMemo2.ContentPadding.Bottom := 20; KMemo2.Align := alClient; KMemo2.Options := KMemo2.Options + [eoShowFormatting, eoWantTab]; KMemo2.Parent := Panel2; KMemo2.Clear; end; procedure TMainForm.FormResize(Sender: TObject); begin Panel1.Width := ClientWidth div 2; end; procedure TMainForm.BUPreviewClick(Sender: TObject); begin Test20; end; procedure TMainForm.BUPrintClick(Sender: TObject); begin Test21; end; procedure TMainForm.BULoadClick(Sender: TObject); begin LoadFiles; end; procedure TMainForm.LoadFiles; begin // KMemo1.LoadFromRTF('test.rtf'); // KMemo1.LoadFromRTF('test1.rtf'); // KMemo1.LoadFromRTF('test_no_img.rtf'); // KMemo1.LoadFromRTF('test_simple.rtf'); KMemo1.LoadFromRTF('kmemo_manual.rtf'); // KMemo1.LoadFromRTF('simpletable.rtf'); // KMemo1.LoadFromRTF('advancedtable.rtf'); // KMemo1.Select(10, 510); KMemo1.SaveToRTF('test_save.rtf'); KMemo2.LoadFromRTF('test_save.rtf'); KMemo2.SaveToRTF('test_copy_save.rtf'); end; procedure TMainForm.KMemo1DropFiles(Sender: TObject; X, Y: Integer; Files: TStrings); begin KMemo1.LoadFromFile(Files[0]); end; procedure TMainForm.BUTestClick(Sender: TObject); begin Test24; end; procedure TMainForm.Test1; begin KMemo1.Blocks.AddTextBlock('Hello world!'); end; procedure TMainForm.Test2; begin KMemo1.Blocks.Clear; KMemo1.Blocks.AddTextBlock('Hello world!'); end; procedure TMainForm.Test3; begin with KMemo1.Blocks do begin LockUpdate; try Clear; AddTextBlock('Hello world!'); finally UnlockUpdate; end; end; end; procedure TMainForm.Test4; begin with KMemo1.Blocks do begin LockUpdate; try Clear; AddTextBlock('First paragraph text!'); AddParagraph; AddTextBlock('Second paragraph text!'); AddParagraph; finally UnlockUpdate; end; end; end; procedure TMainForm.Test5; var TB: TKMemoTextBlock; begin TB := KMemo1.Blocks.AddTextBlock('Hello world!'); TB.TextStyle.Font.Name := 'Arial'; TB.TextStyle.Font.Color := clRed; TB.TextStyle.Font.Style := [fsBold]; end; procedure TMainForm.Test6; var TB: TKMemoTextBlock; PA: TKMemoParagraph; begin TB := KMemo1.Blocks.AddTextBlock('Hello world!'); PA := KMemo1.Blocks.AddParagraph; PA.ParaStyle.HAlign := halCenter; PA.ParaStyle.BottomPadding := 20; end; procedure TMainForm.Test7; var TB: TKMemoTextBlock; PA: TKMemoParagraph; begin TB := KMemo1.Blocks.AddTextBlock('Hello world!'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuArabic; end; procedure TMainForm.Test8; var TB: TKMemoTextBlock; PA: TKMemoParagraph; begin KMemo1.Blocks.LockUpdate; try KMemo1.Blocks.Clear; KMemo1.Blocks.AddTextBlock('This is test text 1. This is test text 1. This is test text 1. This is test text 1. This is test text 1. This is test text 1.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuLetterHi; PA.NumberingListLevel.FirstIndent := -20; PA.NumberingListLevel.LeftIndent := 20; TB := KMemo1.Blocks.AddTextBlock('This is a test text 2.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuLetterHi; TB := KMemo1.Blocks.AddTextBlock('This is a level 2 test text 1.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuRomanLo; PA.NumberingListLevel.FirstIndent := -20; PA.NumberingListLevel.LeftIndent := 60; TB := KMemo1.Blocks.AddTextBlock('This is a level 2 test text 2.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuRomanLo; TB := KMemo1.Blocks.AddTextBlock('This is a level 1 test text 1.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuArabic; PA.NumberingListLevel.FirstIndent := -20; PA.NumberingListLevel.LeftIndent := 40; TB := KMemo1.Blocks.AddTextBlock('This is a level 1 test text 2.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuArabic; TB := KMemo1.Blocks.AddTextBlock('This is a level 2 test text 3.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuRomanLo; TB := KMemo1.Blocks.AddTextBlock('This is a test text 3.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuLetterHi; PA.ParaStyle.NumberStartAt := 1; TB := KMemo1.Blocks.AddTextBlock('This is a bullet text.'); PA := KMemo1.Blocks.AddParagraph; PA.Numbering := pnuBullets; finally KMemo1.Blocks.UnlockUpdate; end; end; procedure TMainForm.Test9; begin KMemo1.Blocks.AddImageBlock('penguins.jpg'); end; procedure TMainForm.Test10; var IB: TKMemoImageBlock; begin IB := KMemo1.Blocks.AddImageBlock('penguins.jpg'); IB.Position := mbpRelative; IB.LeftOffset := 50; end; procedure TMainForm.Test11; var CO: TKMemoContainer; begin CO := KMemo1.Blocks.AddContainer; CO.Position := mbpRelative; CO.LeftOffset := 50; CO.TopOffset := 20; CO.FixedWidth := True; CO.RequiredWidth := 300; CO.BlockStyle.Brush.Color := clLime; CO.Blocks.AddTextBlock('Text in a container!'); CO.Blocks.AddImageBlock('penguins.jpg'); end; procedure TMainForm.Test12; var TBL: TKMemoTable; begin TBL := KMemo1.Blocks.AddTable; TBL.ColCount := 2; TBL.RowCount := 2; TBL.Cells[0, 0].Blocks.AddTextBlock('Table text 1'); TBL.Cells[0, 1].Blocks.AddTextBlock('Table text 2'); TBL.Cells[1, 0].Blocks.AddTextBlock('Table text 3'); TBL.Cells[1, 1].Blocks.AddTextBlock('Table text 4'); TBL.CellStyle.BorderWidth := 1; TBL.ApplyDefaultCellStyle; end; procedure TMainForm.Test13; procedure AddTextField(CO: TKMemoContainer; Text1: Boolean); var TB: TKMemoTextBlock; PA: TKMemoParagraph; begin CO.Blocks.LockUpdate; try if Text1 then begin TB := CO.Blocks.AddTextBlock('This is test text 1'); TB.TextStyle.Font.Color := clRed; PA := CO.Blocks.AddParagraph; PA.ParaStyle.Brush.Color := clInfoBk; PA.ParaStyle.BorderRadius := 5; TB := CO.Blocks.AddTextBlock('This is test text 2'); TB.TextStyle.Brush.Color := clYellow; TB.TextStyle.Font.Style := [fsBold]; CO.Blocks.AddImageBlock('../../resource_src/kmessagebox_stop.png'); CO.Blocks.AddParagraph; CO.Blocks.AddTextBlock('This is test text 3'); CO.Blocks.AddParagraph; CO.Blocks.AddTextBlock('This is test text 4'); CO.Blocks.AddParagraph; CO.Blocks.AddHyperlink('www.google.com', 'www.google.com'); CO.Blocks.AddParagraph; end else begin TB := CO.Blocks.AddTextBlock('This is other text 1'); CO.Blocks.AddParagraph; end; finally CO.Blocks.UnlockUpdate; end; end; var TBL: TKMemoTable; begin KMemo1.Blocks.LockUpdate; try TBL := KMemo1.Blocks.AddTable; TBL.BlockStyle.TopPadding := 20; TBL.BlockStyle.BottomPadding := 30; TBL.CellStyle.BorderWidth := 2; TBL.CellStyle.ContentPadding.AssignFromValues(5,5,5,5); TBL.CellStyle.Brush.Color := clWhite; TBL.ColCount := 3; TBL.RowCount := 3; TBL.Rows[0].RequiredHeight := 200; TBL.Rows[1].Cells[1].ColSpan := 2; TBL.Rows[1].Cells[0].RowSpan := 2; AddTextField(TBL.Rows[0].Cells[0], True); AddTextField(TBL.Rows[0].Cells[1], True); AddTextField(TBL.Rows[0].Cells[2], True); AddTextField(TBL.Rows[1].Cells[0], True); AddTextField(TBL.Rows[1].Cells[1], False); AddTextField(TBL.Rows[1].Cells[2], False); AddTextField(TBL.Rows[2].Cells[0], True); AddTextField(TBL.Rows[2].Cells[1], True); AddTextField(TBL.Rows[2].Cells[2], True); // TBL.FixedWidth := True; // TBL.RequiredWidth := 600; TBL.ApplyDefaultCellStyle; finally KMemo1.Blocks.UnLockUpdate; end; end; procedure TMainForm.Test14; begin KMemo1.Blocks.AddHyperlink('www.google.com', 'www.google.com'); end; procedure TMainForm.Test15; begin KMemo1.Colors.BkGnd := clYellow; KMemo1.Background.Image.LoadFromFile('../../resource_src/clouds.jpg'); end; procedure TMainForm.Test16; begin KMemo1.TextStyle.Font.Name := 'Arial'; KMemo1.TextStyle.Font.Size := 20; KMemo1.ParaStyle.HAlign := halCenter; end; procedure TMainForm.Test17; begin KMemo1.LoadFromRTF('kmemo_manual.rtf'); KMemo1.SaveToRTF('kmemo_manual_copy.rtf'); end; procedure TMainForm.Test18; begin KMemo1.ExecuteCommand(ecSelectAll); KMemo1.ExecuteCommand(ecCopy); end; procedure TMainForm.Test19; var TextStyle: TKMemoTextStyle; ParaStyle: TKMemoParaStyle; begin KMemo1.ExecuteCommand(ecSelectAll); ParaStyle := TKMemoParaStyle.Create; TextStyle := TKMemoTextStyle.Create; try TextStyle.Font.Style := [fsBold]; ParaStyle.FirstIndent := 20; KMemo1.SelectionParaStyle := ParaStyle; KMemo1.SelectionTextStyle := TextStyle; finally ParaStyle.Free; TextStyle.Free; end; end; procedure TMainForm.Test20; begin KPrintPreviewDialog1.Control := KMemo1; KPrintPreviewDialog1.Execute; end; procedure TMainForm.Test21; begin KPrintSetupDialog1.Control := KMemo1; KPrintSetupDialog1.Execute; end; procedure TMainForm.Test22; var StartPos, EndPos: Integer; TextStyle: TKMemoTextStyle; begin TextStyle := TKMemoTextStyle.Create; try TextStyle.Font.Style := [fsBold]; TextStyle.Font.Size := 20; KMemo1.Blocks.Clear; KMemo1.Blocks.AddTextBlock('Hell '); KMemo1.Blocks.AddTextBlock('Hello'); KMemo1.Blocks.AddTextBlock('Hello '); KMemo1.Blocks.AddParagraph; KMemo1.Blocks.AddTextBlock('Hello'); KMemo1.Blocks.AddTextBlock('Hello'); KMemo1.Blocks.AddTextBlock(' Hell'); KMemo1.GetNearestWordIndexes(12, False, StartPos, EndPos); KMemo1.Select(StartPos, EndPos - StartPos); KMemo1.SelectionTextStyle := TextStyle; finally TextStyle.Free; end; end; procedure TMainForm.Test23; var Picture: TPicture; IB: TKMemoImageBlock; begin Picture := TPicture.Create; try Picture.LoadFromFile('penguins.jpg'); IB := TKMemoImageBlock.Create; IB.Image := Picture; KMemo1.Blocks.AddAt(IB, -1); KMemo1.Select(KMemo1.SelectableLength, 0); finally Picture.Free; end; end; procedure TMainForm.Test24; var TBL: TKMemoTable; TB: TKMemoTextBlock; Blocks: TKMemoBlocks; Stream: TMemoryStream; begin Test13; //create a table TBL := KMemo1.Blocks[KMemo1.Blocks.Count - 1] as TKMemoTable; Blocks := TBL.Cells[0, 0].Blocks; TB := Blocks.AddTextBlock('Table text 1 Bold'); TB.TextStyle.Font.Style := [fsBold]; Stream := TMemoryStream.Create; try Blocks.SaveToRTFStream(Stream); //Stream.SaveToFile('testblocks.rtf'); Blocks := TBL.Cells[0, 1].Blocks; Stream.Seek(0, soFromBeginning); Blocks.Clear; Blocks.LoadFromRTFStream(Stream); finally Stream.Free; end; end; end.
unit ncServCom; interface uses Windows, WinProcs, Messages, Classes, SysUtils, ScktComp, ExtCtrls, CSCServer, CSCQueue, CSCBase, CSCTimer, lmdcompo, LMDVersionInfo, Dialogs, ncSessao, ncDebug, ncErros, ncNetMsg, ncMsgCom, ncServBase, ncCredTempo, ncMovEst, ncDebito, ncImpressao, ncCompCliente, ncClassesBase; type TncServComunicacao = class; TncServComunicacao = class ( TComponent ) private FServCom : TCSCServer; FCliente : TClienteNexCafe; FAtivo : Boolean; FWndHandle: HWND; FVersion : TLmdVersionInfo; FTimerR : TTimer; FTimerHora: TTimer; FSockLic : Integer; procedure EnviaEvento(MsgID: Integer; P: Pointer; Tam: Integer; Tipo: Byte); procedure CriaWndHandle; procedure SetServidor(Valor: TncServidorBase); function GetServidor: TncServidorBase; procedure AoConectarCliente(Sender: TObject; Socket: TCustomWinSocket); procedure AoDesconectarCliente(Sender: TObject; Socket: TCustomWinSocket); procedure OnTimerR(Sender: TObject); procedure OnTimerHora(Sender: TObject); protected procedure DespachaMC(var Msg: TMessage); procedure SetAtivo(Valor: Boolean); virtual; {---- TCP/IP Message Handlers -------------------------------------------} procedure nmLogin(var Msg: TCSCMessage); message ncnmLogin; procedure nmLogout(var Msg: TCSCMessage); message ncnmLogout; procedure nmObtemLista(var Msg: TCSCMessage); message ncnmObtemLista; procedure nmAlteraObj(var Msg: TCSCMessage); message ncnmAlteraObj; procedure nmNovoObj(var Msg: TCSCMessage); message ncnmNovoObj; procedure nmApagaObj(var Msg: TCSCMessage); message ncnmApagaObj; procedure nmLoginMaq(var Msg: TCSCMessage); message ncnmLoginMaq; procedure nmLogoutMaq(var Msg: TCSCMessage); message ncnmLogoutMaq; procedure nmPararTempoMaq(var Msg: TCSCMessage); message ncnmPararTempoMaq; procedure nmTransferirMaq(var Msg: TCSCMessage); message ncnmTransferirMaq; procedure nmPreLogoutMaq(var Msg: TCSCMessage); message ncnmPreLogoutMaq; procedure nmCancLogoutMaq(var Msg: TCSCMessage); message ncnmCancLogoutMaq; procedure nmCapturaTelaMaq(var Msg: TCSCMessage); message ncnmCapturaTelaMaq; procedure nmSalvaTelaMaq(var Msg: TCSCMessage); message ncnmSalvaTelaMaq; procedure nmObtemStreamConfig(var Msg: TCSCMessage); message ncnmObtemStreamConfig; procedure nmRefreshPrecos(var Msg: TCSCMessage); message ncnmRefreshPrecos; procedure nmRefreshEspera(var Msg: TCSCMessage); message ncnmRefreshEspera; procedure nmShutdown(var Msg: TCSCMessage); message ncnmShutdown; procedure nmSuporteRem(var Msg: TCSCMessage); message ncnmSuporteRem; procedure nmBaixaAtualizacao(var Msg: TCSCMessage); message ncnmBaixaAtualizacao; procedure nmModoManutencao(var Msg: TCSCMessage); message ncnmModoManutencao; procedure nmAdicionaPassaporte(var Msg: TCSCMessage); message ncnmAdicionaPassaporte; procedure nmPaginasImpressas(var Msg: TCSCMessage); message ncnmPaginasImpressas; procedure nmAvisos(var Msg: TCSCMessage); message ncnmAvisos; procedure nmObtemPastaServ(var Msg: TCSCMessage); message ncnmObtemPastaServ; procedure nmArqFundoEnviado(var Msg: TCSCMessage); message ncnmArqFundoEnviado; procedure nmLimpaFundo(var Msg: TCSCMessage); message ncnmLimpaFundo; procedure nmObtemSenhaCli(var Msg: TCSCMessage); message ncnmObtemSenhaCli; procedure nmSalvaSenhaCli(var Msg: TCSCMessage); message ncnmSalvaSenhaCli; procedure nmEnviaChat(var Msg: TCSCMessage); message ncnmEnviaChat; procedure nmSalvaCredTempo(var Msg: TCSCMessage); message ncnmSalvaCredTempo; procedure nmSalvaMovEst(var Msg: TCSCMessage); message ncnmSalvaMovEst; procedure nmSalvaDebito(var Msg: TCSCMessage); message ncnmSalvaDebito; procedure nmSalvaLancExtra(var Msg: TCSCMessage); message ncnmSalvaLancExtra; procedure nmSalvaDebTempo(var Msg: TCSCMessage); message ncnmSalvaDebTempo; procedure nmSalvaImpressao(var Msg: TCSCMessage); message ncnmSalvaImpressao; procedure nmAlteraSessao(var Msg: TCSCMessage); message ncnmAlteraSessao; procedure nmRefreshSessao(var Msg: TCSCMessage); message ncnmRefreshSessao; procedure nmCancelaTran(var Msg: TCSCMessage); message ncnmCancelaTran; procedure nmAbreCaixa(var Msg: TCSCMessage); message ncnmAbreCaixa; procedure nmFechaCaixa(var Msg: TCSCMessage); message ncnmFechaCaixa; procedure nmCorrigeDataCaixa(var Msg: TCSCMessage); message ncnmCorrigeDataCaixa; procedure nmAjustaPontosFid(var Msg: TCSCMessage); message ncnmAjustaPontosFid; procedure nmObtemProcessos(var Msg: TCSCMessage); message ncnmObtemProcessos; procedure nmFinalizaProcesso(var Msg: TCSCMessage); message ncnmFinalizaProcesso; procedure nmSalvaProcessos(var Msg: TCSCMessage); message ncnmSalvaProcessos; procedure nmObtemSitesBloq(var Msg: TCSCMessage); message ncnmObtemSitesBloq; procedure nmPermitirDownload(var Msg: TCSCMessage); message ncnmPermitirDownload; procedure nmSalvaLic(var Msg: TCSCMessage); message ncnmSalvaLic; procedure nmObtemPatrocinios(var Msg: TCSCMessage); message ncnmObtemPatrocinios; procedure nmSalvaAppUrlLog(var Msg: TCSCMessage); message ncnmSalvaAppUrlLog; procedure nmKeepAlive(var Msg: TCSCMessage); message ncnmKeepAlive; {---- MsgCom Handlers ---------------------------------------------------} procedure tcAtualizaObj(var Msg: TMessage); message ncmc_AtualizaObj; procedure tcNovoObj(var Msg: TMessage); message ncmc_NovoObj; procedure tcDestroiObj(var Msg: TMessage); message ncmc_DestroiObj; procedure tcServidorDesativado(var Msg: TMessage); message ncmc_ServidorDesativado; procedure tcPedeTela(var Msg: TMessage); message ncmc_PedeTela; procedure tcShutdown(var Msg: TMessage); message ncmc_Shutdown; procedure tcChatEv(var Msg: TMessage); message ncmc_ChatEv; procedure tcSuporteRemEv(var Msg: TMessage); message ncmc_SuporteRemEv; procedure tcAbriuFechouCaixaEv(var Msg: TMessage); message ncmc_AbriuFechouCaixa; procedure tcSiteBloqueadoEv(var Msg: TMessage); message ncmc_SiteBloqueado; public procedure ProcessaRequestsPendentes; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Servidor: TncServidorBase read GetServidor write SetServidor; property Ativo: Boolean read FAtivo write SetAtivo; end; function CMServComWndFunc(hWindow : Hwnd; Msg : UINT; wParam : WPARAM; lParam : LPARAM) : LRESULT; stdcall export; var GlobalNotifyHandle : HWND = 0; InternalCliHandle : HWND = 0; const NCServComClassName = 'NCServComunicacao'; implementation uses uLicEXECryptor, ncLancExtra, ncDebTempo, ncSyncLic, ncsFrmPri; procedure FreeObj(var Obj); var P : TObject; begin if TObject(Obj) <> nil then begin P := TObject(Obj); TObject(Obj) := nil; P.Free; end; end; { TncServComunicacao } constructor TncServComunicacao.Create(aOwner: TComponent); begin inherited; FVersion := TLmdVersionInfo.Create(Self); FSockLic := -1; FTimerR := TTimer.Create(nil); FTimerR.OnTimer := OnTimerR; FTimerR.Interval := (4*60*1000) + Random(2*60*1000); FTimerR.Enabled := True; FTimerHora := TTimer.Create(nil); FTimerHora.OnTimer := OnTimerHora; FTimerHora.Interval := 60000; FTimerHora.Enabled := True; FAtivo := False; FCliente := TClienteNexCafe.Create(Self); FCliente.AoDespacharMC := DespachaMC; FCliente.Username := ProxyUsername; FCliente.Senha := ProxySenha; InternalCliHandle := FCliente.WndHandle; FServCom := TCSCServer.Create(nil); CriaWndHandle; FServCom.NotifyHandle := FWndHandle; FServCom.Port := 16201; FServCom.OnConnect := AoConectarCliente; FServCom.OnDisconnect := AoDesconectarCliente; GlobalNotifyHandle := FWndHandle; FServCom.Listening := False; end; destructor TncServComunicacao.Destroy; var T: TCSCTimer; begin SetTimer(T, 1000); while not HasTimerExpired(T) and (FServCom.Daemon.Socket.ActiveConnections > 0) do FServCom.WinsockBreath(0); FCliente.ProcessaMensagens; SetAtivo(False); FServCom.Free; FServCom := nil; FCliente.Ativo := False; FCliente.Free; FVersion.Free; FTimerR.Free; FTimerHora.Free; inherited; end; procedure TncServComunicacao.CriaWndHandle; var XClass : TWndClass; begin XClass.hInstance := HInstance; with XClass do begin Style := 0; lpfnWndProc := @CMServComWndFunc; cbClsExtra := 0; cbWndExtra := SizeOf(Pointer); hIcon := LoadIcon(hInstance, 'DEFICON'); hCursor := LoadCursor(0, idc_Arrow); hbrBackground := 0; lpszMenuName := nil; lpszClassName := NCServComClassName; end; WinProcs.RegisterClass(XClass); FWndHandle := CreateWindow(NCServComClassName, {window class name} '', {caption} 0, {window style} 0, {X} 0, {Y} 1, {width} 1, {height} 0, {parent} 0, {menu} HInstance, {instance} nil); {parameter} SetWindowLong(FWndHandle, 0, Longint(Self)); end; function CMServComWndFunc(hWindow : Hwnd; Msg : UINT; wParam : WPARAM; lParam : LPARAM) : LRESULT; stdcall export; var Obj : TncServComunicacao; function DefWndFunc : LongInt; begin DefWndFunc := DefWindowProc(hWindow, Msg, wParam, lParam); end; begin Result := 0; Obj := nil; if MSG<>wm_Create then begin Obj := TncServComunicacao(GetWindowLong(hWindow, 0)); if Obj=nil then begin Result := DefWndFunc; Exit; end; end; try case Msg of wm_queryendsession : Result := 1; wm_endsession : Result := 1; cscm_EventReceived : Obj.ProcessaRequestsPendentes; cscm_FileEventReceived : Obj.ProcessaRequestsPendentes; else Result := DefWndFunc; end; except end; end; procedure TncServComunicacao.ProcessaRequestsPendentes; var DataMsg : PCSCMessage; C : TncCliente; begin while true do begin if (FServCom=nil) then Exit; DataMsg := FServCom.MsgQueue.ExamineEvents; if (DataMsg = nil) then Exit; DebugMsg('TncServComunicacao.ProcessaRequestPendentes - DataMsg.dmClientSck: ' + IntToStr(Integer(DataMsg^.dmClientSck)) + ' - DataMsg.Msg: ' + IntToStr(DataMsg^.dmMsg)); FServCom.MsgQueue.RemoveEventFromQueue(DataMsg); try C := Servidor.ObtemClientePorSocket(Integer(DataMsg^.dmClientSck)); if C<>nil then begin UsernameAtual := C.Username; HandleCliAtual := C.Handle; end else begin UsernameAtual := ''; HandleCliAtual := -1; end; Dispatch(DataMsg^); except end; FServCom.MsgQueue.DisposeEvent(DataMsg); end; end; {--- Processamento de Mensagens TCP-IP ----------------------------------} procedure TncServComunicacao.nmCapturaTelaMaq(var Msg: TCSCMessage); var S : TMemoryStream; Erro : Integer; begin with Msg, TnmCapturaTela(dmData^) do begin S := TMemoryStream.Create; Erro := FCliente.Servidor.CapturaTelaMaq(nmMaq, S); try if Erro <> 0 then FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdStream, Erro) else FServCom.SendMsg(dmMsg, False, dmClientSck, S, S.Size, nmdStream, 0); finally FreeObj(S); end; end; end; procedure TncServComunicacao.nmCorrigeDataCaixa(var Msg: TCSCMessage); begin with Msg, TnmCorrigeDataCaixaReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.CorrigeDataCaixa(nmFunc, nmCaixa, nmNovaAbertura, nmNovoFechamento)); end; procedure TncServComunicacao.nmEnviaChat(var Msg: TCSCMessage); var S: TStream; SL: TStrings; De, Para: Integer; begin S := TStream(Msg.dmData); S.Position := 0; SL := TStringList.Create; try SL.LoadFromStream(S); De := StrToInt(SL.Values['de']); Para := StrToInt(SL.Values['para']); SL.Delete(0); SL.Delete(0); SL.Delete(0); SL.Delete(0); with Msg do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.EnviarMsg(De, Para, SL.Text)); finally SL.Free; end; end; procedure TncServComunicacao.nmFechaCaixa(var Msg: TCSCMessage); begin with Msg, TnmFechaCaixaReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.FechaCaixa(nmFunc, nmID)); end; procedure TncServComunicacao.nmFinalizaProcesso(var Msg: TCSCMessage); begin with Msg do begin FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, 0); DebugMsg('TncServComunicacao.nmFinalizaProcesso'); EnviaEvento(ncnmFinalizaProcessoEv, Msg.dmData, SizeOf(TnmFinalizaProcesso), nmdByteArray); end; end; procedure TncServComunicacao.nmKeepAlive(var Msg: TCSCMessage); begin FServCom.SendMsg(ncnmKeepAlive, False, Msg.dmClientSck, nil, 0, nmdByteArray, 0); end; procedure TncServComunicacao.nmSalvaTelaMaq(var Msg: TCSCMessage); var Erro: Integer; S : TMemoryStream; Maq : Byte; begin with Msg do begin S := TMemoryStream(dmData); S.Position := S.Size-1; if S.Size > 1 then S.Read(Maq, 1) else Maq := 0; S.Position := 0; S.SetSize(pred(S.Size)); Erro := Servidor.SalvaTelaMaq(Maq, S); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmLogin(var Msg: TCSCMessage); var Erro : integer; Reply : TnmLoginRpy; begin with Msg, TnmLoginReq(dmData^) do begin if nmProxyHandle = 0 then nmProxyHandle := FCliente.Handle; Erro := Servidor.Login(nmUsername, nmSenha, nmMaq, nmFuncAtual, True, 0, nmProxyHandle, Integer(dmClientSck), '', Reply.nmHandle); FServCom.SendMsg(dmMsg, False, dmClientSck, @Reply, SizeOf(Reply), nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmLogout(var Msg: TCSCMessage); begin with Msg do begin Servidor.Logout(Integer(dmData^)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, 0); end; end; procedure TncServComunicacao.nmObtemLista(var Msg: TCSCMessage); var S : TStream; Erro : Integer; begin with Msg, TnmObtemListaReq(dmData^) do begin S := TMemoryStream.Create; Erro := 0; try try case nmTipoClasse of tcMaquina : Erro := FCliente.Servidor.ObtemStreamListaObj(FCliente.Handle, tcMaquina, S); tcUsuario : FCliente.Usuarios.SalvaStream(S); tcSessao : Erro := FCliente.Servidor.ObtemStreamListaObj(FCliente.Handle, tcSessao, S); tcTipoAcesso : gTiposAcesso.SalvaStream(S); tcTarifa : gTarifas.SalvaStream(S); else Erro := ncerrTipoClasseInvalido; end; except Erro := ncerrExcecaoNaoTratada; end; if Erro <> 0 then FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdStream, Erro) else FServCom.SendMsg(dmMsg, False, dmClientSck, S, S.Size, nmdStream, 0); finally FreeObj(S); end; end; end; procedure TncServComunicacao.nmObtemPastaServ(var Msg: TCSCMessage); var S : String; Erro : Integer; Reply : TnmNomeArq; begin with Msg do begin Erro := Servidor.ObtemPastaServ(S); Reply.nmNomeArq := S; FServCom.SendMsg(dmMsg, False, dmClientSck, @Reply, SizeOf(Reply), nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmObtemPatrocinios(var Msg: TCSCMessage); var S: TStream; SL: TStrings; Erro : Integer; begin with Msg do begin S := TMemoryStream.Create; SL := TStringList.Create; try Erro := Servidor.ObtemPatrocinios(SL); SL.SaveToStream(S); FServCom.SendMsg(dmMsg, False, dmClientSck, S, S.Size, nmdStream, Erro); except end; SL.Free; S.Free; end; end; procedure TncServComunicacao.nmObtemProcessos(var Msg: TCSCMessage); begin with Msg do begin FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, 0); DebugMsg('TncServComunicacao.nmObtemProcessos'); EnviaEvento(ncnmObtemProcessosEv, Msg.dmData, SizeOf(TnmObtemProcessos), nmdByteArray); end; end; procedure TncServComunicacao.nmNovoObj(var Msg: TCSCMessage); begin nmAlteraObj(Msg); end; procedure TncServComunicacao.nmAlteraObj(var Msg: TCSCMessage); var Erro: Integer; begin with Msg, TStream(dmData) do begin Position := 0; Erro := Servidor.SalvaStreamObj((dmMsg=ncnmNovoObj), TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmRefreshSessao(var Msg: TCSCMessage); begin with Msg, TnmSessao(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.ForceRefreshSessao(nmSessao)); end; procedure TncServComunicacao.nmAlteraSessao(var Msg: TCSCMessage); var S: TncSessao; begin S := TncSessao.Create(False); with Msg do try try TStream(dmData).Position := 0; S.LeStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.AlteraSessao(S)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally S.Free; end; end; procedure TncServComunicacao.nmApagaObj(var Msg: TCSCMessage); begin with Msg, PnmObj(dmData)^ do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.ApagaObj(nmCliente, nmTipoClasse, nmChave)); end; procedure TncServComunicacao.nmArqFundoEnviado(var Msg: TCSCMessage); begin with Msg, TnmNomeArq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.ArqFundoEnviado(nmNomeArq)); end; {--- Processamento de Mensagens Thread-Com ------------------------------} procedure TncServComunicacao.tcAbriuFechouCaixaEv(var Msg: TMessage); begin DebugMsg('TncServComunicacao.tcAbriuFechouCaixaEv'); EnviaEvento(ncnmAbriuFechouCaixaEv, nil, 0, nmdByteArray); end; procedure TncServComunicacao.tcAtualizaObj(var Msg: TMessage); var S : TStream; begin S := TStream(Msg.lParam); if S <> nil then begin S.Position := 0; DebugMsg('TncServComunicacao.tcAtualizaObj'); EnviaEvento(ncnmAtualizaObjEv, S, S.Size, nmdStream); end; end; procedure TncServComunicacao.tcChatEv(var Msg: TMessage); var S: TStream; begin S := TStream(Msg.lParam); if S <> nil then begin S.Position := 0; DebugMsg('TncServComunicacao.tcChatEv'); EnviaEvento(ncnmChatEv, S, S.Size, nmdStream); end; end; procedure TncServComunicacao.tcSuporteRemEv(var Msg: TMessage); var Evento : TnmSuporteRem; begin with Msg, Evento do begin nmMaq := PmsgSuporteRemEv(LParam)^.msgMaq; nmTec := PmsgSuporteRemEv(LParam)^.msgTec; end; DebugMsg('TncServComunicacao.tcSuporteRemEv'); EnviaEvento(ncnmSuporteRemEv, @Evento, SizeOf(Evento), nmdByteArray); end; procedure TncServComunicacao.tcShutdown(var Msg: TMessage); var Evento : TnmShutdown; begin with Msg, Evento do begin nmMaq := PmsgShutdown(LParam)^.msgMaq; nmOper := PmsgShutdown(LParam)^.msgOper; end; DebugMsg('TncServComunicacao.tcShutdown'); EnviaEvento(ncnmShutdownEv, @Evento, SizeOf(Evento), nmdByteArray); end; procedure TncServComunicacao.tcSiteBloqueadoEv(var Msg: TMessage); var S : TStream; begin S := TStream(Msg.lParam); if S <> nil then begin S.Position := 0; DebugMsg('TncServComunicacao.tcSiteBloqueado'); EnviaEvento(ncnmSiteBloqueadoEv, S, S.Size, nmdStream); end; end; procedure TncServComunicacao.tcPedeTela(var Msg: TMessage); var Evento: TnmCapturaTela; begin Evento.nmMaq := Msg.WParam; DebugMsg('TncServComunicacao.tcPedeTela'); EnviaEvento(ncnmPedeTelaEv, @Evento, SizeOf(Evento), nmdByteArray); end; procedure TncServComunicacao.tcDestroiObj(var Msg: TMessage); var Evento: TnmObj; begin with Msg do begin Evento.nmTipoClasse := PmsgDestroiObj(LParam)^.msgTipoClasse; Evento.nmChave := PmsgDestroiObj(lParam)^.msgChave; DebugMsg('TncServComunicacao.tcDestroiObj - TipoClasse = ' + IntToStr(Evento.nmTipoClasse) + ' - Chave = ' + Evento.nmChave); EnviaEvento(ncnmDestroiObjEv, @Evento, SizeOf(Evento), nmdByteArray); end; end; procedure TncServComunicacao.tcNovoObj(var Msg: TMessage); var S : TStream; begin S := TStream(Msg.lParam); if S <> nil then begin S.Position := 0; DebugMsg('TncServComunicacao,.tcNovoObj'); EnviaEvento(ncnmNovoObjEv, S, S.Size, nmdStream); end; end; procedure TncServComunicacao.EnviaEvento(MsgID: Integer; P: Pointer; Tam: Integer; Tipo: Byte); var I : Integer; L : TList; begin L := TList.Create; try with FServCom, Daemon.Socket do begin Lock; try for I := 0 to pred(ActiveConnections) do if Integer(Connections[I].Data) <> -1 then L.Add(Connections[I]) else DebugMsg('Connection.Data = -1'); finally Unlock; end; for I := 0 to L.Count-1 do try DebugMsg('EnviaEvento - ' + TCustomWinSocket(L[I]).RemoteAddress); SendMsg(MsgID, True, TCustomWinSocket(L[I]), P, Tam, Tipo, 0); except on E: Exception do DebugMsg('EnviaEvento - ' + E.Message); end; end; finally L.Free; end; end; procedure TncServComunicacao.SetServidor(Valor: TncServidorBase); begin if Valor = Servidor then Exit; FServCom.Listening := False; FCliente.Servidor := Valor; end; procedure TncServComunicacao.SetAtivo(Valor: Boolean); begin if (Valor = FAtivo) or (Valor and (Servidor=nil)) then Exit; FCliente.Ativo := Valor; FServCom.Listening := Valor; FAtivo := Valor; end; function TncServComunicacao.GetServidor: TncServidorBase; begin Result := FCliente.Servidor; end; procedure TncServComunicacao.DespachaMC(var Msg: TMessage); begin Dispatch(Msg); end; procedure TncServComunicacao.tcServidorDesativado(var Msg: TMessage); begin FServCom.Listening := False; FAtivo := False; end; procedure TncServComunicacao.AoConectarCliente(Sender: TObject; Socket: TCustomWinSocket); begin end; procedure TncServComunicacao.AoDesconectarCliente(Sender: TObject; Socket: TCustomWinSocket); begin if Ativo then begin Socket.Data := Pointer(-1); Servidor.LogoutSocket(Integer(Socket)); end; end; procedure TncServComunicacao.nmLoginMaq(var Msg: TCSCMessage); var S: TncSessao; begin S := TncSessao.Create(False); with Msg do try try TStream(dmData).Position := 0; S.LeStream(TStream(dmData)); // S.Obs := IntToStr(TStream(dmData).Size); // ShowMessage(S.Obs+'--'+S.NomeCliente+'--Maq='+IntToStr(S.Maq)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.LoginMaq(S)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally S.Free; end; end; procedure TncServComunicacao.nmLogoutMaq(var Msg: TCSCMessage); begin with Msg, TnmLogoutMaqReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.LogoutMaq(nmMaq)); end; procedure TncServComunicacao.nmTransferirMaq(var Msg: TCSCMessage); begin with Msg, TnmTransferirMaqReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.TransferirMaq(nmOrigem, nmDestino)); end; procedure TncServComunicacao.OnTimerHora(Sender: TObject); var Evento : TnmHorarioEv; begin if not Ativo then Exit; with Evento do if gConfig.SincronizarHorarios then begin nmHora := Now; DebugMsg('TncServComunicacao.OnTimerHora'); EnviaEvento(ncnmHorarioEv, @Evento, SizeOf(Evento), nmdByteArray); end; end; procedure TncServComunicacao.OnTimerR(Sender: TObject); var M: Integer; begin try FTimerR.Enabled := False; FTimerR.Interval := (4*60*1000) + Random(3*60*1000); FTimerR.Enabled := True; if not Ativo then Exit; FSockLic := Servidor.GetProxSocketLic(FSockLic, M); if FSockLic<>-1 then FServCom.SendMsg(ncnmChecaLicEv, True, TCustomWinSocket(FSockLic), nil, 0, nmdByteArray, 0); except end; end; procedure TncServComunicacao.nmPararTempoMaq(var Msg: TCSCMessage); begin with Msg, TnmPararTempoMaqReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.PararTempoMaq(nmMaq, nmParar)); end; procedure TncServComunicacao.nmPermitirDownload(var Msg: TCSCMessage); begin with Msg, TnmPermitirDownloadReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.PermitirDownload(nmSessao, nmPerm)); end; procedure TncServComunicacao.nmLimpaFundo(var Msg: TCSCMessage); begin with Msg, TnmLimpaFundoReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.LimpaFundo(nmDesktop)); end; procedure TncServComunicacao.nmPreLogoutMaq(var Msg: TCSCMessage); begin with Msg, TnmLogoutMaqReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.PreLogoutMaq(nmMaq)); end; procedure TncServComunicacao.nmCancelaTran(var Msg: TCSCMessage); begin with Msg, TnmCancelaTranReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.CancelaTran(nmTran, nmFunc)); end; procedure TncServComunicacao.nmCancLogoutMaq(var Msg: TCSCMessage); begin with Msg, TnmLogoutMaqReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.CancLogoutMaq(nmMaq)); end; procedure TncServComunicacao.nmObtemSenhaCli(var Msg: TCSCMessage); var Erro: Integer; Reply: TnmSenhaCli; S: String; begin with Msg, TnmSenhaCli(dmData^) do begin S := ''; Erro := Servidor.ObtemSenhaCli(nmCodigo, S); Reply.nmSenha := S; FServCom.SendMsg(dmMsg, False, dmClientSck, @Reply, SizeOf(Reply), nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmObtemSitesBloq(var Msg: TCSCMessage); var Erro: Integer; Str: String; S: TStream; begin with Msg do begin Erro := Servidor.ObtemSitesBloqueados(Str); if Erro=0 then begin S := TMemoryStream.Create; try if Str>'' then S.WriteBuffer(Str[1], Length(Str)); S.Position := 0; FServCom.SendMsg(dmMsg, False, dmClientSck, S, S.Size, nmdStream, Erro); finally S.Free; end; end else FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdStream, Erro); end; end; procedure TncServComunicacao.nmObtemStreamConfig(var Msg: TCSCMessage); var S: TStream; Erro: Integer; begin S := TMemoryStream.Create; with Msg do try Erro := Servidor.ObtemStreamConfig(S); if Erro=0 then FServCom.SendMsg(dmMsg, False, dmClientSck, Pointer(S), S.Size, nmdStream, 0) else FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, 0, Erro); finally S.Free; end; end; procedure TncServComunicacao.nmRefreshEspera(var Msg: TCSCMessage); begin with Msg do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.RefreshEspera); end; procedure TncServComunicacao.nmRefreshPrecos(var Msg: TCSCMessage); begin with Msg do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.RefreshPrecos); end; procedure TncServComunicacao.nmShutdown(var Msg: TCSCMessage); begin with Msg, TnmShutdown(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.ShutdownMaq(nmMaq, nmOper)); end; procedure TncServComunicacao.nmSuporteRem(var Msg: TCSCMessage); begin with Msg, TnmSuporteRem(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SuporteRem(nmMaq, nmTec)); end; procedure TncServComunicacao.nmBaixaAtualizacao(var Msg: TCSCMessage); var Erro : integer; Versao : String; NArq : String; begin with Msg, TnmBaixaAtualizacao(dmData^) do begin Erro := 0; NArq := ExtractFilePath(ParamStr(0)) + 'Atualiza\nexguard.exe'; try FVersion.RetrieveFilename := ''; FVersion.RetrieveFilename := NArq; Versao := FVersion.FileVersion; if Versao>'' then Versao := FormataNumVersao(Versao); if (Versao=nmVersao) or (Versao='') {Versao <= nmVersao} then Erro := ncerrSemNovaVersao; except Erro := ncerrSemNovaVersao; end; if Erro = 0 then Erro := FServCom.MsgQueue.TransmitFile(dmClientSck, NArq, nmNomeArq, nmPrograma, Erro, 0, dmMsg); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmSalvaAppUrlLog(var Msg: TCSCMessage); begin with Msg do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaLogAppUrl(TStream(dmData))); end; procedure TncServComunicacao.nmSalvaCredTempo(var Msg: TCSCMessage); var CT: TncCredTempo; begin CT := TncCredTempo.Create; with Msg do try try TStream(dmData).Position := 0; CT.LoadFromStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaCredTempo(CT)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally CT.Free; end; end; procedure TncServComunicacao.nmSalvaMovEst(var Msg: TCSCMessage); var ME: TncMovEst; begin ME := TncMovEst.Create; with Msg do try try TStream(dmData).Position := 0; ME.LeStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaMovEst(ME)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally ME.Free; end; end; procedure TncServComunicacao.nmSalvaProcessos(var Msg: TCSCMessage); var SL : TStrings; aIDCliente, aReq : Integer; begin SL := TStringList.Create; with Msg do try try TStream(dmData).Position := 0; SL.LoadFromStream(TStream(dmData)); aIDCliente := StrToIntDef(SL[0], 0); aReq := StrToIntDef(SL[1], 1); SL.Delete(0);SL.Delete(0); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaProcessos(aIDCliente, aReq, SL)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally SL.Free; end; end; procedure TncServComunicacao.nmSalvaDebito(var Msg: TCSCMessage); var D: TncDebito; begin D := TncDebito.Create; with Msg do try try TStream(dmData).Position := 0; D.LeStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaDebito(D)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally D.Free; end; end; procedure TncServComunicacao.nmSalvaDebTempo(var Msg: TCSCMessage); var T: TncDebTempo; begin T := TncDebTempo.Create; with Msg do try try TStream(dmData).Position := 0; T.LeStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaDebTempo(T)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally T.Free; end; end; procedure TncServComunicacao.nmSalvaImpressao(var Msg: TCSCMessage); var Imp: TncImpressao; begin Imp := TncImpressao.Create; with Msg do try try TStream(dmData).Position := 0; Imp.LoadFromStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaImpressao(Imp)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally Imp.Free; end; end; procedure TncServComunicacao.nmSalvaLancExtra(var Msg: TCSCMessage); var L: TncLancExtra; begin L := TncLancExtra.Create; with Msg do try try TStream(dmData).Position := 0; L.LeStream(TStream(dmData)); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.SalvaLancExtra(L)); except FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, ncerrExcecaoNaoTratada); end; finally L.Free; end; end; procedure TncServComunicacao.nmSalvaLic(var Msg: TCSCMessage); var SL: TStrings; begin SL := TStringList.Create; try with Msg do begin try TStream(dmData).Position := 0; SL.LoadFromStream(TStream(dmData)); Servidor.SalvaLic(SL.Text); except end; FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, 0); end; except end; SL.Free; end; procedure TncServComunicacao.nmSalvaSenhaCli(var Msg: TCSCMessage); var Erro: Integer; begin with Msg, TnmSenhaCli(dmData^) do begin Erro := Servidor.SalvaSenhaCli(nmCodigo, nmSenha); FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Erro); end; end; procedure TncServComunicacao.nmModoManutencao(var Msg: TCSCMessage); begin with Msg, TnmModoManutencaoReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.ModoManutencao(nmMaq, nmUsername, nmSenha, nmEntrar)); end; procedure TncServComunicacao.nmAbreCaixa(var Msg: TCSCMessage); var Rpy : TnmAbreCaixaRpy; begin with Msg, TnmAbreCaixaReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, @Rpy, SizeOf(Rpy), nmdByteArray, Servidor.AbreCaixa(nmFunc, Rpy.nmID)); end; procedure TncServComunicacao.nmAdicionaPassaporte(var Msg: TCSCMessage); begin with Msg, TnmAdicionaPassaporteReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.AdicionaPassaporte(nmMaq, nmSenha)); end; procedure TncServComunicacao.nmAjustaPontosFid(var Msg: TCSCMessage); begin with Msg, TnmAjustaPontosFid(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.AjustaPontosFid(nmFunc, nmCliente, nmFator, nmPontos, nmObs)); end; procedure TncServComunicacao.nmPaginasImpressas(var Msg: TCSCMessage); begin with Msg, TnmPaginasImpressasReq(dmData^) do FServCom.SendMsg(dmMsg, False, dmClientSck, nil, 0, nmdByteArray, Servidor.RegistraPaginasImpressas(nmMaq, nmPaginas, nmImp, nmDoc)); end; procedure TncServComunicacao.nmAvisos(var Msg: TCSCMessage); var S: TStream; Erro: Integer; begin S := TMemoryStream.Create; try with Msg do begin Erro := Servidor.ObtemStreamAvisos(S); FServCom.SendMsg(dmMsg, False, dmClientSck, S, S.Size, nmdStream, Erro); end; finally S.Free; end; end; end.
{ InternetExpress sample WebModule This site provides examples and information that help browsers understand the makeup of InternetExpress. Each page component is a TINetXCenterProducer component. This producer component was developed specifically for this application. The InetXCenterComponent.bpl package must be installed to display the web module designer. Information about InternetExpress components is stored in a local ClientDataSet generated file. See ComponentsInfoDS.FileName. This file is edited with the ComponentsInfoEditor sample application. You may see warning messages when viewing a Producer component in the Web Page property editor. For example, 'XMLBroker: XMLBrokerAllCustomers is not connected'. This indicates that the XMLBrokerAllCustomers.Connected property is False. This is not an indication of a problem. In some cases the design time appearance of a page will be different when the component is connnected. For example, if the page contains a TFieldSelectList component that is populated using data retrieved through the connection, the list will not be populated unless connected = True. } unit InextXCenterModule; interface uses Windows, Messages, SysUtils, Classes, HTTPApp, MidItems, Db, DBClient, MConnect, XMLBrokr, CompProd, PagItems, MidProd, LinkFlds, SortFlds, RowSetStatus, ShowXML, FieldAttr, ImgButtons, INetXCenterProd, CustLayout, QueryComps, WebCombo, ReconcileProd, ReadFileClientDataSet, WebComp, HTTPProd; type TWebModule2 = class(TWebModule) Home: TInetXCenterProducer; XMLBrokerAllCustomers: TXMLBroker; DCOMConnection1: TDCOMConnection; CustomComponentGrid: TInetXCenterProducer; DataForm1: TDataForm; DataNavigator1: TDataNavigator; DataGrid1: TDataGrid; StatusColumn1: TStatusColumn; LinkColumn1: TLinkColumn; FirstButton1: TFirstButton; PriorPageButton1: TPriorPageButton; PriorButton1: TPriorButton; NextButton1: TNextButton; NextPageButton1: TNextPageButton; LastButton1: TLastButton; UndoButton1: TUndoButton; PostButton1: TPostButton; ApplyUpdatesButton1: TApplyUpdatesButton; CustOrders: TInetXCenterProducer; DataForm2: TDataForm; FieldGroup1: TFieldGroup; XMLBrokerCustOrders: TXMLBroker; DataNavigator2: TDataNavigator; OrderNo: TFieldText; CustNo2: TFieldText; ItemsTotal: TFieldText; AmountPaid: TFieldText; FieldStatus1: TFieldStatus; SortCustNo: TSortTextColumn; SortCompany: TSortTextColumn; SortLastInvoiceDate: TSortTextColumn; FieldGroup2: TFieldGroup; RowSetStatus1: TRowSetStatus; FieldGroup3: TFieldGroup; RowSetStatus2: TRowSetStatus; LayoutGroup2: TLayoutGroup; FirstButton2: TFirstButton; PriorPageButton2: TPriorPageButton; PriorButton2: TPriorButton; NextButton2: TNextButton; NextPageButton2: TNextPageButton; LastButton2: TLastButton; InsertButton1: TInsertButton; DeleteButton1: TDeleteButton; UndoButton2: TUndoButton; PostButton2: TPostButton; ApplyUpdatesButton2: TApplyUpdatesButton; ShowXMLButton1: TShowXMLButton; LayoutGroup4: TLayoutGroup; LayoutGroup1: TLayoutGroup; ShowDeltaButton1: TShowDeltaButton; CountriesRadioGroup: TInetXCenterProducer; DataForm3: TDataForm; FieldGroup4: TFieldGroup; DataNavigator3: TDataNavigator; XMLBrokerAllCountries: TXMLBroker; Name: TFieldText; Capital: TFieldText; Area: TFieldText; Population: TFieldText; FieldStatus2: TFieldStatus; ContinentRadioGroup: TFieldRadioGroup; CountriesSelectOptions: TInetXCenterProducer; DataForm4: TDataForm; FieldGroup5: TFieldGroup; FieldText1: TFieldText; FieldText2: TFieldText; FieldText3: TFieldText; FieldText4: TFieldText; FieldStatus3: TFieldStatus; DataNavigator4: TDataNavigator; FieldSelectOptions: TFieldSelectOptions; FieldAttr: TInetXCenterProducer; DataForm5: TDataForm; DataNavigator5: TDataNavigator; DataGrid2: TDataGrid; SubmitFieldAttr: TQueryForm; FirstButton3: TFirstButton; PriorPageButton3: TPriorPageButton; PriorButton3: TPriorButton; NextButton3: TNextButton; NextPageButton3: TNextPageButton; LastButton3: TLastButton; QueryFieldGroup3: TQueryFieldGroup; QueryMinValue: TQueryText; QueryMaxValue: TQueryText; QueryDecimals: TQueryText; QueryFixedDecimals: TQueryText; PostButton3: TPostButton; UndoButton3: TUndoButton; QueryButtons1: TQueryButtons; QueryCurrencySymbol: TQueryText; ImgButtons: TInetXCenterProducer; DataForm6: TDataForm; FieldGroup6: TFieldGroup; Name3: TFieldText; Capital2: TFieldText; Continent: TFieldText; Area2: TFieldText; Population2: TFieldText; FieldStatus4: TFieldStatus; ImgDataNavigator1: TImgDataNavigator; ImgFirstButton1: TImgFirstButton; ImgPriorPageButton1: TImgPriorPageButton; ImgPriorButton1: TImgPriorButton; ImgNextButton1: TImgNextButton; ImgNextPageButton1: TImgNextPageButton; ImgLastButton1: TImgLastButton; ImgInsertButton1: TImgInsertButton; ImgDeleteButton1: TImgDeleteButton; ImgUndoButton1: TImgUndoButton; ImgPostButton1: TImgPostButton; ImgApplyUpdatesButton1: TImgApplyUpdatesButton; ComponentsFilter: TInetXCenterProducer; Examples: TInetXCenterProducer; LayoutGroup3: TLayoutGroup; TitleLayoutGroup1: TTitleLayoutGroup; SelectOptionsPage: TInetXCenterProducer; SelectOptionsQueryForm: TQueryForm; QueryFieldGroup2: TQueryFieldGroup; QuerySelectOptions: TQuerySelectOptions; QueryButtons2: TQueryButtons; SearchSelectOptionsPage: TInetXCenterProducer; SearchSelectOptionsQueryForm: TQueryForm; QueryFieldGroup1: TQueryFieldGroup; QuerySearchSelectOptions: TQuerySearchSelectOptions; QueryButtons3: TQueryButtons; PromptButtonPage: TInetXCenterProducer; QueryForm3: TQueryForm; QueryButtons4: TQueryButtons; PromptQueryButton1: TPromptQueryButton; QueryPasswordPage: TInetXCenterProducer; QueryForm1: TQueryForm; QueryFieldGroup4: TQueryFieldGroup; QueryPassword: TQueryPassword; QueryButtons5: TQueryButtons; DumpRequest: TInetXCenterProducer; CustNamesDS: TClientDataSet; QueryForm2: TQueryForm; QueryRadioGroupPackageFilter: TQueryRadioGroup; QueryRadioGroupUsageFilter: TQueryRadioGroup; SubmitQueryButton1: TSubmitQueryButton; QueryFieldGroup8: TQueryFieldGroup; QueryFieldGroup9: TQueryFieldGroup; QueryButtons9: TQueryButtons; LayoutGroup5: TLayoutGroup; LayoutGroup6: TLayoutGroup; ComponentsList: TInetXCenterProducer; CloseFilter: TSubmitValueButton; CustOrdersQuery: TInetXCenterProducer; QueryForm4: TQueryForm; QueryFieldGroup5: TQueryFieldGroup; QuerySelectOptions1: TQuerySelectOptions; QueryButtons6: TQueryButtons; TextColumnAttr: TTextColumnAttr; AboutXML: TInetXCenterProducer; AboutJavaScript: TInetXCenterProducer; ReconcileError: TInetXCenterProducer; QueryForm5: TQueryForm; QueryFieldGroup6: TQueryFieldGroup; QueryTextArea: TQueryTextArea; QueryButtons7: TQueryButtons; SubmitQueryButton2: TSubmitQueryButton; QueryHiddenText: TQueryHiddenText; ReconcilePage: TReconcilePageProducer; CustOrdersMasterDetail: TInetXCenterProducer; DataForm7: TDataForm; FieldGroup7: TFieldGroup; DataNavigator6: TDataNavigator; DataGrid3: TDataGrid; DataNavigator7: TDataNavigator; ApplyUpdatesButton3: TApplyUpdatesButton; ShowXMLButton3: TShowXMLButton; ShowDeltaButton3: TShowDeltaButton; LayoutGroup9: TLayoutGroup; DataNavigator8: TDataNavigator; LayoutGroup12: TLayoutGroup; LayoutGroup7: TLayoutGroup; LayoutGroup11: TLayoutGroup; DataNavigator10: TDataNavigator; DeleteButton4: TDeleteButton; PostButton6: TPostButton; FieldGroup9: TFieldGroup; RowSetStatus4: TRowSetStatus; LayoutGroup15: TLayoutGroup; CustNo: TFieldText; Company: TFieldText; LastInvoiceDate: TFieldText; XMLAllCustOrders: TXMLBroker; OrderNo2: TTextColumn; SaleDate: TTextColumn; ShipDate: TTextColumn; ItemsTotal2: TTextColumn; AmountPaid2: TTextColumn; StatusColumn2: TStatusColumn; Addr1: TFieldText; Addr2: TFieldText; City: TFieldText; State: TFieldText; Zip: TFieldText; Country: TFieldText; Phone: TFieldText; FAX: TFieldText; Contact: TFieldText; LayoutGroup16: TLayoutGroup; LayoutGroup17: TLayoutGroup; LayoutGroup18: TLayoutGroup; LayoutGroup19: TLayoutGroup; FirstButton4: TFirstButton; PriorButton4: TPriorButton; NextButton4: TNextButton; LastButton4: TLastButton; UndoButton4: TUndoButton; PostButton4: TPostButton; PriorButton5: TPriorButton; NextButton5: TNextButton; FieldGroup10: TFieldGroup; RowSetStatus3: TRowSetStatus; FieldStatus5: TFieldStatus; ShowXMLButton2: TShowXMLButton; ShowDeltaButton2: TShowDeltaButton; AboutComponents: TInetXCenterProducer; CustNo3: TFieldText; RadioGroupPage: TInetXCenterProducer; QueryFormRadioGroup: TQueryForm; QueryFieldGroup7: TQueryFieldGroup; QueryButtons8: TQueryButtons; QueryRadioGroup: TQueryRadioGroup; ComponentsInfoDS: TReadFileClientDataSet; procedure XMLBrokerCustOrdersRequestRecords(Sender: TObject; Request: TWebRequest; out RecCount: Integer; var OwnerData: OleVariant; var Records: String); procedure FieldAttrBeforeGetContent(Sender: TObject); procedure SearchSelectOptionsPageBeforeGetContent(Sender: TObject); procedure SelectOptionsPageBeforeGetContent(Sender: TObject); procedure WebModule2Create(Sender: TObject); procedure ComponentsFilterBeforeGetContent(Sender: TObject); procedure WebModuleBeforeDispatch(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule2WebActionItem16Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure RadioGroupPageBeforeGetContent(Sender: TObject); private function CloseButton(Button: TSubmitValueButton; Producer: TInetXCenterProducer): Boolean; { Private declarations } public { Public declarations } ComponentsInfoIntf: IComponentsInfo; end; var WebModule2: TWebModule2; implementation uses WebReq; {$R *.dfm} procedure TWebModule2.XMLBrokerCustOrdersRequestRecords(Sender: TObject; Request: TWebRequest; out RecCount: Integer; var OwnerData: OleVariant; var Records: String); begin // Assign Query to params if XMLBrokerCustOrders.Params.Count = 0 then XMLBrokerCustOrders.FetchParams; XMLBrokerCustOrders.Params.AssignStrings(Request.ContentFields); XMLBrokerCustOrders.Params.AssignStrings(Request.QueryFields); end; procedure TWebModule2.FieldAttrBeforeGetContent(Sender: TObject); function IntValue(Value: string): Integer; begin try Result := StrToInt(Value); except Result := -1; end; end; function BoolValue(Value: string): Boolean; begin try Result := IntValue(Value) > 0; except Result := False; end; end; begin TextColumnAttr.MinValue := ''; TextColumnAttr.MaxValue := ''; TextColumnAttr.CurrencySymbol := ''; TextColumnAttr.Decimals := -1; TextColumnAttr.FixedDecimals := -1; SubmitFieldAttr.AssignStrings(Request.QueryFields); TextColumnAttr.MinValue := QueryMinValue.Text; TextColumnAttr.MaxValue := QueryMaxValue.Text; TextColumnAttr.CurrencySymbol := QueryCurrencySymbol.Text; TextColumnAttr.Decimals := IntValue(QueryDecimals.Text); TextColumnAttr.FixedDecimals := IntValue(QueryFixedDecimals.Text); end; procedure TWebModule2.SelectOptionsPageBeforeGetContent(Sender: TObject); begin // Initialize the values of all components on a query form from the URL SelectOptionsQueryForm.AssignStrings(Request.QueryFields); end; procedure TWebModule2.SearchSelectOptionsPageBeforeGetContent( Sender: TObject); begin // Initialize the values of all components on a query form from the URL SearchSelectOptionsQueryForm.AssignStrings(Request.QueryFields); end; procedure TWebModule2.WebModule2Create(Sender: TObject); begin ComponentsInfoIntf := TComponentsInfo.Create(ComponentsInfoDS); end; function TWebModule2.CloseButton(Button: TSubmitValueButton; Producer: TInetXCenterProducer): Boolean; begin Result := False; if Request.QueryFields.Values[Button.ValueName] <> '' then begin Response.SendRedirect(Producer.HRef); // Response.Content := Producer.HRef; // Response.SendResponse; Result := True; end; end; procedure TWebModule2.ComponentsFilterBeforeGetContent(Sender: TObject); var PackageFilter: string; UsageFilter: string; I: Integer; begin //if CloseButton(CloseFilter, ComponentsList) then Exit; UsageFilter := Request.QueryFields.Values['Usage']; PackageFilter := Request.QueryFields.Values['Package']; if (UsageFilter <> '') and (PackageFilter = '') then PackageFilter := QueryRadioGroupPackageFilter.Values[0] else if (PackageFilter <> '') and (UsageFilter = '') then UsageFilter := QueryRadioGroupUsageFilter.Values[0]; with QueryRadioGroupUsageFilter do begin I := Values.IndexOf(UsageFilter); if I <> -1 then Text := Items[I] else Text := ''; end; with QueryRadioGroupPackageFilter do begin I := Values.IndexOf(PackageFilter); if I <> -1 then Text := Items[I] else Text := ''; end; ComponentsInfoIntf.SetFilter(PackageFilter, UsageFilter, 'All'); end; procedure TWebModule2.WebModuleBeforeDispatch(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin ComponentsInfoIntf.ClearFilter; if WebRequestHandler.ClassNameIs('TCOMWebRequestHandler') then begin DCOMConnection1.Connected := False; XMLBrokerAllCountries.Connected := False; end; end; procedure TWebModule2.WebModule2WebActionItem16Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin if CloseButton(CloseFilter, ComponentsList) then Exit; Response.Content := ComponentsFilter.Content; end; procedure TWebModule2.RadioGroupPageBeforeGetContent(Sender: TObject); begin // Initialize the values of all components on a query form from the URL // To test try a this URL: // .../inetxcentercgi.exe/RadioGroupPage?Value=Two QueryFormRadioGroup.AssignStrings(Request.QueryFields); end; initialization WebRequestHandler.WebModuleClass := TWebModule2; end.
unit HGM.GraphQL.Types; interface uses System.StrUtils, System.SysUtils, System.Generics.Collections; type TGraphArgList = class; TGraphArgString = class; TGraphArgInteger = class; TGraphArgBoolean = class; TGraphArgFloat = class; TGraphArgVar = class; TGraphArgValue = class abstract public function ToString: string; reintroduce; virtual; abstract; end; TGraphArgItem<T> = class abstract(TGraphArgValue) private FValue: T; public constructor Create(const AValue: T); reintroduce; end; TGraphArg = class private FName: string; FValue: TGraphArgValue; procedure SetValue(const Value: TGraphArgValue); procedure SetName(const Value: string); public class function Create(const Name: string; const Value: string; IsVar: Boolean = False): TGraphArg; overload; class function Create(const Name: string; const Value: Integer): TGraphArg; overload; class function Create(const Name: string; const Value: Extended): TGraphArg; overload; class function Create(const Name: string; const Value: Boolean): TGraphArg; overload; class function Create(const Name: string; const Value: TGraphArgValue): TGraphArg; overload; class function Create(const Name: string; const Value: TArray<Integer>): TGraphArg; overload; public property Name: string read FName write SetName; property Value: TGraphArgValue read FValue write SetValue; function ToString: string; reintroduce; virtual; constructor Create(const AName: string = ''); reintroduce; overload; destructor Destroy; override; end; TGraphArgObject = class(TGraphArgValue) private FItems: TObjectList<TGraphArg>; procedure SetItems(const Value: TObjectList<TGraphArg>); public function AddPair(const Name: string; const Value: string; AsVar: Boolean = False): TGraphArgObject; overload; function AddPair(const Name: string; const Value: Integer): TGraphArgObject; overload; function AddPair(const Name: string; const Value: Extended): TGraphArgObject; overload; function AddPair(const Name: string; const Value: Boolean): TGraphArgObject; overload; function AddPair(const Name: string; const Value: TGraphArgValue): TGraphArgObject; overload; function AddPair(const Name: string; const Value: TArray<Integer>): TGraphArgObject; overload; public function ToString: string; override; property Items: TObjectList<TGraphArg> read FItems write SetItems; constructor Create; overload; constructor Create(Values: array of TGraphArg); overload; destructor Destroy; override; end; TGraphArgList = class(TObjectList<TGraphArg>) public function AddPair(const Name: string; const Value: string; AsVar: Boolean = False): TGraphArgList; overload; function AddPair(const Name: string; const Value: Integer): TGraphArgList; overload; function AddPair(const Name: string; const Value: Extended): TGraphArgList; overload; function AddPair(const Name: string; const Value: Boolean): TGraphArgList; overload; function AddPair(const Name: string; const Value: TGraphArgValue): TGraphArgList; overload; function AddPair(const Name: string; const Value: TArray<Integer>): TGraphArgList; overload; public constructor Create; reintroduce; function ToString: string; reintroduce; virtual; end; TGraphArgString = class(TGraphArgItem<string>) public function ToString: string; override; end; TGraphArgInteger = class(TGraphArgItem<Integer>) public function ToString: string; override; end; TGraphArgIntegerArray = class(TGraphArgItem<TArray<Integer>>) public function ToString: string; override; end; TGraphArgBoolean = class(TGraphArgItem<Boolean>) public function ToString: string; override; end; TGraphArgFloat = class(TGraphArgItem<Extended>) public function ToString: string; override; end; TGraphArgVar = class(TGraphArgItem<string>) public function ToString: string; override; end; implementation { TGraphArg } class function TGraphArg.Create(const Name, Value: string; IsVar: Boolean): TGraphArg; begin Result := TGraphArg.Create; if IsVar then Result.Value := TGraphArgVar.Create(Value) else Result.Value := TGraphArgString.Create(Value); Result.Name := Name; end; class function TGraphArg.Create(const Name: string; const Value: Integer): TGraphArg; begin Result := TGraphArg.Create; Result.Value := TGraphArgInteger.Create(Value); Result.Name := Name; end; class function TGraphArg.Create(const Name: string; const Value: Extended): TGraphArg; begin Result := TGraphArg.Create; Result.Value := TGraphArgFloat.Create(Value); Result.Name := Name; end; class function TGraphArg.Create(const Name: string; const Value: Boolean): TGraphArg; begin Result := TGraphArg.Create; Result.Value := TGraphArgBoolean.Create(Value); Result.Name := Name; end; class function TGraphArg.Create(const Name: string; const Value: TGraphArgValue): TGraphArg; begin Result := TGraphArg.Create; Result.Value := Value; Result.Name := Name; end; class function TGraphArg.Create(const Name: string; const Value: TArray<Integer>): TGraphArg; begin Result := TGraphArg.Create; Result.Value := TGraphArgIntegerArray.Create(Value); Result.Name := Name; end; destructor TGraphArg.Destroy; begin if Assigned(FValue) then begin FValue.Free; FValue := nil; end; inherited; end; procedure TGraphArg.SetName(const Value: string); begin FName := Value; end; procedure TGraphArg.SetValue(const Value: TGraphArgValue); begin FValue := Value; end; function TGraphArg.ToString: string; begin Result := Name + ': ' + FValue.ToString; end; { TGraphArgs } function TGraphArgObject.AddPair(const Name, Value: string; AsVar: Boolean): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value, AsVar)); Result := Self; end; function TGraphArgObject.AddPair(const Name: string; const Value: Integer): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgObject.AddPair(const Name: string; const Value: Extended): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgObject.AddPair(const Name: string; const Value: Boolean): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgObject.AddPair(const Name: string; const Value: TGraphArgValue): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgObject.AddPair(const Name: string; const Value: TArray<Integer>): TGraphArgObject; begin FItems.Add(TGraphArg.Create(Name, Value)); Result := Self; end; constructor TGraphArgObject.Create; begin inherited Create; FItems := TObjectList<TGraphArg>.Create(True); end; constructor TGraphArgObject.Create(Values: array of TGraphArg); begin Create; FItems.AddRange(Values); end; destructor TGraphArgObject.Destroy; begin FItems.Free; inherited; end; procedure TGraphArgObject.SetItems(const Value: TObjectList<TGraphArg>); begin FItems := Value; end; function TGraphArgObject.ToString: string; var i: Integer; begin for i := 0 to Pred(FItems.Count) do Result := Result + FItems[i].ToString + ', '; Result := '{' + Result.TrimRight([',', ' ']) + '}'; end; constructor TGraphArg.Create(const AName: string); begin FName := AName; end; { TGraphArgString } function TGraphArgString.ToString: string; begin Result := '"' + FValue + '"'; end; { TGraphArgList } function TGraphArgList.AddPair(const Name, Value: string; AsVar: Boolean): TGraphArgList; begin Add(TGraphArg.Create(Name, Value, AsVar)); Result := Self; end; function TGraphArgList.AddPair(const Name: string; const Value: Integer): TGraphArgList; begin Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgList.AddPair(const Name: string; const Value: Extended): TGraphArgList; begin Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgList.AddPair(const Name: string; const Value: Boolean): TGraphArgList; begin Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgList.AddPair(const Name: string; const Value: TGraphArgValue): TGraphArgList; begin Add(TGraphArg.Create(Name, Value)); Result := Self; end; function TGraphArgList.AddPair(const Name: string; const Value: TArray<Integer>): TGraphArgList; begin Add(TGraphArg.Create(Name, Value)); Result := Self; end; constructor TGraphArgList.Create; begin inherited Create; end; function TGraphArgList.ToString: string; var i: Integer; begin for i := 0 to Pred(Count) do Result := Result + Items[i].ToString + ', '; Result := '(' + Result.TrimRight([',', ' ']) + ')'; end; { TGraphArgItem<T> } constructor TGraphArgItem<T>.Create(const AValue: T); begin FValue := AValue; end; { TGraphArgInteger } function TGraphArgInteger.ToString: string; begin Result := FValue.ToString; end; { TGraphArgBoolean } function TGraphArgBoolean.ToString: string; begin if FValue then Exit('true') else Exit('false'); end; { TGraphArgFloat } function TGraphArgFloat.ToString: string; var FS: TFormatSettings; begin FS := FormatSettings; FS.DecimalSeparator := '.'; Result := FValue.ToString(FS); end; { TGraphArgVar } function TGraphArgVar.ToString: string; begin Result := FValue; end; { TGraphArgIntegerArray } function TGraphArgIntegerArray.ToString: string; var i: Integer; begin for i := 0 to High(FValue) do Result := Result + FValue[i].ToString + ', '; Result := '[' + Result.TrimRight([',', ' ']) + ']'; end; end.
unit u_xpl_udp_socket; {============================================================================== UnitName = u_xpl_udp_socket_client UnitDesc = xPL specific UDP networking management handling UnitCopyright = GPL by Clinique / xPL Project ============================================================================== } {$i xpl.inc} {$M+} interface uses Classes , IdGlobal , IdUDPClient , IdUDPServer , IdSocketHandle , u_xpl_common , uIP ; type // TxPLUDPClient ========================================================= TxPLUDPClient = class(TIdUDPClient) // Connexion used to send xPL messages private fLastSentTime : TDateTime; protected procedure InitComponent; override; public procedure Send(const AData: string); overload; end; // TxPLUDPServer ========================================================= TxPLUDPServer = class(TIdUDPServer) // Specialized connexion used to listen to xPL messages private fOnReceived : TStrParamEvent; protected function InternalGetUsableAddress(const aIPAdd : TIPAddress) : string; virtual; abstract; function InternalCheckIncoming(const {%H-}aPeerIP : string) : boolean; virtual; function InternalGetMaxBufferSize : integer; virtual; abstract; procedure DoUDPRead({%H-}AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); override; procedure DoOnUDPException({%H-}AThread: TIdUDPListenerThread; {%H-}ABinding: TIdSocketHandle; const AMessage : String; const {%H-}AExceptionClass : TClass); override; procedure AfterBind(Sender: TObject); procedure BeforeBind(AHandle: TIdSocketHandle); public constructor Create(const AOwner: TComponent; const aMinPort : integer = XPL_MIN_PORT; const aMaxPort : integer = XPL_MAX_PORT); reintroduce; published property OnReceived : TStrParamEvent read fOnReceived write fOnReceived; end; // THubServer ============================================================ THubServer = class(TxPLUDPServer) protected function InternalGetUsableAddress(const aIPAdd : TIPAddress) : string; override; function InternalCheckIncoming(const aPeerIP : string) : boolean; override; function InternalGetMaxBufferSize : integer; override; public constructor Create(const AOwner: TComponent); reintroduce; end; // TAppServer ============================================================ TAppServer = class(TxPLUDPServer) protected function InternalGetUsableAddress(const aIPAdd : TIPAddress) : string; override; function InternalGetMaxBufferSize : integer; override; end; implementation //============================================================== uses IdStack , IdUDPBase , SysUtils , StrUtils , DateUtils , lin_win_compat , uxPLConst , u_xpl_application ; // ============================================================================ const K_SENDING_TEMPO = 50; // Temporisation to avoid message flooding XPL_UDP_BASE_PORT= 3865; K_SIZE_ERROR = '%s : message size (%d bytes) exceeds xPL limit (%d bytes)'; K_USING_DEFAULT = 'xPL network settings not set, using defaults'; K_MSG_IP_ERROR = 'Socket unable to bind to IP Addresses'; K_MSG_BIND_OK = 'Listening on %s:%u'; // TxPLUDPClient ============================================================== procedure TxPLUDPClient.InitComponent; begin inherited; BroadcastEnabled := True; Port := XPL_UDP_BASE_PORT; Host := TxPLApplication(Owner).Settings.BroadCastAddress; fLastSentTime := now; end; procedure TxPLUDPClient.Send(const AData: string); var Tempo : integer; begin if length(aData) <= XPL_MAX_MSG_SIZE then begin Tempo := MillisecondsBetween(fLastSentTime, now); if Tempo < K_SENDING_TEMPO then Sleep(K_SENDING_TEMPO-Tempo); inherited Send(aData); fLastSentTime := now; end else xPLApplication.Log(etWarning,K_SIZE_ERROR,[ClassName, length(aData), XPL_MAX_MSG_SIZE]) end; // TxPLHubServer ============================================================== constructor THubServer.Create(const AOwner: TComponent); begin inherited Create(aOwner,XPL_UDP_BASE_PORT,XPL_UDP_BASE_PORT); end; function THubServer.InternalGetUsableAddress(const aIPAdd: TIPAddress): string; begin // hub will listen on broadcast addresses Result := aIPAdd.BroadCast; end; function THubServer.InternalCheckIncoming(const aPeerIP: string): boolean; begin with xPLApplication.Settings do Result := ListenToAny or (ListenToLocal and Assigned(LocalIPAddresses.GetByIP(aPeerIP))) or (AnsiPos(aPeerIP,ListenToAddresses) > 0); Result := Result and inherited; end; function THubServer.InternalGetMaxBufferSize: integer; begin Result := ID_UDP_BUFFERSIZE; // Remove xPL limit at hub level : the hub should relay without limiting to 1500 bytes end; // TxPLAppServer ============================================================== function TAppServer.InternalGetUsableAddress(const aIPAdd: TIPAddress): string; begin // apps will listen on specific addresses Result := aIPAdd.Address; end; function TAppServer.InternalGetMaxBufferSize: integer; begin Result := XPL_MAX_MSG_SIZE; end; // TxPLUDPServer =============================================================== constructor TxPLUDPServer.Create(const AOwner: TComponent; const aMinPort : integer = XPL_MIN_PORT; const aMaxPort : integer = XPL_MAX_PORT); var address : TIPAddress; begin inherited Create(aOwner); BufferSize := InternalGetMaxBufferSize; DefaultPort := 0; OnUDPException:=@DoOnUDPException; OnAfterBind:=@AfterBind; OnBeforeBind:=@BeforeBind; with TxPLApplication(aOwner).Settings do begin if not IsValid then xPLApplication.Log(etWarning,K_USING_DEFAULT); for address in LocalIPAddresses do if ListenOnAll or (address.Address = ListenOnAddress) then with Bindings.Add do begin IP := InternalGetUsableAddress(Address); ClientPortMin := aMinPort; ClientPortMax := aMaxPort; end; end; try Active := (Bindings.Count > 0); if not Active then xPLApplication.Log(etError,K_MSG_IP_ERROR); except On E : Exception do xPLApplication.Log(etError,E.Message); end; end; function TxPLUDPServer.InternalCheckIncoming(const aPeerIP: string): boolean; begin Result := Assigned(fOnReceived); end; procedure TxPLUDPServer.DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); begin if InternalCheckIncoming(aBinding.PeerIP) then fOnReceived(BytesToString(aData)); end; procedure TxPLUDPServer.DoOnUDPException(AThread: TIdUDPListenerThread; ABinding: TIdSocketHandle; const AMessage: String; const AExceptionClass: TClass); begin xPLApplication.Log(etWarning,'%s : %s',[ClassName,AnsiReplaceStr(aMessage,#13,' ')]); end; procedure TxPLUDPServer.AfterBind(Sender: TObject); var socket : TCollectionItem; begin For socket in Bindings do with TIdSocketHandle(socket) do xPLApplication.Log(etInfo, K_MSG_BIND_OK, [IP,Port]); end; procedure TxPLUDPServer.BeforeBind(AHandle: TIdSocketHandle); begin xPLApplication.Log(etInfo,'Binding on %s:[%d-%d]',[aHandle.IP,aHandle.ClientPortMin,aHandle.ClientPortMax]); end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x18; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common; // transmitter only procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray); implementation Uses SysUtils; (* Type $18 - Curtain1 - Harrison Buffer[0] = packetlength = $07; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = housecode Buffer[5] = unitcode Buffer[6] = cmnd Buffer[7] = battery_level:4/rssi:4 xPL Schema x10.basic { device=<housecode[unitcode] command=on|off protocol=harrison } TO CHECK : no support for stop and program commands ?? TO CHECK : how to handle transmitter-only in DHS ?? *) const // Packet Length PACKETLENGTH = $07; // Type CURTAIN1 = $18; // Subtype HARRISON = $00; // Commands COMMAND_OFF = 'off'; COMMAND_ON = 'on'; var // Lookup table for commands RFXCommandArray : array[1..2] of TRFXCommandRec = ((RFXCode : $00; xPLCommand : COMMAND_ON), (RFXCode : $01; xPLCommand : COMMAND_OFF)); procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray); begin ResetBuffer(Buffer); Buffer[0] := PACKETLENGTH; Buffer[1] := CURTAIN1; // Type Buffer[2] := HARRISON; // Split the device attribute in housecode and unitcode Buffer[4] := Ord(aMessage.Body.Strings.Values['device'][1]); Buffer[5] := StrToInt(Copy(aMessage.Body.Strings.Values['device'],2,Length(aMessage.Body.Strings.Values['device']))); // Command Buffer[6] := GetRFXCode(aMessage.Body.Strings.Values['command'],RFXCommandArray); Buffer[7] := $0; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXRSAFilter; interface uses Data.DBXTransport, System.SysUtils, Data.DBXPlatform, Data.DBXOpenSSL; const USE_GLOBAL = 'UseGlobalKey'; PUBLIC_KEY = 'PublicKey'; KEY_LENGTH = 'KeyLength'; KEY_EXPONENT = 'KeyExponent'; type TRSAFilter = class(TTransportFilter) private FUseGlobalKey: boolean; FRSACypher: TRSACypher; FKeyLength: Integer; FKeyExponent: Int64; private procedure InitRSA; protected function GetParameters: TDBXStringArray; override; function GetUserParameters: TDBXStringArray; override; public constructor Create; override; destructor Destroy; override; function ProcessInput(const Data: TBytes): TBytes; override; function ProcessOutput(const Data: TBytes): TBytes; override; function Id: UnicodeString; override; function SetConfederateParameter(const ParamName: UnicodeString; const ParamValue: UnicodeString): Boolean; override; function GetParameterValue(const ParamName: UnicodeString): UnicodeString; override; function SetParameterValue(const ParamName: UnicodeString; const ParamValue: UnicodeString): Boolean; override; function IsPublicKeyCryptograph: boolean; override; end; implementation uses Data.DBXCommon; { TRSAFilter } constructor TRSAFilter.Create; begin inherited; FUseGlobalKey := true; FKeyLength := RSA_KEY_LENGTH; FKeyExponent := RSA_KEY_EXPONENT; end; destructor TRSAFilter.Destroy; begin FreeAndNil(FRSACypher); inherited; end; function TRSAFilter.GetParameters: TDBXStringArray; begin SetLength(Result, 1); Result[0] := PUBLIC_KEY; end; function TRSAFilter.GetParameterValue( const ParamName: UnicodeString): UnicodeString; begin if AnsiCompareStr(ParamName, USE_GLOBAL) = 0 then begin if FUseGlobalKey then exit('true') else exit('false'); end; if AnsiCompareStr(ParamName, PUBLIC_KEY) = 0 then begin InitRSA; exit(Encode(FRSACypher.GetPublicKey, 0, -1)); end; if AnsiCompareStr(ParamName, KEY_LENGTH) = 0 then begin exit(IntToStr(FKeyLength)); end; if AnsiCompareStr(ParamName, KEY_EXPONENT) = 0 then begin exit(IntToStr(FKeyExponent)); end; Result := EmptyStr; end; function TRSAFilter.GetUserParameters: TDBXStringArray; begin SetLength(Result, 3); Result[0] := USE_GLOBAL; Result[1] := KEY_LENGTH; Result[2] := KEY_EXPONENT; end; function TRSAFilter.Id: UnicodeString; begin Result := 'RSA'; end; procedure TRSAFilter.InitRSA; begin if FRSACypher = nil then begin if not TRSACypher.LoadSSLAndCreateKey(FKeyLength, FKeyExponent) then raise TDBXError.Create(0, TRSACypher.ErrorLoad); if FUseGlobalKey then FRSACypher := TRSACypher.Create else begin FRSACypher := TRSACypher.Create(kupUseLocalKey); FRSACypher.GenerateKey(FKeyLength, FKeyExponent); end; end; end; function TRSAFilter.IsPublicKeyCryptograph: boolean; begin Result := true; end; function TRSAFilter.ProcessInput(const Data: TBytes): TBytes; begin InitRSA; Result := FRSACypher.PublicEncrypt(Data) end; function TRSAFilter.ProcessOutput(const Data: TBytes): TBytes; begin InitRSA; Result := FRSACypher.PrivateDecrypt(Data) end; function TRSAFilter.SetConfederateParameter(const ParamName, ParamValue: UnicodeString): Boolean; begin if AnsiCompareStr(ParamName, PUBLIC_KEY) = 0 then begin InitRSA; FRSACypher.SetConfederatePublicKey(Decode(ParamValue)); exit(true); end; Result := false; end; function TRSAFilter.SetParameterValue(const ParamName, ParamValue: UnicodeString): Boolean; begin if AnsiCompareStr(ParamName, USE_GLOBAL) = 0 then begin FUseGlobalKey := AnsiCompareText(ParamValue, 'true') = 0; exit(true); end; if AnsiCompareStr(ParamName, KEY_LENGTH) = 0 then begin FKeyLength := StrToInt(ParamValue); exit(true); end; if AnsiCompareStr(ParamName, KEY_EXPONENT) = 0 then begin FKeyExponent := StrToInt64(ParamValue); exit(true); end; exit(false); end; end.
{: TypesB3D<p> Types used on the B3D file loader<p> <b>History :</b><font size=-1><ul> <li>22/12/05 - Mathx - Added to the GLScene Project. </ul></font> } unit TypesB3D; interface uses GLVectorTypes, GLVectorGeometry; type TB3DChunkType = (bctUnknown, bctHeader, bctTexture, bctBrush, bctNode, bctVertex, bctTriangle, bctMesh, bctBone, bctKeyFrame, bctAnimation); PB3DChunk = ^TB3DChunk; TB3DChunk = record chunk: array[0..3] of char; length: Integer; end; PBB3DChunk = ^TBB3DChunk; TBB3DChunk = record Version: Integer; end; PTEXSChunk = ^TTEXSChunk; TTEXSChunk = record fileName: array[0..255] of char; //texture file name this is the filename of the texture, ie "wall.bmp" Has to be in the local Directory flags, blend: Integer; //blitz3D TextureFLags and TextureBlend: default=1,2 //these are the same as far as I know as the flags for a texture in Blitz3D x_pos, y_pos: Single; //x and y position of texture: default=0,0 x_scale, y_scale: Single; //x and y scale of texture: default=1,1 rotation: Single; //rotation of texture (in radians): default=0 radian = 180/pi degrees end; PBRUSChunk = ^TBRUSChunk; TBRUSChunk = record n_texs: Integer; name: array[0..255] of Char; //eg "WATER" - just use texture name by default red, green, blue, alpha: Single; //Blitz3D Brushcolor and Brushalpha: default=1,1,1,1 shininess: Single; //Blitz3D BrushShininess: default=0 blend, fx: Integer; //Blitz3D Brushblend and BrushFX: default=1,0 texture_id: array of Integer; //textures used in brush, ie if there is more then one texture used, ie Alphamaps, colour maps etc, //you put all ID's here as ints. end; PVertexData = ^TVertexData; TVertexData = record next: PVertexData; x, y, z: Single; //always present nx, ny, nz: Single; //vertex normal: present if (flags&1) red, green, blue, alpha: Single; //vertex color: present if (flags&2) tex_coords: array of Single; //tex coords end; PVRTSChunk = ^TVRTSChunk; TVRTSChunk = record flags: Integer; //1=normal values present, 2=rgba values present tex_coord_sets: Integer; //texture coords per vertex (eg: 1 for simple U/V) max=8 tex_coord_set_size: Integer; //components per set (eg: 2 for simple U/V) max=4 vertices: PVertexData; end; PTRISChunk = ^TTRISChunk; TTRISChunk = record next: PTRISChunk; brush_id: Integer; //brush applied to these TRIs: default=-1 vertex_id: array of Integer; //vertex indices end; PMESHChunk = ^TMESHChunk; TMESHChunk = record brush_id: Integer; //'master' brush: default=-1 vertices: TVRTSChunk; //vertices triangles: PTRISChunk; //1 or more sets of triangles end; PBONEChunk = ^TBONEChunk; TBONEChunk = record vertex_id: Integer; //vertex affected by this bone weight: Single; //;how much the vertex is affected end; PKEYSChunk = ^TKEYSChunk; TKEYSChunk = record next: PKEYSChunk; flags: Integer; //1=position, 2=scale, 4=rotation frame: Integer; //where key occurs position: TAffineVector; //present if (flags&1) scale: TAffineVector; //present if (flags&2) rotation: TVector; //present if (flags&4) end; PANIMChunk = ^TANIMChunk; TANIMChunk = record flags: Integer; //unused: default=0 frames: Integer; //how many frames in anim fps: Single; //default=60 end; PNODEChunk = ^TNODEChunk; TNODEChunk = record name: array[0..255] of char; //name of node position: TAffineVector; //local... scale: TAffineVector; //coord... rotation: TVector; //system... //array of node elements //should be one of meshes or bones, support meshes only for now meshes: PMESHChunk; //what 'kind' of node this is - if unrecognized, just use a Blitz3D pivot. { not supprot yet bones: PBONEChunk; } keys: PKEYSChunk; //optional animation keys nodes: PNODEChunk; //optional child nodes animation: TANIMChunk; //optional animation next: PNODEChunk; //point to the next node level: Integer; end; implementation end.
unit UI.ListView.Footer; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Standard, UI.Base, UI.ListView; type TListViewDefaultFooter = class(TFrame, IListViewHeader) RelativeLayout1: TRelativeLayout; tvText: TTextView; AniView: TAniIndicator; private { Private declarations } FOrientation: TOrientation; FStatePullUpStart, FStatePullUpOK, FStatePullUpFinish, FStatePullUpComplete: string; FStatePullLeftStart, FStatePullLeftOK, FStatePullLeftFinish, FStatePullLeftComplete: string; protected function GetOrientation: TOrientation; procedure SetOrientation(AOrientation: TOrientation); public constructor Create(AOwner: TComponent); override; { Public declarations } procedure DoUpdateState(const State: TListViewState; const ScrollValue: Double); procedure SetStateHint(const State: TListViewState; const Msg: string); property Orientation: TOrientation read GetOrientation write SetOrientation; end; implementation {$R *.fmx} { TListViewDefaultFooter } constructor TListViewDefaultFooter.Create(AOwner: TComponent); begin inherited; FOrientation := TOrientation.Vertical; {$IFDEF MSWINDOWS} FStatePullUpStart := '点击加载更多'; {$ELSE} FStatePullUpStart := '上拉或点击加载更多'; {$ENDIF} FStatePullUpOK := '松开加载更多'; FStatePullUpFinish := '正在加载...'; FStatePullUpComplete := '加载完成'; FStatePullLeftStart := '查看更多'; FStatePullLeftOK := '释放查看'; FStatePullLeftFinish := '正在加载'; FStatePullLeftComplete := '加载完成'; end; procedure TListViewDefaultFooter.DoUpdateState(const State: TListViewState; const ScrollValue: Double); begin case Orientation of TOrientation.Horizontal: begin case State of TListViewState.None, TListViewState.PullLeftStart: begin tvText.Checked := False; tvText.Text := FStatePullLeftStart; AniView.Visible := False; AniView.Enabled := False; Visible := State <> TListViewState.None; tvText.Paddings := '0'; tvText.Margin := '0'; tvText.TextSettings.WordWrap := True; tvText.Layout.CenterHorizontal := False; tvText.Layout.AlignParentLeft := True; tvText.Width := 25; Width := tvText.Width + 5; end; TListViewState.PullLeftOK: begin tvText.Checked := False; tvText.Text := FStatePullLeftOK; AniView.Visible := False; AniView.Enabled := False; end; TListViewState.PullLeftFinish: begin tvText.Checked := False; tvText.Text := FStatePullLeftFinish; AniView.Enabled := True; AniView.Visible := True; tvText.Visible := False; AniView.Position.X := (Width - AniView.Width) / 2; AniView.Position.Y := (Height - AniView.Height) / 2; end; TListViewState.PullLeftComplete: begin tvText.Text := FStatePullLeftComplete; AniView.Enabled := False; AniView.Visible := False; tvText.Visible := True; end; end; end; TOrientation.Vertical: begin case State of TListViewState.None, TListViewState.PullUpStart: begin tvText.Checked := False; tvText.Text := FStatePullUpStart; AniView.Visible := False; AniView.Enabled := False; Visible := True; end; TListViewState.PullUpOK: begin tvText.Checked := False; tvText.Text := FStatePullUpOK; AniView.Visible := False; AniView.Enabled := False; end; TListViewState.PullUpFinish: begin tvText.Checked := False; tvText.Text := FStatePullUpFinish; AniView.Enabled := True; AniView.Visible := True; end; TListViewState.PullUpComplete: begin tvText.Checked := True; tvText.Text := FStatePullUpComplete; AniView.Enabled := False; AniView.Visible := False; end; end; end; end; end; function TListViewDefaultFooter.GetOrientation: TOrientation; begin Result := FOrientation; end; procedure TListViewDefaultFooter.SetOrientation(AOrientation: TOrientation); begin FOrientation := AOrientation; end; procedure TListViewDefaultFooter.SetStateHint(const State: TListViewState; const Msg: string); begin case Orientation of TOrientation.Horizontal: begin case State of TListViewState.None, TListViewState.PullLeftStart: FStatePullLeftStart := Msg; TListViewState.PullLeftOK: FStatePullLeftOK := Msg; TListViewState.PullLeftFinish: FStatePullLeftFinish := Msg; TListViewState.PullLeftComplete: FStatePullLeftComplete := Msg; end; end; TOrientation.Vertical: begin case State of TListViewState.None, TListViewState.PullUpStart: FStatePullUpStart := Msg; TListViewState.PullUpOK: FStatePullUpOK := Msg; TListViewState.PullUpFinish: FStatePullUpFinish := Msg; TListViewState.PullUpComplete: FStatePullUpComplete := Msg; end; end; end; end; end.
{ $Id: DemoHaltRepeatingOnError.pas 7 2008-04-24 11:59:47Z judc $ } {: DUnit: An XTreme testing framework for Delphi programs. @author The DUnit Group. @version $Revision: 7 $ } (* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is DUnit. * * The Initial Developers of the Original Code are Kent Beck, Erich Gamma, * and Juancarlo Aņez. * Portions created The Initial Developers are Copyright (C) 1999-2000. * Portions created by The DUnit Group are Copyright (C) 2000. * All rights reserved. * * Contributor(s): * Kent Beck <kentbeck@csi.com> * Erich Gamma <Erich_Gamma@oti.com> * Juanco Aņez <juanco@users.sourceforge.net> * Chris Morris <chrismo@users.sourceforge.net> * Jeff Moore <JeffMoore@users.sourceforge.net> * Kris Golko <neuromancer@users.sourceforge.net> * The DUnit group at SourceForge <http://dunit.sourceforge.net> * *) unit DemoHaltRepeatingOnError; interface uses TestFramework, TestExtensions; const COUNT_MAX = 5; type ITestStub = interface(ITest) function GetCounter: integer; end; TTestStub = class(TTestCase, ITestStub) protected FCounter: integer; public function GetCounter: integer; published {$IFDEF CLR}[Test]{$ENDIF} procedure test; end; TTestStubTest = class(TTestCase) private FTestResult: TTestResult; FTestStub: ITestStub; public procedure SetUp; override; procedure TearDown; override; end; TTestRepeatedTest = class(TTestStubTest) private FIterations: integer; FRepTest: ITest; public procedure SetUp; override; procedure TearDown; override; published {$IFDEF CLR}[Test]{$ENDIF} procedure testRepeatedTest; {$IFDEF CLR}[Test]{$ENDIF} procedure testWithCounting; procedure testWithCountingHaltOnTestFailed; end; TCountCase = class(TTestCase) private FCounter : Integer; FTotal : Integer; FLast : Integer; public procedure SetUp; override; published {$IFDEF CLR}[Test]{$ENDIF} procedure CountTest; virtual; end; TCountCaseFails = class(TTestCase) private FCounter : Integer; FTotal : Integer; FLast : Integer; public procedure SetUp; override; published {$IFDEF CLR}[Test]{$ENDIF} procedure CountTestFails; virtual; end; implementation uses SysUtils; { TTestStub } function TTestStub.GetCounter: integer; begin Result := FCounter; end; procedure TTestStub.test; begin check(true); Inc(FCounter); end; { TTestStubTest } procedure TTestStubTest.SetUp; begin inherited; FTestStub := TTestStub.Create('test'); FTestResult := TTestResult.Create; end; procedure TTestStubTest.TearDown; begin FTestResult.Free; FTestStub := nil; inherited; end; { TTestRepeatedTest } procedure TTestRepeatedTest.SetUp; begin inherited; FIterations := COUNT_MAX; FRepTest := TRepeatedTest.Create(FTestStub, FIterations); end; procedure TTestRepeatedTest.TearDown; begin FRepTest := nil; FRepTest := nil; inherited; end; procedure TTestRepeatedTest.testRepeatedTest; begin check(FRepTest.CountTestCases = COUNT_MAX); check(FTestStub.getEnabled); FRepTest.Run(FTestResult); check(FTestResult.wasSuccessful); check(FTestStub.GetCounter = COUNT_MAX); end; procedure TTestRepeatedTest.testWithCounting; var CountCase :ITest; AREsult :TTestResult; begin CountCase := TRepeatedTest.Create(TCountCase.Create('CountTest'), COUNT_MAX); AResult := CountCase.Run; try check(AResult.runCount = COUNT_MAX, 'wrong runCount, was ' + IntToStr(AResult.runCount) ); check(AResult.failureCount = 0, 'wrong failureCount, was ' + IntToStr(AResult.failureCount) ); check(AResult.errorCount = 0, 'wrong errorCount, was ' + IntToStr(AResult.errorCount) ); finally AResult.Free end end; { TCountCase } procedure TCountCase.CountTest; begin Inc(FCounter); check(FCounter = 1, 'must be one, or SetUp was not called'); Inc(FTotal); check(FTotal >= 1, 'total should be at least one'); check(FTotal = (FLast+1), 'total should be increment'); FLast := FTotal; end; procedure TCountCase.SetUp; begin FCounter := 0; end; procedure TTestRepeatedTest.testWithCountingHaltOnTestFailed; var CountCase :IRepeatedTest; AResult :TTestResult; begin CountCase := TRepeatedTest.Create(TCountCaseFails.Create('CountTestFails'), COUNT_MAX); CountCase.HaltOnError := True; {******** Example use of property *********} AResult := (CountCase as ITest).Run; try check(AResult.runCount = 1, 'wrong runCount, was ' + IntToStr(AResult.runCount) ); check(AResult.failureCount = 1, 'wrong failureCount, was ' + IntToStr(AResult.failureCount) ); check(AResult.errorCount = 0, 'wrong errorCount, was ' + IntToStr(AResult.errorCount) ); finally AResult.Free end end; { TCountCaseFails } procedure TCountCaseFails.CountTestFails; begin Inc(FCounter); check(FCounter = 1, 'must be one, or SetUp was not called'); Inc(FTotal); check(FTotal >= 1, 'total should be at least one'); check(FTotal = (FLast+1), 'total should be increment'); FLast := FTotal; Check(False, 'Forced Fail to halt repetition'); {******* Test fails *********} end; procedure TCountCaseFails.SetUp; begin FCounter := 0; end; initialization RegisterTests('TestExtensions Suite',[ TTestRepeatedTest.Suite]); end.
unit ViewMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, FireDAC.Stan.Def, FireDAC.VCLUI.Wait, FireDAC.Phys.IBWrapper, FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.Phys.IBBase, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.CheckLst, ACBrBase, FireDAC.Phys.FBDef, FireDAC.Phys.FB, NsEditBtn, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Pool, FireDAC.Stan.Async, Data.DB, FireDAC.Comp.Client, System.IniFiles, Migration, Config, MyUtils, MyFileDialogs; type TWindowMain = class(TForm) Page: TPageControl; TabMigration: TTabSheet; Images: TImageList; Actions: TActionList; ActEsc: TAction; ActRestore: TAction; FBRestore: TFDIBRestore; ActMigrate: TAction; TabAdmin: TTabSheet; TxtDbAdmin: TNsEditBtn; LblDbAdmin: TLabel; LblUserAdmin: TLabel; TxtUserAdmin: TEdit; LblPasswordAdmin: TLabel; TxtPasswordAdmin: TEdit; LblProtocolAdmin: TLabel; BoxProtocolAdmin: TComboBox; TxtHostAdmin: TEdit; LblHostAdmin: TLabel; LblPortAdmin: TLabel; TxtPortAdmin: TEdit; CheckVerboseAdmin: TCheckBox; LblBackupFileAdmin: TLabel; FBBackup: TFDIBBackup; ActBackup: TAction; RadioGroupMethodAdmin: TRadioGroup; CheckListOptionsAdmin: TCheckListBox; BtnStartAdmin: TButton; LblDllAdmin: TLabel; TxtDllAdmin: TNsEditBtn; RadioGroupConnMethodAdmin: TRadioGroup; TxtBackupFileAdmin: TNsEditBtn; MemoLogAdmin: TMemo; LblLogAdmin: TLabel; BoxVersionAdmin: TComboBox; LblVersionAdmin: TLabel; PageMigration: TPageControl; TabStart: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; BtnStart: TSpeedButton; ActStart: TAction; procedure ActEscExecute(Sender: TObject); procedure ActRestoreExecute(Sender: TObject); procedure FBError(ASender, AInitiator: TObject; var AException: Exception); procedure FBProgress(ASender: TFDPhysDriverService; const AMessage: string); procedure ActMigrateExecute(Sender: TObject); procedure BtnTestConnClick(Sender: TObject); procedure ActBackupExecute(Sender: TObject); procedure BtnStartAdminClick(Sender: TObject); procedure TxtDbAdminBtnClick(Sender: TObject); procedure Dll(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure RadioGroupConnMethodAdminClick(Sender: TObject); procedure TxtBackupFileAdminBtnClick(Sender: TObject); procedure RadioGroupMethodAdminClick(Sender: TObject); procedure ActStartExecute(Sender: TObject); private procedure LoadConfigs; procedure SaveConfigs; procedure LoadAdminConfigs; procedure SaveAdminConfigs; procedure CopyFirebirdMsg; end; var WindowMain: TWindowMain; MigrationConfig: TMigrationConfig; implementation {$R *.dfm} //INIT procedure TWindowMain.FormCreate(Sender: TObject); begin MigrationConfig := TMigrationConfig.Create; end; procedure TWindowMain.FormDestroy(Sender: TObject); begin MigrationConfig.Free; end; procedure TWindowMain.FormActivate(Sender: TObject); begin LoadConfigs; LoadAdminConfigs; RadioGroupMethodAdminClick(Self); RadioGroupConnMethodAdminClick(Self); end; procedure TWindowMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveConfigs; SaveAdminConfigs; end; ///////////// //MIGRATION// ///////////// procedure TWindowMain.LoadConfigs; begin // var Config := TMigrationConfig.Create; // // TConfig.GetGeral(Config); // // with Config.Source do // begin // TxtUserSource.Text := User; // TxtPasswordSource.Text := Password; // TxtDbSource.Text := Database; // BoxVersionSource.ItemIndex := Integer(Version); // end; // // with Config.Dest do // begin // TxtDbDest.Text := Database; // BoxVersionDest.ItemIndex := Integer(Version); // end; end; procedure TWindowMain.SaveConfigs; begin // var Config := TMigrationConfig.Create; // // with Config.Source do // begin // User := TxtUserSource.Text; // Password := TxtPasswordSource.Text; // Database := TxtDbSource.Text; // Version := TVersion(BoxVersionSource.ItemIndex); // end; // // with Config.Dest do // begin // Database := TxtDbDest.Text; // Version := TVersion(BoxVersionDest.ItemIndex); // end; // // TConfig.SetGeral(Config); // // Config.Free; end; procedure TWindowMain.ActStartExecute(Sender: TObject); begin TabAdmin.TabVisible := false; Page.Height := Page.Height + 27; Page.Top := -27; end; procedure TWindowMain.BtnTestConnClick(Sender: TObject); var FBDriverLink: TFDPhysFBDriverLink; ConnTest: TFDConnection; begin // BtnTestConn.Enabled := false; // // with MigrationConfig.Source do // begin // User := TxtUserSource.Text; // Password := TxtPasswordSource.Text; // Version := TVersion(BoxVersionSource.ItemIndex); // Database := TxtDbSource.Text; // end; // // FBDriverLink := TFDPhysFBDriverLink.Create(self); // // ConnTest := TFDConnection.Create(self); // // try // FBDriverLink.Embedded := true; // FBDriverLink.VendorLib := MigrationConfig.GetPathSourceDll; // FBDriverLink.DriverID := 'FB'; // // ConnTest.DriverName := 'FB'; // // with TFDPhysFBConnectionDefParams(ConnTest.Params) do // begin // UserName := TxtUserSource.Text; // Password := TxtPasswordSource.Text; // Database := TxtDbSource.Text; // Protocol := ipLocal; // end; // // try // ConnTest.Open; // // ShowMessage('Conex„o Ok!'); // Except on E: Exception do // begin // ShowMessage('Erro: ' + E.Message); // end; // end; // finally // ConnTest.Close; // FreeAndNil(ConnTest); // FBDriverLink.Release; // FreeAndNil(FBDriverLink); // BtnTestConn.Enabled := true; // end; end; procedure TWindowMain.ActMigrateExecute(Sender: TObject); var Migration: TMigration; begin // SaveConfigs; // // MemoLog.Clear; // MemoErrors.Clear; // // try // with MigrationConfig.Source do // begin // User := TxtUserSource.Text; // Password := TxtPasswordSource.Text; // Version := TVersion(BoxVersionSource.ItemIndex); // Database := TxtDbSource.Text; // end; // // with MigrationConfig.Dest do // begin // Version := TVersion(BoxVersionDest.ItemIndex); // Database := TxtDbDest.Text; // end; // // Migration := TMigration.Create(MigrationConfig); // // Migration.Migrate(MemoLog, MemoErrors); // finally // Migration.Free; // end; end; ///////////// ////ADMIN//// ///////////// procedure TWindowMain.LoadAdminConfigs; var Arq: TIniFile; begin Arq := TIniFile.Create(TUtils.AppPath + 'Config.ini'); try TxtDbAdmin.Text := Arq.ReadString('GENERAL', 'Database', ''); TxtUserAdmin.Text := Arq.ReadString('GENERAL', 'User', 'SYSDBA'); TxtPasswordAdmin.Text := Arq.ReadString('GENERAL', 'Password', 'masterkey'); RadioGroupConnMethodAdmin.ItemIndex := Arq.ReadString('GENERAL', 'ConnMethod', '0').ToInteger; BoxProtocolAdmin.ItemIndex := Arq.ReadString('GENERAL', 'Protocol', '1').ToInteger; TxtHostAdmin.Text := Arq.ReadString('GENERAL', 'Host', 'localhost'); TxtPortAdmin.Text := Arq.ReadString('GENERAL', 'Port', '3050'); TxtDllAdmin.Text := Arq.ReadString('GENERAL', 'Dll', ''); TxtBackupFileAdmin.Text := Arq.ReadString('GENERAL', 'BackupFile', ''); finally Arq.Free; end; end; procedure TWindowMain.SaveAdminConfigs; var Arq: TIniFile; begin Arq := TIniFile.Create(TUtils.AppPath + 'Config.ini'); try Arq.WriteString('GENERAL', 'Database', TxtDbAdmin.Text); Arq.WriteString('GENERAL', 'User', TxtUserAdmin.Text); Arq.WriteString('GENERAL', 'Password', TxtPasswordAdmin.Text); Arq.WriteString('GENERAL', 'ConnMethod', RadioGroupConnMethodAdmin.ItemIndex.ToString); Arq.WriteString('GENERAL', 'Protocol', BoxProtocolAdmin.ItemIndex.ToString); Arq.WriteString('GENERAL', 'Host', TxtHostAdmin.Text); Arq.WriteString('GENERAL', 'Port', TxtPortAdmin.Text); Arq.WriteString('GENERAL', 'Dll', TxtDllAdmin.Text); Arq.WriteString('GENERAL', 'BackupFile', TxtBackupFileAdmin.Text); finally Arq.Free; end; end; procedure TWindowMain.CopyFirebirdMsg; begin var Arq := ExtractFilePath(TxtDllAdmin.Text) + '\Firebird.msg'; if FileExists(Arq) then CopyFile(PWideChar(Arq), PWideChar(ExtractFilePath(Application.ExeName) + '\Firebird.msg'), false); end; procedure TWindowMain.RadioGroupConnMethodAdminClick(Sender: TObject); begin case RadioGroupConnMethodAdmin.ItemIndex of 0: begin BoxProtocolAdmin.Enabled := true; TxtHostAdmin.Enabled := true; TxtPortAdmin.Enabled := true; end; 1: begin BoxProtocolAdmin.Enabled := false; TxtHostAdmin.Enabled := false; TxtPortAdmin.Enabled := false; TxtDllAdmin.Enabled := true; end; end; end; procedure TWindowMain.RadioGroupMethodAdminClick(Sender: TObject); begin case RadioGroupMethodAdmin.ItemIndex of 0: begin with CheckListOptionsAdmin.Items do begin Clear; Add('boIgnoreChecksum'); Add('boIgnoreLimbo'); Add('boMetadataOnly'); Add('boNoGarbageCollect'); Add('boOldDescriptions'); Add('boNonTransportable'); Add('boConvert'); Add('boExpand'); end; end; 1: begin with CheckListOptionsAdmin.Items do begin Clear; Add('roDeactivateIdx'); Add('roNoShadow'); Add('roNoValidity'); Add('roOneAtATime'); Add('roReplace'); Add('roUseAllSpace'); Add('roValidate'); Add('roFixFSSData'); Add('roFixFSSMetaData'); Add('roMetaDataOnly'); end; end; end; end; procedure TWindowMain.TxtDbAdminBtnClick(Sender: TObject); begin case RadioGroupMethodAdmin.ItemIndex of 0: TFileDialogs.OpenFileFB(Sender); 1: TFileDialogs.SaveFileFB(Sender); end; end; procedure TWindowMain.TxtBackupFileAdminBtnClick(Sender: TObject); begin case RadioGroupMethodAdmin.ItemIndex of 0: TFileDialogs.SaveFileFBK(Sender); 1: TFileDialogs.OpenFileFBK(Sender); end; end; procedure TWindowMain.Dll(Sender: TObject); begin TFileDialogs.OpenFileDLL(Sender); end; procedure TWindowMain.BtnStartAdminClick(Sender: TObject); begin case RadioGroupMethodAdmin.ItemIndex of 0: ActBackup.Execute; 1: ActRestore.Execute; end; end; procedure TWindowMain.ActBackupExecute(Sender: TObject); var I: integer; FBDriverLink: TFDPhysFBDriverLink; begin Page.ActivePageIndex := 0; TabAdmin.Enabled := false; MemoLogAdmin.Clear; Application.ProcessMessages; FBDriverLink := TFDPhysFBDriverLink.Create(nil); try FBBackup.Database := TxtDbAdmin.Text; FBBackup.UserName := TxtUserAdmin.Text; FBBackup.Password := TxtPasswordAdmin.Text; FBBackup.BackupFiles.Clear; FBBackup.BackupFiles.Text := TxtBackupFileAdmin.Text; //TCPIP case RadioGroupConnMethodAdmin.ItemIndex of 0: begin FBDriverLink.Embedded := false; FBDriverLink.VendorLib := TxtDllAdmin.Text; FBBackup.Protocol := TIBProtocol(BoxProtocolAdmin.ItemIndex); FBBackup.Host := TxtHostAdmin.Text; FBBackup.Port := StrToInt(TxtPortAdmin.Text); end; //EMBEDDED 1: begin FBDriverLink.Embedded := true; FBDriverLink.VendorLib := TxtDllAdmin.Text; FBBackup.Protocol := ipLocal; CopyFirebirdMsg; end; end; FBBackup.DriverLink := FBDriverLink; FBBackup.Verbose := CheckVerboseAdmin.Checked; FBBackup.Options := []; for I := 0 to CheckListOptionsAdmin.Count - 1 do begin if CheckListOptionsAdmin.Checked[I] then begin case I of 0: FBBackup.Options := FBBackup.Options + [boIgnoreChecksum]; 1: FBBackup.Options := FBBackup.Options + [boIgnoreLimbo]; 2: FBBackup.Options := FBBackup.Options + [boMetadataOnly]; 3: FBBackup.Options := FBBackup.Options + [boNoGarbageCollect]; 4: FBBackup.Options := FBBackup.Options + [boOldDescriptions]; 5: FBBackup.Options := FBBackup.Options + [boNonTransportable]; 6: FBBackup.Options := FBBackup.Options + [boConvert]; 7: FBBackup.Options := FBBackup.Options + [boExpand]; end; end; end; FBBackup.Backup; finally TabAdmin.Enabled := true; FBDriverLink.Free; end; end; procedure TWindowMain.ActRestoreExecute(Sender: TObject); var I: integer; FBDriverLink: TFDPhysFBDriverLink; begin Page.ActivePageIndex := 0; TabAdmin.Enabled := false; MemoLogAdmin.Clear; Application.ProcessMessages; FBDriverLink := TFDPhysFBDriverLink.Create(nil); try FBRestore.Database := TxtDbAdmin.Text; FBRestore.UserName := TxtUserAdmin.Text; FBRestore.Password := TxtPasswordAdmin.Text; FBRestore.BackupFiles.Clear; FBRestore.BackupFiles.Text := TxtBackupFileAdmin.Text; case RadioGroupConnMethodAdmin.ItemIndex of 0: begin FBDriverLink.Embedded := false; FBRestore.Protocol := TIBProtocol(BoxProtocolAdmin.ItemIndex); FBRestore.Host := TxtHostAdmin.Text; FBRestore.Port := StrToInt(TxtPortAdmin.Text); end; 1: begin FBDriverLink.Embedded := true; FBDriverLink.VendorLib := TxtDllAdmin.Text; FBRestore.Protocol := ipLocal; // CopyFirebirdMsg; end; end; FBRestore.DriverLink := FBDriverLink; FBRestore.Verbose := CheckVerboseAdmin.Checked; FBRestore.Options := []; for I := 0 to CheckListOptionsAdmin.Count - 1 do begin if CheckListOptionsAdmin.Checked[I] then begin case I of 0: FBRestore.Options := FBRestore.Options + [roDeactivateIdx]; 1: FBRestore.Options := FBRestore.Options + [roNoShadow]; 2: FBRestore.Options := FBRestore.Options + [roNoValidity]; 3: FBRestore.Options := FBRestore.Options + [roOneAtATime]; 4: FBRestore.Options := FBRestore.Options + [roReplace]; 5: FBRestore.Options := FBRestore.Options + [roUseAllSpace]; 6: FBRestore.Options := FBRestore.Options + [roValidate]; 7: FBRestore.Options := FBRestore.Options + [roFixFSSData]; 8: FBRestore.Options := FBRestore.Options + [roFixFSSMetaData]; 9: FBRestore.Options := FBRestore.Options + [roMetaDataOnly]; end; end; end; FBRestore.Restore; finally TabAdmin.Enabled := true; FBDriverLink.Free; end; end; procedure TWindowMain.FBProgress(ASender: TFDPhysDriverService; const AMessage: string); begin WindowMain.MemoLogAdmin.Lines.Add(AMessage); end; procedure TWindowMain.FBError(ASender, AInitiator: TObject; var AException: Exception); begin WindowMain.MemoLogAdmin.Lines.Add(AException.Message); end; //OTHERS procedure TWindowMain.ActEscExecute(Sender: TObject); begin Close; end; end.
unit uNickNamesListParam; interface uses dmConnection; type TNickNamesListParam = class(TObject) private FNickNames: string; FChannel: string; FConnection: TConnectionData; procedure SetChannel(const Value: string); procedure SetConnection(const Value: TConnectionData); procedure SetNickNames(const Value: string); public property Connection: TConnectionData read FConnection write SetConnection; property Channel: string read FChannel write SetChannel; property NickNames: string read FNickNames write SetNickNames; end; implementation { TNickNamesListParam } procedure TNickNamesListParam.SetChannel(const Value: string); begin FChannel := Value; end; procedure TNickNamesListParam.SetConnection(const Value: TConnectionData); begin FConnection := Value; end; procedure TNickNamesListParam.SetNickNames(const Value: string); begin FNickNames := Value; end; end.
{ Mystix Copyright (C) 2005 Piotr Jura This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You can contact with me by e-mail: pjura@o2.pl } unit uOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, CheckLst, uMyIniFiles, ActnList, Menus, Registry; type TOptionsDialog = class(TForm) pctrlOptions: TPageControl; btnOK: TButton; btnCancel: TButton; tsGeneral: TTabSheet; tsEditor: TTabSheet; chkSaveWindowPos: TCheckBox; lblInterfaceLanguage: TLabel; cmbLanguage: TComboBox; lblDefExtension: TLabel; txtDefExt: TEdit; chkReopenWorkspace: TCheckBox; chkReopenLastFiles: TCheckBox; chkCreateEmpty: TCheckBox; lblDefDocumentType: TLabel; cmbDocType: TComboBox; tsDocumentTypes: TTabSheet; gbGeneral: TGroupBox; chkAutoIndent: TCheckBox; chkGroupUndo: TCheckBox; chkHighlightLine: TCheckBox; chkInsertMode: TCheckBox; chkScrollPastEOF: TCheckBox; chkScrollPastEOL: TCheckBox; chkIndentGuides: TCheckBox; chkSpecialCharacters: TCheckBox; chkTabsToSpaces: TCheckBox; chkWordWrap: TCheckBox; gbGutterMargin: TGroupBox; lblActiveLine: TLabel; cbActiveLine: TColorBox; lblExtraLine: TLabel; Edit2: TEdit; udExtraSpacing: TUpDown; lblInsertCaret: TLabel; cmbInsertCaret: TComboBox; lblOverwriteCaret: TLabel; cmbOverwriteCaret: TComboBox; Edit3: TEdit; udMaxUndo: TUpDown; lblMaxUndo: TLabel; lblTabWidth: TLabel; Edit4: TEdit; udTabWidth: TUpDown; chkShowGutter: TCheckBox; chkShowRightMargin: TCheckBox; chkShowLineNumbers: TCheckBox; chkShowLeadingZeros: TCheckBox; chkZeroStart: TCheckBox; lblRightMarginPos: TLabel; Edit5: TEdit; udRightMargin: TUpDown; lblGutterColor: TLabel; cbGutter: TColorBox; lblFoldingBarColor: TLabel; cbFoldingBar: TColorBox; lblFoldingLinesColor: TLabel; cbFoldingLines: TColorBox; chkHighlightGuides: TCheckBox; btnFont: TButton; lstDocTypes: TListBox; gbDocTypeProperties: TGroupBox; lblDocTypeName: TLabel; txtDocTypeName: TEdit; txtExtensions: TEdit; lblDocTypeExtensions: TLabel; lblDocTypeSyntaxFile: TLabel; txtSyntax: TEdit; chkCodeFolding: TCheckBox; lblFoldingButton: TLabel; cmbFoldingButton: TComboBox; lblDocTypeRegExp: TLabel; txtRegExp: TEdit; btnSyntax: TButton; btnAddDocType: TButton; btnDeleteDocType: TButton; gbCommonDocTypes: TGroupBox; lstCommonDocTypes: TCheckListBox; lblCommonDocTypesIntro: TLabel; dlgOpen: TOpenDialog; tsKeyboard: TTabSheet; dlgFont: TFontDialog; gbKeyboard: TGroupBox; lblKeyCategories: TLabel; lstKeyCat: TListBox; lstKeyCmd: TListBox; lblKeyCommands: TLabel; lblShortcutKey: TLabel; gbMouse: TGroupBox; lblGestureUp: TLabel; cmbGestureUp: TComboBox; lblGestureLeft: TLabel; cmbGestureLeft: TComboBox; lblGestureDown: TLabel; cmbGestureDown: TComboBox; lblGestureRight: TLabel; cmbGestureRight: TComboBox; lblMiddleButton: TLabel; cmbMiddleButton: TComboBox; lblShortCutAssigned: TLabel; lblShortCutAssignedTo: TLabel; btnHelp: TButton; chkDefEditor: TCheckBox; chkSysContext: TCheckBox; chkOneCopy: TCheckBox; chkCtrl: TCheckBox; chkShift: TCheckBox; chkAlt: TCheckBox; cmbShortCut: TComboBox; procedure FormCreate(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure lstDocTypesClick(Sender: TObject); procedure btnAddDocTypeClick(Sender: TObject); procedure btnDeleteDocTypeClick(Sender: TObject); procedure txtDocTypeNameExit(Sender: TObject); procedure txtExtensionsExit(Sender: TObject); procedure txtSyntaxExit(Sender: TObject); procedure txtRegExpExit(Sender: TObject); procedure btnSyntaxClick(Sender: TObject); procedure btnFontClick(Sender: TObject); procedure lstKeyCatClick(Sender: TObject); procedure lstKeyCmdClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure lstCommonDocTypesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure chkDefEditorClick(Sender: TObject); procedure chkSysContextClick(Sender: TObject); procedure chkCtrlClick(Sender: TObject); procedure chkShiftClick(Sender: TObject); procedure chkAltClick(Sender: TObject); procedure cmbShortCutChange(Sender: TObject); private { Private declarations } fSettingsCopy: TMyIniFile; fSettingShortCut: Boolean; procedure SetDocumentTypeProperty(PropertyName, Value: Variant); procedure ReadLanguageData; procedure ShortcutAssigned; procedure ShortcutChanged; function ShortcutGet: String; function IsDefaultEditorOf(DocumentType: String): Boolean; function IsInContextMenuOf(DocumentType: String): Boolean; function GetClassNameFor(Extension: String): String; procedure MakeDefaultEditor(Index: Integer; Associate: Boolean); procedure AddToSysContext(Index: Integer; Associate: Boolean); procedure GetExtensions(Index: Integer; Extensions: TStringList); public { Public declarations } end; var OptionsDialog: TOptionsDialog; CommandNames: TStringList; const DocTypeKeyNames: array[0..3] of String = ('Name', 'Extensions', 'SyntaxFile', 'FunctionRegExp'); implementation uses uMain, IniFiles, uUtils; {$R *.dfm} procedure TOptionsDialog.FormCreate(Sender: TObject); var i: Integer; TempFileName: String; begin ReadLanguageData; TempFileName := PChar(ExtractFilePath(Settings.FileName) + 'SettingsCopy.ini'); CopyFile(PChar(Settings.FileName), PChar(TempFileName), False); fSettingsCopy := TMyIniFile.Create(TempFileName); with fSettingsCopy do begin // General // Setup controls cmbLanguage.Items.BeginUpdate; try for i := 0 to Languages.Count - 1 do cmbLanguage.Items.Add(Languages.Names[i]); finally cmbLanguage.Items.EndUpdate; end; cmbDocType.Items.BeginUpdate; try cmbDocType.Items.Add(sStrings[siNoDocType]); for i := 0 to DocTypes.Count - 1 do cmbDocType.Items.Add(DocTypes[i]); finally cmbDocType.Items.EndUpdate; end; // Read data chkOneCopy.Checked := ReadBool('General', 'OnlyOneCopy', False); chkSaveWindowPos.Checked := ReadBool('General', 'SaveWindowPosition', False); chkReopenWorkspace.Checked := ReadBool('General', 'ReopenLastWorkspace', False); chkReopenLastFiles.Checked := ReadBool('General', 'ReopenLastFiles', False); chkCreateEmpty.Checked := ReadBool('General', 'CreateEmptyDocument', False); cmbLanguage.ItemIndex := cmbLanguage.Items.IndexOf(ActiveLanguage); cmbDocType.ItemIndex := cmbDocType.Items.IndexOf( ReadString('General', 'DefaultDocumentType', '')); if cmbDocType.ItemIndex = -1 then cmbDocType.ItemIndex := 0; txtDefExt.Text := ReadString('General', 'DefaultExtension', 'txt'); // Editor // Setup controls for i := 8 to 11 do begin cmbInsertCaret.Items.Add(sStrings[i]); cmbOverwriteCaret.Items.Add(sStrings[i]); end; for i := 16 to 17 do cmbFoldingButton.Items.Add(sStrings[i]); // Read data chkAutoIndent.Checked := ReadBool('Editor', 'AutoIndent', False); chkCodeFolding.Checked := ReadBool('Editor', 'CodeFolding', False); chkGroupUndo.Checked := ReadBool('Editor', 'GroupUndo', False); chkHighlightLine.Checked := ReadBool('Editor', 'HighlightActiveLine', False); chkHighlightGuides.Checked := ReadBool('Editor', 'HighlightIndentGuides', False); chkInsertMode.Checked := ReadBool('Editor', 'InsertMode', False); chkScrollPastEOF.Checked := ReadBool('Editor', 'ScrollPastEOF', False); chkScrollPastEOL.Checked := ReadBool('Editor', 'ScrollPastEOL', False); chkIndentGuides.Checked := ReadBool('Editor', 'ShowIndentGuides', False); chkSpecialCharacters.Checked := ReadBool('Editor', 'ShowSpecialCharacters', False); chkTabsToSpaces.Checked := ReadBool('Editor', 'TabsToSpaces', False); chkWordWrap.Checked := ReadBool('Editor', 'WordWrap', False); cbActiveLine.Selected := ReadColor('Editor', 'ActiveLineColor', clYellow); udExtraSpacing.Position := ReadInteger('Editor', 'ExtraLineSpacing', 0); udMaxUndo.Position := ReadInteger('Editor', 'MaximumUndo', 1024); cmbInsertCaret.ItemIndex := ReadInteger('Editor', 'InsertCaret', 0); cmbOverwriteCaret.ItemIndex := ReadInteger('Editor', 'OverwriteCaret', 0); cmbFoldingButton.ItemIndex := ReadInteger('Editor', 'FoldingButtonStyle', 0); udTabWidth.Position := ReadInteger('Editor', 'TabWidth', 4); dlgFont.Font.Name := ReadString('Editor', 'FontName', ''); dlgFont.Font.Size := ReadInteger('Editor', 'FontSize', 10); btnFont.Caption := Format(sStrings[siFontButton], [dlgFont.Font.Name, dlgFont.Font.Size]); chkShowGutter.Checked := ReadBool('Editor', 'ShowGutter', False); chkShowRightMargin.Checked := ReadBool('Editor', 'ShowRightMargin', False); chkShowLineNumbers.Checked := ReadBool('Editor', 'ShowLineNumbers', False); chkShowLeadingZeros.Checked := ReadBool('Editor', 'ShowLeadingZeros', False); chkZeroStart.Checked := ReadBool('Editor', 'ZeroStart', False); udRightMargin.Position := ReadInteger('Editor', 'RightMarginPosition', 80); cbGutter.Selected := ReadColor('Editor', 'GutterColor', clBtnFace); cbFoldingBar.Selected := ReadColor('Editor', 'FoldingBarColor', clDefault); cbFoldingLines.Selected := ReadColor('Editor', 'FoldingBarLinesColor', clDefault); // Document types // Read data lstDocTypes.Items.BeginUpdate; lstCommonDocTypes.Items.BeginUpdate; try i := 1; while ValueExists('DocumentTypes', 'DocumentTypeName' + IntToStr(i)) do begin lstDocTypes.Items.Add(ReadString('DocumentTypes', 'DocumentTypeName' + IntToStr(i), '')); lstCommonDocTypes.Items.Add(ReadString('DocumentTypes', 'DocumentTypeName' + IntToStr(i), '')); Inc(i); end; if lstDocTypes.Count > 0 then begin lstDocTypes.ItemIndex := 0; lstDocTypesClick(nil); end; i := 1; while ValueExists('CommonDocumentTypes', 'DocumentType' + IntToStr(i)) do begin lstCommonDocTypes.Checked[lstCommonDocTypes.Items.IndexOf( ReadString('CommonDocumentTypes', 'DocumentType' + IntToStr(i), '') )] := True; Inc(i); end; finally lstDocTypes.Items.EndUpdate; lstCommonDocTypes.Items.EndUpdate; end; // Keyboard & Mouse // Setup controls with MainForm.actlMain do begin lstKeyCat.Items.BeginUpdate; try for i := 0 to ActionCount - 1 do if lstKeyCat.Items.IndexOf(Actions[i].Category) = -1 then lstKeyCat.Items.Add(Actions[i].Category); if lstKeyCat.Count > 0 then begin lstKeyCat.ItemIndex := 0; lstKeyCatClick(nil); end; finally lstKeyCat.Items.EndUpdate; end; CommandNames := TStringList.Create; for i := 0 to ActionCount - 1 do CommandNames.Add(Actions[i].Name); CommandNames.Sort; cmbGestureUp.Items.Assign(CommandNames); cmbGestureLeft.Items.Assign(CommandNames); cmbGestureDown.Items.Assign(CommandNames); cmbGestureRight.Items.Assign(CommandNames); cmbMiddleButton.Items.Assign(CommandNames); end; // Read data with cmbGestureDown do ItemIndex := Items.IndexOf(ReadString('Mouse', 'GestureDown', '')); with cmbGestureLeft do ItemIndex := Items.IndexOf(ReadString('Mouse', 'GestureLeft', '')); with cmbGestureRight do ItemIndex := Items.IndexOf(ReadString('Mouse', 'GestureRight', '')); with cmbGestureUp do ItemIndex := Items.IndexOf(ReadString('Mouse', 'GestureUp', '')); with cmbMiddleButton do ItemIndex := Items.IndexOf(ReadString('Mouse', 'MiddleButton', '')); end; end; procedure TOptionsDialog.btnOKClick(Sender: TObject); var i, j, Index: Integer; SortedList: TStringList; begin with fSettingsCopy do begin // General WriteBool('General', 'OnlyOneCopy', chkOneCopy.Checked); WriteBool('General', 'SaveWindowPosition', chkSaveWindowPos.Checked); WriteBool('General', 'ReopenLastWorkspace', chkReopenWorkspace.Checked); WriteBool('General', 'ReopenLastFiles', chkReopenLastFiles.Checked); WriteBool('General', 'CreateEmptyDocument', chkCreateEmpty.Checked); WriteString('General', 'ActiveLanguage', cmbLanguage.Items[cmbLanguage.ItemIndex]); ActiveLanguage := cmbLanguage.Items[cmbLanguage.ItemIndex]; if cmbDocType.ItemIndex = 0 then WriteString('General', 'DefaultDocumentType', '') else WriteString('General', 'DefaultDocumentType', cmbDocType.Items[cmbDocType.ItemIndex]); WriteString('General', 'DefaultExtension', txtDefExt.Text); // Editor WriteBool('Editor', 'AutoIndent', chkAutoIndent.Checked); WriteBool('Editor', 'CodeFolding', chkCodeFolding.Checked); WriteBool('Editor', 'GroupUndo', chkGroupUndo.Checked); WriteBool('Editor', 'HighlightActiveLine', chkHighlightLine.Checked); WriteBool('Editor', 'HighlightIndentGuides', chkIndentGuides.Checked); WriteBool('Editor', 'InsertMode', chkInsertMode.Checked); WriteBool('Editor', 'ScrollPastEOF', chkScrollPastEOF.Checked); WriteBool('Editor', 'ScrollPastEOL', chkScrollPastEOL.Checked); WriteBool('Editor', 'ShowIndentGuides', chkIndentGuides.Checked); WriteBool('Editor', 'ShowSpecialCharacters', chkSpecialCharacters.Checked); WriteBool('Editor', 'TabsToSpaces', chkTabsToSpaces.Checked); WriteBool('Editor', 'WordWrap', chkWordWrap.Checked); WriteColor('Editor', 'ActiveLineColor', cbActiveLine.Selected); WriteInteger('Editor', 'ExtraLineSpacing', udExtraSpacing.Position); WriteInteger('Editor', 'MaximumUndo', udMaxUndo.Position); WriteInteger('Editor', 'InsertCaret', cmbInsertCaret.ItemIndex); WriteInteger('Editor', 'OverwriteCaret', cmbOverwriteCaret.ItemIndex); WriteInteger('Editor', 'FoldingButtonStyle', cmbFoldingButton.ItemIndex); WriteInteger('Editor', 'TabWidth', udTabWidth.Position); WriteString('Editor', 'FontName', dlgFont.Font.Name); WriteInteger('Editor', 'FontSize', dlgFont.Font.Size); WriteBool('Editor', 'ShowGutter', chkShowGutter.Checked); WriteBool('Editor', 'ShowRightMargin', chkShowRightMargin.Checked); WriteBool('Editor', 'ShowLineNumbers', chkShowLineNumbers.Checked); WriteBool('Editor', 'ShowLeadingZeros', chkShowLeadingZeros.Checked); WriteBool('Editor', 'ZeroStart', chkZeroStart.Checked); WriteInteger('Editor', 'RightMarginPosition', udRightMargin.Position); WriteColor('Editor', 'GutterColor', cbGutter.Selected); WriteColor('Editor', 'FoldingBarColor', cbFoldingBar.Selected); WriteColor('Editor', 'FoldingBarLinesColor', cbFoldingLines.Selected); // Document types for i := 0 to lstDocTypes.Count - 1 do begin if ReadBool('DocumentTypes', 'DocumentTypeDefEditor' + IntToStr(i + 1), False) then MakeDefaultEditor(i + 1, True) else MakeDefaultEditor(i + 1, False); if ReadBool('DocumentTypes', 'DocumentTypeSysContext' + IntToStr(i + 1), False) then AddToSysContext(i + 1, True) else AddToSysContext(i + 1, False); end; // Common document types EraseSection('CommonDocumentTypes'); Index := 1; for i := 0 to lstCommonDocTypes.Count - 1 do if lstCommonDocTypes.Checked[i] then begin WriteString('CommonDocumentTypes', 'DocumentType' + IntToStr(Index), lstCommonDocTypes.Items[i]); Inc(Index); end; // Keyboard & Mouse WriteString('Mouse', 'GestureDown', cmbGestureDown.Items[cmbGestureDown.ItemIndex]); WriteString('Mouse', 'GestureLeft', cmbGestureLeft.Items[cmbGestureLeft.ItemIndex]); WriteString('Mouse', 'GestureRight', cmbGestureRight.Items[cmbGestureRight.ItemIndex]); WriteString('Mouse', 'GestureUp', cmbGestureUp.Items[cmbGestureUp.ItemIndex]); WriteString('Mouse', 'MiddleButton', cmbMiddleButton.Items[cmbMiddleButton.ItemIndex]); end; DeleteFile(Settings.FileName); CopyFile(PChar(fSettingsCopy.FileName), PChar(Settings.FileName), False); with Settings do begin // Document types EraseSection('DocumentTypes'); SortedList := TStringList.Create; try SortedList.Assign(lstDocTypes.Items); SortedList.Sort; for i := 0 to SortedList.Count -1 do begin Index := Succ( lstDocTypes.Items.IndexOf(SortedList[i]) ); for j := 0 to 3 do WriteString('DocumentTypes', 'DocumentType' + DocTypeKeyNames[j] + IntToStr(i + 1), fSettingsCopy.ReadString('DocumentTypes', 'DocumentType' + DocTypeKeyNames[j] + IntToStr(Index), '')); end; finally SortedList.Free; end; end; DeleteFile(fSettingsCopy.FileName); ModalResult := mrOK; end; procedure TOptionsDialog.lstDocTypesClick(Sender: TObject); var Index: String; begin if lstDocTypes.ItemIndex <> -1 then begin Index := IntToStr(lstDocTypes.ItemIndex + 1); with fSettingsCopy do begin txtDocTypeName.Text := ReadString('DocumentTypes', 'DocumentTypeName' + Index, ''); txtExtensions.Text := ReadString('DocumentTypes', 'DocumentTypeExtensions' + Index, ''); txtSyntax.Text := ReadString('DocumentTypes', 'DocumentTypeSyntaxFile' + Index, ''); txtRegExp.Text := ReadString('DocumentTypes', 'DocumentTypeFunctionRegExp' + Index, ''); if not ValueExists('DocumentTypes', 'DocumentTypeDefEditor' + Index) then begin fSettingsCopy.WriteBool('DocumentTypes', 'DocumentTypeDefEditor' + Index, IsDefaultEditorOf(lstDocTypes.Items[lstDocTypes.ItemIndex])); fSettingsCopy.WriteBool('DocumentTypes', 'DocumentTypeSysContext' + Index, IsInContextMenuOf(lstDocTypes.Items[lstDocTypes.ItemIndex])); end; chkDefEditor.Checked := ReadBool('DocumentTypes', 'DocumentTypeDefEditor' + Index, False); chkSysContext.Checked := ReadBool('DocumentTypes', 'DocumentTypeSysContext' + Index, False); end; end; end; procedure TOptionsDialog.btnAddDocTypeClick(Sender: TObject); var Index: String; begin Index := IntToStr(lstDocTypes.Count + 1); with fSettingsCopy do begin WriteString('DocumentTypes', 'DocumentTypeName' + Index, 'Document Type' + Index); lstDocTypes.Items.Add('Document Type' + Index); lstDocTypes.ItemIndex := lstDocTypes.Count - 1; lstDocTypesClick(nil); lstCommonDocTypes.Items.Add('Document Type' + Index); cmbDocType.Items.Add('Document Type' + Index); txtDocTypeName.Text := 'Document Type' + Index; txtDocTypeName.SetFocus; end; end; procedure TOptionsDialog.btnDeleteDocTypeClick(Sender: TObject); var Index, Count, i, j: Integer; begin Index := lstDocTypes.ItemIndex + 1; if Index <> 0 then begin with fSettingsCopy do begin Count := lstDocTypes.Count - 1; // Move document types by one position for i := Index to Count do for j := 0 to 3 do begin WriteString('DocumentTypes', 'DocumentType' + DocTypeKeyNames[j] + IntToStr(i), ReadString('DocumentTypes', 'DocumentType' + DocTypeKeyNames[j] + IntToStr(i + 1), '')); end; // Delete last item Inc(Count); for i := 0 to 3 do DeleteKey('DocumentTypes', 'DocumentType' + DocTypeKeyNames[i] + IntToStr(Count)); end; // Delete list items lstCommonDocTypes.Items.Delete(lstDocTypes.ItemIndex); cmbDocType.Items.Delete(lstDocTypes.ItemIndex + 1); lstDocTypes.DeleteSelected; if lstDocTypes.Count > 0 then begin lstDocTypes.ItemIndex := 0; lstDocTypesClick(nil); end; end; end; procedure TOptionsDialog.txtDocTypeNameExit(Sender: TObject); begin if lstDocTypes.Items.IndexOf(txtDocTypeName.Text) = -1 then begin SetDocumentTypeProperty('Name', txtDocTypeName.Text); if lstDocTypes.ItemIndex <> -1 then begin lstDocTypes.Items[lstDocTypes.ItemIndex] := txtDocTypeName.Text; lstCommonDocTypes.Items[lstDocTypes.ItemIndex] := txtDocTypeName.Text; cmbDocType.Items[lstDocTypes.ItemIndex + 1] := txtDocTypeName.Text; end; end else txtDocTypeName.SetFocus; end; procedure TOptionsDialog.txtExtensionsExit(Sender: TObject); begin SetDocumentTypeProperty('Extensions', txtExtensions.Text); end; procedure TOptionsDialog.txtSyntaxExit(Sender: TObject); begin SetDocumentTypeProperty('SyntaxFile', txtSyntax.Text); end; procedure TOptionsDialog.txtRegExpExit(Sender: TObject); begin SetDocumentTypeProperty('FunctionRegExp', txtRegExp.Text); end; procedure TOptionsDialog.btnSyntaxClick(Sender: TObject); begin dlgOpen.InitialDir := AppPath + 'DocumentTypes'; if dlgOpen.Execute then begin txtSyntax.Text := ExtractFileName(dlgOpen.FileName); SetDocumentTypeProperty('SyntaxFile', ExtractFileName(dlgOpen.FileName)); end; end; procedure TOptionsDialog.SetDocumentTypeProperty(PropertyName, Value: Variant); begin if lstDocTypes.ItemIndex <> -1 then if VarType(Value) = varString then fSettingsCopy.WriteString('DocumentTypes', 'DocumentType' + PropertyName + IntToStr(lstDocTypes.ItemIndex + 1), Value) else if VarType(Value) = varBoolean then fSettingsCopy.WriteBool('DocumentTypes', 'DocumentType' + PropertyName + IntToStr(lstDocTypes.ItemIndex + 1), Value); end; procedure TOptionsDialog.btnFontClick(Sender: TObject); begin if dlgFont.Execute then btnFont.Caption := Format(sStrings[siFontButton], [dlgFont.Font.Name, dlgFont.Font.Size]); end; procedure TOptionsDialog.ReadLanguageData; var i: Integer; begin with TMyIniFile.Create(Languages.Values[ActiveLanguage]) do try Caption := ReadString('OptionsDialog', 'Caption', ''); for i := 0 to ComponentCount - 1 do if (Components[i] is TControl) then (Components[i] as TControl).SetTextBuf( PChar(ReadString('OptionsDialog', Components[i].Name + '.Caption', '')) ); finally Free; end; end; procedure TOptionsDialog.lstKeyCatClick(Sender: TObject); var i: Integer; Category: String; begin if lstKeyCat.ItemIndex <> -1 then begin lstKeyCmd.Clear; Category := lstKeyCat.Items[lstKeyCat.ItemIndex]; with MainForm.actlMain do for i := 0 to ActionCount - 1 do if SameText(Category, Actions[i].Category) then lstKeyCmd.AddItem(Actions[i].Name, Actions[i]); if lstKeyCmd.Count > 0 then begin lstKeyCmd.ItemIndex := 0; lstKeyCmdClick(nil); end; end; end; procedure TOptionsDialog.lstKeyCmdClick(Sender: TObject); var Shortcut: String; P: Integer; begin fSettingShortCut := True; Shortcut := fSettingsCopy.ReadString('Keyboard', lstKeyCmd.Items[lstKeyCmd.ItemIndex], ''); chkCtrl.Checked := Pos('Ctrl', Shortcut) > 0; chkShift.Checked := Pos('Shift', Shortcut) > 0; chkAlt.Checked := Pos('Alt', Shortcut) > 0; repeat P := Pos('+', Shortcut); if P = 0 then cmbShortCut.ItemIndex := cmbShortCut.Items.IndexOf( Copy(Shortcut, 1, MaxInt)) else Delete(Shortcut, 1, P); until P = 0; fSettingShortCut := False; lblShortCutAssignedTo.Caption := ''; end; procedure TOptionsDialog.FormDestroy(Sender: TObject); begin CommandNames.Free; end; procedure TOptionsDialog.btnCancelClick(Sender: TObject); begin DeleteFile(fSettingsCopy.FileName); ModalResult := mrCancel; end; procedure TOptionsDialog.lstCommonDocTypesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; i, j, c: Integer; begin P.X := X; P.Y := Y; i := lstCommonDocTypes.ItemAtPos(P, True); c := 0; for j := 0 to lstCommonDocTypes.Count - 1 do if lstCommonDocTypes.Checked[j] then Inc(c); if c = 10 then begin Application.MessageBox( PChar(sStrings[siTenDocTypes]), 'Information', MB_OK or MB_ICONINFORMATION); lstCommonDocTypes.Checked[i] := False; end; end; procedure TOptionsDialog.chkDefEditorClick(Sender: TObject); begin SetDocumentTypeProperty('DefEditor', chkDefEditor.Checked); end; procedure TOptionsDialog.chkSysContextClick(Sender: TObject); begin SetDocumentTypeProperty('SysContext', chkSysContext.Checked); end; procedure TOptionsDialog.ShortcutAssigned; var i: Integer; Shortcut: String; begin lblShortCutAssignedTo.Caption := ''; if not fSettingShortCut then begin Shortcut := ShortcutGet; with MainForm.actlMain do for i := 0 to ActionCount - 1 do if (TAction(Actions[i]).ShortCut = TextToShortCut(Shortcut)) and (Shortcut <> '') then lblShortCutAssignedTo.Caption := Actions[i].Name; end; end; procedure TOptionsDialog.ShortcutChanged; begin if not fSettingShortCut then fSettingsCopy.WriteString('Keyboard', lstKeyCmd.Items[lstKeyCmd.ItemIndex], ShortcutGet); end; function TOptionsDialog.ShortcutGet: String; begin if chkCtrl.Checked then Result := 'Ctrl+'; if chkShift.Checked then Result := Result + 'Shift+'; if chkAlt.Checked then Result := Result + 'Alt+'; if cmbShortCut.Items[cmbShortCut.ItemIndex] <> '' then Result := Result + cmbShortCut.Items[cmbShortCut.ItemIndex] else Result := ''; end; procedure TOptionsDialog.chkCtrlClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.chkShiftClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.chkAltClick(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; procedure TOptionsDialog.cmbShortCutChange(Sender: TObject); begin ShortcutAssigned; ShortcutChanged; end; function TOptionsDialog.GetClassNameFor(Extension: String): String; begin Result := ''; with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; if OpenKey(Extension, False) then begin Result := ReadString(''); CloseKey; end; finally Free; end; end; function TOptionsDialog.IsDefaultEditorOf(DocumentType: String): Boolean; var DefEditor, RegClass: String; Extensions: TStringList; i: Integer; begin Result := False; with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; Extensions := TStringList.Create; GetExtensions(lstDocTypes.Items.IndexOf(DocumentType) + 1, Extensions); for i := 0 to Extensions.Count -1 do begin RegClass := GetClassNameFor(Extensions[i]); if (RegClass <> '') and (OpenKey(RegClass + '\shell\open\command', False)) then begin DefEditor := ReadString(''); if i = 0 then Result := Pos(Application.ExeName, DefEditor) > 0 else Result := (Result) and (Pos(Application.ExeName, DefEditor) > 0); CloseKey; end; end; finally Free; end; end; function TOptionsDialog.IsInContextMenuOf(DocumentType: String): Boolean; var i: Integer; Extensions: TStringList; begin Result := False; with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; Extensions := TStringList.Create; GetExtensions(lstDocTypes.Items.IndexOf(DocumentType) + 1, Extensions); for i := 0 to Extensions.Count -1 do if i = 0 then Result := KeyExists(GetClassNameFor(Extensions[i]) + '\shell\Mystix') else Result := (Result) and (KeyExists(GetClassNameFor(Extensions[i]) + '\shell\Mystix')); finally Free; end; end; procedure TOptionsDialog.AddToSysContext(Index: Integer; Associate: Boolean); var RegIniFile: TRegIniFile; Extensions: TStringList; i: Integer; RegClass: String; begin RegIniFile := TRegIniFile.Create; with RegIniFile do try RootKey := HKEY_CLASSES_ROOT; Extensions := TStringList.Create; GetExtensions(Index, Extensions); for i := 0 to Extensions.Count - 1 do begin RegClass := GetClassNameFor(Extensions[i]); if Associate then begin if not KeyExists(RegClass + '\shell\Mystix') then begin CreateKey(RegClass + '\shell\Mystix'); WriteString(RegClass + '\shell\Mystix', '', '&Mystix'); WriteString(RegClass + '\shell\Mystix\command', '', '"' + Application.ExeName + '" "%1"'); end; end else TRegistry(RegIniFile).DeleteKey(RegClass + '\shell\Mystix'); end; finally Free; end; end; procedure TOptionsDialog.MakeDefaultEditor(Index: Integer; Associate: Boolean); var OldProgram: String; Extensions: TStringList; i: Integer; begin with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; Extensions := TStringList.Create; GetExtensions(Index, Extensions); for i := 0 to Extensions.Count - 1 do if OpenKey(GetClassNameFor(Extensions[i]) + '\shell\open\command', True) then begin if Associate then begin OldProgram := ReadString(''); if Pos(Application.ExeName, OldProgram) = 0 then begin WriteString('OldProgram', OldProgram); WriteString('', '"' + Application.ExeName + '" "%1"'); end; end else begin OldProgram := ReadString('OldProgram'); WriteString('', OldProgram); DeleteValue('OldProgram'); end; CloseKey; end; finally Free; end; end; procedure TOptionsDialog.GetExtensions(Index: Integer; Extensions: TStringList); var ExtStr: String; begin ExtStr := fSettingsCopy.ReadString('DocumentTypes', 'DocumentTypeExtensions' + IntToStr(Index), ''); ExtractStrings([';'], [#9, #32], PChar(ExtStr), Extensions); end; end.
unit MTSOptionsFormU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBCtrls, ActnList, StdCtrls, ComCtrls; type TMTSOptionsForm = class(TForm) Button1: TButton; Button2: TButton; ActionList1: TActionList; OK: TAction; AllUsersEditCustomer: TAction; PageControl1: TPageControl; TabSheet2: TTabSheet; GroupBox1: TGroupBox; Label2: TLabel; EditCustomerFieldsCheckBox: TCheckBox; EditCustomerEdit: TEdit; procedure OKExecute(Sender: TObject); procedure EditCustomerEditChange(Sender: TObject); procedure AllUsersEditCustomerExecute(Sender: TObject); private function GetEditCustomerRole: string; { Private declarations } public { Public declarations } property EditCustomerRole: string read GetEditCustomerRole; end; var MTSOptionsForm: TMTSOptionsForm; implementation uses ClientDataModuleU; {$R *.DFM} procedure TMTSOptionsForm.OKExecute(Sender: TObject); begin ModalResult := mrOk; end; procedure TMTSOptionsForm.EditCustomerEditChange(Sender: TObject); begin AllUsersEditCustomer.Checked := EditCustomerEdit.Text = ''; end; procedure TMTSOptionsForm.AllUsersEditCustomerExecute(Sender: TObject); begin if EditCustomerEdit.Text <> '' then AllUsersEditCustomer.Checked := not AllUsersEditCustomer.Checked else begin // Ignore the command and do not check the check box. AllUsersEditCustomer.Checked := not AllUsersEditCustomer.Checked; AllUsersEditCustomer.Checked := not AllUsersEditCustomer.Checked; end; end; function TMTSOptionsForm.GetEditCustomerRole: string; begin if AllUsersEditCustomer.Checked then Result := '' else Result := EditCustomerEdit.Text; end; initialization finalization MTSOptionsForm.Free; end.
unit Restore; interface uses System.SysUtils, System.Variants, System.Classes, FireDAC.Phys.FB, FireDAC.Phys.IBBase, FireDAC.Phys.IBWrapper, Vcl.StdCtrls, FireDAC.Phys, Migration; type TRestore = class procedure RestoreProgress(ASender: TFDPhysDriverService; const AMessage: string); procedure RestoreError(ASender, AInitiator: TObject; var AException: Exception); private FBDriverLink: TFDPhysFBDriverLink; Restore: TFDIBRestore; Log: TMemo; LogErrors: TMemo; public constructor Create(Config: TMigrationConfig); procedure Execute(Log, LogErrors: TMemo); destructor Destroy; end; implementation constructor TRestore.Create(Config: TMigrationConfig); begin FBDriverLink := TFDPhysFBDriverLink.Create(nil); FBDriverLink.Release; FBDriverLink.Embedded := true; FBDriverLink.VendorLib := Config.GetPathDestDll; Restore := TFDIBRestore.Create(nil); Restore.DriverLink := FBDriverLink; // Restore.Protocol := ipTCPIP; Restore.Options := [roReplace]; Restore.Statistics := [bsTime, bsDelta, bsReads, bsWrites]; Restore.Verbose := true; with Config.Dest do begin // Restore.Host := Host; // Restore.Port := Port; Restore.UserName := User; Restore.Password := Password; Restore.Database := Database; end; Restore.BackupFiles.Clear; Restore.BackupFiles.Add(Config.GetPathBackupFile); Restore.OnProgress := RestoreProgress; Restore.OnError := RestoreError; end; procedure TRestore.RestoreProgress(ASender: TFDPhysDriverService; const AMessage: string); begin if Log <> nil then begin Log.Lines.Add(AMessage); end; end; procedure TRestore.RestoreError(ASender, AInitiator: TObject; var AException: Exception); begin if LogErrors <> nil then begin LogErrors.Lines.Add(AException.Message); end; end; procedure TRestore.Execute(Log, LogErrors: TMemo); begin self.Log := Log; self.LogErrors := LogErrors; if Self.Log <> nil then begin with Self.Log.Lines do begin Add(''); Add('************* RESTORE *************'); Add(''); end; end; Restore.Restore; end; destructor TRestore.Destroy; begin FBDriverLink.Free; Restore.Free; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLPhongShader<p> An ARBvp1.0 + ARBfp1.0 shader that implements phong shading.<p> <b>History : </b><font size=-1><ul> <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>28/07/09 - DaStr - Small changes and simplifications <li>24/07/09 - DaStr - TGLShader.DoInitialize() now passes rci (BugTracker ID = 2826217) <li>20/03/07 - DaStr - Moved some of the stuff from TGLCustomAsmShader back here <li>25/02/07 - DaStr - Completely replaced with a descendant of TGLCustomAsmShader. <li>11/10/04 - SG - Creation. </ul></font> } unit GLPhongShader; interface {$I GLScene.inc } uses // VCL Classes, SysUtils, // GLScene GLTexture, GLVectorGeometry, GLVectorLists, OpenGLTokens, GLContext, GLAsmShader, GLRenderContextInfo, GLCustomShader, GLState; type TGLPhongShader = class(TGLCustomAsmShader) private FLightIDs: TIntegerList; FDesignTimeEnabled: Boolean; FAmbientPass: Boolean; procedure SetDesignTimeEnabled(const Value: Boolean); protected { Protected Declarations } procedure DoLightPass(lightID: Cardinal); virtual; procedure DoAmbientPass(var rci: TRenderContextInfo); virtual; procedure UnApplyLights(var rci: TRenderContextInfo); virtual; procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TRenderContextInfo): Boolean; override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ShaderSupported: Boolean; override; published { Published Declarations } property DesignTimeEnabled: Boolean read FDesignTimeEnabled write SetDesignTimeEnabled default False; end; implementation // DoApply // procedure TGLPhongShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); begin if (csDesigning in ComponentState) and not DesignTimeEnabled then Exit; GetActiveLightsList(FLightIDs); FAmbientPass := False; if FLightIDs.Count > 0 then begin rci.GLStates.DepthFunc := cfLEqual; rci.GLStates.Disable(stBlend); DoLightPass(FLightIDs[0]); FLightIDs.Delete(0); end else begin DoAmbientPass(rci); FAmbientPass := True; end; end; // DoUnApply // function TGLPhongShader.DoUnApply(var rci: TRenderContextInfo): Boolean; begin Result := False; if (csDesigning in ComponentState) and not DesignTimeEnabled then Exit; if FLightIDs.Count > 0 then begin UnApplyLights(rci); Result := True; Exit; end else if not FAmbientPass then begin Self.UnApplyShaderPrograms(); rci.GLStates.Enable(stBlend); rci.GLStates.SetBlendFunc(bfOne, bfOne); DoAmbientPass(rci); FAmbientPass := True; Result := True; Exit; end; rci.GLStates.DepthFunc := cfLEqual; end; // DoInitialize // procedure TGLPhongShader.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); begin if (csDesigning in ComponentState) and not DesignTimeEnabled then Exit; inherited; end; // SetDesignTimeEnabled // procedure TGLPhongShader.SetDesignTimeEnabled(const Value: Boolean); begin if Value <> FDesignTimeEnabled then begin FDesignTimeEnabled := Value; NotifyChange(Self); end; end; // Create // constructor TGLPhongShader.Create(AOwner: TComponent); begin inherited; with VertexProgram.Code do begin Add('!!ARBvp1.0'); Add('OPTION ARB_position_invariant;'); Add('PARAM mvinv[4] = { state.matrix.modelview.inverse };'); Add('PARAM mvit[4] = { state.matrix.modelview.invtrans };'); Add('PARAM lightPos = program.local[0];'); Add('TEMP light, normal, eye;'); Add(' ADD eye, mvit[3], -vertex.position;'); Add(' MOV eye.w, 0.0;'); Add(' DP4 light.x, mvinv[0], lightPos;'); Add(' DP4 light.y, mvinv[1], lightPos;'); Add(' DP4 light.z, mvinv[2], lightPos;'); Add(' ADD light, light, -vertex.position;'); Add(' MOV light.w, 0.0;'); Add(' MOV result.texcoord[0], vertex.normal;'); Add(' MOV result.texcoord[1], light;'); Add(' MOV result.texcoord[2], eye;'); Add('END'); end; with FragmentProgram.Code do begin Add('!!ARBfp1.0'); Add('PARAM lightDiff = program.local[0];'); Add('PARAM lightSpec = program.local[1];'); Add('PARAM materialDiff = state.material.diffuse;'); Add('PARAM materialSpec = state.material.specular;'); Add('PARAM shininess = state.material.shininess;'); Add('TEMP temp, light, normal, eye, R, diff, spec;'); Add(' DP3 temp, fragment.texcoord[0], fragment.texcoord[0];'); Add(' RSQ temp, temp.x;'); Add(' MUL normal, temp.x, fragment.texcoord[0];'); Add(' DP3 temp, fragment.texcoord[1], fragment.texcoord[1];'); Add(' RSQ temp, temp.x;'); Add(' MUL light, temp.x, fragment.texcoord[1];'); Add(' DP3 temp, fragment.texcoord[2], fragment.texcoord[2];'); Add(' RSQ temp, temp.x;'); Add(' MUL eye, temp.x, fragment.texcoord[2];'); Add(' DP3_SAT diff, normal, light;'); Add(' MUL diff, diff, lightDiff;'); Add(' MUL diff, diff, materialDiff;'); Add(' DP3 R, normal, light;'); Add(' MUL R, R.x, normal;'); Add(' MUL R, 2.0, R;'); Add(' ADD R, R, -light;'); Add(' DP3_SAT spec, R, eye;'); Add(' POW spec, spec.x, shininess.x;'); Add(' MUL spec, spec, lightDiff;'); Add(' MUL spec, spec, materialDiff;'); Add(' ADD_SAT result.color, diff, spec;'); Add(' MOV result.color.w, 1.0;'); Add('END'); end; FLightIDs := TIntegerList.Create; end; // ShaderSupported // function TGLPhongShader.ShaderSupported: Boolean; var MaxTextures: Integer; begin Result := inherited ShaderSupported and GL.ARB_multitexture; GL.GetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, @MaxTextures); Result := Result and (maxTextures > 2); end; // UnApplyLights // procedure TGLPhongShader.UnApplyLights(var rci: TRenderContextInfo); begin rci.GLStates.DepthFunc := cfLEqual; rci.GLStates.Enable(stBlend); rci.GLStates.SetBlendFunc(bfOne, bfOne); DoLightPass(FLightIDs[0]); FLightIDs.Delete(0); end; destructor TGLPhongShader.Destroy; begin FLightIDs.Free; inherited; end; procedure TGLPhongShader.DoAmbientPass(var rci: TRenderContextInfo); var ambient, materialAmbient: TVector; begin rci.GLStates.Disable(stLighting); GL.GetFloatv(GL_LIGHT_MODEL_AMBIENT, @ambient); GL.GetMaterialfv(GL_FRONT, GL_AMBIENT, @materialAmbient); ScaleVector(ambient, materialAmbient); GL.Color3fv(@ambient); end; procedure TGLPhongShader.DoLightPass(lightID: Cardinal); var LightParam: TVector; begin Self.ApplyShaderPrograms(); with CurrentGLContext.GLStates do begin GL.GetLightfv(GL_LIGHT0+lightID, GL_POSITION, @LightParam); LightParam := LightParam; GL.ProgramLocalParameter4fv(GL_VERTEX_PROGRAM_ARB, 0, @LightParam); LightParam := LightDiffuse[lightID]; GL.ProgramLocalParameter4fv(GL_FRAGMENT_PROGRAM_ARB, 0, @LightParam); LightParam := LightSpecular[lightID]; GL.ProgramLocalParameter4fv(GL_FRAGMENT_PROGRAM_ARB, 1, @LightParam); end; end; initialization RegisterClasses([TGLPhongShader]); end.
unit utils_DValue_JSON; // #34 " // #39 ' // #32 空格 // #58 : // #9 TAB interface uses utils_DValue, utils.strings; type TJsonParser = class(TObject) private FLastStrValue: String; FLastValue: String; end; function JSONParser(s: string; pvDValue: TDValue): Integer; function JSONEncode(v:TDValue): String; implementation function JSONParseEx(var ptrData: PChar; pvDValue: TDValue; pvParser: TJsonParser): Integer; forward; function JSONSkipSpaceAndComment(var ptrData: PChar; pvParser: TJsonParser): Integer;forward; function CreateIndentBlock(pvLevel: Integer; pvBlockSize: Integer = 4): String; var l:Integer; i: Integer; begin l := pvLevel * pvBlockSize; SetLength(Result, l); for i := Low(Result) to High(Result) do begin Result[i] := ' '; end; // fillchar有问题 UNICOPDE下面 //FillChar(Result[1], l, ' '); end; procedure JSONEncodeEx(v: TDValue; pvStringBuilder: TDStringBuilder; pvLevel: Integer); var i:Integer; lvIndentStr, lvChildIndentStr, lvName:String; begin lvIndentStr := CreateIndentBlock(pvLevel); lvChildIndentStr := CreateIndentBlock(pvLevel + 1); if v.ObjectType = vntObject then begin lvName := v.Name.AsString; if Length(lvName) <> 0 then begin pvStringBuilder.AppendQuoteStr(v.Name.AsString); pvStringBuilder.Append(':'); end; pvStringBuilder.AppendLine('{'); for i := 0 to v.Count - 1 do begin pvStringBuilder.Append(lvChildIndentStr); JSONEncodeEx(v.Items[i], pvStringBuilder, pvLevel + 1); if i < v.Count -1 then begin pvStringBuilder.Append(','); end; pvStringBuilder.Append(sLineBreak); end; pvStringBuilder.Append(lvIndentStr); pvStringBuilder.Append('}'); end else if v.ObjectType = vntArray then begin lvName := v.Name.AsString; if Length(lvName) <> 0 then begin pvStringBuilder.AppendQuoteStr(v.Name.AsString); pvStringBuilder.Append(':'); end; pvStringBuilder.AppendLine('['); for i := 0 to v.Count - 1 do begin pvStringBuilder.Append(lvChildIndentStr); JSONEncodeEx(v.Items[i], pvStringBuilder, pvLevel + 1); if i < v.Count -1 then begin pvStringBuilder.Append(','); end; pvStringBuilder.Append(sLineBreak); end; pvStringBuilder.Append(lvIndentStr); pvStringBuilder.Append(']'); end else if v.ObjectType = vntValue then begin if v.Name.AsString <> '' then begin pvStringBuilder.AppendQuoteStr(v.Name.AsString); pvStringBuilder.Append(':'); end; if v.Value.DataType in [vdtString, vdtStringW] then begin pvStringBuilder.AppendQuoteStr(v.AsString); end else begin pvStringBuilder.Append(v.AsString); end; end; end; function JSONParseName(var ptrData:PChar; pvParser:TJsonParser):Integer; var lvEndChar:Char; lvStart:PChar; begin if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ in ['"', ''''] then begin lvEndChar := ptrData^; inc(ptrData); lvStart := ptrData; while ptrData^ <> #0 do begin if ptrData^ = lvEndChar then begin pvParser.FLastStrValue := Copy(lvStart, 0, ptrData - lvStart); Inc(ptrData); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ <> ':' then begin Result := -1; Exit; end; Inc(ptrData); Result := 0; Exit; end else begin Inc(ptrData); end; end; Result := -1; Exit; end else begin lvStart := ptrData; while ptrData^ <> #0 do begin if ptrData^ in [':'] then begin pvParser.FLastStrValue := Copy(lvStart, 0, ptrData - lvStart); Inc(ptrData); Result := 0; Exit; end else if ptrData^ in [#32, #9, #13, #10] then // space, tab, \r, \n begin pvParser.FLastStrValue := Copy(lvStart, 0, ptrData - lvStart); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ <> ':' then begin Result := -1; Exit; end; Inc(ptrData); Result := 0; Exit; end else begin Inc(ptrData); end; end; Result := -1; Exit; end; end; function JSONParseValue(var ptrData: PChar; pvDValue: TDValue; pvParser: TJsonParser): Integer; var lvEndChar:Char; lvStart:PChar; begin pvParser.FLastStrValue := ''; pvParser.FLastValue := ''; if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ in ['"', ''''] then begin lvEndChar := ptrData^; inc(ptrData); lvStart := ptrData; while ptrData^ <> #0 do begin if ptrData^ = lvEndChar then begin pvDValue.Value.AsString := Copy(lvStart, 0, ptrData - lvStart); Inc(ptrData); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ in [',',']','}'] then begin Result := 1; Exit; end; Result := -1; exit; end else begin Inc(ptrData); end; end; Result := -1; Exit; end else if ptrData^ in ['{', '['] then begin JSONParseEx(ptrData, pvDValue, pvParser); Result := 5; end else begin lvStart := ptrData; while ptrData^ <> #0 do begin if ptrData^ in [',',']','}'] then begin pvDValue.Value.AsString := Copy(lvStart, 0, ptrData - lvStart); Result := 2; Exit; end else if ptrData^ in [#32, #9, #13, #10] then // space, tab, \r, \n begin pvDValue.Value.AsString := Copy(lvStart, 0, ptrData - lvStart); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ in [',',']','}'] then begin Result := 2; Exit; end; Result := -1; Exit; end else begin Inc(ptrData); end; end; Result := -1; Exit; end; end; function JSONParseEx(var ptrData: PChar; pvDValue: TDValue; pvParser: TJsonParser): Integer; var lvEndChar:Char; lvChild:TDValue; r:Integer; begin if ptrData^ in ['{', '['] then begin if ptrData^ = '{' then begin pvDValue.CheckSetNodeType(vntObject); lvEndChar := '}'; Result := 1; end else if ptrData^ = '[' then begin pvDValue.CheckSetNodeType(vntArray); lvEndChar := ']'; Result := 2; end; Inc(ptrData); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; while (ptrData^ <> #0) and (ptrData^ <> lvEndChar) do begin if (ptrData^ <> lvEndChar) then begin if pvDValue.ObjectType = vntArray then begin lvChild := pvDValue.AddArrayChild; end else begin lvChild := pvDValue.Add; end; if JSONParseEx(ptrData, lvChild, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ = ',' then begin Inc(ptrData); if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; end; end else // 解析完成 Exit; end; if JSONSkipSpaceAndComment(ptrData, pvParser) = -1 then begin Result := -1; exit; end; if ptrData^ <> lvEndChar then begin Result := -1; Exit; end; Inc(ptrData); JSONSkipSpaceAndComment(ptrData, pvParser); end else if (pvDValue.Parent <> nil) then begin if (pvDValue.Parent.ObjectType = vntObject) and (pvDValue.Name.DataType in [vdtNull, vdtUnset]) then begin if JSONParseName(ptrData, pvParser) = -1 then begin Result := -1; Exit; end else begin pvDValue.Name.AsString := pvParser.FLastStrValue; Result := JSONParseValue(ptrData, pvDValue, pvParser); Exit; end; end else if pvDValue.Parent.ObjectType = vntArray then begin Result := JSONParseValue(ptrData, pvDValue, pvParser); Exit; end else begin // must be vntArray, vntObject(vdtNull, vdtUnset can convert to object) Result := -1; Exit; end; end else begin pvDValue.CheckSetNodeType(vntNull); Result := -1; end; end; function JSONSkipSpaceAndComment(var ptrData: PChar; pvParser: TJsonParser): Integer; begin Result := 0; SkipChars(ptrData, [#10, #13, #9, #32]); while ptrData^ = '/' do begin if ptrData[1] = '/' then begin SkipUntil(ptrData, [#10]); SkipChars(ptrData, [#10, #13, #9, #32]); end else if ptrData[1] = '*' then begin Inc(ptrData, 2); while ptrData^ <> #0 do begin if (ptrData[0] = '*') and (ptrData[1] = '/') then begin Inc(ptrData, 2); SkipChars(ptrData, [#10, #13, #9, #32]); Break; end else Inc(ptrData); end; end else begin Result := -1; Exit; end; end; end; function JSONParser(s: string; pvDValue: TDValue): Integer; var ptrData:PChar; j:Integer; lvParser:TJsonParser; begin Result := -1; ptrData := PChar(s); lvParser := TJsonParser.Create; try j := JSONSkipSpaceAndComment(ptrData, lvParser); if j = -1 then begin Exit; end; if (ptrData ^ in ['{', '[']) then begin JSONParseEx(ptrData, pvDValue, lvParser); Result := 0; end; finally lvParser.Free; end; end; function JSONEncode(v:TDValue): String; var lvSB:TDStringBuilder; begin lvSB := TDStringBuilder.Create; try JSONEncodeEx(v, lvSB, 0); Result := lvSB.ToString(); finally lvSB.Free; end; end; end.
unit fAllgyBox; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fRptBox, StdCtrls, ExtCtrls, ComCtrls, fARTAllgy, ORFn, VA508AccessibilityManager, Vcl.Menus, U_CPTEditMonitor; type TfrmAllgyBox = class(TfrmReportBox) cmdEdit: TButton; cmdAdd: TButton; cmdInError: TButton; procedure cmdAddClick(Sender: TObject); procedure cmdEditClick(Sender: TObject); procedure cmdInErrorClick(Sender: TObject); private { Private declarations } FAllergyIEN: integer; procedure RefreshText; public { Public declarations } end; procedure AllergyBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; AllergyIEN: integer); var frmAllgyBox: TfrmAllgyBox; implementation {$R *.dfm} uses rCover, rODAllergy, uCore; const NEW_ALLERGY = True; ENTERED_IN_ERROR = True; function CreateAllergyBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean): TfrmAllgyBox; var i, AWidth, MaxWidth, AHeight: Integer; Rect: TRect; // %$@# buttons! BtnArray: array of TButton; BtnRight: array of integer; BtnLeft: array of integer; j, k: integer; x: string; begin Result := TfrmAllgyBox.Create(Application); try with Result do begin k := 0; with pnlButton do for j := 0 to ControlCount - 1 do if Controls[j] is TButton then begin SetLength(BtnArray, k+1); SetLength(BtnRight, k+1); BtnArray[j] := TButton(Controls[j]); BtnRight[j] := ResizeWidth(Font, MainFont, BtnArray[j].Width - BtnArray[j].Width - BtnArray[j].Left); k := k + 1; end; MaxWidth := 350; for i := 0 to ReportText.Count - 1 do begin AWidth := lblFontTest.Canvas.TextWidth(ReportText[i]); if AWidth > MaxWidth then MaxWidth := AWidth; end; MaxWidth := MaxWidth + GetSystemMetrics(SM_CXVSCROLL); AHeight := (ReportText.Count * (lblFontTest.Height + 2)) + pnlbutton.Height; AHeight := HigherOf(AHeight, 250); if AHeight > (Screen.Height - 80) then AHeight := Screen.Height - 80; if MaxWidth > Screen.Width then MaxWidth := Screen.Width; ClientWidth := MaxWidth; ClientHeight := AHeight; Rect := BoundsRect; ForceInsideWorkArea(Rect); BoundsRect := Rect; ResizeAnchoredFormToFont(Result); //CQ6889 - force Print & Close buttons to bottom right of form regardless of selected font size cmdClose.Left := (pnlButton.Left+pnlButton.Width)-cmdClose.Width; cmdPrint.Left := (cmdClose.Left-cmdPrint.Width) - 1; //end CQ6889 Constraints.MinWidth := cmdAdd.Width + cmdEdit.Width + cmdInError.Width + cmdPrint.Width + cmdClose.Width + 20; Constraints.MinHeight := 2*pnlButton.Height + memReport.Height; cmdAdd.Left := 1; cmdEdit.Left := (cmdAdd.Left + cmdAdd.Width) + 1; cmdInError.Left := (cmdEdit.Left + cmdEdit.Width) + 1; SetLength(BtnLeft, k); for j := 0 to k - 1 do BtnLeft[j] := pnlButton.Width - BtnArray[j].Width - BtnRight[j]; QuickCopy(ReportText, memReport); for i := 1 to Length(ReportTitle) do if ReportTitle[i] = #9 then ReportTitle[i] := ' '; Caption := ReportTitle; memReport.SelStart := 0; cmdPrint.Visible := AllowPrint; cmdAdd.Enabled := True; //IsARTClinicalUser(x); v26.12 cmdEdit.Enabled := IsARTClinicalUser(x); cmdInError.Enabled := IsARTClinicalUser(x); end; except if assigned(Result) then Result.Free; raise; end; end; procedure AllergyBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; AllergyIEN: integer); begin frmAllgyBox := CreateAllergyBox(ReportText, ReportTitle, AllowPrint); try with frmAllgyBox do begin FAllergyIEN := AllergyIEN; if not ContainsVisibleChar(memReport.Text) then RefreshText; ShowModal; end; finally frmAllgyBox.Release; end; end; procedure TfrmAllgyBox.cmdAddClick(Sender: TObject); begin inherited; Visible := False; EnterEditAllergy(0, NEW_ALLERGY, not ENTERED_IN_ERROR); Close; end; procedure TfrmAllgyBox.cmdEditClick(Sender: TObject); var Changed: boolean; begin inherited; Visible := False; Changed := EnterEditAllergy(FAllergyIEN, not NEW_ALLERGY, not ENTERED_IN_ERROR); if Changed then RefreshText; Visible := True; end; procedure TfrmAllgyBox.cmdInErrorClick(Sender: TObject); begin inherited; Visible := False; MarkEnteredInError(FAllergyIEN); Close; end; procedure TfrmAllgyBox.RefreshText; begin memReport.Clear; QuickCopy(DetailAllergy(FAllergyIEN), memReport); end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 70 O(LgN) Ternary Search } program CounterfeitCoin; var N, L, R, St : Integer; S : string; Re : Extended; I, J : Integer; procedure ReadInput; begin Write('Enter n? '); Readln(N); end; procedure Solve; begin St := 0; Re := N; while Re > 1 do begin Inc(St); Re := Re / 3; end; Writeln('Minimum number of comparisons = ', St); L := 1; R := N; St := 0; while L < R do begin Inc(St); Write(St, ': compare {', L); I := L; for I := L + 1 to L + (R - L) div 3 do Write(',', I); Inc(I); J := I; Write('} and {', I); for J := I + 1 to I + (R - L) div 3 do Write(',', J); Write('}. (<=>)? '); Readln(S); if (Length(S) > 1) or (S = '') then begin Writeln('Error'); Halt; end; case S[1] of '<' : R := L + (R - L) div 3; '>' : begin L := L + (R - L) div 3 + 1; R := J; end; '=' : L := J + 1; else begin Writeln('Error'); Halt; end; end; end; Writeln('Coin #', R, ' is counterfeit.'); end; begin ReadInput; Solve; end.
unit Reversi; //------------------------------------------------------------------ // Othello game (Version 1.0) // Author: Roman Podobedov // Email: romka@ut.ee // http://romka.demonews.com // // Delphi translation by vlad@ifrance.com 10.2000 //------------------------------------------------------------------ interface type sPosData= record // Information about current position corner: boolean; // Is corner seized? square2x2: boolean; // Is square 2x2 at the corners seized? edge: boolean; stable: integer; // Number of stable disks internal: integer; // Number of internal disks disks: integer; // Total disks mx, my: integer; // This move coordinates x and y end; tBoard= array[0..7,0..7] of byte; pBoard= ^tBoard; function CalculateData(cc: byte; cx, cy: integer): sPosData; function CheckMove(color:byte; cx, cy: integer): integer; function DoStep(data: pBoard): word; implementation var brd, brd2, brd3: tBoard; function CalculateData(cc: byte; cx, cy: integer): sPosData; // Calculate data about current position // Parameter: cc - Who do move, black or white? // if (cc == 1) White makes a move // if (cc == 2) Black makes a move var data: sPosData; i, j: integer; intern: boolean; begin data.corner:= FALSE; data.disks:= 0; data.internal:= 0; data.stable:= 0; data.square2x2:= FALSE; data.edge:= FALSE; data.mx:= cx; data.my:= cy; // make a copy of the board and calculate the sum of disks for i:=0 to 7 do for j:=0 to 7 do begin brd3[i,j]:= brd2[i,j]; if brd2[i,j]= cc then inc(data.disks); end; // Fill the "corner" data if ((cy=0) and (cx=0)) or ((cy=0) and (cx=7)) or ((cy=7) and (cx=0)) or ((cy=7) and (cx=7)) then data.corner:= TRUE; // Fill the "square2x2" data if ((cy<=1) and (cx<=1)) or ((cy<=1) and (cx>=6)) or ((cy>=6) and (cx<=1)) or ((cy>=6) and (cx>=6)) then data.square2x2:= TRUE; // Fill the "edge" data if (cy=0) or (cx=0) or (cy=7) or (cx=7) then data.edge:= TRUE; // Calculate number of stable discs for i:=0 to 7 do // Left-Upper corner begin if brd3[i,0] <> cc then break; for j:=0 to 7 do begin if brd3[i,j] <> cc then break; inc(data.stable); brd3[i,j]:= 0; end; end; for i:=7 downto 0 do // Left-Lower corner begin if brd3[i,0] <> cc then break; for j:=0 to 7 do begin if brd3[i,j] <> cc then break; inc(data.stable); brd3[i,j]:= 0; end; end; for i:=7 downto 0 do // Right-Bottom corner begin if brd3[i,7] <> cc then break; for j:=7 downto 0 do begin if brd3[i,j] <> cc then break; inc(data.stable); brd3[i,j]:= 0; end; end; for i:=0 to 7 do // Right-Upper corner begin if brd3[i,7] <> cc then break; for j:=7 downto 0 do begin if brd3[i,j] <> cc then break; inc(data.stable); brd3[i,j]:= 0; end; end; // Calculate number of internal discs for i:=0 to 7 do for j:=0 to 7 do if brd2[i,j] = cc then begin intern:= TRUE; if (i>0) and (j>0) and (brd[i-1, j-1]=0) then intern:= FALSE; if (i>0) and (brd[i-1, j]=0) then intern:= FALSE; if (i>0) and (j<7) and (brd[i-1, j+1]=0) then intern:= FALSE; if (i<7) and (j>0) and (brd[i+1, j-1]=0) then intern:= FALSE; if (i<7) and (brd[i+1, j]=0) then intern:= FALSE; if (i<7) and (j<7) and (brd[i+1, j+1]=0) then intern:= FALSE; if (j>0) and (brd[i, j-1]=0) then intern:= FALSE; if (j<7) and (brd[i, j+1]=0) then intern:= FALSE; if intern then inc(data.internal); end; result:=data; end; function CheckMove(color:byte; cx, cy: integer): integer; // Function check: is move to (cx, cy) possible? // Parameter: color - Who makes the move, black or white? // if (colour == 0) White do a move // if (colour == 1) Black do a move // return: 0 - if impossible // 1.. - if possible, and number // value is amount of the seized disks var test, passed: boolean; i, j, total: integer; wc1, wc2: byte; // What to check begin total:=0; // do a copy of board for i:=0 to 7 do for j:=0 to 7 do brd2[i, j]:= brd[i, j]; if color=0 then //white begin wc1:= 2; wc2:= 1; end else begin wc1:= 1; wc2:= 2; end; if brd[cy, cx]<> 0 then begin result:= 0; exit; end; passed:= FALSE; test:= FALSE; for i:=cx-1 downto 0 do // Check left begin if brd[cy, i] = wc1 then test:= TRUE else if ((brd[cy, i] = wc2) and (test)) then begin passed:= TRUE; for j:=cx-1 downto i+1 do inc(total); for j:=cx-1 downto i+1 do brd2[cy, j]:= wc1; ////??????? break; end else break; end; test:= FALSE; for i:=cx+1 to 7 do // Check Right begin if (brd[cy, i] = wc1) then test:= TRUE else if ((brd[cy, i] = wc2) and test) then begin passed:= TRUE; for j:=cx+1 to i-1 do inc(total); for j:=cx+1 to i-1 do brd2[cy, j]:= wc1; break; end else break; end; test:= FALSE; for i:=cy-1 downto 0 do // Check Up begin if (brd[i, cx] = wc1) then test:= TRUE else if ((brd[i, cx] = wc2) and test) then begin passed:= TRUE; for j:=cy-1 downto i+1 do inc(total); for j:=cy-1 downto i+1 do brd2[j, cx]:= wc1; break; end else break; end; test:= FALSE; for i:=cy+1 to 7 do // Check Down begin if (brd[i, cx] = wc1) then test:= TRUE else if ((brd[i, cx] = wc2) and (test)) then begin passed:= TRUE; for j:=cy+1 to i-1 do inc(total); for j:=cy+1 to i-1 do brd2[j, cx]:= wc1; break; end else break; end; test:= FALSE; for i:=1 to 7 do // Check Left-Up begin if (((cy-i) >= 0) and ((cx-i) >= 0)) then if (brd[cy-i, cx-i] = wc1) then test:= TRUE else if ((brd[cy-i, cx-i] = wc2) and (test)) then begin passed:= TRUE; for j:=1 to i-1 do inc(total); for j:=1 to i-1 do brd2[cy-j, cx-j]:= wc1; break; end else break else break; end; test:= FALSE; for i:=1 to 7 do // Check Left-Down begin if (((cy+i) < 8) and ((cx-i) >= 0)) then if (brd[cy+i, cx-i] = wc1) then test:= TRUE else if ((brd[cy+i, cx-i] = wc2) and (test)) then begin passed:= TRUE; for j:=1 to i-1 do inc(total); for j:=1 to i-1 do brd2[cy+j, cx-j]:= wc1; break; end else break else break; end; test:= FALSE; for i:=1 to 7 do // Check Right-Up begin if (((cy-i) >= 0) and ((cx+i) < 8)) then if (brd[cy-i, cx+i] = wc1) then test:= TRUE else if ((brd[cy-i, cx+i] = wc2) and (test)) then begin passed:= TRUE; for j:=1 to i-1 do inc(total); for j:=1 to i-1 do brd2[cy-j, cx+j]:= wc1; break; end else break else break; end; test:= FALSE; for i:=1 to 7 do // Check Right-Down begin if (((cy+i) < 8) and ((cx+i) < 8)) then if (brd[cy+i, cx+i] = wc1) then test:= TRUE else if ((brd[cy+i, cx+i] = wc2) and (test)) then begin passed:= TRUE; for j:=1 to i-1 do inc(total); for j:=1 to i-1 do brd2[cy+j, cx+j]:= wc1; break; end else break else break; end; if passed then result:= total else result:=0; end; function DoStep(data: pBoard): word; // Function to do a single step // Parameter data - a pointer to game board // Return value WORD: low unsigned char contains x coordinate of move // high unsigned char contains y coordinate of move // if return value contains 0xFFFF then no move var i, j, k, l, value, value1, value2, value3: integer; pd, pdb, savedData: sPosData; fMove, fMoveb: boolean; // First move? begin for i:=0 to 7 do // Copy data from source data to brd for j:=0 to 7 do brd[j,i]:= data^[j,i]; fMove:= TRUE; for i:=0 to 7 do for j:=0 to 7 do begin if (CheckMove(0, j, i) > 0) then begin pd:= CalculateData(1, j, i); fMoveb:= TRUE; value:= 0; for k:=0 to 7 do for l:=0 to 7 do if (CheckMove(1, l, k) > 0) then begin pdb:= CalculateData(2, l, k); if pdb.corner then value3:=200 else value3:=0; value3:=value3+pdb.stable*4; value3:=value3+pdb.internal*3; //value3:=value3+pdb.disks; //if pdb.edge then value3:=value3+ 1; if pdb.square2x2 then value3:=value3-50; if fMoveb then begin value:= value3; fMoveb:= FALSE; end else if (value3 > value) then value:= value3; end; if fMove then begin savedData:= pd; fMove:= FALSE; end else begin if pd.corner then value1:=200 else value1:=0; value1:=value1+ pd.stable*5; value1:=value1+ pd.internal*3; value1:=value1+ pd.disks; if pd.edge then value1:=value1+ 1; if pd.square2x2 then value1:=value1- 50; value1:=value1- value; if savedData.corner then value2:=200 else value2:=0; value2:=value2+ savedData.stable*5; value2:=value2+ savedData.internal*3; value2:=value2+ savedData.disks; if savedData.edge then value2:=value2+ 1; if savedData.square2x2 then value2:=value2-50; if (value1 > value2) then move(pd,savedData,sizeof(sposdata)); //savedData:= pd; end; end; end; if not fMove then result:=savedData.my * 256 + savedData.mx else result:=65535; end; end.
unit JAToyStarSystem; {$mode objfpc}{$H+} {$i JA.inc} interface uses {amiga} exec, agraphics, JATypes, JAMath, JAPalette, JARender, JASpatial, JANode, JAScene, JASketch, JAPolygon, JAPolygonTools, JAToy; type TJAToyStarSystem = record Scene : PJAScene; Bodies : array[0..4] of PJANode; end; PJAToyStarSystem = ^TJAToyStarSystem; function JAToyStarSystemCreate(AScene : PJAScene; AParentNode : PJANode) : PJAToyStarSystem; function JAToyStarSystemDestroy(AToyStarSystem : PJAToyStarSystem) : boolean; function JAToyStarSystemUpdate(AToyStarSystem : PJAToyStarSystem; ADelta : Float32) : Float32; function JASceneGenerateBackgroundStars(AScene : PJAScene) : Float32; function JASceneRenderBackgroundStars(AScene : PJAScene) : Float32; implementation function JAToyStarSystemCreate(AScene : PJAScene; AParentNode : PJANode) : PJAToyStarSystem; var I : SInt16; Polygon : PJAPolygon; Node,NodePrevious : PJANode; BodyOrbit : Float32; BodyRadius : Float32; begin Result := JAMemGet(SizeOf(TJAToyStarSystem)); NodePrevious := AParentNode; BodyOrbit := 0; BodyRadius := 20; with Result^ do begin Scene := AScene; for I := 0 to high(Bodies) do begin Node := JANodeNodeCreate(NodePrevious, JANode_Sketch); if I=0 then BodyOrbit := 0 else if I=1 then BodyOrbit := 300 else if I=2 then BodyOrbit := 100 else BodyOrbit /= 2; if I=0 then BodyRadius := 50 else BodyRadius /= 2.0; BodyOrbit -= (BodyOrbit/15)*I; JANodeSetLocalPosition(Node, vec2(BodyOrbit,0)); //Node^.Spatial.LocalVelocityRotation := 0; //JANodeSetLocalRotation(Node, 45); Bodies[I] := Node; NodePrevious := Node; Polygon := JASketchPolygonCreate(PJANodeDataSketch(Node^.Data)^.Sketch); JAPolygonMakeCircle(Polygon,vec2(0,0),BodyRadius, 8); Node^.Spatial.LocalBRadius := BodyRadius; {$IFDEF JA_ENABLE_SHADOW} Polygon^.ShadowCast := true; {$ENDIF} case I of 0 : Polygon^.Style.PenIndex := Palette^.PenYellow; 1 : Polygon^.Style.PenIndex := Palette^.PenGreen; 2 : Polygon^.Style.PenIndex := Palette^.PenBlue; 3 : Polygon^.Style.PenIndex := Palette^.PenRed; 4 : Polygon^.Style.PenIndex := Palette^.PenGrey; end; end; Bodies[0]^.Spatial.LocalVelocityRotation := -1; JANodeSetLocalPosition(Bodies[0], Vec2(0, 0)); end; end; function JAToyStarSystemDestroy(AToyStarSystem : PJAToyStarSystem) : boolean; var I : SInt16; begin with AToyStarSystem^ do begin //JANodeDestroy(Bodies[0]); //JANodeNodeDestroy(Scene^.RootNode, Bodies[0]); end; JAMemFree(AToyStarSystem,SizeOf(TJAToyStarSystem)); Result := true; end; function JAToyStarSystemUpdate(AToyStarSystem : PJAToyStarSystem; ADelta : Float32) : Float32; var I : SInt16; begin Result := 0; with AToyStarSystem^ do begin for I := 0 to high(Bodies) do begin JANodeSetLocalRotation(Bodies[I], Bodies[I]^.Spatial.LocalRotation + (30*(I*I+1))*ADelta); end; end; end; function JASceneRenderBackgroundStars(AScene : PJAScene) : Float32; var I : SInt32; Pixel : TVec2SInt16; StarHigh : SInt16; begin {StarHigh := high(AScene^.BackgroundStars); for I := 0 to StarHigh do begin Pixel.X := round(JARenderMVP._00*AScene^.BackgroundStars[I].X + JARenderMVP._01*AScene^.BackgroundStars[I].Y + JARenderMVP._02); Pixel.Y := round(JARenderMVP._10*AScene^.BackgroundStars[I].X + JARenderMVP._11*AScene^.BackgroundStars[I].Y + JARenderMVP._12); {reject any offscreen pixels} //if (Pixel.X >= 0) and (Pixel.X <= 320) and (Pixel.Y >= 0) and (Pixel.Y <= 200) then WritePixel(JARenderRasterPort, Pixel.X, Pixel.Y); //JARenderPixel(Vec2(AScene^.BackgroundStars[I].X,AScene^.BackgroundStars[I].Y)); end; } Result := 0; end; function JASceneGenerateBackgroundStars(AScene : PJAScene) : Float32; var I : SInt32; Vec : TVec2; begin {for I := 0 to high(AScene^.BackgroundStars) do begin Vec := Vec2Rotate((Vec2Up * Random) * 2000, Random * 360); AScene^.BackgroundStars[I].X := trunc(Vec.X); AScene^.BackgroundStars[I].Y := trunc(Vec.Y); end; } Result := 0; end; end.
unit RecipientSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, System.Rtti, ADODB, RzButton; type TfrmRecipientSearch = class(TfrmBaseSearch) procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } protected { Protected declarations } procedure SearchList; override; procedure SetReturn; override; procedure Add; override; procedure Cancel; override; end; var frmRecipientSearch: TfrmRecipientSearch; implementation uses EntitiesData, Recipient, AppConstants; {$R *.dfm} procedure TfrmRecipientSearch.SearchList; var filter: string; begin inherited; if Trim(edSearchKey.Text) <> '' then filter := 'name like ''*' + edSearchKey.Text + '*''' else filter := ''; grSearch.DataSource.DataSet.Filter := filter; end; procedure TfrmRecipientSearch.SetReturn; begin with grSearch.DataSource.DataSet do begin rcp.Id := FieldByName('entity_id').AsString; rcp.Name := FieldByName('name').AsString;; end; end; procedure TfrmRecipientSearch.Add; begin end; procedure TfrmRecipientSearch.Cancel; begin end; procedure TfrmRecipientSearch.FormCreate(Sender: TObject); begin inherited; dmEntities := TdmEntities.Create(self); (grSearch.DataSource.DataSet as TADODataSet).Parameters.ParamByName('@entity_type').Value := TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.RP); inherited; end; end.
unit JAShadow; {$mode objfpc}{$H+} interface uses sysutils, math, JATypes, JAGlobal, JAMath, JAPolygon, JARender; function JAPolygonShadowVertexAdd(APolygon : PJAPolygon) : PVec2SInt16; function JAPolygonShadowPenumbra0VertexAdd(APolygon : PJAPolygon) : PVec2SInt16; function JAPolygonShadowPenumbra1VertexAdd(APolygon : PJAPolygon) : PVec2SInt16; procedure JAPolygonShadowGenerate(APolygon: PJAPolygon; AShadowIndex : SInt16; APolygonPosition : TVec2; ALightPosition : TVec2; ALightRadius : Float32; AViewMatrix : TMat3; ClipRect : TJRectSInt16); implementation function JAPolygonShadowVertexAdd(APolygon : PJAPolygon): PVec2SInt16; var NewCapacity : SInt32; begin NewCapacity := APolygon^.ShadowVertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (APolygon^.ShadowVertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>APolygon^.ShadowVertexCapacity then begin if APolygon^.ShadowVertexCapacity=0 then begin APolygon^.ShadowVertex := JAMemGet(SizeOf(TVec2SInt16)*NewCapacity); end else begin APolygon^.ShadowVertex := reallocmem(APolygon^.ShadowVertex, SizeOf(TVec2SInt16)*NewCapacity); end; APolygon^.ShadowVertexCapacity := NewCapacity; end; Result := @APolygon^.ShadowVertex[APolygon^.ShadowVertexCount]; APolygon^.ShadowVertexCount += 1; end; function JAPolygonShadowPenumbra0VertexAdd(APolygon: PJAPolygon): PVec2SInt16; var NewCapacity : SInt32; begin NewCapacity := APolygon^.ShadowPenumbra0VertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (APolygon^.ShadowPenumbra0VertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>APolygon^.ShadowPenumbra0VertexCapacity then begin if APolygon^.ShadowPenumbra0VertexCapacity=0 then begin APolygon^.ShadowPenumbra0Vertex := JAMemGet(SizeOf(TVec2SInt16)*NewCapacity); end else begin APolygon^.ShadowPenumbra0Vertex := reallocmem(APolygon^.ShadowPenumbra0Vertex, SizeOf(TVec2SInt16)*NewCapacity); end; APolygon^.ShadowPenumbra0VertexCapacity := NewCapacity; end; Result := @APolygon^.ShadowPenumbra0Vertex[APolygon^.ShadowPenumbra0VertexCount]; APolygon^.ShadowPenumbra0VertexCount += 1; end; function JAPolygonShadowPenumbra1VertexAdd(APolygon: PJAPolygon): PVec2SInt16; var NewCapacity : SInt32; begin NewCapacity := APolygon^.ShadowPenumbra1VertexCapacity; if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else if (APolygon^.ShadowPenumbra1VertexCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize; if NewCapacity<>APolygon^.ShadowPenumbra1VertexCapacity then begin if APolygon^.ShadowPenumbra1VertexCapacity=0 then begin APolygon^.ShadowPenumbra1Vertex := JAMemGet(SizeOf(TVec2SInt16)*NewCapacity); end else begin APolygon^.ShadowPenumbra1Vertex := reallocmem(APolygon^.ShadowPenumbra1Vertex, SizeOf(TVec2SInt16)*NewCapacity); end; APolygon^.ShadowPenumbra1VertexCapacity := NewCapacity; end; Result := @APolygon^.ShadowPenumbra1Vertex[APolygon^.ShadowPenumbra1VertexCount]; APolygon^.ShadowPenumbra1VertexCount += 1; end; procedure JAPolygonShadowGenerate(APolygon: PJAPolygon; AShadowIndex: SInt16; APolygonPosition: TVec2; ALightPosition: TVec2; ALightRadius: Float32; AViewMatrix: TMat3; ClipRect: TJRectSInt16); var I,J : SInt32; AVec,Vec1 : TVec2; ANormal : TVec2; A,B : TVec2; VecCount : SInt16; Angle0,Angle1,F0 : Float32; LightVector : TVec2; {From the centre of the light to the current polygon vertex} LightDirection : TVec2; {Normalized LightVector} EdgeVector : TVec2; {Vector of Face} UmbraVector : TVec2; {Inner Edge} PenumbraVector : TVec2; {Outer Edge} UmbraDirection : TVec2; {Normalized UmbraVector} PenumbraDirection : TVec2; {Normalized PenumbraVector} FaceBack, FaceBackPrevious : boolean; UmbraPrevious : TVec2; {To save having to calculate it during fin movement} BackIndex : SInt32; Intersect : TVec2; AShadow : PJAPolygonShadow; ShadowHullStart, ShadowHullEnd : TVec2SInt16; ShadowHullStartSide, ShadowHullEndSide : TJRectSide; Penumbra0Start : TVec2SInt16; Penumbra1Start : TVec2SInt16; Penumbra0StartSide, Penumbra1StartSide : TJRectSide; Penumbra0HotFin : SInt16; Penumbra1HotFin : SInt16; Penumbra0FinVectors : array[0..3] of TVec2; Penumbra1FinVectors : array[0..3] of TVec2; procedure CalcultePolygonVertex(AVertexIndex : SInt32); begin LightVector := ALightPosition - APolygon^.WorldVertex[AVertexIndex]; LightDirection := Vec2Normalize(LightVector); {Umbra and Penumbra Vector Calculation} {Get Perpendicular Vector} AVec.Y := -LightDirection.X; AVec.X := LightDirection.Y; {Get Poly Centre to Vertex Vector} ANormal := Vec2Normalize(APolygon^.WorldVertex[AVertexIndex]-APolygonPosition); {Ensure Correct Orientation of Vector} if (Vec2Dot(ANormal, AVec) < 0) then AVec := -AVec; {Scale the perpendicular vector by the radius of the light} AVec *= ALightRadius; UmbraVector := LightVector + AVec; PenumbraVector := LightVector + (-Avec); UmbraDirection := Vec2Normalize(UmbraVector); PenumbraDirection := Vec2Normalize(PenumbraVector); {Get Face Normal} EdgeVector := APolygon^.WorldVertex[AVertexIndex]-APolygon^.WorldVertex[(AVertexIndex+1) mod APolygon^.VertexCount]; ANormal.Y := -EdgeVector.X; ANormal.X := EdgeVector.Y; ANormal := Vec2Normalize(ANormal); {Determine if Face is Pointing backwards from Outer Edge of the Light (UmbraDirection)} FaceBack := (Vec2Dot(ANormal, PenumbraDirection) < 0); end; begin if (APolygon^.VertexCount <= 1) then exit; {if JAPolygonIntersectVertex(APolygon, ALightPosition) then begin {Don't generate shadow for the polygon if the light is inside the polygon} APolygon^.ShadowVertexCount := 0; exit; end; } AShadow := @APolygon^.Shadows[AShadowIndex]; with AShadow^ do begin {Find backfacing edges and shadow start and end indices} ShadowVertexStart := -1; ShadowVertexEnd := -1; FaceBack := false; FaceBackPrevious := false; Penumbra0HotFin := 1000; Penumbra1HotFin := 1000; CalcultePolygonVertex(APolygon^.VertexCount-1); {Find Back-facing Boundry Indices} for I := 0 to APolygon^.VertexCount-1 do begin {Set High as default} FaceBackPrevious := FaceBack; UmbraPrevious := UmbraVector; {store the previous umbra for later use} CalcultePolygonVertex(I); if (ShadowVertexStart = -1) and not FaceBackPrevious and FaceBack then begin {Store State} ShadowVertexStart := I; StartUmbra := -UmbraVector*10; StartPenumbra := -PenumbraVector*10; ShadowPenumbra0Index := I; {Snap Umbra Edge to Face Edge if overlapping Face Edge} Angle0 := Vec2Angle(StartPenumbra, -EdgeVector); Angle1 := Vec2Angle(StartPenumbra, StartUmbra); if (Angle1 < Angle0) then begin StartUmbra := -EdgeVector; ShadowVertexStart := JRepeat(I+1,0,APolygon^.VertexCount-1); {Move the shadow backwards} {Calculate Next Umbra} LightVector := ALightPosition - APolygon^.WorldVertex[ShadowVertexStart]; LightDirection := Vec2Normalize(LightVector); {Umbra and Penumbra Vector Calculation} {Get Perpendicular Vector} AVec.Y := -LightDirection.X; AVec.X := LightDirection.Y; {Scale the perpendicular vector by the radius of the light} AVec *= ALightRadius; {Get Poly Centre to Vertex Vector} ANormal := Vec2Normalize(APolygon^.WorldVertex[ShadowVertexStart]-APolygonPosition); {Ensure Correct Orientation of Vector} if (Vec2Dot(ANormal, AVec) < 0) then AVec := -AVec; UmbraVector := LightVector + AVec; Startumbra := -UmbraVector*10; //Angle1 := abs(Angle1); Angle1 := abs(Vec2Angle(StartPenumbra, StartUmbra)); Angle1 /= (JARenderLightFinCount); {F0 := 0; Penumbra0HotFin := 0; while F0 < abs(Angle0) do begin F0 += Angle1; Penumbra0HotFin += 1; end; Penumbra0HotFin := 3-Penumbra0HotFin;// } Penumbra0HotFin := 2-floor((abs(Angle0)/(abs(Angle1)))); end; Penumbra0FinVectors[0] := StartUmbra; for J := 1 to JARenderLightFinCount-1 do begin Penumbra0FinVectors[J] := Vec2Lerp(StartUmbra,StartPenumbra,(J)/JARenderLightFinCount); Angle0 := Vec2Angle(Penumbra0FinVectors[J], -EdgeVector); Angle1 := Vec2Angle(Penumbra0FinVectors[J], Penumbra0FinVectors[J-1]); if (Angle1 < Angle0) then begin Penumbra0FinVectors[J] := -EdgeVector; end; end; end; if (ShadowVertexEnd = -1) and FaceBackPrevious and not FaceBack then begin {Store State} ShadowVertexEnd := I; EndUmbra := -UmbraVector*10; EndPenumbra := -PenumbraVector*10; ShadowPenumbra1Index := I; {Calculate Previous Edge Vector} if (I-1) < 0 then J := APolygon^.VertexCount-1 else J := I-1; EdgeVector := APolygon^.WorldVertex[J]-APolygon^.WorldVertex[I]; //EdgeVector := APolygon^.WorldVertex[JRepeat(I-1,0,APolygon^.VertexCount-1)]-APolygon^.WorldVertex[I]; {Snap Umbra Edge to Face Edge if overlapping Face Edge} Angle0 := Vec2Angle(EdgeVector, EndPenumbra); Angle1 := Vec2Angle(EndUmbra, EndPenumbra); if (Angle1 < Angle0) then begin EndUmbra := EdgeVector; ShadowVertexEnd := JRepeat(I-1,0,APolygon^.VertexCount-1); {Move the shadow backwards} Endumbra := -umbraPrevious*10; {Use the Previous} Angle1 := abs(Vec2Angle(EndUmbra, EndPenumbra)); Angle1 /= (JARenderLightFinCount); Penumbra1HotFin := 2-floor((abs(Angle0)/(abs(Angle1)))); end; end; if (ShadowVertexStart > -1) and (ShadowVertexEnd > -1) then break; end; if (ShadowVertexStart <= -1) or (ShadowVertexEnd <= -1) then begin ShadowVertexCount := 0; exit; end; {Hard Edge Casting} {FaceBack := false; FaceBackPrevious := false; {Get Last Vertex -> First Vertex Face State} ANormal.Y := -(APolygon^.WorldVertex[APolygon^.VertexCount-1].X-APolygon^.WorldVertex[0].X); ANormal.X := (APolygon^.WorldVertex[APolygon^.VertexCount-1].Y-APolygon^.WorldVertex[0].Y); ANormal := Vec2Normalize(ANormal); LightDirection := Vec2Normalize(ALightPosition - APolygon^.WorldVertex[APolygon^.VertexCount-1]); FaceBack := (Vec2Dot(ANormal, LightDirection) < 0); {Find Back-facing Boundry Indices} for I := 0 to APolygon^.VertexCount-1 do begin FaceBackPrevious := FaceBack; {Normal is perpendicular to face} ANormal.Y := -(APolygon^.WorldVertex[I].X-APolygon^.WorldVertex[(I+1) mod APolygon^.VertexCount].X); ANormal.X := (APolygon^.WorldVertex[I].Y-APolygon^.WorldVertex[(I+1) mod APolygon^.VertexCount].Y); ANormal := Vec2Normalize(ANormal); LightDirection := Vec2Normalize(ALightPosition - APolygon^.WorldVertex[I]); FaceBack := (Vec2Dot(ANormal, LightDirection) < 0); {Detect Boundry Points - where front facing becomes back facing, where back facing becomes front facing} {Note : We're only dealing with convex polys atm - you can handle concave polys by detecting multiple sets of boundries and generating a shadow hull for each one} if (ShadowVertexStart = -1) and not FaceBackPrevious and FaceBack then ShadowVertexStart := I; if (ShadowVertexEnd = -1) and FaceBackPrevious and not FaceBack then ShadowVertexEnd := I; if (ShadowVertexStart > -1) and (ShadowVertexEnd > -1) then break; end; } {Reset Shadow Vertex Count - Memory not freed} AShadow^.ShadowVertexCount := 0; {Calculate Projected Shadow Hull Penumbra Vertices} {TODO : a fixed scale of 1000 is dodgy, we should calculate the direction vector, then Set its length so that it will be about two cliprects max width or height away, when we optimize for integer maths? we'll want the numbers constrained and managed. Like good little numbers.} {From Light Towards Boundry, pick a spot on that line far off in the distance} AVec.X := APolygon^.WorldVertex[ShadowVertexEnd].X + ((EndUmbra.X) * 1000 ); AVec.Y := APolygon^.WorldVertex[ShadowVertexEnd].Y + ((EndUmbra.Y) * 1000 ); AVec := Vec2DotMat3(AVec, AViewMatrix); {translate to screen space} {Calculate intersection with clipping Rect} if JRectIntersectLineResult(APolygon^.WorldVertexI[ShadowVertexEnd], AVec, ClipRect, ShadowHullEndSide, Intersect) then AVec := Intersect; ShadowHullEnd := Vec2SInt16(AVec); AVec.X := APolygon^.WorldVertex[ShadowVertexStart].X + ((StartUmbra.X) * 1000 ); AVec.Y := APolygon^.WorldVertex[ShadowVertexStart].Y + ((StartUmbra.Y) * 1000 ); AVec := Vec2DotMat3(AVec, AViewMatrix); {translate to screen space} {Calculate intersection with clipping Rect} if JRectIntersectLineResult(APolygon^.WorldVertexI[ShadowVertexStart], AVec, ClipRect, ShadowHullStartSide, Intersect) then AVec := Intersect; ShadowHullStart := Vec2SInt16(AVec); {Construct Shadow Geometry using Screen Space Coordinates} if (ShadowVertexStart > -1) and (ShadowVertexEnd > -1) then begin BackIndex := AShadow^.ShadowVertexStart; if not JRectIntersectVertex(APolygon^.WorldVertexI[BackIndex], ClipRect) then begin {Don't Render Offscreen shadows. No seriously, don't do it - it crashes. } ShadowVertexCount := 0; exit; end; JAShadowVertexAdd(AShadow)^ := APolygon^.WorldVertexI[BackIndex]; repeat BackIndex := (BackIndex + 1) mod (APolygon^.VertexCount); if not JRectIntersectVertex(APolygon^.WorldVertexI[BackIndex], ClipRect) then begin ShadowVertexCount := 0; exit; end; JAShadowVertexAdd(AShadow)^ := APolygon^.WorldVertexI[BackIndex]; until (BackIndex = AShadow^.ShadowVertexEnd); end; {Add First Point} JAShadowVertexAdd(AShadow)^ := ShadowHullEnd; {Query Side Spanning} if JRectSideClipping(ShadowHullStartSide, ShadowHullEndSide, JRect(ClipRect), A, B, VecCount) then begin JAShadowVertexAdd(AShadow)^ := Vec2SInt16(A); if VecCount=2 then JAShadowVertexAdd(AShadow)^ := Vec2SInt16(B); end; {Add Last Point} JAShadowVertexAdd(AShadow)^ := ShadowHullStart; {-------------------------------------------------------- Build Penumbras} //AVec.X := WorldVertex[ShadowPenumbra0Index].X + ((StartPenumbra.X) * 1000 ); //AVec.Y := WorldVertex[ShadowPenumbra0Index].Y + ((StartPenumbra.Y) * 1000 ); {Reset Penumbra Vertex Count} ShadowPenumbra0VertexCount := 0; ShadowPenumbra1VertexCount := 0; {Calculate Penumbra0 Polygon} AVec.X := APolygon^.WorldVertex[ShadowPenumbra0Index].X + ((StartPenumbra.X) * 1000 ); AVec.Y := APolygon^.WorldVertex[ShadowPenumbra0Index].Y + ((StartPenumbra.Y) * 1000 ); AVec := Vec2DotMat3(AVec, AViewMatrix); {translate to screen space} {Calculate intersection with clipping Rect} if JRectIntersectLineResult(APolygon^.WorldVertexI[ShadowPenumbra0Index], AVec, ClipRect, Penumbra0StartSide, Intersect) then AVec := Intersect; Penumbra0Start := Vec2SInt16(AVec); {Calculate Penumbra1 Polygon} AVec.X := APolygon^.WorldVertex[ShadowPenumbra1Index].X + ((EndPenumbra.X) * 1000 ); AVec.Y := APolygon^.WorldVertex[ShadowPenumbra1Index].Y + ((EndPenumbra.Y) * 1000 ); AVec := Vec2DotMat3(AVec, AViewMatrix); {translate to screen space} {Calculate intersection with clipping Rect} if JRectIntersectLineResult(APolygon^.WorldVertexI[ShadowPenumbra1Index], AVec, ClipRect, Penumbra1StartSide, Intersect) then AVec := Intersect; Penumbra1Start := Vec2SInt16(AVec); {Calculate Penumbra Fins} {for J := 0 to JARenderLightFinCount-1 do begin Penumbra0Fins[J] := Vec2Lerp(StartPenumbra, StartUmbra, J / JARenderLightFinCount); if (Vec2Angle(StartPenumbra, Penumbra0Fins[0]) < Vec2Angle(StartPenumbra, -EdgeVector)) then begin Penumbra0HotFin := J; end; end; } AVec := ShadowHullStart; for I := 0 to JARenderLightFinCount-1 do begin JAVertexPoolClear(@AShadow^.ShadowPenumbra0Fins[I]); if (I <= Penumbra0HotFin) then JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra0Fins[I])^ := APolygon^.WorldVertexI[ShadowVertexStart] else JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra0Fins[I])^ := APolygon^.WorldVertexI[ShadowPenumbra0Index]; if (I = Penumbra0HotFin) then begin JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra0Fins[I])^ := APolygon^.WorldVertexI[ShadowPenumbra0Index]; end; {Vec1 := Vec2Rotate(StartPenumbra, -(Vec2Angle(StartUmbra, StartPenumbra)/3)*JRadToDeg*I); Vec1 += APolygon^.WorldVertexI[ShadowPenumbra0Index]; } //Vec1 := Startumbra {Calc Fin Start Position} Vec1 := Vec2Lerp( Vec2(ShadowHullStart), Vec2(Penumbra0Start), (I+1) / (JARenderLightFinCount)); JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra0Fins[I])^ := Vec2SInt16(Vec1); JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra0Fins[I])^ := Vec2SInt16(AVec); AVec := Vec1; end; AVec := ShadowHullEnd; for I := 0 to JARenderLightFinCount-1 do begin JAVertexPoolClear(@AShadow^.ShadowPenumbra1Fins[I]); if (I <= Penumbra1HotFin) then JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra1Fins[I])^ := APolygon^.WorldVertexI[ShadowVertexEnd] else JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra1Fins[I])^ := APolygon^.WorldVertexI[ShadowPenumbra1Index]; if (I = Penumbra1HotFin) then begin JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra1Fins[I])^ := APolygon^.WorldVertexI[ShadowPenumbra1Index]; end; {Vec1 := Vec2Rotate(StartPenumbra, -(Vec2Angle(StartUmbra, StartPenumbra)/3)*JRadToDeg*I); Vec1 += APolygon^.WorldVertexI[ShadowPenumbra0Index]; } //Vec1 := Startumbra {Calc Fin Start Position} Vec1 := Vec2Lerp( Vec2(ShadowHullEnd), Vec2(Penumbra1Start), (I+1) / (JARenderLightFinCount)); JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra1Fins[I])^ := Vec2SInt16(Vec1); JAVertexPoolVertexAdd(@AShadow^.ShadowPenumbra1Fins[I])^ := Vec2SInt16(AVec); AVec := Vec1; end; {If Penumbra0 casts along an edge} {if not (ShadowPenumbra0Index<>ShadowVertexStart) then begin {which band cast from the root would overlap the edge} {all bands until this, cast from the root} {this band gets snapped to edge, first half} {remainder of this band is cast from next edge} {remainder of bands cast from next edge} {is it a garuntee that there is only one band with a special case?} end else begin } { {Add Penumbra 0 Root Vertex} JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := APolygon^.WorldVertexI[ShadowPenumbra0Index]; {Add Penumbra Projected Start Vertex} JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := Penumbra0Start; {Query Side Spanning} if JRectSideClipping(ShadowHullStartSide, Penumbra0StartSide, JRect(ClipRect), A, B, VecCount) then begin JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := Vec2SInt16(A); if VecCount=2 then JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := Vec2SInt16(B); end; {Add Penumbra 0 End Vertex} JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := ShadowHullStart; {If the Umbra was shifted back, add the Shadow Start point} if (ShadowPenumbra0Index<>ShadowVertexStart) then JAPolygonShadowPenumbra0VertexAdd(APolygon)^ := APolygon^.WorldVertexI[ShadowVertexStart]; { {If Penumbra1 casts along an edge} if (ShadowPenumbra1Index<>ShadowVertexEnd) then begin end; } {Add Penumbra 1 Root Vertex} JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := APolygon^.WorldVertexI[ShadowPenumbra1Index]; {If the Umbra was shifted back, add the Shadow End Point} if (ShadowPenumbra1Index<>ShadowVertexEnd) then JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := APolygon^.WorldVertexI[ShadowVertexEnd]; {Add Penumbra 1 End Vertex} JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := ShadowHullEnd; {Query Side Spanning} if JRectSideClipping(ShadowHullEndSide, Penumbra1StartSide, JRect(ClipRect), A, B, VecCount) then begin JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := Vec2SInt16(A); if VecCount=2 then JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := Vec2SInt16(B); end; {Add Penumbra 1 Projected Start Vertex} JAPolygonShadowPenumbra1VertexAdd(APolygon)^ := Penumbra1Start; } end; end; end.
unit TabControlImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls; type TTabControlX = class(TActiveXControl, ITabControlX) private { Private declarations } FDelphiControl: TTabControl; FEvents: ITabControlXEvents; procedure ChangeEvent(Sender: TObject); procedure ChangingEvent(Sender: TObject; var AllowChange: Boolean); procedure GetImageIndexEvent(Sender: TObject; TabIndex: Integer; var ImageIndex: Integer); procedure ResizeEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Cursor: Smallint; safecall; function Get_DockSite: WordBool; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_HotTrack: WordBool; safecall; function Get_MultiLine: WordBool; safecall; function Get_MultiSelect: WordBool; safecall; function Get_OwnerDraw: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_RaggedRight: WordBool; safecall; function Get_ScrollOpposite: WordBool; safecall; function Get_Style: TxTabStyle; safecall; function Get_TabHeight: Smallint; safecall; function Get_TabIndex: Integer; safecall; function Get_TabPosition: TxTabPosition; safecall; function Get_Tabs: IStrings; safecall; function Get_TabWidth: Smallint; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DockSite(Value: WordBool); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_HotTrack(Value: WordBool); safecall; procedure Set_MultiLine(Value: WordBool); safecall; procedure Set_MultiSelect(Value: WordBool); safecall; procedure Set_OwnerDraw(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_RaggedRight(Value: WordBool); safecall; procedure Set_ScrollOpposite(Value: WordBool); safecall; procedure Set_Style(Value: TxTabStyle); safecall; procedure Set_TabHeight(Value: Smallint); safecall; procedure Set_TabIndex(Value: Integer); safecall; procedure Set_TabPosition(Value: TxTabPosition); safecall; procedure Set_Tabs(const Value: IStrings); safecall; procedure Set_TabWidth(Value: Smallint); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About34; { TTabControlX } procedure TTabControlX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_TabControlXPage); } end; procedure TTabControlX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ITabControlXEvents; end; procedure TTabControlX.InitializeControl; begin FDelphiControl := Control as TTabControl; FDelphiControl.OnChange := ChangeEvent; FDelphiControl.OnChanging := ChangingEvent; FDelphiControl.OnGetImageIndex := GetImageIndexEvent; FDelphiControl.OnResize := ResizeEvent; end; function TTabControlX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TTabControlX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TTabControlX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TTabControlX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TTabControlX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TTabControlX.Get_DockSite: WordBool; begin Result := FDelphiControl.DockSite; end; function TTabControlX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TTabControlX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TTabControlX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TTabControlX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TTabControlX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TTabControlX.Get_HotTrack: WordBool; begin Result := FDelphiControl.HotTrack; end; function TTabControlX.Get_MultiLine: WordBool; begin Result := FDelphiControl.MultiLine; end; function TTabControlX.Get_MultiSelect: WordBool; begin Result := FDelphiControl.MultiSelect; end; function TTabControlX.Get_OwnerDraw: WordBool; begin Result := FDelphiControl.OwnerDraw; end; function TTabControlX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TTabControlX.Get_RaggedRight: WordBool; begin Result := FDelphiControl.RaggedRight; end; function TTabControlX.Get_ScrollOpposite: WordBool; begin Result := FDelphiControl.ScrollOpposite; end; function TTabControlX.Get_Style: TxTabStyle; begin Result := Ord(FDelphiControl.Style); end; function TTabControlX.Get_TabHeight: Smallint; begin Result := FDelphiControl.TabHeight; end; function TTabControlX.Get_TabIndex: Integer; begin Result := FDelphiControl.TabIndex; end; function TTabControlX.Get_TabPosition: TxTabPosition; begin Result := Ord(FDelphiControl.TabPosition); end; function TTabControlX.Get_Tabs: IStrings; begin GetOleStrings(FDelphiControl.Tabs, Result); end; function TTabControlX.Get_TabWidth: Smallint; begin Result := FDelphiControl.TabWidth; end; function TTabControlX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TTabControlX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TTabControlX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TTabControlX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TTabControlX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TTabControlX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TTabControlX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabControlX.AboutBox; begin ShowTabControlXAbout; end; procedure TTabControlX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TTabControlX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TTabControlX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TTabControlX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TTabControlX.Set_DockSite(Value: WordBool); begin FDelphiControl.DockSite := Value; end; procedure TTabControlX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TTabControlX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TTabControlX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TTabControlX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TTabControlX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabControlX.Set_HotTrack(Value: WordBool); begin FDelphiControl.HotTrack := Value; end; procedure TTabControlX.Set_MultiLine(Value: WordBool); begin FDelphiControl.MultiLine := Value; end; procedure TTabControlX.Set_MultiSelect(Value: WordBool); begin FDelphiControl.MultiSelect := Value; end; procedure TTabControlX.Set_OwnerDraw(Value: WordBool); begin FDelphiControl.OwnerDraw := Value; end; procedure TTabControlX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TTabControlX.Set_RaggedRight(Value: WordBool); begin FDelphiControl.RaggedRight := Value; end; procedure TTabControlX.Set_ScrollOpposite(Value: WordBool); begin FDelphiControl.ScrollOpposite := Value; end; procedure TTabControlX.Set_Style(Value: TxTabStyle); begin FDelphiControl.Style := TTabStyle(Value); end; procedure TTabControlX.Set_TabHeight(Value: Smallint); begin FDelphiControl.TabHeight := Value; end; procedure TTabControlX.Set_TabIndex(Value: Integer); begin FDelphiControl.TabIndex := Value; end; procedure TTabControlX.Set_TabPosition(Value: TxTabPosition); begin FDelphiControl.TabPosition := TTabPosition(Value); end; procedure TTabControlX.Set_Tabs(const Value: IStrings); begin SetOleStrings(FDelphiControl.Tabs, Value); end; procedure TTabControlX.Set_TabWidth(Value: Smallint); begin FDelphiControl.TabWidth := Value; end; procedure TTabControlX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TTabControlX.ChangeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnChange; end; procedure TTabControlX.ChangingEvent(Sender: TObject; var AllowChange: Boolean); var TempAllowChange: WordBool; begin TempAllowChange := WordBool(AllowChange); if FEvents <> nil then FEvents.OnChanging(TempAllowChange); AllowChange := Boolean(TempAllowChange); end; procedure TTabControlX.GetImageIndexEvent(Sender: TObject; TabIndex: Integer; var ImageIndex: Integer); var TempImageIndex: Integer; begin TempImageIndex := Integer(ImageIndex); if FEvents <> nil then FEvents.OnGetImageIndex(TabIndex, TempImageIndex); ImageIndex := Integer(TempImageIndex); end; procedure TTabControlX.ResizeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnResize; end; initialization TActiveXControlFactory.Create( ComServer, TTabControlX, TTabControl, Class_TabControlX, 34, '{695CDBDC-02E5-11D2-B20D-00C04FA368D4}', OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL, tmApartment); end.
unit DefinedGrammars; interface uses Grammar, Classes, Generics.Collections; procedure InitialiseGrammars; var kochCurveGrammar, sierpinskiGrammar, dragonCurveGrammar: TGrammar; implementation procedure InitialiseGrammars; var kcRules, stRules, dcRules: TDictionary<String, String>; kcMovements, stMovements, dcMovements: TDictionary<String, String>; begin // Koch curve grammar rules kcRules := TDictionary<String, String>.Create; kcRules.Add('F', 'F+F-F-F+F'); // Movement rules kcMovements := TDictionary<String, String>.Create; kcMovements.Add('F', 'draw forward'); kcMovements.Add('+', 'turn 90 L'); // 90 degrees left kcMovements.Add('-', 'turn 90 R'); // 90 degrees right kochCurveGrammar := TGrammar.Create('F', kcRules, kcMovements); // Sierpinski triangle grammar rules stRules := TDictionary<String, String>.Create; stRules.Add('F', 'F-G+F+G-F'); stRules.Add('G', 'GG'); // Movement rules stMovements := TDictionary<String, String>.Create; stMovements.Add('F', 'draw forward'); stMovements.Add('G', 'draw forward'); stMovements.Add('+', 'turn 120 L'); // 120 degrees left stMovements.Add('-', 'turn 120 R'); // 120 degrees right sierpinskiGrammar := TGrammar.Create('F-G-G', stRules, stMovements); // Dragon curve grammar rules dcRules := TDictionary<String, String>.Create; dcRules.Add('F', 'F-H'); dcRules.Add('H', 'F+H'); // Movement rules dcMovements := TDictionary<String, String>.Create; dcMovements.Add('F', 'draw forward'); dcMovements.Add('H', 'draw forward'); dcMovements.Add('+', 'turn 90 R'); // 90 degrees right dcMovements.Add('-', 'turn 90 L'); // 90 degrees left dragonCurveGrammar := TGrammar.Create('F', dcRules, dcMovements); end; end.
//****************************************************************************** //*** COMMON DELPHI FUNCTIONS *** //*** *** //*** (c) Massimo Magnano, Beppe Grimaldi 2004-2005 *** //*** *** //*** *** //****************************************************************************** // File : MGRegistry.pas // // Description : Extensions on TRegistry class // Support for Read\Write Components, // TFont, // MultiLine Text // //****************************************************************************** unit MGRegistry; interface {$define TYPE_INFO_1} Uses Windows, Registry, SysUtils, Classes, Graphics, TypInfo; Type TRegFont = packed record Name :ShortString; Size :Byte; Style :Byte; Charset :Byte; Color :TColor; end; TPersistentClasses = class of TPersistent; TMGRegistry =class(TRegistry) protected function ReadWriteClass(Read :Boolean; AClass :TPersistent) :Boolean; virtual; public function ReadBool(Default :Boolean; const Name: string): Boolean; overload; function ReadCurrency(Default :Currency; const Name: string): Currency; overload; function ReadDate(Default :TDateTime; const Name: string): TDateTime; overload; function ReadDateTime(Default :TDateTime; const Name: string): TDateTime; overload; function ReadFloat(Default :Double; const Name: string): Double; overload; function ReadInteger(Default :Integer; const Name: string): Integer; overload; function ReadString(Default :string; AcceptEmpty :Boolean; const Name: string): string; overload; function ReadTime(Default :TDateTime; const Name: string): TDateTime; overload; procedure ReadBinaryDataFromFile(FileName :String; var Buffer :Pointer; var BufSize :Integer); procedure ReadBinaryDataFromString(theString :String; var Buffer :Pointer; var BufSize :Integer); function ReadFont(const Name: string; var AFont :TFont): Boolean; procedure WriteFont(const Name: string; Value :TFont); function ReadClass(var AClass :TPersistent; AClasses :TPersistentClasses): Boolean; function WriteClass(AClass :TPersistent): Boolean; function ReadDFMClass(Name :String; AClass :TPersistent): Boolean; function WriteDFMClass(Name :String; AClass :TPersistent): Boolean; procedure WriteMultiLineString(Name, Value: String); function ReadMultiLineString(const Name: string): string; end; implementation type TReadWritePersist = class (TComponent) private rData :TPersistent; published property Data :TPersistent read rData write rData; end; function TMGRegistry.ReadBool(Default :Boolean; const Name: string): Boolean; begin try Result :=ReadBool(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadCurrency(Default :Currency; const Name: string): Currency; begin try Result :=ReadCurrency(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadDate(Default :TDateTime; const Name: string): TDateTime; begin try Result :=ReadDate(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadDateTime(Default :TDateTime; const Name: string): TDateTime; begin try Result :=ReadDateTime(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadFloat(Default :Double; const Name: string): Double; begin try Result :=ReadFloat(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadInteger(Default :Integer; const Name: string): Integer; begin try Result :=ReadInteger(Name); except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadString(Default :string; AcceptEmpty :Boolean; const Name: string): string; begin try if (ValueExists(Name)) then begin Result := ReadString(Name); if ((Result = '') and not AcceptEmpty) then Result := Default; end else Result := Default; except On E:Exception do Result :=Default; end; end; function TMGRegistry.ReadTime(Default :TDateTime; const Name: string): TDateTime; begin try Result :=ReadTime(Name); except On E:Exception do Result :=Default; end; end; procedure TMGRegistry.ReadBinaryDataFromFile(FileName :String; var Buffer :Pointer; var BufSize :Integer); Var theFile :TFileStream; begin BufSize :=0; Buffer :=Nil; theFile :=Nil; try theFile :=TFileStream.Create(FileName, fmOpenRead); BufSize :=theFile.Size; GetMem(Buffer, BufSize); theFile.Read(Buffer, BufSize); theFile.Free; theFile :=Nil; except On E:Exception do begin if Buffer<>Nil then FreeMem(Buffer); if theFile<>Nil then theFile.Free; Buffer :=Nil; BufSize :=0; end; end; end; procedure TMGRegistry.ReadBinaryDataFromString(theString :String; var Buffer :Pointer; var BufSize :Integer); Var indexStr, indexPtr :Integer; begin BufSize :=Length(theString) div 2; SetLength(theString, BufSize*2); //la stringa deve essere di lunghezza pari GetMem(Buffer, BufSize); indexStr :=1; for indexPtr :=0 to BufSize-1 do begin PChar(Buffer)[indexPtr] :=Char(StrToInt('$'+Copy(theString, indexStr, 2))); inc(indexStr, 2); end; end; function TMGRegistry.ReadFont(const Name: string; var AFont :TFont) :Boolean; var regFont :TRegFont; begin Result := False; try if (not assigned(AFont)) then AFont := TFont.Create; if (ValueExists(Name)) then if (GetDataSize(Name) = sizeOf(TRegFont)) then begin ReadBinaryData(Name, regFont, sizeOf(TRegFont)); AFont.Name := regFont.Name; AFont.Size := regFont.Size; AFont.Style := TFontStyles(regFont.Style); AFont.Charset := regFont.Charset; AFont.Color := regFont.Color; Result := True; end; except On E:Exception do begin end; end; end; procedure TMGRegistry.WriteFont(const Name: string; Value :TFont); var regFont :TRegFont; begin try if (Value <> Nil) then begin regFont.Name := Value.Name; regFont.Size := Value.Size; regFont.Style := Byte(Value.Style); regFont.Charset := Value.Charset; regFont.Color := Value.Color; WriteBinaryData(Name, regFont, sizeOf(TRegFont)); end; except On E:Exception do begin end; end; end; function TMGRegistry.ReadWriteClass(Read :Boolean; AClass :TPersistent) :Boolean; Var rPropList :TPropList; PropName :String; PropValue :Variant; IsClass :Boolean; i :Integer; begin Result := True; try fillchar(rPropList, sizeof(TPropList), 0); TypInfo.GetPropList(AClass.ClassInfo, tkProperties, PPropList(@rPropList)); i := 0; while (rPropList[i] <> Nil) do begin try {$ifdef TYPE_INFO_1} IsClass :=(rPropList[i]^.PropType^.Kind=tkClass); {$else} IsClass :=(rPropList[i]^.PropType^^.Kind=tkClass); {$endif} PropName :=rPropList[i]^.Name; if not(IsClass) then begin if Read then begin PropValue :=Self.ReadString('', True, PropName); SetPropValue(AClass, PropName, PropValue); end else begin PropValue :=GetPropValue(AClass, PropName, True); Self.WriteString(PropName, PropValue); end; end; except On E:Exception do Result :=False; end; Inc(i); end; except On E:Exception do Result :=False; end; end; function TMGRegistry.ReadClass(var AClass :TPersistent; AClasses :TPersistentClasses): Boolean; begin Result :=False; try if (not assigned(AClass)) then begin AClass := TPersistent(AClasses.Create); end; if (AClass<>Nil) then Result :=ReadWriteClass(True, AClass); except On E:Exception do Result :=False; end; end; function TMGRegistry.WriteClass(AClass :TPersistent):Boolean; begin Result :=False; if (AClass<>Nil) then Result :=ReadWriteClass(False, AClass); end; function TMGRegistry.ReadDFMClass(Name :String; AClass :TPersistent): Boolean; Var MStream, MStreamTXT :TMemoryStream; xList :TStringList; toRead :TComponent; begin Result :=False; try if (AClass is TComponent) then toRead :=TComponent(AClass) else begin if (AClass is TPersistent) then begin toRead :=TReadWritePersist.Create(Nil); TReadWritePersist(toRead).Data :=AClass; end else Exit; end; MStream :=TMemoryStream.Create; MStreamTXT :=TMemoryStream.Create; xList :=TStringList.Create; try xList.Text :=Self.ReadMultiLineString(Name); xList.SaveToStream(MStreamTXT); MStreamTXT.Position :=0; ObjectTextToBinary(MStreamTXT, MStream); MStream.Position :=0; MStream.ReadComponent(toRead); Result :=True; finally MStream.Free; MStreamTXT.Free; xList.Free; if (toRead<>AClass) then toRead.Free; end; except On E:Exception do begin end; end; end; function TMGRegistry.WriteDFMClass(Name :String; AClass :TPersistent): Boolean; Var MStream, MStreamTXT :TMemoryStream; xList :TStringList; toWrite :TComponent; begin Result :=False; try if (AClass is TComponent) then toWrite :=TComponent(AClass) else begin if (AClass is TPersistent) then begin toWrite :=TReadWritePersist.Create(Nil); TReadWritePersist(toWrite).Data :=AClass; end else Exit; end; MStream :=TMemoryStream.Create; MStreamTXT :=TMemoryStream.Create; xList :=TStringList.Create; try MStream.WriteComponent(toWrite); MStream.Position :=0; ObjectBinaryToText(MStream, MStreamTXT); MStreamTXT.Position :=0; xList.LoadFromStream(MStreamTXT); Self.WriteMultiLineString(Name, xList.Text); Result :=True; finally MStream.Free; MStreamTXT.Free; xList.Free; if (toWrite<>AClass) then toWrite.Free; end; except On E:Exception do begin end; end; end; procedure TMGRegistry.WriteMultiLineString(Name, Value: String); Var Buffer :PChar; ch :Char; i, k :Integer; begin Buffer :=Nil; try GetMem(Buffer, Length(Value)+1); k :=0; for i :=1 to Length(Value) do begin ch :=Value[i]; case ch of #13 : ch :=#0; #10 : Continue; end; Buffer[k] :=ch; inc(k); end; Buffer[k+1] :=#0; RegSetValueEx(CurrentKey, PChar(Name), 0, REG_MULTI_SZ, Buffer, k); finally if (Buffer<>Nil) then Freemem(Buffer); end; end; function TMGRegistry.ReadMultiLineString(const Name: string): string; Var Buffer :PChar; ch :Char; i :Integer; bufSize :DWord; bufType :DWord; begin if (RegQueryValueEx(CurrentKey, PChar(Name), Nil, @bufType, Nil, @bufSize) =ERROR_SUCCESS) and (bufType=REG_MULTI_SZ) then begin Buffer :=Nil; try GetMem(Buffer, bufSize); RegQueryValueEx(CurrentKey, PChar(Name), Nil, @bufType, PByte(Buffer), @bufSize); for i :=0 to bufSize-2 do begin ch :=Buffer[i]; if ch=#0 then Result :=Result+#13#10 else Result :=Result+ch; end; finally if (Buffer<>Nil) then Freemem(Buffer); end; end; end; end.
unit uPlStimModuleInterface; interface uses Windows, OpenGL, MMSystem; const Class_PlStimModule: TGUID = '{1755994C-0B66-4A68-B454-E4EB28A82F4E}'; type HIMAGE = Integer; HEFFECT = Integer; IPlStimModuleInterface = interface(IInterface) ['{AB411CBE-6558-4775-8632-D280313879DA}'] //Работа с изображениями function Image_LoadFromFile(const FileNameW: PWideChar): HIMAGE; function Image_LoadFromPointer(PData: Pointer; DataSize: Integer): HIMAGE; function Image_WindowShow(MonitorIndex: Integer; WindowRect: TRect): HWND; function Image_WindowHide: HRESULT; function Image_Show(AImage: HIMAGE): HRESULT; function Image_ShowPreview(AImage: HIMAGE): HRESULT; function Image_Hide(AImage: HIMAGE): HRESULT; function Image_GetData(AImage: HIMAGE; var PData: Pointer; var DataSize: Integer): HRESULT; function Image_Duplicate(AImage: HIMAGE): HIMAGE; procedure Image_Free(AImage: HIMAGE); function Image_GetPreviewTex(AImage: HIMAGE; ADC: HDC; ARC: HGLRC): GLuint; procedure Image_FreeGLContext(ADC: HDC; ARC: HGLRC); //Работа со звуком function Effect_LoadFromFile(const FileNameW: PWideChar): HEFFECT; function Effect_LoadFromPointer(var wf: tWAVEFORMATEX; PData: Pointer; DataSize: Integer): HEFFECT; overload; function Effect_LoadFromPointer(PData: Pointer; DataSize: Integer): HEFFECT; overload; function Effect_StartPlay(AEffect: HEFFECT; PlayLooping: Boolean): HRESULT; function Effect_StopPlay(AEffect: HEFFECT): HRESULT; function Effect_StartCapture: HEFFECT; function Effect_StopCapture(AEffect: HEFFECT): HRESULT; function Effect_GetData(AEffect: HEFFECT; var PData: Pointer; var DataSize: Integer): HRESULT; function Effect_GetStatus(AEffect: HEFFECT; var pdwStatus: Cardinal): HRESULT; function Effect_Duplicate(AEffect: HEFFECT): HEFFECT; procedure Effect_Free(AEffect: HEFFECT); procedure Sound_SetWindowHandle(Win: HWND); function ModuleInitialize: Boolean; end; implementation end.
unit ubookutils; {Berisi fungsi perantara untuk unit buku seperti menghitung jumlah buku, mencari indeks buku di array, dll} {REFERENSI : - } interface {PUBLIC VARIABLE, CONST, ADT} uses ucsvwrapper, ubook, uuser, udate; {PUBLIC FUNCTION, PROCEDURE} function countAdmin(ptruser : puser):integer; function countPengunjung(ptruser : puser):integer; function countBuku(category : string; ptrbook : pbook):integer; function checkLocation(id : integer; ptr : pbook):integer; function searchBorrow(id : integer; username: string; ptrborrow: pborrow): BorrowHistory; procedure sortBookByTitle(ptr: pbook; counter: integer); implementation {FUNGSI dan PROSEDUR} function countAdmin(ptruser : puser): integer; {DESKRIPSI : Menghitung banyak admin dalam data user.csv} {PARAMETER : Ptruser (pointer pada user.csv)} {RETURN : sebuah bilangan integer} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin {INISIASI} countAdmin := 0; i := 1; {TAHAP PENCACAHAN} while (i <= userNeff) do begin if (ptruser^[i].isAdmin) then begin countAdmin += 1; end; i += 1; end; end; function countPengunjung(ptruser : puser): integer; {DESKRIPSI : Menghitung banyak pengunjung dalam data user.csv} {PARAMETER : Ptruser (pointer pada user.csv)} {RETURN : sebuah bilangan integer} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin {INISIASI} countPengunjung := 0; i := 1; {TAHAP PENCACAHAN} while (i <= userNeff) do begin if (ptruser^[i].isAdmin = False) then begin countPengunjung += 1; end; i += 1; end; end; function countBuku(category : string; ptrbook : pbook):integer; {DESKRIPSI : Menghitung banyak buku berdasarkan jenis buku dalam book.csv} {PARAMETER : category bertype string dan Ptrbook (pointer pada book.csv)} {RETURN : sebuah bilangan integer} {KAMUS LOKAL} var i : integer; {ALGORITMA} begin {INISIALISASI} countBuku := 0; i := 1; {TAHAP PENCACAHAN} while (i <= bookNeff) do begin if (ptrbook^[i].category = category) then begin countBuku += ptrbook^[i].qty; end; i += 1; end; end; function checkLocation(id : integer; ptr : pbook): integer; {DESKRIPSI : Mencari lokasi keberadaan id dengan skema searching pada book.csv} {PARAMETER : id bertipe integer dan Ptrbook (pointer pada book.csv)} {RETURN : sebuah bilangan integer yang melambangkan indeks dari id} {KAMUS LOKAL} var i : integer; found : boolean; {ALGORITMA} begin {INISIALISASI} found := false; i := 1; {TAHAP PENCARIAN} while ((not found) and (i <= bookNeff)) do begin if (id = ptr^[i].id) then begin checkLocation := i; found := True; end; i += 1; end; end; function searchBorrow(id : integer; username: string; ptrborrow: pborrow): BorrowHistory; {DESKRIPSI : Mencari data peminjaman dengan id dan username tertentu} {PARAMETER : id dan username yang ingin dicari pada array of history} {RETURN : ADT borrowhistory dengan username dan id yang sesuai dengan parameter} {KAMUS LOKAL} var found : boolean; i : integer; {ALGORITMA} begin {SKEMA SEARCHING DENGAN BOOLEAN} found := false; i := 1; while ((not found) and (i <= borrowNeff)) do begin if (ptrborrow^[i].username = username) and (ptrborrow^[i].id = id) and (ptrborrow^[i].isBorrowed) then begin searchBorrow := ptrborrow^[i]; ptrborrow^[i].isBorrowed := false; found := true; end; i += 1; end; if (not found) then begin writeln('Anda tidak sedang meminjam buku tersebut.'); searchBorrow.username := wraptext('Anonymous'); end; end; procedure sortBookByTitle(ptr: pbook; counter: integer); {DESKRIPSI : sortBookByTitle menyusun buku sesuai abjad pada judul buku} {I.S. : array of Book terdefinisi} {F.S. : buku tersusun sesuai abjad pada judul buku} {Proses : dari array of book menyusun abjad pada judul buku dari A sampai Z dengan menggunakan bubble sort versi optimum} {KAMUS LOKAL} var i, pass : integer; tmp : book; tukar : boolean; {ALGORITMA} begin {Skema Sorting dengan Optimized Bubble Sort} tukar := true; pass := 1; while ((pass <= counter-1) and tukar) do begin tukar := false; for i := 1 to (counter-pass) do begin if ptr^[i].title > ptr^[i+1].title then begin {Tukar arraybuku indeks ke-i dengan i+1} tmp := ptr^[i]; ptr^[i] := ptr^[i+1]; ptr^[i+1] := tmp; tukar := true; end; end; pass += 1; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConfig.ConfigDM; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FMX.Edit, FMX.Dialogs, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FMX.StdCtrls, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, FireDAC.DApt, System.Math, FireDAC.Phys.SQLiteVDataSet, FMX.Layouts, FMX.Types, System.IOUtils, FMX.DialogService, System.Generics.Collections, Rest.Json, FMX.ListBox; type TCallbackProc = procedure(ASender: TObject); TAuthorizationItem = class private FGroups: TArray<String>; FPublic: Boolean; FUsers: TArray<String>; public property Groups: TArray<String> read FGroups write FGroups; property Public: Boolean read FPublic write FPublic; property Users: TArray<String> read FUsers write FUsers; function ToJson: string; class function FromJson(const AJsonString: string): TAuthorizationItem; end; TPublicPathsItem = class private FCharset: String; FDefault: String; FDirectory: String; FExtensions: TArray<String>; FMimes: TArray<String>; FPath: String; public property Charset: String read FCharset write FCharset; property Default: String read FDefault write FDefault; property Directory: String read FDirectory write FDirectory; property Extensions: TArray<String> read FExtensions write FExtensions; property Mimes: TArray<String> read FMimes write FMimes; property Path: String read FPath write FPath; function ToJson: string; class function FromJson(const AJsonString: string): TPublicPathsItem; end; TRedirectItem = class private FDestination: String; public property Destination: String read FDestination write FDestination; function ToJson: string; class function FromJson(const AJsonString: string): TRedirectItem; end; TConfigDM = class(TDataModule) SettingsMT: TFDMemTable; DataMT: TFDMemTable; ServerMT: TFDMemTable; PushNotificationsMT: TFDMemTable; ServerStatusMT: TFDMemTable; DataStatusMT: TFDMemTable; PushNotificationsStatusMT: TFDMemTable; private { Private declarations } FCurrentFilename: String; procedure PairTypeToComment(const APairType: Integer; var ACommented, AComment: Boolean); public { Public declarations } procedure ShowHelp(Sender: TObject); procedure LoadFromFile(const AFilename: String); procedure SaveToFile(const AFilename: String = ''); procedure OpenDialogForEdit(AEdit: TEdit; AOpenDialog: TOpenDialog); procedure AddSectionListItem(AEnabled: Boolean; const AName, AValue: String; AListBox: TListBox; ACallback: TNotifyEvent); procedure RenumberListItems(AListBox: TListBox); procedure LoadSectionList(const ASection: String; AListBox: TListBox; ACallback: TNotifyEvent); procedure LoadSection(const ASection: String; AValueMemTable: TFDMemTable; AStatusMemTable: TFDMemTable); procedure SaveSection(const ASection: String; AValueMemTable: TFDMemTable; AStatusMemTable: TFDMemTable); procedure SaveSectionList(const ASection: String; AListBox: TListBox); end; const INI_NAME_VALUE_PAIR = 0; INI_COMMENTED_NAME_VALUE_PAIR = 1; INI_COMMENT = 2; PACKAGES_FRAME = 0; PUBLICPATHS_FRAME = 1; REDIRECT_FRAME = 2; AUTHORIZATION_FRAME = 3; var ConfigDM: TConfigDM; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses RSConsole.FormConfig, RSConfig.NameValueFrame; function TAuthorizationItem.ToJson: string; begin Result := TJson.ObjectToJsonString(Self, [TJsonOption.joIgnoreEmptyArrays, TJsonOption.joIgnoreEmptyStrings]); end; class function TAuthorizationItem.FromJson(const AJsonString: string): TAuthorizationItem; begin Result := TJson.JsonToObject<TAuthorizationItem>(AJsonString) end; function TPublicPathsItem.ToJson: string; begin Result := TJson.ObjectToJsonString(Self, [TJsonOption.joIgnoreEmptyArrays, TJsonOption.joIgnoreEmptyStrings]); end; class function TPublicPathsItem.FromJson(const AJsonString: string): TPublicPathsItem; begin Result := TJson.JsonToObject<TPublicPathsItem>(AJsonString) end; function TRedirectItem.ToJson: string; begin Result := TJson.ObjectToJsonString(Self); end; class function TRedirectItem.FromJson(const AJsonString: string): TRedirectItem; begin Result := TJson.JsonToObject<TRedirectItem>(AJsonString) end; procedure TConfigDM.ShowHelp(Sender: TObject); begin TDialogService.ShowMessage(TButton(Sender).Hint); end; procedure TConfigDM.OpenDialogForEdit(AEdit: TEdit; AOpenDialog: TOpenDialog); begin AOpenDialog.InitialDir := GetCurrentDir; if AOpenDialog.Execute then begin AEdit.Text := AOpenDialog.FileName; TLinkObservers.ControlChanged(AEdit); end; end; procedure TConfigDM.LoadFromFile(const AFilename: String); var LConfigFile: TStringList; LIndex: Integer; LSection: String; LPairType: Integer; LSectionOrder, LOrder: Integer; LName, LValue: String; LEqualLocation: Integer; begin if not TFile.Exists(AFilename) then Exit; SettingsMT.EmptyDataSet; LConfigFile := TStringList.Create; try LConfigFile.LoadFromFile(AFilename); LSectionOrder := 0; LOrder := 0; for LIndex := 0 to LConfigFile.Count - 1 do begin if LConfigFile[LIndex].StartsWith('[') then begin LSection := LConfigFile[LIndex].Replace('[', '').Replace(']', ''); LOrder := 0; Inc(LSectionOrder) end else begin if not LConfigFile[LIndex].IsEmpty then begin LPairType := INI_NAME_VALUE_PAIR; if LConfigFile[LIndex].IndexOf(';#') = 0 then begin SettingsMT.AppendRecord([LSection, LConfigFile[LIndex], '', INI_COMMENT, LOrder, LSectionOrder]); end else begin LEqualLocation := LConfigFile[LIndex].IndexOf('='); if LEqualLocation > -1 then begin LName := LConfigFile[LIndex].Substring(0, LEqualLocation); LValue := LConfigFile[LIndex].Substring(LEqualLocation + 1); if LConfigFile[LIndex].IndexOf(';') = 0 then begin LName := LName.Substring(1).TrimLeft; LPairType := INI_COMMENTED_NAME_VALUE_PAIR; end; SettingsMT.AppendRecord([LSection, LName, LValue, LPairType, LOrder, LSectionOrder]); end; end; Inc(LOrder); end; end; end; finally LConfigFile.Free; end; FCurrentFilename := AFilename; end; procedure TConfigDM.SaveToFile(const AFilename: String = ''); var LConfigFile: TStringList; LSection: String; LPairType: Integer; LName, LValue: String; begin LConfigFile := TStringList.Create; try SettingsMT.First; while not SettingsMT.Eof do begin if LSection <> SettingsMT.FieldByName('Section').AsString then begin if LSection <> '' then LConfigFile.Append(''); LSection := SettingsMT.FieldByName('Section').AsString; LConfigFile.Append('[' + LSection + ']'); end; LPairType := SettingsMT.FieldByName('Type').AsInteger; LName := SettingsMT.FieldByName('Name').AsString; LValue := SettingsMT.FieldByName('Value').AsString; case LPairType of INI_NAME_VALUE_PAIR: begin LConfigFile.Append(LName + '=' + LValue); end; INI_COMMENTED_NAME_VALUE_PAIR: begin LConfigFile.Append(';' + LName + '=' + LValue); end; INI_COMMENT: begin LConfigFile.Append(LName); end; end; SettingsMT.Next; end; if AFilename = '' then LConfigFile.SaveToFile(FCurrentFilename) else LConfigFile.SaveToFile(AFilename); finally LConfigFile.Free; end; end; procedure TConfigDM.PairTypeToComment(const APairType: Integer; var ACommented, AComment: Boolean); begin case APairType of INI_NAME_VALUE_PAIR: begin ACommented := False; AComment := False; end; INI_COMMENTED_NAME_VALUE_PAIR: begin ACommented := True; AComment := False; end; INI_COMMENT: begin ACommented := True; AComment := True; end; else AComment := True; ACommented := True; end; end; procedure TConfigDM.LoadSectionList(const ASection: String; AListBox: TListBox; ACallback: TNotifyEvent); var LPairType: Integer; LCommented: Boolean; LComment: Boolean; begin AListBox.BeginUpdate; try AListBox.Clear; SettingsMT.First; while not SettingsMT.Eof do begin if SettingsMT.FieldByName('Section').AsString = ASection then begin LPairType := SettingsMT.FieldByName('Type').AsInteger; PairTypeToComment(LPairType, LCommented, LComment); if not LComment then begin AddSectionListItem(not LCommented, SettingsMT.FieldByName('Name') .AsString, SettingsMT.FieldByName('Value').AsString, AListBox, ACallback); end; end; SettingsMT.Next; end; finally AListBox.EndUpdate; end; end; procedure TConfigDM.RenumberListItems(AListBox: TListBox); var LIndex: Integer; begin for LIndex := 0 to AListBox.Items.Count - 1 do if AListBox.ListItems[LIndex].TagObject <> nil then if AListBox.ListItems[LIndex].TagObject is TNameValueFrame then TNameValueFrame(AListBox.ListItems[LIndex].TagObject).CheckBox.Text := (LIndex + 1).ToString; end; procedure TConfigDM.AddSectionListItem(AEnabled: Boolean; const AName, AValue: String; AListBox: TListBox; ACallback: TNotifyEvent); var LNameValueFrame: TNameValueFrame; LItem: TListBoxItem; begin LItem := TListBoxItem.Create(AListBox); LItem.Parent := AListBox; LItem.Text := ''; LItem.Height := 60; LNameValueFrame := TNameValueFrame.Create(AListBox); LNameValueFrame.Name := ''; LNameValueFrame.CheckBox.Text := (AListBox.Items.Count).ToString; LNameValueFrame.CheckBox.IsChecked := AEnabled; LNameValueFrame.NameEdit.Text := AName; LNameValueFrame.ValueEdit.Text := AValue; LNameValueFrame.Align := TAlignLayout.Top; LNameValueFrame.Parent := LItem; LNameValueFrame.SetCallback(ACallback); LItem.TagObject := LNameValueFrame; end; procedure TConfigDM.SaveSectionList(const ASection: String; AListBox: TListBox); var LNameValueFrame: TNameValueFrame; LPairType: Integer; LIndex: Integer; LSectionOrder: Integer; begin LSectionOrder := -1; SettingsMT.Last; while not SettingsMT.Bof do begin if SettingsMT.FieldByName('Section').AsString = ASection then begin if LSectionOrder = -1 then LSectionOrder := SettingsMT.FieldByName('SectionOrder').AsInteger; if SettingsMT.FieldByName('Type').AsInteger <> INI_COMMENT then SettingsMT.Delete else SettingsMT.Prior; end else SettingsMT.Prior; end; SettingsMT.FindKey([LSectionOrder]); for LIndex := 0 to AListBox.Items.Count - 1 do begin if AListBox.ListItems[LIndex].TagObject <> nil then if AListBox.ListItems[LIndex].TagObject is TNameValueFrame then begin LNameValueFrame := TNameValueFrame(AListBox.ListItems[LIndex].TagObject); LPairType := IfThen(LNameValueFrame.CheckBox.IsChecked, INI_NAME_VALUE_PAIR, INI_COMMENTED_NAME_VALUE_PAIR); SettingsMT.Insert; SettingsMT.FieldByName('Section').AsString := ASection; SettingsMT.FieldByName('Name').AsString := LNameValueFrame.NameEdit.Text; SettingsMT.FieldByName('Value').AsString := LNameValueFrame.ValueEdit.Text; SettingsMT.FieldByName('Type').AsInteger := LPairType; SettingsMT.FieldByName('ItemOrder').AsInteger := LIndex; SettingsMT.FieldByName('SectionOrder').AsInteger := LSectionOrder; SettingsMT.Post; end; end; end; procedure TConfigDM.LoadSection(const ASection: String; AValueMemTable: TFDMemTable; AStatusMemTable: TFDMemTable); var LPairType: Integer; LCommented: Boolean; LComment: Boolean; begin AValueMemTable.Edit; AStatusMemTable.Edit; SettingsMT.First; while not SettingsMT.Eof do begin if SettingsMT.FieldByName('Section').AsString = ASection then begin LPairType := SettingsMT.FieldByName('Type').AsInteger; PairTypeToComment(LPairType, LCommented , LComment); if not LComment then begin AValueMemTable.FieldByName(SettingsMT.FieldByName('Name').AsString).AsString := SettingsMT.FieldByName('Value').AsString; AStatusMemTable.FieldByName(SettingsMT.FieldByName('Name').AsString).AsBoolean := IfThen(SettingsMT.FieldByName('Type').AsInteger = INI_NAME_VALUE_PAIR, -1, 0) <> 0; end; end; SettingsMT.Next; end; AStatusMemTable.Post; AValueMemTable.Post; end; procedure TConfigDM.SaveSection(const ASection: String; AValueMemTable: TFDMemTable; AStatusMemTable: TFDMemTable); var LPairType: Integer; LCommented: Boolean; LComment: Boolean; begin SettingsMT.First; while not SettingsMT.Eof do begin if SettingsMT.FieldByName('Section').AsString = ASection then begin LPairType := SettingsMT.FieldByName('Type').AsInteger; PairTypeToComment(LPairType, LCommented , LComment); if not LComment then begin SettingsMT.Edit; SettingsMT.FieldByName('Value').AsString := AValueMemTable.FieldByName(SettingsMT.FieldByName('Name').AsString).AsString; SettingsMT.FieldByName('Type').AsInteger := IfThen(AStatusMemTable.FieldByName(SettingsMT.FieldByName('Name').AsString).AsBoolean, INI_NAME_VALUE_PAIR, INI_COMMENTED_NAME_VALUE_PAIR); SettingsMT.Post; end; end; SettingsMT.Next; end; end; end.
unit Amazon.Credentials; interface uses Amazon.Environment, Amazon.Utils, {$IFNDEF FPC} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} inifiles; const aws_defaultcredential_file = 'credentials.ini'; type TAmazonCredentials = class(TAmazonEnvironment) private protected public function Iscredential_file: Boolean; procedure Loadcredential_file; end; implementation function TAmazonCredentials.Iscredential_file: Boolean; begin Try result := True; credential_file := GetAWSUserDir; if credential_file <> '' then credential_file := credential_file + '\' + aws_defaultcredential_file; Finally if Not fileExists(credential_file) then result := False; End; end; procedure TAmazonCredentials.Loadcredential_file; var FIniFile: TIniFile; begin if Not fileExists(credential_file) then Exit; Try FIniFile := TIniFile.Create(credential_file); access_key := FIniFile.Readstring(profile, 'aws_access_key_id', access_key); secret_key := FIniFile.Readstring(profile, 'aws_secret_access_key', secret_key); region := FIniFile.Readstring(profile, 'aws_region', region); Finally FIniFile.Free; End; end; end.
unit Vigilante.Build.Observer; interface uses Vigilante.Build.Model; type IBuildObserver = interface(IInterface) ['{E02F4230-5052-4C3F-BC3B-719F9CC620A2}'] procedure NovaAtualizacao(const ABuild: IBuildModel); end; IBuildSubject = interface(IInterface) ['{7101ECE2-303D-40C5-83A6-52BFD3D92E3E}'] procedure Adicionar(const ABuildObserver: IBuildObserver); procedure Remover(const ABuildObserver: IBuildObserver); procedure Notificar(const ABuild: IBuildModel); end; implementation end.
unit ms3dtypes; interface uses morphmath; type MS3D_Header = PACKED RECORD Id : ARRAY [ 0..9 ] OF CHAR; Version : INTEGER END; MS3D_Vertex = PACKED RECORD Flags : BYTE; Position : Vector3D; BoneID : SHORTINT; refCount : BYTE END; MS3D_Triangle = PACKED RECORD Flags : WORD; VertexIndices : array[0..2]of word; VertexNormals : array[0..2]of Vector3D; S, T : array [0..2]of single; SmoothingGroup, GroupIndex : BYTE END; MS3D_Group = PACKED RECORD Flags : BYTE; Name : ARRAY [ 0..31 ] OF CHAR; nTriangles : WORD; TriangleIndices : ARRAY OF WORD; MaterialIndex : BYTE END; MS3D_Material = PACKED RECORD Name : ARRAY [ 0..31 ] OF CHAR; Ambient, Diffuse, Specular, Emissive : array[0..3]of single; Shininess, Transparency : SINGLE; Mode : BYTE; //unused! Texture, Alphamap : ARRAY [ 0..127 ] OF CHAR END; MS3D_Joint = PACKED RECORD Flags : BYTE; Name, ParentName : ARRAY [ 0..31 ] OF CHAR; Rotation, Translation : Vector3D; nRotKeyframes, nTransKeyframes : WORD END; MS3D_Keyframe = PACKED RECORD Time : SINGLE; Parameter : Vector3D END; TJointName = PACKED RECORD JointIndex : WORD; Name : STRING END; TModelKeyframe = RECORD JointIndex : WORD; Time : SINGLE; //in ms Parameter : Vector3D END; TModelJoint = RECORD LocalRotation, LocalTranslation : Vector3D; AbsoluteMatrix, RelativeMatrix, FinalMatrix : Matrix; CurTransKeyframe, CurRotKeyframe : WORD; Parent : INTEGER; nRotationKeyframes, nTranslationKeyframes : WORD; RotationKeyframes, TranslationKeyframes : ARRAY OF TModelKeyframe END; implementation end.
{ GMPolylineVCL unit ES: contiene las clases VCL necesarias para mostrar polilíneas en un mapa de Google Maps mediante el componente TGMMap EN: includes the VCL classes needed to show polylines on Google Map map using the component TGMMap ========================================================================= MODO DE USO/HOW TO USE ES: poner el componente en el formulario, linkarlo a un TGMMap y poner las polilíneas a mostrar EN: put the component into a form, link to a TGMMap and put the polylines to show ========================================================================= History: ver 1.1.0 ES: nuevo: TPolyline -> añadida propiedad CurveLine. nuevo: TGMPolyline -> añadido evento OnCurveLineChange. EN: new: TPolyline -> added CurveLine property. new: TGMPolyline -> added OnCurveLineChange event. ver 1.0.0 ES: nuevo: se añade la propiedad TIconSequence.Icon. EN: new: TIconSequence.Icon property is added. ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con FireMonkey EN: new: documentation new: now compatible with FireMonkey ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMPolylineVCL unit includes the VCL classes needed to show polylines on Google Map map using the component TGMMap. @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMPolylineVCL contiene las clases VCL necesarias para mostrar polilíneas en un mapa de Google Maps mediante el componente TGMMap @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} unit GMPolylineVCL; {$I ..\gmlib.inc} interface uses {$IFDEF DELPHIXE2} System.Classes, Vcl.Graphics, {$ELSE} Classes, Graphics, {$ENDIF} GMPolyline, GMLinkedComponents; type {*------------------------------------------------------------------------------ VCL class to determine the symbol to show along the path. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para determinar el símbolo a mostrar a lo largo del camino. -------------------------------------------------------------------------------} TSymbol = class(TCustomSymbol) private {*------------------------------------------------------------------------------ The fill color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color de relleno. -------------------------------------------------------------------------------} FFillColor: TColor; {*------------------------------------------------------------------------------ The stroke color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color del trazo. -------------------------------------------------------------------------------} FStrokeColor: TColor; procedure SetFillColor(const Value: TColor); procedure SetStrokeColor(const Value: TColor); protected function GetFillColor: string; override; function GetStrokeColor: string; override; public constructor Create; override; procedure Assign(Source: TPersistent); override; published property FillColor: TColor read FFillColor write SetFillColor default clRed; property StrokeColor: TColor read FStrokeColor write SetStrokeColor default clRed; end; {*------------------------------------------------------------------------------ VCL class to determine the icon and repetition to show in the polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para determinar el icono y la repetición a mostrar en la polilínea. -------------------------------------------------------------------------------} TIconSequence = class(TCustomIconSequence) private {*------------------------------------------------------------------------------ Icon properties. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Propiedades del icono. -------------------------------------------------------------------------------} FIcon: TSymbol; protected procedure CreatePropertiesWithColor; override; public destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Icon: TSymbol read FIcon write FIcon; end; {*------------------------------------------------------------------------------ VCL base class for polylines and polygons. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL base para las polilineas y polígonos. -------------------------------------------------------------------------------} TBasePolylineVCL = class(TBasePolyline) private {*------------------------------------------------------------------------------ The stroke color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color del trazo. -------------------------------------------------------------------------------} FStrokeColor: TColor; procedure SetStrokeColor(const Value: TColor); protected function GetStrokeColor: string; override; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published property StrokeColor: TColor read FStrokeColor write SetStrokeColor default clBlack; end; {*------------------------------------------------------------------------------ VCL class for polylines. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polyline -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para las polilineas. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polyline -------------------------------------------------------------------------------} TPolyline = class(TBasePolylineVCL) private {*------------------------------------------------------------------------------ Features for a curve line polyline. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Propiedades para una polilínea con linea curva. -------------------------------------------------------------------------------} FCurveLine: TCurveLine; {*------------------------------------------------------------------------------ Features for icon and repetition. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Características para el icono y la repetición. -------------------------------------------------------------------------------} FIcon: TIconSequence; procedure OnIconChange(Sender: TObject); procedure OnCurveLineChange(Sender: TObject); protected function ChangeProperties: Boolean; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Icon: TIconSequence read FIcon write FIcon; property CurveLine: TCurveLine read FCurveLine write FCurveLine; end; {*------------------------------------------------------------------------------ VCL class for polylines collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para la colección de polilíneas. -------------------------------------------------------------------------------} TPolylines = class(TBasePolylines) private procedure SetItems(I: Integer; const Value: TPolyline); function GetItems(I: Integer): TPolyline; protected function GetOwner: TPersistent; override; public function Add: TPolyline; function Insert(Index: Integer): TPolyline; {*------------------------------------------------------------------------------ Lists the polylines in the collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Lista de polilíneas en la colección. -------------------------------------------------------------------------------} property Items[I: Integer]: TPolyline read GetItems write SetItems; default; end; {*------------------------------------------------------------------------------ Class management of polylines. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para la gestión de polilíneas. -------------------------------------------------------------------------------} TGMPolyline = class(TGMBasePolyline) private {*------------------------------------------------------------------------------ This event is fired when the polyline's Icon property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad Icon de una polilínea. -------------------------------------------------------------------------------} FOnIconChange: TLinkedComponentChange; {*------------------------------------------------------------------------------ This event is fired when the polyline's CurveLine property are changed. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Este evento ocurre cuando cambia la propiedad CurveLine de una polilínea. -------------------------------------------------------------------------------} FOnCurveLineChange: TLinkedComponentChange; protected function GetAPIUrl: string; override; function GetItems(I: Integer): TPolyline; function GetCollectionItemClass: TLinkedComponentClass; override; function GetCollectionClass: TLinkedComponentsClass; override; public {*------------------------------------------------------------------------------ Creates a new TPolyline instance and adds it to the Items array. @return New TPolyline -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Crea una nueva instancia de TPolyline y la añade en el array de Items. @return Nuevo TPolyline -------------------------------------------------------------------------------} function Add: TPolyline; {*------------------------------------------------------------------------------ Array with the collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Array con la colección de elementos. -------------------------------------------------------------------------------} property Items[I: Integer]: TPolyline read GetItems; default; published property OnIconChange: TLinkedComponentChange read FOnIconChange write FOnIconChange; property OnCurveLineChange: TLinkedComponentChange read FOnCurveLineChange write FOnCurveLineChange; end; implementation uses {$IFDEF DELPHIXE2} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} GMFunctionsVCL, GMConstants; { TSymbol } procedure TSymbol.Assign(Source: TPersistent); begin inherited; if Source is TSymbol then begin FillColor := TSymbol(Source).FillColor; StrokeColor := TSymbol(Source).StrokeColor; end; end; constructor TSymbol.Create; begin inherited; FFillColor := clRed; FStrokeColor := clRed; end; function TSymbol.GetFillColor: string; begin Result := TTransform.TColorToStr(FFillColor); end; function TSymbol.GetStrokeColor: string; begin Result := TTransform.TColorToStr(FStrokeColor); end; procedure TSymbol.SetFillColor(const Value: TColor); begin if FFillColor = Value then Exit; FFillColor := Value; if Assigned(OnChange) then OnChange(Self); end; procedure TSymbol.SetStrokeColor(const Value: TColor); begin if FStrokeColor = Value then Exit; FStrokeColor := Value; if Assigned(OnChange) then OnChange(Self); end; { TIconSequence } procedure TIconSequence.Assign(Source: TPersistent); begin inherited; if Source is TIconSequence then begin Icon.Assign(TIconSequence(Source).Icon); end; end; procedure TIconSequence.CreatePropertiesWithColor; begin inherited; Icon := TSymbol.Create; Icon.OnChange := OnIconChange; end; destructor TIconSequence.Destroy; begin if Assigned(FIcon) then FreeAndNil(FIcon); inherited; end; { TBasePolylineVCL } procedure TBasePolylineVCL.Assign(Source: TPersistent); begin inherited; if Source is TBasePolylineVCL then begin StrokeColor := TBasePolylineVCL(Source).StrokeColor; end; end; constructor TBasePolylineVCL.Create(Collection: TCollection); begin inherited; FStrokeColor := clBlack; end; function TBasePolylineVCL.GetStrokeColor: string; begin Result := TTransform.TColorToStr(FStrokeColor); end; procedure TBasePolylineVCL.SetStrokeColor(const Value: TColor); begin if FStrokeColor = Value then Exit; FStrokeColor := Value; ChangeProperties; if Assigned(TGMPolyline(TPolylines(Collection).FGMLinkedComponent).OnStrokeColorChange) then TGMBasePolyline(TPolylines(Collection).FGMLinkedComponent).OnStrokeColorChange( TGMPolyline(TPolylines(Collection).FGMLinkedComponent), Index, Self); end; { TPolyline } procedure TPolyline.Assign(Source: TPersistent); begin inherited; if Source is TPolyline then begin Icon.Assign(TPolyline(Source).Icon); end; end; function TPolyline.ChangeProperties: Boolean; const StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s'; var Params: string; DistRepeat: string; Offset: string; begin inherited; Result := False; if not Assigned(Collection) or not(Collection is TPolylines) or not Assigned(TPolylines(Collection).FGMLinkedComponent) or //not TGMPolyline(TPolylines(Collection).FGMLinkedComponent).AutoUpdate or not Assigned(TGMPolyline(TPolylines(Collection).FGMLinkedComponent).Map) or (csDesigning in TGMPolyline(TPolylines(Collection).FGMLinkedComponent).ComponentState) then Exit; case Icon.DistRepeat.Measure of mPixels: DistRepeat := IntToStr(Icon.DistRepeat.Value) + 'px'; else DistRepeat := IntToStr(Icon.DistRepeat.Value) + '%'; end; case Icon.OffSet.Measure of mPixels: Offset := IntToStr(Icon.OffSet.Value) + 'px'; else Offset := IntToStr(Icon.OffSet.Value) + '%'; end; Params := Format(StrParams, [ IntToStr(IdxList), IntToStr(Index), LowerCase(TTransform.GMBoolToStr(Clickable, True)), LowerCase(TTransform.GMBoolToStr(Editable, True)), LowerCase(TTransform.GMBoolToStr(Geodesic, True)), QuotedStr(GetStrokeColor), StringReplace(FloatToStr(StrokeOpacity), ',', '.', [rfReplaceAll]), IntToStr(StrokeWeight), LowerCase(TTransform.GMBoolToStr(Visible, True)), QuotedStr(PolylineToStr), QuotedStr(InfoWindow.GetConvertedString), LowerCase(TTransform.GMBoolToStr(InfoWindow.DisableAutoPan, True)), IntToStr(InfoWindow.MaxWidth), IntToStr(InfoWindow.PixelOffset.Height), IntToStr(InfoWindow.PixelOffset.Width), LowerCase(TTransform.GMBoolToStr(InfoWindow.CloseOtherBeforeOpen, True)), QuotedStr(DistRepeat), QuotedStr(Icon.Icon.GetFillColor), StringReplace(FloatToStr(Icon.Icon.FillOpacity), ',', '.', [rfReplaceAll]), QuotedStr(TTransform.SymbolPathToStr(Icon.Icon.Path)), QuotedStr(Icon.Icon.GetStrokeColor), StringReplace(FloatToStr(Icon.Icon.StrokeOpacity), ',', '.', [rfReplaceAll]), IntToStr(Icon.Icon.StrokeWeight), QuotedStr(Offset), LowerCase(TTransform.GMBoolToStr(CurveLine.Active, True)), LowerCase(TTransform.GMBoolToStr(CurveLine.Horizontal, True)), IntToStr(CurveLine.Multiplier), StringReplace(FloatToStr(CurveLine.Resolution), ',', '.', [rfReplaceAll]) ]); Result := TGMPolyline(TPolylines(Collection).FGMLinkedComponent).ExecuteScript('MakePolyline', Params); TGMPolyline(TPolylines(Collection).FGMLinkedComponent).ErrorControl; end; constructor TPolyline.Create(Collection: TCollection); begin inherited Create(Collection); FIcon := TIconSequence.Create(Self); FIcon.OnChange := OnIconChange; FCurveLine := TCurveLine.Create; FCurveLine.OnChange := OnCurveLineChange; end; destructor TPolyline.Destroy; begin if Assigned(FIcon) then FreeAndNil(FIcon); if Assigned(FCurveLine) then FreeAndNil(FCurveLine); inherited; end; procedure TPolyline.OnCurveLineChange(Sender: TObject); begin if ChangeProperties and Assigned(TGMPolyline(TPolylines(Collection).FGMLinkedComponent).FOnCurveLineChange) then TGMPolyline(TPolylines(Collection).FGMLinkedComponent).FOnCurveLineChange( TGMPolyline(TPolylines(Collection).FGMLinkedComponent), Index, Self); end; procedure TPolyline.OnIconChange(Sender: TObject); begin if ChangeProperties and Assigned(TGMPolyline(TPolylines(Collection).FGMLinkedComponent).FOnIconChange) then TGMPolyline(TPolylines(Collection).FGMLinkedComponent).FOnIconChange( TGMPolyline(TPolylines(Collection).FGMLinkedComponent), Index, Self); end; { TPolylines } function TPolylines.Add: TPolyline; begin Result := TPolyline(inherited Add); end; function TPolylines.GetItems(I: Integer): TPolyline; begin Result := TPolyline(inherited Items[I]); end; function TPolylines.GetOwner: TPersistent; begin Result := TGMPolyline(inherited GetOwner); end; function TPolylines.Insert(Index: Integer): TPolyline; begin Result := TPolyline(inherited Insert(Index)); end; procedure TPolylines.SetItems(I: Integer; const Value: TPolyline); begin inherited SetItem(I, Value); end; { TGMPolyline } function TGMPolyline.Add: TPolyline; begin Result := TPolyline(inherited Add); end; function TGMPolyline.GetAPIUrl: string; begin Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#Polyline'; end; function TGMPolyline.GetCollectionClass: TLinkedComponentsClass; begin Result := TPolylines; end; function TGMPolyline.GetCollectionItemClass: TLinkedComponentClass; begin Result := TPolyline; end; function TGMPolyline.GetItems(I: Integer): TPolyline; begin Result := TPolyline(inherited Items[i]); end; end.
unit StoreHouseListQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 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, Vcl.StdCtrls, DSWrap, BaseEventsQuery, StoreHouseListInterface, ProductsInterface; type TStoreHouseListW = class(TDSWrap, IStorehouseList) strict private function GetStoreHouseCount: Integer; function GetStoreHouseTitle: string; private FAbbreviation: TFieldWrap; FAddress: TFieldWrap; FResponsible: TFieldWrap; FTitle: TFieldWrap; FID: TFieldWrap; FProductsInt: IProducts; public constructor Create(AOwner: TComponent); override; procedure AddNewValue(const AValue: string); function LocateByAbbreviation(const AAbbreviation: string): Boolean; function LocateOrAppend(const AValue: string): Boolean; property Abbreviation: TFieldWrap read FAbbreviation; property Address: TFieldWrap read FAddress; property Responsible: TFieldWrap read FResponsible; property Title: TFieldWrap read FTitle; property ID: TFieldWrap read FID; property ProductsInt: IProducts read FProductsInt write FProductsInt; end; TQueryStoreHouseList = class(TQueryBaseEvents) FDUpdateSQL: TFDUpdateSQL; procedure FDQueryDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure FDQueryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); private FW: TStoreHouseListW; procedure DoBeforePost(Sender: TObject); { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; property W: TStoreHouseListW read FW; { Public declarations } end; implementation uses NotifyEvents, RepositoryDataModule, StrHelper, FireDAC.Phys.SQLiteWrapper; {$R *.dfm} { TfrmQueryStoreHouseList } constructor TQueryStoreHouseList.Create(AOwner: TComponent); begin inherited Create(AOwner); FW := FDSWrap as TStoreHouseListW; TNotifyEventWrap.Create(W.BeforePost, DoBeforePost, W.EventList); end; function TQueryStoreHouseList.CreateDSWrap: TDSWrap; begin Result := TStoreHouseListW.Create(FDQuery); end; procedure TQueryStoreHouseList.DoBeforePost(Sender: TObject); begin if W.Title.F.AsString.Trim.IsEmpty then raise Exception.Create('Не задано наименование склада'); // Если сокращённое наименование не задано if (FDQuery.State = dsInsert) and W.Abbreviation.F.IsNull then begin W.Abbreviation.F.AsString := DeleteDouble(W.Title.F.AsString, ' ') .Replace(' ', ''); end; end; procedure TQueryStoreHouseList.FDQueryDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); var ASQLiteNativeException: ESQLiteNativeException; begin inherited; if not(E is ESQLiteNativeException) then Exit; ASQLiteNativeException := E as ESQLiteNativeException; if ASQLiteNativeException.ErrorCode = 787 then E.Message := 'Нельзя удалить склад, т.к. есть связанные с ним счета.' end; procedure TQueryStoreHouseList.FDQueryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); begin inherited; if AException.Message = '[FireDAC][Phys][SQLite] ERROR: UNIQUE constraint failed: Storehouse.Title' then AException.Message := 'Наименование склада должно быть уникальным'; end; constructor TStoreHouseListW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FAbbreviation := TFieldWrap.Create(Self, 'Abbreviation', 'Склад'); FTitle := TFieldWrap.Create(Self, 'Title', 'Наименование'); FResponsible := TFieldWrap.Create(Self, 'Responsible'); FAddress := TFieldWrap.Create(Self, 'Address'); end; procedure TStoreHouseListW.AddNewValue(const AValue: string); begin TryAppend; Title.F.AsString := AValue; TryPost; end; function TStoreHouseListW.GetStoreHouseCount: Integer; begin Result := DataSet.RecordCount; end; function TStoreHouseListW.GetStoreHouseTitle: string; begin Result := Title.F.AsString; end; function TStoreHouseListW.LocateByAbbreviation(const AAbbreviation : string): Boolean; begin Assert(not AAbbreviation.IsEmpty); Result := FDDataSet.Locate(Abbreviation.FieldName, AAbbreviation, []); end; function TStoreHouseListW.LocateOrAppend(const AValue: string): Boolean; begin // Ищем склад по имени без учёта регистра Result := FDDataSet.LocateEx(Title.FieldName, AValue, [lxoCaseInsensitive]); if not Result then AddNewValue(AValue); end; end.
unit Nodes; interface uses Classes, SysUtils; type TNodeKind = Integer; TNode = class protected FAnno: TStringList; public constructor Create; constructor CreateArgs(const AArgs: array of TNode); destructor Destroy; override; class function GetKind: TNodeKind; virtual; abstract; class function GetNrofSons: Integer; virtual; abstract; function GetSon(I: Integer): TNode; virtual; abstract; procedure SetSon(I: Integer; ANode: TNode); virtual; abstract; class function OpName: String; virtual; abstract; function HasData: Boolean; function GetData: String; virtual; procedure SetAnno(AName: String; AObject: TObject); function HasAnno(AName: String): Boolean; function GetAnno(AName: String): TObject; procedure ClearAllAnno; end; TNodeClass = class of TNode; ENodeError = class(Exception) end; ESetSonIndex = class(ENodeError) end; EGetSonIndex = class(ENodeError) end; EGetAnno = class(ENodeError) end; ENodeKind = class(ENodeError) end; implementation {==========================================} constructor TNode.Create; begin inherited Create; FAnno := TStringList.Create; end; constructor TNode.CreateArgs(const AArgs: array of TNode); var I: Integer; begin Create; for I := 0 to High(AArgs) do SetSon(I, AArgs[I]); end; destructor TNode.Destroy; begin FAnno.Free; inherited Destroy; end; function TNode.HasData: Boolean; begin Result := GetData <> ''; end; function TNode.GetData: String; begin Result := ''; end; procedure TNode.SetAnno(AName: String; AObject: TObject); var I: Integer; begin I := FAnno.IndexOf(AName); if I = -1 then FAnno.AddObject(AName, Aobject) else FAnno.Objects[I] := AObject; end; function TNode.HasAnno(AName: String): Boolean; begin Result := FAnno.Indexof(AName) <> -1; end; function TNode.GetAnno(AName: String): TObject; var I: Integer; begin I := FAnno.IndexOf(AName); if I = -1 then raise EGetAnno.Create('Error in GetAnno with argument: '+ AName) else Result := FAnno.Objects[I]; end; procedure TNode.ClearAllAnno; begin FAnno.Clear; end; end.
unit VCLBI.Menus; // Menu related helper classes interface uses System.Classes, VCL.Controls, VCL.Menus; type TBIMenu=record public class function Add(const AMenu:TMenu; const ACaption:String; const AClick:TNotifyEvent=nil):TMenuItem; overload; static; class function Add(const AItem:TMenuItem; const ACaption:String; const AClick:TNotifyEvent=nil):TMenuItem; overload; static; class function AddSeparator(const AMenu:TMenu):TMenuItem; static; class procedure Popup(const APopup:TPopupMenu; const AParent:TControl); static; class function NewItem(const AOwner:TComponent; const ACaption:String; const AClick:TNotifyEvent):TMenuItem; static; end; implementation
Unit SDKUtils; procedure test; begin writeln('test'); end;
// ################################## // # TPLVisor - Michel Kunkler 2013 # // ################################## (* Diese Unit ist für die GUI verantwortlich. Hier werden sämtliche Anzeigerelevante Operationen durchgeführt. Außerdem finden sich hier die Eingangspunkte für die Events der meisten Objekte. Sämtliche andere Units sind im InterfaceTeil bereits eingebunden. *) unit TPLVisorMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus, ComCtrls, Spin, TPLParser, TPLInterpreter, TPLTuringmaschine, TPLMagnetband, TPLZeichen, TPLBefehle, TPLErrors; type TTPLVisorForm = class(TForm) Parse: TButton; Ausfuehren: TButton; Einzelschritt: TButton; AusfuehrenGB: TGroupBox; MainMenu: TMainMenu; Datei1: TMenuItem; Laden1: TMenuItem; Speichern1: TMenuItem; ber1: TMenuItem; ParserGB: TGroupBox; FehlerMemo: TMemo; Weiter: TButton; Pause: TButton; TuringmaschineGB: TGroupBox; TPLGB: TGroupBox; LifeGB: TGroupBox; Informationen1: TMenuItem; Schritte1: TMenuItem; SofortAusfuehren: TButton; Band: TPanel; BandRechts: TButton; BandLinks: TButton; Timer1: TTimer; Magnetband1: TMenuItem; Reset: TButton; InterpreterGB: TGroupBox; InterpreterEdit: TEdit; TPLMemo: TRichEdit; Intervall: TSpinEdit; Label1: TLabel; Magnetband2: TMenuItem; exportieren1: TMenuItem; importieren1: TMenuItem; procedure ParseClick(Sender: TObject); procedure AusfuehrenClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure BandLinksClick(Sender: TObject); procedure BandRechtsClick(Sender: TObject); procedure Magnetband1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ResetClick(Sender: TObject); procedure ber1Click(Sender: TObject); procedure Schritte1Click(Sender: TObject); procedure SofortAusfuehrenClick(Sender: TObject); procedure PauseClick(Sender: TObject); procedure WeiterClick(Sender: TObject); procedure EinzelschrittClick(Sender: TObject); procedure Laden1Click(Sender: TObject); procedure Speichern1Click(Sender: TObject); procedure IntervallChange(Sender: TObject); procedure exportieren1Click(Sender: TObject); procedure importieren1Click(Sender: TObject); private { Private-Deklarationen } Parser : TParser; Turingmaschine : TTuringmaschine; Interpreter : TInterpreter; public { Public-Deklarationen } Padding : integer; Schritt : integer; procedure RotFaerben(Start : integer; Ende : integer); procedure CreateZeichen(ZShape : TShape; ZEdit : TEdit; VLeft : integer); procedure VerschiebeZeichen(Zeichen : TObject; Wert : integer); end; var TPLVisorForm: TTPLVisorForm; implementation {$R *.dfm} (* Färbt Text im Codememo (TPLMemo) rot. Start : Erwartet die Startposition, beginnent bei 0 Ende : Erwartet die Endposition. *) procedure TTPLVisorForm.RotFaerben(Start : integer; Ende : integer); begin // alles auf schwarz setzen self.TPLMemo.SelStart := 0; self.TPLMemo.SelLength := -1; self.TPLMemo.SelAttributes.Color := clBlack; // Bereich rot färben self.TPLMemo.SelStart := Start; self.TPLMemo.SelLength := Ende-Start; self.TPLMemo.SelAttributes.Color := clRed; end; (* Gibt einem erzeugtem Zeichen des Magnetbands seine Eigenschaften. ZShape : Shape Objekt des Zeichens ZEdit : Edit Objekt des Zeichens VLeft : Position "Left" des ZShape Objekts. *) procedure TTPLVisorForm.CreateZeichen(ZShape : TShape; ZEdit : TEdit; VLeft : integer); begin ShowMessage('gerde'); with ZShape do begin Width := 50; Height := 50; Left := VLeft; Top := 25; Shape := stRectangle; Parent := self.Band; SendToBack(); end; with ZEdit do begin AutoSize := False; Text := '#'; Left := VLeft+1; Top := 26; Parent := self.Band; Font.Height := 48; Width := 48; Height := 48; SendToBack; end; end; (* Verschiebt ein Zeichen um einen gewünschten Wert. Zeichen : Zu verschiebendes Zeichen. Wert : Weite um die das Zeichen verschoben wird in Pixel. Positive Werte -> Rechts, Negative WErte -> Links. *) procedure TTPLVisorForm.VerschiebeZeichen(Zeichen : TObject; Wert : integer); begin TZeichen(Zeichen).ZShape.Left := TZeichen(Zeichen).ZShape.Left+Wert; TZeichen(Zeichen).ZEdit.Left := TZeichen(Zeichen).ZShape.Left+1; end; (* Event, das beim Klicken auf den Butten "Parsen" aufgerufen wird. Erzeugt eine Parserinstanz (neu) und ruft die Methode "Parse(TStringList)" auf. *) procedure TTPLVisorForm.ParseClick(Sender: TObject); begin self.FehlerMemo.Clear; if self.Parser <> nil then self.Parser.Destroy; self.Parser := TParser.Create(self.FehlerMemo); TParser(self.Parser).Parse(self.TPLMemo.Lines); end; (* Event, das beim Klicken auf "Programm ausführen" aufgerufen wird. Erzeugt eine Interpreterinstanz (neu) und startet den Interpretertimer (Timer1). *) procedure TTPLVisorForm.AusfuehrenClick(Sender: TObject); begin if self.Parser = nil then begin ShowMessage(InterpreterError.NichtGeparst); exit; end; try self.Intervall.Color := clWindow; self.Timer1.Interval := self.Intervall.Value; self.Timer1.Enabled := True; if self.Interpreter <> nil then self.Interpreter.Destroy; self.Interpreter := TInterpreter.Create(self, self.Turingmaschine, self.Parser); except self.Intervall.Color := clRed; end; end; (* Event, das nach einem festgelegten Timerintervall aufgerufen wird. Ruft die Methode "interpretiere" der Interpreterinstanz auf. *) procedure TTPLVisorForm.Timer1Timer(Sender: TObject); begin if self.Interpreter.Stop then begin self.InterpreterEdit.Text := 'Programm beendet.'; self.Timer1.Enabled := False; end else begin self.Interpreter.interpretiere; end; end; (* Event, das beim klicken auf "<<" aufgerufen wird. Verschiebt die Ansicht des Magnetbandes nach links. *) procedure TTPLVisorForm.BandLinksClick(Sender: TObject); begin if self.Turingmaschine <> nil then self.Turingmaschine.Magnetband.ZeigeLinks; end; (* Event, das beim klicken auf ">>" aufgerufen wird. Verschiebt die Ansicht des Magnetbandes nach rechts. *) procedure TTPLVisorForm.BandRechtsClick(Sender: TObject); begin if self.Turingmaschine <> nil then self.Turingmaschine.Magnetband.ZeigeRechts; end; (* Event, das beim klicken auf "Informationen->Magnetband" im Hauptmenü aufgerufen wird. Zeigt die größe des Magnetbandes. *) procedure TTPLVisorForm.Magnetband1Click(Sender: TObject); begin ShowMessage(inttostr(self.Turingmaschine.Magnetband.Laenge)); end; (* Event, das beim Starten des Programmes aufgerufen wird. *) procedure TTPLVisorForm.FormCreate(Sender: TObject); begin self.Padding := 10; // 10 px padding zwischen Magnetbandelementen self.Schritt := 20; // Schrittlaenge = 20 px self.Turingmaschine := TTuringmaschine.Create(self); end; (* Event, das beim klicken auf "Magnetband resetten" aufgerufen wird. Erzeugt die Instanz der Klasse TTuringmaschine neu. *) procedure TTPLVisorForm.ResetClick(Sender: TObject); begin if self.Turingmaschine <> nil then begin self.Turingmaschine.Destroy; self.Turingmaschine := TTuringmaschine.Create(self); end; end; (* Event, das beim klicken auf "Über" im Hauptmenü aufgerufen wird. *) procedure TTPLVisorForm.ber1Click(Sender: TObject); begin ShowMessage('Michel Kunkler - 2013'); end; (* Event, das beim klicken auf "Informationen->Schritte" im Hauptmenü aufgerufen wird. Zeigt die Anzahl der Schritte, die die Turingmaschine abgearbeitet hat an. *) procedure TTPLVisorForm.Schritte1Click(Sender: TObject); begin if self.Interpreter <> nil then ShowMessage(inttostr(self.Interpreter.Schritte)); end; (* Event, das beim klicken auf "Sofort ausführen" aufgerufen wird. Ruft die Methode "interpretiere" der Turingmaschine so lange auf, bis die Turingmaschine angehalten hat. *) procedure TTPLVisorForm.SofortAusfuehrenClick(Sender: TObject); begin self.ParseClick(self); if self.Parser <> nil then begin self.Interpreter := TInterpreter.Create(self, self.Turingmaschine, self.Parser); while self.Interpreter.Stop <> True do self.Interpreter.interpretiere; end; end; (* Event, das beim klicken auf "Pause" aufgerufen wird. Pausiert die Ausführung der Turingmaschine. *) procedure TTPLVisorForm.PauseClick(Sender: TObject); begin if self.Interpreter <> nil then self.Timer1.Enabled := False; end; (* Event, das beim klicken auf "Weiter" aufgerufen wird. Setzt die Ausführung der Turingmaschine fort. *) procedure TTPLVisorForm.WeiterClick(Sender: TObject); begin if self.Interpreter <> nil then self.Timer1.Enabled := True; end; (* Event, das beim klicken auf "Einzelschritt" aufgerufen wird. Interpretiert einen Befehl. *) procedure TTPLVisorForm.EinzelschrittClick(Sender: TObject); begin if (self.Interpreter <> nil) and (self.Interpreter.Stop = False) then self.Interpreter.interpretiere; end; (* Event, das beim klicken auf "Datei->Laden" im Hauptmenü aufgerufen wird. Lädt Code in das Codememo (TPLMemo) *) procedure TTPLVisorForm.Laden1Click(Sender: TObject); var OpenDialog : TOpenDialog; begin OpenDialog := TOpenDialog.Create(self); OpenDialog.Filter := 'TPLVisor Code|*.tpl'; if OpenDialog.Execute then self.TPLMemo.Lines.LoadFromFile(OpenDialog.FileName); end; (* Event, das beim klicken auf "Datei->Speichern" im Hauptmenü aufgerufen wird. Speichert den Code des Codememos (TPLMemo) *) procedure TTPLVisorForm.Speichern1Click(Sender: TObject); var SaveDialog : TSaveDialog; begin SaveDialog := TSaveDialog.Create(self); SaveDialog.Filter := 'TPLVisor Code|*.tpl'; SaveDialog.DefaultExt := 'tpl'; if SaveDialog.Execute then self.TPLMemo.Lines.SaveToFile(SaveDialog.FileName); end; (* Event, das beim ändern der Intervallgeschwindigkeit aufgerufen wird. *) procedure TTPLVisorForm.IntervallChange(Sender: TObject); begin try self.Timer1.Interval := self.Intervall.Value; except end; end; (* Event, das beim klicken auf "Datei->Magnetband->exportieren" im Hauptmenü aufgerufen wird. Speichert das Magnetband als Zeichenkette. *) procedure TTPLVisorForm.exportieren1Click(Sender: TObject); var SaveDialog : TSaveDialog; Text : TStringList; begin if self.Turingmaschine = nil then exit; SaveDialog := TSaveDialog.Create(self); SaveDialog.Filter := 'TPLVisor Magnetband|*.tub'; SaveDialog.DefaultExt := 'tub'; if SaveDialog.Execute then begin Text := TStringList.Create; Text.Add(self.Turingmaschine.MagnetbandToString); Text.SaveToFile(SaveDialog.FileName); end; end; (* Event, das beim klicken auf "Datei->Magnetband->importieren" im Hauptmenü aufgerufen wird. Lädt ein Magnetband von einer Datei. *) procedure TTPLVisorForm.importieren1Click(Sender: TObject); var OpenDialog : TOpenDialog; Text : TStringList; begin if self.Turingmaschine = nil then exit; OpenDialog := TOpenDialog.Create(self); OpenDialog.Filter := 'TPLVisor Magnetband|*.tub'; if OpenDialog.Execute then begin Text := TStringList.Create; Text.LoadFromFile(OpenDialog.FIleName); self.Turingmaschine.StringToMagnetband(Text[0]); end; end; end.
unit FIToolkit.CommandLine.Types; interface type TCLIOptionString = type String; TCLIOptionStringHelper = record helper for TCLIOptionString public const CHR_SPACE = Char(' '); // do not localize! CHR_QUOTE = Char('"'); // do not localize! end; implementation end.
unit UnitMainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMainForm = class(TForm) ButtonStart: TButton; Memo: TMemo; procedure ButtonStartClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FileList : TStringList; procedure MakeFileList; procedure RepairAllFiles; procedure ReadFile( FileName : string; Lines : TStringList ); procedure RepairFile( Lines : TStringList ); procedure WriteFile( FileName : string; Lines : TStringList ); public { Public declarations } end; var MainForm: TMainForm; implementation uses Registry; {$R *.DFM} //============================================================================== //============================================================================== // // Constructor // //============================================================================== //============================================================================== procedure TMainForm.FormCreate(Sender: TObject); begin FileList := TStringList.Create; end; //============================================================================== //============================================================================== // // Destructor // //============================================================================== //============================================================================== procedure TMainForm.FormDestroy(Sender: TObject); begin FileList.Free; end; //============================================================================== //============================================================================== // // File processing // //============================================================================== //============================================================================== procedure TMainForm.MakeFileList; var Reg : TRegistry; Path : string; SR : TSearchRec; begin FileList.Clear; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey( '\Software\MHD\' , False ); Path := Reg.ReadString( 'Rozvrhy_dir' ); finally Reg.Free; end; if FindFirst( Path+'\*.*' , faAnyFile - faDirectory , SR ) <> 0 then begin FindClose( SR ); exit; end; repeat FileList.Add( Path+'\'+SR.Name ); until FindNext( SR ) <> 0; FindClose( SR ); end; procedure TMainForm.ReadFile( FileName : string; Lines : TStringList ); var Fin : TextFile; S : string; begin AssignFile( Fin , FileName ); {$I-} Reset( Fin ); {$I+} if IOResult <> 0 then exit; Lines.Clear; while not EoF( Fin ) do begin Readln( Fin , S ); Lines.Add( S ); end; CloseFile( Fin ); end; procedure TMainForm.RepairFile( Lines : TStringList ); var I : integer; begin I := 0; while I < Lines.Count do begin if (Lines[I] = '0 0 KONIEC') then begin Inc( I , 2 ); while (Lines[I] = '3') do Lines.Delete( I ); break; end; Inc( I ); end; end; procedure TMainForm.WriteFile( FileName : string; Lines : TStringList ); var I : integer; Fout : TextFile; begin AssignFile( Fout , FileName ); {$I-} Rewrite( Fout ); {$I+} if IOResult <> 0 then exit; for I := 0 to Lines.Count-1 do Writeln( Fout , Lines[I] ); CloseFile( Fout ); end; procedure TMainForm.RepairAllFiles; var I : integer; Lines : TStringList; begin Memo.Clear; Lines := TStringList.Create; try for I := 0 to FileList.Count-1 do begin ReadFile( FileList[I] , Lines ); RepairFile( Lines ); WriteFile( FileList[I] , Lines ); Memo.Lines.Add( FileList[I] ); end; finally Lines.Free; end; end; //============================================================================== //============================================================================== // // Events // //============================================================================== //============================================================================== procedure TMainForm.ButtonStartClick(Sender: TObject); begin Screen.Cursor := crHourGlass; ButtonStart.Enabled := False; try MakeFileList; RepairAllFiles; finally Screen.Cursor := crDefault; ButtonStart.Enabled := True; end; end; end.
unit u_xpl_timer; {============================================================================== UnitName = uxPLTimer UnitDesc = xPL timer management object and function UnitCopyright = GPL by Clinique / xPL Project ============================================================================== 0.90 : Initial version 0.91 : Removed call to TTimer object replaced by TfpTimer (console mode compatibility requirement 0.92 : Modification to stick to timer.basic schema as described in xpl website } {$mode objfpc}{$H+}{$M+} interface uses Classes, fpTimer, u_xpl_header, u_xpl_schema, u_xpl_common, u_xpl_message, u_xpl_collection, u_xpl_custom_message, u_xpl_address; type TTimerMode = (ascending, descending, recurrent); TTimerStatus = (stopped, started, halted, expired); { TxPLTimer } TxPLTimer = class(TxPLCollectionItem) private fMode: TTimerMode; fStatus: TTimerStatus; fFrequency: integer; fRemaining: integer; fTrigMsg: TxPLCustomMessage; fStart_Time, fEnd_Time: TDateTime; fSysTimer: TFPTimer; procedure Set_Mode(const AValue: TTimerMode); protected procedure Set_Status(const aStatus: TTimerStatus); public constructor Create(aOwner: TCollection); override; procedure InitComponent(const aMsg : TxPLMessage); function StatusAsStr: string; procedure SendStatus(const aMsgType: TxPLMessageType = stat); function Target: string; procedure Tick(Sender: TObject); // This procedure should be called every second by owner published property Status: TTimerStatus Read fStatus Write Set_Status; property Mode: TTimerMode Read fMode Write Set_Mode; property Start_Time: TDateTime Read fStart_Time write fStart_Time; property End_Time: TDateTime Read fEnd_Time write fEnd_Time; property Remaining: integer Read fRemaining Write fRemaining; property Frequence: integer Read fFrequency Write fFrequency; end; { TxPLTimerItems } TxPLTimers = specialize TxPLCollection<TxPLTimer> ; var Schema_TimerBasic, Schema_TimerRequest: TxPLSchema; implementation // ============================================================= uses SysUtils , DateUtils , TypInfo , u_xpl_sender , u_xpl_body , u_xpl_application , Math ; {==============================================================================} function DateTimeDiff(Start, Stop: TDateTime): int64; var TimeStamp: TTimeStamp; begin TimeStamp := DateTimeToTimeStamp(Stop - Start); Dec(TimeStamp.Date, TTimeStamp(DateTimeToTimeStamp(0)).Date); Result := (TimeStamp.Date * 24 * 60 * 60) + (TimeStamp.Time div 1000) + 1; end; // TxPLTimer object =========================================================== constructor TxPLTimer.Create(aOwner: TCollection); begin inherited Create(aOwner); fSysTimer := TfpTimer.Create(xPLApplication); fSysTimer.Interval := 1000; fSysTimer.Enabled := False; fSysTimer.OnTimer := @Tick; fTrigMsg := TxPLCustomMessage.Create(xPLApplication); fTrigMsg.Target.IsGeneric := True; fTrigMsg.Schema.Assign(Schema_TimerBasic); fRemaining := 0; fFrequency := 0; end; procedure TxPLTimer.Set_Mode(const AValue: TTimerMode); begin if fMode = AValue then exit; fMode := AValue; if (fMode = Recurrent) and (fFrequency < 1) then fFrequency := 1; end; function TxPLTimer.StatusAsStr: string; begin Result := GetEnumName(TypeInfo(TTimerStatus), Ord(Status)); end; procedure TxPLTimer.InitComponent(const aMsg : TxPLMessage); begin DisplayName := aMsg.Body.GetValueByKey('device'); fRemaining := StrToIntDef(aMsg.Body.GetValueByKey('duration'),0); fFrequency := StrToIntDef(aMsg.Body.GetValueByKey('frequence'),0); if fRemaining = 0 then // 0 sec remaining, it is a UP or RECURRENT timer if fFrequency = 0 then fMode := ascending else fMode := recurrent else // x sec remaining, it is a down timer fMode := descending; fStart_Time := now; if fMode = descending then fEnd_Time := IncSecond(fStart_Time, fRemaining) else fEnd_Time := fStart_Time; Status := started; end; procedure TxPLTimer.Set_Status(const aStatus: TTimerStatus); begin if Status <> aStatus then begin fStatus := aStatus; case fStatus of expired: begin fSysTimer.Enabled := False; fEnd_Time := Now; if fRemaining <> 0 then fStatus := stopped; fRemaining := 0; end; started: fSysTimer.Enabled := True; stopped: begin fSysTimer.Enabled := False; end; end; SendStatus(trig); end; if fStatus = expired then FreeAndNil(self); end; procedure TxPLTimer.SendStatus(const aMsgType: TxPLMessageType = stat); var elapsed : integer; begin if not (csLoading in xPLApplication.ComponentState) then begin fTrigMsg.MessageType := aMsgType; fTrigMsg.Body.ResetValues; fTrigMsg.Body.AddKeyValuePairs(['device', 'current'], [DisplayName, StatusAsStr]); elapsed := Max(DateTimeDiff(Start_Time, now) - 1,0); if elapsed <> 0 then fTrigMsg.Body.AddKeyValuePairs(['elapsed'], [IntToStr(elapsed)]); TxPLSender(xPLApplication).Send(fTrigMsg); end; end; function TxPLTimer.Target: string; begin Result := fTrigMsg.Target.RawxPL; end; procedure TxPLTimer.Tick(Sender: TObject); begin if ((Status = halted) and (End_Time <> 0)) then fEnd_Time := IncSecond(now, fRemaining) else if (Status = started) then case Mode of ascending: Inc(fremaining); descending: begin Dec(fremaining); if fRemaining < 1 then Status := expired; end; recurrent: if Status = started then begin Inc(fremaining); if (fRemaining mod fFrequency = 0) then SendStatus(stat); end; end; end; initialization Schema_TimerBasic := TxPLSchema.Create('timer','basic'); Schema_TimerRequest := TxPLSchema.Create('timer','request'); end.
unit ParamType; interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} Classes, SysUtils, Variants, Menus, ImgList, StdCtrls, ComCtrls, Buttons, ExtCtrls, Graphics, Controls, Forms, Dialogs, DBCtrls, Grids, DBGrids, UniDacVcl, {$IFDEF FPC} LResources, {$ENDIF} DB, DBAccess, DemoFrame, typinfo; type TParamTypeForm = class(TForm) Panel1: TPanel; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; Panel3: TPanel; Label1: TLabel; edParamValue: TEdit; lbValue: TLabel; Panel2: TPanel; Label3: TLabel; lbParameterType: TLabel; btClose: TButton; lbParams: TListBox; Label2: TLabel; rgTypes: TRadioGroup; procedure btCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbParamsClick(Sender: TObject); procedure rgTypesClick(Sender: TObject); procedure edParamValueExit(Sender: TObject); private { Private declarations } public { Public declarations } Params: TParams; end; implementation {$IFNDEF FPC} {$IFDEF CLR} {$R *.nfm} {$ELSE} {$R *.dfm} {$ENDIF} {$ENDIF} procedure TParamTypeForm.btCloseClick(Sender: TObject); begin Close; end; procedure TParamTypeForm.FormShow(Sender: TObject); var i:integer; begin if Params <> nil then begin lbParams.Items.Clear; for i := 0 to Params.Count - 1 do lbParams.Items.Add(Params[i].Name); if Params.Count > 0 then lbParams.ItemIndex:= 0; lbParamsClick(nil); end; end; procedure TParamTypeForm.lbParamsClick(Sender: TObject); begin if lbParams.ItemIndex >= 0 then begin case Params[lbParams.ItemIndex].ParamType of ptUnknown: lbParameterType.Caption := 'Unknown'; ptInput: lbParameterType.Caption := 'Input'; ptOutput: lbParameterType.Caption := 'Output'; ptInputOutput: lbParameterType.Caption := 'InputOutput'; ptResult: lbParameterType.Caption := 'Result'; end; edParamValue.Text := Params[lbParams.ItemIndex].AsString; { edParamValue.Enabled := Params[lbParams.ItemIndex].ParamType in [ptInput, ptInputOutput]; lbValue.Enabled := edParamValue.Enabled; edParamValue.Text := Params[lbParams.ItemIndex].AsString; } case Params[lbParams.ItemIndex].DataType of ftString: rgTypes.ItemIndex:= 0; ftInteger: rgTypes.ItemIndex:= 1; ftFloat: rgTypes.ItemIndex:= 2; ftDate: rgTypes.ItemIndex:= 3; else rgTypes.ItemIndex:= -1; end; end; end; procedure TParamTypeForm.rgTypesClick(Sender: TObject); var DataType: TFieldType; begin if lbParams.ItemIndex >= 0 then begin case rgTypes.ItemIndex of 0: DataType:= ftString; 1: DataType:= ftInteger; 2: DataType:= ftFloat; 3: DataType:= ftDate; else DataType:= ftUnknown; end; Params[lbParams.ItemIndex].DataType:= DataType; Params[lbParams.ItemIndex].Value := edParamValue.Text; end; end; procedure TParamTypeForm.edParamValueExit(Sender: TObject); begin if lbParams.ItemIndex >= 0 then Params[lbParams.ItemIndex].Value := edParamValue.Text; end; {$IFDEF FPC} initialization {$i ParamType.lrs} {$ENDIF} end.
{******************************************************************************* * * * TksPushNotification - Push Notification Component * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 ksPushNotification; interface {$I ksComponents.inc} uses Classes, FMX.MediaLibrary, FMX.Media, FMX.Platform, System.Messaging, FMX.Graphics, ksTypes, System.PushNotification, Json, FMX.Types, {$IFDEF VER290} FMX.Notification {$ELSE} System.Notification {$ENDIF} ; type TksReceivePushTokenEvent = procedure(Sender: TObject; AToken: string) of object; TksReceivePushMessageEvent = procedure(Sender: TObject; AData: TJsonObject) of object; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksPushNotification = class(TComponent) private FAppEvent: IFMXApplicationEventService; FFirebaseSenderID: string; // FTimer: TFmxHandle; FServiceConnection: TPushServiceConnection; FPushService: TPushService; FDeviceToken: string; FNotificationCenter: TNotificationCenter; // FTimerService: IFMXTimerService; // events... FOnReceiveTokenEvent: TksReceivePushTokenEvent; FOnReceivePushMessageEvent: TksReceivePushMessageEvent; //function CreateTimer(AInterval: integer; AProc: TTimerProc): TFmxHandle; // procedure DoCheckStartupNotifications; function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; procedure OnNotificationChange(Sender: TObject; AChange: TPushService.TChanges); procedure OnReceiveNotificationEvent(Sender: TObject; const ANotification: TPushServiceNotification); protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Activate; procedure ClearNotifications; published property FirebaseSenderID: string read FFirebaseSenderID write FFirebaseSenderID stored True; property OnReceiveToken: TksReceivePushTokenEvent read FOnReceiveTokenEvent write FOnReceiveTokenEvent; property OnReceivePushMessageEvent: TksReceivePushMessageEvent read FOnReceivePushMessageEvent write FOnReceivePushMessageEvent; end; procedure Register; implementation uses Types, SysUtils, System.Threading, ksCommon, {$IFDEF VER290} FMX.Dialogs {$ELSE} FMX.DialogService {$ENDIF} {$IFDEF IOS} , FMX.PushNotification.IOS {$ENDIF} {$IFDEF ANDROID} , FMX.PushNotification.Android, FMX.Platform.Android, Androidapi.Helpers, FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes, Androidapi.JNI.Telephony {$ENDIF} ; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksPushNotification]); end; { TksCamara } procedure TksPushNotification.Activate; {$IFDEF ANDROID} var ATask: ITask; {$ENDIF} begin {$IFDEF IOS} FServiceConnection.Active := True; {$ENDIF} {$IFDEF ANDROID} ATask := TTask.Create (procedure () begin try FServiceConnection.Active := True; except on E:Exception do begin TThread.Synchronize(nil, procedure begin TDialogService.ShowMessage(e.Message); end); end; end; end); ATask.Start; {$ENDIF} end; function TksPushNotification.AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; var ICount: integer; ANotification: TPushServiceNotification; begin Result := True; if (AAppEvent = TApplicationEvent.BecameActive) or (AAppEvent = TApplicationEvent.FinishedLaunching) then begin for ICount := Low(FPushService.StartupNotifications) to High(FPushService.StartupNotifications) do begin ANotification := FPushService.StartupNotifications[ICount]; OnReceiveNotificationEvent(Self, ANotification); end; FNotificationCenter.CancelAll; end; end; procedure TksPushNotification.ClearNotifications; begin FNotificationCenter.CancelAll; end; constructor TksPushNotification.Create(AOwner: TComponent); begin inherited; TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(FAppEvent)); if FAppEvent <> nil then FAppEvent.SetApplicationEventHandler(AppEvent); //TPlatformServices.Current.SupportsPlatformService(IFMXTimerService, FTimerService); //CreateTimer(500, DoCheckStartupNotifications); FNotificationCenter := TNotificationCenter.Create(nil); end; { function TksPushNotification.CreateTimer(AInterval: integer; AProc: TTimerProc): TFmxHandle; begin Result := 0; if FTimerService <> nil then Result := FTimerService.CreateTimer(AInterval, AProc); end; } destructor TksPushNotification.Destroy; begin FreeAndNil(FNotificationCenter); inherited; end; { procedure TksPushNotification.DoCheckStartupNotifications; var ICount: integer; ANotification: TPushServiceNotification; begin for ICount := Low(FPushService.StartupNotifications) to High(FPushService.StartupNotifications) do begin ANotification := FPushService.StartupNotifications[ICount]; OnReceiveNotificationEvent(Self, ANotification); end; FNotificationCenter.CancelAll; end; } procedure TksPushNotification.Loaded; var AServiceName: string; begin inherited; {$IFDEF IOS} AServiceName := TPushService.TServiceNames.APS; {$ENDIF} {$IFDEF ANDROID} AServiceName := TPushService.TServiceNames.GCM; {$ENDIF} FPushService := TPushServiceManager.Instance.GetServiceByName(AServiceName); {$IFDEF ANDROID} FPushService.AppProps[TPushService.TAppPropNames.GCMAppID] := FFirebaseSenderID; {$ENDIF} FServiceConnection := TPushServiceConnection.Create(FPushService); FServiceConnection.OnChange := OnNotificationChange; FServiceConnection.OnReceiveNotification := OnReceiveNotificationEvent; end; procedure TksPushNotification.OnNotificationChange(Sender: TObject; AChange: TPushService.TChanges); var AToken: string; begin if (TPushService.TChange.Status in AChange) then begin if (FPushService.Status = TPushService.TStatus.StartupError) then begin FServiceConnection.Active := False; TThread.Synchronize(nil, procedure begin if Pos('java.lang.securityexception', LowerCase(FPushService.StartupError)) > 0 then ksCommon.ShowMessage('Unable to activate push notifications...'+#13+#13+ 'Check that you have enabled "Receive Push Notifications" in Options->Entitlement List') else if Pos('invalid_sender', LowerCase(FPushService.StartupError)) > 0 then ShowMessage('Unable to activate push notifications...'+#13+#13+ 'The FirebaseSenderID value is invalid.') else ShowMessage(FPushService.StartupError); end); Exit; end; end; AToken := Trim(FPushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken]); if AToken <> '' then begin FDeviceToken := AToken; TThread.Synchronize(nil, procedure begin if Assigned(FOnReceiveTokenEvent) then FOnReceiveTokenEvent(Self, FDeviceToken); end); end; end; procedure TksPushNotification.OnReceiveNotificationEvent(Sender: TObject; const ANotification: TPushServiceNotification); var AJson: TJsonObject; begin if Assigned(FOnReceivePushMessageEvent) then begin AJson := ANotification.Json; FOnReceivePushMessageEvent(Self, AJson); end; end; end.
unit csv_parser; interface uses buku_handler, tipe_data; { DEKLARASI FUNGSI DAN PROSEDUR } function baca_csv(filename: string): arr_str; procedure simpan_csv(filename: string; stList: arr_str); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure simpan_csv(filename: string; stList: arr_str); { DESKRIPSI : Prosedur untuk menyimpan file csv dari array of string } { PARAMETER : Nama file yang disimpan dan array of string yang menjadi data tiap baris } { KAMUS LOKAL } var Userfile: text; i : integer; { ALGORITMA } begin Assign(Userfile, filename); Rewrite(Userfile); // write mode for i := 0 to stList.sz-1 do begin writeln(Userfile, stList.st[i]); end; close(userfile); end; function baca_csv(filename: string): arr_str; { DESKRIPSI : Prosedur untuk membaca file csv dan memasukkan ke dalam array of string, yang akan di handle oleh masing-masing handler data seperti buku_handler, pengembalian_handler, dan lainnya } { PARAMETER : Nama file yang di baca } { RETURN : array of string yang menjadi placeholder data } { KAMUS LOKAL } var input : string; userfile: text; ret: arr_str; { ALGORITMA } begin assign(userfile, filename); reset(userfile); // read only mode ret.sz := 0; repeat readln(userfile, input); ret.st[ret.sz] := input; ret.sz := ret.sz+1; until EOF(userfile); close(userfile); baca_csv := ret; end; end.
unit uXplCommon; interface uses XPLMDataAccess, XPLMUtilities; const XPL_MEM_FILE = 'XPL_HIDMACROS_MEMORY_FILE'; XPL_MAX_STRING_SIZE = 1024; HDMC_GET_VAR = 1; HDMC_SET_VAR = 2; HDMC_EXEC_COMMAND = 3; HDMC_COMMAND_BEGIN = 5; HDMC_COMMAND_END = 6; HDMC_SET_POSINTERVAL = 4; COM_SLOTS_COUNT = 8; type Pointer8b = Int64; TXplValue = packed record case Integer of 0: (intData : Integer); 1: (floatData : Single); 2: (doubleData : Double); end; PXplComSlot = ^TXplComSlot; TXplComSlot = packed record XplRequestFlag: byte; HDMcommand: byte; //DataRef: XPLMDataRef; //CommandRef: XPLMCommandRef; DataRef: Pointer8b; CommandRef: Pointer8b; DataType: XPLMDataTypeID; Length: SmallInt; Index: Integer; Writable: Boolean; Value: TXplValue; ValueName: array[0..255] of char; ValueUntyped: array[0..255] of char; StringBuffer: array[0..XPL_MAX_STRING_SIZE-1] of char; end; PXplComRecord = ^TXplComRecord; TXplComRecord = packed record HdmConnected: byte; XplConnected: byte; XplRequestFlag: byte; ComSlots: array[0..COM_SLOTS_COUNT] of TXplComSlot; Debug: Boolean; Latitude: double; Longitude: double; Heading: double; Height: double; PosInterval: Integer; end; TXplVariable = class(TObject) public Name: String; DataType: XPLMDataTypeID; DataRef: Int64; Writable: Boolean; Length: Integer; constructor Create; function IsArray: Boolean; function IsString: Boolean; end; function Pointer2Pointer8b(Input: Pointer) : Pointer8b; function Pointer8b2Pointer(Input: Pointer8b) : Pointer; implementation function Pointer2Pointer8b(Input: Pointer) : Pointer8b; begin {$IFDEF WIN64} Result := Pointer8b(Input); {$ELSE} Result := Pointer8b(Input); {$ENDIF} end; function Pointer8b2Pointer(Input: Pointer8b) : Pointer; begin {$IFDEF WIN64} Result := Pointer(Input); {$ELSE} Result := Pointer(Input); {$ENDIF} end; { TXplVariable } constructor TXplVariable.Create; begin DataRef := 0; end; function TXplVariable.IsArray: Boolean; begin Result := (DataType = xplmType_FloatArray) or (DataType = xplmType_IntArray); end; function TXplVariable.IsString: Boolean; begin Result := (DataType = xplmType_Data); end; end.
unit MapRangeEditItemDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, PASTypes; type TMapRangeEditItemDialog = class(TForm) OKButton: TBitBtn; CancelButton: TBitBtn; LowValueLabel: TLabel; LowValueEdit: TEdit; HighValueLabel: TLabel; HighValueEdit: TEdit; Label4: TLabel; ColorShape: TShape; ColorButton: TButton; ColorDialog: TColorDialog; procedure FormShow(Sender: TObject); procedure ColorButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } MapRangeItemRec : MapRangeItemRecord; end; var MapRangeEditItemDialog: TMapRangeEditItemDialog; implementation {$R *.DFM} {===================================================} Procedure TMapRangeEditItemDialog.FormShow(Sender: TObject); begin with MapRangeItemRec do begin LowValueEdit.Text := LowValue; HighValueEdit.Text := HighValue; ColorShape.Brush.Color := Color; ColorShape.Refresh; end; {with MapRangeItemRec do} end; {FormShow} {===================================================} Procedure TMapRangeEditItemDialog.ColorButtonClick(Sender: TObject); begin ColorDialog.Color := ColorShape.Brush.Color; If ColorDialog.Execute then begin ColorShape.Brush.Color := ColorDialog.Color; ColorShape.Refresh; end; end; {ColorButtonClick} {===================================================} Procedure TMapRangeEditItemDialog.OKButtonClick(Sender: TObject); begin with MapRangeItemRec do begin LowValue := LowValueEdit.Text; HighValue := HighValueEdit.Text; Color := ColorShape.Brush.Color; end; end; {OKButtonClick} end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1999-2001 Borland Software Corp. } { } {*******************************************************} unit PagItems; interface uses Classes, HTTPApp, WebComp, CompProd, SysUtils; type TBasePageItemsProducer = class(TComponentsPageProducer, IGetWebComponentList, ITopLevelWebComponent) private FWebPageItems: TWebComponentList; protected { IGetWebComponentsList } function GetComponentList: TObject; function GetDefaultComponentList: TObject; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure SetChildOrder(Component: TComponent; Order: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property WebPageItems: TWebComponentList read FWebPageItems; end; TPageItemsProducer = class(TBasePageItemsProducer) private FHTMLFile: TFileName; FHTMLDoc: TStrings; procedure SetHTMLFile(const Value: TFileName); procedure SetHTMLDoc(Value: TStrings); protected function GetTemplateStream(out AOwned: Boolean): TStream; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property HTMLDoc: TStrings read FHTMLDoc write SetHTMLDoc; property HTMLFile: TFileName read FHTMLFile write SetHTMLFile; end; implementation constructor TBasePageItemsProducer.Create(AOwner: TComponent); begin FWebPageItems := TWebComponentList.Create(Self); inherited; end; destructor TBasePageItemsProducer.Destroy; begin inherited; FWebPageItems.Free; end; procedure TBasePageItemsProducer.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; WebComponent: TComponent; begin inherited GetChildren(Proc, Root); for I := 0 to FWebPageItems.Count - 1 do begin WebComponent := FWebPageItems.WebComponents[I]; if WebComponent.Owner = Root then Proc(WebComponent); end; end; function TBasePageItemsProducer.GetComponentList: TObject; begin Result := FWebPageItems; end; function TBasePageItemsProducer.GetDefaultComponentList: TObject; begin Assert(False, 'No default components list'); { Do not localize } Result := nil; end; procedure TBasePageItemsProducer.SetChildOrder(Component: TComponent; Order: Integer); var Intf: IWebComponent; begin if FWebPageItems.IndexOf(Component) >= 0 then if Supports(IInterface(Component), IWebComponent, Intf) then Intf.Index := Order else Assert(False, 'Interface not supported'); end; { TPageItemsProducer } constructor TPageItemsProducer.Create(AOwner: TComponent); begin FHTMLDoc := TStringList.Create; inherited; end; destructor TPageItemsProducer.Destroy; begin inherited; FHTMLDoc.Free; end; function TPageItemsProducer.GetTemplateStream(out AOwned: Boolean): TStream; begin AOwned := True; if FHTMLFile <> '' then Result := TFileStream.Create(FHTMLFile, fmOpenRead + fmShareDenyWrite) else Result := TStringStream.Create(FHTMLDoc.Text); end; procedure TPageItemsProducer.SetHTMLFile(const Value: TFileName); begin if AnsiCompareFileName(FHTMLFile, Value) <> 0 then begin FHTMLDoc.Clear; FHTMLFile := Value; end; end; procedure TPageItemsProducer.SetHTMLDoc(Value: TStrings); begin FHTMLDoc.Assign(Value); FHTMLFile := ''; end; end.