text stringlengths 14 6.51M |
|---|
unit Demo.ColumnChart.ColumnStyles;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_ColumnChart_ColumnStyles = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_ColumnChart_ColumnStyles.GenerateChart;
var
Chart: IcfsGChartProducer;
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Visitations'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE)
]);
Chart.Data.AddRow(['2010', 10, 'color: gray']);
Chart.Data.AddRow(['2020', 14, 'color: #76A7FA']);
Chart.Data.AddRow(['2030', 16, 'opacity: 0.2']);
Chart.Data.AddRow(['2040', 22, 'stroke-color: #703593; stroke-width: 4; fill-color: #C5A5CF']);
Chart.Data.AddRow(['2050', 28, 'stroke-color: #871B47; stroke-opacity: 0.6; stroke-width: 8; fill-color: #BC5679; fill-opacity: 0.2']);
// Options
Chart.Options.Legend('position', 'none');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_ColumnChart_ColumnStyles);
end.
|
{
DarkDesktop_src.pas
Author: vhanla (Victor Alberto Gil)
DarkDesktop - software to adjust screen brightness
License: MIT, see LICENSE file
CHANGELOG:
2020-10-04:
Merged on focus Caret Halo feature from another tool a wrote as experiment.
Removed SetLayeredWindowAttributes in favor of built in Delphi AlphaBlend properties
Added custom color for background
Added interactive color from foreground window
Added radio settings for halos
2020-06-20:
Optional Graphics32 drawing over LayeredWindow, it might be better for
cursor
2014-03-12:
Exclude it from AeroPeek
it needs to be digitally signed in order to make it work using the manifest file in conjuction with uiaccess=true
in order to be available over any metro/modernui application, including the startmenu/screen
Using dwmapi to exclude from aero peek and flip3d on windows 7 (this one not tested)
2018-02-27:
Added support to locate APPDATA path in order to save settings there instead of
failed method on ProgramFiles path since this path is admin privileged
2014-12-13:
Modified Settings.frm
chkCrHalo : to enable or disable cursor's halo
Fixed Global Shortcut [ctrl-alt-x : toggle; ctrl-alt-z : set opacity with mouse cursor]
2014-12-07:
Trying out a new method, creating a translucent bitmap and WS_EXLAYERED windows
var bmpmask: TBitmap32; uses gr32;
2014-12-06
Changed icons, added imagelist with the trayicons for ON and OFF states
added variable IconoTray: TIcon;
Added WNProc to restore Icon tray after Explorer restart
Added SetPriorityClass to formcreate in order to make it less cpu intensive
Added Updateposition from AMPortable, in order to show the settings window right above/below the icon tray
Added SwitchToThisWindow Windows API in order to focus to the settings window thus it can be hidden if focus is lost
Added UpdateClockPosition in order to make it easy to update its position
Added Block me feature, this will be configured in order to let people block themselves to relax
Adding Pomodoro features
Adding picture to show relax time
Added Shape (circle) and tmrMouse set to 3 in interval, it seems it doesn't hog the CPU :)
Added doublebuffered on formcreate
Added Screen resolution change message handling
Added ScreenWorkAreaWidth changes monitor in new timer, tmrWorkAreaMonitor
variable used ActualWorkAreaWidth : Integer;
2014-08-14 -
Fixed bad hotkeys
}
unit DarkDesktop_src;
interface
uses
Winapi.Windows, Winapi.Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ShellApi, Menus, IniFiles, jpeg, ExtCtrls, XPMan, Registry,
StdCtrls, Vcl.ImgList, GR32_Image, GR32, DWMApi, System.ImageList, ShlObj, PNGImage;
type
TfrmDarkDesktop = class(TForm)
PopupMenu1: TPopupMenu;
Configuracin1: TMenuItem;
Acercade1: TMenuItem;
N1: TMenuItem;
Salir1: TMenuItem;
IniciarjuntoconWindows1: TMenuItem;
Timer1: TTimer;
lblOpacityChange: TLabel;
Timer2: TTimer;
Desactivar1: TMenuItem;
ImageList1: TImageList;
lblClock: TLabel;
tmrClock: TTimer;
Image321: TImage32;
Shape1: TShape;
tmrCrHalo: TTimer;
tmrWorkAreaMonitor: TTimer;
shpCaretHalo: TShape;
tmrCaretHalo: TTimer;
tmrShowForeground: TTimer;
tmrColorize: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Salir1Click(Sender: TObject);
procedure Acercade1Click(Sender: TObject);
procedure Configuracin1Click(Sender: TObject);
procedure IniciarjuntoconWindows1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
procedure Desactivar1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tmrClockTimer(Sender: TObject);
procedure UpdateClockPosition;
procedure FormResize(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure tmrCrHaloTimer(Sender: TObject);
procedure tmrWorkAreaMonitorTimer(Sender: TObject);
procedure tmrCaretHaloTimer(Sender: TObject);
procedure tmrShowForegroundTimer(Sender: TObject);
procedure tmrColorizeTimer(Sender: TObject);
private
{ Private declarations }
IconData : TNotifyIconData;
procedure Iconito(var msg: TMessage); message WM_USER+1;
procedure WMShowWindow(var msg: TWMShowWindow);
procedure WMHotKey(var msg: TWMHotKey); message WM_HOTKEY;
procedure WndProc(var msg: TMessage); override;
procedure WMDisplayChange(var Message: TWMDisplayChange);message WM_DISPLAYCHANGE;
procedure UpdatePNG;
function GetMostUsed(ABmp: TBitmap): TColor;
procedure ColorFromAppIcon(AHandle: HWND);
public
{ Public declarations }
procedure CreateParams(var params: TCreateParams); override;
procedure RestoreRequest(var message: TMessage); message WM_USER + $1000;
end;
var
frmDarkDesktop: TfrmDarkDesktop;
fwm_TaskbarRestart : Cardinal;
Opacity: Integer;
OpInterval: Integer;
OpPersistent : Boolean;
OpPersistentInterval: Integer;
OpShowOSD : Boolean;
OpCaretHalo: Boolean;
OpShowForeground: Boolean = False;
OpColor: TColor = clBlack;
OpInteractiveColor: Boolean = False;
PrevHandle, OldHandle: HWND;
currentMouseX : integer;
IconoTray : TIcon;
ActualWorkAreaWidth : Integer;
BmpMask: TBitmap32;
ConfigIniPath: String;
procedure SwitchToThisWindow(h1: hWnd; x: bool); stdcall;
external user32 Name 'SwitchToThisWindow';
{type DWMWINDOWATTRIBUTE = (
DWMWA_NCRENDERING_ENABLE = 1,
DWMWA_NCRENDERING_POLICY,
DWMWA_TRANSITIONS_FORCEDISABLED,
DWMWA_ALLOW_NCPAINT,
DWMWA_CAPTION_BUTTON_BOUNDS,
DWMWA_NONCLIENT_RTL_LAYOUT,
DWMWA_FORCE_ICONIC_REPRESENTATION,
DWMWA_FLIP3D_POLICY,
DWMWA_EXTENDED_FRAME_BOUNDS,
DWMWA_HAS_ICONIC_BITMAP,
DWMWA_DISALLOW_PEEK,
DWMWA_EXCLUDED_FROM_PEEK,
DWMWA_LAST
);
function DwmSetWindowAttribute(hwnd:HWND; dwAttribute: DWORD; pvAttribute: Pointer; cbAttribute: DWORD): HRESULT; stdcall; external 'dwmapi.dll' name 'DwmSetWindowAttribute';
}
procedure SetForegroundBackground(AHandle: HWND);
function TColorToHex(AColor: TColor): string;
function HexToTColor(AColor: string): TColor;
implementation
uses Settings, Splash, Math, Generics.Defaults, Generics.Collections;
{$R *.dfm}
function TColorToHex(AColor: TColor): string;
begin
Result := IntToHex(GetRValue(AColor), 2) +
IntToHex(GetGValue(AColor), 2) +
IntToHex(GetBValue(AColor), 2);
end;
function HexToTColor(AColor: string): TColor;
begin
Result := RGB(
StrToInt('$' + Copy(AColor, 1, 2)),
StrToInt('$' + Copy(AColor, 3, 2)),
StrToInt('$' + Copy(AColor, 5, 2)));
end;
function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean):String;
var
FilePath: array[0..MAX_PATH] of char;
begin
SHGetSpecialFolderPath(0, @FilePath[0], Folder, CanCreate);
Result := FilePath;
end;
procedure AutoStartState;
var key: string;
Reg: TRegIniFile;
begin
key := '\Software\Microsoft\Windows\CurrentVersion\Run';
Reg:=TRegIniFile.Create;
try
Reg.RootKey:=HKEY_CURRENT_USER;
if reg.ReadString(key,'DarkDesktop','')<>'' then
frmDarkDesktop.IniciarjuntoconWindows1.Checked:=true;
finally
Reg.Free;
end;
end;
procedure TfrmDarkDesktop.WMHotKey(var msg: TWMHotKey);
var
ini: TIniFile;
//i:integer;
actualOpacity: integer;
begin
actualOpacity:=Opacity;
if Msg.HotKey = GlobalFindAtom('ALT_LESS')then
if Opacity+OpInterval<=255 then Opacity:=Opacity+OpInterval;
if Msg.HotKey = GlobalFindAtom('ALT_PLUS')then
if Opacity>=OpInterval then Opacity:=Opacity-OpInterval;
if msg.HotKey = GlobalFindAtom('CTRL_WIN_ALT')then
begin
if (currentMouseX <> mouse.CursorPos.X) and(Desactivar1.Caption<>'&Activar') then
begin
currentMouseX := Mouse.CursorPos.X;
opacity:= trunc(Mouse.CursorPos.X / Screen.Width*255);
end;
end;
if msg.HotKey = GlobalFindAtom('DISABLEWIN')then
begin
if Timer1.Enabled then begin
frmDarkDesktop.Hide;
Desactivar1.Caption:='&Activar';
Timer1.Enabled:=false;
ImageList1.GetIcon(0, IconoTray);
IconData.hIcon := IconoTray.Handle;
Shell_NotifyIcon(NIM_MODIFY,@IconData);
end
else begin
frmDarkDesktop.Show;
Desactivar1.Caption:='&Desactivar';
Timer1.Enabled:=true;
ImageList1.GetIcon(1, IconoTray);
IconData.hIcon := IconoTray.Handle;
Shell_NotifyIcon(NIM_MODIFY,@IconData);
end;
end;
if actualOpacity <> Opacity then
begin
//SetLayeredWindowAttributes(frmDarkDesktop.Handle,0,Opacity, LWA_ALPHA);
AlphaBlendValue := Opacity;
if frmSettings.Showing then frmSettings.TrackBar1.Position:=Opacity;
ini:=TIniFile.Create(ConfigIniPath);
try
ini.WriteInteger('Settings','Opacity',Opacity);
finally
ini.Free;
end;
//Show OSD text
if OpShowOSD then
begin
//lblOpacityChange.Caption:='Opacidad: '+inttostr(Opacity);
lblOpacityChange.Caption:='';
lblOpacityChange.Top:=Screen.Height div 2;
lblOpacityChange.Width:=Screen.Width;
// lblOpacityChange.Font.Size:=6;
// lblOpacityChange.Font.Color:=clWhite;
//anima pero consume recursos
{for i:=0 to Opacity div 4 do
begin
if (Opacity div 4)div 2 = i - 1 then lblOpacityChange.Caption:=lblOpacityChange.Caption+'[ '+IntToStr(trunc(Opacity/255*100))+' ]';
lblOpacityChange.Caption:=lblOpacityChange.Caption+'|';
end;
}
lblOpacityChange.Caption:=IntToStr(Opacity)+'/255';
lblOpacityChange.Align:=alBottom;
lblOpacityChange.Visible:=true;
timer2.Enabled:=false;
sleep(10);
timer2.Enabled:=true;
end;
end;
end;
procedure TfrmDarkDesktop.Iconito(var msg: TMessage);
var
p: TPoint;
begin
if msg.LParam = WM_RBUTTONDOWN THen begin
try //posible error code 5 , access denied
GetCursorPos(p);
frmDarkDesktop.PopupMenu1.Popup(p.X,p.Y );
except
end;
PostMessage(handle,WM_NULL,0,0)
end
// else if (msg.LParam = WM_LBUTTONDBLCLK) and (frmSettings.Showing = false )then
else if (msg.LParam = WM_LBUTTONUP) and (frmSettings.Showing = false )then
begin
frmSettings.Show;//Modal
SwitchToThisWindow(frmSettings.Handle,True);
frmSettings.UpdatePosition;
end;
{ else if msg.LParam = WM_LBUTTONUP then
begin
if Timer1.Enabled then begin
frmDarkDesktop.Hide;
Desactivar1.Caption:='&Activar';
Timer1.Enabled:=false;
end
else begin
frmDarkDesktop.Show;
Desactivar1.Caption:='&Desactivar';
Timer1.Enabled:=true;
end;
end;}
end;
//the following will deny minimization
procedure TfrmDarkDesktop.WMShowWindow(var msg: TWMShowWindow);
begin
if not msg.Show then
msg.Result := 0
else
inherited
end;
procedure TfrmDarkDesktop.WndProc(var msg: TMessage);
begin
if msg.Msg = fwm_TaskbarRestart then
begin
Shell_NotifyIcon(NIM_ADD, @icondata);
end;
inherited WndProc(msg);
end;
procedure TfrmDarkDesktop.UpdateClockPosition;
begin
with frmSettings do
begin
if rbClock1.Checked then
begin
lblClock.Left := 100;
lblClock.Top := 100;
end
else if rbClock2.Checked then
begin
lblClock.Left := (self.Width - lblClock.Width) div 2;
lblClock.Top := 100;
end
else if rbClock3.Checked then
begin
lblClock.Left := self.Width - lblClock.Width - 100;
lblClock.Top := 100;
end
else if rbClock4.Checked then
begin
lblClock.Left := 100;
lblClock.Top := (self.Height - lblClock.Height) div 2;
end
else if rbClock5.Checked then
begin
lblClock.Left := (self.Width - lblClock.Width) div 2;
lblClock.Top := (self.Height - lblClock.Height) div 2;
end
else if rbClock6.Checked then
begin
lblClock.Left := self.Width - lblClock.Width - 100;
lblClock.Top := (self.Height - lblClock.Height) div 2;
end
else if rbClock7.Checked then
begin
lblClock.Left := 100;
lblClock.Top := self.Height - lblClock.Height - 100;
end
else if rbClock8.Checked then
begin
lblClock.Left := (self.Width - lblClock.Width) div 2;
lblClock.Top := self.Height - lblClock.Height - 100;
end
else if rbClock9.Checked then
begin
lblClock.Left := self.Width - lblClock.Width - 100;
lblClock.Top := self.Height - lblClock.Height - 100;
end;
end;
end;
procedure TfrmDarkDesktop.UpdatePNG;
var
PngFile: TPNGObject;
begin
PngFile := TPNGObject.CreateBlank(clBlack,32,Screen.Width, Screen.Height);
try
PngFile.CreateAlpha;
finally
PngFile.Free;
end;
end;
procedure TfrmDarkDesktop.WMDisplayChange(var Message: TWMDisplayChange);
begin
// Width := Message.Width;
// Height := Message.Height;
if Message.Height < 768 then //it might be showing a windows 8 app, so lets bypass it in less resolutions
Width := Message.Width
else
Width := Screen.WorkAreaWidth;
Height := Message.Height;
end;
procedure TfrmDarkDesktop.CreateParams(var params: TCreateParams);
begin
inherited CreateParams(Params);
params.WinClassName := 'DarkDesktopClass';
//esto es para que no robe el foco pero no es usable aquí
// params.ExStyle:= params.ExStyle or WS_EX_NOACTIVATE or WS_EX_TOOLWINDOW;
end;
procedure TfrmDarkDesktop.RestoreRequest(var message: TMessage);
begin
//mostramos si está oculto
frmDarkDesktop.Show;
end;
procedure TfrmDarkDesktop.FormCreate(Sender: TObject);
var
ini: TIniFile;
I: Integer;
//opacity: Integer;
//rc : TRect;
BlendFunc : TBlendFunction;
BmpPos : TPoint;
BmpSize : TSize;
//exclude from aeropeek
renderPolicy: integer;//DWMWINDOWATTRIBUTE;
begin
SetPriorityClass(GetCurrentProcess, $4000);
//exclude from aeropeek
if DwmCompositionEnabled then
DwmSetWindowAttribute(Handle, DWMWA_EXCLUDED_FROM_PEEK or DWMWA_FLIP3D_POLICY, @renderPolicy, SizeOf(Integer));
tmrCaretHalo.Interval := 100;
tmrCaretHalo.Enabled := False;
shpCaretHalo.Visible := False;
tmrShowForeground.Interval := 100;
tmrShowForeground.Enabled := False;
tmrColorize.Enabled := False;
//showmessage(inttostr(screen.monitorcount));
//BoundsRect:=screen.Monitors[1].BoundsRect+screen.Monitors[0].BoundsRect;
if (GetSystemMetrics(SM_CMONITORS)>1)then
begin
// showmessage('This app only supports one monitor!');
end;
//hiding from taskbar
{ ShowWindow(Application.Handle, SW_HIDE) ;
SetWindowLong(Application.Handle, GWL_EXSTYLE, getWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW) ;
ShowWindow(Application.Handle, SW_SHOW) ;}
BmpMask := TBitmap32.Create;
frmDarkDesktop.Color:= clblack;
frmDarkDesktop.AlphaBlend:=true;
frmDarkDesktop.AlphaBlendValue:=128;
frmDarkDesktop.BorderStyle:=bsNone;
// frmDarkDesktop.WindowState:=wsMaximized;
//primero detectamos si es mas de un monitor
if Screen.MonitorCount>1 then
begin
//copiamos las coordenadas del primer monitor
frmDarkDesktop.Left:=Screen.Monitors[0].Left;
frmDarkDesktop.Top:=Screen.Monitors[0].Top;
frmDarkDesktop.Width:=0;//Screen.Monitors[0].Width;
frmDarkDesktop.Height:=110;//Screen.Monitors[0].Height;
//ahora con los siguientes
for I := 1 to Screen.MonitorCount-1 do
begin
if frmDarkDesktop.Left>Screen.Monitors[I].Left then
frmDarkDesktop.Left:=Screen.Monitors[I].Left;
if frmDarkDesktop.Top>Screen.Monitors[I].Top then
frmDarkDesktop.Top:=Screen.Monitors[I].Top;
end;
//una vez encontrado left y top buscamos el ancho y alto
for I := 0 to Screen.MonitorCount-1 do
begin
// ShowMessage(IntToStr(frmDarkDesktop.Left+Screen.Monitors[I].Width));
if frmDarkDesktop.Left+frmDarkDesktop.Width<Screen.Monitors[I].Left+Screen.Monitors[I].Width then
frmDarkDesktop.Width:=Screen.Monitors[I].Left+Screen.Monitors[I].Width-frmDarkDesktop.Left;
if frmDarkDesktop.Top+frmDarkDesktop.Height<Screen.Monitors[I].Top+Screen.Monitors[I].Height then
frmDarkDesktop.Height:=Screen.Monitors[I].Top+Screen.Monitors[I].Height-frmDarkDesktop.Top;
end;
end
else frmDarkDesktop.WindowState:=wsMaximized;
frmDarkDesktop.FormStyle:=fsStayOnTop;
// creamos el icono del programa
fwm_TaskbarRestart := RegisterWindowMessage('DarkTrayCreated');
IconoTray := TIcon.Create;
ImageList1.GetIcon(1,IconoTray);
with IconData do
begin
cbSize:=IconData.SizeOf;
// sizeof(IconData);
wnd:=handle;
Uid:=100;
uFlags:=NIF_MESSAGE+NIF_ICON+NIF_TIP;
uCallbackMessage:=WM_USER+1;
hIcon:=IconoTray.Handle; //Application.Icon.Handle;
StrPCopy(szTip,'DarkDesktop')
end;
Shell_NotifyIcon(NIM_ADD,@IconData);
//Valores por defecto por si ini write falla
Opacity:=128;
OpInterval:=15;
OpPersistentInterval:=1000;
OpPersistent:=true;
OpShowOSD:=true;
OpCaretHalo := False;
currentMouseX:=Mouse.CursorPos.X;
//Aplicamos oscurecimiento
//SetWindowLong(form1.Handle,GWL_EXSTYLE,GWL)
SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) Or WS_EX_TRANSPARENT or WS_EX_TOOLWINDOW {and not WS_EX_APPWINDOW});
//SetLayeredWindowAttributes(Handle,0,opacity, LWA_ALPHA);
//AppData defining
if Pos(GetSpecialFolderPath(CSIDL_PROGRAM_FILESX86, False), ExtractFilePath(ParamStr(0))) = 1 then
begin
if not DirectoryExists(GetSpecialFolderPath(CSIDL_APPDATA, False)+'\DarkDesktop') then
CreateDir(GetSpecialFolderPath(CSIDL_APPDATA, False)+'\DarkDesktop');
ConfigIniPath := GetSpecialFolderPath(CSIDL_APPDATA, False)+'\DarkDesktop\config.ini';
end
else
ConfigIniPath := ExtractFilePath(ParamStr(0))+'config.ini';
// Leemos datos de inicialización
ini:=TIniFile.Create(ConfigIniPath);
try
if not FileExists(ConfigIniPath)then
ini.WriteInteger('Settings','Opacity',128);
Opacity:=ini.ReadInteger('Settings','Opacity',128);
OpInterval:=ini.ReadInteger('Settings','Interval',15);
OpPersistentInterval:=ini.ReadInteger('Settings','Persist',1000);
OpPersistent:=ini.ReadBool('Settings','Persistent',true);
OpShowOSD:=ini.ReadBool('Settings','Indicator',true);
OpCaretHalo := ini.ReadBool('Settings', 'CaretHalo', false);
OpShowForeground := ini.ReadBool('Settings', 'ShowForeground', False);
OpColor := HexToTColor(ini.ReadString('Settings', 'Color', '000000'));
Color := OpColor;
OpInteractiveColor := ini.ReadBool('Settings', 'InteractiveColor', False);
Shape1.Width := ini.ReadInteger('Settings', 'MouseHaloRadio', 100);
Shape1.Height := Shape1.Width;
shpCaretHalo.Width := ini.ReadInteger('Settings', 'CaretHaloRadio', 100);
shpCaretHalo.Height := shpCaretHalo.Width;
finally
ini.Free;
end;
tmrCaretHalo.Enabled := OpCaretHalo;
if not OpShowForeground then
begin
timer1.Enabled := OpPersistent;
timer1.Interval := OpPersistentInterval;
end
else
begin
timer1.Enabled := False;
Show;
tmrShowForeground.Enabled := True;
end;
tmrColorize.Enabled := OpInteractiveColor;
AlphaBlend := True;
AlphaBlendValue := Opacity;
TransparentColor := True;
// SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width, Height,SWP_NOMOVE or SWP_NOACTIVATE or SWP_NOSIZE);
//for dual monitors or more
{GetWindowRect(handle,rc);
rc.Right:=GetSystemMetrics(SM_CXSCREEN);
rc.Bottom:=GetSystemMetrics(SM_CYSCREEN);
SystemParametersInfo(SPI_GETWORKAREA,0,@rc,0);}
//if t.Top=0 then
//SetBounds(rc.Left,22,r.Right-r.Left,screen.height-80);//r.Bottom-r.Top);
//verificamos si es autoejecutable junto con windows
AutoStartState;
//ocultamos el form de alt+tab
///ahora aplicamos los hotkeys
if(not RegisterHotKey(self.Handle,GlobalAddAtom('ALT_PLUS'),MOD_CONTROL+MOD_ALT,VK_ADD)) then
begin
ShowMessage('Error! Alt_+ ya está siendo utilizado');
if GlobalFindAtom('ALT_PLUS')<>0 then
UnregisterHotKey(Self.Handle,GlobalFindAtom('ALT_PLUS'));
end;
if(not RegisterHotKey(self.Handle,GlobalAddAtom('ALT_LESS'),MOD_CONTROL+MOD_ALT,VK_SUBTRACT)) then
begin
ShowMessage('Error! Alt_- ya está siendo utilizado');
if GlobalFindAtom('ALT_LESS')<>0 then
UnregisterHotKey(Self.Handle,GlobalFindAtom('ALT_LESS'));
end;
// if(not RegisterHotKey(self.Handle, GlobalAddAtom('CTRL_WIN_ALT'),MOD_WIN,ORD('n'))) then
if(not RegisterHotKey(self.Handle, GlobalAddAtom('CTRL_WIN_ALT'),MOD_CONTROL+MOD_ALT,ORD('Z'))) then
begin
ShowMessage('Error! Ctrl+Alt+Z ya está siendo utilizado');
if GlobalFindAtom('CTRL_WIN_ALT')<> 0 then
UnregisterHotKey(Self.Handle,GlobalFindAtom('CTRL_WIN_ALT'));
end;
if (not RegisterHotKey(self.Handle, GlobalAddAtom('DISABLEWIN'),MOD_CONTROL+MOD_ALT,ORD('X'))) then
begin
ShowMessage('Error! Ctrl+Alt+X ya está siendo utilizado');
if GlobalFindAtom('DISABLEWIN')<> 0 then
UnregisterHotKey(Self.Handle,GlobalFindAtom('DISABLEWIN'));
end;
//idioma del usuario
//creamos el bitmap basado en el actual tamaño de la ventana
BmpMask.Width := Width;
BmpMask.Height := Height;
BmpMask.DrawMode := dmBlend;
BmpMask.FillRectS(BmpMask.BoundsRect, clRed32);
//Image321.Bitmap:=BmpMask;
Image321.Visible := False;
BmpPos := Point(0,0);
BmpSize.cx := BmpMask.Width;
BmpSize.cy := BmpMask.Height;
BlendFunc.BlendOp := AC_SRC_OVER;
BlendFunc.BlendFlags := 0;
BlendFunc.SourceConstantAlpha := 255;
BlendFunc.AlphaFormat := 0;
UpdateLayeredWindow(Self.Handle, 0, nil, @BmpSize, BmpMask.Handle, @BmpPos, 0, @blendfunc, ULW_ALPHA);
DoubleBuffered := True;
TransparentColorValue := clWhite;
end;
procedure TfrmDarkDesktop.FormDestroy(Sender: TObject);
begin
if IconData.Wnd <>0 then Shell_NotifyIcon(NIM_DELETE,@IconData);
if GlobalFindAtom('ALT_PLUS')<>0 then
UnregisterHotKey(handle,GlobalFindAtom('ALT_PLUS'));
if GlobalFindAtom('ALT_LESS')<>0 then
UnregisterHotKey(handle,GlobalFindAtom('ALT_LESS'));
if GlobalFindAtom('CTRL_WIN_ALT')<>0 then
UnregisterHotKey(handle,GlobalFindAtom('CTRL_WIN_ALT'));
if GlobalFindAtom('DISABLEWIN')<> 0 then
UnregisterHotKey(Self.Handle,GlobalFindAtom('DISABLEWIN'));
IconoTray.Free;
BmpMask.Free;
end;
procedure TfrmDarkDesktop.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
// Shape1.Left := X - Shape1.Width div 2;
// Shape1.Top := Y - Shape1.Height div 2;
end;
procedure TfrmDarkDesktop.FormResize(Sender: TObject);
begin
if Width >= Height then
begin
Image321.Height := Height;
Image321.Width := Height;
Image321.Left := (Width - Image321.Width) div 2;
end
else
begin
Image321.Width := Width;
Image321.Height := Width;
Image321.Top := (Height - Image321.Height) div 2;
end;
end;
procedure TfrmDarkDesktop.FormShow(Sender: TObject);
begin
ShowWindow(application.Handle, SW_HIDE);
end;
function TfrmDarkDesktop.GetMostUsed(ABmp: TBitmap): TColor;
type
PRGBTripleArray = ^TRGBTripleArray;
TRGBTripleArray = array[0..1023] of TRGBTriple;
var
I, J: Integer;
LBmpScanLine: PRGBTripleArray;
LColors: TDictionary<TColor, Integer>;
LCount: Integer;
LColor: TColor;
begin
Result := clBlack; // by default is black
LColors := TDictionary<TColor,Integer>.Create;
try
for J := 0 to ABmp.Height - 1 do
begin
LBmpScanLine := ABmp.ScanLine[J];
for I := 0 to ABmp.Width - 1 do
begin
LColor := RGB(LBmpScanLine[I].rgbtRed,
LBmpScanLine[I].rgbtGreen,
LBmpScanLine[I].rgbtBlue);
if LColors.ContainsKey(LColor) then
LColors.Items[LColor] := LColors.Items[LColor] + 1
else
LColors.Add(LColor, 1);
end;
end;
LCount := LColors.ToArray[0].Value;
for LColor in LColors.Keys do
if LColors.TryGetValue(LColor, I) and (I > LCount) then
Result := LColor;
finally
LColors.Free;
end;
end;
procedure TfrmDarkDesktop.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmDarkDesktop.Acercade1Click(Sender: TObject);
begin
with TFormSplash.Create(Application)do
Execute;
end;
procedure TfrmDarkDesktop.ColorFromAppIcon(AHandle: HWND);
var
LIcon: HICON;
res: DWORD;
LPic: TPicture;
LBmp: TBitmap;
begin
LIcon := GetClassLong(AHandle, GCL_HICONSM);
if LIcon = 0 then
LIcon := GetClassLong(AHandle, GCL_HICON);
if LIcon = 0 then
LIcon := SendMessageTimeout(AHandle, WM_GETICON, ICON_SMALL, 0, SMTO_ABORTIFHUNG, 100, res);
if LIcon = 0 then
LIcon := SendMessageTimeout(AHandle, WM_GETICON, ICON_BIG, 0, SMTO_ABORTIFHUNG, 100, res);
if LIcon = 0 then
LIcon := SendMessageTimeout(AHandle, WM_GETICON, ICON_SMALL2, 0, SMTO_ABORTIFHUNG, 100, res);
if LIcon = 0 then Exit; // was not possible to get the icon from window
LPic := TPicture.Create;
LBmp := TBitmap.Create;
try
LPic.Icon.Handle := LIcon;
LBmp.PixelFormat := pf24bit;
LBmp.Width := LPic.Icon.Width;
LBmp.Height := LPic.Icon.Height;
LBmp.Canvas.Draw(0, 0, LPic.Icon);
Color := GetMostUsed(LBmp);
if Color = clWhite then
Color := clBlack;
finally
LBmp.Free;
LPic.Free;
end;
end;
procedure TfrmDarkDesktop.Configuracin1Click(Sender: TObject);
begin
timer1.Enabled:=false;
frmSettings.Show//Modal
end;
procedure RegAutoStart;
var
key: string;
reg: TRegIniFile;
begin
key:='\Software\Microsoft\Windows\CurrentVersion\Run';
reg:=TRegIniFile.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
reg.CreateKey(key);
if reg.OpenKey(Key,False) then reg.WriteString(key,'DarkDesktop',pchar(Application.exename));
finally
reg.Free;
end;
end;
procedure UnRegAutoStart;
var key: string;
Reg: TRegIniFile;
begin
key := '\Software\Microsoft\Windows\CurrentVersion\Run';
Reg:=TRegIniFile.Create;
try
Reg.RootKey:=HKEY_CURRENT_USER;
if Reg.OpenKey(Key,False) then Reg.DeleteValue('DarkDesktop');
finally
Reg.Free;
end;
end;
procedure TfrmDarkDesktop.IniciarjuntoconWindows1Click(Sender: TObject);
begin
if IniciarjuntoconWindows1.Checked then
begin
UnRegAutoStart;
IniciarjuntoconWindows1.Checked:=false;
end
else
begin
RegAutoStart;
IniciarjuntoconWindows1.Checked:=true;
end;
end;
function IsWindowOnTop(hWindow: HWND): Boolean;
begin
Result := (GetWindowLong(hWindow, GWL_EXSTYLE) and WS_EX_TOPMOST) <> 0
end;
procedure SetForegroundBackground(AHandle: HWND);
var
fw, res: HWND;
fpid, pid: DWORD;
begin
pid := GetWindowThreadProcessId(AHandle, nil);
fw := GetForegroundWindow;
fpid := GetWindowThreadProcessId(fw, nil);
if pid <> fpid then
begin
SetWindowPos(AHandle, fw, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE);
end;
res := GetForegroundWindow;
if res <> fw then
SetWindowPos(fw, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE);
end;
procedure TfrmDarkDesktop.Timer1Timer(Sender: TObject);
begin
//form1.color:=Random(255);
// form1.Hide;
// Application.BringToFront;
try
if frmSettings.Showing then timer1.Enabled:=false;
except
end;
//if (OpPersistent) and (not FormSplash.Showing) then
if (OpPersistent) then
try
if FormStyle <> fsStayOnTop then
FormStyle := fsStayOnTop;
frmDarkDesktop.Show;
except
end;
{ if not IsWindowOnTop(FindWindow('DarkDesktopClass',nil))then
begin
SetWindowPos(Handle,HWND_TOPMOST,Left,Top,Width, Height,SWP_NOMOVE or SWP_NOACTIVATE or SWP_NOSIZE);
end;}
end;
procedure TfrmDarkDesktop.Timer2Timer(Sender: TObject);
begin
try
frmDarkDesktop.lblOpacityChange.Visible:=false;
timer2.Enabled:=false;
except
end;
end;
procedure TfrmDarkDesktop.tmrCaretHaloTimer(Sender: TObject);
var
pos: TPoint;
gui: tagGUITHREADINFO;
rc: TRect;
clsName: array[0..255] of Char;
begin
gui.cbSize := SizeOf(gui);
GetGUIThreadInfo(0, gui);
GetClassName(gui.hwndActive, clsName, 255);
if (gui.flags and 1 = 1) or (clsName = 'ConsoleWindowClass') then
begin
//Color := clBlack;
GetCaretPos(pos);
shpCaretHalo.Visible := True;
pos.X := gui.rcCaret.Left;
pos.Y := gui.rcCaret.Bottom;
Winapi.Windows.ClientToScreen(gui.hwndCaret, pos);
shpCaretHalo.Left := pos.X - shpCaretHalo.Width div 2;
shpCaretHalo.Top := pos.Y - shpCaretHalo.Height div 2;
//#TODO maybe add also focus rect usage
end
else
begin
// incase you only want to show dark layer when caret is focused #TODO
//Color := clWhite;
shpCaretHalo.Visible := False;
end;
end;
procedure TfrmDarkDesktop.tmrClockTimer(Sender: TObject);
function IntToTimeStr(var timepart: word; docehoras: boolean = false):string;
var
strtime: string;
begin
strtime := IntToStr(timepart);
if docehoras then
begin
if timepart > 12 then
strtime := IntToStr(timepart - 12);
end;
if strtime.Length = 1 then
strtime := '0'+strtime;
Result := strtime;
end;
var
Hora : TSystemTime;
begin
UpdateClockPosition;
GetLocalTime(Hora);
lblClock.Caption := IntToTimeStr(Hora.wHour,True)+':'+IntToTimeStr(Hora.wMinute)+':'+IntToTimeStr(Hora.wSecond); //DateTimeToStr(SystemTimeToDateTime(Hora));
end;
procedure TfrmDarkDesktop.tmrColorizeTimer(Sender: TObject);
var
fw: HWND;
begin
fw := GetForegroundWindow;
if fw <> OldHandle then
begin
OldHandle := fw;
ColorFromAppIcon(fw);
end;
end;
procedure TfrmDarkDesktop.tmrCrHaloTimer(Sender: TObject);
var
P: TPoint;
begin
try
P := ScreenToClient(Mouse.CursorPos);
Shape1.Left := P.X - Shape1.Width div 2;
Shape1.Top := P.Y - Shape1.Height div 2;
except
end;
end;
procedure TfrmDarkDesktop.tmrShowForegroundTimer(Sender: TObject);
var
fw: HWND;
begin
if OpShowForeground then
begin
if FormStyle <> fsNormal then
FormStyle := fsNormal;
fw := GetForegroundWindow;
if PrevHandle <> fw then
begin
PrevHandle := fw;
SetForegroundBackground(Handle);
end;
end;
end;
procedure TfrmDarkDesktop.tmrWorkAreaMonitorTimer(Sender: TObject);
begin
if Screen.WorkAreaWidth <> ActualWorkAreaWidth then
begin
ActualWorkAreaWidth := Screen.WorkAreaWidth;
Width := ActualWorkAreaWidth;
end;
end;
procedure TfrmDarkDesktop.Desactivar1Click(Sender: TObject);
begin
if Timer1.Enabled then begin
frmDarkDesktop.Hide;
Desactivar1.Caption:='&Enable';
Timer1.Enabled:=false;
ImageList1.GetIcon(0, IconoTray);
IconData.hIcon := IconoTray.Handle;
Shell_NotifyIcon(NIM_MODIFY,@IconData);
end
else begin
frmDarkDesktop.Show;
Desactivar1.Caption:='&Disable';
Timer1.Enabled:=true;
ImageList1.GetIcon(1, IconoTray);
IconData.hIcon := IconoTray.Handle;
Shell_NotifyIcon(NIM_MODIFY,@IconData);
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_TYPEINFO.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_TYPEINFO;
interface
uses {$I uses.def}
TypInfo,
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_MAP,
PAXCOMP_CLASSFACT,
PAXCOMP_GENERIC;
type
TParamData = record
Flags: TParamFlags;
ParamName: ShortString;
TypeName: ShortString;
end;
TTypeInfoContainer = class;
TTypeDataContainer = class;
TClassTypeDataContainer = class;
TMethodTypeDataContainer = class;
TFieldDataContainer = class
private
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
public
Id: Integer; // not saved to stream
Offset: Cardinal; { Offset of field in the class data. }
ClassIndex: Word; { Index in the FieldClassTable. }
Name: ShortString;
FullFieldTypeName: String;
// PCU only
FinalFieldTypeId: Byte;
Vis: TClassVisibility;
end;
TFieldListContainer = class(TTypedList)
private
function GetRecord(I: Integer): TFieldDataContainer;
public
function Add: TFieldDataContainer;
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
property Records[I: Integer]: TFieldDataContainer read GetRecord; default;
end;
TAnotherPropRec = class //PCU only
public
Vis: TClassVisibility;
PropName: String;
ParamNames: TStringList;
ParamTypes: TStringList;
PropType: String;
ReadName: String;
WriteName: String;
IsDefault: Boolean;
constructor Create;
destructor Destroy; override;
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
end;
TAnotherPropList = class(TTypedList)
private
function GetRecord(I: Integer): TAnotherPropRec;
public
function Add: TAnotherPropRec;
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
property Records[I: Integer]: TAnotherPropRec read GetRecord; default;
end;
TPropDataContainer = class
private
Owner: TTypeDataContainer;
function GetCount: Integer;
function GetSize: Integer;
public
PropData: TPropData;
PropList: array of TPropInfo;
PropTypeIds: array of Integer;
ReadNames: TStringList;
WriteNames: TStringList;
PropTypeNames: TStringList;
constructor Create(AOwner: TTypeDataContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream);
procedure SaveToBuff(S: TStream);
procedure LoadFromStream(S: TStream);
property Count: Integer read GetCount;
property Size: Integer read GetSize;
end;
TParamListContainer = class
private
Owner: TMethodTypeDataContainer;
function GetCount: Integer;
function GetSize: Integer;
public
ParamList: array of TParamData;
constructor Create(AOwner: TMethodTypeDataContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream);
procedure SaveToBuff(S: TStream);
procedure LoadFromStream(S: TStream);
property Count: Integer read GetCount;
property Size: Integer read GetSize;
end;
{$ifdef GE_DXETOKYO} // XILINX, Tokyo mod
TTypeDataXil = packed record
function NameListFld: TTypeInfoFieldAccessor; inline;
function UnitNameFld: TTypeInfoFieldAccessor; inline;
function IntfUnitFld: TTypeInfoFieldAccessor; inline;
function DynUnitNameFld: TTypeInfoFieldAccessor; inline;
function PropData: PPropData; inline;
function IntfMethods: PIntfMethodTable; inline;
function DynArrElType: PPTypeInfo; inline;
function DynArrAttrData: PAttrData; inline;
case TTypeKind of
tkUnknown: ();
tkUString,
{$IFNDEF NEXTGEN}
tkWString,
{$ENDIF !NEXTGEN}
tkVariant: (AttrData: TAttrData);
tkLString: (
CodePage: Word
{LStrAttrData: TAttrData});
tkInteger, tkChar, tkEnumeration, tkSet, tkWChar: (
OrdType: TOrdType;
case TTypeKind of
tkInteger, tkChar, tkEnumeration, tkWChar: (
MinValue: Integer;
MaxValue: Integer;
case TTypeKind of
tkInteger, tkChar, tkWChar: (
{OrdAttrData: TAttrData});
tkEnumeration: (
BaseType: PPTypeInfo;
NameList: TSymbolName;
{EnumUnitName: TSymbolName;
EnumAttrData: TAttrData}));
tkSet: (
CompType: PPTypeInfo
{SetAttrData: TAttrData}));
tkFloat: (
FloatType: TFloatType
{FloatAttrData: TAttrData});
{$IFNDEF NEXTGEN}
tkString: (
MaxLength: Byte
{StrAttrData: TAttrData});
{$ENDIF !NEXTGEN}
tkClass: (
ClassType: TClass; // most data for instance types is in VMT offsets
ParentInfo: PPTypeInfo;
PropCount: SmallInt; // total properties inc. ancestors
UnitName: TSymbolName;
{PropData: TPropData;
PropDataEx: TPropDataEx;
ClassAttrData: TAttrData;
ArrayPropCount: Word;
ArrayPropData: array[1..ArrayPropCount] of TArrayPropInfo;});
tkMethod: (
MethodKind: TMethodKind; // only mkFunction or mkProcedure
ParamCount: Byte;
{$IFNDEF NEXTGEN}
ParamList: array[0..1023] of AnsiChar
{$ELSE NEXTGEN}
ParamList: array[0..1023] of Byte
{$ENDIF NEXTGEN}
{ParamList: array[1..ParamCount] of
record
Flags: TParamFlags;
ParamName: ShortString;
TypeName: ShortString;
end;
ResultType: ShortString; // only if MethodKind = mkFunction
ResultTypeRef: PPTypeInfo; // only if MethodKind = mkFunction
CC: TCallConv;
ParamTypeRefs: array[1..ParamCount] of PPTypeInfo;
MethSig: PProcedureSignature;
MethAttrData: TAttrData});
tkProcedure: (
ProcSig: PProcedureSignature;
ProcAttrData: TAttrData;);
tkInterface: (
IntfParent : PPTypeInfo; { ancestor }
IntfFlags : TIntfFlagsBase;
Guid : TGUID;
IntfUnit : TSymbolName
{IntfMethods: TIntfMethodTable;
IntfAttrData: TAttrData;});
tkInt64: (
MinInt64Value, MaxInt64Value: Int64;
Int64AttrData: TAttrData;);
tkDynArray: (
elSize: Integer;
elType: PPTypeInfo; // nil if type does not require cleanup
varType: Integer; // Ole Automation varType equivalent
elType2: PPTypeInfo; // independent of cleanup
DynUnitName: TSymbolName;
{DynArrElType: PPTypeInfo; // actual element type, even if dynamic array
DynArrAttrData: TAttrData});
tkRecord: (
RecSize: Integer;
ManagedFldCount: Integer;
{ManagedFields: array[0..ManagedFldCnt - 1] of TManagedField;
NumOps: Byte;
RecOps: array[1..NumOps] of Pointer;
RecFldCnt: Integer;
RecFields: array[1..RecFldCnt] of TRecordTypeField;
RecAttrData: TAttrData;
RecMethCnt: Word;
RecMeths: array[1..RecMethCnt] of TRecordTypeMethod});
tkClassRef: (
InstanceType: PPTypeInfo;
ClassRefAttrData: TAttrData;);
tkPointer: (
RefType: PPTypeInfo;
PtrAttrData: TAttrData);
tkArray: (
ArrayData: TArrayTypeData;
{ArrAttrData: TAttrData});
end;
{$endif}
TTypeDataContainer = class
private
Owner: TTypeInfoContainer;
function GetTypeDataSize: Integer; virtual; //save to buff
function GetSize: Integer; virtual; // save to stream
public
{$ifdef GE_DXETOKYO} // XILINX, Tokyo mod
TypeData: TTypeDataXil;
{$else}
TypeData: TTypeData;
{$endif}
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); virtual;
procedure SaveToBuff(S: TStream); virtual;
procedure LoadFromStream(S: TStream); virtual;
property TypeDataSize: Integer read GetTypeDataSize;
property Size: Integer read GetSize;
end;
TMethodTypeDataContainer = class(TTypeDataContainer)
private
function GetTypeDataSize: Integer; override;
function GetSize: Integer; override;
public
MethodKind: TMethodKind;
ParamCount: Byte;
ParamListContainer: TParamListContainer;
// extra data
ResultType: ShortString;
OwnerTypeName: String;
MethodTableIndex: Integer;
ResultTypeId: Integer;
CallConv: Byte;
OverCount: Byte;
Address: Pointer; // not saved to stream
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TClassTypeDataContainer = class(TTypeDataContainer)
private
function GetTypeDataSize: Integer; override;
function GetSize: Integer; override;
public
// info about published members
PropDataContainer: TPropDataContainer;
MethodTableCount: Integer;
MethodTableSize: Integer;
FieldTableCount: Integer;
FieldTableSize: Integer;
FullParentName: String;
FieldListContainer: TFieldListContainer;
// PCU only
AnotherFieldListContainer: TFieldListContainer;
AnotherPropList: TAnotherPropList;
SupportedInterfaces: TStringList;
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TInterfaceTypeDataContainer = class(TTypeDataContainer)
private
function GetTypeDataSize: Integer; override;
function GetSize: Integer; override;
public
PropDataContainer: TPropDataContainer;
FullParentName: String;
GUID: TGUID;
SubDescList: TSubDescList;
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TSetTypeDataContainer = class(TTypeDataContainer)
private
function GetSize: Integer; override;
public
FullCompName: String;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TEnumTypeDataContainer = class(TTypeDataContainer)
private
function GetTypeDataSize: Integer; override;
function GetSize: Integer; override;
public
NameList: array of ShortString;
EnumUnitName: ShortString;
//pcu only
ValueList: array of Integer;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TArrayTypeDataContainer = class(TTypeDataContainer)
public
FullRangeTypeName: String;
FullElemTypeName: String;
B1: Integer;
B2: Integer;
FinRangeTypeId: Integer;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TRecordTypeDataContainer = class(TTypeDataContainer)
private
function GetSize: Integer; override;
public
IsPacked: Boolean;
FieldListContainer: TFieldListContainer;
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); override;
procedure SaveToBuff(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TAliasTypeDataContainer = class(TTypeDataContainer)
public
FullSourceTypeName: String;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TPointerTypeDataContainer = class(TTypeDataContainer)
public
FullOriginTypeName: String;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TClassRefTypeDataContainer = class(TTypeDataContainer)
public
FullOriginTypeName: String;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TDynArrayTypeDataContainer = class(TTypeDataContainer)
public
FullElementTypeName: String;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
TProceduralTypeDataContainer = class(TTypeDataContainer)
public
SubDesc: TSubDesc;
constructor Create(AOwner: TTypeInfoContainer);
destructor Destroy; override;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
end;
{$IFDEF PAXARM}
TTypeInfoBuff = record
Kind: TTypeKind;
Name: ShortString;
end;
{$ELSE}
TTypeInfoBuff = TTypeInfo;
{$ENDIF}
TTypeInfoContainer = class
private
Buff: Pointer;
Buff4: Pointer;
Processed: Boolean;
function GetSize: Integer;
function GetPosTypeData: Integer;
function GetStreamSize: Integer;
function GetIsGeneric: Boolean;
public
TypeInfo: TTypeInfoBuff;
TypeDataContainer: TTypeDataContainer;
FullName: String;
FinTypeId: Byte;
GenericTypeContainer: TGenericTypeContainer;
constructor Create(AFinTypeId: Integer);
destructor Destroy; override;
procedure SaveToStream(S: TStream);
procedure SaveToBuff(S: TStream);
procedure LoadFromStream(S: TStream;
FinTypeId: Byte);
procedure RaiseError(const Message: string; params: array of Const);
property Size: Integer read GetSize;
property PosTypeData: Integer read GetPosTypeData;
property TypeInfoPtr: Pointer read Buff4;
property IsGeneric: Boolean read GetIsGeneric;
end;
TSetTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TEnumTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TClassTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TMethodTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TInterfaceTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TArrayTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TRecordTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TAliasTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TPointerTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TClassRefTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TDynArrayTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TProceduralTypeInfoContainer = class(TTypeInfoContainer)
public
constructor Create(const AName: String);
end;
TPaxTypeInfoList = class(TTypedList)
private
function GetRecord(I: Integer): TTypeInfoContainer;
procedure RaiseError(const Message: string; params: array of Const);
public
destructor Destroy; override;
procedure Add(Rec: TTypeInfoContainer);
function IndexOf(const FullName: String): Integer;
function LookupFullName(const FullName: String): TTypeInfoContainer;
procedure CopyToBuff;
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
procedure AddToProgram(AProg: Pointer);
function FindMethodFullName(Address: Pointer): String;
function Processed: Boolean;
property Records[I: Integer]: TTypeInfoContainer read GetRecord; default;
end;
function FinTypeToTypeKind(FinTypeId: Integer): TTypeKind;
function GetClassTypeInfoContainer(X: TObject): TClassTypeInfoContainer;
function PtiToFinType(Pti: PTypeInfo): Integer;
implementation
uses
PAXCOMP_CLASSLST,
PAXCOMP_STDLIB,
PAXCOMP_BASERUNNER;
{$ifdef GE_DXETOKYO} // XILINX, Tokyo mod
{ TTypeDataXil }
function TTypeDataXil.NameListFld: TTypeInfoFieldAccessor;
begin
Result.SetData(@NameList);
end;
function TTypeDataXil.UnitNameFld: TTypeInfoFieldAccessor;
begin
Result.SetData(@UnitName);
end;
function TTypeDataXil.IntfUnitFld: TTypeInfoFieldAccessor;
begin
Result.SetData(@IntfUnit);
end;
function TTypeDataXil.DynUnitNameFld: TTypeInfoFieldAccessor;
begin
Result.SetData(@DynUnitName);
end;
function TTypeDataXil.PropData: PPropData;
begin
Result := PPropData(UnitNameFld.Tail)
end;
function TTypeDataXil.IntfMethods: PIntfMethodTable;
begin
Result := PIntfMethodTable(IntfUnitFld.Tail);
end;
function TTypeDataXil.DynArrElType: PPTypeInfo;
type
PPPTypeInfo = ^PPTypeInfo;
begin
Result := PPPTypeInfo(DynUnitNameFld.Tail)^;
end;
function TTypeDataXil.DynArrAttrData: PAttrData;
begin
Result := PAttrData(Self.DynUnitNameFld.Tail + SizeOf(PPTypeInfo));
end;
{$endif}
function FinTypeToTypeKind(FinTypeId: Integer): TTypeKind;
begin
result := tkUnknown;
case FinTypeId of
{$IFNDEF PAXARM}
typeWIDESTRING: result := tkWString;
typeANSISTRING: result := tkLString;
typeANSICHAR: result := tkChar;
typeSHORTSTRING: result := tkString;
{$ENDIF}
{$IFDEF UNIC}
typeUNICSTRING: result := tkUString;
{$ENDIF}
typeVARIANT, typeOLEVARIANT: result := tkVariant;
typeINTEGER, typeBYTE, typeWORD, typeCARDINAL,
typeSMALLINT, typeSHORTINT: result := tkInteger;
typeENUM, typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL: result := tkEnumeration;
typeSET: result := tkSet;
typeWIDECHAR: result := tkWChar;
typeSINGLE, typeDOUBLE, typeEXTENDED, typeCURRENCY: result := tkFloat;
typeEVENT: result := tkMethod;
typeCLASS: result := tkClass;
typeINT64: result := tkInt64;
typeDYNARRAY: result := tkDynArray;
typeINTERFACE: result := tkInterface;
typeRECORD: result := tkRecord;
typeARRAY: result := tkArray;
end;
end;
function PtiToFinType(Pti: PTypeInfo): Integer;
begin
result := 0;
case Pti^.Kind of
tkInteger:
case GetTypeData(pti).OrdType of
otSByte: result := typeSMALLINT;
otUByte: result := typeBYTE;
otSWord: result := typeSHORTINT;
otUWord: result := typeWORD;
otSLong: result := typeINTEGER;
otULong: result := typeCARDINAL;
end;
tkChar:
result := typeCHAR;
tkWChar:
result := typeWIDECHAR;
{$IFNDEF PAXARM}
tkString:
result := typeSHORTSTRING;
tkLString:
result := typeANSISTRING;
tkWString:
result := typeWIDESTRING;
{$ENDIF}
{$IFDEF UNIC}
tkUString:
result := typeUNICSTRING;
{$ENDIF}
tkFloat:
case GetTypeData(pti)^.FloatType of
ftSingle: result := typeSINGLE;
ftDouble: result := typeDOUBLE;
ftExtended: result := typeEXTENDED;
ftComp: result := 0;
ftCurr: result := typeCURRENCY;
end;
{$IFDEF UNIC}
tkPointer:
result := typePOINTER;
{$ENDIF}
tkClass:
result := typeCLASS;
{$IFDEF UNIC}
tkClassRef:
result := typeCLASSREF;
tkProcedure:
result := typePROC;
{$ENDIF}
tkMethod:
result := typeEVENT;
tkInterface:
result := typeINTERFACE;
tkInt64:
result := typeINT64;
tkEnumeration:
result := typeENUM;
tkVariant:
result := typeVARIANT;
end;
end;
// TAnotherPropRec -------------------------------------------------------------
constructor TAnotherPropRec.Create;
begin
inherited;
ParamNames := TStringList.Create;
ParamTypes := TStringList.Create;
end;
destructor TAnotherPropRec.Destroy;
begin
FreeAndNil(ParamNames);
FreeAndNil(ParamTypes);
inherited;
end;
procedure TAnotherPropRec.SaveToStream(S: TStream);
begin
S.Write(Vis, SizeOf(Vis));
SaveStringToStream(PropName, S);
SaveStringListToStream(ParamNames, S);
SaveStringListToStream(ParamTypes, S);
SaveStringToStream(PropType, S);
SaveStringToStream(ReadName, S);
SaveStringToStream(WriteName, S);
S.Write(IsDefault, SizeOf(IsDefault));
end;
procedure TAnotherPropRec.LoadFromStream(S: TStream);
begin
S.Read(Vis, SizeOf(Vis));
PropName := LoadStringFromStream(S);
LoadStringListFromStream(ParamNames, S);
LoadStringListFromStream(ParamTypes, S);
PropType := LoadStringFromStream(S);
ReadName := LoadStringFromStream(S);
WriteName := LoadStringFromStream(S);
S.Read(IsDefault, SizeOf(IsDefault));
end;
// TAnotherPropList ------------------------------------------------------------
function TAnotherPropList.GetRecord(I: Integer): TAnotherPropRec;
begin
result := TAnotherPropRec(L[I]);
end;
function TAnotherPropList.Add: TAnotherPropRec;
begin
result := TAnotherPropRec.Create;
L.Add(result);
end;
procedure TAnotherPropList.SaveToStream(S: TStream);
var
I, K: Integer;
begin
K := Count;
S.Write(K, SizeOf(K));
for I := 0 to K - 1 do
Records[I].SaveToStream(S);
end;
procedure TAnotherPropList.LoadFromStream(S: TStream);
var
I, K: Integer;
R: TAnotherPropRec;
begin
S.Read(K, SizeOf(K));
for I := 0 to K - 1 do
begin
R := Add;
R.LoadFromStream(S);
end;
end;
// TFieldDataContainer ---------------------------------------------------------
procedure TFieldDataContainer.SaveToStream(S: TStream);
begin
S.Write(Offset, SizeOf(Offset));
S.Write(ClassIndex, SizeOf(ClassIndex));
SaveShortStringToStream(Name, S);
SaveStringToStream(FullFieldTypeName, S);
S.Write(Vis, SizeOf(Vis));
{$IFDEF PCU_EX}
S.Write(FinalFieldTypeId, SizeOf(FinalFieldTypeId));
{$ENDIF}
end;
procedure TFieldDataContainer.LoadFromStream(S: TStream);
begin
S.Read(Offset, SizeOf(Offset));
S.Read(ClassIndex, SizeOf(ClassIndex));
Name := LoadShortStringFromStream(S);
FullFieldTypeName := LoadStringFromStream(S);
S.Read(Vis, SizeOf(Vis));
{$IFDEF PCU_EX}
S.Read(FinalFieldTypeId, SizeOf(FinalFieldTypeId));
{$ENDIF}
end;
// TFieldListContainer ---------------------------------------------------------
function TFieldListContainer.GetRecord(I: Integer): TFieldDataContainer;
begin
result := TFieldDataContainer(L[I]);
end;
function TFieldListContainer.Add: TFieldDataContainer;
begin
result := TFieldDataContainer.Create;
L.Add(result);
end;
procedure TFieldListContainer.SaveToStream(S: TStream);
var
I, K: Integer;
begin
K := Count;
S.Write(K, SizeOf(K));
for I := 0 to K - 1 do
Records[I].SaveToStream(S);
end;
procedure TFieldListContainer.LoadFromStream(S: TStream);
var
I, K: Integer;
R: TFieldDataContainer;
begin
S.Read(K, SizeOf(K));
for I := 0 to K - 1 do
begin
R := Add;
R.LoadFromStream(S);
end;
end;
// TParamListContainer ---------------------------------------------------------
constructor TParamListContainer.Create(AOwner: TMethodTypeDataContainer);
begin
inherited Create;
Owner := AOwner;
end;
destructor TParamListContainer.Destroy;
begin
inherited;
end;
function TParamListContainer.GetCount: Integer;
begin
result := System.Length(ParamList);
end;
function TParamListContainer.GetSize: Integer;
var
I: Integer;
begin
result := 0;
for I := 0 to Count - 1 do
begin
Inc(result, SizeOf(ParamList[I].Flags));
Inc(result, Length(ParamList[I].ParamName) + 1);
Inc(result, Length(ParamList[I].TypeName) + 1);
end;
end;
procedure TParamListContainer.SaveToStream(S: TStream);
var
I, K: Integer;
begin
K := Count;
S.Write(K, SizeOf(Integer));
for I := 0 to Count - 1 do
with ParamList[I] do
begin
S.Write(Flags, SizeOf(Flags));
SaveShortStringToStream(ParamName, S);
SaveShortStringToStream(TypeName, S);
end;
end;
procedure TParamListContainer.SaveToBuff(S: TStream);
var
I: Integer;
begin
for I := 0 to Count - 1 do
with ParamList[I] do
begin
S.Write(Flags, SizeOf(Flags));
SaveShortStringToStream(ParamName, S);
SaveShortStringToStream(TypeName, S);
end;
end;
procedure TParamListContainer.LoadFromStream(S: TStream);
var
I, K: Integer;
begin
S.Read(K, SizeOf(Integer));
SetLength(ParamList, K);
for I := 0 to Count - 1 do
with ParamList[I] do
begin
S.Read(Flags, SizeOf(Flags));
ParamName := LoadShortStringFromStream(S);
TypeName := LoadShortStringFromStream(S);
end;
end;
// TPropDataContainer -------------------------------------------------------
constructor TPropDataContainer.Create(AOwner: TTypeDataContainer);
begin
Owner := AOwner;
ReadNames := TStringList.Create;
WriteNames := TStringList.Create;
PropTypeNames := TStringList.Create;
inherited Create;
end;
function PropInfoSize(const PropInfo: TPropInfo): Integer;
begin
{$IFDEF PAXARM}
result := SizeOf(TPropInfo) - SizeOf(ShortString) +
{$IFDEF ARC}
PropInfo.Name + 1;
{$ELSE}
Length(PropInfo.Name) + 1;
{$ENDIF}
{$ELSE}
result := SizeOf(TPropInfo) - SizeOf(ShortString) +
Length(PropInfo.Name) + 1;
{$ENDIF}
end;
destructor TPropDataContainer.Destroy;
begin
FreeAndNil(ReadNames);
FreeAndNil(WriteNames);
FreeAndNil(PropTypeNames);
inherited;
end;
function TPropDataContainer.GetCount: Integer;
begin
result := PropData.PropCount;
end;
function TPropDataContainer.GetSize: Integer;
var
I: Integer;
begin
result := SizeOf(TPropData);
for I := 0 to Count - 1 do
Inc(result, PropInfoSize(PropList[I]));
{$IFDEF DRTTI}
Inc(result, SizeOf(TPropDataEx));
{$ELSE}
{$IFDEF DPULSAR}
Inc(result, SizeOf(TPropInfoEx));
{$ENDIF}
{$ENDIF}
end;
procedure TPropDataContainer.SaveToStream(S: TStream);
var
I, SZ: Integer;
begin
S.Write(PropData, SizeOf(TPropData));
for I := 0 to Count - 1 do
begin
SZ := PropInfoSize(PropList[I]);
S.Write(SZ, SizeOf(Integer));
S.Write(PropList[I], SZ);
end;
SaveStringListToStream(ReadNames, S);
SaveStringListToStream(WriteNames, S);
SaveStringListToStream(PropTypeNames, S);
for I := 0 to Count - 1 do
S.Write(PropTypeIds[I], SizeOf(PropTypeIds[I]));
end;
procedure TPropDataContainer.SaveToBuff(S: TStream);
var
I: Integer;
{$IFDEF DRTTI}
PropEx: TPropDataEx;
{$ELSE}
{$IFDEF DPULSAR}
PropEx: TPropDataEx;
{$ENDIF}
{$ENDIF}
begin
S.Write(PropData, SizeOf(TPropData));
for I := 0 to Count - 1 do
S.Write(PropList[I], PropInfoSize(PropList[I]));
{$IFDEF DRTTI}
FillChar(PropEx, SizeOf(PropEx), #0);
S.Write(PropEx, SizeOf(TPropDataEx));
{$ELSE}
{$IFDEF DPULSAR}
FillChar(PropEx, SizeOf(PropEx), #0);
S.Write(PropEx, SizeOf(TPropDataEx));
{$ENDIF}
{$ENDIF}
end;
procedure TPropDataContainer.LoadFromStream(S: TStream);
var
I, SZ: Integer;
begin
S.Read(PropData, SizeOf(TPropData));
SetLength(PropList, PropData.PropCount);
for I := 0 to PropData.PropCount - 1 do
begin
S.Read(SZ, SizeOf(Integer));
S.Read(PropList[I], SZ);
end;
LoadStringListFromStream(ReadNames, S);
LoadStringListFromStream(WriteNames, S);
LoadStringListFromStream(PropTypeNames, S);
SetLength(PropTypeIds, PropData.PropCount);
for I := 0 to PropData.PropCount - 1 do
S.Read(PropTypeIds[I], SizeOf(PropTypeIds));
end;
// TTypeDataContainer -------------------------------------------------------
constructor TTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
Owner := AOwner;
inherited Create;
end;
destructor TTypeDataContainer.Destroy;
begin
inherited;
end;
function TTypeDataContainer.GetTypeDataSize: Integer;
begin
result := SizeOf(TypeData);
end;
function TTypeDataContainer.GetSize: Integer;
begin
result := SizeOf(TypeData);
end;
procedure TTypeDataContainer.SaveToStream(S: TStream);
begin
S.Write(TypeData, 16);
end;
procedure TTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, SizeOf(TypeData));
end;
procedure TTypeDataContainer.LoadFromStream(S: TStream);
begin
FillChar(TypeData, SizeOf(TypeData), 0);
S.Read(TypeData, 16);
end;
// TMethodTypeDataContainer ----------------------------------------------------
constructor TMethodTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
inherited;
ParamListContainer := TParamListContainer.Create(Self);
end;
destructor TMethodTypeDataContainer.Destroy;
begin
FreeAndNil(ParamListContainer);
inherited;
end;
function TMethodTypeDataContainer.GetTypeDataSize: Integer;
begin
result := SizeOf(MethodKind) + SizeOf(ParamCount);
end;
function TMethodTypeDataContainer.GetSize: Integer;
begin
result := TypeDataSize + ParamListContainer.Size +
Length(ResultType) + 1;
end;
procedure TMethodTypeDataContainer.SaveToStream(S: TStream);
begin
S.Write(MethodKind, SizeOf(MethodKind));
S.Write(ParamCount, SizeOf(ParamCount));
ParamListContainer.SaveToStream(S);
SaveShortStringToStream(ResultType, S);
SaveStringToStream(OwnerTypeName, S);
S.Write(MethodTableIndex, SizeOf(MethodTableIndex));
S.Write(ResultTypeId, SizeOf(ResultTypeId));
S.Write(CallConv, SizeOf(CallConv));
S.Write(OverCount, SizeOf(OverCount));
end;
procedure TMethodTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(MethodKind, SizeOf(MethodKind));
S.Write(ParamCount, SizeOf(ParamCount));
ParamListContainer.SaveToBuff(S);
SaveShortStringToStream(ResultType, S);
end;
procedure TMethodTypeDataContainer.LoadFromStream(S: TStream);
begin
S.Read(MethodKind, SizeOf(MethodKind));
S.Read(ParamCount, SizeOf(ParamCount));
ParamListContainer.LoadFromStream(S);
ResultType := LoadShortStringFromStream(S);
OwnerTypeName := LoadStringFromStream(S);
S.Read(MethodTableIndex, SizeOf(MethodTableIndex));
S.Read(ResultTypeId, SizeOf(ResultTypeId));
S.Read(CallConv, SizeOf(CallConv));
S.Read(OverCount, SizeOf(OverCount));
end;
// TClassTypeDataContainer -----------------------------------------------------
constructor TClassTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
inherited;
PropDataContainer := TPropDataContainer.Create(Self);
FieldListContainer := TFieldListContainer.Create;
AnotherFieldListContainer := TFieldListContainer.Create;
AnotherPropList := TAnotherPropList.Create;
SupportedInterfaces := TStringList.Create;
end;
destructor TClassTypeDataContainer.Destroy;
begin
FreeAndNil(PropDataContainer);
FreeAndNil(FieldListContainer);
FreeAndNil(AnotherFieldListContainer);
FreeAndNil(AnotherPropList);
FreeAndNil(SupportedInterfaces);
inherited;
end;
function TClassTypeDataContainer.GetTypeDataSize: Integer;
begin
{$IFDEF PAXARM}
result := SizeOf(TypeData.ClassType) +
SizeOf(TypeData.ParentInfo) +
SizeOf(TypeData.PropCount) +
{$IFDEF ARC}
TypeData.UnitName + 1;
{$ELSE}
Length(TypeData.UnitName) + 1;
{$ENDIF}
{$ELSE}
result := SizeOf(TypeData.ClassType) +
SizeOf(TypeData.ParentInfo) +
SizeOf(TypeData.PropCount) +
Length(TypeData.UnitName) + 1;
{$ENDIF}
end;
function TClassTypeDataContainer.GetSize: Integer;
begin
result := TypeDataSize +
PropDataContainer.Size;
end;
procedure TClassTypeDataContainer.SaveToStream(S: TStream);
var
K: Integer;
begin
K := TypeDataSize;
S.Write(K, SizeOf(K));
S.Write(TypeData, TypeDataSize);
PropDataContainer.SaveToStream(S);
S.Write(MethodTableCount, SizeOf(MethodTableCount));
S.Write(MethodTableSize, SizeOf(MethodTableSize));
S.Write(FieldTableCount, SizeOf(FieldTableCount));
S.Write(FieldTableSize, SizeOf(FieldTableSize));
SaveStringToStream(FullParentName, S);
FieldListContainer.SaveToStream(S);
AnotherFieldListContainer.SaveToStream(S);
AnotherPropList.SaveToStream(S);
SaveStringListToStream(SupportedInterfaces, S);
end;
procedure TClassTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, TypeDataSize);
PropDataContainer.SaveToBuff(S);
end;
procedure TClassTypeDataContainer.LoadFromStream(S: TStream);
var
K: Integer;
begin
S.Read(K, SizeOf(K));
S.Read(TypeData, K);
PropDataContainer.LoadFromStream(S);
S.Read(MethodTableCount, SizeOf(MethodTableCount));
S.Read(MethodTableSize, SizeOf(MethodTableSize));
S.Read(FieldTableCount, SizeOf(FieldTableCount));
S.Read(FieldTableSize, SizeOf(FieldTableSize));
FullParentName := LoadStringFromStream(S);
FieldListContainer.LoadFromStream(S);
AnotherFieldListContainer.LoadFromStream(S);
AnotherPropList.LoadFromStream(S);
LoadStringListFromStream(SupportedInterfaces, S);
end;
// TSetTypeDataContainer -------------------------------------------------
function TSetTypeDataContainer.GetSize: Integer;
begin
result := SizeOf(TypeData);
end;
procedure TSetTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullCompName, S);
end;
procedure TSetTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, SizeOf(TypeData));
end;
procedure TSetTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullCompName := LoadStringFromStream(S);
end;
// TEnumTypeDataContainer ------------------------------------------------------
function TEnumTypeDataContainer.GetTypeDataSize: Integer;
begin
result := SizeOf(TOrdType) +
SizeOf(Longint) + // min value
SizeOf(Longint) + // max value
SizeOf(Pointer); // base type
end;
function TEnumTypeDataContainer.GetSize: Integer;
begin
result := GetTypeDataSize;
{
for I := 0 to Length(NameList) - 1 do
Inc(result, Length(NameList[I]) + 1);
}
Inc(result, 256);
Inc(result, Length(EnumUnitName) + 1);
end;
procedure TEnumTypeDataContainer.SaveToStream(S: TStream);
var
I, K: Integer;
begin
S.Write(TypeData, GetTypeDataSize);
K := System.Length(NameList);
S.Write(K, SizeOf(K));
for I := 0 to K - 1 do
SaveShortStringToStream(NameList[I], S);
SaveShortStringToStream(EnumUnitName, S);
for I := 0 to K - 1 do
S.Write(ValueList[I], SizeOf(ValueList[I]));
end;
procedure TEnumTypeDataContainer.SaveToBuff(S: TStream);
var
I, K, Z: Integer;
B: Byte;
begin
S.Write(TypeData, GetTypeDataSize);
K := System.Length(NameList);
Z := 0;
for I := 0 to K - 1 do
begin
SaveShortStringToStream(NameList[I], S);
Inc(z, Length(NameList[I]) + 1);
end;
B := 0;
while Z < 256 do
begin
Inc(Z);
S.Write(B, 1);
end;
SaveShortStringToStream(EnumUnitName, S);
end;
procedure TEnumTypeDataContainer.LoadFromStream(S: TStream);
var
I, K: Integer;
begin
S.Read(TypeData, GetTypeDataSize);
S.Read(K, SizeOf(K));
SetLength(NameList, K);
for I := 0 to K - 1 do
NameList[I] := LoadShortStringFromStream(S);
EnumUnitName := LoadShortStringFromStream(S);
SetLength(ValueList, K);
for I := 0 to K - 1 do
S.Read(ValueList[I], SizeOf(ValueList[I]));
end;
// TInterfaceTypeDataContainer -------------------------------------------------
constructor TInterfaceTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
inherited;
PropDataContainer := TPropDataContainer.Create(Self);
SubDescList := TSubDescList.Create;
end;
destructor TInterfaceTypeDataContainer.Destroy;
begin
FreeAndNil(PropDataContainer);
FreeAndNil(SubDescList);
inherited;
end;
function TInterfaceTypeDataContainer.GetTypeDataSize: Integer;
begin
{$IFDEF PAXARM}
result := SizeOf(TypeData.IntfParent) +
SizeOf(TypeData.IntfFlags) +
SizeOf(TypeData.Guid) +
{$IFDEF ARC}
TypeData.IntfUnit + 1;
{$ELSE}
Length(TypeData.IntfUnit) + 1;
{$ENDIF}
{$ELSE}
result := SizeOf(TypeData.IntfParent) +
SizeOf(TypeData.IntfFlags) +
SizeOf(TypeData.Guid) +
Length(TypeData.IntfUnit) + 1;
{$ENDIF}
end;
function TInterfaceTypeDataContainer.GetSize: Integer;
begin
result := TypeDataSize +
PropDataContainer.Size;
end;
procedure TInterfaceTypeDataContainer.SaveToStream(S: TStream);
var
K: Integer;
begin
K := TypeDataSize;
S.Write(K, SizeOf(K));
S.Write(TypeData, TypeDataSize);
PropDataContainer.SaveToStream(S);
SaveStringToStream(FullParentName, S);
SubDescList.SaveToStream(S);
S.Write(GUID, SizeOf(GUID));
end;
procedure TInterfaceTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, TypeDataSize);
PropDataContainer.SaveToBuff(S);
end;
procedure TInterfaceTypeDataContainer.LoadFromStream(S: TStream);
var
K: Integer;
begin
S.Read(K, SizeOf(K));
S.Read(TypeData, K);
PropDataContainer.LoadFromStream(S);
FullParentName := LoadStringFromStream(S);
SubDescList.LoadFromStream(S);
S.Read(GUID, SizeOf(GUID));
end;
// TArrayTypeDataContainer -----------------------------------------------------
procedure TArrayTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullRangeTypeName, S);
SaveStringToStream(FullElemTypeName, S);
S.Write(B1, SizeOf(B1));
S.Write(B2, SizeOf(B2));
S.Write(FinRangeTypeId, SizeOf(FinRangeTypeId));
end;
procedure TArrayTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, SizeOf(TypeData));
end;
procedure TArrayTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullRangeTypeName := LoadStringFromStream(S);
FullElemTypeName := LoadStringFromStream(S);
S.Read(B1, SizeOf(B1));
S.Read(B2, SizeOf(B2));
S.Read(FinRangeTypeId, SizeOf(FinRangeTypeId));
end;
// TRecordTypeDataContainer ----------------------------------------------------
constructor TRecordTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
inherited;
FieldListContainer := TFieldListContainer.Create;
end;
destructor TRecordTypeDataContainer.Destroy;
begin
FreeAndNil(FieldListContainer);
inherited;
end;
function TRecordTypeDataContainer.GetSize: Integer;
begin
result := SizeOf(TypeData);
end;
procedure TRecordTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
S.Write(IsPacked, SizeOf(IsPacked));
FieldListContainer.SaveToStream(S);
end;
procedure TRecordTypeDataContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeData, SizeOf(TypeData));
end;
procedure TRecordTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
S.Read(IsPacked, SizeOf(IsPacked));
FieldListContainer.LoadFromStream(S);
end;
// TAliasTypeDataContainer -----------------------------------------------------
procedure TAliasTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullSourceTypeName, S);
end;
procedure TAliasTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullSourceTypeName := LoadStringFromStream(S);
end;
// TPointerTypeDataContainer ---------------------------------------------------
procedure TPointerTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullOriginTypeName, S);
end;
procedure TPointerTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullOriginTypeName := LoadStringFromStream(S);
end;
// TClassRefTypeDataContainer --------------------------------------------------
procedure TClassRefTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullOriginTypeName, S);
end;
procedure TClassRefTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullOriginTypeName := LoadStringFromStream(S);
end;
// TDynArrayTypeDataContainer --------------------------------------------------
procedure TDynArrayTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SaveStringToStream(FullElementTypeName, S);
end;
procedure TDynArrayTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
FullElementTypeName := LoadStringFromStream(S);
end;
// TProceduralTypeDataContainer ------------------------------------------------
constructor TProceduralTypeDataContainer.Create(AOwner: TTypeInfoContainer);
begin
inherited;
SubDesc := TSubDesc.Create;
end;
destructor TProceduralTypeDataContainer.Destroy;
begin
FreeAndNil(SubDesc);
inherited;
end;
procedure TProceduralTypeDataContainer.SaveToStream(S: TStream);
begin
inherited;
SubDesc.SaveToStream(S);
end;
procedure TProceduralTypeDataContainer.LoadFromStream(S: TStream);
begin
inherited;
SubDesc.LoadFromStream(S);
end;
// TEnumTypeInfoContainer ------------------------------------------------------
constructor TEnumTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkEnumeration;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TEnumTypeDataContainer.Create(Self);
FinTypeId := typeENUM;
end;
// TSetTypeInfoContainer -----------------------------------------------------
constructor TSetTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkSet;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TSetTypeDataContainer.Create(Self);
FinTypeId := typeSET;
end;
// TClassTypeInfoContainer -----------------------------------------------------
constructor TClassTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkClass;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TClassTypeDataContainer.Create(Self);
FinTypeId := typeCLASS;
end;
// TInterfaceTypeInfoContainer -----------------------------------------------------
constructor TInterfaceTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkInterface;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TInterfaceTypeDataContainer.Create(Self);
FinTypeId := typeINTERFACE;
end;
// TMethodTypeInfoContainer -----------------------------------------------------
constructor TMethodTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkMethod;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TMethodTypeDataContainer.Create(Self);
FinTypeId := typeEVENT;
end;
// TArrayTypeInfoContainer -----------------------------------------------------
constructor TArrayTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkArray;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TArrayTypeDataContainer.Create(Self);
FinTypeId := typeARRAY;
end;
// TRecordTypeInfoContainer ----------------------------------------------------
constructor TRecordTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkRecord;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TRecordTypeDataContainer.Create(Self);
FinTypeId := typeRECORD;
end;
// TAliasTypeInfoContainer -----------------------------------------------------
constructor TAliasTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkUnknown;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TAliasTypeDataContainer.Create(Self);
FinTypeId := typeALIAS;
end;
// TPointerTypeInfoContainer ---------------------------------------------------
constructor TPointerTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkUnknown;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TPointerTypeDataContainer.Create(Self);
FinTypeId := typePOINTER;
end;
// TClassRefTypeInfoContainer --------------------------------------------------
constructor TClassRefTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkUnknown;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TClassRefTypeDataContainer.Create(Self);
FinTypeId := typeCLASSREF;
end;
// TDynArrayTypeInfoContainer --------------------------------------------------
constructor TDynArrayTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkDynArray;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TDynArrayTypeDataContainer.Create(Self);
FinTypeId := typeDYNARRAY;
end;
// TProceduralTypeInfoContainer ------------------------------------------------
constructor TProceduralTypeInfoContainer.Create(const AName: String);
begin
inherited Create(0);
TypeInfo.Kind := tkUnknown;
PShortStringFromString(PShortString(@TypeInfo.Name), AName);
FreeAndNil(TypeDataContainer);
TypeDataContainer := TProceduralTypeDataContainer.Create(Self);
FinTypeId := typePROC;
end;
// TTypeInfoContainer -------------------------------------------------------
constructor TTypeInfoContainer.Create(AFinTypeId: Integer);
begin
inherited Create;
TypeDataContainer := TTypeDataContainer.Create(Self);
FinTypeId := AFinTypeId;
GenericTypeContainer := TGenericTypeContainer.Create;
end;
destructor TTypeInfoContainer.Destroy;
begin
if Assigned(Buff) then
FreeMem(Buff, Size);
FreeAndNil(TypeDataContainer);
FreeAndNil(GenericTypeContainer);
inherited;
end;
function TTypeInfoContainer.GetIsGeneric: Boolean;
begin
result := GenericTypeContainer.Definition <> '';
end;
function TTypeInfoContainer.GetSize: Integer;
begin
{$IFDEF ARC}
result := SizeOf(TTypeKind) + TypeInfo.Name[0] + 1 +
TypeDataContainer.Size;
{$ELSE}
result := SizeOf(TTypeKind) + Length(TypeInfo.Name) + 1 +
TypeDataContainer.Size;
{$ENDIF}
end;
function TTypeInfoContainer.GetPosTypeData: Integer;
begin
{$IFDEF ARC}
result := SizeOf(TTypeKind) + TypeInfo.Name[0] + 1;
{$ELSE}
result := SizeOf(TTypeKind) + Length(TypeInfo.Name) + 1;
{$ENDIF}
end;
function TTypeInfoContainer.GetStreamSize: Integer;
var
M: TMemoryStream;
begin
M := TMemoryStream.Create;
try
SaveToStream(M);
result := M.Size;
finally
FreeAndNil(M);
end;
end;
procedure TTypeInfoContainer.SaveToStream(S: TStream);
begin
S.Write(TypeInfo.Kind, SizeOf(TTypeKind));
SaveShortStringToStream(PShortString(@TypeInfo.Name)^, S);
TypeDataContainer.SaveToStream(S);
SaveStringToStream(FullName, S);
GenericTypeContainer.SaveToStream(S);
end;
procedure TTypeInfoContainer.SaveToBuff(S: TStream);
begin
S.Write(TypeInfo.Kind, SizeOf(TTypeKind));
SaveShortStringToStream(PShortString(@TypeInfo.Name)^, S);
TypeDataContainer.SaveToBuff(S);
end;
procedure TTypeInfoContainer.LoadFromStream(S: TStream;
FinTypeId: Byte);
begin
S.Read(TypeInfo.Kind, SizeOf(TTypeKind));
_ShortStringAssign(LoadShortStringFromStream(S), 255, PShortString(@TypeInfo.Name));
FreeAndNil(TypeDataContainer);
case FinTypeId of
typeCLASS: TypeDataContainer := TClassTypeDataContainer.Create(Self);
typeINTERFACE: TypeDataContainer := TInterfaceTypeDataContainer.Create(Self);
typeEVENT: TypeDataContainer := TMethodTypeDataContainer.Create(Self);
typeSET: TypeDataContainer := TSetTypeDataContainer.Create(Self);
typeENUM: TypeDataContainer := TEnumTypeDataContainer.Create(Self);
typeARRAY: TypeDataContainer := TArrayTypeDataContainer.Create(Self);
typeRECORD: TypeDataContainer := TRecordTypeDataContainer.Create(Self);
typeALIAS: TypeDataContainer := TAliasTypeDataContainer.Create(Self);
typePOINTER: TypeDataContainer := TPointerTypeDataContainer.Create(Self);
typeCLASSREF: TypeDataContainer := TClassRefTypeDataContainer.Create(Self);
typeDYNARRAY: TypeDataContainer := TDynArrayTypeDataContainer.Create(Self);
typePROC: TypeDataContainer := TProceduralTypeDataContainer.Create(Self);
else
TypeDataContainer := TTypeDataContainer.Create(Self);
end;
TypeDataContainer.LoadFromStream(S);
FullName := LoadStringFromStream(S);
GenericTypeContainer.LoadFromStream(S);
end;
procedure TTypeInfoContainer.RaiseError(const Message: string; params: array of Const);
begin
raise Exception.Create(Format(Message, params));
end;
// TPaxTypeInfoList ------------------------------------------------------------
destructor TPaxTypeInfoList.Destroy;
begin
inherited;
end;
function TPaxTypeInfoList.GetRecord(I: Integer): TTypeInfoContainer;
begin
result := TTypeInfoContainer(L[I]);
end;
procedure TPaxTypeInfoList.Add(Rec: TTypeInfoContainer);
begin
L.Add(Rec);
end;
procedure TPaxTypeInfoList.SaveToStream(S: TStream);
var
I, K: Integer;
begin
K := Count;
S.Write(K, SizeOf(Integer));
for I:=0 to K - 1 do
begin
S.Write(Records[I].FinTypeId, SizeOf(Records[I].FinTypeId));
Records[I].SaveToStream(S);
end;
end;
procedure TPaxTypeInfoList.LoadFromStream(S: TStream);
var
I, K: Integer;
R: TTypeInfoContainer;
FinTypeId: Byte;
begin
Clear;
S.Read(K, SizeOf(Integer));
for I:=0 to K - 1 do
begin
S.Read(FinTypeId, SizeOf(Byte));
case FinTypeId of
typeCLASS: R := TClassTypeInfoContainer.Create('');
typeINTERFACE: R := TInterfaceTypeInfoContainer.Create('');
typeEVENT: R := TMethodTypeInfoContainer.Create('');
typeSET: R := TSetTypeInfoContainer.Create('');
typeENUM: R := TEnumTypeInfoContainer.Create('');
typeARRAY: R := TArrayTypeInfoContainer.Create('');
typeRECORD: R := TRecordTypeInfoContainer.Create('');
typeALIAS: R := TAliasTypeInfoContainer.Create('');
typePOINTER: R := TPointerTypeInfoContainer.Create('');
typeCLASSREF: R := TClassRefTypeInfoContainer.Create('');
typeDYNARRAY: R := TDynArrayTypeInfoContainer.Create('');
typePROC: R := TProceduralTypeInfoContainer.Create('');
else
R := TTypeInfoContainer.Create(FinTypeId);
end;
R.LoadFromStream(S, FinTypeId);
Add(R);
end;
end;
function TPaxTypeInfoList.LookupFullName(const FullName: String): TTypeInfoContainer;
var
I: Integer;
begin
result := nil;
for I := 0 to Count - 1 do
if StrEql(FullName, String(Records[I].FullName)) then
begin
result := Records[I];
Exit;
end;
end;
function TPaxTypeInfoList.IndexOf(const FullName: String): Integer;
var
I: Integer;
begin
result := -1;
for I := 0 to Count - 1 do
if StrEql(FullName, String(Records[I].FullName)) then
begin
result := I;
Exit;
end;
end;
procedure TPaxTypeInfoList.CopyToBuff;
var
S: TMemoryStream;
I, SZ, StreamSize, K: Integer;
begin
for I := 0 to Count - 1 do
begin
SZ := Records[I].Size;
StreamSize := Records[I].GetStreamSize;
K := SizeOf(Integer) + SZ +
SizeOf(Integer) + StreamSize;
Records[I].Buff := AllocMem(K);
Records[I].Buff4 := ShiftPointer(Records[I].Buff, 4);
S := TMemoryStream.Create;
try
S.Write(SZ, SizeOf(Integer));
Records[I].SaveToBuff(S);
S.Write(StreamSize, SizeOf(Integer));
Records[I].SaveToStream(S);
S.Position := 0;
S.Read(Records[I].Buff^, K);
finally
FreeAndNil(S);
end;
end;
end;
procedure TPaxTypeInfoList.AddToProgram(AProg: Pointer);
var
ClassFactory: TPaxClassFactory;
I, J, JJ: Integer;
P: Pointer;
R: TPaxClassFactoryRec;
C: TClass;
ptd: PTypeData;
pti, pti_parent: PTypeInfo;
Record_Parent, Record_Temp: TTypeInfoContainer;
PropDataContainer: TPropDataContainer;
Prog: TBaseRunner;
FullName: String;
ppi: PPropInfo;
Z, ZZ: Integer;
ClassTypeInfoContainer: TClassTypeInfoContainer;
ClassTypeDataContainer: TClassTypeDataContainer;
MethodTypeInfoContainer: TMethodTypeInfoContainer;
MethodTypeDataContainer: TMethodTypeDataContainer;
InterfaceTypeDataContainer: TInterfaceTypeDataContainer;
SetTypeDataContainer: TSetTypeDataContainer;
MethodTableIndex: Integer;
PMethod: PVmtMethod;
FieldListContainer: TFieldListContainer;
PField: PVmtField;
ClassRec: TClassRec;
RI: TTypeInfoContainer;
ParentPropCount: Integer;
MR, SomeMR: TMapRec;
FileName, ProcName: String;
DestProg: Pointer;
begin
Prog := TBaseRunner(AProg);
ClassFactory := Prog.ProgClassFactory;
CopyToBuff;
for I:=0 to Count - 1 do
Records[I].Processed := false;
repeat
for I:=0 to Count - 1 do
begin
RI := Records[I];
if RI.Processed then
continue;
pti := RI.Buff4;
case RI.TypeInfo.Kind of
tkEnumeration:
begin
ptd := ShiftPointer(pti, RI.PosTypeData);
{$IFDEF FPC}
ptd^.BaseType := RI.Buff4;
{$ELSE}
ptd^.BaseType := @ RI.Buff4;
{$ENDIF}
RI.Processed := true;
end;
tkSet:
begin
RI.Processed := true;
ptd := ShiftPointer(pti, RI.PosTypeData);
SetTypeDataContainer := RI.TypeDataContainer as
TSetTypeDataContainer;
Record_Temp := LookupFullName(SetTypeDataContainer.FullCompName);
if Record_Temp = nil then
ptd^.CompType := nil
else
{$IFDEF FPC}
ptd^.CompType := Record_Temp.buff4;
{$ELSE}
ptd^.CompType := @ Record_Temp.buff4;
{$ENDIF}
end;
tkMethod:
begin
RI.Processed := true;
MethodTypeInfoContainer := TMethodTypeInfoContainer(RI);
MethodTypeDataContainer := TMethodTypeDataContainer(MethodTypeInfoContainer.TypeDataContainer);
if MethodTypeDataContainer.OwnerTypeName = '' then
continue;
Record_Temp := LookupFullName(MethodTypeDataContainer.OwnerTypeName);
if Record_Temp = nil then
RaiseError(errInternalError, []);
R := ClassFactory.FindRecordByFullName(MethodTypeDataContainer.OwnerTypeName);
if R = nil then
RaiseError(errInternalError, []);
ClassTypeInfoContainer := Record_Temp as
TClassTypeInfoContainer;
ClassTypeDataContainer := Record_Temp.TypeDataContainer as
TClassTypeDataContainer;
if R.MethodTableSize = 0 then
begin
R.MethodTableSize := ClassTypeDataContainer.MethodTableSize;
vmtMethodTableSlot(R.VMTPtr)^ := AllocMem(R.MethodTableSize);
PVmtMethodTable(vmtMethodTableSlot(R.VMTPtr)^)^.Count :=
ClassTypeDataContainer.MethodTableCount;
end;
PMethod := ShiftPointer(vmtMethodTableSlot(R.VMTPtr)^,
SizeOf(TVmtMethodCount));
MethodTableIndex := MethodTypeDataContainer.MethodTableIndex;
for J := 0 to MethodTableIndex - 1 do
PMethod := ShiftPointer(PMethod, GetMethodSize(PMethod));
{$IFDEF FPC}
PMethod^.MethName := @ MethodTypeInfoContainer.TypeInfo.Name;
FullName := MethodTypeDataContainer.OwnerTypeName + '.' +
String(PMethod^.MethName^);
PMethod^.MethAddr := Prog.GetAddress(FullName, MR);
DestProg := Prog;
if PMethod^.MethAddr = nil then
begin
FileName := ExtractOwner(FullName) + '.' + PCU_FILE_EXT;
ProcName := Copy(FullName, PosCh('.', FullName) + 1, Length(FullName));
PMethod^.MethAddr := Prog.LoadAddressEx(FileName, ProcName, false,
MethodTypeDataContainer.OverCount, SomeMR, DestProg);
end;
TBaseRunner(DestProg).WrapMethodAddress(PMethod^.MethAddr);
MethodTypeDataContainer.Address := PMethod^.MethAddr;
{$ELSE}
_ShortStringAssign(PShortString(@MethodTypeInfoContainer.TypeInfo.Name)^,
255,
PShortString(@PMethod^.Name));
FullName := MethodTypeDataContainer.OwnerTypeName + '.' +
StringFromPShortString(PShortString(@PMethod^.Name));
PMethod^.Address := Prog.GetAddress(FullName, MR);
DestProg := Prog;
if PMethod^.Address = nil then
begin
FileName := ExtractOwner(FullName) + '.' + PCU_FILE_EXT;
ProcName := Copy(FullName, PosCh('.', FullName) + 1, Length(FullName));
PMethod^.Address := Prog.LoadAddressEx(FileName, ProcName, false,
MethodTypeDataContainer.OverCount, SomeMR, DestProg);
end;
TBaseRunner(DestProg).WrapMethodAddress(PMethod^.Address);
{$ifdef PAX64}
PMethod^.Size := SizeOf(Word) +
SizeOf(Pointer) +
Length(PMethod^.Name) + 1;
{$endif}
{$ifdef WIN32}
PMethod^.Size := SizeOf(Word) +
SizeOf(Pointer) +
Length(PMethod^.Name) + 1;
{$endif}
{$ifdef MACOS}
PMethod^.Size := SizeOf(Word) +
SizeOf(Pointer) +
Length(PMethod^.Name) + 1;
{$endif}
{$ifdef ARC}
PMethod^.Size := SizeOf(Word) +
SizeOf(Pointer) +
PMethod^.Name[0] + 1;
{$ENDIF}
MethodTypeDataContainer.Address := PMethod^.Address;
{$ENDIF}
end;
tkInterface:
begin
RI.Processed := true;
ptd := ShiftPointer(pti, RI.PosTypeData);
InterfaceTypeDataContainer := RI.TypeDataContainer as
TInterfaceTypeDataContainer;
Record_Parent := LookupFullName(InterfaceTypeDataContainer.FullParentName);
if Record_Parent = nil then
ptd^.IntfParent := nil
else
{$IFDEF FPC}
ptd^.IntfParent := Record_Parent.buff4;
{$ELSE}
ptd^.IntfParent := @ Record_Parent.buff4;
{$ENDIF}
Z := RI.TypeDataContainer.TypeDataSize +
SizeOf(TPropData);
PropDataContainer := InterfaceTypeDataContainer.PropDataContainer;
for J := 0 to PropDataContainer.Count - 1 do
begin
ZZ := 0;
if J > 0 then
for JJ := 0 to J - 1 do
Inc(ZZ, PropInfoSize(PropDataContainer.PropList[JJ]));
ppi := ShiftPointer(ptd, Z + ZZ);
ppi^.NameIndex := J;
Record_Temp := LookupFullName(PropDataContainer.PropTypeNames[J]);
if Record_Temp = nil then
begin
ppi^.PropType := nil;
end
else
{$IFDEF FPC}
ppi^.PropType := Record_Temp.Buff4;
{$ELSE}
ppi^.PropType := PPTypeInfo(@Record_Temp.Buff4);
{$ENDIF}
end;
end;
tkClass:
begin
R := ClassFactory.FindRecordByFullName(String(RI.FullName));
if R = nil then
RaiseError(errInternalError, []);
ClassTypeInfoContainer := RI as
TClassTypeInfoContainer;
ClassTypeDataContainer := RI.TypeDataContainer as
TClassTypeDataContainer;
// R.VMTPtr^.DynamicTable := Prog.MessageList.CreateDmtTable(ExtractName(RI.FullName),
// R.DmtTableSize);
ClassRec := Prog.ClassList.Lookup(String(RI.FullName));
if ClassRec <> nil then
begin
if ClassRec.IntfList.Count > 0 then
begin
R.IntfTableSize := ClassRec.GetIntfTableSize;
vmtIntfTableSlot(R.VMTPtr)^ := AllocMem(R.IntfTableSize);
with PInterfaceTable(vmtIntfTableSlot(R.VMTPtr)^)^ do
begin
EntryCount := ClassRec.IntfList.Count;
for J := 0 to EntryCount - 1 do
begin
{$IFDEF FPC}
Entries[J].IID := @ ClassRec.IntfList[J].GUID;
{$ELSE}
Entries[J].IID := ClassRec.IntfList[J].GUID;
{$ENDIF}
Entries[J].VTable := ClassRec.IntfList[J].Buff;
Entries[J].IOffset := ClassRec.GetIntfOffset(ClassRec.IntfList[J].GUID);
end;
end;
end;
end;
if ClassTypeDataContainer.FieldTableCount > 0 then
begin
if R.FieldClassTable = nil then
R.FieldClassTable :=
CreateFieldClassTable(ClassTypeDataContainer.FieldTableCount);
if R.FieldTableSize = 0 then
begin
R.FieldTableSize := ClassTypeDataContainer.FieldTableSize;
vmtFieldTableSlot(R.VMTPtr)^ := AllocMem(R.FieldTableSize);
end;
FieldListContainer :=
ClassTypeDataContainer.FieldListContainer;
PVmtFieldTable(vmtFieldTableSlot(R.VMTPtr)^)^.Count :=
FieldListContainer.Count;
{$IFDEF ARC}
P := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word));
Pointer(P^) := R.FieldClassTable;
PField := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word) + SizeOf(Pointer));
{$ELSE}
{$IFDEF PAX64}
P := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word));
Pointer(P^) := R.FieldClassTable;
PField := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word) + SizeOf(Pointer));
{$ELSE}
{$ifdef WIN32}
P := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word));
Pointer(P^) := R.FieldClassTable;
PField := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word) + SizeOf(Pointer));
{$else}
PField := ShiftPointer(vmtFieldTableSlot(R.VMTPtr)^,
SizeOf(Word) + SizeOf(Word));
{$endif}
{$ENDIF}
{$ENDIF}
for J := 0 to FieldListContainer.Count - 1 do
begin
// set up PField
PField^.Name := FieldListContainer[J].Name;
PField^.Offset := FieldListContainer[J].Offset;
PField^.ClassIndex := J;
ClassRec := Prog.ClassList.Lookup(FieldListContainer[J].FullFieldTypeName);
if ClassRec <> nil then
begin
if ClassRec.Host then
{$IFDEF FPC}
R.FieldClassTable^.Classes[J] := ClassRec.PClass;
{$ELSE}
R.FieldClassTable^.Classes[J] := @ ClassRec.PClass;
{$ENDIF}
end;
PField := ShiftPointer(PField, GetFieldSize(PField));
end;
end;
vmtTypeInfoSlot(R.VMTPtr)^ := pti;
{$IFDEF FPC}
C := TClass(R.VMTPtr);
{$ELSE}
C := vmtSelfPtrSlot(R.VMTPtr)^;
{$ENDIF}
ptd := ShiftPointer(pti, RI.PosTypeData);
ptd^.ClassType := C;
pti_parent := nil;
C := C.ClassParent;
if IsPaxClass(C) then
begin
Record_Parent := LookupFullName(ClassTypeDataContainer.FullParentName);
if Record_Parent <> nil then
if not Record_Parent.Processed then
continue;
if Record_Parent = nil then
begin
ClassRec := Prog.ClassList.Lookup(ClassTypeDataContainer.FullParentName);
if ClassRec = nil then
RaiseError(errInternalError, []);
pti_parent := C.ClassInfo;
end
else
pti_parent := Record_Parent.buff4;
end
else
begin
if Assigned(C) then
pti_parent := C.ClassInfo;
end;
RI.Processed := true;
R.pti_parent := pti_parent;
{$IFDEF FPC}
ptd^.ParentInfo := R.pti_parent;
{$ELSE}
ptd^.ParentInfo := @ R.pti_parent;
{$ENDIF}
ptd^.PropCount := RI.TypeDataContainer.TypeData.PropCount;
ptd^.UnitName := RI.TypeDataContainer.TypeData.UnitName;
Z := RI.TypeDataContainer.TypeDataSize +
SizeOf(TPropData);
PropDataContainer :=
TClassTypeDataContainer(RI.TypeDataContainer).PropDataContainer;
if pti_parent <> nil then
ParentPropCount := GetTypeData(pti_parent)^.PropCount
else
ParentPropCount := 0;
Inc(ptd^.PropCount, ParentPropCount);
for J := 0 to PropDataContainer.Count - 1 do
begin
ZZ := 0;
if J > 0 then
for JJ := 0 to J - 1 do
Inc(ZZ, PropInfoSize(PropDataContainer.PropList[JJ]));
ppi := ShiftPointer(ptd, Z + ZZ);
ppi^.NameIndex := J + ParentPropCount;
Record_Temp := LookupFullName(PropDataContainer.PropTypeNames[J]);
if Record_Temp = nil then
begin
// ClassRec := Prog.ClassList.Lookup(String(ClassTypeDataContainer.FullParentName));
ClassRec := Prog.ClassList.Lookup(PropDataContainer.PropTypeNames[J]);
if ClassRec = nil then
RaiseError(errInternalError, []);
ClassRec.PClass_pti := ClassRec.PClass.ClassInfo;
{$IFDEF FPC}
ppi^.PropType := ClassRec.PClass_pti;
{$ELSE}
ppi^.PropType := @ ClassRec.PClass_pti;
{$ENDIF}
end
else
{$IFDEF FPC}
ppi^.PropType := Record_Temp.Buff4;
{$ELSE}
ppi^.PropType := PPTypeInfo(@Record_Temp.Buff4);
{$ENDIF}
FullName := PropDataContainer.ReadNames[J];
if Length(FullName) > 0 then
begin
DestProg := Prog;
ppi^.GetProc := Prog.GetAddress(FullName, MR);
if ppi^.GetProc = nil then
begin
FileName := ExtractOwner(FullName) + '.' + PCU_FILE_EXT;
ProcName := Copy(FullName, PosCh('.', FullName) + 1, Length(FullName));
ppi^.GetProc := Prog.LoadAddressEx(FileName, ProcName, false, 0, SomeMR, DestProg);
end;
TBaseRunner(DestProg).WrapMethodAddress(ppi^.GetProc);
end;
FullName := PropDataContainer.WriteNames[J];
if Length(FullName) > 0 then
begin
DestProg := Prog;
ppi^.SetProc := Prog.GetAddress(FullName, MR);
if ppi^.SetProc = nil then
begin
FileName := ExtractOwner(FullName) + '.' + PCU_FILE_EXT;
ProcName := Copy(FullName, PosCh('.', FullName) + 1, Length(FullName));
ppi^.SetProc := Prog.LoadAddressEx(FileName, ProcName, false, 0, SomeMR, DestProg);
end;
TBaseRunner(DestProg).WrapMethodAddress(ppi^.SetProc);
end;
ppi^.Index := Integer($80000000); // no index
end;
end; // tkClass
else
begin
RI.Processed := true;
end;
end; // case
end; // i-loop
until Processed;
end;
function TPaxTypeInfoList.Processed: Boolean;
var
I: Integer;
begin
result := true;
for I := 0 to Count - 1 do
if not Records[I].Processed then
begin
result := false;
Exit;
end;
end;
function TPaxTypeInfoList.FindMethodFullName(Address: Pointer): String;
var
I: Integer;
MethodTypeDataContainer: TMethodTypeDataContainer;
begin
result := '';
for I := 0 to Count - 1 do
if Records[I].TypeInfo.Kind = tkMethod then
begin
MethodTypeDataContainer := Records[I].TypeDataContainer as
TMethodTypeDataContainer;
if MethodTypeDataContainer.Address = Address then
begin
result := String(Records[I].FullName);
Exit;
end;
end;
end;
procedure TPaxTypeInfoList.RaiseError(const Message: string; params: array of Const);
begin
raise Exception.Create(Format(Message, params));
end;
function GetClassTypeInfoContainer(X: TObject): TClassTypeInfoContainer;
var
pti: PTypeInfo;
P: Pointer;
sz, StreamSize: Integer;
M: TMemoryStream;
begin
result := nil;
pti := X.ClassInfo;
if pti = nil then
Exit;
if not IsPaxObject(X) then
Exit;
P := ShiftPointer(pti, - SizeOf(Integer));
sz := Integer(p^);
P := ShiftPointer(pti, sz);
StreamSize := Integer(P^);
P := ShiftPointer(P, SizeOf(Integer)); // p points to stream
M := TMemoryStream.Create;
try
M.Write(P^, StreamSize);
M.Position := 0;
result := TClassTypeInfoContainer.Create(X.ClassName);
result.LoadFromStream(M, typeCLASS);
finally
FreeAndNil(M);
end;
end;
function GetTypeInfoContainer(pti: PTypeInfo): TTypeInfoContainer;
var
P: Pointer;
sz, StreamSize: Integer;
M: TMemoryStream;
begin
result := nil;
P := ShiftPointer(pti, - SizeOf(Integer));
sz := Integer(p^);
P := ShiftPointer(pti, sz);
StreamSize := Integer(P^);
P := ShiftPointer(P, SizeOf(Integer)); // p points to stream
M := TMemoryStream.Create;
try
M.Write(P^, StreamSize);
M.Position := 0;
// result := TTypeInfoContainer.Create;
// result.LoadFromStream(M, typeCLASS);
finally
FreeAndNil(M);
end;
end;
end.
|
unit Form.Mailtest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
Types.Mail, Log4d, Objekt.SendMail;
type
Tfrm_Mailtest = class(TForm)
PageControl1: TPageControl;
tbs_Mail: TTabSheet;
tbs_Einstellung: TTabSheet;
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Panel3: TPanel;
edt_Betreff: TEdit;
edt_An: TEdit;
edt_CC: TEdit;
edt_BCC: TEdit;
Panel4: TPanel;
mem_Body: TMemo;
btn_Senden: TButton;
Panel5: TPanel;
Panel6: TPanel;
Label192: TLabel;
Label193: TLabel;
Label5: TLabel;
lbl_MailPort: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Edt_SMTP: TEdit;
Edt_User: TEdit;
Edt_Passwort: TEdit;
Panel7: TPanel;
edt_Port: TEdit;
cbo_TLS: TComboBox;
cbo_AuthType: TComboBox;
cbo_SSLVersion: TComboBox;
edt_AbsMail: TEdit;
Label6: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure btn_SendenClick(Sender: TObject);
private
fPath: string;
fLogPath: string;
fIniFilename: string;
fDemoLog: log4d.TLogLogger;
fSendMail: TSendMail;
procedure MailSenden;
procedure MailError(Sender: TObject; aError: string);
procedure BevorConnect(Sender: TObject);
procedure AfterConnect(Sender: TObject);
procedure BevorSend(Sender: TObject);
procedure AfterSend(Sender: TObject);
public
end;
var
frm_Mailtest: Tfrm_Mailtest;
implementation
{$R *.dfm}
uses
Allgemein.RegIni;
procedure Tfrm_Mailtest.FormCreate(Sender: TObject);
var
i1: Integer;
begin
if (not FileExists(ExtractFilePath(Application.ExeName) + 'log4d.props')) then
raise Exception.Create('Log-Konfigurationsdatei (log4d.props) nicht gefunden');
TLogPropertyConfigurator.Configure(ExtractFilePath(Application.ExeName) + 'log4d.props');
fLogPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + '\LogFiles\';
if not DirectoryExists(fLogPath) then
ForceDirectories(fLogPath);
fDemoLog := TLogLogger.GetLogger('Demo');
if fDemoLog.Appenders.Count = 1 then
(fDemoLog.Appenders[0] as ILogRollingFileAppender).renameLogfile(fLogPath + 'Demo.log'); //<-- Pfad zuweisen
edt_An.Text := '';
edt_CC.Text := '';
edt_BCC.Text := '';
edt_Betreff.Text := '';
mem_Body.Clear;
fPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
fIniFilename := fPath + 'Mailtest.Ini';
cbo_TLS.Items.clear;
for i1 := 0 to c_UstTLSMax do
cbo_TLS.Items.Add(c_UseTLS[i1].Text);
cbo_AuthType.Items.Clear;
for i1 := 0 to c_AuthTypeMax do
cbo_AuthType.Items.Add(c_AuthType[i1].Text);
cbo_SSLVersion.Items.Clear;
for i1 := 0 to c_SSLVersionMax do
cbo_SSLVersion.Items.Add(c_SSLVersion[i1].Text);
fSendMail := TSendMail.Create;
fSendMail.OnMailError := MailError;
fSendMail.OnBevorConnect := BevorConnect;
fSendMail.OnAfterConnect := AfterConnect;
fSendMail.OnBevorSend := BevorSend;
fSendMail.OnAfterSend := AfterSend;
end;
procedure Tfrm_Mailtest.FormDestroy(Sender: TObject);
begin
FreeAndNil(fSendMail);
end;
procedure Tfrm_Mailtest.FormShow(Sender: TObject);
begin
edt_An.Text := ReadIni(fIniFilename, 'Mail', 'An', '');
edt_CC.Text := ReadIni(fIniFilename, 'Mail', 'CC', '');
edt_BCC.Text := ReadIni(fIniFilename, 'Mail', 'BCC', '');
edt_Betreff.Text := ReadIni(fIniFilename, 'Mail', 'Betreff', '');
mem_Body.Text := ReadIni(fIniFilename, 'Mail', 'Body', '');
edt_SMTP.Text := ReadIni(fIniFilename, 'MailEinstellung', 'SMTP', '');
edt_User.Text := ReadIni(fIniFilename, 'MailEinstellung', 'User', '');
edt_Port.Text := ReadIni(fIniFilename, 'MailEinstellung', 'Port', '');
edt_Passwort.Text := ReadIni(fIniFilename, 'MailEinstellung', 'Passwort', '');
edt_AbsMail.Text := ReadIni(fIniFilename, 'MailEinstellung', 'AbsenderMail', '');
cbo_TLS.ItemIndex := StrToInt(ReadIni(fIniFilename, 'MailEinstellung', 'TLS', '-1'));
cbo_AuthType.ItemIndex := StrToInt(ReadIni(fIniFilename, 'MailEinstellung', 'AuthType', '-1'));
cbo_SSLVersion.ItemIndex := StrToInt(ReadIni(fIniFilename, 'MailEinstellung', 'SSLVersion', '-1'));
end;
procedure Tfrm_Mailtest.AfterConnect(Sender: TObject);
begin
fDemoLog.Info('AfterConnect');
end;
procedure Tfrm_Mailtest.AfterSend(Sender: TObject);
begin
fDemoLog.Info('AfterSend');
end;
procedure Tfrm_Mailtest.BevorConnect(Sender: TObject);
begin
fDemoLog.Info('BevorConnect');
end;
procedure Tfrm_Mailtest.BevorSend(Sender: TObject);
begin
fDemoLog.Info('BevorSend');
end;
procedure Tfrm_Mailtest.btn_SendenClick(Sender: TObject);
begin
MailSenden;
end;
procedure Tfrm_Mailtest.FormClose(Sender: TObject; var Action: TCloseAction);
begin
WriteIni(fIniFilename, 'Mail', 'An', edt_An.Text);
WriteIni(fIniFilename, 'Mail', 'CC', edt_CC.Text);
WriteIni(fIniFilename, 'Mail', 'BCC', edt_BCC.Text);
WriteIni(fIniFilename, 'Mail', 'Betreff', edt_Betreff.Text);
WriteIni(fIniFilename, 'Mail', 'Body', mem_Body.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'AbsenderMail', edt_AbsMail.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'SMTP', edt_SMTP.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'User', edt_User.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'Port', edt_Port.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'Passwort', edt_Passwort.Text);
WriteIni(fIniFilename, 'MailEinstellung', 'TLS', IntToStr(cbo_TLS.ItemIndex));
WriteIni(fIniFilename, 'MailEinstellung', 'AuthType', IntToStr(cbo_AuthType.ItemIndex));
WriteIni(fIniFilename, 'MailEinstellung', 'SSLVersion', IntToStr(cbo_SSLVersion.ItemIndex));
end;
procedure Tfrm_Mailtest.MailError(Sender: TObject; aError: string);
begin
fDemoLog.Info(aError);
MessageDlg(aError, mtError, [mbOk], 0);
end;
procedure Tfrm_Mailtest.MailSenden;
begin
fSendMail.MeineEMail := edt_AbsMail.Text;
fSendMail.MeinUsername := Edt_User.Text;
fSendMail.MeinPasswort := edt_Passwort.Text;
fSendMail.MeineEMail := edt_AbsMail.Text;
fSendMail.Betreff := edt_Betreff.Text;
fSendMail.Nachricht := mem_Body.Text;
fSendMail.Host := edt_SMTP.Text;
fSendMail.EMailAdresse := edt_An.Text;
fSendMail.Port := StrToInt(Trim(edt_Port.Text));
fSendMail.UseTLS := cbo_TLS.ItemIndex;
fSendMail.AuthType := cbo_AuthType.ItemIndex;
fSendMail.SSLVersion := cbo_SSLVersion.ItemIndex;
fSendMail.Senden;
end;
end.
|
unit MainRunLib;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, PerlRegEx,Tools,ADODB,Uni, ExtCtrls,ErrorLogsUnit;
type
TMainView = class(TForm)
TimerInit: TTimer;
mmoLogs: TMemo;
procedure TimerInitTimer(Sender: TObject);
procedure RunTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function getStrFromExp(source:string):string; //解析字符串,替换变量
procedure InitTask(Task:TTask);
function checkSqlTyep(sql:string):Boolean;//true,sql语句执行上一步中查询记录数次,false,执行1次
function checkSqlSelect(sql:string):Boolean;//true ,sql语句是查询语句,false,sql语句是update、insert、delete语句。
procedure addLogs(Log:string);
procedure getFile(data:TDataSource); //获取到数据库文件
function RandomStr(): string; //随机数
end;
var
MainView: TMainView;
Datas:TSourceArr;
Tasks:TTaskArr;
implementation
{$R *.dfm}
function TMainView.RandomStr(): string;
var
PicName: string;
I: Integer;
begin
Randomize;
for I := 1 to 4 do
PicName := PicName + chr(97 + random(26));
RandomStr := PicName;
end;
procedure TMainView.addLogs(Log:string);
begin
mmoLogs.Lines.Add(Log);
ErrorLogsUnit.addErrors(Log);
end;
function TMainView.checkSqlSelect(sql:string):Boolean;//true ,sql语句是查询语句,false,sql语句是update、insert、delete语句。
begin
if Pos('select',sql) = 0 then Result := False
else Result := True;
end;
function TMainView.checkSqlTyep(sql:string):Boolean;//true,sql语句执行上一步中查询记录数次,false,执行1次
var
RegEx : TPerlRegEx;
begin
RegEx := TPerlRegEx.Create(Application);
RegEx.RegEx := '.+:\w+';
RegEx.Subject := sql;
Result := RegEx.Match;
RegEx.Free;
end;
procedure TMainView.getFile(data:TDataSource); //获取到数据库文件
var
sr:TSearchRec;
Path,Files,NewFile,Tmep : string;
RegEx:TPerlRegEx;
begin
//获取文件开始
Path := getStrFromExp(data.Server);
if Pos('^_^',data.DataBase) = 0 then
begin
if SysUtils.FindFirst(Path + '\*.*', faAnyFile, sr) = 0 then
begin
RegEx := TPerlRegEx.Create(Application);
RegEx.RegEx := getStrFromExp(data.DataBase);
repeat
if (sr.Name<>'.') and (sr.Name<>'..') then
begin
RegEx.Subject := sr.Name;
if RegEx.Match then
begin
Files := Path + '\' + sr.Name;
end;
end;
until SysUtils.FindNext(sr) <> 0;
RegEx.Free;
SysUtils.FindClose(sr);
end;
end
else
begin
Tmep := Copy(data.DataBase,1,Length(data.DataBase)-3);
Files := Path + '\' + Tmep;
end;
//获取文件结束
if Files = '' then
begin
addLogs('数据源'+data.DataName + '对应的数据库文件('+data.Server +'/' + data.DataBase +')不存在!');
Exit;
end
else
begin
addLogs('数据源'+data.DataName + '对应的数据库文件是:'+Files);
data.FileName := RandomStr;
NewFile := ExtractFileDir(PARAMSTR(0))+'\'+data.FileName+'.b';
if CopyFile(PChar(Files),PChar(NewFile),False) then
begin
addLogs('数据源'+data.DataName + '复制为:'+NewFile);
end
else
begin
addLogs('数据源'+data.DataName + '复制错误:'+NewFile);
end;
data.FileName := ExtractFileDir(PARAMSTR(0))+'\'+data.FileName+'.ldb';
end;
//初始化连接开始
try
data.Connection.Database := NewFile;
data.Connection.Open;
addLogs('数据源'+data.DataName + '对应的文件打开了...');
except
addLogs('数据源'+data.DataName + '对应的文件打开失败...' + SysErrorMessage(GetLastError));
end;
//初始化连接结束
end;
function TMainView.getStrFromExp(source:string):string; //解析字符串,替换变量
var
RegEx,RegEx1:TPerlRegEx;
begin
RegEx := TPerlRegEx.Create(Application);
RegEx.RegEx := '\${[^}${]*}';
RegEx.Subject := source;
RegEx1 := TPerlRegEx.Create(Application);
RegEx1.RegEx := '[^\${}]*';
while RegEx.MatchAgain do
begin
RegEx1.Subject := RegEx.MatchedExpression;;
if RegEx1.Match then
begin
RegEx.Replacement := FormatDateTime(RegEx1.MatchedExpression, now);
RegEx.Replace;
end;
end;
Result := RegEx.Subject;
RegEx.Free;
RegEx1.Free;
end;
procedure TMainView.InitTask(Task:TTask);
begin
Task.Timer := TTimer.Create(Application);
Task.Timer.Enabled := False;
Task.Timer.Interval := Task.time * 1000;
Task.Timer.Name := Task.name;
Task.Timer.OnTimer := RunTimer;
addLogs(Task.name + '启动完毕,执行周期' + InttoStr(Task.time) + '秒');
Task.Timer.Enabled := True;
end;
procedure TMainView.RunTimer(Sender: TObject);
var
Task : TTask;
Data : TDataSource;
I,K,J,Index :Integer;
sql : string;
StringArr :TStringArr;
Query:TUniQuery;
begin
Task := Tasks.Items[(Sender as TTimer).Name];
if Task.isRun then Exit;
Task.isRun := True;
addLogs('开始执行'+Task.name + ',有' + InttoStr(Task.sql.Count) + '步.先检查连接是否都正常..');
for I := 0 to Task.data.Count - 1 do
begin
Data := Datas.Items[Task.data[I]];
if not Data.Connection.Connected then
begin
if (Data.DataType = 'Access') or ((Data.DataType = 'SQLite')) then
begin
getFile(Data);
end
else
begin
try
Data.Connection.Open;
except
addLogs(Data.DataName + '打开失败,本次任务跳过..' + SysErrorMessage(GetLastError));
end;
end;
end;
if not Data.Connection.Connected then
begin
if (Data.DataType = 'Access') or (Data.DataType = 'SQLite') then
begin
DeleteFile(Data.Connection.Database);
DeleteFile(Data.FileName);
end;
Task.isRun := False;
Exit;
end;
if Task.UniQueryArr.Items[Task.data[I]] = nil then
begin
Query := TUniQuery.Create(Application);
Query.Connection := Data.Connection;
Task.UniQueryArr.Add(Task.data[I],query);
end;
end;
for I := 0 to Task.sql.Count - 1 do
begin
sql := getStrFromExp(Task.sql[I]);
Data := Datas.Items[Task.data[I]];
Query := Task.UniQueryArr.Items[Task.data[I]];
addLogs('执行'+sql);
Query.Close;
Query.SQL.Clear;
Query.SQL.Add(sql);
if checkSqlTyep(sql) then //需要参数,并执行多次
begin
SetLength(Task.DataRows2,0);
for J := 0 to Length(Task.DataRows1) - 1 do
begin
for K := 0 to Query.Params.Count - 1 do
begin
Query.Params[K].Value := Task.DataRows1[J].Items[Query.Params[K].Name];
end;
addLogs(Task.name + '第' + InttoStr(I+1) + '步第'+InttoStr(J+1)+'次设置了'+InttoStr(K+1)+'个参数');
//执行
if checkSqlSelect(sql) then //select
begin
try
Query.Open;
Query.First;
addLogs(Task.name + '第' + InttoStr(I+1) + '步查询完毕!');
except
addLogs(Task.name + '第' + InttoStr(I+1) + '步查询失败:'+SysErrorMessage(GetLastError));
end;
index := 0;
while not Query.Eof do
begin
Inc(Index);
StringArr := TStringArr.Create;
for K := 0 to Query.Fields.Count - 1 do
begin
StringArr.Add(Query.Fields[K].FullName,Query.Fields[K].AsString);
end;
SetLength(Task.DataRows2,Length(Task.DataRows2)+1);
Task.DataRows2[Length(Task.DataRows2) - 1] := StringArr;
Query.Next;
end;
addLogs(Task.name + '第' + InttoStr(I+1) + '步第'+InttoStr(J+1)+'次查询'+InttoStr(Index) + '条记录');
Query.Close;
end
else
begin
try
Query.ExecSQL;
addLogs(Task.name + '第' + InttoStr(I+1) + '步执行第'+InttoStr(J+1)+'次完毕!');
except
addLogs(Task.name + '第' + InttoStr(I+1) + '步执行第'+InttoStr(J+1)+'次发生异常:'+SysErrorMessage(GetLastError));
end;
end;
end;
SetLength(Task.DataRows1,0);
Task.DataRows1 := Task.DataRows2;
end
else
begin
if checkSqlSelect(sql) then //查询,
begin
try
Query.Open;
Query.First;
addLogs(Task.name + '第' + InttoStr(I+1) + '步查询完毕!');
except
addLogs(Task.name + '第' + InttoStr(I+1) + '步查询失败:'+SysErrorMessage(GetLastError));
end;
SetLength(Task.DataRows2,0);
Index := 0;
while not Query.Eof do
begin
Inc(Index);
StringArr := TStringArr.Create;
for K := 0 to Query.Fields.Count - 1 do
begin
StringArr.Add(Query.Fields[K].FullName,Query.Fields[K].AsString);
end;
SetLength(Task.DataRows2,Length(Task.DataRows2)+1);
Task.DataRows2[Length(Task.DataRows2) - 1] := StringArr;
Query.Next;
end;
addLogs(Task.name + '第' + InttoStr(I+1) + '步查询'+InttoStr(Index) + '条记录');
SetLength(Task.DataRows1,0);
Task.DataRows1 := Task.DataRows2;
end
else
begin
try
Query.ExecSQL;
addLogs(Task.name + '第' + InttoStr(I+1) + '步执行完毕!');
except
addLogs(Task.name + '第' + InttoStr(I+1) + '步执行发生异常:'+SysErrorMessage(GetLastError));
end;
end;
end;
if (Data.DataType = 'Access') or (Data.DataType = 'SQLite') then
begin
if Data.Connection.Connected then Data.Connection.Close;
DeleteFile(Data.Connection.Database);
DeleteFile(Data.FileName);
end;
end;
Task.isRun := False;
end;
procedure TMainView.TimerInitTimer(Sender: TObject);
var
I,Errors:Integer;
sr:TSearchRec;
begin
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil);
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\task') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\task'), nil);
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\data') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\data'), nil);
if SysUtils.FindFirst(ExtractFileDir(PARAMSTR(0)) + '\*.b', faAnyFile, sr) = 0 then
begin
repeat
if (sr.Name<>'.') and (sr.Name<>'..') then
begin
DeleteFile(ExtractFileDir(PARAMSTR(0)) + '\'+sr.Name);
end;
until SysUtils.FindNext(sr) <> 0;
SysUtils.FindClose(sr);
end;
if SysUtils.FindFirst(ExtractFileDir(PARAMSTR(0)) + '\*.ldb', faAnyFile, sr) = 0 then
begin
repeat
if (sr.Name<>'.') and (sr.Name<>'..') then
begin
DeleteFile(ExtractFileDir(PARAMSTR(0)) + '\'+sr.Name);
end;
until SysUtils.FindNext(sr) <> 0;
SysUtils.FindClose(sr);
end;
TimerInit.Enabled := False;
Errors := 0;
Datas := Tools.initData(Application);
addLogs('加载了' + IntToStr(Datas.Count) + '个数据源,准备打开中...');
for I := 0 to Datas.Count - 1 do
begin
try
if (Datas.Values[I].DataType <> 'Access') and ((Datas.Values[I].DataType <> 'SQLite')) then
begin
Datas.Values[I].Connection.Open;
addLogs(Datas.Keys[I] + '打开了..');
end;
except
addLogs(Datas.Keys[I] + '打开失败!');
Inc(Errors);
end;
end;
if Errors > 0 then
begin
Exit;
end;
Tasks := Tools.getTasks;
addLogs('加载了' + IntToStr(Tasks.Count) + '个任务,准备初始化...');
for I := 0 to Tasks.Count - 1 do
begin
InitTask(Tasks.Values[I]);
end;
end;
end.
|
{*
调用:
Uses CnBase64;
CnBase64.Base64Encode(Edit1.Text, Psw64);
*}
Unit CnBase64;
Interface
Uses
SysUtils, Windows;
Function Base64Encode_EX(InputData: String): String;
Function Base64Encode(InputData: String; Var OutputData: String): byte;
{* 对数据进行BASE64编码,如编码成功返回Base64_OK
|<PRE>
InputData:string - 要编码的数据
var OutputData: string - 编码后的数据
|</PRE>}
Function Base64Decode(InputData: String; Var OutputData: String): byte;
{* 对数据进行BASE64解码,如解码成功返回Base64_OK
|<PRE>
InputData:string - 要解码的数据
var OutputData: string - 解码后的数据
|</PRE>}
Const
BASE64_OK = 0; // 转换成功
BASE64_ERROR = 1;
// 转换错误(未知错误) (e.g. can't encode octet in input stream) -> error in implementation
BASE64_INVALID = 2;
// 输入的字符串中有非法字符 (在 FilterDecodeInput=False 时可能出现)
BASE64_LENGTH = 3; // 数据长度非法
BASE64_DATALEFT = 4;
// too much input data left (receveived 'end of encoded data' but not end of input string)
BASE64_PADDING = 5; // 输入的数据未能以正确的填充字符结束
Implementation
Var
FilterDecodeInput: Boolean = true;
Const
Base64TableLength = 64;
Base64Table : String[Base64TableLength] =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+*';
Pad = '=';
Function Base64Encode_EX(InputData: String): String;
var
OutputData: string;
Begin
Result := '';
if Trim(InputData) = '' then exit;
Base64Encode(InputData, OutputData);
Result := OutputData;
End;
Function Base64Encode(InputData: String; Var OutputData: String): byte;
Var
i : integer;
CurrentB, PrevB : byte;
c : byte;
s : char;
InputLength : integer;
Function ValueToCharacter(value: byte; Var character: char): Boolean;
//******************************************************************
// 将一个在0..Base64TableLength-1区间内的值,转换为与Base64编码相对应
// 的字符来表示,如果转换成功则返回True
//******************************************************************
Begin
result := true;
If (value > Base64TableLength - 1) Then
result := false
Else
character := Base64Table[value + 1];
End;
Begin
OutputData := '';
InputLength := Length(InputData);
i := 1;
If (InputLength = 0) Then Begin
result := BASE64_OK;
Exit;
End;
Repeat
// 第一次转换
CurrentB := Ord(InputData[i]);
i := i + 1;
InputLength := InputLength - 1;
c := (CurrentB Shr 2);
If Not ValueToCharacter(c, s) Then Begin
result := BASE64_ERROR;
Exit;
End;
OutputData := OutputData + s;
PrevB := CurrentB;
// 第二次转换
If InputLength = 0 Then
CurrentB := 0
Else Begin
CurrentB := Ord(InputData[i]);
i := i + 1;
End;
InputLength := InputLength - 1;
c := (PrevB And $03) Shl 4 + (CurrentB Shr 4);
//取出XX后4位并将其左移4位与XX右移4位合并成六位
If Not ValueToCharacter(c, s) Then
{//检测取得的字符是否在Base64Table内} Begin
result := BASE64_ERROR;
Exit;
End;
OutputData := OutputData + s;
PrevB := CurrentB;
// 第三次转换
If InputLength < 0 Then
s := Pad
Else Begin
If InputLength = 0 Then
CurrentB := 0
Else Begin
CurrentB := Ord(InputData[i]);
i := i + 1;
End;
InputLength := InputLength - 1;
c := (PrevB And $0F) Shl 2 + (CurrentB Shr 6);
//取出XX后4位并将其左移2位与XX右移6位合并成六位
If Not ValueToCharacter(c, s) Then
{//检测取得的字符是否在Base64Table内} Begin
result := BASE64_ERROR;
Exit;
End;
End;
OutputData := OutputData + s;
// 第四次转换
If InputLength < 0 Then
s := Pad
Else Begin
c := (CurrentB And $3F); //取出XX后6位
If Not ValueToCharacter(c, s) Then
{//检测取得的字符是否在Base64Table内} Begin
result := BASE64_ERROR;
Exit;
End;
End;
OutputData := OutputData + s;
Until InputLength <= 0;
result := BASE64_OK;
End;
Function Base64Decode(InputData: String; Var OutputData: String): byte;
Var
i : integer;
InputLength : integer;
CurrentB, PrevB : byte;
c : byte;
s : char;
Function CharacterToValue(character: char; Var value: byte): Boolean;
//******************************************************************
// 转换字符为一在0..Base64TableLength-1区间中的值,如果转换成功则返
// 回True(即字符在Base64Table中)
//******************************************************************
Begin
result := true;
value := Pos(character, Base64Table);
If value = 0 Then
result := false
Else
value := value - 1;
End;
Function FilterLine(InputData: String): String;
//******************************************************************
// 过滤所有不在Base64Table中的字符,返回值为过滤后的字符
//******************************************************************
Var
F : byte;
i : integer;
Begin
result := '';
For i := 1 To Length(InputData) Do
If CharacterToValue(InputData[i], F) Or (InputData[i] = Pad) Then
result := result + InputData[i];
End;
Begin
If (InputData = '') Then Begin
result := BASE64_OK;
Exit;
End;
OutputData := '';
If FilterDecodeInput Then
InputData := FilterLine(InputData);
InputLength := Length(InputData);
If InputLength Mod 4 <> 0 Then Begin
result := BASE64_LENGTH;
Exit;
End;
i := 0;
Repeat
// 第一次转换
i := i + 1;
s := InputData[i];
If Not CharacterToValue(s, CurrentB) Then Begin
result := BASE64_INVALID;
Exit;
End;
i := i + 1;
s := InputData[i];
If Not CharacterToValue(s, PrevB) Then Begin
result := BASE64_INVALID;
Exit;
End;
c := (CurrentB Shl 2) + (PrevB Shr 4);
OutputData := OutputData + Chr(c);
// 第二次转换
i := i + 1;
s := InputData[i];
If s = Pad Then Begin
If (i <> InputLength - 1) Then Begin
result := BASE64_DATALEFT;
Exit;
End
Else
If InputData[i + 1] <> Pad Then Begin
result := BASE64_PADDING;
Exit;
End;
End
Else Begin
If Not CharacterToValue(s, CurrentB) Then Begin
result := BASE64_INVALID;
Exit;
End;
c := (PrevB Shl 4) + (CurrentB Shr 2);
OutputData := OutputData + Chr(c);
End;
// 第三次转换
i := i + 1;
s := InputData[i];
If s = Pad Then Begin
If (i <> InputLength) Then Begin
result := BASE64_DATALEFT;
Exit;
End;
End
Else Begin
If Not CharacterToValue(s, PrevB) Then Begin
result := BASE64_INVALID;
Exit;
End;
c := (CurrentB Shl 6) + (PrevB);
OutputData := OutputData + Chr(c);
End;
Until (i >= InputLength);
result := BASE64_OK;
End;
End.
|
//------------------------------------------------------------------------------
//CharacterQueries UNIT
//------------------------------------------------------------------------------
// What it does-
// Character related database routines
//
// Changes -
// February 12th, 2008
//
//------------------------------------------------------------------------------
unit CharacterQueries;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
Account,
Character,
QueryBase,
BeingList,
{3rd Party}
ZSqlUpdate
;
type
//------------------------------------------------------------------------------
//TCharacterQueries CLASS
//------------------------------------------------------------------------------
TCharacterQueries = class(TQueryBase)
protected
public
Function Exists(
const ACharacter : TCharacter
) : Boolean;
Procedure Load(
const ACharacter : TCharacter
);
Function GetName(
const ACharacterID : LongWord
) : String;
Procedure LoadByAccount(
const ACharacterList : TBeingList;
const AnAccount : TAccount
);
Procedure Save(
const ACharacter : TCharacter
);
Procedure New(
const ACharacter : TCharacter
);
Procedure Delete(
const ACharacter : TCharacter
);
function GetVariable(
const ACharacter : TCharacter;
const Key : string;
var AType : Byte
) : string;
procedure SetVariable(
const ACharacter : TCharacter;
const Key : string;
const Value : string;
AType : Byte
);
procedure Rename(
const AccountID : LongWord;
const CharID : LongWord;
const NewName : String
);
function GenerateStorageID:LongWord;
function CreateInventory:LongWord;
function CreateStorage:LongWord;
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
Types,
Math,
{Project}
GameConstants,
ItemTypes,
{3rd Party}
ZDataset,
DB
//none
;
//------------------------------------------------------------------------------
//Load PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Loads an Character
//
// Changes -
// February 12th, 2008 - RaX - Created.
// [2008/09/19] Aeomin - Added left join
// September 29th 2008 - Tsusai - Corrected InventoryID spelling error.
//
//------------------------------------------------------------------------------
Procedure TCharacterQueries.Load(
const ACharacter : TCharacter
);
const
AQuery =
'SELECT characters.id, `account_id`, `name`, `slot`, `job_id`, `base_level`, `job_level`, `base_exp`, '+
'`job_exp`, `zeny`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `status_points`, `skill_points`, '+
'`current_hp`, `current_sp`, `hair_style`, `hair_color`, `clothes_color`, `option`, `inventory_id`, '+
'`storage_id`, `cart_inventory_id`, `righthand_item`, `lefthand_item`, `armor_item`, '+
'`garment_item`, `shoes_item`, `accessory1_item`, `accessory2_item`, `head_top_item`, '+
'`head_middle_item`, `head_bottom_item`, `last_map`, `last_map_x`, `last_map_y`, '+
'`save_map`, `save_map_x`, `save_map_y`, `partner_id`, `parent1_id`, `parent2_id`, '+
'`party_id`, `guild_id`, `is_online`, '+
'inventory.item_storage_use_id, inventory.item_storage_equip_id, inventory.item_storage_etc_id, '+
'itemstorage.items_id,itemstorage.count_capacity,itemstorage.weight_capacity '+
'FROM characters LEFT JOIN inventory ON (characters.inventory_id=inventory.id) LEFT JOIN itemstorage ON (characters.storage_id=itemstorage.id) ';
var
WhereClause : String;
ADataSet : TZQuery;
AParam : TParam;
APoint : TPoint;
begin
if ACharacter.ID > 0 then
begin
WhereClause := ' WHERE characters.id=:ID;';
end else
begin
WhereClause := ' WHERE name=:Name;'
end;
ADataSet := TZQuery.Create(nil);
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := ACharacter.Name;
ADataSet.Params.AddParam(
AParam
);
//
try
Query(ADataSet, AQuery+WhereClause);
ADataSet.First;
if NOT ADataSet.Eof then
begin
//fill character data
with ACharacter do
begin
ID := ADataSet.Fields[0].AsInteger;
AccountID := ADataSet.Fields[1].AsInteger;
Name := ADataSet.Fields[2].AsString;
CharaNum := ADataSet.Fields[3].AsInteger;
JID := ADataSet.Fields[4].AsInteger;
BaseLV := ADataSet.Fields[5].AsInteger;
JobLV := ADataSet.Fields[6].AsInteger;
BaseEXP := ADataSet.Fields[7].AsInteger;
JobEXP := ADataSet.Fields[8].AsInteger;
Zeny := ADataSet.Fields[9].AsInteger;
ParamBase[STR] := ADataSet.Fields[10].AsInteger;
ParamBase[AGI] := ADataSet.Fields[11].AsInteger;
ParamBase[VIT] := ADataSet.Fields[12].AsInteger;
ParamBase[INT] := ADataSet.Fields[13].AsInteger;
ParamBase[DEX] := ADataSet.Fields[14].AsInteger;
ParamBase[LUK] := ADataSet.Fields[15].AsInteger;
StatusPts := ADataSet.Fields[16].AsInteger;
SkillPts := ADataSet.Fields[17].AsInteger;
HP := ADataSet.Fields[18].AsInteger;
SP := ADataSet.Fields[19].AsInteger;
Hair := ADataSet.Fields[20].AsInteger;
HairColor := ADataSet.Fields[21].AsInteger;
ClothesColor := ADataSet.Fields[22].AsInteger;
Option := ADataSet.Fields[23].AsInteger;
Inventory.InventoryID := ADataSet.Fields[24].AsInteger;
Inventory.StorageID := ADataSet.Fields[25].AsInteger;
//CartInventoryID := ADataSet.Fields[26].AsInteger;
Equipment.EquipmentID[RIGHTHAND]:= ADataSet.Fields[27].AsInteger;
Equipment.EquipmentID[LEFTHAND] := ADataSet.Fields[28].AsInteger;
Equipment.EquipmentID[BODY] := ADataSet.Fields[29].AsInteger;
Equipment.EquipmentID[CAPE] := ADataSet.Fields[30].AsInteger;
Equipment.EquipmentID[FEET] := ADataSet.Fields[31].AsInteger;
Equipment.EquipmentID[ACCESSORY1] := ADataSet.Fields[32].AsInteger;
Equipment.EquipmentID[ACCESSORY2] := ADataSet.Fields[33].AsInteger;
Equipment.EquipmentID[HEADUPPER] := ADataSet.Fields[34].AsInteger;
Equipment.EquipmentID[HEADMID] := ADataSet.Fields[35].AsInteger;
Equipment.EquipmentID[HEADLOWER] := ADataSet.Fields[36].AsInteger;
Map := ADataSet.Fields[37].AsString;
APoint.X := ADataSet.Fields[38].AsInteger;
APoint.Y := ADataSet.Fields[39].AsInteger;
Position := APoint;
SaveMap := ADataSet.Fields[40].AsString;
APoint.X := ADataSet.Fields[41].AsInteger;
APoint.Y := ADataSet.Fields[42].AsInteger;
SavePoint := APoint;
PartnerID := ADataSet.Fields[43].AsInteger;
ParentID1 := ADataSet.Fields[44].AsInteger;
ParentID2 := ADataSet.Fields[45].AsInteger;
PartyID := ADataSet.Fields[46].AsInteger;
GuildID := ADataSet.Fields[47].AsInteger;
Online := ADataSet.Fields[48].AsInteger;
Inventory.UseID := ADataSet.Fields[49].AsInteger;
Inventory.EquipID:= ADataSet.Fields[50].AsInteger;
Inventory.EtcID := ADataSet.Fields[51].AsInteger;
{CalcMaxWeight;
CalcMaxHP;
CalcMaxSP;
CalcSpeed;
CalcASpeed;}
end;
end;
finally
ADataSet.Free;
end;
Inherited;
end;//Load
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetName FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Gets a character's name by it's ID
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Function TCharacterQueries.GetName(
const ACharacterID : LongWord
) : String;
const
AQuery =
'SELECT `name` FROM characters WHERE id=:ID;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacterID;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery);
ADataSet.First;
if NOT ADataSet.Eof then
begin
Result := ADataSet.Fields[0].AsString;
end;
finally
ADataSet.Free;
end;
end;//GetName
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadByAccountID PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Loads a list of characters by account id
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TCharacterQueries.LoadByAccount(
const ACharacterList : TBeingList;
const AnAccount : TAccount
);
const
AQuery =
'SELECT `id` FROM characters WHERE account_id=:AccountID;';
var
ADataSet : TZQuery;
AParam : TParam;
ACharacter : TCharacter;
begin
ADataSet := TZQuery.Create(nil);
try
//AccountID
AParam := ADataset.Params.CreateParam(ftInteger, 'AccountID', ptInput);
AParam.AsInteger := AnAccount.ID;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery);
ADataSet.First;
while NOT ADataSet.Eof do
begin
ACharacter := TCharacter.Create(AnAccount.ClientInfo);
ACharacter.ID := ADataSet.Fields[0].AsInteger;
Load(ACharacter);
ACharacterList.Add(ACharacter);
ADataSet.Next;
end;
finally
ADataSet.Free;
end;
end;//LoadByAccountID
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Exists PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Checks to see if a character exists
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Function TCharacterQueries.Exists(
const ACharacter : TCharacter
) : Boolean;
const
AQuery =
'SELECT `id` FROM characters';
var
WhereClause : String;
ADataSet : TZQuery;
AParam : TParam;
begin
Result := TRUE;
if ACharacter.ID > 0 then
begin
WhereClause := ' WHERE id=:ID';
end else
begin
WhereClause := ' WHERE name=:Name'
end;
if ACharacter.CharaNum <> 255 then
begin
WhereClause := WhereClause + ' AND Slot=:Slot;';
end else
begin
WhereClause := WhereClause + ';';
end;
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := ACharacter.Name;
ADataSet.Params.AddParam(
AParam
);
//Slot
AParam := ADataset.Params.CreateParam(ftInteger, 'Slot', ptInput);
AParam.AsInteger := ACharacter.CharaNum;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery+WhereClause);
ADataset.First;
if ADataSet.Eof then
begin
Result := FALSE;
end;
finally
ADataSet.Free;
end;
end;//Exists
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Save a character.
//
// Changes -
// February 12th, 2008 - RaX - Created.
// September 29th, 2008 - Tsusai - Changed is_online to be an integer, as
// boolean wasn't working proper with Zeos and mysql 5
// September 29th 2008 - Tsusai - Corrected InventoryID spelling error.
//
//------------------------------------------------------------------------------
procedure TCharacterQueries.Save(
const
ACharacter : TCharacter
);
const
AQuery =
'UPDATE characters SET ' +
'`slot`=:Slot, ' +
'`name`=:Name, ' +
'`job_id`=:JobID, ' +
'`base_level`=:BaseLevel, ' +
'`job_level`=:JobLevel, ' +
'`base_exp`=:BaseExp, ' +
'`job_exp`=:JobExp, ' +
'`zeny`=:Zeny, ' +
'`str`=:Str, ' +
'`agi`=:Agi, ' +
'`vit`=:Vit, ' +
'`int`=:Int, ' +
'`dex`=:Dex, ' +
'`luk`=:Luk, ' +
'`max_hp`=:MaxHP, ' +
'`current_hp`=:CurrentHP, ' +
'`max_sp`=:MaxSP, ' +
'`current_sp`=:CurrentSP, ' +
'`status_points`=:StatusPoints, ' +
'`skill_points`=:SkillPoints, ' +
'`option`=:Option, ' +
'inventory_id=:InventoryID, '+
//'storage_id=:StorageID, '+
//'cart_inventory_id=:CartInventoryID, '+
'`party_id`=:PartyID, ' +
'`guild_id`=:GuildID, ' +
'`hair_style`=:HairStyle, ' +
'`hair_color`=:HairColor, ' +
'`clothes_color`=:ClothesColor, ' +
'`righthand_item`=:RightHand, ' +
'`lefthand_item`=:LeftHand, ' +
'`armor_item`=:Armor, ' +
'`garment_item`=:Garment, ' +
'`shoes_item`=:Shoes, ' +
'`accessory1_item`=:Accessory1, ' +
'`accessory2_item`=:Accessory2, ' +
'`head_top_item`=:HeadTop, ' +
'`head_middle_item`=:HeadMiddle, ' +
'`head_bottom_item`=:HeadBottom, ' +
'`last_map`=:LastMap, ' +
'`last_map_x`=:LastMapX, ' +
'`last_map_y`=:LastMapY, ' +
'`save_map`=:SaveMap, ' +
'`save_map_x`=:SaveMapX, ' +
'`save_map_y`=:SaveMapY, ' +
'`partner_id`=:PartnerID, ' +
'`parent1_id`=:Parent1ID, ' +
'`parent2_id`=:Parent2ID, ' +
'`is_online`=:Online ' +
'WHERE id=:ID;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
//Slot
AParam := ADataset.Params.CreateParam(ftInteger, 'Slot', ptInput);
AParam.AsInteger := ACharacter.CharaNum;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := ACharacter.Name;
ADataSet.Params.AddParam(
AParam
);
//JobID
AParam := ADataset.Params.CreateParam(ftInteger, 'JobID', ptInput);
AParam.AsInteger := ACharacter.JID;
ADataSet.Params.AddParam(
AParam
);
//BaseLevel
AParam := ADataset.Params.CreateParam(ftInteger, 'BaseLevel', ptInput);
AParam.AsInteger := ACharacter.BaseLV;
ADataSet.Params.AddParam(
AParam
);
//JobLevel
AParam := ADataset.Params.CreateParam(ftInteger, 'JobLevel', ptInput);
AParam.AsInteger := ACharacter.JobLV;
ADataSet.Params.AddParam(
AParam
);
//BaseExp
AParam := ADataset.Params.CreateParam(ftInteger, 'BaseExp', ptInput);
AParam.AsInteger := ACharacter.BaseEXP;
ADataSet.Params.AddParam(
AParam
);
//JobExp
AParam := ADataset.Params.CreateParam(ftInteger, 'JobExp', ptInput);
AParam.AsInteger := ACharacter.JobEXP;
ADataSet.Params.AddParam(
AParam
);
//Zeny
AParam := ADataset.Params.CreateParam(ftInteger, 'Zeny', ptInput);
AParam.AsInteger := ACharacter.Zeny;
ADataSet.Params.AddParam(
AParam
);
//Luk
AParam := ADataset.Params.CreateParam(ftInteger, 'Luk', ptInput);
AParam.AsInteger := ACharacter.ParamBase[LUK];
ADataSet.Params.AddParam(
AParam
);
//Str
AParam := ADataset.Params.CreateParam(ftInteger, 'Str', ptInput);
AParam.AsInteger := ACharacter.ParamBase[STR];
ADataSet.Params.AddParam(
AParam
);
//Agi
AParam := ADataset.Params.CreateParam(ftInteger, 'Agi', ptInput);
AParam.AsInteger := ACharacter.ParamBase[AGI];
ADataSet.Params.AddParam(
AParam
);
//Dex
AParam := ADataset.Params.CreateParam(ftInteger, 'Dex', ptInput);
AParam.AsInteger := ACharacter.ParamBase[DEX];
ADataSet.Params.AddParam(
AParam
);
//Vit
AParam := ADataset.Params.CreateParam(ftInteger, 'Vit', ptInput);
AParam.AsInteger := ACharacter.ParamBase[VIT];
ADataSet.Params.AddParam(
AParam
);
//Int
AParam := ADataset.Params.CreateParam(ftInteger, 'Int', ptInput);
AParam.AsInteger := ACharacter.ParamBase[INT];
ADataSet.Params.AddParam(
AParam
);
//MaxHP
AParam := ADataset.Params.CreateParam(ftInteger, 'MaxHP', ptInput);
AParam.AsInteger := ACharacter.MaxHP;
ADataSet.Params.AddParam(
AParam
);
//MaxSP
AParam := ADataset.Params.CreateParam(ftInteger, 'MaxSP', ptInput);
AParam.AsInteger := ACharacter.MaxSP;
ADataSet.Params.AddParam(
AParam
);
//CurrentHP
AParam := ADataset.Params.CreateParam(ftInteger, 'CurrentHP', ptInput);
AParam.AsInteger := ACharacter.HP;
ADataSet.Params.AddParam(
AParam
);
//CurrentSP
AParam := ADataset.Params.CreateParam(ftInteger, 'CurrentSP', ptInput);
AParam.AsInteger := ACharacter.SP;
ADataSet.Params.AddParam(
AParam
);
//StatusPoints
AParam := ADataset.Params.CreateParam(ftInteger, 'StatusPoints', ptInput);
AParam.AsInteger := ACharacter.StatusPts;
ADataSet.Params.AddParam(
AParam
);
//SkillPoints
AParam := ADataset.Params.CreateParam(ftInteger, 'SkillPoints', ptInput);
AParam.AsInteger := ACharacter.SkillPts;
ADataSet.Params.AddParam(
AParam
);
//Option
AParam := ADataset.Params.CreateParam(ftInteger, 'Option', ptInput);
AParam.AsInteger := ACharacter.Option;
ADataSet.Params.AddParam(
AParam
);
//InventoryID
AParam := ADataset.Params.CreateParam(ftInteger, 'InventoryID', ptInput);
AParam.AsInteger := ACharacter.Inventory.InventoryID;
ADataSet.Params.AddParam(
AParam
);
//PartyID
AParam := ADataset.Params.CreateParam(ftInteger, 'PartyID', ptInput);
AParam.AsInteger := ACharacter.PartyID;
ADataSet.Params.AddParam(
AParam
);
//GuildID
AParam := ADataset.Params.CreateParam(ftInteger, 'GuildID', ptInput);
AParam.AsInteger := ACharacter.GuildID;
ADataSet.Params.AddParam(
AParam
);
//HairStyle
AParam := ADataset.Params.CreateParam(ftInteger, 'HairStyle', ptInput);
AParam.AsInteger := ACharacter.Hair;
ADataSet.Params.AddParam(
AParam
);
//HairColor
AParam := ADataset.Params.CreateParam(ftInteger, 'HairColor', ptInput);
AParam.AsInteger := ACharacter.HairColor;
ADataSet.Params.AddParam(
AParam
);
//ClothesColor
AParam := ADataset.Params.CreateParam(ftInteger, 'ClothesColor', ptInput);
AParam.AsInteger := ACharacter.ClothesColor;
ADataSet.Params.AddParam(
AParam
);
//RightHand
AParam := ADataset.Params.CreateParam(ftInteger, 'RightHand', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[RIGHTHAND];
ADataSet.Params.AddParam(
AParam
);
//LeftHand
AParam := ADataset.Params.CreateParam(ftInteger, 'LeftHand', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[LEFTHAND];
ADataSet.Params.AddParam(
AParam
);
//Armor
AParam := ADataset.Params.CreateParam(ftInteger, 'Armor', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[BODY];
ADataSet.Params.AddParam(
AParam
);
//Garment
AParam := ADataset.Params.CreateParam(ftInteger, 'Garment', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[CAPE];
ADataSet.Params.AddParam(
AParam
);
//Shoes
AParam := ADataset.Params.CreateParam(ftInteger, 'Shoes', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[FEET];
ADataSet.Params.AddParam(
AParam
);
//Accessory1
AParam := ADataset.Params.CreateParam(ftInteger, 'Accessory1', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[ACCESSORY1];
ADataSet.Params.AddParam(
AParam
);
//Accessory2
AParam := ADataset.Params.CreateParam(ftInteger, 'Accessory2', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[ACCESSORY2];
ADataSet.Params.AddParam(
AParam
);
//HeadTop
AParam := ADataset.Params.CreateParam(ftInteger, 'HeadTop', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[HEADUPPER];
ADataSet.Params.AddParam(
AParam
);
//HeadMiddle
AParam := ADataset.Params.CreateParam(ftInteger, 'HeadMiddle', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[HEADMID];
ADataSet.Params.AddParam(
AParam
);
//HeadBottom
AParam := ADataset.Params.CreateParam(ftInteger, 'HeadBottom', ptInput);
AParam.AsInteger := ACharacter.Equipment.EquipmentID[HEADLOWER];
ADataSet.Params.AddParam(
AParam
);
//LastMapID
AParam := ADataset.Params.CreateParam(ftString, 'LastMap', ptInput);
AParam.AsString := ACharacter.Map;
ADataSet.Params.AddParam(
AParam
);
//LastMapX
AParam := ADataset.Params.CreateParam(ftInteger, 'LastMapX', ptInput);
AParam.AsInteger := ACharacter.Position.X;
ADataSet.Params.AddParam(
AParam
);
//LastMapY
AParam := ADataset.Params.CreateParam(ftInteger, 'LastMapY', ptInput);
AParam.AsInteger := ACharacter.Position.Y;
ADataSet.Params.AddParam(
AParam
);
//SaveMapID
AParam := ADataset.Params.CreateParam(ftString, 'SaveMap', ptInput);
AParam.AsString := ACharacter.SaveMap;
ADataSet.Params.AddParam(
AParam
);
//SaveMapX
AParam := ADataset.Params.CreateParam(ftInteger, 'SaveMapX', ptInput);
AParam.AsInteger := ACharacter.SavePoint.X;
ADataSet.Params.AddParam(
AParam
);
//SaveMapY
AParam := ADataset.Params.CreateParam(ftInteger, 'SaveMapY', ptInput);
AParam.AsInteger := ACharacter.SavePoint.Y;
ADataSet.Params.AddParam(
AParam
);
//PartnerID
AParam := ADataset.Params.CreateParam(ftInteger, 'PartnerID', ptInput);
AParam.AsInteger := ACharacter.PartnerID;
ADataSet.Params.AddParam(
AParam
);
//Parent1ID
AParam := ADataset.Params.CreateParam(ftInteger, 'Parent1ID', ptInput);
AParam.AsInteger := ACharacter.ParentID1;
ADataSet.Params.AddParam(
AParam
);
//Parent2ID
AParam := ADataset.Params.CreateParam(ftInteger, 'Parent2ID', ptInput);
AParam.AsInteger := ACharacter.ParentID2;
ADataSet.Params.AddParam(
AParam
);
//Online
AParam := ADataset.Params.CreateParam(ftInteger, 'Online', ptInput);
AParam.AsInteger := (ACharacter.Online);
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//Save
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//New Procedure
//------------------------------------------------------------------------------
// What it does-
// Creates an account.
//
// Changes -
// February 12th, 2008 - RaX - Created.
// September 29th 2008 - Tsusai - Corrected InventoryID spelling error.
//
//------------------------------------------------------------------------------
procedure TCharacterQueries.New(
const
ACharacter : TCharacter
);
const
AQuery =
'INSERT INTO characters '+
'(name, slot, account_id, inventory_id) '+
'VALUES(:Name, :Slot, :AccountID, :InventoryID);';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := ACharacter.Name;
ADataSet.Params.AddParam(
AParam
);
//Slot
AParam := ADataset.Params.CreateParam(ftInteger, 'Slot', ptInput);
AParam.AsInteger := ACharacter.CharaNum;
ADataSet.Params.AddParam(
AParam
);
//AccountID
AParam := ADataset.Params.CreateParam(ftInteger, 'AccountID', ptInput);
AParam.AsInteger := ACharacter.AccountID;
ADataSet.Params.AddParam(
AParam
);
//InventoryID
AParam := ADataset.Params.CreateParam(ftInteger, 'InventoryID', ptInput);
AParam.AsInteger := ACharacter.Inventory.InventoryID;
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//New
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Delete PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Deletes a Character
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TCharacterQueries.Delete(
const ACharacter : TCharacter
);
const
AQuery =
'DELETE FROM characters WHERE id=:ID;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//Delete
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetVariable PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Set variable
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TCharacterQueries.SetVariable(
const ACharacter: TCharacter;
const Key : string;
const Value : string;
AType : Byte
);
const
UpdateVariableQuery =
'UPDATE charactervariables '+
'SET `value`=:Value, `type`=:Type '+
'WHERE character_id=:ID AND `key`=:Key;';
InsertVariableQuery =
'INSERT INTO charactervariables '+
'(`character_id`, `key`, `value`, `type`) '+
'VALUES(:ID, :Key, :Value, :Type);';
CheckVariableQuery =
'SELECT character_id FROM charactervariables WHERE '+
'character_id=:ID AND `key`=:Key;';
var
ADataSet : TZQuery;
ADataSet2 : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
ADataSet2 := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
//Key
AParam := ADataset.Params.CreateParam(ftString, 'Key', ptInput);
AParam.AsString := Key;
ADataSet.Params.AddParam(
AParam
);
//ID
AParam := ADataset2.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet2.Params.AddParam(
AParam
);
//Key
AParam := ADataset2.Params.CreateParam(ftString, 'Key', ptInput);
AParam.AsString := Key;
ADataSet2.Params.AddParam(
AParam
);
//Value
AParam := ADataset2.Params.CreateParam(ftString, 'Value', ptInput);
AParam.AsString := Value;
ADataSet2.Params.AddParam(
AParam
);
//Value
AParam := ADataset2.Params.CreateParam(ftInteger, 'Type', ptInput);
AParam.AsInteger := AType;
ADataSet2.Params.AddParam(
AParam
);
Query(ADataSet, CheckVariableQuery);
ADataset.First;
if NOT ADataSet.Eof then
begin
QueryNoResult(ADataSet2, UpdateVariableQuery);
end else
begin
QueryNoResult(ADataSet2, InsertVariableQuery);
end;
finally
ADataSet.Free;
ADataSet2.Free;
end;
end;//SetVariable
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetVariable PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Gets a variable
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Function TCharacterQueries.GetVariable(
const ACharacter: TCharacter;
const Key : string;
var AType : Byte
) : string;
const
AQuery =
'SELECT `value`, `type` FROM charactervariables WHERE character_id=:ID AND `key`=:Key;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
Result := '';
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
//Key
AParam := ADataset.Params.CreateParam(ftString, 'Key', ptInput);
AParam.AsString := Key;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery);
ADataset.First;
if NOT ADataSet.Eof then
begin
AType := ADataset.Fields[1].AsInteger;
Result := ADataset.Fields[0].AsString;
end;
finally
ADataSet.Free;
end;
end;//GetVariable
//------------------------------------------------------------------------------
procedure TCharacterQueries.Rename(
const AccountID : LongWord;
const CharID : LongWord;
const NewName : String
);
const
AQuery =
'UPDATE characters SET `name`=:Name WHERE `id`=:CID AND `account_id`=:AID;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//CID
AParam := ADataset.Params.CreateParam(ftInteger, 'CID', ptInput);
AParam.AsInteger := CharID;
ADataSet.Params.AddParam(
AParam
);
//AID
AParam := ADataset.Params.CreateParam(ftInteger, 'AID', ptInput);
AParam.AsInteger := AccountID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := NewName;
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;
//------------------------------------------------------------------------------
//GenerateStorageID PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Generate an inventory GUID, improvement needed!
//
// Changes -
// [2008/09/20] Aeomin - Created.
//
//------------------------------------------------------------------------------
function TCharacterQueries.GenerateStorageID:LongWord;
const
AQuery = 'SELECT MAX(cart_inventory_id) FROM characters UNION SELECT MAX(item_storage_etc_id) FROM inventory UNION SELECT MAX(items_id) FROM itemstorage';
var
ADataSet : TZQuery;
begin
Result := 0;
ADataSet := TZQuery.Create(nil);
try
Query(ADataSet, AQuery);
ADataSet.First;
while NOT ADataSet.Eof do
begin
Result:=Max(
EnsureRange(StrToIntDef(ADataSet.Fields[0].AsString,0),0,High(LongWord))
,Result);
ADataSet.Next;
end;
finally
ADataSet.Free;
end;
Inc(Result);
end;{GenerateStorageID}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GenerateStorageID PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Create an inventory record
//
// Changes -
// [2008/09/20] Aeomin - Created.
//
//------------------------------------------------------------------------------
function TCharacterQueries.CreateInventory:LongWord;
const
AQuery = 'INSERT INTO `inventory` (`item_storage_use_id`,`item_storage_equip_id`,`item_storage_etc_id`) VALUES '+
'(:UseID,:EquipID,:EtcID)';
var
ID : LongWord;
ADataSet : TZQuery;
AParam : TParam;
begin
ID := GenerateStorageID;
ADataSet := TZQuery.Create(nil);
//UseID
AParam := ADataset.Params.CreateParam(ftInteger, 'UseID', ptInput);
AParam.AsInteger := ID;
ADataSet.Params.AddParam(
AParam
);
//EquipID
AParam := ADataset.Params.CreateParam(ftInteger, 'EquipID', ptInput);
AParam.AsInteger := ID+1;
ADataSet.Params.AddParam(
AParam
);
//EtcID
AParam := ADataset.Params.CreateParam(ftInteger, 'EtcID', ptInput);
AParam.AsInteger := ID+2;
ADataSet.Params.AddParam(
AParam
);
try
QueryNoResult(ADataSet, AQuery);
Result := LastID(
'`id`',
'`inventory`'
);
finally
ADataSet.Free;
end;
end;{CreateInventory}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//CreateStorage PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Create a storage record
//
// Changes -
// [2008/10/04] Aeomin - Created.
//
//------------------------------------------------------------------------------
function TCharacterQueries.CreateStorage:LongWord;
const
AQuery = 'INSERT INTO `itemstorage` (`items_id`) VALUES '+
'(:StorageID)';
var
ID : LongWord;
ADataSet : TZQuery;
AParam : TParam;
begin
ID := GenerateStorageID;
ADataSet := TZQuery.Create(nil);
//StorageID
AParam := ADataset.Params.CreateParam(ftInteger, 'StorageID', ptInput);
AParam.AsInteger := ID;
ADataSet.Params.AddParam(
AParam
);
try
QueryNoResult(ADataSet, AQuery);
Result := LastID(
'`id`',
'`itemstorage`'
);
finally
ADataSet.Free;
end;
end;{CreateStorage}
//------------------------------------------------------------------------------
end.
|
//
// Title: SFExtDBCtrlReg
//
// Description: register controls
//
// Created by: Frank Huber
//
// Copyright: Frank Huber - The SoftwareFactory -
// Alberweilerstr. 1
// D-88433 Schemmerhofen
//
// http://www.thesoftwarefactory.de
//
unit SFExtDBCtrlReg;
interface
uses System.Classes, System.SysUtils;
procedure Register;
implementation
uses SFDBGrid, SFDBGridInplaceCheckBox;
procedure Register;
begin
RegisterComponents('SFFH ExtDBCtrls', [TSFDBGrid, TSFDBGridInplaceCheckBox]);
end;
end.
|
unit uFNMArtInfo;
{*|<PRE>*****************************************************************************
软件名称 FNM CLIENT MODEL
版权所有 (C) 2004-2005 ESQUEL GROUP GET/IT
单元名称 uFNMArtInfo.pas
创建日期 2004-8-30 下午 04:30:20
创建人员 lvzd
修改人员
修改日期
修改原因
对应用例
字段描述
相关数据库表
调用重要函数/SQL对象说明
1: 后整理工艺基类
2: 标准工艺类
读: PDMDB.dbo.tdGFID; uvw_fnOperationList
读,写: fnStdArtHdr; fnStdArtDtl
3: 实际工艺类
读:
4: 回修工艺类
读:
5: 手织版工艺类
功能描述: CAD工艺类,后整理工艺基类, 标准工艺, 实际工艺, 外回修工艺类,
获取工艺相关字典函数.
******************************************************************************}
interface
{$I Terminal.inc}
uses
DB, DBClient, Classes, SysUtils, StrUtils, Valedit, Grids, Menus, Windows, Forms,
ComCtrls, ServerDllPub, uFNMResource, uGlobal, uShowMessage, uDictionary, Dialogs,
Variants, StdCtrls, Controls, uLogin, uCADInfo;
Type
{TOperateOffset}
TOperateOffset=(ooMoveDown= -1, ooDelete = 0, ooMoveUP=1);
{* 单道工序移动:MoveDown:下移; Delete: 删除; MoveUP: 上移}
{TArtDtlInfo}
TArtDtlInfo=Class
{* 标准工艺,实际工艺,回修工艺的基类}
Private
Fcds_ArtHdr: TClientDataSet;
{* 工艺主表数据集合}
Fcds_ArtDtl: TClientDataSet;
{* 工艺明细表数据集合}
Org_Fcds_ArtDtl: TClientDataSet;
{* 修改前工艺明细表数据集合}
FModify: Boolean;
{* 工艺是否被修改}
FOnAfterEdit: TNotifyEvent;
{* 工艺编辑事件}
FOnBeforeSave: TNotifyEvent;
{* 工艺开始保存事件}
FOnAfterSave: TNotifyEvent;
{* 工艺保存完毕事件}
FOnAfterOpen: TNotifyEvent;
{* 工艺打开事件}
FOnAfterClose: TNotifyEvent;
{* 工艺关闭事件}
procedure SetModify(ModifyValue: Boolean);
{* 标识工艺否被修改}
function GetActive: Boolean;
{* 判断数据集合是否已打开}
procedure MergeStepNOValue;
{* 使某Step_no和EditStep_no两个字段的值相等, 在MoveAOperateStep过程中调用}
procedure SetAOperateEditStep_NOValue(OldKeyValue, NewKeyValue: Integer);
{* 根据Step_no设置EditStep_no的值, 在MoveAOperateStep过程中调用}
procedure FillParameterListControls(FillModle: String; AValueListEditor: TValueListEditor);
{* 填充参数到列表中}
protected
function GetFieldValue(Index: integer): Variant;
{* 获取主表Index字段的值}
procedure SetFieldValue(Index: integer; FieldValue: Variant);
{* 设置主表某各字段的值}
function RepairItemValue(OperationCode, ItemName, ItemValue: String): string; virtual;
{* 修正用户输入的参数值}
procedure TestItemValue(OperationCode, ItemName, ItemValue: String); virtual;
{* 测试参数值是否合法}
public
constructor Create(AOwner: TComponent);
{* Create}
destructor Destroy; override;
{* Destroy}
function CloseArt: Boolean;
{* 关闭工艺}
function SaveArtToDataBase: Boolean; virtual;
{* 保存工艺到数据库中}
function IsEmpty: Boolean;
{* 判断标准工艺主表是否为空}
function GetStepOperateCode(Step_NO: Integer): String;
{* 根据工序步骤取工序的Code}
function GetStepOperateName(Step_NO: Integer): String;
{* 根据工序步骤取工序的Name}
function AddAOperateStep(Operate_ID: Integer; Operation_Code: string = ''): Integer;
{* 追加一个工序步骤}
procedure MoveAOperateStep(Step_NO: Integer; OperateOffset: TOperateOffset);
{* 删除一个工序步骤或使某个工序的步骤加1减1}
procedure ClearAllOperateStep;
{* 清除所有工序}
function SetAOperateParameterValue(Step_NO :Integer; Item_Name, Item_Value: String): String; virtual;
{* 设置某道工序的某个参数的值}
procedure FillOperationToAListControls(AItem: TStrings);
{* 填充工序名到列表中}
procedure FillAStepToAListControls(Step_NO: Integer; AValueListEditor: TValueListEditor);
{* 填充指定工序参数到列表中}
procedure FillAItemToAListControls(ItemName: String; AValueListEditor: TValueListEditor);
{* 填充所有工序的指定参数到列表中}
function GetOperateStepCount: Integer;
{* 获取当前工序的步骤数}
function GetOperations: String;
{* 获取当前工序步骤代号列表(逗号分割)}
procedure ViewArtDtlInNewForm;
{* 在新窗口中查看工艺}
published
property Modify: Boolean read FModify write SetModify;
{* 工艺是否被修改}
property Active: Boolean read GetActive;
{* 工艺是否打开}
property OnAfterEdit: TNotifyEvent read FOnAfterEdit write FOnAfterEdit;
{* 工艺被编辑}
property OnBeforeSave: TNotifyEvent read FOnBeforeSave write FOnBeforeSave;
{* 工艺开始保存}
property OnAfterSave: TNotifyEvent read FOnAfterSave write FOnAfterSave;
{* 工艺保存成功}
property OnAfterOpen: TNotifyEvent read FOnAfterOpen write FOnAfterOpen;
{* 工艺打开成功}
property OnAfterClose: TNotifyEvent read FOnAfterClose write FOnAfterClose;
{* 工艺关闭成功}
end;
{TSTDArtDtlInfo}
TSTDArtDtlInfo=Class(TArtDtlInfo)
{* 标准工艺类}
Private
FOrgArt_ID: Integer;
{* 标准工艺编号, 该变量仅仅用于打开工艺}
FOrgDepartment: String;
{* 标准工艺所属部门, 该变量仅仅用于打开工艺}
procedure SetOrgArt_ID(OrgArt_IDValue: Integer);
{* 设置工艺ID}
procedure SetOrgDepartment(OrgDepartmentValue: String);
{* 设置标注工艺部门}
public
constructor Create(AOwner: TComponent);
{* 构造标准工艺类}
destructor Destroy; override;
{* 释放标准工艺类}
procedure OpenFNSTDArt;
{* 通过GF_ID或GF_NO打开工艺}
procedure CheckStdArt(iType:Integer);
{* 确认标准工艺}
function SaveArtToDataBase: Boolean; override;
procedure SaveFeedbackInfo;
{* 保存工艺到数据库}
procedure CreateStdArt(OrgGF_ID: Integer; Department, Creator: String);
{* 建立标准工艺}
procedure CopyAExistSTDArt(StdArtID: Integer);
{* 拷贝标准工艺}
procedure InitializeDepartmentMenuItem(MenuItem: TMenuItem; ClickEvent: TNotifyEvent);
{* 初使化工艺拷贝部门选择菜单}
function GetFeedbackInfo: OleVariant;
function ViewArtDtl(Index: integer): string;
published
property OrgArt_ID: Integer read FOrgArt_ID write SetOrgArt_ID;
{* 工艺编号}
property OrgDepartment: String read FOrgDepartment write SetOrgDepartment;
{* 标准工艺部门}
property Art_ID :Variant index 1 read GetFieldValue;
{* 工艺编号}
property GF_ID :Variant index 2 read GetFieldValue;
property GF_NO :Variant index 3 read GetFieldValue;
property FN_Art_NO :Variant index 4 read GetFieldValue write SetFieldValue;
{* 后整理工艺代号}
property FN_Color_Code :Variant index 5 read GetFieldValue write SetFieldValue;
{* 后整理颜色代号}
property Shrinkage :Variant index 6 read GetFieldValue write SetFieldValue;
{* 后整理缩水要求}
property HandFeel :Variant index 7 read GetFieldValue write SetFieldValue;
{* 后整理手感要求}
property Product_Width :Variant index 8 read GetFieldValue write SetFieldValue;
{* 后整理门幅}
property Material_Quality :Variant index 9 read GetFieldValue;
{* 当前工艺的适用类型}
property Version :Variant index 10 read GetFieldValue;
{* 工艺版本}
property Current_Department :Variant index 11 read GetFieldValue;
{* 工艺建立的部门}
property Operator :Variant index 12 read GetFieldValue write SetFieldValue;
{* 工艺建立人}
property Operate_Time :Variant index 13 read GetFieldValue;
{* 工艺建立时间}
property Checker :Variant index 14 read GetFieldValue;
{* 工艺确认人}
property Check_Time :Variant index 15 read GetFieldValue;
{* 工艺确认时间}
property Remark :Variant index 16 read GetFieldValue write SetFieldValue;
{* 工艺备注}
property Is_Active :Variant index 17 read GetFieldValue write SetFieldValue;
{* 工艺是否有效}
property Feedback :Variant index 18 read GetFieldValue;
property Feedback_Time :Variant index 19 read GetFieldValue;
property PDARemark :Variant index 20 read GetFieldValue write SetFieldValue;
property PDMRemark :Variant index 21 read GetFieldValue write SetFieldValue;
end;
{TFactArtDtlInfo}
TFactArtDtlInfo=Class(TArtDtlInfo)
{* 实际工艺类}
Private
Fcds_JobTraceDtl: TClientDataSet;
{* 进度跟踪明细数据集合}
FFACT_Art_ID: Integer;
{* 实际工艺编号}
FCardList: string;
{* 使用当前实际工艺的卡号列表, 逗号分割}
FInternal_Repair: Boolean;
{内回修}
FAsSTDArt: Boolean;
{是否做为此品种的标准工艺}
FRepairReason: string;
procedure SetFACT_Art_ID(FACT_Art_IDValue: Integer);
{* 设置实际工艺编号}
function GetRepairSteps: String;
{* 取新添加的工序列表}
public
constructor Create(AOwner: TComponent);
{* Create}
destructor Destroy; override;
{* Destroy}
procedure OpenFNArt;
{* 打开实际工艺}
function GetJobTraceDtlInfo(SelectCardList: String; SelectStepNO: Integer): Boolean;
{* 取进度跟踪明细数}
procedure UpdateAStepNO(OldStepNO: Integer; OperateOffset: TOperateOffset);
{* 更新进度跟踪明细记录}
function SaveArtToDataBase: Boolean; override;
{* 保存实际工艺到数据库}
published
property FACT_Art_ID: Integer read FFACT_Art_ID write SetFACT_Art_ID;
{* 实际工艺代号}
property CardList: String read FCardList write FCardList;
{* 使用当前实际工艺的卡号列表}
property RepairSteps: String read GetRepairSteps;
{* 当前工艺的回修步骤}
property Internal_Repair: Boolean read FInternal_Repair write FInternal_Repair;
{* }
property AsSTDArt: Boolean read FAsSTDArt write FAsSTDArt;
{* }
property RepairReason: String read FRepairReason write FRepairReason;
{* }
property Art_ID :Variant index 1 read GetFieldValue;
{* 实际工艺ID}
property Fact_Art_Version :Variant index 2 read GetFieldValue;
{* 实际工艺版本}
property GF_ID :Variant index 3 read GetFieldValue;
property GF_NO :Variant index 4 read GetFieldValue;
property FN_Art_NO :Variant index 5 read GetFieldValue write SetFieldValue;
{* 后整理工艺代号}
property STD_Art_ID :Variant index 6 read GetFieldValue;
{* 当前工艺的根工艺的标准工艺}
property STD_Art_Version :Variant index 7 read GetFieldValue;
{* 当前工艺的根工艺的标准工艺的版本}
property FN_Color_Code :Variant index 8 read GetFieldValue write SetFieldValue;
{* 当前工艺的颜色代号}
property Shrinkage :Variant index 9 read GetFieldValue write SetFieldValue;
{* 后整理缩水要求}
property HandFeel :Variant index 10 read GetFieldValue write SetFieldValue;
{* 后整理手感要求}
property Product_Width :Variant index 11 read GetFieldValue write SetFieldValue;
{* 后整理门幅}
property Art_Type :Variant index 12 read GetFieldValue;
{* 当前工艺的类型}
property Material_Quality :Variant index 13 read GetFieldValue;
{* 当前工艺的适用类型}
property Operator :Variant index 14 read GetFieldValue write SetFieldValue;
{* 当前工艺的建立人}
property Operate_Time :Variant index 15 read GetFieldValue;
{* 当前工艺的建立时间}
property Remark :Variant index 16 read GetFieldValue write SetFieldValue;
{* 工艺备注}
property fact_art_dtl: TClientDataSet read Fcds_ArtDtl;
{* 实际工艺}
property Org_fact_art_dtl: TClientDataSet read Org_Fcds_ArtDtl;
{* 修改前实际工艺}
end;
{TRepairArtDtlInfo}
TRepairArtDtlInfo=Class(TArtDtlInfo)
{* 回修工艺类}
Private
FCardList: string;
{* 使用当前实际工艺的卡号列表, 逗号分割}
public
procedure SaveRepairArt(var vData: OleVariant; vDataHdr,
vDataDtl: OleVariant; var sErrorMsg: WideString);
procedure CreateRepairArt(RepairIden, GF_ID: Integer; SelectCard: string; CurrentDeparment, Operator: String);
{* 建立回修工艺}
function SaveArtToDataBase(IsQualityOperator:Boolean;RepairIden :Integer;GF_ID:Integer; Quantity:Double ;Repair_Code,Current_Department,Operator :string) : Boolean;
{* 保存回修工艺到数据库}
published
property CardList: String read FCardList write FCardList;
{* 使用当前实际工艺的卡号列表}
property Art_ID :Variant index 1 read GetFieldValue;
{* 实际工艺ID}
property GF_ID :Variant index 2 read GetFieldValue;
{* 工艺的品名代号}
property FN_Art_NO :Variant index 3 read GetFieldValue write SetFieldValue;
{* 后整理工艺代号}
property FN_Color_Code :Variant index 4 read GetFieldValue write SetFieldValue;
{* 当前工艺的颜色代号}
property Shrinkage :Variant index 5 read GetFieldValue write SetFieldValue;
{* 后整理缩水要求}
property HandFeel :Variant index 6 read GetFieldValue write SetFieldValue;
{* 后整理手感要求}
property Product_Width :Variant index 7 read GetFieldValue write SetFieldValue;
{* 后整理门幅}
property Art_Type :Variant index 8 read GetFieldValue;
{* 当前工艺的类型,返工还是正常工艺}
property Material_Quality :Variant index 9 read GetFieldValue;
{* 当前工艺的适用类型,是正常布工艺还是处理布工艺}
property Operator :Variant index 10 read GetFieldValue write SetFieldValue;
{* 当前工艺的建立人}
property Operate_Time :Variant index 11 read GetFieldValue;
{* 当前工艺的建立时间}
property Remark :Variant index 12 read GetFieldValue write SetFieldValue;
{* 工艺备注}
property Reason_Type :Variant index 13 read GetFieldValue write SetFieldValue;
{* 回修类型}
property Reason_Info :Variant index 14 read GetFieldValue write SetFieldValue;
{* 回修原因}
end;
{THLArtDtlInfo}
THLArtDtlInfo=Class(TArtDtlInfo)
{* HL工艺类}
public
procedure CreateHLArt(FN_ID, FN_NO, Creator: String);
{* 建立HL工艺}
function SaveArtToDataBase: Boolean; override;
{* 保存HL工艺到数据库}
published
property FN_ID :Variant index 1 read GetFieldValue;
{* HL工艺ID}
property FN_NO :Variant index 2 read GetFieldValue;
{* HL工艺ID}
property Art_ID :Variant index 3 read GetFieldValue;
{* HL工艺ID}
property FN_Art_NO :Variant index 4 read GetFieldValue write SetFieldValue;
{* 后整工艺代号}
property Art_Type :Variant index 5 read GetFieldValue;
{* 当前工艺的类型,返工还是正常工艺}
property Material_Quality :Variant index 6 read GetFieldValue;
{* 当前工艺的适用类型}
property Operator :Variant index 7 read GetFieldValue write SetFieldValue;
{* 当前工艺的建立人}
property Operate_Time :Variant index 8 read GetFieldValue;
{* 当前工艺的建立时间}
property Remark :Variant index 9 read GetFieldValue write SetFieldValue;
{* 工艺备注}
end;
procedure GetStdArtIDbyGFNO(GF_KeyValue, Department: String; var Art_ID, GF_ID: Integer);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-12-24 14:40:38
参数列表: GF_KeyValue, Department: String; var Art_ID, GF_ID: Integer
功能描述: 通过品名或品名ID取出Art_ID和GF_ID
引用计数:
-------------------------------------------------------------------------------}
procedure GetOnLineCardByGFKeyValue(GFKeyValue, Department: String; CDS: TClientDataSet);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-8-30 下午 05:57:45
参数列表:
功能描述: 取指定品名某部门的在线卡号
引用计数:
-------------------------------------------------------------------------------}
procedure GetOnLineCardByOperation(Operation_Code: String; Department: String; CDS: TClientDataSet);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-8-30 下午 05:57:45
参数列表:
功能描述: 取指定工序某部门的在线卡号
引用计数:
-------------------------------------------------------------------------------}
procedure FillItemsFromDataSet(cds: TDataSet; FirstField, SecondField, KeyField, LinkSymbol: string; TheItems: TStrings;
InsertAll: Boolean=false; TrimSpace: Boolean = true; ClearMode: Boolean = true);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-8-30 下午 05:45:09
参数列表: cds: 数据集; FirstField: 第一字段; SecondField: 第二字段; KeyField: 关键字字段,该字段必须为整型字段
LinkSymbol: 第一字段和第二字段之间的连接符号; TheItems: 添加的目标字符串列表;
InsertAll: 是否插入所有的记录,为True是则插入所有记录,默认为Fase,相同的记录不插入.
功能描述: 填充数据集合到指定的Items中
-------------------------------------------------------------------------------}
procedure FillTreeItemsFromDataSet(cds: TClientDataSet; DisplayField,
ParentField, SubField, KeyField, RootValue: string; TheNodes: TTreeNodes; RootNode: TTreeNode = nil);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-8-30 下午 05:41:54
参数列表: cds: 数据集; DisplayField: 显示字段; ParentField: 父字段; SubField: 子字段;
KeyField: 关键字字段,该字段必须为整型字段; RootValue: 作为根节点的字段值标志;
TheNodes: 添加的目标TreeNodes;
表结构: DisplayField | ParentField | SubField |KeyField
功能描述: 填充数据集合到指定的TreeItems中
-------------------------------------------------------------------------------}
procedure FillTreeItemsFromDataSetByClassField(cds: TClientDataSet;
ValueField, ClassField, KeyField, DescriptionField: string; TheNodes: TTreeNodes);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-10-20 12:18:28
参数列表: cds: 数据集; ValueField: 值字段; ClassField: 分类字段; KeyField: 关键字字段; TheNodes: 添加的目标TreeNodes;
功能描述: 按ClassField,将keyField填充到TreeNodes中
-------------------------------------------------------------------------------}
procedure FillListItemsFromDataSet(cds: TDataSet; FirstField, KeyField: string;
FieldStrings: array of String; TheItems: TListItems);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-9-1 9:32:44
参数列表: cds: 数据集; FirstField: ListItem的Caption, 且不能为空;
KeyField: 关键字字段,该字段必须为整型字段, 如果需要访问该该值, FieldStrings参数必须传入一个字段名
FieldStrings: 需要加入到SubItems中的字段数组;
TheItems: 不言自明;
返回值 : 无
功能描述: 填充数据集合到指定的TListItems中
-------------------------------------------------------------------------------}
procedure AddItemToListItems(KeyValue: String; ItemStrings: array of String; TheItems: TListItems);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-11-20 14:37:21
参数列表: KeyValue: String; ItemStrings: array of String; TheItems: TListItems
功能描述: 向ListItem中添加Item,有重复的KeyValue不添加
引用计数:
-------------------------------------------------------------------------------}
procedure FillFN_Art_NOListToAComboBox(Code_Class: String; AComboBox: TComboBox);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-12-14 14:28:13
参数列表: Code_Class: String; AComboBox: TComboBox
功能描述: 填充FN_Art_NO字典到ComboBox中
引用计数:
-------------------------------------------------------------------------------}
procedure FillArt_NOListToAComboBox(ArtType: String; AComboBox: TComboBox);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-12-22 10:55:39
参数列表: ArtType: String; AComboBox: TComboBox
功能描述: 填充Art_NO字典到ComboBox中
引用计数:
-------------------------------------------------------------------------------}
procedure FillOnLineCardList(GFKeyValue, Department: String; TreeNodes: TTreeNodes);
{*|<PRE> -----------------------------------------------------------------------------
创建人员 lvzd
创建日期 2005-3-9 17:01:43
参数列表 GFKeyValue, Department: String; TreeNodes: TTreeNodes
功能描述 填充在线卡号到树型列表中
引用计数:
-------------------------------------------------------------------------------}
procedure FillMachineListByOperationCode(Department, Operation_Code: String; AItems: TStrings);
{*|<PRE> -----------------------------------------------------------------------------
过程名称 FillMachineListByOperationCode
创建人员 lvzd
创建日期 2005-4-13 12:02:25
参数列表 Operation_Code: String; AItems: TStrings
返回值 无
功能描述
附加说明
-------------------------------------------------------------------------------}
implementation
{$IFNDEF TERMINAL}
uses frmViewArtDtl;
{$ENDIF}
procedure GetStdArtIDbyGFNO(GF_KeyValue, Department: String; var Art_ID, GF_ID: Integer);
var
sErrorMsg: WideString;
begin
if GF_KeyValue = '' then exit;
FNMServerArtObj.GetCheckGFIDAndSTDArt(GF_KeyValue, Department, GF_ID, Art_ID, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetCheckGFIDAndSTDArt, [sErrorMsg]);
//品名不存在
if GF_ID = -1 then
raise ExceptionEx.CreateResFmt(@INV_GFIDorGF_NO, [GF_KeyValue]);
end;
procedure GetOnLineCardByGFKeyValue(GFKeyValue, Department: String; CDS: TClientDataSet);
var
vData: OleVariant;
sErrorMsg: WideString;
begin
//刷新卡号列表。
if GFKeyValue = '' then
exit;
FNMServerArtObj.GetOnLineCard('ByGFKeyValue', GFKeyValue, Department, vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetOnLineCard, [sErrorMsg]);
CDS.Data:=vData;
if CDS.IsEmpty then
raise Exception.CreateRes(@EMP_OnLineCard);
end;
procedure GetOnLineCardByOperation(Operation_Code: String; Department: String; CDS: TClientDataSet);
var
vData: OleVariant;
sErrorMsg: WideString;
begin
if CDS = nil then exit;
FNMServerArtObj.GetOnLineCard('ByOperation', Operation_Code, Department, vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetOnLineCard, [sErrorMsg]);
CDS.Data:=vData;
if CDS.IsEmpty then
raise Exception.CreateRes(@EMP_OnLineCard);
end;
procedure FillItemsFromDataSet(cds: TDataSet; FirstField, SecondField, KeyField, LinkSymbol: string; TheItems: TStrings;
InsertAll: Boolean=false; TrimSpace: Boolean = true; ClearMode: Boolean = true);
var
ItemValue: String;
i, KeyValue: Integer;
begin
if (cds = nil) or (not cds.Active) then Exit;
try
TheItems.BeginUpdate;
if ClearMode then
TheItems.Clear;
cds.DisableControls;
cds.First;
for i := 0 to cds.RecordCount - 1 do
begin
ItemValue:=cds.FieldByName(FirstField).AsString;
if TrimSpace then
ItemValue:=Trim(ItemValue);
//去掉中文机台
if (SecondField <> '') and (SecondField <> 'Machine_Model_CHN') then
begin
ItemValue:=ItemValue+LinkSymbol+cds.FieldByName(SecondField).AsString;
end;
if KeyField <> '' then
begin
KeyValue:=cds.FieldByName(KeyField).Asinteger;
if TheItems.IndexOfObject(TObject(KeyValue)) = -1 then
TheItems.AddObject(ItemValue, TObject(KeyValue))
else if InsertAll then
TheItems.AddObject(ItemValue, TObject(KeyValue));
end
else
if TheItems.IndexOf(ItemValue) = -1 then
TheItems.Add(ItemValue)
else if InsertAll then
TheItems.Add(ItemValue);
cds.Next;
end;
finally
cds.EnableControls;
TheItems.EndUpdate;
end;
end;
procedure FillTreeItemsFromDataSet(cds: TClientDataSet; DisplayField, ParentField, SubField, KeyField, RootValue: string;
TheNodes: TTreeNodes; RootNode: TTreeNode = nil);
var
i: Integer;
NewNode: TTreeNode;
TempCds: TClientDataSet;
procedure FillChildNodes(ParentValue: string; TheNode: TTreeNode);
{*|<PRE>------------------------------------------------------------------------------
创建人员: lvzd
创建日期: 2004-8-30 下午 06:13:45
参数列表: ParentValue: 父节点的ParentField的值; TheNode: 在该节点下插入节点
返回值 : 无
功能描述: 递归插入所有子节点
附加说明: 该函数为递归函数
-------------------------------------------------------------------------------}
var
i: Integer;
OldFilter: String;
begin
OldFilter:=TempCds.Filter;
//过滤子节点
TempCds.Filter:=SubField +' = '''+ParentValue+'''';
for i := 0 to TempCds.RecordCount - 1 do
begin
//添加子节点
if KeyField = '' then
NewNode:=TheNodes.AddChild(TheNode, TempCds.FieldByName(DisplayField).AsString)
else
NewNode:=TheNodes.AddChildObject(TheNode, TempCds.FieldByName(DisplayField).AsString, Pointer(TempCds.FieldByName(KeyField).Asinteger));
//添加子节点的子节点
FillChildNodes(TempCds.FieldByName(ParentField).AsString, NewNode);
TempCds.Delete;
end;
//返回过滤条件
TempCds.Filter:=OldFilter;
end;
begin
if (Cds = nil) or Cds.IsEmpty then exit;
TempCds:=nil;
try
//先克隆数据集合
TempCds:=TClientDataSet.Create(Cds.Owner);
TempCds.Data:=Cds.Data;
//过滤根节点.
TempCds.Filter:=SubField +ifthen(RootValue = '', '= ''''', ' = '''+RootValue+'''') ;
TempCds.Filtered:=true;
//开始插入节点
TheNodes.BeginUpdate;
//删除旧的节点
TheNodes.Clear;
for i := 0 to TempCds.RecordCount - 1 do
begin
//添加根节点
if KeyField = '' then
NewNode:=TheNodes.Add(RootNode, TempCds.FieldByName(DisplayField).AsString)
else
NewNode:=TheNodes.AddObject(RootNode, TempCds.FieldByName(DisplayField).AsString, Pointer(TempCds.FieldByName(KeyField).Asinteger));
//添加子节点
FillChildNodes(TempCds.FieldByName(ParentField).AsString, NewNode);
TempCds.Delete;
end;
finally
TempCds.Destroy;
TheNodes.EndUpdate;
end;
end;
procedure FillTreeItemsFromDataSetByClassField(cds: TClientDataSet; ValueField, ClassField, KeyField, DescriptionField: string; TheNodes: TTreeNodes);
var
i: Integer;
NewNode: TTreeNode;
ChildNodeStrings, NodeText: String;
TempCds: TClientDataSet;
begin
if (Cds = nil) or Cds.IsEmpty then exit;
TempCds:=nil;
try
//先克隆数据集合
TempCds:=TClientDataSet.Create(Cds.Owner);
TempCds.Data:=Cds.Data;
TheNodes.BeginUpdate;
while TempCds.RecordCount <> 0 do
begin
NodeText:=TempCds.FieldByName(ClassField).AsString;
// if DescriptionField <> '' then
// NodeText:=TempCds.FieldByName(DescriptionField).AsString;//NodeText +
NewNode:=TheNodes.AddChild(nil, NodeText);
TempCds.Filter:=Format('%s = ''%s''', [ClassField, TempCds[ClassField]]);
TempCds.Filtered:=true;
ChildNodeStrings:='/\';
for i := 0 to TempCds.RecordCount - 1 do
begin
NodeText:=TempCds.FieldByName(ValueField).AsString;
if DescriptionField <> '' then
NodeText:=NodeText + TempCds.FieldByName(DescriptionField).AsString;
if Pos('/\'+NodeText+'/\', ChildNodeStrings) = 0 then
with TheNodes.AddChild(NewNode, NodeText) do
begin
if KeyField <> '' then
Data:=TObject(TempCds.FieldByName(KeyField).AsInteger);
ChildNodeStrings:=ChildNodeStrings + Text + '/\';
end;
TempCds.Delete;
end;
TempCds.Filtered:=false;
end;
finally
TempCds.Destroy;
TheNodes.EndUpdate;
end;
end;
procedure FillListItemsFromDataSet(cds: TDataSet; FirstField, KeyField: string; FieldStrings: array of String; TheItems: TListItems);
var
i, j: Integer;
NewListItem: TListItem;
begin
if (cds = nil) or (not cds.Active) then Exit;
try
TheItems.BeginUpdate;
TheItems.Clear;
with cds do
begin
DisableControls;
First;
for i := 0 to RecordCount - 1 do
begin
NewListItem:=TheItems.Add;
NewListItem.Caption:=Trim(FieldByName(FirstField).AsString);
for j := 0 to High(FieldStrings) do
NewListItem.SubItems.Add(Trim(FieldByName(FieldStrings[j]).AsString));
if (NewListItem.SubItems.Count <> 0) and (KeyField <> '') then
NewListItem.SubItems.Objects[0]:=TObject(FieldByName(KeyField).AsInteger);
next;
end;
end;
finally
cds.EnableControls;
TheItems.EndUpdate;
end;
end;
procedure AddItemToListItems(KeyValue: String; ItemStrings: array of String; TheItems: TListItems);
var
i, j: Integer;
begin
for i := 0 to TheItems.Count - 1 do
if TheItems.Item[i].Caption = KeyValue then exit;
with TheItems.Add do
begin
Caption:=KeyValue;
for j := 0 to High(ItemStrings) do
SubItems.Add(ItemStrings[j]);
end
end;
procedure FillFN_Art_NOListToAComboBox(Code_Class: String; AComboBox: TComboBox);
begin
Dictionary.cds_ArtDescriptionList.Filter:='Code_Class = ''' + Code_Class + '''';
Dictionary.cds_ArtDescriptionList.Filtered:=true;
FillItemsFromDataSet(Dictionary.cds_ArtDescriptionList, 'FN_Art_Code', 'Description', 'Iden', ' ', AComboBox.Items, false, false);
AComboBox.DropDownCount:=AComboBox.Items.Count;
end;
procedure FillArt_NOListToAComboBox(ArtType: String; AComboBox: TComboBox);
begin
Dictionary.cds_StdArtDtlList.Filter:='Type = ''' + ArtType + '''';
Dictionary.cds_StdArtDtlList.Filtered:=true;
FillItemsFromDataSet(Dictionary.cds_StdArtDtlList, 'Art_NO', 'Description', '', ' ', AComboBox.Items, false, false);
AComboBox.DropDownCount:=AComboBox.Items.Count;
end;
procedure FillOnLineCardList(GFKeyValue, Department: String; TreeNodes: TTreeNodes);
var
i: Integer;
begin
//刷新卡号列表。
if GFKeyValue = '' then exit;
GetOnLineCardByGFKeyValue(GFKeyValue, Department, TempClientDataSet);
if TempClientDataSet.IsEmpty then exit;
TreeNodes.Clear;
FillTreeItemsFromDataSetByClassField(TempClientDataSet, 'FN_Card', 'Fact_Art_Step_NO', '', '', TreeNodes);
with TreeNodes, TreeNodes.Owner do
if Count > 0 then
begin
for i := 0 to Count - 1 do
begin
if Item[i].Level = 0 then
Item[i].StateIndex := 0;
end;
FullExpand;
Selected:=TreeNodes.Item[0];
Selected.MakeVisible;
Enabled:=true;
end;
end;
procedure FillMachineListByOperationCode(Department, Operation_Code: String; AItems: TStrings);
var
i: Integer;
begin
AItems.Clear;
with Dictionary do
try
cds_OperationMapMachineModel.Filter:=Format('Operation_Code = ''%s''', [Operation_Code]);
cds_OperationMapMachineModel.Filtered:=true;
for i := 0 to cds_OperationMapMachineModel.RecordCount - 1 do
begin
cds_FinishMachineList.Filter:=Format('Machine_ID LIKE ''%s%%'' AND Department = ''%s''', [Trim(cds_OperationMapMachineModel['Machine_Model']), Department]);
cds_FinishMachineList.Filtered:=true;
FillItemsFromDataSet(cds_FinishMachineList, 'Machine_ID', 'Machine_Model_CHN', '', '-', AItems, False, True, False);
cds_OperationMapMachineModel.Next;
end;
finally
cds_FinishMachineList.Filtered:=false;
cds_OperationMapMachineModel.Filtered:=false;
end;
end;
{TArtDtlInfo}
constructor TArtDtlInfo.Create(AOwner: TComponent);
begin
inherited Create;
Fcds_ArtHdr:=TClientDataSet.Create(AOwner);
Fcds_ArtDtl:=TClientDataSet.Create(AOwner);
Org_Fcds_ArtDtl:=TClientDataSet.Create(AOwner);
end;
destructor TArtDtlInfo.Destroy;
begin
if not CloseArt then exit;
Fcds_ArtHdr.Destroy;
Fcds_ArtDtl.Destroy;
//Org_Fcds_ArtDtl.Destroy;
inherited Destroy;
end;
function TArtDtlInfo.IsEmpty: Boolean;
begin
result:=Fcds_ArtHdr.IsEmpty;
end;
procedure TArtDtlInfo.SetModify(ModifyValue: Boolean);
begin
if FModify = ModifyValue then exit;
FModify := Active and ModifyValue;
if Active and Assigned(FOnAfterEdit) then FOnAfterEdit(Self);
end;
function TArtDtlInfo.GetActive: Boolean;
begin
result:=Fcds_ArtHdr.Active and Fcds_ArtDtl.Active
end;
function TArtDtlInfo.GetOperateStepCount: Integer;
var
i: Integer;
begin
result:=0;
if Fcds_ArtDtl.IsEmpty then exit;
Fcds_ArtDtl.First;
result:=Fcds_ArtDtl['Step_NO'];
for i := 0 to Fcds_ArtDtl.RecordCount - 1 do
begin
if Fcds_ArtDtl['Step_NO'] > result then
result:=Fcds_ArtDtl['Step_NO'];
Fcds_ArtDtl.Next;
end;
end;
procedure TArtDtlInfo.ViewArtDtlInNewForm;
begin
{$IFNDEF TERMINAL}
if Active then
ViewArtDtl(Fcds_ArtDtl);
{$ENDIF}
end;
function TArtDtlInfo.CloseArt: Boolean;
var
MessResult: Integer;
begin
result := True;
if not Active then
begin
Modify:=False;
exit;
end;
result := False;
//判断用户是否保存了修改数据,没有保存询问用户。
if Modify then
begin
MessResult:=MessageBox(Application.Handle, Pchar(GetResourceString(@AskSaveDataStr)),Pchar(Application.Title), MB_YESNOCANCEL+MB_ICONQUESTION);
if (MessResult = IDYES) and (not SaveArtToDataBase) then
Raise Exception.Create(GetResourceString(@SaveDataFail));
if MessResult = IDNO then
begin
Fcds_ArtHdr.CancelUpdates;
Fcds_ArtDtl.CancelUpdates;
Modify:=false;
end;
if MessResult = IDCANCEL then
exit;
end;
Fcds_ArtHdr.Close;
Fcds_ArtDtl.Close;
Org_Fcds_ArtDtl.Close;
if Assigned(OnAfterClose) then OnAfterClose(self);
result := True;
end;
function TArtDtlInfo.SaveArtToDataBase: Boolean;
Begin
result := True;
end;
function TArtDtlInfo.GetStepOperateCode(Step_NO: Integer): String;
begin
result:='';
if not Active then exit;
if Fcds_ArtDtl.Locate('EditStep_no', IntToStr(Step_NO), []) then
result:=Fcds_ArtDtl.FieldByName('Operation_Code').AsString;
end;
function TArtDtlInfo.GetStepOperateName(Step_NO: Integer): String;
begin
result:='';
if not Active then exit;
if Fcds_ArtDtl.Locate('EditStep_no', IntToStr(Step_NO), []) then
result:=Fcds_ArtDtl.FieldByName('Operation_CHN').AsString;
end;
procedure TArtDtlInfo.SetAOperateEditStep_NOValue(OldKeyValue, NewKeyValue: Integer);
var
i: Integer;
begin
try
Fcds_ArtDtl.DisableControls;
Fcds_ArtDtl.First;
for i := 0 to Fcds_ArtDtl.RecordCount - 1 do
begin
Fcds_ArtDtl.Edit;
//等于-1删除一个工序
if NewKeyValue = -1 then
begin
if Fcds_ArtDtl.FieldByName('Step_no').AsInteger > OldKeyValue then
Fcds_ArtDtl.FieldByName('EditStep_no').AsInteger:=Fcds_ArtDtl.FieldByName('Step_no').AsInteger -1;
if Fcds_ArtDtl.FieldByName('Step_no').AsInteger = OldKeyValue then
begin
Fcds_ArtDtl.Delete;
Continue;
end
end
else
begin
if Fcds_ArtDtl.FieldByName('Step_no').AsInteger = OldKeyValue then
Fcds_ArtDtl.FieldByName('EditStep_no').AsInteger:=NewKeyValue;
end;
Fcds_ArtDtl.Next;
end
finally
Fcds_ArtDtl.EnableControls
end;
end;
procedure TArtDtlInfo.MergeStepNOValue;
var
i: Integer;
begin
try
Fcds_ArtDtl.DisableControls;
Fcds_ArtDtl.First;
for i := 0 to Fcds_ArtDtl.RecordCount - 1 do
begin
Fcds_ArtDtl.Edit;
Fcds_ArtDtl.FieldByName('Step_no').AsInteger:=Fcds_ArtDtl.FieldByName('EditStep_no').AsInteger;
Fcds_ArtDtl.Next;
end;
finally
Fcds_ArtDtl.EnableControls
end;
end;
function TArtDtlInfo.AddAOperateStep(Operate_ID: Integer; Operation_Code: string = ''): Integer;
var
iType,iGFID: Integer;
vData: Olevariant;
sCondition,sErrorMsg: widestring;
begin
if ClassName = 'TSTDArtDtlInfo' then
begin
iType := 0;
iGFID := TSTDArtDtlInfo(Self).GF_ID;
end;
if ClassName = 'TFactArtDtlInfo' then
begin
iType := 1;
iGFID := TFactArtDtlInfo(Self).GF_ID;
end;
if ClassName = 'THLArtDtlInfo' then
begin
iType := 2;
iGFID := THLArtDtlInfo(Self).FN_ID;
end;
if ClassName = 'TRepairArtDtlInfo' then
begin
iType := 3;
iGFID := TRepairArtDtlInfo(Self).GF_ID;
end;
//取出最大的一个Step_no值加1后作为新插入的Step_NO的值
result:=GetOperateStepCount + 1;
sCondition := IntToStr(iGFID)+','+IntToStr(Operate_ID)+','+ QuotedStr(Operation_Code)+','+ IntToStr(iType)+','+ QuotedStr(Login.CurrentDepartment);
FNMServerObj.GetQueryData(vData,'ARTGetOperation',sCondition,sErrorMsg);
if sErrorMsg<>'' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
TempClientDataSet.Data:=vData;
with TempClientDataSet do
begin
First;
while not Eof do
begin
Fcds_ArtDtl.AppendRecord([result, result,
FieldByName('Operation_Code').AsString,
FieldByName('Operation_CHN').AsString,
FieldByName('Item_Name').AsString,
FieldByName('Item_Value').AsString,'', nil]);
Next;
end;
end;
Modify:=true;
end;
procedure TArtDtlInfo.MoveAOperateStep(Step_NO: Integer; OperateOffset: TOperateOffset);
begin
case OperateOffset of
ooMoveUP:
begin
SetAOperateEditStep_NOValue(Step_NO, Step_NO-1); //当前工序的Step_NO的值减1
SetAOperateEditStep_NOValue(Step_NO-1, Step_NO); //上个工序的Step_NO调整为当前的工序的Step_NO
end;
ooMoveDown:
begin
SetAOperateEditStep_NOValue(Step_NO, Step_NO+1); //当前工序的Step_NO的值加1
SetAOperateEditStep_NOValue(Step_NO+1, Step_NO); //下个工序的Step_NO调整为当前的工序的Step_NO
end;
ooDelete:
SetAOperateEditStep_NOValue(Step_NO, -1);
end;
MergeStepNOValue; //使Step_NO和EditStep_NO的值相同,使修改生效.
Modify:=true;
end;
procedure TArtDtlInfo.ClearAllOperateStep;
begin
if Active then
Fcds_ArtDtl.EmptyDataSet;
end;
function TArtDtlInfo.RepairItemValue(OperationCode, ItemName,
ItemValue: String): string;
begin
Result:=ItemValue;
if ItemName = '次序' then
begin
Result:=StringReplace(Result, 'Z', '正', [rfReplaceAll, rfIgnoreCase]);
Result:=StringReplace(Result, 'F', '反', [rfReplaceAll, rfIgnoreCase]);
end;
end;
procedure TArtDtlInfo.TestItemValue(OperationCode, ItemName, ItemValue: String);
var
tempe: Extended;
tempi: Integer;
ValueType: String;
begin
with Dictionary.cds_OperationDtlList do
begin
if ItemName = '次序' then
begin
ItemValue:=StringReplace(ItemValue, '正', '', [rfReplaceAll]);
ItemValue:=StringReplace(ItemValue, '反', '', [rfReplaceAll]);
if ItemValue <> '' then
raise Exception.CreateResFmt(@INV_NOItemValue, ['正 Or 反', '正 Or 反']);
end;
if Locate('Operation_Code;Item_Name', VarArrayOf([OperationCode, ItemName]), []) then
begin
ValueType:=Dictionary.cds_OperationDtlList['Data_Type'];
if ValueType = 'Boolean' then
begin
if (LowerCase(ItemValue) <> 'true') and (LowerCase(ItemValue) <> 'false') then
raise Exception.CreateResFmt(@INV_NOItemValue, ['True Or False', 'True Or False']);
end;
if ValueType = 'int' then
begin
if not TryStrToInt(ItemValue, tempi) then
raise Exception.CreateResFmt(@INV_NOItemValue, ['整数', '整数']);
end;
if ValueType = 'Numeric' then
begin
if not TryStrToFloat(ItemValue, tempe) then
raise Exception.CreateResFmt(@INV_NOItemValue, ['数字', '数字']);
end;
end;
end;
end;
// DAVID ADD FOR TEST BEGIN {
procedure TRepairArtDtlInfo.SaveRepairArt(var vData: OleVariant; vDataHdr,
vDataDtl: OleVariant; var sErrorMsg: WideString);
const
// David Add 2014-10-09 begin, 自动生成回修工艺
UPDATE_REPAIR_HDR_SQL = 'UPDATE dbo.fnFactArtHdr SET Operator=''%s'' ' +
'WHERE FN_Card=''%s'''+#13#10;
DELETE_REPAIR_DTL_SQL = 'DELETE dbo.fnFactArtDtl WHERE Fact_Art_ID=''%s''' +#13#10;
// David Add 2014-10-09 end, 自动生成回修工艺
INSERT_REPAIR_HDR_SQL = 'INSERT INTO dbo.fnFactArtHdr (GF_ID, STD_Art_ID, STD_Art_Version, Art_Type, Material_Quality, Operator, Remark) '+
'VALUES(''%s'', -1, 0, ''%s'', ''%s'', ''%s'', ''%s'')' +#13#10;
INSERT_REPAIR_DTL_SQL = 'INSERT INTO dbo.fnFactArtDtl (Fact_Art_ID, Step_NO, Operation_Code, Item_Name, Item_Value, Operator, Operate_Time) '+
'VALUES(@Fact_Art_ID, ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'') ' +#13#10;
INSERT_REPAIROPERATION_SQL0 = 'INSERT INTO dbo.fnRepairOperation (GF_ID,Quantity,FN_Card, Reason_Code, Internal_External, Repair_Operation, Current_Department, Operator, Operate_Time) '+
'VALUES(''%s'',''%s'',''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', GETDATE())' +#13#10;
INSERT_REPAIROPERATION_SQL1 = 'INSERT INTO dbo.fnRepairOperation (GF_ID,Quantity,FN_Card, Reason_Code, Internal_External, Repair_Operation, Current_Department, Operator, Operate_Time, Checker, Check_Time) '+
'VALUES(''%s'',''%s'',''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', GETDATE(), ''%s'',GETDATE())' +#13#10;
UPDATE_REPAIROPERATION_SQL0 = 'UPDATE dbo.fnRepairOperation SET GF_ID = ''%s'', Quantity = ''%s'',FN_Card = ''%s'', Reason_Code = ''%s'', Internal_External= ''%s'', Repair_Operation= ''%s'', Current_Department= ''%s'','+
' Operator = ''%s'', Operate_Time = GETDATE() '+
' WHERE Check_Time IS NULL AND Iden = ''%s'''+#13#10;
UPDATE_REPAIROPERATION_SQL1 = 'UPDATE dbo.fnRepairOperation SET Checker = ''%s'', Check_Time = GETDATE() '+
' WHERE Check_Time IS NULL AND Iden = ''%s'''+#13#10;
var
i: Integer;
SqlText, FNCardList: String;
cds_Art: TClientDataSet;
begin
SqlText := '';
//更新进度跟踪记录
FNCardList:= vData[0][4];
while FNCardList[Length(FNCardList)] = ',' do
System.Delete(FNCardList, Length(FNCardList), 1);
FNCardList:='(''' + StringReplace(FNCardList, ',', ''',''', [rfReplaceAll]) + ''')';
if vData[0][0] = 1 then //IsQualityOperator
begin
if vData[0][1] = 0 then //new
SqlText := SqlText + Format(INSERT_REPAIROPERATION_SQL0,[vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][7],vData[0][8],vData[0][9]])
else //edit
SqlText := SqlText + Format(UPDATE_REPAIROPERATION_SQL0,[vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][7],vData[0][8],vData[0][9],vData[0][1]]);
end else
begin
if vData[0][1] = 0 then //new
SqlText := SqlText + Format(INSERT_REPAIROPERATION_SQL1,[vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][7],vData[0][8],vData[0][9],vData[0][9]])
else //edit
SqlText := SqlText + Format(UPDATE_REPAIROPERATION_SQL1,[vData[0][9],vData[0][1]]);
end;
if vData[0][0] <> 1 then
begin
cds_Art:=nil;
try
cds_Art:=TClientDataSet.Create(nil);
cds_Art.Data:=vDataHdr;
SqlText := SqlText + 'DECLARE @Fact_Art_ID Int '#13#10;
with cds_Art do
begin
// David 2014-10-09 修改,某些工艺类型疵点会在打卡时生成工艺,需要进行判断是否已经生成工艺
// 需求42677 制定回修工艺,参考 usp_fnAutoGenerateRepairParas
SqlText := SqlText + 'SET @Fact_Art_ID=-1' + #13#10;
SqlText := SqlText + FORMAT('SELECT TOP 1 @Fact_Art_ID=Fact_Art_ID FROM dbo.fnRepairCardAutoFactArtID WHERE FN_Card=''%s''', [FNCardList]);
SqlText := SqlText + 'IF @Fact_Art_ID>0' + #13#10;
SqlText := SqlText + 'BEGIN'+ #13#10;
// 如果已经生成工艺开始 David
SqlText := SqlText + Format(UPDATE_REPAIR_HDR_SQL, [FieldByName('Operator').AsString, FNCardList]) + #13#10;
SqlText := SqlText + Format(DELETE_REPAIR_DTL_SQL, ['@Fact_Art_ID'])+ #13#10;
// 如果已经生成工艺结束 David
SqlText := SqlText + 'END'+ #13#10;
SqlText := SqlText + 'ELSE'+ #13#10;
SqlText := SqlText + 'BEGIN'+ #13#10;
// 如果没有生成工艺 begin, David
SqlText := SqlText + Format(INSERT_REPAIR_HDR_SQL,[FieldByName('GF_ID').AsString,
FieldByName('Art_Type').AsString,
FieldByName('Material_Quality').AsString,
FieldByName('Operator').AsString,
FieldByName('Remark').AsString]);
SqlText := SqlText + 'SET @Fact_Art_ID =IDENT_CURRENT(''fnFactArtHdr'') '+ #13#10;
// 如果没有生成工艺 end, David
SqlText := SqlText + 'END'+ #13#10;
cds_Art.Data:=vDataDtl;
for i := 0 to RecordCount - 1 do
begin
SqlText:=SqlText + Format(INSERT_REPAIR_DTL_SQL,[FieldByName('Step_NO').AsString,
FieldByName('Operation_Code').AsString,
FieldByName('Item_Name').AsString,
FieldByName('Item_Value').AsString,
FieldByName('Operator').AsString,
FieldByName('Operate_Time').AsString]);
Next;
end;
//加入头(000)尾(999)工序
SqlText:=SqlText + 'EXEC dbo.usp_InsertHeadOperate @Fact_Art_ID ' + #13#10;
end;
finally
FreeAndNil(cds_Art);
end;
end;
if vData[0][0] = 1 then //IsQualityOperator //便于操作班长输入工序时数据提取
SqlText := SqlText + 'UPDATE dbo.fnJobTraceHdr SET Fact_Art_ID = -999 ' +
Format('WHERE FN_Card IN %s '#13#10, [FNCardList])
else
SqlText := SqlText + 'UPDATE fnJobTraceHdr SET FACT_Art_ID = @Fact_Art_ID, Step_NO = 1, Operation_Code = dbo.udf_GetOperationCode(@Fact_Art_ID, 1) '+
Format('WHERE FN_Card IN %s '#13#10, [FNCardList]);
//增加扩展保存回修工艺
if vData[0][0] <> 1 then
SqlText := SqlText + ' EXEC dbo.usp_SaveRepairArtEx @Fact_Art_ID ';
end;
// DAVID CAO ADD FOR TEST END!!}
function TArtDtlInfo.SetAOperateParameterValue(Step_NO :Integer; Item_Name, Item_Value: String): String;
var
sStr, sRemark, sErrorMsg: WideString;
begin
try
if Pos('(', Item_Name) >0 then
Item_Name:=Trim(LeftStr(Item_Name, Pos('(', Item_Name) - 1));
Fcds_ArtDtl.DisableControls;
if Fcds_ArtDtl.Locate('Step_NO;Item_Name', VarArrayOf([Step_NO, Item_Name]), []) then
begin
if Item_Value <> '' then
begin
Item_Value:=RepairItemValue(Fcds_ArtDtl['Operation_Code'], Item_Name, Item_Value);
TestItemValue(Fcds_ArtDtl['Operation_Code'], Item_Name, Item_Value);
end;
//丝光工序,修改碱浓时提醒是否提醒PDM
if pos('碱浓', Item_Name)> 0 then
begin
if MessageDlg('是否提醒技术部', mtWarning, mbYesNoCancel,0)= mrYes then
begin
sRemark := InputBox('修改原因', '请输入原因:','');
sStr := QuotedStr(Fcds_ArtHdr['Art_ID'])+ ','
+ VarToStr(Fcds_ArtDtl['Step_NO'])+ ','
+ VarToStr(Fcds_ArtHdr['GF_ID'])+ ','
+ QuotedStr(Fcds_ArtHdr['GF_NO'])+ ','
+ QuotedStr(Fcds_ArtDtl['Operation_Code'])+ ','
+ QuotedStr(VarToStr(Fcds_ArtDtl['Item_Value']))+ ','
+ QuotedStr(VarToStr(Item_Value))+ ','
+ QuotedStr(Login.LoginID)+ ','
+ QuotedStr(sRemark);
FNMServerArtObj.SaveModifiedArtLog(QuotedStr(sStr), sErrorMsg);
if sErrorMsg<> '' then
raise Exception.CreateRes(@DataError);
end;
end;
Fcds_ArtDtl.Edit;
Fcds_ArtDtl['Item_Value']:=Item_Value;
Fcds_ArtDtl['Operator']:=Login.LoginID;
Fcds_ArtDtl['Operate_Time']:= TGlobal.GetServerTime; //Now; cuijf 2008-6-12
end
else
begin
//cuijf 2008-6-12
sStr := '请检查实际工艺'+ VarToStr(Fcds_ArtHdr['Art_ID'])+ '中该工序"'+Fcds_ArtDtl['Operation_CHN']+'"是否有"内回修"参数';
raise Exception.Create(sStr);
//raise Exception.CreateRes(@DataError);
end;
Result:=Item_Value;
Modify:=true;
finally
Fcds_ArtDtl.EnableControls;
end;
end;
procedure TArtDtlInfo.FillOperationToAListControls(AItem: TStrings);
function GetAOperateDispText(Step_NO: Integer; OldText: String): String;
begin
//Format:=Step_NO+)+Operate_CHN
result:=IntToStr(Step_NO);
result := result + StringOfChar(' ', MAX_OPERATE_STEP_NO_LENGTH - Length(result)) + ')' + OldText;
end;
var
ItemValue, Operation_Name, Operation_Addr: String;
i, RecNO, KeyValue: Integer;
begin
if not Active then exit;
try
AItem.BeginUpdate;
AItem.Clear;
Fcds_ArtDtl.DisableControls;
KeyValue:=-1;
Fcds_ArtDtl.IndexFieldNames:='Step_NO';
Fcds_ArtDtl.First;
for i := 0 to Fcds_ArtDtl.RecordCount - 1 do
begin
if KeyValue = Fcds_ArtDtl.FieldByName('Step_NO').Asinteger then
begin
Fcds_ArtDtl.Next;
continue;
end;
RecNO:=Fcds_ArtDtl.RecNo;
Operation_Addr:='';
KeyValue:=Fcds_ArtDtl.FieldByName('Step_NO').Asinteger;
if Fcds_ArtDtl.Locate('Step_NO;Item_Name', VarArrayOf([KeyValue, '加工地点']), []) then
Operation_Addr:=Format('(%s)', [Fcds_ArtDtl.FieldByName('Item_Value').AsString]);
Fcds_ArtDtl.RecNo := RecNO;
Operation_Name:=Fcds_ArtDtl.FieldByName('Operation_CHN').AsString;
Operation_Name:=Operation_Name + StringOfChar(' ', 10 - Length(Operation_Name));
ItemValue:=GetAOperateDispText(KeyValue, Operation_Name + Operation_Addr);
if Fcds_ArtDtl.FieldByName('OrgStep_NO').IsNull then
ItemValue:=ItemValue + ' *';
if AItem.IndexOfObject(TObject(KeyValue)) = -1 then
AItem.AddObject(ItemValue, TObject(KeyValue));
Fcds_ArtDtl.Next;
end;
finally
Fcds_ArtDtl.IndexFieldNames:='';
Fcds_ArtDtl.EnableControls;
AItem.EndUpdate;
end;
end;
procedure TArtDtlInfo.FillParameterListControls(FillModle: String; AValueListEditor: TValueListEditor);
var
i, StepNO: Integer;
Key, Value,Enum_Value,Data_Unit: String;
begin
AValueListEditor.Strings.Clear;
with Dictionary.cds_OperationDtlList do
begin
Filtered := False;
i:=0; Fcds_ArtDtl.First;
while not Fcds_ArtDtl.Eof do
begin
//取字典等信息
if Locate('Operation_Code;Item_Name',
VarArrayOf([Fcds_ArtDtl.FieldByName('Operation_Code').AsString, Fcds_ArtDtl.FieldByName('Item_Name').AsString]), []) then
begin
Key:=Trim(Fcds_ArtDtl.FieldByName('Item_Name').AsString);
if FillModle = 'Step' then
begin
Key:=Key + {补齐空格}StringOfChar(' ' , (10 - Length(Key)));
{数据单位}
Data_Unit := FieldByName('Data_Unit').AsString;
if Data_Unit<>'' then
Key:=Key + '(' + Data_Unit + ')';
end;
if FillModle = 'ItemName' then
Key:=Key + {补齐空格}StringOfChar(' ' , (10 - Length(Key))) + '(' +
{工序名}FieldByName('Operation_CHN').AsString + ')';
Value:=Fcds_ArtDtl['Item_Value'];{参数取值}
StepNO:=Fcds_ArtDtl['Step_NO']; {工序}
AValueListEditor.Strings.AddObject(Format('%s=%s', [Key, Value]), TObject(StepNO));
Enum_Value := FieldByName(Login.CurrentDepartment+'_Enum_Value').AsString;
//设置编辑样式
with AValueListEditor.ItemProps[i] do //此处不能使用Key, 如果Key相同,会造成错误。
if Enum_Value = 'By Function' then
EditStyle:=esEllipsis
else
begin
if Trim(Fcds_ArtDtl.FieldByName('Item_Name').AsString) = '机台' then
begin
EditStyle:=esPickList;
FillMachineListByOperationCode(Login.CurrentDepartment, Fcds_ArtDtl.FieldByName('Operation_Code').AsString, PickList);
end
else if Length(Enum_Value) <> 0 then
begin
EditStyle:=esPickList;
PickList.Text:=StringReplace(Enum_Value, ',', #13, [rfReplaceAll]);
end;
end;
inc(i);
end;
Fcds_ArtDtl.Next;
end;
end;
end;
procedure TArtDtlInfo.FillAStepToAListControls(Step_NO: Integer; AValueListEditor: TValueListEditor);
begin
try
Fcds_ArtDtl.DisableControls;
Fcds_ArtDtl.Filter:='Step_NO = '''+ IntToStr(Step_NO)+'''';
Fcds_ArtDtl.Filtered:=true;
FillParameterListControls('Step', AValueListEditor);
finally
Fcds_ArtDtl.Filtered:=false;
Fcds_ArtDtl.EnableControls;
end;
end;
procedure TArtDtlInfo.FillAItemToAListControls(ItemName: String; AValueListEditor: TValueListEditor);
begin
try
Fcds_ArtDtl.DisableControls;
Fcds_ArtDtl.Filter:=Format('Item_Name = ''%s''', [ItemName]);
Fcds_ArtDtl.Filtered:=true;
FillParameterListControls('ItemName', AValueListEditor);
finally
Fcds_ArtDtl.Filtered:=false;
Fcds_ArtDtl.EnableControls;
end;
end;
function TArtDtlInfo.GetFieldValue(Index: integer): Variant;
begin
result:='';
if (not Active) or IsEmpty then exit;
result:=Fcds_ArtHdr.Fields.Fields[Index - 1].Value;
if Fcds_ArtHdr.Fields.Fields[Index - 1].IsNull then
begin
result:='';
end
end;
procedure TArtDtlInfo.SetFieldValue(Index: integer; FieldValue: Variant);
begin
if (not Active) or IsEmpty then exit;
if VarCompareValue(Fcds_ArtHdr.Fields.Fields[Index - 1].Value, FieldValue) <> vrEqual then
begin
Fcds_ArtHdr.Edit;
Fcds_ArtHdr.Fields.Fields[Index - 1].Value := FieldValue;
end;
Modify:=true;
end;
function TArtDtlInfo.GetOperations: String;
var
CurStep, i: Integer;
begin
result:='';
if Fcds_ArtDtl.IsEmpty then exit;
Fcds_ArtDtl.First;
CurStep:=Fcds_ArtDtl['Step_NO'];
result:=Fcds_ArtDtl['Operation_Code'] + ',';
for i := 0 to Fcds_ArtDtl.RecordCount - 1 do
begin
if Fcds_ArtDtl['Step_NO'] > CurStep then
begin
CurStep:=Fcds_ArtDtl['Step_NO'];
result:=result + Fcds_ArtDtl['Operation_Code'] + ',';
end;
Fcds_ArtDtl.Next;
end;
end;
{TSTDArtDtlInfo}
procedure TSTDArtDtlInfo.SetOrgDepartment(OrgDepartmentValue: String);
begin
if FOrgDepartment = OrgDepartmentValue then exit;
if not CloseArt then exit;
FOrgDepartment:=OrgDepartmentValue;
end;
procedure TSTDArtDtlInfo.SetOrgArt_ID(OrgArt_IDValue: Integer);
begin
if FOrgArt_ID = OrgArt_IDValue then exit;
FOrgArt_ID:=OrgArt_IDValue;
end;
constructor TSTDArtDtlInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOrgArt_ID:=-1
end;
destructor TSTDArtDtlInfo.Destroy;
begin
inherited Destroy;
end;
procedure TSTDArtDtlInfo.OpenFNSTDArt;
var
sCondition,sErrorMsg: WideString;
vData: OleVariant;
begin
if not CloseArt then exit;
if OrgArt_ID = -1 then
raise Exception.CreateRes(@MSG_InfoDeficiency);
sCondition := IntToStr(OrgArt_ID)+','+QuotedStr('S');
FNMServerObj.GetQueryData(vData,'ARTGetArtInfo',sCondition,sErrorMsg);
// FNMServerArtObj.GetArtDtl(FOrgArt_ID, 'S', vDataHdr, vDataDtl, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetStdArtDtl, [sErrorMsg]);
Fcds_ArtHdr.Data:=vData[0];
Fcds_ArtDtl.Data:=vData[1];
if IsEmpty then
begin
CloseArt;
raise Exception.CreateRes(@EMP_STDArt);
end;
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=false;
end;
procedure TSTDArtDtlInfo.SaveFeedbackInfo;
var
sCondition,sErrorMsg: WideString;
begin
sCondition := IntToStr(GF_ID)+ ','+ QuotedStr(PDARemark) + ','+
QuotedStr(PDMRemark) + ','+ QuotedStr(Login.LoginName) + ','+
QuotedStr(Login.CurrentDepartment);
FNMServerObj.SaveDataBySQL('ARTSaveFeedbackInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveStdArtData, [sErrorMsg]);
ShowMsgDialog(@MSG_SaveStdArtInfoSuccess, mtInformation);
end;
function TSTDArtDtlInfo.SaveArtToDataBase: Boolean;
var
sErrorMsg: WideString;
vDataDtl,vDataParam: OleVariant;
sOperation_code,sItem_value:string;
i:Integer;
sCondition:string;
begin
result := True;
//保存工艺时,未check 那么记录修改了多少次参数 版本为1 表示未check过
if not Fcds_ArtHdr.FieldByName('Art_ID').IsNull then
begin
sOperation_code := '';
sItem_value := '';
with Fcds_ArtDtl do
begin
for i := 0 to RecordCount - 1 do
begin
sCondition :=Fcds_ArtHdr.FieldByName('Art_ID').AsString + ',' +
QuotedStr(FieldByName('operation_code').AsString) + ',' +
QuotedStr(FieldByName('Item_name').AsString) + ',' +
QuotedStr(FieldByName('Item_value').AsString) + ',0';
if (sOperation_code <> QuotedStr(FieldByName('operation_code').AsString))
and (sItem_value <> QuotedStr(FieldByName('Item_value').AsString)) then
begin
FNMServerObj.SaveDataBySQL('SaveParaChange',sCondition,sErrorMsg);
sOperation_code := QuotedStr(FieldByName('operation_code').AsString);
sItem_value := QuotedStr(FieldByName('Item_value').AsString);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog('记录修改出错!',mtError);
Exit;
end;
end;
Next;
end;
end;
end;
if (not Active) or (not Modify) or IsEmpty then exit;
if Assigned(FOnBeforeSave) then FOnBeforeSave(Self);
Fcds_ArtHdr.MergeChangeLog;
Fcds_ArtDtl.MergeChangeLog;
//保存数据
vDataDtl:=Fcds_ArtDtl.Data;
vDataParam := VarArrayOf([GF_ID,
PDARemark,
PDMRemark,
Login.LoginName,
Login.CurrentDepartment]);
FNMServerArtObj.SaveStdArt(Fcds_ArtHdr.Data, vDataDtl,vDataParam,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveStdArtData, [sErrorMsg]);
TempClientDataSet.Data:=vDataDtl;
if Fcds_ArtHdr.FieldByName('Art_ID').IsNull then
begin
Fcds_ArtHdr.Edit;
Fcds_ArtHdr.FieldByName('Art_ID').Value:=TempClientDataSet.Fields.Fields[0].Value;
Fcds_ArtHdr.FieldByName('Version').Value:=0;
end;
result:=true;
Modify:=false;
if Assigned(FOnAfterSave) then FOnAfterSave(Self);
ShowMsgDialog(@MSG_SaveStdArtInfoSuccess, mtInformation);
end;
procedure TSTDArtDtlInfo.CheckStdArt(iType:Integer);
var
sCondition,sErrorMsg: WideString;
vData:OleVariant;
cdsR:TClientDataSet;
begin
//先保存!
if Modify then
SaveArtToDataBase;
if (not Active) or IsEmpty then
raise Exception.CreateRes(@EMP_STDArt);
//保存数据
sCondition := QuotedStr(Art_ID)+','+QuotedStr(Version)+','+QuotedStr(Login.LoginName)+','+
QuotedStr(Login.CurrentDepartment)+','+ IntToStr(iType);
FNMServerObj.GetQueryData(vData,'ARTCheckStdArt',sCondition,sErrorMsg);
if sErrorMsg <> '' then
begin
raise ExceptionEx.CreateResFmt(@SaveCheckArtDataError, [sErrorMsg]);
end;
cdsR := TClientDataSet.Create(nil);
cdsR.Data := vData;
if cdsR.FieldByName('result').AsString = '不做预拉斜客户' then
begin
TMsgDialog.ShowMsgDialog('不做预拉斜客户!', mtWarning);
end;
Fcds_ArtHdr.Edit;
Fcds_ArtHdr.FieldByName('Checker').AsString:=Checker;
Fcds_ArtHdr.FieldByName('Check_Time').AsDateTime:= TGlobal.GetServerTime; //Now; cuijf 2008-6-12
Modify:=false;
if Assigned(FOnAfterSave) then FOnAfterSave(Self);
ShowMsgDialog(@MSG_SaveStdArtCheckInfoSuccess, mtInformation);
end;
procedure TSTDArtDtlInfo.CreateStdArt(OrgGF_ID: Integer; Department, Creator: String);
var
vData: OleVariant;
sErrorMsg: WideString;
begin
if not CloseArt then exit;
try
//构造主表字段
with Fcds_ArtHdr do
begin
FieldDefs.Clear;
FieldDefs.Add('Art_ID', ftInteger);
FieldDefs.Add('GF_ID', ftInteger);
FieldDefs.Add('GF_NO', ftString, 20);
FieldDefs.Add('FN_Art_NO', ftString, 10);
FieldDefs.Add('FN_Color_Code', ftString, 2);
FieldDefs.Add('Shrinkage', ftString, 20);
FieldDefs.Add('HandFeel', ftString, 100);
FieldDefs.Add('Product_Width', ftString, 20);
FieldDefs.Add('Material_Quality', ftString, 10);
FieldDefs.Add('Version', ftSmallint);
FieldDefs.Add('Current_Department', ftString, 2);
FieldDefs.Add('Operator', ftString, 20);
FieldDefs.Add('Operate_Time', ftDateTime);
FieldDefs.Add('Checker', ftString, 20);
FieldDefs.Add('Check_Time', ftDateTime);
FieldDefs.Add('Feedback', ftString, 20);
FieldDefs.Add('Feedback_Time', ftDateTime);
FieldDefs.Add('PDARemark', ftString, 300);
FieldDefs.Add('PDMRemark', ftString, 300);
FieldDefs.Add('Remark', ftString, 150);
FieldDefs.Add('Is_Active', ftBoolean);
CreateDataSet;
Fcds_ArtHdr.Append;
Fcds_ArtHdr['GF_ID']:=OrgGF_ID;
Fcds_ArtHdr['Version']:=-1;
Fcds_ArtHdr['Current_Department']:=Department;
Fcds_ArtHdr['Operator']:=Creator;
Fcds_ArtHdr['Operate_Time']:= TGlobal.GetServerTime; //Now; cuijf 2008-6-12
Fcds_ArtHdr['Is_Active']:=true;
//取已经存在的通用的工艺要求
FNMServerArtObj.GetArtItemInfo(OrgGF_ID, vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetArtItemInfo, [sErrorMsg]);
TempClientDataSet.Data:=vData;
if not TempClientDataSet.IsEmpty then
begin
Fcds_ArtHdr['FN_Art_NO']:=TempClientDataSet['FN_Art_NO'];
Fcds_ArtHdr['FN_Color_Code']:=TempClientDataSet['FN_Color_Code'];
Fcds_ArtHdr['Shrinkage']:=TempClientDataSet['Shrinkage'];
Fcds_ArtHdr['HandFeel']:=TempClientDataSet['HandFeel'];
Fcds_ArtHdr['Product_Width']:=TempClientDataSet['Product_Width'];
end
end;
//自动创建工艺步骤和参数
FNMServerArtObj.AutoCreateStdArtDtl(IntToStr(OrgGF_ID), Department, vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_AutoCreateStdArtDtl, [sErrorMsg]);
Fcds_ArtDtl.Data:=vData;
except
on e: Exception do
begin
Fcds_ArtHdr.Close;
Fcds_ArtDtl.Close;
ShowMessage(sErrorMsg);
end;
end;
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=false;
end;
procedure TSTDArtDtlInfo.CopyAExistSTDArt(StdArtID: Integer);
var
MessResult: Integer;
sCondition, sErrorMsg: WideString;
vData:OleVariant;
begin
//工艺没打开不能拷贝
if not Active then
exit;
if not Fcds_ArtDtl.IsEmpty then
begin
MessResult:= ShowMsgDialog(@MSG_ClearCurOperate, mtConfirmation);
if MessResult <> mrOk then exit;
end;
sCondition := IntToStr(StdArtID)+','+QuotedStr('S');
FNMServerObj.GetQueryData(vData,'ARTGetArtInfo',sCondition,sErrorMsg);
// FNMServerArtObj.GetArtDtl(StdArtID, 'S', vDataHdr, vDataDtl, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetStdArtDtl, [sErrorMsg]);
TempClientDataSet.Data:=vData[0];
if TempClientDataSet.IsEmpty then
raise Exception.CreateRes(@EMP_StdArtInfoDtlCantCopy);
Fcds_ArtHdr.Edit;
//只拷贝工艺号
{
Fcds_ArtHdr['FN_Art_NO']:=LeftStr(TempClientDataSet['FN_Art_NO'], 1);
Fcds_ArtHdr['FN_Color_Code']:=TempClientDataSet['FN_Color_Code'];
Fcds_ArtHdr['Shrinkage']:=TempClientDataSet['Shrinkage'];
Fcds_ArtHdr['HandFeel']:=TempClientDataSet['HandFeel'];
Fcds_ArtHdr['Product_Width']:=TempClientDataSet['Product_Width'];
Fcds_ArtHdr['Material_Quality']:=TempClientDataSet['Material_Quality'];
}
Fcds_ArtHdr['Remark']:=TempClientDataSet['Remark'];
Fcds_ArtDtl.Data:=vData[1];
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=True;
end;
procedure TSTDArtDtlInfo.InitializeDepartmentMenuItem(MenuItem: TMenuItem; ClickEvent: TNotifyEvent);
var
i: Integer;
NewMenuItem: TMenuItem;
begin
with Dictionary.cds_DepartmentList do
try
Filter:='Parent_Department = ' + '''FN''';
Filtered:=true;
for i := 0 to RecordCount - 1 do
begin
NewMenuItem:=TMenuItem.Create(MenuItem.Owner);
NewMenuItem.Caption:=Trim(FieldByName('Description').AsString)+'工艺(&'+
RightStr(Trim(FieldByName('Department').AsString),1)+')';
NewMenuItem.Tag:=FieldByName('Iden').AsInteger;
NewMenuItem.OnClick:=ClickEvent;
MenuItem.Add(NewMenuItem);
Next;
end;
finally
Filtered:=false;
end;
end;
function TSTDArtDtlInfo.GetFeedbackInfo: OleVariant;
var
sErrorMsg: WideString;
begin
FNMServerArtObj.GetFeedbackInfo(Result, GF_ID,Current_Department, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetStdArtDtl, [sErrorMsg]);
end;
function TSTDArtDtlInfo.ViewArtDtl(Index: integer): string;
var
Step_NO,ParamStr: String;
begin
Step_NO := '';
ParamStr := '';
with Fcds_ArtDtl do
begin
Filtered := False;
First;
while not Eof do
begin
if Step_NO <> FieldByName('Step_NO').AsString then
begin
if ParamStr<>'' then
Result := Result + ParamStr;
if (Result <> '') then
Result := Result + #10#13;
Step_NO := FieldByName('Step_NO').AsString;
ParamStr := '';
end;
if Trim(FieldByName('Item_Name').AsString) = '加工地点' then
begin
if StrToInt(Step_NO) < 9 then
Step_NO := '0' + Step_NO;
Result := Result + Step_NO + '【'+ FieldByName('Item_Value').AsString+'】'+ FieldByName('Operation_CHN').AsString + ': '
end else
begin
if Index = 0 then
begin
if (Trim(FieldByName('Item_Value').AsString)<>'') then
ParamStr := ParamStr + FieldByName('Item_Name').AsString +':' +FieldByName('Item_Value').AsString +' ';
end
else if Index = 1 then
begin
if (Trim(FieldByName('Item_Value').AsString)='') then
ParamStr := ParamStr + FieldByName('Item_Name').AsString +' ';
end
else
ParamStr := ParamStr + FieldByName('Item_Name').AsString +':' +FieldByName('Item_Value').AsString +' ';
end;
Next;
end;
if ParamStr<>'' then
Result := Result + ParamStr;
end;
end;
{TFactArtDtlInfo}
procedure TFactArtDtlInfo.SetFACT_Art_ID(FACT_Art_IDValue: Integer);
begin
if FFACT_Art_ID = FACT_Art_IDValue then exit;
if not CloseArt then exit;
FFACT_Art_ID:=FACT_Art_IDValue;
end;
constructor TFactArtDtlInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInternal_Repair := False;
FAsSTDArt := False;
Fcds_JobTraceDtl:=TClientDataSet.Create(AOwner);
end;
destructor TFactArtDtlInfo.Destroy;
begin
Fcds_JobTraceDtl.Destroy;
inherited Destroy;
end;
procedure TFactArtDtlInfo.OpenFNArt;
var
sCondition,sErrorMsg: WideString;
vData: OleVariant;
begin
if not CloseArt then exit;
if FACT_Art_ID = -1 then
raise Exception.CreateRes(@InvalidFACT_Art_ID);
FCardList:='';
sCondition := IntToStr(FACT_Art_ID)+','+QuotedStr('F');
FNMServerObj.GetQueryData(vData,'ARTGetArtInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetFactArtDtl, [sErrorMsg]);
Fcds_ArtHdr.Data:=vData[0];
Fcds_ArtDtl.Data:=vData[1];
//luwel
org_Fcds_ArtDtl := Fcds_ArtDtl;
if Fcds_ArtHdr.IsEmpty then
begin
CloseArt;
raise Exception.CreateRes(@FactArtEmpty);
end;
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=false;
end;
function TFactArtDtlInfo.SaveArtToDataBase: Boolean;
var
sJobIden,sJobStepNO, sErrorMsg: WideString;
vDataParam: Variant;
i: Integer;
CurStepNO:Integer;
OperationListt: string;
begin
result := True;
if (not Active) or (not Modify) or IsEmpty then exit;
if Assigned(FOnBeforeSave) then FOnBeforeSave(Self);
if FCardList = '' then
raise Exception.Create('WAR_工艺卡号数据出错,请联系程序员');
if (not Internal_Repair) and (RepairSteps <> '') and (RepairReason = '') then
raise Exception.Create('WAR_工艺自定回修工序时,请选择回修原因');
OperationListt:='';
CurStepNO:=1;
while Fcds_ArtDtl.Locate('Step_NO', CurStepNO, []) do
begin
OperationListt:=OperationListt + Fcds_ArtDtl.FieldByName('Operation_Code').AsString + ',';
Inc(CurStepNO)
end;
//判断工序步骤是否违反禁忌
FNMServerArtObj.GetCheckSpecialArt(GF_ID, Pos('F', FCardList), OperationListt, Login.CurrentDepartment, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetCheckSpecialArt, [sErrorMsg]);
//参数
sJobIden :='';
sJobStepNO := '';
with Fcds_JobTraceDtl do
for I := 0 to RecordCount - 1 do
begin
sJobIden := sJobIden + Fcds_JobTraceDtl.FieldByName('Iden').AsString + ',';
sJobStepNO := sJobStepNO + Fcds_JobTraceDtl.FieldByName('Step_NO').AsString + ',';
next;
end;
vDataParam := VarArrayOf([Login.LoginName,
CardList,
RepairSteps,
IfThen(Internal_Repair,'1','0'),
RepairReason,
sJobIden,
sJobStepNO,
IfThen(AsStdArt,'1','0')]);
//保存工艺
FNMServerArtObj.SaveFactArt(Fcds_ArtHdr.Data, Fcds_ArtDtl.Data, vDataParam, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveFactArtData, [sErrorMsg]);
//合并数据集合
Fcds_ArtHdr.MergeChangeLog;
Fcds_ArtDtl.MergeChangeLog;
result:=true;
FRepairReason:='';
FInternal_Repair:=False;
FAsSTDArt := False;
if Assigned(FOnAfterSave) then FOnAfterSave(Self);
Modify:=false;
ShowMsgDialog(@MSG_SaveFactArtDtlInfoSuccess, mtInformation);
end;
function TFactArtDtlInfo.GetJobTraceDtlInfo(SelectCardList: String;
SelectStepNO: Integer): Boolean;
var
vData: OleVariant;
sErrorMsg: WideString;
begin
FNMServerArtObj.GetUnFinishJobTraceDtl(SelectCardList, SelectStepNO, vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetUnFinishJobTraceDtl, [sErrorMsg]);
Fcds_JobTraceDtl.Data:= vData;
result := True;
end;
procedure TFactArtDtlInfo.UpdateAStepNO(OldStepNO: Integer;
OperateOffset: TOperateOffset);
var
i: Integer;
begin
with Fcds_JobTraceDtl do
if (not Active) or (IsEmpty) then exit;
with Fcds_JobTraceDtl do
case OperateOffset of
ooMoveUP:
begin
First;
for I := 0 to RecordCount - 1 do
begin
Edit;
if Fcds_JobTraceDtl['Step_NO'] = OldStepNO then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := OldStepNO - 1;
end
else if Fcds_JobTraceDtl['Step_NO'] = OldStepNO - 1 then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := OldStepNO;
end;
Next;
end;
end;
ooMoveDown:
begin
First;
for I := 0 to RecordCount - 1 do
begin
if Fcds_JobTraceDtl['Step_NO'] = OldStepNO then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := OldStepNO + 1
end
else if Fcds_JobTraceDtl['Step_NO'] = OldStepNO + 1 then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := OldStepNO;
end;
Next;
end;
end;
ooDelete:
begin
Last;
for I := RecordCount - 1 downto 0 do
begin
if Fcds_JobTraceDtl['Step_NO'] = OldStepNO then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := -1;
end
else if Fcds_JobTraceDtl['Step_NO'] > OldStepNO then
begin
Edit;
Fcds_JobTraceDtl['Step_NO'] := Fcds_JobTraceDtl['Step_NO'] - 1;
end;
Next;
end
end;
end;
Fcds_JobTraceDtl.MergeChangeLog;
end;
function TFactArtDtlInfo.GetRepairSteps: String;
begin
Result:='';
Fcds_ArtDtl.Filter:='OrgStep_NO IS NULL AND NOT(Operation_CHN LIKE ''%复版'')';
Fcds_ArtDtl.Filtered:=True;
try
if Fcds_ArtDtl.RecordCount <> 0 then
begin
Fcds_ArtDtl.Filter:='OrgStep_NO IS NULL';
Result:=GetOperations;
end;
finally
Fcds_ArtDtl.Filter:='';
Fcds_ArtDtl.Filtered:=False;
end;
end;
{TRepairArtDtlInfo}
procedure TRepairArtDtlInfo.CreateRepairArt(RepairIden, GF_ID: Integer; SelectCard: string; CurrentDeparment, Operator: String);
var
vData: OleVariant;
sCondition,sErrorMsg: WideString;
begin
if not CloseArt then exit;
sCondition := IntToStr(RepairIden)+','+IntToStr(GF_ID)+','+ QuotedStr(SelectCard)+','+ QuotedStr(CurrentDeparment)+','+ QuotedStr(Operator);
FNMServerObj.GetQueryData(vData,'ARTCreateRepairArtInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetStdArtDtl, [sErrorMsg]);
Fcds_ArtHdr.Data:=vData[0];
Fcds_ArtDtl.Data:=vData[1];
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetUnFinishJobTraceDtl, [sErrorMsg]);
if IsEmpty then
begin
CloseArt;
raise Exception.CreateRes(@EMP_STDArt);
end;
CardList:='';
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=false;
end;
function TRepairArtDtlInfo.SaveArtToDataBase(IsQualityOperator:Boolean; RepairIden :Integer; GF_ID:Integer; Quantity: Double; Repair_Code,Current_Department,Operator :string) : Boolean;
var
vData: OleVariant;
QualityOperator,CurStepNO: Integer;
OperationListt,sErrorMsg: WideString;
begin
result := True;
if (not Active) or (not Modify) or IsEmpty then exit;
if Assigned(FOnBeforeSave) then FOnBeforeSave(Self);
if CardList = '' then exit;
if Pos(',', CardList) > 0 then
CardList := Copy(CardList,1,Length(CardList)-1);
OperationListt:='';
CurStepNO:=1;
while Fcds_ArtDtl.Locate('Step_NO', CurStepNO, []) do
begin
OperationListt:=OperationListt + Fcds_ArtDtl.FieldByName('Operation_Code').AsString + '/';
Inc(CurStepNO)
end;
//判断工序步骤是否违反禁忌
FNMServerArtObj.GetCheckSpecialArt(GF_ID, 1, OperationListt, Login.CurrentDepartment, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetCheckSpecialArt, [sErrorMsg]);
if OperationListt = '' then exit;
QualityOperator := 0;
if IsQualityOperator then
QualityOperator := 1;
vData := VarArrayCreate([0, 1], VarVariant);
vData[0] := varArrayOf([QualityOperator,
RepairIden,
GF_ID,
Quantity,
CardList,
Repair_Code,
1,
OperationListt,
Current_Department,
Operator]);
Fcds_ArtHdr.MergeChangeLog;
Fcds_ArtDtl.MergeChangeLog;
//保存数据
FNMServerArtObj.SaveRepairArt(vData,Fcds_ArtHdr.Data, Fcds_ArtDtl.Data, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveRepairArtData, [sErrorMsg]);
// David Cao add for 42677 制定回修工艺 IsQualityOperator 质量员给定工序后自动生成工艺
if IsQualityOperator then
FNMServerObj.SaveDataBySQL('AutoGeneRepairParas',QuotedStr(CardList), sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveRepairArtData, [sErrorMsg]);
if Assigned(FOnAfterSave) then FOnAfterSave(Self);
result:=true;
Modify:=false;
ShowMsgDialog(@MSG_SaveRepairArtDtlSuccess, mtInformation);
end;
{ THLArtDtlInfo }
procedure THLArtDtlInfo.CreateHLArt(FN_ID, FN_NO, Creator: String);
begin
if not CloseArt then exit;
//构造主表字段
with Fcds_ArtHdr do
begin
FieldDefs.Clear;
FieldDefs.Add('FN_ID', ftString, 9);
FieldDefs.Add('FN_NO', ftString, 9);
FieldDefs.Add('Art_ID', ftInteger);
FieldDefs.Add('FN_Art_NO', ftString, 10);
FieldDefs.Add('Art_Type', ftString, 1);
FieldDefs.Add('Material_Quality', ftString, 10);
FieldDefs.Add('Operator', ftString, 20);
FieldDefs.Add('Operate_Time', ftDateTime);
FieldDefs.Add('Remark', ftString, 150);
CreateDataSet;
Fcds_ArtHdr.AppendRecord([FN_ID, FN_NO, nil, nil, 'H', '手织版', Creator, TGlobal.GetServerTime, nil]);
end;
//构造从表字段
with Fcds_ArtDtl do
begin
FieldDefs.Clear;
FieldDefs.Add('Step_NO', ftSmallint);
FieldDefs.Add('EditStep_NO', ftSmallint);
FieldDefs.Add('Operation_Code', ftString, 3);
FieldDefs.Add('Operation_CHN', ftString, 20);
FieldDefs.Add('Item_Name', ftString, 10);
FieldDefs.Add('Item_Value', ftString, 50);
FieldDefs.Add('Operator', ftString, 20);
FieldDefs.Add('Operate_Time', ftDateTime);
FieldDefs.Add('OrgStep_NO', ftSmallint);
CreateDataSet;
end;
if Assigned(FOnAfterOpen) then FOnAfterOpen(Self);
Modify:=true;
end;
function THLArtDtlInfo.SaveArtToDataBase: Boolean;
var
vDataDtl: OleVariant;
sErrorMsg: WideString;
begin
result := True;
if (not Active) or (not Modify) or IsEmpty then exit;
if Assigned(FOnBeforeSave) then FOnBeforeSave(Self);
Fcds_ArtHdr.MergeChangeLog;
Fcds_ArtDtl.MergeChangeLog;
//保存数据
vDataDtl:=Fcds_ArtDtl.Data;
FNMServerArtObj.SaveHLArtInfo(Login.CurrentDepartment, Fcds_ArtHdr.Data, vDataDtl, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveHLArtInfo, [sErrorMsg]);
TempClientDataSet.Data:=vDataDtl;
Fcds_ArtHdr.Edit;
Fcds_ArtHdr['Art_ID']:=TempClientDataSet['Fact_Art_ID'];
result:=true;
Modify:=false;
if Assigned(FOnAfterSave) then FOnAfterSave(Self);
ShowMsgDialog(@MSG_SaveHLArtInfoSuccess, mtInformation);
end;
end.
|
unit ulngTranslator;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, Menus, ActnList;
type
{ TfrmLangTranslator }
TfrmLangTranslator = class(TForm)
aabrir: TAction;
aguardar: TAction;
aunir: TAction;
acopiar: TAction;
apegar: TAction;
ActionList1: TActionList;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
Label1: TLabel;
MainMenu1: TMainMenu;
Memo1: TMemo;
Memo2: TMemo;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
MenuItem5: TMenuItem;
MenuItem6: TMenuItem;
MenuItem7: TMenuItem;
MenuItem8: TMenuItem;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
SaveDialog1: TSaveDialog;
Splitter1: TSplitter;
procedure aabrirExecute(Sender: TObject);
procedure aguardarExecute(Sender: TObject);
procedure aunirExecute(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure MenuItem4Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmLangTranslator: TfrmLangTranslator;
resourcestring
LNG_MESSAGE_HELP_TRANSLATOR = 'Abre el archivo .po a traducir.\nCopia el cotenido al portapapeles.\n'+
'Pégalo en tu traductor favorito y tradúcelo.\nCopia el texto traducido y pégalo en el cuadro de abajo.\n'+
'Pulsa Unir.\nEscribe las dos siglas del idioma destino.\nFinalmente guarda el archivo.';
LNG_MESSAGE_CORRECT_JOIN = 'Archivo Juntado Correctamente';
LNG_MESSAGE_SAVED = 'Archivo Guardado Correctamente';
implementation
{$R *.lfm}
{ TfrmLangTranslator }
procedure TfrmLangTranslator.Button1Click(Sender: TObject);
begin
ShowMessage(LNG_MESSAGE_HELP_TRANSLATOR);
end;
procedure TfrmLangTranslator.Button2Click(Sender: TObject);
begin
aunir.Execute;
end;
procedure TfrmLangTranslator.Button3Click(Sender: TObject);
begin
aguardar.Execute;
end;
procedure TfrmLangTranslator.FormCreate(Sender: TObject);
begin
memo1.Lines.LoadFromFile('languages'+DirectorySeparator+'fpg-editor.po');
end;
procedure TfrmLangTranslator.Memo1Change(Sender: TObject);
begin
end;
procedure TfrmLangTranslator.MenuItem4Click(Sender: TObject);
begin
Close;
end;
procedure TfrmLangTranslator.aabrirExecute(Sender: TObject);
begin
if OpenDialog1.Execute then
Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
end;
procedure TfrmLangTranslator.aguardarExecute(Sender: TObject);
var
filename : String;
begin
//'languages'+DirectorySeparator+
filename := 'fpg-editor.' + Edit1.Text + '.po';
SaveDialog1.FileName:=filename;
if SaveDialog1.Execute then
begin
Memo1.Lines.SaveToFile(SaveDialog1.FileName);
ShowMessage(LNG_MESSAGE_SAVED);
end;
end;
procedure TfrmLangTranslator.aunirExecute(Sender: TObject);
var
j : Integer;
tmpline :string;
begin
memo1.Enabled:=false;
memo2.Enabled:=false;
for j := memo1.Lines.Count-1 downto 0 do
begin
tmpline := memo1.Lines.Strings[j];
if AnsiPos(tmpline,'msgid "') > -1 then
begin
if memo2.Lines.Strings[j+1] = 'msgstr ""' then
memo1.Lines.Strings[j+1]:=memo2.Lines.Strings[j];
end;
end;
ShowMessage(LNG_MESSAGE_CORRECT_JOIN);
memo1.Enabled:=true;
memo2.Enabled:=true;
end;
// ISO 639-1 pt
// http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
end.
|
unit misc_utils;
interface
uses Classes, SysUtils, GlobalVars, Forms;
{Miscellaneous help routines}
Type
TStringParser=class(TStringList)
Procedure ParseString(var s:STring);
end;
TMsgType=(mt_info,mt_warning,mt_error); {Message Types for PanMessage() }
Function MsgBox(Txt, Caption:String;flags:Integer):Integer;
Function GetWord(const s:string;p:integer;var w:string):integer;
Function GetWordN(const s:String;n:integer):String;
Function PGetWord(ps:Pchar;pw:Pchar):Pchar; {Same thing, but for PChar strings}
Function StrToDouble(const s:String):Double;
Function StrToLongInt(const s:String):Longint;
Function HexToDword(const s:String):Longint;
Function StrToDword(const s:String):Longint;
Function DwordToStr(d:Longint):String;
Function PScanf(ps:pchar;const format:String;const Vals:array of pointer):boolean;
Function SScanf(const s:string;const format:String;const Vals:array of pointer):boolean;
Procedure PanMessage(mt:TMsgType; const msg:String);
Function Real_Min(a,b:Double):Double;
Function Real_Max(a,b:Double):Double;
Function RoundTo2Dec(d:Double):Double; {Rounds to 2 decimal points}
{handles the number -2147483648 ($80000000) properly.
for some reason, StrToInt gets confused by it}
Function ValInt(const s:String;var i:Integer):Boolean;
Function ValHex(const s:String;var h:LongInt):Boolean;
Function ValDword(const s:String; var d:LongInt):Boolean;
Function ValDouble(const s:String; var d:Double):Boolean;
Procedure RemoveComment(var s:String);
Procedure GetFormPos(f:TForm;var wpos:TWinPos);
Procedure SetFormPos(f:TForm;const wpos:TWinPos);
Procedure SizeFromToFit(f:TForm);
Function ScanForSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
Function ScanForNonSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
Function FindLMDataFile(const Name:string):String;
implementation
uses MsgWindow, Windows;
Function FindLMDataFile(const Name:string):String;
begin
if ProjectDir<>'' then
begin
Result:=ProjectDir+Name;
if FileExists(Result) then exit;
end;
Result:=BaseDir+Name;
if FileExists(Result) then exit;
Result:=BaseDir+'LMDATA\'+Name;
end;
Function ScanForSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
begin
if p<0 then {backwards}
begin
p:=-p;
while (p>1) and not (s[p] in [' ',#9]) do dec(p);
Result:=p;
end else
begin
While (p<=length(s)) and not (s[p] in [' ',#9]) do inc(p);
Result:=p;
end;
end;
Function ScanForNonSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
begin
if p<0 then {backwards}
begin
p:=-p;
while (p>1) and (s[p] in [' ',#9]) do dec(p);
Result:=p;
end else
begin
While (p<=length(s)) and (s[p] in [' ',#9]) do inc(p);
Result:=p;
end;
end;
Function GetWordN(const s:String;n:integer):String;
var i,p:Integer;
begin
p:=1;
for i:=1 to n do
begin
p:=ScanForNonSpace(s,p);
if i<>n then p:=ScanForSpace(s,p);
end;
i:=ScanForSpace(s,p);
Result:=UpperCase(Copy(s,p,i-p));
end;
Procedure RemoveComment(var s:String);
var p:integer;
begin
p:=Pos('#',s);
if p<>0 then SetLength(s,p-1);
end;
Function Real_Min(a,b:Double):Double;
begin
if a>b then result:=b else result:=a;
end;
Function Real_Max(a,b:Double):Double;
begin
if a>b then result:=a else result:=b;
end;
Function RoundTo2Dec(d:Double):Double;
begin
Result:=Round(d*100)/100;
end;
Function StrToDouble(const s:String):Double;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val(s,Result,a);
if a<>0 then raise EConvertError.Create('Invalid number: '+s);
end;
Function StrToLongInt(const s:String):Longint;
var a:Integer;
begin
Val(s,Result,a);
end;
Function HexToDword(const s:String):Longint;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val('$'+s,Result,a);
end;
Function ValInt(const s:String;var i:Integer):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin i:=0; exit; end;
Val(s,i,a);
Result:=a=0;
end;
Function ValHex(const s:String;var h:LongInt):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin h:=0; exit; end;
Val('$'+s,h,a);
Result:=a=0;
end;
Function ValDword(const s:String; var d:LongInt):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin d:=0; exit; end;
Val(s,d,a);
if a=10 then
if s[10] in ['0'..'9'] then
begin
d:=d*10+(ord(s[10])-ord('0'));
a:=0;
end;
Result:=not ((a<>0) and (s[a]<>#0));
end;
Function ValDouble(const s:String; var d:Double):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin d:=0; exit; end;
Val(s,d,a);
Result:=a=0;
end;
Function StrToDword(const s:String):Longint;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val(s,Result,a);
if a=10 then
if s[10] in ['0'..'9'] then
begin
Result:=Result*10+(ord(s[10])-ord('0'));
a:=0;
end;
if (a<>0) and (s[a]<>#0)
then Raise EConvertError.Create(s+' is not a valid number');
end;
Function DwordToStr(d:Longint):String;
var c:Char;
a:Integer;
begin
if d>=0 then Str(d,Result)
else {32th bit set}
begin
asm {Divides D by 10 treating it as unsigned integer}
Mov eax,d
xor edx,edx
mov ecx,10
Div ecx
add dl,'0'
mov c,dl
mov d,eax
end;
Str(d,Result); Result:=Result+c;
end
end;
Function MsgBox(Txt, Caption:String;flags:Integer):Integer;
begin
Result:=Application.MessageBox(Pchar(Txt),Pchar(Caption),flags);
end;
Function GetWord(const s:string;p:integer;var w:string):integer;
var b,e:integer;
begin
if s='' then begin w:=''; result:=1; exit; end;
b:=p;
While (s[b] in [' ',#9]) and (b<=length(s)) do inc(b);
e:=b;
While (not (s[e] in [' ',#9])) and (e<=length(s)) do inc(e);
w:=Copy(s,b,e-b);
GetWord:=e;
end;
Function PGetWord(ps:Pchar;pw:Pchar):Pchar;
var pb,pe:PChar;
begin
if ps^=#0 then begin pw^:=#0; result:=ps; exit; end;
pb:=ps;
while pb^ in [' ',#9] do inc(pb);
pe:=pb;
while not (pe^ in [' ',#9,#0]) do inc(pe);
StrLCopy(pw,pb,pe-pb);
Result:=pe;
end;
Function PScanf(ps:pchar;const format:String;const Vals:array of pointer):boolean;
var pp, {position of % in format string}
pb, {beginning of the prefix}
pv, {position of the value}
pe, {end of the prefix}
pf:Pchar;
tmp:array[0..99] of char;
ptmp:Pchar;
Len:Integer; {Lenth of prefix string}
a, {Dummy variable for Val()}
nval:Integer; {Index in vals[] array}
lastdigit,dw:Dword;
c:Char;
begin
Result:=true;
nval:=0;
pf:=PChar(format);
Repeat
pp:=StrScan(pf,'%'); if pp=nil then break;
pb:=pf;
while (pb^ in [' ',#9]) and (pb<pp) do inc(pb);
if pp=pb then
begin
Len:=0; pv:=ps;
end
else
begin
pe:=pp-1;
while (pe^ in [' ',#9]) and (pe>pb) do dec(pe);
len:=pe-pb+1;
StrLCopy(tmp,pb,len);
pv:=StrPos(ps,tmp);
if pv=nil then begin pf:=pp+1; if pf^<>#0 then inc(pf); inc(nval); continue; end;
pv:=pv+len;
end;
ptmp:=@tmp[1];
ps:=PGetWord(pv,ptmp);
inc(pp); a:=0;
case pp^ of {format specifier}
'd','D': Val(Ptmp,Integer(Vals[nval]^),a);
'u','U': begin
Val(PTmp,dw,a);
if a<>0 then
begin
c:=(Ptmp+a-1)^;
if c in ['0'..'9'] then
begin
lastdigit:=Ord(c)-Ord('0');
dw:=dw*10+lastdigit;
a:=0;
end;
end;
Dword(Vals[nval]^):=dw;
end;
'f','F': Val(Ptmp,Double(Vals[nval]^),a);
'b','B': Val(Ptmp,byte(Vals[nval]^),a);
'c','C': Char(Vals[nval]^):=Ptmp^;
's','S': String(Vals[nval]^):=ptmp;
'x','X': begin
tmp[0]:='$';
Val(tmp,Integer(Vals[nval]^),a);
end;
else a:=1;
end;
if a<>0 then result:=false;
pf:=pp; if pf^<>#0 then inc(pf);
inc(nval);
until false;
end;
Function SScanf(const s:string;const format:String;const Vals:array of pointer):boolean;
begin
Result:=pScanf(PChar(s),format,vals);
end;
Procedure TStringParser.ParseString(var s:STring);
var cpos:Word;w:String;
begin
Clear;
cpos:=1;
While Cpos<Length(s) do
begin
cPos:=GetWord(s,cpos,w);
Add(UpperCase(w));
end;
end;
Procedure PanMessage(mt:TMsgType; const msg:String);
begin
case mt of
mt_info: if sm_ShowInfo then MsgForm.AddMessage('Info: '+msg);
mt_warning: if sm_ShowWarnings then MsgForm.AddMessage('Warning: '+msg);
mt_error: begin
MsgBox(Msg,'Error',mb_OK);
MsgForm.AddMessage('Error: '+msg);
end;
end;
end;
Function StrToDoubleDef(const s:String;def:Double):Double;
var a:Integer;
begin
Val(s,result,a);
if a<>0 then Result:=def;
end;
Procedure GetFormPos(f:TForm;var wpos:TWinPos);
begin
With WPos,f do
begin
Wwidth:=width;
Wheight:=height;
Wtop:=top;
Wleft:=left;
end;
end;
Procedure SetFormPos(f:TForm;const wpos:TWinPos);
begin
if WPos.WWidth=0 then exit;
With WPos do
F.SetBounds(Wleft,Wtop,Wwidth,Wheight);
end;
Procedure SizeFromToFit(f:TForm);
var xmin,xmax,ymin,ymax:integer;
begin
end;
end.
|
unit UPessoasVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UCnaeVO, UCidadeVO, UEstadoVO, UPaisVO;
type
[TEntity]
[TTable('Pessoa')]
TPessoasVO = class(TGenericVO)
private
FidPessoa: Integer;
FcpfCnpj: String;
Fnome: String;
Fcep: String;
FEndereco: String;
Fnumero: String;
Fcomplemento: String;
Fbairro: String;
Femail: String;
FtelefoneI: String;
FtelefoneII: String;
FidCnae: integer;
FIdCidade : integer;
FidEstado : integer;
FidPais : integer;
public
CnaeVO: TCNAEVO;
CidadeVO : TCidadeVO;
EstadoVO : TEstadoVO;
PaisVO : TPaisVO;
[TId('idpessoa')]
[TGeneratedValue(sAuto)]
property idPessoa: Integer read FidPessoa write FidPessoa;
[TColumn('cpfCnpj','Cpf / Cnpj',130,[ldGrid,ldLookup,ldComboBox], False)]
property Cnpjcpf: String read FcpfCnpj write FcpfCnpj;
[TColumn('nome','Nome',250,[ldGrid,ldLookup,ldComboBox], False)]
property nome : String read Fnome write Fnome;
[TColumn('cep','CEP',80,[ldLookup,ldComboBox], False)]
property Cep: String read FCep write FCep;
[TColumn('endereco','Rua',250,[ldLookup,ldComboBox], False)]
property Endereco: String read FEndereco write FEndereco;
[TColumn('numero','numero',50,[ldLookup,ldComboBox], False)]
property Numero: String read FNumero write FNumero;
[TColumn('complemento','complemento',250,[ldLookup,ldComboBox], False)]
property Complemento: String read FComplemento write FComplemento;
[TColumn('bairro','bairro',250,[ldLookup,ldComboBox], False)]
property Bairro: String read FBairro write FBairro;
[TColumn('email','Email',200,[ldGrid,ldLookup,ldComboBox], False)]
property Email: String read FEmail write FEmail;
[TColumn('telefoneI','Tel I',100,[ldGrid,ldLookup,ldComboBox], False)]
[TFormatter(ftTelefone, taLeftJustify)]
property TelefoneI: String read FtelefoneI write FtelefoneI;
[TColumn('telefoneII','Tel II',15,[ldLookup,ldComboBox], False)]
[TFormatter(ftTelefone, taLeftJustify)]
property TelefoneII: String read FTelefoneII write FtelefoneII;
[TColumn('idCnae','idCnae',0,[ldLookup,ldComboBox], False)]
property idCnae: integer read FIdCnae write FIdCnae;
[TColumn('idCidade','idCidade',0,[ldLookup,ldComboBox], False)]
property idCidade: integer read FIdCidade write FIdCidade;
[TColumn('idEstado','idEstado',0,[ldLookup,ldComboBox], False)]
property idEstado: integer read FidEstado write FidEstado;
[TColumn('idPais','idPais',0,[ldLookup,ldComboBox], False)]
property idPais: integer read FidPais write FidPais;
procedure ValidarCampos;
Function ValidaCPF(xCPF: String): Boolean;
Function ValidaCNPJ(xCNPJ: String): Boolean;
Function MascaraCnpjCpf(Str: String): String;
end;
implementation
{ TPessoasVO }
procedure TPessoasVO.ValidarCampos;
begin
if (Self.FcpfCnpj = '') then
raise Exception.Create('O campo Cnpj / Cpf é obrigatório!');
if (Self.Fnome = '') then
raise Exception.Create('O campo Nome é obrigatório!');
if ((length(self.FcpfCnpj)) <= 11) then
begin
if(Self.ValidaCPF(self.FcpfCnpj)=false)then
begin
raise Exception.Create('CPF Inválido');
end;
end
else if (length(self.FcpfCnpj) >= 14) then
begin
if(Self.ValidaCnpj(self.FcpfCnpj)=false)then
begin
raise Exception.Create('CNPJ Inválido');
end;
end;
end;
function TPessoasVO.MascaraCnpjCpf(Str: String): String;
begin
if Length(Str)=11 then
Result:='999.999.999-99;0; '
else
if Length(Str)=14 then
Result:='99.999.999/9999-99;0; '
else Result:='99999999999999;0; ';
end;
function TPessoasVO.ValidaCNPJ(xCNPJ: String): Boolean;
Var
d1, d4, xx, nCount, fator, resto, digito1, digito2: integer;
Check: String;
begin
d1 := 0;
d4 := 0;
xx := 1;
for nCount := 1 to Length(xCNPJ) - 2 do
begin
if Pos(Copy(xCNPJ, nCount, 1), '/-.') = 0 then
begin
if xx < 5 then
begin
fator := 6 - xx;
end
else
begin
fator := 14 - xx;
end;
d1 := d1 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator;
if xx < 6 then
begin
fator := 7 - xx;
end
else
begin
fator := 15 - xx;
end;
d4 := d4 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator;
xx := xx + 1;
end;
end;
resto := (d1 mod 11);
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := (d4 mod 11);
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr(digito1) + IntToStr(digito2);
if Check <> Copy(xCNPJ, succ(Length(xCNPJ) - 2), 2) then
begin
//raise Exception.Create('Cnpj inválido!');
Result := False;
end
else
begin
Result := True;
end;
end;
function TPessoasVO.ValidaCPF(xCPF: String): Boolean;
Var
d1, d4, xx, nCount, resto, digito1, digito2: integer;
Check: String;
Begin
d1 := 0;
d4 := 0;
xx := 1;
for nCount := 1 to Length(xCPF) - 2 do
begin
if Pos(Copy(xCPF, nCount, 1), '/-.') = 0 then
begin
d1 := d1 + (11 - xx) * StrToInt(Copy(xCPF, nCount, 1));
d4 := d4 + (12 - xx) * StrToInt(Copy(xCPF, nCount, 1));
xx := xx + 1;
end;
end;
resto := (d1 mod 11);
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := (d4 mod 11);
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr(digito1) + IntToStr(digito2);
if Check <> Copy(xCPF, succ(Length(xCPF) - 2), 2) then
begin
//raise Exception.Create('O Cpf inválido!');
Result := False;
end
else
begin
Result := True;
end;
end;
begin
end.
|
unit Odontologia.Controlador.Medico;
interface
uses
Data.DB,
System.SysUtils,
System.Generics.Collections,
Odontologia.Controlador.Medico.Interfaces,
Odontologia.Controlador.Estado,
Odontologia.Controlador.Estado.Interfaces,
Odontologia.Modelo,
Odontologia.Modelo.Entidades.Medico,
Odontologia.Modelo.Medico.Interfaces,
Odontologia.Modelo.Estado.Interfaces;
type
TControllerMedico = class(TInterfacedObject, iControllerMedico)
private
FModel : iModelMedico;
FDataSource : TDataSource;
FEstado : iControllerEstado;
procedure DataChange (sender : tobject ; field : Tfield) ;
public
constructor Create;
destructor Destroy; override;
class function New : iControllerMedico;
function DataSource (aDataSource : TDataSource) : iControllerMedico;
function Buscar (aNombre : String) : iControllerMedico; overload;
function Buscar : iControllerMedico; overload;
function Insertar : iControllerMedico;
function Modificar : iControllerMedico;
function Eliminar : iControllerMedico;
function Entidad : TDMEDICO;
function Estado : iControllerEstado;
end;
implementation
{ TControllerMedico }
function TControllerMedico.Buscar: iControllerMedico;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DMEDICO.MED_CODIGO AS CODIGO,')
.Fields('DMEDICO.MED_NOMBRE AS NOMBRE,')
.Fields('DMEDICO.MED_DOCUMENTO AS DOCUMENTO,')
.Fields('DMEDICO.MED_TELEFONO AS TELEFONO,')
.Fields('DMEDICO.MED_MATRICULA AS MATRICULA,')
.Fields('DMEDICO.MED_ESPECIALIDAD AS ESPECIALIDAD,')
.Fields('DMEDICO.MED_FOTO AS FOTO,')
.Fields('DMEDICO.MED_COD_ESTADO AS CODESTADO,')
.Fields('FSITUACION.SIT_SITUACION AS ESTADO ')
.Join('INNER JOIN FSITUACION ON FSITUACION.SIT_CODIGO = DMEDICO.MED_COD_ESTADO')
.Where('')
.OrderBy('NOMBRE')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := False;
FDataSource.dataset.FieldByName('MATRICULA').Visible := False;
FDataSource.dataset.FieldByName('DOCUMENTO').Visible := False;
FDataSource.dataset.FieldByName('FOTO').Visible := False;
FDataSource.dataset.FieldByName('CODESTADO').Visible := False;
FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth := 50;
end;
function TControllerMedico.Buscar(aNombre: String): iControllerMedico;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DMEDICO.MED_CODIGO AS CODIGO,')
.Fields('DMEDICO.MED_NOMBRE AS NOMBRE,')
.Fields('DMEDICO.MED_DOCUMENTO AS DOCUMENTO,')
.Fields('DMEDICO.MED_TELEFONO AS TELEFONO,')
.Fields('DMEDICO.MED_MATRICULA AS MATRICULA,')
.Fields('DMEDICO.MED_ESPECIALIDAD AS ESPECIALIDAD,')
.Fields('DMEDICO.MED_FOTO AS FOTO,')
.Fields('DMEDICO.MED_COD_ESTADO AS CODESTADO,')
.Fields('FSITUACION.SIT_SITUACION AS ESTADO ')
.Join('INNER JOIN FSITUACION ON FSITUACION.SIT_CODIGO = DMEDICO.MED_COD_ESTADO')
.Where('DMEDICO.MED_NOMBRE LIKE ' +QuotedStr(aNombre) + '')
.OrderBy('NOMBRE')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := False;
FDataSource.dataset.FieldByName('MATRICULA').Visible := False;
FDataSource.dataset.FieldByName('DOCUMENTO').Visible := False;
FDataSource.dataset.FieldByName('FOTO').Visible := False;
FDataSource.dataset.FieldByName('CODESTADO').Visible := False;
FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth := 50;
end;
constructor TControllerMedico.Create;
begin
FModel := TModel.New.Medico;
end;
procedure TControllerMedico.DataChange(sender: tobject; field: Tfield);
begin
end;
function TControllerMedico.DataSource(aDataSource: TDataSource) : iControllerMedico;
begin
Result := Self;
FDataSource := aDataSource;
FModel.DataSource(FDataSource);
FDataSource.OnDataChange := DataChange;
end;
destructor TControllerMedico.Destroy;
begin
inherited;
end;
function TControllerMedico.Eliminar: iControllerMedico;
begin
Result := Self;
FModel.DAO.Delete(FModel.Entidad);
end;
function TControllerMedico.Estado: iControllerEstado;
begin
Result := FEstado;
end;
function TControllerMedico.Entidad: TDMEDICO;
begin
Result := FModel.Entidad;
end;
function TControllerMedico.Insertar: iControllerMedico;
begin
Result := Self;
FModel.DAO.Insert(FModel.Entidad);
end;
function TControllerMedico.Modificar: iControllerMedico;
begin
Result := Self;
FModel.DAO.Update(FModel.Entidad);
end;
class function TControllerMedico.New: iControllerMedico;
begin
Result := Self.Create;
end;
end.
|
unit UFlow;
interface
uses URegularFunctions, UConst;
type
Flow = class
mass_flow_rate: real;
mole_flow_rate: real;
volume_flow_rate: real;
mass_fractions: array of real;
volume_fractions: array of real;
mole_fractions: array of real;
molar_fractions: array of real;
temperature: real;
pressure: real;
density: real;
average_mol_mass: real;
cp: real;
constructor(mass_flow_rate: real;
mass_fractions: array of real;
temperature, pressure: real);
procedure gas_separation;
function get_ron: real;
end;
implementation
constructor Flow.Create(mass_flow_rate: real;
mass_fractions: array of real;
temperature, pressure: real);
begin
self.mass_flow_rate := mass_flow_rate;
self.mass_fractions := normalize(mass_fractions);
self.temperature := temperature;
self.pressure := pressure;
self.mole_fractions := convert_mass_to_mole_fractions(
self.mass_fractions, UConst.MR);
self.volume_fractions := convert_mass_to_volume_fractions(
self.mass_fractions, UConst.DENSITIES);
self.density := get_flow_density(self.mass_fractions, UConst.DENSITIES);
self.average_mol_mass := get_average_mol_mass(self.mass_fractions, UConst.MR);
self.mole_flow_rate := self.mass_flow_rate / self.average_mol_mass;
self.volume_flow_rate := self.mass_flow_rate / self.density / 1000;
self.cp := get_flow_cp(self.mass_fractions, UConst.HEATCAPACITYCOEFFS,
self.temperature);
self.molar_fractions := convert_mass_to_molar_fractions(self.mass_fractions,
get_ideal_gas_den(self.temperature, self.pressure, UConst.MR), UConst.MR);
end;
procedure Flow.gas_separation;
begin
var mass_flows := ArrFill(self.mass_fractions.Length, 0.0);
foreach var i in mass_flows.Indices do
mass_flows[i] := self.mass_flow_rate * self.mass_fractions[i];
foreach var i in range(7, 10) do
mass_flows[i] := 0.0;
mass_flows[^1] := 0.0;
self.mass_fractions := normalize(mass_flows);
self.mass_flow_rate := mass_flows.Sum;
self.mole_fractions := convert_mass_to_mole_fractions(
self.mass_fractions, UConst.MR);
self.volume_fractions := convert_mass_to_volume_fractions(
self.mass_fractions, UConst.DENSITIES);
self.density := get_flow_density(self.mass_fractions, UConst.DENSITIES);
self.average_mol_mass := get_average_mol_mass(self.mass_fractions, UConst.MR);
self.mole_flow_rate := self.mass_flow_rate / self.average_mol_mass;
self.volume_flow_rate := self.mass_flow_rate / self.density;
self.cp := get_flow_cp(self.mass_fractions, UConst.HEATCAPACITYCOEFFS,
self.temperature)
end;
function Flow.get_ron: real;
begin
result := URegularFunctions.get_octane_number(self.mass_fractions,
UConst.RON, UConst.Bi)
end;
end. |
unit NFSEditBtn;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.Mask, Vcl.Graphics,
Vcl.ExtCtrls, Vcl.Forms, nfsButton, nfsEditProp, nfsEditBtnProp, Winapi.Messages ;
type
TNFSEditBtn = class(TCustomPanel)
private
fEdit: TMaskEdit;
fButton1: TnfsButton;
fButton2: TnfsButton;
fButton3: TnfsButton;
fEditProp: TnfsEditProp;
fOnEditChange: TNotifyEvent;
fOnEditEnter: TNotifyEvent;
fOnEditExit: TNotifyEvent;
fOnEditDblClick: TNotifyEvent;
fOnEditClick: TNotifyEvent;
fOnEditKeyPress: TKeyPressEvent;
fOnEditKeyDown: TKeyEvent;
fOnEditKeyUp: TKeyEvent;
fBtn1Prop: TnfsEditBtnProp;
fBtn2Prop: TnfsEditBtnProp;
fBtn3Prop: TnfsEditBtnProp;
fOnButton1Click: TNotifyEvent;
fOnButton2Click: TNotifyEvent;
fEnabled: Boolean;
fOnButton3Click: TNotifyEvent;
fOnEditMouseMove: TMouseMoveEvent;
fOnEditMouseEnter: TNotifyEvent;
fOnEditMouseLeave: TNotifyEvent;
fOnEditMouseUp: TMouseEvent;
fOnEditMouseDown: TMouseEvent;
fColorValue: TColor;
//fColor: TColor;
procedure EditPropChanged(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure EditEnter(Sender: TObject);
procedure EditExit(Sender: TObject);
procedure EditClick(Sender: TObject);
procedure EditDblClick(Sender: TObject);
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditKeyPress(Sender: TObject; var Key: Char);
procedure EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure setDefaultButtonStyle(aButton: TnfsButton);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure ButtonResize(Sender: TObject);
procedure EditMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure EditMouseEnter(Sender: TObject);
procedure EditMouseLeave(Sender: TObject);
procedure EditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure EditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
function getText: string;
procedure setText(const Value: string);
procedure setColorValue(const Value: TColor);
// procedure setColor(const Value: TColor);
protected
procedure Resize; override;
procedure WMExitSizeMove(var Message: TMessage); message WM_EXITSIZEMOVE;
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SizeMove(var msg: TWMSize); message WM_SIZE;
procedure setEnabled(const Value: Boolean); reintroduce;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ColorValue: TColor read fColorValue write setColorValue;
published
property Edit: TnfsEditProp read fEditProp write fEditProp;
property Button1: TnfsEditBtnProp read fBtn1Prop write fBtn1Prop;
property Button2: TnfsEditBtnProp read fBtn2Prop write fBtn2Prop;
property Button3: TnfsEditBtnProp read fBtn3Prop write fBtn3Prop;
property OnEditChange: TNotifyEvent read fOnEditChange write fOnEditChange;
property OnEditEnter: TNotifyEvent read fOnEditEnter write fOnEditEnter;
property OnEditExit: TNotifyEvent read fOnEditExit write fOnEditExit;
property OnEditClick: TNotifyEvent read fOnEditClick write fOnEditClick;
property OnEditDblClick: TNotifyEvent read fOnEditDblClick write fOnEditDblClick;
property OnEditKeyDown: TKeyEvent read fOnEditKeyDown write fOnEditKeyDown;
property OnEditKeyPress: TKeyPressEvent read fOnEditKeyPress write fOnEditKeyPress;
property OnEditKeyUp: TKeyEvent read fOnEditKeyUp write fOnEditKeyUp;
property OnButton1Click: TNotifyEvent read fOnButton1Click write fOnButton1Click;
property OnButton2Click: TNotifyEvent read fOnButton2Click write fOnButton2Click;
property OnButton3Click: TNotifyEvent read fOnButton3Click write fOnButton3Click;
property OnEditMouseMove: TMouseMoveEvent read fOnEditMouseMove write fOnEditMouseMove;
property OnEditMouseEnter: TNotifyEvent read fOnEditMouseEnter write fOnEditMouseEnter;
property OnEditMouseLeave: TNotifyEvent read fOnEditMouseLeave write fOnEditMouseLeave;
property OnEditMouseDown: TMouseEvent read fOnEditMouseDown write fOnEditMouseDown;
property OnEditMouseUp: TMouseEvent read fOnEditMouseUp write fOnEditMouseUp;
property Enabled: Boolean read fEnabled write setEnabled default true;
property Text: string read getText write setText;
property Hint;
property ShowHint;
property Anchors;
property Align;
//property Color: TColor read fColor write setColor;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('new frontiers', [TNFSEditBtn]);
end;
{ TNFSEditBtn }
constructor TNFSEditBtn.Create(AOwner: TComponent);
begin
inherited;
ShowCaption := false;
BevelOuter := bvNone;
BevelKind := bkTile;
Height := 22;
ParentBackground := false;
fEnabled := true;
fColorValue := clNone;
fEdit := TMaskEdit.Create(self);
fEdit.Parent := Self;
fEdit.Align := alNone;
fEdit.BorderStyle := bsNone;
fEdit.Top := 1;
fEdit.Left := 1;
fEdit.ReadOnly := true;
fEdit.OnEnter := EditEnter;
FEdit.OnExit := EditExit;
FEdit.OnKeyDown := EditKeyDown;
FEdit.OnKeyPress := EditKeyPress;
FEdit.OnKeyUp := EditKeyUp;
fEdit.OnClick := EditClick;
fEdit.OnDblClick := EditDblClick;
fEdit.OnMouseDown := EditMouseDown;
fEdit.OnMouseEnter := EditMouseEnter;
fEdit.OnMouseLeave := EditMouseLeave;
fEdit.OnMouseMove := EditMouseMove;
fEdit.OnMouseUp := EditMouseUp;
fEdit.Height := Height;
FEdit.Width := 140;
fEdit.Anchors := [akLeft,akTop,akRight,akBottom];
fButton3 := TnfsButton.Create(Self);
fButton3.OnClick := Button3Click;
setDefaultButtonStyle(fButton3);
fButton2 := TnfsButton.Create(Self);
fButton2.OnClick := Button2Click;
setDefaultButtonStyle(fButton2);
fButton1 := TnfsButton.Create(Self);
fButton1.OnClick := Button1Click;
setDefaultButtonStyle(fButton1);
fEditProp := TnfsEditProp.Create;
fEditProp.Edit := fEdit;
fEditProp.OnChanged := EditPropChanged;
fEdit.OnChange := EditChange;
fEdit.OnKeyDown := EditKeyDown;
fEdit.OnKeyPress := EditKeyPress;
fEdit.OnKeyUp := EditKeyUp;
fBtn1Prop := TnfsEditBtnProp.Create;
fBtn1Prop.Button := fButton1;
fBtn1Prop.OnResize := ButtonResize;
fBtn2Prop := TnfsEditBtnProp.Create;
fBtn2Prop.Button := fButton2;
fBtn2Prop.OnResize := ButtonResize;
fBtn3Prop := TnfsEditBtnProp.Create;
fBtn3Prop.Button := fButton3;
fBtn3Prop.Visible := false;
fBtn3Prop.OnResize := ButtonResize;
color := fEdit.Color;
FEdit.Enabled := true;
end;
destructor TNFSEditBtn.Destroy;
begin
FreeAndNil(fEditProp);
FreeAndNil(fBtn1Prop);
FreeAndNil(fBtn2Prop);
FreeAndNil(fBtn3Prop);
inherited;
end;
procedure TNFSEditBtn.setColorValue(const Value: TColor);
begin
fColorValue := Value;
fEdit.Text := ColorToString(Value);
end;
procedure TNFSEditBtn.setDefaultButtonStyle(aButton: TnfsButton);
begin
aButton.Parent := Self;
aButton.Margins.Top := 0;
aButton.Margins.Bottom := 0;
aButton.Margins.Left := 0;
aButton.Margins.Right := 2;
aButton.Align := alRight;
aButton.AlignWithMargins := true;
aButton.TextAlignment := iaLeft;
aButton.Left := 0;
//aButton.TextAlignIgnoreImage := true;
aButton.Width := 17;
aButton.Cursor := crHandPoint;
aButton.Flat := true;
end;
procedure TNFSEditBtn.setEnabled(const Value: Boolean);
begin
fEnabled := Value;
fEdit.Enabled := Value;
fButton1.Enabled := Value;
fButton2.Enabled := Value;
fButton3.Enabled := Value;
end;
procedure TNFSEditBtn.setText(const Value: string);
begin
fEditProp.Text := Value;
end;
procedure TNFSEditBtn.SizeMove(var msg: TWMSize);
begin
ButtonResize(self);
end;
procedure TNFSEditBtn.WMExitSizeMove(var Message: TMessage);
begin
Resize;
end;
procedure TNFSEditBtn.EditChange(Sender: TObject);
begin
if Assigned(fOnEditChange) then
fOnEditChange(self);
end;
procedure TNFSEditBtn.EditClick(Sender: TObject);
begin
if Assigned(fOnEditClick) then
fOnEditClick(Self);
end;
procedure TNFSEditBtn.EditDblClick(Sender: TObject);
begin
if Assigned(fOnEditDblClick) then
fOnEditDblClick(Self);
end;
procedure TNFSEditBtn.EditEnter(Sender: TObject);
begin
if Assigned(fOnEditEnter) then
fOnEditEnter(Self);
end;
procedure TNFSEditBtn.EditExit(Sender: TObject);
begin
if Assigned(fOnEditExit) then
fOnEditExit(Self);
end;
procedure TNFSEditBtn.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Assigned(fOnEditKeyDown) then
fOnEditKeyDown(Sender, Key, Shift);
end;
procedure TNFSEditBtn.EditKeyPress(Sender: TObject; var Key: Char);
begin
if Assigned(fOnEditKeyPress) then
fOnEditKeyPress(Sender, Key);
end;
procedure TNFSEditBtn.EditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Assigned(fOnEditKeyUp) then
fOnEditKeyUp(Sender, Key, Shift);
end;
procedure TNFSEditBtn.EditMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Assigned(fOnEditMouseDown) then
fOnEditMouseDown(Self, Button, Shift, X, X);
end;
procedure TNFSEditBtn.EditMouseEnter(Sender: TObject);
begin
if Assigned(fOnEditMouseEnter) then
fOnEditMouseEnter(Self);
end;
procedure TNFSEditBtn.EditMouseLeave(Sender: TObject);
begin
if Assigned(fOnEditMouseLeave) then
fOnEditMouseLeave(Self);
end;
procedure TNFSEditBtn.EditMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if Assigned(fOnEditMouseMove) then
fOnEditMouseMove(Self, Shift, X, Y);
end;
procedure TNFSEditBtn.EditMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Assigned(fOnEditMouseUp) then
fOnEditMouseUp(Self, Button, Shift, X, X);
end;
procedure TNFSEditBtn.EditPropChanged(Sender: TObject);
begin
fEdit.Font.Assign(fEditProp.Font);
Color := fEdit.Color;
fEdit.Invalidate;
fButton1.Invalidate;
fButton2.Invalidate;
fButton3.Invalidate;
Invalidate;
end;
function TNFSEditBtn.getText: string;
begin
Result := fEditProp.Text;
end;
procedure TNFSEditBtn.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited;
end;
procedure TNFSEditBtn.Resize;
begin
inherited;
end;
procedure TNFSEditBtn.Button1Click(Sender: TObject);
begin
if Assigned(fOnButton1Click) then
fOnButton1Click(Self);
end;
procedure TNFSEditBtn.Button2Click(Sender: TObject);
begin
if Assigned(fOnButton2Click) then
fOnButton2Click(Self);
end;
procedure TNFSEditBtn.Button3Click(Sender: TObject);
begin
if Assigned(fOnButton3Click) then
fOnButton3Click(Self);
end;
procedure TNFSEditBtn.ButtonResize(Sender: TObject);
var
Button1Width: Integer;
Button2Width: Integer;
Button3Width: Integer;
Button1Visible: Boolean;
Button2Visible: Boolean;
Button3Visible: Boolean;
begin
Button1Width := 0;
Button2Width := 0;
Button3Width := 0;
Button1Visible := fButton1.Visible;
Button2Visible := fButton2.Visible;
Button3Visible := fButton3.Visible;
fButton1.Visible := false;
fButton2.Visible := false;
fButton3.Visible := false;
fButton1.Left := 0;
fButton2.Left := 0;
fButton3.Left := 0;
fButton1.Visible := Button1Visible;
fButton2.Visible := Button2Visible;
fButton3.Visible := Button3Visible;
if fButton1.Visible then
Button1Width := fButton1.Width + fButton1.Margins.Left + fButton1.Margins.Right;
if fButton2.Visible then
Button2Width := fButton2.Width + fButton2.Margins.Left + fButton2.Margins.Right;
if fButton3.Visible then
Button3Width := fButton3.Width + fButton3.Margins.Left + fButton3.Margins.Right;
FEdit.Width := ClientWidth - Button1Width - Button2Width - Button3Width - 2;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
NoPluralLabel: TLabel;
NoPluralLabel0: TLabel;
NoPluralLabel1: TLabel;
NoPluralLabel2: TLabel;
HomeLabel: TLabel;
HomeLabel0: TLabel;
HomeLabel1: TLabel;
HomeLabel2: TLabel;
PluralLabel: TLabel;
PluralLabel0: TLabel;
PluralLabel1: TLabel;
PluralLabel2: TLabel;
MultiPluralLabel: TLabel;
MultiPluralLabel1: TLabel;
MultiPluralLabel2: TLabel;
MultiPluralLabel3: TLabel;
MultiPluralLabel4: TLabel;
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtBase, NtPattern;
procedure TForm1.FormCreate(Sender: TObject);
resourcestring
SFile = '%d file';
SFiles = '%d files';
procedure ProcessNoPlural(count: Integer; lab: TLabel);
begin
// On most languages this does not work except when count is 1
// Do not use code like this!
lab.Caption := Format(SFile, [count]);
if TMultiPattern.IsSingleFormLanguage or (count = 1) or (count = 0) and TMultiPattern.IsZeroLikeOne then
lab.Font.Color := clGreen
else
lab.Font.Color := clRed;
end;
procedure ProcessHomeBrewed(count: Integer; lab: TLabel);
begin
// This works on some Western languages (those that use similar plural rules as English)
// but would fail for example in French.
// Do not use code like this!
if count = 1 then
lab.Caption := Format(SFile, [count])
else
lab.Caption := Format(SFiles, [count]);
if not TMultiPattern.IsSingleFormLanguage and (count = 0) and TMultiPattern.IsZeroLikeOne then
lab.Font.Color := clRed
else
lab.Font.Color := clGreen
end;
// The following two samples handle plural forms correctly. Use this kind of code in your applications.
procedure ProcessPluralAware(count: Integer; lab: TLabel);
resourcestring
// This message contains two patterns: one and other.
// Localized strings will contain the patterns used by the target languages:
// - German is like English: one and other
// - Polish: one, paucal, other
// - Japanese: other
SFilesPlural = '{plural, one {%d file} other {%d files}}';
begin
// This works on every count and language (expecting SFiles translated correctly with right patterns)
lab.Caption := TMultiPattern.Format(SFilesPlural, count, [count]);
lab.Font.Color := clGreen;
end;
procedure ProcessMultiPlural(completed, total: Integer; lab: TLabel);
resourcestring
// With top level pattern. This makes pattern shorter and help eliminating
// repeating the same text on multiple patterns. Contains three parts:
// - Top level pattern that has two placeholders for plural parts.
// - Part 1 handles completed steps.
// - Part 2 handles the total amount of steps.
SMessagePlural = 'I have completed {plural, zero {none} one {one} other {%d}} {plural, zero {out of none steps} one {out of one step} other {out of %d steps}}';
begin
// On runtime part 3 is firstly created by choosing the right pattern and injecting total there.
// Then part 2 is created by choosing the right pattern and injecting completed and part 3 there.
// Finally part 1 is created by injecting part 2 there resulting the final string.
lab.Caption := TMultiPattern.Format(SMessagePlural, [completed, total]);
lab.Font.Color := clGreen;
end;
begin
ProcessNoPlural(0, NoPluralLabel0);
ProcessNoPlural(1, NoPluralLabel1);
ProcessNoPlural(2, NoPluralLabel2);
ProcessHomeBrewed(0, HomeLabel0);
ProcessHomeBrewed(1, HomeLabel1);
ProcessHomeBrewed(2, HomeLabel2);
ProcessPluralAware(0, PluralLabel0);
ProcessPluralAware(1, PluralLabel1);
ProcessPluralAware(2, PluralLabel2);
ProcessMultiPlural(0, 1, MultiPluralLabel1);
ProcessMultiPlural(1, 1, MultiPluralLabel2);
ProcessMultiPlural(1, 3, MultiPluralLabel3);
ProcessMultiPlural(2, 3, MultiPluralLabel4);
end;
// Plural engine needs to know the language that the application uses.
// Compiled EXE file does not contain this information. This is why we create
// a resource string that contains the locale code.
// The default locale is set to this code.
// If you name the resource string to SNtLocale NewTool automatically translates
// it to have the locale code of the target language.
resourcestring
SNtLocale = 'en';
initialization
DefaultLocale := SNtLocale;
end.
|
unit EditBox;
interface
uses
SysUtils, Types, Classes, Graphics,
Style, Node, Box, Flow;
type
TRefNode = class(TNode)
public
Ref: TNode;
Text: string;
end;
//
TTextBox = class(TBox)
Text: string;
end;
//
TEditBox = class(TBox)
protected
function FindCursorInBox(var inCursor: Integer; inBox: TBox): Boolean;
procedure PaintLine(inLineBox: TBox);
procedure ResetLines;
public
Canvas: TCanvas;
CursorIndex: Integer;
CursorBox: TBox;
Lines: TBoxList;
function FindCaret(inCursor: Integer): TPoint;
procedure FindCursor(inCursor: Integer);
procedure PaintLines;
procedure WrapLines(inW: Integer);
end;
implementation
uses
Text;
procedure TEditBox.ResetLines;
begin
Lines.Free;
Lines := TBoxList.Create;
end;
procedure TEditBox.WrapLines(inW: Integer);
var
i: Integer;
w: Integer;
line: TBox;
procedure NewLine;
begin
line := Lines.AddBox;
w := inW;
end;
procedure WrapText(const inNode: TNode);
var
t: string;
b: Integer;
node: TNode;
begin
t := inNode.Text;
while (t <> '') do
begin
//node := TRefNode.Create;
//node.Ref := inNode;
node := TNode.Create;
line.AddBox.Node := node;
b := GetWordBreak(Canvas, w, t);
if (b >= 0) then
begin
node.Text := Copy(t, 1, b);
t := Copy(t, b + 1, MAXINT);
NewLine;
end else
begin
node.Text := t;
w := w - Canvas.TextWidth(t);
t := '';
end;
end;
end;
begin
ResetLines;
NewLine;
for i := 0 to Boxes.Max do
WrapText(Boxes[i].Node);
end;
procedure TEditBox.PaintLine(inLineBox: TBox);
var
p: TPoint;
procedure PaintBox(inBox: TBox);
begin
Canvas.TextOut(p.X, p.Y, inBox.Node.Text);
Inc(p.X, Canvas.TextWidth(inBox.Node.Text));
end;
var
i: Integer;
begin
p := Point(inLineBox.Left, inLineBox.Top);
for i := 0 to inLineBox.Boxes.Max do
PaintBox(inLineBox.Boxes[i]);
end;
procedure TEditBox.PaintLines;
var
p: TPoint;
i: Integer;
begin
p := Point(Left, Top);
for i := 0 to Lines.Max do
begin
with Lines[i] do
begin
Left := 0;
Top := p.Y;
end;
PaintLine(Lines[i]);
Inc(p.Y, 16);
end;
end;
function TEditBox.FindCaret(inCursor: Integer): TPoint;
var
pos: TPoint;
function FindCaretInBox(inBox: TBox): Boolean;
var
l: Integer;
begin
l := Length(inBox.Node.Text);
if l > inCursor then
begin
Inc(pos.X, Canvas.TextWidth(Copy(inBox.Node.Text, 1, inCursor)));
Result := true;
exit;
end;
Dec(inCursor, l);
Inc(pos.X, Canvas.TextWidth(inBox.Node.Text));
Result := false;
end;
function FindCaretInLine(inBox: TBox): Boolean;
var
i: Integer;
begin
Result := true;
pos.X := inBox.Left;
for i := 0 to inBox.Boxes.Max do
if FindCaretInBox(inBox.Boxes[i]) then
exit;
Result := false;
end;
var
i: Integer;
begin
pos := Point(Left, Top);
for i := 0 to Lines.Max do
begin
if FindCaretInLine(Lines[i]) then
break;
Inc(pos.Y, 16);
end;
Result := pos;
end;
function TEditBox.FindCursorInBox(var inCursor: Integer; inBox: TBox): Boolean;
function FindCursorInBoxes(inBox: TBox): Boolean;
var
i: Integer;
begin
Result := false;
if (inBox.Boxes <> nil) then
for i := 0 to inBox.Boxes.Max do
Result := FindCursorInBox(inCursor, inBox.Boxes[i]);
end;
var
l: Integer;
begin
l := Length(inBox.Node.Text);
if l > inCursor then
begin
CursorIndex := inCursor;
CursorBox := inBox;
Result := true;
exit;
end;
Dec(inCursor, l);
Result := FindCursorInBoxes(inBox);
end;
procedure TEditBox.FindCursor(inCursor: Integer);
var
i: Integer;
begin
CursorBox := nil;
for i := 0 to Boxes.Max do
if FindCursorInBox(inCursor, Boxes[i]) then
break;
end;
end.
|
unit uDoublyLinkedList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TNode }
TNode = class(TObject)
private
FNext: TNode;
FPrev: TNode;
FValue: Pointer;
public
constructor Create;
function hasNext: boolean;
function hasPrev: boolean;
property Value: Pointer read FValue write FValue;
property Next: TNode read FNext write FNext;
property Prev: TNode read FPrev write FPrev;
end;
{ TDoublyLinkedList }
TDoublyLinkedList = class(TObject)
FHead: TNode;
FTail: TNode;
FCount: integer;
public
procedure InsertBefore(APosNode: TNode; var AValuePtr: Pointer);
procedure InsertNext(APosNode: TNode; var AValuePtr: Pointer);
procedure DeleteAt(APos: TNode);
property Head: TNode read FHead write FHead;
property Tail: TNode read FTail write FTail;
property Count: integer read FCount write FCount;
constructor Create;
end;
implementation
{ TNode }
constructor TNode.Create;
begin
end;
function TNode.hasNext: boolean;
begin
if Assigned(FNext) then
begin
Result := True;
end
else
begin
Result := False;
end;
end;
function TNode.hasPrev: boolean;
begin
if Assigned(FPrev) then
begin
Result := True;
end
else
Result := False;
end;
{ TDoublyLinkedList }
procedure TDoublyLinkedList.InsertBefore(APosNode: TNode; var AValuePtr: Pointer);
var
LNode: TNode;
begin
if not Assigned(APosNode) then
begin
Head := TNode.Create;
Head.Value := AValuePtr;
Tail := Head;
exit;
end;
if Assigned(APosNode.Prev) then
begin
LNode := APosNode.Prev;
APosNode.Prev := TNode.Create;
APosNode.Prev.Value := AValuePtr;
APosNode.Prev.Prev := LNode;
end
else
begin
APosNode.Prev := TNode.Create;
APosNode.Prev.Value := AValuePtr;
Head := APosNode.Prev;
end;
Inc(FCount);
end;
procedure TDoublyLinkedList.InsertNext(APosNode: TNode; var AValuePtr: Pointer);
var
LNode: TNode;
begin
if not Assigned(APosNode) then
begin
Tail := TNode.Create;
Tail.Value := AValuePtr;
Head := Head;
exit;
end;
if Assigned(APosNode.Next) then
begin
LNode := APosNode.Next;
APosNode.Next := TNode.Create;
APosNode.Next.Value := AValuePtr;
APosNode.Next.Prev := LNode;
end
else
begin
APosNode.Next := TNode.Create;
APosNode.Next.Value := AValuePtr;
Tail := APosNode.Next;
end;
Inc(FCount);
end;
procedure TDoublyLinkedList.DeleteAt(APos: TNode);
var
LNode: TNode;
begin
if Assigned(APos.Prev) then
begin
LNode := APos.Prev;
LNode.Next := APos.Next;
FreeAndNil(APos);
end
else
begin
FreeAndNil(APos);
end;
Dec(FCount);
end;
constructor TDoublyLinkedList.Create;
begin
{Init Node}
FHead := nil;
FTail := nil;
FCount := 0;
end;
end.
|
unit eUsusario.Model.Entidade.Empresa;
interface
uses
eUsusario.View.Conexao.Interfaces, Data.DB;
Type
TModelEntidadeEmpresa = class(TInterfacedObject, iEntidade)
private
FQuery : iQuery;
public
constructor Create;
destructor Destroy; override;
class function New : iEntidade;
function Listar(Value : TDataSource) : iEntidade;
end;
implementation
uses
eUsusario.Controller.Factory.Query, System.SysUtils;
{ TModelEntidadeEmpresa }
constructor TModelEntidadeEmpresa.Create;
begin
FQuery := TControllerFactoryQuery.New.Query(Nil);
end;
destructor TModelEntidadeEmpresa.Destroy;
begin
FreeAndNil(FQuery);
inherited;
end;
function TModelEntidadeEmpresa.Listar(Value: TDataSource): iEntidade;
begin
Result := Self;
FQuery.SQL('SELECT * FROM EMPRESA');
Value.DataSet := FQuery.DataSet;
end;
class function TModelEntidadeEmpresa.New: iEntidade;
begin
Result := Self.Create;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082446
////////////////////////////////////////////////////////////////////////////////
unit android.hardware.display.DisplayManager;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.view.Display,
android.hardware.display.DisplayManager_DisplayListener,
Androidapi.JNI.os,
android.hardware.display.VirtualDisplay,
android.view.Surface,
android.hardware.display.VirtualDisplay_Callback;
type
JDisplayManager = interface;
JDisplayManagerClass = interface(JObjectClass)
['{797204E9-91EF-4300-8517-F62836F8F6D8}']
function _GetDISPLAY_CATEGORY_PRESENTATION : JString; cdecl; // A: $19
function _GetVIRTUAL_DISPLAY_FLAG_AUTO_MIRROR : Integer; cdecl; // A: $19
function _GetVIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY : Integer; cdecl; // A: $19
function _GetVIRTUAL_DISPLAY_FLAG_PRESENTATION : Integer; cdecl; // A: $19
function _GetVIRTUAL_DISPLAY_FLAG_PUBLIC : Integer; cdecl; // A: $19
function _GetVIRTUAL_DISPLAY_FLAG_SECURE : Integer; cdecl; // A: $19
function createVirtualDisplay(&name : JString; width : Integer; height : Integer; densityDpi : Integer; surface : JSurface; flags : Integer) : JVirtualDisplay; cdecl; overload;// (Ljava/lang/String;IIILandroid/view/Surface;I)Landroid/hardware/display/VirtualDisplay; A: $1
function createVirtualDisplay(&name : JString; width : Integer; height : Integer; densityDpi : Integer; surface : JSurface; flags : Integer; callback : JVirtualDisplay_Callback; handler : JHandler) : JVirtualDisplay; cdecl; overload;// (Ljava/lang/String;IIILandroid/view/Surface;ILandroid/hardware/display/VirtualDisplay$Callback;Landroid/os/Handler;)Landroid/hardware/display/VirtualDisplay; A: $1
function getDisplay(displayId : Integer) : JDisplay; cdecl; // (I)Landroid/view/Display; A: $1
function getDisplays : TJavaArray<JDisplay>; cdecl; overload; // ()[Landroid/view/Display; A: $1
function getDisplays(category : JString) : TJavaArray<JDisplay>; cdecl; overload;// (Ljava/lang/String;)[Landroid/view/Display; A: $1
procedure registerDisplayListener(listener : JDisplayManager_DisplayListener; handler : JHandler) ; cdecl;// (Landroid/hardware/display/DisplayManager$DisplayListener;Landroid/os/Handler;)V A: $1
procedure unregisterDisplayListener(listener : JDisplayManager_DisplayListener) ; cdecl;// (Landroid/hardware/display/DisplayManager$DisplayListener;)V A: $1
property DISPLAY_CATEGORY_PRESENTATION : JString read _GetDISPLAY_CATEGORY_PRESENTATION;// Ljava/lang/String; A: $19
property VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR : Integer read _GetVIRTUAL_DISPLAY_FLAG_AUTO_MIRROR;// I A: $19
property VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY : Integer read _GetVIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;// I A: $19
property VIRTUAL_DISPLAY_FLAG_PRESENTATION : Integer read _GetVIRTUAL_DISPLAY_FLAG_PRESENTATION;// I A: $19
property VIRTUAL_DISPLAY_FLAG_PUBLIC : Integer read _GetVIRTUAL_DISPLAY_FLAG_PUBLIC;// I A: $19
property VIRTUAL_DISPLAY_FLAG_SECURE : Integer read _GetVIRTUAL_DISPLAY_FLAG_SECURE;// I A: $19
end;
[JavaSignature('android/hardware/display/DisplayManager$DisplayListener')]
JDisplayManager = interface(JObject)
['{FBFE7257-A9D4-4ABD-99D2-A995F9B9D602}']
function createVirtualDisplay(&name : JString; width : Integer; height : Integer; densityDpi : Integer; surface : JSurface; flags : Integer) : JVirtualDisplay; cdecl; overload;// (Ljava/lang/String;IIILandroid/view/Surface;I)Landroid/hardware/display/VirtualDisplay; A: $1
function createVirtualDisplay(&name : JString; width : Integer; height : Integer; densityDpi : Integer; surface : JSurface; flags : Integer; callback : JVirtualDisplay_Callback; handler : JHandler) : JVirtualDisplay; cdecl; overload;// (Ljava/lang/String;IIILandroid/view/Surface;ILandroid/hardware/display/VirtualDisplay$Callback;Landroid/os/Handler;)Landroid/hardware/display/VirtualDisplay; A: $1
function getDisplay(displayId : Integer) : JDisplay; cdecl; // (I)Landroid/view/Display; A: $1
function getDisplays : TJavaArray<JDisplay>; cdecl; overload; // ()[Landroid/view/Display; A: $1
function getDisplays(category : JString) : TJavaArray<JDisplay>; cdecl; overload;// (Ljava/lang/String;)[Landroid/view/Display; A: $1
procedure registerDisplayListener(listener : JDisplayManager_DisplayListener; handler : JHandler) ; cdecl;// (Landroid/hardware/display/DisplayManager$DisplayListener;Landroid/os/Handler;)V A: $1
procedure unregisterDisplayListener(listener : JDisplayManager_DisplayListener) ; cdecl;// (Landroid/hardware/display/DisplayManager$DisplayListener;)V A: $1
end;
TJDisplayManager = class(TJavaGenericImport<JDisplayManagerClass, JDisplayManager>)
end;
const
TJDisplayManagerDISPLAY_CATEGORY_PRESENTATION = 'android.hardware.display.category.PRESENTATION';
TJDisplayManagerVIRTUAL_DISPLAY_FLAG_AUTO_MIRROR = 16;
TJDisplayManagerVIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY = 8;
TJDisplayManagerVIRTUAL_DISPLAY_FLAG_PRESENTATION = 2;
TJDisplayManagerVIRTUAL_DISPLAY_FLAG_PUBLIC = 1;
TJDisplayManagerVIRTUAL_DISPLAY_FLAG_SECURE = 4;
implementation
end.
|
unit DBDateTime;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.ComCtrls, Vcl.DBCtrls,
Data.DB, Winapi.Messages;
type
TDBDateTime = class(TDateTimePicker)
private
function GetDataField: string;
function GetDataSource: TDataSource;
procedure SetDataField(const Value: string);
procedure SetDataSource(const Value: TDataSource);
strict private
FDataLink: TFieldDataLink;
procedure UpdateData(ASender:TObject);
procedure DataChange(ASender: TObject);
procedure CMExit(var Msg: TMessage); message CM_EXIT;
protected
procedure Change; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
implementation
{ TDBDateTime }
procedure TDBDateTime.Change;
begin
if not(FDataLink.Editing) then
FDataLink.Edit;
FDataLink.Modified;
inherited;
end;
procedure TDBDateTime.CMExit(var Msg: TMessage);
begin
try
FDataLink.UpdateRecord;
except
on Exception do
Self.SetFocus;
end;
inherited;
end;
constructor TDBDateTime.Create(AOwner: TComponent);
begin
inherited;
FDataLink := TFieldDataLink.Create;
FDataLink.OnDataChange := DataChange;
FDataLink.OnUpdateData := UpdateData;
end;
procedure TDBDateTime.DataChange(ASender: TObject);
begin
if (Assigned(FDataLink.DataSource)) and (Assigned(FDataLink.Field)) then
begin
Self.Format := TDateTimeField(FDataLink.Field).DisplayFormat;
Self.Date := FDataLink.Field.AsDateTime;
end;
end;
destructor TDBDateTime.Destroy;
begin
FreeAndNil(FDataLink);
inherited;
end;
function TDBDateTime.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
function TDBDateTime.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TDBDateTime.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
procedure TDBDateTime.SetDataSource(const Value: TDataSource);
begin
FDataLink.DataSource := Value;
end;
procedure TDBDateTime.UpdateData(ASender: TObject);
begin
FDataLink.Field.AsDateTime := Self.DateTime;
end;
end.
|
uses crt, graph,joystick;
type JoyType=record X,Y : integer;b1,b2,b3,b4:boolean;END;
var
x, y, z : array[ 1..2,1..24] of shortint;
no, e,b,kX,kY : byte; {Index}
xp1,xp2,yp1,yp2 :array[1..24] of integer;
const
g = 15 ; {g=VergrĒŠerung}
di = 120; {di=Distanz des Objektes}
f = 50; {Zoom}
xv = 320;
yv = 240; {xv, yv : Verschiebung}
kb = pi/180;
(********************************************************************)
procedure center;
var Joy : JoyType;
BEGIN
clrscr;
writeln('Bitte zentrieren sie ihren Joystick und drĀcken sie einen Knopf.');
with joy do BEGIN
repeat
JoyButton(b1, b2, b3, b4);
until not b1 or not b2 or not b3 or not b4;
JoyKoor(X, Y);
END;
kX := Joy.X; kY := Joy.Y;
END;
procedure datlese;
var
er,aha : integer;
t : text;
a : string;
s,n,l: byte;
BEGIN
b:=0;
assign(t, 'c:\tp\cobra2.dat');
reset(t);readln(t,a);readln(t,a);
repeat
inc(b);
readln(t, a);
val(a, aha, er);x[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);y[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);z[1,b]:=aha div 5;
readln(t, a);
val(a, aha, er);x[2,b]:=aha div 5;
readln(t, a);
val(a, aha, er);y[2,b]:=aha div 5;
readln(t, a);
val(a, aha, er);z[2,b]:=aha div 5;
readln(t, a);
until eof(t);
END;
procedure grafik;
var grDriver , grMode : Integer; {InitGraph (640*480*16)}
BEGIN
grDriver := Detect;
InitGraph(grDriver,grMode,'c:\tp');
END;
procedure rotate(rotX,rotY,rotZ: real);
var
zp1, zp2,srotY,crotY,srotX,crotX,srotZ,crotZ: real;
BEGIN
SrotY:=Sin(rotY); CrotY:=Cos(rotY);
SrotX:=Sin(rotX); CrotX:=Cos(rotX);
SrotZ:=Sin(rotZ); CrotZ:=Cos(rotZ); {Sin & Cos-Berechnungen}
for e := 1 to 24 do
BEGIN
setcolor(0); LINE (xp1[e],yp1[e],xp2[e],yp2[e]); {LĒschen}
zp1:=srotY*x[1,e]-crotY*(srotX*z[1,e]+crotX*y[1,e])+di;
xp1[e]:=trunc((f/zp1)*(CrotZ*(crotY*x[1,e]+srotY*(srotX*y[1, e]-crotX*z[1, e]))-srotZ*(crotX*y[1,e]+srotX*z[1,e]))*g)+xv;
yp1[e]:=yv-trunc((f/zp1)*(CrotZ*((crotX*y[1,e]+srotX*z[1, e]))+srotZ*(crotY*x[1,e]+srotY*(srotX*y[1,e]-crotX*z[1,e])))*g);
zp2:=srotY*x[2,e]-crotY*(srotX*z[2,e]+crotX*y[2,e])+di;
xp2[e]:=trunc((f/zp2)*(CrotZ*(crotY*x[2, e]+srotY*(srotX*y[2,e]-crotX*z[2,e]))-srotZ*(crotX*(y[2,e])+srotX*z[2,e]))*g)+xv;
yp2[e]:=yv-trunc((f/zp2)*(CrotZ*(crotX*y[2, e]+srotX*z[2, e])+srotZ*(crotY*x[2,e]+srotY*(srotX*y[2, e]-crotX*z[2,e])))*g);
setcolor(7);LINE (xp1[e],yp1[e],xp2[e],yp2[e]); {Zeichnen}
END;
END;
Procedure JoyAbfrage;
var Joy : joytype;
rotY, rotX, rotZ : real;
xt,yt : shortint;
BEGIN
rotY :=0;rotX:=0;rotZ:=0;
repeat
with joy do
BEGIN
joykoor(x,y);
xt :=x-kx;yt :=y-ky;
if (xt < -10) or (xt > 10) or (yt< -10) or (yt > 10) then
BEGIN
rotX:= rotX+ yt/1000;
joybutton(b1,b2,b3,b4);
if b3 = true then begin
rotY :=rotY+sin(rotX)*(xt/1000);
rotZ :=rotZ+cos(rotX)*(xt/1000);
end
else begin
rotY :=rotY+cos(rotZ)*(xt/1000);
rotZ :=rotZ+sin(rotZ)*(xt/1000);
end;
rotate(rotX,rotY,rotZ);
END;
END;
until keypressed;
END;
BEGIN {Main}
Datlese;
Center;
Grafik;
JoyAbfrage;
Closegraph;
END. |
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0097.PAS
Description: Percentages
Author: MICHAEL HOENIE
Date: 05-27-95 10:36
*)
{
Hi Gayle. Got a couple of routines here for you. These are calculation
routines to find an accurate percentage between two given numbers. While
they are quite simple, perhaps they will help anyone who is just starting
out.
the following procedure will calculate the percentage between two
given numbers, and report the percentage in a string. }
type string10=string[10];
function calc_p1(num1,num2:integer):string10;
var
z:real;
out1:string[10];
begin
out1:=' 0';
if num1=0 then exit;
if num2=0 then exit;
z:=num1/num2;
str(z:2:2,out1);
if out1='1.00' then
begin
out1:='100';
calc_p1:=out1;
exit;
end;
delete(out1,1,2);
if out1[1]='0' then delete(out1,1,1);
while length(out1)<2 do insert(' ',out1,1);
if out1='0' then out1:='100';
if out1='' then out1:='0';
calc_p1:=out1;
end;
{ this procedure does the same thing, but breaks the percentage down
to a tenth of a percentage (ie. 10.5% 99.98%, etc.) }
function calc_p2(num1,num2:integer):string10;
var
z:real;
out1:string[10];
begin
out1:=' -0- ';
if num1=0 then exit;
if num2=0 then exit;
z:=num1 / num2;
str(z:2:3,out1);
delete(out1,1,2);
if copy(out1,1,2)='00' then
begin
delete(out1,1,2);
insert('.',out1,1);
end else
if copy(out1,1,1)='0' then
begin
delete(out1,1,1);
insert('.',out1,2);
end else insert('.',out1,3);
if out1='.0' then out1:='100.00';
calc_p2:=out1;
end;
begin
writeln('calc_p1: 50 into 100 is ',calc_p1(50,100),'%');
writeln('calc_p2: 67 into 161 is ',calc_p2(67,161),'%');
end.
|
unit UIconEngine;
interface
uses USettings, Generics.Collections, XmlDoc,
Xml.XMLIntf, UPredefinedSizes, ULogger,
Graphics, SysUtils, System.Types;
type
TIconEngine = class
private
BaseFileName: string;
ImageList: TDictionary<string, string>;
PredefinedSizes: TPredefinedSizes;
FLog: TLogger;
DefaultSettings: TSettings;
procedure LoadSettings;
procedure LoadImages(const folder: string);
function GetImageId(const w, h: integer): string;
procedure SaveImages(const folder: string);
procedure ProcessPropGroup(const AlreadyProcessed: TDictionary<string, boolean>; Proj: IXmlDocument; PropGroup: IXmlNode; var ProcessedCount: integer);
procedure ProcessProject(Proj: IXmlDocument; ProjNode: IXmlNode);
function ProcessIcon(const AlreadyProcessed: TDictionary<string, boolean>; Icon: IXmlNode; const prefix: string; var ProcessedCount: integer): boolean;
function GetPlat(const s: string): string;
function GetTarget(const s: string): string;
function IsNumberOrX(const c: char): boolean;
procedure ClearDestFolder;
function TryToGenerate(const sz: TSize; const NodeName: string; out SourceFileName: string): boolean;
function GetDestFileName(const Pattern: string; sz: TSize; NodeName, SourceFileName: string): string;
procedure CopyIcon(const NodeName: string; var GeneratedInPlace: boolean; var Skip: Boolean; sz: TSize; var SourceFileName: string; var DestFileName: string);
function SkipIcon(const sz: TSize): boolean;
function SkipLaunch(const sz: TSize): boolean;
function TryToGenerateRect(const sz: TSize; const SourceFileName: string): boolean;
function TryToGenerateSquare(const sz: TSize; const SourceFileName: string): boolean;
function FindRectImg(const sz: TSize; out FileName: string; out OrigSz: TSize): boolean;
function FindSquareImg(const sz: TSize; out FileName: string): boolean;
function GetColorHex(cl: TColor): string;
function GetSizeFromId(const s: string): TSize;
function CalcRatio(const sz: TSize): double;
function NearestRatio(const DesiredRatio: double; const sz1,
sz2: TSize): boolean;
public
Settings: TSettings;
constructor Create(const aBaseFileName: string; const aDefaultSettings: TSettings; const aLogger: TLogger);
destructor Destroy; override;
procedure SaveSettings(const forced: boolean);
function FullMasterFolder: string;
function FullGeneratedFolder: string;
procedure GenerateFiles;
property Log: TLogger read FLog write FLog;
end;
implementation
uses IOUtils, PngImage, URunner, Windows;
const
IconSpreadFileName = '.IconSpread';
{ TIconEngine }
constructor TIconEngine.Create(const aBaseFileName: string; const aDefaultSettings: TSettings; const aLogger: TLogger);
begin
BaseFileName := aBaseFileName;
ImageList := TDictionary<string, string>.Create;
DefaultSettings := aDefaultSettings;
Settings := DefaultSettings;
LoadSettings;
PredefinedSizes := TPredefinedSizes.Create;
Log := aLogger;
end;
destructor TIconEngine.Destroy;
begin
PredefinedSizes.Free;
ImageList.Free;
inherited;
end;
procedure TIconEngine.GenerateFiles;
begin
LoadImages(FullMasterFolder);
SaveImages(FullGeneratedFolder);
end;
//see https://developer.apple.com/library/ios/qa/qa1686/_index.html
//see https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html#//apple_ref/doc/uid/TP40006556-CH27-SW2
function TIconEngine.SkipIcon(const sz: TSize): boolean;
begin
if sz.cx <> sz.cy then exit(SkipLaunch(sz));
if Settings.GenerateIPhone then
begin
case sz.cx of
57,
120,
180: exit(false);
end;
end;
if Settings.GenerateIPad then
begin
case sz.cx of
72,
76,
152: exit(false);
end;
end;
if Settings.GenerateAndroid then
begin
case sz.cx of
48,
72,
96,
144,
192: exit(false);
end;
end;
Result := true;
end;
function TIconEngine.SkipLaunch(const sz: TSize): boolean;
begin
if Settings.GenerateIPhone then
begin
case sz.cx of
750: if sz.cy = 1334 then exit(false); //6
1334: if sz.cy = 750 then exit(false); //6
1242: if sz.cy = 2208 then exit(false); //6+
2208: if sz.cy = 1242 then exit(false); //6+
640:
begin
if sz.cy = 960 then exit(false); //4
if sz.cy = 1136 then exit(false); //5
end;
end;
end;
if Settings.GenerateIPad then
begin
case sz.cx of
1536: if sz.cy = 2048 then exit(false); //2x
2048: if sz.cy = 1536 then exit(false); //2x
768: if sz.cy = 1024 then exit(false); //1x
1024: if sz.cy = 768 then exit(false); //1x
end;
end;
//http://stackoverflow.com/questions/13487124/android-splash-screen-sizes-for-ldpi-mdpi-hdpi-xhdpi-displays-eg-1024x76
if Settings.GenerateAndroid then
begin
case sz.cx of
960: if sz.cy = 720 then exit(false);
640: if sz.cy = 480 then exit(false);
470: if sz.cy = 320 then exit(false);
426: if sz.cy = 320 then exit(false);
end;
end;
Result := true;
end;
procedure TIconEngine.CopyIcon(const NodeName: string; var GeneratedInPlace: boolean; var Skip: Boolean; sz: TSize; var SourceFileName: string; var DestFileName: string);
begin
if not ImageList.TryGetValue(GetImageId(sz.Width, sz.Height), SourceFileName) then
begin
if (Settings.OnlyGenerateRequired and SkipIcon(sz)) or (not Settings.CreateNewFiles) then
begin
Skip := true;
Log(TLogChannel.Main, 'Skipped: ' + IntToStr(sz.Width) + 'x' + IntToStr(sz.Height));
exit;
end;
if not TryToGenerate(sz, NodeName, SourceFileName) then
raise Exception.Create('Image with size ' + NodeName + ' doesn''t exist. Size: ' + IntToStr(sz.Width) + 'x' + IntToStr(sz.Height));
GeneratedInPlace := true;
Log(TLogChannel.Main, 'AutoGenerated: ' + TPath.GetFileName(SourceFileName));
end;
DestFileName := GetDestFileName(Settings.OutputPattern, sz, NodeName, SourceFileName);
if not GeneratedInPlace then
Log(TLogChannel.Main, 'Renamed: ' + TPath.GetFileName(SourceFileName) + ' -> ' + TPath.GetFileName(DestFileName));
end;
function TIconEngine.GetDestFileName(const Pattern: string; sz: TSize; NodeName, SourceFileName: string): string;
begin
Result := Format(Pattern, [sz.Width, sz.Height, GetPlat(NodeName), GetTarget(NodeName), TPath.GetFileNameWithoutExtension(BaseFileName), TPath.GetFileNameWithoutExtension(SourceFileName)]);
end;
function TIconEngine.FullGeneratedFolder: string;
begin
if TPath.IsRelativePath(Settings.GeneratedFolder) then exit (TPath.Combine(TPath.GetDirectoryName(BaseFileName), Settings.GeneratedFolder));
Result := Settings.GeneratedFolder;
end;
function TIconEngine.FullMasterFolder: string;
begin
if TPath.IsRelativePath(Settings.MasterFolder) then exit (TPath.Combine(TPath.GetDirectoryName(BaseFileName), Settings.MasterFolder));
Result := Settings.MasterFolder;
end;
function TIconEngine.GetImageId(const w, h: integer): string;
begin
Result := IntToStr(w) + 'x' + IntToStr(h);
end;
function TIconEngine.GetSizeFromId(const s: string): TSize;
begin
Result.Width := StrToInt(s.Substring(0, s.IndexOf('x')));
Result.Height := StrToInt(s.Substring(s.IndexOf('x') + 1));
end;
procedure TIconEngine.LoadImages(const folder: string);
var
files: TStringDynArray;
fi, fiold: string;
id: string;
Image: TPngImage;
begin
ImageList.Clear;
files := TDirectory.GetFiles(folder, '*.png', TSearchOption.soAllDirectories);
for fi in files do
begin
Image := TPngImage.Create;
try
Image.LoadFromFile(fi);
id := GetImageId(Image.Width, Image.Height);
if ImageList.TryGetValue(id, fiold) then raise Exception.Create('Images "' + fiold + '" and "' + fi + '" in the master folder have the same dimensions (' + Id + '). Please delete one.');
ImageList.AddOrSetValue(Id , fi);
finally
Image.Free;
end;
end;
end;
procedure TIconEngine.ClearDestFolder;
var
f: TStringDynArray;
i: Integer;
begin
f := TDirectory.GetFiles(FullGeneratedFolder, '*.png', TSearchOption.soTopDirectoryOnly);
for i := 0 to Length(f) - 1 do
begin
TFile.Delete(f[i]);
end;
end;
procedure TIconEngine.SaveImages(const folder: string);
var
Proj: IXMLDocument;
PropGroups: IXmlNodeList;
ProjNode: IXmlNode;
i: Integer;
begin
ClearDestFolder;
Proj := TXMLDocument.Create(nil);
Proj.ParseOptions := Proj.ParseOptions + [poPreserveWhiteSpace];
Proj.LoadFromFile(BaseFileName);
PropGroups := Proj.ChildNodes;
for i := 0 to PropGroups.Count - 1 do
begin
ProjNode := PropGroups[i];
if ProjNode.NodeName <> 'Project' then continue;
ProcessProject(Proj, ProjNode);
end;
Proj.SaveToFile(BaseFileName);
end;
procedure TIconEngine.ProcessProject(Proj: IXmlDocument; ProjNode: IXmlNode);
var
PropGroups: IXmlNodeList;
PropGroup: IXmlNode;
i: integer;
ProcessedCount: integer;
AlreadyProcessed: TDictionary<string, boolean>;
begin
ProcessedCount := 0;
AlreadyProcessed := TDictionary<string, boolean>.Create;
try
PropGroups := ProjNode.ChildNodes;
for i := 0 to PropGroups.Count - 1 do
begin
PropGroup := PropGroups[i];
if PropGroup.NodeName <> 'PropertyGroup' then continue;
ProcessPropGroup(AlreadyProcessed, Proj, PropGroup, ProcessedCount);
end;
finally
AlreadyProcessed.Free;
end;
end;
procedure TIconEngine.ProcessPropGroup(const AlreadyProcessed: TDictionary<string, boolean>; Proj: IXmlDocument; PropGroup: IXmlNode; var ProcessedCount: integer);
var
PropGroupItems: IXmlNodeList;
Icon: IXmlNode;
i: integer;
begin
PropGroupItems := PropGroup.ChildNodes;
for i := 0 to PropGroupItems.Count - 1 do
begin
Icon := PropGroupItems[i];
if Settings.GenerateIPhone then
begin
if ProcessIcon(AlreadyProcessed, Icon, 'iPhone_AppIcon', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPhone_Spotlight', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPhone_Setting', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPhone_Launch', ProcessedCount) then continue;
end;
if Settings.GenerateIPad then
begin
if ProcessIcon(AlreadyProcessed, Icon, 'iPad_AppIcon', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPad_SpotLight', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPad_Setting', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'iPad_Launch', ProcessedCount) then continue;
end;
if (Settings.GenerateAndroid) then
begin
if ProcessIcon(AlreadyProcessed, Icon, 'Android_SplashImage', ProcessedCount) then continue;
if ProcessIcon(AlreadyProcessed, Icon, 'Android_LauncherIcon', ProcessedCount) then continue;
end;
end;
end;
function TIconEngine.ProcessIcon(const AlreadyProcessed: TDictionary<string, boolean>; Icon: IXmlNode; const prefix: string; var ProcessedCount: integer): boolean;
var
NameOnDisk: string;
SourceFileName, DestFileName: string;
sz: TSize;
GeneratedInPlace: boolean;
Skip: Boolean;
FullDest: string;
begin
Skip := false;
if (not Icon.NodeName.StartsWith(prefix)) then exit(false);
Inc(ProcessedCount);
Log(TLogChannel.Count, IntToStr(ProcessedCount));
GeneratedInPlace := false;
sz := PredefinedSizes.GetSize(Icon.NodeName);
NameOnDisk := TPath.Combine(FullMasterFolder, Icon.NodeName + '.png');
if TFile.Exists(NameOnDisk) then
begin
SourceFileName := NameOnDisk;
DestFileName := GetDestFileName(Settings.OutputPatternOnDisk, sz, Icon.NodeName, SourceFileName);
Log(TLogChannel.Main, 'Direct: ' + TPath.GetFileName(SourceFileName) + ' -> ' + TPath.GetFileName(DestFileName));
end
else
begin
CopyIcon(Icon.NodeName, GeneratedInPlace, Skip, sz, SourceFileName, DestFileName);
end;
if not Skip then
begin
FullDest := TPath.Combine(FullGeneratedFolder, DestFileName);
if not AlreadyProcessed.ContainsKey(FullDest) then
begin
if not GeneratedInPlace then TFile.Copy(SourceFileName, FullDest, true);
if (Settings.OptimizePng) then Run(Log, TLogChannel.Optimize, Settings.CmdOptimizer, FullGeneratedFolder, ' "' + FullDest + '"');
AlreadyProcessed.Add(FullDest, true);
end;
Icon.Text := TPath.Combine(Settings.GeneratedFolder, TPath.GetFileName(DestFileName));
end
else
begin
Icon.Text := '';
end;
Result := true;
end;
function TIconEngine.GetColorHex(cl: TColor): string;
var
c: integer;
begin
c := ColorToRGB(cl);
Result :=
'"#' +
IntToHex(GetRValue(c), 2) +
IntToHex(GetGValue(c), 2) +
IntToHex(GetBValue(c), 2) +
'"';
end;
function TIconEngine.FindSquareImg(const sz: TSize; out FileName: string): boolean;
var
key: string;
ksz, rsz: TSize;
FoundBigger: boolean;
begin
FileName := '';
Result := false;
FoundBigger := false;
rsz := TSize.Create(0, 0);
for key in ImageList.Keys do
begin
ksz := GetSizeFromId(key);
if (ksz.Width <> ksz.Height) then continue;
if (ksz.Width < sz.Width) then
begin
if not FoundBigger and (rsz.Width < ksz.Width) then rsz := ksz;
end else
begin
if (rsz.Width = 0) or (not FoundBigger) or (rsz.Width > ksz.Width) then rsz := ksz;
FoundBigger := true;
end;
end;
if rsz.Width > 0 then
begin
FileName := ImageList[GetImageId(rsz.Width, rsz.Height)];
exit(true);
end;
end;
function TIconEngine.CalcRatio(const sz: TSize): double;
begin
Result := sz.Width / sz.Height;
end;
function TIconEngine.NearestRatio(const DesiredRatio: double; const sz1, sz2: TSize): boolean;
begin
Result := Abs(DesiredRatio - CalcRatio(sz1)) < Abs(DesiredRatio - CalcRatio(sz2));
end;
function TIconEngine.FindRectImg(const sz: TSize; out FileName: string; out OrigSz: TSize): boolean;
var
key: string;
ksz, rsz: TSize;
Ratio: double;
FoundBigger: boolean;
begin
FileName := '';
Result := false;
FoundBigger := false;
Ratio := CalcRatio(sz);
rsz := TSize.Create(0, 0);
for key in ImageList.Keys do
begin
ksz := GetSizeFromId(key);
if (ksz.Width = ksz.Height) then continue;
if (ksz.Width < sz.Width) and (ksz.Height < ksz.Height) then
begin
if (not FoundBigger) and NearestRatio(Ratio, ksz, rsz) then rsz := ksz;
end else
begin
if (rsz.Width = 0) or (not FoundBigger) or NearestRatio(Ratio, ksz, rsz) then rsz := ksz;
FoundBigger := true;
end;
end;
if rsz.Width > 0 then
begin
FileName := ImageList[GetImageId(rsz.Width, rsz.Height)];
exit(true);
end;
end;
function TIconEngine.TryToGenerate(const sz: TSize; const NodeName: string; out SourceFileName: string): boolean;
begin
SourceFileName := TPath.Combine(FullGeneratedFolder, GetDestFileName(Settings.OutputPattern, sz, NodeName, SourceFileName));
if sz.Height <> sz.Width then exit(TryToGenerateRect(sz, SourceFileName));
Result := TryToGenerateSquare(sz, SourceFileName);
end;
function TIconEngine.TryToGenerateSquare(const sz: TSize; const SourceFileName: string): boolean;
var
OrigFileName: string;
begin
if not FindSquareImg(sz, OrigFileName) then exit(false);
Run(Log, TLogChannel.Resize, Settings.CmdResizer, TPath.GetDirectoryName(SourceFileName),
'"' + OrigFileName + '" -resize ' + IntToStr(sz.Width) + ' -verbose "' + SourceFileName + '"' );
Result := true;
end;
function TIconEngine.TryToGenerateRect(const sz: TSize; const SourceFileName: string): boolean;
var
OrigFileName: string;
OrigSz: TSize;
NewSize: string;
begin
if not FindRectImg(sz, OrigFileName, OrigSz) then exit(false);
NewSize := IntToStr(sz.Width) + 'x' + IntToStr(sz.Height);
Run(Log, TLogChannel.Resize, Settings.CmdResizer, TPath.GetDirectoryName(SourceFileName),
'"' + OrigFileName + '" -resize ' + NewSize
+ ' -gravity center -background '
+ GetColorHex(TColor(Settings.ImgBackColor))
+ ' -extent ' + NewSize
+ ' -verbose "' + SourceFileName + '"' );
Result := true;
end;
procedure TIconEngine.LoadSettings;
begin
Settings.LoadFromDisk(BaseFileName + IconSpreadFileName, DefaultSettings);
end;
procedure TIconEngine.SaveSettings(const forced: boolean);
begin
Settings.SaveToDisk(BaseFileName + IconSpreadFileName, forced);
end;
function TIconEngine.GetPlat(const s: string): string;
begin
Result := s.Substring(0, s.IndexOf('_'));
end;
function TIconEngine.GetTarget(const s: string): string;
begin
Result := s.Substring(s.IndexOf('_') + 1);
while (Result.Length > 0) and IsNumberOrX(Result[Result.Length - 1]) do Result := Result.Remove(Result.Length - 1);
end;
function TIconEngine.IsNumberOrX(const c: char): boolean;
begin
if c = 'x' then exit(true);
if (c >= '0') and (c <= '9') then exit(true);
Result := false;
end;
end.
|
unit UniStrUtils;
{$WEAKPACKAGEUNIT ON}
{ Solves a host of cross-platform/compiler char problems by introducing stable
char/string types:
Ansi* 1-byte char, any encoding multibyte-string
Uni* Best Unicode option available on platform
Unicode strings can be implemented as:
WideChar + UnicodeString on modern Delphi
WideChar + WideString on older Delphi
WideChar + string (UnicodeString) on FPC
AnsiChar + AnsiString where Unicode is not available at all
It's possible to write your own unit which redefines Uni* types and functions,
e.g. by encoding unicode in AnsiStrings, and include it after this one.
All functions are available in the following versions:
Function: string-type agnostic (uses String type of your compiler)
AnsiFunction (FunctionA): takes AnsiString
UniFunction (FunctionU): takes UniString
WideFunction (FunctionW): takes WideString specifically
Redeclares standard functions to match their names (some Ansi*-functions were
in fact Unicode in Delphi for compability) and adds missing ones:
Agnostic ones if they were forgotten (declared as Ansi* instead)
True Ansi*, if Delphi had agnostic ones under this name instead.
True Wide*, if standard libraries lack these.
And optimal Uni*.
Uses standard Delphi naming/parameter passing patterns where applicable.
Relies on conditionals to test:
UNICODE string===UnicodeString
DCC + CompilerVersion>=21 UnicodeString is avaialable in principle (maybe not as default string)
TLDR: If you need *, use *:
1-byte char AnsiChar
UTF16 char WideChar (or UTF16Char, which is the same)
Unicode char (platform best) UniChar
Platform default char char
1/multibyte encoded string AnsiString
UTF16 string (platform best) UTF16String
Windows OLE compatible string WideString
Unicode string (platform best) UniString (or UnicodeString, as redeclared here)
Platform default string string
The more cross-platform coverage you're planning to have, the more you should
rely only on functions from this module (as they'll be available and adjusted
on every platform).
}
interface
uses SysUtils, {$IFDEF MSWINDOWS}Windows,{$ENDIF} StrUtils, WideStrUtils;
{ If you lack WideStrUtils, find/write a reimplementation. }
{
String type optimizations.
Please read if you're adding functions here.
I. Casting to PWideChar
==============================
@s[1] calls UniqueStringU
PWideChar(s) calls WCharFromUStr
If you just need to get a pointer, do:
PWideChar(pointer(s))+offset*SizeOf(WideChar)
Shortcuts (if your platform supports inline):
PWC(s), PWC(s,3), etc.
II. Length
=============
Calls UniqueStringU for some reason.
If you just want to test for non-emptiness, this is faster:
pointer(s) <> nil
III. Const string
=====================
Everywhere where input parameter is a string, array of record, strive to declare
it as "const". This makes function call several times faster.
III. String Format Checking
==============================
In all Unicode-enabled Delphi "String Format Checking" is on by default.
This makes all string operations several times slower, disables const string
optimization and hides horrible errors. See:
http://www.micro-isv.asia/2008/10/needless-string-checks-with-ensureunicodestring/
It must be disabled everywhere, first thing you do.
}
type
//IntPtr is missing in older versions of Delphi and it's easier to simply redeclare it
//FPC and Delphi use a lot of different define
{$IF Defined(CPU64) or Defined(CPUX64) or Defined(CPUX86_64)}
IntPtr = int64;
{$ELSEIF Defined(CPU32) or Defined(CPUX86) or Defined(CPU386) or Defined(CPUI386) or Defined(I386) }
IntPtr = integer;
{$ELSE}
{$MESSAGE Error 'Cannot declare IntPtr for this target platform'}
{$IFEND}
type
{ UnicodeString is the best Unicode type available on the platform. On newer
compilers it's supported native, on older links to WideString. }
{$IF Defined(DCC) and (CompilerVersion >= 21)}
UniString = UnicodeString;
PUniString = PUnicodeString;
{$ELSE}
{$IF Defined(FPC)}
UniString = UnicodeString;
PUniString = PUnicodeString;
{$ELSE}
UnicodeString = WideString;
PUnicodeString = PWideString;
UniString = UnicodeString;
PUniString = PUnicodeString;
{$IFEND}
{$IFEND}
{ FPC declares char as AnsiChar even on Unicode, so if you need cross-platform
chars, use UniChar. }
UniChar = WideChar;
PUniChar = PWideChar;
TAnsiStringArray = array of AnsiString;
TUniStringArray = array of UniString;
TWideStringArray = array of WideString;
TFilenameArray = array of TFilename;
TUnicodeStringArray = TUniStringArray;
{$IFDEF UNICODE}
TStringArray = TUniStringArray;
{$ELSE}
TStringArray = TAnsiStringArray;
{$ENDIF}
//Pointers
PStringArray = ^TStringArray;
PAnsiStringArray = ^TAnsiStringArray;
PWideStringArray = ^TWideStringArray;
PUniStringArray = ^TUniStringArray;
{$IF Defined(DCC) and (CompilerVersion < 21)}
//Not declared in older versions
UCS2Char = WideChar;
PUCS2Char = PWideChar;
UCS4Char = type LongWord;
PUCS4Char = ^UCS4Char;
TUCS4CharArray = array [0..$effffff] of UCS4Char;
PUCS4CharArray = ^TUCS4CharArray;
UCS4String = array of UCS4Char;
{ Older compilers do not auto-convert AnsiString encodings on assigments so
it's safe to store UTF8 and RawByte in it }
UTF8String = AnsiString;
PUTF8String = ^UTF8String;
RawByteString = AnsiString;
PRawByteString = ^RawByteString;
{$IFEND}
{$IFDEF UNICODE}
(*
In Unicode Delphi versions some Ansi functions are declared as Unicode for
compability. E.g.:
UpperCase - takes string and works only with ASCII
AnsiUpperCase - takes string and understands unicode
These are "fair versions" of those functions:
*)
function AnsiPos(const Substr, S: AnsiString): Integer;
function AnsiStringReplace(const S, OldPattern, NewPattern: AnsiString;
Flags: TReplaceFlags): AnsiString;
function AnsiReplaceStr(const AText, AFromText, AToText: AnsiString): AnsiString; inline;
function AnsiReplaceText(const AText, AFromText, AToText: AnsiString): AnsiString; inline;
function AnsiUpperCase(const S: AnsiString): AnsiString;
function AnsiLowerCase(const S: AnsiString): AnsiString;
function AnsiCompareStr(const S1, S2: AnsiString): Integer;
function AnsiSameStr(const S1, S2: AnsiString): Boolean; inline;
function AnsiCompareText(const S1, S2: AnsiString): Integer;
function AnsiSameText(const S1, S2: AnsiString): Boolean; inline;
{$ENDIF}
{ Unicode versions of WideStrUtils functions. }
function UStrPCopy(Dest: PUniChar; const Source: UnicodeString): PUniChar; inline;
function UStrPLCopy(Dest: PUniChar; const Source: UnicodeString; MaxLen: Cardinal): PUniChar; inline;
(*
These are present in SysUtils/StrUtils/WideStrUtils
function WideUpperCase(const S: WideString): WideString;
function WideLowerCase(const S: WideString): WideString;
...etc
But we have unicode versions (always optimal):
*)
function UniLastChar(const S: UnicodeString): PUniChar; inline;
function UniQuotedStr(const S: UnicodeString; Quote: UniChar): UnicodeString; inline;
function UniExtractQuotedStr(var Src: PUniChar; Quote: UniChar): UnicodeString; inline;
function UniDequotedStr(const S: UnicodeString; AQuote: UniChar): UnicodeString; inline;
function UniAdjustLineBreaks(const S: UnicodeString; Style: TTextLineBreakStyle = tlbsCRLF): UnicodeString; inline;
function UniStringReplace(const S, OldPattern, NewPattern: UnicodeString;
Flags: TReplaceFlags): UnicodeString; inline;
function UniReplaceStr(const AText, AFromText, AToText: UnicodeString): UnicodeString; inline;
function UniReplaceText(const AText, AFromText, AToText: UnicodeString): UnicodeString; inline;
function UniUpperCase(const S: UnicodeString): UnicodeString; inline;
function UniLowerCase(const S: UnicodeString): UnicodeString; inline;
function UniCompareStr(const S1, S2: UnicodeString): Integer; inline;
function UniSameStr(const S1, S2: UnicodeString): Boolean; inline;
function UniCompareText(const S1, S2: UnicodeString): Integer; inline;
function UniSameText(const S1, S2: UnicodeString): Boolean; inline;
(*
Wide-версии стандартных функций.
На новых компиляторах функции линкуются к системным. На старых реализованы с нуля.
*)
//remember, this returns the BYTE offset
function WidePos(const Substr, S: UnicodeString): Integer;
function WideMidStr(const AText: UnicodeString; const AStart: integer; const ACount: integer): UnicodeString;
//Логика функций сравнения та же, что у Ansi-версий: сравнение лингвистическое,
//с учётом юникод-цепочек, а не бинарное, по байтам.
function WideStrComp(S1, S2: PWideChar): Integer;
function WideStrIComp(S1, S2: PWideChar): Integer;
function WideStartsStr(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
function WideEndsStr(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
function WideContainsStr(const AText: UnicodeString; const ASubText: UnicodeString): boolean;
function WideStartsText(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
function WideEndsText(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
function WideContainsText(const AText: UnicodeString; const ASubText: UnicodeString): boolean;
(*
Далее идут вспомогательные функции библиотеки, написанные во всех версиях с нуля.
Юникод-версии представлены как FunctionW или WideFunction.
*)
//Поиск строки в массивах
//Wide-версии нет, поскольку TWideStringArray ==def== TUniStringArray
function AnsiStrInArray(const a: TAnsiStringArray; const s: AnsiString): integer;
function AnsiTextInArray(const a: TAnsiStringArray; const s: AnsiString): integer;
function UniStrInArray(const a: TUniStringArray; const s: UnicodeString): integer;
function UniTextInArray(const a: TUniStringArray; const s: UnicodeString): integer;
function StrInArray(const a: TStringArray; const s: string): integer;
function TextInArray(const a: TStringArray; const s: string): integer;
//Splits a string by a single type of separators. Ansi version.
function StrSplitA(s: PAnsiChar; sep: AnsiChar): TAnsiStringArray;
function StrSplitW(s: PUniChar; sep: UniChar): TUniStringArray;
function StrSplit(s: PChar; sep: char): TStringArray;
//Same, just with Strings
function AnsiSepSplit(const s: AnsiString; sep: AnsiChar): TAnsiStringArray;
function WideSepSplit(const s: UnicodeString; sep: UniChar): TUniStringArray;
function SepSplit(const s: string; sep: char): TStringArray;
//Бьёт строку по нескольким разделителям, с учётом кавычек
function StrSplitExA(s: PAnsiChar; sep: PAnsiChar; quote: AnsiChar): TAnsiStringArray;
function StrSplitExW(s: PUnichar; sep: PUniChar; quote: UniChar): TUniStringArray;
function StrSplitEx(s: PChar; sep: PChar; quote: Char): TStringArray;
//Joins a string array usng the specified separator
function AnsiSepJoin(const s: TAnsiStringArray; sep: AnsiChar): AnsiString; overload;
function WideSepJoin(const s: TUniStringArray; sep: UniChar): UnicodeString; overload;
function SepJoin(const s: TStringArray; sep: Char): string; overload;
//Same, just receives a point to a first string, and their number
function AnsiSepJoin(s: PAnsiString; cnt: integer; sep: AnsiChar): AnsiString; overload;
function WideSepJoin(s: PUniString; cnt: integer; sep: UniChar): UnicodeString; overload;
function SepJoin(s: PString; cnt: integer; sep: Char): string; overload;
//Возвращает в виде WideString строку PWideChar, но не более N символов
//Полезно для чтения всяких буферов фиксированного размера, где не гарантирован ноль.
function AnsiStrFromBuf(s: PAnsiChar; MaxLen: integer): AnsiString;
function WideStrFromBuf(s: PUniChar; MaxLen: integer): UnicodeString;
function StrFromBuf(s: PChar; MaxLen: integer): string;
//Checks if a char is a number
function AnsiCharIsNumber(c: AnsiChar): boolean; inline;
function WideCharIsNumber(c: UniChar): boolean; inline;
function CharIsNumber(c: char): boolean; inline;
//Check if a char is a latin symbol
function AnsiCharIsLatinSymbol(c: AnsiChar): boolean; inline;
function WideCharIsLatinSymbol(c: UniChar): boolean; inline;
function CharIsLatinSymbol(c: char): boolean; inline;
//Check if a string is composed only from numbers and latin symbols
function AnsiStrIsLnOnly(const str: AnsiString): boolean;
function WideStrIsLnOnly(const str: UnicodeString): boolean;
function StrIsLnOnly(const str: string): boolean;
//These have significantly different implementation when working with Ansi code page,
//so they're implemented only in Unicode yet.
function IsDigit(c: UniChar): boolean;
function IsHiragana(c: UniChar): boolean;
function IsKatakana(c: UniChar): boolean;
function IsKana(c: UniChar): boolean;
function IsKanji(c: UniChar): boolean;
function IsCJKSymbolOrPunctuation(c: UniChar): boolean;
function IsFullWidthCharacter(c: UniChar): boolean;
function ContainsKanji(const s: UniString): boolean;
//Возвращает номер символа, на который указывает ptr, в строке str
function AnsiPcharInd(str, ptr: PAnsiChar): integer;
function WidePcharInd(str, ptr: PUniChar): integer;
function PcharInd(str, ptr: PChar): integer;
//Возвращает длину отрезка PChar в символах.
function CharLenA(p1, p2: PAnsiChar): integer;
function CharLenW(p1, p2: PUniChar): integer;
function CharLen(p1, p2: PChar): integer;
//Находит конец строки
function StrEndA(s: PAnsiChar): PAnsiChar;
function StrEndW(s: PUniChar): PUniChar;
function StrEnd(s: PChar): PChar;
//Быстрое обращение к следующему-предыдущему символу
function NextChar(p: PAnsiChar; c: integer = 1): PAnsiChar; overload;
function PrevChar(p: PAnsiChar; c: integer = 1): PAnsiChar; overload;
function NextChar(p: PWideChar; c: integer = 1): PWideChar; overload;
function PrevChar(p: PWideChar; c: integer = 1): PWideChar; overload;
{ Арифметика указателей }
function PwcOff(var a; n: integer): PWideChar; inline;
function PwcCmp(var a; var b): integer; inline; overload;
function PwcCmp(var a; an: integer; var b; bn: integer): integer; inline; overload;
//Возвращает подстроку с заданного места и нужного размера.
function StrSubLA(beg: PAnsiChar; len: integer): AnsiString;
function StrSubLW(beg: PUniChar; len: integer): UnicodeString;
function StrSubL(beg: PChar; len: integer): string;
//Возвращает подстроку с заданного места и до заданного места не включительно.
function StrSubA(beg: PAnsiChar; en: PAnsiChar): AnsiString;
function StrSubW(beg: PUniChar; en: PUniChar): UnicodeString;
function StrSub(beg: PChar; en: PChar): string;
//Обратная совместимость
function SubStrPchA(beg, en: PAnsiChar): AnsiString;
function SubStrPchW(beg, en: PUniChar): UnicodeString;
function SubStrPch(beg, en: pchar): string;
//Scans the specified string for the specfied character. Starts at position <start_at>.
//Ends at <end_at> - 1 symbols. Returns first symbol index in string or -1 if not found any.
function AnsiFindChar(const s: AnsiString; c: AnsiChar; start_at: integer = 1; end_at: integer = -1): integer;
function WideFindChar(const s: UnicodeString; c: UniChar; start_at: integer = 1; end_at: integer = -1): integer;
function FindChar(const s: string; c: char; start_at: integer = 1; end_at: integer = -1): integer; inline;
//Дополнения к стандартной дельфийской StrScan
function StrScanA(str: PAnsiChar; chr: AnsiChar): PAnsiChar;
function StrScanW(str: PUniChar; chr: UniChar): PUniChar;
//Ищет любой из перечисленных символов, иначе возвращает nil.
function StrScanAnyA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar;
function StrScanAnyW(str: PUniChar; symbols: PUniChar): PUniChar;
function StrScanAny(str: PChar; symbols: PChar): PChar;
//Ищет любой из перечисленных символов, иначе возвращает указатель на конец строки.
function StrScanEndA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar;
function StrScanEndW(str: PUniChar; symbols: PUniChar): PWideChar;
function StrScanEnd(str: PChar; symbols: PChar): PChar;
(*
Обратная совместимость:
1. Функции StrScanAny раньше назывались StrPosAny.
2. Функции StrScanDef раньше назывались StrScan.
Оба переименования совершены с целью унификации названий с Дельфи.
StrScanAny ведёт себя в точности как StrScan, только для нескольких символов.
*)
//Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него.
//Если такого символа нет, возвращает остаток строки и nil.
function AnsiReadUpToNext(str: PAnsiChar; const cs: AnsiString; out block: AnsiString): PAnsiChar;
function WideReadUpToNext(str: PUniChar; const cs: UnicodeString; out block: UnicodeString): PUniChar;
function ReadUpToNext(str: PChar; const cs: string; out block: string): PChar;
//Сравнивает строки до окончания любой из них.
function StrCmpNext(a, b: PChar): boolean; inline;
//Возвращает длину совпадающего участка c начала строк, в символах, включая нулевой.
function StrMatch(a, b: PChar): integer; inline;
//Пропускает все символы до первого, не входящего в chars (null-term string)
procedure SkipChars(var pc: PChar; chars: PChar);
//Removes quote characters from around the string, if they exist.
//Duplicate: UniDequotedStr, although this one is more powerful
function AnsiStripQuotes(const s: AnsiString; qc1, qc2: AnsiChar): AnsiString;
function WideStripQuotes(const s: UnicodeString; qc1, qc2: UniChar): UnicodeString;
function StripQuotes(const s: string; qc1, qc2: char): string;
//Удаляет пробелы из конца строки - версия для String
function STrimStartA(const s: AnsiString; sep: AnsiChar = ' '): AnsiString;
function STrimStartW(const s: UnicodeString; sep: UniChar = ' '): UnicodeString;
function STrimStart(const s: string; sep: Char = ' '): string;
function STrimEndA(const s: AnsiString; sep: AnsiChar = ' '): AnsiString;
function STrimEndW(const s: UnicodeString; sep: UniChar = ' '): UnicodeString;
function STrimEnd(const s: string; sep: Char = ' '): string;
function STrimA(const s: AnsiString; sep: AnsiChar = ' '): AnsiString;
function STrimW(const s: UnicodeString; sep: UniChar = ' '): UnicodeString;
function STrim(const s: string; sep: Char = ' '): string;
//Удаляет пробелы из конца строки - версия для PChar
function PTrimStartA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString;
function PTrimStartW(s: PUniChar; sep: UniChar = ' '): UnicodeString;
function PTrimStart(s: PChar; sep: Char = ' '): string;
function PTrimEndA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString;
function PTrimEndW(s: PUniChar; sep: UniChar = ' '): UnicodeString;
function PTrimEnd(s: PChar; sep: Char = ' '): string;
function PTrimA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString;
function PTrimW(s: PUniChar; sep: UniChar = ' '): UnicodeString;
function PTrim(s: PChar; sep: Char = ' '): string;
//Удаляет пробелы из начала и конца строки, заданных прямо.
function BETrimA(beg, en: PAnsiChar; sep: AnsiChar = ' '): AnsiString;
function BETrimW(beg, en: PUniChar; sep: UniChar = ' '): UnicodeString;
function BETrim(beg, en: PChar; sep: Char = ' '): string;
{ Binary/string conversion }
//Преобразует данные в цепочку hex-кодов.
function BinToHex(ptr: pbyte; sz: integer): AnsiString;
//Преобразует массив байт в цепочку hex-кодов.
function DataToHex(data: array of byte): AnsiString;
//Декодирует один hex-символ в число от 1 до 16
function HexCharValue(c: AnsiChar): byte; inline;
//Декодирует строку из hex-пар в данные. Место под данные должно быть выделено заранее
procedure HexToBin(const s: AnsiString; p: pbyte; size: integer);
{ Codepage utils }
{$IFDEF MSWINDOWS}
//Превращает один символ в Wide/Ansi
function ToWideChar(c: AnsiChar; cp: cardinal): WideChar;
function ToChar(c: WideChar; cp: cardinal): AnsiChar;
//Превращает строку в Wide/Ansi
function ToWideString(const s: AnsiString; cp: cardinal): WideString;
function ToString(const s: WideString; cp: cardinal): AnsiString;
//Превращает буфер заданной длины в Wide/Ansi
function BufToWideString(s: PAnsiChar; len: integer; cp: cardinal): WideString;
function BufToString(s: PWideChar; len: integer; cp: cardinal): AnsiString;
//Меняет кодировку Ansi-строки
function Convert(const s: AnsiString; cpIn, cpOut: cardinal): AnsiString;
//Меняет кодировку Ansi-строки с системной на консольную и наоборот
function WinToOEM(const s: AnsiString): AnsiString; inline;
function OEMToWin(const s: AnsiString): AnsiString; inline;
{$ENDIF}
type
(*
StringBuilder.
Сбросьте перед работой с помощью Clear. Добавляйте куски с помощью Add.
В конце либо используйте, как есть (длина в Used), либо обрежьте с помощью Pack.
*)
TAnsiStringBuilder = record
Data: AnsiString;
Used: integer;
procedure Clear;
function Pack: AnsiString;
procedure Add(c: AnsiChar); overload;
procedure Add(pc: PAnsiChar); overload;
procedure Add(const s: AnsiString); overload;
procedure Pop(SymbolCount: integer = 1);
end;
PAnsiStringBuilder = ^TAnsiStringBuilder;
TUniStringBuilder = record
Data: UnicodeString;
Used: integer;
procedure Clear;
function Pack: UnicodeString;
procedure Add(c: UniChar); overload;
procedure Add(pc: PUniChar); overload;
procedure Add(const s: UnicodeString); overload;
procedure Pop(SymbolCount: integer = 1);
end;
PUniStringBuilder = ^TUniStringBuilder;
//Обратная совместимость
TWideStringBuilder = TUniStringBuilder;
PWideStringBuilder = PUniStringBuilder;
{$IFDEF UNICODE}
TStringBuilder = TUniStringBuilder;
PStringBuilder = ^TStringBuilder;
{$ELSE}
TStringBuilder = TAnsiStringBuilder;
PStringBuilder = ^TStringBuilder;
{$ENDIF}
{ Html encoding }
type
TUrlEncodeOption = (
ueNoSpacePlus //Encode space as %20, not "+"
);
TUrlEncodeOptions = set of TUrlEncodeOption;
function UrlEncode(const s: UnicodeString; options: TUrlEncodeOptions = []): AnsiString;
function HtmlEscape(const s: UnicodeString): UnicodeString;
function HtmlEscapeObvious(const s: UnicodeString): UnicodeString;
function HtmlEscapeToAnsi(const s: UnicodeString): AnsiString;
implementation
////////////////////////////////////////////////////////////////////////////////
{$IFDEF UNICODE}
(*
Все реализации скопированы у Борланд.
*)
function AnsiPos(const Substr, S: AnsiString): Integer;
var
P: PAnsiChar;
begin
Result := 0;
P := AnsiStrPos(PAnsiChar(S), PAnsiChar(SubStr));
if P <> nil then
Result := (IntPtr(P) - IntPtr(PAnsiChar(S))) div SizeOf(AnsiChar) + 1;
end;
function AnsiStringReplace(const S, OldPattern, NewPattern: AnsiString;
Flags: TReplaceFlags): AnsiString;
var
SearchStr, Patt, NewStr: AnsiString;
Offset: Integer;
begin
if rfIgnoreCase in Flags then
begin
SearchStr := AnsiUpperCase(S);
Patt := AnsiUpperCase(OldPattern);
end else
begin
SearchStr := S;
Patt := OldPattern;
end;
NewStr := S;
Result := '';
while SearchStr <> '' do
begin
Offset := AnsiPos(Patt, SearchStr);
if Offset = 0 then
begin
Result := Result + NewStr;
Break;
end;
Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
if not (rfReplaceAll in Flags) then
begin
Result := Result + NewStr;
Break;
end;
SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
end;
end;
function AnsiReplaceStr(const AText, AFromText, AToText: AnsiString): AnsiString;
begin
Result := AnsiStringReplace(AText, AFromText, AToText, [rfReplaceAll]);
end;
function AnsiReplaceText(const AText, AFromText, AToText: AnsiString): AnsiString;
begin
Result := AnsiStringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]);
end;
function AnsiUpperCase(const S: AnsiString): AnsiString;
{$IFDEF MSWINDOWS}
var
Len: Integer;
begin
Len := Length(S);
SetString(Result, PAnsiChar(S), Len);
if Len > 0 then
CharUpperBuffA(PAnsiChar(Result), Len);
end;
{$ELSE}
begin
//No other way
Result := AnsiString(UpperCase(string(S)));
end;
{$ENDIF}
function AnsiLowerCase(const S: AnsiString): AnsiString;
{$IFDEF MSWINDOWS}
var
Len: Integer;
begin
Len := Length(S);
SetString(Result, PAnsiChar(S), Len);
if Len > 0 then
CharLowerBuffA(PAnsiChar(Result), Len);
end;
{$ELSE}
begin
Result := AnsiString(LowerCase(string(S)));
end;
{$ENDIF}
function AnsiCompareStr(const S1, S2: AnsiString): Integer;
{$IFDEF MSWINDOWS}
begin
Result := CompareStringA(LOCALE_USER_DEFAULT, 0, PAnsiChar(S1), Length(S1),
PAnsiChar(S2), Length(S2)) - CSTR_EQUAL;
end;
{$ELSE}
begin
Result := CompareStr(string(S1), string(S2));
end;
{$ENDIF}
function AnsiSameStr(const S1, S2: AnsiString): Boolean;
begin
Result := AnsiCompareStr(S1, S2) = 0;
end;
function AnsiCompareText(const S1, S2: AnsiString): Integer;
{$IFDEF MSWINDOWS}
begin
Result := CompareStringA(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PAnsiChar(S1),
Length(S1), PAnsiChar(S2), Length(S2)) - CSTR_EQUAL;
end;
{$ELSE}
begin
Result := AnsiCompareText(string(S1), string(S2));
end;
{$ENDIF}
function AnsiSameText(const S1, S2: AnsiString): Boolean;
begin
Result := AnsiCompareText(S1, S2) = 0;
end;
{$ENDIF}
(*
Unicode versions of WideStrUtils functions.
*)
function UStrPCopy(Dest: PUniChar; const Source: UnicodeString): PUniChar;
begin
Result := WStrPLCopy(Dest, PWideChar(Source), Length(Source));
end;
function UStrPLCopy(Dest: PUniChar; const Source: UnicodeString; MaxLen: Cardinal): PUniChar;
begin
Result := WStrLCopy(Dest, PWideChar(Source), MaxLen);
end;
function UniLastChar(const S: UnicodeString): PUniChar;
begin
{Copied from WideStrUtils for speed}
if S = '' then
Result := nil
else
Result := @S[Length(S)];
end;
function UniQuotedStr(const S: UnicodeString; Quote: UniChar): UnicodeString;
begin
{$IFDEF UNICODE}
//There's no "agnostic" version of QuotedStr. This one works for "strings" on Unicode.
Result := AnsiQuotedStr(S, Quote);
{$ELSE}
Result := WideQuotedStr(S, Quote);
{$ENDIF}
end;
function UniExtractQuotedStr(var Src: PUniChar; Quote: UniChar): UnicodeString;
begin
{$IFDEF UNICODE}
//There's no "agnostic" version of ExtractQuotedStr.
Result := AnsiExtractQuotedStr(Src, Quote);
{$ELSE}
Result := WideExtractQuotedStr(Src, Quote);
{$ENDIF}
end;
function UniDequotedStr(const S: UnicodeString; AQuote: UniChar): UnicodeString;
begin
{$IFDEF UNICODE}
//There's no "agnostic" version of DequotedStr.
Result := AnsiDequotedStr(S, AQuote);
{$ELSE}
Result := WideDequotedStr(S, AQuote);
{$ENDIF}
end;
function UniAdjustLineBreaks(const S: UnicodeString; Style: TTextLineBreakStyle = tlbsCRLF): UnicodeString;
begin
{$IFDEF UNICODE}
Result := AdjustLineBreaks(S, Style);
{$ELSE}
Result := WideAdjustLineBreaks(S, Style);
{$ENDIF}
end;
function UniStringReplace(const S, OldPattern, NewPattern: UnicodeString;
Flags: TReplaceFlags): UnicodeString;
begin
{$IFDEF UNICODE}
Result := StringReplace(S, OldPattern, NewPattern, Flags);
{$ELSE}
Result := WideStringReplace(S, OldPattern, NewPattern, Flags);
{$ENDIF}
end;
function UniReplaceStr(const AText, AFromText, AToText: UnicodeString): UnicodeString;
begin
{$IFDEF UNICODE}
Result := ReplaceStr(AText, AFromText, AToText);
{$ELSE}
Result := WideReplaceStr(AText, AFromText, AToText);
{$ENDIF}
end;
function UniReplaceText(const AText, AFromText, AToText: UnicodeString): UnicodeString;
begin
{$IFDEF UNICODE}
Result := ReplaceText(AText, AFromText, AToText);
{$ELSE}
Result := WideReplaceText(AText, AFromText, AToText);
{$ENDIF}
end;
(*
Note about UpperCase/LowerCase:
1. SysUtils.UpperCase sucks and works only with dirty ANSI, even on unicode. Don't use it!
2. SysUtils.AnsiUpperCase works for Unicode on Unicode compilers.
3. UniStrUtils.AnsiUpperCase works as pure, but proper Ansi/multibyte, everywhere.
*)
function UniUpperCase(const S: UnicodeString): UnicodeString;
begin
{$IFDEF UNICODE}
Result := SysUtils.AnsiUpperCase(S);
{$ELSE}
Result := WideUpperCase(S);
{$ENDIF}
end;
function UniLowerCase(const S: UnicodeString): UnicodeString;
begin
{$IFDEF UNICODE}
Result := SysUtils.AnsiLowerCase(S);
{$ELSE}
Result := WideLowerCase(S);
{$ENDIF}
end;
function UniCompareStr(const S1, S2: UnicodeString): Integer;
begin
{$IFDEF UNICODE}
Result := CompareStr(S1, S2);
{$ELSE}
Result := WideCompareStr(S1, S2);
{$ENDIF}
end;
function UniSameStr(const S1, S2: UnicodeString): Boolean;
begin
{$IFDEF UNICODE}
Result := SameStr(S1, S2);
{$ELSE}
Result := WideSameStr(S1, S2);
{$ENDIF}
end;
function UniCompareText(const S1, S2: UnicodeString): Integer;
begin
{$IFDEF UNICODE}
Result := CompareText(S1, S2);
{$ELSE}
Result := WideCompareText(S1, S2);
{$ENDIF}
end;
function UniSameText(const S1, S2: UnicodeString): Boolean;
begin
{$IFDEF UNICODE}
Result := SameText(S1, S2);
{$ELSE}
Result := WideSameText(S1, S2);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
//Wide versions of standard routines.
//На новых компиляторах все функции линкуются к системным. На старых реализованы с нуля.
//Ansi-версии и дефолтные версии присутствовали и присутствуют в хедерах.
function WidePos(const Substr, S: UnicodeString): Integer;
{$IFDEF UNICODE}
begin
Result := Pos(SubStr, S);
end;
{$ELSE}
var
P: PWideChar;
begin
Result := 0;
P := WStrPos(PWideChar(S), PWideChar(SubStr));
if P <> nil then
Result := IntPtr(P) - IntPtr(PWideChar(S)) + 1;
end;
{$ENDIF}
//Returns substring of s, starting at <start> characters and continuing <length> of them.
function WideMidStr(const AText: UnicodeString; const AStart: integer; const ACount: integer): UnicodeString;
{$IFDEF UNICODE}
begin
Result := StrUtils.MidStr(AText, AStart, ACount);
end;
{$ELSE}
begin
SetLength(Result, ACount);
if ACount <= Length(AText) - AStart then
//If there's enough symbols in s, copy len of them
Move(AText[AStart], Result[1], ACount*SizeOf(AText[1]))
else
//Else just copy everything that we can
Move(AText[AStart], Result[1], (Length(AText)-AStart)*SizeOf(AText[1]));
end;
{$ENDIF}
function WideStrComp(S1, S2: PWideChar): Integer;
begin
{$IFDEF UNICODE}
//На Unicode-компиляторах эта функция существует под Ansi-названием в Wide-конфигурации.
Result := AnsiStrComp(S1, S2);
{$ELSE}
Result := CompareStringW(LOCALE_USER_DEFAULT, 0, S1, -1, S2, -1) - 2;
{$ENDIF}
end;
function WideStrIComp(S1, S2: PWideChar): Integer;
begin
{$IFDEF UNICODE}
//На Unicode-компиляторах эта функция существует под Ansi-названием в Wide-конфигурации.
Result := AnsiStrIComp(S1, S2);
{$ELSE}
Result := CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, S1, -1,
S2, -1) - 2;
{$ENDIF}
end;
function WideStartsStr(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
{$IFDEF UNICODE}
begin
Result := StrUtils.StartsStr(ASubText, AText);
end;
{$ELSE}
begin
if Length(ASubText) > Length(AText) then
Result := false
else
//Сравниваем только начало
Result := CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE,
PWideChar(ASubText), -1, PWideChar(AText), Length(ASubText)) = 2;
end;
{$ENDIF}
function WideEndsStr(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
{$IFDEF UNICODE}
begin
Result := StrUtils.EndsStr(ASubText, AText);
end;
{$ELSE}
var
SubTextLocation: Integer;
begin
SubTextLocation := Length(AText) - Length(ASubText) + 1;
if (SubTextLocation > 0) and (ASubText <> '') then
Result := WideStrComp(Pointer(ASubText), Pointer(@AText[SubTextLocation])) = 0
else
Result := False;
end;
{$ENDIF}
//Аргументы в обратном порядке, как и у AnsiContainsStr
function WideContainsStr(const AText: UnicodeString; const ASubText: UnicodeString): boolean;
begin
{$IFDEF UNICODE}
Result := StrUtils.ContainsStr(AText, ASubText);
{$ELSE}
Result := (WStrPos(PWideChar(AText), PWideChar(ASubText)) <> nil);
{$ENDIF}
end;
function WideStartsText(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
begin
{$IFDEF UNICODE}
Result := StrUtils.StartsText(ASubText, AText);
{$ELSE}
Result := WideStartsStr(WideLowerCase(ASubText), WideLowerCase(AText));
{$ENDIF}
end;
function WideEndsText(const ASubText: UnicodeString; const AText: UnicodeString): boolean;
begin
{$IFDEF UNICODE}
Result := StrUtils.EndsText(ASubText, AText);
{$ELSE}
Result := WideEndsStr(WideLowerCase(ASubText), WideLowerCase(AText));
{$ENDIF}
end;
//Аргументы в обратном порядке, как и у AnsiContainsText
function WideContainsText(const AText: UnicodeString; const ASubText: UnicodeString): boolean;
begin
{$IFDEF UNICODE}
Result := StrUtils.StartsText(AText, ASubText);
{$ELSE}
Result := WideContainsStr(WideLowerCase(AText), WideLowerCase(ASubText));
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
/// Находит индекс первого появления строки в массиве
function AnsiStrInArray(const a: TAnsiStringArray; const s: AnsiString): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(a)-1 do
if AnsiSameStr(s, a[i]) then begin
Result := i;
break;
end;
end;
function AnsiTextInArray(const a: TAnsiStringArray; const s: AnsiString): integer;
var i: integer;
ts: AnsiString;
begin
Result := -1;
ts := AnsiUpperCase(s);
for i := 0 to Length(a)-1 do
if AnsiSameStr(ts, a[i]) then begin
Result := i;
break;
end;
end;
function UniStrInArray(const a: TUniStringArray; const s: UnicodeString): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(a)-1 do
if UniSameStr(s, a[i]) then begin
Result := i;
break;
end;
end;
function UniTextInArray(const a: TUniStringArray; const s: UnicodeString): integer;
var i: integer;
ts: UnicodeString;
begin
Result := -1;
ts := UniUpperCase(s);
for i := 0 to Length(a)-1 do
if UniSameStr(ts, a[i]) then begin
Result := i;
break;
end;
end;
function StrInArray(const a: TStringArray; const s: string): integer;
begin
{$IFDEF UNICODE}
Result := UniStrInArray(a, s);
{$ELSE}
Result := AnsiStrInArray(a, s);
{$ENDIF}
end;
function TextInArray(const a: TStringArray; const s: string): integer;
begin
{$IFDEF UNICODE}
Result := UniTextInArray(a, s);
{$ELSE}
Result := AnsiTextInArray(a, s);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
(*
Splits a string by a single type of separators.
A,,,B => five items (A,,,B)
*)
function StrSplitA(s: PAnsiChar; sep: AnsiChar): TAnsiStringArray;
var pc: PAnsiChar;
i: integer;
begin
if (s=nil) or (s^=#00) then begin
SetLength(Result, 0);
exit;
end;
//Count the number of separator characters
i := 1;
pc := s;
while pc^ <> #00 do begin
if pc^=sep then
Inc(i);
Inc(pc);
end;
//Reserve array
SetLength(Result, i);
//Parse
i := 0;
pc := s;
while pc^<>#00 do
if pc^=sep then begin
Result[i] := StrSubA(s, pc);
Inc(i);
Inc(pc);
s := pc;
end else
Inc(pc);
//Last time
Result[i] := StrSubA(s, pc);
end;
function StrSplitW(s: PUniChar; sep: UniChar): TUniStringArray;
var pc: PUniChar;
i: integer;
begin
if (s=nil) or (s^=#00) then begin
SetLength(Result, 0);
exit;
end;
//Count the number of separator characters
i := 1;
pc := s;
while pc^ <> #00 do begin
if pc^=sep then
Inc(i);
Inc(pc);
end;
//Reserve array
SetLength(Result, i);
//Parse
i := 0;
pc := s;
while pc^<>#00 do
if pc^=sep then begin
Result[i] := StrSubW(s, pc);
Inc(i);
Inc(pc);
s := pc;
end else
Inc(pc);
//Last time
Result[i] := StrSubW(s, pc);
end;
function StrSplit(s: PChar; sep: char): TStringArray;
begin
{$IFDEF UNICODE}
Result := StrSplitW(PWideChar(s), sep);
{$ELSE}
Result := StrSplitA(PAnsiChar(s), sep);
{$ENDIF}
end;
function AnsiSepSplit(const s: AnsiString; sep: AnsiChar): TAnsiStringArray;
begin
Result := StrSplitA(PAnsiChar(s), sep);
end;
function WideSepSplit(const s: UnicodeString; sep: UniChar): TUniStringArray;
begin
Result := StrSplitW(PWideChar(s), sep);
end;
function SepSplit(const s: string; sep: char): TStringArray;
begin
{$IFDEF UNICODE}
Result := StrSplitW(PWideChar(s), sep);
{$ELSE}
Result := StrSplitA(PAnsiChar(s), sep);
{$ENDIF}
end;
function StrSplitExA(s: PAnsiChar; sep: PAnsiChar; quote: AnsiChar): TAnsiStringArray;
var pc: PAnsiChar;
i: integer;
in_q: boolean;
function match_q(c: AnsiChar): boolean;
var sc: PAnsiChar;
begin
sc := sep;
while (sc^<>#00) and (sc^<>c) do Inc(sc);
Result := (sc^=c);
end;
begin
//Count the number of separator characters not between
i := 1;
pc := s;
in_q := false;
while pc^ <> #00 do begin
if pc^=quote then
in_q := not in_q
else
if (not in_q) and match_q(pc^) then
Inc(i);
Inc(pc);
end;
//Reserve array
SetLength(Result, i);
//Parse
i := 0;
pc := s;
in_q := false;
while pc^<>#00 do begin
if pc^=quote then begin
in_q := not in_q;
Inc(pc);
end else
if (not in_q) and match_q(pc^) then begin
Result[i] := StrSubA(s, pc);
Inc(i);
Inc(pc);
s := pc;
end else
Inc(pc);
end;
//Last time
Result[i] := StrSubA(s, pc);
end;
function StrSplitExW(s: PUnichar; sep: PUniChar; quote: UniChar): TUniStringArray;
var pc: PUniChar;
i: integer;
in_q: boolean;
function match_q(c: UniChar): boolean;
var sc: PUniChar;
begin
sc := sep;
while (sc^<>#00) and (sc^<>c) do Inc(sc);
Result := (sc^=c);
end;
begin
//Count the number of separator characters not between
i := 1;
pc := s;
in_q := false;
while pc^ <> #00 do begin
if pc^=quote then
in_q := not in_q
else
if (not in_q) and match_q(pc^) then
Inc(i);
Inc(pc);
end;
//Reserve array
SetLength(Result, i);
//Parse
i := 0;
pc := s;
in_q := false;
while pc^<>#00 do begin
if pc^=quote then begin
in_q := not in_q;
Inc(pc);
end else
if (not in_q) and match_q(pc^) then begin
Result[i] := StrSubW(s, pc);
Inc(i);
Inc(pc);
s := pc;
end else
Inc(pc);
end;
//Last time
Result[i] := StrSubW(s, pc);
end;
function StrSplitEx(s: PChar; sep: PChar; quote: Char): TStringArray;
begin
{$IFDEF UNICODE}
Result := StrSplitExW(PWideChar(s), PWideChar(sep), quote);
{$ELSE}
Result := StrSplitExA(PAnsiChar(s), PAnsiChar(sep), quote);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
//Joins a string array usng the specified separator.
function AnsiSepJoin(const s: TAnsiStringArray; sep: AnsiChar): AnsiString;
begin
Result := AnsiSepJoin(@s[0], Length(s), sep);
end;
function WideSepJoin(const s: TUniStringArray; sep: UniChar): UnicodeString;
begin
Result := WideSepJoin(@s[0], Length(s), sep);
end;
function SepJoin(const s: TStringArray; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := WideSepJoin(@s[0], Length(s), sep);
{$ELSE}
Result := AnsiSepJoin(@s[0], Length(s), sep);
{$ENDIF}
end;
function AnsiSepJoin(s: PAnsiString; cnt: integer; sep: AnsiChar): AnsiString;
var si: PAnsiString;
ci: integer;
len, li: integer;
begin
//Считаем общий размер
len := cnt - 1; //число разделителей
si := s;
ci := cnt;
while ci>0 do begin
len := len + Length(si^);
Inc(si);
Dec(ci);
end;
//Выделяем память
SetLength(Result, len);
li := 1;
while cnt>1 do begin
Move(s^[1], Result[li], Length(s^)*SizeOf(AnsiChar));
li := li + Length(s^);
Result[li] := sep;
li := li + 1;
Inc(s);
Dec(cnt);
end;
//Последний кусок
if cnt >= 1 then
Move(s^[1], Result[li], Length(s^)*SizeOf(AnsiChar));
end;
function WideSepJoin(s: PUniString; cnt: integer; sep: UniChar): UnicodeString;
var si: PUniString;
ci: integer;
len, li: integer;
begin
//Считаем общий размер
len := cnt - 1; //число разделителей
si := s;
ci := cnt;
while ci>0 do begin
len := len + Length(si^);
Inc(si);
Dec(ci);
end;
//Выделяем память
SetLength(Result, len);
li := 1;
while cnt>1 do begin
Move(s^[1], Result[li], Length(s^)*SizeOf(UniChar));
li := li + Length(s^);
Result[li] := sep;
li := li + 1;
Inc(s);
Dec(cnt);
end;
//Последний кусок
if cnt >= 1 then
Move(s^[1], Result[li], Length(s^)*SizeOf(UniChar));
end;
function SepJoin(s: PString; cnt: integer; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := WideSepJoin(s, cnt, sep);
{$ELSE}
Result := AnsiSepJoin(s, cnt, sep);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
//Возвращает в виде WideString строку PWideChar, но не более N символов
//Полезно для чтения всяких буферов фиксированного размера, где не гарантирован ноль.
function AnsiStrFromBuf(s: PAnsiChar; MaxLen: integer): AnsiString;
var p: PAnsiChar;
begin
p := s;
while (p^ <> #00) and (MaxLen > 0) do begin
Inc(p);
Dec(MaxLen);
end;
//p указывает на символ, копировать который уже не надо
Result := SubStrPchA(s, p);
end;
function WideStrFromBuf(s: PUniChar; MaxLen: integer): UnicodeString;
var p: PWideChar;
begin
p := s;
while (p^ <> #00) and (MaxLen > 0) do begin
Inc(p);
Dec(MaxLen);
end;
//p указывает на символ, копировать который уже не надо
Result := SubStrPchW(s, p);
end;
function StrFromBuf(s: PChar; MaxLen: integer): string;
begin
{$IFDEF UNICODE}
Result := WideStrFromBuf(s, MaxLen);
{$ELSE}
Result := AnsiStrFromBuf(s, MaxLen);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
/// Character checks
//Checks if char is a number
function AnsiCharIsNumber(c: AnsiChar): boolean;
begin
Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9'));
end;
function WideCharIsNumber(c: UniChar): boolean;
begin
Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9'));
end;
function CharIsNumber(c: char): boolean;
begin
Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9'));
end;
//Checks if char is a latin symbol
function AnsiCharIsLatinSymbol(c: AnsiChar): boolean;
begin
Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z')))
or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z')));
end;
function WideCharIsLatinSymbol(c: UniChar): boolean;
begin
Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z')))
or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z')));
end;
function CharIsLatinSymbol(c: char): boolean;
begin
Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z')))
or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z')));
end;
//Check if string is composed only from numbers and latin symbols
function AnsiStrIsLnOnly(const str: AnsiString): boolean;
var i: integer;
begin
Result := true;
for i := 1 to Length(str) do
if not AnsiCharIsNumber(str[i])
and not AnsiCharIsLatinSymbol(str[i]) then begin
Result := false;
exit;
end;
end;
function WideStrIsLnOnly(const str: UnicodeString): boolean;
var i: integer;
begin
Result := true;
for i := 1 to Length(str) do
if not WideCharIsNumber(str[i])
and not WideCharIsLatinSymbol(str[i]) then begin
Result := false;
exit;
end;
end;
function StrIsLnOnly(const str: string): boolean;
begin
{$IFDEF UNICODE}
Result := WideStrIsLnOnly(str);
{$ELSE}
Result := AnsiStrIsLnOnly(str);
{$ENDIF}
end;
function IsDigit(c: UniChar): boolean;
begin
Result := (c>='0') and (c<='9');
end;
(*
Following stuff isn't precise.
1. We don't include repetition marks etc in Hiragana/Katakana
2. There are both unique to H/K and shared H-K marks
3. Unicode includes copies of H/K with effects:
- Normal [included]
- Small [included]
- Circled
- Other?
4. Unicode has various special symbols for KIROGURAMU in H/K, for instance. Not included.
5. Kanjis are included only from Basic Plane.
*)
function IsHiragana(c: UniChar): boolean;
begin
Result := (Ord(c) >= $3040) and (Ord(c) <= $309F);
end;
function IsKatakana(c: UniChar): boolean;
begin
Result := ((Ord(c) >= $30A0) and (Ord(c) <= $30FF))
or ((Ord(c) >= $31F0) and (Ord(c) <= $31FF)); //katakana phonetic extensions
end;
function IsKana(c: UniChar): boolean;
begin
Result := IsKatakana(c) or IsHiragana(c);
end;
function IsKanji(c: UniChar): boolean;
begin
Result := ((Ord(c) >= $4E00) and (Ord(c) <= $9FFF)) //CJK Unified Ideographs
or ((Ord(c) >= $F900) and (Ord(c) <= $FAFF)); //CJK Compatibility Ideographs
end;
//Символ относится к диапазону "CJK Symbols and Punctuation"
function IsCJKSymbolOrPunctuation(c: UniChar): boolean;
begin
Result := (Ord(c) >= $3000) and (Ord(c) <= $303F);
end;
//Символ относится к диапазонам "Fullwidth Characters"
function IsFullWidthCharacter(c: UniChar): boolean;
begin
Result := (Ord(c) >= $FF01) and (Ord(c) <= $FF5E)
or (Ord(c) >= $FFE0) and (Ord(c) <= $FFE6);
end;
function ContainsKanji(const s: UniString): boolean;
var i: integer;
begin
Result := false;
for i := 1 to Length(s) do
if IsKanji(s[i]) then begin
Result := true;
break;
end;
end;
////////////////////////////////////////////////////////////////////////////////
/// Indexing and lengths
// Возвращает номер символа, на который указывает ptr, в строке str
function AnsiPcharInd(str, ptr: PAnsiChar): integer;
begin
Result := IntPtr(ptr)-IntPtr(str)+1;
end;
function WidePcharInd(str, ptr: PUniChar): integer;
begin
Result := (IntPtr(ptr)-IntPtr(str)) div SizeOf(UniChar) + 1;
end;
function PcharInd(str, ptr: PChar): integer;
begin
Result := (IntPtr(ptr)-IntPtr(str)) div SizeOf(char) + 1;
end;
//Возвращает длину отрезка в символах
function CharLenA(p1, p2: PAnsiChar): integer;
begin
Result := (cardinal(p2) - cardinal(p1)) div SizeOf(AnsiChar);
end;
function CharLenW(p1, p2: PUniChar): integer;
begin
Result := (cardinal(p2) - cardinal(p1)) div SizeOf(UniChar);
end;
function CharLen(p1, p2: PChar): integer;
begin
Result := (cardinal(p2) - cardinal(p1)) div SizeOf(Char);
end;
//Находит конец строки
function StrEndA(s: PAnsiChar): PAnsiChar;
begin
Result := s;
while Result^ <> #00 do Inc(Result);
end;
function StrEndW(s: PUniChar): PUniChar;
begin
Result := s;
while Result^ <> #00 do Inc(Result);
end;
function StrEnd(s: PChar): PChar;
begin
Result := s;
while Result^ <> #00 do Inc(Result);
end;
////////////////////////////////////////////////////////////////////////////////
/// Быстрое обращение к следующему-предыдущему символу
function NextChar(p: PAnsiChar; c: integer = 1): PAnsiChar;
begin
Result := PAnsiChar(IntPtr(p) + SizeOf(AnsiChar)*c);
end;
function PrevChar(p: PAnsiChar; c: integer = 1): PAnsiChar;
begin
Result := PAnsiChar(IntPtr(p) - SizeOf(AnsiChar)*c);
end;
function NextChar(p: PWideChar; c: integer = 1): PWideChar;
begin
Result := PWideChar(IntPtr(p) + SizeOf(WideChar)*c);
end;
function PrevChar(p: PWideChar; c: integer = 1): PWideChar;
begin
Result := PWideChar(IntPtr(p) - SizeOf(WideChar)*c);
end;
////////////////////////////////////////////////////////////////////////////////
/// Арифметика указателей
//Возвращает указатель на n-й знак строки. Быстрее и безопасней, чем дельфийская хрень.
//Отступ считает с единицы.
function PwcOff(var a; n: integer): PWideChar;
begin
Result := PWideChar(IntPtr(a) + (n-1)*SizeOf(WideChar));
end;
//Сравнивает указатели. Больше нуля, если a>b.
function PwcCmp(var a; var b): integer;
begin
Result := IntPtr(a)-IntPtr(b);
end;
//Отступ считает с единицы.
function PwcCmp(var a; an: integer; var b; bn: integer): integer;
begin
Result := IntPtr(a)+(an-1)*SizeOf(WideChar)-IntPtr(b)-(bn-1)*SizeOf(WideChar);
end;
////////////////////////////////////////////////////////////////////////////////
/// Возвращает строку между заданными позициями, или заданной длины
function StrSubLA(beg: PAnsiChar; len: integer): AnsiString;
var i: integer;
begin
SetLength(Result, len);
i := 1;
while i <= len do begin
Result[i] := beg^;
Inc(beg);
Inc(i);
end;
end;
function StrSubLW(beg: PUniChar; len: integer): UnicodeString;
var i: integer;
begin
SetLength(Result, len);
i := 1;
while i <= len do begin
Result[i] := beg^;
Inc(beg);
Inc(i);
end;
end;
function StrSubL(beg: PChar; len: integer): string;
begin
{$IFDEF UNICODE}
Result := StrSubLW(beg, len);
{$ELSE}
Result := StrSubLA(beg, len);
{$ENDIF}
end;
function StrSubA(beg: PAnsiChar; en: PAnsiChar): AnsiString;
begin
Result := StrSubLA(beg, (IntPtr(en)-IntPtr(beg)) div SizeOf(AnsiChar));
end;
function StrSubW(beg: PUniChar; en: PUniChar): UnicodeString;
begin
Result := StrSubLW(beg, (IntPtr(en)-IntPtr(beg)) div SizeOf(WideChar));
end;
function StrSub(beg: PChar; en: PChar): string;
begin
{$IFDEF UNICODE}
Result := StrSubW(beg, en);
{$ELSE}
Result := StrSubA(beg, en);
{$ENDIF}
end;
//Обратная совместимость
function SubStrPchA(beg, en: PAnsiChar): AnsiString;
begin
Result := StrSubA(beg, en);
end;
function SubStrPchW(beg, en: PUniChar): UnicodeString;
begin
Result := StrSubW(beg, en);
end;
function SubStrPch(beg, en: pchar): string;
begin
//Редиректим сразу на нужные функции, без проводников
{$IFDEF UNICODE}
Result := StrSubW(beg, en);
{$ELSE}
Result := StrSubA(beg, en);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
/// Поиск символов в строке
//Scans the specified string for the specfied character. Starts at position <start_at>.
//Ends at <end_at> symbols - 1. Returns first symbol index in string or -1 if not found any.
function AnsiFindChar(const s: AnsiString; c: AnsiChar; start_at: integer; end_at: integer): integer;
var i: integer;
begin
if end_at=-1 then
end_at := Length(s);
Result := -1;
for i := start_at to end_at - 1 do
if s[i]=c then begin
Result := i;
exit;
end;
end;
function WideFindChar(const s: UnicodeString; c: UniChar; start_at: integer; end_at: integer): integer;
var i: integer;
begin
if end_at=-1 then
end_at := Length(s);
Result := -1;
for i := start_at to end_at - 1 do
if s[i]=c then begin
Result := i;
exit;
end;
end;
function FindChar(const s: string; c: char; start_at: integer; end_at: integer): integer;
begin
{$IFDEF UNICODE}
Result := WideFindChar(s, c, start_at, end_at);
{$ELSE}
Result := AnsiFindChar(s, c, start_at, end_at);
{$ENDIF}
end;
//Дополнения к стандартной дельфийской StrScan
function StrScanA(str: PAnsiChar; chr: AnsiChar): PAnsiChar;
begin
Result := StrScan(str, chr);
end;
function StrScanW(str: PUniChar; chr: UniChar): PUniChar;
begin
{$IFDEF UNICODE}
Result := StrScan(str, chr); //has unicode version
{$ELSE}
{ Copied from SysUtils }
Result := Str;
while Result^ <> #0 do
begin
if Result^ = Chr then
Exit;
Inc(Result);
end;
if Chr <> #0 then
Result := nil;
{$ENDIF}
end;
//Ищет любой из перечисленных символов, иначе возвращает nil.
function StrScanAnyA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar;
var smb: PAnsiChar;
begin
Result := nil;
while str^ <> #00 do begin
smb := symbols;
while smb^ <> #00 do
if smb^ = str^ then begin
Result := str;
exit;
end else
Inc(smb);
Inc(str);
end;
end;
function StrScanAnyW(str: PUniChar; symbols: PUniChar): PUniChar;
var smb: PWideChar;
begin
Result := nil;
while str^ <> #00 do begin
smb := symbols;
while smb^ <> #00 do
if smb^ = str^ then begin
Result := str;
exit;
end else
Inc(smb);
Inc(str);
end;
end;
function StrScanAny(str: PChar; symbols: PChar): PChar;
begin
{$IFDEF UNICODE}
Result := StrScanAnyW(str, symbols);
{$ELSE}
Result := StrScanAnyA(str, symbols);
{$ENDIF}
end;
//Ищет любой из перечисленных символов, иначе возвращает указатель на конец строки.
//Для скорости алгоритмы скопированы из StrScanAny
function StrScanEndA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar;
var smb: PAnsiChar;
begin
while str^ <> #00 do begin
smb := symbols;
while smb^ <> #00 do
if smb^ = str^ then begin
Result := str;
exit;
end else
Inc(smb);
Inc(str);
end;
//If nothing is found, return endstr
Result := str;
end;
function StrScanEndW(str: PUniChar; symbols: PUniChar): PUniChar;
var smb: PWideChar;
begin
while str^ <> #00 do begin
smb := symbols;
while smb^ <> #00 do
if smb^ = str^ then begin
Result := str;
exit;
end else
Inc(smb);
Inc(str);
end;
//If nothing is found, return endstr
Result := str;
end;
function StrScanEnd(str: PChar; symbols: PChar): PChar;
begin
{$IFDEF UNICODE}
Result := StrScanEndW(str, symbols);
{$ELSE}
Result := StrScanEndA(str, symbols);
{$ENDIF}
end;
//Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него.
//Если такого символа нет, возвращает остаток строки и nil.
function AnsiReadUpToNext(str: PAnsiChar; const cs: AnsiString; out block: AnsiString): PAnsiChar;
begin
Result := StrScanAnyA(str, PAnsiChar(cs));
if Result <> nil then
SetLength(block, AnsiPcharInd(str, Result)-1)
else
SetLength(block, StrLen(str));
if Length(block) > 0 then
StrLCopy(@block[1], str, Length(block)); //null not included
end;
//Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него.
//Если такого символа нет, возвращает остаток строки и nil.
function WideReadUpToNext(str: PUniChar; const cs: UnicodeString; out block: UnicodeString): PUniChar;
begin
Result := StrScanAnyW(str, PWideChar(cs));
if Result <> nil then
SetLength(block, WidePCharInd(str, Result)-1)
else
SetLength(block, WStrLen(str));
if Length(block) > 0 then
WStrLCopy(@block[1], str, Length(block)); //null not included
end;
function ReadUpToNext(str: PChar; const cs: string; out block: string): PChar;
begin
{$IFDEF UNICODE}
Result := WideReadUpToNext(str, cs, block);
{$ELSE}
Result := AnsiReadUpToNext(str, cs, block);
{$ENDIF}
end;
//Проверяет, что строки совпадают до окончания одной из них
function StrCmpNext(a, b: PChar): boolean;
begin
while (a^ = b^) and (a^<>#00) do begin //#00 не выедаем даже общий
Inc(a);
Inc(b);
end;
Result := (a^=#00) or (b^=#00);
end;
//Возвращает длину совпадающего участка c начала строк, в символах, включая нулевой.
function StrMatch(a, b: PChar): integer;
begin
Result := 0;
while (a^ = b^) and (a^<>#00) do begin //#00 не выедаем даже общий
Inc(a);
Inc(b);
Inc(Result);
end;
//сверяем #00
if (a^=b^) then Inc(Result);
end;
procedure SkipChars(var pc: PChar; chars: PChar);
var pcc: PChar;
begin
while pc^<>#00 do begin
pcc := chars;
while pcc^<>#00 do
if pcc^=pc^ then begin
pcc := nil;
break;
end else
Inc(pcc);
if pcc=nil then //skip char
Inc(pc)
else
exit; //non-skip char
end;
end;
////////////////////////////////////////////////////////////////////////////////
/// Удаление лишних символов по краям
//Removes quote characters around the string, if they exist.
function AnsiStripQuotes(const s: AnsiString; qc1, qc2: AnsiChar): AnsiString;
begin
Result := s;
if Length(Result) < 2 then exit;
//Если кавычки есть, убираем их.
if (Result[1]=qc1) and (Result[Length(Result)-1]=qc2) then begin
Move(Result[2], Result[1], (Length(Result)-2)*SizeOf(Result[1]));
SetLength(Result, Length(Result)-2);
end;
end;
function WideStripQuotes(const s: UnicodeString; qc1, qc2: UniChar): UnicodeString;
begin
Result := s;
if Length(Result) < 2 then exit;
//Если кавычки есть, убираем их.
if (Result[1]=qc1) and (Result[Length(Result)-1]=qc2) then begin
Move(Result[2], Result[1], (Length(Result)-2)*SizeOf(Result[1]));
SetLength(Result, Length(Result)-2);
end;
end;
function StripQuotes(const s: string; qc1, qc2: char): string;
begin
{$IFDEF UNICODE}
Result := WideStripQuotes(s, qc1, qc2);
{$ELSE}
Result := AnsiStripQuotes(s, qc1, qc2);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
/// Тримы - версия для String
function STrimStartA(const s: AnsiString; sep: AnsiChar): AnsiString;
var ps, pe: PAnsiChar;
begin
if s='' then begin
Result := '';
exit;
end;
ps := @s[1];
if ps^<>sep then begin
Result := s; //короткая версия
exit;
end;
//Длинная версия
pe := @s[Length(s)];
while (cardinal(ps) <= cardinal(pe)) and (ps^=sep) do
Inc(ps);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1);
Move(s[1], Result[1], Length(Result)*SizeOf(AnsiChar));
end;
function STrimStartW(const s: UnicodeString; sep: UniChar): UnicodeString;
var ps, pe: PWideChar;
begin
if s='' then begin
Result := '';
exit;
end;
ps := @s[1];
if ps^<>sep then begin
Result := s; //короткая версия
exit;
end;
//Длинная версия
pe := @s[Length(s)];
while (cardinal(ps) <= cardinal(pe)) and (ps^=sep) do
Inc(ps);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1);
Move(s[1], Result[1], Length(Result)*SizeOf(WideChar));
end;
function STrimStart(const s: string; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := STrimStartW(s, sep);
{$ELSE}
Result := STrimStartA(s, sep);
{$ENDIF}
end;
function STrimEndA(const s: AnsiString; sep: AnsiChar): AnsiString;
var ps, pe: PAnsiChar;
begin
if s='' then begin
Result := '';
exit;
end;
pe := @s[Length(s)];
if pe^<>sep then begin
Result := s; //короткая версия
exit;
end;
//Длинная версия
ps := @s[1];
while (cardinal(pe) > cardinal(ps)) and (pe^=sep) do
Dec(pe);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1);
Move(s[1], Result[1], Length(Result)*SizeOf(AnsiChar));
end;
function STrimEndW(const s: UnicodeString; sep: UniChar): UnicodeString;
var ps, pe: PWideChar;
begin
if s='' then begin
Result := '';
exit;
end;
pe := @s[Length(s)];
if pe^<>sep then begin
Result := s; //короткая версия
exit;
end;
//Длинная версия
ps := @s[1];
while (cardinal(pe) > cardinal(ps)) and (pe^=sep) do
Dec(pe);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1);
Move(s[1], Result[1], Length(Result)*SizeOf(WideChar));
end;
function STrimEnd(const s: string; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := STrimEndW(s, sep);
{$ELSE}
Result := STrimEndA(s, sep);
{$ENDIF}
end;
function STrimA(const s: AnsiString; sep: AnsiChar): AnsiString;
var ps, pe: PAnsiChar;
begin
if s='' then begin
Result := '';
exit;
end;
ps := @s[1];
pe := @s[Length(s)];
while (cardinal(pe) >= cardinal(ps)) and (pe^ = sep) do
Dec(pe);
while (cardinal(ps) <= cardinal(pe)) and (ps^ = sep) do
Inc(ps);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1);
Move(ps^, Result[1], Length(Result)*SizeOf(AnsiChar));
end;
function STrimW(const s: UnicodeString; sep: UniChar): UnicodeString;
var ps, pe: PWideChar;
begin
if s='' then begin
Result := '';
exit;
end;
ps := @s[1];
pe := @s[Length(s)];
while (cardinal(pe) >= cardinal(ps)) and (pe^ = sep) do
Dec(pe);
while (cardinal(ps) <= cardinal(pe)) and (ps^ = sep) do
Inc(ps);
if cardinal(ps) > cardinal(pe) then begin
Result := '';
exit;
end;
SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1);
Move(ps^, Result[1], Length(Result)*SizeOf(WideChar));
end;
function STrim(const s: string; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := STrimW(s, sep);
{$ELSE}
Result := STrimA(s, sep);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
/// Тримы - версия для PChar
function PTrimStartA(s: PAnsiChar; sep: AnsiChar): AnsiString;
begin
while s^=sep do Inc(s);
Result := s;
end;
function PTrimStartW(s: PUniChar; sep: UniChar): UnicodeString;
begin
while s^=sep do Inc(s);
Result := s;
end;
function PTrimStart(s: PChar; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := PTrimStartW(s, sep);
{$ELSE}
Result := PTrimStartA(s, sep);
{$ENDIF}
end;
function PTrimEndA(s: PAnsiChar; sep: AnsiChar): AnsiString;
var se: PAnsiChar;
begin
//Конец строки
se := s;
while se^<>#00 do Inc(se);
//Откатываемся назад
Dec(se);
while (se^=sep) and (IntPtr(se) > IntPtr(s)) do
Dec(se);
//Пустая строка
if IntPtr(se) <= IntPtr(s) then begin
Result := '';
exit;
end;
Inc(se);
Result := StrSubA(s, se);
end;
function PTrimEndW(s: PUniChar; sep: UniChar): UnicodeString;
var se: PWideChar;
begin
//Конец строки
se := s;
while se^<>#00 do Inc(se);
//Откатываемся назад
Dec(se);
while (se^=sep) and (IntPtr(se) > IntPtr(s)) do
Dec(se);
//Пустая строка
if IntPtr(se) < IntPtr(s) then begin
Result := '';
exit;
end;
Inc(se);
Result := StrSubW(s, se);
end;
function PTrimEnd(s: PChar; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := PTrimEndW(s, sep);
{$ELSE}
Result := PTrimEndA(s, sep);
{$ENDIF}
end;
function PTrimA(s: PAnsiChar; sep: AnsiChar): AnsiString;
begin
//Пробелы в начале
while s^=sep do Inc(s);
if s^=#00 then begin
Result := '';
exit;
end;
Result := PTrimEndA(s, sep);
end;
function PTrimW(s: PUniChar; sep: UniChar): UnicodeString;
begin
//Пробелы в начале
while s^=sep do Inc(s);
if s^=#00 then begin
Result := '';
exit;
end;
Result := PTrimEndW(s, sep);
end;
function PTrim(s: PChar; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := PTrimW(s, sep);
{$ELSE}
Result := PTrimA(s, sep);
{$ENDIF}
end;
function BETrimA(beg, en: PAnsiChar; sep: AnsiChar): AnsiString;
begin
//Trim spaces
Dec(en);
while (IntPtr(en) > IntPtr(beg)) and (en^=sep) do
Dec(en);
Inc(en);
while (IntPtr(en) > IntPtr(beg)) and (beg^=sep) do
Inc(beg);
Result := StrSubA(beg, en);
end;
function BETrimW(beg, en: PUniChar; sep: UniChar): UnicodeString;
begin
//Trim spaces
Dec(en);
while (IntPtr(en) > IntPtr(beg)) and (en^=sep) do
Dec(en);
Inc(en);
while (IntPtr(en) > IntPtr(beg)) and (beg^=sep) do
Inc(beg);
Result := StrSubW(beg, en);
end;
function BETrim(beg, en: PChar; sep: Char): string;
begin
{$IFDEF UNICODE}
Result := BETrimW(beg, en, sep);
{$ELSE}
Result := BETrimA(beg, en, sep);
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
// Binary/string conversions
const
sHexSymbols: AnsiString = '0123456789ABCDEF';
function ByteToHex(b: byte): AnsiString; inline;
begin
SetLength(Result, 2);
Result[1] := sHexSymbols[(b shr 4) + 1];
Result[2] := sHexSymbols[(b mod 16) + 1];
end;
function BinToHex(ptr: pbyte; sz: integer): AnsiString;
var i: integer;
begin
SetLength(Result, sz*2);
i := 0;
while i < sz do begin
Result[i*2+1] := sHexSymbols[(ptr^ shr 4) + 1];
Result[i*2+2] := sHexSymbols[(ptr^ mod 16) + 1];
Inc(ptr);
Inc(i);
end;
end;
function DataToHex(data: array of byte): AnsiString;
begin
Result := BinToHex(@data[0], Length(data));
end;
function HexCharValue(c: AnsiChar): byte; inline;
begin
if c in ['0'..'9'] then
Result := Ord(c) - Ord('0')
else
if c in ['a'..'f'] then
Result := 10 + Ord(c) - Ord('a')
else
if c in ['A'..'F'] then
Result := 10 + Ord(c) - Ord('A')
else
raise Exception.Create('Illegal hex symbol: '+c);
end;
//Буфер должен быть выделен заранее.
//Переведено будет лишь столько, сколько влезло в указанный размер.
procedure HexToBin(const s: AnsiString; p: pbyte; size: integer);
var i: integer;
begin
if size > (Length(s) div 2) then
size := (Length(s) div 2);
for i := 0 to size-1 do begin
p^ := HexCharValue(s[2*i+1]) * 16
+ HexCharValue(s[2*i+2]);
Inc(p);
end;
end;
////////////////////////////////////////////////////////////////////////////////
/// Codepage utils
{$IFDEF MSWINDOWS}
function ToWideChar(c: AnsiChar; cp: cardinal): WideChar;
begin
if MultiByteToWideChar(cp, 0, @c, 1, @Result, 2) = 0 then
RaiseLastOsError;
end;
function ToChar(c: WideChar; cp: cardinal): AnsiChar;
begin
if WideCharToMultiByte(cp, 0, @c, 2, @Result, 1, nil, nil) = 0 then
RaiseLastOsError;
end;
function ToWideString(const s: AnsiString; cp: cardinal): WideString;
begin
Result := BufToWideString(PAnsiChar(s), Length(s), cp);
end;
function ToString(const s: WideString; cp: cardinal): AnsiString;
begin
Result := BufToString(PWideChar(s), Length(s), cp);
end;
function BufToWideString(s: PAnsiChar; len: integer; cp: cardinal): WideString;
var size: integer;
begin
if s^=#00 then begin
Result := '';
exit;
end;
size := MultiByteToWideChar(cp, 0, s, len, nil, 0);
if size=0 then
RaiseLastOsError;
SetLength(Result, size);
if MultiByteToWideChar(cp, 0, s, len, pwidechar(Result), size) = 0 then
RaiseLastOsError;
end;
function BufToString(s: PWideChar; len: integer; cp: cardinal): AnsiString;
var size: integer;
begin
if s^=#00 then begin
Result := '';
exit;
end;
size := WideCharToMultiByte(cp, 0, s, len, nil, 0, nil, nil);
if size=0 then
RaiseLastOsError;
SetLength(Result, size);
if WideCharToMultiByte(cp, 0, s, len, PAnsiChar(Result), size, nil, nil) = 0 then
RaiseLastOsError;
end;
function Convert(const s: AnsiString; cpIn, cpOut: cardinal): AnsiString;
begin
Result := ToString(ToWideString(s, cpIn), cpOut);
end;
//Переводит строку из текущей кодировки системы в текущую кодировку консоли.
function WinToOEM(const s: AnsiString): AnsiString;
begin
Result := Convert(s, CP_ACP, CP_OEMCP);
end;
//Переводит строку из текущей кодировки консоли в текущую кодировку системы.
function OEMToWin(const s: AnsiString): AnsiString;
begin
Result := Convert(s, CP_OEMCP, CP_ACP);
end;
{$ENDIF}
////////////////////////////////////////////////////////////////////////////////
/// StringBuilder
procedure TAnsiStringBuilder.Clear;
begin
Used := 0;
end;
function TAnsiStringBuilder.Pack: AnsiString;
begin
SetLength(Data, Used);
Result := Data;
end;
procedure TAnsiStringBuilder.Add(c: AnsiChar);
begin
if Used >= Length(Data) then
SetLength(Data, Length(Data)*2 + 20);
Inc(Used);
Data[Used] := c;
end;
procedure TAnsiStringBuilder.Add(pc: PAnsiChar);
var len, i: integer;
begin
len := StrLen(pc);
if Used+len >= Length(Data) then
if len > Length(Data)+20 then
SetLength(Data, Length(Data)+len+20)
else
SetLength(Data, Length(Data)*2 + 20);
for i := 1 to len do begin
Data[Used+i] := pc^;
Inc(pc);
end;
Inc(Used, len);
end;
procedure TAnsiStringBuilder.Add(const s: AnsiString);
var len, i: integer;
begin
len := Length(s);
if Used+len >= Length(Data) then
if len > Length(Data)+20 then
SetLength(Data, Length(Data)+len+20)
else
SetLength(Data, Length(Data)*2 + 20);
for i := 1 to len do
Data[Used+i] := s[i];
Inc(Used, len);
end;
procedure TAnsiStringBuilder.Pop(SymbolCount: integer = 1);
begin
if SymbolCount >= Used then
Used := 0
else
Used := Used - SymbolCount;
end;
procedure TUniStringBuilder.Clear;
begin
Used := 0;
end;
function TUniStringBuilder.Pack: UnicodeString;
begin
SetLength(Data, Used);
Result := Data;
end;
procedure TUniStringBuilder.Add(c: UniChar);
begin
if Used >= Length(Data) then
SetLength(Data, Length(Data)*2 + 20);
Inc(Used);
Data[Used] := c;
end;
procedure TUniStringBuilder.Add(pc: PUniChar);
var len, i: integer;
begin
len := WStrLen(pc);
if Used+len >= Length(Data) then
if len > Length(Data)+20 then
SetLength(Data, Length(Data)+len+20)
else
SetLength(Data, Length(Data)*2 + 20);
for i := 1 to len do begin
Data[Used+i] := pc^;
Inc(pc);
end;
Inc(Used, len);
end;
procedure TUniStringBuilder.Add(const s: UnicodeString);
var len, i: integer;
begin
len := Length(s);
if Used+len >= Length(Data) then
if len > Length(Data)+20 then
SetLength(Data, Length(Data)+len+20)
else
SetLength(Data, Length(Data)*2 + 20);
for i := 1 to len do
Data[Used+i] := s[i];
Inc(Used, len);
end;
procedure TUniStringBuilder.Pop(SymbolCount: integer = 1);
begin
if SymbolCount >= Used then
Used := 0
else
Used := Used - SymbolCount;
end;
{ Функции кодирования в HTML-форматы. Пока сделаны медленно и просто,
при необходимости можно ускорить. }
//Кодирует строку в URI-форме: "(te)(su)(to) str" -> "%E3%83%86%E3%82%B9%E3%83%88+str"
//Пока сделано медленно и просто, при необходимости можно ускорить
function UrlEncode(const s: UnicodeString; options: TUrlEncodeOptions): AnsiString;
var i, j: integer;
U: UTF8String;
begin
Result := '';
for i := 1 to Length(s) do
if CharInSet(s[i], ['a'..'z', 'A'..'Z', '1'..'9', '0']) then
Result := Result + AnsiChar(s[i])
else
if s[i]=' ' then
if ueNoSpacePlus in options then
Result := Result + '%20'
else
Result := Result + '+'
else begin
//Вообще говоря, символ в UTF-16 может занимать несколько пар...
//Но мы здесь это игнорируем.
U := UTF8String(s[i]); // explicit Unicode->UTF8 conversion
for j := 1 to Length(U) do
Result := Result + '%' + AnsiString(IntToHex(Ord(U[j]), 2));
end;
end;
//Кодирует строку в HTML-форме. Заменяет только символы, которые не могут
//встречаться в правильном HTML.
//Все остальные юникод-символы остаются в нормальной форме.
function HtmlEscape(const s: UnicodeString): UnicodeString;
var i: integer;
begin
Result := '';
for i := 1 to Length(s) do
if s[i]='&' then Result := Result + '&' else
if s[i]='''' then Result := Result + ''' else
if s[i]='"' then Result := Result + '"' else
if s[i]='<' then Result := Result + '<' else
if s[i]='>' then Result := Result + '>' else
Result := Result + s[i];
end;
//Кодирует строку в HTML-форме. Неизвестно, была ли строка закодирована до сих пор.
//Пользователь мог закодировать некоторые последовательности, но забыть другие.
//Поэтому кодируются только те символы, которые встречаться в итоговой строке
//не могут никак:
// "asd & bsd <esd>" --> "asd & bsd <esd>"
function HtmlEscapeObvious(const s: UnicodeString): UnicodeString;
var i: integer;
begin
Result := '';
for i := 1 to Length(s) do
//& не кодируем
if s[i]='''' then Result := Result + ''' else
if s[i]='"' then Result := Result + '"' else
if s[i]='<' then Result := Result + '<' else
if s[i]='>' then Result := Result + '>' else
Result := Result + s[i];
end;
//Кодирует строку в HTML-форме. Заменяет все символы, не входящие в Ansi-набор.
// "(te)(su)(to) str" -> "&12486;&12473;&12488; str"
//При необходимости можно сделать флаг "эскейпить в 16-ричные коды: ホ"
function HtmlEscapeToAnsi(const s: UnicodeString): AnsiString;
var i: integer;
begin
Result := '';
for i := 1 to Length(s) do
if s[i]='&' then Result := Result + '&' else
if s[i]='''' then Result := Result + ''' else
if s[i]='"' then Result := Result + '"' else
if s[i]='<' then Result := Result + '<' else
if s[i]='>' then Result := Result + '>' else
//ANSI-символы
if CharInSet(s[i], ['a'..'z', 'A'..'Z', '1'..'9', '0', ' ']) then
Result := Result + AnsiChar(s[i])
else
Result := Result + '&#'+AnsiString(IntToStr(word(s[i])))+';'
end;
end.
|
unit frmJournalPedagogueByCollectiveGroupChild;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, dbfunc, uKernel,
DateUtils;
type
TfJournalPedagogueByCollectiveGroupChild = class(TForm)
Panel3: TPanel;
Panel1: TPanel;
lvCollectiveJournal: TListView;
Panel4: TPanel;
Button2: TButton;
Button3: TButton;
bToIndividualJournal: TButton;
Button5: TButton;
Button6: TButton;
cbMonth: TComboBox;
RadioGroup1: TRadioGroup;
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbMonthChange(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure bToIndividualJournalClick(Sender: TObject);
procedure lvCollectiveJournalSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure RadioGroup1Click(Sender: TObject);
private
FIDPedagogue: integer;
FIDAcademicYear: integer;
FStrPedagogue: string;
FStrAcademicYear: string;
NumberMonth: integer;
CollectiveJournal: TResultTable;
procedure ShowCollectiveJournal(const IDPedagogue, IDAcademicYear,
NumberMonth: integer);
procedure SetIDPedagogue(const Value: integer);
procedure SetIDAcademicYear(const Value: integer);
procedure SetStrPedagogue(const Value: string);
procedure SetStrAcademicYear(const Value: string);
public
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
property StrPedagogue: string read FStrPedagogue write SetStrPedagogue;
property StrAcademicYear: string read FStrAcademicYear
write SetStrAcademicYear;
end;
var
fJournalPedagogueByCollectiveGroupChild
: TfJournalPedagogueByCollectiveGroupChild;
implementation
{$R *.dfm}
uses frmJournalPedagogueByIndividualGroupChild;
procedure TfJournalPedagogueByCollectiveGroupChild.bToIndividualJournalClick(
Sender: TObject);
begin
if (not Assigned(fJournalPedagogueByIndividualGroupChild)) then
fJournalPedagogueByIndividualGroupChild :=
TfJournalPedagogueByIndividualGroupChild.Create(Self);
fJournalPedagogueByIndividualGroupChild.IDPedagogue := IDPedagogue;
fJournalPedagogueByIndividualGroupChild.IDAcademicYear := IDAcademicYear;
fJournalPedagogueByIndividualGroupChild.StrPedagogue := StrPedagogue;
fJournalPedagogueByIndividualGroupChild.StrAcademicYear := StrAcademicYear;
fJournalPedagogueByIndividualGroupChild.Month := NumberMonth;
fJournalPedagogueByIndividualGroupChild.Show;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.Button2Click
(Sender: TObject);
begin
// если нет ни одного занятия в этой теме хотя бы в одной строке, необходимо делать проверку на незаполненные периоды в журнале - может оказаться пустота...
end;
procedure TfJournalPedagogueByCollectiveGroupChild.Button6Click(
Sender: TObject);
begin
Close;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.cbMonthChange
(Sender: TObject);
begin
if cbMonth.ItemIndex <= 3 then
NumberMonth := cbMonth.ItemIndex + 9
else
NumberMonth := cbMonth.ItemIndex - 3;
ShowCollectiveJournal(IDPedagogue, IDAcademicYear, NumberMonth);
Panel1.Caption := StrPedagogue + ' ' + StrAcademicYear + ' г. ' + cbMonth.Text;
RadioGroup1.ItemIndex := cbMonth.ItemIndex;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.FormCreate(Sender: TObject);
begin
CollectiveJournal := nil;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.FormDestroy(Sender: TObject);
begin
if Assigned(CollectiveJournal) then
FreeAndNil(CollectiveJournal);
end;
procedure TfJournalPedagogueByCollectiveGroupChild.FormShow(Sender: TObject);
begin
NumberMonth := MonthOf(Now);
if NumberMonth >= 9 then
begin
cbMonth.ItemIndex := NumberMonth - 9;
RadioGroup1.ItemIndex := NumberMonth - 9;
end
else if NumberMonth <= 5 then
begin
cbMonth.ItemIndex := NumberMonth + 3;
RadioGroup1.ItemIndex := NumberMonth + 3;
end
else
begin
cbMonth.ItemIndex := 8;
RadioGroup1.ItemIndex := 8;
end;
Panel1.Caption := StrPedagogue + ' ' + StrAcademicYear + ' г. ' + cbMonth.Text;
if (NumberMonth <= 5) or (NumberMonth >= 9) then
ShowCollectiveJournal(IDPedagogue, IDAcademicYear, NumberMonth)
else // в летние месяцы будет определяться май прошедщего учгода
ShowCollectiveJournal(IDPedagogue, IDAcademicYear, 5);
end;
procedure TfJournalPedagogueByCollectiveGroupChild.lvCollectiveJournalSelectItem(
Sender: TObject; Item: TListItem; Selected: Boolean);
begin
if (not Assigned(fJournalPedagogueByIndividualGroupChild)) then
fJournalPedagogueByIndividualGroupChild :=
TfJournalPedagogueByIndividualGroupChild.Create(Self);
// fJournalPedagogueByIndividualGroupChild.IDLearningGroup := GropeNameLastLesson
// [Item.Index].ValueByName('ID_OUT');
with CollectiveJournal[Item.Index] do
begin
fJournalPedagogueByIndividualGroupChild.IDLearningGroup := ValueByName('ID_OUT');
fJournalPedagogueByIndividualGroupChild.StrLGName := ValueByName('NAME_LG');
fJournalPedagogueByIndividualGroupChild.StrEducationProgram := ValueByName('PROGRAM_SHORT_NAME');
fJournalPedagogueByIndividualGroupChild.StrLearningLevel := ValueByName('L_LEVEL');
fJournalPedagogueByIndividualGroupChild.WeekCountHour := ValueByName('WEEK_COUNT_HOUR');
end;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.RadioGroup1Click(
Sender: TObject);
begin
cbMonth.ItemIndex := RadioGroup1.ItemIndex;
cbMonthChange(Sender);
end;
procedure TfJournalPedagogueByCollectiveGroupChild.SetIDAcademicYear
(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.SetIDPedagogue
(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.SetStrAcademicYear
(const Value: string);
begin
if FStrAcademicYear <> Value then
FStrAcademicYear := Value;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.SetStrPedagogue
(const Value: string);
begin
if FStrPedagogue <> Value then
FStrPedagogue := Value;
end;
procedure TfJournalPedagogueByCollectiveGroupChild.ShowCollectiveJournal
(const IDPedagogue, IDAcademicYear, NumberMonth: integer);
begin
if Assigned(CollectiveJournal) then
FreeAndNil(CollectiveJournal);
CollectiveJournal := Kernel.GetCollectiveJournal(IDPedagogue, IDAcademicYear,
NumberMonth);
Kernel.GetLVCollectiveJournal(lvCollectiveJournal, CollectiveJournal);
if lvCollectiveJournal.Items.Count > 0 then
lvCollectiveJournal.ItemIndex := 0;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmOutlook
Purpose : A simple implementation of the M$ Outlook style control
Date : 03-06-01
Author : Ryan J. Mills
Version : 1.92
Notes : This unit was originally based upon the work of Patrick O'Keeffe.
It was at his request that I took the component over and rm'ified it.
================================================================================}
unit rmOutlook;
interface
{$I CompilerDefines.INC}
{$define rmHardcore}
uses Windows, Messages, Forms, Classes, Controls, Graphics, ImgList, sysutils;
type
TrmOutlookControl = class;
TrmOutlookPage = class;
TrmOutlookPageEvent = procedure(ASheet : TrmOutlookPage) of object;
TrmOutlookQueryPageEvent = procedure(ASheet : TrmOutlookPage; var CanClose : Boolean) of object;
TrmDrawingStyle = (ds3D, dsFlat, dsNone);
TrmOutlookPage = class(TCustomControl)
private
FOutlookControl : TrmOutlookControl;
FImageIndex : Integer;
FAlignment: TAlignment;
FCloseButtonDown : Boolean;
FCloseMouseOver : Boolean;
FCloseButton: Boolean;
fMouseOverBtn: boolean;
FOnQueryClosePage: TrmOutlookQueryPageEvent;
FOnDestroy : TrmOutlookPageEvent;
fData: integer;
procedure SetImageIndex(Value : Integer);
function GetPageIndex : Integer;
procedure SetOutlookControl(AOutlookControl : TrmOutlookControl);
procedure SetPageIndex(Value : Integer);
procedure SetAlignment(const Value: TAlignment);
procedure SetCloseButton(const Value: Boolean);
procedure UpdatePage;
function BtnRect:TRect;
function CloseBtnRect:TRect;
function BtnHeight:integer;
protected
{$ifdef rmHardcore}
procedure WMNCHITTEST(var MSG:TWMNCHitTest); Message WM_NCHITTEST;
procedure WMNCCALCSIZE(Var MSG:TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMNCPaint(var MSG:TWMNCPaint); message WM_NCPAINT;
{$else}
procedure AdjustClientRect(var Rect: TRect); override;
{$endif}
procedure PaintButton;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure CreateParams(var Params : TCreateParams); override;
procedure ReadState(Reader : TReader); override;
procedure WMErase(var Message : TMessage); message WM_ERASEBKGND;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED;
procedure CMParentFontChanged(var Message: TMessage); message CM_PARENTFONTCHANGED;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Paint; override;
property OutlookControl : TrmOutlookControl read FOutlookControl write SetOutlookControl;
published
property Color default clAppWorkSpace;
property Caption;
property Data : integer read fData write fData;
property Font;
property Enabled;
property Hint;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property ParentFont;
property ParentColor;
property Alignment : TAlignment read FAlignment write SetAlignment default taCenter;
property CloseButton : Boolean read FCloseButton write SetCloseButton;
property ImageIndex : Integer read FImageIndex write SetImageIndex;
property PageIndex : Integer read GetPageIndex write SetPageIndex stored False;
property OnEnter;
property OnExit;
property OnResize;
property OnDestroy : TrmOutlookPageEvent read FOnDestroy write FOnDestroy;
property OnQueryClosePage : TrmOutlookQueryPageEvent read FOnQueryClosePage write FOnQueryClosePage;
end;
TrmOutlookControl = class(TCustomControl)
private
FPages : TList;
FImages : TCustomImageList;
FActivePage : TrmOutlookPage;
FImageChangeLink : TChangeLink;
FButtonHeight : Integer;
fDrawingStyle: TrmDrawingStyle;
FPageChanged : TNotifyEvent;
procedure AdjustPages;
function GetPage(Index : Integer) : TrmOutlookPage;
function GetPageCount : Integer;
procedure InsertPage(Page : TrmOutlookPage);
procedure RemovePage(Page : TrmOutlookPage);
procedure SetActivePage(Page : TrmOutlookPage);
procedure SetImages(Value : TCustomImageList);
procedure ImageListChange(Sender : TObject);
procedure SetButtonHeight(value : integer);
procedure SetDrawingStyle(const Value: TrmDrawingStyle);
procedure CMDialogKey(var Message : TCMDialogKey); message CM_DIALOGKEY;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
protected
procedure GetChildren(Proc : TGetChildProc; Root : TComponent); override;
procedure SetChildOrder(Child : TComponent; Order : Integer); override;
procedure ShowControl(AControl : TControl); override;
procedure WMErase(var Message : TMessage); message WM_ERASEBKGND;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetBorderWidth:integer;
function GetClientRect: TRect; override;
procedure Resize; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Paint; override;
function FindNextPage(CurPage : TrmOutlookPage; GoForward : Boolean) : TrmOutlookPage;
procedure SelectNextPage(GoForward : Boolean);
property PageCount : Integer read GetPageCount;
property Pages[Index : Integer] : TrmOutlookPage read GetPage;
published
property Align;
property Color default clAppWorkspace;
property Font;
property Images : TCustomImageList read FImages write SetImages;
property ActivePage : TrmOutlookPage read FActivePage write SetActivePage;
property ButtonHeight : Integer read fButtonHeight write SetButtonHeight default 18;
property DrawingStyle : TrmDrawingStyle read fDrawingStyle write SetDrawingStyle default ds3D;
property OnPageChanged : TNotifyEvent read fPageChanged write fPageChanged;
property OnResize;
end;
implementation
uses extCtrls, rmLibrary;
const
SOutlookIndexError = 'Sheet index Error';
{ TrmOutlookPage }
constructor TrmOutlookPage.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csClickEvents, csAcceptsControls]-[csDesignInteractive];
Visible := True;
Caption := '';
FImageIndex := -1;
color := clAppWorkSpace;
FAlignment := taCenter;
end;
procedure TrmOutLookPage.UpdatePage;
var
loop : Integer;
begin
if Assigned(FOutlookControl) then
begin
for loop := 0 to ControlCount - 1 do
Controls[loop].Visible := (Self = FOutlookControl.FActivePage);
end;
Realign;
end;
procedure TrmOutlookPage.SetImageIndex(Value : Integer);
begin
FImageIndex := Value;
PaintButton;
end;
destructor TrmOutlookPage.Destroy;
begin
if Assigned(FOnDestroy) then
FOnDestroy(Self);
inherited Destroy;
end;
function TrmOutlookPage.GetPageIndex : Integer;
begin
if FOutlookControl <> nil then
Result := FOutlookControl.FPages.IndexOf(Self)
else
Result := -1;
end;
procedure TrmOutlookPage.CreateParams(var Params : TCreateParams);
begin
inherited CreateParams(Params);
with Params.WindowClass do
style := style and not (CS_HREDRAW or CS_VREDRAW);
end;
procedure TrmOutlookPage.ReadState(Reader : TReader);
begin
inherited ReadState(Reader);
if Reader.Parent is TrmOutlookControl then
OutlookControl := TrmOutlookControl(Reader.Parent);
end;
procedure TrmOutlookPage.SetOutlookControl(AOutlookControl : TrmOutlookControl);
begin
if FOutlookControl <> AOutlookControl then
begin
if FOutlookControl <> nil then
FOutlookControl.RemovePage(Self);
Parent := AOutlookControl;
if AOutlookControl <> nil then
AOutlookControl.InsertPage(Self);
end;
end;
procedure TrmOutlookPage.SetPageIndex(Value : Integer);
var
MaxPageIndex : Integer;
begin
if FOutlookControl <> nil then
begin
MaxPageIndex := FOutlookControl.FPages.Count - 1;
if Value > MaxPageIndex then
raise EListError.CreateFmt(SOutlookIndexError, [Value, MaxPageIndex]);
FOutlookControl.FPages.Move(PageIndex, Value);
end;
end;
procedure TrmOutlookPage.SetAlignment(const Value: TAlignment);
begin
FAlignment := Value;
PaintButton;
end;
procedure TrmOutlookPage.Paint;
begin
if not (csDestroying in ComponentState) and (Assigned(FOutlookControl)) then
begin
if ParentColor then
Canvas.Brush.Color := FOutlookControl.Color
else
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
{$ifdef rmHardcore}
Canvas.FillRect(Rect(0, 0, Width, Height));
{$else}
Canvas.FillRect(Rect(0, BtnHeight, Width, Height));
{$endif}
Canvas.Brush.Style := bsClear;
PaintButton;
end;
end;
procedure TrmOutlookPage.WMErase(var Message: TMessage);
begin
Message.Result := 1;
end;
procedure TrmOutlookPage.CMMouseEnter(var Message: TMessage);
begin
FCloseMouseOver := false;
fMouseOverBtn := false;
PaintButton;
end;
procedure TrmOutlookPage.CMMouseLeave(var Message: TMessage);
begin
FCloseMouseOver := false;
fMouseOverBtn := false;
PaintButton;
end;
procedure TrmOutlookPage.SetCloseButton(const Value: Boolean);
begin
FCloseButton := Value;
PaintButton;
end;
procedure TrmOutlookPage.CMVisibleChanged(var Message: TMessage);
begin
Inherited;
if Assigned(FOutlookControl) then
begin
if Visible then
FOutlookControl.AdjustPages
else
begin
if Self.PageIndex = (FOutlookControl.FPages.Count - 1) then
FOutlookControl.SelectNextPage(False)
else
FOutlookControl.SelectNextPage(True);
end;
end;
end;
procedure TrmOutlookPage.CMFontChanged(var Message: TMessage);
begin
Inherited;
PaintButton;
end;
function TrmOutlookPage.BtnRect: TRect;
begin
result := Rect(0, 0, Width, BtnHeight);
end;
function TrmOutlookPage.CloseBtnRect: TRect;
var
wBtn : TRect;
begin
wBtn := BtnRect;
result := Rect((wBtn.Right - btnHeight) + 4,
wBtn.Top + 2,
wBtn.Right - 3,
wBtn.Bottom - 3);
end;
procedure TrmOutlookPage.CMColorChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmOutlookPage.CMTextChanged(var Message: TMessage);
begin
Inherited;
PaintButton;
end;
procedure TrmOutlookPage.CMParentColorChanged(var Message: TMessage);
begin
inherited;
if ParentColor then
Invalidate;
end;
procedure TrmOutlookPage.CMParentFontChanged(var Message: TMessage);
begin
Inherited;
if ParentFont then
Invalidate;
end;
procedure TrmOutlookPage.MouseMove(Shift: TShiftState; X, Y: Integer);
var
wLast1, wLast2 : boolean;
begin
inherited MouseMove(Shift, X, Y);
if Y < 0 then
begin
y := abs(y);
wLast1 := fMouseOverBtn;
fMouseOverBtn := PtInRect(BtnRect, Point(X, Y));
wLast2 := fCloseMouseOver;
FCloseMouseOver := fMouseOverBtn and FCloseButton and PtInRect(CloseBtnRect, Point(X, Y));
if (wLast1 <> fMouseOverBtn) or (wLast2 <> fCloseMouseOver) then
PaintButton;
end;
end;
procedure TrmOutlookPage.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if (csdesigning in componentstate) then
begin
beep;
if Y < 0 then
begin
y := abs(y);
if PtInRect(BtnRect, Point(X,Y)) and (Button = mbLeft) then
begin
if (FCloseButton and PtInRect(CloseBtnRect, Point(X, Y))) then
begin
FCloseButtonDown := True;
SetCaptureControl(self);
PaintButton; // Might have to be invalidate...?
end
else
FOutlookControl.SetActivePage(self);
end;
end;
end;
if Y < 0 then
begin
y := abs(y);
if PtInRect(BtnRect, Point(X,Y)) and (Button = mbLeft) then
begin
if (FCloseButton and PtInRect(CloseBtnRect, Point(X, Y))) then
begin
FCloseButtonDown := True;
SetCaptureControl(self);
PaintButton; // Might have to be invalidate...?
end
else
FOutlookControl.SetActivePage(self);
end;
end;
end;
procedure TrmOutlookPage.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
CanClose : Boolean;
begin
inherited MouseUp(Button, Shift, X, Y);
SetCaptureControl(nil);
if y < 0 then
begin
y := abs(y);
if (FCloseButton and PtInRect(CloseBtnRect, Point(X, Y))) then
begin
if FCloseButtonDown then
begin
//close the page....
CanClose := True;
if Assigned(FOnQueryClosePage) then
FOnQueryClosePage(Self, CanClose);
if CanClose then
Self.Free;
FCloseButtonDown := False;
PaintButton;
end;
end
else
begin
FCloseMouseOver := False;
PaintButton;
end;
end;
end;
{$ifdef rmHardcore}
procedure TrmOutlookPage.WMNCCALCSIZE(var MSG: TWMNCCalcSize);
begin
with MSG.CalcSize_Params^ do
begin
rgrc[0].Top := rgrc[0].Top + btnHeight;
end;
inherited;
end;
procedure TrmOutlookPage.WMNCPaint(var MSG: TWMNCPaint);
begin
PaintButton;
end;
procedure TrmOutlookPage.WMNCHITTEST(var MSG: TWMNCHitTest);
begin
msg.Result := htclient;
end;
procedure TrmOutlookPage.PaintButton;
var
PaintRect : TRect;
DrawFlags : Integer;
DC : HDC;
wBMP : TBitMAP;
begin
if not (csDestroying in ComponentState) and (Assigned(FOutlookControl)) then
begin
wBMP := TBitMap.create;
try
wBMP.height := rectHeight(BtnRect);
wBMP.Width := rectWidth(BtnRect);
//paint the frame..
DrawFlags := DFCS_BUTTONPUSH;
case FOutlookControl.DrawingStyle of
ds3D :; //Do nothing...
dsFlat: DrawFlags := DrawFlags or DFCS_FLAT;
dsNone: DrawFlags := DrawFlags or DFCS_Mono;
end;
DrawFrameControl(wBMP.Canvas.handle, BtnRect, DFC_BUTTON, DrawFlags);
if FCloseButton then
begin
Canvas.Brush.Color := clBlack;
DrawFlags := DFCS_CAPTIONCLOSE;
if FCloseButtonDown and FCloseMouseOver then
DrawFlags := Drawflags or DFCS_PUSHED
else
DrawFlags := Drawflags or DFCS_FLAT;
DrawFrameControl(wBMP.Canvas.Handle, CloseBtnRect, DFC_CAPTION, DrawFlags);
Canvas.Brush.Style := bsClear;
end;
PaintRect := BtnRect;
//paint the bitmap if there is one...
if ImageIndex <> -1 then
begin
if Assigned(FOutlookControl.FImages) then
begin
FOutlookControl.FImages.Draw(wBMP.Canvas, 2, ((btnHeight div 2) - (FOutlookControl.FImages.Width div 2)), ImageIndex);
PaintRect.left := FOutlookControl.FImages.Width+4;
end;
end;
//Adjust for closebtn...
PaintRect.right := ClosebtnRect.Left - 2;
//paint the text...
DrawFlags := DT_SINGLELINE or DT_VCENTER or DT_END_ELLIPSIS;
case FAlignment of
taLeftJustify : DrawFlags := DrawFlags or DT_LEFT;
taRightJustify : DrawFlags := DrawFlags or DT_RIGHT;
taCenter : DrawFlags := DrawFlags or DT_CENTER;
end;
if ParentFont then
wBMP.Canvas.Font.assign(fOutlookControl.Font)
else
wBMP.Canvas.Font.assign(Font);
if fMouseOverBtn then
wBMP.canvas.font.color := clHighlight;
wBMP.Canvas.Brush.Style := bsclear;
DrawTextEx(wBMP.canvas.handle, PChar(Caption), Length(Caption), PaintRect, DrawFlags, nil);
DC := GetWindowDC(Handle) ;
try
BitBlt(DC, 0, 0, wBMP.width, wBMP.height, wBMP.Canvas.Handle, 0, 0, SRCCOPY) ;
finally
ReleaseDC(Handle, DC) ;
end;
finally
wBMP.Free;
end;
end;
end;
{$else}
procedure TrmOutlookPage.PaintButton;
var
PaintRect : TRect;
DrawFlags : Integer;
begin
if not (csDestroying in ComponentState) and (Assigned(FOutlookControl)) then
begin
//paint the frame..
DrawFlags := DFCS_BUTTONPUSH;
case FOutlookControl.DrawingStyle of
ds3D :; //Do nothing...
dsFlat: DrawFlags := DrawFlags or DFCS_FLAT;
dsNone: DrawFlags := DrawFlags or DFCS_Mono;
end;
DrawFrameControl(Canvas.Handle, BtnRect, DFC_BUTTON, DrawFlags);
if FCloseButton then
begin
Canvas.Brush.Color := clBlack;
DrawFlags := DFCS_CAPTIONCLOSE;
if FCloseButtonDown and FCloseMouseOver then
DrawFlags := Drawflags or DFCS_PUSHED
else
DrawFlags := Drawflags or DFCS_FLAT;
DrawFrameControl(Canvas.Handle, CloseBtnRect, DFC_CAPTION, DrawFlags);
Canvas.Brush.Style := bsClear;
end;
PaintRect := BtnRect;
//paint the bitmap if there is one...
if ImageIndex <> -1 then
begin
if Assigned(FOutlookControl.FImages) then
begin
FOutlookControl.FImages.Draw(Canvas, 2, (FOutlookControl.ButtonHeight div 2) - (FOutlookControl.FImages.Width div 2) , ImageIndex);
PaintRect.left := FOutlookControl.FImages.Width+4;
end;
end;
//Adjust for closebtn...
PaintRect.right := ClosebtnRect.Left - 2;
//paint the text...
DrawFlags := DT_SINGLELINE or DT_VCENTER or DT_END_ELLIPSIS;
case FAlignment of
taLeftJustify : DrawFlags := DrawFlags or DT_LEFT;
taRightJustify : DrawFlags := DrawFlags or DT_RIGHT;
taCenter : DrawFlags := DrawFlags or DT_CENTER;
end;
if ParentFont then
Canvas.Font.assign(fOutlookControl.Font)
else
Canvas.Font.assign(Font);
if fMouseOverBtn then
canvas.font.color := clHighlight;
DrawTextEx(Canvas.Handle, PChar(Caption), Length(Caption), PaintRect, DrawFlags, nil);
end;
end;
procedure TrmOutlookPage.AdjustClientrect(var Rect: TRect);
begin
Rect.Top := Rect.Top + btnHeight;
inherited AdjustClientRect(Rect);
end;
{$endif}
function TrmOutlookPage.BtnHeight: integer;
begin
if fOutlookControl <> nil then
result := FOutlookControl.ButtonHeight
else
result := 18;
end;
{ TrmOutlookControl }
constructor TrmOutlookControl.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
width := 175;
height := 250;
fDrawingStyle := ds3D;
Caption := '';
FButtonHeight := 18;
color := clAppWorkspace;
FPages := TList.Create;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
destructor TrmOutlookControl.Destroy;
var
I : Integer;
begin
for I := FPages.Count - 1 downto 0 do
TrmOutlookPage(FPages[I]).Free;
FPages.Free;
FImageChangeLink.Free;
inherited Destroy;
end;
procedure TrmOutlookControl.ImageListChange(Sender : TObject);
begin
Invalidate;
end;
procedure TrmOutlookControl.AdjustPages;
var
loop : Integer;
wVisibleCount : Integer;
ProcessFlag : Boolean;
wTop : integer;
wPage : TrmOutLookPage;
begin
if (csDestroying in ComponentState) then
exit;
//how many are visible?
wVisibleCount := 0;
if (csDesigning in ComponentState) then
begin
wVisibleCount := FPages.Count;
end
else
begin
for loop := 0 to FPages.Count - 1 do
begin
if TrmOutLookPage(fPages[loop]).Visible then
inc(wVisibleCount);
end;
end;
wTop := GetBorderWidth;
for loop := 0 to FPages.Count - 1 do
begin
if (csDesigning in ComponentState) then
ProcessFlag := True
else
begin
if TrmOutLookPage(FPages[loop]).Visible then
ProcessFlag := True
else
ProcessFlag := False;
end;
if ProcessFlag then
begin
wPage := TrmOutLookPage(FPages[loop]);
wPage.Left := GetBorderWidth;
wPage.Width := ClientWidth - GetBorderWidth;
wPage.Top := wTop;
if assigned(fActivePage) then
begin
if (loop = FActivePage.PageIndex) then
wPage.Height := ((ClientHeight - GetBorderWidth) - ((wVisibleCount - 1) * FButtonHeight))
else
wPage.Height := FButtonHeight;
end
else
begin
//fpages.count = 1???
wPage.Height := ((ClientHeight - GetBorderWidth) - ((wVisibleCount - 1) * FButtonHeight));
if FPages.Count = 1 then
FActivePage := wPage;
end;
wPage.UpdatePage;
wPage.Invalidate;
inc(wTop, wPage.Height);
end;
end;
end;
function TrmOutlookControl.FindNextPage(CurPage : TrmOutlookPage; GoForward : Boolean) : TrmOutlookPage;
var
I, StartIndex : Integer;
begin
Result := nil;
if FPages.Count <> 0 then
begin
StartIndex := FPages.IndexOf(CurPage);
if StartIndex = -1 then
begin
if GoForward then
begin
StartIndex := FPages.Count - 1;
for I := StartIndex downto 0 do
begin
if TrmOutlookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end
else
begin
StartIndex := 0;
for I := 0 to FPages.Count - 1 do
begin
if TrmOutlookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end;
end;
if GoForward then
begin
Inc(StartIndex);
if StartIndex = FPages.Count then
StartIndex := 0;
for I := StartIndex to FPages.Count - 1 do
begin
if TrmOutlookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end
else
begin
if StartIndex = 0 then
StartIndex := FPages.Count;
Dec(StartIndex);
for I := StartIndex downto 0 do
begin
if TrmOutlookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end;
Result := FPages[StartIndex];
end;
end;
procedure TrmOutlookControl.GetChildren(Proc : TGetChildProc; Root : TComponent);
var
I : Integer;
begin
for I := 0 to FPages.Count - 1 do
Proc(TComponent(FPages[I]));
end;
function TrmOutlookControl.GetPage(Index : Integer) : TrmOutlookPage;
begin
Result := FPages[Index];
end;
function TrmOutlookControl.GetPageCount : Integer;
begin
Result := FPages.Count;
end;
procedure TrmOutlookControl.InsertPage(Page : TrmOutlookPage);
begin
FPages.Add(Page);
Page.FOutlookControl := Self;
Page.FreeNotification(self);
end;
procedure TrmOutlookControl.RemovePage(Page : TrmOutlookPage);
var
wPage : TrmOutlookPage;
begin
if FActivePage = Page then
begin
wPage := FindNextPage(FActivePage, True);
if wPage = Page then
FActivePage := nil
else
FActivePage := wPage;
end;
FPages.Remove(Page);
Page.FOutlookControl := nil;
if not (csDestroying in ComponentState) then
Invalidate;
end;
procedure TrmOutlookControl.SelectNextPage(GoForward : Boolean);
begin
SetActivePage(FindNextPage(ActivePage, GoForward));
end;
procedure TrmOutlookControl.SetActivePage(Page : TrmOutlookPage);
begin
if not (csDestroying in ComponentState) then
begin
if (assigned(Page) and (Page.OutlookControl = Self)) or (Page = nil) then
begin
fActivePage := Page;
AdjustPages;
if Assigned(FPageChanged) and not (csDestroying in ComponentState) then
FPageChanged(self);
end;
end;
end;
procedure TrmOutlookControl.SetChildOrder(Child : TComponent; Order : Integer);
begin
TrmOutlookPage(Child).PageIndex := Order;
end;
procedure TrmOutlookControl.ShowControl(AControl : TControl);
begin
if (AControl is TrmOutlookPage) and (TrmOutlookPage(AControl).OutlookControl = Self) then
SetActivePage(TrmOutlookPage(AControl));
inherited ShowControl(AControl);
end;
procedure TrmOutlookControl.CMDialogKey(var Message : TCMDialogKey);
begin
if (Message.CharCode = VK_TAB) and (GetKeyState(VK_CONTROL) < 0) then
begin
SelectNextPage(GetKeyState(VK_SHIFT) >= 0);
Message.Result := 1;
end
else
inherited;
end;
procedure TrmOutlookControl.SetImages(Value : TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
Invalidate;
end;
procedure TrmOutlookControl.SetButtonHeight(value : integer);
begin
FButtonHeight := value;
Invalidate;
end;
procedure TrmOutlookControl.Paint;
var
wRect : TRect;
begin
wRect := ClientRect;
InflateRect(wRect, GetBorderWidth, GetBorderWidth);
Canvas.Brush.Color := clAppworkspace;
Canvas.Brush.Style := bsSolid;
case fDrawingStyle of
ds3D:
begin
Frame3d(Canvas, wRect, clBtnShadow, clBtnHighlight, 1);
Frame3d(Canvas, wRect, cl3DDkShadow, cl3DLight, 1);
end;
dsFlat:
begin
Frame3d(Canvas, wRect, cl3DDkShadow, cl3DDkShadow, 1);
end;
else
//Do Nothing...
end;
Canvas.FillRect(wRect);
AdjustPages;
if assigned(FActivePage) then
fActivePage.Invalidate;
end;
procedure TrmOutlookControl.WMErase(var Message: TMessage);
begin
Message.Result := 1;
end;
function TrmOutlookControl.GetClientRect: TRect;
begin
result := inherited GetClientRect;
InflateRect(result, -GetBorderWidth, -GetBorderWidth);
end;
procedure TrmOutlookControl.SetDrawingStyle(const Value: TrmDrawingStyle);
begin
fDrawingStyle := Value;
invalidate;
end;
function TrmOutlookControl.GetBorderWidth: integer;
begin
case fDrawingStyle of
ds3D : result := 2;
dsFlat : result := 1;
else
result := 0;
end;
end;
procedure TrmOutlookControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = Images then
Images := nil;
if (AComponent is TrmOutlookPage) and (TrmOutlookPage(AComponent).OutlookControl = self) then
RemovePage(TrmOutlookPage(AComponent));
end;
end;
procedure TrmOutlookControl.CMColorChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmOutlookControl.CMFontChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmOutlookControl.Resize;
begin
inherited;
AdjustPages;
end;
end.
|
unit ibSHConstraint;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTConstraint = class(TibBTDBObject, IibSHConstraint)
private
FTableName: string;
FConstraintType: string;
FReferenceTable: string;
FReferenceFields: TStrings;
FOnUpdateRule: string;
FOnDeleteRule: string;
FIndexName: string;
FIndexSorting: string;
FCheckSource: TStrings;
function GetConstraintType: string;
procedure SetConstraintType(Value: string);
function GetTableName: string;
procedure SetTableName(Value: string);
function GetReferenceTable: string;
procedure SetReferenceTable(Value: string);
function GetReferenceFields: TStrings;
procedure SetReferenceFields(Value: TStrings);
function GetOnUpdateRule: string;
procedure SetOnUpdateRule(Value: string);
function GetOnDeleteRule: string;
procedure SetOnDeleteRule(Value: string);
function GetIndexName: string;
procedure SetIndexName(Value: string);
function GetIndexSorting: string;
procedure SetIndexSorting(Value: string);
function GetCheckSource: TStrings;
procedure SetCheckSource(Value: TStrings);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property ConstraintType: string read GetConstraintType {write SetConstraintType};
property TableName: string read GetTableName {write SetTableName};
property Fields;
property ReferenceTable: string read GetReferenceTable {write SetReferenceTable};
property ReferenceFields: TStrings read GetReferenceFields {write SetReferenceFields};
property OnUpdateRule: string read GetOnUpdateRule {write SetOnUpdateRule};
property OnDeleteRule: string read GetOnDeleteRule {write SetOnDeleteRule};
property IndexName: string read GetIndexName {write SetIndexName};
property IndexSorting: string read GetIndexSorting {write SetIndexSorting};
property CheckSource: TStrings read GetCheckSource {write SetCheckSource};
end;
implementation
{ TibBTConstraint }
constructor TibBTConstraint.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FReferenceFields := TStringList.Create;
FCheckSource := TStringList.Create;
end;
destructor TibBTConstraint.Destroy;
begin
FReferenceFields.Free;
FCheckSource.Free;
inherited Destroy;
end;
function TibBTConstraint.GetTableName: string;
begin
Result := FTableName;
end;
procedure TibBTConstraint.SetTableName(Value: string);
begin
FTableName := Value;
end;
function TibBTConstraint.GetConstraintType: string;
begin
Result := FConstraintType;
end;
procedure TibBTConstraint.SetConstraintType(Value: string);
begin
FConstraintType := Value;
end;
function TibBTConstraint.GetReferenceTable: string;
begin
Result := FReferenceTable;
end;
procedure TibBTConstraint.SetReferenceTable(Value: string);
begin
FReferenceTable := Value;
end;
function TibBTConstraint.GetReferenceFields: TStrings;
begin
Result := FReferenceFields;
end;
procedure TibBTConstraint.SetReferenceFields(Value: TStrings);
begin
FReferenceFields.Assign(Value);
end;
function TibBTConstraint.GetOnUpdateRule: string;
begin
Result := FOnUpdateRule;
end;
procedure TibBTConstraint.SetOnUpdateRule(Value: string);
begin
FOnUpdateRule := Value;
end;
function TibBTConstraint.GetOnDeleteRule: string;
begin
Result := FOnDeleteRule;
end;
procedure TibBTConstraint.SetOnDeleteRule(Value: string);
begin
FOnDeleteRule := Value;
end;
function TibBTConstraint.GetIndexName: string;
begin
Result := FIndexName;
end;
procedure TibBTConstraint.SetIndexName(Value: string);
begin
FIndexName := Value;
end;
function TibBTConstraint.GetIndexSorting: string;
begin
Result := FIndexSorting;
end;
procedure TibBTConstraint.SetIndexSorting(Value: string);
begin
FIndexSorting := Value;
end;
function TibBTConstraint.GetCheckSource: TStrings;
begin
Result := FCheckSource;
end;
procedure TibBTConstraint.SetCheckSource(Value: TStrings);
begin
FCheckSource.Assign(Value);
end;
end.
|
namespace RemObjects.Elements.System;
type
WrappedException = public class(Exception)
public
constructor(aObj: Object);
begin
inherited constructor(aObj.toString);
Object := aObj;
end;
class method Wrap(o: Object): Exception;
begin
if o = nil then exit nil;
if o is Exception then exit Exception(o);
exit new WrappedException(o);
end;
property Object: Object; readonly;
end;
end. |
unit EstoqueFactory.Model.Interf;
interface
uses Produto.Model.Interf, Orcamento.Model.Interf, OrcamentoItens.Model.Interf,
OrcamentoFornecedores.Model.Interf, Cotacao.Model.Interf;
type
IEstoqueFactoryModel = interface
['{F4CF2812-5430-4922-AB34-FBEDD6F8135D}']
function Produto: IProdutoModel;
function orcamento: IOrcamentoModel;
function orcamentoItens: IOrcamentoItensModel;
function orcamentoFornecedores: IOrcamentoFornecedoresModel;
function cotacao: ICotacaoModel;
end;
implementation
end.
|
unit uNewTipeBarang;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uTSBaseClass, uNewUnit;
type
TNewTipeBarang = class(TSBaseClass)
private
FID: string;
FKode: string;
FNama: string;
function FLoadFromDB( aSQL : String ): Boolean;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function CustomTableName: string;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function ExecuteGenerateSQL: Boolean;
function GenerateInterbaseMetaData: Tstrings;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_Kode: string; dynamic;
function GetFieldNameFor_Nama: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
function LoadByCode(ACode: string): Boolean;
function LoadByID(aID: string): Boolean;
procedure UpdateData(aID, aKode, aNama: string);
property ID: string read FID write FID;
property Kode: string read FKode write FKode;
property Nama: string read FNama write FNama;
end;
implementation
uses udmMain;
{
******************************** TNewTipeBarang ********************************
}
constructor TNewTipeBarang.Create(aOwner : TComponent);
begin
inherited create(aOwner);
//FNewUnit := TUnit.Create(Self);
end;
destructor TNewTipeBarang.Destroy;
begin
//FNewUnit.free;
inherited Destroy;
end;
procedure TNewTipeBarang.ClearProperties;
begin
ID := '';
Kode := '';
Nama := '';
end;
function TNewTipeBarang.CustomTableName: string;
begin
result := 'REF$TIPE_BARANG';
end;
function TNewTipeBarang.ExecuteCustomSQLTask: Boolean;
begin
result := True;
end;
function TNewTipeBarang.ExecuteCustomSQLTaskPrior: Boolean;
begin
result := True;
end;
function TNewTipeBarang.ExecuteGenerateSQL: Boolean;
var
S: string;
// i: Integer;
// SS: Tstrings;
begin
result := True;
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit;
end
else begin
// If FID <= 0 then
if FID = '' then
begin
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_ID + ', '
+ GetFieldNameFor_Kode + ', '
+ GetFieldNameFor_Nama
+ ') values ('
+ QuotedStr(FID) + ', '
+ QuotedStr(FKode) + ','
+ QuotedStr(FNama)
+ ');'
end else
begin
S := 'Update ' + CustomTableName + ' set '
+ GetFieldNameFor_Kode + ' = ' + QuotedStr(FKode)
+ ', ' + GetFieldNameFor_Nama + ' = ' + QuotedStr(FNama)
+ ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID) + ';';
end;
end;
if not cExecSQL(S,dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end
else begin
Result := ExecuteCustomSQLTask;
end;
end;
function TNewTipeBarang.FLoadFromDB( aSQL : String ): Boolean;
begin
result := false;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
Begin
if not EOF then
begin
FID := FieldByName(GetFieldNameFor_ID).asString;
FKode := FieldByName(GetFieldNameFor_Kode).asString;
FNama := FieldByName(GetFieldNameFor_Nama).AsString;
Self.State := csLoaded;
Result := True;
end;
Free;
End;
end;
function TNewTipeBarang.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TNewTipeBarang ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'Kode Varchar(30) Not Null , ' );
result.Append( 'Nama Integer Not Null , ' );
result.Append( 'NewUnit_ID Integer Not Null, ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TNewTipeBarang.GetFieldNameFor_ID: string;
begin
Result := 'TPBRG_ID';// <<-- Rubah string ini untuk mapping
Result := 'REF$TIPE_BARANG_ID';
end;
function TNewTipeBarang.GetFieldNameFor_Kode: string;
begin
Result := 'TPBRG_CODE';// <<-- Rubah string ini untuk mapping
end;
function TNewTipeBarang.GetFieldNameFor_Nama: string;
begin
Result := 'TPBRG_NAME';// <<-- Rubah string ini untuk mapping
end;
function TNewTipeBarang.GetGeneratorName: string;
begin
Result :='GEN_REF$TIPE_BARANG_ID' ;
end;
function TNewTipeBarang.GetHeaderFlag: Integer;
begin
result := 4868;
end;
function TNewTipeBarang.LoadByCode(ACode: string): Boolean;
begin
Result := FloadFromDB('Select * from '+ CustomTableName
+ ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(ACode));
end;
function TNewTipeBarang.LoadByID(aID: string): Boolean;
begin
Result := FloadFromDB('Select * from '+ CustomTableName
+ ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(aID));
end;
procedure TNewTipeBarang.UpdateData(aID, aKode, aNama: string);
begin
ClearProperties;
FID := aID;
FKode := trim(aKode);
FNama := Trim(aNama);
State := csCreated;
end;
end.
|
unit TESTPRODUTO.Entidade.Model;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.Classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('TESTPRODUTO', '')]
[PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')]
TTESTPRODUTO = class
private
{ Private declarations }
FCODIGO: String;
FIDPRODUTO: Integer;
FCODIGO_SINAPI: string;
FDESCRICAO: nullable<String>;
FUNIDMEDIDA: nullable<String>;
FORIGEM_PRECO: nullable<String>;
FPRMEDIO: Double;
FPRMEDIO_SINAPI: Double;
FDATA_CADASTRO: TDateTime;
FULTIMA_ATUALIZACAO: TDateTime;
function getCodigo: String;
function getData_Cadastro: TDateTime;
function getUltima_Atualizacao: TDateTime;
public
{ Public declarations }
[Restrictions([NotNull])]
[Column('CODIGO', ftString, 64)]
[Dictionary('CODIGO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property CODIGO: String read getCodigo write FCODIGO;
[Restrictions([NotNull])]
[Column('IDPRODUTO', ftInteger)]
[Dictionary('IDPRODUTO', 'Mensagem de validação', '', '', '', taCenter)]
property IDPRODUTO: Integer read FIDPRODUTO write FIDPRODUTO;
[Column('CODIGO_SINAPI', ftString, 22)]
[Dictionary('CODIGO_SINAPI', 'Mensagem de validação', '', '', '', taCenter)]
property CODIGO_SINAPI: string read FCODIGO_SINAPI write FCODIGO_SINAPI;
[Column('DESCRICAO', ftString, 550)]
[Dictionary('DESCRICAO', 'Mensagem de validação', '', '', '',
taLeftJustify)]
property DESCRICAO: nullable<String> read FDESCRICAO write FDESCRICAO;
[Column('UNIDMEDIDA', ftString, 10)]
[Dictionary('UNIDMEDIDA', 'Mensagem de validação', '', '', '',
taLeftJustify)]
property UNIDMEDIDA: nullable<String> read FUNIDMEDIDA write FUNIDMEDIDA;
[Column('ORIGEM_PRECO', ftString, 10)]
[Dictionary('UNIDMEDIDA', 'Mensagem de validação', '', '', '',
taLeftJustify)]
property ORIGEM_PRECO: nullable<String> read FORIGEM_PRECO
write FORIGEM_PRECO;
[Column('PRMEDIO', ftBCD, 18, 4)]
[Dictionary('PRMEDIO', 'Mensagem de validação', '0', '', '',
taRightJustify)]
property PRMEDIO: Double read FPRMEDIO write FPRMEDIO;
[Column('PRMEDIO_SINAPI', ftBCD, 18, 4)]
[Dictionary('PRMEDIO_SINAPI', 'Mensagem de validação', '0', '', '',
taRightJustify)]
property PRMEDIO_SINAPI: Double read FPRMEDIO_SINAPI write FPRMEDIO_SINAPI;
[Restrictions([NotNull])]
[Column('DATA_CADASTRO', ftDateTime)]
[Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property DATA_CADASTRO: TDateTime read getData_Cadastro
write FDATA_CADASTRO;
[Restrictions([NotNull])]
[Column('ULTIMA_ATUALIZACAO', ftDateTime)]
[Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property ULTIMA_ATUALIZACAO: TDateTime read getUltima_Atualizacao
write FULTIMA_ATUALIZACAO;
end;
implementation
{ TTESTPRODUTO }
function TTESTPRODUTO.getCodigo: String;
begin
if FCODIGO.IsEmpty then
FCODIGO := TGUID.NewGuid.ToString;
Result := FCODIGO;
end;
function TTESTPRODUTO.getData_Cadastro: TDateTime;
begin
if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then
FDATA_CADASTRO := Now;
Result := FDATA_CADASTRO;
end;
function TTESTPRODUTO.getUltima_Atualizacao: TDateTime;
begin
FULTIMA_ATUALIZACAO := Now;
Result := FULTIMA_ATUALIZACAO;
end;
initialization
TRegisterClass.RegisterEntity(TTESTPRODUTO)
end.
|
unit svm_stack;
{$mode objfpc}
{$H+}
interface
uses
SysUtils,
svm_mem;
const
StackBlockSize = 256;
type
TStack = object
public
items: array of pointer;
size, i_pos: cardinal;
procedure init;
procedure push(p: pointer); inline;
function peek: pointer; inline;
procedure pop; inline;
function popv: pointer; inline;
procedure swp; inline;
procedure drop; inline;
procedure free; inline;
end;
PStack = ^TStack;
implementation
procedure TStack.init;
begin
SetLength(items, StackBlockSize);
i_pos := 0;
size := StackBlockSize;
end;
procedure TStack.push(p: pointer); inline;
begin
items[i_pos] := p;
Inc(i_pos);
if i_pos >= size then
begin
size := size + StackBlockSize;
SetLength(items, size);
end;
end;
function TStack.peek: pointer; inline;
begin
Result := items[i_pos - 1];
end;
procedure TStack.pop; inline;
begin
Dec(i_pos);
if size - i_pos > StackBlockSize then
begin
size := size - StackBlockSize;
SetLength(items, size);
end;
end;
function TStack.popv: pointer; inline;
begin
Dec(i_pos);
Result := items[i_pos];
if size - i_pos > StackBlockSize then
begin
size := size - StackBlockSize;
SetLength(items, size);
end;
end;
procedure TStack.swp; inline;
var
p: pointer;
begin
p := items[i_pos - 2];
items[i_pos - 2] := items[i_pos - 1];
items[i_pos - 1] := p;
end;
procedure TStack.drop; inline;
var
c: cardinal;
m: TSVMMem;
begin
c := 0;
while c < i_pos do
begin
m := TSVMMem(items[c]);
if m.m_type <> svmtNull then
InterlockedDecrement(m.m_rcnt);
Inc(c);
end;
SetLength(items, StackBlockSize);
size := StackBlockSize;
i_pos := 0;
end;
procedure TStack.free; inline;
begin
drop;
SetLength(items, 0);
size := 0;
end;
end.
|
program fre_illumos_sdparameter;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage UTF8}
{$modeswitch nestedprocvars}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp,
BaseUnix,FOS_DEFAULT_IMPLEMENTATION,FOS_BASIS_TOOLS,FOS_TOOL_INTERFACES,FRE_PROCESS,FRE_DB_INTERFACE,
fre_db_core,FRE_SYSTEM,fre_configuration,fre_dbbase;
{$I fos_version_helper.inc}
type
{ TFRE_IllumosSDParameter }
TFRE_IllumosSDParameter = class(TCustomApplication)
protected
sd_structure : IFRE_DB_Object;
fremote_key : string;
procedure DoRun ; override;
procedure GetSDStructure ;
procedure GetSDParameters (const sd: IFRE_DB_Object);
procedure GetSDVendor (const sd: IFRE_DB_Object);
procedure CheckAndSetRemote(const proc : TFRE_Process);
procedure SetParam ;
procedure PrintSDStructure ;
function ExecWithRemote (const cmd: string; const procparams: TFRE_DB_StringArray; const inputstring: string; out outputstring, errorstring:string): integer;
public
constructor Create (TheOwner: TComponent); override;
destructor Destroy ; override;
procedure WriteHelp ; virtual;
end;
{ TFRE_SolarisKernel }
procedure TFRE_IllumosSDParameter.DoRun;
var
ErrorMsg: String;
begin
// quick check parameters
ErrorMsg:=CheckOptions('hlocH:t:r:',['help','listsd','other','comstar','remotehost:','timeout:','retry:']);
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h','help') then begin
WriteHelp;
Terminate;
Exit;
end;
InitMinimal(false);
fre_dbbase.Register_DB_Extensions;
GFRE_DB.Initialize_Extension_ObjectsBuild;
Initialize_Read_FRE_CFG_Parameter;
if HasOption('H','remotehost') then begin
cFRE_REMOTE_HOST := GetOptionValue('H','remotehost');
cFRE_REMOTE_USER := 'root';
fremote_key := SetDirSeparators(cFRE_SERVER_DEFAULT_DIR+'/ssl/user/id_rsa');
end;
if HasOption('l','listsd') then begin
GetSDStructure;
PrintSDStructure;
Terminate;
Exit;
end;
if HasOption('o','other') and HasOption('c','comstar') then begin
writeln('Option other and option comstar can not be used together!');
Terminate;
Exit;
end;
if HasOption('t','timeout') or HasOption('r','retry') then begin
GetSDStructure;
PrintSDStructure;
SetParam;
GetSDStructure;
PrintSDStructure;
Terminate;
Exit;
end;
{ add your program here }
// stop program loop
WriteHelp;
Terminate;
Exit;
end;
procedure TFRE_IllumosSDParameter.GetSDStructure;
var res : integer;
outstring : string;
errorstring : string;
sl : TStringList;
i : NativeInt;
sd : IFRE_DB_Object;
begin
sd_structure := GFRE_DBI.NewObject;
res := ExecWithRemote('mdb -k',nil,'::walk sd_state | ::grep ''.!=0'''+LineEnding,outstring,errorstring);
if res=0 then
begin
sl := TStringList.Create;
try
sl.text := outstring;
for i := 0 to sl.count-1 do
begin
sd := GFRE_DBI.NewObject;
sd.Field('addr').AsString:=sl[i];
GetSDParameters(sd);
GetSDVendor(sd);
sd_structure.Field(sd.Field('addr').asstring).AsObject:=sd;
end;
finally
sl.Free;
end;
end
else
GFRE_LOG.LogConsole('Error getting sd_lun structures!'+outstring+' '+errorstring);
//writeln(sd_structure.DumpToString());
end;
procedure TFRE_IllumosSDParameter.GetSDParameters(const sd: IFRE_DB_Object);
var res : integer;
outstring : string;
errorstring : string;
sl : TStringList;
i : NativeInt;
s : string;
begin
res := ExecWithRemote('mdb -k',nil,sd.Field('addr').asstring+'::print -a struct sd_lun'+LineEnding,outstring,errorstring);
if res=0 then
begin
sl := TStringList.Create;
try
sl.text := outstring;
for i := 0 to sl.count-1 do
begin
s := sl[i];
if Pos('un_sd =',s)>0 then
sd.Field('un_sd').asstring:= trim(GFRE_BT.SepRight(s,'='));
if Pos('un_cmd_timeout =',s)>0 then
begin
sd.Field('un_cmd_timeout_addr').asstring:= trim(GFRE_BT.SepLeft(s,'un_cmd'));
sd.Field('un_cmd_timeout').asstring:= trim(GFRE_BT.SepRight(s,'='));
sd.Field('un_cmd_timeout_int16').asint16 := StrToInt(sd.Field('un_cmd_timeout').asstring);
end;
if Pos('un_retry_count =',s)>0 then
begin
sd.Field('un_retry_count_addr').asstring:= trim(GFRE_BT.SepLeft(s,'un_retry'));
sd.Field('un_retry_count').asstring:= trim(GFRE_BT.SepRight(s,'='));
sd.Field('un_retry_count_int16').asint16 := StrToInt(sd.Field('un_retry_count').asstring);
end;
end;
finally
sl.Free;
end;
end
else
GFRE_LOG.LogConsole('Error getting sd_lun structure!'+outstring+' '+errorstring);
end;
procedure TFRE_IllumosSDParameter.GetSDVendor(const sd: IFRE_DB_Object);
var res : integer;
outstring : string;
errorstring : string;
sl : TStringList;
i : NativeInt;
s : string;
begin
res := ExecWithRemote('mdb -k',nil,sd.Field('un_sd').asstring+'::print struct scsi_device sd_inq | ::print struct scsi_inquiry inq_vid inq_pid'+LineEnding,outstring,errorstring);
if res=0 then
begin
sl := TStringList.Create;
try
sl.text := outstring;
for i := 0 to sl.count-1 do
begin
s := sl[i];
if Pos('inq_vid =',s)>0 then
sd.Field('inq_vid').asstring:= GFRE_BT.SepLeft(trim(GFRE_BT.SepRight(s,'[ "')),'" ]');
if Pos('inq_pid =',s)>0 then
sd.Field('inq_pid').asstring:= GFRE_BT.SepLeft(trim(GFRE_BT.SepRight(s,'[ "')),'" ]');
end;
finally
sl.Free;
end;
end
else
GFRE_LOG.LogConsole('Error getting sd_inq structure!'+outstring+' '+errorstring);
end;
procedure TFRE_IllumosSDParameter.CheckAndSetRemote(const proc: TFRE_Process);
begin
if cFRE_REMOTE_HOST<>'' then
begin
proc.ConfigureRemote_SSH_Mode(cFRE_REMOTE_USER,cFRE_REMOTE_HOST,fremote_key);
end;
end;
procedure TFRE_IllumosSDParameter.SetParam;
var cs_to,cs_rtr: Word;
procedure _SetComstar(const obj:IFRE_DB_Object);
var res : integer;
outstring,errorstring:string;
param : string;
begin
if HasOption('o','other') then
if Pos('COMSTAR',obj.Field('inq_pid').asstring)>0 then
exit;
if HasOption('c','comstar') then
if Pos('COMSTAR',obj.Field('inq_pid').asstring)=0 then
exit;
if cs_to>0 then begin
param := obj.Field('un_cmd_timeout_addr').asstring+'/W '+lowercase('0x'+IntToHex(cs_to,2))+LineEnding;
res := ExecWithRemote('mdb -kw',nil,param,outstring,errorstring);
if res=0 then
writeln(obj.Field('addr').asstring+':',outstring)
else
begin
writeln('error setting un_cmd_timeout for ',obj.Field('addr').asstring,' ',errorstring);
abort;
end;
end;
if cs_rtr>0 then begin
param := obj.Field('un_retry_count_addr').asstring+'/W '+lowercase('0x'+IntToHex(cs_rtr,2))+LineEnding;
res := ExecWithRemote('mdb -kw',nil,param,outstring,errorstring);
if res=0 then
writeln(obj.Field('addr').asstring+':',outstring)
else
begin
writeln('error setting un_retry_count for ',obj.Field('addr').asstring,' ',errorstring);
abort;
end;
end;
end;
begin
cs_to := 0;
cs_rtr := 0;
if HasOption('t','timeout') then
cs_to := StrToIntDef(GetOptionValue('t','timeout'),0);
if HasOption('r','retry') then
cs_rtr := StrToIntDef(GetOptionValue('r','retry'),0);
sd_structure.ForAllObjects(@_SetComstar);
end;
procedure TFRE_IllumosSDParameter.PrintSDStructure;
var fmts: string;
procedure _PrintSD(const obj:IFRE_DB_Object);
var s: string;
begin
s:=Format(fmts,[obj.Field('addr').asstring,obj.Field('inq_vid').asstring,obj.Field('inq_pid').asstring,inttostr(obj.Field('un_cmd_timeout_int16').asint16),inttostr(obj.Field('un_retry_count_int16').asint16)]);
writeln(s);
end;
begin
fmts :='%-16s %-16s %-16s %-12s %-12s';
writeln(Format(fmts,['sd_state_addr','vid','pid','cmd_timeout','cmd_retry']));
sd_structure.ForAllObjects(@_PrintSD);
// writeln(sd_structure.DumpToString());
end;
function TFRE_IllumosSDParameter.ExecWithRemote(const cmd: string; const procparams: TFRE_DB_StringArray; const inputstring: string; out outputstring, errorstring: string): integer;
var proc : TFRE_Process;
begin
proc := TFRE_Process.Create(nil);
try
CheckAndSetRemote(proc);
result := proc.ExecutePiped(cmd,procparams,inputstring,outputstring,errorstring);
finally
proc.free;
end;
end;
constructor TFRE_IllumosSDParameter.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TFRE_IllumosSDParameter.Destroy;
begin
inherited Destroy;
end;
procedure TFRE_IllumosSDParameter.WriteHelp;
begin
{ add your help code here }
writeln(GFOS_VHELP_GET_VERSION_STRING);
writeln('Usage:');
writeln('-h --help : print help');
writeln('-l --listsd : list sd devices and parameter');
writeln('-t --timeout=<value> : set cmd timeout for sd devices');
writeln('-r --retry=<value> : set retry count for sd devices');
writeln('-H --remotehost=<value> : set remotehost');
writeln('-c --comstar : set only COMSTAR devices');
writeln('-o --other : set only non-COMSTAR devices');
end;
var
Application: TFRE_IllumosSDParameter;
begin
Application:=TFRE_IllumosSDParameter.Create(nil);
Application.Title:='ill'
+'um'
+'os'
+'_'
+'sd'
+'pa'
+'ra'
+'me'
+'te'
+'r';
Application.Run;
Application.Free;
end.
|
unit LIB.Lattice.D1;
interface //#################################################################### ■
uses System.UITypes,
FMX.Graphics,
LIB;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMap1D<_TYPE_>
TMap1D<_TYPE_> = class
private
///// メソッド
procedure InitMap;
protected
_Map :TArray<_TYPE_>;
_SizeX :Integer;
///// アクセス
procedure SetSizeX( const SizeX_:Integer );
public
constructor Create; overload;
constructor Create( const SizeX_:Integer ); overload; virtual;
///// プロパティ
property SizeX :Integer read _SizeX write SetSizeX;
///// メソッド
procedure Clear( const Value_:_TYPE_ );
procedure LoadFromFile( const FileName_:String ); virtual; abstract;
procedure SaveToFile( const FileName_:String ); virtual; abstract;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TColorMap1D
TColorMap1D = class( TMap1D<TAlphaColorF> )
private
protected
public
///// メソッド
procedure LoadFromFile( const FileName_:String ); override;
procedure SaveToFile( const FileName_:String ); override;
procedure ImportFrom( const BMP_:TBitmap );
procedure ExportTo( const BMP_:TBitmap );
function Interp( const X_:Single ) :TAlphaColorF;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.Math;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMap1D
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// メソッド
procedure TMap1D<_TYPE_>.InitMap;
begin
SetLength( _Map, _SizeX );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
procedure TMap1D<_TYPE_>.SetSizeX( const SizeX_:Integer );
begin
_SizeX := SizeX_;
InitMap;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TMap1D<_TYPE_>.Create;
begin
Create( 0 );
end;
constructor TMap1D<_TYPE_>.Create( const SizeX_:Integer );
begin
inherited Create;
_SizeX := SizeX_;
InitMap;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TMap1D<_TYPE_>.Clear( const Value_:_TYPE_ );
var
X :Integer;
begin
for X := 0 to _SizeX-1 do _Map[ X ] := Value_;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TColorMap1D
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
/////////////////////////////////////////////////////////////////////// メソッド
procedure TColorMap1D.LoadFromFile( const FileName_:String );
var
B :TBitmap;
begin
B := TBitmap.Create;
B.LoadFromFile( FileName_ );
ImportFrom( B );
B.DisposeOf;
end;
procedure TColorMap1D.SaveToFile( const FileName_:String );
var
B :TBitmap;
begin
B := TBitmap.Create;
ExportTo( B );
B.SaveToFile( FileName_ );
B.DisposeOf;
end;
//------------------------------------------------------------------------------
procedure TColorMap1D.ImportFrom( const BMP_:TBitmap );
var
B :TBitmapData;
X :Integer;
P :PAlphaColor;
begin
SizeX := BMP_.Width;
BMP_.Map( TMapAccess.Read, B );
P := B.GetScanline( 0 );
for X := 0 to _SizeX-1 do
begin
_Map[ X ] := TAlphaColorF.Create( P^ ); Inc( P );
end;
BMP_.Unmap( B );
end;
procedure TColorMap1D.ExportTo( const BMP_:TBitmap );
var
B :TBitmapData;
X :Integer;
P :PAlphaColor;
begin
BMP_.SetSize( SizeX, 1 );
BMP_.Map( TMapAccess.Write, B );
P := B.GetScanline( 0 );
for X := 0 to _SizeX-1 do
begin
P^ := _Map[ X ].ToAlphaColor; Inc( P );
end;
BMP_.Unmap( B );
end;
//------------------------------------------------------------------------------
function TColorMap1D.Interp( const X_:Single ) :TAlphaColorF;
var
Xi :Integer;
begin
Xi := Clamp( Floor( _SizeX * X_ ), 0, _SizeX-1 );
Result := _Map[ Xi ];
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [GED_DOCUMENTO_DETALHE]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit GedDocumentoDetalheController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, FileUtil, Controller,
VO, ZDataset, GedDocumentoDetalheVO, GedVersaoDocumentoVO, FPJson,
Biblioteca;
type
TGedDocumentoDetalheController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaGedDocumentoDetalheVO;
class function ConsultaObjeto(pFiltro: String): TGedDocumentoDetalheVO;
class procedure Insere(pObjeto: TGedDocumentoDetalheVO);
class function Altera(pObjeto: TGedDocumentoDetalheVO; pArquivoStream, pAssinaturaStream: TMemoryStream; pMD5:String): Boolean;
class function Exclui(pId: Integer): Boolean;
class function ArmazenarArquivo(pArquivoStream, pAssinaturaStream: TMemoryStream; pOperacao: String; pIdPai: Integer; pMD5:String): Boolean;
end;
implementation
uses UDataModule, T2TiORM;
var
ObjetoLocal: TGedDocumentoDetalheVO;
class function TGedDocumentoDetalheController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TGedDocumentoDetalheVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TGedDocumentoDetalheController.ConsultaLista(pFiltro: String): TListaGedDocumentoDetalheVO;
begin
try
ObjetoLocal := TGedDocumentoDetalheVO.Create;
Result := TListaGedDocumentoDetalheVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TGedDocumentoDetalheController.ConsultaObjeto(pFiltro: String): TGedDocumentoDetalheVO;
begin
try
Result := TGedDocumentoDetalheVO.Create;
Result := TGedDocumentoDetalheVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
class procedure TGedDocumentoDetalheController.Insere(pObjeto: TGedDocumentoDetalheVO);
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TGedDocumentoDetalheController.Altera(pObjeto: TGedDocumentoDetalheVO; pArquivoStream, pAssinaturaStream: TMemoryStream; pMD5:String): Boolean;
var
UltimoID: Integer;
VersaoDocumento: TGedVersaoDocumentoVO;
begin
try
if pObjeto.Id > 0 then
begin
Result := TT2TiORM.Alterar(pObjeto);
ArmazenarArquivo(pArquivoStream, pAssinaturaStream, 'A', pObjeto.Id, pMD5);
end
else
begin
UltimoID := TT2TiORM.Inserir(pObjeto);
ArmazenarArquivo(pArquivoStream, pAssinaturaStream, 'I', UltimoID, pMD5);
Result := True;
end;
finally
end;
end;
class function TGedDocumentoDetalheController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TGedDocumentoDetalheVO;
begin
try
ObjetoLocal := TGedDocumentoDetalheVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TGedDocumentoDetalheController.ArmazenarArquivo(pArquivoStream, pAssinaturaStream: TMemoryStream; pOperacao: String; pIdPai: Integer; pMD5:String): Boolean;
var
VersaoDocumento: TGedVersaoDocumentoVO;
UltimoIdVersao: Integer;
begin
if not DirectoryExistsUTF8(ExtractFilePath(Application.ExeName) + '\Arquivos\GED\') then
ForceDirectoriesUTF8(ExtractFilePath(Application.ExeName) + '\Arquivos\GED\');
try
try
//salva o arquivo de assinatura em disco
if Assigned(pAssinaturaStream) then
begin
pAssinaturaStream.SaveToFile(ExtractFilePath(Application.ExeName) + '\Arquivos\GED\' + pMD5 + '.assinatura');
end;
//salva o arquivo enviado em disco
/// EXERCICIO: identifique o tipo de arquivo para salvar esse dado de modo dinâmico
if Assigned(pAssinaturaStream) then
begin
pArquivoStream.SaveToFile(ExtractFilePath(Application.ExeName) + '\Arquivos\GED\' + pMD5 + '.jpg');
end;
//devemos inserir um registro de versionamento informando a inclusão/alteração do documento
if pOperacao = 'I' then
begin
VersaoDocumento := TGedVersaoDocumentoVO.Create;
VersaoDocumento.Versao := 1;
VersaoDocumento.Acao := 'I';
end
else if pOperacao = 'A' then
begin
UltimoIdVersao := TT2TiORM.SelectMax('GED_VERSAO_DOCUMENTO', 'ID_GED_DOCUMENTO=' + QuotedStr(IntToStr(pIdPai)));
if UltimoIdVersao = 0 then
begin
VersaoDocumento := TGedVersaoDocumentoVO.Create;
VersaoDocumento.Versao := 1;
end
else
begin
Filtro := 'ID=' + QuotedStr(IntToStr(UltimoIdVersao));
VersaoDocumento := TGedVersaoDocumentoVO(TT2TiORM.ConsultarUmObjeto(VersaoDocumento, Filtro, True));
VersaoDocumento.Versao := VersaoDocumento.Versao + 1;
end;
VersaoDocumento.Acao := 'A';
end;
VersaoDocumento.IdColaborador := 1;//Sessao.Usuario.Id;
VersaoDocumento.IdGedDocumento := pIdPai;
VersaoDocumento.DataHora := Now;
VersaoDocumento.HashArquivo := pMD5;
VersaoDocumento.Caminho := ExtractFilePath(Application.ExeName) + '\Arquivos\GED\' + pMD5; //+ tipoarquivo;
VersaoDocumento.Caminho := StringReplace(VersaoDocumento.Caminho,'\','/',[rfReplaceAll]);
TT2TiORM.Inserir(VersaoDocumento);
Result := True;
except
Result := False;
end;
finally
end;
end;
initialization
Classes.RegisterClass(TGedDocumentoDetalheController);
finalization
Classes.UnRegisterClass(TGedDocumentoDetalheController);
end.
|
unit Common.Entities.Round;
interface
uses Neon.Core.Attributes,
Generics.Collections,
Common.Entities.Card;
type
TCardThrown=class
private
FPlayerName:String;
FCard:TCardKey;
public
property PlayerName:String read FPlayerName write FPlayerName;
property Card:TCardKey read FCard write FCard;
constructor Create(const AName:String);overload;
procedure Assign(const ASource:TCardThrown);
end;
TCardsThrown=class(TObjectList<TCardThrown>)
function Exists(const ACard:TCardKey):Boolean;
function Find(const ACard:TCardKey):TCardThrown;
function TotalValue:Double;
end;
TGameRound=class
private
FCardsThrown: TCardsThrown;
FTurnOn: String;
FWinner: String;
function GetDone: Boolean;
public
property TurnOn:String read FTurnOn write FTurnOn;
[NeonInclude(IncludeIf.Always)]
property CardsThrown:TCardsThrown read FCardsThrown write FCardsThrown;
[NeonIgnore]
property Done:Boolean read GetDone;
[NeonIgnore]
property Winner:String read FWinner write FWinner;
function Clone:TGameRound;
procedure ThrowCard(APlayer:String; ACard:TCardKey);
constructor Create;
destructor Destroy;override;
end;
implementation
{ TGameRound }
function TGameRound.Clone: TGameRound;
var i: Integer;
c:TCardThrown;
begin
result:=TGameRound.Create;
Result.FTurnOn:=FTurnOn;
for i :=0 to FCardsThrown.Count-1 do begin
c:=TCardThrown.Create;
c.Assign(FCardsThrown[i]);
Result.FCardsThrown.Add(c);
end;
end;
constructor TGameRound.Create;
begin
inherited;
FCardsThrown:=TCardsThrown.Create(True);
end;
destructor TGameRound.Destroy;
begin
FCardsThrown.Free;
inherited;
end;
function TGameRound.GetDone: Boolean;
var itm:TCardThrown;
begin
Result:=True;
for itm in FCardsThrown do begin
if itm.Card=None then begin
result:=False;
Exit;
end;
end;
end;
procedure TGameRound.ThrowCard(APlayer:String; ACard: TCardKey);
var itm:TCardThrown;
begin
for itm in FCardsThrown do begin
if itm.PlayerName=APlayer then begin
itm.Card:=ACard;
Break;
end;
end
end;
{ TCardThrown }
procedure TCardThrown.Assign(const ASource: TCardThrown);
begin
FPlayerName:=ASource.PlayerName;
FCard:=ASource.Card;
end;
constructor TCardThrown.Create(const AName: String);
begin
inherited Create;
FPlayerName:=AName;
end;
{ TCardsThrown }
function TCardsThrown.Exists(const ACard: TCardKey): Boolean;
begin
Result:=Assigned(Find(ACard));
end;
function TCardsThrown.Find(const ACard: TCardKey): TCardThrown;
var itm:TCardThrown;
begin
Result:=nil;
for itm in Self do begin
if itm.Card=ACard then begin
Result:=itm;
Exit;
end;
end;
end;
function TCardsThrown.TotalValue: Double;
var card: TCardThrown;
begin
Result:=0;
for card in Self do
Result:=Result+ALLCARDS.Find(card.Card).Points-0.666;
end;
end.
|
namespace com.example.android.jetboy;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
// Android JET demonstration code:
// All inline comments related to the use of the JetPlayer class are preceded by "JET info:"
uses
android.content,
android.content.res,
android.graphics,
android.media,
android.os,
android.util,
android.view,
android.widget,
java.util,
java.util.concurrent;
type
// JET info: the JetBoyThread receives all the events from the JET player
// JET info: through the OnJetEventListener interface.
JetBoyThread = public class(Thread, JetPlayer.OnJetEventListener)
private
// how many frames per beat? The basic animation can be changed for
// instance to 3/4 by changing this to 3.
// untested is the impact on other parts of game logic for non 4/4 time.
const ANIMATION_FRAMES_PER_BEAT = 4;
// string value for timer display
var mTimerValue: String;
//NOTE: in the original code the two title bitmaps were declared in JetBoyView
// a lazy graphic fudge for the initial title splash
var mTitleBG: Bitmap;
var mTitleBG2: Bitmap;
// The drawable to use as the far background of the animation canvas
var mBackgroundImageFar: Bitmap;
// The drawable to use as the close background of the animation canvas
var mBackgroundImageNear: Bitmap;
// JET info: event IDs within the JET file.
// JET info: in this game 80 is used for sending asteroid across the screen
// JET info: 82 is used as game time for 1/4 note beat.
const NEW_ASTEROID_EVENT = 80;
const TIMER_EVENT = 82;
//NOTE: these track numbers were hardcoded in the original code
const LASER_CHANNEL = 23;
const EXPLOSION_CHANNEL = 24;
// used to track beat for synch of mute/unmute actions
var mBeatCount: Integer := 1;
// our intrepid space boy
var mShipFlying: array of Bitmap := new Bitmap[4];
// the twinkly bit
var mBeam: array of Bitmap := new Bitmap[4];
// the things you are trying to hit
var mAsteroids: array of Bitmap := new Bitmap[12];
// hit animation
var mExplosions: array of Bitmap := new Bitmap[4];
var mTimerShell: Bitmap;
var mLaserShot: Bitmap;
// used to save the beat event system time.
var mLastBeatTime: Int64;
// how much do we move the asteroids per beat?
var mPixelMoveX: Integer := 25;
// the asteroid send events are generated from the Jet File.
// but which land they start in is random.
var mRandom: Random := new Random;
// JET info: the star of our show, a reference to the JetPlayer object.
var mJet: JetPlayer := nil;
var mJetPlaying: Boolean := false;
// Message handler used by thread to interact with TextView
var mHandler: Handler;
// Handle to the surface manager object we interact with
var mSurfaceHolder: SurfaceHolder;
// Handle to the application context, used to e.g. fetch Drawables.
var mContext: Context;
// Thread management members
var mPauseLock: Object := new Object;
var mPaused: Boolean;
// updates the screen clock. Also used for tempo timing.
var mTimer: Timer := nil;
var mTimerTask: TimerTask := nil;
// one second - used to update timer
const mTaskIntervalInMillis = 1000;
// Current height of the surface/canvas.
// see setSurfaceSize
var mCanvasHeight: Integer := 1;
// Current width of the surface/canvas.
// see setSurfaceSize
var mCanvasWidth: Integer := 1;
// used to track the picture to draw for ship animation
var mShipIndex: Integer := 0;
// stores all of the asteroid objects in order
var mDangerWillRobinson: Vector<Asteroid>;
var mExplosion: Vector<Explosion>;
// right to left scroll tracker for near and far BG
var mBGFarMoveX: Integer := 0;
var mBGNearMoveX: Integer := 0;
// how far up (close to top) jet boy can fly
var mJetBoyYMin: Integer := 40;
var mJetBoyX: Integer := 0;
var mJetBoyY: Integer := 0;
//NOTE: various hardcoded numbers used to place the laser beam guide and
//work out asteroid shootability caused problems on larger displays.
//Hence some extra fields and some calculations rather than fixed values.
var mBeamImageXOffset: Integer;
const mGuideOffsetInBeamImage = 40;
const mAsteroidOffsetInImage = 8;
const mAsteroidImageWidth = 64;
const mAsteroidImageHeight = 64;
var mNumAsteroidPaths: Integer;
// this is the pixel position of the laser beam guide.
var mAsteroidMoveLimitX: Integer; //NOTE: was hardcoded at 110;
// how far up asteroid can be painted
var mAsteroidMinY: Integer := 40;
var mJetBoyView: JetBoyView;
// array to store the mute masks that are applied during game play to respond to
// the player's hit streaks
var muteMask: array of array of Boolean;
method initializeJetPlayer;
method setInitialGameState;
method doDraw(aCanvas: Canvas);
method doDrawRunning(aCanvas: Canvas);
method doDrawReady(aCanvas: Canvas);
method doDrawPlay(aCanvas: Canvas);
method doAsteroidCreation;
method doAsteroidAnimation(aCanvas: Canvas);
protected
// Queue for GameEvents
var mEventQueue: ConcurrentLinkedQueue<GameEvent> := new ConcurrentLinkedQueue<GameEvent>;
// Context for processKey to maintain state accross frames
var mKeyContext: Object := nil;
method updateGameState;
method updateLaser(inputContext: Object);
method updateAsteroids(inputContext: Object);
method updateExplosions(inputContext: Object);
method processKeyEvent(evt: KeyGameEvent; ctx: Object): Object;
method processJetEvent(player: JetPlayer; segment: SmallInt; track, channel, controller, value: SByte);
assembly
// has laser been fired and for how long?
// user for fx logic on laser fire
var mLaserOn: Boolean := false;
var mLaserFireTime: Int64 := 0;
var mRes: Resources;
public
const TAG = 'JetBoy';
// State-tracking constants.
const STATE_START = - 1;
const STATE_PLAY = 0;
const STATE_LOSE = 1;
const STATE_PAUSE = 2;
const STATE_RUNNING = 3;
var mInitialized: Boolean := false;
// the timer display in seconds
var mTimerLimit: Integer;
// used for internal timing logic.
const TIMER_LIMIT = 72;
// start, play, running, lose are the states we use
var mState: Integer;
constructor(aJetBoyView: JetBoyView; aSurfaceHolder: SurfaceHolder; aContext: Context; aHandler: Handler);
method run; override;
method onJetNumQueuedSegmentUpdate(player: JetPlayer; nbSegments: Integer);
method onJetEvent(player: JetPlayer; segment: SmallInt; track, channel, controller, value: SByte);
method onJetPauseUpdate(player: JetPlayer; paused: Integer);
method onJetUserIdUpdate(player: JetPlayer; userId, repeatCount: Integer);
method doKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
method doKeyUp(keyCode: Integer; msg: KeyEvent): Boolean;
method doCountDown;
method setSurfaceSize(width, height: Integer);
method pause;
method unPause;
method getGameState: Integer;
method setGameState(mode: Integer);
end;
CountdownTimerTask nested in JetBoyThread = private class(TimerTask)
private
_thread: JetBoyThread;
public
constructor(aThread: JetBoyThread);
method run; override;
end;
implementation
/// <summary>
/// This is the constructor for the main worker bee
/// </summary>
constructor JetBoyThread(aJetBoyView: JetBoyView; aSurfaceHolder: SurfaceHolder; aContext: Context; aHandler: Handler);
begin
mJetBoyView := aJetBoyView;
mSurfaceHolder := aSurfaceHolder;
mHandler := aHandler;
mContext := aContext;
mRes := aContext.Resources;
// JET info: this are the mute arrays associated with the music beds in the
// JET info: JET file
//Alocate all the muteMasks
muteMask := new array of Boolean[9];
for ii: Integer := 0 to pred(muteMask.length) do
muteMask[ii] := new Boolean[32];
for ii: Integer := 0 to pred(8) do
for xx: Integer := 0 to pred(32) do
muteMask[ii][xx] := true;
muteMask[0][2] := false;
muteMask[0][3] := false;
muteMask[0][4] := false;
muteMask[0][5] := false;
muteMask[1][2] := false;
muteMask[1][3] := false;
muteMask[1][4] := false;
muteMask[1][5] := false;
muteMask[1][8] := false;
muteMask[1][9] := false;
muteMask[2][2] := false;
muteMask[2][3] := false;
muteMask[2][6] := false;
muteMask[2][7] := false;
muteMask[2][8] := false;
muteMask[2][9] := false;
muteMask[3][2] := false;
muteMask[3][3] := false;
muteMask[3][6] := false;
muteMask[3][11] := false;
muteMask[3][12] := false;
muteMask[4][2] := false;
muteMask[4][3] := false;
muteMask[4][10] := false;
muteMask[4][11] := false;
muteMask[4][12] := false;
muteMask[4][13] := false;
muteMask[5][2] := false;
muteMask[5][3] := false;
muteMask[5][10] := false;
muteMask[5][12] := false;
muteMask[5][15] := false;
muteMask[5][17] := false;
muteMask[6][2] := false;
muteMask[6][3] := false;
muteMask[6][14] := false;
muteMask[6][15] := false;
muteMask[6][16] := false;
muteMask[6][17] := false;
muteMask[7][2] := false;
muteMask[7][3] := false;
muteMask[7][6] := false;
muteMask[7][14] := false;
muteMask[7][15] := false;
muteMask[7][16] := false;
muteMask[7][17] := false;
muteMask[7][18] := false;
// set all tracks to play
for xx: Integer := 0 to pred(32) do
muteMask[8][xx] := false;
// always set state to start, ensure we come in from front door if
// app gets tucked into background
mState := STATE_START;
setInitialGameState;
mTitleBG := BitmapFactory.decodeResource(mRes, R.drawable.title_hori);
// load background image as a Bitmap instead of a Drawable b/c
// we don't need to transform it and it's faster to draw this
// way...thanks lunar lander :)
// two background since we want them moving at different speeds
mBackgroundImageFar := BitmapFactory.decodeResource(mRes, R.drawable.background_a);
mLaserShot := BitmapFactory.decodeResource(mRes, R.drawable.laser);
mBackgroundImageNear := BitmapFactory.decodeResource(mRes, R.drawable.background_b);
mShipFlying[0] := BitmapFactory.decodeResource(mRes, R.drawable.ship2_1);
mShipFlying[1] := BitmapFactory.decodeResource(mRes, R.drawable.ship2_2);
mShipFlying[2] := BitmapFactory.decodeResource(mRes, R.drawable.ship2_3);
mShipFlying[3] := BitmapFactory.decodeResource(mRes, R.drawable.ship2_4);
mBeam[0] := BitmapFactory.decodeResource(mRes, R.drawable.intbeam_1);
mBeam[1] := BitmapFactory.decodeResource(mRes, R.drawable.intbeam_2);
mBeam[2] := BitmapFactory.decodeResource(mRes, R.drawable.intbeam_3);
mBeam[3] := BitmapFactory.decodeResource(mRes, R.drawable.intbeam_4);
mBeamImageXOffset := (mShipFlying[0].Width div 2) + 40;
mAsteroidMoveLimitX := mBeamImageXOffset + mGuideOffsetInBeamImage;
mTimerShell := BitmapFactory.decodeResource(mRes, R.drawable.int_timer);
// I wanted them to rotate in a certain way
// so I loaded them backwards from the way created.
mAsteroids[11] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid01);
mAsteroids[10] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid02);
mAsteroids[9] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid03);
mAsteroids[8] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid04);
mAsteroids[7] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid05);
mAsteroids[6] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid06);
mAsteroids[5] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid07);
mAsteroids[4] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid08);
mAsteroids[3] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid09);
mAsteroids[2] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid10);
mAsteroids[1] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid11);
mAsteroids[0] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid12);
mExplosions[0] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid_explode1);
mExplosions[1] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid_explode2);
mExplosions[2] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid_explode3);
mExplosions[3] := BitmapFactory.decodeResource(mRes, R.drawable.asteroid_explode4);
mTimerValue := mContext.String[R.string.timer];
end;
/// <summary>
/// Does the grunt work of setting up initial jet requirements
/// </summary>
method JetBoyThread.initializeJetPlayer();
begin
// JET info: let's create our JetPlayer instance using the factory.
// JET info: if we already had one, the same singleton is returned.
mJet := JetPlayer.JetPlayer;
mJetPlaying := false;
// JET info: make sure we flush the queue,
// JET info: otherwise left over events from previous gameplay can hang around.
// JET info: ok, here we don't really need that but if you ever reuse a JetPlayer
// JET info: instance, clear the queue before reusing it, this will also clear any
// JET info: trigger clips that have been triggered but not played yet.
mJet.clearQueue;
// JET info: we are going to receive in this example all the JET callbacks
// JET info: inthis animation thread object.
mJet.EventListener := self;
Log.d(TAG, 'opening jet file');
// JET info: load the actual JET content the game will be playing,
// JET info: it's stored as a raw resource in our APK, and is labeled "level1"
mJet.loadJetFile(mContext.Resources.openRawResourceFd(R.raw.level1));
// JET info: if our JET file was stored on the sdcard for instance, we would have used
// JET info: mJet.loadJetFile("/sdcard/level1.jet");
Log.d(TAG, 'opening jet file DONE');
mJetBoyView.mCurrentBed := 0;
var sSegmentID: SByte := 0;
Log.d(TAG, ' start queuing jet file');
// JET info: now we're all set to prepare queuing the JET audio segments for the game.
// JET info: in this example, the game uses segment 0 for the duration of the game play,
// JET info: and plays segment 1 several times as the "outro" music, so we're going to
// JET info: queue everything upfront, but with more complex JET compositions, we could
// JET info: also queue the segments during the game play.
// JET info: this is the main game play music
// JET info: it is located at segment 0
// JET info: it uses the first DLS lib in the .jet resource, which is at index 0
// JET info: index -1 means no DLS
mJet.queueJetSegment(0, 0, 0, 0, 0, sSegmentID);
// JET info: end game music, loop 4 times normal pitch
mJet.queueJetSegment(1, 0, 4, 0, 0, sSegmentID);
// JET info: end game music loop 4 times up an octave
mJet.queueJetSegment(1, 0, 4, 1, 0, sSegmentID);
// JET info: set the mute mask as designed for the beginning of the game, when the
// JET info: the player hasn't scored yet.
mJet.setMuteArray(muteMask[0], true);
Log.d(TAG, ' start queuing jet file DONE')
end;
/// <summary>
/// the heart of the worker bee
/// </summary>
method JetBoyThread.run;
begin
while true do
begin
var c: Canvas := nil;
if mState = STATE_RUNNING then
begin
// Process any input and apply it to the game state
updateGameState;
if not mJetPlaying then
begin
mInitialized := false;
Log.d(TAG, '------> STARTING JET PLAY');
mJet.play;
mJetPlaying := true
end;
// kick off the timer task for counter update if not already
// initialized
if mTimerTask = nil then
begin
mTimerTask := new CountdownTimerTask(self);
mTimer.schedule(mTimerTask, mTaskIntervalInMillis)
end
end
else
if (mState = STATE_PLAY) and not mInitialized then
setInitialGameState
else
if mState = STATE_LOSE then
mInitialized := false;
try
c := mSurfaceHolder.lockCanvas(nil);
//NOTE: original SDK demo had this commented out
locking mSurfaceHolder do
begin
//NOTE: original SDK demo did not check for nil here
//On some devices immediately after pause (on switching away) c will be nil
if c <> nil then
doDraw(c);
end;
finally
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if c <> nil then
mSurfaceHolder.unlockCanvasAndPost(c)
end;
//If the thread has been paused, then block until we are
//notified we can proceed
locking mPauseLock do
while mPaused do
try
mPauseLock.wait
except
on e: InterruptedException do
{ whatever };
end
end;
end;
// JET info: JET event listener interface implementation:
/// <summary>
/// required OnJetEventListener method. Notifications for queue updates
/// </summary>
/// <param name="player"></param>
/// <param name="nbSegments"></param>
method JetBoyThread.onJetNumQueuedSegmentUpdate(player: JetPlayer; nbSegments: Integer);
begin
//Log.i(TAG, "onJetNumQueuedUpdate(): nbSegs =" + nbSegments);
end;
// JET info: JET event listener interface implementation:
/// <summary>
/// The method which receives notification from event listener.
/// This is where we queue up events 80 and 82.
///
/// Most of this data passed is unneeded for JetBoy logic but shown
/// for code sample completeness.
/// </summary>
/// <param name="player"></param>
/// <param name="segment"></param>
/// <param name="track"></param>
/// <param name="channel"></param>
/// <param name="controller"></param>
/// <param name="value"></param>
method JetBoyThread.onJetEvent(player: JetPlayer; segment: SmallInt; track, channel, controller, value: SByte);
begin
// Log.d(TAG, "jet got event " + value);
// events fire outside the animation thread. This can cause timing issues.
// put in queue for processing by animation thread.
mEventQueue.&add(new JetGameEvent(player, segment, track, channel, controller, value));
end;
// JET info: JET event listener interface implementation:
method JetBoyThread.onJetPauseUpdate(player: JetPlayer; paused: Integer);
begin
//Log.i(TAG, "onJetPauseUpdate(): paused =" + paused);
end;
// JET info: JET event listener interface implementation:
method JetBoyThread.onJetUserIdUpdate(player: JetPlayer; userId, repeatCount: Integer);
begin
//Log.i(TAG, "onJetUserIdUpdate(): userId =" + userId + " repeatCount=" + repeatCount);
end;
/// <summary>
/// Add key press input to the GameEvent queue
/// </summary>
/// <param name="keyCode"></param>
/// <param name="msg"></param>
/// <returns></returns>
method JetBoyThread.doKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
begin
mEventQueue.add(new KeyGameEvent(keyCode, false, msg));
exit true;
end;
/// <summary>
/// Add key press input to the GameEvent queue
/// </summary>
/// <param name="keyCode"></param>
/// <param name="msg"></param>
/// <returns></returns>
method JetBoyThread.doKeyUp(keyCode: Integer; msg: KeyEvent): Boolean;
begin
mEventQueue.add(new KeyGameEvent(keyCode, true, msg));
exit true;
end;
/// <summary>
/// Does the work of updating timer
/// </summary>
method JetBoyThread.doCountDown;
begin
// Log.d(TAG,"Time left is " + mTimerLimit);
dec(mTimerLimit);
try
// subtract one minute and see what the result is.
var moreThanMinute: Integer := mTimerLimit - 60;
if moreThanMinute >= 0 then
begin
if moreThanMinute > 9 then
mTimerValue := '1:' + moreThanMinute
else
mTimerValue := '1:0' + moreThanMinute
end
else
begin
if mTimerLimit > 9 then
mTimerValue := '0:' + mTimerLimit
else
mTimerValue := '0:0' + mTimerLimit
end;
except
on e1: Exception do
Log.e(TAG, 'doCountDown threw ' + e1.toString)
end;
var msg: Message := mHandler.obtainMessage;
var b: Bundle := new Bundle;
b.putString('text', mTimerValue);
// time's up
if mTimerLimit = 0 then
begin
b.putString('STATE_LOSE', '' + STATE_LOSE);
mTimerTask := nil;
mState := STATE_LOSE
end
else
begin
mTimerTask := new CountdownTimerTask(self);
mTimer.schedule(mTimerTask, mTaskIntervalInMillis)
end;
// this is how we send data back up to the main JetBoyView thread.
// if you look in constructor of JetBoyView you will see code for
// Handling of messages. This is borrowed directly from lunar lander.
// Thanks again!
msg.Data := b;
mHandler.sendMessage(msg);
end;
/// <summary>
/// Callback invoked when the surface dimensions change.
/// </summary>
method JetBoyThread.setSurfaceSize(width, height: Integer);
begin
// synchronized to make sure these all change atomically
locking mSurfaceHolder do
begin
mCanvasWidth := width;
mCanvasHeight := height;
// don't forget to resize the background image
mBackgroundImageFar := Bitmap.createScaledBitmap(mBackgroundImageFar, width * 2, height, true);
// don't forget to resize the background image
mBackgroundImageNear := Bitmap.createScaledBitmap(mBackgroundImageNear, width * 2, height, true);
//NOTE: new code to work out no. of asteroid paths based on height
//minus the non-beam section at top and bottom
mNumAsteroidPaths := (mCanvasHeight - mAsteroidMinY - mAsteroidMinY) div mAsteroidImageHeight;
end;
end;
/// <summary>
/// Pauses the physics update & animation.
/// </summary>
method JetBoyThread.pause;
begin
//Check for already-paused state
if mPaused then
exit;
locking mSurfaceHolder do
begin
//NOTE: JetBoy doesn't seem to have any support for a PAUSE state, so we'll ignore this
//if mState = STATE_RUNNING then
// setGameState(STATE_PAUSE);
if mTimerTask <> nil then
begin
mTimerTask.cancel;
//NOTE: original code did not set mTimerTask to nil
mTimerTask := nil
end;
if mJet <> nil then
begin
Log.d(TAG, ' pausing JET');
if mJetPlaying then
mJet.pause;
Log.d(TAG, ' paused JET');
//NOTE: this wasn't in the original code
mJetPlaying := false;
end;
end;
//NOTE: new thread management code
//To pause the thread we set a flag to true
locking mPauseLock do
mPaused := true;
end;
/// <summary>
/// Resumes the physics update & animation.
/// </summary>
method JetBoyThread.unPause;
begin
//NOTE: new thread management code
//To resume the thread we unset the flag and notify all waiting on the lock
locking mPauseLock do
begin
mPaused := false;
mPauseLock.notifyAll
end;
end;
/// <summary>
/// returns the current int value of game state as defined by state
/// tracking constants
/// </summary>
method JetBoyThread.getGameState: Integer;
begin
locking mSurfaceHolder do
exit mState
end;
/// <summary>
/// Sets the game mode. That is, whether we are running, paused, in the
/// failure state, in the victory state, etc.
/// see setState(int, CharSequence)
/// </summary>
/// <param name="mode">one of the STATE_* constants</param>
method JetBoyThread.setGameState(mode: Integer);
begin
locking mSurfaceHolder do
begin
// change state if needed
if mState <> mode then
mState := mode;
if mState = STATE_PLAY then
begin
var res: Resources := mContext.Resources;
mBackgroundImageFar := BitmapFactory.decodeResource(res, R.drawable.background_a);
// don't forget to resize the background image
mBackgroundImageFar := Bitmap.createScaledBitmap(mBackgroundImageFar, mCanvasWidth * 2, mCanvasHeight, true);
mBackgroundImageNear := BitmapFactory.decodeResource(res, R.drawable.background_b);
// don't forget to resize the background image
mBackgroundImageNear := Bitmap.createScaledBitmap(mBackgroundImageNear, mCanvasWidth * 2, mCanvasHeight, true)
end
else
if mState = STATE_RUNNING then
begin
// When we enter the running state we should clear any old
// events in the queue
mEventQueue.clear;
// And reset the key state so we don't think a button is pressed when it isn't
mKeyContext := nil
end
end;
end;
method JetBoyThread.doDraw(aCanvas: Canvas);
begin
if mState = STATE_RUNNING then
doDrawRunning(aCanvas)
else
if mState = STATE_START then
doDrawReady(aCanvas)
else
if mState in [STATE_PLAY, STATE_LOSE] then
begin
if mTitleBG2 = nil then
mTitleBG2 := BitmapFactory.decodeResource(mRes, R.drawable.title_bg_hori);
doDrawPlay(aCanvas)
end; // end state play block
end;
/// <summary>
/// Draws current state of the game Canvas.
/// </summary>
/// <param name="aCanvas"></param>
method JetBoyThread.doDrawRunning(aCanvas: Canvas);
begin
// decrement the far background
mBGFarMoveX := mBGFarMoveX - 1;
// decrement the near background
mBGNearMoveX := mBGNearMoveX - 4;
// calculate the wrap factor for matching image draw
var newFarX: Integer := mBackgroundImageFar.Width - - mBGFarMoveX;
// if we have scrolled all the way, reset to start
if newFarX <= 0 then
begin
mBGFarMoveX := 0;
// only need one draw
aCanvas.drawBitmap(mBackgroundImageFar, mBGFarMoveX, 0, nil)
end
else
begin
// need to draw original and wrap
aCanvas.drawBitmap(mBackgroundImageFar, mBGFarMoveX, 0, nil);
aCanvas.drawBitmap(mBackgroundImageFar, newFarX, 0, nil)
end;
// same story different image...
// TODO possible method call
var newNearX: Integer := mBackgroundImageNear.Width - -mBGNearMoveX;
if newNearX <= 0 then
begin
mBGNearMoveX := 0;
aCanvas.drawBitmap(mBackgroundImageNear, mBGNearMoveX, 0, nil)
end
else
begin
aCanvas.drawBitmap(mBackgroundImageNear, mBGNearMoveX, 0, nil);
aCanvas.drawBitmap(mBackgroundImageNear, newNearX, 0, nil)
end;
doAsteroidAnimation(aCanvas);
//NOTE: original code used hardcoded numbers here (X = 50 + 21), which made things
//very tight for the space ship on larger displays.
//Also the beam wasn't stretched across the full vertical space of larger displays
//TODO: remove this from the oft-called drawing code and scale the bitmap when the surface changes
var src := new Rect(0, 0, mBeam[mShipIndex].Width, mBeam[mShipIndex].Height);
var dest := new Rect(mBeamImageXOffset, 0, mBeam[mShipIndex].Width + mBeamImageXOffset, aCanvas.Height);
aCanvas.drawBitmap(mBeam[mShipIndex], src, dest, nil);
inc(mShipIndex);
if mShipIndex = 4 then
mShipIndex := 0;
// draw the space ship in the same lane as the next asteroid
aCanvas.drawBitmap(mShipFlying[mShipIndex], mJetBoyX, mJetBoyY, nil);
if mLaserOn then
aCanvas.drawBitmap(mLaserShot, mJetBoyX + mShipFlying[0].Width, mJetBoyY + (mShipFlying[0].Height div 2), nil);
// tick tock
aCanvas.drawBitmap(mTimerShell, mCanvasWidth - mTimerShell.Width, 0, nil)
end;
method JetBoyThread.doDrawReady(aCanvas: Canvas);
begin
//NOTE: original code did not resize the bitmap, so it didn't cover larger displays
//TODO: remove this from the oft-called drawing code and scale the bitmap when the surface changes
var src := new Rect(0, 0, mTitleBG.Width, mTitleBG.Height);
var dest := new Rect(0, 0, aCanvas.Width, aCanvas.Height);
aCanvas.drawBitmap(mTitleBG, src, dest, nil);
end;
method JetBoyThread.doDrawPlay(aCanvas: Canvas);
begin
//NOTE: original code did not resize the bitmap, so it didn't cover larger displays
//TODO: remove this from the oft-called drawing code and scale the bitmap when the surface changes
var src := new Rect(0, 0, mTitleBG2.Width, mTitleBG2.Height);
var dest := new Rect(0, 0, aCanvas.Width, aCanvas.Height);
aCanvas.drawBitmap(mTitleBG2, src, dest, nil);
end;
method JetBoyThread.setInitialGameState;
begin
mTimerLimit := TIMER_LIMIT;
mJetBoyY := mJetBoyYMin;
// set up jet stuff
initializeJetPlayer;
mTimer := new Timer;
mDangerWillRobinson := new Vector<Asteroid>;
mExplosion := new Vector<Explosion>;
mInitialized := true;
mJetBoyView.mHitStreak := 0;
mJetBoyView.mHitTotal := 0
end;
method JetBoyThread.doAsteroidCreation;
begin
// Log.d(TAG, 'asteroid created');
var ast: Asteroid := new Asteroid;
//NOTE: original code hardcoded 4 asteroid paths and hardcoded
//a value of 63 to multiply drawIndex by
var drawIndex: Integer := mRandom.nextInt(mNumAsteroidPaths);
ast.mDrawY := mAsteroidMinY + (drawIndex * mAsteroidImageHeight);
ast.mDrawX := mCanvasWidth - mAsteroids[0].Width;
ast.mStartTime := System.currentTimeMillis;
mDangerWillRobinson.&add(ast);
end;
method JetBoyThread.doAsteroidAnimation(aCanvas: Canvas);
begin
if ((mDangerWillRobinson = nil) or (mDangerWillRobinson.size = 0)) and
((mExplosion <> nil) and (mExplosion.size = 0)) then
exit;
// Compute what percentage through a beat we are and adjust
// animation and position based on that. This assumes 140bpm(428ms/beat).
// This is just inter-beat interpolation, no game state is updated
var frameDelta: Int64 := System.currentTimeMillis - mLastBeatTime;
var animOffset: Integer := ANIMATION_FRAMES_PER_BEAT * frameDelta div 428;
for i: Integer := mDangerWillRobinson.size - 1 downto 0 do
begin
var ast: Asteroid := mDangerWillRobinson.elementAt(i);
if not ast.mMissed then
mJetBoyY := ast.mDrawY;
// Log.d(TAG, ' drawing asteroid ' + ii.toString + ' at ' + ast.mDrawX );
aCanvas.drawBitmap(mAsteroids[(ast.mAniIndex + animOffset) mod mAsteroids.length], ast.mDrawX, ast.mDrawY, nil);
end;
for i: Integer := mExplosion.size - 1 downto 0 do
begin
var ex: Explosion := mExplosion.elementAt(i);
aCanvas.drawBitmap(mExplosions[(ex.mAniIndex + animOffset) mod mExplosions.length], ex.mDrawX, ex.mDrawY, nil);
end;
end;
/// <summary>
/// This method handles updating the model of the game state. No
/// rendering is done here only processing of inputs and update of state.
/// This includes positons of all game objects (asteroids, player,
/// explosions), their state (animation frame, hit), creation of new
/// objects, etc.
/// </summary>
method JetBoyThread.updateGameState;
begin
// Process any game events and apply them
while true do
begin
var evt: GameEvent := mEventQueue.poll;
if evt = nil then
break;
// Log.d(TAG,'*** EVENT = ' + event);
// Process keys tracking the input context to pass in to later
// calls
if evt is KeyGameEvent then
begin
// Process the key for affects other then asteroid hits
mKeyContext := processKeyEvent(KeyGameEvent(evt), mKeyContext);
// Update laser state. Having this here allows the laser to
// be triggered right when the key is pressed. If we comment
// this out the laser will only be turned on when updateLaser
// is called when processing a timer event below.
updateLaser(mKeyContext)
end
else
if evt is JetGameEvent then
begin
var jetEvent: JetGameEvent := JetGameEvent(evt);
// Only update state on a timer event
if jetEvent.value = TIMER_EVENT then
begin
// Note the time of the last beat
mLastBeatTime := System.currentTimeMillis;
// Update laser state, turning it on if a key has been
// pressed or off if it has been on for too long.
updateLaser(mKeyContext);
// Update explosions before we update asteroids because
// updateAsteroids may add new explosions that we do
// not want updated until next frame
updateExplosions(mKeyContext);
// Update asteroid positions, hit status and animations
updateAsteroids(mKeyContext)
end;
processJetEvent(jetEvent.player, jetEvent.segment, jetEvent.track, jetEvent.channel, jetEvent.controller, jetEvent.value)
end
end;
end;
/// <summary>
/// This method updates the laser status based on user input and shot
/// duration
/// </summary>
method JetBoyThread.updateLaser(inputContext: Object);
begin
// Lookup the time of the fire event if there is one
var keyTime: Int64 := if inputContext = nil then 0 else GameEvent(inputContext).eventTime;
// Log.d(TAG, 'keyTime delta = ' +
// System.currentTimeMillis-keyTime + ": obj = " + inputContext);
// If the laser has been on too long shut it down
if mLaserOn and (System.currentTimeMillis - mLaserFireTime > 400) then
mLaserOn := false
else
if System.currentTimeMillis - mLaserFireTime > 300 then
begin
// JET info: the laser sound is on track 23, we mute it (true) right away (false)
mJet.setMuteFlag(LASER_CHANNEL, true, false)
end;
// Now check to see if we should turn the laser on. We do this after
// the above shutdown logic so it can be turned back on in the same frame
// it was turned off in. If we want to add a cooldown period this may change.
if not mLaserOn and (System.currentTimeMillis - keyTime <= 400) then
begin
mLaserOn := true;
mLaserFireTime := keyTime;
// JET info: unmute the laser track (false) right away (false)
mJet.setMuteFlag(LASER_CHANNEL, false, false)
end;
end;
/// <summary>
/// Update asteroid state including position and laser hit status.
/// </summary>
method JetBoyThread.updateAsteroids(inputContext: Object);
begin
if (mDangerWillRobinson = nil) or (mDangerWillRobinson.size = 0) then
exit;
for i: Integer := pred(mDangerWillRobinson.size) downto 0 do
begin
var ast: Asteroid := mDangerWillRobinson.elementAt(i);
// If the asteroid is within laser range but not already missed
// check if the key was pressed close enough to the beat to make a hit
//NOTE: original code hardcoded a figure of 20 instead of mAsteroidOffsetInImage
if (ast.mDrawX <= mAsteroidMoveLimitX + mAsteroidOffsetInImage) and not ast.mMissed then
begin
// If the laser was fired on the beat destroy the asteroid
if mLaserOn then
begin
// Track hit streak for adjusting music
inc(mJetBoyView.mHitStreak);
inc(mJetBoyView.mHitTotal);
// replace the asteroid with an explosion
var ex: Explosion := new Explosion;
ex.mAniIndex := 0;
ex.mDrawX := ast.mDrawX;
ex.mDrawY := ast.mDrawY;
mExplosion.add(ex);
mJet.setMuteFlag(EXPLOSION_CHANNEL, false, false);
mDangerWillRobinson.removeElementAt(i);
// This asteroid has been removed process the next one
continue;
end
else
begin
// Sorry, timing was not good enough, mark the asteroid
// as missed so on next frame it cannot be hit even if it is still
// within range
ast.mMissed := true;
dec(mJetBoyView.mHitStreak);
if mJetBoyView.mHitStreak < 0 then
mJetBoyView.mHitStreak := 0;
end;
end;
// Update the asteroids position, even missed ones keep moving
ast.mDrawX := ast.mDrawX - mPixelMoveX;
// Update asteroid animation frame
ast.mAniIndex := (ast.mAniIndex + ANIMATION_FRAMES_PER_BEAT) mod mAsteroids.length;
// if we have scrolled off the screen
if ast.mDrawX < 0 then
mDangerWillRobinson.removeElementAt(i);
end;
end;
/// <summary>
/// This method updates explosion animation and removes them once they
/// have completed.
/// </summary>
method JetBoyThread.updateExplosions(inputContext: Object);
begin
if (mExplosion = nil) or (mExplosion.size = 0) then
exit;
for i: Integer := pred(mExplosion.size) downto 0 do
begin
var ex: Explosion := mExplosion.elementAt(i);
ex.mAniIndex := ex.mAniIndex + ANIMATION_FRAMES_PER_BEAT;
// When the animation completes remove the explosion
if ex.mAniIndex > 3 then
begin
mJet.setMuteFlag(EXPLOSION_CHANNEL, true, false);
mJet.setMuteFlag(LASER_CHANNEL, true, false);
mExplosion.removeElementAt(i)
end;
end;
end;
/// <summary>
/// This method handles the state updates that can be caused by key press
/// events. Key events may mean different things depending on what has
/// come before, to support this concept this method takes an opaque
/// context object as a parameter and returns an updated version. This
/// context should be set to null for the first event then should be set
/// to the last value returned for subsequent events.
/// </summary>
/// <param name="evt"></param>
/// <param name="ctx"></param>
/// <returns></returns>
method JetBoyThread.processKeyEvent(evt: KeyGameEvent; ctx: Object): Object;
begin
// Log.d(TAG, "key code is " + event.keyCode + " " + (event.up ?
// "up":"down"));
// If it is a key up on the fire key make sure we mute the
// associated sound
if evt.up then
begin
if evt.keyCode = KeyEvent.KEYCODE_DPAD_CENTER then
exit nil
end
else
begin
if (evt.keyCode = KeyEvent.KEYCODE_DPAD_CENTER) and (ctx = nil) then
exit evt
end;
// Return the context unchanged
exit ctx;
end;
/// <summary>
/// This method handles the state updates that can be caused by JET
/// events.
/// </summary>
method JetBoyThread.processJetEvent(player: JetPlayer; segment: SmallInt; track, channel, controller, value: SByte);
begin
// Log.d(TAG, "onJetEvent(): seg=" + segment + " track=" + track + " chan=" + channel
// + " cntrlr=" + controller + " val=" + value);
// Check for an event that triggers a new asteroid
if value = NEW_ASTEROID_EVENT then
doAsteroidCreation;
inc(mBeatCount);
if mBeatCount > 4 then
mBeatCount := 1;
// Scale the music based on progress
// it was a game requirement to change the mute array on 1st beat of
// the next measure when needed
// and so we track beat count, after that we track hitStreak to
// determine the music "intensity"
// if the intensity has gone up, call a corresponding trigger clip, otherwise just
// execute the rest of the music bed change logic.
if mBeatCount = 1 then
begin
// do it back wards so you fall into the correct one
if mJetBoyView.mHitStreak > 28 then
begin
// did the bed change?
if mJetBoyView.mCurrentBed <> 7 then
begin
// did it go up?
if mJetBoyView.mCurrentBed < 7 then
mJet.triggerClip(7);
mJetBoyView.mCurrentBed := 7;
// JET info: change the mute mask to update the way the music plays based
// JET info: on the player's skills.
mJet.setMuteArray(muteMask[7], false)
end
end
else
if mJetBoyView.mHitStreak > 24 then
begin
if mJetBoyView.mCurrentBed <> 6 then
begin
if mJetBoyView.mCurrentBed < 6 then
begin
// JET info: quite a few asteroids hit, trigger the clip with the guy's
// JET info: voice that encourages the player.
mJet.triggerClip(6)
end;
mJetBoyView.mCurrentBed := 6;
mJet.setMuteArray(muteMask[6], false)
end
end
else
if mJetBoyView.mHitStreak > 20 then
begin
if mJetBoyView.mCurrentBed <> 5 then
begin
if mJetBoyView.mCurrentBed < 5 then
mJet.triggerClip(5);
mJetBoyView.mCurrentBed := 5;
mJet.setMuteArray(muteMask[5], false)
end
end
else
if mJetBoyView.mHitStreak > 16 then
begin
if mJetBoyView.mCurrentBed <> 4 then
begin
if mJetBoyView.mCurrentBed < 4 then
mJet.triggerClip(4);
mJetBoyView.mCurrentBed := 4;
mJet.setMuteArray(muteMask[4], false)
end
end
else
if mJetBoyView.mHitStreak > 12 then
begin
if mJetBoyView.mCurrentBed <> 3 then
begin
if mJetBoyView.mCurrentBed < 3 then
mJet.triggerClip(3);
mJetBoyView.mCurrentBed := 3;
mJet.setMuteArray(muteMask[3], false)
end
end
else
if mJetBoyView.mHitStreak > 8 then
begin
if mJetBoyView.mCurrentBed <> 2 then
begin
if mJetBoyView.mCurrentBed < 2 then
mJet.triggerClip(2);
mJetBoyView.mCurrentBed := 2;
mJet.setMuteArray(muteMask[2], false)
end
end
else
if mJetBoyView.mHitStreak > 4 then
begin
if mJetBoyView.mCurrentBed <> 1 then
begin
if mJetBoyView.mCurrentBed < 1 then
mJet.triggerClip(1);
mJet.setMuteArray(muteMask[1], false);
mJetBoyView.mCurrentBed := 1
end
end
end;
end;
constructor JetBoyThread.CountdownTimerTask(aThread: JetBoyThread);
begin
inherited constructor;
_thread := aThread
end;
method JetBoyThread.CountdownTimerTask.run;
begin
_thread.doCountDown
end;
end. |
{/*!
Provides interface and base class for user vehicle factory.
\modified 2019-07-09 13:45pm
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl;
type
VehicleMonitorOption = public flags (
None = $00000000,
Update = $00000001,
Position = $00000002,
CarFollowingSubject = $00000010,
CarFollowingLeader = $00000020,
CarFollowingFollower = $00000040,
CarFollowingAll = $00000070,
All = $0000000F
) of UInt32;
TripType = public enum (
Regular = $00,
Access = $01,
Business = $02,
Closing = $03
) of Byte;
SignalState = public enum (
Blank = $00,
Red = $01,
Yellow = $02,
Green = $03,
Free = $04,
RTOR = $05,
ProtectedSignal = $07,
TransitProtected = $08,
FlashingRed = $09,
FlashingYellow = $0A,
NonTransitPermitted = $0B,
Blocked = $0C,
NonTransitProtected = $0F
) of Byte;
AutomationLevel = public enum (
L0_None = $00,
L1A_AssistedAccelDecel = $1A,
L1A_AssistedSteering = $1B,
L2_Partial = $20,
L3_Conditional = $30,
L4_High = $40,
L5_Full = $50
) of Byte;
VehicleProperty = public record
public
VehicleClass: Int16;
Occupancts: Int16;
Length: Single;
Width: Single;
PreviousTripID: Int32;
Trip: TripType;
Automation: AutomationLevel;
Parked: Boolean;
end;
VehicleBasicState = public record
public
SegmentID: Int32;
Grade: Single;
Speed: Single;
Accel: Single;
end;
TransitStopInfo = public record
public
RouteID: Int32;
StopID: Int32;
MaxCapacity: Int16;
Passengers: Int16;
Delay: Single;
end;
VehiclePosition = public record
public
X: Double;
Y: Double;
Z: Double;
XY_Angle: Double;
Z_Angle: Double;
end;
CarFollowingData = public record
public
VehicleID: Int32;
Speed: Single;
MaxSpeed: Single;
DesiredSpeed: Single;
CurAccel: Single;
MaxAccel: Single;
MaxDecel: Single;
NormalDecel: Single;
DistanceToStop: Single;
StoppedGap: Single;
DistanceFromMLC: Single;
LaneChanges: SByte;
Signal: SignalState;
Grade: Single;
GapDistance: Single;
Leader: ^CarFollowingData;
Follower: ^CarFollowingData;
end;
[CallingConvention(CallingConvention.FastCall)]
DepartureMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double);
[CallingConvention(CallingConvention.FastCall)]
ParkedMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double);
[CallingConvention(CallingConvention.FastCall)]
StalledMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double;
aStalled: Boolean);
[CallingConvention(CallingConvention.FastCall)]
ArrivalMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double);
[CallingConvention(CallingConvention.FastCall)]
UpdateMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double;
aState: ^VehicleBasicState);
[CallingConvention(CallingConvention.FastCall)]
CarFollowingMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double;
aData: ^CarFollowingData;
aTsmProposedAccelRate: Single): Single;
[CallingConvention(CallingConvention.FastCall)]
TransitStopMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double;
aTransitStopInfo: ^TransitStopInfo;
aDwellTime: Single): Single;
[CallingConvention(CallingConvention.FastCall)]
PositionMethodType = public method(
aSelf: ^UserVehicle;
aTime: Double;
aPosition: ^VehiclePosition);
[CallingConvention(CallingConvention.FastCall)]
AttachVehicleFailMethodType = public method(
aSelf: ^UserVehicle;
aMessage: OleString): Boolean;
UserVehicleMethodTable = public record
public
DepartureMethod: DepartureMethodType;
ParkedMethod: ParkedMethodType;
StalledMethod: StalledMethodType;
ArrivalMethod: ArrivalMethodType;
UpdateMethod: UpdateMethodType;
CarFollowingMethod: CarFollowingMethodType;
TranitStopMethod: TransitStopMethodType;
PositionMethod: PositionMethodType;
AttachVehicleFailMethod: AttachVehicleFailMethodType;
end;
UserVehicle = public record
public
MT: ^UserVehicleMethodTable; // "Faked" C++ VMT
Data: Object;
end;
UserVehicleFactory = public abstract class
private
fBuffer: List<^UserVehicle>;
fLock: Integer := 0;
method DeleteUserVehicle(aUserVehicle: ^UserVehicle);
begin
aUserVehicle^.Data := nil;
free(^Void(aUserVehicle));
end;
protected
method GetUserVehicleData(aID: LongInt; aProperty: ^VehicleProperty; aFlags: ^VehicleMonitorOption): Object; virtual; abstract;
method GetUserVehicleMethodTable: ^UserVehicleMethodTable; virtual; abstract;
public
constructor;
begin
fBuffer := new List<^UserVehicle>(10000);
end;
finalizer;
begin
Reset;
end;
method CreateUserVehicle(aID: LongInt; aProperty: ^VehicleProperty; aFlags: ^VehicleMonitorOption): ^UserVehicle;
begin
result := ^UserVehicle(malloc(sizeOf(UserVehicle)));
memset(^Byte(result), 0, sizeOf(UserVehicle));
result^.MT := GetUserVehicleMethodTable;
result^.Data := GetUserVehicleData(aID, aProperty, aFlags);
Utilities.SpinLockEnter(var fLock);
fBuffer.Add(result);
Utilities.SpinLockExit(var fLock);
end;
method Reset;
begin
for each userVehicle in fBuffer do DeleteUserVehicle(userVehicle);
fBuffer.Clear;
end;
method UserVehicleDataSet<T>: ImmutableList<T>;
begin
var lList := new List<T>;
for each userVehicle in fBuffer do lList.Add(userVehicle as T);
exit lList.ToImmutableList;
end;
end;
end. |
{
Copyright (c) 2020 Adrian Siekierka
Based on a reconstruction of code from ZZT,
Copyright 1991 Epic MegaGames, used with permission.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
{$I-}
{$V-}
unit FileSel;
interface
uses GameVars;
function FileExists(name: TFilenameString): boolean;
function FileSelect(title, extension: TString50; var cachedLinePos: integer): TFilenameString;
implementation
uses Dos, Game, TxtWind;
const
PATH_PREVIEW_LENGTH = 24;
function FileExists(name: TFilenameString): boolean;
var
f: file;
begin
Assign(f, name);
Reset(f);
if IOResult = 0 then begin
Close(f);
FileExists := true;
end else begin
FileExists := false;
end;
end;
function FileSelect(title, extension: TString50; var cachedLinePos: integer): TFilenameString;
var
textWindow: TTextWindowState;
fileSearchRec: SearchRec;
entryName: TFilenameString;
{$IFDEF WORLDDSC}
useWorldFileDesc: boolean;
{$ENDIF}
searching: boolean;
i: integer;
curPath: TFilenameString;
startPath: TFilenameString;
previewPath: string[PATH_PREVIEW_LENGTH + 4];
begin
searching := true;
{$IFDEF WORLDDSC}
useWorldFileDesc := extension = '.ZZT';
{$ENDIF}
{$IFDEF SUBDIRS}
GetDir(0, startPath);
{$ENDIF}
while searching do begin
TextWindowInitState(textWindow);
{$IFDEF SUBDIRS}
GetDir(0, curPath);
if Length(curPath) > PATH_PREVIEW_LENGTH then
previewPath := '...' + Copy(curPath, Length(curPath) - PATH_PREVIEW_LENGTH + 1, PATH_PREVIEW_LENGTH)
else
previewPath := curPath;
textWindow.Title := title + ': ' + previewPath;
{$ELSE}
textWindow.Title := title;
{$ENDIF}
textWindow.Selectable := true;
textWIndow.Hyperlink := '';
{$IFDEF SUBDIRS}
{ Directories }
FindFirst('*', Directory, fileSearchRec);
while DosError = 0 do begin
if (fileSearchRec.Attr and Directory) <> 0 then begin
entryName := fileSearchRec.Name;
if (Length(entryName) > 0) and (entryName <> '.') then
if (Length(curPath) > 3) or (entryName <> '..') then
TextWindowAppend(textWindow, '!' + entryName + ';[' + entryName + ']');
end;
FindNext(fileSearchRec);
end;
{$ENDIF}
{ Files }
FindFirst('*' + extension, AnyFile, fileSearchRec);
while DosError = 0 do begin
if (fileSearchRec.Attr and Directory) = 0 then begin
entryName := Copy(fileSearchRec.Name, 1, Length(fileSearchRec.name) - Length(extension));
{$IFDEF WORLDDSC}
if useWorldFileDesc then
for i := 1 to WorldFileDescCount do
if entryName = WorldFileDescKeys[i] then
entryName := WorldFileDescValues[i];
{$ENDIF}
TextWindowAppend(textWindow, entryName);
end;
FindNext(fileSearchRec);
end;
textWindow.LinePos := cachedLinePos;
TextWindowAppend(textWindow, 'Exit');
TextWindowDrawOpen(textWindow);
TextWindowSelect(textWindow, TWS_HYPERLINK_AS_SELECT);
TextWindowDrawClose(textWindow);
if (textWindow.LinePos = textWindow.LineCount) or TextWindowRejected then begin
{ Exit }
FileSelect := '';
searching := false;
{$IFDEF SUBDIRS}
ChDir(startPath);
end else if Length(textWindow.Hyperlink) > 0 then begin
{ Directory }
ChDir(textWindow.Hyperlink);
{$ENDIF}
end else begin
{ File }
entryName := textWindow.Lines[textWindow.LinePos]^;
if Pos(' ', entryName) <> 0 then
entryName := Copy(entryName, 1, Pos(' ', entryName) - 1);
FileSelect := entryName;
searching := false;
if startPath <> curPath then
ResetCachedLinePos;
cachedLinePos := textWindow.LinePos;
end;
TextWindowFree(textWindow);
{ Clear IOResult }
if IOResult <> 0 then begin end;
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
BASS based sound-manager (http://www.un4seen.com/music/, free for freeware).
Unsupported feature(s) :
sound source velocity
looping (sounds are played either once or forever)
source priorities (not relevant, channels are not limited)
}
unit VXS.SMBASS;
interface
{$I VXScene.inc}
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
FMX.Forms,
VXS.Sound,
VXS.Scene,
VXS.VectorGeometry,
Bass;
type
TBASS3DAlgorithm = (algDefault, algOff, algFull, algLight);
TVXSMBASS = class (TVXSoundManager)
private
FActivated : Boolean;
FAlgorithm3D : TBASS3DAlgorithm;
protected
function DoActivate : Boolean; override;
procedure DoDeActivate; override;
procedure NotifyMasterVolumeChange; override;
procedure Notify3DFactorsChanged; override;
procedure NotifyEnvironmentChanged; override;
procedure KillSource(aSource : TVXBaseSoundSource); override;
procedure UpdateSource(aSource : TVXBaseSoundSource); override;
procedure MuteSource(aSource : TVXBaseSoundSource; muted : Boolean); override;
procedure PauseSource(aSource : TVXBaseSoundSource; paused : Boolean); override;
function GetDefaultFrequency(aSource : TVXBaseSoundSource) : Integer;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
function CPUUsagePercent : Single; override;
function EAXSupported : Boolean; override;
published
property Algorithm3D : TBASS3DAlgorithm read FAlgorithm3D write FAlgorithm3D default algDefault;
end;
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
type
TBASSInfo = record
channel : HCHANNEL;
sample : HSAMPLE;
end;
PBASSInfo = ^TBASSInfo;
// VectorToBASSVector
//
procedure VectorToBASSVector(const aVector : TVector; var aBASSVector : BASS_3DVECTOR);
begin
aBASSVector.x:=aVector.X;
aBASSVector.y:=aVector.Y;
aBASSVector.z:=-aVector.Z;
end;
// ------------------
// ------------------ TVXSMBASS ------------------
// ------------------
constructor TVXSMBASS.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
BASS_Load(bassdll);
MaxChannels:=32;
end;
destructor TVXSMBASS.Destroy;
begin
inherited Destroy;
BASS_UnLoad;
end;
function TVXSMBASS.DoActivate : Boolean;
const
c3DAlgo : array [algDefault..algLight] of Integer =
(BASS_3DALG_DEFAULT, BASS_3DALG_OFF, BASS_3DALG_FULL, BASS_3DALG_LIGHT);
var
AHWND: HWND;
begin
Assert(bass_isloaded,'BASS DLL is not present');
if not BASS_Init(1, OutputFrequency, BASS_DEVICE_3D, AHWND, nil) then
begin
Result:=False;
Exit;
end;
if not BASS_Start then begin
Result:=False;
Exit;
end;
FActivated:=True;
BASS_SetConfig(BASS_CONFIG_3DALGORITHM, c3DAlgo[FAlgorithm3D]);
NotifyMasterVolumeChange;
Notify3DFactorsChanged;
if Environment<>seDefault then
NotifyEnvironmentChanged;
Result:=True;
end;
procedure TVXSMBASS.DoDeActivate;
begin
FActivated:=False;
BASS_Stop;
BASS_Free;
end;
procedure TVXSMBASS.NotifyMasterVolumeChange;
begin
if FActivated then
BASS_SetVolume(Round(MasterVolume*100));
end;
procedure TVXSMBASS.Notify3DFactorsChanged;
begin
if FActivated then
BASS_Set3DFactors(DistanceFactor, RollOffFactor, DopplerFactor);
end;
procedure TVXSMBASS.NotifyEnvironmentChanged;
const
cEnvironmentToBASSConstant : array [seDefault..sePsychotic] of Integer = (
EAX_ENVIRONMENT_GENERIC, EAX_ENVIRONMENT_PADDEDCELL, EAX_ENVIRONMENT_ROOM,
EAX_ENVIRONMENT_BATHROOM, EAX_ENVIRONMENT_LIVINGROOM, EAX_ENVIRONMENT_STONEROOM,
EAX_ENVIRONMENT_AUDITORIUM, EAX_ENVIRONMENT_CONCERTHALL, EAX_ENVIRONMENT_CAVE,
EAX_ENVIRONMENT_ARENA, EAX_ENVIRONMENT_HANGAR, EAX_ENVIRONMENT_CARPETEDHALLWAY,
EAX_ENVIRONMENT_HALLWAY, EAX_ENVIRONMENT_STONECORRIDOR, EAX_ENVIRONMENT_ALLEY,
EAX_ENVIRONMENT_FOREST, EAX_ENVIRONMENT_CITY, EAX_ENVIRONMENT_MOUNTAINS,
EAX_ENVIRONMENT_QUARRY, EAX_ENVIRONMENT_PLAIN, EAX_ENVIRONMENT_PARKINGLOT,
EAX_ENVIRONMENT_SEWERPIPE, EAX_ENVIRONMENT_UNDERWATER, EAX_ENVIRONMENT_DRUGGED,
EAX_ENVIRONMENT_DIZZY, EAX_ENVIRONMENT_PSYCHOTIC);
begin
if FActivated and EAXSupported then
BASS_SetEAXParameters(cEnvironmentToBASSConstant[Environment],-1,-1,-1);
end;
procedure TVXSMBASS.KillSource(aSource : TVXBaseSoundSource);
var
p : PBASSInfo;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if p.channel<>0 then
if not BASS_ChannelStop(p.channel) then Assert(False);
BASS_SampleFree(p.sample);
FreeMem(p);
aSource.ManagerTag:=0;
end;
end;
procedure TVXSMBASS.UpdateSource(aSource : TVXBaseSoundSource);
var
i : Integer;
p : PBASSInfo;
objPos, objOri, objVel : TVector;
position, orientation, velocity : BASS_3DVECTOR;
res: Boolean;
begin
if (sscSample in aSource.Changes) then
begin
KillSource(aSource);
end;
if (aSource.Sample=nil) or (aSource.Sample.Data=nil) or
(aSource.Sample.Data.WAVDataSize=0) then Exit;
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if BASS_ChannelIsActive(p.channel)=0 then begin
p.channel:=0;
aSource.Free;
Exit;
end;
end else begin
p:=AllocMem(SizeOf(TBASSInfo));
p.channel:=0;
i:=BASS_SAMPLE_VAM+BASS_SAMPLE_3D+BASS_SAMPLE_OVER_DIST;
if aSource.NbLoops>1 then
i:=i+BASS_SAMPLE_LOOP;
p.sample:=BASS_SampleLoad(True, aSource.Sample.Data.WAVData, 0,
aSource.Sample.Data.WAVDataSize,
MaxChannels, i);
Assert(p.sample<>0, 'BASS Error '+IntToStr(Integer(BASS_ErrorGetCode)));
aSource.ManagerTag:=Integer(p);
if aSource.Frequency<=0 then
aSource.Frequency:=-1;
end;
if aSource.Origin<>nil then begin
objPos:=aSource.Origin.AbsolutePosition;
objOri:=aSource.Origin.AbsoluteZVector;
objVel:=NullHmgVector;
end else begin
objPos:=NullHmgPoint;
objOri:=ZHmgVector;
objVel:=NullHmgVector;
end;
VectorToBASSVector(objPos, position);
VectorToBASSVector(objVel, velocity);
VectorToBASSVector(objOri, orientation);
if p.channel=0 then begin
p.channel:=BASS_SampleGetChannel(p.sample,false);
Assert(p.channel<>0);
BASS_ChannelSet3DPosition(p.channel,position, orientation, velocity);
BASS_ChannelSet3DAttributes(p.channel, BASS_3DMODE_NORMAL,
aSource.MinDistance, aSource.MaxDistance,
Round(aSource.InsideConeAngle),
Round(aSource.OutsideConeAngle),
Round(aSource.ConeOutsideVolume*100));
if not aSource.Pause then
BASS_ChannelPlay(p.channel,true);
end else BASS_ChannelSet3DPosition(p.channel, position, orientation, velocity);
if p.channel<>0 then
begin
res := BASS_ChannelSetAttribute(p.channel, BASS_ATTRIB_FREQ, 0);
Assert(res);
if aSource.Mute then
res := BASS_ChannelSetAttribute(p.channel, BASS_ATTRIB_VOL, 0)
else
res := BASS_ChannelSetAttribute(p.channel, BASS_ATTRIB_VOL, aSource.Volume);
Assert(res);
end else aSource.Free;
inherited UpdateSource(aSource);
end;
procedure TVXSMBASS.MuteSource(aSource : TVXBaseSoundSource; muted : Boolean);
var
p : PBASSInfo;
res : Boolean;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if muted then
res:=BASS_ChannelSetAttribute(p.channel, BASS_ATTRIB_VOL, 0)
else res:=BASS_ChannelSetAttribute(p.channel, BASS_ATTRIB_VOL, aSource.Volume);
Assert(res);
end;
end;
procedure TVXSMBASS.PauseSource(aSource : TVXBaseSoundSource; paused : Boolean);
var
p : PBASSInfo;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if paused then
BASS_ChannelPause(p.channel)
else BASS_ChannelPlay(p.channel,false);
end;
end;
procedure TVXSMBASS.UpdateSources;
var
objPos, objVel, objDir, objUp : TVector;
position, velocity, fwd, top : BASS_3DVECTOR;
begin
// update listener
ListenerCoordinates(objPos, objVel, objDir, objUp);
VectorToBASSVector(objPos, position);
VectorToBASSVector(objVel, velocity);
VectorToBASSVector(objDir, fwd);
VectorToBASSVector(objUp, top);
if not BASS_Set3DPosition(position, velocity, fwd, top) then Assert(False);
// update sources
inherited;
{if not }BASS_Apply3D;{ then Assert(False);}
end;
function TVXSMBASS.CPUUsagePercent : Single;
begin
Result:=BASS_GetCPU*100;
end;
function TVXSMBASS.EAXSupported : Boolean;
var
c : Cardinal;
s : Single;
begin
Result:=BASS_GetEAXParameters(c, s, s, s);
end;
function TVXSMBASS.GetDefaultFrequency(aSource : TVXBaseSoundSource): integer;
var
p : PBASSInfo;
sampleInfo : BASS_Sample;
begin
try
p:=PBASSInfo(aSource.ManagerTag);
BASS_SampleGetInfo(p.sample, sampleInfo);
Result:=sampleInfo.freq;
except
Result:=-1;
end;
end;
end.
|
{Una empresa de transportes realiza envíos de cargas, por cada bulto se
ingresa PESO de la carga (número real) y CATEGORIA (dato codificado: 1 -
común , 2 - especial , 3 – aéreo).
El precio se calcula a $25 por Kg para categoría común, $32.5 por Kg para
categoría especial y $50 por Kg para categoría aérea.Se cobra recargo por
sobrepeso: 30% si sobrepasa los 15 Kg, 20% si pesa más de 10 Kg y hasta 15Kg
inclusive, 10% más de 5Kg y hasta 10 Kg inclusive.
Se desea calcular y mostrar el importe a pagar por cada uno de N bultos y al final
del proceso el total recaudado en cada una de las tres categorías.
Implementar y utilizar función Precio correctamente parametrizada que devuelva el
importe a pagar por un bulto.}
Program Transportes;
Function Precio(Pes:real; Ca:char):real;
Var
Pr:real;
Begin
Pr:= 0;
If (Ca = '1') then
Pr:= Pes * 25
Else
if (Ca = '2') then
Pr:= Pes * 32.5
Else
Pr:= Pes * 50;
If (Pes <= 10) then
Pr:= Pr * 1.1
Else
if (Pes <= 15) then
Pr:= Pr * 1.2
Else
Pr:= Pr * 1.3;
Precio:= Pr;
end;
Var
i,N:word;
Cat:char;
Peso,Pr,Acum1,Acum2,Acum3:real;
Begin
Acum1:= 0;
Acum2:= 0;
Acum3:= 0;
Pr:= 0;
write('Ingrese la cantidad de bultos: ');readln(N);
For i:= 1 to N do
begin
write('Ingrese el peso de la carga: ');readln(Peso);
write('Ingrese la categoria: 1- Comun / 2- Especial / 3- Aereo : ');readln(Cat);
writeln('El importe a abonar por este bulto es: $',Precio(Peso,Cat):2:0);
writeln;
Pr:= Precio(Peso,Cat);
If (Cat = '1') then //Acumulamos segun cada categoria y luego le sumamos el valor que retorna la funcion para ir acumulando.
Acum1:= Acum1 + Pr
Else
if (Cat = '2') then
Acum2:= Acum2 + Pr
Else
Acum3:= Acum3 + Pr;
end;
writeln('El total recaudado por la categoria 1 es: $',Acum1:2:0);
writeln('El total recaudado por la categoria 2 es: $',Acum2:2:0);
writeln('El total recaudado por la categoria 3 es: $',Acum3:2:0);
end.
|
{
Создание стандартных диалогов (ShowMessage, etc) в виде, аналогичном
диалогам помощника из MS Office 2000.
(с) 2002, HyperSoft, Игорь Шевченко.
}
unit HSDialogs;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
// Позиция треугольного хвостика относительно окна
type
TTrianglePosition = (tpNone, //Нету
tpLeftTop, tpLeftBottom, //На левой стороне, вверху или внизу
tpTopLeft, tpTopRight, //На верхней стороне, слева или справа
tpRightTop, tpRightBottom, //На правой стороне, вверху или внизу
tpBottomLeft, tpBottomRight); //На нижней стороне, слева или справа
TfRgnDialog = class(TForm)
private
FMessageText : TLabel;
FRegion : HRGN;
FTrianglePosition: TTrianglePosition;
FXCursorOffset,
FYCursorOffset : Integer;
procedure FreeCurrentRegion();
procedure SetTrianglePosition(const Value: TTrianglePosition);
procedure WMNCHitTest (var Message : TWMNCHitTest); message WM_NCHITTEST;
procedure HelpButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
{ Позиция кончика хвостика относительно левого края Control'а по горизонтали }
property XCursorOffset : Integer read FXCursorOffset write FXCursorOffset;
{ Позиция кончика хвостика относительно
верхнего или нижнего края Control'а по горизонтали. }
property YCursorOffset : Integer read FYCursorOffset write FYCursorOffset;
protected
procedure Paint; override;
public
procedure AlignWindow (AEditorControl : TControl);
{ Позиция треугольного хвостика }
property TrianglePosition : TTrianglePosition read FTrianglePosition
write SetTrianglePosition default tpNone;
constructor CreateNew (AOwner : TComponent); reintroduce;
destructor Destroy; override;
end;
var
RoundRectCurve : Integer = 20; { Размер эллипса для скругления углов }
TriangleWidth : Integer = 10; { Ширина треугольного хвостика }
TriangleHeight : Integer = 20; { Высота треугольного хвостика }
TriangleIndent : Integer = 40; { Смещение треугольного хвостика
относительно края окна }
var
MessageColor : TColor; { Цвет формы сообщения }
function CreateHSMessageDialog (const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons;
{ Control, на который указывает хвостик }
AEditorControl : TControl = nil;
{ Позиция хвостика относительно левого края Control }
AXCursorOffset : Integer = 20;
{ Позиция хвостика относительно
верхнего (или нижнего) края Control }
AYCursorOffset : Integer = 2): TCustomForm;
function HSMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2): Integer;
procedure HSShowMessage(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowMessageFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowError(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowErrorFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowWarning(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowWarningFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowInfo(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
procedure HSShowInfoFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
function HSConfirmMessage(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Boolean;
function HSConfirmMessageFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Boolean;
function HSAskYesNoCancel(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Integer;
function HSAskYesNoCancelFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Integer;
{
Заголовки кнопок, некий аналог Consts.pas.
Так как программа рассчитана на русскоязычный интерфейс, то и заголовки кнопок
по умолчанию указаны русскими. Translation Manager может исправить этот
недостаток :-)
}
resourcestring
SHSMsgDlgYes = 'Да';
SHSMsgDlgNo = 'Нет';
SHSMsgDlgOK = 'OK';
SHSMsgDlgCancel = 'Отмена';
SHSMsgDlgAbort = 'Прервать';
SHSMsgDlgRetry = 'Повторить';
SHSMsgDlgIgnore = 'Пропустить';
SHSMsgDlgAll = 'Все';
SHSMsgDlgNoToAll = 'Нет для всех';
SHSMsgDlgYesToAll = 'Да для всех';
SHSMsgDlgHelp = 'Справка';
implementation
uses
Consts, Math, ExtCtrls, HSFlatButton;
{ TfRgnDialog }
destructor TfRgnDialog.Destroy;
begin
FreeCurrentRegion;
inherited;
end;
procedure TfRgnDialog.FreeCurrentRegion;
begin
if FRegion <> 0 then begin
SetWindowRgn (Handle, 0, true);
DeleteObject (FRegion);
FRegion := 0;
end;
end;
// Так как я еще не узнал событие, в котором можно создавать
// регион, он создается на событии OnActivate формы
procedure TfRgnDialog.FormActivate(Sender: TObject);
var
FTriangle : array[0..2] of TPoint;
RectRgn, TriRgn : HRGN;
R : TRect;
begin
FreeCurrentRegion();
R := ClientRect;
if TrianglePosition <> tpNone then begin
{ Регион, в котором будут смешаны регионы. Без этого комбинация регионов
не работает }
FRegion := CreateRectRgn(0,0,R.Right,R.Bottom);
case TrianglePosition of
tpBottomLeft, tpBottomRight:
Dec(R.Bottom, TriangleHeight);
tpTopLeft, tpTopRight:
Inc(R.Top, TriangleHeight);
tpLeftTop, tpLeftBottom:
Inc(R.Left, TriangleHeight);
tpRightTop, tpRightBottom:
Dec(R.Right, TriangleHeight);
end;
{ Создание прямоугольника со скругленными углами }
with R do
RectRgn := CreateRoundRectRgn (Left, Top, Right, Bottom,
RoundRectCurve, RoundRectCurve);
{ Создание треугольного хвостика }
case TrianglePosition of
tpBottomLeft:
begin
FTriangle[0] := Point(R.Left + TriangleIndent, R.Bottom-1);
FTriangle[1] := Point(R.Left + TriangleIndent,
R.Bottom-1 + TriangleHeight);
FTriangle[2] := Point(R.Left + TriangleIndent + TriangleWidth,
R.Bottom-1);
end;
tpBottomRight:
begin
FTriangle[0] := Point(R.Right - TriangleIndent, R.Bottom-1);
FTriangle[1] := Point(R.Right - TriangleIndent,
R.Bottom-1 + TriangleHeight);
FTriangle[2] := Point(R.Right - TriangleIndent - TriangleWidth,
R.Bottom-1);
end;
tpTopLeft:
begin
FTriangle[0] := Point(R.Left + TriangleIndent, R.Top);
FTriangle[1] := Point(R.Left + TriangleIndent, R.Top - TriangleHeight);
FTriangle[2] := Point(R.Left + TriangleIndent + TriangleWidth, R.Top);
end;
tpTopRight:
begin
FTriangle[0] := Point(R.Right - TriangleIndent, R.Top);
FTriangle[1] := Point(R.Right - TriangleIndent, R.Top - TriangleHeight);
FTriangle[2] := Point(R.Right - TriangleIndent - TriangleWidth, R.Top);
end;
tpLeftTop:
begin
FTriangle[0] := Point(R.Left, R.Top + TriangleIndent);
FTriangle[1] := Point(R.Left - TriangleHeight, R.Top + TriangleIndent);
FTriangle[2] := Point(R.Left, R.Top + TriangleIndent + TriangleWidth);
end;
tpLeftBottom:
begin
FTriangle[0] := Point(R.Left, R.Bottom - TriangleIndent);
FTriangle[1] := Point(R.Left - TriangleHeight,
R.Bottom - TriangleIndent);
FTriangle[2] := Point(R.Left,
R.Bottom - TriangleIndent - TriangleWidth);
end;
tpRightTop:
begin
FTriangle[0] := Point(R.Right-1, R.Top + TriangleIndent);
FTriangle[1] := Point(R.Right-1 + TriangleHeight,
R.Top + TriangleIndent);
FTriangle[2] := Point(R.Right-1,
R.Top + TriangleIndent + TriangleWidth);
end;
tpRightBottom:
begin
FTriangle[0] := Point(R.Right-1, R.Bottom - TriangleIndent);
FTriangle[1] := Point(R.Right-1 + TriangleHeight,
R.Bottom - TriangleIndent);
FTriangle[2] := Point(R.Right-1,
R.Bottom - TriangleIndent - TriangleWidth);
end;
end;
TriRgn := CreatePolygonRgn(FTriangle, 3, WINDING);
if TriRgn = 0 then
RaiseLastWin32Error;
if CombineRgn(FRegion,RectRgn,TriRgn,RGN_OR) = ERROR then
RaiseLastWin32Error;
end else begin
{ Хвостика нет, только прямоугольник со скругленными углами }
with R do
RectRgn := CreateRoundRectRgn (Left, Top, Right, Bottom,
RoundRectCurve, RoundRectCurve);
FRegion := RectRgn;
end;
if FRegion <> 0 then
SetWindowRgn (Handle, FRegion, true);
end;
procedure TfRgnDialog.Paint;
// Рисуем окантовку вокруг формы
var
HFrameBrush : HBRUSH;
DC : HDC;
Rgn : HRGN;
begin
{ Цвет окантовки - черный }
HFrameBrush := CreateSolidBrush(clBlack);
DC := GetWindowDC(Handle);
{ Создать регион, куда будут копироваться области окна. Насколько я понимаю,
он должен изначально быть заведомо больше. }
Rgn := CreateRectRgnIndirect (BoundsRect);
GetWindowRgn(Handle, Rgn);
try
FrameRgn (DC, Rgn, HFrameBrush, 1, 1);
finally
ReleaseDC(Handle, DC);
DeleteObject(HFrameBrush);
DeleteObject(Rgn);
end;
end;
procedure TfRgnDialog.SetTrianglePosition(const Value: TTrianglePosition);
var I : Integer;
begin
if (FTrianglePosition <> Value) then begin
FTrianglePosition := Value;
case FTrianglePosition of
tpBottomLeft, tpBottomRight, // В этом режиме увеличивается высота формы
// за счет появления треугольника.
tpTopLeft, tpTopRight:
begin
Height := Height + TriangleHeight;
if FTrianglePosition in [tpTopLeft, tpTopRight] then
for I:=0 to Pred(ControlCount) do
with Controls[I] do
Top := Top + TriangleHeight;
end;
tpLeftTop, tpLeftBottom, tpRightTop, tpRightBottom:
begin
Width := Width + TriangleHeight; //В этом режиме увеличивается ширина формы
//за счет появления треугольника.
//И сдвигаются контролы по горизонтали
if FTrianglePosition in [tpLeftTop, tpLeftBottom] then begin
for I:=0 to Pred(ControlCount) do
with Controls[I] do
Left := Left + TriangleHeight DIV 2;
end else begin
for I:=0 to Pred(ControlCount) do
with Controls[I] do
Left := Left - TriangleHeight DIV 2;
end;
end;
end;
RecreateWnd(); // Так как я еще не узнал событие, в котором можно создавать
// регион, он создается на событии OnActivate
end;
end;
{
Для таскания формы за форму обрабатываем сообщение WM_NCHITTEST и
представляем всю форму как сплошной залоговок.
}
procedure TfRgnDialog.WMNCHitTest(var Message: TWMNCHitTest);
begin
//Message.Result := HTCAPTION;
end;
{ Функция скопирована из Borland'овского Dialogs.pas }
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: array[0..51] of Char;
begin
for I := 0 to 25 do
Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do
Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := Result.X div 52;
end;
{
Большинство кода этой функции взято из почти одноименной функции
CreateMessageDialog из Borland'овского Dialogs.pas
}
var
IconIDs: array[TMsgDlgType] of PChar = (IDI_EXCLAMATION, IDI_HAND,
IDI_ASTERISK, IDI_QUESTION, nil);
ButtonCaptions: array[TMsgDlgBtn] of Pointer = (
@SHSMsgDlgYes, @SHSMsgDlgNo, @SHSMsgDlgOK, @SHSMsgDlgCancel,
@SHSMsgDlgAbort, @SHSMsgDlgRetry, @SHSMsgDlgIgnore, @SHSMsgDlgAll,
@SHSMsgDlgNoToAll, @SHSMsgDlgYesToAll, @SHSMsgDlgHelp);
ButtonNames: array[TMsgDlgBtn] of String = (
'Yes', 'No', 'OK', 'Cancel', 'Abort',
'Retry', 'Ignore', 'All', 'NoToAll', 'YesToAll',
'Help');
ModalResults: array[TMsgDlgBtn] of Integer = (
mrYes, mrNo, mrOk, mrCancel, mrAbort, mrRetry, mrIgnore, mrAll, mrNoToAll,
mrYesToAll, 0);
var
ButtonWidths : array[TMsgDlgBtn] of integer; // Инициализуется нулями при
// компиляции
function CreateHSMessageDialog (const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons;
AEditorControl : TControl;
AXCursorOffset : Integer;
AYCursorOffset : Integer): TCustomForm;
const
mcHorzMargin = 8;
mcVertMargin = 8;
mcHorzSpacing = 10;
mcVertSpacing = 10;
mcButtonWidth = 50;
mcButtonHeight = 14;
mcButtonSpacing = 4;
var
AForm : TfRgnDialog; { Созданная форма }
DialogUnits: TPoint;
HorzMargin, VertMargin, HorzSpacing, VertSpacing, ButtonWidth,
ButtonHeight, ButtonSpacing, ButtonCount, ButtonGroupWidth,
IconTextWidth, IconTextHeight, X, ALeft: Integer;
B, DefaultButton, CancelButton: TMsgDlgBtn;
IconID: PChar;
TextRect: TRect;
begin
Result := TfRgnDialog.CreateNew(Application);
AForm := TfRgnDialog(Result);
with Result do begin
BiDiMode := Application.BiDiMode; { Метод ввода }
BorderStyle := bsNone; { Нет бордюра }
Canvas.Font := Font; { Шрифт, стандартный для MessageBox }
DialogUnits := GetAveCharSize(Canvas); { Коэффициент для расчетов границ и
смещений }
HorzMargin := MulDiv(mcHorzMargin, DialogUnits.X, 4);
VertMargin := MulDiv(mcVertMargin, DialogUnits.Y, 8);
HorzSpacing := MulDiv(mcHorzSpacing, DialogUnits.X, 4);
VertSpacing := MulDiv(mcVertSpacing, DialogUnits.Y, 8);
ButtonWidth := MulDiv(mcButtonWidth, DialogUnits.X, 4);
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then begin
if ButtonWidths[B] = 0 then begin
TextRect := Rect(0,0,0,0);
Windows.DrawText( Canvas.Handle,
PChar(LoadResString(ButtonCaptions[B])), -1,
TextRect, DT_CALCRECT or DT_LEFT or DT_SINGLELINE or
DrawTextBiDiModeFlagsReadingOnly);
with TextRect do
ButtonWidths[B] := Right - Left + 8;
end;
if ButtonWidths[B] > ButtonWidth then
ButtonWidth := ButtonWidths[B];
end;
ButtonHeight := MulDiv(mcButtonHeight, DialogUnits.Y, 8);
ButtonSpacing := MulDiv(mcButtonSpacing, DialogUnits.X, 4);
SetRect(TextRect, 0, 0, Screen.Width div 2, 0);
DrawText(Canvas.Handle, PChar(Msg), Length(Msg)+1, TextRect,
DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK or
DrawTextBiDiModeFlagsReadingOnly);
IconID := IconIDs[DlgType];
IconTextWidth := TextRect.Right;
IconTextHeight := TextRect.Bottom;
if IconID <> nil then begin
Inc(IconTextWidth, 32 + HorzSpacing);
if IconTextHeight < 32 then
IconTextHeight := 32;
end;
ButtonCount := 0;
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then
Inc(ButtonCount);
ButtonGroupWidth := 0; { Размер кнопок }
if ButtonCount <> 0 then
ButtonGroupWidth := ButtonWidth * ButtonCount +
ButtonSpacing * (ButtonCount - 1);
ClientWidth := Max(IconTextWidth, ButtonGroupWidth) + HorzMargin * 2;
ClientHeight := IconTextHeight + ButtonHeight + VertSpacing +
VertMargin * 2;
Left := (Screen.Width div 2) - (Width div 2);
Top := (Screen.Height div 2) - (Height div 2);
if IconID <> nil then
with TImage.Create(Result) do begin
Name := 'Image';
Parent := Result;
Picture.Icon.Handle := LoadIcon(0, IconID);
SetBounds(HorzMargin, VertMargin, 32, 32);
end;
AForm.FMessageText := TLabel.Create(Result);
with AForm.FMessageText do begin
Name := 'Message';
Parent := Result;
WordWrap := True;
Caption := Msg;
BoundsRect := TextRect;
BiDiMode := Result.BiDiMode;
ALeft := IconTextWidth - TextRect.Right + HorzMargin;
if UseRightToLeftAlignment then
ALeft := Result.ClientWidth - ALeft - Width;
SetBounds(ALeft, VertMargin, TextRect.Right, TextRect.Bottom);
end;
if mbOk in Buttons then
DefaultButton := mbOk
else if mbYes in Buttons then
DefaultButton := mbYes
else
DefaultButton := mbRetry;
if mbCancel in Buttons then
CancelButton := mbCancel
else if mbNo in Buttons then
CancelButton := mbNo
else
CancelButton := mbOk;
X := (ClientWidth - ButtonGroupWidth) div 2;
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then
with THSFlatButton.Create(Result) do begin
Shape := hbsRoundRect; //Прямоугольник с закругленными краями. Форма влияет
// на поведение и раскраску кнопки, в частности,
// появляется стандартный Focus Rectangle, так как
// в этом режиме нестандартный выглядит некрасиво.
// Также, в этом режиме текст кнопки при нажатии
// съезжает вправо и вниз, чего нет при прямоугольной
// форме.
Name := ButtonNames[B];
Parent := Result;
Caption := LoadResString(ButtonCaptions[B]);
Color := Result.Color; // Цвет нажатой кнопки и отжатой соответствуют друг
// другу. В этом случае сохраняется скругленность
// краев прямоугольника.
DownColor := Result.Color;
FocusRectColor := clBlack;
if Color = clBtnFace then
BorderColor := clBlack { clBtnShadow ??? }
else
BorderColor := clBtnFace;
ModalResult := ModalResults[B];
if B = DefaultButton then
Default := True;
if B = CancelButton then
Cancel := True;
SetBounds(X, IconTextHeight + VertMargin + VertSpacing,
ButtonWidth, ButtonHeight);
Inc(X, ButtonWidth + ButtonSpacing);
if B = mbHelp then
OnClick := AForm.HelpButtonClick;
end;
end;
AForm.XCursorOffset := AXCursorOffset;
AForm.YCursorOffset := AYCursorOffset;
AForm.AlignWindow (AEditorControl);
end;
function HSMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint;
AEditorControl : TControl;
AXCursorOffset : Integer;
AYCursorOffset : Integer): Integer;
begin
with CreateHSMessageDialog(Msg, DlgType, Buttons, AEditorControl,
AXCursorOffset, AYCursorOffset) do
try
HelpContext := HelpCtx;
Result := ShowModal();
finally
Free;
end;
end;
procedure TfRgnDialog.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
constructor TfRgnDialog.CreateNew(AOwner: TComponent);
var
NonClientMetrics: TNonClientMetrics;
begin
inherited CreateNew(AOwner);
{ Создается шрифт, аналогичный тому, который используется в MessageBox }
NonClientMetrics.cbSize := sizeof(NonClientMetrics);
if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then
Font.Handle := CreateFontIndirect(NonClientMetrics.lfMessageFont);
OnActivate := FormActivate;
Color := MessageColor;
end;
{
Выравнивание диалога относительно элемента управления, к которому диалог
относится. Преимущественно, хотелось бы, чтобы диалог располагался над
элементом управления, и крайне редко - под ним.
Пока используются только позиции хвостика в верхней или нижней левой части
формы.
}
procedure TfRgnDialog.AlignWindow(AEditorControl: TControl);
var P: TPoint;
Y: Integer;
X: Integer;
WorkArea: TRect;
R : TRect;
begin
if NOT Assigned(AEditorControl) then begin
TrianglePosition := tpNone;
Position := poMainFormCenter;
Exit;
end;
R := BoundsRect;
{ Координаты требуемого контрола на экране }
P := AEditorControl.Parent.ClientToScreen(
Point(AEditorControl.Left, AEditorControl.Top));
{ Его нижняя точка }
Y := P.Y + AEditorControl.Height;
X := P.X + XCursorOffset;
{ Рабочая область экрана }
SystemParametersInfo(SPI_GETWORKAREA,0,Pointer(@WorkArea),0);
if P.Y > (Height +
GetSystemMetrics(SM_CYCAPTION)*2 + TriangleHeight) then begin
{ Треугольник будет располагаться внизу формы. Желательно, в первой трети
элемента управления }
TrianglePosition := tpBottomLeft;
Top := P.Y - YCursorOffset - Pred(Height);
Left := X - TriangleIndent;
end else begin
{ Треугольник будет располагаться вверху формы. Желательно, в первой трети
элемента управления }
TrianglePosition := tpTopLeft;
Top := Pred(Y) + YCursorOffset;
Left := X - TriangleIndent;
end;
end;
procedure HSShowMessage(const Msg: string;
AEditorControl : TControl;
AXCursorOffset : Integer;
AYCursorOffset : Integer);
begin
HSMessageDlg(Msg, mtCustom, [mbOK], 0, AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowMessageFmt(const Msg: string; Params : array of const;
AEditorControl : TControl;
AXCursorOffset : Integer;
AYCursorOffset : Integer);
begin
HSShowMessage(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowError(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSMessageDlg(Msg, mtError, [mbOK], 0, AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowErrorFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSShowError(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowWarning(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSMessageDlg(Msg, mtWarning, [mbOK], 0, AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowWarningFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSShowWarning(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowInfo(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSMessageDlg(Msg, mtInformation, [mbOK], 0, AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
procedure HSShowInfoFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2);
begin
HSShowInfo(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
function HSConfirmMessage(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Boolean;
begin
Result := HSMessageDlg(Msg, mtConfirmation, [mbYes, mbNo], 0, AEditorControl,
AXCursorOffset, AYCursorOffset) = mrYes;
end;
function HSConfirmMessageFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Boolean;
begin
Result := HSConfirmMessage(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
function HSAskYesNoCancel(const Msg: string;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Integer;
begin
Result := HSMessageDlg(Msg, mtConfirmation, [mbYes, mbNo, mbCancel], 0,
AEditorControl, AXCursorOffset, AYCursorOffset);
end;
function HSAskYesNoCancelFmt(const Msg: string; Params : array of const;
AEditorControl : TControl = nil;
AXCursorOffset : Integer = 20;
AYCursorOffset : Integer = 2) : Integer;
begin
Result := HSAskYesNoCancel(Format(Msg, Params), AEditorControl,
AXCursorOffset, AYCursorOffset);
end;
{ Мелкая служебная процедура для определения цветового разрешения экрана }
function Get256ColorMode : Boolean;
var
DC : HDC;
begin
DC := GetDC(0);
try
Result := GetDeviceCaps(DC, BITSPIXEL) = 8;
finally
ReleaseDC (0, DC);
end;
end;
initialization
if Get256ColorMode then
{ Стандартный цвет, очень похожий на цвет hint'а, но корректно отображающийся
в режиме 256 цветов }
MessageColor := TColor($F0FBFF) //Стандартный цвет clCream в 256-цветной палитре MS
else
MessageColor := TColor($CCFFFF); //Цвет помощника в MS Office 2000.
end.
|
{Даны 3 вещественных числа. Вывести на экран:
те из них, которые принадлежат интервалу 0,7 — 5,1}
var a, b, c: real;
begin
read(a, b, c);
if(a > 0.7)and(a < 5.1)then
begin
writeln(a);
end
else
begin
writeln(' Число a не входит в данный интервал.');
end;
if (b > 0.7) and (b < 5.1) then
begin
writeln(b);
end
else
begin
writeln(' Число b не входит в данный интервал.');
end;
if (c > 0.7) and (c < 5.1) then
begin
writeln(c);
end
else
begin
writeln(' Число c не входит в данный интервал.');
end;
end.
{проверочные данные: 0.0, 0.5, 5.5
(Число a не входит в данный интервал.
Число b не входит в данный интервал.
Число c не входит в данный интервал.)
проверочные данные:1.0, 2.0, 3.0, (1, 2, 3)
проверочные данные:-3.0, 1.5, 4.7
( Число a не входит в данный интервал.
1.5
4.7)} |
unit UVisitorList;
interface
var
visitorsLen: Integer = 0;
type
// Адрес посетителся библиотеки
TAddress = packed record
city: String[10];
street: String[20];
houseNumber: Integer;
case blockOfFlats: Boolean of
true: (flatNumber: Integer);
false: ();
end;
// ФИО
TName = packed record
firstName: String[20];
middleName: String[20];
lastName: String[20];
end;
// Запись о пользователе
TVisitor = packed record
ID: Integer;
name: TName;
address: TAddress;
phoneNumber: String[20];
end;
TVisitors = array of TVisitor;
// Конструктор TName
function toName(const firstName,
middleName,
lastName: String):TName;
// Конструктор TAddress
// Если flatNumber = -1, то выбирается вариант blockOfFlats = false
function toAddress(const city,
street: String;
const houseNumber,
flatNumber: Integer):TAddress;
// Конструктор TVisitor
function toVisitor(const ID: Integer;
const name: TName;
const address: TAddress;
const phoneNumber: String):TVisitor;
// Добавление посетителся библиотеки
procedure addVisitor(visitor: TVisitor);
// Поиск посетителей по имени
function findByName(visitorName: TName):TVisitors;
// Поиск посетителя по номеру
function findByID(ID: Integer):TVisitor;
// Удаление посетителя по номеру
procedure deleteByID(ID: Integer);
// Изменение посетителя по номеру
procedure changeByID(ID: Integer; newVisitor: TVisitor);
// Возвращает записи о всех посетителях библиотеки
function returnAllVisitors:TVisitors;
// Перевод TName в строку
function nameToStr(name: TName):String;
// Первод TAddress в строку
function addressToStr(address: TAddress):String;
// Проверяет, существует ли посетитель с кодом
function visitorExist(code: Integer):Boolean;
implementation
uses
SysUtils, UMain;
type
// Список посетителей библиотеки
TVisitorList = ^TVisitorElem;
TVisitorElem = packed record
visitor: TVisitor;
next: TVisitorList;
end;
var
visitors: TVisitorList;
// Перевод TName в строку
function nameToStr(name: TName):String;
begin
result := name.lastName + ' ' + name.firstName + ' ' + name.middleName;
end;
// Первод TAddress в строку
function addressToStr(address: TAddress):String;
begin
result := sCITY_SHORT + ' ' + address.city + ', ' + address.street +
' ' + sHOUSE_SHORT + ' ' + IntToStr(address.houseNumber);
if address.blockOfFlats then
result := result + ' ' + sFLAT_SHORT + ' ' + IntToStr(address.flatNumber);
end;
// Конструктор TName
function toName(const firstName,
middleName,
lastName: String):TName;
begin
result.firstName := firstName;
result.middleName := middleName;
result.lastName := lastName;
end;
// Конструктор TAddress
function toAddress(const city,
street: String;
const houseNumber,
flatNumber: Integer):TAddress;
begin
result.city := city;
result.street := street;
result.houseNumber := houseNumber;
if flatNumber = -1 then
result.blockOfFlats := false
else
begin
result.blockOfFlats := true;
result.flatNumber := flatNumber;
end;
end;
// Конструктор TVisitor
function toVisitor(const ID: Integer;
const name: TName;
const address: TAddress;
const phoneNumber: String):TVisitor;
begin
result.ID := ID;
result.name := name;
result.address := address;
result.phoneNumber := phoneNumber;
end;
// Добавление элемента в список
procedure insert(list: TVisitorList; visitor: TVisitor);
var
temp: TVisitorList;
begin
new(temp);
temp^.visitor := visitor;
temp^.next := list^.next;
list^.next := temp;
end;
// Сравнение двух записей TName
function lessThan(const nameA, nameB: TName):Boolean;
begin
result := true;
if nameA.lastName > nameB.lastName then
result := false
else
begin
if nameA.lastName = nameB.lastName then
begin
if nameA.firstName > nameB.firstName then
result := false
else
begin
if nameA.firstName = nameB.firstName then
begin
if nameA.middleName > nameB.middleName then
result := false;
end;
end;
end;
end;
end;
// Добавление посетителся библиотеки
procedure addVisitor(visitor: TVisitor);
var
list: TVisitorList;
begin
list := visitors;
while (list^.next <> nil) and lessThan(list^.next^.visitor.name, visitor.name) do
list := list^.next;
insert(list, visitor);
if visitor.ID > visitorsLen then
visitorsLen := visitor.ID;
end;
// Изменение посетителя по номеру
procedure changeByID(ID: Integer; newVisitor: TVisitor);
var
list: TVisitorList;
begin
list := visitors;
while (list^.next <> nil) and (list^.next^.visitor.ID <> ID) do
list := list^.next;
if list^.next <> nil then
list^.next^.visitor := newVisitor;
end;
// Равенство двух записей TName
function equal(recA, recB: TName):Boolean;
begin
if (recB.firstName = '') and (recB.middleName = '') then
begin
result := (recA.lastName = recB.lastName);
end
else
begin
result := (recA.firstName = recB.firstName) and
(recA.middleName = recB.middleName) and
(recA.lastName = recB.lastName);
end;
end;
// Поиск посетителей по имени
function findByName(visitorName: TName):TVisitors;
var
list: TVisitorList;
begin
list := visitors;
SetLength(result, 0);
while list^.next <> nil do
begin
list := list^.next;
if equal(list^.visitor.name, visitorName) then
begin
SetLength(result, length(result) + 1);
result[length(result) - 1] := list^.visitor;
end;
end;
end;
// Поиск посетителя по номеру
function findByID(ID: Integer):TVisitor;
var
list: TVisitorList;
begin
list := visitors;
result.ID := ID - 1;
while list^.next <> nil do
begin
list := list^.next;
if list^.visitor.ID = ID then
result := list^.visitor;
end;
end;
// Удаление элемента из списка
procedure delete(list: TVisitorList);
var
temp: TVisitorList;
begin
if list^.next <> nil then
begin
temp := list^.next;
list^.next := temp^.next;
dispose(temp);
end;
end;
// Удаление посетителя по номеру
procedure deleteByID(ID: Integer);
var
list: TVisitorList;
begin
list := visitors;
while list^.next <> nil do
begin
if list^.next^.visitor.ID = ID then
delete(list)
else
list := list^.next;
end;
end;
// Возвращает записи о всех посетителях библиотеки
function returnAllVisitors:TVisitors;
var
list: TVisitorList;
begin
list := visitors;
SetLength(result, 0);
while list^.next <> nil do
begin
list := list^.next;
SetLength(result, length(result) + 1);
result[length(result) - 1] := list^.visitor;
end;
end;
// Проверяет, существует ли посетитель с кодом
function visitorExist(code: Integer):Boolean;
var
list: TVisitorList;
begin
list := visitors;
result := false;
while list^.next <> nil do
begin
list := list^.next;
if list^.visitor.ID = code then
result := true;
end;
end;
// Очистка списка
procedure clear(list: TVisitorList);
begin
while list^.next <> nil do
delete(list);
end;
// Создание списка
procedure create(var list: TVisitorList);
begin
new(list);
list^.next := nil;
end;
// Удаление списка
procedure destroy(var list: TVisitorList);
begin
clear(list);
dispose(list);
list := nil;
end;
initialization
create(visitors);
visitorsLen := 0;
finalization
destroy(visitors);
end.
|
Unit TLogManager;
Interface
Uses Classes, Dialogs, SysUtils;
Type
TLog = Class
Procedure CreateLog(LogDirPath: String);
private
{ Private declarations }
DATLOT: String;
logFile: TextFile;
public
{ Public declarations }
logFileName: String;
published
Function LogIt(logStr: String): String;
Function WarnIt(logStr: String): String;
protected
End;
Implementation
Function TLog.LogIt(logStr: String): String;
Var
timestamp: String;
fh: integer;
toAbort, logExists: LongBool;
Begin
// ouverture du log
fh := 0;
toAbort :=false;
logExists :=false;
If FileExists(logFileName) = false Then
Begin
fh := filecreate(logFileName);
If fh < 0 Then
Begin
showmessage('impossible de créer le log ' + logfilename);
logFileName := '';
toabort := true;
End;
End
Else
logExists := true;
If toabort = true Then exit;
If fh > 0 Then FileClose(fh);
AssignFile(logFile, logFileName);
Append(logFile);
// écriture dans le log
timestamp := formatdatetime('YYYY/MM/DD hh:mm:ss', now);
If (logstr <> '') Then
writeln(logfile, timestamp + ' : ' + logstr)
Else
writeln(logfile, logstr);
flush(logFile);
//fermeture du log
If logFileName <> '' Then CloseFile(logFile);
result := logStr;
End;
Function TLog.WarnIt(logStr: String): string;
Begin
showmessage(logStr);
result:=LogIt(logstr);
End;
//
Procedure TLog.CreateLog(LogDirPath: String);
Begin
DATLOT := FormatDateTime('yyyy-mm-dd', Now);
//chdir(ExtractfilePath(Application.ExeName) + 'log');
logFileName := LogDirPath + 'log\log_' + DATLOT + '.txt';
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: JvDirFrm.PAS, released on 2002-07-04.
The Initial Developers of the Original Code are: Fedor Koshevnikov, Igor Pavluk and Serge Korolev
Copyright (c) 1997, 1998 Fedor Koshevnikov, Igor Pavluk and Serge Korolev
Copyright (c) 2001,2002 SGB Software
All Rights Reserved.
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.sourceforge.net
Known Issues:
-----------------------------------------------------------------------------}
// $Id: JvDirectoryListForm.pas,v 1.16 2004/08/24 13:33:08 asnepvangers Exp $
unit dlgDirectoryList;
interface
uses
SysUtils, Classes, Windows, Controls, Forms, StdCtrls;
type
TJvDirectoryListDialog = class(TForm)
AddBtn: TButton;
RemoveBtn: TButton;
ModifyBtn: TButton;
OKBtn: TButton;
CancelBtn: TButton;
DirectoryList: TListBox;
procedure AddBtnClick(Sender: TObject);
procedure ModifyBtnClick(Sender: TObject);
procedure RemoveBtnClick(Sender: TObject);
procedure DirectoryListClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DirectoryListDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure DirectoryListDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
private
procedure CheckButtons;
end;
function EditFolderList(Folders: TStrings; FormCaption : string = 'Directory List';
HelpCntxt : integer = 0): Boolean;
implementation
uses
JvJVCLUtils, JvJCLUtils, JvBrowseFolder, JvConsts, JVBoxProcs,
dmCommands;
{$R *.dfm}
function EditFolderList(Folders: TStrings; FormCaption : string = 'Directory List';
HelpCntxt : integer = 0): Boolean;
var
I: Integer;
begin
with TJvDirectoryListDialog.Create(Application) do
try
Caption := FormCaption;
HelpContext := HelpCntxt;
if Assigned(Folders) then
for I := 0 to Folders.Count - 1 do
DirectoryList.Items.Add(Folders[I]);
Result := ShowModal = mrOK;
if Result and Assigned(Folders) then
begin
Folders.Clear;
for I := 0 to DirectoryList.Items.Count - 1 do
Folders.Add(DirectoryList.Items[I]);
end;
finally
Free;
end;
end;
//=== { TJvDirectoryListDialog } =============================================
procedure TJvDirectoryListDialog.CheckButtons;
begin
ModifyBtn.Enabled := (DirectoryList.Items.Count > 0) and
(DirectoryList.ItemIndex >= 0);
RemoveBtn.Enabled := ModifyBtn.Enabled;
end;
procedure TJvDirectoryListDialog.AddBtnClick(Sender: TObject);
var
S: string;
begin
S := '';
if BrowseDirectory(S, 'Select Director to Add:', 0) then
begin
if DirectoryList.Items.IndexOf(S) < 0 then begin
DirectoryList.AddItem(S, nil);
DirectoryList.ItemIndex := DirectoryList.Count -1
end;
CheckButtons;
end;
end;
procedure TJvDirectoryListDialog.ModifyBtnClick(Sender: TObject);
var
I: Integer;
S: string;
begin
if DirectoryList.ItemIndex < 0 then
Exit;
I := DirectoryList.ItemIndex;
S := DirectoryList.Items[I];
if BrowseDirectory(S, 'Select Directory:', 0) then
DirectoryList.Items[I] := S;
end;
procedure TJvDirectoryListDialog.RemoveBtnClick(Sender: TObject);
var
I: Integer;
begin
if DirectoryList.ItemIndex < 0 then
Exit;
I := DirectoryList.ItemIndex;
DirectoryList.Items.Delete(I);
CheckButtons;
end;
procedure TJvDirectoryListDialog.DirectoryListClick(Sender: TObject);
begin
CheckButtons;
end;
procedure TJvDirectoryListDialog.FormShow(Sender: TObject);
begin
CheckButtons;
CommandsDataModule.Images.GetIcon(84, Icon)
end;
procedure TJvDirectoryListDialog.DirectoryListDragDrop(Sender, Source: TObject;
X, Y: Integer);
begin
BoxMoveFocusedItem(DirectoryList, DirectoryList.ItemAtPos(Point(X, Y), True));
CheckButtons;
end;
procedure TJvDirectoryListDialog.DirectoryListDragOver(Sender, Source: TObject;
X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
BoxDragOver(DirectoryList, Source, X, Y, State, Accept, DirectoryList.Sorted);
CheckButtons;
end;
end.
|
unit FileLoggerInterface;
interface
uses
SysUtils;
type
IFileLogger = interface['{31286155-9B2E-4BCD-A97F-8BEF261BA62B}']
function GetFileName :string;
property FileName :string read GetFileName;
end;
implementation
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 180705
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.cookie.CookieSpecRegistry;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.cookie.CookieSpecFactory,
org.apache.http.cookie.CookieSpec,
org.apache.http.params.HttpParams;
type
JCookieSpecRegistry = interface;
JCookieSpecRegistryClass = interface(JObjectClass)
['{734AA04A-7CDC-4A8C-9D80-938113DBBF6B}']
function getCookieSpec(&name : JString) : JCookieSpec; cdecl; overload; // (Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec; A: $21
function getCookieSpec(&name : JString; params : JHttpParams) : JCookieSpec; cdecl; overload;// (Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec; A: $21
function getSpecNames : JList; cdecl; // ()Ljava/util/List; A: $21
function init : JCookieSpecRegistry; cdecl; // ()V A: $1
procedure ®ister(&name : JString; factory : JCookieSpecFactory) ; cdecl; // (Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V A: $21
procedure setItems(map : JMap) ; cdecl; // (Ljava/util/Map;)V A: $21
procedure unregister(id : JString) ; cdecl; // (Ljava/lang/String;)V A: $21
end;
[JavaSignature('org/apache/http/cookie/CookieSpecRegistry')]
JCookieSpecRegistry = interface(JObject)
['{C5E58DC2-E84C-4335-9196-94B75F81DC60}']
end;
TJCookieSpecRegistry = class(TJavaGenericImport<JCookieSpecRegistryClass, JCookieSpecRegistry>)
end;
implementation
end.
|
unit uFTDIFunctions;
interface
uses
Windows, SysUtils, StdCtrls, ComCtrls, ExtCtrls, Dialogs ;
type
FT_Device_Info_Node = record
Flags : Dword;
DeviceType : Dword;
ID : DWord;
LocID : DWord;
SerialNumber : array [0..15] of Char;
Description : array [0..63] of Char;
DeviceHandle : DWord;
end;
PFTDeviceInfo = ^FT_Device_Info_Node;
PicoBlazeInfo = record {in use}
PB_FTNodeIndex : integer;
PB_TabIndex : integer;
PB_Address : byte;
PB_ID : array [0..3] of byte;
end;
PPicoBlazeInfo = ^PicoBlazeInfo; {in use}
PicoReplyType = (PB_Failed, PB_NoReply, PB_Illegal, PB_Notification, PB_Data, PB_OK);
var
FTDevInfo : array [0..15] of FT_Device_Info_Node;
FTDevFound, DevNumber, MyDevNumber : integer;
FTDevConnected : array [0..15] of boolean;
PB_LogEnabled,PB_FullLogView, PB_ErrorShow, PB_ThroughCOM : boolean;
{FT_NodeTree : TTreeView;}
{PBFirstReply: TLabel;}
Lister : TMemo;
FlashTimer : TTimer;
FlashProgr : TProgressBar;
FlashSave : TSaveDialog;
FTBaudRate : integer = 3000000;
function ByteArrToString (var InData : array of byte; DatLength, StartIndex : integer) : string;
function TextToBytes (InString : string; var Data : array of byte; var DataQty : cardinal) : boolean;//получаем строку и переводим ее в байты учитываем ,.
procedure CodeDataArray (ChannAddr : byte; var DataIn, DataOut : array of byte; var InLength,OutLength : cardinal); // big procedure that
//code data to apropriate format for sending to PB. rturns data out
procedure FTDSetInit; {in use; zero out FTDevConnected and FTDevFound}
procedure GetFTDIDeviceInfo ; {in use; loads data to array FTDevinfo; FTDevFound:=q [0;15], -1 FT error, -2 q>16}
function ConnectToFTDevice (devNum : integer) : boolean; {in use; FT connection deep checking, FTDevConncentd(devNum):=true}
function DisconnectFTDevice (devNum : integer) : boolean; {in use;}
procedure DisconnectAllFTDev; {in use; desconnects all FT devices from dev(0) to FTDevFound-1}
function TestIfProperFTDevice (devNum : integer) : boolean; //почему-то была закоментирована, проверяет .description(devNum)?= FT2
function TestIfPicoBlazePresent (FTNum,PBNum : integer; var PBInfo : array of byte) : boolean; //то же закоментирована, отправляет команду getDevId и отвечает тру если
//ответ пришел и длина = 4 байта, и ложь если ответ не пришел или длина не равна 4 байта
function SearchForAllPicoblaze(var st: string ) : boolean; {in use; gets a lable as a link and returns true if smth
and falce if smth else}
function GetIndexBySerial (var SerialNumber : array of Char) : integer;
function PB_FTDataExcange (DevNum : integer;var DataTo,DataFrom : array of byte; QtyTo : cardinal; var QtyFrom : cardinal) : boolean;
function PB_SendCommandToDevice (DevNum : integer; ChannAddr : byte; var OutputArray, InputArray : array of byte;
var QtyTo,QtyFrom : cardinal; var StrFrom : string) : PicoReplyType; // sends command and returns reply codes and reply record
procedure StartFlashProgram (Filename : string; DevNum : integer; PBAddr : byte);
procedure StartFlashVerify (Filename : string; DevNum : integer; PBAddr : byte);
procedure StartFlashRead (DevNum : integer; PBAddr : byte);
function AddFlashPrepare (Filename : string;DevNum : integer; PBAddr : byte; StartAddr : cardinal) : boolean;
//function DefineFLASHType (DevNum : integer; Addr : byte; var FlashLen : cardinal; var FType : FLASH_Type) : boolean;
//function FlashErase (DevNum : integer; Addr : byte; FType : FLASH_Type; StartAddr,Size : cardinal) : boolean;
//function GetFlashState (DevNum : integer; Addr : byte; var state : byte): boolean;
//function ReadFPGAData (Filename : string; var DataArray : array of byte; var DataQty : cardinal) : boolean;
//procedure ConvertToUfpFile (Filename : string; var DataArray : array of byte;DataQty : integer);
function GetFlashData (var DataArray : array of byte; var DataPointer,DataQty : cardinal) : boolean;
//function SendFlashPage : boolean;
procedure FlashTimerDo;
function FT_PARALLEL_PORT_READ (QtyFrom: cardinal; FT_Parallel_Handle : DWORD;var DataIn: array of byte ):boolean;
function FT_PARALLEL_PORT_CLEAR_BUFFER (FT_Parallel_Handle : DWORD;var qtt: integer):boolean;
procedure CloseLogFile;
implementation
{uses COMFunctions;}
Type FT_Result = Integer;
TFlashState = (NOP,Erasing,Writing,Verifying,Reading,ErasingAdd,WritingAdd,VerifyingAdd,PreReadingAdd,ReadingAdd);
FLASH_Type = (AT25F1024A,AT25FS040);
EEByte = record
adress : word;
data : byte;
end;
const
FT_OK = 0;
FT_DLL_Name = 'FTD2XX.DLL';
FT_In_Buffer_Index = $FFFF;
FT_Out_Buffer_Index = $FFFF;
//standard & debug Picoblase commands
SetMemWIncComm = $00; //writes data to IO with address increment (addr+data)
SetMemConstComm = $01; //writes all data to a fixed address (addr+data)
Set16RegComm = $02; //sets a 16-bit register, MSB @ addr+1, then LSB @ addr (addr+data)
GetMemWIncComm = $03; //reads data from IO with address increment (addr+qty)
GetMemConstComm = $04; //reads data from a fixed address (addr+qty)
DoSPIExchComm = $05; //transmits all data to SPI & sends reply
WriteFlashComm = $06; //transmits start address in SPI flash, must be sent before WriteFlashData command
ReadFlashComm = $07; //transmits start address and byte qty (up to 256), recieves data from SPI flash
WriteFlashData = $08; //transmits proper quantity of flash data (up to 1 page)
GetDeviceID = $0E; //returnes: PCB index, Hardvare version, Software version, Serial number
DoEchoComm = $0F; //returnes all sent data
//service digits
StartSymbol = $FD;
StopSymbol = $FE;
ShiftSymbol = $FF;
//Configuration flash commands
WREN = $06; //Set Write Enable Latch
RDSR = $05; //Read Status Register
//RDDAT = $03; //Read Data from Memory Array
PROG = $02; //Program Data into Memory Array
ERASE =$62; //Erase All Sectors in Memory Array
AltERASE = $60;
BlockErase = $52;
SectorErase = $20;
RDID = $15; //Read Manufacturer and Product ID
AltRDID = $9F;
FlashPageSize = 256;
FTDITimeout = 50;
MaxAddFlashCap = $4000; //16k
PB_OKReplyCode = $DA;
PB_LengthMisErr = $E0; //data length mismatch
PB_ChecksumMisErr = $E1; //cheksm mismatch
PB_CommAbsentErr = $E2; //command with code recieved is absent
PB_OutOfMemErr = $E3; //adress goes over $FF thrue writing or reading
PB_TooLittleErr = $E4; //too little data sent
PB_DataFormatErr = $E5; //improper data for specified command
PB_ParamAbsentErr = $E6; //requested parameter is undefined
PB_MethForbidErr = $E7; //method of parameter is not available
var FT_In_Buffer,FT_In_Buffer1 : Array[0..FT_In_Buffer_Index] of Byte;
FT_Out_Buffer,FT_Out_Buffer1 : Array[0..FT_Out_Buffer_Index] of Byte;
RootNode : TTreeNode;
TimeoutLimit : int64;
FlashState : TFlashState;
CurrFlashSize,FlDataQty,CurrFlashIndex,CurrSectorSize,StartFlashAddr,StopFlashAddr,CurrFlashAddr,EraseSize : cardinal;
//StartFlashAddr,StopFlashAddr,CurrFlashAddr - in Flash address space, CurrFlashIndex - data array index
ProgDevNum,VeryErrCounter,PageCounter,MaxPages : integer;
ProgPBAddr,CurrEraseComm : byte;
CurrFlashType : FLASH_Type;
DatArray : array of byte;
LogFile : TextFile;
MaxAddAddr,MinAddAddr,MinSector,MaxSector,CurrSector : word;
BaseAddAddr,AddDataQty,CurrBlockSize : cardinal;
FlashProgData : array [0..MaxAddFlashCap-1] of EEByte;
AddPgToErase, AddPgToWrite, IsWritingAdd, CurrPageDone : boolean;
ProgressData : real;
function FT_CreateDeviceInfoList(NumDevs:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_CreateDeviceInfoList';
function FT_GetDeviceInfoList(pFT_Device_Info_List:Pointer; NumDevs:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetDeviceInfoList';
function FT_Open(Index:Integer; ftHandle:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Open';
function FT_Close(ftHandle:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_Close';
function FT_Read(ftHandle:Dword; FTInBuf:Pointer; BufferSize:LongInt; ResultPtr:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Read';
function FT_GetQueueStatus(ftHandle:Dword; RxBytes:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_GetQueueStatus';
function FT_Write(ftHandle:Dword; FTOutBuf:Pointer; BufferSize:LongInt; ResultPtr:Pointer):FT_Result; stdcall; External FT_DLL_Name name 'FT_Write';
function FT_SetChars(ftHandle:Dword; EventChar,EventCharEnabled,ErrorChar,ErrorCharEnabled:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetChars';
function FT_SetBaudRate(ftHandle:Dword; BaudRate:DWord):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetBaudRate';
function FT_Purge(ftHandle:Dword; Mask:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_Purge';
function FT_SetDataCharacteristics(ftHandle:Dword; WordLength,StopBits,Parity:Byte):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetDataCharacteristics';
function FT_SetTimeouts(ftHandle:Dword; ReadTimeout,WriteTimeout:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetTimeouts';
function FT_SetUSBParameters(ftHandle:Dword; InSize,OutSize:Dword):FT_Result; stdcall; External FT_DLL_Name name 'FT_SetUSBParameters';
procedure CodeDataArray (ChannAddr : byte; var DataIn, DataOut : array of byte; var InLength,OutLength : cardinal);
var I,MaxOut : integer;
bb : byte;
begin
OutLength:=2;
MaxOut:=Length(DataOut);
bb:=ChannAddr;
DataOut[0]:=StartSymbol;
DataOut[1]:=ChannAddr;
for I := 0 to InLength - 1 do
begin
if DataIn[I]<StartSymbol then
begin
DataOut[OutLength]:=DataIn[I];
OutLength:=OutLength+1;
if OutLength>=MaxOut then
exit;
end
else
begin
DataOut[OutLength]:=ShiftSymbol;
DataOut[OutLength+1]:=DataIn[I]-StartSymbol;
OutLength:=OutLength+2;
end;
bb:=bb xor DataIn[I];
end;
if bb<StartSymbol then
begin
DataOut[OutLength]:=bb;
OutLength:=OutLength+1;
end
else
begin
DataOut[OutLength]:=ShiftSymbol;
DataOut[OutLength+1]:=bb-StartSymbol;
OutLength:=OutLength+2;
end;
DataOut[OutLength]:=StopSymbol;
OutLength:=OutLength+1;
end;
function DecodeDataArray (var DataIn,DataOut : array of byte; var InLength,OutLength : cardinal) : boolean;
var I,a : integer;
bb : byte;
MaxLen : cardinal;
begin
MaxLen:=Length(DataOut);
OutLength:=0;
I:=1;
bb:=0;
result:=false;
if (DataIn[0]<>StartSymbol) or (DataIn[InLength-1]<>StopSymbol) then
begin
if InLength>MaxLen then
InLength:=MaxLen;
OutLength:=InLength;
for a := 0 to InLength - 1 do
DataOut[a]:=DataIn[a];
exit;
end;
while I<InLength-1 do
begin
if OutLength>=MaxLen then
exit;
if DataIn[I]=ShiftSymbol then
begin
DataOut[OutLength]:=DataIn[I+1]+StartSymbol;
I:=I+1;
end
else
DataOut[OutLength]:=DataIn[I];
I:=I+1;
bb:=bb xor DataOut[OutLength];
OutLength:=OutLength+1;
end;
result:=(bb=0);
OutLength:=OutLength-1;
end;
function ByteArrToString (var InData : array of byte; DatLength, StartIndex : integer) : string;
var I : integer;
begin
result:='';
for I := StartIndex to DatLength - 1 do
result:=result+IntToHex(InData[I],2)+'.';
end;
procedure SaveDataToLog (str : string; QtyTo,QtyFrom : integer);
begin
//WriteLN(LogFile,str);
//WriteLN(LogFile,ByteArrToString(FT_Out_Buffer,QtyTo,0));
//WriteLN(LogFile,ByteArrToString(FT_In_Buffer,QtyFrom,0));
//Flush(LogFile);
end;
procedure OpenLogFile;
begin
//AssignFile(LogFile,'.\Logfile.txt');
// Rewrite(LogFile);
end;
procedure CloseLogFile;
begin
try
FlashState:=NOP;
//CloseFile(LogFile);
except
end;
end;
function TextToBytes (InString : string; var Data : array of byte; var DataQty : cardinal) : boolean;
var q,a,z : integer;
str : string;
begin
result:=false;
z:=0;
a:=0;
str:='$';
for q:=1 to Length(InString) do
if (InString[q]<>'.') and (InString[q]<>',') then
begin
str:=str+InString[q];
z:=z+1;
if z>1 then
begin
try
Data[a]:=StrToInt(str); //поддерживает 0x, x, $ для шестнадцати разрядных команд
except
//InString.SetFocus;
exit;
end;
z:=0;
str:='$';
a:=a+1;
end;
end;
result:=true;
DataQty:=a;
end;
function DecodeNotification (notif : byte) : string;
begin
case notif of
PB_OKReplyCode: result:='OK!';
PB_LengthMisErr: result:='Length mismatch';
PB_ChecksumMisErr: result:='Checksum mismatch';
PB_CommAbsentErr: result:='Command not recognized';
PB_OutOfMemErr: result:='Out of memory';
PB_TooLittleErr: result:='Too little data';
PB_DataFormatErr: result:='Improper data';
PB_ParamAbsentErr: result:='Parameter not found';
PB_MethForbidErr: result:='Method is not available';
else
result:='Unrecognized: '+IntToHex(notif,2);
end;
end;
procedure FTDSetInit;
var I : integer;
begin
FlashState:=NOP;
for I := 0 to 15 do
FTDevConnected[I]:=false;
FTDevFound:=0;
end;
procedure GetFTDIDeviceInfo ;
var q : cardinal;
begin
FTDevFound:=-1;
if FT_CreateDeviceInfoList(@q)<>FT_OK then
exit;
if q>16 then
begin
FTDevFound:=-2;
exit;
end;
if FT_GetDeviceInfoList(@FTDevInfo,@q)<>FT_OK then
exit;
FTDevFound:=q;
end;
function ConnectToFTDevice (devNum : integer) : boolean;
begin
result:=false;
if FTDevConnected[devNum] then
begin
result:=true; //device is already opened
exit;
end;
if FT_Open(devNum,@FTDevInfo[devNum].DeviceHandle)<>FT_OK then
exit;
FTDevConnected[devNum]:=true;
// if FT_SetDataCharacteristics(FTDevInfo[devNum].DeviceHandle,8,1,0)<>FT_OK then
// exit;
// if FT_SetBaudRate(FTDevInfo[devNum].DeviceHandle,FTBaudRate)<>FT_OK then
// exit;
if FT_SetChars(FTDevInfo[devNum].DeviceHandle,$FE,1,0,0)<>FT_OK then
exit;
if FT_Purge(FTDevInfo[devNum].DeviceHandle,3)<>FT_OK then
exit;
result:=true;
end;
function DisconnectFTDevice (devNum : integer) : boolean;
begin
result:=false;
if FTDevConnected[devNum] then
result:=FT_Close(FTDevInfo[devNum].DeviceHandle)=FT_OK;
FTDevConnected[devNum]:=false;
end;
procedure DisconnectAllFTDev;
var I : integer;
begin
for I := 0 to FTDevFound - 1 do
if FTDevConnected[I] then
DisconnectFTDevice(I);
end;
function TestIfProperFTDevice (devNum : integer) : boolean;
var str : string;
I : integer;
begin
result:=false;
str:='';
for I := 0 to 2 do
str:=str+FTDevInfo[devNum].Description[I];
if (str='FT2') then
begin
result:=true;
exit;
end;
end;
function TestIfPicoBlazePresent (FTNum,PBNum : integer; var PBInfo : array of byte) : boolean;
var DataOut,DataIn : array [0..7] of byte;
qtyTo,qtyFrom : cardinal;
str : string;
I : integer;
begin
DataOut[0]:=GetDeviceID;
qtyTo:=1;
result:=false;
if (PB_SendCommandToDevice(FTNum,PBNum,DataOut,DataIn,qtyTo,qtyFrom,str)=PB_Data) and (qtyFrom=4) then
begin
result:=true;
for I := 0 to 3 do
PBInfo[I]:=DataIn[I];
end;
end;
function GetIndexBySerial (var SerialNumber : array of Char) : integer;
var I,q : integer;
bb : boolean;
begin
result:=-1;
for I := 0 to FTDevFound - 1 do
begin
bb:=true;
for q := 0 to 15 do
if SerialNumber[q]<>FTDevInfo[I].SerialNumber[q] then
begin
bb:=false;
break;
end;
if bb then
begin
result:=I;
exit;
end;
end;
end;
function SearchForAllPicoblaze(var st: string) : boolean;
var q,I,a : integer;
SomeNode : TTreeNode; {Это такой список с плюсиками}
P : PPicoBlazeInfo;
PicoID : array [0..3] of byte;
begin
result:=false;
{FT_NodeTree.Items.Clear; parts of priveous implimentation}
QueryPerformanceFrequency(TimeoutLimit); {WINDOWS standart function; TimeoutLimit: int64 это системный высокочастотный таймер
использовался в прошлых программах, в этой то же в функции pb_ft_data exchange}
TimeoutLimit:=TimeoutLimit div FTDITimeout; {еще какая то фигня с таймаутами}
DisconnectAllFTDev; {дисконектит от фт девайсы от 0 до FTDevFound-1}
GetFTDIDeviceInfo; {фактически конектимся заново}
if FTDevFound<=0 then
exit;
{RootNode:=FT_NodeTree.Items.Add(nil,'FTDI devices found');}
for q := 0 to FTDevFound - 1 do
begin
if TestIfProperFTDevice(q) then
begin
{SomeNode:=FT_NodeTree.Items.AddChildObject(RootNode,FTDevInfo[q].Description+':'+FTDevInfo[q].SerialNumber+' at '+
IntToHex(FTDevInfo[q].LocID,4),@FTDevInfo[q]); }
if ConnectToFTDevice(q) then
for I := 1 to 15 do
if TestIfPicoBlazePresent(q,I,PicoID) then
begin
{if q>0
then if(FTDevInfo[q].Description=' LAPlatform B') and
(FTDevInfo[q-1].Description=' LAPlatform A') then
ConnectToFTDevice(q-1); }
New(P);
result:=true;
P^.PB_FTNodeIndex:=q;
P^.PB_TabIndex:=-1;
P^.PB_Address:=I;
for a := 0 to 3 do
P^.PB_ID[a]:=PicoID[a];
st:='';
st:=st+ByteArrToString(P^.PB_ID,4,0);
MyDevNumber:=q;
{FT_NodeTree.Items.AddChildObject(SomeNode,ByteArrToString(PicoID,4,0),P); }
end;
DevNumber:=q;
DisconnectFTDevice(q);
end;
end;
end;
function PB_FTDataExcange (DevNum : integer;var DataTo,DataFrom : array of byte; QtyTo : cardinal; var QtyFrom : cardinal) : boolean;
Var I : Integer;
qty,qty1 : cardinal;
Tim1,Tim2 : int64;
begin
QtyFrom:=0;
result:=false;
if DevNum<0 then
exit;
if not FTDevConnected[devNum] then
exit;
if FT_Write(FTDevInfo[DevNum].DeviceHandle,@DataTo,QtyTo,@qty)<>FT_OK then
exit;
QueryPerformanceCounter(Tim1);
repeat
FT_GetQueueStatus(FTDevInfo[DevNum].DeviceHandle,@qty);
if qty>0 then
begin
FT_Read(FTDevInfo[DevNum].DeviceHandle,@FT_In_Buffer1,qty,@qty1);
for I := 0 to qty1 - 1 do
DataFrom[QtyFrom+I]:=FT_In_Buffer1[I];
QtyFrom:=QtyFrom+qty1;
if DataFrom[QtyFrom-1]=StopSymbol then
break;
QueryPerformanceCounter(Tim1);
end;
QueryPerformanceCounter(Tim2);
if (Tim2-Tim1)>TimeoutLimit then
break;
until false;
result:=true;
end;
function PB_SendCommandToDevice (DevNum : integer; ChannAddr : byte; var OutputArray, InputArray : array of byte;
var QtyTo,QtyFrom : cardinal; var StrFrom : string) : PicoReplyType;
var q: integer;
a,z : cardinal;
StrTo : string;
rr : boolean;
begin
CodeDataArray(ChannAddr,OutputArray,FT_Out_Buffer1,QtyTo,a);
z:=QtyFrom;
if PB_FullLogView then
StrTo:=ByteArrToString(FT_Out_Buffer1,a,0)
else
StrTo:=IntToHex(ChannAddr,2)+': '+ByteArrToString(OutputArray,QtyTo,0);
{if PB_ThroughCOM then
rr:=PB_COMExcange(DevNum,FT_Out_Buffer1,FT_In_Buffer,a,z)
else}
rr:=PB_FTDataExcange(DevNum,FT_Out_Buffer1,FT_In_Buffer,a,z);
if rr then
begin
QtyFrom:=z;
if z=0 then
begin
result:=PB_NoReply;
StrFrom:='No reply';
// if PB_ErrorShow and (not PB_LogEnabled) then
// begin
// Lister.Text:=Lister.Text+'To->'+StrTo+chr($0D)+Chr($0A);
// Lister.Text:=Lister.Text+StrFrom+chr($0D)+Chr($0A);
// end;
end
else
begin
if z<4 then
begin
if (z=3)and (FT_In_Buffer[0]= (FT_In_Buffer[1] xor $FF)) then
begin
result:=PB_Notification;
StrFrom:=DecodeNotification(FT_In_Buffer[0]);
if FT_In_Buffer[0]=PB_OKReplyCode then
result:=PB_OK;
end
else
begin
result:=PB_Illegal;
for q := 0 to z - 1 do
InputArray[q]:=FT_In_Buffer[q];
StrFrom:='Illegal '+ByteArrToString(FT_In_Buffer,QtyFrom,0);
// if PB_ErrorShow and (not PB_LogEnabled) then
// begin
// Lister.Text:=Lister.Text+'To->'+StrTo+chr($0D)+Chr($0A);
// Lister.Text:=Lister.Text+StrFrom+chr($0D)+Chr($0A);
// end;
end;
end
else
begin
if not DecodeDataArray(FT_In_Buffer,InputArray,z,QtyFrom) then
begin
result:=PB_Illegal;
QtyFrom:=z;
StrFrom:='Illegal '+ByteArrToString(FT_In_Buffer,QtyFrom,0);
// if PB_ErrorShow and (not PB_LogEnabled) then
// begin
// Lister.Text:=Lister.Text+'To->'+StrTo+chr($0D)+Chr($0A);
// Lister.Text:=Lister.Text+StrFrom+chr($0D)+Chr($0A);
// end;
end
else
begin
result:=PB_Data;
if PB_FullLogView then
StrFrom:=ByteArrToString(FT_In_Buffer,z,0)
else
StrFrom:=IntToHex(ChannAddr,2)+': '+ByteArrToString(InputArray,QtyFrom,0)
end;
end;
end;
end
else
begin
result:=PB_Failed;
StrFrom:='Failed';
// if PB_ErrorShow and (not PB_LogEnabled) then
// begin
// Lister.Text:=Lister.Text+'To->'+StrTo+chr($0D)+Chr($0A);
// Lister.Text:=Lister.Text+StrFrom+chr($0D)+Chr($0A);
// end;
end;
if PB_LogEnabled then
begin
Lister.Text:=Lister.Text+'To->'+StrTo+chr($0D)+Chr($0A);
Lister.Text:=Lister.Text+'From<-'+StrFrom+chr($0D)+Chr($0A);
end;
end;
function DefineFLASHType (DevNum : integer; Addr : byte) : boolean;
var QtyTo,QtyFrom : cardinal;
str,str1 : string;
begin
result:=false;
str:='FLASH is undefined';
CurrFlashSize:=0;
FT_Out_Buffer[0]:=DoSPIExchComm;
FT_Out_Buffer[1]:=RDID;
FT_Out_Buffer[2]:=0;
FT_Out_Buffer[3]:=0;
QtyTo:=4;
if PB_SendCommandToDevice(DevNum,Addr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str1)=PB_Data then
begin
if (QtyFrom=3) and (FT_In_Buffer[1]=$1F) and (FT_In_Buffer[2]=$60) then
begin
result:=true;
CurrFlashType:=AT25F1024A;
CurrFlashSize:=$20000;
CurrSectorSize:=$8000;
CurrBlockSize:=$8000;
str:='AT25F1024A is found';
end
else
begin
FT_Out_Buffer[1]:=AltRDID;
FT_Out_Buffer[4]:=0;
QtyTo:=5;
if PB_SendCommandToDevice(DevNum,Addr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str1)=PB_Data then
begin
if (QtyFrom=4) and (FT_In_Buffer[1]=$1F) and (FT_In_Buffer[2]=$66) and (FT_In_Buffer[3]=$04) then
begin
result:=true;
CurrFlashType:=AT25FS040;
CurrFlashSize:=$80000;
CurrSectorSize:=$10000;
CurrBlockSize:=$1000;
str:='AT25FS040 is found';
end;
end;
end;
end;
str:=IntToStr(Addr)+'@'+IntToStr(DevNum)+': '+str;
Lister.Text:=Lister.Text+str+chr($0D)+Chr($0A);
end;
function FlashSectorErase : boolean; //Стирает блок/сектор (в зависимости от кода команды CurrEraseComm)
var QtyTo,QtyFrom : cardinal; //содержащий CurrFlashAddr, который после операции увеличивается на EraseSize
str1 : string;
begin
result:=false;
FT_Out_Buffer[0]:=DoSPIExchComm;
FT_Out_Buffer[1]:=WREN;
QtyTo:=2;
if PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str1)=PB_Data then
begin
FT_Out_Buffer[0]:=DoSPIExchComm;
FT_Out_Buffer[1]:=CurrEraseComm;
FT_Out_Buffer[2]:=CurrFlashAddr div $10000;
FT_Out_Buffer[3]:=(CurrFlashAddr mod $10000) div $100;
FT_Out_Buffer[4]:=(CurrFlashAddr mod $100);
QtyTo:=5;
QtyFrom:=11;
if PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str1)=PB_Data then
result:=true;
end;
CurrFlashAddr:=CurrFlashAddr+EraseSize;
if not result then
FlashState:=NOP;
end;
procedure FlashErase (StartAddr,Size : cardinal);
var q,a : cardinal;
str,str1 : string;
begin
FlashState:=Erasing;
CurrFlashAddr:=StartAddr; //for erasing
q:=StartAddr div CurrSectorSize;
a:=(StartAddr+Size) div CurrSectorSize;
MaxPages:=a-q+1;
PageCounter:=0;
CurrEraseComm:=BlockErase;
EraseSize:=CurrSectorSize;
FlashTimer.Interval:=300;
FlashTimer.Enabled:=true;
end;
function GetFlashState (var state : byte): boolean;
var DataTo,DataFrom : array [0..7] of byte;
QtyTo,QtyFrom : cardinal;
str1 : string;
begin
result:=false;
DataTo[0]:=DoSPIExchComm;
DataTo[1]:=RDSR;
DataTo[2]:=0;
QtyTo:=3;
QtyFrom:=10;
if PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,DataTo,DataFrom,QtyTo,QtyFrom,str1)=PB_Data then
if QtyFrom=2 then
begin
state:=DataFrom[1];
result:=true;
end;
if not result then
Lister.Text:=Lister.Text+IntToStr(ProgPBAddr)+'@'+IntToStr(ProgDevNum)+': Status request failed'+chr($0D)+Chr($0A);
end;
procedure SwapBits (var bb : byte);
var q : integer;
a,z : byte;
begin
z:=0;
for q:=0 to 7 do
begin
a:=bb mod 2;
z:=z*2+a;
bb:=bb div 2;
end;
bb:=z;
end;
function ReadFPGAData (Filename : string; var DataArray : array of byte; var DataQty : cardinal) : boolean;
var FL : TextFile;
FileExt,str,str1 : string;
Ch1,Ch2 : char;
q,len : integer;
a : byte;
begin
result:=false;
try
AssignFile(FL,Filename);
except
Lister.Text:=Lister.Text+'File '+Filename+' not found!'+chr($0D)+Chr($0A);
exit;
end;
Reset(FL);
FileExt:=ExtractFileExt(Filename);
if (FileExt<>'.ufp') then
begin
Lister.Text:=Lister.Text+FileExt+' is not a valid exttnsion!'+chr($0D)+Chr($0A);
CloseFile(FL);
exit;
end;
DataQty:=0;
len:=Length(DataArray);
while not EOF(FL) do
begin
ReadLn(FL,str);
for q:=0 to (Length(str) div 2)-1 do
begin
str1:='$'+str[2*q+1]+str[2*q+2];
try
a:=StrToInt(str1);
except
Lister.Text:=Lister.Text+'Illegal hex coding '+str1+' in byte $'+IntToHex(DataQty,5)+chr($0D)+Chr($0A);
CloseFile(FL);
exit;
end;
SwapBits(a);
DataArray[DataQty]:=a;
DataQty:=DataQty+1;
if DataQty>len then
begin
Lister.Text:=Lister.Text+'File is too long!';
CloseFile(FL);
exit;
end;
end;
end;
CloseFile(FL);
if (DataQty mod 4)<>0 then
Lister.Text:=Lister.Text+'Byte quantity mus be a multiple of 4!'+chr($0D)+Chr($0A)
else
result:=true;
end;
procedure ConvertToUfpFile (Filename : string; var DataArray : array of byte;DataQty : integer);
var FL : TextFile;
str : string;
q,a,z,I : integer;
bb : byte;
begin
AssignFile(FL,Filename);
Rewrite(FL);
z:=0;
for I := 0 to (DataQty div 16)-1 do
begin
str:='';
a:=DataQty-z;
if a<=0 then
break;
if a>16 then
a:=16;
for q := 0 to a-1 do
begin
bb:=DataArray[z];
SwapBits(bb);
str:=str+IntToHex(bb,2);
z:=z+1;
end;
WriteLn(FL,str);
end;
CloseFile(FL);
end;
function GenStringDecode (InStr : string; var MemRec : EEByte) : boolean;
var str : string;
q : integer;
sw : boolean;
begin
str:='';
sw:=false;
result:=false;
for q:=1 to Length(InStr) do
if InStr[q]=':' then
begin
sw:=true;
try
MemRec.Adress:=StrToInt('$'+str);
except
exit;
end;
str:='';
end
else
str:=str+InStr[q];
if not sw then
exit;
try
MemRec.Data:=StrToInt('$'+str);
except
exit;
end;
result:=true;
end;
function ReadGenFile (Filename : string; var DataQty : cardinal) : boolean;
var fl : TextFile;
q : integer;
str : string;
begin
result:=false;
AssignFile(fl,Filename);
Reset(fl);
q:=0;
MaxAddAddr:=0;
MinAddAddr:=MaxAddFlashCap;
While not EOF(fl) do
begin
ReadLn(fl,str);
if not GenStringDecode(str,FlashProgData[q]) then
begin
Lister.Text:=Lister.Text+'Wrong file format! Error in string '+IntToStr(q)+' = '+str;
CloseFile(fl);
exit;
end;
if FlashProgData[q].Adress>=MaxAddFlashCap then
begin
Lister.Text:=Lister.Text+'Too large FLASH adress = $'+IntToHex(FlashProgData[q].Adress,4)+'!';
CloseFile(fl);
exit;
end;
q:=q+1;
if FlashProgData[q].Adress>MaxAddAddr then
MaxAddAddr:=FlashProgData[q].Adress;
if FlashProgData[q].Adress<MinAddAddr then
MinAddAddr:=FlashProgData[q].Adress;
if q>MaxAddFlashCap then
begin
Lister.Text:=Lister.Text+'Too long data file!';
CloseFile(fl);
exit;
end;
end; //all data are loaded from file
DataQty:=q;
CloseFile(fl);
result:=true;
end;
procedure StartAddSectorProc;
begin
CurrFlashAddr:=CurrSector*CurrBlockSize;
CurrFlashIndex:=0;
StopFlashAddr:=(CurrSector+1)*CurrBlockSize;
end;
function AddFlashPrepare (Filename : string;DevNum : integer; PBAddr : byte; StartAddr : cardinal) : boolean;
begin
result:=false;
if FlashState<>NOP then
begin
Lister.Text:=Lister.Text+'Some FLASH operation is already in progress!';
exit;
end;
if not DefineFLASHType(DevNum,PBAddr) then
exit;
if ReadGenFile(Filename,AddDataQty) then
Lister.Text:=Lister.Text+'Read data from '+Filename+chr($0D)+Chr($0A)
else
exit;
BaseAddAddr:=StartAddr;
if (BaseAddAddr+MaxAddAddr)>=CurrFlashSize then
begin
Lister.Text:=Lister.Text+'Addres is outside the FLASH!';
exit;
end;
MinSector:=(BaseAddAddr+MinAddAddr) div CurrBlockSize;
MaxSector:=(BaseAddAddr+MaxAddAddr) div CurrBlockSize;
CurrSector:=MinSector;
SetLength(DatArray,CurrBlockSize);
ProgDevNum:=DevNum;
ProgPBAddr:=PBAddr;
if CurrFlashType=AT25F1024A then
CurrEraseComm:=BlockErase
else
CurrEraseComm:=SectorErase;
EraseSize:=CurrBlockSize;
AddPgToErase:=false;
AddPgToWrite:=false;
StartAddSectorProc;
FlashTimer.Interval:=20;
FlashTimer.Enabled:=true;
IsWritingAdd:=false;
FlashState:=PreReadingAdd;
result:=true;
end;
function GetFlashData (var DataArray : array of byte; var DataPointer,DataQty : cardinal) : boolean;
var DataLength,RepLen,q : cardinal;
str : string; //reads DataQty bytes from address DataPointer into DataArray
ExRes : PicoReplyType;
I : integer;
begin
result:=false;
if DataQty=0 then
exit;
FT_Out_Buffer[0]:=ReadFlashComm;
FT_Out_Buffer[1]:=DataPointer div $10000;
FT_Out_Buffer[2]:=(DataPointer mod $10000) div $100;
FT_Out_Buffer[3]:=DataPointer mod $100;
q:=DataQty mod 256;
FT_Out_Buffer[4]:=q;
DataLength:=5;
ExRes:=PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,FT_Out_Buffer,DataArray,DataLength,RepLen,str);
if q=0 then
q:=256;
result:=(ExRes=PB_Data) and (RepLen = q);
if result then
DataQty:=q
else
Lister.Text:=Lister.Text+'Flash reading failed! '+IntToStr(RepLen)+' '+IntToStr(Ord(ExRes))+chr($0D)+Chr($0A);
end;
procedure TestAddFlashData;
var I : integer;
bFlash, bData : byte;
CAddr,MinAddr,MaxAddr : cardinal;
begin
MinAddr:=CurrSector*CurrBlockSize; //absolute addresses
MaxAddr:=MinAddr+CurrBlockSize;
for I := 0 to AddDataQty - 1 do
begin
CAddr:=FlashProgData[I].adress+BaseAddAddr;
if (CAddr>=MinAddr)and (CAddr<MaxAddr) then //only iside the current sector/page
begin
bFlash:=DatArray[CAddr-MinAddr];
bData:=FlashProgData[I].data;
if bFlash<>bData then
begin
AddPgToWrite:=true;
IsWritingAdd:=true;
DatArray[CAddr-MinAddr]:=bData;
end;
if (bData and (not bFlash))<>0 then
AddPgToErase:=true;
end;
end; //formed new flash block
end;
function GetAddFlashSector : boolean;
var I,q : integer;
z : cardinal;
begin
result:=false;
CurrPageDone:=false;
for I := 0 to 7 do
begin
z:=(CurrSector+1)*CurrBlockSize-CurrFlashAddr;
if not GetFlashData(FT_In_Buffer,CurrFlashAddr,z) then
exit;
for q := 0 to z - 1 do
DatArray[CurrFlashIndex+q]:=FT_In_Buffer[q];
CurrFlashIndex:=CurrFlashIndex+z;
CurrFlashAddr:=CurrFlashAddr+z;
if (CurrFlashAddr mod CurrBlockSize)=0 then //current sector is read
begin
TestAddFlashData;
CurrPageDone:=true;
end;
end;
result:=true;
end;
procedure PrepareFlashVerify;
begin
FlashState:=Verifying; //start autoverifying
FlashTimer.Interval:=20;
CurrFlashAddr:=StartFlashAddr;
CurrFlashIndex:=0;
VeryErrCounter:=0;
end;
function SendFlashPage : boolean; //записывает страницу памяти, содержащую CurrFlashAddr
var QtyTo,QtyFrom,a,z : cardinal; //данными, содержащимися в DatArray начиная с CurrFlashIndex
q : integer; //к-во: до конца страницы или до StopFlashAddr
str : string; //затем CurrFlashIndex и CurrFlashAddr увеличиваются на к-во
begin
result:=false;
if (FlashState<>Writing) and (FlashState<>WritingAdd) then
begin
Lister.Text:=Lister.Text+'Illegal flash writing call!';
exit;
end;
z:=((CurrFlashAddr div FlashPageSize)+1)*FlashPageSize; //first address at the next page
if z>StopFlashAddr then
a:=StopFlashAddr-CurrFlashAddr
else
a:=z-CurrFlashAddr;
FT_Out_Buffer[0]:=DoSPIExchComm;
FT_Out_Buffer[1]:=WREN;
QtyTo:=2;
if not (PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str)=PB_Data) then
exit;
FT_Out_Buffer[0]:=WriteFlashComm;
FT_Out_Buffer[2]:=(a+4) div 256;
FT_Out_Buffer[1]:=(a+4) mod 256;
FT_Out_Buffer[3]:=PROG;
FT_Out_Buffer[4]:=CurrFlashAddr div $10000;
FT_Out_Buffer[5]:=(CurrFlashAddr mod $10000) div $100;
FT_Out_Buffer[6]:=CurrFlashAddr mod $100;
for q := 0 to a-1 do
FT_Out_Buffer[q+7]:=DatArray[CurrFlashIndex+q];
QtyTo:=a+7;
QtyFrom:=3;
if (PB_SendCommandToDevice(ProgDevNum,ProgPBAddr,FT_Out_Buffer,FT_In_Buffer,QtyTo,QtyFrom,str)=PB_OK) then
begin
result:=true;
CurrFlashAddr:=CurrFlashAddr+a;
CurrFlashIndex:=CurrFlashIndex+a;
end;
if not result then
FlashState:=NOP;
end;
function FT_PARALLEL_PORT_READ (QtyFrom: cardinal; FT_Parallel_Handle : DWORD;var DataIn: array of byte ):boolean;//(var DataIn: array of byte; QtyFrom: cardinal):boolean;
var
Read_result:integer;
qty,q,tim,Total,I:cardinal;
FT_IO_Status: FT_Result;
buffer: array [0..FT_In_Buffer_Index] of byte;
Inta: integer;
begin
Inta := FT_SetUSBParameters(FT_Parallel_Handle,64000,4096);
If Inta = FT_OK then
begin
tim:=0;
Total:=0;
repeat
q:= FT_GetQueueStatus(FT_Parallel_Handle,@qty);
If q <> FT_OK then
begin
//FT_Error_Report('FT_GetQueueStatus',q);
break;
end
else
begin
if qty>0 then
begin
FT_IO_Status := FT_Read(FT_Parallel_Handle,@buffer,qty,@Read_Result);
If FT_IO_Status <> FT_OK then
begin
// FT_Error_Report('FT_Read',FT_IO_Status);
break;
end
else
begin
tim:=0;
if Total<QtyFrom-1 then
begin
// AttArray[AttQty]:=qty; //
// AttQty:=AttQty+1; //
for I := 0 to qty - 1 do
begin
if ((Total+I)<QtyFrom-1) then
DataIn[Total+I]:=buffer[I];
// QtyFrom:=QtyFrom+1;
/// if DataIn[I]=$FE then
// exit;
end;
Total:=Total+I;
// if (QtyFrom+qty =2)and (DataOut[0]<>StartSymbol) and (DataOut[0]=(DataOut[1] xor $FF)) then
// begin
// result:=true;
// exit;
// end;
end;
end;
end;
tim:=tim+1;
if tim>250000 then
begin
Result := FALSE;
break;
end;
end;
until (Total>=QtyFrom);
Result := (Read_Result=Total);
end;
end;
function FT_PARALLEL_PORT_CLEAR_BUFFER (FT_Parallel_Handle : DWORD;var qtt: integer):boolean;
var
Read_result:integer;
qty,q:cardinal;
FT_IO_Status: FT_Result;
buffer: array [0..FT_In_Buffer_Index] of byte;
begin
qty:=0;
q:= FT_GetQueueStatus(FT_Parallel_Handle,@qty);
If q <> FT_OK then
begin
Result:=false;
end
else
begin
qtt:=qty;
if qty>0 then
begin
FT_IO_Status := FT_Read(FT_Parallel_Handle,@buffer,qty,@Read_Result);
If FT_IO_Status <> FT_OK then
Result:=false
else
Result:=false;
end
else
Result:=true;
end;
end;
function PrepareDataTo (Filename : string; DevNum : integer; PBAddr : byte; StartAddr : cardinal) : boolean;
begin
result:=false;
if FlashState<>NOP then
begin
Lister.Text:=Lister.Text+'Some FLASH operation is already in progress!';
exit;
end;
if not DefineFLASHType(DevNum,PBAddr) then
exit;
OpenLogFile; //
SetLength(DatArray,CurrFlashSize);
if ReadFPGAData(Filename,DatArray,FlDataQty) then
Lister.Text:=Lister.Text+'Read data from '+Filename+chr($0D)+Chr($0A)
else
exit;
StartFlashAddr:=StartAddr;
CurrFlashAddr:=StartAddr;
CurrFlashIndex:=0;
StopFlashAddr:=StartAddr+FlDataQty;
ProgDevNum:=DevNum;
ProgPBAddr:=PBAddr;
result:=true;
end;
function PrepareDataFrom (DevNum : integer; PBAddr : byte; StartAddr : cardinal) : boolean;
begin
result:=false;
if FlashState<>NOP then
begin
Lister.Text:=Lister.Text+'Some FLASH operation is already in progress!';
exit;
end;
if not DefineFLASHType(DevNum,PBAddr) then
exit;
OpenLogFile; //
SetLength(DatArray,CurrFlashSize);
StartFlashAddr:=StartAddr;
CurrFlashAddr:=StartAddr;
CurrFlashIndex:=0;
StopFlashAddr:=StartAddr+CurrFlashSize;
ProgDevNum:=DevNum;
ProgPBAddr:=PBAddr;
result:=true;
end;
procedure StartFlashProgram (Filename : string; DevNum : integer; PBAddr : byte);
begin
if not PrepareDataTo(Filename,DevNum,PBAddr,0) then
exit;
FlashErase(0,FlDataQty);
end;
function VerifyFlashData : boolean;
var I,q : integer; //comparing up to 8 pages (2kB) from address CurrFlashAddr with
z : cardinal; //data in DatArray from CurrFlashIndex position
begin
result:=false;
for I := 0 to 7 do
begin
z:=StopFlashAddr-CurrFlashAddr;
result:=GetFlashData(FT_In_Buffer,CurrFlashAddr,z);
if result then
begin
for q := 0 to z - 1 do
begin
if FT_In_Buffer[q]<>DatArray[CurrFlashIndex+q] then
begin
VeryErrCounter:=VeryErrCounter+1;
if VeryErrCounter<20 then
Lister.Text:=Lister.Text+'Address $'+IntToHex(CurrFlashIndex+q,6)+': $'+ IntToHex(FT_In_Buffer[q],2)+
'<>$'+IntToHex(DatArray[CurrFlashIndex+q],2)+chr($0D)+Chr($0A);
end;
end;
end
else
exit;
CurrFlashIndex:=CurrFlashIndex+z;
CurrFlashAddr:=CurrFlashAddr+z;
if CurrFlashAddr>=StopFlashAddr then
break;
end;
end;
function ReadFlashData : boolean;
var I,q : integer; //reads up to 8 pages (2kB) from CurrFlashAddr to StopFlashAddr
z : cardinal; //then increments CurrFlashAddr
begin
for I := 0 to 7 do
begin
z:=StopFlashAddr-CurrFlashAddr;
result:=GetFlashData(FT_In_Buffer,CurrFlashAddr,z);
if result then
begin
for q := 0 to z - 1 do
DatArray[CurrFlashIndex+q]:=FT_In_Buffer[q];
CurrFlashIndex:=CurrFlashIndex+z;
CurrFlashAddr:=CurrFlashAddr+z;
if CurrFlashAddr>=StopFlashAddr then
break;
end
else
exit;
end;
end;
procedure StartFlashVerify (Filename : string; DevNum : integer; PBAddr : byte);
begin
if not PrepareDataTo(Filename,DevNum,PBAddr,0) then
exit;
PrepareFlashVerify;
FlashTimer.Enabled:=true;
end;
procedure StartFlashRead (DevNum : integer; PBAddr : byte);
begin
PrepareDataFrom(DevNum,PBAddr,0);
FlashState:=Reading;
FlashTimer.Interval:=20;
FlashTimer.Enabled:=true;
end;
procedure FlashTimerDo;
var FLState : byte;
Succ : boolean;
str : string;
begin
FlashTimer.Enabled:=false;
str:='';
if not GetFlashState(FLState) then
begin
FlashState:=NOP;
exit;
end;
if (FLState and 1)<>0 then
begin
FlashTimer.Enabled:=true;
exit;
end;
case FlashState of
Erasing:
begin
Succ:=FlashSectorErase;
PageCounter:=PageCounter+1;
ProgressData:=PageCounter/MaxPages;
if PageCounter=MaxPages then
begin
str:='Flash erasing done';
FlashState:=Writing;
FlashTimer.Interval:=36;
ProgressData:=0;
CurrFlashAddr:=StartFlashAddr;
end
else
begin
if Succ then
str:='Erasing sector '
else
str:='Erasing failed at sector ';
str:=str+IntToStr(PageCounter-1);
end;
end;
Writing:
begin
Succ:=SendFlashPage;
if StopFlashAddr=CurrFlashAddr then
begin
PrepareFlashVerify;
str:='FLASH programming done. Verifying starting.';
end;
ProgressData:=(CurrFlashAddr-StartFlashAddr)/(StopFlashAddr-StartFlashAddr);
end;
Reading:
begin
Succ:=ReadFlashData;
ProgressData:=(CurrFlashAddr-StartFlashAddr)/(StopFlashAddr-StartFlashAddr);
if CurrFlashAddr=StopFlashAddr then
begin
ProgressData:=0;
FlashState:=NOP;
if FlashSave.Execute then
begin
ConvertToUfpFile(FlashSave.FileName,DatArray,CurrFlashSize);
str:='Data saved to '+FlashSave.FileName;
end
else
str:='Saving cancelled';
end;
end;
Verifying:
begin
Succ:=VerifyFlashData;
ProgressData:=(CurrFlashAddr-StartFlashAddr)/(StopFlashAddr-StartFlashAddr);
if CurrFlashAddr=StopFlashAddr then
begin
if VeryErrCounter=0 then
Lister.Text:=Lister.Text+'Verification succeded!'+chr($0D)+Chr($0A);
ProgressData:=0;
FlashState:=NOP;
end;
end;
ErasingAdd:
begin;
Succ:=FlashSectorErase;
FlashState:=WritingAdd; //writing 1 sector per time
str:='Sector '+IntToStr(CurrSector) +' was erased';
end;
WritingAdd:
begin
Succ:=SendFlashPage;
if CurrFlashAddr=StopFlashAddr then
begin //current sector is written
if CurrSector<MaxSector then
begin //next sector
CurrSector:=CurrSector+1;
StartAddSectorProc;
FlashState:=PreReadingAdd; //back to reading initial flash content
str:='Sector '+IntToStr(CurrSector) +' was written';
end
else
begin
CurrSector:=MinSector; //to verifying
StartAddSectorProc;
FlashState:=ReadingAdd;
end;
end;
end;
PreReadingAdd:
begin
Succ:=GetAddFlashSector;
if CurrPageDone then
begin
if AddPgToWrite then
begin
StartAddSectorProc;
if AddPgToErase then
FlashSectorErase;
FlashState:=WritingAdd;
StartAddSectorProc;
end
else
begin
if CurrSector<MaxSector then
begin
CurrSector:=CurrSector+1;
StartAddSectorProc;
end
else
begin
if IsWritingAdd then
begin
CurrSector:=MinSector;
StartAddSectorProc;
FlashState:=ReadingAdd;
end
else
begin
str:='Additional memory is compatible';
FlashState:=NOP;
end;
end;
end;
end;
end;
ReadingAdd:
begin
Succ:=GetAddFlashSector;
if CurrPageDone then
begin
if AddPgToWrite then
str:='Additional memory error in sector '+IntToStr(CurrSector);
if CurrSector<MaxSector then
begin
CurrSector:=CurrSector+1;
StartAddSectorProc;
end
else
begin
str:='Additional memory verification completed';
FlashState:=NOP;
end;
end;
end;
end;
FlashTimer.Enabled:=(Succ and (FlashState<>NOP));
if str<>'' then
Lister.Text:=Lister.Text+str+chr($0D)+Chr($0A);
FlashProgr.Position:=Round((FlashProgr.Max-FlashProgr.Min)*ProgressData+FlashProgr.Min);
if not Succ then
FlashState:=NOP;
end;
end.
|
unit ThLabel;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics, ExtCtrls,
ThInterfaces, ThTextPaint, ThWebControl, ThAttributeList,
ThCssStyle, ThStyleList, ThTag, ThAnchor;
type
TThCustomLabel = class(TThWebGraphicControl, IThStyleSource)
private
FWordWrap: Boolean;
FHAlign: TThHAlign;
FVAlign: TThVAlign;
FFitStyleToText: Boolean;
FAnchor: TThAnchor;
FLabelFor: TControl;
protected
function GetAnchorStyle: TThCssStyle;
function GetContent: string; virtual;
function GetHtmlAsString: string; override;
function GetString: string; virtual;
procedure SetAnchor(const Value: TThAnchor);
procedure SetFitStyleToText(const Value: Boolean);
procedure SetHAlign(const Value: TThHAlign);
procedure SetLabelFor(const Value: TControl);
procedure SetVAlign(const Value: TThVAlign);
procedure SetWordWrap(const Value: Boolean);
protected
function CreateAnchor: TThAnchor; virtual;
procedure AnchorChange(inSender: TObject);
procedure BuildStyle; override;
procedure LabelTag(inTag: TThTag); virtual;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Paint; override;
procedure PerformAutoSize; override;
procedure PublishStyles(inStyles: TStringList);
procedure Tag(inTag: TThTag); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CellTag(inTag: TThTag); override;
public
property Anchor: TThAnchor read FAnchor write SetAnchor;
property AutoSize default true;
property FitStyleToText: Boolean read FFitStyleToText
write SetFitStyleToText;
property HAlign: TThHAlign read FHAlign write SetHAlign default haDefault;
property LabelFor: TControl read FLabelFor write SetLabelFor;
property WordWrap: Boolean read FWordWrap write SetWordWrap default false;
property VAlign: TThVAlign read FVAlign write SetVAlign default vaDefault;
end;
//
TThLabel = class(TThCustomLabel)
published
property Align;
property Anchor;
property AutoSize;
property Caption;
property DesignOpaque;
property FitStyleToText;
property HAlign;
property LabelFor;
property Style;
property StyleClass;
property WordWrap;
property VAlign;
property Visible;
end;
//
TThText = class(TThCustomLabel)
private
FText: TStringList;
FUseBR: Boolean;
protected
function GetContent: string; override;
function GetString: string; override;
procedure SetText(const Value: TStringList);
procedure SetUseBR(const Value: Boolean);
protected
procedure TextChange(inSender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchor;
property AutoSize;
property DesignOpaque;
property FitStyleToText;
property HAlign;
property LabelFor;
property Style;
property StyleClass;
property Text: TStringList read FText write SetText;
property UseBR: Boolean read FUseBR write SetUseBR default true;
property VAlign;
property Visible;
end;
const
ssHAlign: array[TThHAlign] of string = ( '', 'left', 'center', 'right' );
ssVAlign: array[TThVAlign] of string = ( '', 'top', 'middle', 'bottom',
'baseline' );
implementation
uses
ThStyleSheet, ThHtmlPage;
{ TThCustomLabel }
constructor TThCustomLabel.Create(AOwner: TComponent);
begin
inherited;
// Using AutoSize setter invokes PerformAutoSize below
// which clobbers the control's design time display
// for unknown reasons
//AutoSize := true;
FAutoSize := true;
FAnchor := CreateAnchor;
FAnchor.OnChange := AnchorChange;
end;
destructor TThCustomLabel.Destroy;
begin
FAnchor.Free;
inherited;
end;
function TThCustomLabel.CreateAnchor: TThAnchor;
begin
Result := TThAnchor.Create;
end;
procedure TThCustomLabel.AnchorChange(inSender: TObject);
begin
Invalidate;
end;
procedure TThCustomLabel.SetWordWrap(const Value: Boolean);
begin
FWordWrap := Value;
AdjustSize;
end;
function TThCustomLabel.GetString: string;
begin
Result := Caption;
end;
procedure TThCustomLabel.PerformAutoSize;
var
s: string;
begin
s := GetString;
if (Parent <> nil) and (Canvas <> nil) {and (Canvas.HandleAllocated)} then
try
case Align of
alLeft, alRight, alNone:
if (not WordWrap) and (s <> '') then
Width := ThTextWidth(Canvas, s) + Style.GetBoxWidthMargin;
end;
case Align of
alTop, alBottom, alNone:
if (s <> '') then
Height :=
ThTextHeight(Canvas, s, AdjustedClientRect, haDefault, WordWrap)
+ Style.GetBoxHeightMargin;
end;
except
end;
end;
function TThCustomLabel.GetAnchorStyle: TThCssStyle;
var
p: TThHtmlPage;
s: string;
begin
p := ThFindHtmlPage(Self);
if p <> nil then
begin
s := Anchor.Styles.Link;
if (s = '') then
s := p.AnchorStyles.Link;
Result := ThFindStyleSheetStyle(Self, s);
end else
Result := nil;
end;
procedure TThCustomLabel.BuildStyle;
var
s: TThCssStyle;
begin
s := GetAnchorStyle;
if (s = nil) or (Anchor.Empty) then
begin
CtrlStyle.Assign(Style);
if not Anchor.Empty then
CtrlStyle.Font.FontDecoration := fdUnderline;
end
else begin
CtrlStyle.Assign(s);
CtrlStyle.Inherit(Style);
end;
CtrlStyle.Inherit(SheetStyle);
CtrlStyle.Font.Inherit(PageStyle.Font);
CtrlStyle.Font.ToFont(Font);
Canvas.Font := Font;
Color := CtrlStyle.Color;
if not ThVisibleColor(Color) and DesignOpaque then
if (Parent <> nil) then
Color := TPanel(Parent).Color;
end;
procedure TThCustomLabel.Paint;
begin
inherited;
ThPaintText(Canvas, GetString, AdjustedClientRect, HAlign, VAlign, WordWrap,
true);
end;
procedure TThCustomLabel.LabelTag(inTag: TThTag);
begin
with inTag do
begin
Attributes.Add('nowrap', not WordWrap);
Add('class', StyleClass);
Style.ListStyles(Styles);
ListJsAttributes(Attributes);
end;
end;
procedure TThCustomLabel.CellTag(inTag: TThTag);
begin
with inTag do
begin
case Align of
alLeft, alClient, alRight: Add('height', '100%');
else Add('height', Height);
end;
case Align of
alTop, alClient, alBottom: ;
else Add('width', Width);
end;
Add('align', ssHAlign[HAlign]);
Add('valign', ssVAlign[VAlign]);
if not FitStyleToText then
LabelTag(inTag);
end;
end;
function TThCustomLabel.GetContent: string;
begin
Result := GetString;
end;
procedure TThCustomLabel.Tag(inTag: TThTag);
begin
with inTag do
begin
Content := GetContent;
if FitStyleToText then
Element := 'span';
if LabelFor <> nil then
begin
Element := 'label';
inTag.Add('for', LabelFor.Name);
end
else if FitStyleToText then
Element := 'span';
if FitStyleToText then
LabelTag(inTag);
end;
end;
function TThCustomLabel.GetHtmlAsString: string;
begin
Anchor.Name := Name + 'A';
Result := Anchor.Wrap(inherited GetHtmlAsString);
end;
procedure TThCustomLabel.SetHAlign(const Value: TThHAlign);
begin
FHAlign := Value;
Invalidate;
end;
procedure TThCustomLabel.SetVAlign(const Value: TThVAlign);
begin
FVAlign := Value;
Invalidate;
end;
procedure TThCustomLabel.SetFitStyleToText(const Value: Boolean);
begin
FFitStyleToText := Value;
end;
procedure TThCustomLabel.SetAnchor(const Value: TThAnchor);
begin
FAnchor.Assign(Value);
end;
procedure TThCustomLabel.SetLabelFor(const Value: TControl);
begin
if FLabelFor <> nil then
FLabelFor.RemoveFreeNotification(Self);
FLabelFor := Value;
if FLabelFor <> nil then
FLabelFor.FreeNotification(Self);
end;
procedure TThCustomLabel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (LabelFor = AComponent) then
FLabelFor := nil;
end;
procedure TThCustomLabel.PublishStyles(inStyles: TStringList);
begin
if not Anchor.Empty then
Anchor.Styles.GenerateStyles(inStyles, ThFindStyleSheet(Self), Anchor.Name);
end;
{ TThText }
constructor TThText.Create(AOwner: TComponent);
begin
inherited;
FText := TStringList.Create;
FText.OnChange := TextChange;
WordWrap := true;
FUseBr := true;
end;
destructor TThText.Destroy;
begin
FText.Free;
inherited;
end;
function TThText.GetString: string;
begin
Result := Text.Text;
end;
function TThText.GetContent: string;
begin
Result := inherited GetContent;
if UseBr then
Result := StringReplace(Result, #$D#$A, '<br>', [ rfReplaceAll ]);
//Result := '<pre>' + inherited GetContent + '</pre>';
end;
procedure TThText.SetText(const Value: TStringList);
begin
FText.Assign(Value);
end;
procedure TThText.TextChange(inSender: TObject);
begin
Invalidate;
end;
procedure TThText.SetUseBR(const Value: Boolean);
begin
FUseBR := Value;
end;
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uCarregaConfiguracoes;
interface
uses
System.Classes, IniFiles, uParametrosConexao, uEnum, uLog,
System.SysUtils, System.ioutils, Winapi.Windows, ShellApi, TlHelp32, Forms, StrUtils;
type
ICarregaConfiguracoes = interface
['{EF8A0C2B-1935-411E-82A6-DD08E34A64CE}']
function GetConfiguracaoOrigem: IParametrosConexao;
function GetConfiguracaoDestino: IParametrosConexao;
end;
TCarregaConfiguracoes = class(TInterfacedObject, ICarregaConfiguracoes)
FServer: string;
FPorta: string;
FBanco: string;
FUsuario: string;
FSenha: string;
FDriverID: string;
function CarregarConfiguracoes(AcSessao: String): IParametrosConexao;
public
class function new: ICarregaConfiguracoes;
function GetConfiguracaoOrigem: IParametrosConexao;
function GetConfiguracaoDestino: IParametrosConexao;
end;
implementation
{ TCarregaConfiguracoes }
class function TCarregaConfiguracoes.new: ICarregaConfiguracoes;
begin
Result := TCarregaConfiguracoes.Create;
end;
function TCarregaConfiguracoes.GetConfiguracaoOrigem: IParametrosConexao;
begin
Result := CarregarConfiguracoes('Origem');
end;
function TCarregaConfiguracoes.GetConfiguracaoDestino: IParametrosConexao;
begin
Result := CarregarConfiguracoes('Destino');
end;
function TCarregaConfiguracoes.CarregarConfiguracoes(AcSessao: String): IParametrosConexao;
var
FIni: TIniFile;
begin
try
TLog.New.Logar('Lendo configuração...');
try
FIni := TIniFile.Create(ExtractFileDir(Forms.Application.ExeName) + '\' +
ReplaceStr(ExtractFileName(Forms.Application.ExeName), '.exe', '.ini'));
FServer := FIni.ReadString(AcSessao, 'Server', EmptyStr);
FPorta := FIni.ReadString(AcSessao, 'Porta', EmptyStr);
FBanco := FIni.ReadString(AcSessao, 'Banco', EmptyStr);
FUsuario := FIni.ReadString(AcSessao, 'Usuario', EmptyStr);
FSenha := FIni.ReadString(AcSessao, 'Senha', EmptyStr);
FDriverID := FIni.ReadString(AcSessao, 'DriverID', EmptyStr);
finally
Fini.Free;
end;
Result := TParametrosConexao.New( FServer
, FPorta
, FBanco
, FUsuario
, FSenha
, FDriverID
);
except
on E: Exception do
begin
TLog.New.Logar('Erro ao ler configurações: ' + E.Message);
end
end;
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
UNIT TETRIS_SACK;
INTERFACE
USES
TETRIS_PIECE;
TYPE
tetrissack = ARRAY [1 .. 7] OF TTauTetrisPiece;
TTauTetrisSack = CLASS
PRIVATE
sack: tetrissack;
index: integer;
PUBLIC
CONSTRUCTOR Create();
DESTRUCTOR Destroy(); OVERRIDE;
PROCEDURE Clear();
PROCEDURE Reset();
FUNCTION GetNext(): TTauTetrisPiece;
END;
IMPLEMENTATION
CONSTRUCTOR TTauTetrisSack.Create();
VAR
i: integer;
BEGIN
index := 0;
FOR i := 1 TO 7 DO
BEGIN
sack[i] := NIL;
END;
Reset();
END;
DESTRUCTOR TTauTetrisSack.Destroy();
BEGIN
Clear();
END;
PROCEDURE TTauTetrisSack.Reset();
VAR
ri, i: integer;
used: ARRAY[1 .. 7] OF boolean;
BEGIN
index := 0;
ri := -1;
Clear();
FOR i := 1 TO 7 DO
BEGIN
used[i] := FALSE;
END;
FOR i := 1 TO 7 DO
BEGIN
WHILE ((ri = -1) OR (used[ri + 1])) DO
BEGIN
ri := Random(7);
END;
used[ri + 1] := TRUE;
IF (ri = 1) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_RL);
END
ELSE IF (ri = 2) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_L);
END
ELSE IF (ri = 3) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_S);
END
ELSE IF (ri = 4) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_Z);
END
ELSE IF (ri = 5) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_I);
END
ELSE IF (ri = 6) THEN
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_T);
END
ELSE
BEGIN
sack[i] := TTauTetrisPiece.Create(TETRIS_PIECE_Q);
END;
END;
END;
PROCEDURE TTauTetrisSack.Clear();
VAR
i: integer;
BEGIN
FOR i := 1 TO 7 DO
BEGIN
IF (sack[i] <> NIL) THEN
BEGIN
// sack[i].Free();
sack[i] := NIL;
END;
END;
END;
FUNCTION TTauTetrisSack.GetNext(): TTauTetrisPiece;
VAR
piece: TTauTetrisPiece;
BEGIN
piece := NIL;
index := index + 1;
IF (index > 7) THEN
BEGIN
WriteLn('Sack index > 7, ', index);
Reset();
index := 1;
END;
IF (sack[index] = NIL) THEN
RaiSE ExceptionClass.Create();
GetNext := sack[index];
END;
END.
|
unit ThAlignUtils;
interface
uses
Controls, ThComponentIterator;
function OverlapX(inI, inJ: TControl): Boolean;
function OverlapY(inI, inJ: TControl): Boolean;
function AdjustX(i, j: TThCtrlIterator): Boolean;
function AdjustY(i, j: TThCtrlIterator): Boolean;
procedure UnoverlapControls(i, j: TThCtrlIterator);
implementation
function OverlapX(inI, inJ: TControl): Boolean;
begin
Result :=
((inI.Left < inJ.BoundsRect.Right) and (inJ.Left < inI.BoundsRect.Right))
or
((inJ.Left < inI.BoundsRect.Right) and (inI.Left < inJ.BoundsRect.Right));
end;
function OverlapY(inI, inJ: TControl): Boolean;
begin
Result :=
((inI.Top < inJ.BoundsRect.Bottom) and (inI.BoundsRect.Bottom > inJ.Top))
or
((inJ.Top < inI.BoundsRect.Bottom) and (inJ.BoundsRect.Bottom > inI.Top));
end;
function AdjustX(i, j: TThCtrlIterator): Boolean;
var
dx, dy: Integer;
begin
Result := false;
while i.Next do
begin
if (i.Ctrl.Align <> alNone) then
continue;
if (i.Ctrl.Left < 0) then
dx := 1
else if (i.Ctrl.Left > 0) then
dx := -1
else
dx := 0;
while (dx < 1) and j.Next do
begin
//if (j.Ctrl.Align <> alNone) then
// continue;
if (i.Index = j.Index) then
continue;
if OverlapY(i.Ctrl, j.Ctrl) then
begin
if (i.Ctrl.Left > j.Ctrl.Left)
and (i.Ctrl.Left < j.Ctrl.BoundsRect.Right) then
begin
if (j.Ctrl.Top >= i.Ctrl.Top) then
dy := 0
else
dy := j.Ctrl.BoundsRect.Bottom - i.Ctrl.Top;
if (dy <= 0) or (dy > j.Ctrl.BoundsRect.Right - i.Ctrl.Left) then
dx := 1
else if (dx = -1) then
dx := 0;
end
else if j.Ctrl.BoundsRect.Right = i.Ctrl.Left then
dx := 0;
end;
end;
j.Reset;
if (dx <> 0) then
begin
Result := true;
i.Ctrl.Left := i.Ctrl.Left + dx;
//i.Ctrl.Update;
//Sleep(1);
end;
end;
end;
function AdjustY(i, j: TThCtrlIterator): Boolean;
var
dy: Integer;
begin
Result := false;
while i.Next do
begin
if (i.Ctrl.Align <> alNone) then
continue;
if (i.Ctrl.Top < 0) then
dy := 1
else if (i.Ctrl.Top > 0) then
dy := -1
else
dy := 0;
while (dy < 1) and j.Next do
begin
//if (j.Ctrl.Align <> alNone) then
// continue;
if (i.Index = j.Index) then
continue;
if OverlapX(i.Ctrl, j.Ctrl) then
begin
if (i.Ctrl.Top > j.Ctrl.Top)
and (i.Ctrl.Top < j.Ctrl.BoundsRect.Bottom) then
dy := 1
else if j.Ctrl.BoundsRect.Bottom = i.Ctrl.Top then
dy := 0;
end;
end;
j.Reset;
if (dy <> 0) then
begin
Result := true;
i.Ctrl.Top := i.Ctrl.Top + dy;
//i.Ctrl.Update;
//Sleep(1);
end;
end;
end;
procedure UnoverlapControls(i, j: TThCtrlIterator);
var
dx, dy: Integer;
work: Boolean;
begin
repeat
work := false;
while i.Next do
begin
j.Reset;
while j.Next do
begin
if i.Index = j.Index then
continue;
if OverlapX(i.Ctrl, j.Ctrl) and OverlapY(i.Ctrl, j.Ctrl) then
begin
dx := j.Ctrl.BoundsRect.Right - i.Ctrl.Left;
dy := j.Ctrl.BoundsRect.Bottom - i.Ctrl.Top;
if (dx > 0) or (dy > 0) then
begin
work := true;
if (abs(dx) < abs(dy)) then
begin
if dx > 0 then
i.Ctrl.Left := i.Ctrl.Left + dx //1
end else
if dy > 0 then
i.Ctrl.Top := i.Ctrl.Top + dy; //1;
end;
end; // Overlap
end; // j.Next
end; // i.Next
until not work;
end;
end.
|
unit uParser;
interface
uses classes ;
const
TT_NUMB =1 ;
TT_STRING =2 ;
TT_TOKEN = 3 ;
TT_LEFT = 4 ;
TT_RIGHT = 5 ;
TT_INT = 6 ;
TT_EOF = 0 ;
TT_NOTMATCH = -1 ;
TT_NULL = 7 ;
TT_TRUE = 8;
TT_FALSE = 9 ;
TT_LIST = 101 ;
type
TLispParser = class
private
mStream : TStream ;
function isDelimiter(ch : char):boolean ;
function isQDelimiter(ch : char):boolean ;
function isEnter(ch : char):boolean ;
function TokenType(token : string): Integer ;
public
//constructor create (s : TStream);
procedure load (s : TStream);
function nextToken (var token : String):Integer;
end;
implementation
{ TLispParser }
//constructor TLispParser.create(s: TStream);
procedure TLispParser.load(s: TStream);
begin
mstream := s ;
mstream.position := 0 ;
end;
function TLispParser.nextToken(var token: String): Integer;
var
ch : char ;
i, frontpos,backpos : longint;
buffer : array [0..128] of char ;
label
retry ;
begin
if mstream.Position = mstream.Size then
begin
result := TT_EOF ;
EXIT
end;
mstream.Read(ch,1);
while ((ch = ' ') or (ch = #10) or (ch= #13)) and (mstream.Position<mstream.Size) do
begin
mstream.read(ch,1);
end;
if ((ch = ' ') or (ch = #10) or (ch= #13)) and (mstream.Position = mstream.Size) then
begin
result := TT_EOF ;
EXIT
end;
case ch of
'(':
begin
result := TT_LEFT ;
end;
')':
begin
result := TT_RIGHT ;
end;
''''://SKIP COMMENTS
begin
mstream.read(ch,1);
while not isEnter(ch) do
mstream.read(ch,1);
end;
'"':
begin
frontpos := mstream.position ;
mstream.read(ch,1);
while not isQDelimiter(ch) do
begin
mstream.read(ch,1);
end;
if ch <> '"' then
begin
result := TT_NOTMATCH ;
exit;
end;
backpos := mstream.Position -1 ;
mstream.Seek(frontpos,soFromBeginning);
fillchar(buffer,sizeof(buffer),#0);
mstream.read(buffer,backpos-frontpos);
//add
mstream.Seek(backpos+1,soFromBeginning);
i := 0 ;
while (buffer[i]<> #0) do
begin
token := token + buffer[i];
inc(i);
end;
Result := TT_STRING ;
end;
{#10:
begin
end;
#13:
begin
end;}
else
begin
// NEXT delimeter
frontpos := mstream.Position -1;
mstream.read(ch,1);
while not isDelimiter(ch) do
mstream.read(ch,1);
//if (pos(ch,'''"()')<>0) then
begin
backpos := mstream.Position-1 ;
mstream.Seek(frontpos,soFromBeginning);
fillchar (buffer ,sizeof(buffer),#0);
mstream.read(buffer,backpos-frontpos);
i := 0 ;
while (buffer[i]<> #0) do
begin
token := token + buffer[i];
inc(i);
end;
mstream.Seek(backPos,soFromBeginning);
// is numberic
result := TokenType(token);
end;
end;
end;//case
end;
function TLispParser.isDelimiter(ch : char):boolean ;
begin
result := not ((pos(ch,'''"() '#13#10)=0) and (mstream.Position<mstream.Size));
end;
function TLispParser.isEnter(ch : char):boolean ;
begin
result := not ((pos(ch,#13#10)=0) and (mstream.Position<mstream.Size));
end;
function TLispParser.TokenType(token : string): Integer ;
var
dotcount ,i : integer ;
begin
dotcount := 0 ;
//flag := false ;
if (length(token) = 1) and (pos(token,'0123456789') = 0 )then begin
result := TT_TOKEN;
exit ;
end;
for i := 1 to length(token) do
begin
if (token[i]='.') then
inc(dotcount) ;
if (i = 1) then
begin
if (pos(token[i],'-0123456789.') = 0 ) or (dotcount>1) then
begin
result := TT_TOKEN;
exit ;
end;
end
else
if (pos(token[i],'0123456789.') = 0 ) or (dotcount>1) then
begin
result := TT_TOKEN;
exit ;
end;
end;
if (dotcount=0 ) then begin
if (length(token) = 1) and (pos(token,'0123456789')=-1) then
Result := TT_TOKEN
else
Result := TT_INT
end
else
Result := TT_NUMB ;
end;
function TLispParser.isQDelimiter(ch: char): boolean;
begin
// Quote Delimeter NOT include space
result := not ((pos(ch,'''"()'#13#10)=0) and (mstream.Position<mstream.Size));
end;
end.
|
unit DA;
{*******************************************************************************
Copyright (C) 2004-2005 ESQUEL GROUP IT DEPARTMENT
文件名: TDA
创建人: WLX
日 期: 2004-5-31
修改人:
修改内容描述:
修改日期:
描 述: 该类封装了访问sqlserver数据库的常见方式。可以返回数据集,可以返回一个
单字段值,也可以执行常用的insert,delete ,update语句等 .同时提供多层模式
的 DatasetProvider.ApplyUpdate 通用方法。
版 本: V 1.00
*******************************************************************************}
interface
uses Classes, DBClient, StdVcl, DB, ADODB, SysUtils,IdGlobal, Variants, Provider;
type
TDA = class(TObject)
protected
mADOCommand: TADOCommand;
mADODataset: TADODataset;
private
mErrorMessage: string;
function GetCommandText: string;
procedure SetCommandText(const Value: string);
function GetCommand: TADOCommand;
function GetConnection: TADOConnection;
procedure SetConnection(Value: TADOConnection);
function GetParameters: TParameters;
function GetTimeOut: Integer;
procedure SetTimeOut(Value: Integer);
function GetCommandType: TCommandType;
procedure SetCommandType(const Value: TCommandType);
function GetDefaultDatabase(sqlText :String):String;
function GetOldDefaultDatabase(connectionString:string):String;
procedure DatasetProviderUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse);
function GetConnectionError(adoConnection:TADOConnection):string;
public
constructor Create(); overload;
constructor Create(commandText: string; commandType: TCommandType; conn: TADOConnection); overload;
destructor Destroy; override;
procedure ExecuteNonQuery(var sErrorMsg: widestring); overload; //执行insert,delete,updaate等不需要记录集的sql语句
procedure ExecuteNonQuery(); overload;
function ExecuteScalar(var sErrorMsg: widestring): variant; overload; //返回第一条记录第一个字段值,一般用来获取单个字段值,如果根据id好获取名称
function ExecuteScalar: variant; overload;
function Execute(var sErrorMsg: widestring): _Recordset; overload; //返回记录集
function Execute: _Recordset; overload;
function DataSet(var sErrorMsg: widestring; bNextRecordSet: boolean = false): TADODataSet; overload;
function DataSet(bNextRecordSet: boolean = false): TADODataSet; overload;
procedure AddParameter(parameterName: string; parameterType: TFieldType; parameterValue: Variant; parameterDirection: TParameterDirection); //增加或设定参数值、类型等
procedure ApplyUpdate(datasetProvider: TDataSetProvider; delta: OleVariant; var sErrorMsg: widestring); overload;
procedure ApplyUpdate(datasetProvider: TDataSetProvider; delta: OleVariant; sql: Widestring; connection: TADOConnection; var sErrorMsg: widestring); overload;
//按指定的字段作为Update KEY更新数据集
procedure ApplyUpdate(datasetProvider: TDataSetProvider;delta: OleVariant; sql,sKeyField: Widestring; connection: TADOConnection; var sErrorMsg: widestring); overload;
function CheckParaByName(parameterName: string): boolean; //检查一个参数是否存在
function GetParameterValue(parameterName: string): variant; //返回参数值
procedure SetParameterValue(parameterName: string; parameterValue: variant); //设定参数值
function GetParameterType(parameterName: string): TFieldType; //返回参数类型
procedure SetParameterType(parameterName: string; parameterType: TFieldType); //设定返回参数类型
function GetParameterDirection(parameterName: string): TParameterDirection; //返回参数传递方向
procedure SetParameterDirection(parameterName: string; parameterDirection: TParameterDirection); //返回参数传递方向
property CommandText: string read GetCommandText write SetCommandText; //获取或设定执行的sql语句
property CommandType: TCommandType read GetCommandType write SetCommandType; //获取或设定sql语句类型,cmdText,cmdStoredProc ...
property Command: TADOCommand read GetCommand; //获取执行sql语句的TADOCommand对象
property Connection: TADOConnection read GetConnection write SetConnection; //获取TADOCommand的连接对象
property Parameters: TParameters read GetParameters; //获取TADOCommand的Parameters对象
property TimeOut: Integer read GetTimeOut write SetTimeOut; //获取或设定TADOCommand的CommandTimeOut时间
end;
implementation
{ TDA }
constructor TDA.Create;
begin
mADOCommand := TADOCommand.Create(nil);
end;
constructor TDA.Create(commandText: string; commandType: TCommandType; conn: TADOConnection);
begin
mADOCommand := TADOCommand.Create(nil);
mADOCommand.Connection := conn;
mADOCommand.CommandText := commandText;
mADOCommand.CommandType := commandType;
mADOCommand.CommandTimeout :=conn.ConnectionTimeout;
end;
destructor TDA.Destroy;
begin
mADOCommand.Free;
if mADODataset <> nil then
mADODataset.Free;
inherited;
end;
//检查一个参数是否存在
function TDA.CheckParaByName(parameterName: string): boolean;
begin
if mADOCommand.Parameters.FindParam(parameterName) = nil then
result := false
else
result := true;
end;
// 如果参数已经存在则不添加参数,但是会替换其余参数属性
procedure TDA.AddParameter(parameterName: string;
parameterType: TFieldType; parameterValue: Variant;
parameterDirection: TParameterDirection);
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then //如果指定的参数名不存在,添加参数
begin
mParameter := mADOCommand.Parameters.AddParameter;
mParameter.Name := parameterName; //这一句不能放到 begin ..end 后面
end;
mParameter.dataType := parameterType;
mParameter.direction := parameterDirection;
mParameter.value := parameterValue;
end;
//执行sql语句返回数据集
function TDA.Execute(var sErrorMsg: widestring): _Recordset;
begin
try
result := mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
except on e: Exception do
sErrorMsg := e.Message;
end;
end;
function TDA.Execute: _Recordset;
var sErrorMsg:widestring;
begin
try
result := mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
if sErrorMsg<>'' then raise Exception.Create(sErrorMsg);
except on e: Exception do
raise Exception.Create(e.Message);
end;
end;
//执行sql语句返回数据集第一条记录的第一个字段值
function TDA.ExecuteScalar(var sErrorMsg: widestring): variant;
var
mRecordSet: _RecordSet;
returnValue: Variant;
begin
try
mRecordSet := mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
if sErrorMsg<>'' then
raise exception.Create(sErrorMsg);
if mRecordSet.RecordCount > 0 then
begin
mRecordSet.MoveFirst;
result := mRecordSet.Fields[0].Value;
end
else
result := returnValue;
except on e: Exception do
sErrorMsg := e.Message;
end;
end;
function TDA.ExecuteScalar: variant;
var
mRecordSet: _RecordSet;
returnValue: Variant;
sErrorMsg:widestring;
begin
try
mRecordSet := mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
if sErrorMsg<>'' then raise Exception.Create(sErrorMsg);
if mRecordSet.RecordCount > 0 then
begin
mRecordSet.MoveFirst;
result := mRecordSet.Fields[0].Value;
end
else
result := returnValue;
except on e: Exception do
raise Exception.Create(e.Message);
end;
end;
//执行insert,delete,update等不需要返回记录集的sql语句
procedure TDA.ExecuteNonQuery(var sErrorMsg: widestring);
begin
try
mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
except on e: Exception do
sErrorMsg := e.Message;
end;
end;
procedure TDA.ExecuteNonQuery;
var
sErrorMsg:widestring;
begin
try
mADOCommand.Execute;
sErrorMsg:=GetConnectionError(mADOCommand.Connection);
if sErrorMsg<>'' then raise Exception.Create(sErrorMsg);
except on e: Exception do
raise Exception.Create(e.Message);
end;
end;
function TDA.DataSet(var sErrorMsg: widestring; bNextRecordSet: boolean = false): TADODataSet;
var
i: integer;
begin
try
if mADODataset = nil then
mADODataset := TADODataset.create(nil);
if not mAdoDataSet.Active then
begin
mADODataSet.Connection := mADOCommand.Connection;
mADODataSet.CommandTimeout := mADOCommand.CommandTimeout;
mADODataSet.CommandText := mADOCommand.CommandText;
mADODataSet.CommandType := mADOCommand.CommandType;
mADODataSet.Parameters := mADOCommand.Parameters;
mADODataSet.Open;
end;
if mADODataSet.Connection.Errors.Count > 0 then
raise Exception.Create(GetConnectionError(mADODataSet.Connection));
if bNextRecordSet then
mAdoDataSet.Recordset := mAdoDataSet.NextRecordset(i);
result := mADODataSet;
except
on e: Exception do
begin
result := nil;
sErrorMsg := e.Message;
end;
end;
end;
function TDA.DataSet(bNextRecordSet: boolean = false): TADODataSet;
var
i: integer;
begin
if mADODataset = nil then
mADODataset := TADODataset.create(nil);
try
if not mAdoDataSet.Active then
begin
mADODataSet.Connection := mADOCommand.Connection;
mADODataSet.CommandTimeout := mADOCommand.CommandTimeout;
mADODataSet.CommandText := mADOCommand.CommandText;
mADODataSet.CommandType := mADOCommand.CommandType;
mADODataSet.Parameters := mADOCommand.Parameters;
mADODataSet.Open;
end;
if bNextRecordSet then
mAdoDataSet.Recordset := mAdoDataSet.NextRecordset(i);
result := mADODataSet;
except on e: Exception do
raise Exception.Create(e.Message);
end;
end;
procedure TDA.ApplyUpdate(datasetProvider: TDataSetProvider;
delta: OleVariant; var sErrorMsg: widestring);
var
iErrorCount: integer;
begin
datasetProvider.OnUpdateError := DatasetProviderUpdateError;
try
datasetProvider.ApplyUpdates(delta, 0, iErrorCount);
finally
sErrorMsg := mErrorMessage
end;
end;
procedure TDA.ApplyUpdate(datasetProvider: TDataSetProvider;
delta: OleVariant; sql: Widestring; connection: TADOConnection;
var sErrorMsg: widestring);
var
tempAdoQuery: TAdoQuery;
begin
tempAdoQuery := TADOQuery.Create(nil);
tempAdoQuery.SQL.Add(sql);
tempAdoQuery.Connection := connection;
connection.DefaultDatabase :=GetDefaultDatabase(sql);
datasetProvider.DataSet := tempAdoQuery;
ApplyUpdate(datasetProvider, delta, sErrorMsg);
connection.DefaultDatabase :=GetoldDefaultDatabase(connection.ConnectionString);
end;
procedure TDA.ApplyUpdate(datasetProvider: TDataSetProvider;
delta: OleVariant; sql,sKeyField: Widestring;
connection: TADOConnection; var sErrorMsg: widestring);
var
i:integer;
tempAdoQuery: TAdoQuery;
KeyFieldLst:TStringList;
begin
try
tempAdoQuery := TADOQuery.Create(nil);
datasetprovider.UpdateMode:=upWhereKeyOnly; //upWhereChanged;
tempAdoQuery.SQL.Add(sql);
tempAdoQuery.Connection := connection;
connection.DefaultDatabase :=GetDefaultDatabase(sql);
datasetProvider.DataSet := tempAdoQuery;
//sKeyField为字段列表,字段之间以','分隔,如'PPO_NO,GF_NO'
KeyFieldLst:=TStringList.create;
sKeyField:=stringreplace(sKeyField,',',#13,[rfReplaceAll]);
KeyFieldLst.Text:=sKeyField;
//设置作为更新记录的KEY字段
tempAdoQuery.Open;
For i:=0 to KeyFieldLst.Count-1 do
tempAdoQuery.FieldByName(KeyFieldLst.Strings[i]).ProviderFlags := [pfInUpdate, pfInWhere, pfInKey];
ApplyUpdate(datasetProvider, delta, sErrorMsg);
connection.DefaultDatabase :=GetoldDefaultDatabase(connection.ConnectionString);
finally
datasetprovider.UpdateMode:=upWhereAll;
FreeAndNil(tempAdoQuery);
FreeAndNil(KeyFieldLst);
end;
end;
function TDA.GetDefaultDatabase(sqlText: String): String;
var
i:integer;
tempChar,dbname,tmpSql:string;
begin
sqlText:=Uppercase(sqlText);
i:=pos('..',sqlText);
if i=0 then
i:=pos('.DBO.',sqlText);
if i=0 then
dbname:='';
if i>0 then
begin
tmpSql:=copy(sqlText,0,i-1);
dbname:='';
i:=length(tmpSql);
while (i>=1) do
begin
tempChar:=copy(tmpSql,i,1);
i:=i-1;
if tempChar<>' ' then
dbname:=tempChar+dbname
else
break;
end;
end;
result:=dbname;
end;
function TDA.GetOldDefaultDatabase(connectionString: string): String;
var i,j:integer;
begin
i:=pos('Initial Catalog=',connectionString);
j:=pos(';Data Source=',connectionString);
result:=copy(connectionString,i+16,j-i-16);
end;
procedure TDA.DatasetProviderUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
mErrorMessage := '';
if e.ErrorCode <> 0 then
begin
mErrorMessage := 'Error Code: ' + inttostr(e.ErrorCode) + #10 + #13 + 'Description: ' + e.Message;
end
end;
//***********************下面是所有属性设置******************************//
function TDA.GetCommandText: string;
begin
// TODO -cMM: TDA.GetName default body inserted
Result := mADOCommand.CommandText;
end;
procedure TDA.SetCommandText(const Value: string);
begin
// TODO -cMM: TDA.SetName default body inserted
mADOCommand.CommandText := Value;
end;
function TDA.GetCommand: TADOCommand;
begin
// TODO -cMM: TDA.GetCommand default body inserted
Result := mADOCommand;
end;
function TDA.GetConnection: TADOConnection;
begin
// TODO -cMM: TDA.GetConnection default body inserted
Result := mADOCommand.Connection;
end;
procedure TDA.SetConnection(Value: TADOConnection);
begin
// TODO -cMM: TDA.SetConnection default body inserted
mADOCommand.Connection := value;
end;
function TDA.GetParameters: TParameters;
begin
// TODO -cMM: TDA.GetParameters default body inserted
Result := mADOCommand.Parameters;
end;
function TDA.GetTimeOut: Integer;
begin
// TODO -cMM: TDA.GetTimeOut default body inserted
Result := mADOCommand.CommandTimeout;
end;
procedure TDA.SetTimeOut(Value: Integer);
begin
// TODO -cMM: TDA.SetTimeOut default body inserted
mADOCommand.CommandTimeout := Value;
end;
function TDA.GetCommandType: TCommandType;
begin
result := mADOCommand.CommandType;
end;
procedure TDA.SetCommandType(const Value: TCommandType);
begin
mADOCommand.CommandType := value;
end;
//获取参数值
function TDA.GetParameterValue(parameterName: string): variant;
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
result := mParameter.Value;
end;
procedure TDA.SetParameterValue(parameterName: string;
parameterValue: variant);
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
mParameter.Value := parameterValue;
end;
function TDA.GetParameterDirection(
parameterName: string): TParameterDirection;
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
result := mParameter.Direction;
end;
procedure TDA.SetParameterDirection(parameterName: string;
parameterDirection: TParameterDirection);
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
mParameter.Direction := parameterDirection;
end;
function TDA.GetParameterType(
parameterName: string): TFieldType;
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
result := mParameter.DataType;
end;
procedure TDA.SetParameterType(parameterName: string;
parameterType: TFieldType);
var mParameter: TParameter;
begin
mParameter := mADOCommand.Parameters.FindParam(parameterName);
if mParameter = nil then
raise Exception.Create('Parameter:' + parameterName + ' not found!')
else
mParameter.DataType := parameterType;
end;
function TDA.GetConnectionError(adoConnection: TADOConnection): string;
var
sErrorMsg:widestring;
i:integer;
begin
sErrorMsg:='';
if adoConnection.Errors.Count >0 then
begin
for i:=0 to adoConnection.Errors.Count-1 Do
sErrorMsg:=sErrorMsg+adoConnection.Errors[i].Description +#13;
end;
result:=sErrorMsg;
end;
{
--------------------------------------------------------------------------------
使用方法举例:
1)返回记录集 或 数据集
procedure TForm1.Button1Click(Sender: TObject);
var cdb :TDA;
sqlText:string;
mAdoQuery:TADOQuery;
begin
mAdoQuery:=TADOQuery.create(nil);
sqlText:='usp_StroProcName';
cdb:=TDA.Create(sqlText,cmdStoredProc,adoConnection1);
//也可以这样创建
// cdb:=TDA.Create();
// cdb.CommandText:=sqlTest;
// cdb.CommandType:=cmdStoredProc;
// cdb.Connection:=adoConnection1;
cdb.AddParameter('@parameter1',ftString,edit1.text,pdInput);
cdb.AddParameter('@parameter2',ftInteger,4,pdInput);
cdb.AddParameter('@parameter3',ftString,'',pdOutput);
mAdoQuery.recordset:=cdb.Execute; //获取记录集
datasoruce1.dataset:=cdb.DataSet; //返回数据集
datasetProvider.dataset:=cdb.DataSet; //DatasetProvider.dataset
//获取参数值值
edit2.text:=cdb.GetParameterValue('@parameter3');
end;
2)返回字段值
procedure TForm1.Button1Click(Sender: TObject);
var cdb :DA;
sqlText:string;
begin
sqlText:='select fname from employee where emp_id=:emp_id'; //可以是存储过程
cdb:=TDA.Create(sqlText,cmdText,adoConnection1);
cdb.AddParameter('emp_id',ftString,edit1.text,pdInput);
edit1.text:=cdb.executescalar;
cdb.CommandText:='select currtime=Getdate()';
edit2.text:=cdb.executescalar;
end;
3) 执行sql语句
procedure TForm1.Button1Click(Sender: TObject);
var cdb :TDA;
sqlText:string;
begin
sqlText:='delete from employee where emp_id=:emp_id'; //可以是存储过程
cdb:=TDA.Create(sqlText,cmdText,adoConnection1);
cdb.AddParameter('emp_id',ftString,edit1.text,pdInput);
cdb.executenonquery;
//下面通过替换参数值,执行sql语句的方法,可以在循环当中根据参数值多次调用执行 如下:
cdb.SetParameterValue('emp_id','A'); //替换参数值
cdb.executenonquery;
end;
4) 中间层datasetProvider applyupdate 方法
//如果在设计的时候DataSetProvider 已经邦定了一个dataset ,并且没有改变那么可以如
//下面一样直接调用该方法
procedure TDataAccess.SaveData(vData: OleVariant;
var sErrorMsg: WideString);
var
sqlText:string;
cdb:TDA;
begin
//datasetProvider 已经提供dataset
cdb:=TDA.Create();
try
cdb.ApplyUpdate(datasetProvider,vData,sErrorMsg);
except
raise;
end;
end;
//如果在设计时候datasetprovider有邦定dataset ,或动态创建的datasetprovider 等可以用
//下面方法调用
procedure TDataAccess.SaveData(vData: OleVariant;
var sErrorMsg: WideString);
var
sqlText:string;
cdb:TDA;
begin
//datasetProvider 还没有提供dataset
sqlText:='SELECT * from employee where 1=2';
cdb:=TDA.Create();
try
cdb.ApplyUpdate(datasetProvider,vData,sqlText,adoConnection,sErrorMsg);
except
raise;
end;
end;
}
end.
|
unit TestUItensLeituraGasVO;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, SysUtils, Atributos, UUnidadeVO, Generics.Collections, UGenericVO,
Classes, Constantes, UItensLeituraGasVO;
type
// Test methods for class TItensLeituraGasVO
TestTItensLeituraGasVO = class(TTestCase)
strict private
FItensLeituraGasVO: TItensLeituraGasVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCamposObrigatorios;
procedure TestValidarCamposObrigatoriosNaoEncontrado;
end;
implementation
procedure TestTItensLeituraGasVO.SetUp;
begin
FItensLeituraGasVO := TItensLeituraGasVO.Create;
end;
procedure TestTItensLeituraGasVO.TearDown;
begin
FItensLeituraGasVO.Free;
FItensLeituraGasVO := nil;
end;
procedure TestTItensLeituraGasVO.TestValidarCamposObrigatorios;
var
Leitura : TItensLeituraGasVO;
begin
Leitura := TItensLeituraGasVO.Create;
Leitura.dtLeitura := StrToDate('01/01/2016');
Leitura.vlMedido := 1;
try
Leitura.ValidarCamposObrigatorios;
Check(True,'Sucesso!')
except on E: Exception do
Check(false,'Erro!');
end;
end;
procedure TestTItensLeituraGasVO.TestValidarCamposObrigatoriosNaoEncontrado;
var
Leitura : TItensLeituraGasVO;
begin
Leitura := TItensLeituraGasVO.Create;
Leitura.dtLeitura := StrToDate('01/01/2016');
Leitura.vlMedido := -1;
try
Leitura.ValidarCamposObrigatorios;
Check(false,'Erro!')
except on E: Exception do
Check(true,'Sucesso!');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTItensLeituraGasVO.Suite);
end.
|
function printline(val:integer):string;
begin
writeln(val,' -> (', val mod 3,', ', val mod 5,', ', val mod 7,', ', val mod 11,')');
end;
procedure printall(val:string);
var a,b,c:integer;
a3,b3,c3,
a5,b5,c5,
a7,b7,c7,
a11,b11,c11:integer;
begin
a := System.Convert.ToInt32(val[1].ToString());
b := System.Convert.ToInt32(val[2].ToString());
c := System.Convert.ToInt32(val[3].ToString());
a3 := a mod 3;
b3 := b mod 3;
c3 := c mod 3;
a5 := a mod 5;
b5 := b mod 5;
c5 := c mod 5;
a7 := a mod 7;
b7 := b mod 7;
c7 := c mod 7;
a11 := a mod 11;
b11 := b mod 11;
c11 := c mod 11;
printline(a);
printline(b);
printline(c);
writeln();
var tmp:integer:=(a3+b3+c3) mod 3;
writeln(Format('a1 = r3(1*{0} + 1*{1} + 1*{2}) = {3} ',a3,b3,c3,tmp));
tmp:= c5 mod 5;
writeln(Format('a1 = r5(0*{0} + 0*{1} + 1*{2}) = {3} ',a5,b5,c5,tmp));
tmp:= (2*a7+3*b7+c7) mod 7;
writeln(Format('a1 = r7(2*{0} + 3*{1} + 1*{2}) = {3} ',a7,b7,c7,tmp));
tmp:= (a11+10*b11+c11) mod 11;
writeln(Format('a1 =r11(1*{0} +10*{1} + 1*{2}) = {3} ',a11,b11,c11,tmp));
end;
begin
printall('208');
end. |
program FindAllSolutions;
uses
SysUtils;
var
a, b, c, x, y: Integer; // correspond to values in ax + by = c
Solutions: Boolean = False;
begin
Writeln('Please enter the values for a, b and c in ax + by = c:');
Write('a = ');
Readln(a);
Write('b = ');
Readln(b);
Write('c = ');
Readln(c);
Writeln('===========================================================');
Writeln('Equation: ', a, 'x + ', b, 'y = ', c);
Writeln('===========================================================');
Writeln('Solutions: ');
y := 1;
// Start at one because solutions must be positive integers.
while y < c do
// Because solutions to x and y must be positive
// neither can be greater than c.
begin
x := 1; // same reason as y
while x < c do // again, same reason as y
begin
if ((a * x) + (b * y)) = c then // ax + by = c ?
begin
if not Solutions then
Solutions := True;
Writeln('x = ', x,', y = ', y);
end;
x := x + 1;
end;
y := y + 1;
end;
if not Solutions then
Writeln('No solutions were found.');
Readln
end.
|
unit NewFrontiers.Configuration.Registry;
interface
uses NewFrontiers.Configuration, Registry, Windows;
type
TConfigurationRegistry = class(TInterfacedObject, IConfiguration)
protected
_rootKey: HKEY;
_baseKey: string;
_registry: TRegistry;
procedure openRegistry(aWriteAccess: boolean);
procedure closeRegistry;
public
/// <summary>
/// Root-Schlüssel, der verwendet wird. Üblicherweise HKEY_CURRENT_USER
/// </summary>
property RootKey: HKEY read _rootKey write _rootKey;
/// <summary>
/// Basis-Schlüssel, der geöffnet wird. z.B. Software\ASS\Optima
/// </summary>
property BaseKey: string read _baseKey write _baseKey;
function getString(aName: string; aDefault: string = ''): string;
function getInteger(aName: string; aDefault: integer = 0): integer;
function getBoolean(aName: string; aDefault: boolean = false): boolean;
function getDateTime(aName: string; aDefault: TDateTime = 0): TDateTime;
function setString(aName, aValue: string): boolean;
function setInteger(aName: string; aValue: integer): boolean;
function setBoolean(aName: string; aValue: boolean): boolean;
function setDateTime(aName: string; aValue: TDateTime): boolean;
end;
implementation
uses SysUtils, NewFrontiers.Utility.StringUtil;
procedure TConfigurationRegistry.closeRegistry;
begin
_registry.CloseKey;
freeAndNil(_registry);
end;
function TConfigurationRegistry.getBoolean(aName: string;
aDefault: boolean): boolean;
var Ident, Section: string;
begin
openRegistry(false);
TStringUtil.StringParts(aName, '.', Section, Ident);
if (_registry.ValueExists(Section + '\' + Ident)) then
result := _registry.ReadBool(Section + '\' + Ident)
else
result := aDefault;
closeRegistry;
end;
function TConfigurationRegistry.getDateTime(aName: string;
aDefault: TDateTime): TDateTime;
var Ident, Section: string;
begin
openRegistry(false);
TStringUtil.StringParts(aName, '.', Section, Ident);
if (_registry.ValueExists(Section + '\' + Ident)) then
result := _registry.ReadDateTime(Section + '\' + Ident)
else
result := aDefault;
closeRegistry;
end;
function TConfigurationRegistry.getInteger(aName: string;
aDefault: integer): integer;
var Ident, Section: string;
begin
openRegistry(false);
TStringUtil.StringParts(aName, '.', Section, Ident);
if (_registry.ValueExists(Section + '\' + Ident)) then
result := _registry.ReadInteger(Section + '\' + Ident)
else
result := aDefault;
closeRegistry;
end;
function TConfigurationRegistry.getString(aName, aDefault: string): string;
var Ident, Section: string;
begin
openRegistry(false);
TStringUtil.StringParts(aName, '.', Section, Ident);
if (_registry.ValueExists(Section + '\' + Ident)) then
result := _registry.ReadString(Section + '\' + Ident)
else
result := aDefault;
closeRegistry;
end;
procedure TConfigurationRegistry.openRegistry(aWriteAccess: boolean);
begin
_registry := TRegistry.Create;
_registry.RootKey := _rootKey;
if (not aWriteAccess) then
_registry.OpenKeyReadOnly(_baseKey)
else
_registry.OpenKey(_baseKey, true);
end;
function TConfigurationRegistry.setBoolean(aName: string;
aValue: boolean): boolean;
var Ident, Section: string;
begin
result := true;
openRegistry(true);
TStringUtil.StringParts(aName, '.', Section, Ident);
_registry.WriteBool(Section + '\' + Ident, aValue);
closeRegistry;
end;
function TConfigurationRegistry.setDateTime(aName: string;
aValue: TDateTime): boolean;
var Ident, Section: string;
begin
result := true;
openRegistry(true);
TStringUtil.StringParts(aName, '.', Section, Ident);
_registry.WriteDateTime(Section + '\' + Ident, aValue);
closeRegistry;
end;
function TConfigurationRegistry.setInteger(aName: string;
aValue: integer): boolean;
var Ident, Section: string;
begin
result := true;
openRegistry(true);
TStringUtil.StringParts(aName, '.', Section, Ident);
_registry.WriteInteger(Section + '\' + Ident, aValue);
closeRegistry;
end;
function TConfigurationRegistry.setString(aName, aValue: string): boolean;
var Ident, Section: string;
begin
result := true;
openRegistry(true);
TStringUtil.StringParts(aName, '.', Section, Ident);
_registry.WriteString(Section + '\' + Ident, aValue);
closeRegistry;
end;
end.
|
namespace LocalXMLDataStore;
interface
type
Program = public static class
public
class method Main;
end;
implementation
uses
System.Windows.Forms;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
class method Program.Main;
begin
try
Application.EnableVisualStyles();
Application.Run(new MainForm());
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
end. |
unit URepositorioFilial;
interface
uses
UFilial,
UEntidade,
URepositorioDB,
URepositorioEmpresaMatriz,
URepositorioPais,
URepositorioEstado,
URepositorioCidade,
UPais,
UEstado,
UCidade,
UEmpresaMatriz,
SqlExpr
;
type
TRepositorioFilial = class (TRepositorioDB<TFilial>)
private
FRepositorioEmpresa : TRepositorioEmpresa;
FRepositorioCidade : TRepositorioCidade;
FRepositorioEstado : TRepositorioEstado;
FRepositorioPais : TRepositorioPais;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade (const coFilial : TFILIAL); override;
procedure AtribuiEntidadeParaDB (const coFilial : TFILIAL;
const coSQlQuery : TSQLQuery); override;
end;
implementation
uses
UDM,
SysUtils
;
{ TRepositorioFilial }
procedure TRepositorioFilial.AtribuiDBParaEntidade(const coFilial: TFILIAL);
begin
inherited;
with FSQLSelect do
begin
coFilial.NOME := FieldByName(FLD_FILIAL_NOME).Asstring;
coFilial.CNPJ := FieldByName(FLD_FILIAL_CNPJ).AsString;
coFilial.IE := FieldByName(FLD_FILIAL_IE).AsInteger;
coFilial.TELEFONE := FieldByName(FLD_FILIAL_TELEFONE).AsString;
coFilial.LOGRADOURO := FieldByName(FLD_FILIAL_LOGRADOURO).AsString;
coFilial.NUMERO := FieldByName(FLD_FILIAL_NUMERO).AsInteger;
coFilial.BAIRRO := FieldByName(FLD_FILIAL_BAIRR0).AsString;
coFilial.CIDADE := TCIDADE(
FRepositorioCidade.Retorna (FieldByName (FLD_FILIAL_CIDADE).AsInteger));
coFilial.EMPRESA := TEmpresa(
FRepositorioEmpresa.Retorna(FieldByname(FLD_FILIAL_EMPRESA).Asinteger));
end;
end;
procedure TRepositorioFilial.AtribuiEntidadeParaDB(const coFilial: TFILIAL;
const coSQlQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_FILIAL_NOME).AsString := coFilial.NOME;
ParamByName(FLD_FILIAL_CNPJ).AsString := coFilial.CNPJ;
ParamByName(FLD_FILIAL_IE).AsInteger := coFilial.IE;
ParamByName(FLD_FILIAL_TELEFONE).AsString := coFilial.TELEFONE;
ParamByName(FLD_FILIAL_LOGRADOURO).AsString := coFilial.LOGRADOURO;
ParamByName(FLD_FILIAL_NUMERO).AsInteger := coFilial.NUMERO;
ParamByName(FLD_FILIAL_BAIRR0).AsString := coFilial.BAIRRO;
ParamByName(FLD_FILIAL_CIDADE).AsInteger := coFilial.CIDADE.ID;
ParamByName(FLD_FILIAL_EMPRESA).AsInteger := coFilial.EMPRESA.ID;
end;
end;
constructor TRepositorioFilial.Create;
begin
inherited Create (TFILIAL, TBL_FILIAL, FLD_ENTIDADE_ID, STR_EMPRESAMATRIZ);
FRepositorioCidade := TRepositorioCidade.Create;
FRepositorioEstado := TRepositorioEstado.Create;
FRepositorioPais := TRepositorioPais.Create;
FRepositorioEmpresa := TRepositorioEmpresa.Create;
end;
destructor TRepositorioFilial.Destroy;
begin
FreeAndNil(FRepositorioCidade);
FreeAndNil(FRepositorioEstado);
FreeAndNil(FRepositorioPais);
FreeAndNil(FRepositorioEmpresa);
inherited;
end;
end.
|
unit CCJSO_AutoDialEdit;
{
© PgkSoft 29.06.2016
Журнал регистрации автодозвонов
Регистрационная карточка
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
CCJSO_AutoDial, StdCtrls, ExtCtrls, ActnList;
type
TfrmCCJSO_AutoDialEdit = class(TForm)
pnlFields: TPanel;
lblSCreateDate: TLabel;
lblSFullOrder: TLabel;
lblSOrderDT: TLabel;
lblSPhone: TLabel;
lblSClient: TLabel;
lblSAutoDialType: TLabel;
lblICounter: TLabel;
lblSNameFileRoot: TLabel;
lblSAutoDialBegin: TLabel;
lblSAutoDialEnd: TLabel;
lblSAutoDialResult: TLabel;
lblSFileExists: TLabel;
lblNCheckCounter: TLabel;
lblSCheckDate: TLabel;
lblNRetryCounter: TLabel;
edCreateDate: TEdit;
edSFullOrder: TEdit;
edSOrderDT: TEdit;
edSPhone: TEdit;
edSClient: TEdit;
edSAutoDialType: TEdit;
edICounter: TEdit;
edSNameFileRoot: TEdit;
edSAutoDialBegin: TEdit;
edSAutoDialEnd: TEdit;
edSAutoDialResult: TEdit;
edSFileExists: TEdit;
edNCheckCounter: TEdit;
edSCheckDate: TEdit;
edNRetryCounter: TEdit;
aList: TActionList;
aExit: TAction;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aExitExecute(Sender: TObject);
private
{ Private declarations }
ISignActive : boolean;
RecItem : TJSOAutoDial_Item;
procedure ShowGets;
public
{ Public declarations }
procedure SetRecItem(Parm : TJSOAutoDial_Item);
end;
var
frmCCJSO_AutoDialEdit: TfrmCCJSO_AutoDialEdit;
implementation
uses UCCenterJournalNetZkz;
{$R *.dfm}
procedure TfrmCCJSO_AutoDialEdit.FormCreate(Sender: TObject);
begin
ISignActive := false;
end;
procedure TfrmCCJSO_AutoDialEdit.FormActivate(Sender: TObject);
begin
if not ISignActive then begin
{ Иконка формы }
FCCenterJournalNetZkz.imgMain.GetIcon(370,self.Icon);
{ Инициализация }
edCreateDate.Text := RecItem.SCreateDate;
edSFullOrder.Text := RecItem.SFullOrder;
edSOrderDT.Text := RecItem.SOrderDT;
edSPhone.Text := RecItem.SPhone;
edSClient.Text := RecItem.SClient;
edSAutoDialType.Text := RecItem.SAutoDialType;
edICounter.Text := VarToStr(RecItem.ICounter);
edSNameFileRoot.Text := RecItem.SNameFileRoot;
edSAutoDialBegin.Text := RecItem.SAutoDialBegin;
edSAutoDialEnd.Text := RecItem.SAutoDialEnd;
edSAutoDialResult.Text := RecItem.SAutoDialResult;
edSFileExists.Text := RecItem.SFileExists;
edNCheckCounter.Text := VarToStr(RecItem.NCheckCounter);
edSCheckDate.Text := RecItem.SCheckDate;
edNRetryCounter.Text := VarToStr(RecItem.NRetryCounter);
{ Форма активна }
ISignActive := true;
ShowGets;
end;
end;
procedure TfrmCCJSO_AutoDialEdit.ShowGets;
begin
if ISignActive then begin
end;
end;
procedure TfrmCCJSO_AutoDialEdit.SetRecItem(Parm : TJSOAutoDial_Item); begin RecItem := Parm; end;
procedure TfrmCCJSO_AutoDialEdit.aExitExecute(Sender: TObject);
begin
Self.Close;
end;
end.
|
unit UDFieldMapping;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeFieldMappingDlg = class(TForm)
pnlMapFields: TPanel;
lbReportFields: TListBox;
lblUnmappedFields: TLabel;
cbDatabaseFields: TComboBox;
lblDatabaseFields: TLabel;
btnMap: TButton;
btnOk: TButton;
btnCancel: TButton;
editFieldType: TEdit;
lblFieldType: TLabel;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lbReportFieldsClick(Sender: TObject);
procedure btnMapClick(Sender: TObject);
procedure cbDatabaseFieldsChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ReportFields1 : TList;
DataBaseFields1 : TList;
end;
var
CrpeFieldMappingDlg: TCrpeFieldMappingDlg;
RptFields : TCrFieldMappingInfo;
DBFields : TCrFieldMappingInfo;
slRptFields : TStringList;
slDBFields : TStringList;
implementation
{$R *.DFM}
uses TypInfo, UCrpeUtl, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.FormShow(Sender: TObject);
var
cnt: integer;
begin
slRptFields := TStringList.Create;
slDBFields := TStringList.Create;
for cnt := 0 to ReportFields1.Count - 1 do
begin
RptFields := TCrFieldMappingInfo(ReportFields1[cnt]);
if RptFields.MapTo = -1 then
begin
slRptFields.Add(RptFields.TableName + '.' + RptFields.FieldName);
slRptFields.Objects[slRptFields.Count - 1] := ReportFields1[cnt];
end;
end;
lbReportFields.Items.AddStrings(slRptFields);
for cnt := 0 to DatabaseFields1.Count - 1 do
begin
DBFields := TCrFieldMappingInfo(DatabaseFields1[cnt]);
if DBFields.MapTo = -1 then
begin
slDBFields.Add(DBFields.TableName + '.' + DBFields.FieldName);
slDBFields.Objects[slDBFields.Count - 1] := DatabaseFields1[cnt];
DBFields.MapTo := cnt;
end;
end;
cbDatabaseFields.Items.AddStrings(slDBFields);
btnMap.Enabled := False;
lbReportFields.ItemIndex := 0;
lbReportFieldsClick(lbReportFields);
end;
{------------------------------------------------------------------------------}
{ lbReportFieldsClick }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.lbReportFieldsClick(Sender: TObject);
begin
RptFields := TCrFieldMappingInfo(slRptFields.Objects[lbReportFields.ItemIndex]);
editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType),
Ord(RptFields.FieldType));
end;
{------------------------------------------------------------------------------}
{ btnMapClick }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.btnMapClick(Sender: TObject);
begin
if (lbReportFields.ItemIndex > -1) and
(cbDatabaseFields.ItemIndex > -1) then
begin
{Assign the pointers}
RptFields := TCrFieldMappingInfo(slRptFields.Objects[lbReportFields.ItemIndex]);
DBFields := TCrFieldMappingInfo(slDBFields.Objects[cbDatabaseFields.ItemIndex]);
{Set the MapTo number to the Database field item number}
RptFields.MapTo := DBFields.MapTo;
{Delete the two fields from the listbox and combobox}
lbReportFields.Items.Delete(lbReportFields.ItemIndex);
cbDatabaseFields.Items.Delete(cbDatabaseFields.ItemIndex);
end;
btnMap.Enabled := (lbReportFields.Items.Count > 0);
btnMap.Enabled := (cbDatabaseFields.ItemIndex > -1);
end;
{------------------------------------------------------------------------------}
{ cbDatabaseFieldsChange }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.cbDatabaseFieldsChange(Sender: TObject);
begin
btnMap.Enabled := (cbDatabaseFields.ItemIndex > -1);
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeFieldMappingDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
slRptFields.Free;
slDBFields.Free;
Release;
end;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots.Communications;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
System.Diagnostics;
type
MessageEventArgs = assembly class(EventArgs)
private
var _message: Message;
assembly or protected
constructor(Message: Message);
property Message: Message read get_Message;
method get_Message: Message;
end;
MessageHandler = assembly class
private
var _connection: UT3Connection;
var _messageQueue: Queue<Message>;
method _connection_OnErrorOccurred(sender: Object; e: TcpErrorEventArgs);
assembly
method Disconnect();
private
method ErrorOccurred(sender: Object; e: TcpErrorEventArgs);
method DataReceived(sender: Object; e: TcpDataEventArgs);
assembly
//Constructor
constructor(Server: String; Port: Integer);
property Connection: UT3Connection read get_Connection;
method get_Connection: UT3Connection;
property MessageQueue: Queue<Message> read get_MessageQueue;
method get_MessageQueue: Queue<Message>;
event OnEventReceived: EventHandler<MessageEventArgs>;
end;
implementation
constructor MessageEventArgs(Message: Message);
begin
Self._message := Message
end;
method MessageEventArgs.get_Message: Message;
begin
Result := Self._message
end;
method MessageHandler.Disconnect();
begin
Self._connection.Disconnect()
end;
method MessageHandler.ErrorOccurred(sender: Object; e: TcpErrorEventArgs);
begin
Self.Disconnect()
end;
method MessageHandler.DataReceived(sender: Object; e: TcpDataEventArgs);
begin
var newMessages: List<Message> := Message.FromData(System.Text.UTF8Encoding.UTF8.GetString(e.Data, 0, e.Data.Length));
locking Self._messageQueue do
begin
for each m: Message in newMessages do
begin
if (m.IsEvent and (Self.OnEventReceived <> nil)) then
begin
OnEventReceived.Invoke(Self, new MessageEventArgs(m))
end
else
begin
Self._messageQueue.Enqueue(m)
end
end
end
end;
constructor MessageHandler(Server: String; Port: Integer);
begin
Self._messageQueue := new Queue<Message>();
Self._connection := new UT3Connection(Server, Port);
Self._connection.OnDataReceived += @Self.DataReceived;
Self._connection.OnErrorOccurred += @Self.ErrorOccurred;
//Self._connection.OnDataReceived := Self._connection.OnDataReceived + new EventHandler<TcpDataEventArgs>(DataReceived);
//Self._connection.OnErrorOccurred := Self._connection.OnErrorOccurred + new EventHandler<TcpErrorEventArgs>(ErrorOccurred)
end;
method MessageHandler.get_Connection: UT3Connection;
begin
Result := Self._connection
end;
method MessageHandler.get_MessageQueue: Queue<Message>;
begin
Result := Self._messageQueue
end;
method MessageHandler._connection_OnErrorOccurred(sender: Object; e: TcpErrorEventArgs);
begin
end;
end.
|
var
i: integer;
begin
for i := 1 to 10 do
writeln('Git is good');
end.
|
unit CashFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzButton, StdCtrls, Mask, RzEdit, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
cxTextEdit, cxCurrencyEdit, RzLabel;
type
TfrmCash = class(TForm)
blAllContainer: TBevel;
btnClose: TRzBitBtn;
btnOK: TRzBitBtn;
lbNet: TLabel;
lbInterest: TLabel;
lbAmount: TLabel;
edAmount: TcxCurrencyEdit;
lbChange: TLabel;
RzLabel5: TRzLabel;
RzLabel1: TRzLabel;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
RzLabel4: TRzLabel;
procedure btnCloseClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edAmountKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
private
FIsOK: boolean;
FCurrAmount: currency;
FPayAmount: currency;
FPayNet: currency;
FPayVat: currency;
FChagngeAmt: currency;
FReceiveAmt: currency;
FReceiveNet: currency;
procedure SetIsOK(const Value: boolean);
procedure SetCurrAmount(const Value: currency);
procedure SetPayAmount(const Value: currency);
procedure SetPayNet(const Value: currency);
procedure SetPayVat(const Value: currency);
procedure SetChagngeAmt(const Value: currency);
procedure SetReceiveAmt(const Value: currency);
procedure SetReceiveNet(const Value: currency);
{ Private declarations }
public
{ Public declarations }
FAllowCash : boolean;
property IsOK: boolean read FIsOK write SetIsOK;
property CurrAmount : currency read FCurrAmount write SetCurrAmount;
property PayAmount : currency read FPayAmount write SetPayAmount;
property PayVat : currency read FPayVat write SetPayVat;
property PayNet :currency read FPayNet write SetPayNet;
property ChagngeAmt : currency read FChagngeAmt write SetChagngeAmt;
property ReceiveAmt : currency read FReceiveAmt write SetReceiveAmt;
property ReceiveNet : currency read FReceiveNet write SetReceiveNet;
end;
var
frmCash: TfrmCash;
implementation
uses Math, CommonLIB;
{$R *.dfm}
procedure TfrmCash.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmCash.SetIsOK(const Value: boolean);
begin
FIsOK := Value;
end;
procedure TfrmCash.btnOKClick(Sender: TObject);
begin
if not btnOK.Enabled then Exit;
IsOK :=true;
Close;
end;
procedure TfrmCash.FormShow(Sender: TObject);
begin
IsOK := false;
btnOK.Enabled := false;
edAmount.SetFocus;
end;
procedure TfrmCash.SetCurrAmount(const Value: currency);
begin
FCurrAmount := Value;
end;
procedure TfrmCash.SetPayAmount(const Value: currency);
begin
FPayAmount := Value;
lbAmount.Caption := FormatCurr('#,##0.00',Value)+' ';
end;
procedure TfrmCash.SetPayNet(const Value: currency);
begin
FPayNet := Value;
lbNet.Caption := FormatCurr('#,##0.00',Value)+' ';
end;
procedure TfrmCash.SetPayVat(const Value: currency);
begin
FPayVat := Value;
lbInterest.Caption := FormatCurr('#,##0.00',Value)+' ';
end;
procedure TfrmCash.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_ESCAPE then btnCloseClick(nil);
if Key=VK_F11 then btnOKClick(nil);
end;
procedure TfrmCash.edAmountKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key =VK_RETURN then
begin
ReceiveAmt := edAmount.Value;
ChagngeAmt := ReceiveAmt - PayNet;
if ChagngeAmt>=0 then
begin
FAllowCash := true;
btnOK.Enabled:=true;
end else
begin
FAllowCash:= false;
btnOK.Enabled := false;
end;
end;
end;
procedure TfrmCash.SetChagngeAmt(const Value: currency);
begin
FChagngeAmt := Value;
lbChange.Caption:= FormatCurr('#,###.00',ChagngeAmt)
end;
procedure TfrmCash.SetReceiveAmt(const Value: currency);
begin
FReceiveAmt := Value;
end;
procedure TfrmCash.SetReceiveNet(const Value: currency);
begin
FReceiveNet := Value;
end;
procedure TfrmCash.FormCreate(Sender: TObject);
begin
FAllowCash := false;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Repository.Base;
interface
uses
Generics.Defaults,
VSoft.Awaitable,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Sources.Types,
DPM.Core.Dependency.Version,
DPM.Core.Logging,
DPM.Core.Options.Search,
DPM.Core.Package.Interfaces,
DPM.Core.Configuration.Interfaces,
DPM.Core.Repository.Interfaces;
type
TBaseRepository = class(TInterfacedObject)
private
FLogger : ILogger;
FName : string;
FSourceUri : string;
FUserName : string;
FPassword : string;
FRepositoryType : TSourceType;
FEnabled : boolean;
protected
//IPackageRepository;
function GetRepositoryType : TSourceType;
function GetName : string;
function GetSource : string;
procedure Configure(const source : ISourceConfig); virtual;
function GetEnabled : boolean;
procedure SetEnabled(const value : boolean);
//exposing these for descendants
property Logger : ILogger read FLogger;
property Name : string read FName;
property SourceUri : string read FSourceUri;
property UserName : string read FUserName;
property Password : string read FPassword;
property RepositoryType : TSourceType read GetRepositoryType;
public
constructor Create(const logger : ILogger); virtual;
end;
implementation
{ TBaseRepository }
constructor TBaseRepository.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TBaseRepository.GetEnabled: boolean;
begin
result := FEnabled;
end;
function TBaseRepository.GetName : string;
begin
result := FName;
end;
function TBaseRepository.GetRepositoryType : TSourceType;
begin
result := FRepositoryType;
end;
function TBaseRepository.GetSource : string;
begin
result := FSourceUri;
end;
procedure TBaseRepository.SetEnabled(const value: boolean);
begin
FEnabled := value;
end;
procedure TBaseRepository.Configure(const source : ISourceConfig);
begin
FName := source.Name;
FSourceUri := source.Source;
FUserName := source.UserName;
FPassword := source.Password;
FRepositoryType := source.SourceType;
FEnabled := source.IsEnabled;
end;
end.
|
unit OthelloCounterSet;
interface
uses FMX.Objects3D, System.Classes, OthelloCounters, FMX.MaterialSources, System.SysUtils;
type
TOthelloCounterSet = class(TDummy)
private
GridSize: Integer;
TileSize: Single;
Counters: Array of Array of TOthelloCounter;
procedure CheckDirection(startX, startY, currentX, currentY, dirX,
dirY: Integer; startState: TOthelloState);
procedure FlipLine(startX, startY, endX, endY: Integer;
cState: TOthelloState);
public
CurrentTurn: TOthelloState;
constructor Create(aOwner: TComponent; aGridSize: Integer; aTileSize: Single;
aBlackMaterial, aWhiteMaterial : TMaterialSource);
destructor Destroy; override;
procedure AddCounter(i,j: Integer);
function GetScore(ScoreState: TOthelloState): Integer;
end;
implementation
constructor TOthelloCounterSet.Create(aOwner: TComponent; aGridSize: Integer; aTileSize: Single;
aBlackMaterial, aWhiteMaterial : TMaterialSource);
var
i: Integer;
j: Integer;
begin
inherited Create(aOwner);
GridSize := aGridSize;
TileSize := aTileSize;
//Create 2D array of counters
SetLength(Counters, GridSize, GridSize);
for i := 0 to High(Counters) do
for j := 0 to High(Counters) do
begin
Counters[i][j] := TOthelloCounter.Create(Self, TileSize, aBlackMaterial, aWhiteMaterial);
Counters[i][j].Parent := Self;
Counters[i][j].Position.X := TileSize * i;
Counters[i][j].Position.Y := TileSize * j;
Counters[i][j].Visible := False;
end;
//Show starting four counters
Counters[GridSize DIV 2][GridSize DIV 2].Visible := True;
Counters[-1+GridSize DIV 2][GridSize DIV 2].Visible := True;
Counters[GridSize DIV 2][-1+GridSize DIV 2].Visible := True;
Counters[-1+GridSize DIV 2][-1+GridSize DIV 2].Visible := True;
//Set the states of starting four counters
Counters[GridSize DIV 2][GridSize DIV 2].CounterState := TOthelloState.Black;
Counters[-1+GridSize DIV 2][GridSize DIV 2].CounterState := TOthelloState.White;
Counters[GridSize DIV 2][-1+GridSize DIV 2].CounterState := TOthelloState.White;
Counters[-1+GridSize DIV 2][-1+GridSize DIV 2].CounterState := TOthelloState.Black;
//Set who goes first
CurrentTurn := TOthelloState.Black;
end;
destructor TOthelloCounterSet.Destroy;
var
i: Integer;
j: Integer;
begin
for i := 0 to High(Counters) do
for j := 0 to High(Counters) do
begin
Counters[i][j].Free;
end;
SetLength(Counters,0,0);
inherited;
end;
procedure TOthelloCounterSet.AddCounter(i,j: Integer);
var
ValidPosition: Boolean;
begin
ValidPosition := False;
if i<High(Counters) then
if Counters[i+1][j].Visible = True then ValidPosition := True;
if i>0 then
if Counters[i-1][j].Visible = True then ValidPosition := True;
if j<High(Counters) then
if Counters[i][j+1].Visible = True then ValidPosition := True;
if j>0 then
if Counters[i][j-1].Visible = True then ValidPosition := True;
if (i<High(Counters)) AND (j<High(Counters)) then
if Counters[i+1][j+1].Visible = True then ValidPosition := True;
if (i>0) AND (j>0) then
if Counters[i-1][j-1].Visible = True then ValidPosition := True;
if (i<High(Counters)) AND (j>0) then
if Counters[i+1][j-1].Visible = True then ValidPosition := True;
if (i>0) AND (j<High(Counters)) then
if Counters[i-1][j+1].Visible = True then ValidPosition := True;
if ValidPosition = False then Exit;
Counters[i][j].CounterState := CurrentTurn;
Counters[i][j].Visible := True;
CheckDirection(i,j,i,j,1,0,CurrentTurn);
CheckDirection(i,j,i,j,-1,0,CurrentTurn);
CheckDirection(i,j,i,j,0,1,CurrentTurn);
CheckDirection(i,j,i,j,0,-1,CurrentTurn);
CheckDirection(i,j,i,j,1,1,CurrentTurn);
CheckDirection(i,j,i,j,-1,-1,CurrentTurn);
CheckDirection(i,j,i,j,1,-1,CurrentTurn);
CheckDirection(i,j,i,j,-1,1,CurrentTurn);
case CurrentTurn of
Black: CurrentTurn := White;
White: CurrentTurn := Black;
end;
end;
procedure TOthelloCounterSet.CheckDirection(startX,startY,currentX,currentY, dirX, dirY: Integer; startState : TOthelloState);
var
i: Integer;
j: Integer;
lowX, lowY: Integer;
highX, highY: Integer;
begin
if (currentX+dirX < 0) OR (currentX+dirX > High(Counters)) OR (currentY+dirY < 0) OR (currentY+dirY > High(Counters)) then Exit;
if Counters[currentX+dirX][currentY+dirY].Visible = False then Exit;
if Counters[currentX+dirX][currentY+dirY].CounterState = startState then
begin
(*
if startX > currentX then
begin
highX := startX;
lowX := currentX;
end
else
begin
lowX := startX;
highX := currentX;
end;
if startY > currentY then
begin
highY := startY;
lowY := currentY;
end
else
begin
lowY := startY;
highY := currentY;
end;
for i := lowX to highX do
for j := lowY to highY do
begin
Counters[i][j].CounterState := startState;
end; *)
//ShowMessage(IntToStr(currentY));
FlipLine(startX, startY, currentX, currentY, startState);
end
else
begin
CheckDirection(startX,startY,currentX+dirX,currentY+dirY,dirX,dirY,startState);
end;
end;
procedure TOthelloCounterSet.FlipLine(startX,startY,endX,endY: Integer; cState: TOthelloState);
var
dirX, dirY: Integer;
cx, cy: Integer;
begin
if endX > startX then
dirX := 1
else if endX < startX then
dirX := -1
else
dirX := 0;
if endY > startY then
dirY := 1
else if endY < startY then
dirY := -1
else
dirY := 0;
cx := startX;
cy := startY;
while (cx <> endX+dirX) OR (cy <> endY+dirY) do
begin
Counters[cx][cy].CounterState := cState;
cx := cx + dirX;
cy := cy + dirY;
end;
end;
function TOthelloCounterSet.GetScore(ScoreState: TOthelloState): Integer;
var
i: Integer;
j: Integer;
n: Integer;
begin
n := 0;
for i := 0 to High(Counters) do
for j := 0 to High(Counters) do
begin
if Counters[i][j].CounterState = ScoreState then Inc(n)
end;
Result := n;
end;
end.
|
unit MainFormView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FIBDatabase, pFIBDatabase, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, StdCtrls, ComCtrls,
cxGridBandedTableView, FIBDataSet, pFIBDataSet,IBase, ToolWin, Buttons,
cxCalc, cxButtonEdit, cxMaskEdit, cxLabel, cxDropDownEdit, cxCalendar,
cxCheckBox, cxContainer, cxTextEdit, cxMemo, ExtCtrls,LoaderClBank,
ImgList, cxCurrencyEdit,ConstClBank, FIBQuery, pFIBQuery, pFIBStoredProc,
frxClass, frxDesgn, frxDBSet, Menus, cxDBEdit, cxDBLabel, frxExportXLS,
frxExportRTF, frxExportXML;
type
TfrmMainFormView = class(TForm)
Database: TpFIBDatabase;
Transaction: TpFIBTransaction;
StatusBar1: TStatusBar;
GroupBox1: TGroupBox;
cxGridDBTableView1: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid: TcxGrid;
pFIBDataSet: TpFIBDataSet;
DataSource: TDataSource;
NATIVE_RS: TcxGridDBColumn;
DATE_DOC: TcxGridDBColumn;
DATE_VIP: TcxGridDBColumn;
CUSTOMER_NAME: TcxGridDBColumn;
NUM_DOC: TcxGridDBColumn;
SUM_DOC_PR: TcxGridDBColumn;
SUM_DOC_RAS: TcxGridDBColumn;
TYPE_DOC: TcxGridDBColumn;
ToolBar1: TToolBar;
ToolButtonFind: TToolButton;
ToolButtonRefresh: TToolButton;
StyleRepository: TcxStyleRepository;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyleYellow: TcxStyle;
cxStyleFontBlack: TcxStyle;
cxStyleMalin: TcxStyle;
cxStyleBorder: TcxStyle;
cxStylemalinYellow: TcxStyle;
cxStyleGrid: TcxStyle;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
ToolButtonADD: TToolButton;
ToolButtonEdit: TToolButton;
ImageList1: TImageList;
ToolButtonExit: TToolButton;
GroupBox2: TGroupBox;
LabelRsCustomer: TLabel;
IS_DELETE: TcxGridDBColumn;
IS_WORK_DOC: TcxGridDBColumn;
IS_ADD_CLBANK: TcxGridDBColumn;
ToolButtonDelete: TToolButton;
pFIBStoredProc: TpFIBStoredProc;
WriteTransaction: TpFIBTransaction;
ToolButton1: TToolButton;
FROM_DOC: TcxGridDBColumn;
PanelWait: TPanel;
Timer1: TTimer;
ToolButtonPrint: TToolButton;
frxDBDataset: TfrxDBDataset;
frxDesigner: TfrxDesigner;
Image1: TImage;
frxReport1: TfrxReport;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
RATE_ACCOUNT_NAT: TcxGridDBColumn;
PrintGroup: TMenuItem;
frxReport: TfrxReport;
cxDBMemo1: TcxDBMemo;
cxDBTextEdit1: TcxDBTextEdit;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
PopupMenu2: TPopupMenu;
ActionDel: TMenuItem;
ActionDelAll: TMenuItem;
Query: TpFIBQuery;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SpeedButton1Click(Sender: TObject);
procedure ToolButtonFindClick(Sender: TObject);
procedure ToolButtonADDClick(Sender: TObject);
procedure ToolButtonEditClick(Sender: TObject);
procedure ToolButtonExitClick(Sender: TObject);
procedure ToolButtonRefreshClick(Sender: TObject);
procedure cxGridDBTableView1CustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
procedure ToolButtonDeleteClick(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure PrintGroupClick(Sender: TObject);
procedure ActionDelClick(Sender: TObject);
procedure ActionDelAllClick(Sender: TObject);
private
id_session : int64;
constructor Create(AOwner : TComponent;DBH:TISC_DB_HANDLE);overload;
public
procedure RefreshData();
{ Public declarations }
end;
function ViewClBank(AOwner : TComponent;DB:TISC_DB_HANDLE):Integer;stdcall;
exports ViewClBank;
var
frmMainFormView: TfrmMainFormView;
paramFN:Variant;
ColorFont:Tcolor;
FlClose:Integer;
FlFirstRun:Integer;
implementation
uses
FindForm;
{$R *.dfm}
function ViewClBank(AOwner : TComponent;DB:TISC_DB_HANDLE):Integer;stdcall;
var
View: TfrmMainFormView;
begin
View:=TfrmMainFormView.Create(AOwner,DB);
end;
constructor TfrmMainFormView.Create(AOwner : TComponent;DBH:TISC_DB_HANDLE);
var
i:Integer;
begin
inherited Create(AOwner);
Database.Handle:=DBH;
pFIBDataSet.Database := Database;
pFIBDataSet.Transaction := Transaction;
Transaction.StartTransaction;
FlFirstRun:=0;
FlClose := 0;
DecimalSeparator := ',';
cxDBMemo1.Text :='';
colorFont:=cxGrid.Canvas.Font.Color;
cxDBTextEdit1.Text:=ConstClBank.ClBank_rs_customer;
ToolButtonADD.Caption:=ConstClBank.ClBank_ACTION_ADD_CONST;
ToolButtonEdit.Caption:=ConstClBank.ClBank_ACTION_EDIT_CONST;
ToolButtonDelete.Caption:=ConstClBank.ClBank_ACTION_DELETE_CONST;
ToolButtonRefresh.Caption:=ConstClBank.ClBank_ACTION_REFRESH_CONST;
ToolButtonFind.Caption:=ConstClBank.ClBank_ACTION_FILTER_CONST;
ToolButtonExit.Caption:=ConstClBank.ClBank_ACTION_CLOSE_CONST;
ToolButtonPrint.Caption:=ConstClBank.ClBank_ACTION_PRINT_CONST;
ActionDel.Caption:=ConstClBank.ClBank_ACTION_DELETE_CONST;
ActionDelAll.Caption:=ConstClBank.ClBank_ACTION_DELETE_ALL_CONST;
id_session := Database.Gen_Id('CLBANK_ALL_DOC_VIEW_GEN', 1);
ParamFN:=VarArrayCreate([0,11],varVariant);
for i:=0 to 11 do
begin
ParamFN[i]:=VarArrayOf([0,0,0,0,0]);
end;
Timer1.Enabled:=true;
end;
procedure TfrmMainFormView.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Query.Transaction := WriteTransaction;
WriteTransaction.StartTransaction;
Query.SQL.Clear;
Query.SQL.Add('DELETE FROM CLBANK_ALL_DOC_VIEW_TMP WHERE ID_SESSION='+IntToStr(id_session)+'');
Query.ExecQuery;
WriteTransaction.Commit;
Action:=caFree;
end;
procedure TfrmMainFormView.RefreshData();
begin
PanelWait.Visible:=true;
Refresh;
Query.Database := Database;
Query.Transaction := WriteTransaction;
WriteTransaction.StartTransaction;
Query.close;
Query.SQL.Clear;
Query.SQL.Text := 'INSERT INTO CLBANK_ALL_DOC_ViEW_TMP (ID_doc, ID_SESSION,TYPE_DOC)';
Query.SQL.Add('select distinct c.id_doc as id_doc, '+IntToStr(id_session)+' as ID_SESSION, '+IntToStr(1)+' as TYPE_DOC_');
Query.SQL.Add('from clbank_buff c');
if paramFN[6][0]=1 then
begin
Query.SQL.Add(', PUB_SP_CUSTOMER cust, PUB_SP_CUST_RATE_ACC cust_acc ');
end;
Query.SQL.Add('where c.id_doc>0');
{по дате докумена}
if paramFN[0][0]=1 then
begin
if paramFN[0][1]=1 then
begin
Query.SQL.Add('and c.DATE_DOC >='''+DateToStr(paramFN[0][2])+'''');
end;
if paramFN[0][3]=1 then
begin
Query.SQL.Add('AND c.DATE_DOC <='''+DateToStr(paramFN[0][4])+'''');
end;
end;
{по дате банковской выписки}
if paramFN[1][0]=1 then
begin
if paramFN[1][1]=1 then
begin
Query.SQL.Add('and c.date_vip >='''+DateToStr(paramFN[1][2])+'''');
end;
if paramFN[1][3]=1 then
begin
Query.SQL.Add('and c.date_doc<='''+DateToStr(paramFN[1][4])+'''');
end;
end;
{по номеру документа}
if paramFN[2][0]=1 then
begin
Query.SQL.Add(' and c.num_doc Like '''+'%'+ paramFN[2][1]+'%'+'''');
end;
{по сумме}
if paramFN[3][0]=1 then
begin
if paramFN[3][1]=1 then
begin
Query.SQL.Add(' and c.SUM_DOC>='+StringReplace(vartostr(paramFN[3][2]), ',', '.', [rfReplaceAll])+'');
end;
if paramFN[3][3]=1 then
begin
Query.SQL.Add(' and c.SUM_DOC<='+StringReplace(vartostr(paramFN[3][4]), ',', '.', [rfReplaceAll])+'');
end;
end;
{то приходу/расходу}
if paramFN[4][0]=1 then
begin
if paramFN[4][1]=1 then
begin
Query.SQL.Add('AND c.TYPE_DOC=1');
end;
if paramFN[4][1]=2 then
begin
Query.SQL.Add('AND c.TYPE_DOC=-1');
end;
end;
// по нашему р/с *
if paramFN[5][0]=1 then
begin
Query.SQL.Add('AND c.id_account_native='+VarToStr(paramFN[5][1])+'');
end;
{по контрагенту}
if paramFN[6][0]=1 then
begin
if paramFN[6][1]=0 then
begin
Query.SQL.Add('AND cust.id_customer='+VarToStr(paramFN[6][2])+'');
Query.SQL.Add('AND cust.id_customer=cust_acc.id_customer and cust_acc.id_rate_account=c.id_account_customer');
end;
if paramFN[6][1]=1 then
begin
Query.SQL.Add(' and upper(cust.name_customer) Like '''+'%'+AnsiUpperCase(paramFN[6][4])+'%'+'''');
Query.SQL.Add('AND cust.id_customer=cust_acc.id_customer and cust_acc.id_rate_account=c.id_account_customer');
end;
end;
//по р/с контрагента *
if paramFN[7][0]=1 then
begin
Query.SQL.Add('AND c.id_account_customer='+VarToStr(paramFN[7][1])+'');
end;
//по основанию докумета *
if paramFN[8][0]=1 then
begin
Query.SQL.Add(' and upper(c.note) Like'''+'%'+AnsiUpperCase(paramFN[8][1])+'%'+'''');
end;
{то обработан/не обработан}
if paramFN[9][0]=1 then
begin
if paramFN[9][1]=0 then
begin
Query.SQL.Add('AND (c.obrabotan=0 or c.obrabotan is null)');
end;
if paramFN[9][1]=1 then
begin
Query.SQL.Add('AND c.obrabotan=1');
end;
end;
{удален не удален}
if paramFN[10][0]=1 then
begin
if paramFN[10][1]=0 then
begin
Query.SQL.Add('AND c.IS_DELETE=0');
end;
end;
Query.ExecQuery;
/////////////////////////////////////////////////////////////////////////////////////////
Query.close;
Query.SQL.Text := 'INSERT INTO CLBANK_ALL_DOC_ViEW_TMP (ID_doc, ID_SESSION,TYPE_DOC)';
Query.SQL.Add('select distinct d.id_key as id_doc, '+IntToStr(id_session)+' as ID_SESSION, '+IntToStr(2)+' as TYPE_DOC_');
Query.SQL.Add('from dog_dt_pl_doc d');
if paramFN[6][0]=1 then
begin
Query.SQL.Add(', PUB_SP_CUSTOMER cust');
end;
Query.SQL.Add('where d.id_key>0 and (d.deleted_system=0 OR d.deleted_system=2) ');
{по дате докумена}
if paramFN[0][0]=1 then
begin
if paramFN[0][1]=1 then
begin
Query.SQL.Add('and d.export_day >='''+DateToStr(paramFN[0][2])+'''');
end;
if paramFN[0][3]=1 then
begin
Query.SQL.Add('AND d.export_day <='''+DateToStr(paramFN[0][4])+'''');
end;
end;
{по дате банковской выписки}
if paramFN[1][0]=1 then
begin
if paramFN[1][1]=1 then
begin
Query.SQL.Add('and d.export_day >='''+DateToStr(paramFN[1][2])+'''');
end;
if paramFN[1][3]=1 then
begin
Query.SQL.Add('and d.export_day<='''+DateToStr(paramFN[1][4])+'''');
end;
end;
{по номеру документа}
if paramFN[2][0]=1 then
begin
Query.SQL.Add(' and d.num_doc Like '''+'%'+ paramFN[2][1]+'%'+'''');
end;
{по сумме}
if paramFN[3][0]=1 then
begin
if paramFN[3][1]=1 then
begin
Query.SQL.Add(' and d.summa>='+StringReplace(vartostr(paramFN[3][2]), ',', '.', [rfReplaceAll])+'');
end;
if paramFN[3][3]=1 then
begin
Query.SQL.Add(' and d.summa<='+StringReplace(vartostr(paramFN[3][4]), ',', '.', [rfReplaceAll])+'');
end;
end;
// по нашему р/с *
if paramFN[5][0]=1 then
begin
Query.SQL.Add('AND d.id_rate_account_native='+VarToStr(paramFN[5][1])+'');
end;
{по контрагенту}
if paramFN[6][0]=1 then
begin
if paramFN[6][1]=0 then
begin
Query.SQL.Add('AND d.id_customer='+VarToStr(paramFN[6][2])+'');
end;
if paramFN[6][1]=1 then
begin
Query.SQL.Add(' and upper(cust.name_customer) Like '''+'%'+AnsiUpperCase(paramFN[6][4])+'%'+'''');
Query.SQL.Add('AND cust.id_customer=d.id_customer ');
end;
end;
//по р/с контрагента *
if paramFN[7][0]=1 then
begin
Query.SQL.Add('AND d.id_rate_account='+VarToStr(paramFN[7][1])+'');
end;
//по основанию докумета *
if paramFN[8][0]=1 then
begin
Query.SQL.Add(' and upper(d.note) Like'''+'%'+AnsiUpperCase(paramFN[8][1])+'%'+'''');
end;
Query.ExecQuery;
WriteTransaction.Commit;
pFIBDataSet.Close;
pFIBDataSet.SQLs.SelectSQL.Text := 'SELECT * FROM CLBANK_FIND_DOC('+ IntToStr(id_session)+')';
pFIBDataSet.Open;
pFIBDataSet.FetchAll;
PanelWait.Visible:=false;
Refresh;
end;
procedure TfrmMainFormView.SpeedButton1Click(Sender: TObject);
begin
RefreshData();
end;
procedure TfrmMainFormView.ToolButtonFindClick(Sender: TObject);
var
Find:TfrmFindForm;
begin
Find:=TfrmFindForm.Create(self,paramFN);
paramFN:=Find.FindClBankDoc();
Query.Transaction := WriteTransaction;
WriteTransaction.StartTransaction;
Query.SQL.Clear;
Query.SQL.Add('DELETE FROM CLBANK_ALL_DOC_VIEW_TMP WHERE ID_SESSION='+IntToStr(id_session)+'');
Query.ExecQuery;
WriteTransaction.Commit;
if Find.closeFind=1 then
begin
Find.free;
RefreshData();
FlClose:=0;
FlFirstRun:=1;
end
else
begin
Find.free;
FlClose:=1;
if FlFirstRun = 0
then Close;
end;
end;
procedure TfrmMainFormView.ToolButtonADDClick(Sender: TObject);
var
res:Integer;
begin
res:=LoaderClBank.LoadAddDocClBank(self,Database.Handle,fsNormal,0,Date);
if res=0 then
begin
RefreshData();
end;
end;
procedure TfrmMainFormView.ToolButtonEditClick(Sender: TObject);
var
res:Integer;
begin
if pFIBDataSet.RecordCount=0 then
begin
exit;
end;
res:=LoaderClBank.LoadEditDocClBank(self,Database.Handle,fsNormal,pFIBDataSet.FieldByName('ID_DOC').AsVariant);
if res=0 then
begin
RefreshData();
end;
end;
procedure TfrmMainFormView.ToolButtonExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmMainFormView.ToolButtonRefreshClick(Sender: TObject);
begin
RefreshData();
end;
procedure TfrmMainFormView.cxGridDBTableView1CustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
Arect:TRect;
ind:Integer;
begin
Arect:=AViewInfo.Bounds;
ind:=Sender.IndexOfItem(IS_DELETE);
if AViewInfo.GridRecord.Values[ind]=1 then
begin
ACanvas.Canvas.Font.Color:=clSilver;
ACanvas.Canvas.Font.Style:=[fsStrikeOut];
ACanvas.Canvas.FillRect(Arect);
end
else
begin
ACanvas.Canvas.Pen.Color:=colorFont;
ACanvas.Canvas.Font.Style:=[];
ACanvas.Canvas.FillRect(Arect);
end;
end;
procedure TfrmMainFormView.ToolButtonDeleteClick(Sender: TObject);
begin
if pFIBDataSet.RecordCount=0 then
begin
exit;
end;
if messageBox(Handle,PChar(ConstClBank.ClBank_MESSAGE_DELETE),
PChar(ConstClBank.ClBank_MESSAGE_WARNING),MB_OKCANCEL or MB_ICONWARNING)=1 then
begin
pFIBDataSet.First;
while not pFIBDataSet.Eof do
begin
LoaderClBank.LoadDelDocClBank(self,Database.Handle,fsNormal,pFIBDataSet.FieldByName('ID_DOC').AsVariant);
pFIBDataSet.Next;
end;
RefreshData();
end;
end;
procedure TfrmMainFormView.ToolButton1Click(Sender: TObject);
begin
LoaderClBank.LoadViewDocClBank(self,Database.Handle,fsNormal,pFIBDataSet.FieldByName('id_doc').AsVariant);
end;
procedure TfrmMainFormView.FormShow(Sender: TObject);
begin
if (FlClose=1) and (FlFirstRun=0) then
begin
Close;
end;
if (FlClose=1) and (FlFirstRun=0) then
begin
Close;
end;
end;
procedure TfrmMainFormView.Timer1Timer(Sender: TObject);
begin
timer1.Enabled:=false;
ToolButtonFindClick(self);
end;
procedure TfrmMainFormView.N1Click(Sender: TObject);
begin
DataSource.Enabled := false;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\ClBank\PrintAllDoc.fr3');
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
DataSource.Enabled := true;
//frxReport.DesignReport;
end;
procedure TfrmMainFormView.N2Click(Sender: TObject);
begin
DataSource.Enabled := false;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\ClBank\PrintAllDoc2010.fr3');
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
DataSource.Enabled := true;
//frxReport.DesignReport;
end;
procedure TfrmMainFormView.PrintGroupClick(Sender: TObject);
begin
DataSource.Enabled := false;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\ClBank\PrintAllDoc2011_group_rs.fr3');
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
DataSource.Enabled := true;
//frxReport.DesignReport;
end;
procedure TfrmMainFormView.ActionDelClick(Sender: TObject);
begin
if pFIBDataSet.RecordCount=0 then
begin
exit;
end;
if messageBox(Handle,PChar(ConstClBank.ClBank_DOC_NUM+pFIBDataSet.FieldByName('NUM_DOC').AsString+'?'),
PChar(ConstClBank.ClBank_MESSAGE_WARNING),MB_OKCANCEL or MB_ICONWARNING)=1 then
begin
LoaderClBank.LoadDelDocClBank(self,Database.Handle,fsNormal,pFIBDataSet.FieldByName('ID_DOC').AsVariant);
RefreshData();
end;
end;
procedure TfrmMainFormView.ActionDelAllClick(Sender: TObject);
begin
if pFIBDataSet.RecordCount=0 then
begin
exit;
end;
if messageBox(Handle,PChar(ConstClBank.ClBank_MESSAGE_DELETE_ALL_NEOBR),
PChar(ConstClBank.ClBank_MESSAGE_WARNING),MB_OKCANCEL or MB_ICONWARNING)=1 then
begin
PanelWait.Visible:=true;
Refresh;
pFIBDataSet.First;
while not pFIBDataSet.Eof do
begin
LoaderClBank.LoadDelDocClBank(self,Database.Handle,fsNormal,pFIBDataSet.FieldByName('ID_DOC').AsVariant);
pFIBDataSet.Next;
end;
PanelWait.Visible:=false;
Refresh;
RefreshData();
end;
end;
end. |
library Socks;
uses SysUtils,
Classes,
blcksock,
svm in '..\svm.pas';
type
TMashSocket = class
public
sock: TBlockSocket;
constructor Create;
destructor Destroy; override;
procedure Close;
procedure Connect(host: string; port: cardinal);
procedure Bind(host: string; port: cardinal);
procedure Listen;
function Accept: TMashSocket;
procedure SetTimeOut(ms: integer);
procedure SetBlockingMode(bool: integer);
procedure SendStream(Stream: TStream);
procedure SendString(Str: string);
procedure ReceiveStream(Stream: TStream; TimeOut: integer);
function Receive(Stream: TStream; Len: integer): integer;
function ReceiveString(TimeOut: integer): string;
end;
constructor TMashSocket.Create;
begin
sock := TBlockSocket.Create;
end;
destructor TMashSocket.Destroy;
begin
sock.Free;
inherited Destroy;
end;
procedure TMashSocket.Close;
begin
sock.CloseSocket;
end;
procedure TMashSocket.Connect(host: string; port: cardinal);
begin
sock.Connect(host, IntToStr(port));
end;
procedure TMashSocket.Bind(host: string; port: cardinal);
begin
sock.Bind(host, IntToStr(port));
end;
procedure TMashSocket.Listen;
begin
sock.Listen;
end;
function TMashSocket.Accept: TMashSocket;
begin
Result := TMashSocket.Create;
Result.sock.Socket := sock.Accept;
end;
procedure TMashSocket.SetTimeOut(ms: integer);
begin
sock.SetTimeout(ms);
end;
procedure TMashSocket.SetBlockingMode(bool: integer);
begin
// true - block
// false - no block
sock.NonBlockMode := bool <> -1;
end;
procedure TMashSocket.SendStream(Stream: TStream);
begin
Stream.Seek(0, soFromBeginning);
sock.SendStreamRaw(Stream);
end;
procedure TMashSocket.SendString(Str: string);
begin
sock.SendString(Str + CRLF);
end;
procedure TMashSocket.ReceiveStream(Stream: TStream; TimeOut: integer);
begin
sock.RecvStream(Stream, TimeOut);
end;
function TMashSocket.Receive(Stream: TStream; Len: integer): integer;
var
Buf: TBytes;
begin
SetLength(Buf, Len);
Result := sock.RecvBuffer(@Buf, Len);
Stream.Write(Buf, Result);
SetLength(Buf, 0);
end;
function TMashSocket.ReceiveString(TimeOut: integer): string;
begin
Result := sock.RecvString(TimeOut);
end;
// Exports
procedure SockDestroy(obj: pointer); stdcall;
begin
TMashSocket(obj).Free;
end;
procedure _Socket_Create(pctx: pointer); stdcall;
begin
__Return_Ref(pctx, TMashSocket.Create, @SockDestroy);
end;
procedure _Socket_Close(pctx: pointer); stdcall;
begin
TMashSocket(__Next_Ref(pctx)).Close;
end;
procedure _Socket_Connect(pctx: pointer); stdcall;
var
sock: TMashSocket;
host: string;
port: cardinal;
begin
sock := TMashSocket(__Next_Ref(pctx));
host := __Next_StringA(pctx);
port := __Next_Word(pctx);
sock.Connect(host, port);
try
sock.sock.ExceptCheck;
__Return_Bool(pctx, true);
except
__Return_Bool(pctx, false);
end;
end;
procedure _Socket_Bind(pctx: pointer); stdcall;
var
sock: TMashSocket;
host: string;
port: cardinal;
begin
sock := TMashSocket(__Next_Ref(pctx));
host := __Next_StringA(pctx);
port := __Next_Word(pctx);
sock.Bind(host, port);
try
sock.sock.ExceptCheck;
__Return_Bool(pctx, true);
except
__Return_Bool(pctx, false);
end;
end;
procedure _Socket_Listen(pctx: pointer); stdcall;
begin
TMashSocket(__Next_Ref(pctx)).Listen;
end;
procedure _Socket_Accept(pctx: pointer); stdcall;
begin
__Return_Ref(pctx, TMashSocket(__Next_Ref(pctx)).Accept, @SockDestroy);
end;
procedure _Socket_SetTimeOut(pctx: pointer); stdcall;
var
sock: TMashSocket;
tm: integer;
begin
sock := TMashSocket(__Next_Ref(pctx));
tm := __Next_Int(pctx);
sock.SetTimeOut(tm);
end;
procedure _Socket_SetBlockingMode(pctx: pointer); stdcall;
var
sock: TMashSocket;
bm: integer;
begin
sock := TMashSocket(__Next_Ref(pctx));
bm := __Next_Int(pctx);
sock.SetBlockingMode(bm);
end;
procedure _Socket_SendStream(pctx: pointer); stdcall;
var
sock: TMashSocket;
stream: TStream;
begin
sock := TMashSocket(__Next_Ref(pctx));
stream := TStream(__Next_Ref(pctx));
sock.SendStream(stream);
try
sock.sock.ExceptCheck;
__Return_Bool(pctx, true);
except
__Return_Bool(pctx, false);
end;
end;
procedure _Socket_SendString(pctx: pointer); stdcall;
var
sock: TMashSocket;
str: string;
begin
sock := TMashSocket(__Next_Ref(pctx));
str := __Next_StringA(pctx);
sock.SendString(str);
try
sock.sock.ExceptCheck;
__Return_Bool(pctx, true);
except
__Return_Bool(pctx, false);
end;
end;
procedure _Socket_ReceiveStream(pctx: pointer); stdcall;
var
sock: TMashSocket;
stream: TStream;
tm: integer;
begin
sock := TMashSocket(__Next_Ref(pctx));
stream := TStream(__Next_Ref(pctx));
tm := __Next_Int(pctx);
sock.ReceiveStream(stream, tm);
try
sock.sock.ExceptCheck;
__Return_Bool(pctx, true);
except
__Return_Bool(pctx, false);
end;
end;
procedure _Socket_ReceiveBuffer(pctx: pointer); stdcall;
var
sock: TMashSocket;
stream: TStream;
len, gt: integer;
begin
sock := TMashSocket(__Next_Ref(pctx));
stream := TStream(__Next_Ref(pctx));
len := __Next_Int(pctx);
gt := sock.Receive(stream, len);
try
sock.sock.ExceptCheck;
__Return_Int(pctx, gt);
except
__Return_Null(pctx);
end;
end;
procedure _Socket_ReceiveString(pctx: pointer); stdcall;
var
sock: TMashSocket;
tm: integer;
s: string;
begin
sock := TMashSocket(__Next_Ref(pctx));
tm := __Next_Int(pctx);
s := sock.ReceiveString(tm);
try
sock.sock.ExceptCheck;
__Return_StringA(pctx, s);
except
__Return_Null(pctx);
end;
end;
{ EXPORTS }
exports _Socket_Create name '_Socket_Create';
exports _Socket_Close name '_Socket_Close';
exports _Socket_Connect name '_Socket_Connect';
exports _Socket_Bind name '_Socket_Bind';
exports _Socket_Listen name '_Socket_Listen';
exports _Socket_Accept name '_Socket_Accept';
exports _Socket_SetTimeOut name '_Socket_SetTimeOut';
exports _Socket_SetBlockingMode name '_Socket_SetBlockingMode';
exports _Socket_SendStream name '_Socket_SendStream';
exports _Socket_SendString name '_Socket_SendString';
exports _Socket_ReceiveStream name '_Socket_ReceiveStream';
exports _Socket_ReceiveBuffer name '_Socket_ReceiveBuffer';
exports _Socket_ReceiveString name '_Socket_ReceiveString';
begin
end.
|
unit Cache.EventsMove;
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
Cache.Root,
Adapter.MySQL,
Geo.Pos,
ZConnection, ZDataset,
Ils.MySql.Conf,
Event.Cnst;
// ,Ils.Logger,
// Ils.Utils;
//------------------------------------------------------------------------------
type
TProcessedEvent = procedure(const AObj: TCacheDataObjectAbstract; const AUpdate: Boolean) of object;
//------------------------------------------------------------------------------
//!
//------------------------------------------------------------------------------
TSystemMoveEvent = class(TCacheDataObjectAbstract)
private
FIMEI: Int64;
FDTMark: TDateTime;
FEventType: TEventSystemType;
FDuration: TTime;
FLatitude: Double;
FLongitude: Double;
FRadius: Double;
FDispersion: Double;
FOffset: Int64;
protected
//!
function GetDTMark(): TDateTime; override;
public
constructor Create(
const IMEI: Int64;
const DTMark: TDateTime;
const EventType: TEventSystemType;
const Duration: TTime;
const Latitude: Double;
const Longitude: Double;
const Radius: Double;
const Dispersion: Double;
const Offset: Int64
); overload;
constructor Create(
Source: TSystemMoveEvent
); overload;
function Clone(): TCacheDataObjectAbstract; override;
property IMEI: Int64 read FIMEI;
property DTMark: TDateTime read GetDTMark;
property EventType: TEventSystemType read FEventType;
property Duration: TTime read FDuration write FDuration;
property Latitude: Double read FLatitude;
property Longitude: Double read FLongitude;
property Radius: Double read FRadius;
property Dispersion: Double read FDispersion;
property Offset: Int64 read FOffset;
end;
//------------------------------------------------------------------------------
//!
//------------------------------------------------------------------------------
TSystemMoveEventCacheDataAdapter = class(TCacheAdapterMySQL)
// TTrackPointCacheDataAdapter = class(TCacheAdapterMySQL)
private
FProcessedEvent: TProcessedEvent;
public
procedure Flush(
const ACache: TCache
); override;
procedure Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); override;
procedure Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); override;
function MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract; override;
constructor Create(
const AReadConnection, AWriteConnection: TZConnection;
const AProcessedEvent: TProcessedEvent
);
end;
//------------------------------------------------------------------------------
//! класс списка кэшей точек трека
//------------------------------------------------------------------------------
TTrackPointCacheDictionary = TCacheDictionary<Int64>;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
constructor TSystemMoveEvent.Create(
const IMEI: Int64;
const DTMark: TDateTime;
const EventType: TEventSystemType;
const Duration: TTime;
const Latitude: Double;
const Longitude: Double;
const Radius: Double;
const Dispersion: Double;
const Offset: Int64
);
begin
inherited Create();
//
FIMEI := IMEI;
FDTMark := DTMark;
FEventType := EventType;
FDuration := Duration;
FLatitude := Latitude;
FLongitude := Longitude;
FRadius := Radius;
FDispersion := Dispersion;
FOffset := Offset;
end;
constructor TSystemMoveEvent.Create(
Source: TSystemMoveEvent
);
begin
inherited Create();
//
FIMEI := Source.IMEI;
FDTMark := Source.DTMark;
FEventType := Source.EventType;
FDuration := Source.Duration;
FLatitude := Source.Latitude;
FLongitude := Source.Longitude;
FRadius := Source.Radius;
FDispersion := Source.Dispersion;
FOffset := Source.Offset;
end;
function TSystemMoveEvent.Clone(): TCacheDataObjectAbstract;
begin
Result := TSystemMoveEvent.Create(Self);
end;
function TSystemMoveEvent.GetDTMark(): TDateTime;
begin
Result := FDTMark;
end;
{ TSystemMoveEventCacheDataAdapter }
constructor TSystemMoveEventCacheDataAdapter.Create(
const AReadConnection, AWriteConnection: TZConnection;
const AProcessedEvent: TProcessedEvent
);
const
SQLReadRange =
'SELECT *'
+ ' FROM eventsystem_move'
+ ' WHERE IMEI = :imei'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to'
;
SQLReadBefore =
'SELECT MAX(DT) as DT'
+ ' FROM eventsystem_move'
+ ' WHERE IMEI = :imei'
+ ' AND DT < :dt'
;
SQLReadAfter =
'SELECT MIN(DT) as DT'
+ ' FROM eventsystem_move'
+ ' WHERE IMEI = :imei'
+ ' AND DT > :dt'
;
SQLInsert =
'insert ignore into eventsystem_move set'
+ ' IMEI = :IMEI,'
+ ' DT = :DT,'
+ ' EventTypeID = :EventTypeID,'
+ ' Duration = :Duration,'
+ ' Latitude = :Latitude,'
+ ' Longitude = :Longitude,'
+ ' Radius = :Radius,'
+ ' Dispersion = :Dispersion'
;
SQLUpdate =
'update eventsystem_move set'
+ ' EventTypeID = :EventTypeID,'
+ ' Duration = :Duration,'
+ ' Latitude = :Latitude,'
+ ' Longitude = :Longitude,'
+ ' Radius = :Radius,'
+ ' Dispersion = :Dispersion'
+ ' where'
+ ' IMEI = :IMEI'
+ ' and DT = :DT'
;
SQLDeleteOne =
'delete from eventsystem_move'
+ ' where'
+ ' IMEI = :IMEI'
+ ' and DT = :DT'
;
begin
FProcessedEvent := AProcessedEvent;
inherited Create(
AReadConnection, AWriteConnection,
SQLInsert, SQLUpdate, SQLReadBefore, SQLReadAfter, SQLReadRange, SQLDeleteOne);
end;
procedure TSystemMoveEventCacheDataAdapter.Flush(const ACache: TCache);
begin
//Nothing!
end;
procedure TSystemMoveEventCacheDataAdapter.Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FInsertQry);
with (AObj as TSystemMoveEvent), FInsertQry do
begin
ParamByName('DT').AsDateTime := FDTMark;
ParamByName('EventTypeID').AsInteger := Ord(FEventType);
ParamByName('Duration').AsFloat := FDuration;
ParamByName('Latitude').AsFloat := FLatitude;
ParamByName('Longitude').AsFloat := FLongitude;
ParamByName('Radius').AsFloat := FRadius;
ParamByName('Dispersion').AsFloat := FDispersion;
ExecSQL;
try
if Assigned(FProcessedEvent) then
FProcessedEvent(AObj, False);
except
on E: Exception do begin
end;
end;
end;
end;
procedure TSystemMoveEventCacheDataAdapter.Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FUpdateQry);
with (AObj as TSystemMoveEvent), FUpdateQry do
begin
ParamByName('DT').AsDateTime := FDTMark;
ParamByName('EventTypeID').AsInteger := Ord(FEventType);
ParamByName('Duration').AsFloat := FDuration;
ParamByName('Latitude').AsFloat := FLatitude;
ParamByName('Longitude').AsFloat := FLongitude;
ParamByName('Radius').AsFloat := FRadius;
ParamByName('Dispersion').AsFloat := FDispersion;
ExecSQL;
try
if Assigned(FProcessedEvent) then
FProcessedEvent(AObj, True);
except
on E: Exception do begin
end;
end;
end;
end;
function TSystemMoveEventCacheDataAdapter.MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract;
begin
with AQuery do
begin
Result := TSystemMoveEvent.Create(
FieldByName('IMEI').AsLargeInt,
FieldByName('DT').AsDateTime,
TEventSystemType(FieldByName('EventTypeID').AsInteger),
FieldByName('Duration').AsFloat,
FieldByName('Latitude').AsFloat,
FieldByName('Longitude').AsFloat,
FieldByName('Radius').AsFloat,
FieldByName('Dispersion').AsFloat,
0
);
end;
end;
end.
|
{=====================================================================================
Copyright (C) combit GmbH
--------------------------------------------------------------------------------------
File : expfm.pas
Module : export sample
Descr. : D: Dieses Beispiel demonstriert den Export ohne Benutzerinteraktion.
US: This example demonstrates a quiet export.
======================================================================================}
unit expfm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, L28, DB, DBTables,cmbtll28, Registry, ADODB
{$If CompilerVersion >=28} // >=XE7
, System.UITypes
{$ENDIF}
;
type
TForm1 = class(TForm)
Label1: TLabel;
LL: TL28_;
Label2: TLabel;
FormatCombo: TComboBox;
Label3: TLabel;
Label4: TLabel;
Edit1: TEdit;
FileSelectBtn: TButton;
SaveDialog1: TSaveDialog;
GoBtn: TButton;
CheckShowFile: TCheckBox;
ADOConnection1: TADOConnection;
ADOTableArticle: TADOTable;
procedure FormCreate(Sender: TObject);
procedure LLDefineFields(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var EventResult: Integer);
procedure FormatComboChange(Sender: TObject);
procedure FileSelectBtnClick(Sender: TObject);
procedure GoBtnClick(Sender: TObject);
procedure LLSetPrintOptions(Sender: TObject;
var PrintMethodOptionFlags: Integer);
private
{ Private declarations }
FileFilter: String;
FileName: String;
ExporterName: String;
CurPath: String;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var errorOccurred: Boolean;
var registry: TRegistry;
var regKeyPath: String;
var errorText: String;
var DataFileName: String;
var DataFilePath: String;
begin
{D: Bestimme den Dateinamen der Beispiel-Datenbank}
{US: Set the filename for the test database }
errorOccurred := true;
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
DataFilePath := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir');
if (DataFilePath[Length(DataFilePath)] = '\') then
begin
DataFileName:='samples.mdb';
end
else
DataFileName:='\samples.mdb';
registry.CloseKey();
if FileExists(DataFilePath + DataFileName) then
begin
{D: Lade die Datenbank, fange Fehler ab }
{US: Load the database, checks for errors }
Try
begin
ADOConnection1.ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ' + DataFilePath + DataFileName +';' ;
ADOConnection1.Connected :=true;
ADOConnection1.LoginPrompt :=false;
ADOTableArticle.active := false;
ADOTableArticle.TableName :='article';
ADOTableArticle.active := true;
{D: Setze Dateipfad für LL Projektdateien }
{US: Set path fo LL project files}
CurPath := GetCurrentDir()+'\';
errorOccurred := false;
end
Except On EDBEngineError Do
//
End;
end;
end;
end;
registry.Free();
if errorOccurred then
begin
errorText := 'D: Beispiel-Datenbank nicht gefunden' + #13 + 'US: Test database not found';
MessageDlg(errorText, mtError, [mbOK], 0);
end;
FormatCombo.ItemIndex:=0;
FormatComboChange(self);
end;
procedure TForm1.LLDefineFields(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var EventResult: Integer);
{D: Dieser Event wird von den List & Label - Befehlen design und print
ausgelöst. Er wird für jeden Datensatz aufgerufen, um die Felder
und deren Inhalt an List & Label zu übergeben.
US: This event is called by the List & Label methods design and print.
It gets called once per record to define the fields and their
contents.}
var
i: integer;
begin
{D: Wiederholung für alle Datensatzfelder }
{US: Loop through all fields in the present recordset}
For i:= 0 to (ADOTableArticle.FieldCount-1) do
begin
{D: Umsetzung der Datenbank-Feldtypen in List & Label Feldtypen }
{US: Transform database field types into List & Label field types}
LL.LlDefineFieldFromTField(ADOTableArticle.Fields[i]);
end;
{D: Werden Echt-Daten benötigt (nicht bei Designer-Aufruf) }
{US: Is real data needed (not when method design has been called) }
if not IsDesignMode then
begin
{D: Prozentanzeige aktualisieren und zu nächsten Datensatz wechseln }
{US: Set percentage value for meter info and move to next record }
Percentage:=Round(ADOTableArticle.RecNo/ADOTableArticle.RecordCount*100);
ADOTableArticle.Next;
{D: Druck beenden, wenn kein weiterer Datensatz vorhanden ist}
{US: End printing if last record is reached }
if ADOTableArticle.EOF=True then IsLastRecord:=true;
end;
end;
procedure TForm1.FormatComboChange(Sender: TObject);
begin
{D: Default-Dateinamen, Filter und Exporternamen setzen}
{US: Set default file name, path and exporter name}
case FormatCombo.ItemIndex of
0: begin
FileFilter := 'Adobe PDF Format|*.pdf';
FileName := 'export.pdf';
ExporterName := 'PDF';
end;
1: begin
FileFilter := 'Multi-Mime HTML Format|*.mht';
FileName := 'export.mht';
ExporterName := 'MHTML';
end;
2: begin
FileFilter := 'Rich Text Format (RTF)*.rtf';
FileName := 'export.rtf';
ExporterName := 'RTF';
end;
3: begin
FileFilter := 'XML Format|*.xml';
FileName := 'export.xml';
ExporterName := 'XML';
end;
4: begin
FileFilter := 'TIFF Picture|*.tif';
FileName := 'export.tif';
ExporterName := 'PICTURE_MULTITIFF';
end;
5: begin
FileFilter := 'Text Format|*.txt';
FileName := 'export.txt';
ExporterName := 'TXT';
end;
6: begin
FileFilter := 'Microsoft Excel Format|*.xls';
FileName := 'export.xls';
ExporterName := 'XLS';
end;
7: begin
FileFilter := 'List & Label Preview Format|*.ll';
FileName := 'export.ll';
ExporterName := 'PRV';
end;
end;
FileName:=CurPath + FileName;
Edit1.Text := FileName;
end;
procedure TForm1.FileSelectBtnClick(Sender: TObject);
begin
{D: Dateiauswahl für Exportdatei}
{US: Choose file name for export file}
with SaveDialog1 do
begin
InitialDir := ExtractFilePath(self.FileName);
FileName := ExtractFileName(self.FileName);
Filter := FileFilter;
if Execute then
begin
self.FileName := FileName;
Edit1.Text := FileName;
end;
end;
end;
procedure TForm1.GoBtnClick(Sender: TObject);
begin
{D: Druck starten. Die Exporteroptionen werden in LLSetPrintOptions übergeben.
Wichtig: hier keinen Dateiauswahl- und keinen Druckoptionsdialog anzeigen}
{US: Start printing. The exporter options are passed in LLSetPrintOptions.
Important: no file selection dialog and no print options dialog is displayed.}
ADOTableArticle.First;
LL.Print(0,LL_PROJECT_LIST,CurPath + 'simple.lst',false,LL_PRINT_EXPORT,
LL_BOXTYPE_STDWAIT,handle,'Print list...', false,
'');
end;
procedure TForm1.LLSetPrintOptions(Sender: TObject;
var PrintMethodOptionFlags: Integer);
begin
{D: Exportoptionen setzen}
{US: Set export options}
{D: Exportformat festlegen}
{US: Set export format}
LL.LlPrintSetOptionString(LL_PRNOPTSTR_EXPORT, ExporterName);
{D: Pfad}
{US: Path}
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Path', ExtractFilePath(FileName)+'\');
{D: Dateiname}
{US: Filename}
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.File', ExtractFileName(FileName));
{D: Modus ohne Interaktion}
{US: Quiet mode}
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Quiet', '1');
{D: Je nach Benutzerauswahl: Anzeige des Ergebnisses}
{US: Depending on user's choice: show result}
if CheckShowFile.Checked then
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.ShowResult', '1')
else
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.ShowResult', '0')
{D: Um jetzt noch zusätzlich das Exportergebnis per Mail zu versenden, würden die unten
stehenden Codezeilen benötigt. Damit wird eine Mail an llmailtest@combit.net gesendet.
Als Exportformat ist in diesem Beispiel HTML notwendig, so dass das Ergebnis des HTML-
Exportes direkt als HTML Body der Mail versendet würde. Ausserdem muß über die
Export.Mail.SMTP...-Optionen ein gültiger SMTP-Server angegeben werden.
US: To additonally send the result as eMail, you'd need the following code lines. This
will send an email to llmailtest@combit.net. Set the export format to HTML, as this sample
will send the result as HTML body of the mail. You need to set a valid SMTP server
using the Export.Mail.SMTP... options..}
(*
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.SendAsMail', '1');
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Mail.To', 'combit GmbH <SMTP:llmailtest@combit.net>');
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Mail.Subject', 'combit List & Label mail test');
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Mail.ShowDialog', '1');
LL.LlXSetParameter(LL_LLX_EXTENSIONTYPE_EXPORT, ExporterName, 'Export.Mail.SendResultAs', 'text/html');
*)
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.OpenGL,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
GLScene,
GLObjects,
GLGeomObjects,
GLCadencer,
GLWin32Viewer,
GLTexture,
GLFileTGA,
GLBehaviours,
GLContext,
GLAsyncTimer,
GLMovement,
GLRenderContextInfo,
GLVectorFileObjects,
GLFileObj,mikmod,
GLBitmapFont,
GLWindowsFont,
GLHUDObjects;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLDirectOpenGL1: TGLDirectOpenGL;
AsyncTimer1: TGLAsyncTimer;
GLFreeForm1: TGLFreeForm;
GLDummyCube1: TGLDummyCube;
GLHUDText1: TGLHUDText;
GLWindowsBitmapFont1: TGLWindowsBitmapFont;
procedure GLDirectOpenGL1Render(Sender: TObject;
var rci: TGLRenderContextInfo);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure AsyncTimer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TRGBACol=record
r,g,b,a:byte;
end;
TBuf=array of dword;
PBuf=^TBuf;
var
Form1: TForm1;
buf:TBuf;
scrh,scrw,lng:integer;
curr_effect:byte;
procedure MakeGrayEffect(buffer:PBuf;length:dword);
procedure MakeNegativeEffect(buffer:PBuf;length:dword);
procedure MakeFigZnaetKakoyEffect2(buffer:PBuf;length:dword);
procedure MakeFigZnaetKakoyEffect(buffer:PBuf;length:dword);
implementation
{$R *.dfm}
procedure MakeFigZnaetKakoyEffect(buffer:PBuf;length:dword);
var i:dword;
begin
for i:=0 to length do
begin
if buffer^[i]=0 then Continue;
TRGBACol(buffer^[i]).r:=round(TRGBACol(buffer^[i+5]).r*2);
TRGBACol(buffer^[i]).g:=round(TRGBACol(buffer^[i]).g*1.5);
TRGBACol(buffer^[i]).b:=round(TRGBACol(buffer^[i+5]).b*1.5);
end;
end;
procedure MakeFigZnaetKakoyEffect2(buffer:PBuf;length:dword);
var i:dword; r,rnd:single;
begin
for i:=0 to length do
begin
if buffer^[i]=0 then Continue;
rnd:=random+1;
r:=TRGBACol(buffer^[i]).r*1.5*rnd;
if r>255 then r:=255;
TRGBACol(buffer^[i]).r:=round(r);
TRGBACol(buffer^[i]).g:=round(TRGBACol(buffer^[i]).g*rnd);
TRGBACol(buffer^[i]).b:=round(TRGBACol(buffer^[i]).b*rnd);
end;
end;
procedure MakeNegativeEffect(buffer:PBuf;length:dword);
var i:dword; red:byte;
begin
for i:=0 to length do
begin
red:=TRGBACol(buffer^[i]).r;
TRGBACol(buffer^[i]).r:=TRGBACol(buffer^[i]).b;
TRGBACol(buffer^[i]).b:=red;
end;
end;
procedure MakeGrayEffect(buffer:PBuf;length:dword);
var i:dword; gray:byte;
begin
for i:=0 to length do
begin
gray:=Round( ( 0.30 * TRGBACol(buffer^[i]).r ) +
( 0.59 * TRGBACol(buffer^[i]).g ) +
( 0.11 * TRGBACol(buffer^[i]).b ) );
TRGBACol(buffer^[i]).r:=gray;
TRGBACol(buffer^[i]).g:=gray;
TRGBACol(buffer^[i]).b:=gray;
end;
end;
procedure TForm1.GLDirectOpenGL1Render(Sender: TObject;
var rci: TGLRenderContextInfo);
begin
if curr_effect=0 then exit;
glReadPixels(0,0,Width,Height,GL_RGBA,GL_UNSIGNED_BYTE,buf);
case curr_effect of
1:MakeFigZnaetKakoyEffect(@buf,lng);
2:MakeNegativeEffect(@buf,lng);
3:MakeGrayEffect(@buf,lng);
4:MakeFigZnaetKakoyEffect2(@buf,lng);
end;
glDrawPixels(Width,Height,GL_RGBA,GL_UNSIGNED_BYTE,buf);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
MikWin_Init(44100, True, True, True, Handle, 0);
MikWin_Load(PChar('Moving of star.s3m'));
MikWin_Play(false);
Randomize;
scrw:=Width;
scrh:=Height;
lng:=scrw*scrh;
SetLength(buf,lng);
lng:=lng-1;
curr_effect:=1;
GLFreeForm1.LoadFromFile('town.obj');
GetMovement(GLDummyCube1).StartPathTravel;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
buf:=nil;
MikWin_Free;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=vk_escape then
close;
if key=VK_NUMPAD0 then
curr_effect:=0;
if key=VK_NUMPAD1 then
curr_effect:=1;
if key=VK_NUMPAD2 then
curr_effect:=2;
if key=VK_NUMPAD3 then
curr_effect:=3;
if key=VK_NUMPAD4 then
curr_effect:=4;
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
if GLHUDText1.Position.X>-1200 then
GLHUDText1.Position.X:=GLHUDText1.Position.X-5 else
GLHUDText1.Position.X:=800;
Caption:=Format('%.2f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
MikWin_Update;
if not MikWin_Playing then close;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
unit DPM.Core.Package.Installer;
// TODO : Lots of common code between install and restore - refactor!
interface
uses
VSoft.CancellationToken,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Package.Interfaces,
DPM.Core.Package.Installer.Interfaces,
DPM.Core.Options.Cache,
DPM.Core.Options.Search,
DPM.Core.Options.Install,
DPM.Core.Options.Uninstall,
DPM.Core.Options.Restore,
DPM.Core.Project.Interfaces,
DPM.Core.Spec.Interfaces,
DPM.Core.Configuration.Interfaces,
DPM.Core.Repository.Interfaces,
DPM.Core.Cache.Interfaces,
DPM.Core.Dependency.Interfaces,
DPM.Core.Compiler.Interfaces;
type
TPackageInstaller = class(TInterfacedObject, IPackageInstaller)
private
FLogger: ILogger;
FConfigurationManager: IConfigurationManager;
FRepositoryManager: IPackageRepositoryManager;
FPackageCache: IPackageCache;
FDependencyResolver: IDependencyResolver;
FContext: IPackageInstallerContext;
FCompilerFactory: ICompilerFactory;
protected
function Init(const options : TSearchOptions) : IConfiguration;
function GetPackageInfo(const cancellationToken: ICancellationToken; const packageId: IPackageId): IPackageInfo;
function CreateProjectRefs(const cancellationToken: ICancellationToken; const rootnode: IPackageReference; const seenPackages: IDictionary<string, IPackageInfo>;
const projectReferences: IList<TProjectReference>): boolean;
function CollectSearchPaths(const packageGraph: IPackageReference; const resolvedPackages: IList<IPackageInfo>; const compiledPackages: IList<IPackageInfo>;
const compilerVersion: TCompilerVersion; const platform: TDPMPlatform; const searchPaths: IList<string>): boolean;
procedure GenerateSearchPaths(const compilerVersion: TCompilerVersion; const platform: TDPMPlatform; packageSpec: IPackageSpec; const searchPaths: IList<string>);
function DownloadPackages(const cancellationToken: ICancellationToken; const resolvedPackages: IList<IPackageInfo>; var packageSpecs: IDictionary<string, IPackageSpec>): boolean;
function CollectPlatformsFromProjectFiles(const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration) : boolean;
function GetCompilerVersionFromProjectFiles(const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration) : boolean;
function CompilePackage(const cancellationToken: ICancellationToken; const Compiler: ICompiler; const packageInfo: IPackageInfo; const packageReference: IPackageReference;
const packageSpec: IPackageSpec; const force: boolean; const forceDebug : boolean): boolean;
function BuildDependencies(const cancellationToken: ICancellationToken; const packageCompiler: ICompiler; const projectPackageGraph: IPackageReference;
const packagesToCompile: IList<IPackageInfo>; const compiledPackages: IList<IPackageInfo>; packageSpecs: IDictionary<string, IPackageSpec>;
const Options: TSearchOptions): boolean;
function CopyLocal(const cancellationToken: ICancellationToken; const resolvedPackages: IList<IPackageInfo>; const packageSpecs: IDictionary<string, IPackageSpec>;
const projectEditor: IProjectEditor; const platform: TDPMPlatform): boolean;
function InstallDesignPackages(const cancellationToken: ICancellationToken; const projectFile : string; const packageSpecs: IDictionary<string, IPackageSpec>) : boolean;
function DoRestoreProjectForPlatform(const cancellationToken: ICancellationToken; const Options: TRestoreOptions; const projectFile: string; const projectEditor: IProjectEditor;
const platform: TDPMPlatform; const config: IConfiguration; const context: IPackageInstallerContext): boolean;
function DoInstallPackageForPlatform(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const projectFile: string; const projectEditor: IProjectEditor;
const platform: TDPMPlatform; const config: IConfiguration; const context: IPackageInstallerContext): boolean;
function DoUninstallFromProject(const cancellationToken: ICancellationToken; const Options: TUnInstallOptions; const projectFile: string; const projectEditor: IProjectEditor;
const platform: TDPMPlatform; const config: IConfiguration; const context: IPackageInstallerContext): boolean;
function DoCachePackage(const cancellationToken: ICancellationToken; const Options: TCacheOptions; const platform: TDPMPlatform): boolean;
// works out what compiler/platform then calls DoInstallPackage
function InstallPackage(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const projectFile: string; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
// user specified a package file - will install for single compiler/platform - calls InstallPackage
function InstallPackageFromFile(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
// resolves package from id - calls InstallPackage
function InstallPackageFromId(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
function UnInstallFromProject(const cancellationToken: ICancellationToken; const Options: TUnInstallOptions; const projectFile: string; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
function RestoreProject(const cancellationToken: ICancellationToken; const Options: TRestoreOptions; const projectFile: string; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
// calls either InstallPackageFromId or InstallPackageFromFile depending on options.
function Install(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const context: IPackageInstallerContext): boolean;
function Uninstall(const cancellationToken: ICancellationToken; const Options: TUnInstallOptions; const context: IPackageInstallerContext): boolean;
// calls restore project
function Restore(const cancellationToken: ICancellationToken; const Options: TRestoreOptions; const context: IPackageInstallerContext): boolean;
function Remove(const cancellationToken: ICancellationToken; const Options: TUnInstallOptions): boolean;
function Cache(const cancellationToken: ICancellationToken; const Options: TCacheOptions): boolean;
function context: IPackageInstallerContext;
public
constructor Create(const logger: ILogger;
const configurationManager: IConfigurationManager;
const repositoryManager: IPackageRepositoryManager;
const packageCache: IPackageCache;
const dependencyResolver: IDependencyResolver;
const context: IPackageInstallerContext;
const compilerFactory: ICompilerFactory);
end;
implementation
uses
System.IOUtils,
System.Types,
System.SysUtils,
Spring,
Spring.Collections.Extensions,
VSoft.AntPatterns,
DPM.Core.Constants,
DPM.Core.Compiler.BOM,
DPM.Core.Utils.Path,
DPM.Core.Utils.Files,
DPM.Core.Utils.System,
DPM.Core.Project.Editor,
DPM.Core.Project.GroupProjReader,
DPM.Core.Options.List,
DPM.Core.Dependency.Graph,
DPM.Core.Dependency.Version,
DPM.Core.Package.Metadata,
DPM.Core.Spec.Reader,
DPM.Core.Package.InstallerContext;
{ TPackageInstaller }
function TPackageInstaller.Cache(const cancellationToken: ICancellationToken; const Options: TCacheOptions): boolean;
var
config: IConfiguration;
platform: TDPMPlatform;
platforms: TDPMPlatforms;
begin
result := false;
config := Init(Options);
//logged in init
if config = nil then
exit;
platforms := Options.platforms;
if platforms = [] then
platforms := AllPlatforms(Options.compilerVersion);
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit;
Options.platforms := [platform];
result := DoCachePackage(cancellationToken, Options, platform) and result;
end;
end;
function TPackageInstaller.CollectPlatformsFromProjectFiles(const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration): boolean;
var
projectFile: string;
projectEditor: IProjectEditor;
begin
result := true;
for projectFile in projectFiles do
begin
projectEditor := TProjectEditor.Create(FLogger, config,
Options.compilerVersion);
result := result and projectEditor.LoadProject(projectFile);
if result then
Options.platforms := Options.platforms + projectEditor.platforms;
end;
end;
function TPackageInstaller.CollectSearchPaths(const packageGraph: IPackageReference; const resolvedPackages: IList<IPackageInfo>; const compiledPackages: IList<IPackageInfo>;
const compilerVersion: TCompilerVersion; const platform: TDPMPlatform; const searchPaths: IList<string>): boolean;
var
packageInfo: IPackageInfo;
packageMetadata: IPackageMetadata;
packageSearchPath: string;
packageBasePath: string;
begin
result := true;
// we need to apply usesource from the graph to the package info's
packageGraph.VisitDFS(
procedure(const node: IPackageReference)
var
pkgInfo: IPackageInfo;
begin
// not the most efficient thing to do
pkgInfo := resolvedPackages.FirstOrDefault(
function(const pkg: IPackageInfo): boolean
begin
result := SameText(pkg.Id, node.Id);
//FLogger.Debug('Testing pkg [' + pkg.Id + '] against [' + node.Id + ']');
end);
Assert(pkgInfo <> nil, 'pkgInfo is null for id [' + node.Id + '], but should never be');
pkgInfo.UseSource := pkgInfo.UseSource or node.UseSource;
end);
// reverse the list so that we add the paths in reverse order, small optimisation for the compiler.
resolvedPackages.Reverse;
for packageInfo in resolvedPackages do
begin
if (not packageInfo.UseSource) and compiledPackages.Contains(packageInfo)
then
begin
packageBasePath := packageInfo.Id + PathDelim + packageInfo.Version.ToStringNoMeta + PathDelim;
searchPaths.Add(packageBasePath + 'lib');
end
else
begin
packageMetadata := FPackageCache.GetPackageMetadata(packageInfo);
if packageMetadata = nil then
begin
FLogger.Error('Unable to get metadata for package ' + packageInfo.ToString);
exit(false);
end;
packageBasePath := packageMetadata.Id + PathDelim + packageMetadata.Version.ToStringNoMeta + PathDelim;
for packageSearchPath in packageMetadata.searchPaths do
searchPaths.Add(packageBasePath + packageSearchPath);
end;
end;
end;
function TPackageInstaller.CompilePackage(const cancellationToken : ICancellationToken; const Compiler: ICompiler; const packageInfo: IPackageInfo; const packageReference: IPackageReference;
const packageSpec: IPackageSpec; const force: boolean; const forceDebug : boolean): boolean;
var
buildEntry: ISpecBuildEntry;
packagePath: string;
projectFile: string;
searchPaths: IList<string>;
dependency : IPackageReference;
bomNode: IPackageReference;
bomFile: string;
childSearchPath: string;
configuration : string;
procedure DoCopyFiles(const entry: ISpecBuildEntry);
var
copyEntry: ISpecCopyEntry;
antPattern: IAntPattern;
fsPatterns: TArray<IFileSystemPattern>;
fsPattern: IFileSystemPattern;
searchBasePath: string;
Files: TStringDynArray;
f: string;
destFile: string;
begin
for copyEntry in entry.CopyFiles do
begin
FLogger.Debug('Post Compile Copy [' + copyEntry.Source + ']..');
try
// note : this can throw if the source path steps outside of the base path.
searchBasePath := TPathUtils.StripWildCard(TPathUtils.CompressRelativePath(packagePath, copyEntry.Source));
searchBasePath := ExtractFilePath(searchBasePath);
antPattern := TAntPattern.Create(packagePath);
fsPatterns := antPattern.Expand(copyEntry.Source);
for fsPattern in fsPatterns do
begin
ForceDirectories(fsPattern.Directory);
Files := TDirectory.GetFiles(fsPattern.Directory, fsPattern.FileMask, TSearchOption.soTopDirectoryOnly);
for f in Files do
begin
// copy file to lib directory.
if copyEntry.flatten then
destFile := Compiler.LibOutputDir + '\' + ExtractFileName(f)
else
destFile := Compiler.LibOutputDir + '\' +
TPathUtils.StripBase(searchBasePath, f);
ForceDirectories(ExtractFilePath(destFile));
// FLogger.Debug('Copying "' + f + '" to "' + destFile + '"');
TFile.Copy(f, destFile, true);
end;
end;
except
on e: Exception do
begin
FLogger.Error('Error copying files to lib folder : ' + e.Message);
raise;
end;
end;
FLogger.Debug('Post Compile Copy [' + copyEntry.Source + ']..');
end;
end;
begin
result := true;
packagePath := FPackageCache.GetPackagePath(packageInfo);
bomFile := TPath.Combine(packagePath, 'package.bom');
if (not force) and FileExists(bomFile) then
begin
// Compare Bill of materials file against node dependencies to determine if we need to compile or not.
// if the bom file exists that means it was compiled before. We will check that the bom matchs the dependencies
// in the graph
bomNode := TBOMFile.LoadFromFile(FLogger, bomFile);
if bomNode <> nil then
begin
if bomNode.AreEqual(packageReference) then
begin
exit;
end;
end;
end;
// if we get here the previous compliation was done with different dependency versions,
// so we delete the bom and compile again
DeleteFile(bomFile);
for buildEntry in packageSpec.TargetPlatform.BuildEntries do
begin
FLogger.Information('Building project : ' + buildEntry.Project);
projectFile := TPath.Combine(packagePath, buildEntry.Project);
projectFile := TPathUtils.CompressRelativePath('', projectFile);
// if it's a design time package then we need to do a lot more work.
// design time packages are win32 (as the IDE is win32) - since we can
// only have one copy of the design package installed we need to check if
// it has already been installed via another platform.
if forceDebug then
configuration := 'Debug'
else
configuration := buildEntry.Config;
if buildEntry.DesignOnly and (packageInfo.platform <> TDPMPlatform.Win32) then
begin
Compiler.BPLOutputDir := TPath.Combine(packagePath,
buildEntry.BPLOutputDir);
Compiler.LibOutputDir := TPath.Combine(packagePath,
buildEntry.LibOutputDir);
Compiler.Configuration := buildEntry.config;
if Compiler.platform <> TDPMPlatform.Win32 then
begin
Compiler.BPLOutputDir := TPath.Combine(Compiler.BPLOutputDir, 'win32');
Compiler.LibOutputDir := TPath.Combine(Compiler.LibOutputDir, 'win32');
end
else
begin
packageReference.LibPath := Compiler.LibOutputDir;
packageReference.BplPath := Compiler.BPLOutputDir;
end;
if packageReference.HasDependencies then
begin
searchPaths := TCollections.CreateList<string>;
for dependency in packageReference.Dependencies do
begin
childSearchPath := FPackageCache.GetPackagePath(dependency.Id, dependency.Version.ToStringNoMeta, Compiler.compilerVersion, Compiler.platform);
childSearchPath := TPath.Combine(childSearchPath, 'lib\win32');
searchPaths.Add(childSearchPath);
end;
Compiler.SetSearchPaths(searchPaths);
end
else
Compiler.SetSearchPaths(nil);
FLogger.Information('Building project [' + projectFile + '] for design time...');
result := Compiler.BuildProject(cancellationToken, projectFile, configuration, packageInfo.Version, true);
if result then
FLogger.Success('Project [' + buildEntry.Project + '] build succeeded.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
FLogger.NewLine;
end
else
begin
// note we are assuming the build entry paths are all relative.
Compiler.BPLOutputDir := TPath.Combine(packagePath, buildEntry.BPLOutputDir);
Compiler.LibOutputDir := TPath.Combine(packagePath, buildEntry.LibOutputDir);
Compiler.Configuration := buildEntry.config;
packageReference.LibPath := Compiler.LibOutputDir;
packageReference.BplPath := Compiler.BPLOutputDir;
if packageReference.HasDependencies then
begin
searchPaths := TCollections.CreateList<string>;
for dependency in packageReference.Dependencies do
begin
childSearchPath := FPackageCache.GetPackagePath(dependency.Id, dependency.Version.ToStringNoMeta, Compiler.compilerVersion, Compiler.platform);
childSearchPath := TPath.Combine(childSearchPath, 'lib');
searchPaths.Add(childSearchPath);
end;
Compiler.SetSearchPaths(searchPaths);
end
else
Compiler.SetSearchPaths(nil);
result := Compiler.BuildProject(cancellationToken, projectFile, configuration, packageInfo.Version);
if result then
FLogger.Success('Project [' + buildEntry.Project + '] build succeeded.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
FLogger.NewLine;
if buildEntry.BuildForDesign and (Compiler.platform <> TDPMPlatform.Win32)
then
begin
FLogger.Information('Building project [' + projectFile + '] for design time support...');
// if buildForDesign is true, then it means the design time bpl's also reference
// this bpl, so if the platform isn't win32 then we need to build it for win32
Compiler.BPLOutputDir := TPath.Combine(Compiler.BPLOutputDir, 'win32');
Compiler.LibOutputDir := TPath.Combine(Compiler.LibOutputDir, 'win32');
if packageReference.HasDependencies then
begin
searchPaths := TCollections.CreateList<string>;
for dependency in packageReference.Dependencies do
begin
childSearchPath := FPackageCache.GetPackagePath(dependency.Id, dependency.Version.ToStringNoMeta, Compiler.compilerVersion, Compiler.platform);
childSearchPath := TPath.Combine(childSearchPath, 'lib\win32');
searchPaths.Add(childSearchPath);
end;
Compiler.SetSearchPaths(searchPaths);
end
else
Compiler.SetSearchPaths(nil);
result := Compiler.BuildProject(cancellationToken, projectFile, buildEntry.config, packageInfo.Version, true);
if result then
FLogger.Success('Project [' + buildEntry.Project + '] Compiled for designtime Ok.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
end;
if buildEntry.CopyFiles.Any then
DoCopyFiles(buildEntry);
end;
end;
// save the bill of materials file for future reference.
TBOMFile.SaveToFile(FLogger, bomFile, packageReference);
end;
function TPackageInstaller.context: IPackageInstallerContext;
begin
result := FContext;
end;
function TPackageInstaller.CopyLocal(const cancellationToken : ICancellationToken; const resolvedPackages: IList<IPackageInfo>; const packageSpecs: IDictionary<string, IPackageSpec>;
const projectEditor: IProjectEditor; const platform: TDPMPlatform): boolean;
var
configName: string;
projectConfig: IProjectConfiguration;
packageSpec: IPackageSpec;
resolvedPackage: IPackageInfo;
configNames: IReadOnlyList<string>;
outputDir: string;
lastOutputDir: string;
bplSourceFile: string;
bplTargetFile: string;
packageFolder: string;
runtimeCopyLocalFiles: TArray<ISpecBPLEntry>;
runtimeEntry: ISpecBPLEntry;
begin
result := true;
configNames := projectEditor.GetConfigNames;
for resolvedPackage in resolvedPackages do
begin
packageSpec := packageSpecs[LowerCase(resolvedPackage.Id)];
Assert(packageSpec <> nil);
// FLogger.Debug('Copylocal for package [' + resolvedPackage.Id + ']');
// TODO : Is there any point in the copylocal option now.. shouldn't all runtime bpls be copied?
runtimeCopyLocalFiles := packageSpec.TargetPlatform.RuntimeFiles.Where(
function(const entry: ISpecBPLEntry): boolean
begin
result := entry.CopyLocal;
end).ToArray;
// if no runtime bpl's are defined with copylocal in the dspec then there is nothing to do.
if Length(runtimeCopyLocalFiles) = 0 then
continue;
lastOutputDir := '';
packageFolder := FPackageCache.GetPackagePath(resolvedPackage);
// FLogger.Debug('Package folder [' + packageFolder + ']');
for configName in configNames do
begin
if configName = 'Base' then
continue;
// FLogger.Debug('Config [' + configName + ']');
projectConfig := projectEditor.GetProjectConfiguration(configName,
platform);
// we're only doing this for projects using runtime configs.
if not projectConfig.UsesRuntimePackages then
continue;
// FLogger.Debug('uses runtime packages');
outputDir := projectConfig.outputDir;
if (outputDir <> '') and (not SameText(outputDir, lastOutputDir)) then
begin
lastOutputDir := outputDir;
for runtimeEntry in runtimeCopyLocalFiles do
begin
bplSourceFile := TPath.Combine(packageFolder, runtimeEntry.Source);
if not FileExists(bplSourceFile) then
begin
FLogger.Warning('Unabled to find runtime package [' + bplSourceFile + '] during copy local');
continue;
end;
bplTargetFile := TPath.Combine(outputDir,
ExtractFileName(bplSourceFile));
if TPathUtils.IsRelativePath(bplTargetFile) then
begin
bplTargetFile :=
TPath.Combine(ExtractFilePath(projectEditor.projectFile), bplTargetFile);
bplTargetFile := TPathUtils.CompressRelativePath('', bplTargetFile);
end;
// if the file exists already, then we need to work out if they are the same or not.
if FileExists(bplTargetFile) and
TFileUtils.AreSameFiles(bplSourceFile, bplTargetFile) then
continue;
// now actually copy files.
try
ForceDirectories(ExtractFilePath(bplTargetFile));
TFile.Copy(bplSourceFile, bplTargetFile, true);
except
on e: Exception do
begin
FLogger.Warning('Unable to copy runtime package [' + bplSourceFile + '] to [' + bplTargetFile + '] during copy local');
FLogger.Warning(' ' + e.Message);
end;
end;
end;
end;
end;
end;
end;
constructor TPackageInstaller.Create(const logger: ILogger; const configurationManager: IConfigurationManager; const repositoryManager: IPackageRepositoryManager;
const packageCache: IPackageCache; const dependencyResolver: IDependencyResolver; const context: IPackageInstallerContext;
const compilerFactory: ICompilerFactory);
begin
FLogger := logger;
FConfigurationManager := configurationManager;
FRepositoryManager := repositoryManager;
FPackageCache := packageCache;
FDependencyResolver := dependencyResolver;
FContext := context;
FCompilerFactory := compilerFactory;
end;
function TPackageInstaller.GetPackageInfo(const cancellationToken: ICancellationToken; const packageId: IPackageId): IPackageInfo;
begin
result := FPackageCache.GetPackageInfo(cancellationToken, packageId);
if result = nil then
result := FRepositoryManager.GetPackageInfo(cancellationToken, packageId);
end;
function TPackageInstaller.DoCachePackage(const cancellationToken : ICancellationToken; const Options: TCacheOptions; const platform: TDPMPlatform): boolean;
var
packageIdentity: IPackageIdentity;
packageFileName: string;
begin
result := false;
if not Options.Version.IsEmpty then
// sourceName will be empty if we are installing the package from a file
packageIdentity := TPackageIdentity.Create('', Options.packageId, Options.Version, Options.compilerVersion, platform)
else
begin
// no version specified, so we need to get the latest version available;
packageIdentity := FRepositoryManager.FindLatestVersion(cancellationToken, options.PackageId, options.CompilerVersion, TPackageVersion.Empty, platform, Options.PreRelease, options.Sources);
if packageIdentity = nil then
begin
FLogger.Error('Package [' + Options.packageId + '] for platform [' + DPMPlatformToString(platform) + '] not found on any sources');
exit;
end;
end;
FLogger.Information('Caching package ' + packageIdentity.ToString);
if not FPackageCache.EnsurePackage(packageIdentity) then
begin
// not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, packageIdentity, FPackageCache.PackagesFolder, packageFileName) then
begin
if cancellationToken.IsCancelled then
FLogger.Error('Downloading package [' + packageIdentity.ToString + '] cancelled.')
else
FLogger.Error('Failed to download package [' + packageIdentity.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to cache package file [' + packageFileName + '] into the cache');
exit;
end;
end;
result := true;
end;
//convert the dependency graph to a flat list, with the packageinfo (which has dependencies).
function TPackageInstaller.CreateProjectRefs(const cancellationToken : ICancellationToken; const rootnode: IPackageReference; const seenPackages: IDictionary<string, IPackageInfo>;
const projectReferences: IList<TProjectReference>): boolean;
var
dependency: IPackageReference;
info: IPackageInfo;
projectRef: TProjectReference;
begin
result := true;
//breadth first is important here.. we want to process top level nodes first!
for dependency in rootNode.Dependencies do
begin
if seenPackages.TryGetValue(LowerCase(dependency.Id), info) then
begin
// if a node uses source then we need to find the projectRef and update i
if dependency.UseSource then
info.UseSource := true;
end
else
begin
info := GetPackageInfo(cancellationToken, dependency);
if info = nil then
begin
FLogger.Error('Unable to resolve package : ' + dependency.ToIdVersionString);
exit(false);
end;
info.UseSource := dependency.UseSource;
projectRef.Package := info;
projectRef.VersionRange := dependency.SelectedOn;
if projectRef.VersionRange.IsEmpty then
projectRef.VersionRange := TVersionRange.Create(info.Version);
projectRef.ParentId := dependency.Parent.Id;
seenPackages[LowerCase(dependency.Id)] := info;
projectReferences.Add(projectRef);
end;
end;
for dependency in rootnode.Dependencies do
begin
if dependency.HasDependencies then
result := result or CreateProjectRefs(cancellationToken, dependency, seenPackages, projectReferences);
if not result then
exit;
end;
end;
function TPackageInstaller.DoInstallPackageForPlatform(const cancellationToken : ICancellationToken; const Options: TInstallOptions; const projectFile: string;
const projectEditor: IProjectEditor; const platform: TDPMPlatform; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
var
newPackageIdentity: IPackageIdentity;
packageFileName: string;
packageInfo: IPackageInfo; // includes dependencies;
existingPackageRef: IPackageReference;
projectPackageGraph: IPackageReference;
packageSpecs: IDictionary<string, IPackageSpec>;
projectReferences: IList<TProjectReference>;
resolvedPackages: IList<IPackageInfo>;
packagesToCompile: IList<IPackageInfo>;
compiledPackages: IList<IPackageInfo>;
packageSearchPaths: IList<string>;
dependency : IPackageReference;
packageCompiler: ICompiler;
seenPackages: IDictionary<string, IPackageInfo>;
begin
result := false;
projectPackageGraph := projectEditor.GetPackageReferences(platform);
// can return nil
if projectPackageGraph = nil then
projectPackageGraph := TPackageReference.CreateRoot(Options.compilerVersion, platform);
// see if it's already installed.
existingPackageRef := projectPackageGraph.FindDependency(Options.packageId);
if (existingPackageRef <> nil) then
begin
// if it's installed already and we're not forcing it to install then we're done.
if (not (Options.force or Options.IsUpgrade)) and (not existingPackageRef.IsTransitive) then
begin
// Note this error won't show from the IDE as we always force install from the IDE.
FLogger.Error('Package [' + Options.packageId + '] is already installed. Use option -force to force reinstall, or -upgrade to install a different version.');
exit;
end;
// remove it so we can force resolution to happen later.
projectPackageGraph.RemoveTopLevelPackageReference(existingPackageRef.Id);
existingPackageRef := nil; // we no longer need it.
end;
// We could have a transitive dependency that is being promoted.
// Since we want to control what version is installed, we will remove
// any transitive references to that package so the newly installed version
// will take precedence when resolving.
dependency := projectPackageGraph.FindFirstPackageReference(Options.packageId);
while dependency <> nil do
begin
projectPackageGraph.RemovePackageReference(dependency);
dependency := projectPackageGraph.FindFirstPackageReference(Options.packageId);
end;
// if the user specified a version, either the on the command line or via a file then we will use that
if not Options.Version.IsEmpty then
// sourceName will be empty if we are installing the package from a file
newPackageIdentity := TPackageIdentity.Create('', Options.packageId, Options.Version, Options.compilerVersion, platform)
else
begin
// no version specified, so we need to get the latest version available;
newPackageIdentity := FRepositoryManager.FindLatestVersion(cancellationToken, options.PackageId, options.CompilerVersion, TPackageVersion.Empty, platform, Options.PreRelease, options.Sources);
if newPackageIdentity = nil then
begin
FLogger.Error('Package [' + Options.packageId + '] for platform [' + DPMPlatformToString(platform) + '] not found on any sources');
exit;
end;
end;
FLogger.Information('Installing package ' + newPackageIdentity.ToString);
if not FPackageCache.EnsurePackage(newPackageIdentity) then
begin
// not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, newPackageIdentity, FPackageCache.PackagesFolder, packageFileName) then
begin
FLogger.Error('Failed to download package [' + newPackageIdentity.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to install package file [' + packageFileName + '] into the cache');
exit;
end;
end;
// get the package info, which has the dependencies.
packageInfo := GetPackageInfo(cancellationToken, newPackageIdentity);
if packageInfo = nil then
begin
FLogger.Error('Unable to get package info for package [' + newPackageIdentity.ToIdVersionString + ']');
exit(false);
end;
packageInfo.UseSource := Options.UseSource;
// we need this later when collecting search paths.
seenPackages := TCollections.CreateDictionary<string, IPackageInfo>;
projectReferences := TCollections.CreateList<TProjectReference>;
if not CreateProjectRefs(cancellationToken, projectPackageGraph, seenPackages, projectReferences) then
exit;
if not FDependencyResolver.ResolveForInstall(cancellationToken, Options.CompilerVersion, platform, projectFile, Options, packageInfo, projectReferences, projectPackageGraph, resolvedPackages) then
begin
FLogger.Debug('ResolveForInstall failed');
// we need to carry on here as resolution may have failed for another package
// not sure what the best solution is here.. a better resolver perhaps.
exit;
end;
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit(false);
end;
FContext.RecordGraph(projectFile, platform, projectPackageGraph);
// get the package we were installing.
packageInfo := resolvedPackages.FirstOrDefault(
function(const info: IPackageInfo): boolean
begin
result := SameText(info.Id, packageInfo.Id);
end);
// this is just a sanity check, should never happen.
if packageInfo = nil then
begin
FLogger.Error('Something went wrong, resolution did not return installed package!');
exit(false);
end;
// downloads the package files to the cache if they are not already there and
// returns the deserialized dspec as we need it for search paths and design
if not DownloadPackages(cancellationToken, resolvedPackages, packageSpecs) then
exit;
compiledPackages := TCollections.CreateList<IPackageInfo>;
packagesToCompile := TCollections.CreateList<IPackageInfo>(resolvedPackages);
packageSearchPaths := TCollections.CreateList<string>;
packageCompiler := FCompilerFactory.CreateCompiler(Options.compilerVersion, platform);
if not BuildDependencies(cancellationToken, packageCompiler, projectPackageGraph, packagesToCompile, compiledPackages, packageSpecs, Options) then
exit;
if not CollectSearchPaths(projectPackageGraph, resolvedPackages, compiledPackages, projectEditor.compilerVersion, platform, packageSearchPaths) then
exit;
if not CopyLocal(cancellationToken, resolvedPackages, packageSpecs,
projectEditor, platform) then
exit;
if not InstallDesignPackages(cancellationToken, projectFile, packageSpecs) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths,
config.PackageCacheLocation) then
exit;
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
result := projectEditor.SaveProject();
end;
function TPackageInstaller.DoRestoreProjectForPlatform(const cancellationToken : ICancellationToken; const Options: TRestoreOptions; const projectFile: string;
const projectEditor: IProjectEditor; const platform: TDPMPlatform; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
var
projectPackageGraph: IPackageReference;
packageSpecs: IDictionary<string, IPackageSpec>;
projectReferences: IList<TProjectReference>;
resolvedPackages: IList<IPackageInfo>;
packagesToCompile: IList<IPackageInfo>;
compiledPackages: IList<IPackageInfo>;
packageSearchPaths: IList<string>;
packageCompiler: ICompiler;
seenPackages: IDictionary<string, IPackageInfo>;
begin
result := false;
projectPackageGraph := projectEditor.GetPackageReferences(platform);
// can return nil
// if there is no project package graph then there is nothing to do.
if projectPackageGraph = nil then
exit(true);
seenPackages := TCollections.CreateDictionary<string, IPackageInfo>;
projectReferences := TCollections.CreateList<TProjectReference>;
// TODO : Can packagerefs be replaced by just adding the info to the nodes?
if not CreateProjectRefs(cancellationToken, projectPackageGraph, seenPackages, projectReferences) then
exit;
if not FDependencyResolver.ResolveForRestore(cancellationToken, Options.CompilerVersion, platform, projectFile, Options, projectReferences, projectPackageGraph, resolvedPackages) then
exit;
// TODO : The code from here on is the same for install/uninstall/restore - refactor!!!
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit(false);
end;
FContext.RecordGraph(projectFile, platform, projectPackageGraph);
// downloads the package files to the cache if they are not already there and
// returns the deserialized dspec as we need it for search paths and
if not DownloadPackages(cancellationToken, resolvedPackages, packageSpecs) then
exit;
compiledPackages := TCollections.CreateList<IPackageInfo>;
packagesToCompile := TCollections.CreateList<IPackageInfo>(resolvedPackages);
packageSearchPaths := TCollections.CreateList<string>;
packageCompiler := FCompilerFactory.CreateCompiler(Options.compilerVersion, platform);
if not BuildDependencies(cancellationToken, packageCompiler, projectPackageGraph, packagesToCompile, compiledPackages, packageSpecs, Options) then
exit;
if not CollectSearchPaths(projectPackageGraph, resolvedPackages, compiledPackages, projectEditor.compilerVersion, platform, packageSearchPaths) then
exit;
if not CopyLocal(cancellationToken, resolvedPackages, packageSpecs, projectEditor, platform) then
exit;
if not InstallDesignPackages(cancellationToken, projectFile, packageSpecs) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths, config.PackageCacheLocation) then
exit;
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
// TODO : need to detect if anything has actually changed and only save if it has.
// saving triggers the IDE to reload (although we do work around that) - would be good to avoid.
result := projectEditor.SaveProject();
end;
function TPackageInstaller.DoUninstallFromProject(const cancellationToken : ICancellationToken; const Options: TUnInstallOptions;const projectFile: string;
const projectEditor: IProjectEditor; const platform: TDPMPlatform; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
var
projectPackageGraph: IPackageReference;
foundReference: IPackageReference;
begin
projectPackageGraph := projectEditor.GetPackageReferences(platform);
// can return nil
// if there is no project package graph then there is nothing to do.
if projectPackageGraph = nil then
begin
FLogger.Information('Package [' + Options.packageId + '] was not referenced in project [' + projectFile + '] for platform [' + DPMPlatformToString(platform) + '] - nothing to do.');
exit(true);
end;
foundReference := projectPackageGraph.FindDependency(Options.packageId);
if foundReference = nil then
begin
FLogger.Information('Package [' + Options.packageId + '] was not referenced in project [' + projectFile + '] for platform [' + DPMPlatformToString(platform) + '] - nothing to do.');
// TODO : Should this fail with an error? It's a noop
exit(true);
end;
//remove the node from the graph
projectPackageGraph.RemoveTopLevelPackageReference(foundReference.Id);
//TODO : Context - Remove Design Packages if no longer referenced.
//TODO : Tell contect to upgrade graph.
// FContext.PackageGraphTrimmed(projectFile, platform, projectPackageGraph)
//now work out which search paths we can remove;
//walk the package reference tree and check transitive dependencies
foundReference.VisitDFS(
procedure(const node: IPackageReference)
begin
//if there is no other transitive dependency then we can remove
//from the search path.
if not projectPackageGraph.HasAnyDependency(node.Id) then
projectEditor.RemoveFromSearchPath(platform, node.Id);
end);
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
result := projectEditor.SaveProject();
end;
function TPackageInstaller.BuildDependencies(const cancellationToken : ICancellationToken; const packageCompiler: ICompiler; const projectPackageGraph: IPackageReference;
const packagesToCompile: IList<IPackageInfo>; const compiledPackages: IList<IPackageInfo>;
packageSpecs: IDictionary<string, IPackageSpec>; const Options: TSearchOptions): boolean;
begin
result := false;
try
// build the dependency graph in the correct order.
projectPackageGraph.VisitDFS(
procedure(const packageReference: IPackageReference)
var
pkgInfo: IPackageInfo;
Spec: IPackageSpec;
otherNodes: IList<IPackageReference>;
forceCompile: boolean;
begin
Assert(packageReference.IsRoot = false, 'graph should not visit root node');
pkgInfo := packagesToCompile.FirstOrDefault(
function(const value: IPackageInfo): boolean
begin
result := SameText(value.Id, packageReference.Id);
end);
// if it's not found that means we have already processed the package elsewhere in the graph
if pkgInfo = nil then
exit;
// do we need an option to force compilation when restoring?
forceCompile := Options.force and SameText(pkgInfo.Id, Options.SearchTerms); // searchterms backs packageid
// removing it so we don't process it again
packagesToCompile.Remove(pkgInfo);
Spec := packageSpecs[LowerCase(packageReference.Id)];
Assert(Spec <> nil);
if Spec.TargetPlatform.BuildEntries.Any then
begin
// we need to build the package.
if not CompilePackage(cancellationToken, packageCompiler, pkgInfo, packageReference, Spec, forceCompile, Options.DebugMode) then
begin
if cancellationToken.IsCancelled then
raise Exception.Create('Compiling package [' + pkgInfo.ToIdVersionString + '] cancelled.')
else
raise Exception.Create('Compiling package [' + pkgInfo.ToIdVersionString + '] failed.');
end;
compiledPackages.Add(pkgInfo);
// compiling updates the node searchpaths and libpath, so just copy to any same package nodes
otherNodes := projectPackageGraph.FindPackageReferences(packageReference.Id);
if otherNodes.Count > 1 then
otherNodes.ForEach(
procedure(const otherNode: IPackageReference)
begin
otherNode.searchPaths.Clear;
otherNode.searchPaths.AddRange(packageReference.searchPaths);
otherNode.LibPath := packageReference.LibPath;
otherNode.BplPath := packageReference.BplPath;
end);
end;
end);
result := true;
except
on e: Exception do
begin
FLogger.Error(e.Message);
exit;
end;
end;
end;
function TPackageInstaller.DownloadPackages(const cancellationToken : ICancellationToken; const resolvedPackages: IList<IPackageInfo>; var packageSpecs: IDictionary<string, IPackageSpec>): boolean;
var
packageInfo: IPackageInfo;
packageFileName: string;
Spec: IPackageSpec;
begin
result := false;
packageSpecs := TCollections.CreateDictionary<string, IPackageSpec>;
for packageInfo in resolvedPackages do
begin
if cancellationToken.IsCancelled then
exit;
if not FPackageCache.EnsurePackage(packageInfo) then
begin
// not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, packageInfo, FPackageCache.PackagesFolder, packageFileName) then
begin
FLogger.Error('Failed to download package [' +
packageInfo.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to install package file [' + packageFileName + '] into the cache');
exit;
end;
if cancellationToken.IsCancelled then
exit;
end;
if not packageSpecs.ContainsKey(LowerCase(packageInfo.Id)) then
begin
Spec := FPackageCache.GetPackageSpec(packageInfo);
packageSpecs[LowerCase(packageInfo.Id)] := Spec;
end;
end;
result := true;
end;
function TPackageInstaller.InstallPackage(const cancellationToken : ICancellationToken; const Options: TInstallOptions; const projectFile: string;
const config: IConfiguration; const context: IPackageInstallerContext): boolean;
var
projectEditor: IProjectEditor;
platforms: TDPMPlatforms;
platform: TDPMPlatform;
platformResult: boolean;
ambiguousProjectVersion: boolean;
ambiguousVersions: string;
platformOptions: TInstallOptions;
erroredPlatforms : TDPMPlatforms;
begin
result := false;
// make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config,
Options.compilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
ambiguousProjectVersion := IsAmbigousProjectVersion
(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and (Options.compilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions + '), recommend specifying compiler version on command line.');
// if the compiler version was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that version.
if Options.compilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.compilerVersion <> Options.compilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.compilerVersion := Options.compilerVersion;
end;
end
else
Options.compilerVersion := projectEditor.compilerVersion;
// if the platform was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that platform.
if Options.platforms <> [] then
begin
platforms := Options.platforms * projectEditor.platforms;
// gets the intersection of the two sets.
if platforms = [] then // no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile +
'] as it does not match target specified platforms.');
exit;
end;
// TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.platforms;
result := true;
erroredPlatforms := [];
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit;
// do not modify the passed in options!
platformOptions := Options.Clone;
platformOptions.platforms := [platform];
FLogger.Information('Installing [' + platformOptions.SearchTerms + '-' + DPMPlatformToString(platform) + '] into [' + projectFile + ']', true);
platformResult := DoInstallPackageForPlatform(cancellationToken, platformOptions, projectFile, projectEditor, platform, config, context);
if not platformResult then
begin
FLogger.Error('Install failed for [' + platformOptions.SearchTerms + '-' + DPMPlatformToString(platform) + ']');
Include(erroredPlatforms, platform);
end
else
FLogger.Success('Install succeeded for [' + platformOptions.SearchTerms + '-' + DPMPlatformToString(platform) + ']', true);
result := platformResult and result;
FLogger.Information('');
end;
if not result then
FLogger.Error('Install failed for [' + Options.SearchTerms + '] on platforms [' + DPMPlatformsToString(erroredPlatforms) + ']')
end;
procedure TPackageInstaller.GenerateSearchPaths(const compilerVersion : TCompilerVersion; const platform: TDPMPlatform; packageSpec: IPackageSpec; const searchPaths: IList<string>);
var
packageBasePath: string;
packageSearchPath: ISpecSearchPath;
begin
packageBasePath := packageSpec.Metadata.Id + PathDelim + packageSpec.Metadata.Version.ToStringNoMeta + PathDelim;
for packageSearchPath in packageSpec.TargetPlatform.searchPaths do
searchPaths.Add(packageBasePath + packageSearchPath.Path);
end;
function TPackageInstaller.GetCompilerVersionFromProjectFiles(const Options: TInstallOptions; const projectFiles: TArray<string>; const config: IConfiguration): boolean;
var
projectFile: string;
projectEditor: IProjectEditor;
compilerVersion: TCompilerVersion;
bFirst: boolean;
begin
result := true;
compilerVersion := TCompilerVersion.UnknownVersion;
bFirst := true;
for projectFile in projectFiles do
begin
projectEditor := TProjectEditor.Create(FLogger, config, Options.compilerVersion);
result := result and projectEditor.LoadProject(projectFile);
if result then
begin
if not bFirst then
begin
if projectEditor.compilerVersion <> compilerVersion then
begin
FLogger.Error('Projects are not all the for same compiler version.');
result := false;
end;
end;
compilerVersion := Options.compilerVersion;
Options.compilerVersion := projectEditor.compilerVersion;
bFirst := false;
end;
end;
end;
function TPackageInstaller.Init(const options: TSearchOptions): IConfiguration;
begin
result := nil;
if (not Options.Validated) and (not Options.Validate(FLogger)) then
exit
else if not Options.IsValid then
exit;
result := FConfigurationManager.LoadConfig(Options.ConfigFile);
if result = nil then
exit;
FPackageCache.Location := result.PackageCacheLocation;
//also inits the repository manager.
if not FDependencyResolver.Initialize(result) then
begin
FLogger.Error('Unable to initialize the dependency manager.');
exit(nil);
end;
if not FRepositoryManager.HasSources then
begin
FLogger.Error
('No package sources are defined. Use `dpm sources add` command to add a package source.');
exit(nil);
end;
end;
function TPackageInstaller.Install(const cancellationToken: ICancellationToken; const Options: TInstallOptions; const context: IPackageInstallerContext): boolean;
var
projectFiles: TArray<string>;
config: IConfiguration;
GroupProjReader: IGroupProjectReader;
projectList: IList<string>;
i: integer;
projectRoot: string;
begin
result := false;
try
config := Init(Options);
//logged in Init
if config = nil then
exit;
if Length(options.Projects) > 0 then
begin
projectFiles := options.Projects;
end
else if FileExists(Options.ProjectPath) then
begin
if ExtractFileExt(Options.ProjectPath) = '.groupproj' then
begin
GroupProjReader := TGroupProjectReader.Create(FLogger);
if not GroupProjReader.LoadGroupProj(Options.ProjectPath) then
exit;
projectList := TCollections.CreateList<string>;
if not GroupProjReader.ExtractProjects(projectList) then
exit;
// projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(Options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
// sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
// TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot,
projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := Options.ProjectPath;
end;
end
else if DirectoryExists(Options.ProjectPath) then
begin
projectFiles := TArray<string>(TDirectory.GetFiles(Options.ProjectPath, '*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No dproj files found in projectPath : ' + Options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) + ' dproj file(s) to install into.');
end
else
begin
// should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
if Options.PackageFile <> '' then
begin
if not FileExists(Options.PackageFile) then
begin
// should never happen if validation is called on the options.
FLogger.Error('The specified packageFile [' + Options.PackageFile + '] does not exist.');
exit;
end;
result := InstallPackageFromFile(cancellationToken, Options, TArray<string>(projectFiles), config, context);
end
else
result := InstallPackageFromId(cancellationToken, Options, TArray<string>(projectFiles), config, context);
except
on e: Exception do
begin
FLogger.Error(e.Message);
result := false;
end;
end;
end;
function TPackageInstaller.InstallDesignPackages(const cancellationToken: ICancellationToken; const projectFile : string; const packageSpecs: IDictionary<string, IPackageSpec>): boolean;
begin
//Note : we delegate this to the context as this is a no-op in the command line tool, the IDE plugin provides it's own context implementation.
result := FContext.InstallDesignPackages(cancellationToken, projectFile, packageSpecs);
end;
function TPackageInstaller.InstallPackageFromFile(const cancellationToken : ICancellationToken; const Options: TInstallOptions;const projectFiles: TArray<string>;
const config: IConfiguration; const context: IPackageInstallerContext): boolean;
var
packageIdString: string;
packageIdentity: IPackageIdentity;
projectFile: string;
i: integer;
begin
// get the package into the cache first then just install as normal
result := FPackageCache.InstallPackageFromFile(Options.PackageFile, true);
if not result then
exit;
// get the identity so we can get the compiler version
packageIdString := ExtractFileName(Options.PackageFile);
packageIdString := ChangeFileExt(packageIdString, '');
if not TPackageIdentity.TryCreateFromString(FLogger, packageIdString, '', packageIdentity) then
exit;
// update options so we can install from the packageid.
Options.PackageFile := '';
Options.packageId := packageIdentity.Id + '.' + packageIdentity.Version.ToStringNoMeta;
Options.compilerVersion := packageIdentity.compilerVersion;
// package file is for single compiler version
Options.platforms := [packageIdentity.platform];
// package file is for single platform.
for i := 0 to Length(projectFiles) - 1 do
begin
if cancellationToken.IsCancelled then
exit;
projectFile := projectFiles[i];
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
result := InstallPackage(cancellationToken, Options, projectFile, config, context) and result;
end;
end;
function TPackageInstaller.InstallPackageFromId(const cancellationToken : ICancellationToken; const Options: TInstallOptions; const projectFiles: TArray<string>;
const config: IConfiguration; const context: IPackageInstallerContext): boolean;
var
projectFile: string;
i: integer;
begin
result := true;
for i := 0 to Length(projectFiles) - 1 do
begin
if cancellationToken.IsCancelled then
exit;
projectFile := projectFiles[i];
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
result := InstallPackage(cancellationToken, Options, projectFile, config, context) and result;
end;
end;
function TPackageInstaller.Remove(const cancellationToken: ICancellationToken; const Options: TUnInstallOptions): boolean;
begin
result := false;
end;
function TPackageInstaller.Restore(const cancellationToken: ICancellationToken; const Options: TRestoreOptions; const context: IPackageInstallerContext): boolean;
var
projectFiles: TArray<string>;
projectFile: string;
config: IConfiguration;
GroupProjReader: IGroupProjectReader;
projectList: IList<string>;
i: integer;
projectRoot: string;
stopwatch : TStopwatch;
begin
result := false;
stopwatch := TStopwatch.Create;
stopwatch.Start;
try
config := Init(Options);
//logged in init
if config = nil then
exit;
if FileExists(Options.ProjectPath) then
begin
// TODO : If we are using a groupProj then we shouldn't allow different versions of a package in different projects
// need to work out how to detect this.
if ExtractFileExt(Options.ProjectPath) = '.groupproj' then
begin
GroupProjReader := TGroupProjectReader.Create(FLogger);
if not GroupProjReader.LoadGroupProj(Options.ProjectPath) then
exit;
projectList := TCollections.CreateList<string>;
if not GroupProjReader.ExtractProjects(projectList) then
exit;
// projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(Options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
// sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
// TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot, projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := Options.ProjectPath;
end;
end
else if DirectoryExists(Options.ProjectPath) then
begin
// todo : add groupproj support!
projectFiles := TArray<string>(TDirectory.GetFiles(Options.ProjectPath,
'*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No project files found in projectPath : ' + Options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) +' project file(s) to restore.');
end
else
begin
// should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
result := true;
for i := 0 to Length(projectFiles) - 1 do
begin
if cancellationToken.IsCancelled then
exit;
projectFile := projectFiles[i];
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
// order is important so we avoid shortcut boolean eval
result := RestoreProject(cancellationToken, Options, projectFile, config, context) and result;
end;
stopwatch.Stop;
if result then
FLogger.Success('Restore succeeded in [' + IntToStr(stopwatch.ElapsedMilliseconds) + '] ms', true)
else
FLogger.Error('Restore failed in [' + IntToStr(stopwatch.ElapsedMilliseconds) + '] ms');
except
on e: Exception do
begin
FLogger.Error(e.Message);
result := false;
end;
end;
end;
function TPackageInstaller.RestoreProject(const cancellationToken : ICancellationToken; const Options: TRestoreOptions; const projectFile: string; const config: IConfiguration;
const context: IPackageInstallerContext): boolean;
var
projectEditor: IProjectEditor;
platforms: TDPMPlatforms;
platform: TDPMPlatform;
errorPlatforms : TDPMPlatforms;
platformResult: boolean;
ambiguousProjectVersion: boolean;
ambiguousVersions: string;
platformOptions: TRestoreOptions;
begin
result := false;
// make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config, Options.compilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
if cancellationToken.IsCancelled then
exit;
ambiguousProjectVersion := IsAmbigousProjectVersion(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and
(Options.compilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions + '), recommend specifying compiler version on command line.');
// if the compiler version was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that version.
if Options.compilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.compilerVersion <> Options.compilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.compilerVersion := Options.compilerVersion;
end;
end
else
Options.compilerVersion := projectEditor.compilerVersion;
FLogger.Information('Restoring for compiler version [' + CompilerToString(Options.compilerVersion) + '].', true);
// if the platform was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that platform.
if Options.platforms <> [] then
begin
platforms := Options.platforms * projectEditor.platforms;
// gets the intersection of the two sets.
if platforms = [] then // no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile + '] as it does not match specified platforms.');
exit;
end;
// TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.platforms;
result := true;
errorPlatforms := [];
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit(false);
// do not modify options here!
platformOptions := Options.Clone;
platformOptions.platforms := [platform];
FLogger.Information('Restoring project [' + projectFile + '] for [' + DPMPlatformToString(platform) + ']', true);
platformResult := DoRestoreProjectForPlatform(cancellationToken, platformOptions, projectFile, projectEditor, platform, config, context);
if not platformResult then
begin
if cancellationToken.IsCancelled then
FLogger.Error('Restore Cancelled.')
else
begin
FLogger.Error('Restore failed for ' + DPMPlatformToString(platform));
Include(errorPlatforms, platform);
end;
end
else
FLogger.Success('Restore succeeded for ' + DPMPlatformToString(platform), true);
result := platformResult and result;
FLogger.Information('');
end;
if not result then
FLogger.Error('Restore failed for [' + projectFile + '] on platforms [' + DPMPlatformsToString(errorPlatforms) + ']')
end;
function TPackageInstaller.Uninstall(const cancellationToken : ICancellationToken; const Options: TUnInstallOptions; const context: IPackageInstallerContext): boolean;
var
projectFiles: TArray<string>;
projectFile: string;
config: IConfiguration;
GroupProjReader: IGroupProjectReader;
projectList: IList<string>;
i: integer;
projectRoot: string;
begin
result := false;
// commandline would have validated already, but IDE probably not.
if (not Options.Validated) and (not Options.Validate(FLogger)) then
exit
else if not Options.IsValid then
exit;
config := FConfigurationManager.LoadConfig(Options.ConfigFile);
if config = nil then // no need to log, config manager will
exit;
FDependencyResolver.Initialize(config);
FPackageCache.Location := config.PackageCacheLocation;
if not FRepositoryManager.Initialize(config) then
begin
FLogger.Error('Unable to initialize the repository manager.');
exit;
end;
if Length(options.Projects) > 0 then
begin
projectFiles := options.Projects;
end
else if FileExists(Options.ProjectPath) then
begin
// TODO : If we are using a groupProj then we shouldn't allow different versions of a package in different projects
// need to work out how to detect this.
if ExtractFileExt(Options.ProjectPath) = '.groupproj' then
begin
GroupProjReader := TGroupProjectReader.Create(FLogger);
if not GroupProjReader.LoadGroupProj(Options.ProjectPath) then
exit;
projectList := TCollections.CreateList<string>;
if not GroupProjReader.ExtractProjects(projectList) then
exit;
// projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(Options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
// sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
// TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot, projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := Options.ProjectPath;
end;
end
else if DirectoryExists(Options.ProjectPath) then
begin
// todo : add groupproj support!
projectFiles := TArray<string>(TDirectory.GetFiles(Options.ProjectPath, '*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No project files found in projectPath : ' + Options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) + ' project file(s) to uninstall from.');
end
else
begin
// should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
result := true;
// TODO : create some sort of context object here to pass in so we can collect runtime/design time packages
for projectFile in projectFiles do
begin
if cancellationToken.IsCancelled then
exit;
result := UnInstallFromProject(cancellationToken, Options, projectFile, config, context) and result;
end;
end;
function TPackageInstaller.UnInstallFromProject(const cancellationToken : ICancellationToken; const Options: TUnInstallOptions; const projectFile: string;
const config: IConfiguration; const context: IPackageInstallerContext): boolean;
var
projectEditor: IProjectEditor;
platforms: TDPMPlatforms;
platform: TDPMPlatform;
platformResult: boolean;
ambiguousProjectVersion: boolean;
ambiguousVersions: string;
begin
result := false;
// make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config,
Options.compilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
if cancellationToken.IsCancelled then
exit;
ambiguousProjectVersion := IsAmbigousProjectVersion
(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and
(Options.compilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions + '), recommend specifying compiler version on command line.');
// if the compiler version was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that version.
if Options.compilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.compilerVersion <> Options.compilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.compilerVersion := Options.compilerVersion;
end;
end
else
Options.compilerVersion := projectEditor.compilerVersion;
FLogger.Information('Uninstalling for compiler version [' + CompilerToString(Options.compilerVersion) + '].', true);
// if the platform was specified (either on the command like or through a package file)
// then make sure our dproj is actually for that platform.
if Options.platforms <> [] then
begin
platforms := Options.platforms * projectEditor.platforms;
// gets the intersection of the two sets.
if platforms = [] then // no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile + '] as it does not match specified platforms.');
exit;
end;
// TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.platforms;
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit(false);
Options.platforms := [platform];
FLogger.Information('Uninstalling from project [' + projectFile + '] for ['
+ DPMPlatformToString(platform) + ']', true);
platformResult := DoUninstallFromProject(cancellationToken, Options,
projectFile, projectEditor, platform, config, context);
if not platformResult then
FLogger.Error('Uninstall failed for ' + DPMPlatformToString(platform))
else
FLogger.Success('Uninstall succeeded for ' + DPMPlatformToString(platform), true);
result := platformResult and result;
FLogger.Information('');
end;
end;
end.
|
unit NetUtils;
{**********************************************
Kingstar Delphi Library
Copyright (C) Kingstar Corporation
<Unit> NetUtils
<What> 有关网络的工具
<Written By> Huang YanLai
<History>
**********************************************}
interface
uses Windows, SysUtils, WinSock, Nb30;
type
TAdapter = packed record
adapt : TADAPTERSTATUS;
NameBuff : array[0..30-1] of Char;
end;
{
<Function>GetMACAddr
<What>获得网卡地址
<Params>
-
<Return>
<Exception>
}
function GetMACAddr : string;
procedure SocketError(ErrorCode : Integer; const Msg : string);
procedure CheckSocketCall(ReturnCode : Integer; const Msg : string);
const
DefaultMaxLength = 8*1024;
type
EKSSocketError = class(Exception);
TKSUDPMessage = class(TObject)
private
FAddr : TSockAddr;
FMessage: string;
function GetIP: string;
function GetPort: Word;
procedure SetIP(const Value: string);
procedure SetPort(const Value: Word);
public
constructor Create;
property Message : string read FMessage write FMessage;
property IP : string read GetIP write SetIP;
property Port : Word read GetPort write SetPort;
end;
TKSUDPSocket = class
private
FPort: Word;
FSocket : TSOCKET;
FAddr : TSockAddr;
FPeerPort: Integer;
FPeerIP: string;
FMaxMessageLength: LongWord;
public
// 创建套接字,绑定到指定的端口
constructor Create(APort : Word=0);
destructor Destroy; override;
// 设置需要通讯的目的地址,方便使用Send
procedure SetPeer(const ToIP : string; ToPort : Word);
// 向SetPeer设定的目的地址发送消息,返回实际发送的字节数。
function Send(Buffer : Pointer; Count : Longword) : Integer; overload;
// 向指定的目的地址发送消息,地址由ToIP,ToPort指定,返回实际发送的字节数。
function SendTo(const ToIP : string; ToPort : Word; Buffer : Pointer; Count : Longword) : Integer; overload;
// 向指定的目的地址发送消息,地址由ToAddr指定,返回实际发送的字节数。
function SendTo(var ToAddr : TSockAddr; Buffer : Pointer; Count : Longword) : Integer; overload;
// 检查是否有数据到达,TimeOut的单位是毫秒
function IsDataArrived(TimeOut : LongWord) : Boolean;
// 阻塞方式接收数据,返回接收到的字节数
function Receive(Buffer : Pointer; MaxCount : Longword) : Integer; overload;
// 阻塞方式接收数据,返回接收到的字节数。FromAddr返回消息的来源地址
function Receive(Buffer : Pointer; MaxCount : Longword; var FromAddr : TSockAddr) : Integer; overload;
// 发送字符串消息,目的地址已经由SetPeer设置好了
function SendMessage(const Msg : string) : Integer;
// 接收字符串消息,MaxLength代表最大的字符串长度
function ReceiveMessage(MaxLength : Integer=DefaultMaxLength) : string;
// 发送一个字符串消息,目的地址和消息由MsgObj对象指定
procedure Send(MsgObj : TKSUDPMessage); overload;
// 返回接收到的消息,消息和来源地址保存到MsgObj对象里面。
procedure Receive(MsgObj : TKSUDPMessage); overload;
// 使得可以广播消息
procedure EnableBroadcast;
// 获得最大的消息大小
function GetMaxPackageSize : Integer;
// 广播消息
function Broadcast(ToPort : Word; Buffer : Pointer; Count : Longword) : Integer;
property Port : Word read FPort;
property Socket : TSOCKET read FSocket;
property PeerIP : string read FPeerIP;
property PeerPort : Integer read FPeerPort;
property MaxMessageLength : LongWord read FMaxMessageLength write FMaxMessageLength;
end;
resourcestring
SSendOutOfLength = '发送数据的长度超过允许的范围';
sWindowsSocketError = 'Windows socket error: %s (%d), on API ''%s''';
implementation
uses Registry, Classes;
{
function GetMACAddr : string;
const
MaxLength = 6;
var
reg : TRegistry;
Buffer : array[0..MaxLength-1] of char;
TextBuffer : array[0..MaxLength*2] of char;
count : integer;
begin
reg := TRegistry.Create(KEY_READ);
try
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKeyReadOnly('\Software\Description\Microsoft\Rpc\UuidTemporaryData');
fillChar(Buffer,MaxLength,0);
fillChar(TextBuffer,MaxLength*2+1,0);
count := reg.ReadBinaryData('NetworkAddress',Buffer,MaxLength);
assert(count=MaxLength);
BinToHex(Buffer,TextBuffer,count);
Result := TextBuffer;
finally
reg.free;
end;
end;
}
(*
function GetMACAddr : string;
var
Ncb : TNCB ;
uRetCode : Char;
lenum : TLANAENUM;
I, Len : Integer;
Adapter : TAdapter;
begin
Result := '';
FillChar(Ncb, sizeof(Ncb), 0);
Ncb.ncb_command := Char(NCBENUM);
Ncb.ncb_buffer := @lenum;
Ncb.ncb_length := SizeOf(lenum);
{uRetCode := }Netbios(@Ncb);
Len := Byte(lenum.length);
for I:=0 to Len do
begin
FillChar(Ncb, sizeof(Ncb), 0);
Ncb.ncb_command := Char(NCBRESET);
Ncb.ncb_lana_num := lenum.lana[i];
{uRetCode := }Netbios(@Ncb);
FillChar(Ncb, sizeof(Ncb), 0);
Ncb.ncb_command := Char(NCBASTAT);
Ncb.ncb_lana_num := lenum.lana[i];
strcopy(PChar(@Ncb.ncb_callname),'* ' );
Ncb.ncb_buffer := @Adapter;
Ncb.ncb_length := sizeof(Adapter);
uRetCode := Netbios(@Ncb);
if (Byte(uRetCode)= 0) then
begin
Result := Format('%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x',
[
Byte(Adapter.adapt.adapter_address[0]),
Byte(Adapter.adapt.adapter_address[1]),
Byte(Adapter.adapt.adapter_address[2]),
Byte(Adapter.adapt.adapter_address[3]),
Byte(Adapter.adapt.adapter_address[4]),
Byte(Adapter.adapt.adapter_address[5])
]);
Break;
end;
end;
end;
*)
function GetMACAddr : string;
var
Ncb : TNCB ;
uRetCode : Char;
I : Integer;
Adapter : TAdapter;
begin
Result := '';
for I:=0 to 255 do
begin
FillChar(Ncb, sizeof(Ncb), 0);
Ncb.ncb_command := Char(NCBRESET);
Ncb.ncb_lana_num := Char(I);
Netbios(@Ncb);
FillChar(Ncb, sizeof(Ncb), 0);
Ncb.ncb_command := Char(NCBASTAT);
Ncb.ncb_lana_num := Char(I);
strcopy(PChar(@Ncb.ncb_callname),'* ' );
Ncb.ncb_buffer := @Adapter;
Ncb.ncb_length := sizeof(Adapter);
uRetCode := Netbios(@Ncb);
if (Byte(uRetCode)= 0) then
begin
Result := Format('%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x',
[
Byte(Adapter.adapt.adapter_address[0]),
Byte(Adapter.adapt.adapter_address[1]),
Byte(Adapter.adapt.adapter_address[2]),
Byte(Adapter.adapt.adapter_address[3]),
Byte(Adapter.adapt.adapter_address[4]),
Byte(Adapter.adapt.adapter_address[5])
]);
Break;
end;
end;
end;
procedure SocketError(ErrorCode : Integer; const Msg : string);
begin
if ErrorCode=0 then
ErrorCode:=WSAGetLastError;
raise EKSSocketError.CreateResFmt(@sWindowsSocketError,
[SysErrorMessage(ErrorCode), ErrorCode, Msg]);
end;
procedure CheckSocketCall(ReturnCode : Integer; const Msg : string);
begin
if ReturnCode=SOCKET_ERROR then
SocketError(0,Msg);
end;
procedure Startup;
var
ErrorCode: Integer;
WSAData : TWSAData;
begin
ErrorCode := WSAStartup($0101, WSAData);
if ErrorCode <> 0 then
SocketError(ErrorCode, 'WSAStartup');
end;
procedure Cleanup;
var
ErrorCode: Integer;
begin
ErrorCode := WSACleanup;
if ErrorCode <> 0 then
SocketError(ErrorCode, 'WSACleanup');
end;
{ TKSUDPSocket }
constructor TKSUDPSocket.Create(APort: Word);
var
Addr : TSockAddr;
begin
FPort := APort;
FSocket := WinSock.socket(AF_INET, SOCK_DGRAM , IPPROTO_IP);
if FSocket=INVALID_SOCKET then
SocketError(0, 'socket');
with Addr do
begin
sin_family := AF_INET;
sin_port := htons(FPort);
sin_addr.S_addr := INADDR_ANY;
fillchar(sin_zero,sizeof(sin_zero),0);
end;
CheckSocketCall(
WinSock.bind(FSocket,Addr,Sizeof(Addr)),
'bind');
FMaxMessageLength := GetMaxPackageSize;
if FMaxMessageLength>DefaultMaxLength then
FMaxMessageLength:=DefaultMaxLength;
end;
destructor TKSUDPSocket.Destroy;
begin
WinSock.closesocket(FSocket);
inherited;
end;
function TKSUDPSocket.IsDataArrived(TimeOut : LongWord): Boolean;
var
FDSet: TFDSet;
TimeVal: TTimeVal;
I : Integer;
begin
FD_ZERO(FDSet);
FD_SET(FSocket, FDSet);
TimeVal.tv_sec := TimeOut div 1000;
TimeVal.tv_usec := TimeOut mod 1000;
I := WinSock.select(0, @FDSet, nil, nil, @TimeVal);
Result := I>0;
CheckSocketCall(I,'select');
end;
function TKSUDPSocket.Receive(Buffer: Pointer;
MaxCount: Longword): Integer;
var
Addr : TSockAddr;
begin
Result := Receive(Buffer,MaxCount, Addr);
end;
function TKSUDPSocket.Receive(Buffer: Pointer; MaxCount: Longword;
var FromAddr: TSockAddr): Integer;
var
FromSize : Integer;
begin
FromSize := SizeOf(FromAddr);
Result := WinSock.recvfrom(FSocket,Buffer^,MaxCount, 0, FromAddr,FromSize);
CheckSocketCall(Result,'recvfrom');
end;
function TKSUDPSocket.ReceiveMessage(MaxLength: Integer): string;
var
Len : Integer;
begin
SetLength(Result,MaxLength);
Len := Receive(PChar(Result),MaxLength);
SetLength(Result,Len);
end;
function TKSUDPSocket.Send(Buffer: Pointer; Count: Longword): Integer;
begin
Result := SendTo(FAddr, Buffer, Count);
end;
function TKSUDPSocket.SendTo(const ToIP: string; ToPort: Word;
Buffer: Pointer; Count: Longword): Integer;
var
ToAddr: TSockAddr;
begin
with ToAddr do
begin
sin_family := AF_INET;
sin_port := htons(ToPort);
sin_addr.S_addr := inet_addr(PChar(ToIP));
Fillchar(sin_zero,sizeof(sin_zero),0);
end;
Result := SendTo(ToAddr, Buffer, Count);
end;
function TKSUDPSocket.SendMessage(const Msg: string): Integer;
begin
Result := Send(PChar(Msg),Length(Msg));
end;
function TKSUDPSocket.SendTo(var ToAddr: TSockAddr; Buffer: Pointer;
Count: Longword): Integer;
begin
Result := WinSock.sendto(FSocket,
Buffer^,
Count,
0,
ToAddr,
Sizeof(ToAddr));
CheckSocketCall(Result, 'sendto');
end;
procedure TKSUDPSocket.SetPeer(const ToIP: string; ToPort: Word);
begin
FPeerIP := ToIP;
FPeerPort := ToPort;
with FAddr do
begin
sin_family := AF_INET;
sin_port := htons(ToPort);
sin_addr.S_addr := inet_addr(PChar(ToIP));
Fillchar(sin_zero,sizeof(sin_zero),0);
end;
end;
procedure TKSUDPSocket.Receive(MsgObj: TKSUDPMessage);
var
Len : Integer;
begin
SetLength(MsgObj.FMessage,MaxMessageLength);
Len := Receive(PChar(MsgObj.FMessage),MaxMessageLength,MsgObj.FAddr);
SetLength(MsgObj.FMessage,Len);
end;
procedure TKSUDPSocket.Send(MsgObj: TKSUDPMessage);
var
Len1,Len2 : Integer;
begin
Len1 := Length(MsgObj.FMessage);
Len2 := SendTo(MsgObj.FAddr,PChar(MsgObj.FMessage),Len1);
if Len2<Len1 then
raise EKSSocketError.Create(SSendOutOfLength);
end;
procedure TKSUDPSocket.EnableBroadcast;
var
EnableFlag : integer;
begin
EnableFlag := 1;
CheckSocketCall(
WinSock.setsockopt(FSocket,SOL_SOCKET,SO_BROADCAST,@EnableFlag,sizeof(EnableFlag)),
'setsockopt');
end;
const
SO_MAX_MSG_SIZE = $2003;
function TKSUDPSocket.GetMaxPackageSize: Integer;
var
ASize : Integer;
begin
ASize := SizeOf(Result);
CheckSocketCall(
WinSock.getsockopt(FSocket,SOL_SOCKET,SO_MAX_MSG_SIZE,PChar(@Result), ASize),
'getsockopt'
);
end;
function TKSUDPSocket.Broadcast(ToPort: Word; Buffer: Pointer;
Count: Longword): Integer;
var
ToAddr: TSockAddr;
begin
with ToAddr do
begin
sin_family := AF_INET;
sin_port := htons(ToPort);
//LongWord(sin_addr.S_addr) := INADDR_BROADCAST;
sin_addr.S_addr := LongInt(INADDR_BROADCAST);
Fillchar(sin_zero,sizeof(sin_zero),0);
end;
Result := SendTo(ToAddr, Buffer, Count);
end;
{ TKSUDPMessage }
constructor TKSUDPMessage.Create;
begin
with FAddr do
begin
sin_family := AF_INET;
sin_port := WinSock.htons(0);
sin_addr.S_addr := INADDR_ANY;
fillchar(sin_zero,sizeof(sin_zero),0);
end;
end;
function TKSUDPMessage.GetIP: string;
begin
Result := WinSock.inet_ntoa(FAddr.sin_addr);
end;
function TKSUDPMessage.GetPort: Word;
begin
Result := WinSock.ntohs(FAddr.sin_Port);
end;
procedure TKSUDPMessage.SetIP(const Value: string);
begin
FAddr.sin_addr.S_addr := WinSock.inet_addr(PChar(Value));
end;
procedure TKSUDPMessage.SetPort(const Value: Word);
begin
FAddr.sin_Port := WinSock.htons(Value);
end;
initialization
Startup;
finalization
Cleanup;
end.
|
unit nsThreadUtils;
interface
uses
nsXPCOM, nsTypes, nsGeckoStrings;
type
nsIEnvironment = interface;
nsIEventTarget = interface;
nsIProcess = interface;
nsIRunnable = interface;
nsISupportsPriority = interface;
nsIThread = interface;
nsIThreadInternal = interface;
nsIThreadObserver = interface;
nsIThreadEventFilter = interface;
nsIThreadManager = interface;
nsIThreadPoolListener = interface;
nsIThreadPool = interface;
nsITimer = interface;
nsIEnvironment = interface(nsISupports)
['{101d5941-d820-4e85-a266-9a3469940807}']
procedure _set(aName: nsAString; aValue: nsAString); safecall;
procedure get(aName: nsAString; aResult: nsAString); safecall;
function exists(aName: nsAString): PRBool; safecall;
end;
nsIEventTarget = interface(nsISupports)
['{4e8febe4-6631-49dc-8ac9-308c1cb9b09c}']
procedure dispatch(event: nsIRunnable; flags: PRUint32); safecall;
function isOnCurrentThread(): PRBool; safecall;
end;
nsIProcess = interface(nsISupports)
['{9da0b650-d07e-4617-a18a-250035572ac8}']
procedure init(aExecutable: nsIFile); safecall;
procedure initWithPid(aPid: PRUint32); safecall;
procedure kill(); safecall;
function run(aBlocking: PRBool; aArgs: PAnsiCharArray; aCount: PRUint32): PRUint32; safecall;
function getLocation(): nsIFile; safecall;
property location: nsIFile read getLocation;
function getPid(): PRUint32; safecall;
property pid: PRUint32 read getPid;
function getProcessName(): PAnsiChar; safecall;
property processName: PAnsiChar read getProcessName;
function getProcessSignature: PRUint32; safecall;
property processSignature: PRUint32 read getProcessSignature;
function getExitValue: PRInt32; safecall;
property exitValue: PRInt32 read getExitValue;
end;
nsIRunnable = interface(nsISupports)
['{4a2abaf0-6886-11d3-9382-00104ba0fd40}']
procedure run(); safecall;
end;
nsISupportsPriority = interface(nsISupports)
['{aa578b44-abd5-4c19-8b14-36d4de6fdc36}']
function getPriority: PRInt32; safecall;
procedure setPriority(aValue: PRInt32); safecall;
property priority: PRInt32 read getPriority write setPriority;
procedure adjustPriority(aDelta: PRInt32); safecall;
end;
nsIThread = interface(nsIEventTarget)
['{9c889946-a73a-4af3-ae9a-ea64f7d4e3ca}']
function getPRThread: Pointer; safecall;
property PRThread: Pointer read getPRThread;
procedure shutdown(); safecall;
function hasPendingEvents(): PRBool; safecall;
function processNextEvent(mayWait: PRBool): PRBool; safecall;
end;
nsIThreadInternal = interface(nsISupports)
['{f89b5063-b06d-42f8-bf23-4dfcf2d80d6a}']
function getObserver: nsIThreadObserver; safecall;
procedure setObserver(aValue: nsIThreadObserver); safecall;
property observer: nsIThreadObserver read getObserver write setObserver;
procedure pushEventQueue(aFilter: nsIThreadEventFilter); safecall;
procedure popEventQueue(); safecall;
end;
nsIThreadObserver = interface(nsISupports)
['{81D0B509-F198-4417-8020-08EB4271491F}']
procedure onDispatchedEvent(aThread: nsIThreadInternal); safecall;
procedure onProcessNextEvent(aThread: nsIThreadInternal; aMayWait: PRBool; aRecursionDepth: PRUint32); safecall;
procedure afterProcessNextEvent(aThread: nsIThreadInternal; aRecursionDepth: PRUint32); safecall;
end;
nsIThreadEventFilter = interface(nsISupports)
['{a0605c0b-17f5-4681-b8cd-a1cd75d42559}']
function acceptEvent(aEvent: nsIRunnable): PRBool; stdcall;
end;
nsIThreadManager = interface(nsISupports)
['{2bbbc38c-cf96-4099-ba6b-f6a44d8b014c}']
function newThread(creationFlag: PRUint32; stackSize: PRUint32 = 0): nsIThread; safecall;
function getThreadFromPRThread(prthread: Pointer): nsIThread; safecall;
function getMainThread: nsIThread; safecall;
property mainThread: nsIThread read getMainThread;
function getCurrentThread: nsIThread; safecall;
property currentThread: nsIThread read getCurrentThread;
function getIsMainThread: PRBool; safecall;
property isMainThread: PRBool read getIsMainThread;
function getIsCycleCollectorThread: PRBool; safecall;
property isCycleCollectorThread: PRBool read getIsCycleCollectorThread;
end;
nsIThreadPoolListener = interface(nsISupports)
['{ef194cab-3f86-4b61-b132-e5e96a79e5d1}']
procedure onThreadCreated(); safecall;
procedure onThreadShuttingDown(); safecall;
end;
nsIThreadPool = interface(nsIEventTarget)
['{394c29f0-225f-487f-86d3-4c259da76cab}']
procedure shutdown(); safecall;
function getThreadLimit(): PRUint32; safecall;
procedure setThreadLimit(aValue: PRUint32); safecall;
property threadLimit: PRUint32 read getThreadLimit write setThreadLimit;
function getIdleThreadLimit(): PRUint32; safecall;
procedure setIdleThreadLimit(aValue: PRUint32); safecall;
property idleThreadLimit: PRUint32 read getIdleThreadLimit write setIdleThreadLimit;
function getIdleThreadTimeout(): PRUint32; safecall;
procedure setIdleThreadTimeout(aValue: PRUint32); safecall;
property idleThreadTimeout: PRUint32 read getIdleThreadTimeout write setIdleThreadTimeout;
function getListener: nsIThreadPoolListener; safecall;
procedure setListener(aValue: nsIThreadPoolListener); safecall;
property listener: nsIThreadPoolListener read getListener write setListener;
end;
nsITimer = interface(nsISupports)
['{a796816d-7d47-4348-9ab8-c7aeb3216a7d}']
procedure notify(aTimer: nsITimer); safecall;
end;
const
NS_IEVENTTARGET_DISPATCH_NORMAL = 0;
NS_IEVENTTARGET_DISPATCH_SYNC = 1;
NS_ISUPPORTSPRIORITY_PRIORITY_HIGHEST = -20;
NS_ISUPPORTSPRIORITY_PRIORITY_HIGH = -10;
NS_ISUPPORTSPRIORITY_PRIORITY_NORMAL = 0;
NS_ISUPPORTSPRIORITY_PRIORITY_LOW = 10;
NS_ISUPPORTSPRIORITY_PRIORITY_LOWEST = 20;
const
NS_THREADMANAGER_CONTRACTID = '@mozilla.org/thread-manager;1';
NS_DISPATCH_NORMAL = NS_IEVENTTARGET_DISPATCH_NORMAL;
NS_DISPATCH_SYNC = NS_IEVENTTARGET_DISPATCH_SYNC;
type
nsTimerCallbackFunc = procedure (aTimer: nsITimer; aClosure: Pointer); cdecl;
function NS_NewThread(aInitialEvent: nsIRunnable = nil): nsIThread;
function NS_GetCurrentThread(): nsIThread;
function NS_GetMainThread(): nsIThread;
function NS_IsMainThread(): PRBool;
procedure NS_DispatchToCurrentThread(aEvent: nsIRunnable);
procedure NS_DispatchToMainThread(aEvent: nsIRunnable;
aDispatchFlags: PRUint32 = NS_DISPATCH_NORMAL);
procedure NS_ProcessPendingEvents(aThread: nsIThread;
aTimeout: PRUint32 = $ffffffff);
// const PR_INTERVAL_NO_TIMEOUT = $ffffffff;
function NS_HasPendingEvents(aThread: nsIThread = nil): PRBool;
function NS_ProcessNextEvent(aThread: nsIThread = nil;
aMayWait: PRBool = True): PRBool;
implementation
uses
nsXPCOMGlue, nsError, mmsystem;
function NS_NewThread(aInitialEvent: nsIRunnable): nsIThread;
var
tm: nsIThreadManager;
thread: nsIThread;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
thread := tm.newThread(0);
if Assigned(aInitialEvent) then
thread.dispatch(aInitialEvent, NS_DISPATCH_NORMAL);
Result := thread;
end;
function NS_GetCurrentThread(): nsIThread;
var
tm: nsIThreadManager;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
Result := tm.currentThread;
end;
function NS_GetMainThread(): nsIThread;
var
tm: nsIThreadManager;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
Result := tm.mainThread;
end;
function NS_IsMainThread(): PRBool;
var
tm: nsIThreadManager;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
Result := tm.isMainThread;
end;
procedure NS_DispatchToCurrentThread(aEvent: nsIRunnable);
var
tm: nsIThreadManager;
thread: nsIThread;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
thread := tm.currentThread;
thread.dispatch(aEvent, NS_DISPATCH_NORMAL);
end;
procedure NS_DispatchToMainThread(aEvent: nsIRunnable;
aDispatchFlags: PRUint32);
var
tm: nsIThreadManager;
thread: nsIThread;
begin
NS_GetService(NS_THREADMANAGER_CONTRACTID, nsIThreadManager, tm);
thread := tm.mainThread;
thread.dispatch(aEvent, aDispatchFlags);
end;
procedure NS_ProcessPendingEvents(aThread: nsIThread;
aTimeout: PRUint32);
var
start: PRUint32;
processedEvent: PRBool;
begin
if not Assigned(aThread) then
aThread := NS_GetCurrentThread;
start := timeGetTime();
while True do
begin
processedEvent := aThread.processNextEvent(False);
if not ProcessedEvent then
Break;
if (timeGetTime()-start)>aTimeout then
Break;
end;
end;
function NS_HasPendingEvents(aThread: nsIThread): PRBool;
begin
if not Assigned(aThread) then
aThread := NS_GetCurrentThread;
result := aThread.hasPendingEvents;
end;
function NS_ProcessNextEvent(aThread: nsIThread; aMayWait: PRBool): PRBool;
begin
if not Assigned(aThread) then
aThread := NS_GetCurrentThread;
result := aThread.processNextEvent(aMayWait);
end;
end.
|
unit BankAccountMovement;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorEditDialog, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dsdDB, dsdAction,
Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons,
cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
cxTextEdit, dsdGuides, cxButtonEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
cxCurrencyEdit, cxLabel, dxSkinsCore, dxSkinsDefaultPainters;
type
TBankAccountMovementForm = class(TAncestorEditDialogForm)
Код: TcxLabel;
cxLabel1: TcxLabel;
ceOperDate: TcxDateEdit;
cxLabel2: TcxLabel;
ceBankAccount: TcxButtonEdit;
GuidesBankAccount: TdsdGuides;
ceAmountIn: TcxCurrencyEdit;
cxLabel7: TcxLabel;
ceAmountOut: TcxCurrencyEdit;
cxLabel3: TcxLabel;
cxLabel6: TcxLabel;
ceObject: TcxButtonEdit;
lGuidesObject: TdsdGuides;
cxLabel5: TcxLabel;
ceInfoMoney: TcxButtonEdit;
GuidesInfoMoney: TdsdGuides;
ceContract: TcxButtonEdit;
cxLabel8: TcxLabel;
GuidesContract: TdsdGuides;
cxLabel10: TcxLabel;
ceComment: TcxTextEdit;
cxLabel9: TcxLabel;
ceCurrency: TcxButtonEdit;
GuidesCurrency: TdsdGuides;
edInvNumber: TcxTextEdit;
cxLabel11: TcxLabel;
ceCurrencyPartnerValue: TcxCurrencyEdit;
cxLabel12: TcxLabel;
ceParPartnerValue: TcxCurrencyEdit;
ceBank: TcxButtonEdit;
cxLabel13: TcxLabel;
GuidesBank: TdsdGuides;
cxLabel4: TcxLabel;
ceAmountSumm: TcxCurrencyEdit;
ceUnit: TcxButtonEdit;
cxLabel14: TcxLabel;
GuidesUnit: TdsdGuides;
cxLabel15: TcxLabel;
ceInvoice: TcxButtonEdit;
GuidesInvoice: TdsdGuides;
cxLabel16: TcxLabel;
ceComment_Invoice: TcxTextEdit;
cxLabel17: TcxLabel;
ceServiceDate: TcxDateEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TBankAccountMovementForm);
end.
|
unit FactoryMethod.Concretes.ConcreteProduct1;
interface
uses
FactoryMethod.Interfaces.IProduct;
type
TConcreteProduct1 = class(TInterfacedObject, IProduct)
public
function Operation: string;
end;
implementation
{ TConcreteProduct1 }
function TConcreteProduct1.Operation: string;
begin
Result := '{ConcreteProduct1}';
end;
end.
|
namespace iOSApp.AuthenticatedCore;
uses
AppAuth.Authentication,
AppAuth.Authentication.Models,
Foundation,
iOSApp.Core,
iOSApp.AuthenticatedCore.Models,
iOSApp.AuthenticatedCore.Storage,
Moshine.Foundation,
RemObjects.Elements.RTL,
UIKit;
type
AuthenticatedServiceBase = public class(ServiceBase,IAuthenticationInterestedService)
protected
method newSession(auth:Authenticated); virtual;
begin
Authorized(auth);
end;
method noSession; virtual;
begin
end;
method clearMySettings; virtual;
begin
self.AuthenticationService.clear;
Storage.clearMySettings;
end;
private
{IAuthenticationInterestedService}
method stateChanged(info:UserInfo);
begin
if(assigned(info))then
begin
var auth := new Authenticated;
auth.Name := info.Name;
auth.Email := info.Email;
auth.GivenName := info.GivenName;
auth.FamilyName := info.FamilyName;
auth.Gender := info.Gender;
newSession(auth);
end
else
begin
noSession;
end;
end;
property AppDelegate:AuthenticationAppDelegate read
begin
exit (UIApplication.sharedApplication.&delegate) as AuthenticationAppDelegate;
end;
protected
property AuthenticationService:AuthenticationService read
begin
exit AppDelegate.AuthenticationService;
end;
method Handle(someCode:block; initiatedAction:InitiatedActionEnumeration := InitiatedActionEnumeration.Unknown);
begin
var outerExecutionBlock: NSBlockOperation := NSBlockOperation.blockOperationWithBlock(method()
begin
var value := AccessToken;
if(String.IsNullOrEmpty(value))then
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method()
begin
&delegate:OnNotAuthorized(initiatedAction);
end);
end
else
begin
try
someCode;
except
on a:AuthenticationRequiredException do
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method()
begin
&delegate:OnNotAuthorized(initiatedAction);
end);
end;
on h:HttpStatusCodeException do
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method()
begin
&delegate:OnError(h);
end);
end;
on e:NSException do
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method()
begin
&delegate:OnError(e);
end);
end;
end;
end;
end);
workerQueue.addOperation(outerExecutionBlock);
end;
method anyExceptions(values:sequence of operationTypesEnumeration):Boolean;
begin
for each value in values do
begin
if value = operationTypesEnumeration.exception then
begin
exit true;
end;
end;
exit false;
end;
method anyCantContinue(values:sequence of operationTypesEnumeration):Boolean;
begin
for each value in values do
begin
if value = operationTypesEnumeration.UnableToContinue then
begin
exit true;
end;
end;
exit false;
end;
method anyAuthenticationRequired(values:sequence of operationTypesEnumeration):Boolean;
begin
for each value in values do
begin
if value = operationTypesEnumeration.authenticationRequired then
begin
exit true;
end;
end;
exit false;
end;
method SetResults(results:List<operationTypesEnumeration>) withValue(value:operationTypesEnumeration);
begin
for x:Integer := 0 to results.Count-1 do
begin
results[x] := value;
end;
end;
method dispatcher(results : sequence of operationTypesEnumeration;callback:SimpleDelegate);
begin
if(anyCantContinue(results))then
begin
end
else if(anyExceptions(results))then
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method begin
&delegate:OnError(nil);
end);
end
else if(anyAuthenticationRequired(results))then
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method begin
&delegate:OnNotAuthorized(InitiatedActionEnumeration.Startup);
end);
end
else
begin
if(assigned(callback))then
begin
NSOperationQueue.mainQueue.addOperationWithBlock(method begin
callback;
end);
end;
end;
end;
method Ready:Boolean;
begin
exit assigned(AccessToken) and (AccessToken.Length > 0);
end;
public
property &delegate:IServiceEvents;
method Storage:AuthenticatedStorageBase; reintroduce;
begin
exit inherited Storage as AuthenticatedStorageBase;
end;
method currentAuthenticated:Authenticated;
begin
exit Storage.AuthenticatedUser;
end;
property localUser:Boolean read
begin
exit assigned(Storage.AuthenticatedUser);
end;
property AccessToken:String read
begin
if(not assigned(AppDelegate.AuthenticationService.AuthState))then
begin
NSLog('No AuthState');
exit '';
end;
if(AppDelegate.AuthenticationService.Expired)then
begin
NSLog('Access token has expired, calling refresh');
AppDelegate.AuthenticationService.refresh;
end;
exit AppDelegate.AuthenticationService.AccessToken;
end;
method Authorized(auth:Authenticated; overwrite:Boolean := false );
begin
var authenticated := Storage.AuthenticatedUser;
var updatedStore := false;
if(assigned(authenticated))then
begin
if(authenticated.Email <> auth.Email)then
begin
if(overwrite = false)then
begin
&delegate:OnAuthorizingDifference(authenticated.Email, auth.Email);
end
else
begin
Storage.MergeAuthenticated(auth);
clearMySettings;
updatedStore := true;
end;
end
else
begin
Storage.MergeAuthenticated(auth);
updatedStore := true;
end;
end
else
begin
Storage.MergeAuthenticated(auth);
updatedStore := true;
end;
if(updatedStore)then
begin
self.delegate:OnAuthorized;
end;
end;
method AuthenticatedStartup(results : List<operationTypesEnumeration>; innerBlock:Block; reload:Boolean; callback:SimpleDelegate);
begin
var outerExecutionBlock: NSBlockOperation := NSBlockOperation.blockOperationWithBlock(method
begin
var authenticatedUser := Storage.AuthenticatedUser;
if ((not assigned(authenticatedUser)) and (offline))then
begin
NSLog('No authenticatedUser and offline');
NSOperationQueue.mainQueue.addOperationWithBlock(method begin
var e:= new NoNetworkConnectionException withName('ProxyException') reason('Authentication required but no network connection') userInfo(nil) ;
&delegate:OnError(e);
end);
SetResults(results) withValue(operationTypesEnumeration.UnableToContinue);
end
else if((not assigned(authenticatedUser)) or (assigned(authenticatedUser) and reload ))then
begin
var assignedAccessToken := self.AuthenticationService.AccessToken;
if(String.IsNullOrEmpty(assignedAccessToken))then
begin
NSLog('No access token not requesting data');
SetResults(results) withValue(operationTypesEnumeration.authenticationRequired)
end
else
begin
var innerExecutionBlock: NSBlockOperation := NSBlockOperation.blockOperationWithBlock(NSProgressUnpublishingHandler(innerBlock));
var innerQueue: NSOperationQueue := new NSOperationQueue;
innerQueue.addOperation(innerExecutionBlock);
innerQueue.waitUntilAllOperationsAreFinished;
end;
end
else
begin
NSLog('authenticatedUser present');
SetResults(results) withValue(operationTypesEnumeration.completed)
end;
dispatcher(results,callback);
end);
workerQueue.addOperation(outerExecutionBlock);
end;
end;
end. |
unit KerbalSpaceCtrl.ViewModel;
interface
uses
System.Classes,
EventQueue,
BackgndMethods,
KerbalSpaceControls,
KerbalSpaceCtrl.Model;
type
TKerbalSpaceCtrlViewModel = class
private
FCtrlModel: TKerbalSpaceControl;
FControlQueue: TEventQueue;
FHost: string;
FBusyLock: TLockFlag;
FOnConnectionChanged: TNotifyEvent;
FOnModelConnectionChanged: TNotifyEvent;
FPort: Integer;
procedure DoOnConnectionChanged(Sender: TObject);
procedure DoProcessControlQueue(
const Value: TEventQueueItem;
var RemoveFromQueue: boolean);
function DoSendControlEvent(
const CheckForAbort: TBoolFunc;
const InputValue: TKSPControlEntry;
out OutputValue: Integer): TBackgndProcResult;
function GetIsConnected: boolean;
function GetLastConnectionError: string;
function GetServerVersion: string;
public
constructor Create;
destructor Destroy; override;
procedure DisconnectFromServer;
/// <summary>
/// Tries to establish socket connection to specified host. Returns right away,
/// but will generate an OnConnectionChanged event when done.
/// </summary>
procedure ConnectToServer(
const Host: string;
const Port: Integer);
property IsConnected: boolean read GetIsConnected;
property LastConnectionError: string read GetLastConnectionError;
/// <summary>
/// Event fired when connection to host is established or lost.
/// </summary>
property OnConnectionChanged: TNotifyEvent read FOnConnectionChanged
write FOnConnectionChanged;
property ServerVersion: string read GetServerVersion;
procedure AddToControlQueue(
const Ctrl: TKSPControl;
const StrValue: string);
end;
implementation
uses
System.SysUtils;
{ TKerbalSpaceViewModel }
procedure TKerbalSpaceCtrlViewModel.AddToControlQueue(
const Ctrl: TKSPControl;
const StrValue: string);
var
eqiCtrl: TEventQueueItem;
begin
eqiCtrl.ID := Ord(Ctrl);
eqiCtrl.StrValue := StrValue;
FControlQueue.AddToEndOfQueue(eqiCtrl, True);
end;
procedure TKerbalSpaceCtrlViewModel.ConnectToServer(
const Host: string;
const Port: Integer);
var
thrdConnect: TThread;
begin
if not FBusyLock.Lock then
exit;
FHost := Host;
FPort := Port;
FCtrlModel.OnConnected := FOnModelConnectionChanged;
FCtrlModel.OnDisconnected := FOnModelConnectionChanged;
// use thread to connect, call OnDone (via Synchronize) when done
thrdConnect := TThread.CreateAnonymousThread(
procedure()
begin
FCtrlModel.OpenConnection(Host, Port, 'ViewModel', 4000);
TThread.Synchronize(TThread.CurrentThread,
procedure()
begin
try
DoOnConnectionChanged(Self);
finally
FBusyLock.Release;
end;
end);
end);
thrdConnect.Start;
end;
constructor TKerbalSpaceCtrlViewModel.Create;
begin
FCtrlModel := TKerbalSpaceControl.Create;
FControlQueue := TEventQueue.Create;
FControlQueue.OnProcessItem := DoProcessControlQueue;
end;
destructor TKerbalSpaceCtrlViewModel.Destroy;
begin
FreeAndNil(FCtrlModel);
inherited;
end;
procedure TKerbalSpaceCtrlViewModel.DisconnectFromServer;
begin
FCtrlModel.CloseConnection; // if connected, then OnDisconnected event will get fired
end;
procedure TKerbalSpaceCtrlViewModel.DoOnConnectionChanged(Sender: TObject);
begin
if Assigned(FOnConnectionChanged) then
FOnConnectionChanged(Sender);
if IsConnected then
FControlQueue.StartProcessingQueue(100)
else
FControlQueue.StopProcessingQueue;
end;
procedure TKerbalSpaceCtrlViewModel.DoProcessControlQueue(
const Value: TEventQueueItem;
var RemoveFromQueue: boolean);
var
bgmCall: TBackgndMethodCall<TKSPControlEntry, Integer>;
ceCtrl: TKSPControlEntry;
begin
// this method is called from timer event to process entries in the queue
// check if connected
if not IsConnected then
begin
FControlQueue.StopProcessingQueue;
RemoveFromQueue := False; // keep entry in queue
exit;
end;
// init parameter value
ceCtrl.CtrlID := TKSPControl(Value.ID);
ceCtrl.Value := Value.StrValue;
// send control event to server
RemoveFromQueue := bgmCall.Start(ceCtrl, DoSendControlEvent, nil, nil, FBusyLock);
end;
function TKerbalSpaceCtrlViewModel.DoSendControlEvent(
const CheckForAbort: TBoolFunc;
const InputValue: TKSPControlEntry;
out OutputValue: Integer): TBackgndProcResult;
begin
end;
function TKerbalSpaceCtrlViewModel.GetIsConnected: boolean;
begin
Result := FCtrlModel.IsConnected;
end;
function TKerbalSpaceCtrlViewModel.GetLastConnectionError: string;
begin
Result := FCtrlModel.LastConnectionError;
end;
function TKerbalSpaceCtrlViewModel.GetServerVersion: string;
begin
Result := FCtrlModel.ServerVersion;
end;
end.
|
unit UVersionCheck;
interface
procedure CheckMyVersion;
implementation
uses Vars, System.Net.HttpClient, System.JSON, Vcl.Dialogs,
ULanguage, System.SysUtils, System.UITypes, System.Classes,
Winapi.ShellAPI, Winapi.Windows;
const URL_GITHUB = 'https://api.github.com/repos/digao-dalpiaz/Planning-Poker/releases/latest';
type
TThCheck = class(TThread)
protected
procedure Execute; override;
private
procedure Check;
end;
procedure TThCheck.Check;
var
H: THTTPClient;
Res, tag_versao, tag_url: string;
data: TJSONObject;
begin
H := THTTPClient.Create;
try
Res := H.Get(URL_GITHUB).ContentAsString;
finally
H.Free;
end;
data := TJSONObject.ParseJSONValue(Res) as TJSONObject;
try
tag_versao := data.GetValue('tag_name').Value;
tag_url := data.GetValue('html_url').Value;
finally
data.Free;
end;
if 'v'+STR_VERSION<>tag_versao then
begin
Synchronize(procedure
begin
if MessageDlg(Format(Lang.Get('NEW_VERSION_INFO'), [tag_versao]), mtInformation, mbYesNo, 0) = mrYes then
ShellExecute(0, '', PChar(tag_url), '', '', SW_SHOWNORMAL);
end);
end;
end;
procedure TThCheck.Execute;
begin
inherited;
FreeOnTerminate := True;
try
Check;
except
on E: Exception do
Synchronize(procedure
begin
MessageDlg('Error checking version updates: '+E.Message, mtError, [mbOK], 0);
end);
end;
end;
procedure CheckMyVersion;
begin
TThCheck.Create;
end;
end.
|
unit fmAviso;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fmBase, Readhtml, FramView, FramBrwz, Web;
type
TfAviso = class(TfBase)
FrameBrowser: TFrameBrowser;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
WebFrameBrowser: TWebFrameBrowser;
public
procedure Cargar(URL: string);
destructor Destroy; override;
end;
procedure MostrarAvisoSiExiste;
implementation
uses UserServerCalls, dmConfiguracion;
type
TAvisoThread = class(TThread)
private
FExisteAviso: boolean;
URL: string;
procedure Mostrar;
procedure ExisteAviso;
public
procedure Execute; override;
end;
{$R *.dfm}
procedure MostrarAvisoSiExiste;
var avisoThread: TAvisoThread;
begin
avisoThread:= TAvisoThread.Create(true);
avisoThread.FreeOnTerminate := true;
avisoThread.Resume;
end;
procedure TfAviso.Cargar(URL: string);
begin
WebFrameBrowser := TWebFrameBrowser.Create(FrameBrowser);
WebFrameBrowser.LoadURL(Configuracion.Sistema.URLServidor + URL);
end;
destructor TfAviso.Destroy;
begin
WebFrameBrowser.Free;
inherited;
end;
procedure TfAviso.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
{ TAvisoThread }
procedure TAvisoThread.Execute;
begin
try
Synchronize(ExisteAviso);
if FExisteAviso then
Synchronize(Mostrar);
except
end;
end;
procedure TAvisoThread.ExisteAviso;
var serverCall: TMensajeServerCall;
begin
serverCall := TMensajeServerCall.Create;
try
try
URL := serverCall.CallEntrada;
FExisteAviso := URL <> 'no';
except
FExisteAviso := false;
end;
finally
serverCall.Free;
end;
end;
procedure TAvisoThread.Mostrar;
var aviso: TfAviso;
begin
aviso := TfAviso.Create(nil);
try
aviso.Cargar(URL);
aviso.ShowModal;
finally
aviso.Free;
end;
end;
end.
|
program alg;
type
algebraic = record
case is_left: boolean of
true: (l: integer);
false: (r: char);
end;
lfunc_type = function(v: integer): boolean;
rfunc_type = function(v: char): boolean;
var x, y: algebraic;
function in_L(v: integer): algebraic;
begin
result.is_left := true;
result.l := v;
end;
function in_R(v: char): algebraic;
begin
result.is_left := false;
result.r := v;
end;
function alg_case(sum: algebraic; lfunc: lfunc_type; rfunc: rfunc_type): boolean;
begin
case sum.is_left of
true: alg_case := lfunc(sum.l);
false: alg_case := rfunc(sum.r);
end;
end;
function is_odd(x: integer): boolean;
begin
result := x mod 2 <> 0;
end;
function is_letter_a(x: char): boolean;
begin
result := (x = 'a') or (x = 'A');
end;
begin
x := in_L(15);
y := in_R('A');
writeln(alg_case(x, is_odd, is_letter_a));
writeln(alg_case(y, is_odd, is_letter_a));
end.
|
unit uGCAxCustomTransceiverOption;
{$I twcomp.pas}
interface
uses
Windows, Registry, tWConst, pGCAxTransceiver_TLB, uTWCAxPresentationService,
uTransceiverSyncOrder, tWTools, CAS_REGISTRY;
type
TGCAxCustomTransceiverOption = class(TTWCAxPresentationService, IGCAxCustomTransceiverOption)
private
FSyncOrder : TTransceiverSyncOrder;
function GetParameterValue(index: Widestring): Widestring;
procedure SetParameterValue(index: Widestring; const Value: Widestring);
protected
procedure Initialize; override;
function Get_SyncOrderXML: WideString; virtual; safecall;
procedure Set_SyncOrderXML(const Value: WideString); virtual; safecall;
property ParameterValue[index: Widestring] : Widestring read GetParameterValue write SetParameterValue;
public
class procedure RegisterOptionSheet(SystemID, ClassInterpreterOptions, ClassGeneratorOptions: WideString);
destructor Destroy; override;
end;
implementation
{$R *.DFM}
{==============================================================================}
{ Initialize }
{==============================================================================}
procedure TGCAxCustomTransceiverOption.Initialize;
begin
inherited;
FSyncOrder := TTransceiverSyncOrder.Create('');
end;
{==============================================================================}
{ Get_SyncOrderXML }
{==============================================================================}
function TGCAxCustomTransceiverOption.Get_SyncOrderXML: WideString;
begin
result := FSyncOrder.xml;
end;
{==============================================================================}
{ Set_SyncOrderXML }
{==============================================================================}
procedure TGCAxCustomTransceiverOption.Set_SyncOrderXML(const Value: WideString);
begin
FSyncOrder.xml := value;
end;
{==============================================================================}
{ GetParameterValue }
{==============================================================================}
function TGCAxCustomTransceiverOption.GetParameterValue(index: Widestring): Widestring;
begin
result := FSyncOrder.GetValue('PARAMETER/@' + index);
end;
{==============================================================================}
{ SetParameterValue }
{==============================================================================}
procedure TGCAxCustomTransceiverOption.SetParameterValue(index: Widestring;const Value: Widestring);
begin
FSyncOrder.SetAttribute('PARAMETER',index,value);
end;
{==============================================================================}
{ class procedure RegisterOptionSheet }
{==============================================================================}
class procedure TGCAxCustomTransceiverOption.RegisterOptionSheet(SystemID, ClassInterpreterOptions, ClassGeneratorOptions: WideString);
var Registry : TCASRegistry;
begin
Registry := TCASRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
Registry.OpenKey( '\' + GenesisRegistryPath1 + 'Transceiver\InterpreterOptions\', true );
if ClassInterpreterOptions <> '' then
Registry.WriteString(SystemID,ClassInterpreterOptions);
Registry.OpenKey( '\' + GenesisRegistryPath1 + 'Transceiver\GeneratorOptions\', true );
if ClassGeneratorOptions <> '' then
Registry.WriteString(SystemID,ClassGeneratorOptions);
finally
FreeAndNilEx(Registry);
end;
end;
{==============================================================================}
{ Destroy }
{==============================================================================}
destructor TGCAxCustomTransceiverOption.Destroy;
begin
try
FreeAndNilEx(FSyncOrder);
finally
inherited;
end;
end;
end.
|
// Written By Ismael Heredia in the year 2016
unit Producto;
interface
uses Windows, SysUtils;
type
TProducto = class
private
public
id_producto: integer;
nombre_producto: string;
descripcion: string;
precio: integer;
fecha_registro: string;
id_proveedor: integer;
function getId_producto(): integer;
procedure setId_producto(id_producto: integer);
function getNombre_producto(): string;
procedure setNombre_producto(nombre_producto: string);
function getDescripcion(): string;
procedure setDescripcion(descripcion: string);
function getPrecio(): integer;
procedure setPrecio(precio: integer);
function getFecha_registro(): string;
procedure setFecha_registro(fecha_registro: string);
function getId_proveedor(): integer;
procedure setId_proveedor(id_proveedor: integer);
Constructor Create; overload;
Constructor Create(id_producto: integer; nombre_producto: string;
descripcion: string; precio: integer; fecha_registro: string;
id_proveedor: integer); overload;
function ToString(): string;
end;
implementation
function TProducto.getId_producto(): integer;
begin
Result := id_producto;
end;
procedure TProducto.setId_producto(id_producto: integer);
begin
self.id_producto := id_producto;
end;
function TProducto.getNombre_producto(): string;
begin
Result := nombre_producto;
end;
procedure TProducto.setNombre_producto(nombre_producto: string);
begin
self.nombre_producto := nombre_producto;
end;
function TProducto.getDescripcion(): string;
begin
Result := descripcion;
end;
procedure TProducto.setDescripcion(descripcion: string);
begin
self.descripcion := descripcion;
end;
function TProducto.getPrecio(): integer;
begin
Result := precio;
end;
procedure TProducto.setPrecio(precio: integer);
begin
self.precio := precio;
end;
function TProducto.getFecha_registro(): string;
begin
Result := fecha_registro;
end;
procedure TProducto.setFecha_registro(fecha_registro: string);
begin
self.fecha_registro := fecha_registro;
end;
function TProducto.getId_proveedor(): integer;
begin
Result := id_proveedor;
end;
procedure TProducto.setId_proveedor(id_proveedor: integer);
begin
self.id_proveedor := id_proveedor;
end;
constructor TProducto.Create;
begin
inherited;
//
end;
constructor TProducto.Create(id_producto: integer; nombre_producto: string;
descripcion: string; precio: integer; fecha_registro: string;
id_proveedor: integer);
begin
self.id_producto := id_producto;
self.nombre_producto := nombre_producto;
self.descripcion := descripcion;
self.precio := precio;
self.fecha_registro := fecha_registro;
self.id_proveedor := id_proveedor;
end;
function TProducto.ToString(): string;
begin
Result := 'Producto{" + "id_producto="' + IntToStr(id_producto) +
'", nombre_producto="' + nombre_producto + '", descripcion="' + descripcion
+ '", precio="' + IntToStr(precio) + '", fecha_registro="' + fecha_registro
+ ', id_proveedor="' + IntToStr(id_proveedor) + '"}';
end;
end.
|
unit UCommonTypes;
interface
uses
KRK.Lib.Rtl.Common.Classes;
type
{ TSessionData precisa ser do tipo TObjectFile de forma a poder usar o método
LoadFromTextualRepresentation para carregar uma sessão a partir da lista de
sessões em UAuthenticatorImpl.pas no servidor }
TSessionData = class(TObjectFile)
private
Fsm_usuarios_id: SmallInt;
Fva_nome: String;
Fva_login: String;
Fch_senha: String;
Fva_email: String;
Fbo_superusuario: Boolean;
published
property sm_usuarios_id: SmallInt read Fsm_usuarios_id write Fsm_usuarios_id;
property va_nome: String read Fva_nome write Fva_nome;
property va_login: String read Fva_login write Fva_login;
property ch_senha: String read Fch_senha write Fch_senha;
property va_email: String read Fva_email write Fva_email;
property bo_superusuario: Boolean read Fbo_superusuario write Fbo_superusuario;
end;
{ Usado apenas no cliente, esta classe, guarda os dados da sessão do usuário
atualmente logado}
TCurrentSession = class
private
FID: String;
FData: TSessionData;
public
constructor Create;
destructor Destroy; override;
property Data: TSessionData read FData;
property ID: String read FID write FID;
end;
implementation
{ TCurrentSession }
constructor TCurrentSession.Create;
begin
FData := TSessionData.Create(nil);
end;
destructor TCurrentSession.Destroy;
begin
FData.Free;
inherited;
end;
end.
|
unit dmPlusvaliaRiesgo;
interface
uses
SysUtils, Classes, DB, IBCustomDataSet, IBQuery;
type
TDataPlusvaliaRiesgo = record
OIDValor: Integer;
plusvalia: Currency;
riesgo: Currency;
end;
TArrayDataPlusvaliaRiesgo= array of TDataPlusvaliaRiesgo;
PArrayDataPlusvaliaRiesgo = ^TArrayDataPlusvaliaRiesgo;
TPlusvaliaRiesgo = class(TDataModule)
Cotizacion: TIBQuery;
CotizacionCIERRE: TIBBCDField;
private
ArrayData: TArrayDataPlusvaliaRiesgo;
function GetPDataPlusvaliaRiesgo: PArrayDataPlusvaliaRiesgo;
function GetCount: integer;
procedure calcularPlusvaliaRiesgo(const i: integer);
public
procedure calculate;
procedure IrA(const i: integer);
property PDataPlusvaliaRiesgo: PArrayDataPlusvaliaRiesgo read GetPDataPlusvaliaRiesgo;
property Count: integer read GetCount;
end;
implementation
uses dmBD, dmData, UtilDB, Tipos, Escenario;
{$R *.dfm}
{ TPlusvaliaRiesgo }
procedure TPlusvaliaRiesgo.calcularPlusvaliaRiesgo(const i: integer);
var cambios: TArrayCurrency;
j, num: integer;
fieldCierre: TCurrencyField;
escenarioMultipleCreator: TEscenarioMultipleCreator;
escenarioMultiple: TEscenarioMultiple;
begin
num := Cotizacion.RecordCount;
SetLength(cambios, num);
dec(num);
//Minimo numero de cambios
if num <= 30 then begin
ArrayData[i].plusvalia := 0;
ArrayData[i].riesgo := 0;
end
else begin
fieldCierre := TCurrencyField(Cotizacion.Fields[0]);
Cotizacion.First;
for j := 0 to num do begin
cambios[j] := fieldCierre.Value;
Cotizacion.Next;
end;
escenarioMultipleCreator := TEscenarioMultipleCreator.Create;
try
escenarioMultipleCreator.Cambios := @cambios;
escenarioMultipleCreator.CrearEscenarioMultiple;
escenarioMultiple := escenarioMultipleCreator.EscenarioMultiple;
try
ArrayData[i].plusvalia := escenarioMultiple.PlusvaliaMaxima;
ArrayData[i].riesgo := escenarioMultiple.Riesgo;
finally
escenarioMultiple.Free;
end;
finally
escenarioMultipleCreator.Free;
end;
end;
end;
procedure TPlusvaliaRiesgo.calculate;
var dataSet: TDataSet;
inspect: TInspectDataSet;
i, num, OIDValor: integer;
fieldOIDValor: TIntegerField;
paramOIDValor: TParam;
begin
dataSet := Data.Valores;
inspect := StartInspectDataSet(dataSet);
try
fieldOIDValor := TIntegerField(dataSet.FieldByName('OID_VALOR'));
paramOIDValor := Cotizacion.Params[0];
num := dataSet.RecordCount;
SetLength(ArrayData, num);
dec(num);
dataSet.First;
for i := 0 to num do begin
OIDValor := fieldOIDValor.Value;
ArrayData[i].OIDValor := OIDValor;
Cotizacion.Close;
paramOIDValor.AsInteger := OIDValor;
OpenDataSetRecordCount(Cotizacion);
calcularPlusvaliaRiesgo(i);
dataSet.Next;
end;
finally
EndInspectDataSet(inspect);
end;
end;
function TPlusvaliaRiesgo.GetCount: integer;
begin
result := length(ArrayData);
end;
function TPlusvaliaRiesgo.GetPDataPlusvaliaRiesgo: PArrayDataPlusvaliaRiesgo;
begin
Result := @ArrayData;
end;
procedure TPlusvaliaRiesgo.IrA(const i: integer);
var OIDValor: integer;
begin
OIDValor := ArrayData[i].OIDValor;
if Data.OIDValor <> OIDValor then
Data.IrAValor(OIDValor);
end;
end.
|
unit openmap;
// OpenStreetMap Utilities Unit
// License: New BSD License
// Documentation at: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
// Revision History:
// @001 2009.11.19 Noah SILVA Started library
// @002 2009.11.20 Noah SILVA Added omGetTileFile
// @003 2010.01.03 Noah SILVA Added Tile Number -> Location functions
{$mode objfpc}{$H+}
interface
TYPE
TOSMTile = Record
Zoom : Integer;
TileX: Integer;
TileY: Integer;
end;
// Gets the URL for a tile containing the specified Latitude, Longitude, and
// Zoom level.
Function omGetTileURL(const Lat:Real; const Lon:Real; const Zoom:Integer):String;
// Note that the tile contains the specified point, it is not centered on it.
// Zoom = 0..18. (0 is the whole earth, 18 is the highest zoom)
Function omGetTileURL(const Tile:TOSMTile):String; overload; //@002=
// Returns the URL to a static map (image) for the given location and zoom level
Function omGetStaticMapURL(const Lat:Real; const Lon:Real;
const Zoom:Integer):String;
// The image is composed of stitched-together tiles
// This service is not guaranteed by OpenStreetMap and may be unreliable.
// Fetches the map tile for a given location and zoom level, and returns a file
// name for the caller to retrieve it at.
Function omGetTileFile(const Lat:Real; const Lon:Real; //@002+
const Zoom:Integer):String; Overload; //@002+
Function omGetTileFile(Const Tile:TOSMTile):String; Overload; //@002+
// Returns a structure with the tile's x, y, and zoom. This is useful if you
// want to get a tile to the left, right, etc.
Function omGetTile(const Lat:Real; const Lon:Real; //@002+
const ZoomLevel:Integer):TOSMTile; //@002+
// Calculates the Longitude of the NW corner of a tile.
Function omTile2Long(Const Tile:TOSMTile):Real; //@003+
// Calculates the Latitude of the NW corner of a tile.
Function omTile2Lat(Const Tile:TOSMTile):Real; //@003+
Function MarkerX(Const Tile:TOSMTile;
Const Lat:Real; Const Long:Real):Integer; //@003+
Function MarkerY(Const Tile:TOSMTile;
Const Lat:Real; Const Long:Real):Integer; //@003+
implementation
uses
Classes, SysUtils,
math, // for Ln, Cos, etc.
MD5, // for Hash
httpsend; // for Internet
Var
CacheRoot:String; // Root for storing Map Images //@003+
//@002+ Begin of Insertion
// Private function, gets tile X from coordinates and zoom level
Function omGetTileX(const Lat:Real; const Lon:Real; const Zoom:Integer):integer;
Begin
Result := Floor((lon + 180) / 360 * Power(2, Zoom));
end;
// Private function, gets tile Y from coordinates and zoom level
Function omGetTileY(const Lat:Real; const Lon:Real; const Zoom:Integer):integer;
Const
PI = 3.14159;
Begin
Result := Floor( (1 - ln(Tan(lat * PI / 180)
+ 1 / Cos(lat * PI / 180))
/ PI) / 2 * Power(2, Zoom));
end;
//@002+ Begin of Insertion
Function omGetTile(const Lat:Real; const Lon:Real;
const ZoomLevel:Integer):TOSMTile;
Begin
With Result Do
Begin
Zoom := ZoomLevel;
TileX := omGetTileX(lat, lon, ZoomLevel);
TileY := omGetTileY(lat, lon, ZoomLevel);
End; // of WITH
End; // of FUNCTION
Function omGetURLTileNumber(const Tile:TOSMTile):String; overload;
// Returns tile number triplet in such a way as to be conducive to use for a
// HTTP URL for the OSM Tile Server
Begin
With Tile do
result := IntToStr(Zoom) + '/' + FloatToStr(TileX) + '/' + FloatToStr(TileY);
End;
Function omGetFileTileNumber(const Tile:TOSMTile):String; overload;
// Returns tile number triplet in such a way as to be conducive to use for a
// HTTP URL for a file name
Begin
With Tile do
result := IntToStr(Zoom) + '_' + FloatToStr(TileX) + '_' + FloatToStr(TileY);
End;
//@002+ End of Insertion
// Returns tile number triplet in such a way as to be conducive to use for a
// file name
Function omGetFileTileNumber(const Lat:Real; const Lon:Real;
const Zoom:Integer):String; overload; //@002=
var
x:Integer;
y:real;
begin
X := omGetTileX(Lat, Lon, Zoom);
Y := omGetTileY(Lat, Lon, Zoom);
result := inttostr(zoom) + '_' + FloatToStr(x) + '_' + FloatToStr(y);
end;
//@002+ End of Insertion
// Gets a tile ID String for a URL.
Function omGetURLTileNumber(const Lat:Real; const Lon:Real; //@002=
const Zoom:Integer):String; overload; //@002=
// Const //@002-
// PI = 3.14159; //@002-
var
x:Integer; //@002=
y:real; //@002=
begin
// x := Floor((lon + 180) / 360 * Power(2, Zoom)); //@002-
X := omGetTileX(Lat, Lon, Zoom); //@002+
// y := Floor( (1 - ln(Tan(lat * PI / 180) //@002-
// + 1 / Cos(lat * PI / 180)) //@002-
// / PI) / 2 * Power(2, Zoom)); //@002-
Y := omGetTileY(Lat, Lon, Zoom); //@002+
result := inttostr(zoom) + '/' + FloatToStr(x) + '/' + FloatToStr(y);
end;
// Returns the URL for a tile at a particular location and zoom level
Function omGetTileURL(const Lat:Real; const Lon:Real; const Zoom:Integer):String;
begin
result := 'http://tile.openstreetmap.org/'
+ omGetURLTileNumber(lat, lon, zoom) + '.png'
end; // of Function
Function omGetTileURL(const Tile:TOSMTile):String; overload;
// Gets tile URL, given tile coordinates
begin
result := 'http://tile.openstreetmap.org/'
+ omGetURLTileNumber(Tile) + '.png'
end; // of Function
Function omGetStaticMapURL(const Lat:Real; const Lon:Real; const Zoom:Integer):String;
const
protocol = 'http://'; //@002+
// HostName = 'old-dev.openstreetmap.org'; //@002+
HostName = 'ojw.dev.openstreetmap.org';
// BaseURL = '/~ojw/StaticMap'; //@002+
BaseURL = '/StaticMap';
begin
Result := Protocol + HostName + BaseURL + '/?' //@002=
+ 'lat=' + FloatToStr(lat)
+ '&lon='+ FloatToStr(lon)
+ '&z=' + IntToStr(Zoom)
// + '&att=' + 'logo' // or text or none
+ '&att=' + 'none' // or text or none
+ '&fmt=' + 'png' // or jpg
// optional marker
+ '&mlat0=' + FloatToStr(lat)
+ '&mlon0=' + FloatToStr(lon)
+ '&mico0=' + '0' // the icon, 0 = bullseye
// Show = 1 for image, 0 for HTML page
+ '&layer=cloudmade_2&mode=Location&show=1';
end;
function StringToHash(const text:string):STRING;
//VAR output : TMD5Digest;
// The MD5Digest is actually 16 bytes long,
// Which means it should be 32 characters when represented in ASCII
begin
result := mdprint(md5string(text));
end;
//@002+ Begin of Insertion
Function omGetTileFileName(const Lat:Real; const Lon:Real;
const Zoom:Integer):String;
// Private Function to get tile name (computes filename only)
// Doesn't download the file or check it's existance, etc.
Begin
Result := CacheRoot //@003=
+ omGetFileTileNumber(Lat, Lon, Zoom) + '.png';
End;
Function omGetTileFileName(const Tile:TOSMTile):String; Overload;
// Private Function to get tile name (computes filename only)
// Doesn't download the file or check it's existance, etc.
Begin
Result := CacheRoot //@003=
+ omGetFileTileNumber(Tile) + '.png';
End;
Function omTileCacheCheck(const FileName:String):Boolean;
// Returns True is cached (exists), False if not.
Begin
Result := FileExists(FileName);
End;
Function URLDownload(const URL:String; const FullPath:String):Boolean;
// Downloads the specified URL to the complete path given.
// Returns true if no problems, false if it couldn't download.
Var
FileStream:TMemoryStream;
Begin
FileStream := TMemoryStream.Create;
Try
If not HttpGetBinary(URL, FileStream) then
Result := False
Else
Begin
FileStream.SaveToFile(FullPath);
result := True;
end;
finally
FileStream.Free;
end; // of TRY..FINALLY
end; // of FUNCTION
Function omGetTileFile(Const Tile:TOSMTile):String; overload;
// Gives a pointer to the file name containing the desired tile, given by
// an actual tile structure (i.e. no lookup required).
var
TileURL:String;
filename:String;
Begin
Result := '';
TileURL := omGetTileURL(Tile);
If TileURL = '' then
Exit;
FileName := omGetTileFileName(Tile);
If omTileCacheCheck(FileName) then
Result := Filename // We already have it, just return
else // We don't have it, we'll have to
Begin // Download it...
If Not URLDownload(TileURL, FileName) then
Result := ''
Else
result := FileName;
end;// of IF Not (InCache)
end;
//@002+ End of Insertion
Function omGetTileFile(const Lat:Real; const Lon:Real;
const Zoom:Integer):String; overload; //@002=
var
TileURL:String;
filename:String;
// ImageStream:TMemoryStream; //@002-
begin
Result := '';
TileURL := omGetTileURL(lat, lon, Zoom);
If TileURL = '' then
Exit;
//@002 Begin of Insertion
FileName := omGetTileFileName(Lat, Lon, Zoom);
If omTileCacheCheck(FileName) then
Result := Filename // We already have it, just return
else // We don't have it, we'll have to
Begin // Download it...
//@002 End of Insertion
// ImageStream := TMemoryStream.Create; //@002-
// Try //@002-
// If not HttpGetBinary(TileURL, ImageStream) then
If Not URLDownload(TileURL, FileName) then
// Exit //@002-
Result := '' //@002+
Else
// Begin //@002-
// FileName := '/Users/shiruba/Library/OpenStreetMap/' //@002-
// + omGetFileTileNumber(Lat, Lon, Zoom) + '.png'; //@002-
// ImageStream.SaveToFile(FileName); //@002-
result := FileName; //@002+
// end; //@002-
// finally //@002-
// ImageStream.Free; //@002-
// end; //@002-
end;// of IF Not (InCache) //@002+
end; // of FUNCTION
// Converts a Tile into the NW corner's longitude
Function omTile2Long(Const Tile:TOSMTile):Real; //@003+
Begin
With Tile do
Result := TileX / Power(2.0, Zoom) * 360.0 - 180;
End; //
// Converts a Tile into the NW corner's latitude
Function omTile2Lat(Const Tile:TOSMTile):Real; //@003+
CONST
PI = 3.14159;
var
n:real;
Begin
With Tile do
begin
n := PI - 2.0 * PI * TileY / Power(2.0, Zoom);
Result := 180.0 / PI * ArcTan(0.5 * (exp(n) - exp(-n)));
end;
End; //
// Returns the X Position of the map marker relative to the tile on the screen,
// Given the current tile, and the latitude and longitude of the actual point
// of interest.
Function MarkerX(Const Tile:TOSMTile;
Const Lat:Real; Const Long:Real):Integer; //@003+
Var
TileNW_Lat:Real;
TileNW_Long:Real;
TileSE_Lat:Real;
TileSE_Long:Real;
TileSE:TOSMTile;
Range_Lat:Real;
Range_Long:Real;
Normalized_Lat:Real;
Normalized_Long:Real;
Begin
// First, get the NW corner
TileNW_Lat := omTile2Lat(Tile);
TileNW_Long := omTile2Long(Tile);
//Create a tile to the SE of this one
TileSE := Tile;
Inc(TileSE.TileX);
Inc(TileSE.TileY);
// Calculate that tile's NW corner, which is the same as the SE corner of the
// tile we really want.
TileSE_Lat := omTile2Lat(TileSE);
TileSE_Long := omTile2Long(TileSE);
// Calculate the range at this zoom level in the current tile.
Range_Lat := Abs(TileSE_Lat - TileNW_Lat);
Range_Long := Abs(TileSE_Long - TileNW_Long);
// Calculated a normalize Lat and Long value, setting the NW corner of the
// current tile to (0,0)
Normalized_Lat := Abs(Lat - TileNW_lat);
Normalized_Long := Abs(Long - TileNW_long);
// Finally, calculate the result using proportions
Result := Floor((Normalized_long * 256 ) / Range_Long);
// NL X
// __ = __
// RL 256
End;
Function MarkerY(Const Tile:TOSMTile;
Const Lat:Real; Const Long:Real):Integer; //@003+
Var
TileNW_Lat:Real;
TileNW_Long:Real;
TileSE_Lat:Real;
TileSE_Long:Real;
TileSE:TOSMTile;
Range_Lat:Real;
Range_Long:Real;
Normalized_Lat:Real;
Normalized_Long:Real;
Begin
// First, get the NW corner
TileNW_Lat := omTile2Lat(Tile);
TileNW_Long := omTile2Long(Tile);
//Create a tile to the SE of this one
TileSE := Tile;
Inc(TileSE.TileX);
Inc(TileSE.TileY);
// Calculate that tile's NW corner, which is the same as the SE corner of the
// tile we really want.
TileSE_Lat := omTile2Lat(TileSE);
TileSE_Long := omTile2Long(TileSE);
// Calculate the range at this zoom level in the current tile.
Range_Lat := Abs(TileSE_Lat - TileNW_Lat);
Range_Long := Abs(TileSE_Long - TileNW_Long);
// Calculated a normalize Lat and Long value, setting the NW corner of the
// current tile to (0,0)
Normalized_Lat := Abs(Lat - TileNW_lat);
Normalized_Long := Abs(Long - TileNW_long);
// Finally, calculate the result using proportions
Result := Floor((Normalized_lat * 256 ) / Range_Lat);
// NL X
// __ = __
// RL 256
End;
initialization //@003+
CacheRoot := GetEnvironmentVariable('HOME');
// CacheRoot := CacheRoot + '/Library/OpenStreetMap';
CacheRoot := CacheRoot + '/Library';
SetDirSeparators(CacheRoot);
If not DirectoryExists(CacheRoot) then
CreateDir(CacheRoot);
CacheRoot := CacheRoot + '/OpenStreetMap';
If not DirectoryExists(CacheRoot) then
CreateDir(CacheRoot);
CacheRoot := CacheRoot + '/';
SetDirSeparators(CacheRoot);
end. // of UNIT
|
unit CadastroDeClientes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, Model.Cliente, DAO.Cliente,
PesquisarClientes;
type
TFrmCadastroDeClientes = class(TForm)
EdtID: TLabeledEdit;
EdtNome: TLabeledEdit;
BtnSalvar: TBitBtn;
BtnCancelar: TBitBtn;
BtnExcluir: TBitBtn;
SpeedButton1: TSpeedButton;
BtnFechar: TBitBtn;
procedure BtnSalvarClick(Sender: TObject);
procedure BtnExcluirClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SpeedButton1Click(Sender: TObject);
procedure BtnFecharClick(Sender: TObject);
procedure BtnCancelarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure LimparFormulario();
public
{ Public declarations }
class procedure CadastrarCliente( ); overload;
class procedure CadastrarCliente( const AID: Integer ); overload;
end;
resourcestring
RSClienteNaoEncontrado = 'Cliente não contrado';
RSNomeClienteNaoInformado = 'Nome do cliente não encontrado';
implementation
{$R *.dfm}
procedure TFrmCadastroDeClientes.BtnCancelarClick(Sender: TObject);
begin
LimparFormulario();
end;
procedure TFrmCadastroDeClientes.BtnExcluirClick(Sender: TObject);
var
Cliente: TModelCliente;
DAOCliente: TDAOCliente;
begin
Cliente := TModelCliente.Create();
try
DAOCliente := TDAOCliente.Create();
try
with Cliente do
begin
ID := StrToIntDef(EdtID.Text, 0);
if ( ID > 0 ) then
DAOCliente.Excluir(Cliente);
end;
finally
FreeAndNil(DAOCliente)
end;
finally
FreeAndNil(Cliente)
end;
LimparFormulario();
end;
procedure TFrmCadastroDeClientes.BtnFecharClick(Sender: TObject);
begin
Close();
end;
procedure TFrmCadastroDeClientes.BtnSalvarClick(Sender: TObject);
var
Cliente: TModelCliente;
DAOCliente: TDAOCliente;
begin
// Somente para evitar o cadastro do nome em branco.
// Esse validação deve estar em outro local
if ( EdtNome.Text = EmptyStr ) then
begin
MessageDlg( RSNomeClienteNaoInformado, mtInformation, [MBOK], 0 );
EdtNome.SetFocus;
Exit;
end;
Cliente := TModelCliente.Create;
try
DAOCliente := TDAOCliente.Create();
try
with Cliente do
begin
ID := StrToIntdEF(EdtID.Text, 0);
Nome := EdtNome.Text;
DAOCliente.Salvar(Cliente);
end;
finally
FreeAndNil(DAOCliente);
end;
finally
FreeAndNil(Cliente);
end;
LimparFormulario();
end;
class procedure TFrmCadastroDeClientes.CadastrarCliente(
const AID: Integer );
var
FrmCadastroDeClientes: TFrmCadastroDeClientes;
begin
FrmCadastroDeClientes := TFrmCadastroDeClientes.Create(nil);
try
// Pega o código do cliente e popula o Edit para
// fazer a peaquisa
FrmCadastroDeClientes.EdtID.Text:= IntToStr( AID );
FrmCadastroDeClientes.ShowModal();
finally
FreeAndNil(FrmCadastroDeClientes);
end;
end;
class procedure TFrmCadastroDeClientes.CadastrarCliente;
var
FrmCadastroDeClientes: TFrmCadastroDeClientes;
begin
FrmCadastroDeClientes := TFrmCadastroDeClientes.Create(nil);
try
FrmCadastroDeClientes.ShowModal();
finally
FreeAndNil(FrmCadastroDeClientes);
end;
end;
procedure TFrmCadastroDeClientes.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
DAOCliente: TDAOCliente;
Cliente: TModelCliente;
begin
if (Key = 13) then
begin
if (ActiveControl = EdtID) then
begin
DAOCliente := TDAOCliente.Create();
try
Cliente := DAOCliente.Pesquisar(StrToIntdEF(EdtID.Text, 0));
try
if (Cliente.ID > 0) then
begin
// Popula os campos da tela
EdtNome.Text := Cliente.Nome;
end
else if ( EdtID.Text <> EmptyStr ) then
begin
MessageDlg( RSClienteNaoEncontrado, mtInformation, [mbok], 0 );
Exit;
end;
SelectNext(ActiveControl, True, True);
finally
FreeAndNil(Cliente);
end;
finally
FreeAndNil(DAOCliente);
end;
end
else if ( ActiveControl = EdtNome ) then
begin
//
SelectNext(ActiveControl, True, True);
end;
end;
end;
procedure TFrmCadastroDeClientes.FormShow(Sender: TObject);
begin
// Simula o ENTRE para inicar a pesquisa do cliente e popular os campos da tela
// Isso deve ser melhorado, feito somente par demontrar a funcionalidade
if ( EdtID.Text <> EmptyStr ) then
keybd_event( 13, 0 ,0 , 0);
end;
procedure TFrmCadastroDeClientes.LimparFormulario;
begin
// Limpa os dados do formulário
EdtID.Clear;
EdtNome.Clear;
EdtID.SetFocus;
end;
procedure TFrmCadastroDeClientes.SpeedButton1Click(Sender: TObject);
var
ID: Integer;
begin
ID := TFrmPesquisarClientes.PesquisarCliente();
if (ID > 0) then
EdtID.Text := IntToStr(ID);
EdtID.SetFocus;
end;
end.
|
unit Alcinoe.iOSApi.WebRTC;
interface
uses
Macapi.CoreFoundation,
Macapi.CoreServices,
Macapi.Dispatch,
Macapi.Mach,
Macapi.ObjCRuntime,
Macapi.ObjectiveC,
iOSapi.AVFoundation,
iOSapi.CocoaTypes,
iOSapi.CoreGraphics,
iOSapi.CoreVideo,
iOSapi.Foundation,
iOSapi.OpenGLES,
iOSapi.UIKit;
{$M+}
type
//Represents the signaling state of the peer connection.
//typedef NS_ENUM(NSInteger, RTCSignalingState)
RTCSignalingState = NSInteger;
const
RTCSignalingStateStable = 0;
RTCSignalingStateHaveLocalOffer = 1;
RTCSignalingStateHaveLocalPrAnswer = 2;
RTCSignalingStateHaveRemoteOffer = 3;
RTCSignalingStateHaveRemotePrAnswer = 4;
RTCSignalingStateClosed = 5;
type
//Represents the ice connection state of the peer connection.
//typedef NS_ENUM(NSInteger, RTCIceConnectionState)
RTCIceConnectionState = NSInteger;
const
RTCIceConnectionStateNew = 0;
RTCIceConnectionStateChecking = 1;
RTCIceConnectionStateConnected = 2;
RTCIceConnectionStateCompleted = 3;
RTCIceConnectionStateFailed = 4;
RTCIceConnectionStateDisconnected = 5;
RTCIceConnectionStateClosed = 6;
RTCIceConnectionStateCount = 7;
type
//Represents the ice gathering state of the peer connection.
//typedef NS_ENUM(NSInteger, RTCIceGatheringState)
RTCIceGatheringState = NSInteger;
const
RTCIceGatheringStateNew = 0;
RTCIceGatheringStateGathering = 1;
RTCIceGatheringStateComplete = 2;
type
//Represents the stats output level.
//typedef NS_ENUM(NSInteger, RTCStatsOutputLevel)
RTCStatsOutputLevel = NSInteger;
const
RTCStatsOutputLevelStandard = 0;
RTCStatsOutputLevelDebug = 1;
type
//typedef NS_ENUM(NSInteger, RTCSourceState)
RTCSourceState = NSInteger;
const
RTCSourceStateInitializing = 0;
RTCSourceStateLive = 1;
RTCSourceStateEnded = 2;
RTCSourceStateMuted = 3;
type
//Represents the state of the track. This exposes the same states in C++.
//typedef NS_ENUM(NSInteger, RTCMediaStreamTrackState)
RTCMediaStreamTrackState = NSInteger;
const
RTCMediaStreamTrackStateLive = 0;
RTCMediaStreamTrackStateEnded = 1;
type
//typedef NS_ENUM(NSInteger, RTCVideoRotation)
RTCVideoRotation = NSInteger;
const
RTCVideoRotation_0 = 0;
RTCVideoRotation_90 = 90;
RTCVideoRotation_180 = 180;
RTCVideoRotation_270 = 270;
type
//Subset of rtc::LoggingSeverity.
//typedef NS_ENUM(NSInteger, RTCLoggingSeverity)
RTCLoggingSeverity = NSInteger;
const
RTCLoggingSeverityVerbose = 0;
RTCLoggingSeverityInfo = 1;
RTCLoggingSeverityWarning = 2;
RTCLoggingSeverityError = 3;
RTCLoggingSeverityNone = 4;
type
//H264 Profiles and levels.
//NS_ENUM(NSUInteger, RTCH264Profile)
RTCH264Profile = NSUInteger;
const
RTCH264ProfileConstrainedBaseline = 0;
RTCH264ProfileBaseline = 1;
RTCH264ProfileMain = 2;
RTCH264ProfileConstrainedHigh = 3;
RTCH264ProfileHigh = 4;
type
//NS_ENUM(NSUInteger, RTCH264Level)
RTCH264Level = NSUInteger;
const
RTCH264Level1_b = 0;
RTCH264Level1 = 10;
RTCH264Level1_1 = 11;
RTCH264Level1_2 = 12;
RTCH264Level1_3 = 13;
RTCH264Level2 = 20;
RTCH264Level2_1 = 21;
RTCH264Level2_2 = 22;
RTCH264Level3 = 30;
RTCH264Level3_1 = 31;
RTCH264Level3_2 = 32;
RTCH264Level4 = 40;
RTCH264Level4_1 = 41;
RTCH264Level4_2 = 42;
RTCH264Level5 = 50;
RTCH264Level5_1 = 51;
RTCH264Level5_2 = 52;
type
//Represents the chosen SDP semantics for the RTCPeerConnection.
//NS_ENUM(NSInteger, RTCSdpSemantics)
RTCSdpSemantics = NSInteger;
const
RTCSdpSemanticsPlanB = 0;
RTCSdpSemanticsUnifiedPlan = 1;
type
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiverdirection
//NS_ENUM(NSInteger, RTCRtpTransceiverDirection)
RTCRtpTransceiverDirection = NSInteger;
const
RTCRtpTransceiverDirectionSendRecv = 0;
RTCRtpTransceiverDirectionSendOnly = 1;
RTCRtpTransceiverDirectionRecvOnly = 2;
RTCRtpTransceiverDirectionInactive = 3;
type
//Represents the media type of the RtpReceiver.
//NS_ENUM(NSInteger, RTCRtpMediaType)
RTCRtpMediaType = NSInteger;
const
RTCRtpMediaTypeAudio = 0;
RTCRtpMediaTypeVideo = 1;
RTCRtpMediaTypeData = 2;
type
//Represents the session description type. This exposes the same types that are
//in C++, which doesn't include the rollback type that is in the W3C spec.
//NS_ENUM(NSInteger, RTCSdpType)
RTCSdpType = NSInteger;
const
RTCSdpTypeOffer = 0;
RTCSdpTypePrAnswer = 1;
RTCSdpTypeAnswer = 2;
type
//typedef NS_OPTIONS(NSUInteger, AVAudioSessionCategoryOptions)
AVAudioSessionCategoryOptions = NSUInteger;
const
//MixWithOthers is only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute
AVAudioSessionCategoryOptionMixWithOthers = $1;
//DuckOthers is only valid with AVAudioSessionCategoryAmbient, AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute
AVAudioSessionCategoryOptionDuckOthers = $2;
//AllowBluetooth is only valid with AVAudioSessionCategoryRecord and AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryOptionAllowBluetooth = $4;
//DefaultToSpeaker is only valid with AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryOptionDefaultToSpeaker = $8;
//InterruptSpokenAudioAndMixWithOthers is only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute
AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers = $11;
//AllowBluetoothA2DP is only valid with AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryOptionAllowBluetoothA2DP = $20;
//AllowAirPlay is only valid with AVAudioSessionCategoryPlayAndRecord
AVAudioSessionCategoryOptionAllowAirPlay = $40;
//const
//RTCH264PacketizationModeNonInterleaved = 0;
//RTCH264PacketizationModeSingleNalUnit = 1;
//RTCIceTransportPolicyNone = 0;
//RTCIceTransportPolicyRelay = 1;
//RTCIceTransportPolicyNoHost = 2;
//RTCIceTransportPolicyAll = 3;
//RTCBundlePolicyBalanced = 0;
//RTCBundlePolicyMaxCompat = 1;
//RTCBundlePolicyMaxBundle = 2;
//RTCRtcpMuxPolicyNegotiate = 0;
//RTCRtcpMuxPolicyRequire = 1;
//RTCTcpCandidatePolicyEnabled = 0;
//RTCTcpCandidatePolicyDisabled = 1;
//RTCCandidateNetworkPolicyAll = 0;
//RTCCandidateNetworkPolicyLowCost = 1;
//RTCContinualGatheringPolicyGatherOnce = 0;
//RTCContinualGatheringPolicyGatherContinually = 1;
//RTCEncryptionKeyTypeRSA = 0;
//RTCEncryptionKeyTypeECDSA = 1;
//RTCDataChannelStateConnecting = 0;
//RTCDataChannelStateOpen = 1;
//RTCDataChannelStateClosing = 2;
//RTCDataChannelStateClosed = 3;
//RTCFrameTypeEmptyFrame = 0;
//RTCFrameTypeAudioFrameSpeech = 1;
//RTCFrameTypeAudioFrameCN = 2;
//RTCFrameTypeVideoFrameKey = 3;
//RTCFrameTypeVideoFrameDelta = 4;
//RTCVideoContentTypeUnspecified = 0;
//RTCVideoContentTypeScreenshare = 1;
//RTCVideoCodecModeRealtimeVideo = 0;
//RTCVideoCodecModeScreensharing = 1;
//RTCDispatcherTypeMain = 0;
//RTCDispatcherTypeCaptureSession = 1;
//RTCDispatcherTypeAudioSession = 2;
//RTCFileLoggerSeverityVerbose = 0;
//RTCFileLoggerSeverityInfo = 1;
//RTCFileLoggerSeverityWarning = 2;
//RTCFileLoggerSeverityError = 3;
//RTCFileLoggerTypeCall = 0;
//RTCFileLoggerTypeApp = 1;
//RTCTlsCertPolicySecure = 0;
//RTCTlsCertPolicyInsecureNoCheck = 1;
//RTCDeviceTypeUnknown = 0;
//RTCDeviceTypeIPhone1G = 1;
//RTCDeviceTypeIPhone3G = 2;
//RTCDeviceTypeIPhone3GS = 3;
//RTCDeviceTypeIPhone4 = 4;
//RTCDeviceTypeIPhone4Verizon = 5;
//RTCDeviceTypeIPhone4S = 6;
//RTCDeviceTypeIPhone5GSM = 7;
//RTCDeviceTypeIPhone5GSM_CDMA = 8;
//RTCDeviceTypeIPhone5CGSM = 9;
//RTCDeviceTypeIPhone5CGSM_CDMA = 10;
//RTCDeviceTypeIPhone5SGSM = 11;
//RTCDeviceTypeIPhone5SGSM_CDMA = 12;
//RTCDeviceTypeIPhone6Plus = 13;
//RTCDeviceTypeIPhone6 = 14;
//RTCDeviceTypeIPhone6S = 15;
//RTCDeviceTypeIPhone6SPlus = 16;
//RTCDeviceTypeIPhone7 = 17;
//RTCDeviceTypeIPhone7Plus = 18;
//RTCDeviceTypeIPhoneSE = 19;
//RTCDeviceTypeIPhone8 = 20;
//RTCDeviceTypeIPhone8Plus = 21;
//RTCDeviceTypeIPhoneX = 22;
//RTCDeviceTypeIPhoneXS = 23;
//RTCDeviceTypeIPhoneXSMax = 24;
//RTCDeviceTypeIPhoneXR = 25;
//RTCDeviceTypeIPodTouch1G = 26;
//RTCDeviceTypeIPodTouch2G = 27;
//RTCDeviceTypeIPodTouch3G = 28;
//RTCDeviceTypeIPodTouch4G = 29;
//RTCDeviceTypeIPodTouch5G = 30;
//RTCDeviceTypeIPodTouch6G = 31;
//RTCDeviceTypeIPad = 32;
//RTCDeviceTypeIPad2Wifi = 33;
//RTCDeviceTypeIPad2GSM = 34;
//RTCDeviceTypeIPad2CDMA = 35;
//RTCDeviceTypeIPad2Wifi2 = 36;
//RTCDeviceTypeIPadMiniWifi = 37;
//RTCDeviceTypeIPadMiniGSM = 38;
//RTCDeviceTypeIPadMiniGSM_CDMA = 39;
//RTCDeviceTypeIPad3Wifi = 40;
//RTCDeviceTypeIPad3GSM_CDMA = 41;
//RTCDeviceTypeIPad3GSM = 42;
//RTCDeviceTypeIPad4Wifi = 43;
//RTCDeviceTypeIPad4GSM = 44;
//RTCDeviceTypeIPad4GSM_CDMA = 45;
//RTCDeviceTypeIPad5 = 46;
//RTCDeviceTypeIPad6 = 47;
//RTCDeviceTypeIPadAirWifi = 48;
//RTCDeviceTypeIPadAirCellular = 49;
//RTCDeviceTypeIPadAirWifiCellular = 50;
//RTCDeviceTypeIPadAir2 = 51;
//RTCDeviceTypeIPadMini2GWifi = 52;
//RTCDeviceTypeIPadMini2GCellular = 53;
//RTCDeviceTypeIPadMini2GWifiCellular = 54;
//RTCDeviceTypeIPadMini3 = 55;
//RTCDeviceTypeIPadMini4 = 56;
//RTCDeviceTypeIPadPro9Inch = 57;
//RTCDeviceTypeIPadPro12Inch = 58;
//RTCDeviceTypeIPadPro12Inch2 = 59;
//RTCDeviceTypeIPadPro10Inch = 60;
//RTCDeviceTypeSimulatori386 = 61;
//RTCDeviceTypeSimulatorx86_64 = 62;
type
RTCPeerConnection = interface;
RTCVideoSource = interface;
RTCVideoTrack = interface;
RTCCertificate = interface;
RTCSessionDescription = interface;
RTCRtpParameters = interface;
TWebRTCPeerConnectionOfferForConstraintsCompletionHandler = procedure(sdp: RTCSessionDescription; error: NSError) of object;
TWebRTCPeerConnectionAnswerForConstraintsCompletionHandler = procedure(sdp: RTCSessionDescription; error: NSError) of object;
TWebRTCPeerConnectionSetLocalDescriptionCompletionHandler = procedure(error: NSError) of object;
TWebRTCPeerConnectionSetRemoteDescriptionCompletionHandler = procedure(error: NSError) of object;
//NSInteger = Integer;
//PNSInteger = ^NSInteger;
//NSUInteger = Cardinal;
//PNSUInteger = ^NSUInteger;
//AVAudioSessionRouteChangeReason = NSUInteger;
//NSTimeInterval = Double;
//PNSTimeInterval = ^NSTimeInterval;
//AVAudioSessionPortOverride = NSUInteger;
//TWebRTCCallback = procedure(param1: NSString) of object;
//CVBufferRef = Pointer;
//PCVBufferRef = ^CVBufferRef;
//CVImageBufferRef = CVBufferRef;
//PCVImageBufferRef = ^CVImageBufferRef;
//CVPixelBufferRef = CVImageBufferRef;
//PCVPixelBufferRef = ^CVPixelBufferRef;
//FourCharCode = UInt32;
//PFourCharCode = ^FourCharCode;
//TWebRTCCompletionHandler1 = procedure() of object;
//RTCH264PacketizationMode = NSUInteger;
//RTCIceTransportPolicy = NSInteger;
//RTCBundlePolicy = NSInteger;
//RTCRtcpMuxPolicy = NSInteger;
//RTCTcpCandidatePolicy = NSInteger;
//RTCCandidateNetworkPolicy = NSInteger;
//RTCContinualGatheringPolicy = NSInteger;
//RTCEncryptionKeyType = NSInteger;
//RTCDataChannelState = NSInteger;
//RTCFrameType = NSUInteger;
//RTCVideoContentType = NSUInteger;
//RTCVideoCodecMode = NSUInteger;
//RTCVideoDecoderCallback = procedure(param1: RTCVideoFrame) of object;
//RTCVideoEncoderCallback = function(param1: RTCEncodedImage; param2: Pointer; param3: RTCRtpFragmentationHeader): Boolean; cdecl;
//RTCDispatcherQueueType = NSInteger;
//CGFloat = Single;
//PCGFloat = ^CGFloat;
//CGSize = record
//width: CGFloat;
//height: CGFloat;
//end;
//PCGSize = ^CGSize;
//GLuint = LongWord;
//PGLuint = ^GLuint;
//CGPoint = record
//x: CGFloat;
//y: CGFloat;
//end;
//PCGPoint = ^CGPoint;
//CGRect = record
//origin: CGPoint;
//size: CGSize;
//end;
//PCGRect = ^CGRect;
//__darwin_size_t = LongWord;
//P__darwin_size_t = ^__darwin_size_t;
//RTCFileLoggerSeverity = NSUInteger;
//RTCFileLoggerRotationType = NSUInteger;
//RTCFileVideoCapturerErrorBlock = procedure(param1: NSError) of object;
//RTCTlsCertPolicy = NSUInteger;
//CFTimeInterval = Double;
//PCFTimeInterval = ^CFTimeInterval;
//UIViewContentMode = NSInteger;
//TWebRTCCompletionHandler3 = procedure(param1: NSArray) of object;
//RTCDeviceType = NSInteger;
//{*********************************************}
//RTCAudioSessionClass = interface(NSObjectClass)
//['{A6B6114F-8A68-4D27-B6DC-0D31A79AF1D9}']
//{ class } function sharedInstance: Pointer { instancetype }; cdecl;
//end;
//RTCAudioSession = interface(NSObject)
//['{72EA274E-32EC-4F26-A431-9209D20B8589}']
//function session: AVAudioSession; cdecl;
//function isActive: Boolean; cdecl;
//function isLocked: Boolean; cdecl;
//procedure setUseManualAudio(useManualAudio: Boolean); cdecl;
//function useManualAudio: Boolean; cdecl;
//procedure setIsAudioEnabled(isAudioEnabled: Boolean); cdecl;
//function isAudioEnabled: Boolean; cdecl;
//function category: NSString; cdecl;
//function categoryOptions: AVAudioSessionCategoryOptions; cdecl;
//function mode: NSString; cdecl;
//function secondaryAudioShouldBeSilencedHint: Boolean; cdecl;
//function currentRoute: AVAudioSessionRouteDescription; cdecl;
//function maximumInputNumberOfChannels: NSInteger; cdecl;
//function maximumOutputNumberOfChannels: NSInteger; cdecl;
//function inputGain: Single; cdecl;
//function inputGainSettable: Boolean; cdecl;
//function inputAvailable: Boolean; cdecl;
//function inputDataSources: NSArray; cdecl;
//function inputDataSource: AVAudioSessionDataSourceDescription; cdecl;
//function outputDataSources: NSArray; cdecl;
//function outputDataSource: AVAudioSessionDataSourceDescription; cdecl;
//function sampleRate: Double; cdecl;
//function preferredSampleRate: Double; cdecl;
//function inputNumberOfChannels: NSInteger; cdecl;
//function outputNumberOfChannels: NSInteger; cdecl;
//function outputVolume: Single; cdecl;
//function inputLatency: NSTimeInterval; cdecl;
//function outputLatency: NSTimeInterval; cdecl;
//function IOBufferDuration: NSTimeInterval; cdecl;
//function preferredIOBufferDuration: NSTimeInterval; cdecl;
//procedure addDelegate(delegate: Pointer); cdecl;
//procedure removeDelegate(delegate: Pointer); cdecl;
//procedure lockForConfiguration; cdecl;
//procedure unlockForConfiguration; cdecl;
//function setActive(active: Boolean; error: NSError): Boolean; cdecl;
//function setCategory(category: NSString; withOptions: AVAudioSessionCategoryOptions; error: NSError): Boolean; cdecl;
//function setMode(mode: NSString; error: NSError): Boolean; cdecl;
//function setInputGain(gain: Single; error: NSError): Boolean; cdecl;
//function setPreferredSampleRate(sampleRate: Double; error: NSError): Boolean; cdecl;
//function setPreferredIOBufferDuration(duration: NSTimeInterval; error: NSError): Boolean; cdecl;
//function setPreferredInputNumberOfChannels(count: NSInteger; error: NSError): Boolean; cdecl;
//function setPreferredOutputNumberOfChannels(count: NSInteger; error: NSError): Boolean; cdecl;
//function overrideOutputAudioPort(portOverride: AVAudioSessionPortOverride; error: NSError): Boolean; cdecl;
//function setPreferredInput(inPort: AVAudioSessionPortDescription; error: NSError): Boolean; cdecl;
//function setInputDataSource(dataSource: AVAudioSessionDataSourceDescription; error: NSError): Boolean; cdecl;
//function setOutputDataSource(dataSource: AVAudioSessionDataSourceDescription; error: NSError): Boolean; cdecl;
//[MethodName('setConfiguration:error:')]
//function setConfigurationError(configuration: RTCAudioSessionConfiguration; error: NSError): Boolean; cdecl;
//[MethodName('setConfiguration:active:error:')]
//function setConfigurationActiveError(configuration: RTCAudioSessionConfiguration; active: Boolean; error: NSError): Boolean; cdecl;
//end;
//TRTCAudioSession = class(TOCGenericImport<RTCAudioSessionClass, RTCAudioSession>) end;
//PRTCAudioSession = Pointer;
//{*************************************}
RTCAudioSessionConfiguration = interface;
//{************************************************}
//@interface RTCAudioSessionConfiguration : NSObject
RTCAudioSessionConfigurationClass = interface(NSObjectClass)
['{5391E964-2176-41A0-9362-E2C5D2230817}']
//Returns the current configuration of the audio session.
//+ (instancetype)currentConfiguration;
//{ class } function currentConfiguration: Pointer { instancetype }; cdecl;
//Returns the configuration that WebRTC needs.
//+ (instancetype)webRTCConfiguration;
{ class } function webRTCConfiguration: Pointer { instancetype }; cdecl;
//Provide a way to override the default configuration./
//+ (void)setWebRTCConfiguration:(RTCAudioSessionConfiguration *)configuration;
{ class } procedure setWebRTCConfiguration(configuration: RTCAudioSessionConfiguration); cdecl;
end;
RTCAudioSessionConfiguration = interface(NSObject)
['{F0B3D9A6-B0B4-4CBD-9769-FF2FE4CA5F05}']
//@property(nonatomic, strong) NSString *category;
//procedure setCategory(category: NSString); cdecl;
//function category: NSString; cdecl;
//@property(nonatomic, assign) AVAudioSessionCategoryOptions categoryOptions;
procedure setCategoryOptions(categoryOptions: AVAudioSessionCategoryOptions); cdecl;
function categoryOptions: AVAudioSessionCategoryOptions; cdecl;
//@property(nonatomic, strong) NSString *mode;
//procedure setMode(mode: NSString); cdecl;
//function mode: NSString; cdecl;
//@property(nonatomic, assign) double sampleRate;
//procedure setSampleRate(sampleRate: Double); cdecl;
//function sampleRate: Double; cdecl;
//@property(nonatomic, assign) NSTimeInterval ioBufferDuration;
//procedure setIoBufferDuration(IOBufferDuration: NSTimeInterval); cdecl;
//function IOBufferDuration: NSTimeInterval; cdecl;
//@property(nonatomic, assign) NSInteger inputNumberOfChannels;
//procedure setInputNumberOfChannels(inputNumberOfChannels: NSInteger); cdecl;
//function inputNumberOfChannels: NSInteger; cdecl;
//@property(nonatomic, assign) NSInteger outputNumberOfChannels;
//procedure setOutputNumberOfChannels(outputNumberOfChannels: NSInteger); cdecl;
//function outputNumberOfChannels: NSInteger; cdecl;
//Initializes configuration to defaults.
//- (instancetype)init NS_DESIGNATED_INITIALIZER;
//function init: Pointer { instancetype }; cdecl;
end;
TRTCAudioSessionConfiguration = class(TOCGenericImport<RTCAudioSessionConfigurationClass, RTCAudioSessionConfiguration>) end;
PRTCAudioSessionConfiguration = Pointer;
{************************************}
//@interface RTCMediaSource : NSObject
RTCMediaSourceClass = interface(NSObjectClass)
['{BF16BBB0-F9DD-4483-AF2B-4503EC43D476}']
end;
RTCMediaSource = interface(NSObject)
['{77A69BA4-3968-4235-AF7B-7E5A224294B7}']
//The current state of the RTCMediaSource.
//@property(nonatomic, readonly) RTCSourceState state;
function state: RTCSourceState; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
end;
TRTCMediaSource = class(TOCGenericImport<RTCMediaSourceClass, RTCMediaSource>) end;
PRTCMediaSource = Pointer;
{******************************************}
//@interface RTCAudioSource : RTCMediaSource
RTCAudioSourceClass = interface(RTCMediaSourceClass)
['{90AB4822-6838-4B2D-9BC8-A6798E51ADA5}']
end;
RTCAudioSource = interface(RTCMediaSource)
['{7018504B-82F1-4C7F-BAEE-141FEBDC296B}']
//- (instancetype)init NS_UNAVAILABLE;
//Sets the volume for the RTCMediaSource. |volume| is a gain value in the range [0, 10].
//Temporary fix to be able to modify volume of remote audio tracks.
//TODO(kthelgason): Property stays here temporarily until a proper volume-api
//is available on the surface exposed by webrtc.
//@property(nonatomic, assign) double volume;
procedure setVolume(volume: Double); cdecl;
function volume: Double; cdecl;
end;
TRTCAudioSource = class(TOCGenericImport<RTCAudioSourceClass, RTCAudioSource>) end;
PRTCAudioSource = Pointer;
{*****************************************}
//@interface RTCMediaStreamTrack : NSObject
RTCMediaStreamTrackClass = interface(NSObjectClass)
['{C08DFEAA-9074-49DC-B5B9-04A6BFB410C9}']
end;
RTCMediaStreamTrack = interface(NSObject)
['{12C83840-E22E-4DDF-A0C6-EA130FF79708}']
//The kind of track. For example, "audio" if this track represents an audio
//track and "video" if this track represents a video track.
//@property(nonatomic, readonly) NSString *kind;
function kind: NSString; cdecl;
//An identifier string.
//@property(nonatomic, readonly) NSString *trackId;
//function trackId: NSString; cdecl;
//The enabled state of the track.
//@property(nonatomic, assign) BOOL isEnabled;
procedure setIsEnabled(isEnabled: Boolean); cdecl;
function isEnabled: Boolean; cdecl;
//The state of the track.
//@property(nonatomic, readonly) RTCMediaStreamTrackState readyState;
//function readyState: RTCMediaStreamTrackState; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
end;
TRTCMediaStreamTrack = class(TOCGenericImport<RTCMediaStreamTrackClass, RTCMediaStreamTrack>) end;
PRTCMediaStreamTrack = Pointer;
{**********************************************}
//@interface RTCAudioTrack : RTCMediaStreamTrack
RTCAudioTrackClass = interface(RTCMediaStreamTrackClass)
['{4F246275-31AB-41F9-B091-18F051C7A486}']
end;
RTCAudioTrack = interface(RTCMediaStreamTrack)
['{A9828D51-5F7A-4F66-AAFC-EC173651A1DC}']
//The audio source for this audio track.
//@property(nonatomic, readonly) RTCAudioSource *source;
//function source: RTCAudioSource; cdecl;
end;
TRTCAudioTrack = class(TOCGenericImport<RTCAudioTrackClass, RTCAudioTrack>) end;
PRTCAudioTrack = Pointer;
//{***********************************************}
//RTCCallbackLoggerClass = interface(NSObjectClass)
//['{D5096C46-8F94-4AAA-9A8A-06BA8576B3FD}']
//end;
//RTCCallbackLogger = interface(NSObject)
//['{20D563D2-C274-42C1-943C-C0015D9A399A}']
//procedure setSeverity(severity: RTCLoggingSeverity); cdecl;
//function severity: RTCLoggingSeverity; cdecl;
//procedure start(callback: TWebRTCCallback); cdecl;
//procedure stop; cdecl;
//end;
//TRTCCallbackLogger = class(TOCGenericImport<RTCCallbackLoggerClass, RTCCallbackLogger>) end;
//PRTCCallbackLogger = Pointer;
//{************************************************}
//RTCCameraPreviewViewClass = interface(UIViewClass)
//['{F4BABECA-DE65-4237-ADF2-99628993E518}']
//end;
//RTCCameraPreviewView = interface(UIView)
//['{BD3B6360-22DD-438B-877F-1687A37C7813}']
//procedure setCaptureSession(captureSession: AVCaptureSession); cdecl;
//function captureSession: AVCaptureSession; cdecl;
//end;
//TRTCCameraPreviewView = class(TOCGenericImport<RTCCameraPreviewViewClass, RTCCameraPreviewView>) end;
//PRTCCameraPreviewView = Pointer;
{***********************************}
//@interface RTCVideoFrame : NSObject
RTCVideoFrameClass = interface(NSObjectClass)
['{EFA1CAD4-76CA-4029-9AE4-FDF8185B63B8}']
end;
RTCVideoFrame = interface(NSObject)
['{BC992027-8BC1-4AFB-B839-E0F379070055}']
//Width without rotation applied.
//@property(nonatomic, readonly) int width;
function width: Integer; cdecl;
//Height without rotation applied.
//@property(nonatomic, readonly) int height;
function height: Integer; cdecl;
//@property(nonatomic, readonly) RTCVideoRotation rotation;
function rotation: RTCVideoRotation; cdecl;
//Timestamp in nanoseconds.
//@property(nonatomic, readonly) int64_t timeStampNs;
function timeStampNs: Int64; cdecl;
//Timestamp 90 kHz.
//@property(nonatomic, assign) int32_t timeStamp;
//procedure setTimeStamp(timeStamp: Int32); cdecl;
function timeStamp: Int32; cdecl;
//@property(nonatomic, readonly) id<RTCVideoFrameBuffer> buffer;
function buffer: Pointer; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//- (instancetype) new NS_UNAVAILABLE;
//Initialize an RTCVideoFrame from a pixel buffer, rotation, and timestamp.
//Deprecated - initialize with a RTCCVPixelBuffer instead
//- (instancetype)initWithPixelBuffer:(CVPixelBufferRef)pixelBuffer
// rotation:(RTCVideoRotation)rotation
// timeStampNs:(int64_t)timeStampNs
// DEPRECATED_MSG_ATTRIBUTE("use initWithBuffer instead");
//[MethodName('initWithPixelBuffer:rotation:timeStampNs:')]
//function initWithPixelBufferRotationTimeStampNs (pixelBuffer: CVPixelBufferRef; rotation: RTCVideoRotation; timeStampNs: Int64): Pointer { instancetype }; cdecl; deprecated;
//Initialize an RTCVideoFrame from a pixel buffer combined with cropping and
//scaling. Cropping will be applied first on the pixel buffer, followed by
//scaling to the final resolution of scaledWidth x scaledHeight.
//- (instancetype)initWithPixelBuffer:(CVPixelBufferRef)pixelBuffer
// scaledWidth:(int)scaledWidth
// scaledHeight:(int)scaledHeight
// cropWidth:(int)cropWidth
// cropHeight:(int)cropHeight
// cropX:(int)cropX
// cropY:(int)cropY
// rotation:(RTCVideoRotation)rotation
// timeStampNs:(int64_t)timeStampNs
// DEPRECATED_MSG_ATTRIBUTE("use initWithBuffer instead");
//[MethodName ('initWithPixelBuffer:scaledWidth:scaledHeight:cropWidth:cropHeight:cropX:cropY:rotation:timeStampNs:') ]
//function initWithPixelBufferScaledWidthScaledHeightCropWidthCropHeightCropXCropYRotationTimeStampNs (pixelBuffer: CVPixelBufferRef; scaledWidth: Integer; scaledHeight: Integer; cropWidth: Integer; cropHeight: Integer; cropX: Integer; cropY: Integer; rotation: RTCVideoRotation; timeStampNs: Int64): Pointer { instancetype }; cdecl; deprecated;
//Initialize an RTCVideoFrame from a frame buffer, rotation, and timestamp.
//- (instancetype)initWithBuffer:(id<RTCVideoFrameBuffer>)frameBuffer
// rotation:(RTCVideoRotation)rotation
// timeStampNs:(int64_t)timeStampNs;
//function initWithBuffer(frameBuffer: Pointer; rotation: RTCVideoRotation; timeStampNs: Int64): Pointer { instancetype }; cdecl;
//Return a frame that is guaranteed to be I420, i.e. it is possible to access
//the YUV data on it.
//- (RTCVideoFrame *)newI420VideoFrame;
function newI420VideoFrame: RTCVideoFrame; cdecl;
end;
TRTCVideoFrame = class(TOCGenericImport<RTCVideoFrameClass, RTCVideoFrame>) end;
PRTCVideoFrame = Pointer;
{**************************************}
//@interface RTCVideoCapturer : NSObject
RTCVideoCapturerClass = interface(NSObjectClass)
['{A470FB28-9FFF-441E-97BB-C62B958F9C23}']
end;
RTCVideoCapturer = interface(NSObject)
['{C1C314C8-3EE1-4F48-9DCC-15969C3B3C11}']
//@property(nonatomic, weak) id<RTCVideoCapturerDelegate> delegate;
procedure setDelegate(delegate: Pointer); cdecl;
function delegate: Pointer; cdecl;
//- (instancetype)initWithDelegate:(id<RTCVideoCapturerDelegate>)delegate;
function initWithDelegate(delegate: Pointer): Pointer { instancetype }; cdecl;
end;
TRTCVideoCapturer = class(TOCGenericImport<RTCVideoCapturerClass, RTCVideoCapturer>) end;
PRTCVideoCapturer = Pointer;
{****************************************************}
//@interface RTCCameraVideoCapturer : RTCVideoCapturer
RTCCameraVideoCapturerClass = interface(RTCVideoCapturerClass)
['{DCABFA66-0A5D-4881-B490-E31B73C73CD5}']
//Returns list of available capture devices that support video capture.
//+ (NSArray<AVCaptureDevice *> *)captureDevices;
{ class } function captureDevices: NSArray; cdecl;
// Returns list of formats that are supported by this class for this device.
//+ (NSArray<AVCaptureDeviceFormat *> *)supportedFormatsForDevice:(AVCaptureDevice *)device;
{ class } function supportedFormatsForDevice(device: AVCaptureDevice): NSArray; cdecl;
end;
RTCCameraVideoCapturer = interface(RTCVideoCapturer)
['{C8751868-E389-4BEB-AC6A-9F630E73BC58}']
//Capture session that is used for capturing. Valid from initialization to dealloc.
//@property(readonly, nonatomic) AVCaptureSession *captureSession;
//function captureSession: AVCaptureSession; cdecl;
//Returns the most efficient supported output pixel format for this capturer.
//- (FourCharCode)preferredOutputPixelFormat;
function preferredOutputPixelFormat: FourCharCode; cdecl;
//Starts the capture session asynchronously and notifies callback on completion.
//The device will capture video in the format given in the `format` parameter. If the pixel format
//in `format` is supported by the WebRTC pipeline, the same pixel format will be used for the
//output. Otherwise, the format returned by `preferredOutputPixelFormat` will be used.
//- (void)startCaptureWithDevice:(AVCaptureDevice *)device
// format:(AVCaptureDeviceFormat *)format
// fps:(NSInteger)fps
// completionHandler:(nullable void (^)(NSError *))completionHandler;
//[MethodName('startCaptureWithDevice:format:fps:completionHandler:')]
//procedure startCaptureWithDeviceFormatFpsCompletionHandler (device: AVCaptureDevice; format: AVCaptureDeviceFormat; fps: NSInteger; completionHandler: TWebRTCCompletionHandler); cdecl;
//Stops the capture session asynchronously and notifies callback on completion.
//- (void)stopCaptureWithCompletionHandler:(nullable void (^)(void))completionHandler;
//procedure stopCaptureWithCompletionHandler(completionHandler: TWebRTCCompletionHandler1); cdecl;
//Starts the capture session asynchronously.
//- (void)startCaptureWithDevice:(AVCaptureDevice *)device
// format:(AVCaptureDeviceFormat *)format
// fps:(NSInteger)fps;
[MethodName('startCaptureWithDevice:format:fps:')]
procedure startCaptureWithDeviceFormatFps(device: AVCaptureDevice; format: AVCaptureDeviceFormat; fps: NSInteger); cdecl;
//Stops the capture session asynchronously.
//- (void)stopCapture;
procedure stopCapture; cdecl;
end;
TRTCCameraVideoCapturer = class(TOCGenericImport<RTCCameraVideoCapturerClass, RTCCameraVideoCapturer>) end;
PRTCCameraVideoCapturer = Pointer;
{************************************************}
//@interface RTCCertificate : NSObject <NSCopying>
RTCCertificateClass = interface(NSObjectClass)
['{C9AFAF4F-D1EB-4EA3-AE98-B00BF94AB5DC}']
//Generate a new certificate for 're' use.
//Optional dictionary of parameters. Defaults to KeyType ECDSA if none are
//provided.
//- name: "ECDSA" or "RSASSA-PKCS1-v1_5"
//+ (nullable RTCCertificate *)generateCertificateWithParams:(NSDictionary *)params;
{ class } function generateCertificateWithParams(params: NSDictionary): RTCCertificate; cdecl;
end;
RTCCertificate = interface(NSObject)
['{3952697D-06D6-4E0B-BA49-CE026B8C41FD}']
//Private key in PEM.
//@property(nonatomic, readonly, copy) NSString *private_key;
function private_key: NSString; cdecl;
// Public key in an x509 cert encoded in PEM.
//@property(nonatomic, readonly, copy) NSString *certificate;
function certificate: NSString; cdecl;
//Initialize an RTCCertificate with PEM strings for private_key and certificate.
//- (instancetype)initWithPrivateKey:(NSString *)private_key
// certificate:(NSString *)certificate NS_DESIGNATED_INITIALIZER;
function initWithPrivateKey(private_key: NSString; certificate: NSString): Pointer { instancetype }; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
end;
TRTCCertificate = class(TOCGenericImport<RTCCertificateClass, RTCCertificate>) end;
PRTCCertificate = Pointer;
//{******************************************************}
//RTCCodecSpecificInfoH264Class = interface(NSObjectClass)
//['{96F3E93A-D2B8-401E-8016-612FA13D274B}']
//end;
//RTCCodecSpecificInfoH264 = interface(NSObject)
//['{4502F845-EAA2-40B8-89D6-7793DFBEDB62}']
//procedure setPacketizationMode(packetizationMode: RTCH264PacketizationMode); cdecl;
//function packetizationMode: RTCH264PacketizationMode; cdecl;
//end;
//TRTCCodecSpecificInfoH264 = class (TOCGenericImport<RTCCodecSpecificInfoH264Class, RTCCodecSpecificInfoH264>) end;
//PRTCCodecSpecificInfoH264 = Pointer;
{**********************************}
//@interface RTCIceServer : NSObject
RTCIceServerClass = interface(NSObjectClass)
['{D15624FE-A7D9-4EFA-AD79-1251BE9107D3}']
end;
RTCIceServer = interface(NSObject)
['{B6AE16E6-34F2-4F29-A17D-E88F2E0397ED}']
//URI(s) for this server represented as NSStrings.
//@property(nonatomic, readonly) NSArray<NSString *> *urlStrings;
function urlStrings: NSArray; cdecl;
//Username to use if this RTCIceServer object is a TURN server.
//@property(nonatomic, readonly, nullable) NSString *username;
function username: NSString; cdecl;
//Credential to use if this RTCIceServer object is a TURN server.
//@property(nonatomic, readonly, nullable) NSString *credential;
function credential: NSString; cdecl;
//TLS certificate policy to use if this RTCIceServer object is a TURN server.
//@property(nonatomic, readonly) RTCTlsCertPolicy tlsCertPolicy;
//function tlsCertPolicy: RTCTlsCertPolicy; cdecl;
//If the URIs in |urls| only contain IP addresses, this field can be used
//to indicate the hostname, which may be necessary for TLS (using the SNI
//extension). If |urls| itself contains the hostname, this isn't necessary.
//@property(nonatomic, readonly, nullable) NSString *hostname;
function hostname: NSString; cdecl;
//List of protocols to be used in the TLS ALPN extension.
//@property(nonatomic, readonly) NSArray<NSString *> *tlsAlpnProtocols;
//function tlsAlpnProtocols: NSArray; cdecl;
//List elliptic curves to be used in the TLS elliptic curves extension.
//Only curve names supported by OpenSSL should be used (eg. "P-256","X25519").
//@property(nonatomic, readonly) NSArray<NSString *> *tlsEllipticCurves;
//function tlsEllipticCurves: NSArray; cdecl;
//- (nonnull instancetype)init NS_UNAVAILABLE;
//Convenience initializer for a server with no authentication (e.g. STUN).
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings;
[MethodName('initWithURLStrings:')]
function initWithURLStrings(urlStrings: NSArray): Pointer { instancetype }; cdecl;
//Initialize an RTCIceServer with its associated URLs, optional username,
//optional credential, and credentialType.
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings
// username:(nullable NSString *)username
// credential:(nullable NSString *)credential;
[MethodName('initWithURLStrings:username:credential:')]
function initWithURLStringsUsernameCredential(urlStrings: NSArray; username: NSString; credential: NSString): Pointer { instancetype }; cdecl;
//Initialize an RTCIceServer with its associated URLs, optional username,
//optional credential, and TLS cert policy.
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings
// username:(nullable NSString *)username
// credential:(nullable NSString *)credential
// tlsCertPolicy:(RTCTlsCertPolicy)tlsCertPolicy;
//[MethodName('initWithURLStrings:username:credential:tlsCertPolicy:')]
//function initWithURLStringsUsernameCredentialTlsCertPolicy (urlStrings: NSArray; username: NSString; credential: NSString; tlsCertPolicy: RTCTlsCertPolicy): Pointer { instancetype }; cdecl;
//Initialize an RTCIceServer with its associated URLs, optional username,
//optional credential, TLS cert policy and hostname.
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings
// username:(nullable NSString *)username
// credential:(nullable NSString *)credential
// tlsCertPolicy:(RTCTlsCertPolicy)tlsCertPolicy
// hostname:(nullable NSString *)hostname;
//[MethodName ('initWithURLStrings:username:credential:tlsCertPolicy:hostname:')]
//function initWithURLStringsUsernameCredentialTlsCertPolicyHostname (urlStrings: NSArray; username: NSString; credential: NSString; tlsCertPolicy: RTCTlsCertPolicy; hostname: NSString): Pointer { instancetype }; cdecl;
//Initialize an RTCIceServer with its associated URLs, optional username,
//optional credential, TLS cert policy, hostname and ALPN protocols.
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings
// username:(nullable NSString *)username
// credential:(nullable NSString *)credential
// tlsCertPolicy:(RTCTlsCertPolicy)tlsCertPolicy
// hostname:(nullable NSString *)hostname
// tlsAlpnProtocols:(NSArray<NSString *> *)tlsAlpnProtocols;
//[MethodName ('initWithURLStrings:username:credential:tlsCertPolicy:hostname:tlsAlpnProtocols:') ]
//function initWithURLStringsUsernameCredentialTlsCertPolicyHostnameTlsAlpnProtocols (urlStrings: NSArray; username: NSString; credential: NSString; tlsCertPolicy: RTCTlsCertPolicy; hostname: NSString; tlsAlpnProtocols: NSArray): Pointer { instancetype }; cdecl;
//Initialize an RTCIceServer with its associated URLs, optional username,
//optional credential, TLS cert policy, hostname, ALPN protocols and
//elliptic curves.
//- (instancetype)initWithURLStrings:(NSArray<NSString *> *)urlStrings
// username:(nullable NSString *)username
// credential:(nullable NSString *)credential
// tlsCertPolicy:(RTCTlsCertPolicy)tlsCertPolicy
// hostname:(nullable NSString *)hostname
// tlsAlpnProtocols:(nullable NSArray<NSString *> *)tlsAlpnProtocols
// tlsEllipticCurves:(nullable NSArray<NSString *> *)tlsEllipticCurves
// NS_DESIGNATED_INITIALIZER;
//[MethodName ('initWithURLStrings:username:credential:tlsCertPolicy:hostname:tlsAlpnProtocols:tlsEllipticCurves:') ]
//function initWithURLStringsUsernameCredentialTlsCertPolicyHostnameTlsAlpnProtocolsTlsEllipticCurves (urlStrings: NSArray; username: NSString; credential: NSString; tlsCertPolicy: RTCTlsCertPolicy; hostname: NSString; tlsAlpnProtocols: NSArray; tlsEllipticCurves: NSArray): Pointer { instancetype }; cdecl;
end;
TRTCIceServer = class(TOCGenericImport<RTCIceServerClass, RTCIceServer>) end;
PRTCIceServer = Pointer;
//{**********************************************}
//RTCIntervalRangeClass = interface(NSObjectClass)
//['{D9929EBD-D3EA-461A-B3D8-C6B564E7FAEB}']
//end;
//RTCIntervalRange = interface(NSObject)
//['{68C6B303-BB26-43BB-89D0-1F0696FD94D2}']
//function min: NSInteger; cdecl;
//function max: NSInteger; cdecl;
//function init: Pointer { instancetype }; cdecl;
//function initWithMin(min: NSInteger; max: NSInteger): Pointer { instancetype }; cdecl;
//end;
//TRTCIntervalRange = class(TOCGenericImport<RTCIntervalRangeClass, RTCIntervalRange>) end;
//PRTCIntervalRange = Pointer;
{**************************************}
//@interface RTCConfiguration : NSObject
RTCConfigurationClass = interface(NSObjectClass)
['{B6FBFCDC-7338-4389-8449-F4F5107582BA}']
end;
RTCConfiguration = interface(NSObject)
['{D3B3564D-780E-497C-8E9C-FAEE23376E5C}']
//An array of Ice Servers available to be used by ICE.
//@property(nonatomic, copy) NSArray<RTCIceServer *> *iceServers;
procedure setIceServers(iceServers: NSArray); cdecl;
function iceServers: NSArray; cdecl;
//An RTCCertificate for 're' use.
//@property(nonatomic, nullable) RTCCertificate *certificate;
procedure setCertificate(certificate: RTCCertificate); cdecl;
function certificate: RTCCertificate; cdecl;
//Which candidates the ICE agent is allowed to use. The W3C calls it
//|iceTransportPolicy|, while in C++ it is called |type|.
//@property(nonatomic, assign) RTCIceTransportPolicy iceTransportPolicy;
//procedure setIceTransportPolicy(iceTransportPolicy: RTCIceTransportPolicy); cdecl;
//function iceTransportPolicy: RTCIceTransportPolicy; cdecl;
//The media-bundling policy to use when gathering ICE candidates.
//@property(nonatomic, assign) RTCBundlePolicy bundlePolicy;
//procedure setBundlePolicy(bundlePolicy: RTCBundlePolicy); cdecl;
//function bundlePolicy: RTCBundlePolicy; cdecl;
//The rtcp-mux policy to use when gathering ICE candidates.
//@property(nonatomic, assign) RTCRtcpMuxPolicy rtcpMuxPolicy;
//procedure setRtcpMuxPolicy(rtcpMuxPolicy: RTCRtcpMuxPolicy); cdecl;
//function rtcpMuxPolicy: RTCRtcpMuxPolicy; cdecl;
//@property(nonatomic, assign) RTCTcpCandidatePolicy tcpCandidatePolicy;
//procedure setTcpCandidatePolicy(tcpCandidatePolicy: RTCTcpCandidatePolicy); cdecl;
//function tcpCandidatePolicy: RTCTcpCandidatePolicy; cdecl;
//@property(nonatomic, assign) RTCCandidateNetworkPolicy candidateNetworkPolicy;
//procedure setCandidateNetworkPolicy(candidateNetworkPolicy: RTCCandidateNetworkPolicy); cdecl;
//function candidateNetworkPolicy: RTCCandidateNetworkPolicy; cdecl;
//@property(nonatomic, assign) RTCContinualGatheringPolicy continualGatheringPolicy;
//procedure setContinualGatheringPolicy(continualGatheringPolicy: RTCContinualGatheringPolicy); cdecl;
//function continualGatheringPolicy: RTCContinualGatheringPolicy; cdecl;
//By default, the PeerConnection will use a limited number of IPv6 network
//interfaces, in order to avoid too many ICE candidate pairs being created
//and delaying ICE completion.
//Can be set to INT_MAX to effectively disable the limit.
//@property(nonatomic, assign) int maxIPv6Networks;
//procedure setMaxIPv6Networks(maxIPv6Networks: Integer); cdecl;
//function maxIPv6Networks: Integer; cdecl;
//Exclude link-local network interfaces
//from considertaion for gathering ICE candidates.
//Defaults to NO.
//@property(nonatomic, assign) BOOL disableLinkLocalNetworks;
//procedure setDisableLinkLocalNetworks(disableLinkLocalNetworks: Boolean); cdecl;
//function disableLinkLocalNetworks: Boolean; cdecl;
//@property(nonatomic, assign) int audioJitterBufferMaxPackets;
//procedure setAudioJitterBufferMaxPackets(audioJitterBufferMaxPackets: Integer); cdecl;
//function audioJitterBufferMaxPackets: Integer; cdecl;
//@property(nonatomic, assign) BOOL audioJitterBufferFastAccelerate;
//procedure setAudioJitterBufferFastAccelerate(audioJitterBufferFastAccelerate: Boolean); cdecl;
//function audioJitterBufferFastAccelerate: Boolean; cdecl;
//@property(nonatomic, assign) int iceConnectionReceivingTimeout;
//procedure setIceConnectionReceivingTimeout(iceConnectionReceivingTimeout: Integer); cdecl;
//function iceConnectionReceivingTimeout: Integer; cdecl;
//@property(nonatomic, assign) int iceBackupCandidatePairPingInterval;
//procedure setIceBackupCandidatePairPingInterval (iceBackupCandidatePairPingInterval: Integer); cdecl;
//function iceBackupCandidatePairPingInterval: Integer; cdecl;
//Key type used to generate SSL identity. Default is ECDSA.
//@property(nonatomic, assign) RTCEncryptionKeyType keyType;
//procedure setKeyType(keyType: RTCEncryptionKeyType); cdecl;
//function keyType: RTCEncryptionKeyType; cdecl;
//ICE candidate pool size as defined in JSEP. Default is 0.
//@property(nonatomic, assign) int iceCandidatePoolSize;
//procedure setIceCandidatePoolSize(iceCandidatePoolSize: Integer); cdecl;
//function iceCandidatePoolSize: Integer; cdecl;
//Prune turn ports on the same network to the same turn server.
//Default is NO.
//@property(nonatomic, assign) BOOL shouldPruneTurnPorts;
//procedure setShouldPruneTurnPorts(shouldPruneTurnPorts: Boolean); cdecl;
//function shouldPruneTurnPorts: Boolean; cdecl;
//If set to YES, this means the ICE transport should presume TURN-to-TURN
//candidate pairs will succeed, even before a binding response is received.
//@property(nonatomic, assign) BOOL shouldPresumeWritableWhenFullyRelayed;
//procedure setShouldPresumeWritableWhenFullyRelayed (shouldPresumeWritableWhenFullyRelayed: Boolean); cdecl;
//function shouldPresumeWritableWhenFullyRelayed: Boolean; cdecl;
//If set to non-nil, controls the minimal interval between consecutive ICE
//check packets.
//@property(nonatomic, copy, nullable) NSNumber *iceCheckMinInterval;
//procedure setIceCheckMinInterval(iceCheckMinInterval: NSNumber); cdecl;
//function iceCheckMinInterval: NSNumber; cdecl;
//ICE Periodic Regathering
//If set, WebRTC will periodically create and propose candidates without
//starting a new ICE generation. The regathering happens continuously with
//interval specified in milliseconds by the uniform distribution [a, b].
//@property(nonatomic, strong, nullable) RTCIntervalRange *iceRegatherIntervalRange;
//procedure setIceRegatherIntervalRange(iceRegatherIntervalRange: RTCIntervalRange); cdecl;
//function iceRegatherIntervalRange: RTCIntervalRange; cdecl;
//Configure the SDP semantics used by this PeerConnection. Note that the
//WebRTC 1.0 specification requires UnifiedPlan semantics. The
//RTCRtpTransceiver API is only available with UnifiedPlan semantics.
//
//PlanB will cause RTCPeerConnection to create offers and answers with at
//most one audio and one video m= section with multiple RTCRtpSenders and
//RTCRtpReceivers specified as multiple a=ssrc lines within the section. This
//will also cause RTCPeerConnection to ignore all but the first m= section of
//the same media type.
//
//UnifiedPlan will cause RTCPeerConnection to create offers and answers with
//multiple m= sections where each m= section maps to one RTCRtpSender and one
//RTCRtpReceiver (an RTCRtpTransceiver), either both audio or both video. This
//will also cause RTCPeerConnection to ignore all but the first a=ssrc lines
//that form a Plan B stream.
//
//For users who wish to send multiple audio/video streams and need to stay
//interoperable with legacy WebRTC implementations or use legacy APIs,
//specify PlanB.
//
//For all other users, specify UnifiedPlan.
//@property(nonatomic, assign) RTCSdpSemantics sdpSemantics;
procedure setSdpSemantics(sdpSemantics: RTCSdpSemantics); cdecl;
function sdpSemantics: RTCSdpSemantics; cdecl;
//Actively reset the SRTP parameters when the DTLS transports underneath are
//changed after offer/answer negotiation. This is only intended to be a
//workaround for crbug.com/835958
//@property(nonatomic, assign) BOOL activeResetSrtpParams;
//procedure setActiveResetSrtpParams(activeResetSrtpParams: Boolean); cdecl;
//function activeResetSrtpParams: Boolean; cdecl;
//If MediaTransportFactory is provided in PeerConnectionFactory, this flag informs PeerConnection
//that it should use the MediaTransportInterface.
//@property(nonatomic, assign) BOOL useMediaTransport;
//procedure setUseMediaTransport(useMediaTransport: Boolean); cdecl;
//function useMediaTransport: Boolean; cdecl;
//- (instancetype)init;
//function init: Pointer { instancetype }; cdecl;
end;
TRTCConfiguration = class(TOCGenericImport<RTCConfigurationClass, RTCConfiguration>) end;
PRTCConfiguration = Pointer;
{************************************************************}
//@interface RTCCVPixelBuffer : NSObject <RTCVideoFrameBuffer>
RTCCVPixelBufferClass = interface(NSObjectClass)
['{AF44B741-EAD5-44A8-BB93-53A6303E5E7A}']
//+ (NSSet<NSNumber *> *)supportedPixelFormats;
{ class } function supportedPixelFormats: NSSet; cdecl;
end;
RTCCVPixelBuffer = interface(NSObject)
['{82775AF1-460D-46D2-90D4-8FC2B1412A50}']
//@property(nonatomic, readonly) CVPixelBufferRef pixelBuffer;
function pixelBuffer: CVPixelBufferRef; cdecl;
//@property(nonatomic, readonly) int cropX;
function cropX: Integer; cdecl;
//@property(nonatomic, readonly) int cropY;
function cropY: Integer; cdecl;
//@property(nonatomic, readonly) int cropWidth;
function cropWidth: Integer; cdecl;
//@property(nonatomic, readonly) int cropHeight;
function cropHeight: Integer; cdecl;
//- (instancetype)initWithPixelBuffer:(CVPixelBufferRef)pixelBuffer;
//[MethodName('initWithPixelBuffer:')]
//function initWithPixelBuffer(pixelBuffer: CVPixelBufferRef): Pointer { instancetype }; cdecl;
//- (instancetype)initWithPixelBuffer:(CVPixelBufferRef)pixelBuffer
// adaptedWidth:(int)adaptedWidth
// adaptedHeight:(int)adaptedHeight
// cropWidth:(int)cropWidth
// cropHeight:(int)cropHeight
// cropX:(int)cropX
// cropY:(int)cropY;
//[MethodName ('initWithPixelBuffer:adaptedWidth:adaptedHeight:cropWidth:cropHeight:cropX:cropY:') ]
//function initWithPixelBufferAdaptedWidthAdaptedHeightCropWidthCropHeightCropXCropY (pixelBuffer: CVPixelBufferRef; adaptedWidth: Integer; adaptedHeight: Integer; cropWidth: Integer; cropHeight: Integer; cropX: Integer; cropY: Integer): Pointer { instancetype }; cdecl;
//- (BOOL)requiresCropping;
//function requiresCropping: Boolean; cdecl;
//- (BOOL)requiresScalingToWidth:(int)width height:(int)height;
//function requiresScalingToWidth(width: Integer; height: Integer): Boolean; cdecl;
//- (int)bufferSizeForCroppingAndScalingToWidth:(int)width height:(int)height;
//function bufferSizeForCroppingAndScalingToWidth(width: Integer; height: Integer): Integer; cdecl;
//The minimum size of the |tmpBuffer| must be the number of bytes returned from the
//bufferSizeForCroppingAndScalingToWidth:height: method.
//If that size is 0, the |tmpBuffer| may be nil.
//- (BOOL)cropAndScaleTo:(CVPixelBufferRef)outputPixelBuffer
// withTempBuffer:(nullable uint8_t *)tmpBuffer;
//function cropAndScaleTo(outputPixelBuffer: CVPixelBufferRef; withTempBuffer: PByte): Boolean; cdecl;
end;
TRTCCVPixelBuffer = class(TOCGenericImport<RTCCVPixelBufferClass, RTCCVPixelBuffer>) end;
PRTCCVPixelBuffer = Pointer;
//{*******************************************}
//RTCDataBufferClass = interface(NSObjectClass)
//['{8B28D4C3-41A6-437C-92DE-68FC37CCF93F}']
//end;
//RTCDataBuffer = interface(NSObject)
//['{94218B3E-1882-45BA-897A-BD136219374E}']
//function data: NSData; cdecl;
//function isBinary: Boolean; cdecl;
//function initWithData(data: NSData; isBinary: Boolean): Pointer { instancetype }; cdecl;
//end;
//TRTCDataBuffer = class(TOCGenericImport<RTCDataBufferClass, RTCDataBuffer>) end;
//PRTCDataBuffer = Pointer;
{************************************}
//@interface RTCDataChannel : NSObject
RTCDataChannelClass = interface(NSObjectClass)
['{025C6769-3D1F-4FA4-90C2-CD10AD41AD33}']
end;
RTCDataChannel = interface(NSObject)
['{2FDBC0D3-56B7-4A43-A2CE-DAD670FB2940}']
//A label that can be used to distinguish this data channel from other data
//channel objects.
//@property(nonatomic, readonly) NSString *label;
function &label: NSString; cdecl;
//Whether the data channel can send messages in unreliable mode.
//@property(nonatomic, readonly) BOOL isReliable DEPRECATED_ATTRIBUTE;
//function isReliable: Boolean; cdecl;
//Returns whether this data channel is ordered or not.
//@property(nonatomic, readonly) BOOL isOrdered;
//function isOrdered: Boolean; cdecl;
//Deprecated. Use maxPacketLifeTime.
//@property(nonatomic, readonly) NSUInteger maxRetransmitTime DEPRECATED_ATTRIBUTE;
//function maxRetransmitTime: NSUInteger; cdecl; deprecated;
//The length of the time window (in milliseconds) during which transmissions
//and retransmissions may occur in unreliable mode.
//@property(nonatomic, readonly) uint16_t maxPacketLifeTime;
//function maxPacketLifeTime: Word; cdecl;
//The maximum number of retransmissions that are attempted in unreliable mode.
//@property(nonatomic, readonly) uint16_t maxRetransmits;
//function maxRetransmits: Word; cdecl;
//The name of the sub-protocol used with this data channel, if any. Otherwise
//this returns an empty string.
//@property(nonatomic, readonly) NSString *protocol;
//function protocol: NSString; cdecl;
//Returns whether this data channel was negotiated by the application or not.
//@property(nonatomic, readonly) BOOL isNegotiated;
//function isNegotiated: Boolean; cdecl;
//Deprecated. Use channelId.
//@property(nonatomic, readonly) NSInteger streamId DEPRECATED_ATTRIBUTE;
//function streamId: NSInteger; cdecl; deprecated;
//The identifier for this data channel.
//@property(nonatomic, readonly) int channelId;
function channelId: Integer; cdecl;
//The state of the data channel.
//@property(nonatomic, readonly) RTCDataChannelState readyState;
//function readyState: RTCDataChannelState; cdecl;
//The number of bytes of application data that have been queued using
//|sendData:| but that have not yet been transmitted to the network.
//@property(nonatomic, readonly) uint64_t bufferedAmount;
//function bufferedAmount: UInt64; cdecl;
//The delegate for this data channel.
//@property(nonatomic, weak) id<RTCDataChannelDelegate> delegate;
//procedure setDelegate(delegate: Pointer); cdecl;
//function delegate: Pointer; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Closes the data channel.
//- (void)close;
//procedure close; cdecl;
//Attempt to send |data| on this data channel's underlying data transport.
//- (BOOL)sendData:(RTCDataBuffer *)data;
//function sendData(data: RTCDataBuffer): Boolean; cdecl;
end;
TRTCDataChannel = class(TOCGenericImport<RTCDataChannelClass, RTCDataChannel>) end;
PRTCDataChannel = Pointer;
//{*********************************************************}
//RTCDataChannelConfigurationClass = interface(NSObjectClass)
//['{135B2907-3AF7-4050-ABEB-B3C05595693C}']
//end;
//RTCDataChannelConfiguration = interface(NSObject)
//['{1F85DF5C-6E32-4B77-8959-9057060BE601}']
//procedure setIsOrdered(isOrdered: Boolean); cdecl;
//function isOrdered: Boolean; cdecl;
//procedure setMaxRetransmitTimeMs(maxRetransmitTimeMs: NSInteger); cdecl;
//function maxRetransmitTimeMs: NSInteger; cdecl;
//procedure setMaxPacketLifeTime(maxPacketLifeTime: Integer); cdecl;
//function maxPacketLifeTime: Integer; cdecl;
//procedure setMaxRetransmits(maxRetransmits: Integer); cdecl;
//function maxRetransmits: Integer; cdecl;
//procedure setIsNegotiated(isNegotiated: Boolean); cdecl;
//function isNegotiated: Boolean; cdecl;
//procedure setStreamId(streamId: Integer); cdecl;
//function streamId: Integer; cdecl;
//procedure setChannelId(channelId: Integer); cdecl;
//function channelId: Integer; cdecl;
//procedure setProtocol(protocol: NSString); cdecl;
//function protocol: NSString; cdecl;
//end;
//TRTCDataChannelConfiguration = class(TOCGenericImport<RTCDataChannelConfigurationClass, RTCDataChannelConfiguration>) end;
//PRTCDataChannelConfiguration = Pointer;
{*****************************************************************************}
//Holds information to identify a codec. Corresponds to webrtc::SdpVideoFormat.
//@interface RTCVideoCodecInfo : NSObject <NSCoding>
RTCVideoCodecInfoClass = interface(NSObjectClass)
['{E9946732-49E4-43BE-B3B3-64FBA9779070}']
end;
RTCVideoCodecInfo = interface(NSObject)
['{1475B502-6FB2-4868-9624-CDC139211A85}']
//- (instancetype)init NS_UNAVAILABLE;
//- (instancetype)initWithName:(NSString *)name;
[MethodName('initWithName:')]
function initWithName(name: NSString): Pointer { instancetype }; cdecl;
//- (instancetype)initWithName:(NSString *)name
// parameters:(nullable NSDictionary<NSString *, NSString *> *)parameters
//NS_DESIGNATED_INITIALIZER;
[MethodName('initWithName:parameters:')]
function initWithNameParameters(name: NSString; parameters: NSDictionary): Pointer { instancetype }; cdecl;
//- (BOOL)isEqualToCodecInfo:(RTCVideoCodecInfo *)info;
function isEqualToCodecInfo(info: RTCVideoCodecInfo): Boolean; cdecl;
//@property(nonatomic, readonly) NSString *name;
function name: NSString; cdecl;
//@property(nonatomic, readonly) NSDictionary<NSString *, NSString *> *parameters;
function parameters: NSDictionary; cdecl;
end;
TRTCVideoCodecInfo = class(TOCGenericImport<RTCVideoCodecInfoClass, RTCVideoCodecInfo>) end;
PRTCVideoCodecInfo = Pointer;
//{*********************************************}
//RTCEncodedImageClass = interface(NSObjectClass)
//['{D03D5F46-4AEA-4638-9C0C-D1F150622A8F}']
//end;
//RTCEncodedImage = interface(NSObject)
//['{923A43FD-EFC0-4DD9-B200-3A4ACACA8E69}']
//procedure setBuffer(buffer: NSData); cdecl;
//function buffer: NSData; cdecl;
//procedure setEncodedWidth(encodedWidth: Int32); cdecl;
//function encodedWidth: Int32; cdecl;
//procedure setEncodedHeight(encodedHeight: Int32); cdecl;
//function encodedHeight: Int32; cdecl;
//procedure setTimeStamp(timeStamp: LongWord); cdecl;
//function timeStamp: LongWord; cdecl;
//procedure setCaptureTimeMs(captureTimeMs: Int64); cdecl;
//function captureTimeMs: Int64; cdecl;
//procedure setNtpTimeMs(ntpTimeMs: Int64); cdecl;
//function ntpTimeMs: Int64; cdecl;
//procedure setFlags(flags: Byte); cdecl;
//function flags: Byte; cdecl;
//procedure setEncodeStartMs(encodeStartMs: Int64); cdecl;
//function encodeStartMs: Int64; cdecl;
//procedure setEncodeFinishMs(encodeFinishMs: Int64); cdecl;
//function encodeFinishMs: Int64; cdecl;
//procedure setFrameType(frameType: RTCFrameType); cdecl;
//function frameType: RTCFrameType; cdecl;
//procedure setRotation(rotation: RTCVideoRotation); cdecl;
//function rotation: RTCVideoRotation; cdecl;
//procedure setCompleteFrame(completeFrame: Boolean); cdecl;
//function completeFrame: Boolean; cdecl;
//procedure setQp(qp: NSNumber); cdecl;
//function qp: NSNumber; cdecl;
//procedure setContentType(contentType: RTCVideoContentType); cdecl;
//function contentType: RTCVideoContentType; cdecl;
//end;
//TRTCEncodedImage = class(TOCGenericImport<RTCEncodedImageClass, RTCEncodedImage>) end;
//PRTCEncodedImage = Pointer;
//{*****************************************************}
//RTCVideoEncoderSettingsClass = interface(NSObjectClass)
//['{0CE09797-07F1-4609-A56B-2A0C412037CD}']
//end;
//RTCVideoEncoderSettings = interface(NSObject)
//['{2BA97AC8-2DAB-4E0F-86D4-8FDF1166F156}']
//procedure setName(name: NSString); cdecl;
//function name: NSString; cdecl;
//procedure setWidth(width: Word); cdecl;
//function width: Word; cdecl;
//procedure setHeight(height: Word); cdecl;
//function height: Word; cdecl;
//procedure setStartBitrate(startBitrate: Cardinal); cdecl;
//function startBitrate: Cardinal; cdecl;
//procedure setMaxBitrate(maxBitrate: Cardinal); cdecl;
//function maxBitrate: Cardinal; cdecl;
//procedure setMinBitrate(minBitrate: Cardinal); cdecl;
//function minBitrate: Cardinal; cdecl;
//procedure setTargetBitrate(targetBitrate: Cardinal); cdecl;
//function targetBitrate: Cardinal; cdecl;
//procedure setMaxFramerate(maxFramerate: LongWord); cdecl;
//function maxFramerate: LongWord; cdecl;
//procedure setQpMax(qpMax: Cardinal); cdecl;
//function qpMax: Cardinal; cdecl;
//procedure setMode(mode: RTCVideoCodecMode); cdecl;
//function mode: RTCVideoCodecMode; cdecl;
//end;
//TRTCVideoEncoderSettings = class(TOCGenericImport<RTCVideoEncoderSettingsClass, RTCVideoEncoderSettings>) end;
//PRTCVideoEncoderSettings = Pointer;
{****************************************************************************************}
//This decoder factory include support for all codecs bundled with WebRTC. If using custom
//codecs, create custom implementations of RTCVideoEncoderFactory and RTCVideoDecoderFactory.
//@interface RTCDefaultVideoDecoderFactory : NSObject <RTCVideoDecoderFactory>
RTCDefaultVideoDecoderFactoryClass = interface(NSObjectClass)
['{F72D68FF-8EC7-47AE-B260-37CF79B19418}']
end;
RTCDefaultVideoDecoderFactory = interface(NSObject)
['{6BD5BA9E-A505-460C-BBEF-2841DF55C7D3}']
end;
TRTCDefaultVideoDecoderFactory = class(TOCGenericImport<RTCDefaultVideoDecoderFactoryClass, RTCDefaultVideoDecoderFactory>) end;
PRTCDefaultVideoDecoderFactory = Pointer;
//{*******************************************************}
//RTCRtpFragmentationHeaderClass = interface(NSObjectClass)
//['{1DB1DFAD-ACBE-4F4C-95AE-D592774CB766}']
//end;
//RTCRtpFragmentationHeader = interface(NSObject)
//['{72DC1468-0712-4DED-8CB0-955DA0E21CD8}']
//procedure setFragmentationOffset(fragmentationOffset: NSArray); cdecl;
//function fragmentationOffset: NSArray; cdecl;
//procedure setFragmentationLength(fragmentationLength: NSArray); cdecl;
//function fragmentationLength: NSArray; cdecl;
//procedure setFragmentationTimeDiff(fragmentationTimeDiff: NSArray); cdecl;
//function fragmentationTimeDiff: NSArray; cdecl;
//procedure setFragmentationPlType(fragmentationPlType: NSArray); cdecl;
//function fragmentationPlType: NSArray; cdecl;
//end;
//TRTCRtpFragmentationHeader = class(TOCGenericImport<RTCRtpFragmentationHeaderClass, RTCRtpFragmentationHeader>) end;
//PRTCRtpFragmentationHeader = Pointer;
//{*********************************************************}
//RTCVideoEncoderQpThresholdsClass = interface(NSObjectClass)
//['{0B602B2D-CAD2-47BC-BDD6-90686D731BF1}']
//end;
//RTCVideoEncoderQpThresholds = interface(NSObject)
//['{A5687575-ABC5-44F9-9808-DA92EA96C774}']
//function initWithThresholdsLow(low: NSInteger; high: NSInteger): Pointer { instancetype }; cdecl;
//function low: NSInteger; cdecl;
//function high: NSInteger; cdecl;
//end;
//TRTCVideoEncoderQpThresholds = class(TOCGenericImport<RTCVideoEncoderQpThresholdsClass, RTCVideoEncoderQpThresholds>) end;
//PRTCVideoEncoderQpThresholds = Pointer;
{****************************************************************************************}
//This encoder factory include support for all codecs bundled with WebRTC. If using custom
//codecs, create custom implementations of RTCVideoEncoderFactory and RTCVideoDecoderFactory.
//@interface RTCDefaultVideoEncoderFactory : NSObject <RTCVideoEncoderFactory>
RTCDefaultVideoEncoderFactoryClass = interface(NSObjectClass)
['{06A55D95-5B90-4E2B-98F6-E03F35C746C3}']
//+ (NSArray<RTCVideoCodecInfo *> *)supportedCodecs;
{ class } function supportedCodecs: NSArray; cdecl;
end;
RTCDefaultVideoEncoderFactory = interface(NSObject)
['{1205BC8D-3182-42AD-BB6A-02E06E17A866}']
//@property(nonatomic, retain) RTCVideoCodecInfo *preferredCodec;
procedure setPreferredCodec(preferredCodec: RTCVideoCodecInfo); cdecl;
function preferredCodec: RTCVideoCodecInfo; cdecl;
end;
TRTCDefaultVideoEncoderFactory = class(TOCGenericImport<RTCDefaultVideoEncoderFactoryClass, RTCDefaultVideoEncoderFactory>) end;
PRTCDefaultVideoEncoderFactory = Pointer;
//{*******************************************}
//RTCDispatcherClass = interface(NSObjectClass)
//['{BE18E651-39AE-49CC-B161-0F83CE99E90E}']
//{ class } procedure dispatchAsyncOnType(dispatchType: RTCDispatcherQueueType; block: Pointer { dispatch_block_t } ); cdecl;
//{ class } function isOnQueueForType(dispatchType: RTCDispatcherQueueType): Boolean; cdecl;
//end;
//RTCDispatcher = interface(NSObject)
//['{53C8DE2D-B117-4265-92F4-5FE9BCE7FA76}']
//end;
//TRTCDispatcher = class(TOCGenericImport<RTCDispatcherClass, RTCDispatcher>) end;
//PRTCDispatcher = Pointer;
//{********************************************}
//RTCEAGLVideoViewClass = interface(UIViewClass)
//['{F498FC75-6552-49DD-8E8A-1F98B77DA8B7}']
//end;
//RTCEAGLVideoView = interface(UIView)
//['{CE927B4A-A238-4CCB-B371-A88236D87761}']
//procedure setDelegate(delegate: Pointer); cdecl;
//function delegate: Pointer; cdecl;
//function initWithFrame(frame: CGRect; shader: Pointer): Pointer { instancetype }; cdecl;
//function initWithCoder(aDecoder: NSCoder; shader: Pointer): Pointer { instancetype }; cdecl;
//end;
//TRTCEAGLVideoView = class(TOCGenericImport<RTCEAGLVideoViewClass, RTCEAGLVideoView>) end;
//PRTCEAGLVideoView = Pointer;
//{*******************************************}
//RTCFileLoggerClass = interface(NSObjectClass)
//['{8CFD272C-B1A1-4595-AE58-F2CCFA45DEA0}']
//end;
//RTCFileLogger = interface(NSObject)
//['{D5706349-63B1-4055-B178-25D937340C7E}']
//procedure setSeverity(severity: RTCFileLoggerSeverity); cdecl;
//function severity: RTCFileLoggerSeverity; cdecl;
//function rotationType: RTCFileLoggerRotationType; cdecl;
//procedure setShouldDisableBuffering(shouldDisableBuffering: Boolean); cdecl;
//function shouldDisableBuffering: Boolean; cdecl;
//function init: Pointer { instancetype }; cdecl;
//[MethodName('initWithDirPath:maxFileSize:')]
//function initWithDirPathMaxFileSize(dirPath: NSString; maxFileSize: NSUInteger): Pointer { instancetype }; cdecl;
//[MethodName('initWithDirPath:maxFileSize:rotationType:')]
//function initWithDirPathMaxFileSizeRotationType(dirPath: NSString; maxFileSize: NSUInteger; rotationType: RTCFileLoggerRotationType): Pointer { instancetype }; cdecl;
//procedure start; cdecl;
//procedure stop; cdecl;
//function logData: NSData; cdecl;
//end;
//TRTCFileLogger = class(TOCGenericImport<RTCFileLoggerClass, RTCFileLogger>) end;
//PRTCFileLogger = Pointer;
//{**********************************************************}
//RTCFileVideoCapturerClass = interface(RTCVideoCapturerClass)
//['{B039F9AD-EB1C-45C0-97DD-9F25828B6420}']
//end;
//RTCFileVideoCapturer = interface(RTCVideoCapturer)
//['{61A9BD01-16F2-4244-B1A0-0D7894DA5E95}']
//procedure startCapturingFromFileNamed(nameOfFile: NSString; onError: RTCFileVideoCapturerErrorBlock); cdecl;
//procedure stopCapture; cdecl;
//end;
//TRTCFileVideoCapturer = class(TOCGenericImport<RTCFileVideoCapturerClass, RTCFileVideoCapturer>) end;
//PRTCFileVideoCapturer = Pointer;
{*******************************************}
//@interface RTCH264ProfileLevelId : NSObject
RTCH264ProfileLevelIdClass = interface(NSObjectClass)
['{4967D0E3-E801-4551-9529-D81B051D4075}']
end;
RTCH264ProfileLevelId = interface(NSObject)
['{4961CCA6-548C-44A1-BC10-3D9884820149}']
//@property(nonatomic, readonly) RTCH264Profile profile;
function profile: RTCH264Profile; cdecl;
//@property(nonatomic, readonly) RTCH264Level level;
function level: RTCH264Level; cdecl;
//@property(nonatomic, readonly) NSString *hexString;
function hexString: NSString; cdecl;
//- (instancetype)initWithHexString:(NSString *)hexString;
function initWithHexString(hexString: NSString): Pointer { instancetype }; cdecl;
//- (instancetype)initWithProfile:(RTCH264Profile)profile level:(RTCH264Level)level;
function initWithProfile(profile: RTCH264Profile; level: RTCH264Level): Pointer { instancetype }; cdecl;
end;
TRTCH264ProfileLevelId = class(TOCGenericImport<RTCH264ProfileLevelIdClass, RTCH264ProfileLevelId>) end;
PRTCH264ProfileLevelId = Pointer;
{*************************************}
//@interface RTCIceCandidate : NSObject
RTCIceCandidateClass = interface(NSObjectClass)
['{A096C28C-D525-4E4C-8875-5235481CDAB9}']
end;
RTCIceCandidate = interface(NSObject)
['{029E5282-6864-4B38-B93A-9449CDF82EF7}']
//If present, the identifier of the "media stream identification" for the media
//component this candidate is associated with.
//@property(nonatomic, readonly, nullable) NSString *sdpMid;
function sdpMid: NSString; cdecl;
//The index (starting at zero) of the media description this candidate is
//associated with in the SDP.
//@property(nonatomic, readonly) int sdpMLineIndex;
function sdpMLineIndex: Integer; cdecl;
//The SDP string for this candidate.
//@property(nonatomic, readonly) NSString *sdp;
function sdp: NSString; cdecl;
//The URL of the ICE server which this candidate is gathered from.
//@property(nonatomic, readonly, nullable) NSString *serverUrl;
function serverUrl: NSString; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Initialize an RTCIceCandidate from SDP.
//- (instancetype)initWithSdp:(NSString *)sdp
// sdpMLineIndex:(int)sdpMLineIndex
// sdpMid:(nullable NSString *)sdpMid NS_DESIGNATED_INITIALIZER;
function initWithSdp(sdp: NSString; sdpMLineIndex: Integer; sdpMid: NSString): Pointer { instancetype }; cdecl;
end;
TRTCIceCandidate = class(TOCGenericImport<RTCIceCandidateClass, RTCIceCandidate>) end;
PRTCIceCandidate = Pointer;
//{**************************************************}
//RTCLegacyStatsReportClass = interface(NSObjectClass)
//['{6CDFB5E6-6BBC-410E-B34E-7AE4030A3BD7}']
//end;
//RTCLegacyStatsReport = interface(NSObject)
//['{173B5644-F310-4338-A0A3-13779F046F24}']
//function timeStamp: CFTimeInterval; cdecl;
//function &type: NSString; cdecl;
//function reportId: NSString; cdecl;
//function values: NSDictionary; cdecl;
//end;
//TRTCLegacyStatsReport = class(TOCGenericImport<RTCLegacyStatsReportClass, RTCLegacyStatsReport>) end;
//PRTCLegacyStatsReport = Pointer;
{*****************************************}
//@interface RTCMediaConstraints : NSObject
RTCMediaConstraintsClass = interface(NSObjectClass)
['{8235D2CB-7359-4F52-9F78-7BF285C1BE26}']
end;
RTCMediaConstraints = interface(NSObject)
['{99D7E0CC-E384-4C0E-9B41-B6E3411568D8}']
//- (instancetype)init NS_UNAVAILABLE;
//Initialize with mandatory and/or optional constraints.
//- (instancetype)
// initWithMandatoryConstraints:(nullable NSDictionary<NSString *, NSString *> *)mandatory
// optionalConstraints:(nullable NSDictionary<NSString *, NSString *> *)optional
// NS_DESIGNATED_INITIALIZER;
function initWithMandatoryConstraints(mandatory: NSDictionary; optionalConstraints: NSDictionary): Pointer { instancetype }; cdecl;
end;
TRTCMediaConstraints = class(TOCGenericImport<RTCMediaConstraintsClass, RTCMediaConstraints>) end;
PRTCMediaConstraints = Pointer;
{**********************************************}
//@interface RTCPeerConnectionFactory : NSObject
RTCPeerConnectionFactoryClass = interface(NSObjectClass)
['{60AF5637-A719-4C21-A04A-FE89DA61E82B}']
end;
RTCPeerConnectionFactory = interface(NSObject)
['{AC489494-5259-4C88-81A9-6AA20A16E36A}']
//Initialize object with default H264 video encoder/decoder factories
//- (instancetype)init;
function init: Pointer { instancetype }; cdecl;
//Initialize object with injectable video encoder/decoder factories
//- (instancetype)initWithEncoderFactory:(nullable id<RTCVideoEncoderFactory>)encoderFactory
// decoderFactory:(nullable id<RTCVideoDecoderFactory>)decoderFactory;
function initWithEncoderFactory(encoderFactory: Pointer; decoderFactory: Pointer): Pointer { instancetype }; cdecl;
//Initialize an RTCAudioSource with constraints.
//- (RTCAudioSource *)audioSourceWithConstraints:(nullable RTCMediaConstraints *)constraints;
function audioSourceWithConstraints(constraints: RTCMediaConstraints): RTCAudioSource; cdecl;
//Initialize an RTCAudioTrack with an id. Convenience ctor to use an audio source with no constraints.
//- (RTCAudioTrack *)audioTrackWithTrackId:(NSString *)trackId;
//function audioTrackWithTrackId(trackId: NSString): RTCAudioTrack; cdecl;
//Initialize an RTCAudioTrack with a source and an id.
//- (RTCAudioTrack *)audioTrackWithSource:(RTCAudioSource *)source trackId:(NSString *)trackId;
function audioTrackWithSource(source: RTCAudioSource; trackId: NSString): RTCAudioTrack; cdecl;
//Initialize a generic RTCVideoSource. The RTCVideoSource should be passed to a RTCVideoCapturer
//implementation, e.g. RTCCameraVideoCapturer, in order to produce frames.
//- (RTCVideoSource *)videoSource;
function videoSource: RTCVideoSource; cdecl;
//Initialize an RTCVideoTrack with a source and an id.
//- (RTCVideoTrack *)videoTrackWithSource:(RTCVideoSource *)source trackId:(NSString *)trackId;
function videoTrackWithSource(source: RTCVideoSource; trackId: NSString): RTCVideoTrack; cdecl;
//Initialize an RTCMediaStream with an id.
//- (RTCMediaStream *)mediaStreamWithStreamId:(NSString *)streamId;
//function mediaStreamWithStreamId(streamId: NSString): RTCMediaStream; cdecl;
//Initialize an RTCPeerConnection with a configuration, constraints, and delegate.
//- (RTCPeerConnection *)peerConnectionWithConfiguration:(RTCConfiguration *)configuration
// constraints:(RTCMediaConstraints *)constraints
// delegate:(nullable id<RTCPeerConnectionDelegate>)delegate;
function peerConnectionWithConfiguration(configuration: RTCConfiguration; constraints: RTCMediaConstraints; delegate: Pointer): RTCPeerConnection; cdecl;
//Set the options to be used for subsequently created RTCPeerConnections
//- (void)setOptions:(nonnull RTCPeerConnectionFactoryOptions *)options;
//procedure setOptions(options: RTCPeerConnectionFactoryOptions); cdecl;
//Start an AecDump recording. This API call will likely change in the future.
//- (BOOL)startAecDumpWithFilePath:(NSString *)filePath maxSizeInBytes:(int64_t)maxSizeInBytes;
//function startAecDumpWithFilePath(filePath: NSString; maxSizeInBytes: Int64): Boolean; cdecl;
//Stop an active AecDump recording
//- (void)stopAecDump;
//procedure stopAecDump; cdecl;
end;
TRTCPeerConnectionFactory = class(TOCGenericImport<RTCPeerConnectionFactoryClass, RTCPeerConnectionFactory>) end;
PRTCPeerConnectionFactory = Pointer;
{**********************************************}
//@interface RTCVideoTrack : RTCMediaStreamTrack
RTCVideoTrackClass = interface(RTCMediaStreamTrackClass)
['{42239C62-26A1-46EA-87EC-B897743D22A4}']
end;
RTCVideoTrack = interface(RTCMediaStreamTrack)
['{E87017EA-5159-4770-BC33-BFBE9BD5AE86}']
//The video source for this video track.
//@property(nonatomic, readonly) RTCVideoSource *source;
function source: RTCVideoSource; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Register a renderer that will render all frames received on this track.
//- (void)addRenderer:(id<RTCVideoRenderer>)renderer;
procedure addRenderer(renderer: Pointer); cdecl;
//Deregister a renderer.
//- (void)removeRenderer:(id<RTCVideoRenderer>)renderer;
procedure removeRenderer(renderer: Pointer); cdecl;
end;
TRTCVideoTrack = class(TOCGenericImport<RTCVideoTrackClass, RTCVideoTrack>) end;
PRTCVideoTrack = Pointer;
{************************************}
//@interface RTCMediaStream : NSObject
RTCMediaStreamClass = interface(NSObjectClass)
['{DD661051-CD33-460C-A285-BDE3C672670D}']
end;
RTCMediaStream = interface(NSObject)
['{89DE6B02-4016-4CF2-9164-59C006DF9B4A}']
//The audio tracks in this stream.
//@property(nonatomic, strong, readonly) NSArray<RTCAudioTrack *> *audioTracks;
//function audioTracks: NSArray; cdecl;
//The video tracks in this stream.
//@property(nonatomic, strong, readonly) NSArray<RTCVideoTrack *> *videoTracks;
//function videoTracks: NSArray; cdecl;
//An identifier for this media stream.
//@property(nonatomic, readonly) NSString *streamId;
function streamId: NSString; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Adds the given audio track to this media stream.
//- (void)addAudioTrack:(RTCAudioTrack *)audioTrack;
//procedure addAudioTrack(audioTrack: RTCAudioTrack); cdecl;
//Adds the given video track to this media stream.
//- (void)addVideoTrack:(RTCVideoTrack *)videoTrack;
//procedure addVideoTrack(videoTrack: RTCVideoTrack); cdecl;
//Removes the given audio track to this media stream.
//- (void)removeAudioTrack:(RTCAudioTrack *)audioTrack;
//procedure removeAudioTrack(audioTrack: RTCAudioTrack); cdecl;
//Removes the given video track to this media stream.
//- (void)removeVideoTrack:(RTCVideoTrack *)videoTrack;
//procedure removeVideoTrack(videoTrack: RTCVideoTrack); cdecl;
end;
TRTCMediaStream = class(TOCGenericImport<RTCMediaStreamClass, RTCMediaStream>) end;
PRTCMediaStream = Pointer;
//{**************************************************}
//RTCMetricsSampleInfoClass = interface(NSObjectClass)
//['{3299719D-AFF9-4EC0-B86F-9DB3CB1334C1}']
//end;
//RTCMetricsSampleInfo = interface(NSObject)
//['{A909A86F-F4C3-42DF-8B46-E7479A6A674D}']
//function name: NSString; cdecl;
//function min: Integer; cdecl;
//function max: Integer; cdecl;
//function bucketCount: Integer; cdecl;
//function samples: NSDictionary; cdecl;
//end;
//TRTCMetricsSampleInfo = class(TOCGenericImport<RTCMetricsSampleInfoClass, RTCMetricsSampleInfo>) end;
//PRTCMetricsSampleInfo = Pointer;
//{*******************************************}
//RTCMTLVideoViewClass = interface(UIViewClass)
//['{BA32C167-DB82-4A95-87AD-14D09A9D54AC}']
//end;
//RTCMTLVideoView = interface(UIView)
//['{5FA2C7EE-0A9E-470F-B434-9C8530CD29C0}']
//procedure setDelegate(delegate: Pointer); cdecl;
//function delegate: Pointer; cdecl;
//procedure setVideoContentMode(videoContentMode: UIViewContentMode); cdecl;
//function videoContentMode: UIViewContentMode; cdecl;
//procedure setEnabled(enabled: Boolean); cdecl;
//function isEnabled: Boolean; cdecl;
//procedure setRotationOverride(rotationOverride: NSValue); cdecl;
//function rotationOverride: NSValue; cdecl;
//end;
//TRTCMTLVideoView = class(TOCGenericImport<RTCMTLVideoViewClass, RTCMTLVideoView>) end;
//PRTCMTLVideoView = Pointer;
{*******************************************}
RTCI420BufferClass = interface(NSObjectClass)
['{CD148B90-CE83-4B88-BE05-4248C65A57B3}']
end;
RTCI420Buffer = interface(NSObject)
['{EBB60134-F56C-441D-8407-4C628BD81CE4}']
//@property(nonatomic, readonly) int width;
function width: Integer; cdecl;
//@property(nonatomic, readonly) int height;
function height: Integer; cdecl;
//- (id<RTCI420Buffer>)toI420;
//function toI420: Pointer; cdecl;
//@property(nonatomic, readonly) int chromaWidth;
function chromaWidth: Integer; cdecl;
//@property(nonatomic, readonly) int chromaHeight;
function chromaHeight: Integer; cdecl;
//@property(nonatomic, readonly) const uint8_t *dataY;
function dataY: PByte; cdecl;
//@property(nonatomic, readonly) const uint8_t *dataU;
function dataU: PByte; cdecl;
//@property(nonatomic, readonly) const uint8_t *dataV;
function dataV: PByte; cdecl;
//@property(nonatomic, readonly) int strideY;
function strideY: Integer; cdecl;
//@property(nonatomic, readonly) int strideU;
function strideU: Integer; cdecl;
//@property(nonatomic, readonly) int strideV;
function strideV: Integer; cdecl;
//- (instancetype)initWithWidth:(int)width
// height:(int)height
// dataY:(const uint8_t *)dataY
// dataU:(const uint8_t *)dataU
// dataV:(const uint8_t *)dataV;
//[MethodName('initWithWidth:height:dataY:dataU:dataV:')]
//function initWithWidthHeightDataYDataUDataV(width: Integer; height: Integer; dataY: PByte; dataU: PByte; dataV: PByte): Pointer { instancetype }; cdecl;
//- (instancetype)initWithWidth:(int)width height:(int)height;
//[MethodName('initWithWidth:height:')]
//function initWithWidthHeight(width: Integer; height: Integer): Pointer { instancetype }; cdecl;
//- (instancetype)initWithWidth:(int)width
// height:(int)height
// strideY:(int)strideY
// strideU:(int)strideU
// strideV:(int)strideV;
//[MethodName('initWithWidth:height:strideY:strideU:strideV:')]
//function initWithWidthHeightStrideYStrideUStrideV(width: Integer; height: Integer; strideY: Integer; strideU: Integer; strideV: Integer): Pointer { instancetype }; cdecl;
end;
TRTCI420Buffer = class(TOCGenericImport<RTCI420BufferClass, RTCI420Buffer>) end;
PRTCI420Buffer = Pointer;
//{*******************************************}
//RTCMutableI420Buffer = interface(IObjectiveC)
//['{EEB18C16-8EBF-462A-8FA0-EDEC2F03E588}']
//end;
{***********************************}
//@protocol RTCRtpReceiver <NSObject>
//@interface RTCRtpReceiver : NSObject <RTCRtpReceiver>
RTCRtpReceiverClass = interface(NSObjectClass)
['{1AAB73CC-2B5B-41B4-8771-CBFCF003223F}']
end;
RTCRtpReceiver = interface(NSObject)
['{C24EB32B-1630-457B-A0F8-F495370ADF57}']
//A unique identifier for this receiver.
//@property(nonatomic, readonly) NSString *receiverId;
//function receiverId: NSString; cdecl;
//The currently active RTCRtpParameters, as defined in
//https://www.w3.org/TR/webrtc/#idl-def-RTCRtpParameters.
//The WebRTC specification only defines RTCRtpParameters in terms of senders,
//but this API also applies them to receivers, similar to ORTC:
//http://ortc.org/wp-content/uploads/2016/03/ortc.html#rtcrtpparameters*.
//@property(nonatomic, readonly) RTCRtpParameters *parameters;
//function parameters: RTCRtpParameters; cdecl;
//The RTCMediaStreamTrack associated with the receiver.
//Note: reading this property returns a new instance of
//RTCMediaStreamTrack. Use isEqual: instead of == to compare
//RTCMediaStreamTrack instances.
//@property(nonatomic, readonly, nullable) RTCMediaStreamTrack *track;
function track: RTCMediaStreamTrack; cdecl;
//The delegate for this RtpReceiver.
//@property(nonatomic, weak) id<RTCRtpReceiverDelegate> delegate;
//procedure setDelegate(delegate: Pointer); cdecl;
//function delegate: Pointer; cdecl;
end;
TRTCRtpReceiver = class(TOCGenericImport<RTCRtpReceiverClass, RTCRtpReceiver>) end;
PRTCRtpReceiver = Pointer;
{*********************************}
//@protocol RTCRtpSender <NSObject>
RTCRtpSenderClass = interface(NSObjectClass)
['{0AE0ED18-0EB7-485A-B6AF-0730F5608655}']
end;
RTCRtpSender = interface(NSObject)
['{F51462D8-AC7F-45DB-9B4C-6D8237AD14AB}']
//A unique identifier for this sender.
//@property(nonatomic, readonly) NSString *senderId;
//function senderId: NSString; cdecl;
//The currently active RTCRtpParameters, as defined in
//https://www.w3.org/TR/webrtc/#idl-def-RTCRtpParameters.
//@property(nonatomic, copy) RTCRtpParameters *parameters;
procedure setParameters(parameters: RTCRtpParameters); cdecl;
function parameters: RTCRtpParameters; cdecl;
//The RTCMediaStreamTrack associated with the sender.
//Note: reading this property returns a new instance of
//RTCMediaStreamTrack. Use isEqual: instead of == to compare
//RTCMediaStreamTrack instances.
//@property(nonatomic, copy, nullable) RTCMediaStreamTrack *track;
procedure setTrack(track: RTCMediaStreamTrack); cdecl;
function track: RTCMediaStreamTrack; cdecl;
//The RTCDtmfSender accociated with the RTP sender.
//@property(nonatomic, readonly, nullable) id<RTCDtmfSender> dtmfSender;
//function dtmfSender: Pointer; cdecl;
end;
TRTCRtpSender = class(TOCGenericImport<RTCRtpSenderClass, RTCRtpSender>) end;
PRTCRtpSender = Pointer;
{*************************}
//The RTCRtpTransceiver maps to the RTCRtpTransceiver defined by the WebRTC
//specification. A transceiver represents a combination of an RTCRtpSender
//and an RTCRtpReceiver that share a common mid. As defined in JSEP, an
//RTCRtpTransceiver is said to be associated with a media description if its
//mid property is non-nil; otherwise, it is said to be disassociated.
//JSEP: https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24
//Note that RTCRtpTransceivers are only supported when using
//RTCPeerConnection with Unified Plan SDP.
//WebRTC specification for RTCRtpTransceiver, the JavaScript analog:
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver
//@protocol RTCRtpTransceiver <NSObject>
//@interface RTCRtpTransceiver : NSObject <RTCRtpTransceiver>
RTCRtpTransceiverClass = interface(NSObjectClass)
['{86DACB46-DC39-493E-9B6F-CC1A998D351A}']
end;
RTCRtpTransceiver = interface(NSObject)
['{3322A9ED-3447-4596-BEE6-B7F3E9A71B4A}']
//Media type of the transceiver. The sender and receiver will also have this
//type.
//@property(nonatomic, readonly) RTCRtpMediaType mediaType;
function mediaType: RTCRtpMediaType; cdecl;
//The mid attribute is the mid negotiated and present in the local and
//remote descriptions. Before negotiation is complete, the mid value may be
//nil. After rollbacks, the value may change from a non-nil value to nil.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-mid
//@property(nonatomic, readonly) NSString *mid;
//function mid: NSString; cdecl;
//The sender attribute exposes the RTCRtpSender corresponding to the RTP
//media that may be sent with the transceiver's mid. The sender is always
//present, regardless of the direction of media.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-sender
//@property(nonatomic, readonly) RTCRtpSender *sender;
//function sender: RTCRtpSender; cdecl;
//The receiver attribute exposes the RTCRtpReceiver corresponding to the RTP
//media that may be received with the transceiver's mid. The receiver is
//always present, regardless of the direction of media.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-receiver
//@property(nonatomic, readonly) RTCRtpReceiver *receiver;
function receiver: RTCRtpReceiver; cdecl;
//The isStopped attribute indicates that the sender of this transceiver will
//no longer send, and that the receiver will no longer receive. It is true if
//either stop has been called or if setting the local or remote description
//has caused the RTCRtpTransceiver to be stopped.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-stopped
//@property(nonatomic, readonly) BOOL isStopped;
//function isStopped: Boolean; cdecl;
//The direction attribute indicates the preferred direction of this
//transceiver, which will be used in calls to createOffer and createAnswer.
//An update of directionality does not take effect immediately. Instead,
//future calls to createOffer and createAnswer mark the corresponding media
//descriptions as sendrecv, sendonly, recvonly, or inactive.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-direction
//@property(nonatomic) RTCRtpTransceiverDirection direction;
//procedure setDirection(direction: RTCRtpTransceiverDirection); cdecl;
//function direction: RTCRtpTransceiverDirection; cdecl;
//The currentDirection attribute indicates the current direction negotiated
//for this transceiver. If this transceiver has never been represented in an
//offer/answer exchange, or if the transceiver is stopped, the value is not
//present and this method returns NO.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-currentdirection
//- (BOOL)currentDirection:(RTCRtpTransceiverDirection *)currentDirectionOut;
//function currentDirection(currentDirectionOut: PRTCRtpTransceiverDirection): Boolean; cdecl;
//The stop method irreversibly stops the RTCRtpTransceiver. The sender of
//this transceiver will no longer send, the receiver will no longer receive.
//https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver-stop
//- (void)stop;
//procedure stop; cdecl;
end;
TRTCRtpTransceiver = class(TOCGenericImport<RTCRtpTransceiverClass, RTCRtpTransceiver>) end;
PRTCRtpTransceiver = Pointer;
//{***************************************************}
//RTCRtpTransceiverInitClass = interface(NSObjectClass)
//['{2A8922EB-41E8-41E6-966F-26C914045A32}']
//end;
//RTCRtpTransceiverInit = interface(NSObject)
//['{49DD4612-4E85-40E0-8FF4-A53B35217CE9}']
//procedure setDirection(direction: RTCRtpTransceiverDirection); cdecl;
//function direction: RTCRtpTransceiverDirection; cdecl;
//procedure setStreamIds(streamIds: NSArray); cdecl;
//function streamIds: NSArray; cdecl;
//procedure setSendEncodings(sendEncodings: NSArray); cdecl;
//function sendEncodings: NSArray; cdecl;
//end;
//TRTCRtpTransceiverInit = class(TOCGenericImport<RTCRtpTransceiverInitClass, RTCRtpTransceiverInit>) end;
//PRTCRtpTransceiverInit = Pointer;
{***************************************************}
RTCSessionDescriptionClass = interface(NSObjectClass)
['{A5B3B5A3-5F03-4ED0-B9CC-3A8B0E894050}']
//+ (NSString *)stringForType:(RTCSdpType)type;
{ class } function stringForType(&type: RTCSdpType): NSString; cdecl;
//+ (RTCSdpType)typeForString:(NSString *)string;
{ class } function typeForString(&string: NSString): RTCSdpType; cdecl;
end;
RTCSessionDescription = interface(NSObject)
['{E3C8A270-2141-4F67-BDC5-36F42368E506}']
//The type of session description.
//@property(nonatomic, readonly) RTCSdpType type;
function &type: RTCSdpType; cdecl;
//The SDP string representation of this session description.
//@property(nonatomic, readonly) NSString *sdp;
function sdp: NSString; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Initialize a session description with a type and SDP string.
//- (instancetype)initWithType:(RTCSdpType)type sdp:(NSString *)sdp NS_DESIGNATED_INITIALIZER;
function initWithType(&type: RTCSdpType; sdp: NSString): Pointer { instancetype }; cdecl;
end;
TRTCSessionDescription = class(TOCGenericImport<RTCSessionDescriptionClass, RTCSessionDescription>) end;
PRTCSessionDescription = Pointer;
{***********************************************}
//@interface RTCPeerConnection : NSObject
RTCPeerConnectionClass = interface(NSObjectClass)
['{72035A56-D3E9-42F0-BA42-986BC2E10196}']
end;
RTCPeerConnection = interface(NSObject)
['{F5473616-4DB0-4E75-B869-555761CA6794}']
//The object that will be notifed about events such as state changes and
//streams being added or removed.
//@property(nonatomic, weak, nullable) id<RTCPeerConnectionDelegate> delegate;
procedure setDelegate(delegate: Pointer); cdecl;
function delegate: Pointer; cdecl;
//This property is not available with RTCSdpSemanticsUnifiedPlan. Please use
//|senders| instead.
//@property(nonatomic, readonly) NSArray<RTCMediaStream *> *localStreams;
//function localStreams: NSArray; cdecl;
//@property(nonatomic, readonly, nullable) RTCSessionDescription *localDescription;
function localDescription: RTCSessionDescription; cdecl;
//@property(nonatomic, readonly, nullable) RTCSessionDescription *remoteDescription;
function remoteDescription: RTCSessionDescription; cdecl;
//@property(nonatomic, readonly) RTCSignalingState signalingState;
function signalingState: RTCSignalingState; cdecl;
//@property(nonatomic, readonly) RTCIceConnectionState iceConnectionState;
function iceConnectionState: RTCIceConnectionState; cdecl;
//@property(nonatomic, readonly) RTCIceGatheringState iceGatheringState;
function iceGatheringState: RTCIceGatheringState; cdecl;
//@property(nonatomic, readonly, copy) RTCConfiguration *configuration;
//function configuration: RTCConfiguration; cdecl;
//Gets all RTCRtpSenders associated with this peer connection.
//Note: reading this property returns different instances of RTCRtpSender.
//Use isEqual: instead of == to compare RTCRtpSender instances.
//@property(nonatomic, readonly) NSArray<RTCRtpSender *> *senders;
function senders: NSArray; cdecl;
//Gets all RTCRtpReceivers associated with this peer connection.
//Note: reading this property returns different instances of RTCRtpReceiver.
//Use isEqual: instead of == to compare RTCRtpReceiver instances.
//@property(nonatomic, readonly) NSArray<RTCRtpReceiver *> *receivers;
//function receivers: NSArray; cdecl;
//Gets all RTCRtpTransceivers associated with this peer connection.
//Note: reading this property returns different instances of
//RTCRtpTransceiver. Use isEqual: instead of == to compare RTCRtpTransceiver
//instances.
//This is only available with RTCSdpSemanticsUnifiedPlan specified.
//@property(nonatomic, readonly) NSArray<RTCRtpTransceiver *> *transceivers;
function transceivers: NSArray; cdecl;
//- (instancetype)init NS_UNAVAILABLE;
//Sets the PeerConnection's global configuration to |configuration|.
//Any changes to STUN/TURN servers or ICE candidate policy will affect the
//next gathering phase, and cause the next call to createOffer to generate
//new ICE credentials. Note that the BUNDLE and RTCP-multiplexing policies
//cannot be changed with this method.
//- (BOOL)setConfiguration:(RTCConfiguration *)configuration;
//function setConfiguration(configuration: RTCConfiguration): Boolean; cdecl;
//Terminate all media and close the transport.
//- (void)close;
procedure close; cdecl;
//Provide a remote candidate to the ICE Agent.
//- (void)addIceCandidate:(RTCIceCandidate *)candidate;
procedure addIceCandidate(candidate: RTCIceCandidate); cdecl;
//Remove a group of remote candidates from the ICE Agent.
//- (void)removeIceCandidates:(NSArray<RTCIceCandidate *> *)candidates;
procedure removeIceCandidates(candidates: NSArray); cdecl;
//Add a new media stream to be sent on this peer connection.
//This method is not supported with RTCSdpSemanticsUnifiedPlan. Please use
//addTrack instead.
//- (void)addStream:(RTCMediaStream *)stream;
//procedure addStream(stream: RTCMediaStream); cdecl;
//Remove the given media stream from this peer connection.
//This method is not supported with RTCSdpSemanticsUnifiedPlan. Please use
//removeTrack instead.
//- (void)removeStream:(RTCMediaStream *)stream;
//procedure removeStream(stream: RTCMediaStream); cdecl;
//Add a new media stream track to be sent on this peer connection, and return
//the newly created RTCRtpSender. The RTCRtpSender will be associated with
//the streams specified in the |streamIds| list.
//
//Errors: If an error occurs, returns nil. An error can occur if:
//- A sender already exists for the track.
//- The peer connection is closed.
//- (RTCRtpSender *)addTrack:(RTCMediaStreamTrack *)track streamIds:(NSArray<NSString *> *)streamIds;
function addTrack(track: RTCMediaStreamTrack; streamIds: NSArray): RTCRtpSender; cdecl;
//With PlanB semantics, removes an RTCRtpSender from this peer connection.
//
//With UnifiedPlan semantics, sets sender's track to null and removes the
//send component from the associated RTCRtpTransceiver's direction.
//
//Returns YES on success.
//- (BOOL)removeTrack:(RTCRtpSender *)sender;
function removeTrack(sender: RTCRtpSender): Boolean; cdecl;
//addTransceiver creates a new RTCRtpTransceiver and adds it to the set of
//transceivers. Adding a transceiver will cause future calls to CreateOffer
//to add a media description for the corresponding transceiver.
//
//The initial value of |mid| in the returned transceiver is nil. Setting a
//new session description may change it to a non-nil value.
//
//https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-addtransceiver
//
//Optionally, an RtpTransceiverInit structure can be specified to configure
//the transceiver from construction. If not specified, the transceiver will
//default to having a direction of kSendRecv and not be part of any streams.
//
//These methods are only available when Unified Plan is enabled (see
//RTCConfiguration).
//
//Adds a transceiver with a sender set to transmit the given track. The kind
//of the transceiver (and sender/receiver) will be derived from the kind of
//the track.
//- (RTCRtpTransceiver *)addTransceiverWithTrack:(RTCMediaStreamTrack *)track;
//[MethodName('addTransceiverWithTrack:')]
//function addTransceiverWithTrack(track: RTCMediaStreamTrack): RTCRtpTransceiver; cdecl;
//- (RTCRtpTransceiver *)addTransceiverWithTrack:(RTCMediaStreamTrack *)track
// init:(RTCRtpTransceiverInit *)init;
//[MethodName('addTransceiverWithTrack:init:')]
//function addTransceiverWithTrackInit(track: RTCMediaStreamTrack; init: RTCRtpTransceiverInit): RTCRtpTransceiver; cdecl;
//Adds a transceiver with the given kind. Can either be RTCRtpMediaTypeAudio
//or RTCRtpMediaTypeVideo.
//- (RTCRtpTransceiver *)addTransceiverOfType:(RTCRtpMediaType)mediaType;
//[MethodName('addTransceiverOfType:')]
//function addTransceiverOfType(mediaType: RTCRtpMediaType): RTCRtpTransceiver; cdecl;
//- (RTCRtpTransceiver *)addTransceiverOfType:(RTCRtpMediaType)mediaType
// init:(RTCRtpTransceiverInit *)init;
//[MethodName('addTransceiverOfType:init:')]
//function addTransceiverOfTypeInit(mediaType: RTCRtpMediaType; init: RTCRtpTransceiverInit): RTCRtpTransceiver; cdecl;
//Generate an SDP offer.
//- (void)offerForConstraints:(RTCMediaConstraints *)constraints
// completionHandler:(nullable void (^)(RTCSessionDescription *_Nullable sdp,
// NSError *_Nullable error))completionHandler;
procedure offerForConstraints(constraints: RTCMediaConstraints; completionHandler: TWebRTCPeerConnectionOfferForConstraintsCompletionHandler); cdecl;
//Generate an SDP answer.
//- (void)answerForConstraints:(RTCMediaConstraints *)constraints
// completionHandler:(nullable void (^)(RTCSessionDescription *_Nullable sdp,
// NSError *_Nullable error))completionHandler;
procedure answerForConstraints(constraints: RTCMediaConstraints; completionHandler: TWebRTCPeerConnectionAnswerForConstraintsCompletionHandler); cdecl;
//Apply the supplied RTCSessionDescription as the local description.
//- (void)setLocalDescription:(RTCSessionDescription *)sdp
// completionHandler:(nullable void (^)(NSError *_Nullable error))completionHandler;
procedure setLocalDescription(sdp: RTCSessionDescription; completionHandler: TWebRTCPeerConnectionSetLocalDescriptionCompletionHandler); cdecl;
//Apply the supplied RTCSessionDescription as the remote description.
//- (void)setRemoteDescription:(RTCSessionDescription *)sdp
// completionHandler:(nullable void (^)(NSError *_Nullable error))completionHandler;
procedure setRemoteDescription(sdp: RTCSessionDescription; completionHandler: TWebRTCPeerConnectionSetRemoteDescriptionCompletionHandler); cdecl;
//Limits the bandwidth allocated for all RTP streams sent by this
//PeerConnection. Nil parameters will be unchanged. Setting
//|currentBitrateBps| will force the available bitrate estimate to the given
//value. Returns YES if the parameters were successfully updated.
//- (BOOL)setBweMinBitrateBps:(nullable NSNumber *)minBitrateBps
// currentBitrateBps:(nullable NSNumber *)currentBitrateBps
// maxBitrateBps:(nullable NSNumber *)maxBitrateBps;
//function setBweMinBitrateBps(minBitrateBps: NSNumber; currentBitrateBps: NSNumber; maxBitrateBps: NSNumber): Boolean; cdecl;
//Start or stop recording an Rtc EventLog.
//- (BOOL)startRtcEventLogWithFilePath:(NSString *)filePath maxSizeInBytes:(int64_t)maxSizeInBytes;
function startRtcEventLogWithFilePath(filePath: NSString; maxSizeInBytes: Int64): Boolean; cdecl;
//- (void)stopRtcEventLog;
procedure stopRtcEventLog; cdecl;
//Create an RTCRtpSender with the specified kind and media stream ID.
//See RTCMediaStreamTrack.h for available kinds.
//This method is not supported with RTCSdpSemanticsUnifiedPlan. Please use
//addTransceiver instead.
//- (RTCRtpSender *)senderWithKind:(NSString *)kind streamId:(NSString *)streamId;
//function senderWithKind(kind: NSString; streamId: NSString): RTCRtpSender; cdecl;
//Create a new data channel with the given label and configuration.
//- (nullable RTCDataChannel *)dataChannelForLabel:(NSString *)label
// configuration:(RTCDataChannelConfiguration *)configuration;
//function dataChannelForLabel(&label: NSString; configuration: RTCDataChannelConfiguration): RTCDataChannel; cdecl;
//Gather stats for the given RTCMediaStreamTrack. If |mediaStreamTrack| is nil
//statistics are gathered for all tracks.
//- (void)statsForTrack:(nullable RTCMediaStreamTrack *)mediaStreamTrack
// statsOutputLevel:(RTCStatsOutputLevel)statsOutputLevel
// completionHandler:(nullable void (^)(NSArray<RTCLegacyStatsReport *> *stats))completionHandler;
//procedure statsForTrack(mediaStreamTrack: RTCMediaStreamTrack; statsOutputLevel: RTCStatsOutputLevel; completionHandler: TWebRTCCompletionHandler3); cdecl;
end;
TRTCPeerConnection = class(TOCGenericImport<RTCPeerConnectionClass, RTCPeerConnection>) end;
PRTCPeerConnection = Pointer;
{*********************************************************************}
//@interface RTCVideoSource : RTCMediaSource <RTCVideoCapturerDelegate>
RTCVideoSourceClass = interface(RTCMediaSourceClass)
['{81E090DA-C21F-4034-A60C-311FF5E99DE2}']
end;
RTCVideoSource = interface(RTCMediaSource)
['{889191B4-4AB0-4AF3-B527-2ACB2759FFE3}']
//- (instancetype)init NS_UNAVAILABLE;
//Calling this function will cause frames to be scaled down to the
//requested resolution. Also, frames will be cropped to match the
//requested aspect ratio, and frames will be dropped to match the
//requested fps. The requested aspect ratio is orientation agnostic and
//will be adjusted to maintain the input orientation, so it doesn't
//matter if e.g. 1280x720 or 720x1280 is requested.
//- (void)adaptOutputFormatToWidth:(int)width height:(int)height fps:(int)fps;
procedure adaptOutputFormatToWidth(width: Integer; height: Integer; fps: Integer); cdecl;
end;
TRTCVideoSource = class(TOCGenericImport<RTCVideoSourceClass, RTCVideoSource>) end;
PRTCVideoSource = Pointer;
//{*************************************************************}
//RTCPeerConnectionFactoryOptionsClass = interface(NSObjectClass)
//['{8E5529AB-311A-4C3C-A854-2C0EA00230FD}']
//end;
//RTCPeerConnectionFactoryOptions = interface(NSObject)
//['{C67B18A4-5472-42D5-8C92-CF89C3AC3566}']
//procedure setDisableEncryption(disableEncryption: Boolean); cdecl;
//function disableEncryption: Boolean; cdecl;
//procedure setDisableNetworkMonitor(disableNetworkMonitor: Boolean); cdecl;
//function disableNetworkMonitor: Boolean; cdecl;
//procedure setIgnoreLoopbackNetworkAdapter(ignoreLoopbackNetworkAdapter: Boolean); cdecl;
//function ignoreLoopbackNetworkAdapter: Boolean; cdecl;
//procedure setIgnoreVPNNetworkAdapter(ignoreVPNNetworkAdapter: Boolean); cdecl;
//function ignoreVPNNetworkAdapter: Boolean; cdecl;
//procedure setIgnoreCellularNetworkAdapter(ignoreCellularNetworkAdapter: Boolean); cdecl;
//function ignoreCellularNetworkAdapter: Boolean; cdecl;
//procedure setIgnoreWiFiNetworkAdapter(ignoreWiFiNetworkAdapter: Boolean); cdecl;
//function ignoreWiFiNetworkAdapter: Boolean; cdecl;
//procedure setIgnoreEthernetNetworkAdapter(ignoreEthernetNetworkAdapter: Boolean); cdecl;
//function ignoreEthernetNetworkAdapter: Boolean; cdecl;
//procedure setEnableAes128Sha1_32CryptoCipher(enableAes128Sha1_32CryptoCipher: Boolean); cdecl;
//function enableAes128Sha1_32CryptoCipher: Boolean; cdecl;
//procedure setEnableGcmCryptoSuites(enableGcmCryptoSuites: Boolean); cdecl;
//function enableGcmCryptoSuites: Boolean; cdecl;
//procedure setRequireFrameEncryption(requireFrameEncryption: Boolean); cdecl;
//function requireFrameEncryption: Boolean; cdecl;
//function init: Pointer { instancetype }; cdecl;
//end;
//TRTCPeerConnectionFactoryOptions = class(TOCGenericImport<RTCPeerConnectionFactoryOptionsClass, RTCPeerConnectionFactoryOptions>) end;
//PRTCPeerConnectionFactoryOptions = Pointer;
//{***********************************************}
//RTCRtcpParametersClass = interface(NSObjectClass)
//['{E8094EC1-7A9B-4487-9FC9-F8C92D8F6DDD}']
//end;
//RTCRtcpParameters = interface(NSObject)
//['{0D8FD227-2A68-4018-85CC-5A3499E57C53}']
//function cname: NSString; cdecl;
//procedure setIsReducedSize(isReducedSize: Boolean); cdecl;
//function isReducedSize: Boolean; cdecl;
//function init: Pointer { instancetype }; cdecl;
//end;
//TRTCRtcpParameters = class(TOCGenericImport<RTCRtcpParametersClass, RTCRtcpParameters>) end;
//PRTCRtcpParameters = Pointer;
//{***************************************************}
//RTCRtpCodecParametersClass = interface(NSObjectClass)
//['{37FE9BA9-2F15-4E8C-9128-49475017F625}']
//end;
//RTCRtpCodecParameters = interface(NSObject)
//['{1BEBD056-C52B-4D12-8443-165BEA74E193}']
//procedure setPayloadType(payloadType: Integer); cdecl;
//function payloadType: Integer; cdecl;
//function name: NSString; cdecl;
//function kind: NSString; cdecl;
//function clockRate: NSNumber; cdecl;
//function numChannels: NSNumber; cdecl;
//function parameters: NSDictionary; cdecl;
//function init: Pointer { instancetype }; cdecl;
//end;
//TRTCRtpCodecParameters = class(TOCGenericImport<RTCRtpCodecParametersClass, RTCRtpCodecParameters>) end;
//PRTCRtpCodecParameters = Pointer;
{**********************************************}
//@interface RTCRtpEncodingParameters : NSObject
RTCRtpEncodingParametersClass = interface(NSObjectClass)
['{B4DA3F62-1BF3-48BB-8F95-1BE788B12E73}']
end;
RTCRtpEncodingParameters = interface(NSObject)
['{6B905749-0D33-4DF7-9121-B18EB2E8E071}']
//Controls whether the encoding is currently transmitted.
//@property(nonatomic, assign) BOOL isActive;
//procedure setIsActive(isActive: Boolean); cdecl;
//function isActive: Boolean; cdecl;
//The maximum bitrate to use for the encoding, or nil if there is no
//limit.
//@property(nonatomic, copy, nullable) NSNumber *maxBitrateBps;
procedure setMaxBitrateBps(maxBitrateBps: NSNumber); cdecl;
function maxBitrateBps: NSNumber; cdecl;
//The minimum bitrate to use for the encoding, or nil if there is no
//limit.
//@property(nonatomic, copy, nullable) NSNumber *minBitrateBps;
//procedure setMinBitrateBps(minBitrateBps: NSNumber); cdecl;
//function minBitrateBps: NSNumber; cdecl;
//The maximum framerate to use for the encoding, or nil if there is no
//limit.
//@property(nonatomic, copy, nullable) NSNumber *maxFramerate;
//procedure setMaxFramerate(maxFramerate: NSNumber); cdecl;
//function maxFramerate: NSNumber; cdecl;
//The requested number of temporal layers to use for the encoding, or nil
//if the default should be used.
//@property(nonatomic, copy, nullable) NSNumber *numTemporalLayers;
//procedure setNumTemporalLayers(numTemporalLayers: NSNumber); cdecl;
//function numTemporalLayers: NSNumber; cdecl;
//The SSRC being used by this encoding. */
//@property(nonatomic, readonly, nullable) NSNumber *ssrc;
//function ssrc: NSNumber; cdecl;
//- (instancetype)init NS_DESIGNATED_INITIALIZER;
//function init: Pointer { instancetype }; cdecl;
end;
TRTCRtpEncodingParameters = class(TOCGenericImport<RTCRtpEncodingParametersClass, RTCRtpEncodingParameters>) end;
PRTCRtpEncodingParameters = Pointer;
//{***************************************************}
//RTCRtpHeaderExtensionClass = interface(NSObjectClass)
//['{F8164A6A-F3AD-4347-BF90-B41A004FF44E}']
//end;
//RTCRtpHeaderExtension = interface(NSObject)
//['{7D06813C-1545-463D-A4FA-FB3D4FB4915A}']
//function uri: NSString; cdecl;
//function id: Integer; cdecl;
//function isEncrypted: Boolean; cdecl;
//function init: Pointer { instancetype }; cdecl;
//end;
//TRTCRtpHeaderExtension = class(TOCGenericImport<RTCRtpHeaderExtensionClass, RTCRtpHeaderExtension>) end;
//PRTCRtpHeaderExtension = Pointer;
{**************************************}
//@interface RTCRtpParameters : NSObject
RTCRtpParametersClass = interface(NSObjectClass)
['{9FD0BAE1-C448-4A1E-A244-78B31E04AAB1}']
end;
RTCRtpParameters = interface(NSObject)
['{41D43D16-F1A1-419F-A356-BFC8FEE7A66F}']
//A unique identifier for the last set of parameters applied.
//@property(nonatomic, copy) NSString *transactionId;
procedure setTransactionId(transactionId: NSString); cdecl;
function transactionId: NSString; cdecl;
//Parameters used for RTCP.
//@property(nonatomic, readonly, copy) RTCRtcpParameters *rtcp;
//function rtcp: RTCRtcpParameters; cdecl;
//An array containing parameters for RTP header extensions.
//@property(nonatomic, readonly, copy) NSArray<RTCRtpHeaderExtension *> *headerExtensions;
function headerExtensions: NSArray; cdecl;
//The currently active encodings in the order of preference.
//@property(nonatomic, copy) NSArray<RTCRtpEncodingParameters *> *encodings;
procedure setEncodings(encodings: NSArray); cdecl;
function encodings: NSArray; cdecl;
//The negotiated set of send codecs in order of preference.
//@property(nonatomic, copy) NSArray<RTCRtpCodecParameters *> *codecs;
procedure setCodecs(codecs: NSArray); cdecl;
function codecs: NSArray; cdecl;
//- (instancetype)init NS_DESIGNATED_INITIALIZER;
function init: Pointer { instancetype }; cdecl;
end;
TRTCRtpParameters = class(TOCGenericImport<RTCRtpParametersClass, RTCRtpParameters>) end;
PRTCRtpParameters = Pointer;
//{********************************************************}
//RTCVideoDecoderFactoryH264Class = interface(NSObjectClass)
//['{AB6A5448-09E3-40F4-8BA4-C98EF63768D9}']
//end;
//RTCVideoDecoderFactoryH264 = interface(NSObject)
//['{CC95BD22-56FA-4B33-BE77-0EC5F85B49B6}']
//end;
//TRTCVideoDecoderFactoryH264 = class(TOCGenericImport<RTCVideoDecoderFactoryH264Class, RTCVideoDecoderFactoryH264>) end;
//PRTCVideoDecoderFactoryH264 = Pointer;
//{*************************************************}
//RTCVideoDecoderH264Class = interface(NSObjectClass)
//['{4AE2C9E4-82F9-4FE6-8DA5-ECD9A275EAC0}']
//end;
//RTCVideoDecoderH264 = interface(NSObject)
//['{3536063B-C468-4A52-86EC-6950E6980EF7}']
//end;
//TRTCVideoDecoderH264 = class(TOCGenericImport<RTCVideoDecoderH264Class, RTCVideoDecoderH264>) end;
//PRTCVideoDecoderH264 = Pointer;
//{************************************************}
//RTCVideoDecoderVP8Class = interface(NSObjectClass)
//['{E0189880-17DA-445F-AE7F-87945B87AC14}']
//{ class } function vp8Decoder: Pointer; cdecl;
//end;
//RTCVideoDecoderVP8 = interface(NSObject)
//['{A81E1B58-629B-4CD3-9374-8571A0306EE2}']
//end;
//TRTCVideoDecoderVP8 = class(TOCGenericImport<RTCVideoDecoderVP8Class, RTCVideoDecoderVP8>) end;
//PRTCVideoDecoderVP8 = Pointer;
//{************************************************}
//RTCVideoDecoderVP9Class = interface(NSObjectClass)
//['{49ADA230-1A6D-4470-B9D0-47C6161B4CAC}']
//{ class } function vp9Decoder: Pointer; cdecl;
//end;
//RTCVideoDecoderVP9 = interface(NSObject)
//['{1DF313DA-FCEB-4C7B-90FB-414906295340}']
//end;
//TRTCVideoDecoderVP9 = class(TOCGenericImport<RTCVideoDecoderVP9Class, RTCVideoDecoderVP9>) end;
//PRTCVideoDecoderVP9 = Pointer;
//{********************************************************}
//RTCVideoEncoderFactoryH264Class = interface(NSObjectClass)
//['{17D653AF-6374-415F-9464-FB3E2CF10EC4}']
//end;
//RTCVideoEncoderFactoryH264 = interface(NSObject)
//['{3544F254-E238-4514-8358-AD68F66231DD}']
//end;
//TRTCVideoEncoderFactoryH264 = class(TOCGenericImport<RTCVideoEncoderFactoryH264Class, RTCVideoEncoderFactoryH264>) end;
//PRTCVideoEncoderFactoryH264 = Pointer;
//{*************************************************}
//RTCVideoEncoderH264Class = interface(NSObjectClass)
//['{7E87C686-5E63-4474-B292-F675A02852F5}']
//end;
//RTCVideoEncoderH264 = interface(NSObject)
//['{DCB7D623-99E1-4D50-B8BA-DC7CDA4A443C}']
//function initWithCodecInfo(codecInfo: RTCVideoCodecInfo): Pointer { instancetype }; cdecl;
//end;
//TRTCVideoEncoderH264 = class(TOCGenericImport<RTCVideoEncoderH264Class, RTCVideoEncoderH264>) end;
//PRTCVideoEncoderH264 = Pointer;
//{************************************************}
//RTCVideoEncoderVP8Class = interface(NSObjectClass)
//['{50C9BCEF-C572-43CB-8B45-2D41F47EC199}']
//{ class } function vp8Encoder: Pointer; cdecl;
//end;
//RTCVideoEncoderVP8 = interface(NSObject)
//['{9C42EE69-7803-4ED1-9490-5363AA9CE379}']
//end;
//TRTCVideoEncoderVP8 = class(TOCGenericImport<RTCVideoEncoderVP8Class, RTCVideoEncoderVP8>) end;
//PRTCVideoEncoderVP8 = Pointer;
//{************************************************}
//RTCVideoEncoderVP9Class = interface(NSObjectClass)
//['{F85718EE-23DC-4D16-BB84-CD6C44879F01}']
//{ class } function vp9Encoder: Pointer; cdecl;
//end;
//RTCVideoEncoderVP9 = interface(NSObject)
//['{70A9750A-F8E2-4ABC-B41A-B9749F56B43F}']
//end;
//TRTCVideoEncoderVP9 = class(TOCGenericImport<RTCVideoEncoderVP9Class, RTCVideoEncoderVP9>) end;
//PRTCVideoEncoderVP9 = Pointer;
//{********************************}
//RTCDevice = interface(IObjectiveC)
//['{3F119A2E-EC1F-4C58-A3BB-01F225062DA5}']
//function deviceType: RTCDeviceType; cdecl;
//function isIOS11OrLater: Boolean; cdecl;
//end;
//{**********************************************}
//RTCAudioSessionDelegate = interface(IObjectiveC)
//['{D688ED74-51FA-4722-96A8-F6D4B9F480A9}']
//procedure audioSessionDidBeginInterruption(session: RTCAudioSession); cdecl;
//procedure audioSessionDidEndInterruption(session: RTCAudioSession; shouldResumeSession: Boolean); cdecl;
//procedure audioSessionDidChangeRoute(session: RTCAudioSession; reason: AVAudioSessionRouteChangeReason; previousRoute: AVAudioSessionRouteDescription); cdecl;
//procedure audioSessionMediaServerTerminated (session: RTCAudioSession); cdecl;
//procedure audioSessionMediaServerReset(session: RTCAudioSession); cdecl;
//[MethodName('audioSession:didChangeCanPlayOrRecord:')]
//procedure audioSessionDidChangeCanPlayOrRecord(session: RTCAudioSession; didChangeCanPlayOrRecord: Boolean); cdecl;
//procedure audioSessionDidStartPlayOrRecord(session: RTCAudioSession); cdecl;
//procedure audioSessionDidStopPlayOrRecord(session: RTCAudioSession); cdecl;
//[MethodName('audioSession:didChangeOutputVolume:')]
//procedure audioSessionDidChangeOutputVolume(audioSession: RTCAudioSession; didChangeOutputVolume: Single); cdecl;
//[MethodName('audioSession:didDetectPlayoutGlitch:')]
//procedure audioSessionDidDetectPlayoutGlitch(audioSession: RTCAudioSession; didDetectPlayoutGlitch: Int64); cdecl;
//[MethodName('audioSession:willSetActive:')]
//procedure audioSessionWillSetActive(audioSession: RTCAudioSession; willSetActive: Boolean); cdecl;
//[MethodName('audioSession:didSetActive:')]
//procedure audioSessionDidSetActive(audioSession: RTCAudioSession; didSetActive: Boolean); cdecl;
//[MethodName('audioSession:failedToSetActive:error:')]
//procedure audioSessionFailedToSetActiveError(audioSession: RTCAudioSession; failedToSetActive: Boolean; error: NSError); cdecl;
//end;
//{********************************************************}
//RTCAudioSessionActivationDelegate = interface(IObjectiveC)
//['{15161B43-B6A7-4D66-AA08-586FEC66D10B}']
//procedure audioSessionDidActivate(session: AVAudioSession); cdecl;
//procedure audioSessionDidDeactivate(session: AVAudioSession); cdecl;
//end;
{****************************************}
//@protocol RTCVideoFrameBuffer <NSObject>
//RTCVideoFrameBuffer = interface(IObjectiveC)
//['{EAEE9751-BBF7-44DC-918D-80D87B1A1BC9}']
//@property(nonatomic, readonly) int width;
//function width: Integer; cdecl;
//@property(nonatomic, readonly) int height;
//function height: Integer; cdecl;
//- (id<RTCI420Buffer>)toI420;
//function toI420: Pointer; cdecl;
//end;
{*********************************************}
//@protocol RTCVideoCapturerDelegate <NSObject>
RTCVideoCapturerDelegate = interface(IObjectiveC)
['{128218E8-24D4-4AE6-B4E2-998C3B7AB6E9}']
//- (void)capturer:(RTCVideoCapturer *)capturer didCaptureVideoFrame:(RTCVideoFrame *)frame;
procedure capturer(capturer: RTCVideoCapturer; didCaptureVideoFrame: RTCVideoFrame); cdecl;
end;
//{*******************************************}
//RTCCodecSpecificInfo = interface(IObjectiveC)
//['{A4E42988-D478-4D4C-ACA7-C173335E0D85}']
//end;
//{*********************************************}
//RTCDataChannelDelegate = interface(IObjectiveC)
//['{FE3BF9F7-BEF6-42A2-BBA2-BF923C87446B}']
//procedure dataChannelDidChangeState(dataChannel: RTCDataChannel); cdecl;
//[MethodName('dataChannel:didReceiveMessageWithBuffer:')]
//procedure dataChannelDidReceiveMessageWithBuffer (dataChannel: RTCDataChannel; didReceiveMessageWithBuffer: RTCDataBuffer); cdecl;
//[MethodName('dataChannel:didChangeBufferedAmount:')]
//procedure dataChannelDidChangeBufferedAmount(dataChannel: RTCDataChannel; didChangeBufferedAmount: UInt64); cdecl;
//end;
//{**************************************}
//RTCVideoDecoder = interface(IObjectiveC)
//['{CA3AC1F9-7545-466E-8832-0FA2E44D413F}']
//procedure setCallback(callback: RTCVideoDecoderCallback); cdecl;
//function startDecodeWithSettings(settings: RTCVideoEncoderSettings; numberOfCores: Integer): NSInteger; cdecl;
//function releaseDecoder: NSInteger; cdecl;
//function decode(encodedImage: RTCEncodedImage; missingFrames: Boolean; codecSpecificInfo: Pointer; renderTimeMs: Int64): NSInteger; cdecl;
//function implementationName: NSString; cdecl;
//function startDecodeWithNumberOfCores(numberOfCores: Integer): NSInteger; cdecl;
//end;
//{*********************************************}
//RTCVideoDecoderFactory = interface(IObjectiveC)
//['{78896CE3-4543-41A4-8451-0BF665F321ED}']
//function createDecoder(info: RTCVideoCodecInfo): Pointer; cdecl;
//function supportedCodecs: NSArray; cdecl;
//end;
//{**************************************}
//RTCVideoEncoder = interface(IObjectiveC)
//['{7310F706-7913-4B4C-AE9F-924BBB273649}']
//procedure setCallback(callback: RTCVideoEncoderCallback); cdecl;
//function startEncodeWithSettings(settings: RTCVideoEncoderSettings; numberOfCores: Integer): NSInteger; cdecl;
//function releaseEncoder: NSInteger; cdecl;
//function encode(frame: RTCVideoFrame; codecSpecificInfo: Pointer; frameTypes: NSArray): NSInteger; cdecl;
//function setBitrate(bitrateKbit: LongWord; framerate: LongWord): Integer; cdecl;
//function implementationName: NSString; cdecl;
//function scalingSettings: RTCVideoEncoderQpThresholds; cdecl;
//end;
//{*********************************************}
//RTCVideoEncoderFactory = interface(IObjectiveC)
//['{2440D44B-5404-4460-B60C-C1BBF5AB8BCA}']
//function createEncoder(info: RTCVideoCodecInfo): Pointer; cdecl;
//function supportedCodecs: NSArray; cdecl;
//end;
//{************************************}
//RTCDtmfSender = interface(IObjectiveC)
//['{32F586AC-065E-45E4-A704-D04BF78739A0}']
//function canInsertDtmf: Boolean; cdecl;
//function insertDtmf(tones: NSString; duration: NSTimeInterval; interToneGap: NSTimeInterval): Boolean; cdecl;
//function remainingTones: NSString; cdecl;
//function duration: NSTimeInterval; cdecl;
//function interToneGap: NSTimeInterval; cdecl;
//end;
{*************************************}
//@protocol RTCVideoRenderer <NSObject>
RTCVideoRenderer = interface(IObjectiveC)
['{161733F8-4379-4F41-B7F7-1985FAAF9A11}']
//The size of the frame.
//- (void)setSize:(CGSize)size;
procedure setSize(size: CGSize); cdecl;
//The frame to be displayed.
//- (void)renderFrame:(nullable RTCVideoFrame *)frame;
procedure renderFrame(frame: RTCVideoFrame); cdecl;
end;
//{*******************************************}
//RTCVideoViewDelegate = interface(IObjectiveC)
//['{62563606-CFC0-47FC-B147-FD8881C8A6CE}']
//procedure videoView(videoView: Pointer; didChangeVideoSize: CGSize); cdecl;
//end;
//{******************************************}
//RTCVideoViewShading = interface(IObjectiveC)
//['{88021F97-F59B-408E-AA7E-FD0BA1D15E0A}']
//[MethodName ('applyShadingForFrameWithWidth:height:rotation:yPlane:uPlane:vPlane:')]
//procedure applyShadingForFrameWithWidthHeightRotationYPlaneUPlaneVPlane (width: Integer; height: Integer; rotation: RTCVideoRotation; yPlane: GLuint; uPlane: GLuint; vPlane: GLuint); cdecl;
//[MethodName ('applyShadingForFrameWithWidth:height:rotation:yPlane:uvPlane:')]
//procedure applyShadingForFrameWithWidthHeightRotationYPlaneUvPlane (width: Integer; height: Integer; rotation: RTCVideoRotation; yPlane: GLuint; uvPlane: GLuint); cdecl;
//end;
//{*****************************************}
//RTCYUVPlanarBuffer = interface(IObjectiveC)
//['{B2C25DC6-5976-4911-B710-67E03A53F16D}']
//function chromaWidth: Integer; cdecl;
//function chromaHeight: Integer; cdecl;
//function dataY: PByte; cdecl;
//function dataU: PByte; cdecl;
//function dataV: PByte; cdecl;
//function strideY: Integer; cdecl;
//function strideU: Integer; cdecl;
//function strideV: Integer; cdecl;
//[MethodName('initWithWidth:height:dataY:dataU:dataV:')]
//function initWithWidthHeightDataYDataUDataV(width: Integer; height: Integer; dataY: PByte; dataU: PByte; dataV: PByte): Pointer { instancetype }; cdecl;
//[MethodName('initWithWidth:height:')]
//function initWithWidthHeight(width: Integer; height: Integer): Pointer { instancetype }; cdecl;
//[MethodName('initWithWidth:height:strideY:strideU:strideV:')]
//function initWithWidthHeightStrideYStrideUStrideV(width: Integer; height: Integer; strideY: Integer; strideU: Integer; strideV: Integer): Pointer { instancetype }; cdecl;
//end;
//{************************************************}
//RTCMutableYUVPlanarBuffer = interface(IObjectiveC)
//['{BCF71D8A-E4BD-4506-ACE6-3CE0EE691EE5}']
//function mutableDataY: PByte; cdecl;
//function mutableDataU: PByte; cdecl;
//function mutableDataV: PByte; cdecl;
//end;
{**********************************************}
//@protocol RTCPeerConnectionDelegate <NSObject>
RTCPeerConnectionDelegate = interface(IObjectiveC)
['{511BE845-750C-4A21-9125-C996A51BEF2C}']
//Called when the SignalingState changed.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didChangeSignalingState:(RTCSignalingState)stateChanged;
[MethodName('peerConnection:didChangeSignalingState:')]
procedure peerConnectionDidChangeSignalingState(peerConnection: RTCPeerConnection; didChangeSignalingState: RTCSignalingState); cdecl;
//Called when media is received on a new stream from remote peer.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection didAddStream:(RTCMediaStream *)stream;
[MethodName('peerConnection:didAddStream:')]
procedure peerConnectionDidAddStream(peerConnection: RTCPeerConnection; didAddStream: RTCMediaStream); cdecl;
//Called when a remote peer closes a stream.
//This is not called when RTCSdpSemanticsUnifiedPlan is specified.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection didRemoveStream:(RTCMediaStream *)stream;
[MethodName('peerConnection:didRemoveStream:')]
procedure peerConnectionDidRemoveStream(peerConnection: RTCPeerConnection; didRemoveStream: RTCMediaStream); cdecl;
//Called when negotiation is needed, for example ICE has restarted.
//- (void)peerConnectionShouldNegotiate:(RTCPeerConnection *)peerConnection;
procedure peerConnectionShouldNegotiate(peerConnection: RTCPeerConnection); cdecl;
//Called any time the IceConnectionState changes.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didChangeIceConnectionState:(RTCIceConnectionState)newState;
[MethodName('peerConnection:didChangeIceConnectionState:')]
procedure peerConnectionDidChangeIceConnectionState(peerConnection: RTCPeerConnection; didChangeIceConnectionState: RTCIceConnectionState); cdecl;
//Called any time the IceGatheringState changes.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didChangeIceGatheringState:(RTCIceGatheringState)newState;
[MethodName('peerConnection:didChangeIceGatheringState:')]
procedure peerConnectionDidChangeIceGatheringState(peerConnection: RTCPeerConnection; didChangeIceGatheringState: RTCIceGatheringState); cdecl;
//New ice candidate has been found.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didGenerateIceCandidate:(RTCIceCandidate *)candidate;
[MethodName('peerConnection:didGenerateIceCandidate:')]
procedure peerConnectionDidGenerateIceCandidate(peerConnection: RTCPeerConnection; didGenerateIceCandidate: RTCIceCandidate); cdecl;
//Called when a group of local Ice candidates have been removed.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didRemoveIceCandidates:(NSArray<RTCIceCandidate *> *)candidates;
[MethodName('peerConnection:didRemoveIceCandidates:')]
procedure peerConnectionDidRemoveIceCandidates(peerConnection: RTCPeerConnection; didRemoveIceCandidates: NSArray); cdecl;
//New data channel has been opened.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didOpenDataChannel:(RTCDataChannel *)dataChannel;
[MethodName('peerConnection:didOpenDataChannel:')]
procedure peerConnectionDidOpenDataChannel(peerConnection: RTCPeerConnection; didOpenDataChannel: RTCDataChannel); cdecl;
//Called when signaling indicates a transceiver will be receiving media from
//the remote endpoint.
//This is only called with RTCSdpSemanticsUnifiedPlan specified.
//@optional
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didStartReceivingOnTransceiver:(RTCRtpTransceiver *)transceiver;
[MethodName('peerConnection:didStartReceivingOnTransceiver:')]
procedure peerConnectionDidStartReceivingOnTransceiver(peerConnection: RTCPeerConnection; didStartReceivingOnTransceiver: RTCRtpTransceiver); cdecl;
//Called when a receiver and its track are created.
//@optional
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didAddReceiver:(RTCRtpReceiver *)rtpReceiver
// streams:(NSArray<RTCMediaStream *> *)mediaStreams;
[MethodName('peerConnection:didAddReceiver:streams:')]
procedure peerConnectionDidAddReceiverStreams(peerConnection: RTCPeerConnection; didAddReceiver: RTCRtpReceiver; streams: NSArray); cdecl;
//Called when the receiver and its track are removed.
//- (void)peerConnection:(RTCPeerConnection *)peerConnection
// didRemoveReceiver:(RTCRtpReceiver *)rtpReceiver;
[MethodName('peerConnection:didRemoveReceiver:')]
procedure peerConnectionDidRemoveReceiver(peerConnection: RTCPeerConnection; didRemoveReceiver: RTCRtpReceiver); cdecl;
end;
//{*********************************************}
//RTCRtpReceiverDelegate = interface(IObjectiveC)
//['{8E81C44C-673D-4CBB-86C8-E19CBEFED21C}']
//procedure rtpReceiver(rtpReceiver: RTCRtpReceiver; didReceiveFirstPacketForMediaType: RTCRtpMediaType); cdecl;
//end;
//{*********************************************}
//function kRTCAudioSessionErrorDomain: NSString;
//function kRTCAudioSessionErrorLockRequired: Pointer;
//function kRTCAudioSessionErrorConfiguration: Pointer;
//function kRTCAudioSessionPreferredNumberOfChannels: Pointer;
//function kRTCAudioSessionHighPerformanceSampleRate: Pointer;
//function kRTCAudioSessionLowComplexitySampleRate: Pointer;
//function kRTCAudioSessionHighPerformanceIOBufferDuration: Pointer;
//function kRTCAudioSessionLowComplexityIOBufferDuration: Pointer;
//function kRTCMediaStreamTrackKindAudio: NSString;
//function kRTCMediaStreamTrackKindVideo: NSString;
//function kRTCFieldTrialAudioSendSideBweKey: NSString;
//function kRTCFieldTrialAudioSendSideBweForVideoKey: NSString;
//function kRTCFieldTrialAudioForceNoTWCCKey: NSString;
//function kRTCFieldTrialAudioForceABWENoTWCCKey: NSString;
//function kRTCFieldTrialSendSideBweWithOverheadKey: NSString;
//function kRTCFieldTrialFlexFec03AdvertisedKey: NSString;
//function kRTCFieldTrialFlexFec03Key: NSString;
//function kRTCFieldTrialImprovedBitrateEstimateKey: NSString;
//function kRTCFieldTrialH264HighProfileKey: NSString;
//function kRTCFieldTrialMinimizeResamplingOnMobileKey: NSString;
//function kRTCFieldTrialEnabledValue: NSString;
//function kRTCFieldTrialMedianSlopeFilterKey: NSString;
//function kRTCFieldTrialTrendlineFilterKey: NSString;
//function kRTCVideoCodecH264Name: NSString;
//function kRTCLevel31ConstrainedHigh: NSString;
//function kRTCLevel31ConstrainedBaseline: NSString;
//function kRTCMaxSupportedH264ProfileLevelConstrainedHigh: NSString;
//function kRTCMaxSupportedH264ProfileLevelConstrainedBaseline: NSString;
//function kRTCMediaConstraintsMinAspectRatio: NSString;
//function kRTCMediaConstraintsMaxAspectRatio: NSString;
//function kRTCMediaConstraintsMaxWidth: NSString;
//function kRTCMediaConstraintsMinWidth: NSString;
//function kRTCMediaConstraintsMaxHeight: NSString;
//function kRTCMediaConstraintsMinHeight: NSString;
//function kRTCMediaConstraintsMaxFrameRate: NSString;
//function kRTCMediaConstraintsMinFrameRate: NSString;
//function kRTCMediaConstraintsAudioNetworkAdaptorConfig: NSString;
//function kRTCMediaConstraintsIceRestart: NSString;
//function kRTCMediaConstraintsOfferToReceiveAudio: NSString;
//function kRTCMediaConstraintsOfferToReceiveVideo: NSString;
//function kRTCMediaConstraintsVoiceActivityDetection: NSString;
//function kRTCMediaConstraintsValueTrue: NSString;
//function kRTCMediaConstraintsValueFalse: NSString;
//function kRTCPeerConnectionErrorDomain: NSString;
//function kRTCSessionDescriptionErrorCode: Pointer;
//function kRTCRtxCodecName: NSString;
//function kRTCRedCodecName: NSString;
//function kRTCUlpfecCodecName: NSString;
//function kRTCFlexfecCodecName: NSString;
//function kRTCOpusCodecName: NSString;
//function kRTCIsacCodecName: NSString;
//function kRTCL16CodecName: NSString;
//function kRTCG722CodecName: NSString;
//function kRTCIlbcCodecName: NSString;
//function kRTCPcmuCodecName: NSString;
//function kRTCPcmaCodecName: NSString;
//function kRTCDtmfCodecName: NSString;
//function kRTCComfortNoiseCodecName: NSString;
//function kRTCVp8CodecName: NSString;
//function kRTCVp9CodecName: NSString;
//function kRTCH264CodecName: NSString;
//function kRTCVideoCodecVp8Name: NSString;
//function kRTCVideoCodecVp9Name: NSString;
//RTC_EXTERN void RTCSetupInternalTracer(void);
procedure RTCSetupInternalTracer; cdecl; external framework 'WebRTC' name _PU + 'RTCSetupInternalTracer';
//Starts capture to specified file. Must be a valid writable path.
//Returns YES if capture starts.
//RTC_EXTERN BOOL RTCStartInternalCapture(NSString* filePath);
function RTCStartInternalCapture(filePath: Pointer { NSString }): Boolean; cdecl; external framework 'WebRTC' name _PU + 'RTCStartInternalCapture';
//RTC_EXTERN void RTCStopInternalCapture(void);
procedure RTCStopInternalCapture; cdecl; external framework 'WebRTC' name _PU + 'RTCStopInternalCapture';
//RTC_EXTERN void RTCShutdownInternalTracer(void);
procedure RTCShutdownInternalTracer; cdecl; external framework 'WebRTC' name _PU + 'RTCShutdownInternalTracer';
//Initialize field trials using a dictionary mapping field trial keys to their
//values. See above for valid keys and values. Must be called before any other
//call into WebRTC. See: webrtc/system_wrappers/include/field_trial.h
//RTC_EXTERN void RTCInitFieldTrialDictionary(NSDictionary<NSString *, NSString *> *fieldTrials);
procedure RTCInitFieldTrialDictionary(fieldTrials: Pointer { NSDictionary } ); cdecl; external framework 'WebRTC' name _PU + 'RTCInitFieldTrialDictionary';
//Initialize and clean up the SSL library. Failure is fatal. These call the
//corresponding functions in webrtc/rtc_base/ssladapter.h.
//RTC_EXTERN BOOL RTCInitializeSSL(void);
function RTCInitializeSSL: Boolean; cdecl; external framework 'WebRTC' name _PU + 'RTCInitializeSSL';
//RTC_EXTERN BOOL RTCCleanupSSL(void);
function RTCCleanupSSL: Boolean; cdecl; external framework 'WebRTC' name _PU + 'RTCCleanupSSL';
//Wrapper for rtc::LogMessage::LogToDebug.
//Sets the minimum severity to be logged to console.
//RTC_EXTERN void RTCSetMinDebugLogLevel(RTCLoggingSeverity severity);
procedure RTCSetMinDebugLogLevel(severity: RTCLoggingSeverity); cdecl; external framework 'WebRTC' name _PU + 'RTCSetMinDebugLogLevel';
//procedure RTCLogEx(severity: RTCLoggingSeverity; log_string: Pointer { NSString } ); cdecl; external framework libWebRTC name _PU + 'RTCLogEx';
//function RTCFileName(filePath: MarshaledAString): Pointer { NSString }; cdecl; external framework libWebRTC name _PU + 'RTCFileName';
//function RTCFieldTrialMedianSlopeFilterValue(windowSize: LongWord; thresholdGain: Double): Pointer { NSString }; cdecl; external framework libWebRTC name _PU + 'RTCFieldTrialMedianSlopeFilterValue';
//function RTCFieldTrialTrendlineFilterValue(windowSize: LongWord; smoothingCoeff: Double; thresholdGain: Double): Pointer { NSString }; cdecl; external framework libWebRTC name _PU + 'RTCFieldTrialTrendlineFilterValue';
//procedure RTCEnableMetrics; cdecl; external framework libWebRTC name _PU + 'RTCEnableMetrics';
//function RTCGetAndResetMetrics: Pointer { NSArray }; cdecl; external framework libWebRTC name _PU + 'RTCGetAndResetMetrics';
implementation
//{*********************************************}
//function kRTCAudioSessionErrorDomain: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCAudioSessionErrorDomain');
//end;
//{***********************************************}
//function kRTCMediaStreamTrackKindAudio: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaStreamTrackKindAudio');
//end;
//{***********************************************}
//function kRTCMediaStreamTrackKindVideo: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaStreamTrackKindVideo');
//end;
//{***************************************************}
//function kRTCFieldTrialAudioSendSideBweKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialAudioSendSideBweKey');
//end;
//{***********************************************************}
//function kRTCFieldTrialAudioSendSideBweForVideoKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialAudioSendSideBweForVideoKey');
//end;
//{***************************************************}
//function kRTCFieldTrialAudioForceNoTWCCKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialAudioForceNoTWCCKey');
//end;
//{*******************************************************}
//function kRTCFieldTrialAudioForceABWENoTWCCKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialAudioForceABWENoTWCCKey');
//end;
//{**********************************************************}
//function kRTCFieldTrialSendSideBweWithOverheadKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialSendSideBweWithOverheadKey');
//end;
//{******************************************************}
//function kRTCFieldTrialFlexFec03AdvertisedKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialFlexFec03AdvertisedKey');
//end;
//{********************************************}
//function kRTCFieldTrialFlexFec03Key: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialFlexFec03Key');
//end;
//{**********************************************************}
//function kRTCFieldTrialImprovedBitrateEstimateKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialImprovedBitrateEstimateKey');
//end;
//{**************************************************}
//function kRTCFieldTrialH264HighProfileKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialH264HighProfileKey');
//end;
//{*************************************************************}
//function kRTCFieldTrialMinimizeResamplingOnMobileKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialMinimizeResamplingOnMobileKey');
//end;
//{********************************************}
//function kRTCFieldTrialEnabledValue: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialEnabledValue');
//end;
//{****************************************************}
//function kRTCFieldTrialMedianSlopeFilterKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialMedianSlopeFilterKey');
//end;
//{**************************************************}
//function kRTCFieldTrialTrendlineFilterKey: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFieldTrialTrendlineFilterKey');
//end;
//{****************************************}
//function kRTCVideoCodecH264Name: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCVideoCodecH264Name');
//end;
//{********************************************}
//function kRTCLevel31ConstrainedHigh: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCLevel31ConstrainedHigh');
//end;
//{************************************************}
//function kRTCLevel31ConstrainedBaseline: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCLevel31ConstrainedBaseline');
//end;
//{*****************************************************************}
//function kRTCMaxSupportedH264ProfileLevelConstrainedHigh: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMaxSupportedH264ProfileLevelConstrainedHigh');
//end;
//{*********************************************************************}
//function kRTCMaxSupportedH264ProfileLevelConstrainedBaseline: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMaxSupportedH264ProfileLevelConstrainedBaseline');
//end;
//{****************************************************}
//function kRTCMediaConstraintsMinAspectRatio: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMinAspectRatio');
//end;
//{****************************************************}
//function kRTCMediaConstraintsMaxAspectRatio: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMaxAspectRatio');
//end;
//{**********************************************}
//function kRTCMediaConstraintsMaxWidth: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMaxWidth');
//end;
//{**********************************************}
//function kRTCMediaConstraintsMinWidth: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMinWidth');
//end;
//{***********************************************}
//function kRTCMediaConstraintsMaxHeight: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMaxHeight');
//end;
//{***********************************************}
//function kRTCMediaConstraintsMinHeight: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMinHeight');
//end;
//{**************************************************}
//function kRTCMediaConstraintsMaxFrameRate: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMaxFrameRate');
//end;
//{**************************************************}
//function kRTCMediaConstraintsMinFrameRate: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsMinFrameRate');
//end;
//{***************************************************************}
//function kRTCMediaConstraintsAudioNetworkAdaptorConfig: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsAudioNetworkAdaptorConfig');
//end;
//{************************************************}
//function kRTCMediaConstraintsIceRestart: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsIceRestart');
//end;
//{*********************************************************}
//function kRTCMediaConstraintsOfferToReceiveAudio: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsOfferToReceiveAudio');
//end;
//{*********************************************************}
//function kRTCMediaConstraintsOfferToReceiveVideo: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsOfferToReceiveVideo');
//end;
//{************************************************************}
//function kRTCMediaConstraintsVoiceActivityDetection: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsVoiceActivityDetection');
//end;
//{***********************************************}
//function kRTCMediaConstraintsValueTrue: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsValueTrue');
//end;
//{************************************************}
//function kRTCMediaConstraintsValueFalse: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCMediaConstraintsValueFalse');
//end;
//{***********************************************}
//function kRTCPeerConnectionErrorDomain: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCPeerConnectionErrorDomain');
//end;
//{**********************************}
//function kRTCRtxCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCRtxCodecName');
//end;
//{**********************************}
//function kRTCRedCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCRedCodecName');
//end;
//{*************************************}
//function kRTCUlpfecCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCUlpfecCodecName');
//end;
//{**************************************}
//function kRTCFlexfecCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCFlexfecCodecName');
//end;
//{***********************************}
//function kRTCOpusCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCOpusCodecName');
//end;
//{***********************************}
//function kRTCIsacCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCIsacCodecName');
//end;
//{**********************************}
//function kRTCL16CodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCL16CodecName');
//end;
//{***********************************}
//function kRTCG722CodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCG722CodecName');
//end;
//{***********************************}
//function kRTCIlbcCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCIlbcCodecName');
//end;
//{***********************************}
//function kRTCPcmuCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCPcmuCodecName');
//end;
//{***********************************}
//function kRTCPcmaCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCPcmaCodecName');
//end;
//{***********************************}
//function kRTCDtmfCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCDtmfCodecName');
//end;
//{*******************************************}
//function kRTCComfortNoiseCodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCComfortNoiseCodecName');
//end;
//{**********************************}
//function kRTCVp8CodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCVp8CodecName');
//end;
//{**********************************}
//function kRTCVp9CodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCVp9CodecName');
//end;
//{***********************************}
//function kRTCH264CodecName: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCH264CodecName');
//end;
//{***************************************}
//function kRTCVideoCodecVp8Name: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCVideoCodecVp8Name');
//end;
//{***************************************}
//function kRTCVideoCodecVp9Name: NSString;
//begin
//Result := CocoaNSStringConst(libWebRTC, 'kRTCVideoCodecVp9Name');
//end;
//{**************************************************}
//function kRTCAudioSessionErrorLockRequired: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionErrorLockRequired');
//end;
//{***************************************************}
//function kRTCAudioSessionErrorConfiguration: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionErrorConfiguration');
//end;
//{**********************************************************}
//function kRTCAudioSessionPreferredNumberOfChannels: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionPreferredNumberOfChannels');
//end;
//{**********************************************************}
//function kRTCAudioSessionHighPerformanceSampleRate: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionHighPerformanceSampleRate');
//end;
//{********************************************************}
//function kRTCAudioSessionLowComplexitySampleRate: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionLowComplexitySampleRate');
//end;
//{****************************************************************}
//function kRTCAudioSessionHighPerformanceIOBufferDuration: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionHighPerformanceIOBufferDuration');
//end;
//{**************************************************************}
//function kRTCAudioSessionLowComplexityIOBufferDuration: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCAudioSessionLowComplexityIOBufferDuration');
//end;
//{************************************************}
//function kRTCSessionDescriptionErrorCode: Pointer;
//begin
//Result := CocoaPointerConst(libWebRTC, 'kRTCSessionDescriptionErrorCode');
//end;
end.
|
unit dxfparse;
{$ifdef fpc}{$mode delphi}{$H+}{$endif}
interface
uses
Classes, SysUtils, dxftypes;
{
NOTE: Accommodating DXF files from future releases of AutoCAD® will be easier
if you write your DXF processing program in a table-driven way, ignore undefined
group codes, and make no assumptions about the order of group codes in an
entity. With each new AutoCAD release, new group codes will be added to entities
to accommodate additional features.
}
type
TDxfScanResult = (scError, scValue, scEof, scInit);
{ TDxfScanner }
TDxfScanner = class(TObject)
protected
function DoNext(var errmsg: string): TDxfScanResult; virtual; abstract;
public
LastScan : TDxfScanResult; // set by Next, result of DoNext
DataType : TDxfType; // set by DoNext. Defaulted to dtUnknown. if DoNext() returns dtUnknown
// but CodeGroup is set to a non-negative value, it tries to determine the actual type
ErrStr : string; // the error set by Next, returned via errmsg of DoNext
CodeGroup : Integer; // set by DoNext
ValStr : string; // set by DoNext
ValInt : Int32; // set by DoNext
ValInt64 : Int64; // set by DoNext
ValBin : array of byte; // set by DoNext
ValBinLen : Integer; // set by DoNext
ValFloat : Double; // set by DoNext
// Binds a source ot the scanner. if OWnStream, the Scanner will free source, if the scanner is freed
procedure SetSource(ASource: TStream; OwnStream: Boolean); virtual;
// reads the next pair in the
function Next: TDxfScanResult;
// Returns the information about the current position
// LineNum <= 0, if reading is binary Offset value indicates the offset in the stream
// LineNum >=1, the reading is text the line number is indicatd. Offset is zero
procedure GetLocationInfo(out LineNum, Offset: Integer); virtual; abstract;
end;
{ TDxfAsciiScanner }
TDxfAsciiScanner = class(TDxfScanner)
private
fSrc : TStream;
fSrcOwn : Boolean;
protected
function DoNext(var errmsg: string): TDxfScanResult; override;
function PrepareValues: Boolean;
public
buf : string;
idx : integer;
lineNum : integer;
procedure SetSource(ASource: TStream; OwnStream: Boolean); override;
destructor Destroy; override;
procedure SetBuf(const astr: string);
procedure GetLocationInfo(out ALineNum, AOffset: Integer); override;
end;
{ TDxfBinaryScanner }
// Parses the binary input Stream. Note thet the binary header
// must skipped over, prior to calling SetSource
TDxfBinaryScanner = class(TDxfScanner)
protected
function DoNext(var errmsg: string): TDxfScanResult; override;
public
src : TStream;
srcStart : Int64;
srcOwn : Boolean;
isEof : Boolean;
destructor Destroy; override;
procedure SetSource(ASource: TStream; OwnStream: Boolean); override;
procedure GetLocationInfo(out ALineNum, AOffset: Integer); override;
end;
// tries to detect if stream is binary or not.
// note the Stream is read for the first 22-bytes to detect
// if it's binary or not.
function DxfisBinary(AStream: TStream): Boolean;
// Allocates the scanner according to the stream type. (SetSource method is called)
// for binary, the header is also skipped over
// The Stream must allow random-access, because it's first read using isBinary.
// after reading the position might be shifted back for ASCII reading
function DxfAllocScanner(AStream: TStream; OwnStream: boolean): TDxfScanner;
function DxfValAsStr(s: TDxfScanner): string;
function ConsumeCodeBlock(p : TDxfScanner; expCode: Integer; var value: string): Boolean;
type
TDxfParseToken = (
prUnknown, //unrecognized entry in the file
prError,
prEof,
prSecStart,
prSecEnd,
prClassStart,
prClassAttr,
prTableStart,
prTableAttr,
prTableEnd,
prTableEntry,
prTableEntryAttr,
prVarName,
prVarValue,
prBlockStart, // encountered 0/BLOCK
prBlockAttr, // still within block
prEntityInBlock,
prBlockEnd, //
prEntityAttr,
prEntityStart,
prObjStart,
prObjAttr,
prComment
);
{ TDxfParser }
TDxfParser = class(TObject)
protected
mode : integer;
inSec: integer;
function ParseRoot(t: TDxfScanner; var newmode: Integer): TDxfParseToken;
function ParseHeader(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function ParseClasses(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function ParseTables(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function ParseBlocks(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function ParseEntities(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function ParseObjects(t: TDxfScanner; var newmode: integer): TDxfParseToken;
function DoNext: TDxfParseToken;
procedure SetError(const msg: string);
public
token : TDxfParseToken;
scanner : TDxfScanner;
secName : string;
varName : string;
Comment : string;
ErrStr : string;
EntityType : string; // entity type
function Next: TDxfParseToken;
end;
const
INVALID_CODEGROUP = $10000; // the code group max is $FFFF. Int16
const
MODE_ROOT = 0;
MODE_HEADER = 1;
MODE_CLASSES = 2;
MODE_TABLES = 3;
MODE_BLOCKS = 4;
MODE_ENTITIES = 5;
MODE_OBJECTS = 6;
MODE_ENTITIESINBLOCK = 7;
// if the current CodeObject is equal to cd, return its value and calls Next()
// otherwise returns "def" and takes no action.
function ConsumeStr(p: TDxfParser; cd: Integer; const def: string = ''): string;
function ConsumeInt(p: TDxfParser; cd: Integer; const def: Integer = 0): Integer;
function ConsumeFlt(p: TDxfParser; cd: Integer; const def: double = 0): double;
implementation
const
LBChars = [#10,#13];
Digits = ['0'..'9'];
Signs = ['-','+'];
SignDigits = Digits + Signs;
function SkipLineBreak(const s: string; var idx: integer): Boolean;
var
inich : Char;
sec : Char;
begin
if (idx < 0) or (idx>length(s)) then begin
Result := true;
Exit;
end;
Result := false;
inich := s[idx];
if (inich <> #10) and (inich<>#13) then Exit;
Result := true;
inc(idx);
if (idx>length(s)) then Exit;
sec := s[idx];
if ((sec <> #10) and (sec<>#13)) or (sec = inich) then Exit;
inc(idx);
end;
{ TDxfBinaryScanner }
function ReadNullChar(src: TStream): string;
var
buf : string;
i : integer;
b : byte;
begin
SetLength(buf, 32);
i:=1;
while true do begin
src.ReadBuffer(b, 1);
if b = 0 then break;
if i>length(buf) then
SetLength(buf, length(buf) * 2);
buf[i]:=char(b);
inc(i);
end;
SetLength(buf, i-1);
Result:=buf;
end;
{ TDxfScanner }
procedure TDxfScanner.SetSource(ASource: TStream; OwnStream: Boolean);
begin
LastScan := scInit;
end;
function TDxfScanner.Next: TDxfScanResult;
begin
ValStr := '';
ValInt := 0;
ValInt64 := 0;
ValBinLen := 0;
ValFloat := 0;
CodeGroup := INVALID_CODEGROUP;
DataType := dtUnknown;
ErrStr := '';
try
LastScan := DoNext(ErrStr);
except
on E: Exception do begin
LastScan := scError;
ErrStr := E.Message;
end
end;
Result := LastScan;
end;
destructor TDxfBinaryScanner.Destroy;
begin
if srcOwn then src.Free;
inherited Destroy;
end;
procedure TDxfBinaryScanner.SetSource(ASource: TStream; OwnStream: Boolean);
begin
if not Assigned(ASource) then Exit;
src := ASource;
srcStart := src.Position;
srcOwn := OwnStream;
inherited SetSource(ASource, OwnStream);
end;
procedure TDxfBinaryScanner.GetLocationInfo(out ALineNum, AOffset: Integer);
begin
ALineNum := 0;
if Assigned(src) then
AOffset := src.Position - srcStart
else
AOffset := 0;
end;
function TDxfBinaryScanner.DoNext(var errmsg: string): TDxfScanResult;
var
sz : integer;
b : byte;
w : Word;
begin
if isEof or (src.Position>=src.Size) then begin
Result := scEof;
Exit;
end;
Result := scValue;
src.ReadBuffer(codegroup, sizeof(codegroup));
datatype := DxfDataType(codegroup);
case datatype of
dtBin1: begin
sz := 0;
src.ReadBuffer(sz, 1);
SetLength(ValBin, sz);
src.Read(ValBin[0], sz);
end;
dtStr2049, dtStr255, dtStrHex:
begin
ValStr := ReadNullChar(src);
if (length(ValStr)=3) and (ValStr[1]='E')
and (ValStr[2]='O') and (ValStr[3]='F') then
isEof := true;
end;
dtBoolean: begin
src.ReadBuffer(b, sizeof(b));
ValInt := b;
end;
dtInt16: begin
src.ReadBuffer(w, sizeof(w));
ValInt := w;
end;
dtInt32: begin
src.ReadBuffer(ValInt, sizeof(ValInt));
end;
dtDouble:
src.Read(ValFloat, sizeof(ValFloat));
end;
end;
{ TDxfAsciiScanner }
procedure TDxfAsciiScanner.SetSource(ASource: TStream; OwnStream: Boolean);
var
sz : Int64;
s : string;
begin
if not Assigned(ASource) then Exit;
fSrc := ASource;
fSrcOwn := OwnStream;
SetLength(s, fSrc.Size-fSrc.Position);
if length(s)>0 then fSrc.Read(s[1], length(s));
SetBuf(s);
inherited SetSource(ASource, OwnStream);
end;
destructor TDxfAsciiScanner.Destroy;
begin
if fSrcOwn then fSrc.Free;
inherited Destroy;
end;
function TDxfAsciiScanner.DoNext(var errmsg: string): TDxfScanResult;
var
i : integer;
err : integer;
begin
if (idx>length(buf)) then begin
Result:=scEof;
Exit;
end;
while (idx<=length(buf)) and not (buf[idx] in SignDigits) do begin
if buf[idx] in LBChars then begin
SkipLineBreak(buf, idx);
inc(lineNum);
end else
inc(idx);
end;
i := idx;
if (idx<=length(buf)) and (buf[idx] in Signs) then inc(idx);
while (idx<=length(buf)) and (buf[idx] in Digits) do inc(idx);
Val(Copy(buf, i, idx-i), codegroup, err);
if err<>0 then begin
errmsg := 'invalid block code format'; // integer expected
Result := scError;
Exit;
end;
while not (idx<=length(buf)) and (buf[idx] in LBChars) do inc(idx);
if not SkipLineBreak(buf, idx) then begin
errmsg := 'expecting end of line'; // integer expected
Result := scError;
Exit;
end;
inc(LineNum);
i:=idx;
while (idx<=length(buf)) and not (buf[idx] in LBChars) do inc(idx);
ValStr := Copy(buf, i, idx-i);
PrepareValues;
Result := scValue;
end;
function TDxfAsciiScanner.PrepareValues: Boolean;
var
err : integer;
begin
Result := true;
DataType := DxfDataType(CodeGroup);
case DataType of
dtInt16, dtInt32, dtBoolean: begin
Val(ValStr, ValInt, err);
Result := err = 0;
ValInt64 := ValInt;
end;
dtInt64: begin
Val(ValStr, ValInt64, err);
Result := err = 0;
end;
dtDouble: begin
Val(ValStr, ValFloat, err);
Result := err = 0;
end;
dtBin1:
begin
if ValStr = '' then
ValBinLen := 0
else begin
ValBinLen :=length(valStr) div 2;
if length(valBin) < valBinLen then
SetLength(valBin, valBinLen);
HexToBin(@ValStr[1], @valBin[0], valBinLen);
end;
end;
end;
end;
procedure TDxfAsciiScanner.SetBuf(const astr: string);
begin
lineNum := 1;
buf := astr;
idx := 1;
end;
procedure TDxfAsciiScanner.GetLocationInfo(out ALineNum, AOffset: Integer);
begin
ALineNum := lineNum;
AOffset := 0;
end;
function ConsumeCodeBlock(p : TDxfScanner; expCode: Integer; var value: string): Boolean;
begin
Result := Assigned(p);
if not Result then Exit;
Result := p.Next = scValue;
if not Result then Exit;
Result := p.codegroup = expCode;
if Result then Value := p.ValStr;
end;
function TDxfParser.ParseRoot(t: TDxfScanner; var newmode: Integer): TDxfParseToken;
begin
if (t.codegroup = 0) then begin
if (t.ValStr = NAME_EOF) then begin
t.Next;
Result := prEof;
Exit; // end of file
end else if (t.valStr = NAME_SECTION) then begin
if inSec>0 then begin
SetError('nested section is not allowed');
Result := prError;
Exit;
end;
if not ConsumeCodeBlock(t, CB_SECTION_NAME, secName) then begin
SetError('expected section name');
Result := prError;
Exit;
end;
Result := prSecStart;
if secName = NAME_HEADER then newmode := MODE_HEADER
else if secName = NAME_CLASSES then newmode := MODE_CLASSES
else if secName = NAME_TABLES then newmode := MODE_TABLES
else if secName = NAME_BLOCKS then newmode := MODE_BLOCKS
else if secName = NAME_ENTITIES then newMode := MODE_ENTITIES
else if secName = NAME_OBJECTS then newMode := MODE_OBJECTS;
end else if (t.valStr=NAME_ENDSEC) then begin
if mode = MODE_HEADER then varName := '';
secName := '';
mode := 0;
Result := prSecEnd;
{end else if (t.valStr = 'TABLE') and (mode = MODE_TABLES) then begin
Result := prTableStart;
tableName := '';
handle := '';}
end;
end;
end;
function TDxfParser.ParseHeader(t: TDxfScanner; var newmode: integer): TDxfParseToken;
begin
if (t.codegroup = CB_VARNAME) then begin
varName := t.ValStr;
Result := prVarName
end else if (varName<>'') then
Result := prVarValue;
end;
function TDxfParser.ParseClasses(t: TDxfScanner; var newmode: integer
): TDxfParseToken;
begin
if (t.valStr = NAME_CLASS) then
Result := prClassStart
else
Result := prClassAttr;
end;
function TDxfParser.ParseTables(t: TDxfScanner; var newmode: integer): TDxfParseToken;
begin
if (t.CodeGroup = CB_CONTROL) and (t.valStr = NAME_TABLE) then begin
Result := prTableStart;
end else if (t.CodeGroup = CB_CONTROL) and (t.valStr = NAME_ENDTAB) then begin
Result := prTableEnd;
end else if (t.codeGroup = CB_CONTROL) then begin
Result := prTableEntry;
end else begin
//Result := prTableEntryAttr;
Result := prTableAttr;
end;
end;
function TDxfParser.ParseBlocks(t: TDxfScanner; var newmode: integer): TDxfParseToken;
begin
if (t.CodeGroup = CB_CONTROL) and (t.valStr = NAME_BLOCK) then begin
Result := prBlockStart;
end else if (t.CodeGroup = CB_CONTROL) and (t.valStr = NAME_ENDBLK) then begin
Result := prBlockEnd;
end else if (t.CodeGroup = CB_CONTROL) then begin
// Entity!
Result := ParseEntities(t, newmode);
newmode := MODE_ENTITIESINBLOCK;
end else begin
Result := prBlockAttr;
end;
end;
function TDxfParser.ParseEntities(t: TDxfScanner; var newmode: integer
): TDxfParseToken;
begin
if (newmode = MODE_ENTITIESINBLOCK) and (t.CodeGroup = 0) and (t.ValStr = NAME_ENDBLK) then begin
newmode := MODE_BLOCKS; // return to block parsing mode
Result := ParseBlocks(t, newmode);
end else if (t.CodeGroup = 0) then begin
EntityType := t.ValStr;
Result := prEntityStart;
end else begin
Result := prEntityAttr;
end;
end;
function TDxfParser.ParseObjects(t: TDxfScanner; var newmode: integer
): TDxfParseToken;
begin
if (t.CodeGroup = 0) then begin
EntityType := t.ValStr;
Result := prObjStart;
end else begin
Result := prObjAttr;
end;
end;
function TDxfParser.DoNext: TDxfParseToken;
var
//mode : integer; // 0 - core, 1 - header
t : TDxfScanner;
res : TDxfScanResult;
begin
if not Assigned(scanner) then begin
SetError('no scanner');
Exit;
end;
Result := prUnknown;
t := scanner;
res := scanner.LastScan;
if (res = scInit) then res := t.Next;
if res = scError then begin
SetError('scanner error: '+t.errStr);
Exit;
end else if res = scEof then begin
Result := prEof;
Exit;
end;
if (t.CodeGroup=CB_COMMENT) then begin
comment := t.ValStr;
Result := prComment;
end else if (t.CodeGroup=0) and (t.ValStr = NAME_ENDSEC) then begin
Result := prSecEnd
end else if (t.CodeGroup=0) and (t.ValStr = NAME_EOF) then begin
Result := prEof
end else
case mode of
MODE_ROOT:
Result := ParseRoot(t, mode);
MODE_HEADER: begin
Result := ParseHeader(t, mode);
end;
MODE_CLASSES:
Result := ParseClasses(t, mode); // it's always class attribute
MODE_BLOCKS:
Result := ParseBlocks(t, mode);
MODE_ENTITIES, MODE_ENTITIESINBLOCK:
Result := ParseEntities(t, mode);
MODE_OBJECTS:
Result := ParseObjects(t, mode);
MODE_TABLES:
Result := ParseTables(t, mode);
end;
case Result of
prSecStart:
inc(inSec);
prSecEnd: begin
dec(inSec);
mode := MODE_ROOT;
end;
end;
scanner.Next;
end;
procedure TDxfParser.SetError(const msg: string);
begin
ErrStr := msg;
end;
function TDxfParser.Next: TDxfParseToken;
begin
token := DoNext;
Result := token;
end;
function DxfisBinary(AStream: TStream): Boolean;
var
buf : string;
sz : integer;
pos : int64;
begin
Result := Assigned(AStream);
if not Result then Exit;
SetLength(buf, length(DxfBinaryHeader));
Result := AStream.Read(buf[1], length(buf)) = length(buf);
if not Result then Exit;
Result := buf = DxfBinaryHeader;
end;
function DxfAllocScanner(AStream: TStream; OwnStream: boolean): TDxfScanner;
var
pos : Int64;
begin
if not Assigned(AStream) then begin
Result := nil;
Exit;
end;
pos := AStream.Position;
if DxfisBinary(AStream) then
Result := TDxfBinaryScanner.Create
else begin
AStream.Position := pos;
Result := TDxfAsciiScanner.Create;
end;
Result.SetSource(AStream, OwnStream);
end;
function DxfValAsStr(s: TDxfScanner): string;
begin
if not Assigned(s) then begin
Result := '';
exit;
end;
case s.DataType of
dtUnknown:
Result := s.ValStr;
dtBoolean, dtInt16, dtInt32:
Result := IntToStr(s.ValInt);
dtInt64:
Result := IntToStr(s.ValInt64);
dtDouble: begin
Str(s.ValFloat, Result);
end;
dtStr2049, dtStr255, dtStrHex:
Result := s.ValStr;
dtBin1: begin
SetLength(Result, s.ValBinLen*2);
if length(Result)>0 then
BinToHex(@s.ValBin[0], @Result[1], s.ValBinLen);
end;
end;
end;
function ConsumeStr(p: TDxfParser; cd: Integer; const def: string = ''): string;
begin
if Assigned(p) and (p.scanner.CodeGroup = cd) then begin
Result := p.scanner.ValStr;
p.Next;
end else
Result := def;
end;
function ConsumeInt(p: TDxfParser; cd: Integer; const def: Integer = 0): Integer;
begin
if Assigned(p) and (p.scanner.CodeGroup = cd) then begin
Result := p.scanner.ValInt;
p.Next;
end else
Result := def;
end;
function ConsumeFlt(p: TDxfParser; cd: Integer; const def: double = 0): double;
begin
if Assigned(p) and (p.scanner.CodeGroup = cd) then begin
Result := p.scanner.ValFloat;
p.Next;
end else
Result := def;
end;
end.
|
unit SAPMrpAreaStockReader;
interface
uses
Classes, SysUtils, ComObj, SAPOPOReader2, SAPStockReader2, CommUtils;
type
TMyStringList = class(TStringList)
public
tag: TObject;
end;
TSAPMrpAREA = class
private
procedure GetOPOs(slNumber: TStringList; lst: TList);
public
sAreaNo: string;
sAreaName: string;
FList: TStringList;
FOPOList: TMyStringList;
FSAPStockSum: TSAPStockSum;
constructor Create;
destructor Destroy; override;
procedure Clear;
function Alloc(slNumber: TStringList; dt: TDateTime; dQty: Double): Double;
end;
TSAPMrpAreaStockReader = class
private
FList: TStringList;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
FReadOk: Boolean;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): TSAPMrpAREA;
public
constructor Create(const sfile: string; aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
procedure SetOPOList(aSAPOPOReader2: TSAPOPOReader2);
function Alloc(slNumber: TStringList; dt: TDateTime; dQty: Double;
const sMrpArea: string): Double;
procedure SetStock(aSAPStockReader: TSAPStockReader2);
function AllocStock(const snumber: string; dQty: Double;
const smrparea: string): Double;
function AllocStock2(const snumber: string; dQty: Double;
const smrparea: string): Double;
function AllocStock_area(const snumber, sname: string; dt: TDateTime;
dQty: Double; const smrparea: string; slTransfer: TList): Double;
function AccDemand(const snumber: string; dQty: Double;
const smrparea: string): Double;
function GetSAPMrpAREA(const sMrpArea: string): TSAPMrpAREA;
procedure GetOPOs(slNumber: TStringList; lst: TList; const sMrpArea: string);
function MrpAreaNo2Name(const sMrpAreaNo: string): string;
function MrpAreaOfStockNo(const sstock: string): string;
function GetStockSum(const snumber: string): Double;
function GetOPOSum(const snumber: string): Double;
property Count: Integer read GetCount;
property Items[i: Integer]: TSAPMrpAREA read GetItems;
property ReadOk: Boolean read FReadOk;
end;
implementation
procedure QuickSort(sl: TStringList; L, R: Integer;
SCompare: TStringListSortCompare);
var
I, J: Integer;
P, T: Pointer;
iP: Integer;
o: TObject;
s: string;
begin
repeat
I := L;
J := R;
iP := (L + R) shr 1;
repeat
while SCompare(sl, I, iP) < 0 do
Inc(I);
while SCompare(sl, J, iP) > 0 do
Dec(J);
if I <= J then
begin
o := sl.Objects[I];
sl.Objects[I] := sl.Objects[J];
sl.Objects[J] := o;
s := sl[I];
sl[I] := sl[J];
sl[J] := s;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(sl, L, J, SCompare);
L := I;
until I >= R;
end;
function StringListSortCompare_OPO(List: TStringList; Index1, Index2: Integer): Integer;
var
aSAPMrpAREA: TSAPMrpAREA;
aSAPOPOLine1: TSAPOPOLine;
aSAPOPOLine2: TSAPOPOLine;
begin
aSAPMrpAREA := TSAPMrpAREA( TMyStringList(List).tag );
Result := 0;
// if List[Index1] <> List[Index2] then Exit; // 料号不同,不变顺序
aSAPOPOLine1 := TSAPOPOLine(List.Objects[Index1]);
aSAPOPOLine2 := TSAPOPOLine(List.Objects[Index2]);
if aSAPOPOLine1.FNumber > aSAPOPOLine2.FNumber then
begin
Result := 1
end
else if aSAPOPOLine1.FNumber < aSAPOPOLine2.FNumber then
begin
Result := -1
end
else
begin
if DoubleG( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := 1;
end
else if DoubleL( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := -1
end
else
begin
if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) >= 0) and // 仓库在本区域, 排前面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) < 0) then
begin
Result := -1;
end
else if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) < 0) and // 仓库不在本区域, 排后面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) >= 0) then
begin
Result := 1;
end
else
begin
Result := 0;
end;
end;
end;
end;
{ TSAPMrpAREA }
constructor TSAPMrpAREA.Create;
begin
FOPOList := TMyStringList.Create;
FOPOList.CaseSensitive := False;
FOPOList.tag := Self;
FList := TStringList.Create;
FSAPStockSum := TSAPStockSum.Create;
end;
destructor TSAPMrpAREA.Destroy;
begin
Clear;
FList.Free;
FOPOList.Free;
FSAPStockSum.Free;
inherited;
end;
procedure TSAPMrpAREA.Clear;
begin
FOPOList.Clear;
FList.Clear;
FSAPStockSum.Clear;
end;
function ListSortCompare(Item1, Item2: Pointer): Integer;
var
aSAPOPOLine1: TSAPOPOLine;
aSAPOPOLine2: TSAPOPOLine;
aSAPMrpAREA: TSAPMrpAREA;
begin
aSAPOPOLine1 := TSAPOPOLine(Item1);
aSAPOPOLine2 := TSAPOPOLine(Item2);
if DoubleG( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := 1;
end
else if DoubleL( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := -1
end
else
begin
aSAPMrpAREA := TSAPMrpAREA(aSAPOPOLine1.Tag);
if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) >= 0) and // 仓库在本区域, 排前面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) < 0) then
begin
Result := -1;
end
else if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) < 0) and // 仓库不在本区域, 排后面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) >= 0) then
begin
Result := 1;
end
else
begin
Result := 0;
end;
end;
end;
procedure TSAPMrpAREA.GetOPOs(slNumber: TStringList; lst: TList);
var
i: Integer;
idx: Integer;
begin
for i := 0 to slNumber.Count - 1 do
begin
idx := FOPOList.IndexOf(slNumber[i]);
if idx >= 0 then
begin
while (idx >= 0) and (FOPOList[idx] = slNumber[i]) do
begin
idx := idx - 1;
end;
idx := idx + 1;
while (idx < FOPOList.Count) and (FOPOList[idx] = slNumber[i]) do
begin
lst.Add(FOPOList.Objects[idx]);
idx := idx + 1;
end;
end;
end;
lst.Sort(ListSortCompare);
//
// for i := 0 to FOPOList.Count - 1 do
// begin
// if slNumber.IndexOf(FOPOList[i]) >= 0 then
// begin
// lst.Add( FOPOList.Objects[i] );
// end;
// end;
end;
function TSAPMrpAREA.Alloc(slNumber: TStringList; dt: TDateTime; dQty: Double): Double;
var
lst: TList;
i: Integer;
p: TSAPOPOLine;
begin
Result := 0;
lst := TList.Create;
GetOPOs(slNumber, lst); // 找到所有替代料的可用采购订单
for i := 0 to lst.Count - 1 do
begin
p := TSAPOPOLine(lst[i]);
Result := Result + p.Alloc(dt, dQty, sAreaNo);
if DoubleE( dQty, 0) then // 需求满足分配了
begin
Break;
end;
end;
lst.Free;
end;
{ TSAPMrpAreaStockReader }
constructor TSAPMrpAreaStockReader.Create(const sfile: string;
aLogEvent: TLogEvent = nil);
begin
FFile := sfile;
FLogEvent := aLogEvent;
FList := TStringList.Create;
Open;
end;
destructor TSAPMrpAreaStockReader.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPMrpAreaStockReader.Clear;
var
i: Integer;
p: TSAPMrpAREA;
begin
for i := 0 to FList.Count - 1 do
begin
p := TSAPMrpAREA(FList.Objects[i]);
p.Free;
end;
FList.Clear;
end;
function StringListSortCompare(List: TStringList; Index1, Index2: Integer): Integer;
var
aSAPMrpAREA: TSAPMrpAREA;
aSAPOPOLine1: TSAPOPOLine;
aSAPOPOLine2: TSAPOPOLine;
begin
aSAPMrpAREA := TSAPMrpAREA( TMyStringList(List).tag );
aSAPOPOLine1 := TSAPOPOLine(List.Objects[Index1]);
aSAPOPOLine2 := TSAPOPOLine(List.Objects[Index2]);
if DoubleG( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := 1;
end
else if DoubleL( aSAPOPOLine1.FDate, aSAPOPOLine2.FDate ) then
begin
Result := -1
end
else
begin
if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) >= 0) and // 仓库在本区域, 排前面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) < 0) then
begin
Result := -1;
end
else if (aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine1.FStock) < 0) and // 仓库不在本区域, 排后面
(aSAPMrpAREA.FList.IndexOfName(aSAPOPOLine2.FStock) >= 0) then
begin
Result := 1;
end
else
begin
Result := 0;
end;
end;
end;
procedure TSAPMrpAreaStockReader.SetOPOList(aSAPOPOReader2: TSAPOPOReader2);
var
iLine: Integer;
aSAPOPOLine: TSAPOPOLine;
iArea: Integer;
aSAPMrpAREA: TSAPMrpAREA;
begin
for iLine := 0 to aSAPOPOReader2.Count - 1 do
begin
aSAPOPOLine := aSAPOPOReader2.Items[iLine];
for iArea := 0 to Self.Count - 1 do
begin
aSAPMrpAREA := Items[iArea];
aSAPOPOLine.Tag := aSAPMrpAREA;
aSAPMrpAREA.FOPOList.AddObject(aSAPOPOLine.FNumber, aSAPOPOLine);
end;
end;
for iArea := 0 to Self.Count - 1 do
begin
aSAPMrpAREA := Items[iArea];
aSAPMrpAREA.FOPOList.Sort;
QuickSort(aSAPMrpAREA.FOPOList, 0, aSAPMrpAREA.FOPOList.Count - 1, StringListSortCompare_OPO);
// aSAPMrpAREA.FOPOList.CustomSort( StringListSortCompare );
end;
end;
procedure TSAPMrpAreaStockReader.SetStock(aSAPStockReader: TSAPStockReader2);
var
iLine: Integer;
aSAPStockRecordPtr: PSAPStockRecord;
aSAPMrpAREA: TSAPMrpAREA;
idx: Integer;
p: PSAPStockRecord;
sArea: string;
begin
for iLine := 0 to aSAPStockReader.Count - 1 do
begin
aSAPStockRecordPtr := aSAPStockReader.Items[iLine];
if aSAPStockRecordPtr^.snumber = '01.01.1013014' then
begin
Sleep(10);
end;
if aSAPStockRecordPtr^.sstock = 'AM0M' then
begin
Sleep(10);
end;
sArea := MrpAreaOfStockNo( aSAPStockRecordPtr^.sstock );
if sArea = '' then
begin
Log('仓库 ' + aSAPStockRecordPtr^.sstock + ' 没有对应的MRP区域');
Continue;
end;
aSAPMrpAREA := GetSAPMrpAREA(sArea);
if aSAPMrpAREA = nil then
begin
Log( 'mrp area of stock ' + aSAPStockRecordPtr^.sstock + ' not found (TSAPMrpAreaStockReader.SetStock)' );
//raise Exception.Create('mrp area of stock ' + aSAPStockRecordPtr^.sstock + ' not found');
end;
try
idx := aSAPMrpAREA.FSAPStockSum.FList.IndexOf(aSAPStockRecordPtr^.snumber);
if idx < 0 then
begin
p := New(PSAPStockRecord);
p^ := aSAPStockRecordPtr^;
aSAPMrpAREA.FSAPStockSum.FList.AddObject(aSAPStockRecordPtr^.snumber, TObject(p));
end
else
begin
p := PSAPStockRecord(aSAPMrpAREA.FSAPStockSum.FList.Objects[idx]);
p^.dqty := p^.dqty + aSAPStockRecordPtr^.dqty;
end;
except
raise Exception.Create('error');
end;
end;
end;
function TSAPMrpAreaStockReader.AllocStock(const snumber: string; dQty: Double;
const smrparea: string): Double;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
dQtyAlloc: Double;
begin
Result := 0;
// if snumber = '01.01.1013014A' then
// begin
// Sleep(1);
// end;
// aSAPMrpAREA := GetSAPMrpAREA(sMrpArea);
// if aSAPMrpAREA = nil then
// begin
// raise Exception.Create('MRP Area not exists ' + sMrpArea);
// end;
// 不分区域, 有库存就分配。 分配了哪个区域、仓库的库存,记录下来
for i := 0 to Self.Count - 1 do
begin
aSAPMrpAREA := Items[i];
dQtyAlloc := aSAPMrpAREA.FSAPStockSum.Alloc2(sMrpArea, snumber, dQty);
dQty := dQty - dQtyAlloc;
Result := Result + dQtyAlloc;
end;
end;
//只考虑本代工厂库存
function TSAPMrpAreaStockReader.AllocStock2(const snumber: string; dQty: Double;
const smrparea: string): Double;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
dQtyAlloc: Double;
begin
Result := 0;
aSAPMrpAREA := GetSAPMrpAREA(sMrpArea);
if aSAPMrpAREA = nil then
begin
raise Exception.Create('MRP Area not exists ' + sMrpArea);
end;
Result := aSAPMrpAREA.FSAPStockSum.Alloc2(sMrpArea, snumber, dQty);
end;
function TSAPMrpAreaStockReader.AllocStock_area(const snumber, sname: string;
dt: TDateTime; dQty: Double; const smrparea: string; slTransfer: TList): Double;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
aTransferRecordPtr: PTransferRecord;
dAlloc: Double;
begin
Result := 0;
for i := 0 to Self.Count - 1 do
begin
if self.Items[i].sAreaNo = sMrpArea then // 本区域已经分配过了,无需再计算
begin
Continue;
end;
aSAPMrpAREA := self.Items[i];
dAlloc := aSAPMrpAREA.FSAPStockSum.AllocStock_area(snumber, dQty);
if dAlloc > 0 then
begin
aTransferRecordPtr := New(PTransferRecord);
aTransferRecordPtr^.snumber := snumber;
aTransferRecordPtr^.sname := sname;
aTransferRecordPtr^.dt := dt;
aTransferRecordPtr^.sfrom := aSAPMrpAREA.sAreaNo;
aTransferRecordPtr^.sto := smrparea;
aTransferRecordPtr^.dqty := dAlloc;
slTransfer.Add(aTransferRecordPtr);
Result := Result + dAlloc;
end;
end;
end;
function TSAPMrpAreaStockReader.AccDemand(const snumber: string; dQty: Double;
const smrparea: string): Double;
var
aSAPMrpAREA: TSAPMrpAREA;
begin
Result := 0;
aSAPMrpAREA := GetSAPMrpAREA(sMrpArea);
if aSAPMrpAREA = nil then
begin
raise Exception.Create('MRP Area not exists ' + sMrpArea);
end;
Result := aSAPMrpAREA.FSAPStockSum.AccDemand(snumber, dQty);
end;
function ListSortCompare_DateTime_PO(Item1, Item2: Pointer): Integer;
var
p1, p2: TSAPOPOLine;
begin
p1 := TSAPOPOLine(Item1);
p2 := TSAPOPOLine(Item2);
if DoubleG(p1.FDate, p2.FDate) then
Result := 1
else if DoubleL(p1.FDate, p2.FDate) then
Result := -1
else Result := 0;
end;
function TSAPMrpAreaStockReader.Alloc(slNumber: TStringList; dt: TDateTime;
dQty: Double; const sMrpArea: string): Double;
var
aSAPMrpAREA: TSAPMrpAREA;
begin
Result := 0;
aSAPMrpAREA := GetSAPMrpAREA(sMrpArea);
if aSAPMrpAREA = nil then
begin
raise Exception.Create('MRP Area not exists ' + sMrpArea);
end;
Result := aSAPMrpAREA.Alloc(slNumber, dt, dQty);
end;
function TSAPMrpAreaStockReader.GetSAPMrpAREA(const sMrpArea: string): TSAPMrpAREA;
var
i: Integer;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
begin
if self.Items[i].sAreaNo = sMrpArea then
begin
Result := self.Items[i];
Break;
end;
end;
end;
procedure TSAPMrpAreaStockReader.GetOPOs(slNumber: TStringList; lst: TList;
const sMrpArea: string);
var
aSAPMrpAREA: TSAPMrpAREA;
begin
aSAPMrpAREA := GetSAPMrpAREA(sMrpArea);
if aSAPMrpAREA = nil then
begin
raise Exception.Create('TSAPMrpAreaStockReader.GetOPOs mrp area not exists ' + sMrpArea);
end;
aSAPMrpAREA.GetOPOs(slNumber, lst);
end;
function TSAPMrpAreaStockReader.MrpAreaNo2Name(const sMrpAreaNo: string): string;
var
aSAPMrpAREA: TSAPMrpAREA;
begin
Result := '';
if sMrpAreaNo = '' then
begin
Exit;
end;
aSAPMrpAREA := GetSAPMrpAREA(sMrpAreaNo);
// if aSAPMrpAREA = nil then
// begin
// raise Exception.Create('TSAPMrpAreaStockReader.MrpAreaNo2Name mrp area not exists ' + sMrpAreaNo);
// end;
Result := aSAPMrpAREA.sAreaName;
end;
function TSAPMrpAreaStockReader.MrpAreaOfStockNo(const sstock: string): string;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
begin
Result := '';
for i := 0 to self.Count - 1 do
begin
aSAPMrpAREA := Items[i];
if aSAPMrpAREA.FList.IndexOfName(sstock) >= 0 then
begin
Result := aSAPMrpAREA.sAreaNo;
Break;
end;
end;
end;
function TSAPMrpAreaStockReader.GetStockSum(const snumber: string): Double;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
begin
Result := 0;
for i := 0 to self.Count - 1 do
begin
aSAPMrpAREA := Items[i];
Result := Result + aSAPMrpAREA.FSAPStockSum.GetStock(snumber);
end;
end;
function TSAPMrpAreaStockReader.GetOPOSum(const snumber: string): Double;
var
i: Integer;
aSAPMrpAREA: TSAPMrpAREA;
iNumber: Integer;
aSAPOPOLine: TSAPOPOLine;
begin
Result := 0;
for i := 0 to self.Count - 1 do
begin
aSAPMrpAREA := Items[i];
for iNumber := 0 to aSAPMrpAREA.FOPOList.Count - 1 do
begin
if aSAPMrpAREA.FOPOList[iNumber] = snumber then
begin
aSAPOPOLine := TSAPOPOLine(aSAPMrpAREA.FOPOList.Objects[iNumber]);
Result := Result + aSAPOPOLine.FQty;
end;
end;
Break;
end;
end;
function TSAPMrpAreaStockReader.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPMrpAreaStockReader.GetItems(i: Integer): TSAPMrpAREA;
begin
Result := TSAPMrpAREA(FList.Objects[i]);
end;
procedure TSAPMrpAreaStockReader.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
function IndexOfCol(ExcelApp: Variant; irow: Integer; const scol: string): Integer;
var
i: Integer;
s: string;
begin
Result := -1;
for i := 1 to 50 do
begin
s := ExcelApp.Cells[irow, i].Value;
if s = scol then
begin
Result := i;
Break;
end;
end;
end;
procedure TSAPMrpAreaStockReader.Open;
var
iSheetCount, iSheet: Integer;
sSheet: string;
stitle1, stitle2, stitle3, stitle4, stitle5, stitle6: string;
stitle: string;
irow: Integer;
sAreaNo: string;
sMrp: string;
aSAPMrpAREA: TSAPMrpAREA;
sStockNo: string;
sStockName: string;
icolFac: Integer;
icolAreaNo: Integer;
icolAreaName: Integer;
icolStockNo: Integer;
icolStockName: Integer;
icolMrp: Integer;
begin
Clear;
FReadOk := False;
if not FileExists(FFile) then Exit;
ExcelApp := CreateOleObject('Excel.Application' );
ExcelApp.Visible := False;
ExcelApp.Caption := '应用程序调用 Microsoft Excel';
try
WorkBook := ExcelApp.WorkBooks.Open(FFile);
try
iSheetCount := ExcelApp.Sheets.Count;
for iSheet := 1 to iSheetCount do
begin
if not ExcelApp.Sheets[iSheet].Visible then Continue;
ExcelApp.Sheets[iSheet].Activate;
sSheet := ExcelApp.Sheets[iSheet].Name;
Log(sSheet);
irow := 1;
stitle1 := ExcelApp.Cells[irow, 1].Value;
stitle2 := ExcelApp.Cells[irow, 2].Value;
stitle3 := ExcelApp.Cells[irow, 3].Value;
stitle4 := ExcelApp.Cells[irow, 4].Value;
stitle5 := ExcelApp.Cells[irow, 5].Value;
stitle6 := ExcelApp.Cells[irow, 6].Value;
stitle := stitle1 + stitle2 + stitle3 + stitle4 + stitle5 + stitle6;
if (stitle = 'MRP区域MRP区域描述仓库仓库描述')
or (stitle = 'MRP区域MRP区域描述仓库仓库描述是否参于MRP计算') then
begin
icolFac := -1;
icolAreaNo := 1;
icolAreaName := 2;
icolStockNo := 3;
icolStockName := 4;
icolMrp := -1;
end
else if stitle = '工厂库位仓储地点描述MMRP 范围' then
begin
icolFac := 1;
icolAreaNo := 5;
icolAreaName := -1;
icolStockNo := 2;
icolStockName := 3;
icolMrp := -1;
end
else if stitle = '工厂MRP区域MRP区域描述仓库仓储描述是否参与MRP计算' then
begin
icolFac := 1;
icolAreaNo := 2;
icolAreaName := 3;
icolStockNo := 4;
icolStockName := 5;
icolMrp := 6;
end
else
begin
Log(sSheet +' 不是 MRP区域 格式');
Continue;
end;
FReadOk := True;
irow := 2;
sStockNo := ExcelApp.Cells[irow, icolStockNo].Value;
while sStockNo <> '' do
begin
sAreaNo := ExcelApp.Cells[irow, icolAreaNo].Value;
if sAreaNo = '' then
begin
irow := irow + 1;
sStockNo := ExcelApp.Cells[irow, icolStockNo].Value;
Continue;
end;
if icolMrp <> -1 then
begin
sMrp := ExcelApp.Cells[irow, icolMrp].Value;
if sMrp <> 'Y' then
begin
irow := irow + 1;
sStockNo := ExcelApp.Cells[irow, icolStockNo].Value;
Continue;
end;
end;
aSAPMrpAREA := GetSAPMrpAREA( sAreaNo );
if aSAPMrpAREA = nil then
begin
aSAPMrpAREA := TSAPMrpAREA.Create;
aSAPMrpAREA.sAreaNo := sAreaNo;
if icolAreaName <> - 1 then
begin
aSAPMrpAREA.sAreaName := ExcelApp.Cells[irow, icolAreaName].Value;
end
else aSAPMrpAREA.sAreaName := '';
FList.AddObject(sAreaNo, aSAPMrpAREA);
end;
sStockName := ExcelApp.Cells[irow, icolStockName].Value;
aSAPMrpAREA.FList.Add(sStockNo + '=' + sStockName);
irow := irow + 1;
sStockNo := ExcelApp.Cells[irow, icolStockNo].Value;
end;
end;
finally
ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存
WorkBook.Close;
end;
finally
ExcelApp.Visible := True;
ExcelApp.Quit;
end;
end;
end.
|
{*****************************************************************************
* The contents of this file are used with permission, 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 express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*****************************************************************************
*
* This file was created by Mason Wheeler. He can be reached for support at
* tech.turbu-rpg.com.
*****************************************************************************}
unit rsSystemUnit;
interface
uses
TypInfo,
rsDefs;
type
TAddType = reference to procedure(info: PTypeInfo; parent: TUnitSymbol);
const
SYSNAME = 'SYSTEM';
function BuildSysUnit(AddType: TAddType): TUnitSymbol;
implementation
uses
SysUtils, RTTI, Types,
rsImport;
type
TNameHackSymbol = class(TSymbol);
TStringArray = type TStringDynArray;
function BuildSysUnit(AddType: TAddType): TUnitSymbol;
var
ctx: TRttiContext;
rType: TRttiInstanceType;
table: ISymbolTable;
clsType: TExternalClassType;
list: IParamList;
stringType: TTypeSymbol;
fieldSymbol: TSymbol;
realType: TRttiType;
begin
ctx := TRttiContext.Create;
table := CreateSymbolTable(true);
result := TUnitSymbol.Create(SYSNAME, table, table, true);
AddType(typeInfo(boolean), result);
AddType(typeInfo(integer), result);
AddType(typeInfo(string), result);
AddType(typeInfo(TStringArray), result);
realType := ctx.GetType(TypeInfo(extended));
if not NativeTypeDefined(realType) then
AddNativeType(realType, TExternalType.Create(realType));
TNameHackSymbol(TypeOfRttiType(realType)).FName := 'Real';
result.publics.Add('REAL', TypeOfNativeType(typeInfo(extended)));
rType := ctx.GetType(TObject) as TRttiInstanceType;
if not NativeTypeDefined(rType) then
begin
clsType := TExternalClassType.Create(rType);
clsType.AddMethod('CREATE', clsType, mvPublic, false, EmptyParamList);
clsType.AddMethod('FREE', clsType, mvPublic, false, EmptyParamList);
AddNativeType(rType, clsType);
end
else clsType := TypeOfRttiType(rType) as TExternalClassType;
table.Add(UpperCase(rType.Name), clsType);
rType := ctx.GetType(TInterfacedObject) as TRttiInstanceType;
if not NativeTypeDefined(rType) then
begin
clsType := TExternalClassType.Create(rType);
AddNativeType(rType, clsType);
end
else clsType := TypeOfRttiType(rType) as TExternalClassType;
table.Add(UpperCase(rType.Name), clsType);
stringType := TypeOfNativeType(TypeInfo(string));
rType := ctx.GetType(Exception) as TRttiInstanceType;
if not NativeTypeDefined(rType) then
begin
clsType := TExternalClassType.Create(rType);
list := EmptyParamList;
list.Add(TParamSymbol.Create('message', stringType, [pfConst]));
clsType.AddMethod('Create', clsType, mvPublic, false, list);
clsType.AddField('FMessage', stringType, mvPrivate);
fieldSymbol := clsType.SymbolLookup('FMESSAGE');
clsType.AddProp('Message', stringType, mvPublic, false, EmptyParamList, fieldSymbol, fieldSymbol);
AddNativeType(rType, clsType);
end
else clsType := TypeOfRttiType(rType) as TExternalClassType;
table.Add(UpperCase(rType.Name), clsType);
table.Add('CRLF', TConstSymbol.Create('CRLF', #13#10));
if not NativeTypeDefined(nil) then
AddNativeType(nil, TTypeSymbol.Create('NULL*TYPE'));
end;
end.
|
{%RunFlags MESSAGES+}
unit uUsuario;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, db;
type
TUsuario = class
private
fid : integer;
flogin : string;
fnome : string;
fperfil: integer;
fsenha : string;
fativo : string;
public
property id : integer read fid write fid ;
property login : string read flogin write flogin ;
property nome : string read fnome write fnome ;
property perfil: integer read fperfil write fperfil;
property senha : string read fsenha write fsenha ;
property ativo : string read fativo write fativo ;
constructor create(pid : integer;
plogin : string;
pnome : string;
pperfil: integer;
psenha : string;
pativo : string); overload;
constructor create(dataSetUsuario: TDataSet); overload;
procedure setUsuario(pid : integer;
plogin : string;
pnome : string;
pperfil: integer;
psenha : string;
pativo : string); overload;
procedure setUsuario(dataSetUsuario: TDataSet); overload;
end;
implementation
constructor TUsuario.create(pid : integer;
plogin : string;
pnome : string;
pperfil: integer;
psenha : string;
pativo : string);
begin
setUsuario(pid, plogin, pnome, pperfil, psenha, pativo);
end;
constructor TUsuario.create(dataSetUsuario: TDataSet);
begin
setUsuario(dataSetUsuario);
end;
procedure TUsuario.setUsuario(pid : integer;
plogin : string;
pnome : string;
pperfil: integer;
psenha : string;
pativo : string);
begin
fid := pid;
flogin := plogin;
fnome := pnome;
fperfil := pperfil;
fsenha := psenha;
fativo := pativo;
end;
procedure TUsuario.setUsuario(dataSetUsuario: TDataSet);
begin
fid := dataSetUsuario.FieldByName('id').AsInteger;
flogin := dataSetUsuario.FieldByName('login').AsString;
fnome := dataSetUsuario.FieldByName('nome').AsString;
fperfil := dataSetUsuario.FieldByName('fk_perfil_usuario_id').AsInteger;
fsenha := dataSetUsuario.FieldByName('senha').AsString;
fativo := dataSetUsuario.FieldByName('ativo').AsString;
end;
end.
|
unit filethread;
interface
uses
Classes;
type
TFileThread = class(TThread)
private
FVideoFiles: TStringList;
function GetVideoFiles: TStrings;
protected
procedure FileSearch(const PathName, FileName : string; const InDir : boolean);
public
constructor Create(CreateSuspended: Boolean);
procedure Execute; override;
property VideoFiles: TStrings read GetVideoFiles;
destructor Destroy; override;
end;
implementation
uses
sysutils;
destructor TFileThread.Destroy;
begin
FVideoFiles.Free;
end;
constructor TFileThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := false;
FVideoFiles := TStringList.create;
Priority := tpLowest;
end;
function TFileThread.GetVideoFiles: TStrings;
begin
result := FVideoFiles
end;
procedure TFileThread.Execute;
begin
FileSearch(ExtractFilePath(ParamStr(0)), '*.mp4', true);
ReturnValue := 1;
end;
procedure TFileThread.FileSearch(const PathName, FileName : string; const InDir : boolean);
var
Rec : TSearchRec;
Path : string;
begin
Path := IncludeTrailingBackslash(PathName);
if FindFirst(Path + FileName, faAnyFile - faDirectory, Rec) = 0 then
try
repeat
FVideoFiles.Add(Path + Rec.Name);
until FindNext(Rec) <> 0;
finally
SysUtils.FindClose(Rec);
end;
if not InDir then Exit;
if FindFirst(Path + '*.*', faDirectory, Rec) = 0 then
try
repeat
if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name<>'.') and (Rec.Name<>'..') then
FileSearch(Path + Rec.Name, FileName, True);
until FindNext(Rec) <> 0;
finally
SysUtils.FindClose(Rec);
end;
end; //procedure FileSearch
end.
|
unit Clothes.ViewModel;
interface
uses
Data.DB,
System.UITypes, System.SysUtils,
Common.Types,
Clothes.Classes, Clothes.Model, Clothes.DataModule,
FMX.ListBox;
type
TClothesViewModel = class
private
constructor Create; reintroduce;
private
FClothesModel: TClothesModel;
FClothesTypeModel: TClothesTypeModel;
FDataModule: TdmClothes;
FClothesType: TClothesType;
FClothes: TClothes;
function GetClothesTypesDataset: TDataSet;
procedure SetClothes(const Value: TClothes);
procedure SetClothesType(const Value: TClothesType);
public
class function GetInstance: TClothesViewModel;
procedure FillComboBox(AComboBox: TComboBox);
procedure SaveClothes(AClothesType: TClothesType; const SerNo: string);
property ClothesTypesDataset: TDataSet read GetClothesTypesDataset;
procedure AppendClothesTypesDataset;
procedure SaveClothesDataset(AModalResult: TModalResult);
function SaveClothesTypesDataset: TFunctionResult;
property Clothes: TClothes read FClothes write SetClothes;
property ClothesType: TClothesType read FClothesType write SetClothesType;
end;
implementation
var
ViewModel: TClothesViewModel = nil;
{ TClothesViewModel }
procedure TClothesViewModel.AppendClothesTypesDataset;
begin
// dmClothes.cdsClothesTypes.Insert;
end;
constructor TClothesViewModel.Create;
begin
inherited Create;
FClothesModel := TClothesModel.Create;
FClothesTypeModel := TClothesTypeModel.Create;
dmClothes := TdmClothes.Create(nil);
FDataModule := dmClothes;
FClothesType := TClothesType.Create(0, '', 0);
FClothes := TClothes.Create(0, '', '', FClothesType);
end;
procedure TClothesViewModel.FillComboBox(AComboBox: TComboBox);
var
AClothesType: TClothesType;
begin
for AClothesType in FClothesTypeModel.ClothesTypes do
begin
AComboBox.Items.AddObject(AClothesType.Name, AClothesType);
end;
end;
function TClothesViewModel.GetClothesTypesDataset: TDataSet;
begin
Result := dmClothes.cdsClothesTypes;
end;
class function TClothesViewModel.GetInstance: TClothesViewModel;
begin
if ViewModel = nil then
begin
ViewModel := TClothesViewModel.Create;
end;
Result := ViewModel;
end;
procedure TClothesViewModel.SaveClothes(AClothesType: TClothesType;
const SerNo: string);
begin
FClothesModel.SaveToDatabase(AClothesType, SerNo);
end;
procedure TClothesViewModel.SaveClothesDataset(AModalResult: TModalResult);
begin
if AModalResult = mrOk then
begin
FDataModule.SaveClothes(FClothes);
end
else
begin
FDataModule.CancelClothesTypesDataset;
end;
end;
function TClothesViewModel.SaveClothesTypesDataset: TFunctionResult;
begin
try
FDataModule.SaveClothesTypes(FClothesType);
Result.Successful := True;
except
on e: Exception do
begin
FDataModule.CancelClothesTypesDataset;
Result.Successful := False;
Result.MessageOnError := e.Message;
end;
end;
end;
procedure TClothesViewModel.SetClothes(const Value: TClothes);
begin
FClothes := Value;
end;
procedure TClothesViewModel.SetClothesType(const Value: TClothesType);
begin
FClothesType := Value;
end;
initialization
ViewModel := TClothesViewModel.Create;
finalization
if ViewModel <> nil then
begin
ViewModel.Free;
ViewModel := nil;
end;
end.
|
unit EditExts;
(***** Code Written By Huang YanLai *****)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs,StdCtrls,ExtCtrls;
type
{ keys:
'0'..'9','+','-','.'
back,delete : 删除最后一个字符
shift+delete : 清空
deleteChar : 删除最后一个字符
ClearChar : 清空
}
TDigitalEdit = class(TCustomControl)
private
FAllowPoint: boolean;
FAllowNegative: boolean;
FUserSeprator: boolean;
FOnChange: TNotifyEvent;
FReadOnly: boolean;
FDeleteChar: char;
FRedNegative: boolean;
FNegativeColor: TColor;
FMaxIntLen: integer;
FPrecision: integer;
FClearChar: char;
FLeading: string;
FBorderStyle: TBorderStyle;
FErrorBeep: boolean;
FAutoselect:boolean; //add
Ftextbackground:TColor; //add
Fframebackground:TColor; //add
{ Private declarations }
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure SetUserSeprator(const Value: boolean);
procedure WMSetFocus(var Message:TWMSetFocus); message WM_SetFocus;
procedure WMKillFocus(var Message:TWMKillFocus); message WM_KillFocus;
procedure HandleDelete;
procedure SetNegativeColor(const Value: TColor);
procedure SetRedNegative(const Value: boolean);
procedure Settextbackground(const Value: TColor); //add
procedure Setframebackground(const Value: TColor); //add
procedure SetLeading(const Value: string);
procedure SetBorderStyle(const Value: TBorderStyle);
procedure UpdateHeight;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
protected
{ Protected declarations }
procedure Paint; override;
procedure PaintBorder(var R:TRect); dynamic;
procedure PaintText(var R:TRect); dynamic;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
//procedure KeyUp(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override; //modify
function acceptKey(key:char):boolean; dynamic;
procedure HandleKey(Key:char); dynamic;
procedure Change; dynamic;
function CanAddDigital(const AText:string): boolean; dynamic;
procedure AdjustSize; override;
procedure Loaded; override;
procedure DoDrawText(var Rect: TRect); dynamic; //add
procedure DoDrawRect; //add
procedure DeleteDrawRect(var Rect: TRect); //add
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
function GetDisplayText : string; dynamic;
procedure Clear;
published
{ Published declarations }
property AllowPoint : boolean read FAllowPoint write FAllowPoint default false;
property AllowNegative : boolean read FAllowNegative write FAllowNegative default false;
property UserSeprator : boolean read FUserSeprator write SetUserSeprator default false;
property ReadOnly : boolean read FReadOnly write FReadOnly default false;
property DeleteChar : char read FDeleteChar write FDeleteChar default #0;
property ClearChar : char read FClearChar write FClearChar default #0;
property RedNegative : boolean read FRedNegative write SetRedNegative default false;
property NegativeColor : TColor read FNegativeColor write SetNegativeColor default clRed;
property Precision : integer read FPrecision write FPrecision default -1;
property MaxIntLen : integer read FMaxIntLen write FMaxIntLen default -1;
property Leading : string read FLeading write SetLeading;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property ErrorBeep : boolean read FErrorBeep write FErrorBeep default false;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
property AutoSelect: boolean read FAutoselect write FAutoselect default false; //add
property FrameBackground: TColor read Fframebackground write Setframebackground default clNavy;//add
property TextBackground:TColor read Ftextbackground write Settextbackground default clwhite; //add
property Anchors;
//property AutoSelect;
property AutoSize default true;
property BiDiMode;
//property BorderStyle;
//property CharCase;
property Color default clWhite;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
//property HideSelection;
property ImeMode;
property ImeName;
//property MaxLength;
//property OEMConvert;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
//property PasswordChar;
property PopupMenu;
//
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
var
station:boolean;
implementation
procedure Register;
begin
RegisterComponents('UserCtrls', [TDigitalEdit]);
end;
{ TDigitalEdit }
constructor TDigitalEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 121;
Height := 25;
TabStop := True;
ParentColor := False;
Text:='0';
AutoSize:=true;
FAllowPoint:=false;
FAllowNegative:=false;
FUserSeprator:=false;
FReadOnly := false;
FDeleteChar := #0;
FClearChar := #0;
FRedNegative := false;
FNegativeColor := clRed;
FPrecision:=-1;
FMaxIntLen:=-1;
FBorderStyle:=bsSingle;
FErrorBeep := false;
Ftextbackground:=clwhite;
Fframebackground:=clNavy;
end;
function TDigitalEdit.acceptKey(key: char): boolean;
begin
result := not ReadOnly and
(
(key in ['0'..'9',char(VK_Back),DeleteChar,ClearChar]) or
( (key in ['+','-']) and AllowNegative) or
( (key='.') and AllowPoint)
);
end;
procedure TDigitalEdit.HandleKey(Key: char);
var
l : integer;
AText : string;
begin
if key=#0 then exit;
AText := text;
l := length(AText);
if (key=char(VK_Back)) or ((key=DeleteChar)) then
begin
//if l>0 then text:=Copy(AText,1,l-1);
HandleDelete;
end
else if key=ClearChar then Clear
else if key in ['0'..'9'] then
begin
if AText='0' then
Text:=key
else if CanAddDigital(AText) then
begin
text:=Atext+key;
end;
end
else if (key in ['+','-']) and (l>0) then
begin
{if AText[1]='-' then
delete(AText,1,1);
if (key='-') and (AText<>'0') then AText:='-'+AText;}
if AText[1]='-' then
// no matter when key='+' or key='-'
delete(AText,1,1)
else if (key='-') and (AText<>'0') then
// positive to negative
AText:='-'+AText;
Text:=AText;
end
else if (key='.') and (pos('.',AText)<=0) then
Text:=AText+'.';
end;
procedure TDigitalEdit.KeyPress(var Key: Char);
var
AText : string;
begin
inherited KeyPress(Key);
AText := Text;
//begin add
if AText='0' then
begin
if acceptKey(Key) then
begin
HandleKey(Key);
Key := #0;
end
else if ErrorBeep then Beep;
end
else
if station then
begin
paint;
text:='0';
station:=false;
if acceptKey(Key) then
begin
HandleKey(Key);
Key := #0;
end
else if ErrorBeep then Beep;
end
else
if AText<>'0' then
begin
if acceptKey(Key) then
begin
HandleKey(Key);
Key := #0;
end
else if ErrorBeep then Beep;
end
//end add
end;
procedure TDigitalEdit.Paint;
var
r : TRect;
begin
HideCaret(Handle);
r := GetClientRect;
PaintBorder(r);
InflateRect(r,-1,-1);
PaintText(r);
ShowCaret(Handle);
end;
procedure TDigitalEdit.PaintBorder(var R:TRect);
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(r);
if BorderStyle=bsSingle then
if Ctl3D then
Frame3D(Canvas,r,clBlack,clBtnHighlight,2)
else Frame3D(Canvas,r,clBlack,clBlack,1);
end;
procedure TDigitalEdit.PaintText(var R:TRect);
var
AText : string;
begin
Canvas.Font := Font;
if RedNegative then
begin
AText := Text;
if (length(AText)>0) and (AText[1]='-') then
Canvas.Font.Color := NegativeColor;
end;
WINDOWS.DrawText(Canvas.handle,pchar(FLeading),-1,R,
DT_Left or DT_SINGLELINE or DT_VCENTER );
WINDOWS.DrawText(Canvas.handle,pchar(GetDisplayText),-1,R,
DT_RIGHT or DT_SINGLELINE or DT_VCENTER );
end;
function TDigitalEdit.GetDisplayText: string;
var
i,l : integer;
AText : string;
PositivePart,NegativePart : string;
Negativechar : char;
begin
AText :=text;
if (AText='') or not UserSeprator then
result := Atext
else
begin
if AText[1] in ['-','+'] then
begin
Negativechar:=AText[1];
delete(Atext,1,1);
end
else
begin
Negativechar:=#0;
end;
i:=pos('.',Atext);
if i>0 then
begin
PositivePart := copy(AText,1,i-1);
NegativePart := copy(AText,i,length(Atext)-i+1);
end
else
begin
PositivePart := AText;
NegativePart := '';
end;
result := NegativePart;
l := length(PositivePart);
for i:=0 to l-1 do
begin
result := PositivePart[l-i]+result;
if ( ((i+1) mod 3)=0 ) and (i<>l-1) then
result := ','+result;
end;
if Negativechar<>#0 then result := Negativechar+result;
end;
end;
procedure TDigitalEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
Change;
end;
procedure TDigitalEdit.WMLButtonDown(var Message: TWMLButtonDown);
begin
inherited;
if CanFocus then SetFocus;
end;
procedure TDigitalEdit.SetUserSeprator(const Value: boolean);
begin
if FUserSeprator <> Value then
begin
FUserSeprator := Value;
Invalidate;
end;
end;
procedure TDigitalEdit.Change;
begin
if assigned(FOnChange) then FOnChange(self);
Invalidate;
end;
procedure TDigitalEdit.WMKillFocus(var Message: TWMKillFocus);
var
r:TRect;
begin
inherited ;
DestroyCaret;
DeleteDrawRect(r);
paint;
end;
procedure TDigitalEdit.WMSetFocus(var Message: TWMSetFocus);
var
atext : string;
r : TRect;
begin
inherited ;
atext := text;
r := GetClientRect;
//begin add
if FAutoselect then
begin
if atext<>'0'then
begin
DoDrawText(r);
CreateCaret(Handle, 0, 2, abs(Font.Height));
SetCaretPos(width-4,(Height-abs(Font.Height))div 2);
ShowCaret(handle);
end
else
begin
CreateCaret(Handle, 0, 2, abs(Font.Height));
SetCaretPos(width-4,(Height-abs(Font.Height))div 2);
ShowCaret(handle);
end
end
else
CreateCaret(Handle, 0, 2, abs(Font.Height));
SetCaretPos(width-4,(Height-abs(Font.Height))div 2);
ShowCaret(handle);
//end add
end;
procedure TDigitalEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key,Shift);
if (key=VK_Delete) and not ReadOnly then
begin
if not (ssShift in Shift) then HandleDelete
else Clear;
end;
end;
procedure TDigitalEdit.HandleDelete;
var
AText : string;
l : integer;
begin
AText := text;
l := length(AText);
if l>0 then Atext:=Copy(AText,1,l-1);
if (AText='') or (AText='-') or (AText='+') then
AText:='0';
Text:=AText;
end;
procedure TDigitalEdit.SetNegativeColor(const Value: TColor);
begin
if FNegativeColor <> Value then
begin
FNegativeColor := Value;
if RedNegative then
Invalidate;
end;
end;
procedure TDigitalEdit.SetRedNegative(const Value: boolean);
begin
if FRedNegative <> Value then
begin
FRedNegative := Value;
Invalidate;
end;
end;
//begin add
procedure TDigitalEdit.Settextbackground(const Value: TColor);
begin
if Ftextbackground <> Value then
begin
Ftextbackground:= Value;
Invalidate;
end;
end;
procedure TDigitalEdit.Setframebackground(const Value: TColor);
begin
if Fframebackground <> Value then
begin
Fframebackground:= Value;
Invalidate;
end;
end;
//end add
function TDigitalEdit.CanAddDigital(const AText: string): boolean;
var
i,l : integer;
begin
l:=length(AText);
i:=pos('.',Atext);
if i>0 then
begin
// after point
result := (Precision<0) or (l-i<Precision);
end
else
begin
// before point
result := (MaxIntLen<0) or (l=0) or (l<MaxIntLen)
or ((Atext[1]='-') and (l-1<MaxIntLen));
end;
end;
procedure TDigitalEdit.Clear;
begin
Text:='0';
end;
procedure TDigitalEdit.SetLeading(const Value: string);
begin
if FLeading <> Value then
begin
FLeading := Value;
Invalidate;
end;
end;
procedure TDigitalEdit.SetBorderStyle(const Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
if AutoSize then UpdateHeight
else invalidate;
end;
end;
const
Margin = 1;
procedure TDigitalEdit.UpdateHeight;
var
Delta : integer;
begin
if not (csLoading in ComponentState) then
begin
if BorderStyle=bsNone then
Delta:=0
else if Ctl3D then
Delta:=2*2
else Delta:=2*1;
//Height := abs(Font.Height)+Delta+2*Margin;
SetBounds(Left, Top, Width, abs(Font.Height)+Delta+2*Margin);
end;
end;
procedure TDigitalEdit.AdjustSize;
begin
UpdateHeight;
end;
procedure TDigitalEdit.CMFontChanged(var Message: TMessage);
begin
Inherited;
if AutoSize then UpdateHeight;
end;
procedure TDigitalEdit.CMCtl3DChanged(var Message: TMessage);
begin
inherited;
if AutoSize then UpdateHeight;
end;
procedure TDigitalEdit.Loaded;
begin
inherited Loaded;
if AutoSize then UpdateHeight;
end;
//begin add
procedure TDigitalEdit.DoDrawText(var Rect: TRect);
var
Text: string;
begin
DoDrawRect;
Text := GetDisplayText;
Canvas.Font := Font;
OffsetRect(Rect, 1, 1);
Canvas.Font.Color := Ftextbackground;
DrawText(Canvas.Handle, PChar(Text), Length(Text)+1, Rect,
DT_Right or DT_SINGLELINE or DT_VCENTER);
end;
procedure TDigitalEdit.DoDrawRect;
var
X, Y: Integer;
begin
X:= Width - Length(text);
Y:= (Height - abs(font.Height))div 2;
Canvas.brush.Color:=Fframebackground;
Rectangle(canvas.Handle,X,Y,X+Length(text),Y+abs(font.Height));
station:=true;
end;
procedure TDigitalEdit.DeleteDrawRect(var Rect: TRect);
begin
canvas.Brush.color:=clwhite;
FillRect(canvas.Handle,Rect,brush.handle);
end;
//end add
end.
|
unit TrackPainter;
interface
uses Graphics, Types;
// *************** TLines ***************
type TLine = record
X1 : integer;
Y1 : integer;
X2 : integer;
Y2 : integer;
end;
type PLine = ^TLine;
type TLines = class
protected
Lines : array of TLine;
Count : integer;
public
procedure Clear;
procedure AddLine( X1, Y1, X2, Y2 : integer );
procedure Paint( Canvas : TCanvas; OffsetX, OffsetY : integer );
end;
// *************** TLinesWide ***************
type TLineWide = record
X1 : integer;
Y1 : integer;
X2 : integer;
Y2 : integer;
Width : integer;
end;
PLineWide = ^TLineWide;
type TLinesWide = class
protected
Lines : array of TLineWide;
Count : integer;
public
procedure Clear;
procedure AddLine( X1, Y1, X2, Y2, Width : integer );
procedure Paint( Canvas : TCanvas; OffsetX, OffsetY : integer );
end;
// *************** THoles ***************
type THole = record
X : integer;
Y : integer;
end;
PHole = ^THole;
type THoles = class
protected
Holes : array of THole;
Count : integer;
public
procedure Clear;
procedure AddHole( X1, Y1 : integer );
procedure Paint( Canvas : TCanvas; OffsetX, OffsetY, Radius : integer );
end;
type TteTrackEditPainter = class
protected
// objects store primitives to be painted
FTrackLines : TLines;
FSegmentLines : TLinesWide;
FBoardHoles : THoles;
// drawing settings
FPixelsPerCell : integer;
FStripColor : TColor;
FStripWidth1000 : integer;
FStripsVisible : boolean;
FHolesVisible : boolean;
FHoleColor : TColor;
FHoleOutlineColor : TColor;
FHoleDiameter1000 : integer;
public
// draw stuff with board offset given by pixels
LeftX : integer;
TopY : integer;
XOR_Mode : boolean;
// track items add primitives here
property TrackLines : TLines read FTrackLines;
property SegmentLines : TLinesWide read FSegmentLines;
property BoardHoles : THoles read FBoardHoles;
// appearance
property PixelsPerCell : integer read FPixelsPerCell write FPixelsPerCell;
property StripColor : TColor read FStripColor write FStripColor;
property StripWidth1000 : integer read FStripWidth1000 write FStripWidth1000;
property StripsVisible : boolean read FStripsVisible write FStripsVisible;
property HolesVisible : boolean read FHolesVisible write FHolesVisible;
property HoleColor : TColor read FHoleColor write FHoleColor;
property HoleOutlineColor : TColor read FHoleOutlineColor write FHoleOutlineColor;
property HoleDiameter1000 : integer read FHoleDiameter1000 write FHoleDiameter1000;
procedure Clear;
// draw entire board on Bitmap - using current appearance properties
// if necessary, resizing bitmap to suit
procedure Paint( Canvas : TCanvas );
constructor Create;
destructor Destroy; override;
end;
implementation
// ****************************************
// TLines - Standard Width Strips
// ****************************************
procedure TLines.Clear;
begin
Count := 0;
end;
procedure TLines.AddLine( X1, Y1, X2, Y2 : integer );
var
P : PLine;
begin
// make room in dynamic array if needed
if Count >= Length( Lines ) then begin
SetLength( Lines, Count + 200 );
end;
// store Line details in next array element
P := @(Lines[Count]);
P^.X1 := X1;
P^.Y1 := Y1;
P^.X2 := X2;
P^.Y2 := Y2;
// count item addes
Inc( Count );
end;
procedure TLines.Paint( Canvas : TCanvas; OffsetX, OffsetY : integer );
var
i : integer;
LineP : PLine;
begin
for i := 0 to Count -1 do begin
LineP := @Lines[i];
Canvas.MoveTo( LineP^.X1 + OffsetX, LineP^.Y1 + OffsetY );
Canvas.LineTo( LineP^.X2 + OffsetX, LineP^.Y2 + OffsetY );
end;
end;
// *****************************************
// TLinesWide - Definable Width Segments
// *****************************************
procedure TLinesWide.Clear;
begin
Count := 0;
end;
procedure TLinesWide.AddLine( X1, Y1, X2, Y2, Width : integer );
var
P : PLineWide;
begin
// make room in dynamic array if needed
if Count >= Length( Lines ) then begin
SetLength( Lines, Count + 200 );
end;
// store Line details in next array element
P := @(Lines[Count]);
P^.X1 := X1;
P^.Y1 := Y1;
P^.X2 := X2;
P^.Y2 := Y2;
P^.Width := Width;
// count item addes
Inc( Count );
end;
procedure TLinesWide.Paint( Canvas : TCanvas; OffsetX, OffsetY : integer );
var
i : integer;
LineP : PLineWide;
begin
for i := 0 to Count -1 do begin
LineP := @Lines[i];
Canvas.Pen.Width := LineP^.Width;
Canvas.MoveTo( LineP^.X1 + OffsetX, LineP^.Y1 + OffsetY );
Canvas.LineTo( LineP^.X2 + OffsetX, LineP^.Y2 + OffsetY );
end;
end;
// ********************************************
// THoles - Standard Radius Holes
// ********************************************
procedure THoles.Clear;
begin
Count := 0;
end;
procedure THoles.AddHole( X1, Y1 : integer );
var
P : PHole;
begin
// make room in dynamic array if needed
if Count >= Length( Holes ) then begin
SetLength( Holes, Count + 200 );
end;
// store Line details in next array element
P := @(Holes[Count]);
P^.X := X1;
P^.Y := Y1;
// count item addes
Inc( Count );
end;
procedure THoles.Paint( Canvas : TCanvas; OffsetX, OffsetY, Radius : integer );
var
i : integer;
HoleP : PHole;
begin
for i := 0 to Count -1 do begin
HoleP := @Holes[i];
Canvas.Ellipse(
HoleP^.X - Radius + OffsetX, HoleP^.Y - Radius + OffsetY,
HoleP^.X + Radius + OffsetX, HoleP^.Y + Radius + OffsetY );
end;
end;
// *****************************************
// TRACK PAINTER
// *****************************************
constructor TteTrackEditPainter.Create;
begin
// objects store primitives to be painted
FTrackLines := TLines.Create;
FSegmentLines := TLinesWide.Create;
FBoardHoles := THoles.Create;
FPixelsPerCell := 20;
FStripColor := $E0E0E0; // light grey
FStripWidth1000 := 500; // half width
FStripsVisible := True;
FHolesVisible := True;
FHoleDiameter1000 := 167; // 1/6th of a cell
FHoleColor := clWhite;
FHoleOutlineColor := clWhite;
end;
destructor TteTrackEditPainter.Destroy;
begin
FTrackLines.Free;
FSegmentLines.Free;
FBoardHoles.Free;
inherited;
end;
procedure TteTrackEditPainter.Clear;
begin
FTrackLines.Clear;
FSegmentLines.Clear;
FBoardHoles.Clear;
end;
procedure TteTrackEditPainter.Paint( Canvas : TCanvas );
var
StripWidthPixels : integer;
HoleRadius : integer;
begin
// draw strips as lines on top of board background
Canvas.Pen.Style := psSolid;
StripWidthPixels := (StripWidth1000 * FPixelsPerCell) div 1000;
Canvas.Pen.Width := StripWidthPixels;
if XOR_Mode then begin
Canvas.Pen.Mode := pmXOR;
end
else begin
Canvas.Pen.Mode := pmCopy;
end;
Canvas.Pen.Color := FStripColor;
TrackLines.Paint( Canvas, -LeftX, -TopY );
// draw segments as lines on top of board background
SegmentLines.Paint( Canvas, -LeftX, -TopY );
// if not XOR_Mode then begin
// draw board holes
// Canvas.Pen.Mode := pmCopy;
Canvas.Pen.Color := HoleColor;
Canvas.Pen.Width := 1;
Canvas.Brush.Color := HoleOutlineColor;
HoleRadius := ((HoleDiameter1000 * FPixelsPerCell) div 2000) +1;
BoardHoles.Paint( Canvas, -LeftX, -TopY, HoleRadius );
// end;
end;
(*
procedure TteTrackEditPainter.Paint( Canvas : TCanvas; Board : TbeTracks );
var
PixelsWidth : integer;
PixelsHeight : integer;
StripWidth : integer;
// InterStripWidth : integer;
TopStripY : integer;
LeftStripX : integer;
i : integer;
Item : TbeTrack;
Strip : TteStrip;
Segment : TteSegment;
x,y : integer;
StripX, StripY : integer;
HoleDiam, HoleRadius : integer;
begin
// * defined patterns get drawn using Board.StripSets *
// calculate TPaintbox or TCustomControl dimensions : 2 extra pixels for border
PixelsWidth := (Board.Width * FPixelsPerCell) +2;
PixelsHeight := (Board.Height * FPixelsPerCell) +2;
// calculate common parameters
StripWidth := (FPixelsPerCell * FStripWidth1000) div 1000;
TopStripY := FPixelsPerCell div 2;
LeftStripX := TopStripY;
// draw board
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := FBoardColor;
Canvas.FillRect( Rect(0, 0, PixelsWidth, PixelsHeight ) );
// draw strips and segments
if FStripsVisible then begin
// draw strips as lines on top of board background
Canvas.Pen.Style := psSolid;
Canvas.Pen.Width := StripWidth;
Canvas.Pen.Mode := pmCopy;
// XOR reveals how tracks drawn : make this a menu item, just for
// editor use - Editor.XORMode := True - property sets a XORMode in
// Editor.Board. Or just do Editor.Board.XORMode := True etc. Use
// menu item that has checkmark
// Canvas.Pen.Mode := pmXOR;
Canvas.Pen.Color := FStripColor;
for i := 0 to Board.Count - 1 do begin
Item := Board.Items[i];
if Item is TteStrip then begin
Strip := TteStrip(Item);
Canvas.MoveTo(
(Strip.Start.X * FPixelsPerCell) + LeftStripX - LeftX,
(Strip.Start.Y * FPixelsPerCell) + TopStripY - TopY );
Canvas.LineTo(
(Strip.Finish.X * FPixelsPerCell) + LeftStripX - LeftX,
(Strip.Finish.Y * FPixelsPerCell) + TopStripY -TopY );
end;
end;
// Draw segments (non-strip) copper segments, for display only
// 500 offset is half a cell - moves segments onto the centre of cell
// coords used by strips
for i := 0 to Board.Count - 1 do begin
Item := Board.Items[i];
if Item is TteSegment then begin
Segment := TteSegment(Item);
Canvas.Pen.Width := (PixelsPerCell * Segment.Width_1000) div 1000;
Canvas.MoveTo(
((Segment.Start_1000.X + 500) * FPixelsPerCell) div 1000 - LeftX,
((Segment.Start_1000.Y + 500) * FPixelsPerCell) div 1000 - TopY
);
Canvas.LineTo(
((Segment.Finish_1000.X + 500) * FPixelsPerCell) div 1000 - LeftX,
((Segment.Finish_1000.Y + 500) * FPixelsPerCell) div 1000 - TopY
);
end;
end;
end;
// draw holes
if FHolesVisible then begin
// ellipse is outlined using Pen, and filled fsBrush.
Canvas.Pen.Style := psDot;
Canvas.Pen.Width := 1;
Canvas.Pen.Mode := pmCopy;
Canvas.Pen.Color := FHoleOutlineColor;
Canvas.Brush.Color := FHoleColor;
HoleDiam := ( FPixelsPerCell * FHoleDiameter1000 ) div 1000;
HoleRadius := ( FPixelsPerCell * FHoleDiameter1000 ) div 2000;
// draw holes in all strips
for i := 0 to Board.Count - 1 do begin
Item := Board.Items[i];
if Item is TteStrip then begin
Strip := TteStrip(Item);
// coords of top or left hole
StripX := (Strip.Start.X * FPixelsPerCell) +
LeftStripX - HoleRadius -LeftX;
StripY := (Strip.Start.Y * FPixelsPerCell) +
TopStripY - HoleRadius -TopY ;
// horizontal
if Strip.IsHorizontal then begin
for x := Strip.Start.X to Strip.Finish.X do begin
Canvas.Ellipse(
StripX, StripY,
StripX + HoleDiam +1, StripY + HoleDiam +1);
Inc( StripX, FPixelsPerCell );
end;
end
// vertical
else begin
for y := Strip.Start.Y to Strip.Finish.Y do begin
Canvas.Ellipse(
StripX, StripY,
StripX + HoleDiam +1, StripY + HoleDiam +1);
Inc( StripY, FPixelsPerCell );
end;
end;
end;
end;
end;
end;
*)
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Messaging.Message;
interface
uses
System.Classes, System.SysUtils, System.Rtti,
WiRL.Core.JSON;
type
TWiRLMessage = class
private
FCreationDateTime: TDateTime;
public
constructor Create(); virtual;
procedure Assign(ASource: TWiRLMessage); virtual;
function ToJSON: TJSONObject; virtual;
property CreationDateTime: TDateTime read FCreationDateTime;
end;
TWiRLCustomMessage = class(TWiRLMessage)
private
public
class function Clone<T: TWiRLMessage, constructor>(ASource: T): T;
end;
TWiRLStringMessage = class(TWiRLCustomMessage)
private
FValue: string;
public
constructor Create(const AValue: string); reintroduce;
procedure Assign(ASource: TWiRLMessage); override;
function ToJSON: TJSONObject; override;
property Value: string read FValue write FValue;
end;
TWiRLJSONObjectMessage = class(TWiRLCustomMessage)
private
FValue: TJSONObject;
procedure SetValue(const AValue: TJSONObject);
public
constructor Create(AValue: TJSONObject); reintroduce;
destructor Destroy; override;
procedure Assign(ASource: TWiRLMessage); override;
function ToJSON: TJSONObject; override;
property Value: TJSONObject read FValue write SetValue;
end;
implementation
uses
System.DateUtils,
WiRL.Core.Utils;
{ TWiRLMessage }
procedure TWiRLMessage.Assign(ASource: TWiRLMessage);
begin
FCreationDateTime := ASource.FCreationDateTime;
end;
constructor TWiRLMessage.Create();
begin
inherited Create;
FCreationDateTime := Now;
end;
function TWiRLMessage.ToJSON: TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('MessageType', ClassName);
Result.AddPair('CreationDateTime', DateToISO8601(CreationDateTime));
end;
{ TWiRLCustomMessage }
class function TWiRLCustomMessage.Clone<T>(ASource: T): T;
begin
Result := T.Create;
Result.Assign(ASource);
end;
{ TWiRLStringMessage }
procedure TWiRLStringMessage.Assign(ASource: TWiRLMessage);
begin
inherited;
if ASource is TWiRLStringMessage then
Self.FValue := TWiRLStringMessage(ASource).FValue;
end;
constructor TWiRLStringMessage.Create(const AValue: string);
begin
inherited Create;
FValue := AValue;
end;
function TWiRLStringMessage.ToJSON: TJSONObject;
begin
Result := inherited ToJSON;
Result.AddPair('Value', Value);
end;
{ TWiRLJSONObjectMessage }
procedure TWiRLJSONObjectMessage.Assign(ASource: TWiRLMessage);
begin
inherited;
if ASource is TWiRLJSONObjectMessage then
begin
Value := TWiRLJSONObjectMessage(ASource).Value;
end;
end;
constructor TWiRLJSONObjectMessage.Create(AValue: TJSONObject);
begin
inherited Create;
Value := AValue;
end;
destructor TWiRLJSONObjectMessage.Destroy;
begin
FValue.Free;
inherited;
end;
procedure TWiRLJSONObjectMessage.SetValue(const AValue: TJSONObject);
begin
if FValue <> AValue then
FValue := AValue.Clone as TJSONObject;
end;
function TWiRLJSONObjectMessage.ToJSON: TJSONObject;
begin
Result := inherited ToJSON;
Result.AddPair('Value', Value);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.