text stringlengths 14 6.51M |
|---|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmMsgList
Purpose : To provide a simple method of identifying window messages or even
control messages.
Date : 11-13-1999
Author : Ryan J. Mills
Version : 1.92
Notes : This code was originally given to me by Daniel Parnell, and I've
continued to add to it.
================================================================================}
unit rmMSGList;
interface
{$I CompilerDefines.INC}
uses Messages;
type
TrmMsgEvent = procedure(Message:TMessage) of object;
function GetMessageName(Msg: Integer): string;
implementation
uses
SysUtils, Classes;
var
MsgList: TStringList;
function GetMessageName (Msg: Integer): string;
var
N: Integer;
begin
N := MsgList.IndexOfObject (TObject(Msg));
if N >= 0 then
Result := MsgList.Strings [N]
else if (Msg >= wm_User) and
(Msg <= $7FFF) then
Result := Format (
'wm_User message (%d)', [Msg])
else
Result := Format (
'Undocumented (%d)', [Msg]);
end;
initialization
MsgList := TStringList.Create;
MsgList.AddObject ('wm_Null', TObject($0000));
MsgList.AddObject ('wm_Create', TObject($0001));
MsgList.AddObject ('wm_Destroy', TObject($0002));
MsgList.AddObject ('wm_Move', TObject($0003));
MsgList.AddObject ('wm_Size', TObject($0005));
MsgList.AddObject ('wm_Activate', TObject($0006));
MsgList.AddObject ('wm_SetFocus', TObject($0007));
MsgList.AddObject ('wm_KillFocus', TObject($0008));
MsgList.AddObject ('wm_Enable', TObject($000A));
MsgList.AddObject ('wm_SetRedraw', TObject($000B));
MsgList.AddObject ('wm_SetText', TObject($000C));
MsgList.AddObject ('wm_GetText', TObject($000D));
MsgList.AddObject ('wm_GetTextLength', TObject($000E));
MsgList.AddObject ('wm_Paint', TObject($000F));
MsgList.AddObject ('wm_Close', TObject($0010));
MsgList.AddObject ('wm_QueryEndSession', TObject($0011));
MsgList.AddObject ('wm_Quit', TObject($0012));
MsgList.AddObject ('wm_QueryOpen', TObject($0013));
MsgList.AddObject ('wm_EraseBkGnd', TObject($0014));
MsgList.AddObject ('wm_SysColorChange', TObject($0015));
MsgList.AddObject ('wm_EndSession', TObject($0016));
MsgList.AddObject ('wm_SystemError', TObject($0017));
MsgList.AddObject ('wm_ShowWindow', TObject($0018));
MsgList.AddObject ('wm_CtlColor', TObject($0019));
MsgList.AddObject ('wm_WinIniChange', TObject($001A));
MsgList.AddObject ('wm_DevModeChange', TObject($001B));
MsgList.AddObject ('wm_ActivateApp', TObject($001C));
MsgList.AddObject ('wm_FontChange', TObject($001D));
MsgList.AddObject ('wm_TimeChange', TObject($001E));
MsgList.AddObject ('wm_CancelMode', TObject($001F));
MsgList.AddObject ('wm_SetCursor', TObject($0020));
MsgList.AddObject ('wm_MouseActivate', TObject($0021));
MsgList.AddObject ('wm_ChildActivate', TObject($0022));
MsgList.AddObject ('wm_QueueSync', TObject($0023));
MsgList.AddObject ('wm_GetMinMaxInfo', TObject($0024));
MsgList.AddObject ('wm_PaintIcon', TObject($0026));
MsgList.AddObject ('wm_IconEraseBkGnd', TObject($0027));
MsgList.AddObject ('wm_NextDlgCtl', TObject($0028));
MsgList.AddObject ('wm_SpoolerStatus', TObject($002A));
MsgList.AddObject ('wm_DrawItem', TObject($002B));
MsgList.AddObject ('wm_MeasureItem', TObject($002C));
MsgList.AddObject ('wm_DeleteItem', TObject($002D));
MsgList.AddObject ('wm_VKeyToItem', TObject($002E));
MsgList.AddObject ('wm_CharToItem', TObject($002F));
MsgList.AddObject ('wm_SetFont', TObject($0030));
MsgList.AddObject ('wm_GetFont', TObject($0031));
MsgList.AddObject ('wm_SetHotKey', TObject($0032));
MsgList.AddObject ('wm_GetHotKey', TObject($0033));
MsgList.AddObject ('wm_QueryDragIcon', TObject($0037));
MsgList.AddObject ('wm_CompareItem', TObject($0039));
MsgList.AddObject ('wm_Compacting', TObject($0041));
MsgList.AddObject ('wm_CommNotify', TObject($0044));
MsgList.AddObject ('wm_WindowPosChanging', TObject($0046));
MsgList.AddObject ('wm_WindowPosChanged', TObject($0047));
MsgList.AddObject ('wm_Power', TObject($0048));
MsgList.AddObject ('wm_CopyData', TObject($004A));
MsgList.AddObject ('wm_CancelJournal', TObject($004B));
MsgList.AddObject ('wm_Notify', TObject($004E));
MsgList.AddObject ('wm_InputLangChangeRequest', TObject($0050));
MsgList.AddObject ('wm_InputLangChange', TObject($0051));
MsgList.AddObject ('wm_tCard', TObject($0052));
MsgList.AddObject ('wm_Help', TObject($0053));
MsgList.AddObject ('wm_UserChanged', TObject($0054));
MsgList.AddObject ('wm_NotifyFormat', TObject($0055));
MsgList.AddObject ('wm_ContextMenu', TObject($007B));
MsgList.AddObject ('wm_StyleChanging', TObject($007C));
MsgList.AddObject ('wm_StyleChanged', TObject($007D));
MsgList.AddObject ('wm_DisplayChange', TObject($007E));
MsgList.AddObject ('wm_GetIcon', TObject($007F));
MsgList.AddObject ('wm_SetIcon', TObject($0080));
MsgList.AddObject ('wm_NCCreate', TObject($0081));
MsgList.AddObject ('wm_NCDestroy', TObject($0082));
MsgList.AddObject ('wm_NCCalcSize', TObject($0083));
MsgList.AddObject ('wm_NCHitTest', TObject($0084));
MsgList.AddObject ('wm_NCPaint', TObject($0085));
MsgList.AddObject ('wm_NCActivate', TObject($0086));
MsgList.AddObject ('wm_GetDlgCode', TObject($0087));
MsgList.AddObject ('wm_NCMouseMove', TObject($00A0));
MsgList.AddObject ('wm_NCLButtonDown', TObject($00A1));
MsgList.AddObject ('wm_NCLButtonUp', TObject($00A2));
MsgList.AddObject ('wm_NCLButtonDblClk', TObject($00A3));
MsgList.AddObject ('wm_NCRButtonDown', TObject($00A4));
MsgList.AddObject ('wm_NCRButtonUp', TObject($00A5));
MsgList.AddObject ('wm_NCRButtonDblClk', TObject($00A6));
MsgList.AddObject ('wm_NCMButtonDown', TObject($00A7));
MsgList.AddObject ('wm_NCMButtonUp', TObject($00A8));
MsgList.AddObject ('wm_NCMButtonDblClk', TObject($00A9));
MsgList.AddObject ('wm_KeyDown', TObject($0100));
MsgList.AddObject ('wm_KeyUp', TObject($0101));
MsgList.AddObject ('wm_Char', TObject($0102));
MsgList.AddObject ('wm_DeadChar', TObject($0103));
MsgList.AddObject ('wm_SysKeyDown', TObject($0104));
MsgList.AddObject ('wm_SysKeyUp', TObject($0105));
MsgList.AddObject ('wm_SysChar', TObject($0106));
MsgList.AddObject ('wm_SysDeadChar', TObject($0107));
MsgList.AddObject ('wm_KeyLast', TObject($0108));
MsgList.AddObject ('wm_IME_StartComposition', TObject($010D));
MsgList.AddObject ('wm_IME_EndComposition', TObject($010E));
MsgList.AddObject ('wm_IME_Composition/KeyLast', TObject($010F));
MsgList.AddObject ('wm_InitDialog', TObject($0110));
MsgList.AddObject ('wm_Command', TObject($0111));
MsgList.AddObject ('wm_SysCommand', TObject($0112));
MsgList.AddObject ('wm_Timer', TObject($0113));
MsgList.AddObject ('wm_HScroll', TObject($0114));
MsgList.AddObject ('wm_VScroll', TObject($0115));
MsgList.AddObject ('wm_InitMenu', TObject($0116));
MsgList.AddObject ('wm_InitMenuPopup', TObject($0117));
MsgList.AddObject ('wm_MenuSelect', TObject($011F));
MsgList.AddObject ('wm_MenuChar', TObject($0120));
MsgList.AddObject ('wm_EnterIdle', TObject($0121));
MsgList.AddObject ('wm_CtlColorMsgbox', TObject($0132));
MsgList.AddObject ('wm_CtlColorEdit', TObject($0133));
MsgList.AddObject ('wm_CtlColorListbox', TObject($0134));
MsgList.AddObject ('wm_CtlColorBtn', TObject($0135));
MsgList.AddObject ('wm_CtlColorDlg', TObject($0136));
MsgList.AddObject ('wm_CtlColorScrollbar', TObject($0137));
MsgList.AddObject ('wm_CtlColorStatic', TObject($0138));
MsgList.AddObject ('wm_MouseMove', TObject($0200));
MsgList.AddObject ('wm_LButtonDown', TObject($0201));
MsgList.AddObject ('wm_LButtonUp', TObject($0202));
MsgList.AddObject ('wm_LButtonDblClk', TObject($0203));
MsgList.AddObject ('wm_RButtonDown', TObject($0204));
MsgList.AddObject ('wm_RButtonUp', TObject($0205));
MsgList.AddObject ('wm_RButtonDblClk', TObject($0206));
MsgList.AddObject ('wm_MButtonDown', TObject($0207));
MsgList.AddObject ('wm_MButtonUp', TObject($0208));
MsgList.AddObject ('wm_MButtonDblClk', TObject($0209));
MsgList.AddObject ('wm_MouseLast/Wheel', TObject($020A));
MsgList.AddObject ('wm_ParentNotify', TObject($0210));
MsgList.AddObject ('wm_EnterMenuLoop', TObject($0211));
MsgList.AddObject ('wm_ExitMenuLoop', TObject($0212));
MsgList.AddObject ('wm_NextMenu', TObject($0213));
MsgList.AddObject ('wm_Sizing', TObject($0214));
MsgList.AddObject ('wm_CaptureChanged', TObject($0215));
MsgList.AddObject ('wm_Moving', TObject($0216));
MsgList.AddObject ('wm_PowerBroadcast', TObject($0218));
MsgList.AddObject ('wm_DeviceChange', TObject($0219));
MsgList.AddObject ('wm_MDICreate', TObject($0220));
MsgList.AddObject ('wm_MDIDestroy', TObject($0221));
MsgList.AddObject ('wm_MDIActivate', TObject($0222));
MsgList.AddObject ('wm_MDIRestore', TObject($0223));
MsgList.AddObject ('wm_MDINext', TObject($0224));
MsgList.AddObject ('wm_MDIMaximize', TObject($0225));
MsgList.AddObject ('wm_MDITile', TObject($0226));
MsgList.AddObject ('wm_MDICascade', TObject($0227));
MsgList.AddObject ('wm_MDIIconArrange', TObject($0228));
MsgList.AddObject ('wm_MDIGetActive', TObject($0229));
MsgList.AddObject ('wm_MDISetMenu', TObject($0230));
MsgList.AddObject ('wm_EnterSizeMove', TObject($0231));
MsgList.AddObject ('wm_ExitSizeMove', TObject($0232));
MsgList.AddObject ('wm_DropFiles', TObject($0233));
MsgList.AddObject ('wm_MDIRefreshMenu', TObject($0234));
MsgList.AddObject ('wm_IME_Setcontext', TObject($0281));
MsgList.AddObject ('wm_IME_Notify', TObject($0282));
MsgList.AddObject ('wm_IME_Control', TObject($0283));
MsgList.AddObject ('wm_IME_Compositionfull', TObject($0284));
MsgList.AddObject ('wm_IME_Select', TObject($0285));
MsgList.AddObject ('wm_IME_Char', TObject($0286));
MsgList.AddObject ('wm_IME_Keydown', TObject($0290));
MsgList.AddObject ('wm_IME_Keyup', TObject($0291));
MsgList.AddObject ('wm_MouseHover', TObject($02a1));
MsgList.AddObject ('wm_MouseLeave', TObject($02a3));
MsgList.AddObject ('wm_Cut', TObject($0300));
MsgList.AddObject ('wm_Copy', TObject($0301));
MsgList.AddObject ('wm_Paste', TObject($0302));
MsgList.AddObject ('wm_Clear', TObject($0303));
MsgList.AddObject ('wm_Undo', TObject($0304));
MsgList.AddObject ('wm_RenderFormat', TObject($0305));
MsgList.AddObject ('wm_RenderAllFormats', TObject($0306));
MsgList.AddObject ('wm_DestroyClipboard', TObject($0307));
MsgList.AddObject ('wm_DrawClipboard', TObject($0308));
MsgList.AddObject ('wm_PaintClipboard', TObject($0309));
MsgList.AddObject ('wm_VScrollClipboard', TObject($030A));
MsgList.AddObject ('wm_SizeClipboard', TObject($030B));
MsgList.AddObject ('wm_AskCBFormatName', TObject($030C));
MsgList.AddObject ('wm_ChangeCBChain', TObject($030D));
MsgList.AddObject ('wm_HScrollClipboard', TObject($030E));
MsgList.AddObject ('wm_QueryNewPalette', TObject($030F));
MsgList.AddObject ('wm_PaletteIsChanging', TObject($0310));
MsgList.AddObject ('wm_PaletteChanged', TObject($0311));
MsgList.AddObject ('wm_HotKey', TObject($0312));
MsgList.AddObject ('wm_Print', TObject($0317));
MsgList.AddObject ('wm_PrintClient', TObject($0318));
MsgList.AddObject ('CM_ACTIVATE', TObject($B000 + 0));
MsgList.AddObject ('CM_DEACTIVATE', TObject($B000 + 1));
MsgList.AddObject ('CM_GOTFOCUS', TObject($B000 + 2));
MsgList.AddObject ('CM_LOSTFOCUS', TObject($B000 + 3));
MsgList.AddObject ('CM_CANCELMODE', TObject($B000 + 4));
MsgList.AddObject ('CM_DIALOGKEY', TObject($B000 + 5));
MsgList.AddObject ('CM_DIALOGCHAR', TObject($B000 + 6));
MsgList.AddObject ('CM_FOCUSCHANGED', TObject($B000 + 7));
MsgList.AddObject ('CM_PARENTFONTCHANGED', TObject($B000 + 8));
MsgList.AddObject ('CM_PARENTCOLORCHANGED', TObject($B000 + 9));
MsgList.AddObject ('CM_HITTEST', TObject($B000 + 10));
MsgList.AddObject ('CM_VISIBLECHANGED', TObject($B000 + 11));
MsgList.AddObject ('CM_ENABLEDCHANGED', TObject($B000 + 12));
MsgList.AddObject ('CM_COLORCHANGED', TObject($B000 + 13));
MsgList.AddObject ('CM_FONTCHANGED', TObject($B000 + 14));
MsgList.AddObject ('CM_CURSORCHANGED', TObject($B000 + 15));
MsgList.AddObject ('CM_CTL3DCHANGED', TObject($B000 + 16));
MsgList.AddObject ('CM_PARENTCTL3DCHANGED', TObject($B000 + 17));
MsgList.AddObject ('CM_TEXTCHANGED', TObject($B000 + 18));
MsgList.AddObject ('CM_MOUSEENTER', TObject($B000 + 19));
MsgList.AddObject ('CM_MOUSELEAVE', TObject($B000 + 20));
MsgList.AddObject ('CM_MENUCHANGED', TObject($B000 + 21));
MsgList.AddObject ('CM_APPKEYDOWN', TObject($B000 + 22));
MsgList.AddObject ('CM_APPSYSCOMMAND', TObject($B000 + 23));
MsgList.AddObject ('CM_BUTTONPRESSED', TObject($B000 + 24));
MsgList.AddObject ('CM_SHOWINGCHANGED', TObject($B000 + 25));
MsgList.AddObject ('CM_ENTER', TObject($B000 + 26));
MsgList.AddObject ('CM_EXIT', TObject($B000 + 27));
MsgList.AddObject ('CM_DESIGNHITTEST', TObject($B000 + 28));
MsgList.AddObject ('CM_ICONCHANGED', TObject($B000 + 29));
MsgList.AddObject ('CM_WANTSPECIALKEY', TObject($B000 + 30));
MsgList.AddObject ('CM_INVOKEHELP', TObject($B000 + 31));
MsgList.AddObject ('CM_WINDOWHOOK', TObject($B000 + 32));
MsgList.AddObject ('CM_RELEASE', TObject($B000 + 33));
MsgList.AddObject ('CM_SHOWHINTCHANGED', TObject($B000 + 34));
MsgList.AddObject ('CM_PARENTSHOWHINTCHANGED', TObject($B000 + 35));
MsgList.AddObject ('CM_SYSCOLORCHANGE', TObject($B000 + 36));
MsgList.AddObject ('CM_WININICHANGE', TObject($B000 + 37));
MsgList.AddObject ('CM_FONTCHANGE', TObject($B000 + 38));
MsgList.AddObject ('CM_TIMECHANGE', TObject($B000 + 39));
MsgList.AddObject ('CM_TABSTOPCHANGED', TObject($B000 + 40));
MsgList.AddObject ('CM_UIACTIVATE', TObject($B000 + 41));
MsgList.AddObject ('CM_UIDEACTIVATE', TObject($B000 + 42));
MsgList.AddObject ('CM_DOCWINDOWACTIVATE', TObject($B000 + 43));
MsgList.AddObject ('CM_CONTROLLISTCHANGE', TObject($B000 + 44));
MsgList.AddObject ('CM_GETDATALINK', TObject($B000 + 45));
MsgList.AddObject ('CM_CHILDKEY', TObject($B000 + 46));
MsgList.AddObject ('CM_DRAG', TObject($B000 + 47));
MsgList.AddObject ('CM_HINTSHOW', TObject($B000 + 48));
MsgList.AddObject ('CM_DIALOGHANDLE', TObject($B000 + 49));
MsgList.AddObject ('CM_ISTOOLCONTROL', TObject($B000 + 50));
MsgList.AddObject ('CM_RECREATEWND', TObject($B000 + 51));
MsgList.AddObject ('CM_INVALIDATE', TObject($B000 + 52));
MsgList.AddObject ('CM_SYSFONTCHANGED', TObject($B000 + 53));
MsgList.AddObject ('CM_CONTROLCHANGE', TObject($B000 + 54));
MsgList.AddObject ('CM_CHANGED', TObject($B000 + 55));
MsgList.AddObject('CM_DOCKCLIENT', TObject($B000 + 56));
MsgList.AddObject('CM_UNDOCKCLIENT', TObject($B000 + 57));
MsgList.AddObject('CM_FLOAT', TObject($B000 + 58));
MsgList.AddObject('CM_BORDERCHANGED', TObject($B000 + 59));
MsgList.AddObject('CM_BIDIMODECHANGED', TObject($B000 + 60));
MsgList.AddObject('CM_PARENTBIDIMODECHANGED', TObject($B000 + 61));
MsgList.AddObject('CM_ALLCHILDRENFLIPPED', TObject($B000 + 62));
MsgList.AddObject('CM_ACTIONUPDATE', TObject($B000 + 63));
MsgList.AddObject('CM_ACTIONEXECUTE', TObject($B000 + 64));
MsgList.AddObject('CM_HINTSHOWPAUSE', TObject($B000 + 65));
MsgList.AddObject('CM_DOCKNOTIFICATION', TObject($B000 + 66));
MsgList.AddObject('CM_MOUSEWHEEL', TObject($B000 + 67));
MsgList.AddObject('CN_CHARTOITEM', TObject($BC00 + WM_CHARTOITEM));
MsgList.AddObject('CN_COMMAND', TObject($BC00 + WM_COMMAND));
MsgList.AddObject('CN_COMPAREITEM', TObject($BC00 + WM_COMPAREITEM));
MsgList.AddObject('CN_CTLCOLORBTN', TObject($BC00 + WM_CTLCOLORBTN));
MsgList.AddObject('CN_CTLCOLORDLG', TObject($BC00 + WM_CTLCOLORDLG));
MsgList.AddObject('CN_CTLCOLOREDIT', TObject($BC00 + WM_CTLCOLOREDIT));
MsgList.AddObject('CN_CTLCOLORLISTBOX', TObject($BC00 + WM_CTLCOLORLISTBOX));
MsgList.AddObject('CN_CTLCOLORMSGBOX', TObject($BC00 + WM_CTLCOLORMSGBOX));
MsgList.AddObject('CN_CTLCOLORSCROLLBAR', TObject($BC00 + WM_CTLCOLORSCROLLBAR));
MsgList.AddObject('CN_CTLCOLORSTATIC', TObject($BC00 + WM_CTLCOLORSTATIC));
MsgList.AddObject('CN_DELETEITEM', TObject($BC00 + WM_DELETEITEM));
MsgList.AddObject('CN_DRAWITEM', TObject($BC00 + WM_DRAWITEM));
MsgList.AddObject('CN_HSCROLL', TObject($BC00 + WM_HSCROLL));
MsgList.AddObject('CN_MEASUREITEM', TObject($BC00 + WM_MEASUREITEM));
MsgList.AddObject('CN_PARENTNOTIFY', TObject($BC00 + WM_PARENTNOTIFY));
MsgList.AddObject('CN_VKEYTOITEM', TObject($BC00 + WM_VKEYTOITEM));
MsgList.AddObject('CN_VSCROLL', TObject($BC00 + WM_VSCROLL));
MsgList.AddObject('CN_KEYDOWN', TObject($BC00 + WM_KEYDOWN));
MsgList.AddObject('CN_KEYUP', TObject($BC00 + WM_KEYUP));
MsgList.AddObject('CN_CHAR', TObject($BC00 + WM_CHAR));
MsgList.AddObject('CN_SYSKEYDOWN', TObject($BC00 + WM_SYSKEYDOWN));
MsgList.AddObject ('CN_SYSKEYUP', TObject($BC00 + WM_SYSKEYUP));
MsgList.AddObject('CN_SYSCHAR', TObject($BC00 + WM_SYSCHAR));
MsgList.AddObject('CN_NOTIFY', TObject($BC00 + WM_NOTIFY));
MsgList.AddObject('TVM_INSERTITEMA', TObject($1100 + 0));
MsgList.AddObject('TVM_INSERTITEMW', TObject($1100 + 50));
MsgList.AddObject('TVM_DELETEITEM', TObject($1100 + 1));
MsgList.AddObject('TVM_EXPAND', TObject($1100 + 2));
MsgList.AddObject('TVM_GETITEMRECT', TObject($1100 + 4));
MsgList.AddObject('TVM_GETCOUNT', TObject($1100 + 5));
MsgList.AddObject('TVM_GETINDENT', TObject($1100 + 6));
MsgList.AddObject('TVM_SETINDENT', TObject($1100 + 7));
MsgList.AddObject('TVM_GETIMAGELIST', TObject($1100 + 8));
MsgList.AddObject('TVM_SETIMAGELIST', TObject($1100 + 9));
MsgList.AddObject('TVM_GETNEXTITEM', TObject($1100 + 10));
MsgList.AddObject('TVM_SELECTITEM', TObject($1100 + 11));
MsgList.AddObject('TVM_GETITEMA', TObject($1100 + 12));
MsgList.AddObject('TVM_GETITEMW', TObject($1100 + 62));
MsgList.AddObject('TVM_SETITEMA', TObject($1100 + 13));
MsgList.AddObject('TVM_SETITEMW', TObject($1100 + 63));
MsgList.AddObject('TVM_EDITLABELA', TObject($1100 + 14));
MsgList.AddObject('TVM_EDITLABELW', TObject($1100 + 65));
MsgList.AddObject('TVM_GETEDITCONTROL', TObject($1100 + 15));
MsgList.AddObject('TVM_GETVISIBLECOUNT', TObject($1100 + 16));
MsgList.AddObject('TVM_HITTEST', TObject($1100 + 17));
MsgList.AddObject('TVM_CREATEDRAGIMAGE', TObject($1100 + 18));
MsgList.AddObject('TVM_SORTCHILDREN', TObject($1100 + 19));
MsgList.AddObject('TVM_ENSUREVISIBLE', TObject($1100 + 20));
MsgList.AddObject('TVM_SORTCHILDRENCB', TObject($1100 + 21));
MsgList.AddObject('TVM_ENDEDITLABELNOW', TObject($1100 + 22));
MsgList.AddObject('TVM_GETISEARCHSTRINGA', TObject($1100 + 23));
MsgList.AddObject('TVM_GETISEARCHSTRINGW', TObject($1100 + 64));
MsgList.AddObject('TVM_SETTOOLTIPS', TObject($1100 + 24));
MsgList.AddObject('TVM_GETTOOLTIPS', TObject($1100 + 25));
MsgList.AddObject('TVM_SETINSERTMARK', TObject($1100 + 26));
MsgList.AddObject('TVM_SETITEMHEIGHT', TObject($1100 + 27));
MsgList.AddObject('TVM_GETITEMHEIGHT', TObject($1100 + 28));
MsgList.AddObject('TVM_SETBKCOLOR', TObject($1100 + 29));
MsgList.AddObject('TVM_SETTEXTCOLOR', TObject($1100 + 30));
MsgList.AddObject('TVM_GETBKCOLOR', TObject($1100 + 31));
MsgList.AddObject('TVM_GETTEXTCOLOR', TObject($1100 + 32));
MsgList.AddObject('TVM_SETSCROLLTIME', TObject($1100 + 33));
MsgList.AddObject('TVM_GETSCROLLTIME', TObject($1100 + 34));
MsgList.AddObject('Unknown (TVM-$1123)', TObject($1100 + 35));
MsgList.AddObject('Unknown (TVM-$1124)', TObject($1100 + 36));
MsgList.AddObject('TVM_SETINSERTMARKCOLOR', TObject($1100 + 37));
MsgList.AddObject('TVM_GETINSERTMARKCOLOR', TObject($1100 + 38));
end.
|
unit RunErr;
interface
function GetErrorStr(code:byte):string;
implementation
function GetErrorStr(code:byte):string;
begin
case code of
1 :GetErrorStr:='Invalid function number';
2 :GetErrorStr:='File not found';
3 :GetErrorStr:='Path not found';
4 :GetErrorStr:='Too many open files';
5 :GetErrorStr:='File access denied';
6 :GetErrorStr:='Invalid file handle';
12 :GetErrorStr:='Invalid file access code';
15 :GetErrorStr:='Invalid drive number';
16 :GetErrorStr:='Cannot remove current directory';
17 :GetErrorStr:='Cannot rename across drives';
18 :GetErrorStr:='No more files';
100 :GetErrorStr:='Disk read error';
101 :GetErrorStr:='Disk write error';
102 :GetErrorStr:='File not assigned';
103 :GetErrorStr:='File not open';
104 :GetErrorStr:='File not open for input';
105 :GetErrorStr:='File not open for output';
106 :GetErrorStr:='Invalid numeric format';
150 :GetErrorStr:='Disk is write-protected';
151 :GetErrorStr:='Bad drive request struct length';
152 :GetErrorStr:='Drive not ready';
154 :GetErrorStr:='CRC error in data';
156 :GetErrorStr:='Disk seek error';
157 :GetErrorStr:='Unknown media type';
158 :GetErrorStr:='Sector Not Found';
159 :GetErrorStr:='Printer out of paper';
160 :GetErrorStr:='Device write fault';
161 :GetErrorStr:='Device read fault';
162 :GetErrorStr:='Hardware failure';
200 :GetErrorStr:='Division by zero';
201 :GetErrorStr:='Range check error';
202 :GetErrorStr:='Stack overflow error';
203 :GetErrorStr:='Heap overflow error';
204 :GetErrorStr:='Invalid pointer operation';
205 :GetErrorStr:='Floating point overflow';
206 :GetErrorStr:='Floating point underflow';
207 :GetErrorStr:='Invalid floating point operation';
208 :GetErrorStr:='Overlay manager not installed';
209 :GetErrorStr:='Overlay file read error';
210 :GetErrorStr:='Object not initialized';
211 :GetErrorStr:='Call to abstract method';
212 :GetErrorStr:='Stream registration error';
213 :GetErrorStr:='Collection index out of range';
214 :GetErrorStr:='Collection overflow error';
215 :GetErrorStr:='Arithmetic overflow error';
216 :GetErrorStr:='General Protection fault';
else GetErrorStr:='Unknown error'
end;
end;
begin
end. |
program SpritePackTest;
uses SwinGame, sgTypes;
procedure HandleSpriteEvents(s: Sprite; kind: SpriteEventKind);
begin
case kind of
SpriteArrivedEvent: SpriteMoveTo(s, RandomScreenPoint(), 5);
end;
end;
procedure CreateNewBall();
var
ball: Sprite;
begin
ball := CreateSprite(BitmapNamed('ball'));
SpriteSetPosition(ball, RandomScreenPoint());
SpriteMoveTo(ball, RandomScreenPoint(), 5);
end;
procedure Main();
begin
OpenGraphicsWindow('SpritePackTest');
LoadDefaultColors();
LoadBitmapNamed('ball', 'ball_small.png');
CallOnSpriteEvent(@HandleSpriteEvents);
CreateSpritePack('Other');
CreateNewBall();
repeat
ProcessEvents();
if KeyTyped(SpaceKey) then CreateNewBall();
if KeyTyped(Key1) then SelectSpritePack('Default');
if KeyTyped(Key2) then SelectSpritePack('Other');
if KeyTyped(Key3) then SelectSpritePack('Non Existant');
ClearScreen(ColorWhite);
DrawText('Pack: ' + CurrentSpritePack(), ColorBlack, 0, 0);
DrawFramerate(0, 20);
DrawAllSprites();
UpdateAllSprites();
RefreshScreen();
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end.
|
unit uTickTockTimer;
interface
uses
System.Classes, System.SysUtils, FMX.Types
, uObserver
, uObservable;
type
IClockTimer = interface(IVMObservable)
['{5F05B7B7-9300-4559-9A1D-104CF343108E}']
function GetTime: string;
property Time: string read GetTime;
end;
TClockTimer = class(TInterfacedObject, IClockTimer)
strict private
FTimer: TTimer;
FInternalTime: TDateTime;
FLstObservers: IInterfaceList;
procedure Tick(Sender: TObject);
function GetTime: string;
protected
procedure NotifyObservers;
public
constructor Create;
destructor Destroy; override;
procedure Attach(aObserver: IVMObserver);
procedure Detach(aObserver: IVMObserver);
procedure DetachAll;
property Time: string read GetTime;
end;
implementation
function ClockTimer: IClockTimer;
begin
Result := TClockTimer.Create;
end;
constructor TClockTimer.Create;
begin
inherited Create;
FTimer := TTimer.Create(nil);
FTimer.Interval := 1000;
FTimer.OnTimer := Tick;
FTimer.Enabled := True;
FLstObservers := nil;
end;
destructor TClockTimer.Destroy;
begin
FTimer.Enabled := False;
FreeAndNil(FTimer);
DetachAll;
inherited Destroy;
end;
function TClockTimer.GetTime: string;
begin
Result := FormatDateTime('dd/mm/yyyy hh:nn:ss', FInternalTime);
end;
procedure TClockTimer.NotifyObservers;
begin
for var I := 0 to Pred(FLstObservers.Count) do
IVMObserver(FLstObservers[I]).UpdateObserver(Self);
end;
procedure TClockTimer.Attach(aObserver: IVMObserver);
begin
if FLstObservers = nil then
FLstObservers := TInterfaceList.Create;
if FLstObservers.IndexOf(aObserver) < 0 then
FLstObservers.Add(aObserver);
end;
procedure TClockTimer.Tick(Sender: TObject);
begin
FInternalTime := Now;
NotifyObservers;
end;
procedure TClockTimer.Detach(aObserver: IVMObserver);
begin
if FLstObservers <> nil then
begin
FLstObservers.Remove(AObserver);
if FLstObservers.Count = 0 then
FLstObservers := nil;
end;
end;
procedure TClockTimer.DetachAll;
begin
if FLstObservers <> nil then
begin
FLstObservers.Clear;
FLstObservers := nil;
end;
end;
end.
|
{ Turbo Assembler example. Copyright (c) 1993 By Borland International, Inc. }
{ Use with exchmod.asm }
program TextExchange;
type
EmployeeRecord = record
Name : string[30];
Address : string[30];
City : string[15];
State : string[2];
Zip : string[10];
end;
var
OldEmployee, NewEmployee : EmployeeRecord;
procedure Exchange(var Var1,Var2; Count : Word); far; external;
{$L EXCHMOD.OBJ}
begin
with OldEmployee do
begin
Name := 'John Smith';
Address := '123 F Street';
City := 'Scotts Valley';
State := 'CA';
Zip := '90000-0000';
end;
with NewEmployee do
begin
Name := 'Mary Jones';
Address := '9471 41st Avenue';
City := 'New York';
State := 'NY';
Zip := '10000-1111';
end;
Writeln('Before: ',OldEmployee.Name,' ',NewEmployee.Name);
Exchange(OldEmployee,NewEmployee,sizeof(OldEmployee));
Writeln('After: ',OldEmployee.Name,' ',NewEmployee.Name);
Exchange(OldEmployee,NewEmployee,sizeof(OldEmployee));
Writeln('After: ',OldEmployee.Name,' ',NewEmployee.Name);
end.
|
unit Dmitry.Utils.ShortCut;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
System.SysUtils,
System.Classes,
System.Win.ComObj,
Winapi.ActiveX,
Winapi.ShlObj,
Winapi.Windows;
type
TShortCut = class
private
FShellLink: IShellLink;
FPersistFile: IPersistFile;
function GetArguments: string;
function GetDescription: string;
function GetHotKey: System.Classes.TShortCut;
function GetIconLocation: string;
function GetIDList: PItemIDList;
function GetPath: string;
function GetShowCMD: Integer;
function GetWorkingDirectory: string;
procedure SetArguments(const Value: string);
procedure SetDescription(const Value: string);
procedure SetHotKey(const Value: System.Classes.TShortCut);
procedure SetIDList(const Value: PItemIDList);
procedure SetPath(const Value: string);
procedure SetRelativePath(const Value: string);
procedure SetShowCMD(const Value: Integer);
procedure SetWorkingDirectory(const Value: string);
public
// Creates empty unlinked shortcut
constructor Create; overload;
// Creates shortcut object loading parameters from specified *.lnk file
constructor Create(LinkPath: string); overload;
// Destroys shortcut without saving
destructor Destroy; override;
// Saves shortcut info to a specified file
procedure Save(Filename: string);
// Loads shortcut object from specified *.lnk file
procedure Load(Filename: string);
procedure SetIcon(const ExeDllName: string; Index : Integer);
// Resolves shortcut (validates path and if object shortcut points to does not exists,
// opens window and searchs for lost object. Under Windows NT and NTFS if Distributed Link
// Tracking system is enabled method finds shortcut object and sets correct path
function Resolve(Window: HWND; Options: DWORD): HResult;
// Returns last error text
function GetLastErrorText(ErrorCode: Cardinal): string;
// Property to access command line parameters for shortcut object
property Arguments: string read GetArguments write SetArguments;
// Property to access shortcut object description
property Description: string read GetDescription write SetDescription;
// Hot key for shortcut object
property HotKey: System.Classes.TShortCut read GetHotKey write SetHotKey;
// Icon location property
property IconLocation: string read GetIconLocation;
// IDList property for special shell icon objects
property IDList: PItemIDList read GetIDList write SetIDList;
// Path to shortcut abject
property Path: string read GetPath write SetPath;
// Relative path set property
property RelativePath: string write SetRelativePath;
// Property to find out how to show the running shortcut object
property ShowCMD: Integer read GetShowCMD write SetShowCMD;
// Property to access working directory for shortcut object
property WorkingDirectory: string read GetWorkingDirectory write SetWorkingDirectory;
end;
type
EVRSIShortCutError = class(Exception)
end;
const
IID_IPersistFile: TGUID = (D1: $0000010B; D2: $0000; D3: $0000; D4: ($C0, $00, $00, $00, $00, $00, $00, $46));
// Autostart : CSIDL_Startup
// Startmenu : CSIDL_Startmenu
// Programs : CSIDL_Programs
// Favorites : CSIDL_Favorites
// Desktop : CSIDL_Desktopdirectory
// "Send to"-dir : CSIDL_Sendto
function VRSIGetSpecialDirectoryName(ID: Integer; PlusSlash: Boolean): string;
implementation
function VRSIGetSpecialDirectoryName(ID: Integer; PlusSlash: Boolean): string;
var
Pidl: PItemIDList;
Path: PChar;
begin
if SUCCEEDED(SHGetSpecialFolderLocation(0, ID, Pidl)) then
begin
Path := StrAlloc(MAX_PATH);
SHGetPathFromIDList(Pidl, Path);
Result := string(Path);
if PlusSlash then
Result := IncludeTrailingBackSlash(Result);
end;
end;
constructor TShortCut.Create;
var
Err: Integer;
begin
inherited;
Err := CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLink, FShellLink);
if Err <> S_OK then
raise EVRSIShortCutError.Create('Unable to get interface IShellLink!' + #10#13 + GetLastErrorText(Err));
Err := FShellLink.QueryInterface(IID_IPersistFile, FPersistFile);
if (Err <> S_OK) then
raise EVRSIShortCutError.Create('Unable to get interface IPersistFile!' + #10#13 + GetLastErrorText(Err));
end;
constructor TShortCut.Create(LinkPath: string);
begin
Self.Create;
Self.Load(LinkPath);
end;
destructor TShortCut.Destroy;
begin
inherited;
end;
function TShortCut.GetArguments: string;
var
Arguments: string;
begin
SetLength(Arguments, MAX_PATH);
Self.FShellLink.GetArguments(PChar(Arguments), MAX_PATH);
SetString(Result, PChar(Arguments), Length(PChar(Arguments)));
end;
function TShortCut.GetDescription: string;
var
Description: string;
begin
SetLength(Description, MAX_PATH);
Self.FShellLink.GetDescription(PChar(Description), MAX_PATH);
SetString(Result, PChar(Description), Length(PChar(Description)));
end;
function TShortCut.GetHotKey: System.Classes.TShortCut;
var
HotKey: System.Classes.TShortCut;
begin
Self.FShellLink.GetHotkey(Word(HotKey));
Result := HotKey;
end;
function TShortCut.GetIconLocation: string;
var
IconLocation: string;
Icon: Integer;
begin
SetLength(IconLocation, MAX_PATH);
Self.FShellLink.GetIconLocation(PChar(IconLocation), MAX_PATH, Icon);
Result := PChar(IconLocation) + ',' + IntToStr(Icon);
end;
function TShortCut.GetIDList: PItemIDList;
var
List: PItemIDList;
begin
Self.FShellLink.GetIDList(List);
Result := List;
end;
function TShortCut.GetLastErrorText(ErrorCode: Cardinal): string;
var
WinErrMsg: PChar;
begin
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode,
(((WORD((SUBLANG_DEFAULT)) shl 10)) or Word((LANG_NEUTRAL))), @WinErrMsg, 0, nil);
Result := WinErrMsg;
end;
function TShortCut.GetPath: string;
var
Path: string;
FindData: WIN32_FIND_DATA;
begin
SetLength(Path, MAX_PATH);
Self.FShellLink.GetPath(PChar(Path), MAX_PATH, FindData, SLGP_UNCPRIORITY);
SetString(Result, PChar(Path), Length(PChar(Path)));
end;
function TShortCut.GetShowCMD: Integer;
var
ShowCMD: Integer;
begin
Self.FShellLink.GetShowCmd(ShowCMD);
Result := ShowCMD;
end;
function TShortCut.GetWorkingDirectory: string;
var
WorkDir: string;
begin
SetLength(WorkDir, MAX_PATH);
Self.FShellLink.GetWorkingDirectory(PChar(WorkDir), MAX_PATH);
SetString(Result, PChar(WorkDir), Length(PChar(WorkDir)));
end;
procedure TShortCut.Load(Filename: string);
begin
FPersistFile.Load(StringToOLEStr(Filename), 0);
end;
function TShortCut.Resolve(Window: HWND; Options: DWORD): HResult;
begin
Result := Self.FShellLink.Resolve(Window, Options);
end;
procedure TShortCut.Save(Filename: string);
begin
FPersistFile.Save(PChar(Filename), True);
end;
procedure TShortCut.SetArguments(const Value: string);
begin
Self.FShellLink.SetArguments(PChar(Value));
end;
procedure TShortCut.SetDescription(const Value: string);
begin
Self.FShellLink.SetDescription(PChar(Value));
end;
procedure TShortCut.SetHotKey(const Value: System.Classes.TShortCut);
begin
Self.FShellLink.SetHotkey(Value);
end;
procedure TShortCut.SetIcon(const ExeDllName: string; Index: Integer);
begin
Self.FShellLink.SetIconLocation(PChar(ExeDllName), Index);
end;
procedure TShortCut.SetIDList(const Value: PItemIDList);
begin
Self.FShellLink.SetIDList(Value);
end;
procedure TShortCut.SetPath(const Value: string);
begin
Self.FShellLink.SetPath(PChar(Value));
end;
procedure TShortCut.SetRelativePath(const Value: string);
begin
Self.FShellLink.SetRelativePath(PChar(Value), 0);
end;
procedure TShortCut.SetShowCMD(const Value: Integer);
begin
Self.FShellLink.SetShowCmd(Value);
end;
procedure TShortCut.SetWorkingDirectory(const Value: string);
begin
Self.FShellLink.SetWorkingDirectory(PChar(Value));
end;
end.
|
unit LIB.Render;
interface //#################################################################### ■
uses System.UITypes, System.TimeSpan, System.Classes, System.Threading, System.Diagnostics,
LIB, LIB.Lattice.D2;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRender
TRender = class( TColorMap2D )
private
_ProgreTask :ITask;
_RenderTask :ITask;
protected
_Timer :TStopwatch;
_IsRun :Boolean;
///// イベント
_OnBeginRender :TThreadProcedure;
_OnProgress :TThreadProcedure;
_OnEndRender :TThreadProcedure;
///// アクセス
function GetTimer :TTimeSpan;
///// メソッド
function GetRender( const X_,Y_:Integer ) :TAlphaColorF; virtual; abstract;
public
constructor Create( const SizeX_,SizeY_:Integer ); overload; override;
///// プロパティ
property Timer :TTimeSpan read GetTimer;
property IsRun :Boolean read _IsRun;
///// イベント
property OnBeginRender :TThreadProcedure read _OnBeginRender write _OnBeginRender;
property OnProgress :TThreadProcedure read _OnProgress write _OnProgress ;
property OnEndRender :TThreadProcedure read _OnEndRender write _OnEndRender ;
///// メソッド
procedure Render;
procedure Cancel;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRender
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TRender.GetTimer :TTimeSpan;
begin
Result := _Timer.Elapsed;
end;
/////////////////////////////////////////////////////////////////////// メソッド
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TRender.Create( const SizeX_,SizeY_:Integer );
begin
inherited;
_Timer := TStopWatch.Create;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TRender.Render;
begin
_RenderTask := TTask.Create( procedure
begin
Clear( TAlphaColorF.Create( TAlphaColors.Null ) );
_IsRun := True;
if Assigned( _OnBeginRender ) then TThread.Synchronize( nil, _OnBeginRender );
_ProgreTask.Start;
_Timer.Start;
TParallel.For( 0, _SizeY-1, procedure( Y:Integer; S:TParallel.TLoopState )
var
X :Integer;
begin
if _RenderTask.Status = TTaskStatus.Running then
begin
for X := 0 to _SizeX-1 do _Map[ Y, X ] := GetRender( X, Y );
end
else S.Stop;
end );
_Timer.Stop;
_ProgreTask.Cancel;
end );
_ProgreTask := TTask.Create( procedure
begin
repeat
Sleep( 500{ms} );
if Assigned( _OnProgress ) then TThread.Synchronize( nil, _OnProgress );
until TTask.CurrentTask.Status = TTaskStatus.Canceled;
_IsRun := False;
if Assigned( _OnEndRender ) then TThread.Synchronize( nil, _OnEndRender );
end );
_RenderTask.Start;
end;
procedure TRender.Cancel;
begin
_RenderTask.Cancel;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
unit uFrmCliente;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.ComCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, uClienteController, uClienteModel,
uDmCliente, System.StrUtils;
type
TOperacao = (opNovo, opAlterar, opNavegar);
TfrmCliente = class(TForm)
pnlRodape: TPanel;
btnFechar: TButton;
pgcPrincipal: TPageControl;
tbsPesquisa: TTabSheet;
tbsManutencao: TTabSheet;
pnlFiltro: TPanel;
edtPesquisa: TLabeledEdit;
btnPesquisar: TButton;
pnlBtnPesq: TPanel;
btnNovo: TButton;
btnDetalhar: TButton;
btnExcluir: TButton;
dsrPesq: TDataSource;
edtCodigo: TLabeledEdit;
edtNome: TLabeledEdit;
cbxTipo: TComboBox;
Label1: TLabel;
edtDocumento: TLabeledEdit;
edtTelefone: TLabeledEdit;
Panel1: TPanel;
btnListar: TButton;
btnAlterar: TButton;
btnGravar: TButton;
btnCancelar: TButton;
pnlGrid: TPanel;
grdDados: TDBGrid;
pnlPesquisa: TPanel;
lblQtdeRegistros: TLabel;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnFecharClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnDetalharClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnListarClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FMenuItem: TMenuItem;
FOperacao: TOperacao;
procedure Novo;
procedure Detalhar;
procedure Configuracoes;
procedure CarregarCliente;
procedure Listar;
procedure Alterar;
procedure Excluir;
procedure Inserir;
procedure Gravar;
procedure HabilitarControles(sOperacao: TOperacao);
procedure SetMenuItem(const Value: TMenuItem);
function Pesquisar: TDataSet;
procedure ConfiguracaoPnlPesquisa;
{ Private declarations }
public
{ Public declarations }
property MenuItem: TMenuItem read FMenuItem write SetMenuItem;
end;
var
frmCliente: TfrmCliente;
implementation
{$R *.dfm}
procedure TfrmCliente.Alterar;
var
oClienteController: TClienteController;
oCliente: TCliente;
sErro: string;
begin
oClienteController := TClienteController.Create;
oCliente := TCliente.Create;
try
oCliente.ID := StrToInt(edtCodigo.Text);
oCliente.Nome := edtNome.Text;
oCliente.Tipo := IfThen(cbxTipo.ItemIndex = 0, 'F', 'J');
oCliente.Documento := edtDocumento.Text;
oCliente.Telefone := edtTelefone.Text;
if not oClienteController.Alterar(oCliente, sErro) then
raise Exception.Create(sErro)
else
Application.MessageBox('Alterado com sucesso.', 'Atenção', MB_OK +
MB_ICONWARNING);
finally
oCliente.Free;
oClienteController.Free;
end;
end;
procedure TfrmCliente.btnAlterarClick(Sender: TObject);
begin
FOperacao := opAlterar;
HabilitarControles(opAlterar);
end;
procedure TfrmCliente.btnCancelarClick(Sender: TObject);
begin
HabilitarControles(opNavegar);
pgcPrincipal.ActivePage := tbsPesquisa;
end;
procedure TfrmCliente.btnDetalharClick(Sender: TObject);
begin
Detalhar;
HabilitarControles(opNavegar);
end;
procedure TfrmCliente.btnExcluirClick(Sender: TObject);
begin
Excluir;
end;
procedure TfrmCliente.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TfrmCliente.btnGravarClick(Sender: TObject);
begin
Gravar;
HabilitarControles(opNavegar);
pgcPrincipal.ActivePage := tbsPesquisa;
end;
procedure TfrmCliente.btnListarClick(Sender: TObject);
begin
Listar;
end;
procedure TfrmCliente.btnNovoClick(Sender: TObject);
begin
Novo;
HabilitarControles(opNovo);
end;
procedure TfrmCliente.btnPesquisarClick(Sender: TObject);
begin
Pesquisar;
ConfiguracaoPnlPesquisa;
end;
procedure TfrmCliente.CarregarCliente;
var
oClienteController: TClienteController;
oCliente: TCliente;
begin
oClienteController := TClienteController.Create;
oCliente := TCliente.Create;
try
if dsrPesq.DataSet.RecordCount <= 0 then
begin
raise Exception.Create('Nenhum Cliente foi selecionado.');
end;
oClienteController.CarregarCliente(oCliente, dsrPesq.DataSet.FieldByName('id').AsInteger);
edtCodigo.Text := IntToStr(oCliente.ID);
edtNome.Text := oCliente.Nome;
cbxTipo.ItemIndex := StrToInt(IfThen(oCliente.Tipo = 'F', '0', '1'));
edtDocumento.Text := oCliente.Documento;
edtTelefone.Text := oCliente.Telefone;
finally
oCliente.Free;
oClienteController.Free;
end;
end;
procedure TfrmCliente.Configuracoes;
begin
pgcPrincipal.Pages[0].TabVisible := False;
pgcPrincipal.Pages[1].TabVisible := False;
pgcPrincipal.ActivePage := tbsPesquisa;
end;
procedure TfrmCliente.Detalhar;
begin
FOperacao := opNavegar;
CarregarCliente;
pgcPrincipal.ActivePage := tbsManutencao;
end;
procedure TfrmCliente.Excluir;
var
oClienteController: TClienteController;
sErro: string;
begin
oClienteController := TClienteController.Create;
try
if (dmCliente.cdsPesquisar.Active) and (dmCliente.cdsPesquisar.RecordCount > 0) then
begin
if Application.MessageBox('Deseja realmente excluir o Cliente?',
'Atenção', MB_YESNO + MB_ICONWARNING) = IDYES then
begin
if not oClienteController.Excluir(dsrPesq.DataSet.FieldByName('ID').AsInteger, sErro) then
begin
raise Exception.Create(sErro);
end
else
Application.MessageBox('Excluído com sucesso.', 'Atenção', MB_OK +
MB_ICONWARNING);
end;
end
else
raise Exception.Create('Não há registro para ser excluído.');
finally
oClienteController.Pesquisar(edtPesquisa.Text);
oClienteController.Free;
end;
end;
procedure TfrmCliente.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FMenuItem.Enabled := True;
FreeAndNil(dmCliente);
frmCliente := nil;
Action := caFree;
end;
procedure TfrmCliente.FormCreate(Sender: TObject);
begin
dmCliente := TdmCliente.Create(nil);
ConfiguracaoPnlPesquisa;
end;
procedure TfrmCliente.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TfrmCliente.FormShow(Sender: TObject);
begin
Configuracoes;
end;
procedure TfrmCliente.Gravar;
var
oClienteController: TClienteController;
begin
oClienteController := TClienteController.Create;
try
case FOperacao of
opNovo: Inserir;
opAlterar: Alterar;
end;
oClienteController.Pesquisar(edtPesquisa.Text);
finally
oClienteController.Free;
end;
end;
procedure TfrmCliente.HabilitarControles(sOperacao: TOperacao);
begin
case sOperacao of
opNovo:
begin
edtNome.Enabled := True;
cbxTipo.Enabled := True;
edtDocumento.Enabled := True;
edtTelefone.Enabled := True;
btnListar.Enabled := False;
btnFechar.Enabled := False;
btnAlterar.Enabled := False;
btnGravar.Enabled := True;
btnCancelar.Enabled := True;
edtNome.Clear;
cbxTipo.ItemIndex := 0;
edtDocumento.Clear;
edtTelefone.Clear;
edtCodigo.Clear;
edtNome.SetFocus;
end;
opAlterar:
begin
edtNome.Enabled := True;
cbxTipo.Enabled := True;
edtDocumento.Enabled := True;
edtTelefone.Enabled := True;
btnListar.Enabled := False;
btnFechar.Enabled := False;
btnAlterar.Enabled := False;
btnGravar.Enabled := True;
btnCancelar.Enabled := True;
edtNome.SetFocus;
end;
opNavegar:
begin
edtNome.Enabled := False;
cbxTipo.Enabled := False;
edtDocumento.Enabled := False;
edtTelefone.Enabled := False;
btnListar.Enabled := True;
btnFechar.Enabled := True;
btnAlterar.Enabled := True;
btnGravar.Enabled := False;
btnCancelar.Enabled := False;
end;
end;
end;
procedure TfrmCliente.Inserir;
var
oClienteController: TClienteController;
oCliente: TCliente;
sErro: string;
begin
oClienteController := TClienteController.Create;
oCliente := TCliente.Create;
try
oCliente.ID := 0;
oCliente.Nome := edtNome.Text;
oCliente.Tipo := IfThen(cbxTipo.ItemIndex = 0, 'F', 'J');
oCliente.Documento := edtDocumento.Text;
oCliente.Telefone := edtTelefone.Text;
if not oClienteController.Inserir(oCliente, sErro) then
raise Exception.Create(sErro)
else
Application.MessageBox('Inserido com sucesso.', 'Atenção', MB_OK +
MB_ICONWARNING);
finally
oCliente.Free;
oClienteController.Free;
end;
end;
procedure TfrmCliente.Listar;
begin
pgcPrincipal.ActivePage := tbsPesquisa;
end;
procedure TfrmCliente.Novo;
begin
FOperacao := opNovo;
pgcPrincipal.ActivePage := tbsManutencao;
end;
function TfrmCliente.Pesquisar: TDataSet;
var
oClienteController: TClienteController;
begin
oClienteController := TClienteController.Create;
try
oClienteController.Pesquisar(edtPesquisa.Text);
finally
oClienteController.Free;
end;
end;
procedure TfrmCliente.SetMenuItem(const Value: TMenuItem);
begin
FMenuItem := Value;
end;
procedure TfrmCliente.ConfiguracaoPnlPesquisa;
begin
if grdDados.DataSource.DataSet.RecordCount > 0 then
begin
pnlPesquisa.Align := alClient;
pnlPesquisa.Visible := False;
pnlPesquisa.SendToBack;
lblQtdeRegistros.Caption := ' Total de Registros: ' + IntToStr(grdDados.DataSource.DataSet.RecordCount);
end
else
begin
pnlPesquisa.Align := alClient;
pnlPesquisa.Visible := True;
lblQtdeRegistros.Caption := 'Total de Registros: 0';
pnlPesquisa.BringToFront;
end;
end;
end.
|
unit AozoraParser;
interface
uses SysUtils, Classes, UniStrUtils, StreamUtils, JWBIO;
{
Aozora Bunko fragments:
《furigana》
text|text 《furigana》
<image inserts and tags>
only allowed on newlines
[#comment]
[#改ページ]
[#「さわり」に傍点]
}
type
TAozoraParser = class
protected
//Иногда удаётся угадать, какое слово подписано
procedure OnRuby(w, r: string); virtual;
procedure OnTag(s: string); virtual;
procedure OnComment(s: string); virtual;
procedure OnChar(c: char); virtual;
procedure OnStr(s: string);
public
procedure Parse(ASource: TStream);
end;
TAozoraStats = record
CharCount: integer;
RubyCount: integer;
RubySz: integer;
TagCount: integer;
TagSz: integer;
CommentCount: integer;
CommentSz: integer;
end;
TAozoraStatParser = class(TAozoraParser)
protected
procedure OnRuby(w: string; s: string); override;
procedure OnTag(s: string); override;
procedure OnComment(s: string); override;
public
Stats: TAozoraStats;
end;
TAozoraStripParser = class(TAozoraStatParser)
protected
FWriter: TStreamEncoder;
procedure OnChar(c: char); override;
public
procedure Parse(ASource: TStream; AOutput: TStream); reintroduce;
end;
implementation
const
MAX_PRERUBY_LENGTH = 100;
MAX_RUBY_LENGTH = 50;
MAX_TAG_LENGTH = 200;
MAX_COMMENT_LENGTH = 200;
type
TParsingMode = (pmNormal, pmPreruby, pmRuby, pmTag, pmComment);
procedure TAozoraParser.Parse(ASource: TStream);
var r: TStreamDecoder;
c, prevchar: UniChar;
pm: TParsingMode;
PreRuby: string;
LineCnt: integer;
s: string;
ln: string;
i: integer;
begin
pm := pmNormal;
LineCnt := 0;
s := '';
PreRuby := '';
r := OpenStream(ASource, {OwnsStream=}false);
try
while r.ReadLn(ln) do begin
Inc(LineCnt);
c := #00;
for i := 1 to Length(ln) do begin
prevchar := c;
c := ln[i];
if (pm in [pmNormal]) and (c='|') then begin
pm := pmPreRuby;
PreRuby := '';
continue;
end;
if (pm in [pmNormal, pmPreRuby]) and (c='《') then begin
pm := pmRuby;
s := '';
continue;
end;
if (pm = pmPreRuby) then begin
PreRuby := PreRuby + c;
if Length(PreRuby)>MAX_PRERUBY_LENGTH then begin
pm := pmNormal;
writeln(ErrOutput, 'Broken pre-ruby found with no ruby @ line '+IntToStr(LineCnt));
OnChar('|');
OnStr(PreRuby);
end;
continue;
end;
if (pm = pmRuby) and (c='》') then begin
pm := pmNormal;
OnRuby(PreRuby, s);
PreRuby := '';
continue;
end;
if (pm = pmRuby) then begin
s := s + c;
if Length(s)>MAX_RUBY_LENGTH then begin
pm := pmNormal;
OnRuby('', ''); //register as empty
writeln(ErrOutput, 'Broken ruby found with no closing @ line '+IntToStr(LineCnt));
if PreRuby<>'' then begin
OnChar('|');
OnStr(PreRuby);
end;
OnChar('《'); //have to guess that was legal
OnStr(s);
PreRuby := '';
end;
continue;
end;
if (pm in [pmNormal]) and (c='<') and (prevchar=#00) then begin
pm := pmTag;
s := '';
continue;
end;
if (pm = pmTag) and (c='>') then begin
pm := pmNormal;
OnTag(s);
continue;
end;
if (pm = pmTag) then begin
s := s + c;
if Length(s)>MAX_TAG_LENGTH then begin
pm := pmNormal;
OnTag(''); //register as empty
writeln(ErrOutput, 'Broken tag found with no closing @ line '+IntToStr(LineCnt));
OnChar('<');
OnStr(s);
end;
continue;
end;
if (pm in [pmNormal]) and (c='#') and (prevchar='[') then begin
pm := pmComment;
s := '';
continue;
end;
if (pm = pmComment) and (c=']') then begin
pm := pmNormal;
OnComment(s);
continue;
end;
if (pm = pmComment) then begin
s := s + c;
if Length(s)>MAX_COMMENT_LENGTH then begin
pm := pmNormal;
OnComment(''); //register as empty
writeln(ErrOutput, 'Broken comment found with no closing @ line '+IntToStr(LineCnt));
OnStr('[#');
OnStr(s);
end;
continue;
end;
//Finally, more broken stuff detection
if c='》' then
writeln(ErrOutput, 'Broken ruby found with no opening @ line '+IntToStr(LineCnt));
//can't test for > since it's used in comparisons and smiles
//can't test for ] since there could be legal [s without #
OnChar(c);
end;
end;
finally
FreeAndNil(r);
end;
end;
procedure TAozoraParser.OnRuby(w, r: string);
begin
//Normally we process W as text
OnStr(w);
end;
procedure TAozoraParser.OnTag(s: string);
begin
end;
procedure TAozoraParser.OnComment(s: string);
begin
end;
procedure TAozoraParser.OnChar(c: char);
begin
end;
//Same as OnChar, only several characters
procedure TAozoraParser.OnStr(s: string);
var i: integer;
begin
for i := 1 to Length(s) do
OnChar(s[i]);
end;
procedure TAozoraStatParser.OnRuby(w, s: string);
begin
Inc(Stats.RubyCount);
Inc(Stats.RubySz, Length(s));
inherited;
end;
procedure TAozoraStatParser.OnTag(s: string);
begin
Inc(Stats.TagCount);
Inc(Stats.TagSz, Length(s));
inherited;
end;
procedure TAozoraStatParser.OnComment(s: string);
begin
Inc(Stats.CommentCount);
Inc(Stats.CommentSz, Length(s));
inherited;
end;
procedure TAozoraStripParser.Parse(ASource: TStream; AOutput: TStream);
begin
FreeAndNil(FWriter); //if we had one
FWriter := WriteToStream(AOutput, false, TUTF16Encoding);
inherited Parse(ASource);
end;
procedure TAozoraStripParser.OnChar(c: char);
begin
if Assigned(FWriter) then
FWriter.WriteChar(c);
inherited;
end;
end.
|
unit uDMPuppyTracker;
interface
uses
SysUtils, Classes, DB, DBClient;
const
LINE_TYPE_PUPS = 'pups';
LINE_TYPE_LITTERS = 'litters';
LINE_TYPE_BREED = 'breed';
LINE_TYPE_BREEDERS = 'breeders';
LINE_TYPE_HOUSESHOTS = 'houseshots';
LINE_TYPE_PUPPYSHOTS = 'puppyshots';
LINE_TYPE_VACCINES = 'vaccines';
LINE_TYPE_VACCMANU = 'vaccmanu';
LINE_TYPE_DEFECTS = 'defects';
LINE_TYPE_PEDIGREES = 'Pedigrees';
type
TDMPuppyTracker = class(TDataModule)
cdsPup: TClientDataSet;
cdsPupPuppy_No: TStringField;
cdsPupBreed: TStringField;
cdsPupSex: TStringField;
cdsPupPur_Price: TCurrencyField;
cdsPupWeight: TCurrencyField;
cdsPupColor: TStringField;
cdsPupUSDA: TStringField;
cdsPupSales_Price: TCurrencyField;
cdsPupChip_No: TStringField;
cdsPupDied_Date: TDateTimeField;
cdsPupComments: TStringField;
cdsPupInvoice_Date: TDateTimeField;
cdsPupDate_Purchased: TDateTimeField;
cdsPupLitter_No: TStringField;
cdsLitters: TClientDataSet;
cdsLittersLitter_No: TStringField;
cdsLittersDam: TStringField;
cdsLittersSire: TStringField;
cdsLittersBreeder: TStringField;
cdsLittersRegistry_No: TStringField;
cdsLittersWhelp_Date: TDateTimeField;
cdsLittersRegistry: TStringField;
cdsBreed: TClientDataSet;
cdsBreedBreed_Code: TStringField;
cdsBreedBreed_Name: TStringField;
cdsBreedSpecies: TStringField;
cdsBreeder: TClientDataSet;
cdsBreederBreeder: TStringField;
cdsBreederAddress1: TStringField;
cdsBreederCity: TStringField;
cdsBreederState: TStringField;
cdsBreederZip: TStringField;
cdsBreederFirst_Name: TStringField;
cdsBreederLast_Name: TStringField;
cdsHouseShots: TClientDataSet;
cdsHouseShotsVaccine_Code: TStringField;
cdsHouseShotsManu_Code: TStringField;
cdsHouseShotsWeek_Ending_Date: TDateTimeField;
cdsHouseShotsSpecies: TStringField;
cdsHouseShotsLot: TStringField;
cdsHouseShotsExpires: TDateTimeField;
cdsHouseShotsDates_Given: TStringField;
cdsPuppyShots: TClientDataSet;
cdsPuppyShotsPuppy_No: TStringField;
cdsPuppyShotsVaccine_Code: TStringField;
cdsPuppyShotsManu_Code: TStringField;
cdsPuppyShotsLot: TStringField;
cdsPuppyShotsExpires: TDateTimeField;
cdsPuppyShotsDates_Given: TStringField;
cdsVaccines: TClientDataSet;
cdsVaccinesVaccine_Code: TStringField;
cdsVaccinesType: TIntegerField;
cdsVaccinesVaccine_Name: TStringField;
cdsVaccManu: TClientDataSet;
cdsVaccManuManu_Code: TStringField;
cdsVaccManuManufacturer: TStringField;
cdsDefects: TClientDataSet;
cdsDefectsDefect_Code: TStringField;
cdsDefectsdefect_description: TStringField;
cdsPedigrees: TClientDataSet;
cdsPedigreesregistrycode: TStringField;
cdsPedigreesdog_name: TStringField;
cdsPedigreessire_name: TStringField;
cdsPedigreesdam_name: TStringField;
cdsPedigreesakc_registry: TStringField;
cdsPupDefects: TStringField;
cdsPupSurgery: TStringField;
cdsLittersLitter_Pur_Date: TDateTimeField;
cdsPupInv_Comments: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FPuppyData : TStringList;
function LoadDataFromFile : Boolean;
function GetLineType(sLine : String) : Boolean;
function ImportPupLine(sLine : String) : Boolean;
function ImportLitterLine(sLine : String) : Boolean;
function ImportBreedLine(sLine : String) : Boolean;
function ImportBreederLine(sLine : String) : Boolean;
function ImportHouseShotsLine(sLine : String) : Boolean;
function ImportPuppyShotsLine(sLine : String) : Boolean;
function ImportVaccinesLine(sLine : String) : Boolean;
function ImportVaccManuLine(sLine : String) : Boolean;
function ImportDefectsLine(sLine : String) : Boolean;
function ImportPedigreesLine(sLine : String) : Boolean;
procedure CloseCDS;
procedure OpenCDS;
public
function LoadPuppyTrackerData(FFilePath : String) : Boolean;
function ParseFieldData(sLine, sField : String) : String;
function FormatSpecies(sSpecies : String) : String;
function FormatVaccineType(sType : String) : Integer;
end;
implementation
uses StrUtils, uDateTimeFunctions, uNumericFunctions;
{$R *.dfm}
{ TDMPuppyTracker }
{
--Treatment
Treatment
TreatmentType
Mfg
TreatmentLotSize
--TreatmentLot
LotNumber
ExpirationDate
--Pet
SKU
Microchip
Collar
--Pet_PetTreatment
IDUser
ExpirationDate
DosesUsed
TreatmentDate
Notes
litters.Litter_Pur_Date < houseshots.Week_Ending_Date
Adicionar treatment
}
function TDMPuppyTracker.LoadPuppyTrackerData(FFilePath: String): Boolean;
begin
Result := False;
if FileExists(FFilePath) then
begin
FPuppyData.LoadFromFile(FFilePath);
Result := LoadDataFromFile;
end;
end;
procedure TDMPuppyTracker.DataModuleCreate(Sender: TObject);
begin
FPuppyData := TStringList.Create;
end;
procedure TDMPuppyTracker.DataModuleDestroy(Sender: TObject);
begin
CloseCDS;
FreeAndNil(FPuppyData);
end;
function TDMPuppyTracker.LoadDataFromFile: Boolean;
var
i : Integer;
begin
Result := True;
try
CloseCDS;
OpenCDS;
for i := 0 to FPuppyData.Count-1 do
GetLineType(FPuppyData.Strings[i]);
except
raise;
Result := False;
end;
end;
procedure TDMPuppyTracker.CloseCDS;
begin
cdsPup.Close;
cdsLitters.Close;
cdsBreed.Close;
cdsBreeder.Close;
cdsHouseShots.Close;
cdsPuppyShots.Close;
cdsVaccines.Close;
cdsVaccManu.Close;
cdsDefects.Close;
cdsPedigrees.Close;
end;
procedure TDMPuppyTracker.OpenCDS;
begin
cdsPup.CreateDataSet;
cdsLitters.CreateDataSet;
cdsBreed.CreateDataSet;
cdsBreeder.CreateDataSet;
cdsHouseShots.CreateDataSet;
cdsPuppyShots.CreateDataSet;
cdsVaccines.CreateDataSet;
cdsVaccManu.CreateDataSet;
cdsDefects.CreateDataSet;
cdsPedigrees.CreateDataSet;
end;
function TDMPuppyTracker.GetLineType(sLine: String): Boolean;
var
iEndType : Integer;
begin
Result := False;
iEndType := Pos('{', sLine);
if Copy(sLine, 2, iEndType-2) = LINE_TYPE_PUPS then
Result := ImportPupLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_LITTERS then
Result := ImportLitterLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_BREED then
Result := ImportBreedLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_BREEDERS then
Result := ImportBreederLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_HOUSESHOTS then
Result := ImportHouseShotsLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_PUPPYSHOTS then
Result := ImportPuppyShotsLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_VACCINES then
Result := ImportVaccinesLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_VACCMANU then
Result := ImportVaccManuLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_DEFECTS then
Result := ImportDefectsLine(sLine)
else if Copy(sLine, 2, iEndType-2) = LINE_TYPE_PEDIGREES then
Result := ImportPedigreesLine(sLine);
end;
function TDMPuppyTracker.ImportPupLine(sLine : String) : Boolean;
begin
Result := True;
try
with cdsPup do
begin
Append;
FieldByName('Puppy_No').Value := ParseFieldData(sLine, 'Puppy_No');
FieldByName('Breed').Value := ParseFieldData(sLine, 'Breed');
FieldByName('Sex').Value := ParseFieldData(sLine, 'Sex');
FieldByName('Weight').Value := ParseFieldData(sLine, 'Weight');
FieldByName('Color').Value := ParseFieldData(sLine, 'Color');
FieldByName('USDA').Value := ParseFieldData(sLine, 'USDA');
FieldByName('Chip_No').Value := ParseFieldData(sLine, 'Chip_No');
FieldByName('Comments').Value := ParseFieldData(sLine, 'Comments');
FieldByName('Defects').Value := ParseFieldData(sLine, 'Defects');
FieldByName('Surgery').Value := ParseFieldData(sLine, 'Surgery');
FieldByName('Litter_No').Value := ParseFieldData(sLine, 'Litter_No');
FieldByName('Inv_Comments').Value := ParseFieldData(sLine, 'Inv_Comments');
FieldByName('Sales_Price').Value := MyStrToMoney(ParseFieldData(sLine, 'Sales_Price'));
FieldByName('Pur_Price').Value := MyStrToMoney(ParseFieldData(sLine, 'Pur_Price'));
FieldByName('Died_Date').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Died_Date'), 0);
FieldByName('Invoice_Date').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Invoice_Date'), 0);
FieldByName('Date_Purchased').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Date_Purchased'), 0) - 5;
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportLitterLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsLitters do
begin
Append;
FieldByName('Dam').Value := ParseFieldData(sLine, 'Dam');
FieldByName('Sire').Value := ParseFieldData(sLine, 'Sire');
FieldByName('Breeder').Value := ParseFieldData(sLine, 'Breeder');
FieldByName('Registry_No').Value := ParseFieldData(sLine, 'Registry_No');
FieldByName('Registry').Value := ParseFieldData(sLine, 'Registry');
FieldByName('Litter_No').Value := ParseFieldData(sLine, 'Litter_No');
FieldByName('Whelp_Date').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Whelp_Date'), 0);
FieldByName('Litter_Pur_Date').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Litter_Pur_Date'), 0);
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportBreedLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsBreed do
begin
Append;
FieldByName('Breed_Name').Value := ParseFieldData(sLine, 'Breed_Name');
FieldByName('Species').Value := FormatSpecies(ParseFieldData(sLine, 'Species'));
FieldByName('Breed_Code').Value := ParseFieldData(sLine, 'Breed_Code');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportBreederLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsBreeder do
begin
Append;
FieldByName('Breeder').Value := ParseFieldData(sLine, 'Breeder');
FieldByName('Address1').Value := ParseFieldData(sLine, 'Address1');
FieldByName('City').Value := ParseFieldData(sLine, 'City');
FieldByName('State').Value := ParseFieldData(sLine, 'State');
FieldByName('Zip').Value := ParseFieldData(sLine, 'Zip');
FieldByName('First_Name').Value := ParseFieldData(sLine, 'First_Name');
FieldByName('Last_Name').Value := ParseFieldData(sLine, 'Last_Name');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ParseFieldData(sLine, sField: String): String;
var
FFieldPos : Integer;
i : Integer;
begin
Result := '';
FFieldPos := Pos('{' + sField + '}', sLine) + Length('{' + sField + '}');
Result := Copy(sLine, FFieldPos, Length(sLine));
FFieldPos := Pos('\', Result) - 1;
Result := Copy(Result, 0, FFieldPos);
end;
function TDMPuppyTracker.FormatSpecies(sSpecies: String): String;
begin
if sSpecies = 'D' then
Result := 'Dog'
else if sSpecies = 'C' then
Result := 'Cat'
else
Result := 'Dog';
end;
function TDMPuppyTracker.ImportHouseShotsLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsHouseShots do
begin
Append;
FieldByName('Vaccine_Code').Value := ParseFieldData(sLine, 'Vaccine_Code');
FieldByName('Manu_Code').Value := ParseFieldData(sLine, 'Manu_Code');
FieldByName('Week_Ending_Date').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Week_Ending_Date'), 0);
FieldByName('Species').Value := FormatSpecies(ParseFieldData(sLine, 'Species'));
FieldByName('Lot').Value := ParseFieldData(sLine, 'Lot');
FieldByName('Expires').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Expires'), 0);
FieldByName('Dates_Given').Value := ParseFieldData(sLine, 'Dates_Given');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportPuppyShotsLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsPuppyShots do
begin
Append;
FieldByName('Puppy_No').Value := ParseFieldData(sLine, 'Puppy_No');
FieldByName('Vaccine_Code').Value := ParseFieldData(sLine, 'Vaccine_Code');
FieldByName('Manu_Code').Value := ParseFieldData(sLine, 'Manu_Code');
FieldByName('Lot').Value := ParseFieldData(sLine, 'Lot');
FieldByName('Expires').Value := StrToDateTimeDef(ParseFieldData(sLine, 'Expires'), 0);
FieldByName('Dates_Given').Value := ParseFieldData(sLine, 'Dates_Given');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportVaccinesLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsVaccines do
begin
Append;
FieldByName('Vaccine_Code').Value := ParseFieldData(sLine, 'Vaccine_Code');
FieldByName('Vaccine_Name').Value := ParseFieldData(sLine, 'Vaccine_Name');
FieldByName('Type').Value := FormatVaccineType(ParseFieldData(sLine, 'Type'));
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.FormatVaccineType(sType: String): Integer;
begin
if sType = 'V' then
Result := 1
else if sType = 'W' then
Result := 2
else if sType = 'P' then
Result := 3
else
Result := 1;
end;
function TDMPuppyTracker.ImportVaccManuLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsVaccManu do
begin
Append;
FieldByName('Manu_Code').Value := ParseFieldData(sLine, 'Man_Code');
FieldByName('Manufacturer').Value := ParseFieldData(sLine, 'Manufacturer');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportDefectsLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsDefects do
begin
Append;
FieldByName('Defect_Code').Value := ParseFieldData(sLine, 'Defect_Code');
FieldByName('defect_description').Value := ParseFieldData(sLine, 'defect_description');
Post;
end;
except
raise;
Result := False;
end;
end;
function TDMPuppyTracker.ImportPedigreesLine(sLine: String): Boolean;
begin
Result := True;
try
with cdsPedigrees do
begin
Append;
FieldByName('registrycode').Value := ParseFieldData(sLine, 'registrycode');
FieldByName('dog_name').Value := ParseFieldData(sLine, 'dog_name');
FieldByName('sire_name').Value := ParseFieldData(sLine, 'sire_name');
FieldByName('dam_name').Value := ParseFieldData(sLine, 'dam_name');
FieldByName('akc_registry').Value := ParseFieldData(sLine, 'akc_registry');
Post;
end;
except
raise;
Result := False;
end;
end;
end.
|
unit Module;
interface
uses
SDK;
procedure MainOutMessasge(Msg: string; nMode: Integer);
function GetProcAddr(sProcName: string; nCode: Integer): Pointer;
function GetProcCode(sProcName: string): Integer;
function SetProcAddr(ProcAddr: Pointer; sProcName: string; nCode: Integer): Boolean;
function SetProcCode(sProcName: string; nCode: Integer): Boolean;
function GetObjAddr(sObjName: string; nCode: Integer): TObject;
var
OutMessage: TMsgProc;
GetFunctionAddr: TGetFunAddr;
FindOBjTable_: TFindOBjTable_;
SetProcCode_: TSetProcCode_;
SetProcTable_: TSetProcTable_;
FindProcCode_: TFindProcCode_;
FindProcTable_: TFindProcTable_;
implementation
procedure MainOutMessasge(Msg: string; nMode: Integer);
begin
if Assigned(OutMessage) then begin
OutMessage(PChar(Msg), Length(Msg), nMode);
end;
end;
function GetProcAddr(sProcName: string; nCode: Integer): Pointer;
var
Obj: TObject;
begin
Result := nil;
if Assigned(FindProcTable_) then begin
Result := FindProcTable_(PChar(sProcName), Length(sProcName), nCode);
end;
end;
function GetProcCode(sProcName: string): Integer;
begin
Result := -1;
if Assigned(FindProcCode_) then begin
Result := FindProcCode_(PChar(sProcName), Length(sProcName));
end;
end;
function GetObjAddr(sObjName: string; nCode: Integer): TObject;
begin
Result := nil;
if Assigned(FindOBjTable_) then begin
Result := FindOBjTable_(PChar(sObjName), Length(sObjName), nCode);
end;
end;
function SetProcAddr(ProcAddr: Pointer; sProcName: string; nCode: Integer): Boolean;
var
Obj: TObject;
begin
Result := False;
if Assigned(SetProcTable_) then begin
Result := SetProcTable_(ProcAddr, PChar(sProcName), Length(sProcName), nCode);
end;
end;
function SetProcCode(sProcName: string; nCode: Integer): Boolean;
var
Obj: TObject;
begin
Result := False;
if Assigned(SetProcCode_) then begin
Result := SetProcCode_(PChar(sProcName), Length(sProcName), nCode);
end;
end;
end.
|
unit uDSON;
//Delphi JSON Serializer
interface
uses
System.SysUtils, System.Rtti, System.TypInfo, System.JSON,
System.Generics.Collections, System.Classes;
type
SerializedNameAttribute = class(TCustomAttribute)
strict private
FName: string;
public
constructor Create(const name: string);
property name: string read FName;
end;
DefValueAttribute = class(TCustomAttribute)
strict private
FValue: TValue;
public
constructor Create(const defValue: Integer); overload;
constructor Create(const defValue: string); overload;
constructor Create(const defValue: Single); overload;
constructor Create(const defValue: Double); overload;
constructor Create(const defValue: Extended); overload;
constructor Create(const defValue: Currency); overload;
constructor Create(const defValue: Int64); overload;
constructor Create(const defValue: Boolean); overload;
property defVal: TValue read FValue;
end;
EDSONException = class(Exception);
TDSON = record
public
class function fromJson<T>(const json: string): T; overload; static;
class function fromJson<T>(const jsonStream: TStream): T; overload; static;
class function toJson<T>(const value: T; const ignoreUnknownTypes: Boolean = False): string; static;
end;
IMap<K, V> = interface
['{830D3690-DAEF-40D1-A186-B6B105462D89}']
function getKeys(): TEnumerable<K>;
function getValues(): TEnumerable<V>;
procedure add(const key: K; const value: V);
procedure remove(const key: K);
function extractPair(const key: K): TPair<K, V>;
procedure clear;
function getValue(const key: K): V;
function tryGetValue(const key: K; out value: V): Boolean;
procedure addOrSetValue(const key: K; const value: V);
function containsKey(const key: K): Boolean;
function containsValue(const value: V): Boolean;
function toArray(): TArray<TPair<K, V>>;
function getCount(): Integer;
function getEnumerator: TEnumerator<TPair<K, V>>;
property keys: TEnumerable<K> read getKeys;
property values: TEnumerable<V> read getValues;
property items[const key: K]: V read getValue write addOrSetValue;
property count: Integer read getCount;
end;
TMapClass<K, V> = class(TInterfacedObject, IMap<K,V>)
private
FMap: TDictionary<K, V>;
public
constructor Create();
destructor Destroy(); override;
function getKeys(): TEnumerable<K>;
function getValues(): TEnumerable<V>;
procedure add(const key: K; const value: V);
procedure remove(const key: K);
function extractPair(const key: K): TPair<K, V>;
procedure clear;
function getValue(const key: K): V;
function tryGetValue(const key: K; out value: V): Boolean;
procedure addOrSetValue(const key: K; const value: V);
function containsKey(const key: K): Boolean;
function containsValue(const value: V): Boolean;
function toArray(): TArray<TPair<K, V>>;
function getCount(): Integer;
function getEnumerator: TEnumerator<TPair<K, V>>;
property Keys: TEnumerable<K> read getKeys;
property Values: TEnumerable<V> read getValues;
property items[const key: K]: V read getValue write addOrSetValue;
property count: Integer read getCount;
end;
TMap<K, V> = record
private
FMapIntf: IMap<K, V>;
{$HINTS OFF}
FValueType: V;
FKeyType: K;
{$HINTS ON}
function getMap(): IMap<K, V>;
public
function getKeys(): TEnumerable<K>;
function getValues(): TEnumerable<V>;
procedure add(const key: K; const value: V);
procedure remove(const key: K);
function extractPair(const key: K): TPair<K, V>;
procedure clear;
function getValue(const key: K): V;
function tryGetValue(const key: K; out value: V): Boolean;
procedure addOrSetValue(const key: K; const value: V);
function containsKey(const key: K): Boolean;
function containsValue(const value: V): Boolean;
function toArray(): TArray<TPair<K, V>>;
function getCount(): Integer;
function getEnumerator: TEnumerator<TPair<K, V>>;
property keys: TEnumerable<K> read getKeys;
property values: TEnumerable<V> read getValues;
property items[const key: K]: V read getValue write addOrSetValue;
property count: Integer read getCount;
end;
type
TDSONBase = class
private class var
booleanTi: Pointer;
protected
FRttiContext: TRttiContext;
function getObjInstance(const value: TValue): Pointer;
public
constructor Create();
destructor Destroy(); override;
end;
TDSONValueReader = class(TDSONBase)
strict private
function readIntegerValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readInt64Value(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readFloatValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readStringValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readEnumValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readClassValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readRecordValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readDynArrayValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
function readDynArrayValues(const rttiType: TRttiType; const jv: TJSONValue): TArray<TValue>;
function readSetValue(const rttiType: TRttiType; const jv: TJSONValue): TValue;
procedure setObjValue(const instance: TValue; const rttiMember: TRttiMember;
const jv: TJSONValue);
procedure fillObjectValue(const instance: TValue; const jo: TJSONObject);
procedure fillMapValue(const instance: TValue; const jo: TJSONObject);
function tryReadValueFromJson(const rttiType: TRttiType; const jv: TJSONValue;
var outV: TValue): Boolean;
public
function processRead(const _typeInfo: PTypeInfo; const jv: TJSONValue): TValue;
end;
TDSONValueWriter = class(TDSONBase)
strict private
FIgnoreUnknownTypes: Boolean;
function writeIntegerValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeInt64Value(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeFloatValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeStringValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeEnumValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeClassValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeDynArrayValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function writeSetValue(const rttiType: TRttiType; const value: TValue): TJSONValue;
function getObjValue(const instance: TValue; const rttiMember: TRttiMember): TJSONValue;
function writeObject(const instance: TValue): TJSONObject;
function writeMap(const instance: TValue): TJSONObject;
function tryWriteJsonValue(const value: TValue; var jv: TJSONValue): Boolean;
public
function processWrite(const value: TValue; const ignoreUnknownTypes: Boolean): TJSONValue;
end;
function DSON(): TDSON;
resourcestring
rsNotSupportedType = 'Not supported type %s, type kind: %s';
rsInvalidJsonArray = 'Json value is not array.';
rsInvalidJsonObject = 'Json value is not object.';
implementation
const
MAP_PREFIX = 'TMap<';
function DSON(): TDSON;
begin
end;
type
TRttiMemberHelper = class helper for TRttiMember
private
function hasAttribute<A: TCustomAttribute>(var attr: A): Boolean; overload;
public
procedure setValue(const instance: Pointer; const value: TValue);
function getValue(const instance: Pointer): TValue;
function getType(): TRttiType;
function canWrite(): Boolean;
function canRead(): Boolean;
function getName(): string;
end;
{ TDSONValueReader }
procedure TDSONValueReader.fillMapValue(const instance: TValue;
const jo: TJSONObject);
var
rttiType: TRttiType;
addMethod: TRttiMethod;
valueType: TRttiType;
keyType: TRttiType;
jp: TJSONPair;
key: TValue;
value: TValue;
begin
rttiType := FRttiContext.GetType(instance.TypeInfo);
addMethod := rttiType.GetMethod('addOrSetValue');
keyType := rttiType.GetField('FKeyType').FieldType;
valueType := rttiType.GetField('FValueType').FieldType;
for jp in jo do
begin
if tryReadValueFromJson(keyType, jp.JsonString, key) and tryReadValueFromJson(valueType, jp.JsonValue, value) then
addMethod.Invoke(instance, [key, value])
end;
end;
procedure TDSONValueReader.fillObjectValue(const instance: TValue;
const jo: TJSONObject);
procedure processReadRttiMember(const rttiMember: TRttiMember);
var
propertyName: string;
jv: TJSONValue;
begin
if not ((rttiMember.Visibility in [mvPublic, mvPublished]) and rttiMember.canWrite()) then
Exit();
propertyName := rttiMember.getName();
jv := jo.GetValue(propertyName);
setObjValue(instance, rttiMember, jv);
end;
var
rttiType: TRttiType;
rttiMember: TRttiMember;
begin
rttiType := FRttiContext.GetType(instance.TypeInfo);
for rttiMember in rttiType.GetDeclaredProperties() do
processReadRttiMember(rttiMember);
for rttiMember in rttiType.GetDeclaredFields() do
processReadRttiMember(rttiMember);
end;
function TDSONValueReader.readEnumValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
var
enumItemName: string;
i: Int64;
begin
if rttiType.Handle = booleanTi then
Result := jv.GetValue<Boolean>()
else
begin
enumItemName := jv.Value;
i := GetEnumValue(rttiType.Handle, enumItemName);
Result := TValue.FromOrdinal(rttiType.Handle, i);
end;
end;
function TDSONValueReader.readClassValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
var
ret: TValue;
begin
if not (jv is TJSONObject) then
raise EDSONException.Create(rsInvalidJsonObject);
ret := rttiType.GetMethod('Create').Invoke(rttiType.AsInstance.MetaclassType, []);
try
fillObjectValue(ret, jv as TJSONObject);
Result := ret;
except
ret.AsObject.Free();
raise;
end;
end;
function TDSONValueReader.readDynArrayValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
begin
Result := TValue.FromArray(rttiType.Handle, readDynArrayValues(rttiType, jv));
end;
function TDSONValueReader.readDynArrayValues(const rttiType: TRttiType;
const jv: TJSONValue): TArray<TValue>;
var
ja: TJSONArray;
jav: TJSONValue;
i: Integer;
values: TArray<TValue>;
elementType: TRttiType;
begin
if not (jv is TJSONArray) then
raise EDSONException.Create(rsInvalidJsonArray);
ja := jv as TJSONArray;
elementType := (rttiType as TRttiDynamicArrayType).ElementType;
SetLength(values, ja.Count);
for i := 0 to ja.Count - 1 do
begin
values[i] := TValue.Empty;
jav := ja.Items[i];
tryReadValueFromJson(elementType, jav, values[i])
end;
Result := values;
end;
function TDSONValueReader.readFloatValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
var
rft: TRttiFloatType;
begin
rft := rttiType as TRttiFloatType;
case rft.FloatType of
ftSingle: Result := jv.GetValue<Single>();
ftDouble: Result := jv.GetValue<Double>();
ftExtended: Result := jv.GetValue<Extended>();
ftComp: Result := jv.GetValue<Comp>();
ftCurr: Result := jv.GetValue<Currency>();
end;
end;
function TDSONValueReader.readInt64Value(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
begin
Result := jv.GetValue<Int64>();
end;
function TDSONValueReader.readIntegerValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
begin
Result := jv.GetValue<Integer>();
end;
function TDSONValueReader.readRecordValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
var
ret: TValue;
rttiRecord: TRttiRecordType;
begin
if not (jv is TJSONObject) then
raise EDSONException.Create(rsInvalidJsonObject);
rttiRecord := rttiType as TRttiRecordType;
TValue.Make(nil, rttiRecord.Handle, ret);
if rttiType.Name.StartsWith(MAP_PREFIX) then
fillMapValue(ret, jv as TJSONObject)
else
fillObjectValue(ret, jv as TJSONObject);
Result := ret;
end;
function TDSONValueReader.readSetValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
begin
TValue.Make(nil, rttiType.Handle, Result);
StringToSet(rttiType.Handle, jv.GetValue<string>(), Result.GetReferenceToRawData());
end;
function TDSONValueReader.readStringValue(const rttiType: TRttiType;
const jv: TJSONValue): TValue;
var
rst: TRttiStringType;
begin
rst := rttiType as TRttiStringType;
case rst.StringKind of
skShortString: Result := TValue.From(jv.GetValue<ShortString>());
skAnsiString: Result := TValue.From(jv.GetValue<AnsiString>());
skWideString: Result := TValue.From(jv.GetValue<WideString>());
skUnicodeString: Result := jv.GetValue<string>();
end;
end;
procedure TDSONValueReader.setObjValue(const instance: TValue;
const rttiMember: TRttiMember; const jv: TJSONValue);
var
value: TValue;
rttiType: TRttiType;
instanceP: Pointer;
defValueAttr: DefValueAttribute;
begin
instanceP := getObjInstance(instance);
value := rttiMember.getValue(instanceP);
rttiType := rttiMember.getType();
if value.IsObject then
value.AsObject.Free();
if tryReadValueFromJson(rttiType, jv, value) then
rttiMember.setValue(instanceP, value)
else if rttiMember.hasAttribute<DefValueAttribute>(defValueAttr) then
rttiMember.setValue(instanceP, defValueAttr.defVal);
end;
function TDSONValueReader.processRead(const _typeInfo: PTypeInfo; const jv: TJSONValue): TValue;
begin
Result := TValue.Empty;
tryReadValueFromJson(FRttiContext.GetType(_typeInfo), jv, Result)
end;
function TDSONValueReader.tryReadValueFromJson(const rttiType: TRttiType;
const jv: TJSONValue; var outV: TValue): Boolean;
var
tk: TTypeKind;
begin
Result := False;
if (jv = nil) or jv.Null then
Exit();
tk := rttiType.TypeKind;
case tk of
tkInteger: outV := readIntegerValue(rttiType, jv);
tkInt64: outV := readInt64Value(rttiType, jv);
tkEnumeration: outV := readEnumValue(rttiType, jv);
tkFloat: outV := readFloatValue(rttiType, jv);
tkString, tkLString, tkWString, tkUString: outV := readStringValue(rttiType, jv);
tkClass: outV := readClassValue(rttiType, jv);
tkDynArray, tkArray: outV := readDynArrayValue(rttiType, jv);
tkRecord: outV := readRecordValue(rttiType, jv);
tkSet: outV := readSetValue(rttiType, jv);
else
raise EDSONException.CreateFmt(rsNotSupportedType, [rttiType.Name]);
end;
Result := True;
end;
{ TDSON }
class function TDSON.fromJson<T>(const json: string): T;
var
dvr: TDSONValueReader;
jv: TJSONValue;
begin
jv := nil;
dvr := TDSONValueReader.Create();
try
jv := TJSONObject.ParseJSONValue(json);
Result := dvr.processRead(TypeInfo(T), jv).AsType<T>();
finally
jv.Free();
dvr.Free();
end;
end;
class function TDSON.fromJson<T>(const jsonStream: TStream): T;
var
dvr: TDSONValueReader;
jv: TJSONValue;
jsonData: TArray<Byte>;
begin
jv := nil;
dvr := TDSONValueReader.Create();
try
jsonStream.Position := 0;
SetLength(jsonData, jsonStream.Size);
jsonStream.ReadBuffer(Pointer(jsonData)^, jsonStream.Size);
jv := TJSONObject.ParseJSONValue(jsonData, 0);
Result := dvr.processRead(TypeInfo(T), jv).AsType<T>();
finally
jv.Free();
dvr.Free();
end;
end;
class function TDSON.toJson<T>(const value: T;
const ignoreUnknownTypes: Boolean): string;
var
dvw: TDSONValueWriter;
jv: TJSONValue;
begin
Result := '';
jv := nil;
dvw := TDSONValueWriter.Create();
try
jv := dvw.processWrite(TValue.From(value), ignoreUnknownTypes);
if jv <> nil then
Result := jv.ToJSON;
finally
jv.Free();
dvw.Free();
end;
end;
{ TDSONBase }
constructor TDSONBase.Create();
begin
FRttiContext := TRttiContext.Create();
end;
destructor TDSONBase.Destroy();
begin
FRttiContext.Free();
inherited;
end;
function TDSONBase.getObjInstance(const value: TValue): Pointer;
begin
if value.Kind = tkRecord then
Result := value.GetReferenceToRawData()
else if value.Kind = tkClass then
Result := value.AsObject
else
Result := nil;
end;
{ TDSONValueWriter }
function TDSONValueWriter.getObjValue(const instance: TValue;
const rttiMember: TRttiMember): TJSONValue;
var
value: TValue;
instanceP: Pointer;
begin
Result := nil;
instanceP := getObjInstance(instance);
value := rttiMember.GetValue(instanceP);
tryWriteJsonValue(value, Result);
end;
function TDSONValueWriter.processWrite(const value: TValue;
const ignoreUnknownTypes: Boolean): TJSONValue;
begin
Result := nil;
FIgnoreUnknownTypes := ignoreUnknownTypes;
tryWriteJsonValue(value, Result);
end;
function TDSONValueWriter.tryWriteJsonValue(const value: TValue;
var jv: TJSONValue): Boolean;
var
tk: TTypeKind;
rttiType: TRttiType;
begin
Result := False;
if value.IsEmpty then
Exit();
rttiType := FRttiContext.GetType(value.TypeInfo);
tk := rttiType.TypeKind;
case tk of
tkInteger: jv := writeIntegerValue(rttiType, value);
tkInt64: jv := writeInt64Value(rttiType, value);
tkEnumeration: jv := writeEnumValue(rttiType, value);
tkFloat: jv := writeFloatValue(rttiType, value);
tkString, tkLString, tkWString, tkUString: jv := writeStringValue(rttiType, value);
tkClass, tkRecord: jv := writeClassValue(rttiType, value);
tkDynArray, tkArray: jv := writeDynArrayValue(rttiType, value);
tkSet: jv := writeSetValue(rttiType, value);
else
if FIgnoreUnknownTypes then
Exit(False)
else
raise EDSONException.CreateFmt(rsNotSupportedType, [rttiType.Name, TRttiEnumerationType.GetName(tk)]);
end;
Result := True;
end;
function TDSONValueWriter.writeClassValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
if rttiType.Name.StartsWith(MAP_PREFIX) then
Result := writeMap(value)
else
Result := writeObject(value);
end;
function TDSONValueWriter.writeDynArrayValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
var
ret: TJSONArray;
jv: TJSONValue;
i: Integer;
begin
ret := TJSONArray.Create();
try
for i := 0 to value.GetArrayLength() - 1 do
begin
if tryWriteJsonValue(value.GetArrayElement(i), jv) then
ret.AddElement(jv);
end;
except
ret.Free();
raise;
end;
Result := ret;
end;
function TDSONValueWriter.writeEnumValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
var
enumItemName: string;
begin
if rttiType.Handle = booleanTi then
Result := TJSONBool.Create(value.AsBoolean)
else
begin
enumItemName := GetEnumName(value.TypeInfo, value.AsOrdinal);
Result := TJSONString.Create(enumItemName);
end;
end;
function TDSONValueWriter.writeFloatValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
Result := TJSONNumber.Create(value.AsExtended);
end;
function TDSONValueWriter.writeInt64Value(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
Result := TJSONNumber.Create(value.AsInt64);
end;
function TDSONValueWriter.writeIntegerValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
Result := TJSONNumber.Create(value.AsInteger);
end;
function TDSONValueWriter.writeMap(const instance: TValue): TJSONObject;
var
ret: TJSONObject;
rttiType: TRttiType;
toArrayMethod: TRttiMethod;
pairsArray: TValue;
arrayType: TRttiDynamicArrayType;
paitType: TRttiType;
keyField: TRttiField;
valueField: TRttiField;
pair: TValue;
i, c: Integer;
key: string;
begin
rttiType := FRttiContext.GetType(instance.TypeInfo);
toArrayMethod := rttiType.GetMethod('toArray');
pairsArray := toArrayMethod.Invoke(instance, []);
arrayType := FRttiContext.GetType(pairsArray.TypeInfo) as TRttiDynamicArrayType;
paitType := arrayType.ElementType;
keyField := paitType.GetField('Key');
valueField := paitType.GetField('Value');
ret := TJSONObject.Create();
try
c := pairsArray.GetArrayLength();
for i := 0 to c - 1 do
begin
pair := pairsArray.GetArrayElement(i);
key := keyField.getValue(pair.GetReferenceToRawData()).ToString;
ret.AddPair(TJSONPair.Create(key, getObjValue(pair, valueField)));
end;
Result := ret;
except
ret.Free();
raise;
end;
end;
function TDSONValueWriter.writeObject(const instance: TValue): TJSONObject;
var
ret: TJSONObject;
procedure processRttiMember(const rttiMember: TRttiMember);
var
propertyName: string;
jv: TJSONValue;
begin
if not ((rttiMember.Visibility in [mvPublic, mvPublished]) and rttiMember.canRead()) then
Exit();
propertyName := rttiMember.getName();
jv := getObjValue(instance, rttiMember);
if jv <> nil then
ret.AddPair(propertyName, jv);
end;
var
rttiType: TRttiType;
rttiMember: TRttiMember;
begin
Result := nil;
if instance.IsEmpty then
Exit();
rttiType := FRttiContext.GetType(instance.TypeInfo);
ret := TJSONObject.Create();
try
for rttiMember in rttiType.GetDeclaredProperties() do
processRttiMember(rttiMember);
for rttiMember in rttiType.GetDeclaredFields() do
processRttiMember(rttiMember);
Result := ret;
except
ret.Free();
raise;
end;
end;
function TDSONValueWriter.writeSetValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
Result := TJSONString.Create(SetToString(rttiType.Handle, value.GetReferenceToRawData(), True));
end;
function TDSONValueWriter.writeStringValue(const rttiType: TRttiType;
const value: TValue): TJSONValue;
begin
Result := TJSONString.Create(value.AsString);
end;
{ TRttiMemberHelper }
function TRttiMemberHelper.getName(): string;
var
attr: SerializedNameAttribute;
begin
if hasAttribute<SerializedNameAttribute>(attr) then
Result := attr.name
else
Result := Self.Name;
end;
function TRttiMemberHelper.getType(): TRttiType;
begin
if Self is TRttiProperty then
Result := (Self as TRttiProperty).PropertyType
else if Self is TRttiField then
Result := (Self as TRttiField).FieldType
else
Result := nil;
end;
function TRttiMemberHelper.getValue(const instance: Pointer): TValue;
begin
if Self is TRttiProperty then
Result := (Self as TRttiProperty).GetValue(instance)
else if Self is TRttiField then
Result := (Self as TRttiField).GetValue(instance)
else
Result := TValue.Empty;
end;
function TRttiMemberHelper.hasAttribute<A>(var attr: A): Boolean;
var
attribute: TCustomAttribute;
begin
attr := nil;
Result := False;
for attribute in self.GetAttributes() do
begin
if attribute is A then
begin
attr := A(attribute);
Result := True;
Break;
end;
end;
end;
function TRttiMemberHelper.canRead(): Boolean;
begin
if Self is TRttiProperty then
Result := (Self as TRttiProperty).IsReadable
else if Self is TRttiField then
Result := True
else
Result := False;
end;
function TRttiMemberHelper.canWrite(): Boolean;
begin
if Self is TRttiProperty then
Result := (Self as TRttiProperty).IsWritable
else if Self is TRttiField then
Result := True
else
Result := False;
end;
procedure TRttiMemberHelper.setValue(const instance: Pointer;
const value: TValue);
begin
if Self is TRttiProperty then
(Self as TRttiProperty).SetValue(instance, value)
else if Self is TRttiField then
(Self as TRttiField).SetValue(instance, value)
end;
{ SerializedNameAttribute }
constructor SerializedNameAttribute.Create(const name: string);
begin
FName := name;
end;
{ DefValueAttribute }
constructor DefValueAttribute.Create(const defValue: Integer);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Double);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Extended);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: string);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Single);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Boolean);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Currency);
begin
FValue := defValue;
end;
constructor DefValueAttribute.Create(const defValue: Int64);
begin
FValue := defValue;
end;
{ TMapClass<K, V> }
procedure TMapClass<K, V>.add(const key: K; const value: V);
begin
FMap.Add(key, value);
end;
procedure TMapClass<K, V>.addOrSetValue(const key: K; const value: V);
begin
FMap.AddOrSetValue(key, value);
end;
procedure TMapClass<K, V>.clear();
begin
FMap.Clear();
end;
function TMapClass<K, V>.containsKey(const key: K): Boolean;
begin
Result := FMap.ContainsKey(key);
end;
function TMapClass<K, V>.containsValue(const value: V): Boolean;
begin
Result := FMap.ContainsValue(value);
end;
constructor TMapClass<K, V>.Create();
begin
FMap := TDictionary<K, V>.Create();
end;
destructor TMapClass<K, V>.Destroy();
begin
FMap.Free();
inherited;
end;
function TMapClass<K, V>.extractPair(const key: K): TPair<K, V>;
begin
Result := FMap.ExtractPair(key);
end;
function TMapClass<K, V>.getCount(): Integer;
begin
Result := FMap.Count;
end;
function TMapClass<K, V>.getEnumerator(): TEnumerator<TPair<K, V>>;
begin
Result := FMap.GetEnumerator;
end;
function TMapClass<K, V>.getKeys(): TEnumerable<K>;
begin
Result := FMap.Keys;
end;
function TMapClass<K, V>.getValue(const key: K): V;
begin
Result := FMap[key];
end;
function TMapClass<K, V>.getValues(): TEnumerable<V>;
begin
Result := FMap.Values;
end;
procedure TMapClass<K, V>.remove(const key: K);
begin
FMap.Remove(key);
end;
function TMapClass<K, V>.toArray(): TArray<TPair<K, V>>;
begin
Result := FMap.ToArray;
end;
function TMapClass<K, V>.tryGetValue(const key: K; out value: V): Boolean;
begin
Result := FMap.TryGetValue(key, value);
end;
{ TMap<K, V> }
procedure TMap<K, V>.add(const key: K; const value: V);
begin
getMap().add(key, value);
end;
procedure TMap<K, V>.addOrSetValue(const key: K; const value: V);
begin
getMap().items[key] := value;
end;
procedure TMap<K, V>.clear();
begin
getMap().clear();
end;
function TMap<K, V>.containsKey(const key: K): Boolean;
begin
Result := getMap().containsKey(key);
end;
function TMap<K, V>.containsValue(const value: V): Boolean;
begin
Result := getMap().containsValue(value);
end;
function TMap<K, V>.extractPair(const key: K): TPair<K, V>;
begin
Result := getMap().extractPair(key);
end;
function TMap<K, V>.getCount(): Integer;
begin
Result := getMap().count;
end;
function TMap<K, V>.getEnumerator(): TEnumerator<TPair<K, V>>;
begin
Result := getMap().getEnumerator();
end;
function TMap<K, V>.getKeys(): TEnumerable<K>;
begin
Result := getMap().keys;
end;
function TMap<K, V>.getMap(): IMap<K, V>;
begin
if FMapIntf = nil then
FMapIntf := TMapClass<K, V>.Create();
Result := FMapIntf;
end;
function TMap<K, V>.getValue(const key: K): V;
begin
Result := getMap().items[key];
end;
function TMap<K, V>.getValues(): TEnumerable<V>;
begin
Result := getMap().values;
end;
procedure TMap<K, V>.remove(const key: K);
begin
getMap().remove(key);
end;
function TMap<K, V>.toArray(): TArray<TPair<K, V>>;
begin
Result := getMap().toArray();
end;
function TMap<K, V>.tryGetValue(const key: K; out value: V): Boolean;
begin
Result := getMap().tryGetValue(key, value);
end;
initialization
TDSONBase.booleanTi := TypeInfo(Boolean);
end.
|
unit htLabel;
interface
uses
SysUtils, Classes, Controls, Graphics,
LrGraphics, LrTextPainter,
htControls, htMarkup;
type
ThtLabel = class(ThtGraphicControl)
private
FTextPainter: TLrTextPainter;
protected
function GetHAlign: TLrHAlign;
function GetWordWrap: Boolean;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
procedure PerformAutoSize; override;
procedure SetHAlign(const Value: TLrHAlign);
procedure SetWordWrap(const Value: Boolean);
procedure StylePaint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
property TextPainter: TLrTextPainter read FTextPainter;
published
property Align;
property AutoSize;
property HAlign: TLrHAlign read GetHAlign write SetHAlign;
property Caption;
property Outline;
property Style;
property WordWrap: Boolean read GetWordWrap write SetWordWrap;
end;
implementation
{ ThtLabel }
constructor ThtLabel.Create(inOwner: TComponent);
begin
inherited;
FTextPainter := TLrTextPainter.Create;
TextPainter.Canvas := Canvas;
TextPainter.Transparent := true;
//TextPainter.OnChange := TextPainterChange;
end;
destructor ThtLabel.Destroy;
begin
TextPainter.Free;
inherited;
end;
function ThtLabel.GetHAlign: TLrHAlign;
begin
Result := TextPainter.HAlign;
end;
function ThtLabel.GetWordWrap: Boolean;
begin
Result := TextPainter.WordWrap;
end;
procedure ThtLabel.SetHAlign(const Value: TLrHAlign);
begin
TextPainter.HAlign := Value;
Invalidate;
end;
procedure ThtLabel.SetWordWrap(const Value: Boolean);
begin
TextPainter.WordWrap := Value;
Invalidate;
AdjustSize;
end;
procedure ThtLabel.PerformAutoSize;
begin
SetBounds(Left, Top, TextPainter.Width(Caption),
TextPainter.Height(Caption, ClientRect));
end;
procedure ThtLabel.StylePaint;
begin
inherited;
TextPainter.PaintText(Caption, ClientRect);
end;
procedure ThtLabel.Generate(const inContainer: string;
inMarkup: ThtMarkup);
function Prespace(const inString: string): string;
begin
if inString = '' then
Result := ''
else
Result := ' ' + inString;
end;
begin
GenerateStyle('#' + Name, inMarkup);
inMarkup.Styles.Add(
Format('#%s { width: %dpx; height: %dpx }',
[ Name, Width, Height ]));
inMarkup.Add(
Format('<span id="%s"%s>%s</span>',
[ Name, Prespace(ExtraAttributes), Caption ]));
//inMarkup.Add(
// Format('<div id="%s"%s>%s</div>',
// [ Name, Prespace(ExtraAttributes), Caption ]));
//inMarkup.Add(Caption);
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Quake2 MD2 vector file format implementation.
}
unit VXS.FileMD2;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.VectorFileObjects,
VXS.ApplicationFileIO,
uFileMD2;
type
{ The MD2 vector file (Quake2 actor file).
Stores a set of "frames" describing the different postures of the actor,
it may be animated by TVXActor. The "Skin" must be loaded indepentendly
(the whole mesh uses a single texture bitmap).
Based on code by Roger Cao. }
TVXMD2VectorFile = class(TVXVectorFile)
public
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
//===================================================================
implementation
//===================================================================
// ------------------
// ------------------ TVXMD2VectorFile ------------------
// ------------------
class function TVXMD2VectorFile.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead];
end;
procedure TVXMD2VectorFile.LoadFromStream(aStream: TStream);
var
i, j: Integer;
MD2File: TFileMD2;
mesh: TVXMorphableMeshObject;
faceGroup: TFGIndexTexCoordList;
morphTarget: TVXMeshMorphTarget;
begin
MD2File := TFileMD2.Create;
MD2File.LoadFromStream(aStream);
try
// retrieve mesh data
mesh := TVXMorphableMeshObject.CreateOwned(Owner.MeshObjects);
with mesh, MD2File do
begin
Mode := momFaceGroups;
faceGroup := TFGIndexTexCoordList.CreateOwned(FaceGroups);
with faceGroup do
begin
MaterialName := '';
VertexIndices.Capacity := iTriangles * 3;
TexCoords.Capacity := iTriangles * 3;
// copy the face list
for i := 0 to iTriangles - 1 do
with IndexList[i] do
begin
Add(a, a_s, -a_t);
Add(b, b_s, -b_t);
Add(c, c_s, -c_t);
end;
end;
// retrieve frames data (morph targets)
for i := 0 to iFrames - 1 do
begin
morphTarget := TVXMeshMorphTarget.CreateOwned(MorphTargets);
with morphTarget do
begin
Name := 'Frame' + IntToStr(i);
Vertices.Capacity := iVertices;
for j := 0 to iVertices - 1 do
Vertices.Add(VertexList[i][j]);
BuildNormals(faceGroup.VertexIndices, momTriangles);
end;
end;
end;
if GetOwner is TVXActor then
with TVXActor(GetOwner).Animations do
begin
Clear;
with MD2File do
for i := 0 to frameNames.Count - 1 do
with Add do
begin
Name := frameNames[i];
Reference := aarMorph;
StartFrame := Integer(frameNames.Objects[i]);
if i < frameNames.Count - 1 then
EndFrame := Integer(frameNames.Objects[i + 1]) - 1
else
EndFrame := iFrames - 1;
end;
end;
if mesh.MorphTargets.Count > 0 then
mesh.MorphTo(0);
finally
MD2File.Free;
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterVectorFileFormat('md2', 'Quake II model files', TVXMD2VectorFile);
end.
|
unit MainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.AddressBook.Types, FMX.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.StdCtrls, FMX.ListView,
FMX.Controls.Presentation, FMX.AddressBook;
type
TForm1 = class(TForm)
AddressBook1: TAddressBook;
ToolBar1: TToolBar;
lvContacts: TListView;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure AddressBook1PermissionRequest(ASender: TObject;
const AMessage: string; const AAccessGranted: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses System.Threading;
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
procedure TForm1.AddressBook1PermissionRequest(ASender: TObject;
const AMessage: string; const AAccessGranted: Boolean);
begin
if not AAccessGranted then
ShowMessage('Nao permitido!');
end;
procedure TForm1.Button1Click(Sender: TObject);
Var Task : ITask;
begin
Task := TTask.Create(procedure
var
Contact : TAddressBookContact;
Contacts : TAddressBookContacts;
LVI: TListViewItem;
begin
Contacts := TAddressBookContacts.Create;
try
AddressBook1.AllContacts(Contacts);
for Contact in Contacts do begin
TThread.Synchronize(nil,procedure
begin
LVI := lvContacts.Items.Add;
LVI.Text := Contact.DisplayName;
LVI.Detail := Contact.Source.SourceName;
LVI.Bitmap.Assign(Contact.PhotoThumbnail);
LVI.Data['ID'] := Contact.ID;
end)
end;
finally
Contacts.Free;
end;
end);
Task.Start;
end;
end.
|
unit t_ImportChecking;
interface
uses Classes, SysUtils, DateUtils, SyncObjs,
n_free_functions, n_server_common, n_LogThreads, n_DataCacheInMemory,
v_DataTrans, v_constants;
type
CountProcessRun = record
All: integer;
Rep: integer;
Imp: integer;
User: integer;
end;
TCheckProcess = class (TObject)
FCheckKind: integer; // constOpExport = 3 (Экспорт/отчет); constOpImport = 4; (Импорт) // TImpKind;
FCheckEmpl: integer; // пользователь
FCheckThreadDataID: integer; //
FCheckTypeName: string; // наименование типа: Получение данных/Импорт из файлов
FCheckImpType: word; // тип импорта
FCheckTimeBegin: TDateTime; // время начала процесса
FCheckLastTime: TDateTime; // время последней проверки
FCheckFilterComment: string; //
FCheckStop: integer; // признак снятия процесса UserID, который снимает процесс
FCheckPercent: real; // процент выполнения
FCheckRun: boolean; // выполняется //070715
public
constructor Create(pKindOp, pCheckEmpl: integer; pCheckImpType: word; pCheckTimeBegin: TDateTime; pCheckFilterComment: string; pCheckThreadDataID: integer; pCheckRun: boolean);
//destructor Destroy; override;
end;
TImpKind = (ikBaseStamp, ikImport); // импорт-экспорт
TImpCheck = class
//CheckKind : TImpKind; // признак импорт-экспорт
CheckList: TList; //список процессов
CrSection: TCriticalSection;
MaxTime: integer; // мах время в минутах для выполнения, если больше - снимать
//LastTime: TDateTime; // время последней проверки ? в процесс
public
//CheckList: TList;
constructor Create;
destructor Destroy; override;
function FindUserProc( pUserID, pThreadDataID: Integer): integer; //Проверка наличия активной операции у пользователя
procedure AddProcess(pKindOp, pUserID, pProc: Integer; ThreadData: TThreadData; pComment: string=''){: Integer}; // Добавить операцию в контроль
procedure DelProcess( pUserID, pThreadDataID: Integer); // Удалить операцию из контроля
function ListUserProcess( pUserIDFrom, pUserIDAbout: Integer; var PList: TStringList): boolean; // список процессов пользователя (время начала, процесс)
procedure SetCheckStop( pUserIDFrom, pThreadDataID: Integer); // проставление в признак на снятие процесса UserID, от которого пришло указание
procedure SetProcessPercent( pUserID, pThreadDataID: Integer; pPercent: Real); // проставление процента выполнения процесса
procedure SetComment( pUserID, pThreadDataID: Integer; pComment: string='') ; // проставление комментария
function GetImpType (pUserID, pThreadDataID: Integer) : word;
function GetCheckKind (pUserID, pThreadDataID: Integer) : word;
function GetCheckComment (pUserID, pThreadDataID: Integer) : String;
function GetCountProcessRun( pUserID: integer): CountProcessRun;
end;
EStopError = class(Exception)
end;
var ImpCheck: TImpCheck;
//StampCheck: TImpCheck;
function CreateFilterComment(filter_data: string = ''): string; // текст комментария
procedure prStopProcess( pUserID, pThreadDataID: Integer);
function GetProcessName(pUserID, pThreadDataID: Integer): string; //полное наименование процесса
function GetProcessRun(pUserID, pThreadDataID: Integer): boolean;
procedure prStopProcessS(pUserID, pThreadDataID: Integer; var stopped: boolean);
implementation
uses n_constants;
function TImpCheck.GetCheckComment (pUserID, pThreadDataID: Integer) : string;
var Process: TCheckProcess;
i: integer;
begin
Result:= '';
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(ImpCheck.CheckList.Items[i]);
Result:= Process.FCheckFilterComment;
end;
end;
function TImpCheck.GetCheckKind (pUserID, pThreadDataID: Integer) : word;
var Process: TCheckProcess;
i: integer;
begin
Result:= 0;
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(ImpCheck.CheckList.Items[i]);
Result:= Process.FCheckKind;
end;
end;
function TImpCheck.GetImpType (pUserID, pThreadDataID: Integer) : word;
var Process: TCheckProcess;
i: integer;
begin
Result:= 0;
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(ImpCheck.CheckList.Items[i]);
Result:= Process.FCheckImpType;
end;
end;
function GetProcessName(pUserID, pThreadDataID: Integer): string;
var Process: TCheckProcess;
i: integer;
begin
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(ImpCheck.CheckList.Items[i]);
Result:= Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment;
end;
end;
function GetProcessRun(pUserID, pThreadDataID: Integer): boolean;
var Process: TCheckProcess;
i: integer;
begin
Result:= false;
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(ImpCheck.CheckList.Items[i]);
Result:= Process.FCheckRun;
end;
end;
function TImpCheck.GetCountProcessRun( pUserID: integer): CountProcessRun;
var Process: TCheckProcess;
i: integer;
countAll, countRep, countImp, countUser: integer;
begin
Result.All:= 0;
Result.Rep:= 0;
Result.Imp:= 0;
Result.User:= 0;
for i:= 0 to CheckList.Count-1 do begin
Process:= TCheckProcess(CheckList.Items[i]);
if Process.FCheckRun then begin
inc(Result.All);
if Process.FCheckImpType=constOpExport then inc(Result.Rep);
if Process.FCheckImpType=constOpImport then inc(Result.Imp);
if Process.FCheckEmpl=pUserID then inc(Result.User);
end;
end;
end;
procedure TImpCheck.SetProcessPercent( pUserID, pThreadDataID: Integer; pPercent: Real);
var Process: TCheckProcess;
i: integer;
begin
i:= FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(CheckList.Items[i]);
//while not Process.FCheckRun do sleep(100);
if Process.FCheckPercent+ pPercent<= 100 then
Process.FCheckPercent:= Process.FCheckPercent+ pPercent;
end;
end;
procedure prStopProcess(pUserID, pThreadDataID: Integer);
const nmProc= 'prStopProcess';
var i : integer;
lstBodyMail: TStringList;
Subj, ss: string;
Process: TCheckProcess;
begin
//lstBodyMail:= TStringList.Create;
Subj:= 'Остановка выполнения задания';
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if (i> -1) then begin
lstBodyMail:= TStringList.Create;
try
Process:= TCheckProcess(ImpCheck.CheckList[i]);
lstBodyMail.Add('Выполнение задания: '+Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment);
if (Process.FCheckStop>0) then begin
if Process.FCheckStop<> pUserID then begin
lstBodyMail.Add('было остановлено по требованию '+ cache.arEmplInfo[Process.FCheckStop].EmplShortName);
ss:= n_SysMailSend(Cache.arEmplInfo[pUserID].Mail, Subj, lstBodyMail);
if ss<>'' then
prMessageLOGS(nmProc+' Ошибка отправки почты на email '+Cache.arEmplInfo[pUserID].Mail+': '+ss,'Error' , true);
end;
raise EStopError.Create('процесс '+Process.FCheckTypeName+' "'+cache.GetImpTypeName(Process.FCheckImpType)+'" '+ Process.FCheckFilterComment+' прерван по требованию пользователя '+ cache.arEmplInfo[Process.FCheckStop].EmplShortName);
end
else
if AppStatus in [stSuspending, stSuspended, stExiting] then begin
if AppStatus in [stSuspending, stSuspended] then
while AppStatus in [stSuspending, stSuspended]
do sleep(100)
else begin
lstBodyMail.Add('было остановлено из-за остановки системы ');
ss:= n_SysMailSend(Cache.arEmplInfo[pUserID].Mail, Subj, lstBodyMail);
if ss<>'' then
prMessageLOGS(nmProc+' Ошибка отправки почты на email '+Cache.arEmplInfo[pUserID].Mail+': '+ss,'Error' , true);
raise EStopError.Create('процесс '+Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment+' прерван из-за остановки системы');
end;
end;
finally
prFree(lstBodyMail);
//lstBodyMail.Free;
i:= ImpCheck.CheckList.Count;
end;
end
else
raise EStopError.Create('процесс '+Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment+' прерван из-за остановки системы');
end;
procedure prStopProcessS(pUserID, pThreadDataID: Integer; var stopped: boolean);
const nmProc= 'prStopProcessS';
var i : integer;
lstBodyMail: TStringList;
Subj, ss: string;
Process: TCheckProcess;
begin
//lstBodyMail:= TStringList.Create;
stopped:= false;
Subj:= 'Остановка выполнения задания';
i:= ImpCheck.FindUserProc( pUserID, pThreadDataID);
if (i> -1) then begin
lstBodyMail:= TStringList.Create;
try
Process:= TCheckProcess(ImpCheck.CheckList[i]);
lstBodyMail.Add('Выполнение задания: '+Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment);
if (Process.FCheckStop>0) then begin
stopped:= true;
if Process.FCheckStop<> pUserID then begin
lstBodyMail.Add('было остановлено по требованию '+ cache.arEmplInfo[Process.FCheckStop].EmplShortName);
ss:= n_SysMailSend(Cache.arEmplInfo[pUserID].Mail, Subj, lstBodyMail);
if ss<>'' then
prMessageLOGS(nmProc+' Ошибка отправки почты на email '+Cache.arEmplInfo[pUserID].Mail+': '+ss,'Error' , true);
end;
raise EBOBError.Create('процесс '+Process.FCheckTypeName+' "'+cache.GetImpTypeName(Process.FCheckImpType)+'" '+ Process.FCheckFilterComment+' прерван по требованию пользователя '+ cache.arEmplInfo[Process.FCheckStop].EmplShortName);
end
else
if AppStatus in [stSuspending, stSuspended, stExiting] then begin
lstBodyMail.Add('было остановлено из-за остановки системы ');
ss:= n_SysMailSend(Cache.arEmplInfo[pUserID].Mail, Subj, lstBodyMail);
if ss<>'' then
prMessageLOGS(nmProc+' Ошибка отправки почты на email '+Cache.arEmplInfo[pUserID].Mail+': '+ss,'Error' , true);
raise EBOBError.Create('процесс '+Process.FCheckTypeName+' '+cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment+' прерван из-за остановки системы');
end;
finally
prFree(lstBodyMail);
//lstBodyMail.Free;
end;
end
else stopped:= true;
end;
procedure TImpCheck.SetComment(pUserID, pThreadDataID: Integer; pComment: string='');
var Process: TCheckProcess;
i: integer;
begin
i:= FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(CheckList.Items[i]);
Process.FCheckFilterComment:= pComment;
end;
end;
function TImpCheck.ListUserProcess( pUserIDFrom, pUserIDAbout: Integer; var PList: TStringList): boolean;
var i: integer;
Process: TCheckProcess;
ss: string;
begin
ss:='';
Result:= False;
if (pUserIDAbout = pUserIDFrom) then Result:= True
else begin
Result:=cache.arEmplInfo[pUserIDFrom].UserRoleExists(rolManageUsers);
{for i:= 0 to length(cache.arEmplInfo)-1 do begin
if (cache.arEmplInfo[i].EmplID= pUserIDFrom) and (cache.arEmplInfo[i].UserRoleExists(rolManageUsers)) then begin
Result:= True;
break;
end;
end;}
end;
if Result= True then begin
for i:= 0 to CheckList.Count-1 do begin
Process:= TCheckProcess(CheckList.Items[i]);
if pUserIDAbout = -1 then begin
ss:= DateTimeToStr(Process.FCheckTimeBegin); //PList.AddObject(DateTimeToStr(Process.CheckTimeBegin),Process)
ss:= ss+ ' '+Process.FCheckTypeName+' '+cache.arEmplInfo[Process.FCheckEmpl].Name +' '+ cache.arEmplInfo[Process.FCheckEmpl].Surname;
ss:= ss +' ' +cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment;
end
else if (Process.FCheckEmpl= pUserIDAbout) then begin
ss:= DateTimeToStr(Process.FCheckTimeBegin)+' ';
ss:= ss +' '+Process.FCheckTypeName+' ' +cache.GetImpTypeName(Process.FCheckImpType)+' '+ Process.FCheckFilterComment;
try
prStopProcess(Process.FCheckEmpl, Process.FCheckThreadDataID);
except
on E: Exception do begin
ImpCheck.DelProcess(Process.FCheckEmpl, Process.FCheckThreadDataID);
ss:='';
end;
end;
end;
if ss<>'' then begin
PList.AddObject(ss,Process);
Process.FCheckLastTime:= Now;
end;
ss:= '';
{ss:= DateTimeToStr(IncMinute(Process.CheckTimeBegin,-3)); //PList.AddObject(DateTimeToStr(Process.CheckTimeBegin),Process)
ss:= ss+ ' ' +cache.arEmplInfo[Process.CheckEmpl].Name +' '+ cache.arEmplInfo[Process.CheckEmpl].Surname;
if CheckKind=ikBaseStamp then ss:= ss +' Операция получения данных.'
else ss:= ss +' Операции импорта из файлов.';
ss:= ss +' ' +cache.GetImpTypeName(Process.CheckImpType)+' '+ Process.CheckFilterComment;
if ss<>'' then PList.AddObject(ss,Process);
//ss:=DateTimeToStr(IncMinute(Process.CheckLastTime, MaxTime));
ss:= PList.CommaText;
ss:= ''; }
end;
end;
PList.Sort;
end;
function CreateFilterComment(filter_data: string = ''): string;
var ss: integer;
FilterData: TStringList;
begin
Result:= '';
FilterData:= TStringList.Create;
FilterData.Text:= filter_data;
if {filter_data}FilterData.Text = '' then begin
Result:= '';
exit;
end;
if pos('dop_gbbrand',FilterData.Text{filter_data})>0 then begin
ss:= StrToIntDef(FilterData.Values['dop_gbbrand'],-1);
if ss>-1 then Result:= 'Бренд '+TBrandItem(Cache.WareBrands[ss]).Name;
exit;
end;
if pos('dop_manuflistauto',FilterData.Text{filter_data})>0 then begin
ss:= StrToIntDef(FilterData.Values['dop_manuflistauto'],-1);
if ss>-1 then Result:= 'Производитель авто '+Cache.FDCA.Manufacturers[ss].Name;
exit;
end;
prFree(FilterData);
//FilterData.Free;
end;
procedure TImpCheck.AddProcess(pKindOp,pUserID, pProc: Integer; ThreadData: TThreadData; pComment: string='');
var Process: TCheckProcess;
i, iProcess: integer;
pRun: boolean;
CountRun: CountProcessRun;
begin
iProcess:= -1;
for i:= 0 to CheckList.Count-1 do begin
Process:= TCheckProcess(CheckList.Items[i]);
if (Process.FCheckEmpl = pUserID) {20.03.14} and (Process.FCheckKind = pKindOp) and (Process.FCheckImpType = pProc) then begin
iProcess:= i;
break;
end;
end;
//i:= FindUserProc( pUserID, ThreadData.ID );
if iProcess < 0 then begin
try
CrSection.Enter;
// if CheckList.Count>0 then pRun:= false
// else
CountRun:= ImpCheck.GetCountProcessRun(pUserID);
if (CountRun.All<Cache.GetConstItem(pcStartImportLimit).IntValue )
and (CountRun.User<Cache.GetConstItem(pcStartImportLimit).IntValue)
and (((CountRun.Rep<Cache.GetConstItem(pcStartImportLimit).IntValue) and (pKindOp=constOpExport))
or ((CountRun.Imp<Cache.GetConstItem(pcStartImportLimit).IntValue) and (pKindOp=constOpImport)))
then pRun:= true
else pRun:= false;
Process:= TCheckProcess.Create(pKindOp, pUserID, pProc,Now, CreateFilterComment(pComment),ThreadData.ID, pRun);
CheckList.Add(Process);
ThreadData.pProcess:= Pointer(Process);
finally;
CrSection.Leave;
end;
end
else begin
Process:= TCheckProcess(ImpCheck.CheckList[i]);
raise EBOBError.Create({200314} Process.FCheckTypeName+' '+ cache.GetImpTypeName(pProc)+#13#10+
CreateFilterComment(pComment)+'Процесс импорта/экспорта Вы уже выполняете. Дождитесь результата!'); //vv
end;
end;
function TImpCheck.FindUserProc(pUserID, pThreadDataID: Integer): integer;
{ Result
-1: не найден
i: найден(индекс)}
var Process: TCheckProcess;
begin
try
for Result:= 0 to CheckList.Count-1 do begin
Process:= TCheckProcess(CheckList.Items[Result]);
if (Process.FCheckThreadDataID = pThreadDataID) {and (Process.FCheckEmpl = pUserID)} then begin
exit;
end;
end;
except
on E: Exception do begin
// Result:= -1;
prMessageLOGS('Ошибка проверки наличия процесса в наблюдаемых. '+E.Message ,'Import', false);
end;
end;
Result:= -1;
end;
procedure TImpCheck.DelProcess(pUserID, pThreadDataID: Integer);
var i, j: integer;
Proc: TCheckProcess;
pRun: boolean;
CountRun: CountProcessRun;
begin
i:= FindUserProc( pUserID, pThreadDataID);
if i > -1 then begin
try
CrSection.Enter;
Proc:= TCheckProcess(CheckList.Items[i]);
pRun:= Proc.FCheckRun;
self.CheckList.Delete(i);
prFree(Proc);
if pRun and (CheckList.Count>0) then //070715
for j:=0 to CheckList.Count-1 do begin
Proc:= TCheckProcess(CheckList.Items[j]);
if Proc<>nil then begin
CountRun:= ImpCheck.GetCountProcessRun(Proc.FCheckEmpl);
if (CountRun.All<Cache.GetConstItem(pcStartImportLimit).IntValue )
and (CountRun.User<Cache.GetConstItem(pcStartImportLimit).IntValue)
and (((CountRun.Rep<Cache.GetConstItem(pcStartImportLimit).IntValue) and (Proc.FCheckKind=constOpExport))
or ((CountRun.Imp<Cache.GetConstItem(pcStartImportLimit).IntValue) and (Proc.FCheckKind=constOpImport)))
then begin
Proc.FCheckRun:= true;
break;
end;
end;
end;
//TCheckProcess(CheckList.Items[i]).Free;
//Remove(Process);
//Process.Destroy;
finally
CrSection.Leave;
end;
{end
else begin
raise Exception.Create('Процесс уже завершен.'); //vv}
end;
end;
{ TImpCheck }
constructor TImpCheck.Create;
begin
CheckList:= TList.Create;
CrSection := TCriticalSection.Create;
self.MaxTime:= 15;
end;
destructor TImpCheck.Destroy;
begin
prFree(CheckList);
prFree(CrSection);
//CheckList.Free;
//CrSection.Free;
inherited;
end;
procedure TImpCheck.SetCheckStop({pUserID,} pUserIDFrom, pThreadDataID: Integer);
var i: integer;
Process: TCheckProcess;
// Result: boolean;
begin
{if pUserID = pUserIDFrom then Result:= True
else begin
for i:= 0 to length(cache.arEmplInfo)-1 do begin
if (cache.arEmplInfo[i].EmplID= pUserIDFrom) and (cache.arEmplInfo[i].UserRoleExists(rolManageUsers)) then begin
Result:= True;
break;
end;
end;
end;
if Result = True then begin }
i:= FindUserProc(pUserIDFrom, pThreadDataID);
if i > -1 then begin
Process:= TCheckProcess(CheckList.Items[i]);
Process.FCheckStop:= pUserIDFrom;
end;
{end;}
end;
{ TCheckProcess }
constructor TCheckProcess.Create(pKindOp, pCheckEmpl: integer; pCheckImpType: word;
pCheckTimeBegin: TDateTime; pCheckFilterComment: string; pCheckThreadDataID: integer; pCheckRun: boolean);
begin
FCheckKind:= pKindOp;
FCheckEmpl:= pCheckEmpl;
FCheckThreadDataID:= pCheckThreadDataID;
if pKindOp= constOpExport then FCheckTypeName:= 'Получение данных.';
if pKindOp= constOpImport then FCheckTypeName:= 'Импорт из файлов.';
FCheckImpType:= pCheckImpType;
FCheckTimeBegin:= pCheckTimeBegin;
FCheckLastTime:= pCheckTimeBegin;
FCheckFilterComment:= pCheckFilterComment;
FCheckStop:= 0;
FCheckPercent:= 1;
FCheckRun:= pCheckRun; //070715
end;
end.
|
unit ITCbrd;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses windows,classes,
util1,varconf1,
debug0,
stmdef,AcqBrd1,ITCmm,stimInf2,
dataGeneFile,FdefDac2,
Ncdef2,
acqCom1,ITCopt1, AcqInterfaces,
acqDef2,acqInf2
;
{ Driver des cartes ITC
Quand deux PCI1600 sont disponibles,
- on connecte trigOut de device0 à trigIn de Device1
- le retard de la 2eme carte est compensé sur la première en ignorant
quelques échantillons en entrées et en envoyant qq échantillons en sortie
- le retard est de l'ordre de 205 microsecondes
- on connecte aussi world clock output de la première carte PCI1600 à
world clock input de la seconde carte au moyen d'un cable plat 10 conducteur.
Il se trouve que les indications concernant ces connecteurs sont inversées:
input est en réalité output et réciproquement. Ceci permet d'utiliser la
même horloge pour les deux systèmes.
L'entrée trigger est toujours trigIN sur la première carte.
}
Const
ITC18USB_ID=5;
Const
Bit0 = $1;
Bit1 = $2;
Bit2 = $4;
Bit3 = $8;
Bit4 = $10;
Bit5 = $20;
Bit6 = $40;
Bit7 = $80;
Bit8 = $100;
Bit9 = $200;
Bit10 = $400;
Bit11 = $800;
Bit12 = $1000;
Bit13 = $2000;
Bit14 = $4000;
Bit15 = $8000;
const
maxChITC=32;
type
TinfoITCChannel=record
PhysNum:byte;
isDigi:boolean;
Numbuf: smallint;
end;
TinfoDev= record
nbIn,nbOut:integer;
infoIn: array of TinfoITCChannel;
infoOut:array of TinfoITCChannel;
end;
TITCinterface = class(TacqInterface)
private
{FifoBuf:array of array of array of smallint;}
infoDev:array[0..1] of TinfoDev;
bufIn:array of array of smallint;
nbBufIn:integer;
nbBufInTot:integer;
BufInSize:integer;
nbCount,Iadc:integer;
InChannels,OutChannels: array of array of ITCChannelInfo;
ITCdataIn:array of array of ITCChannelDataEx;
ITCdataOut:array of array of ITCChannelDataEx;
Vhold:array[0..1,0..100] of smallint; { premier indice=device, second=numéro output absolu }
{ ainsi, en changeant de config, le Vhold est toujours correct }
HoldBuf:array of array of array of smallint;
pstimBuf: TFbuffer;
StoredEp:integer;
EpSize:integer;
EpSize1:integer;
HoldSize:integer;
IsiSize:integer;
nbDataOut:int64;
nbChOut:integer;
oldNbOut:integer;
DeviceType,DeviceNumber:array[0..1] of integer;
DeviceHandle:array[0..1] of Thandle;
HWfunc: array[0..1] of HWfunction;
Dual1600:boolean; { True si deux 1600 utilisées }
nbDelay1600:integer; { Délai en nb d'échantillons }
deviceInfo:array[0..1] of GlobalDeviceInfo;
DVersion,KVersion,HVersion:array[0..1] of VersionInfo;
chTrig:integer;
FsyncState:boolean;
SyncMask:word;
Fwaiting:boolean;
FlagNum:boolean;
FlagNumStim:boolean;
FlagStim:boolean;
FextraDigi0:boolean;
bufDigi0:array of smallint;
procedure InPoints(nb:integer);
function getCount:integer;override;
function getCount2:integer;override;
procedure ManageDelay1600;
procedure doContinuous;
procedure doInterne;
procedure doNumPlus;
procedure doNumPlusStim;
procedure DoAnalogAbs;
procedure DoAnalogAbs1;
procedure nextSample;override;
procedure CopySample(i:integer);override;
procedure relancer;override;
procedure restartAfterWait;override;
function OutData(i0,nb:integer):boolean;
function OutDataHold(nb:integer):boolean;
function OutDataDelay(nb:integer):boolean;
function OutPossible:integer;
Procedure OutPoints(i0,nb:int64);
procedure PreloadDac;
function isWaiting: boolean;override;
procedure setChannels;
procedure ITCMessage(numDev:integer;Status:integer;const stAd:AnsiString='');
procedure saveBufIn;
procedure VersionMessage(n:integer);
public
Delay1600:integer; { Délai 2eme 1600 en microsecondes }
constructor create(var st1:driverString);override;
destructor destroy;override;
procedure init;override;
procedure lancer;override;
procedure terminer;override;
function dataFormat:TdataFormat;override;
function dacFormat:TdacFormat;override;
function PeriodeElem:float;override;
function PeriodeMini:float;override;
procedure outdac(num,j:word);override;
function outDIO(dev,port,value: integer): integer;override;
function inADC(n:integer):smallint;override;
function inDIO(dev,port:integer):integer;override;
function RAngeString:AnsiString;override;
function MultiGain:boolean;override;
function gainLabel:AnsiString;override;
function nbGain:integer;override;
function channelRange:boolean;override;
procedure GetOptions;override;
procedure setDoAcq(var procInt:ProcedureOfObject);override;
procedure initcfgOptions(conf:TblocConf);override;
function TagMode:TtagMode;override;
function tagShift:integer;override;
function TagCount:integer;override;
function getMinADC:integer;override;
function getMaxADC:integer;override;
function deviceCount:integer;override; { nb device }
function ADCcount(dev:integer):integer;override; { nb ADC par device }
function DACcount(dev:integer):integer;override; { nb DAC par device }
function DigiOutCount(dev:integer):integer;override; { nb Digi Out par device }
function DigiInCount(dev:integer):integer;override; { nb Digi In par device }
function bitInCount(dev:integer):integer;override; { nb bits par entrée digi }
function bitOutCount(dev:integer):integer;override; { nb bits par sortie digi }
function CheckParams:boolean;override;
function nbVoieAcq(n:integer):integer;override;
procedure setVSoptions;override;
procedure GetPeriods(PeriodU:float;nbADC,nbDI,nbDAC,nbDO:integer;var periodIn,periodOut:float);override;
function setValue(Device,tpout,physNum,value:integer):boolean;override;
function getValue(Device,tpIn,physNum:integer;var value:smallint):boolean;override;
end;
procedure TestITC;
implementation
function ITCerror(handle:Thandle;Status:integer):AnsiString;
var
err:integer;
st:AnsiString;
begin
setLength(st,256);
fillchar(st[1],256,' ');
err:=ITC_GetStatusText(handle,Status,@st[1],256);
if err<>0 then st:='';
if pos(#0,st)>0
then st:=copy(st,1,pos(#0,st)-1);
result:=st;
end;
procedure TITCinterface.ITCMessage(numDev:integer;Status:integer;const stAd:AnsiString='');
begin
messageCentral('ITC error device='+Istr(numDev)+' '+stAd +crlf+ITCerror(Devicehandle[numDev],Status));
end;
procedure TITCinterface.VersionMessage(n:integer);
var
st:string;
begin
with Dversion[n] do
st:= Istr(Major)+' '+Istr(Minor)+' '+crlf+ tabToString(description,80)+crlf+tabToString(date,80) ;
messageCentral(st);
end;
constructor TITCinterface.create(var st1:driverString);
var
code:integer;
st:AnsiString;
i:integer;
error:integer;
nbTest:integer;
begin
boardFileName:='ITC';
Dual1600:=false;
Delay1600:=205;
st:=st1;
delete(st,1,pos('#',st));
val(st,deviceNumber[0],code);
st:=st1;
delete(st,pos('#',st)-1,100);
{Mise en place de DeviceType et DeviceNumber }
if st='ITC16' then deviceType[0]:=ITC16_ID
else
if st='ITC18' then deviceType[0]:=ITC18_ID
else
if st='ITC1600' then deviceType[0]:=ITC1600_ID
else
if st='DUAL ITC1600' then
begin
deviceType[0]:=ITC1600_ID;
deviceType[1]:=ITC1600_ID;
Dual1600:=true;
deviceNumber[1]:=1;
end
else
if st='ITC18USB' then deviceType[0]:=ITC18USB_ID;
HWFunc[0].Mode := ITC1600_internal_CLOCK;
HWFunc[1].Mode := ITC1600_intraBox_CLOCK;
for i:=0 to ord(Dual1600) do
begin
nbTest:=0;
repeat
error:=ITC_OpenDevice(DeviceType[i],DeviceNumber[i], Smart_mode,DeviceHandle[i]);
inc(nbTest);
until (error=0) or (nbTest>20);
if error=0 then
begin
error:=ITC_InitDevice(deviceHandle[i],HWfunc[i]);
if error<>0 then ITCmessage(i,error,'InitDevice');
error:=ITC_getDeviceInfo(deviceHandle[i],deviceInfo[i]);
if error<>0 then ITCmessage(i,error,'GetDeviceInfo');
error:=ITC_GetVersions(DeviceHandle[i], DVersion[i],KVersion[i],HVersion[i]);
if error<>0 then ITCmessage(i,error,'GetVersions');
end
else ITCmessage(i,error,'OpenDevice');
end;
end;
destructor TITCinterface.destroy;
var
i:integer;
error:integer;
begin
for i:=0 to ord(Dual1600) do
begin
error:=ITC_CloseDevice(DeviceHandle[i]);
if error<>0 then ITCmessage(i,error);
end;
end;
procedure TITCinterface.init;
var
dev,i:integer;
st:AnsiString;
error:integer;
out0:integer;
begin
//VersionMessage(0);
flagStim:=AcqInf.Fstim and
(AcqInf.ModeSynchro in [MSimmediat,MSinterne,MSnumPlus]);
flagNum:=(AcqInf.ModeSynchro=MSnumPlus) and not AcqInf.Fstim;
flagNumStim:=(AcqInf.ModeSynchro=MSnumPlus) and AcqInf.Fstim;
pstimBuf:=paramStim.buffers;
StoredEp:=paramStim.StoredEp;
EpSize:=paramStim.EpSize;
if EpSize=0 then EpSize:=10000;
EpSize1:=EpSize*AcqInf.nbVoieAcq;
if acqInf.continu then IsiSize:=EpSize
else
if (acqInf.ModeSynchro = MSnumPlus)
or
(acqInf.ModeSynchro in [MSimmediat,MSinterne]) and (acqInf.WaitMode)
then IsiSize:=10000000
else IsiSize:=AcqInf.IsiPts div AcqInf.nbVoieAcq;
HoldSize:=IsiSize-EpSize;
nbChOut:=length(pstimBuf);
for dev:=0 to 1 do
with infodev[dev] do { Reset InfoDev }
begin
nbIn:=0;
nbOut:=0;
setLength(infoIn,0);
setLength(infoOut,0);
end;
with AcqInf do { Compter les INPUT sur chaque device}
for i:=0 to QnbVoie-1 do
if (channels[i].Qdevice <>0) and Dual1600
then inc(infoDev[1].nbIn)
else inc(infoDev[0].nbIn);
if flagNum or FuseTagStart then inc(infoDev[0].nbIn);
for dev:=0 to 1 do
with infodev[dev] do
begin
setLength(infoIn,nbIn); { Ajuster la taille des InfoIN }
nbIn:=0;
end;
with AcqInf do
for i:=1 to QnbVoie do { remplir les infoIN }
begin
dev:=ord((channels[i-1].Qdevice <>0) and Dual1600);
with infoDev[dev] do
begin
with infoIn[nbIn] do
begin
PhysNum:=channels[i-1].QvoieAcq;
isDigi:=(channels[i-1].ChannelType <>TI_analog);
numBuf:=i-1;
end;
inc(nbIn);
end;
end;
if flagNum or FuseTagStart then
with infoDev[0] do
begin
with infoIn[nbIn] do
begin
PhysNum:=0;
isDigi:=true;
numBuf:=nbIn + InfoDev[1].nbIn;
end;
inc(nbIn);
end;
BufInSize:=50000;
nbBufIn:=InfoDev[0].nbIn + InfoDev[1].nbIn;
nbBufInTot:=nbBufIn;
if flagNum then
begin
if not FuseTagStart then dec(nbBufIn);
chTrig:=nbBufInTot-1;
FsyncState:=false;
if (acqInf.voieSynchro>=0) and (acqInf.voieSynchro<=3)
then SyncMask:=1 shl acqInf.voieSynchro
else SyncMask:=1 shl 4;
end;
setLength(bufIn,nbBufInTot ,BufInSize);
out0:=-1;
if Flagstim then
with paramStim do
begin
for i:=0 to ActiveChannels-1 do {Compter les outPut sur chaque device }
with bufferInfo[i]^ do
begin
if (Device<>0) and Dual1600
then inc(infoDev[1].nbOut)
else inc(infoDev[0].nbOut);
if (device=0) and (tpOut=to_digiBit) and (physNum=0)
then out0:=i; { out0>=0 indique que le canal Outdigi0 est utilisé}
end;
{on ajoute le canal OutDigi0 si nécessaire }
FextraDigi0:= (out0<0) and Dual1600;
if FextraDigi0 then inc(infoDev[0].nbOut);
for dev:=0 to 1 do
with infodev[dev] do
begin
setLength(infoOut,nbOut); { Ajuster la taille des InfoOut }
nbOut:=0;
end;
for i:=0 to ActiveChannels-1 do
with bufferInfo[i]^ do { Remplir les infoOut }
begin
dev:=ord((Device<>0) and Dual1600);
with infoDev[dev] do
begin
infoOut[nbOut].PhysNum:=PhysNum;
infoOut[nbOut].isDigi:=(tpOut=to_digiBit);
infoOut[nbOut].Numbuf :=i;
inc(nbOut);
end;
end;
if FextraDigi0 then {ajouter OutDigi0 si nécessaire}
with infoDev[0] do
begin
infoOut[nbOut].PhysNum:=0;
infoOut[nbOut].isDigi:=true;
infoOut[nbOut].Numbuf :=-1; {avec numéro buffer -1 }
inc(nbOut);
setLength(bufDigi0,EpSize);
fillchar(bufDigi0[0],EpSize*2,0);
for i:=0 to EpSize div 4-1 do BufDigi0[i]:=$FF;
end
else
if Dual1600 and (out0>=0) then
for i:=0 to EpSize div 2-1 do PstimBuf[out0,i]:=PstimBuf[out0,i] or $10;
end
else
if Dual1600 and (infodev[1].nbIn>0) then
with infoDev[0] do
begin
setLength(infoOut,1); { Ajuster la taille des InfoOut }
infoOut[0].PhysNum:=0;
infoOut[0].isDigi:=true;
infoOut[0].Numbuf :=-1; {avec numéro buffer -1 }
nbOut:=1;
setLength(bufDigi0,EpSize);
fillchar(bufDigi0[0],EpSize*2,0);
for i:=0 to EpSize div 4-1 do BufDigi0[i]:=$FF;
end;
setLength(HoldBuf,2);
for dev:=0 to 1 do
with infodev[dev] do
setLength(HoldBuf[dev],nbOut);
{Mise en place des structures ITCdataIn pour les entrées }
setLength(ITCdataIn,2);
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
setLength(ITCdataIn[dev],nbIn);
fillchar(ITCdataIn[dev,0],sizeof(ITCchannelDataEx)*nbIn,0);
for i:=0 to nbIn-1 do
begin
if InfoIn[i].isDigi
then ITCdataIn[dev,i].ChannelType:=digital_input
else ITCdataIn[dev,i].ChannelType:=D2H;
ITCdataIn[dev,i].ChannelNumber:=InfoIn[i].PhysNum;
end;
end;
{Mise en place des structures ITCdataOut pour les sorties }
setLength(ITCdataOut,2);
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
setLength(ITCdataOut[dev],nbOut);
fillchar(ITCdataOut[dev,0],sizeof(ITCchannelDataEx)*nbOut,0);
for i:=0 to nbOut-1 do
begin
if InfoOut[i].isDigi
then ITCdataOut[dev,i].ChannelType:=digital_output
else ITCdataOut[dev,i].ChannelType:=H2D;
ITCdataOut[dev,i].ChannelNumber:=InfoOut[i].PhysNum;
end;
end;
{ Structures pour la programmation des canaux }
setLength(InChannels,2);
setLength(OutChannels,2);
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
setLength(InChannels[dev],nbIn);
fillchar(InChannels[dev,0],sizeof(ITCChannelInfo)*nbIn,0); {Input channels}
for i:=0 to nbIn-1 do
with InChannels[dev,i] do
begin
if InfoIn[i].isDigi
then ChannelType:=digital_input
else ChannelType:=D2H;
ChannelNumber:=InfoIn[i].PhysNum ;
SamplingIntervalFlag:=US_scale or Use_time or Adjust_rate;
SamplingRate:=AcqInf.periodeparvoieMS*1000;
end;
if Flagstim or Dual1600 then
begin
setLength(OutChannels[dev],nbOut);
fillchar(OutChannels[dev,0],sizeof(ITCChannelInfo)*nbOut,0); {output channels}
for i:=0 to nbOut-1 do
with OutChannels[dev,i] do
begin
if infoOut[i].isDigi
then ChannelType:=Digital_output
else ChannelType:=H2D;
ChannelNumber:=infoOut[i].PhysNum;
SamplingIntervalFlag:=US_scale or Use_time;
SamplingRate:=AcqInf.periodeparvoieMS*1000;
end;
end;
end;
GI1:=-1;
initPadc;
cntStim:=0;
nbdelay1600:=round(Delay1600/1000/acqInf.periodeParVoieMS);
setChannels;
nbvoie:=nbBufInTot;
end;
procedure TITCinterface.setChannels;
var
dev,error:integer;
i:integer;
begin
{setLength(FifoBuf,2);}
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
ITC_resetChannels(deviceHandle[dev]); {resetChannels }
{
setLength(FifoBuf[dev],nbIn,131072);
for i:=0 to nbIn-1 do
begin
inChannels[dev,i].FIFONumberOfPoints:=65536;
inChannels[dev,i].FIFOPointer:=@FifoBuf[dev,i,0];
end;
}
error:=ITC_setChannels(deviceHandle[dev],nbIn,InChannels[dev,0]); {setChannels }
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
exit;
end;
if (Flagstim or Dual1600) and (nbOut>0) then
begin
error:=ITC_setChannels(deviceHandle[dev],nbOut,OutChannels[dev,0]);{setChannels }
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
exit;
end;
end;
{ Mettre à jour les canaux }
error:=ITC_UpdateChannels(deviceHandle[dev]); {updateChannels}
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
exit;
end;
end;
(*
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
if nbIn>0 then
begin
{fillchar(InChannels[dev,0],sizeof(ITCChannelInfo)*nbIn,0);
InChannels[dev,0].SamplingIntervalFlag:=0; }
error:=ITC_getChannels(deviceHandle[dev],nbIn,InChannels[dev,0]); {getChannels }
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
exit;
end;
end;
if (Flagstim or Dual1600) and (nbOut>0) then
begin
error:=ITC_getChannels(deviceHandle[dev],nbOut,OutChannels[dev,0]);{getChannels }
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
exit;
end;
end;
end;
*)
end;
procedure TITCinterface.lancer;
var
dev,i,n:integer;
error:integer;
info:ITCstartInfo;
begin
restartOnTimer:= not AcqInf.continu and
(acqInf.ModeSynchro in [MSimmediat,MSinterne]) and
acqInf.waitMode;
nbCount:=0;
Iadc:=0;
initPmainDac;
PreloadDAC;
AcqTime0:=GetTickCount;
fillchar(info,sizeof(info),0); { Info pour ITC_start }
with Info do
begin
ExternalTrigger:=bit0+bit3;
OutputEnable:=longword(-1);
StopOnOverflow:=longword(-1);
StopOnUnderrun:=longword(-1);
RunningOption:=longword(-1);
end;
{
for ITC16/18: Bit 0: Enable trigger.
for ITC1600:
Bit 0: Enable trigger.
Bit 1: Use trigger from PCI1600
Bit 2: Use timer trigger
Bit 3: Use Rack 0 TrigIn BNC
Bit 4: Use Rack 0 Digital Input 0 BNC
Bit 5: Use Rack 0 Digital Input 1 BNC
Bit 6: Use Rack 0 Digital Input 2 BNC
Bit 7: Use Rack 0 Digital Input 3 BNC
Bit 8: Use trigger from PCI1600, but with Rack Reload function, for better synch.
}
if Dual1600 then
begin
error:=ITC_start(deviceHandle[1], Info);
if error<>0 then
begin
ITCmessage(1,error);
flagStop:=true;
exit;
end;
end;
{lancer l'acquisition }
if flagNumStim then
begin
case acqInf.voieSynchro of
0: info.ExternalTrigger:=bit0+bit4;
1: info.ExternalTrigger:=bit0+bit5;
2: info.ExternalTrigger:=bit0+bit6;
3: info.ExternalTrigger:=bit0+bit7;
else info.ExternalTrigger:=bit0+bit3;
end;
error:=ITC_start(deviceHandle[0],info);
end
else error:=ITC_start(deviceHandle[0],ITCstartInfo((nil)^));
if error<>0 then
begin
ITCmessage(0,error);
flagStop:=true;
exit;
end;
Fwaiting:=false;
ManageDelay1600;
end;
procedure TITCinterface.ManageDelay1600;
var
error:integer;
buf:array[0..999] of smallint;
nbdataIn:integer;
i,x:integer;
begin
if not Dual1600 or (nbDelay1600=0) then exit;
repeat
with infoDev[0] do
begin
error:=ITC_getDataAvailable(deviceHandle[0],nbIn,ITCdataIn[0,0]);
if error<>0 then
begin
ITCmessage(0,error);
flagStop:=true;
end;
nbdataIn:=maxEntierLong;
for i:=0 to nbIn-1 do
begin
x:=ITCdataIn[0,i].value;
if x<nbdataIn then nbdataIn:=x;
end;
end;
until (nbdataIn>nbDelay1600) or flagStop or testEscape;
with infoDev[0] do
begin
for i:=0 to nbIn-1 do
begin
ITCdataIn[0,i].value:=nbDelay1600;
ITCdataIn[0,i].DataPointer:=@buf;
end;
Error:= ITC_ReadWriteFIFO(DeviceHandle[0], nbIn, ITCdataIn[0,0]);
if error<>0 then
begin
ITCmessage(0,error);
flagStop:=true;
end;
end;
end;
procedure TITCinterface.InPoints(nb:integer);
var
dev,i:integer;
n,nstart:integer;
error:integer;
begin
nStart:=(Iadc div nbBufIn) mod bufInSize;
repeat
n:=nb;
if nstart+n>BufInSize then n:=BufInSize-nStart;
for dev:=0 to ord(dual1600) do
with infoDev[dev] do
begin
for i:=0 to nbIn-1 do
begin
ITCdataIn[dev,i].value:=n;
ITCdataIn[dev,i].DataPointer:=@bufIn[infoIn[i].numBuf,nStart];
end;
Error:= ITC_ReadWriteFIFO(DeviceHandle[dev], nbIn, ITCdataIn[dev,0]);
if error<>0 then ITCmessage(dev,error);
end;
nStart:=(nStart+n) mod BufInSize;
dec(nb,n);
until nb=0;
end;
function TITCinterface.getCount:integer;
var
dev,i:integer;
x,error:integer;
nbdataIn:integer;
begin
nbdataIn:=maxEntierLong;
for dev:=0 to ord(dual1600) do
with infoDev[dev] do
begin
error:=ITC_getDataAvailable(deviceHandle[dev],nbIn,ITCdataIn[dev,0]);
if error<>0 then ITCmessage(dev,error);
if nbin>0 then affdebug('count'+Istr(dev)+'='+Istr(ITCdataIn[dev,0].Value) ,21);
for i:=0 to nbIn-1 do
begin
x:=ITCdataIn[dev,i].value;
if x<nbdataIn then nbdataIn:=x;
end;
end;
InPoints(nbdataIn);
inc(nbCount,nbdataIn*nbBufin);
result:=nbCount;
affdebug('getCount='+Istr(nbCount),21);
end;
procedure TITCinterface.nextSample;
var
n:integer;
begin
if Iadc>=nbCount then exit;
n:=Iadc mod nbBufIn;
wsample[0]:=bufIn[n][(Iadc div nbBufIn) mod BufInSize];
wsampleR[0]:=wsample[0];
inc(Iadc);
end;
function TITCinterface.getCount2:integer;
begin
result:=0;
end;
procedure TITCinterface.relancer;
begin
if Flagstim then
begin
inc(baseIndex,nbptStim);
end;
setChannels;
lancer;
Fwaiting:=false;
end;
procedure TITCinterface.terminer;
var
dev:integer;
sparam:ITCstatus;
error:integer;
begin
for dev:=0 to ord(Dual1600) do
begin
error:=ITC_stop(deviceHandle[dev],nil);
if error<>0 then ITCmessage(dev,error);
end;
(*
for dev:=0 to ord(Dual1600) do
repeat
error:=ITC_GetState(DeviceHandle[dev],@sParam);
until (error<>0) or (sparam.RunningMode and RUN_STATE=0) or testEscape;
*)
saveBufIn; { pour debug }
{
setLength(bufIn,0);
setLength(ITCdataIn,0);
setLength(ITCdataOut,0);
setLength(Vhold,0);
setLength(HoldBuf,0);
setLength(pstimBuf,0);
}
Fwaiting:=false;
end;
procedure TITCInterface.doContinuous;
var
i:integer;
begin
GI2:=getCount-1;
for i:=GI1+1 to GI2 do
begin
nextSample;
storeWsample;
end;
if withStim
then outPoints(nbdataOut,(GI2-GI1) div nbvoie);
GI1:=GI2;
end;
procedure TITCinterface.doInterne;
var
i,k:integer;
begin
GI2:=getCount-1;
for i:=GI1+1 to GI2 do
begin
k:=i mod isi;
nextSample;
if (k>=0) and (k<nbpt) then storeWsample;
end;
if withStim
then outPoints(nbdataOut,(GI2-GI1) div nbvoie);
GI1:=GI2;
end;
{****************** Synchro mode numérique Plus sans stim *********************}
procedure TITCInterface.DoNumPlus;
var
i,j:integer;
ch:integer;
begin
GI2:=getcount-1;
for i:=GI1+1 to GI2 do
begin
nextSample;
ch:=i mod nbBufIn;
FsyncState:= bufIn[ChTrig][(i div nbBufIn) mod BufInSize] and SyncMask <>0;
if not Ftrig then
begin
if (i>nbAv) and not oldSyncNum and FsyncState then
begin
TrigDate:=i div nbBufIn*nbBufIn;
Ftrig:=true;
for j:=trigDate-nbAv to i do copySample(j);
affdebug('trigDate= '+Istr(trigDate)+' i='+Istr(i),27);
end;
oldSyncNum:=FsyncState;
end
else
begin
if (i-trigDate>=nbAp) then
begin
Ftrig:=false;
oldSyncNum:=true;
end
else
begin
storeWsample;
oldSyncNum:=FsyncState;
end;
end;
end;
GI1:=GI2;
affdebug(Istr(ChTrig)+' '+Istr(nbBufIn) +' '+Istr(nbBufInTot)+' '+Istr(BufInSize) ,27);
affdebug(Istr(nbvoie)+' '+Istr(nbAv) +' '+Istr(nbAp)+' ',27);
with infodev[0] do
for i:=0 to nbIn-1 do
affdebug('Numbuf['+Istr(i)+']= '+Istr(infoIn[i].numbuf),27);
end;
procedure TITCInterface.doNumPlusStim;
var
i,j,k,GI2,GI2x:integer;
i1:integer;
t:longWord;
begin
if Fwaiting then exit;
GI2:=getcount-1;
for i:=GI1+1 to GI2 do
begin
nextSample;
storeWsample;
if i=EpSize1-1 then
begin
GI1:=-1;
GI2:=0;
terminer;
GI1x:=-1;
Fwaiting:=true;
exit;
end;
end;
if withStim
then outPoints(nbdataOut,(GI2-GI1) div nbvoie);
GI1:=GI2;
end;
{****************** Synchro mode analogique absolu ***************************}
{l'ADC est en mode circulaire. On teste la voie synchro en permanence.
La voie synchro doit faire partie des voies acquises. Sinon voir DoAnalogAbs1
}
procedure TITCinterface.DoAnalogAbs;
var
j:integer;
i:integer;
begin
GI2:=getCount-1;
for i:=GI1+1 to GI2 do
begin
nextSample;
if not Ftrig then
begin
if (i mod nbvoie=VoieSync-1) then
begin
if (i>nbAv) and
( (wSampleR[0]>=seuilP) and (oldw1<seuilP)
OR
(wSampleR[0]<=seuilM) and (oldw1>seuilM)
) then
begin
TrigDate:=i div nbvoie*nbvoie;
Ftrig:=true;
for j:=trigDate-nbAv to i do copySample(j);
end;
oldw1:=wSampleR[0];
end
end
else
begin
if (i-trigDate>=nbAp)
then Ftrig:=false
else storeWSample;
if (i mod nbvoie=VoieSync-1) then oldw1:=wSampleR[0];
end;
end;
GI1:=GI2;
end;
{****************** Synchro mode analogique absolu ***************************}
{l'ADC est en mode circulaire. On teste la voie synchro en permanence.
La voie synchro ne fait pas partie des voies acquises. Sinon voir DoAnalogAbs
}
procedure TITCInterface.DoAnalogAbs1;
var
i,j:integer;
k,index,ideb:integer;
x:boolean;
tt:single;
begin
GI2:=getCount-1;
for i:=GI1+1 to GI2 do
begin
nextSample;
if not Ftrig then
begin
if (i mod nbvoie=VoieSync-1) then
begin
if (i>nbAv) and
((wSampleR[0]>=seuilP) and (oldw1<seuilP) OR (wSampleR[0]<=seuilM) and (oldw1>seuilM)) then
begin
TrigDate:=i div nbvoie*nbvoie;
Ftrig:=true;
for j:=trigDate-nbAv to i do
if j mod nbvoie<>nbvoie-1 then copySample(j);
end;
oldw1:=wSampleR[0];
end
end
else
begin
if (i-trigDate>=nbAp) then Ftrig:=false
else
begin
if (i mod nbvoie=VoieSync-1)
then oldw1:=wSampleR[0]
else storeWSample;
end;
end;
end;
GI1:=GI2;
end;
function TITCinterface.isWaiting: boolean;
begin
result:=Fwaiting;
end;
function TITCinterface.dataFormat:TdataFormat;
begin
result:=F16bits;
end;
function TITCinterface.DacFormat:TdacFormat;
begin
result:=DacF1322;
end;
function TITCinterface.PeriodeElem:float;
begin
result:=5;
end;
function TITCinterface.PeriodeMini:float;
begin
result:=5;
end;
procedure TITCinterface.outdac(num,j:word);
begin
end;
function TITCinterface.outDIO(dev,port,value:integer): integer;
var
ItcData: ITCChannelDataEx;
error: integer;
begin
fillchar(ItcData, sizeof(ItcData),0);
ItcData.ChannelType := DIGITAL_OUTPUT;
ItcData.ChannelNumber := port;
Error := ITC_AsyncIO(DeviceHandle[dev], 1, ItcData);
end;
function TITCinterface.inADC(n:integer):smallint;
begin
end;
function TITCinterface.inDIO(dev,port:integer):integer;
var
ItcData: ITCChannelDataEx;
error: integer;
begin
fillchar(ItcData, sizeof(ItcData),0);
ItcData.ChannelType := DIGITAL_INPUT;
ItcData.ChannelNumber := port;
Error := ITC_AsyncIO(DeviceHandle[dev], 1, ItcData);
if error=0
then result:=ItcData.Value
else result:=-1;
end;
procedure TITCinterface.copySample(i:integer);
var
n:integer;
begin
n:=i mod nbBufIn;
wsample[0]:=bufIn[n][(i div nbBufIn) mod BufInSize];
wsampleR[0]:=wsample[0];
storeWsample;
end;
function TITCinterface.RangeString:AnsiString;
begin
result:='-10 V to 10 V';
end;
function TITCinterface.MultiGain:boolean;
begin
result:=false;
end;
function TITCinterface.GainLabel:AnsiString;
begin
result:='Range';
end;
function TITCinterface.nbGain;
begin
result:=1;
end;
function TITCinterface.channelRange:boolean;
begin
result:=false;
end;
procedure TITCinterface.GetOptions;
begin
ITCoptions.execution(self);
end;
procedure TITCinterface.setDoAcq(var procInt:ProcedureOfObject);
var
modeSync:TmodeSync;
begin
with acqInf do
begin
if continu
then modeSync:=MSimmediat
else modeSync:=modeSynchro;
if continu then ProcInt:=DoContinuous
else
case modeSync of
MSimmediat, MSinterne: if not WaitMode
then ProcInt:=doInterne
else ProcInt:=doNumPlusStim;
MSnumPlus: if AcqInf.Fstim then ProcInt:=doNumPlusStim
else ProcInt:=doNumPlus;
MSanalogAbs: ProcInt:=DoAnalogAbs;
else ProcInt:=nil;
end;
end;
end;
procedure TITCinterface.initcfgOptions(conf:TblocConf);
begin
with conf do
begin
setvarconf('UseTagStart',FUseTagStart,sizeof(FUseTagStart));
setvarconf('Delay1600',Delay1600,sizeof(Delay1600));
end;
end;
function TITCinterface.TagMode:TtagMode;
begin
if FuseTagStart
then result:=tmITC
else result:=tmNone;
end;
function TITCinterface.tagShift:integer;
begin
result:=0;
end;
function TITCinterface.TagCount: integer;
begin
result:=5;
end;
procedure TITCinterface.restartAfterWait;
begin
end;
function TITCinterface.getMinADC:integer;
begin
result:=-32768;
end;
function TITCinterface.getMaxADC:integer;
begin
result:=32767;
end;
procedure initITCBoards;
var
ITC16Nb: longword;
ITC18Nb: longword;
ITC1600Nb:longword;
ITC00Nb: longword;
ITC18USBnb: longword;
error: longword;
i:integer;
begin
if not initITClib then exit;
Error := ITC_Devices (ITC16_ID, ITC16Nb);
if Error <> 0 then ITC16Nb:=0;
Error := ITC_Devices (ITC18_ID, ITC18Nb);
if Error <> 0 then ITC18Nb:=0;
Error := ITC_Devices (ITC1600_ID, ITC1600Nb);
if Error <> 0 then ITC1600Nb:=0;
Error := ITC_Devices (ITC18USB_ID, ITC18USBNb);
if Error <> 0 then ITC18USBNb:=0;
for i:=0 to ITC16nb-1 do
registerBoard('ITC16 #'+Istr(i),pointer(TITCinterface));
for i:=0 to ITC18nb-1 do
registerBoard('ITC18 #'+Istr(i),pointer(TITCinterface));
for i:=0 to ITC1600nb-1 do
registerBoard('ITC1600 #'+Istr(i),pointer(TITCinterface));
if ITC1600nb=2 then
registerBoard('DUAL ITC1600 #0',pointer(TITCinterface));
for i:=0 to ITC18USBnb-1 do
registerBoard('ITC18USB #'+Istr(i),pointer(TITCinterface));
end;
var
DevHandle: Thandle;
procedure TestITC;
var
error:integer;
begin
if not initITClib then exit;
error:=ITC_OpenDevice(ITC1600_ID,0,Smart_Mode,devHandle);
if error<>0 then messageCentral(ITCerror(DevHandle,error));
end;
{ OutData: i0 est l'indice de départ des data dans PstimBuf (0 à EpSize*StoredEp)
nb est le nombre de points à envoyer }
function TITCinterface.OutData(i0, nb: integer):boolean;
var
dev,i,error:integer;
numB,numAbs:integer;
begin
affDebug('outData '+Istr1(i0,10)+Istr1(nb,10),25);
for dev:=0 to ord(dual1600) do
with infoDev[dev] do
begin
for i:=0 to nbOut-1 do
begin
ITCdataOut[dev,i].Command := PRELOAD_FIFO_COMMAND_EX ;
ITCdataOut[dev,i].value:=nb;
with infoOut[i] do
begin
numB:=infoOut[i].Numbuf;
numAbs:=physNum+DACcount(dev)*ord(isDigi);
end;
if numB>=0 then
begin
ITCdataOut[dev,i].DataPointer:=@Pstimbuf[numB,i0];
Vhold[dev,numAbs]:=Pstimbuf[numB,i0+nb-1];
end
else
begin
ITCdataOut[dev,i].DataPointer:=@bufDigi0[0];
Vhold[dev,numAbs]:=bufDigi0[(i0+nb-1) mod EpSize];
end;
end;
Error:= ITC_ReadWriteFIFO(DeviceHandle[dev], nbOut, ITCdataOut[dev,0]);
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
break;
end;
end;
inc(cntStim,Nb*nbChOut);
result:=not flagStop;
end;
{ OutDataHold sort nb points avec les valeurs courantes de Vhold }
function TITCinterface.OutDataHold(nb: integer):boolean;
var
dev,i,j,error:integer;
w:smallint;
numAbs:integer;
begin
for dev:=0 to ord(dual1600) do
with infoDev[dev] do
begin
for i:=0 to nbOut-1 do
begin
with infoOut[i] do
numAbs:=physNum+DACcount(dev)*ord(isDigi);
w:=Vhold[dev,numAbs];
if length(HoldBuf[dev,i])<nb then setLength(HoldBuf[dev,i],nb);
for j:=0 to nb-1 do HoldBuf[dev,i][j]:=w;
ITCdataOut[dev,i].Command := PRELOAD_FIFO_COMMAND_EX;
ITCdataOut[dev,i].value:=nb;
ITCdataOut[dev,i].DataPointer:=@HoldBuf[dev,i][0];
end;
Error:= ITC_ReadWriteFIFO(DeviceHandle[dev], nbOut, ITCdataOut[dev,0]);
if error<>0 then
begin
ITCmessage(dev,error);
flagStop:=true;
break;
end;
end;
result:=not flagStop;
end;
function TITCinterface.OutDataDelay(nb: integer):boolean;
var
i,j,error:integer;
w:smallint;
numAbs:integer;
begin
if not Dual1600 then exit;
with infoDev[0] do
begin
for i:=0 to nbOut-1 do
begin
with infoOut[i] do
numAbs:=physNum+DACcount(0)*ord(isDigi);
w:=Vhold[0,numAbs];
if length(HoldBuf[0,i])<nb then setLength(HoldBuf[0,i],nb);
for j:=0 to nb-1 do HoldBuf[0,i][j]:=w;
ITCdataOut[0,i].Command := PRELOAD_FIFO_COMMAND_EX;
ITCdataOut[0,i].value:=nb;
ITCdataOut[0,i].DataPointer:=@HoldBuf[0,i][0];
if infoOut[i].isDigi and (infoOut[i].physNum=0) then
for j:=0 to nb-1 do HoldBuf[0,i][j]:=HoldBuf[0,i][j] or $10;
end;
Error:= ITC_ReadWriteFIFO(DeviceHandle[0], nbOut, ITCdataOut[0,0]);
if error<>0 then
begin
ITCmessage(0,error);
flagStop:=true;
end;
end;
result:=not flagStop;
end;
function TITCinterface.OutPossible: integer;
var
dev,i,error:integer;
x:integer;
begin
{ Combien de points peut-on envoyer par voie ? }
result:=maxEntierLong;
for dev:=0 to ord(dual1600) do
with infoDev[dev] do
begin
error:=ITC_getDataAvailable(deviceHandle[dev],nbOut,ITCdataOut[dev,0]);
if error<>0 then ITCmessage(dev,error);
for i:=0 to nbOut-1 do
begin
ITCdataOut[dev,i].Command := 0;
x:=ITCdataOut[dev,i].value;
if x<result then result:=x;
end;
end;
end;
{ OutPoints : i0 est l'index absolu de départ
nb un nombre de points
Ce nombre doit être inférieur à OutPossible
}
procedure TITCinterface.OutPoints(i0, nb: int64);
var
ep,epS,Iisi,IfinEp,IfinIsi:int64;
nbE:int64;
Ifin:int64;
begin
if nb<=0 then exit;
Ifin:=i0+nb;
repeat
ep:= i0 div IsiSize; { Ep absolu }
epS:= ep mod StoredEp; { Ep relatif dans les stored Ep }
Iisi:= i0 mod IsiSize; { Index dans Isi }
IfinEp:= ep*IsiSize+ EpSize; { index absolu de la fin de l'épisode }
IfinIsi:= (ep+1)*IsiSize; { index absolu de la fin de l'isi }
if i0<IfinEp then
begin
if i0+nb<=IfinEp
then nbE:=nb
else nbE:=IfinEp-i0;
if i0+nbE>Ifin then nbE:=Ifin-i0;
outData(EpS*EpSize+Iisi,nbE);
inc(i0,nbE);
end
else
if i0<IfinIsi then
begin
if i0+nb<=IfinIsi
then nbE:=nb
else nbE:=IfinIsi-i0;
if i0+nbE>Ifin then nbE:=Ifin-i0;
outDataHold(nbE);
inc(i0,nbE);
end;
until i0>=Ifin;
inc(nbDataOut,nb);
end;
procedure TITCinterface.PreloadDac;
var
maxDataOut:int64;
nb:int64;
numEp:int64;
begin
if not (FlagStim or Dual1600) then exit;
OutDataDelay(nbDelay1600);
{}
oldNbOut:=0;
maxdataOut:=OutPossible;
if nbchOut>0 then
begin
numEp:=baseIndex div nbchOut div EpSize;
nbdataOut:=numEp*IsiSize;
end
else nbdataOut:=IsiSize;
nb:=IsiSize*storedEp;
if nb>maxdataOut
then nb:=maxdataOut;
outPoints(nbDataOut ,nb);
{cntStim:=cntStim-EpSize*nbChOut;}
{paramStim.setOutPutValues(cntStim);}
end;
function TITCinterface.deviceCount: integer;
begin
result:=1 + ord(dual1600);
end;
function TITCinterface.ADCcount(dev:integer): integer;
begin
result:=deviceInfo[dev].NumberOfADCs;
end;
function TITCinterface.DACcount(dev:integer): integer;
begin
result:=deviceInfo[dev].NumberOfDACs;
end;
function TITCinterface.DigiInCount(dev:integer): integer;
begin
result:=deviceInfo[dev].NumberOfDIs;
end;
function TITCinterface.DigiOutCount(dev:integer): integer;
begin
result:=deviceInfo[dev].NumberOfDOs;
end;
function TITCinterface.bitInCount(dev:integer): integer;
begin
result:=16;
end;
function TITCinterface.bitOutCount(dev:integer): integer;
begin
result:=16;
end;
function TITCinterface.CheckParams: boolean;
var
i,dev:integer;
error:integer;
InChannels1,OutChannels1: array of array of ITCChannelInfo;
st:AnsiString;
begin
init;
setLength(InChannels1,2);
setLength(OutChannels1,2);
for dev:=0 to ord(Dual1600) do
with infoDev[dev] do
begin
ITC_resetChannels(deviceHandle[dev]); {resetChannels }
error:=ITC_setChannels(deviceHandle[dev],nbIn,InChannels[dev,0]); {setChannels }
if error<>0 then
begin
ITCmessage(dev,error);
exit;
end;
if (Flagstim or Dual1600) and (nbOut>0) then
begin
error:=ITC_setChannels(deviceHandle[dev],nbOut,OutChannels[dev,0]);{setChannels }
if error<>0 then
begin
ITCmessage(dev,error);
exit;
end;
end;
{ Mettre à jour les canaux }
error:=ITC_UpdateChannels(deviceHandle[dev]); {updateChannels}
if error<>0 then
begin
ITCmessage(dev,error);
exit;
end;
setLength(InChannels1[dev],length(InChannels[dev]));
move(InChannels[dev,0],InChannels1[dev,0],sizeof(ITCchannelInfo)*length(InChannels[dev]));
setLength(OutChannels1[dev],length(OutChannels[dev]));
move(OutChannels[dev,0],OutChannels1[dev,0],sizeof(ITCchannelInfo)*length(OutChannels[dev]));
st:='';
{ Relire les valeurs effectives en entrée}
if nbIn>0 then
begin
error:=ITC_GetChannels(deviceHandle[dev],nbin,InChannels1[dev,0]);
if error<>0 then ITCmessage(dev,error);
end;
for i:=0 to nbin-1 do
st:=st+ Estr(InChannels1[dev,i].samplingRate,3) +crlf;
{ Relire les valeurs effectives en sortie}
if nbOut>0 then
begin
error:=ITC_GetChannels(deviceHandle[dev],nbOut,OutChannels1[dev,0]);
if error<>0 then ITCmessage(dev,error);
end;
for i:=0 to nbout-1 do
st:=st+ Estr(OutChannels1[dev,i].samplingRate,3) +crlf;
end;
messageCentral(st);
end;
function TITCinterface.nbVoieAcq(n: integer): integer;
begin
result:=n+ord(FuseTagStart);
end;
procedure TITCinterface.saveBufIn;
var
tb:array of smallint;
n1,n2,i,j:integer;
begin
(*
n1:=length(FifoBuf[0]);
n2:=20000;
setLength(tb,n1*n2);
for i:=0 to n1-1 do
move(Fifobuf[0,i,0],tb[i*n2],n2*2);
*)
(*
n1:=length(bufIn);
n2:=length(bufIn[0]);
setLength(tb,n1*n2);
for i:=0 to n1-1 do
move(bufIn[i,0],tb[i*n2],n2*2);
*)
{SaveArrayAsDac2File(debugPath+'BufIn.dat',tb[0],length(tb),g_smallint);}
end;
procedure TITCinterface.setVSoptions;
begin
FuseTagStart:=true;
acqInf.voieSynchro:=0;
end;
procedure TITCinterface.GetPeriods(PeriodU: float; nbADC, nbDI, nbDAC, nbDO: integer; var periodIn,periodOut: float);
var
p:float;
begin
if nbADC<1 then nbADC:=1;
if nbADC>=3 then nbADC:=4;
p:=periodU*1000/nbADC; { période globale en microsecondes}
p:=round(p/periodeElem)*periodeElem; { doit être un multiple de periodeElem }
if p<periodeMini then p:=periodeMini; { doit être supérieure à periodeMini }
periodIn:=p*nbADC/1000; { période calculée en millisecondes }
periodOut:=periodIn;
end;
function TITCinterface.setValue(Device, tpOut, physNum, value: integer):boolean;
var
data:ITCchannelDataEx;
error:integer;
begin
result:=false;
if (device<0) or (device>ord(dual1600)) then sortieErreur('Tstimulator.SetValue : bad device');
fillchar(data,sizeof(data),0);
case tpOut of
0: data.ChannelType:=H2D;
1: data.ChannelType:=Digital_Output;
2: data.ChannelType:=Aux_Output;
else sortieErreur('Tstimulator.SetValue : bad output type');
end;
data.ChannelNumber:=physNum;
data.Value:=value;
error:=ITC_AsyncIO(deviceHandle[Device],1,data);
result:=(error=0);
if not result then sortieErreur(ITCerror(deviceHandle[device],error));
end;
function TITCinterface.getValue(Device, tpIn,physNum: integer;var value: smallint):boolean;
var
data:ITCchannelDataEx;
error:integer;
begin
result:=false;
if (device<0) or (device>ord(dual1600)) then sortieErreur('Tstimulator.SetValue : bad device');
fillchar(data,sizeof(data),0);
case tpIn of
0: data.ChannelType:=D2H;
1: data.ChannelType:=Digital_Input;
2: data.ChannelType:=Aux_Input;
else sortieErreur('Tstimulator.getValue : bad input type');
end;
data.ChannelNumber:=physNum;
error:=ITC_AsyncIO(deviceHandle[Device],1,data);
result:=(error=0);
if not result then sortieErreur(ITCerror(deviceHandle[device],error));
value:=data.Value;
end;
Initialization
AffDebug('Initialization ITCbrd',0);
initITCboards;
end.
|
unit Common;
interface
uses
Classes, Contnrs;
type
TConfig = class
ne_type: String;
ne_release: String;
description: String;
sysOIDValue: String;
addOIDName1: String;
addOIDValue1: String;
addOIDName2: String;
addOIDValue2: String;
addOIDName3: String;
addOIDValue3: String;
addOIDName4: String;
addOIDValue4: String;
parseStatus: String;
validateStatus: String;
generateStatus: String;
deployStatus: String;
generalStatus: String;
createUser: String;
deployUser: String;
createDate: String;
deployDate: String
end;
TConfigList = class
Items: TObjectList;
constructor Create;
destructor Destroy; override;
end;
TMetaData = class
mibFiles: TStringList;
allOIDs: TObjectList;
suggestOIDs: TObjectList;
constructor Create;
destructor Destroy; override;
end;
TOIDResult = class
name: String;
value: String;
desc: String
end;
TStatus = class
status: String;
end;
function ParseConfigListJSONStringToObject(json: String): TConfigList;
function ParseConfigJSONStringToObject(json: String): TConfig;
function ParseStatusJSONString(json: String): String;
function ParseMetaJSONStringToObject(json: String): TMetaData;
function BuildConfigJSONString(config: TConfig): String;
function GetJSONResponse(url: String): String;
function PostJSONRequest(url: String; json: String): String;
procedure UploadFile(url, ne_type, ne_release, file_name: String);
implementation
uses
uLkJSON, Variants, IdHTTP, IdMultipartFormData;
{ TConfig }
constructor TConfigList.Create;
begin
Items := TObjectList.Create;
end;
destructor TConfigList.Destroy;
begin
Items.Free;
end;
constructor TMetaData.Create;
begin
mibFiles := TStringList.Create;
allOIDs := TObjectList.Create;
suggestOIDs := TObjectList.Create;
end;
destructor TMetaData.Destroy;
begin
mibFiles.Free;
allOIDs.Free;
suggestOIDs.Free;
end;
function ParseConfigListJSONStringToObject(json: String): TConfigList;
var
jo1, jo2, jo3, jo4: TlkJSONBase;
i: Integer;
config: TConfig;
configList: TConfigList;
begin
configList := TConfigList.Create;
jo1 := TlkJSON.ParseText(json);
jo2 := jo1.Field['configList'];
for i:=0 to jo2.Count - 1 do
begin
jo3 := jo2.Child[i];
config := TConfig.Create;
config.ne_type := VarToStr(jo3.Field['type'].Value);
config.ne_release := VarToStr(jo3.Field['release'].Value);
config.description := VarToStr(jo3.Field['description'].Value);
config.sysOIDValue := VarToStr(jo3.Field['sysOIDValue'].Value);
config.parseStatus := VarToStr(jo3.Field['parseStatus'].Value);
config.validateStatus := VarToStr(jo3.Field['validateStatus'].Value);
config.generateStatus := VarToStr(jo3.Field['generateStatus'].Value);
config.deployStatus := VarToStr(jo3.Field['deployStatus'].Value);
config.generalStatus := VarToStr(jo3.Field['generalStatus'].Value);
config.createUser := VarToStr(jo3.Field['createUser'].Value);
config.deployUser := VarToStr(jo3.Field['deployUser'].Value);
config.createDate := VarToStr(jo3.Field['createDate'].Value);
config.deployDate := VarToStr(jo3.Field['deployDate'].Value);
jo4 := jo3.Field['additionalOID'];
config.addOIDName1 := jo4.Child[0].Field['oid'].Value;
config.addOIDValue1 := jo4.Child[0].Field['value'].Value;
config.addOIDName2 := jo4.Child[1].Field['oid'].Value;
config.addOIDValue2 := jo4.Child[1].Field['value'].Value;
config.addOIDName3 := jo4.Child[2].Field['oid'].Value;
config.addOIDValue3 := jo4.Child[2].Field['value'].Value;
config.addOIDName4 := jo4.Child[3].Field['oid'].Value;
config.addOIDValue4 := jo4.Child[3].Field['value'].Value;
configList.Items.Add(config);
end;
result := configList;
jo1.Free;
end;
function ParseConfigJSONStringToObject(json: String): TConfig;
var
jo1, jo2, jo3: TlkJSONBase;
config: TConfig;
begin
config := TConfig.Create;
jo1 := TlkJSON.ParseText(json);
jo2 := jo1.Field['config'];
config.ne_type := VarToStr(jo2.Field['type'].Value);
config.ne_release := VarToStr(jo2.Field['release'].Value);
config.description := VarToStr(jo2.Field['description'].Value);
config.sysOIDValue := VarToStr(jo2.Field['sysOIDValue'].Value);
config.parseStatus := VarToStr(jo2.Field['parseStatus'].Value);
config.validateStatus := VarToStr(jo2.Field['validateStatus'].Value);
config.generateStatus := VarToStr(jo2.Field['generateStatus'].Value);
config.deployStatus := VarToStr(jo2.Field['deployStatus'].Value);
config.generalStatus := VarToStr(jo2.Field['generalStatus'].Value);
config.createUser := VarToStr(jo2.Field['createUser'].Value);
config.deployUser := VarToStr(jo2.Field['deployUser'].Value);
config.createDate := VarToStr(jo2.Field['createDate'].Value);
config.deployDate := VarToStr(jo2.Field['deployDate'].Value);
jo3 := jo2.Field['additionalOID'];
config.addOIDName1 := jo3.Child[0].Field['oid'].Value;
config.addOIDValue1 := jo3.Child[0].Field['value'].Value;
config.addOIDName2 := jo3.Child[1].Field['oid'].Value;
config.addOIDValue2 := jo3.Child[1].Field['value'].Value;
config.addOIDName3 := jo3.Child[2].Field['oid'].Value;
config.addOIDValue3 := jo3.Child[2].Field['value'].Value;
config.addOIDName4 := jo3.Child[3].Field['oid'].Value;
config.addOIDValue4 := jo3.Child[3].Field['value'].Value;
result := config;
jo1.Free;
end;
function BuildConfigJSONString(config: TConfig): String;
var
jo_root: TlkJsonObject;
jo_addOIDList: TlkJsonList;
jo_addOID1, jo_addOID2, jo_addOID3, jo_addOID4: TlkJsonObject;
begin
jo_root := TlkJsonObject.Create;
jo_root.Add('type', config.ne_type);
jo_root.Add('release', config.ne_release);
if config.description <> '' then jo_root.Add('description', config.description);
if config.createUser <> '' then jo_root.Add('createUser', config.createUser);
if config.createDate <> '' then jo_root.Add('createDate', config.createDate);
if config.parseStatus <> '' then jo_root.Add('parseStatus', config.parseStatus);
if config.validateStatus <> '' then jo_root.Add('validateStatus', config.validateStatus);
if config.generateStatus <> '' then jo_root.Add('generateStatus', config.generateStatus);
if config.deployStatus <> '' then jo_root.Add('deployStatus', config.deployStatus);
if config.generalStatus <> '' then jo_root.Add('generalStatus', config.generalStatus);
if config.deployUser <> '' then jo_root.Add('deployUser', config.deployUser);
if config.deployDate <> '' then jo_root.Add('deployDate', config.deployDate);
if config.sysOIDValue <> '' then jo_root.Add('sysOIDValue', config.sysOIDValue);
jo_addOIDList := TlkJsonList.Create;
jo_addOID1 := nil;
jo_addOID2 := nil;
jo_addOID3 := nil;
jo_addOID4 := nil;
if (config.addOIDName1 <> '') and (config.addOIDValue1 <> '') then
begin
jo_addOID1 := TlkJsonObject.Create;
jo_addOID1.Add('oid', config.addOIDName1);
jo_addOID1.Add('value', config.addOIDValue1);
jo_addOIDList.Add(jo_addOID1);
end;
if (config.addOIDName2 <> '') and (config.addOIDValue2 <> '') then
begin
jo_addOID2 := TlkJsonObject.Create;
jo_addOID2.Add('oid', config.addOIDName2);
jo_addOID2.Add('value', config.addOIDValue2);
jo_addOIDList.Add(jo_addOID2);
end;
if (config.addOIDName3 <> '') and (config.addOIDValue3 <> '') then
begin
jo_addOID3 := TlkJsonObject.Create;
jo_addOID3.Add('oid', config.addOIDName3);
jo_addOID3.Add('value', config.addOIDValue3);
jo_addOIDList.Add(jo_addOID3);
end;
if (config.addOIDName4 <> '') and (config.addOIDValue4 <> '') then
begin
jo_addOID4 := TlkJsonObject.Create;
jo_addOID4.Add('oid', config.addOIDName4);
jo_addOID4.Add('value', config.addOIDValue4);
jo_addOIDList.Add(jo_addOID4);
end;
if jo_addOIDList.Count > 0 then jo_root.Add('additionalOID', jo_addOIDList);
result := TlkJSON.GenerateText(jo_root);
jo_root.Free;
end;
function ParseMetaJSONStringToObject(json: String): TMetaData;
var
joRoot, joMibFileList, joAllOIDList, joSuggestOIDList, joOID: TlkJSONBase;
i: Integer;
metaData: TMetaData;
OIDResult: TOIDResult;
begin
metaData := TMetaData.Create;
joRoot := TlkJSON.ParseText(json);
joMibFileList := joRoot.Field['mibFiles'];
joAllOIDList := joRoot.Field['allOIDs'];
joSuggestOIDList := joRoot.Field['suggestOIDs'];
for i:=0 to joMibFileList.Count - 1 do
begin
metaData.mibFiles.Add(VarToStr(joMibFileList.Child[i].Value));
end;
for i:=0 to joAllOIDList.Count - 1 do
begin
joOID := joAllOIDList.Child[i];
OIDResult := TOIDResult.Create;
OIDResult.name := VarToStr(joOID.Field['name'].Value);
OIDResult.value := VarToStr(joOID.Field['value'].Value);
OIDResult.desc := VarToStr(joOID.Field['description'].Value);
metaData.allOIDs.Add(OIDResult);
end;
for i:=0 to joSuggestOIDList.Count - 1 do
begin
joOID := joSuggestOIDList.Child[i];
OIDResult := TOIDResult.Create;
OIDResult.name := VarToStr(joOID.Field['name'].Value);
OIDResult.value := VarToStr(joOID.Field['value'].Value);
OIDResult.desc := VarToStr(joOID.Field['description'].Value);
metaData.suggestOIDs.Add(OIDResult);
end;
result := metaData;
joRoot.Free;
end;
function ParseStatusJSONString(json: String): String;
var
jo: TlkJSONBase;
status: TStatus;
begin
status := TStatus.Create;
jo := TlkJSON.ParseText(json);
result := VarToStr(jo.Field['status'].Value);
status.free;
jo.Free;
end;
function GetJSONResponse(url: String): String;
var
idHttp: TIdHTTP;
begin
idHttp := TIdHTTP.Create(nil);
try
result := idHttp.Get(url);
finally
idHttp.Free;
end;
end;
function PostJSONRequest(url: String; json: String): String;
var
idHttp: TIdHTTP;
js: TStringStream;
begin
idHttp := TIdHTTP.Create(nil);
js := TStringStream.Create(json);
try
idHttp.Request.ContentType := 'application/json';
result := idHttp.Post(url, js);
finally
idHttp.Free;
js.Free;
end;
end;
procedure UploadFile(url, ne_type, ne_release, file_name: String);
var
idHttp: TIdHTTP;
content: TIdMultiPartFormDataStream;
begin
idHttp := TIdHttp.Create(nil);
content := TIdMultiPartFormDataStream.Create;
try
content.AddFormField('type', ne_type);
content.AddFormField('release', ne_release);
content.AddFile('file', file_name, 'application/octet-stream');
idHttp.Post(url, content);
finally
idHttp.Free;
content.Free;
end;
end;
end.
|
{Dado un archivo de enteros, leerlos en un arreglo A, obtener el promedio de
todos los números divisores del máximo y con ellos armar otro arreglo B.
Mostrar ambos arreglos.
Ejemplo:
Archivo : 5 7 1 12 15 -8 10 2 25 26 50 13
A= (5, 7, 1, 12, 15, -8, 10, 2, 25, 26, 50, 13)
Maximo = 50 Prom=15.5 B=( 5, 1, 10, 2, 25, 50 )}
Program TP_array;
Type
TV = array[1..100] of integer;
Procedure LeerArchivo(Var A:TV; Var N:byte);
Var
arch:text;
begin
N:= 0;
assign(arch,'TP_array.txt');reset(arch);
while not eof (arch) do
begin
N:= N + 1;
readln(arch,A[N]);
end;
close(arch);
end;
Function Maximo(A:TV; N:byte):byte;
Var
i,Max:byte;
begin
Max:= 0;
For i:= 1 to N do
begin
If (A[i] > Max) then
Max:= A[i];
end;
Maximo:= Max;
end;
Procedure GenerarArray(A:TV; N:byte; Var B:TV; Var M:byte);
Var
i:byte;
Max:byte;
begin
M:= 0;
Max:= Maximo(A,N);
For i:= 1 to N do
begin
If (Max MOD A[i] = 0) then
begin
M:= M + 1;
B[M]:= A[i];
end;
end;
end;
Function Promedio(B:TV; M:byte):real;
Var
i,Cont:byte;
Suma:integer;
begin
Suma:= 0;
Cont:= 0;
For i:= 1 to M do
begin
Suma:= Suma + B[i];
Cont:= Cont + 1;
end;
Promedio:= Suma / Cont;
end;
Procedure ImprimeArray(A:TV; N:byte);
Var
i:byte;
begin
For i:= 1 to N do
write(A[i]:4);
end;
Var
A,B:TV;
N,M:byte;
Begin
LeerArchivo(A,N);
GenerarArray(A,N,B,M);
writeln('Maximo: ',Maximo(A,N));
writeln;
writeln('El promedio de los maximos es: ',Promedio(B,M):2:1);
writeln;
write('Vector A: ');
ImprimeArray(A,N);
writeln;
writeln;
write('Vector B: ');
ImprimeArray(B,M);
end.
|
//******************************************************************************
// Пакет для добавленя, изменения, удаления данных о свойствах людей
// параметры: ID - идентификатор, если добавление, то идентификатор человека, иначе
// идентификатор свойства человека.
//******************************************************************************
unit PeopleComandirovki_Ctrl_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, StdCtrls, cxButtons, cxCalendar,
cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls,
cxControls, cxGroupBox,ZMessages, ZProc,
Unit_ZGlobal_Consts, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase, DB, FIBDataSet, pFIBDataSet, ZTypes, IBase, ActnList, PeopleComandiriovki_Ctrl_DM,
cxCalc, cxButtonEdit, GlobalSpr, PackageLoad;
type
TFSp_People_WorkMode_Control = class(TForm)
IdentificationBox: TcxGroupBox;
PeopleLabel: TcxLabel;
PeopleEdit: TcxMaskEdit;
PeriodBox: TcxGroupBox;
YesBtn: TcxButton;
CancelBtn: TcxButton;
DateBegLabel: TcxLabel;
DateBeg: TcxDateEdit;
DateEndLabel: TcxLabel;
DateEnd: TcxDateEdit;
Actions: TActionList;
ActionYes: TAction;
WorkDogLabel: TcxLabel;
cxMaskEdit1: TcxMaskEdit;
cxLabel1: TcxLabel;
AvgCalc: TcxCalcEdit;
EditSmeta: TcxButtonEdit;
LabelSmetaName: TcxLabel;
cxLabel2: TcxLabel;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
EditVidOpl: TcxButtonEdit;
LabelVidOplData: TcxLabel;
cxLabel3: TcxLabel;
procedure CancelBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaExit(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure EditVidOplExit(Sender: TObject);
procedure EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
Ins_Id_Man:LongWord;
PParameter:TZPeopleComandirovParameters;
DM:TDMWorkMode_Ctrl;
PLanguageIndex:Byte;
pNumPredpr:integer;
PId_Smeta:Integer;
PId_VidOpl:Integer;
public
constructor Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZPeopleComandirovParameters;Is_Grant: TZChildSystems);reintroduce;
property ID_Man:LongWord read Ins_Id_Man write Ins_Id_Man;
property Parameter:TZPeopleComandirovParameters read PParameter;
end;
implementation
uses StrUtils;
{$R *.dfm}
constructor TFSp_People_WorkMode_Control.Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZPeopleComandirovParameters;Is_Grant: TZChildSystems);
begin
inherited Create(AOwner);
PParameter := AParameters;
DM := TDMWorkMode_Ctrl.Create(AOwner,DB_Handle,AParameters,Is_Grant);
PLanguageIndex:=LanguageIndex;
pNumPredpr := StrToInt(VarToStrDef(ValueFieldZSetup(DB_Handle,'NUM_PREDPR'),'1'));
//******************************************************************************
PeopleLabel.Caption := LabelMan_Caption[PLanguageIndex];
WorkDogLabel.Caption := 'Трудовий договір';
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]+' - ';
DateEndLabel.Caption := ' - '+AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]);
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
//******************************************************************************
case PParameter.ControlFormStyle of
zcfsInsert:
begin
DateBeg.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']);
DateBeg.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']);
DateEnd.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']);
DateEnd.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']);
cxMaskEdit1.Text :=DM.DSetData['NAME_POST'];
Caption := 'Додати відрядження';
PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']);
DateBeg.Date := Date;
DateEnd.Date := Date;
EditVidOpl.Text := AParameters.kod_vidopl;
//Pid_vidopl := AParameters.id_vidopl;
EditVidOplExit(self); //подгрузить заголовок и айди
end;
zcfsUpdate:
begin
DateBeg.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']);
DateBeg.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']);
DateEnd.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']);
DateEnd.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']);
cxMaskEdit1.Text :=DM.DSetData['NAME_POST'];
Caption := 'Змінити відрядження';
PeopleEdit.Text := VarToStr(DM.DSetData['FIO']);
DateBeg.Date := AParameters.date_beg;
DateEnd.Date := AParameters.date_end;
if AParameters.avg_sum=NULL
then begin
AvgCalc.Enabled:=false;
CheckBox2.Checked:=true;
end
else begin
AvgCalc.EditValue := AParameters.avg_sum;
AvgCalc.Enabled:=true;
CheckBox2.Checked:=false;
end;
EditSmeta.Text := AParameters.smeta_kod;
PId_Smeta := AParameters.id_smeta;
EditVidOpl.Text := AParameters.kod_vidopl;
Pid_vidopl := AParameters.id_vidopl;
EditVidOplExit(self); //подгрузить заголовок
if AParameters.id_smeta<>0
then begin
LabelSmetaName.Caption:=IntToStr(PId_Smeta);
EditSmeta.Enabled:=true;
LabelSmetaName.Enabled:=true;
CheckBox1.Checked:=false;
end
else begin
LabelSmetaName.Caption:='АВТО';
EditSmeta.Enabled:=false;
LabelSmetaName.Enabled:=false;
CheckBox1.Checked:=true;
end;
end;
zcfsShowDetails:
begin
cxMaskEdit1.Text :=DM.DSetData['NAME_POST'];
Caption := 'Інформація по відрядженню';
PeopleEdit.Text := VarToStr(DM.DSetData['FIO']);
DateBeg.Date := AParameters.date_beg;
DateEnd.Date := AParameters.date_end;
PeriodBox.Enabled := False;
YesBtn.Visible := False;
AvgCalc.EditValue := AParameters.avg_sum;
AvgCalc.Enabled := False;
CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex];
EditVidOpl.Text := AParameters.kod_vidopl;
Pid_vidopl := AParameters.id_vidopl;
EditVidOplExit(self); //подгрузить заголовок
EditVidOpl.Enabled := False;
LabelVidOplData.Enabled := False;
end;
end;
end;
procedure TFSp_People_WorkMode_Control.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFSp_People_WorkMode_Control.FormCreate(Sender: TObject);
begin
if PParameter.ControlFormStyle = zcfsDelete
then begin
if ZShowMessage(ZPeopleWorkModeCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes
then begin
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_COMANDIROVKI_DEL';
StoredProc.Prepare;
StoredProc.ParamByName('ID_COM').AsInteger := PParameter.ID;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
end
else ModalResult:=mrCancel;
end;
end;
procedure TFSp_People_WorkMode_Control.ActionYesExecute(Sender: TObject);
var ID:integer;
begin
if (AvgCalc.EditValue<0)
then begin
ZShowMessage(Error_Caption[PLanguageIndex],'Не можна вводити від''''ємне середне!',mtWarning,[mbOK]);
AvgCalc.SetFocus;
Exit;
end;
if DateBeg.Date>DateEnd.Date
then begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
DateBeg.SetFocus;
end
else begin
case PParameter.ControlFormStyle of
zcfsInsert:
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_COMANDIROVKI_INS';
StoredProc.Prepare;
StoredProc.ParamByName('rmoving').AsInteger := PParameter.rmoving;
StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date;
StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date;
if CheckBox2.Checked
then StoredProc.ParamByName('AVG_SUM').Value :=NULL
else StoredProc.ParamByName('AVG_SUM').Value := AvgCalc.EditValue;
if CheckBox1.Checked
then StoredProc.ParamByName('ID_SMETA').Value := 0
else StoredProc.ParamByName('ID_SMETA').Value := PId_Smeta;
StoredProc.ParamByName('Id_VIDOPL').AsInteger := PId_VidOpl;
StoredProc.ExecProc;
ID:=StoredProc.ParamByName('ID_com').AsInteger;
StoredProc.Transaction.Commit;
PParameter.ID := ID;
ModalResult:=mrYes;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
zcfsUpdate:
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_COMANDIROVKI_UPD';
StoredProc.Prepare;
StoredProc.ParamByName('ID_com').AsInteger := PParameter.ID;
StoredProc.ParamByName('rmoving').AsInteger:= PParameter.rmoving;
StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date;
StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date;
if CheckBox2.Checked
then StoredProc.ParamByName('AVG_SUM').Value:=NULL
else StoredProc.ParamByName('AVG_SUM').Value := AvgCalc.EditValue;
if CheckBox1.Checked
then StoredProc.ParamByName('ID_SMETA').Value := 0
else StoredProc.ParamByName('ID_SMETA').Value := PId_Smeta;
StoredProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
end;
end;
end;
procedure TFSp_People_WorkMode_Control.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
procedure TFSp_People_WorkMode_Control.EditSmetaPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,Dm.DB.Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
EditSmeta.Text := Smeta[3];
LabelSmetaName.Caption := Smeta[2];
PId_Smeta := Smeta[0];
end;
end;
procedure TFSp_People_WorkMode_Control.EditSmetaExit(Sender: TObject);
var Smeta:variant;
begin
if EditSmeta.Text<>'' then
begin
Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),DM.db.Handle);
if not VarIsNull(Smeta) then
begin
PId_Smeta:=Smeta[0];
LabelSmetaName.Caption:=VarToStr(Smeta[2]);
end
else
EditSmeta.SetFocus;
end
end;
procedure TFSp_People_WorkMode_Control.CheckBox1Click(Sender: TObject);
begin
EditSmeta.Enabled:=not CheckBox1.Checked;
LabelSmetaName.Enabled:=not CheckBox1.Checked;
end;
procedure TFSp_People_WorkMode_Control.CheckBox2Click(Sender: TObject);
begin
AvgCalc.Enabled:=not CheckBox2.Checked;
end;
procedure TFSp_People_WorkMode_Control.EditVidOplExit(Sender: TObject);
var VidOpl:Variant;
begin
if EditVidOpl.Text<>'' then
begin
VidOpl:=VoByKod(StrToInt(EditVidOpl.Text),date,DM.DB.Handle,ValueFieldZSetup(DM.DB.Handle,'Z_ID_SYSTEM'),0);
if VarArrayDimCount(VidOpl)>0 then
begin
PId_VidOpl:=VidOpl[0];
LabelVidOplData.Caption := VidOpl[2];
EditVidOpl.EditValue:=VarToStrDef(VidOpl[1],'');
end
else
EditVidOpl.SetFocus;
end;
end;
procedure TFSp_People_WorkMode_Control.EditVidOplPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var VidOpl:Variant;
begin
VidOPl:=LoadVidOpl(self,
DM.DB.Handle,zfsModal,
0,
ValueFieldZSetup(DM.DB.Handle,'Z_ID_SYSTEM'));
if VarArrayDimCount(VidOpl)>0 then
begin
PId_VidOpl:=VidOpl[0];
EditVidOpl.Text := VarToStrDef(VidOpl[2],'');
LabelVidOplData.Caption := VidOpl[1];
end
else
EditVidOpl.SetFocus;
end;
end.
|
{ Taken from PC World Best of *.* Volume 1 (1988) }
{ NO LICENSE PROVIDED, PROBABLY PUBLIC DOMAIN (published on coverdisk) }
{ Documentation: }
{ Load POPUP.PAS into Turbo Pascal's editor. If you have a Monochrome }
{ or Hercules display, change the DISPLAY constant to $0B000. Compile }
{ and run. If you don't have Turbo Pascal, type POPUP and press }
{ <Enter> at the DOS prompt. You'll see a display full of text. Press }
{ <Enter> to clear the screen. Then press <Enter> again to restore a }
{ portion of the display. }
{ Procedure MoveFromScreen in POPUP.PAS moves the screen contents into }
{ an array variable. Procedure MoveToScreen moves the array's contents }
{ back to the screen. Together, the two routines save and restore any }
{ rectangular display window. }
{ REFERENCES }
{ "Pascal Pop-Ups" by Michael Fang, February 1988 }
{ "Pop-Up Bug" by George L. Shevenock II, August 1988 }
{ "Pop Goes the Window" by Stephen R. Brazzell, June 1988 }
PROGRAM PopUp;
USES crt, turbo3; { Turbo 4.0-5.0. Remove for earlier versions. }
CONST DISPLAY = $0B800; { $0B000 for Monochrome & Hercules displays }
VAR buffer : ARRAY[ 1 .. 4000 ] OF BYTE;
ulc, ulr, i, j : INTEGER;
PROCEDURE MoveFromScreen( x1, y1, x2, y2 : BYTE; VAR Buff );
VAR upper, right, down, first, second, start : INTEGER;
buffer : ARRAY[ 1 .. 4000 ] OF BYTE ABSOLUTE Buff;
BEGIN
start := 1;
upper := (((2*x1)-2)+((y1-1)*160))-1;
right := ((x2-x1)+1)*2;
down := (y2-y1)+1;
FOR first := 1 TO down DO BEGIN
FOR second := 1 TO right DO BEGIN
buffer[ start ] := mem[ DISPLAY:upper + second ];
start := succ( start )
END;
upper := upper + 160; { advance to next line }
END;
END;
PROCEDURE MoveToScreen( x1, y1, x2, y2 : BYTE; VAR Buff );
VAR upper, right, down, first, second, start : INTEGER;
buffer : ARRAY[ 1 .. 4000 ] OF BYTE ABSOLUTE Buff;
BEGIN
start := 1;
upper := (((2*x1)-2)+((y1-1)*160))-1;
right := ((x2-x1)+1)*2;
down := (y2-y1)+1;
FOR first := 1 TO down DO BEGIN
FOR second := 1 TO right DO BEGIN
mem[ DISPLAY:upper+second ] := buffer[ start ];
start := succ(start);
END;
upper := upper + 160; { advance to next line }
END;
END;
BEGIN
ulc := 20; ulr := 6;
TextMode(3); ClrScr;
FOR i := 1 TO 19 DO { create some text on screen }
FOR j := 33 TO 123 DO
Write( chr(j) );
Write( ' *.*. PC Word, February 1988' );
Writeln; Writeln;
Write( ' Press <Enter> to display pop-up window.' );
MoveFromScreen( 20, 6, 60, 18, buffer ); { Save screen }
Readln;
Gotoxy( ulc, ulr); Write( 'ЙНННННННННННННННННННННННННННННННН»' );
Gotoxy( ulc, ulr+1 ); Write( 'є є' );
Gotoxy( ulc, ulr+2 ); Write( 'є This pop-up window could є' );
Gotoxy( ulc, ulr+3 ); Write( 'є display a menu listing є' );
Gotoxy( ulc, ulr+4 ); Write( 'є or help information. є' );
Gotoxy( ulc, ulr+5 ); Write( 'є є' );
Gotoxy( ulc, ulr+6 ); Write( 'є є' );
Gotoxy( ulc, ulr+7 ); Write( 'є є' );
Gotoxy( ulc, ulr+8 ); Write( 'є Press <Enter> to є' );
Gotoxy( ulc, ulr+9 ); Write( 'є restore screen. є' );
Gotoxy( ulc, ulr+10); Write( 'є є' );
Gotoxy( ulc, ulr+11); Write( 'ИННННННННННННННННННННННННННННННННј' );
Gotoxy( 1, 23 );
Readln;
MoveToScreen( 20, 6, 60, 18, buffer ); { Restore screen }
END.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
OpenDialog1: TOpenDialog;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure RenderToEmf(aFilename: string);
end;
var
Form1: TForm1;
implementation
uses
BVE.SVG2Types,
BVE.SVG2Intf,
BVE.SVG2SaxParser,
BVE.SVG2Elements,
BVE.SVG2Elements.Vcl,
BVE.SVG2ContextGP;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
RenderToEmf(OpenDialog1.FileName);
end;
procedure TForm1.RenderToEmf(aFilename: string);
var
Filename: string;
SVGParser: TSVGSaxParser;
SVGRoot: ISVGRoot;
R: TSVGRect;
W, H: integer;
procedure Render;
var
RC: ISVGRenderContext;
begin
// Define a size
W := 250;
H := 250;
// or calc the inttrinsic size of the SVG (optional)
RC := TSVGContextGP.Create(W, H);
R := SVGRoot.CalcIntrinsicSize(RC, SVGRect(0, 0, W, H));
RC := TSVGContextGP.Create(Filename, Round(R.Width), Round(R.Height));
RC.BeginScene;
try
SVGRenderToRenderContext(
SVGRoot,
RC,
Round(R.Width), Round(R.Height));
finally
RC.EndScene;
end;
end;
begin
// Instructions:
//
// Compile application with {$Define SVGGDIP} enabled in ..\Vcl\ContextSettingsVCL.inc
//
// Render to EMF is GDI+ functionality.
// - The radial gradient is not very good in GDI+.
// - Filters, clippaths etc will be rendered to a embedded bitmap
// Create a root to store the SVG rendering tree
SVGRoot := TSVGRootVCL.Create;
// Create a SAX parser instance
SVGParser := TSVGSaxParser.Create(nil);
try
Filename := ChangeFileExt(aFilename, '.emf');
// Parse SVG document and build the rendering tree
SVGParser.Parse(aFileName, SVGRoot);
Render;
finally
SVGParser.Free;
end;
end;
end.
|
unit ExceptionMon;
{ TExceptionMonitor - компонент для перехвата ошибок, необработанных приложением.
В режиме по умолчанию выводит сообщение об ошибке при помощи динамически создаваемой формы.
Для успешного использования требуется:
1. библиотека JCL (Jedi)
2. в файле проекта должны быть включены опции
// JCL_DEBUG_EXPERT_GENERATEJDBG ON
// JCL_DEBUG_EXPERT_INSERTJDBG ON
3. в настройках проекта должна быть включена опция генерации map-файла
4. в настройках проекта должна быть включена debug-информация
Протестировано на Delphi 7 и Delphi XE6.
Поддерживается несколько методов отображения сообщения об ошибке:
- smSystem - сообщение, генерируемое операционной системой;
- smDefault - диалоговое окно генерируется процедурой ShowException(E: Exception);
- smExternal - "внешняя обработка - вызывается обработчик события OnShowException;
- smNone - диалоговые окна отключены.
Для поддержки работы в приложениях-сервисах имеется свойство ApplicationType:
- atForms (по умолчанию);
- atServices.
Информация о перехваченной ошибке содержится в runtime-свойствах:
- StackList: TStrings;
- ErrorClassType: TClass;
- ErrorCode: string;
- ErrorMessage: string;
- ErrorMessageEx: string;
- ErrorTime: TDateTime.
Содержание отображаемой информации можно регулировать при помощи свойства
ShowElements: TExceptionElements, которое позволяет ограничивать количество
выдаваемой информации в диалоговом окне.
По умолчанию включены все доступные элементы.
P.S. Справедливо для функции ExceptionToString(AllInfo = false).
Также доступно свойство ExternalData: TStrings, содержимое которого включается
"как есть" в текст сообщения об ошибке.
Компонент подключется к TApplicationEvents.OnException - при этом если
свойство ApplicationEvents: TApplicationEvents не задано явно, то используется
внутренний экземпляр TApplicationEvents.
Компонент обрабатывает два события:
- OnRegisteredError: TNotifyEvent - сообщает о факте появления ошибки;
- OnShowException: TOnShowException - используется для вывода сообщения
об ошибке в режиме ShowMethod = smExternal.
Методы компонента:
- procedure RegistrationException(E: Exception);
позволяет "принудительно" регистрировать ошибку. Например, в блоках
try except on E: Exception do;
- procedure SaveToFile(const AFileName: string; const Rewrite: boolean = false);
позволяет сохранять сообщение об ошибке в файл AFileName. По умолчанию
выполняется дописывание сообщения в конец файла.
- function ExceptionToString(const AllInfo: boolean = True; const ShowFirstLineCallStack: integer = 3): string;
позволяет сформатировать сообщение об ошибке в виде строки.
Параметр AllInfo указывает необходимость учитывания настроек
в свойстве ShowElements и параметра ShowFirstLineCallStack}
interface
uses
{$IFDEF VER150}
Windows, SysUtils, Classes, AppEvnts, Forms, StdCtrls, ComCtrls, SvcMgr,
{$ELSE}
WinAPI.Windows, System.SysUtils, System.Classes, Vcl.AppEvnts, Vcl.Forms,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.SvcMgr,
{$ENDIF}
JclDebug;
type
TShowMethod = (smSystem, smDefault, smExternal, smNone);
TOnShowException = procedure(Sender: TObject; E: Exception) of object;
TExceptionElement = (eeEventTime, eeApplicationName, eeExternalData,
eeClassName, eeMessage, eeErrorCode, eeMessageEx,
eeCallStack);
TExceptionElements = set of TExceptionElement;
TApplicationType = (atForms, atServices);
TExceptionMonitor = class(TComponent)
private
fInnerAppEvents: TApplicationEvents;
fApplicationEvents: TApplicationEvents;
fStackList: TStrings;
fOnRegisteredError: TNotifyEvent;
fErrorMessageEx: string;
fErrorMessage: string;
fErrorClassType: TClass;
fShowMethod: TShowMethod;
fOnShowException: TOnShowException;
fErrorTime: TDateTime;
fExternalData: TStrings;
fErrorCode: string;
fShowElements: TExceptionElements;
fApplicationType: TApplicationType;
procedure DoException(Sender: TObject; E: Exception);
procedure SetApplicationEvents(const Value: TApplicationEvents);
protected
MessageBox: TRichEdit;
MessageBoxHeight: integer;
MessageBoxWidth: integer;
FormHeight : integer;
FormWidth : integer;
ButtonTop: integer;
procedure SetFormBounds;
procedure TabSetChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
procedure ShowException(E: Exception);
procedure SaveClick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RegistrationException(E: Exception);
procedure SaveToFile(const AFileName: string; const Rewrite: boolean = false);
function ExceptionToString(const AllInfo: boolean = True; const ShowFirstLineCallStack: integer = 3): string;
property StackList: TStrings read fStackList;
property ErrorClassType: TClass read fErrorClassType;
property ErrorCode: string read fErrorCode;
property ErrorMessage: string read fErrorMessage;
property ErrorMessageEx: string read fErrorMessageEx;
property ErrorTime: TDateTime read fErrorTime;
published
property ApplicationEvents: TApplicationEvents read fApplicationEvents write SetApplicationEvents;
property ApplicationType: TApplicationType read fApplicationType write fApplicationType;
property ShowElements: TExceptionElements read fShowElements write fShowElements;
property ExternalData: TStrings read fExternalData;
property ShowMethod: TShowMethod read fShowMethod write fShowMethod;
property OnRegisteredError: TNotifyEvent read fOnRegisteredError write fOnRegisteredError;
property OnShowException: TOnShowException read fOnShowException write fOnShowException;
end;
var
ExceptionMonitor: TExceptionMonitor;
implementation
uses
{$IFDEF VER150}
Controls, Dialogs, ExtCtrls, Tabs, Graphics
{$ELSE}
Vcl.Controls, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Tabs, Vcl.Graphics, System.IOUtils
{$ENDIF};
{ local methods}
procedure CleanUpStackInfoJCL(Info: Pointer);
begin
FreeMem(Info);
end;
function GetExceptionStackInfoJCL(P: PExceptionRecord): Pointer;
const
cDelphiException = $0EEDFADE;
var
Stack: TJclStackInfoList;
Str: TStringList;
Trace: String;
Sz: Integer;
begin
{$IFDEF VER150}
Stack := JclCreateStackList(False, 3, P^.ExceptionAddress);
{$ELSE}
if P^.ExceptionCode = cDelphiException then
Stack := JclCreateStackList(False, 3, P^.ExceptAddr)
else
Stack := JclCreateStackList(False, 3, P^.ExceptionAddress);
{$ENDIF}
try
Str := TStringList.Create;
try
Str.Add('Exception Code: $'+IntToHex(P^.ExceptionCode,8));
Stack.AddToStrings(Str, True, True, True, True);
Trace := Str.Text;
finally
FreeAndNil(Str);
end;
finally
FreeAndNil(Stack);
end;
if Trace <> '' then
begin
Sz := (Length(Trace) + 1) * SizeOf(Char);
GetMem(Result, Sz);
Move(Pointer(Trace)^, Result^, Sz);
end
else
Result := nil;
end;
function GetStackInfoStringJCL(Info: Pointer): string;
begin
Result := PChar(Info);
end;
{ TExceptionMonitor }
constructor TExceptionMonitor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fInnerAppEvents := TApplicationEvents.Create(Self);
fInnerAppEvents.Name := 'InnerAppEvents';
fInnerAppEvents.OnException := DoException;
fApplicationEvents := fInnerAppEvents;
fStackList := TStringList.Create;
fExternalData := TStringList.Create;
fShowMethod := smDefault;
MessageBox := nil;
{$IFDEF VER150}
{$ELSE}
Exception.GetExceptionStackInfoProc := GetExceptionStackInfoJCL;
Exception.GetStackInfoStringProc := GetStackInfoStringJCL;
Exception.CleanUpStackInfoProc := CleanUpStackInfoJCL;
{$ENDIF}
FormHeight := 200;
FormWidth := 400;
fShowElements := [eeEventTime, eeApplicationName, eeExternalData,
eeClassName, eeMessage, eeErrorCode, eeMessageEx, eeCallStack];
fApplicationType := atForms;
end;
destructor TExceptionMonitor.Destroy;
begin
{$IFDEF VER150}
{$ELSE}
Exception.GetExceptionStackInfoProc := nil;
Exception.GetStackInfoStringProc := nil;
Exception.CleanUpStackInfoProc := nil;
{$ENDIF}
fExternalData.Free;
fStackList.Free;
fInnerAppEvents.Free;
inherited;
end;
procedure TExceptionMonitor.DoException(Sender: TObject; E: Exception);
var
{$IFDEF VER150}
Stack: TJclStackInfoList;
{$ELSE}
Inner: Exception;
{$ENDIF}
begin
fStackList.Clear;
fErrorTime := Now;
// Log unhandled exception stack info to ExceptionLogMemo
fStackList.Add(E.Message);
{$IFDEF VER150}
Stack := JclGetExceptStackList(MainThreadID);
try
fStackList.Add('Exception Code: $-');
Stack.AddToStrings(fStackList, True, True, True, True);
finally
FreeAndNil(Stack);
end;
{$ELSE}
fStackList.Add(E.StackTrace);
Inner := E.InnerException;
while Inner <> nil do
begin
fStackList.Add(#13#10+Inner.Message);
fStackList.Add(Inner.StackTrace);
Inner := Inner.InnerException;
end;
{$ENDIF}
//JclLastExceptStackListToStrings(fStackList, False, True, False, False);
fErrorMessage := E.Message;
{$IFDEF VER150}
fErrorMessageEx := E.Message;
{$ELSE}
fErrorMessageEx := E.ToString;
{$ENDIF}
fErrorClassType := E.ClassType;
fErrorCode := Copy(fStackList[1],pos('$',fStackList[1]),9);
// Display default VCL unhandled exception dialog
case fShowMethod of
smSystem:
case fApplicationType of
atForms: {$IFDEF VER150}{$ELSE}Vcl.{$ENDIF}Forms.Application.ShowException(E);
atServices: ;
end;
smDefault:
ShowException(E);
smExternal:
if Assigned(fOnShowException) then
fOnShowException(Self,E);
smNone: ;
end;
if Assigned(fOnRegisteredError) then
fOnRegisteredError(Self);
end;
function TExceptionMonitor.ExceptionToString(const AllInfo: boolean;
const ShowFirstLineCallStack: integer): string;
var
SL, ST: TStringList;
i: integer;
S: string;
begin
Result := '';
SL := TStringList.Create;
try
if AllInfo or (eeEventTime in fShowElements) then
SL.Add('Event time: ' + DateTimeToStr(fErrorTime));
case fApplicationType of
atForms: S := {$IFDEF VER150}{$ELSE}Vcl.{$ENDIF}Forms.Application.Title;
atServices: S := {$IFDEF VER150}{$ELSE}Vcl.{$ENDIF}SvcMgr.Application.Title;
end;
if AllInfo or (eeApplicationName in fShowElements) then
SL.Add('Application: ' + S);
if AllInfo or (eeExternalData in fShowElements) then
SL.Add(fExternalData.Text);
if AllInfo or (eeClassName in fShowElements) then
SL.Add('Error ClassName: ' + fErrorClassType.ClassName);
if AllInfo or (eeMessage in fShowElements) then
SL.Add('Error Message: ' + fErrorMessage);
if AllInfo or (eeErrorCode in fShowElements) then
SL.Add('Error Code: ' + fErrorCode);
if AllInfo or (eeMessageEx in fShowElements) then
begin
SL.Add('');
SL.Add('All Messages: ');
SL.Add(fErrorMessageEx);
end;
if AllInfo or (eeCallStack in fShowElements) then
begin
SL.Add('');
SL.Add('Call Stack:');
if AllInfo then
SL.AddStrings(fStackList)
else begin
ST:=TStringList.Create;
ST.Text := fStackList.Text;
for i := 0 to ShowFirstLineCallStack-1 do
SL.Add(ST[i]);
ST.Free;
end;
end;
Result := SL.Text;
finally
SL.Free;
end;
end;
procedure TExceptionMonitor.RegistrationException(E: Exception);
begin
DoException(Self,E);
end;
procedure TExceptionMonitor.SaveClick(Sender: TObject);
var
sFileName: string;
begin
sFileName := 'report.txt';
with TSaveDialog.Create(Self) do
begin
FileName := sFileName;
DefaultExt := '.txt';
Filter := 'Text files|*.txt';
if Execute then
begin
sFileName := FileName;
SaveToFile(sFileName,True);
end;
Free;
end;
end;
procedure TExceptionMonitor.SaveToFile(const AFileName: string; const Rewrite: boolean);
var
{$IFDEF VER150}
Stream: TStream;
S: string;
{$ELSE}
SW: TStreamWriter;
{$ENDIF}
begin
{$IFDEF VER150}
if not Rewrite and FileExists(AFileName) then
Stream := TFileStream.Create(AFileName,fmOpenReadWrite)
else
Stream := TFileStream.Create(AFileName,fmCreate);
Stream.Seek(0,soFromEnd);
try
S := ExceptionToString+#13#10;
Stream.WriteBuffer(Pointer(S)^, Length(S));
finally
Stream.Free;
end;
{$ELSE}
if Rewrite then
SW := TFile.CreateText(AFileName)
else
SW := TFile.AppendText(AFileName);
try
SW.AutoFlush := true;
SW.Write(ExceptionToString+#13#10);
finally
SW.Close;
SW.Free;
end;
{$ENDIF}
end;
procedure TExceptionMonitor.SetApplicationEvents(const Value: TApplicationEvents);
begin
if Value <> nil then
begin
fApplicationEvents := Value;
fApplicationEvents.OnException := DoException;
fInnerAppEvents.OnException := nil;
end else begin
if fApplicationEvents <> nil then
fApplicationEvents.OnException := nil;
fApplicationEvents := fInnerAppEvents;
fInnerAppEvents.OnException := DoException;
end;
end;
procedure TExceptionMonitor.SetFormBounds;
var
i, n, cur, max: integer;
begin
//autosize dialog
max := 0;
n := -1;
for i := 0 to MessageBox.Lines.Count-1 do
begin
cur := Length(MessageBox.Lines[i]);
if cur > max then
begin
max := cur;
n := i;
end;
end;
if n >= 0 then
{$IFDEF VER150}
max := round(1.5*(MessageBox.Owner as TForm).Canvas.TextWidth(MessageBox.Lines[n]));
{$ELSE}
max := (MessageBox.Owner as TForm).Canvas.TextWidth(MessageBox.Lines[n]);
{$ENDIF}
if MessageBoxWidth < max + 32 then
cur := max + 32
else
cur := MessageBoxWidth;
if Screen.WorkAreaWidth < cur then
cur := Screen.WorkAreaWidth;
(MessageBox.Owner as TForm).Width := FormWidth + cur - MessageBoxWidth;
max := (MessageBox.Lines.Count + 2) * (MessageBox.Owner as TForm).Canvas.TextHeight(MessageBox.Lines[n]);
if MessageBoxHeight < max then
cur := max
else
cur := MessageBoxWidth;
if Screen.WorkAreaHeight < cur then
cur := Screen.WorkAreaHeight - 2*(FormHeight - ButtonTop);
(MessageBox.Owner as TForm).Height := FormHeight + cur - MessageBoxHeight;
end;
procedure TExceptionMonitor.ShowException(E: Exception);
const
cHorizMargin = 12;
var
Form: TForm;
Control: TControl;
Panel: TPanel;
TabSet: TTabSet;
begin
if fApplicationType = atServices then
Exit;
Form := TForm.Create(Application);
with Form do
begin
BorderStyle := bsSizeable;
BorderIcons := [biSystemMenu];
Position := poScreenCenter;
Width := FormWidth;
Height := FormHeight;
Caption := 'Error message - ' + {$IFDEF VER150}{$ELSE}Vcl.{$ENDIF}Forms.Application.Title;
//button
Control := TButton.Create(Form);
Control.Left := (ClientWidth - Control.Width) div 2;
ButtonTop := ClientHeight - Control.Height - 8;
Control.Top := ButtonTop;
(Control as TButton).ModalResult := mrOk;
(Control as TButton).Caption := 'OK';
(Control as TButton).Default := True;
Control.Parent := Form;
Control.Anchors := [akBottom];
//save button
Control := TButton.Create(Form);
Control.Left := cHorizMargin;
Control.Top := ButtonTop;
(Control as TButton).ModalResult := mrNone;
(Control as TButton).Caption := 'Save as ...';
(Control as TButton).OnClick := SaveClick;
Control.Parent := Form;
Control.Anchors := [akLeft, akBottom];
//panel
Panel := TPanel.Create(Form);
Panel.Parent := Form;
Panel.Left := 0;
Panel.Top := 0;
{$IFDEF VER150}
Panel.Height := ButtonTop - 30;
{$ELSE}
Panel.Height := ButtonTop - 12;
{$ENDIF}
Panel.Width := Width;
Panel.Anchors := [akLeft,akTop,akRight,akBottom];
//image
Control := TImage.Create(Form);
with Control as TImage do
begin
Name := 'Image';
Parent := Panel;
Picture.Icon.Handle := LoadIcon(0, IDI_HAND);
Stretch := true;
SetBounds(cHorizMargin, (Panel.Height - 32) div 2, 32, 32);
end;
//tabs
TabSet := TTabSet.Create(Form);
TabSet.Parent := Panel;
TabSet.SetBounds(32+2*cHorizMargin, Panel.Height - TabSet.Height - 16,
Panel.ClientWidth - 32 - 2*cHorizMargin - 24, TabSet.Height);
TabSet.Tabs.Add('Message');
TabSet.Tabs.Add('Call Stack');
TabSet.Anchors := [akLeft,akBottom,akRight];
//message
MessageBox := TRichEdit.Create(Form);
MessageBox.Parent := Panel;
MessageBox.Left := 32+2*cHorizMargin;;
MessageBox.Top := 12; // TabSet.Top+TabSet.Height;
MessageBox.Height := TabSet.Top - 12;
MessageBox.Width := Panel.ClientWidth - 32 - 2*cHorizMargin - 24;
MessageBox.ScrollBars := ssBoth;
MessageBox.WordWrap := true;
MessageBox.Color := clBtnFace;
MessageBox.ReadOnly := true;
MessageBox.Anchors := [akLeft,akTop,akRight,akBottom];
MessageBoxWidth := MessageBox.Width;
MessageBoxHeight := MessageBox.Height;
TabSet.OnChange := TabSetChange;
TabSet.TabIndex := 0;
SetFormBounds;
//show dialog
ShowModal;
Free;
end;
end;
procedure TExceptionMonitor.TabSetChange(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean);
begin
case NewTab of
0: begin
MessageBox.Text := ExceptionToString(false);
end;
1: begin
MessageBox.Text := fStackList.Text;
end;
end;
end;
initialization
// Enable raw mode (default mode uses stack frames which aren't always generated by the compiler)
Include(JclStackTrackingOptions, stRawMode);
// Disable stack tracking in dynamically loaded modules (it makes stack tracking code a bit faster)
Include(JclStackTrackingOptions, stStaticModuleList);
Include(JclStackTrackingOptions, stExceptFrame);
// Initialize Exception tracking
JclStartExceptionTracking;
ExceptionMonitor := TExceptionMonitor.Create(nil);
finalization
ExceptionMonitor.Free;
// Uninitialize Exception tracking
JclStopExceptionTracking;
end.
|
unit UTypes;
interface
const
FIELD_SIZE = 50;
type
TGameResult = (grEND, grPROCESS, grPAUSE);
TFieldCellContent = (fccLAND, fccGRASS, fccSNAKE, fccFOOD, fccPOISON, fccBOT);
TField = array [0..FIELD_SIZE - 1, 0..FIELD_SIZE - 1] of TFieldCellContent;
TCell = record
x, y: Integer;
end;
TDirection = (dirUP, dirRIGHT, dirDOWN, dirLEFT);
TSnakeData = record
cell: TCell;
landType: TFieldCellContent;
end;
TSnake = array [1..FIELD_SIZE * FIELD_SIZE] of TSnakeData;
TSaveRecord = packed record
saveName: String[255];
field: TField;
playerSnake, botSnake: TSnake;
playerScore, botScore: Integer;
botAlive: Boolean;
playerLength, botLength: Integer;
playerDirection, botDirection: TDirection;
end;
function toSnakeData(cell: TCell; landType: TFieldCellContent):TSnakeData;
function toSaveRecord(saveName: String; field: TField;
playerSnake, botSnake: TSnake;
playerScore, botScore: Integer;
botAlive: Boolean;
playerLength, botLength: Integer;
playerDirection, botDirection: TDirection):TSaveRecord;
implementation
function toSnakeData(cell: TCell; landType: TFieldCellContent):TSnakeData;
begin
result.cell := cell;
result.landType := landType;
end;
function toSaveRecord(saveName: String; field: TField;
playerSnake, botSnake: TSnake;
playerScore, botScore: Integer;
botAlive: Boolean;
playerLength, botLength: Integer;
playerDirection, botDirection: TDirection):TSaveRecord;
begin
result.saveName := saveName;
result.field := field;
result.playerSnake := playerSnake;
result.botSnake := botSnake;
result.playerScore := playerScore;
result.botScore := botScore;
result.botAlive := botAlive;
result.playerLength := playerLength;
result.botLength := botLength;
result.playerDirection := playerDirection;
result.botDirection := botDirection;
end;
end.
|
unit ClienteDAO;
interface
uses
DBXCommon, SqlExpr, BaseDAO, Cliente;
type
TClienteDAO = class(TBaseDAO)
public
function List: TDBXReader;
function NextCodigo: string;
function Insert(Cliente: TCliente): Boolean;
function Update(Cliente: TCliente): Boolean;
function Delete(Cliente: TCliente): Boolean;
function FindByCodigo(Codigo: string): TCliente;
end;
implementation
uses uSCPrincipal, StringUtils;
{ TClienteDAO }
function TClienteDAO.List: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT * FROM CLIENTES';
Result := FComm.ExecuteQuery;
end;
function TClienteDAO.NextCodigo: string;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'SELECT MAX(CODIGO) AS MAX_CODIGO FROM CLIENTES';
query.Open;
//
if query.FieldByName('MAX_CODIGO').IsNull then
Result := StrZero(1, 6)
else
Result := StrZero(query.FieldByName('MAX_CODIGO').AsInteger + 1, 6);
finally
query.Free;
end;
end;
function TClienteDAO.Insert(Cliente: TCliente): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'INSERT INTO CLIENTES (CODIGO, NOME, TELEFONE) VALUES (:CODIGO, :NOME, :TELEFONE)';
//
query.ParamByName('CODIGO').AsString := Cliente.Codigo;
query.ParamByName('NOME').AsString := Cliente.Nome;
query.ParamByName('TELEFONE').AsString := Cliente.Telefone;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TClienteDAO.Update(Cliente: TCliente): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'UPDATE CLIENTES SET NOME = :NOME, TELEFONE = :TELEFONE '+
'WHERE CODIGO = :CODIGO';
//
query.ParamByName('NOME').AsString := Cliente.Nome;
query.ParamByName('CODIGO').AsString := Cliente.Codigo;
query.ParamByName('TELEFONE').AsString := Cliente.Telefone;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TClienteDAO.Delete(Cliente: TCliente): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'DELETE FROM CLIENTES WHERE CODIGO = :CODIGO';
//
query.ParamByName('CODIGO').AsString := Cliente.Codigo;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TClienteDAO.FindByCodigo(Codigo: string): TCliente;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'SELECT * FROM CLIENTES WHERE CODIGO = ''' + Codigo + '''';
query.Open;
//
Result := TCliente.Create(query.FieldByName('CODIGO').AsString,
query.FieldByName('NOME').AsString,
query.FieldByName('TELEFONE').AsString);
finally
query.Free;
end;
end;
end.
|
//create a program that reads 15 exam scores.
//The program should find the average,
//and print all the exam scores and the average of the 15 scores.
Program ClassAverage;
var
ExamScores :array [1..5] of real;
sum,avg:real;
index:integer;
begin
sum:=0;
FOR index:= 1 to 5 DO
begin
writeln ('Please enter an exam score');
readln (ExamScores[index]);
sum := sum + ExamScores[index] ;
end;
avg := sum / 5;
FOR index:= 1 to 5 DO
begin
writeln (ExamScores[index]:3:2);
end;
writeln ('The average is ' , avg:3:2);
readln();
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FRMaterialPreview<p>
Material Preview frame.<p>
<b>Historique : </b><font size=-1><ul>
</ul></font>
}
// Âîçíèêëè ïðîáëåìû ñ GLSceneViewer è TFrame (ïðè ïåðåäà÷å áóôåðó õýíäëà),
// ïîýòîìó åãî ïðèøëîñü çàìåíèòü íà MemoryViewer
unit FRMaterialPreviewLCL;
interface
{$i GLScene.inc}
uses
lresources,
Classes, Forms, StdCtrls, Controls, ExtCtrls,
GLScene, GLObjects, GLTexture, GLHUDObjects, GLTeapot,
GLGeomObjects, GLColor, GLCoordinates,
GLCrossPlatform, GLMaterial,GLgraphics, LCLIntf;
type
{ TRMaterialPreview }
TRMaterialPreview = class(TFrame)
GLMemoryViewer1: TGLMemoryViewer;
GLScene1: TGLScene;
CBObject: TComboBox;
Camera: TGLCamera;
Cube: TGLCube;
imgFull: TImage;
Sphere: TGLSphere;
LightSource: TGLLightSource;
CBBackground: TComboBox;
BackGroundSprite: TGLHUDSprite;
Cone: TGLCone;
Teapot: TGLTeapot;
Timer1: TTimer;
World: TGLDummyCube;
Light: TGLDummyCube;
FireSphere: TGLSphere;
GLMaterialLibrary: TGLMaterialLibrary;
procedure CBObjectChange(Sender: TObject);
procedure CBBackgroundChange(Sender: TObject);
procedure imgFullMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgFullMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure imgFullMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure imgFullResize(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
function GetMaterial: TGLMaterial;
procedure SetMaterial(const Value: TGLMaterial);
{ Déclarations privées }
public
Procedure Render;
{ Déclarations publiques }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
property Material : TGLMaterial read GetMaterial write SetMaterial;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
Graphics;
var
MX, MY: Integer;
constructor TRMaterialPreview.Create(AOwner : TComponent);
begin
inherited;
BackGroundSprite.Position.X := imgFull.Width div 2;
BackGroundSprite.Position.Y := imgFull.Height div 2;
BackGroundSprite.Width := imgFull.Width;
BackGroundSprite.Height := imgFull.Height;
CBObject.ItemIndex:=0; CBObjectChange(Self);
CBBackground.ItemIndex:=0; CBBackgroundChange(Self);
end;
destructor TRMaterialPreview.Destroy;
begin
inherited;
end;
procedure TRMaterialPreview.CBObjectChange(Sender: TObject);
var
i : Integer;
begin
i:=CBObject.ItemIndex;
Cube.Visible := I = 0;
Sphere.Visible := I = 1;
Cone.Visible := I = 2;
Teapot.Visible := I = 3;
end;
procedure TRMaterialPreview.CBBackgroundChange(Sender: TObject);
var
bgColor : TColor;
begin
case CBBackground.ItemIndex of
1 : bgColor:=clWhite;
2 : bgColor:=clBlack;
3 : bgColor:=clBlue;
4 : bgColor:=clRed;
5 : bgColor:=clGreen;
else
bgColor:=clNone;
end;
with BackGroundSprite.Material do begin
Texture.Disabled:=(bgColor<>clNone);
FrontProperties.Diffuse.Color:=ConvertWinColor(bgColor);
end;
end;
procedure TRMaterialPreview.imgFullMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
MX := X;
MY := Y;
end;
procedure TRMaterialPreview.imgFullMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if (ssRight in Shift) and (ssLeft in Shift) then
Camera.AdjustDistanceToTarget(1 - 0.01 * (MY - Y))
else
if (ssRight in Shift) or (ssLeft in Shift) then
Camera.MoveAroundTarget(Y - MY, X - MX);
MX := X;
MY := Y;
end;
procedure TRMaterialPreview.imgFullMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
var Handled: Boolean);
begin
Camera.AdjustDistanceToTarget(1 - 0.1 * (Abs(WheelDelta) / WheelDelta));
end;
procedure TRMaterialPreview.imgFullResize(Sender: TObject);
begin
GLMemoryViewer1.Height:= imgFull.Height;
GLMemoryViewer1.Width:= imgFull.Width;
end;
procedure TRMaterialPreview.Timer1Timer(Sender: TObject);
Var
BitMap : TBitmap;
Image : TGLBitmap32;
fWidth, fHeight:Integer;
begin
GLMemoryViewer1.Render;
Image := GLMemoryViewer1.Buffer.CreateSnapShot;
Bitmap := Image.Create32BitsBitmap;
try
imgFull.Canvas.Brush.Color := clBlack;
imgFull.Canvas.FillRect(imgFull.Canvas.ClipRect);
fWidth :=imgFull.Width;
fHeight:= imgFull.Height;
imgFull.Canvas.StretchDraw(Rect(0, 0, fWidth, fHeight), Bitmap);{}
finally
Bitmap.Free;
Image.Free;
end;
end;
function TRMaterialPreview.GetMaterial: TGLMaterial;
begin
Result := GLMaterialLibrary.Materials[0].Material;
end;
procedure TRMaterialPreview.SetMaterial(const Value: TGLMaterial);
begin
GLMaterialLibrary.Materials[0].Material.Assign(Value);
end;
Procedure TRMaterialPreview.Render;
begin
Timer1.OnTimer(self);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{$i FRMaterialPreviewLCL.lrs}
end.
|
unit CurrentLocationForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Sensors,
System.Sensors.Components, FMX.Maps, FMX.Controls.Presentation, FMX.StdCtrls,
FMX.Objects, FMX.ListView.Types, FMX.ListView, FMX.ListBox, FMX.Layouts,
System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions,
FMX.MultiView;
type
TMapsForm = class(TForm)
LocationSensor1: TLocationSensor;
Long: TLabel;
Lat: TLabel;
BitmapSource: TImage;
ListBox1: TListBox;
LocationSensorItem: TListBoxItem;
LongitudeItem: TListBoxItem;
LatitudeItem: TListBoxItem;
Switch1: TSwitch;
ScreenshotItem: TListBoxItem;
btnShareImage: TButton;
ToolBar1: TToolBar;
Label1: TLabel;
Image1: TImage;
ToolBar2: TToolBar;
Label2: TLabel;
ActionList1: TActionList;
ShowShareSheetAction1: TShowShareSheetAction;
btnScreenshot: TSpeedButton;
MapView1: TMapView;
procedure EnableLocationSensorClick(Sender: TObject);
procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation,
NewLocation: TLocationCoord2D);
procedure Switch1Switch(Sender: TObject);
procedure MapView1MarkerClick(Marker: TMapMarker);
procedure ShowShareSheetAction1BeforeExecute(Sender: TObject);
procedure btnScreenshotClick(Sender: TObject);
private
const Accuracy = 0.0005;
private
FCurrentPosition: TLocationCoord2D;
{ Private declarations }
procedure SnapShotReady(const Bitmap: TBitmap);
public
{ Public declarations }
end;
TLocationCoord2DHelper = record helper for TLocationCoord2D
function Distance(const NewCoord: TLocationCoord2D): Double;
end;
var
MapsForm: TMapsForm;
implementation
{$R *.fmx}
procedure TMapsForm.EnableLocationSensorClick(Sender: TObject);
begin
LocationSensor1.Active := True;
end;
procedure TMapsForm.LocationSensor1LocationChanged(Sender: TObject;
const OldLocation, NewLocation: TLocationCoord2D);
var
MyLocation: TMapCoordinate;
Desqr: TMapMarkerDescriptor;
begin
Lat.Text := Format('%2.6f', [NewLocation.Latitude]);
Long.Text := Format('%2.6f', [NewLocation.Longitude]);
MyLocation := TMapCoordinate.Create(StrToFloat(Lat.Text),StrToFloat(Long.Text));
MapView1.Location := MyLocation;
if FCurrentPosition.Distance(NewLocation) > Accuracy then
begin
FCurrentPosition := NewLocation;
Desqr := TMapMarkerDescriptor.Create(MyLocation, 'Dropped marker');
Desqr.Icon := BitmapSource.Bitmap;
Desqr.Draggable := True;
MapView1.AddMarker(Desqr);
MapView1.Zoom := 7;
end;
end;
procedure TMapsForm.MapView1MarkerClick(Marker: TMapMarker);
begin
Marker.DisposeOf;
end;
procedure TMapsForm.Switch1Switch(Sender: TObject);
begin
LocationSensor1.Active := Switch1.IsChecked;
end;
procedure TMapsForm.ShowShareSheetAction1BeforeExecute(Sender: TObject);
begin
ShowShareSheetAction1.Bitmap.Assign(Image1.Bitmap);
end;
procedure TMapsForm.SnapShotReady(const Bitmap: TBitmap);
begin
Image1.Bitmap.Assign(Bitmap);
end;
procedure TMapsForm.btnScreenshotClick(Sender: TObject);
begin
MapView1.Snapshot(SnapshotReady);
end;
{ TLocationCoord2DHelper }
function TLocationCoord2DHelper.Distance(const NewCoord: TLocationCoord2D): Double;
begin
Result := Sqrt(Sqr(Abs(Self.Latitude - NewCoord.Latitude)) + Sqr(Abs(Self.Longitude - NewCoord.Longitude)));
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.Utils.Config;
interface
type
TConfigUtils = class
public
class procedure EnsureDefaultConfigDir;
class function GetDefaultConfigFileName : string;
class function GetDefaultDMPFolder : string;
end;
implementation
uses
System.SysUtils,
DPM.Core.Utils.System,
DPM.Core.Constants;
{ TConfigUtils }
class procedure TConfigUtils.EnsureDefaultConfigDir;
var
sConfigFolder : string;
begin
sConfigFolder := ExtractFilePath(TSystemUtils.ExpandEnvironmentStrings(cDefaultConfigFile));
if not DirectoryExists(sConfigFolder) then
begin
//ensure our .dpm folder exists.
ForceDirectories(sConfigFolder);
end;
end;
class function TConfigUtils.GetDefaultConfigFileName : string;
begin
result := TSystemUtils.ExpandEnvironmentStrings(cDefaultConfigFile);
end;
class function TConfigUtils.GetDefaultDMPFolder : string;
begin
result := TSystemUtils.ExpandEnvironmentStrings(cDefaultDPMFolder);
end;
end.
|
unit u_variables;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, u_global;
type
TVarManager = class(TObject)
public
DefinedVars: TStringList;
constructor Create;
destructor Destroy; override;
procedure DefVar(Name: string);
function Get(Name: string): cardinal;
end;
implementation
{** Variables **}
constructor TVarManager.Create;
begin
DefinedVars := TStringList.Create;
inherited Create;
end;
destructor TVarManager.Destroy;
begin
FreeAndNil(DefinedVars);
inherited Destroy;
end;
procedure TVarManager.DefVar(Name: string);
begin
if not CheckName(Name) then
AsmError('Invalid variable name "' + Name + '".');
if DefinedVars.IndexOf(Name) = -1 then
DefinedVars.Add(Name);
{else
AsmError('Trying to redefine variable "'+name+'".');}
end;
function TVarManager.Get(Name: string): cardinal;
begin
DefVar(Name);
Result := DefinedVars.IndexOf(Name);
// if Result = -1 then
// AsmError('Invalid variable call "' + Name + '".');
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit VaryingRestitution;
interface
uses Test, Box2D.Common, Box2D.Collision, Box2D.Dynamics, DebugDraw;
type
TVaryingRestitution = class(TTest)
public
constructor Create;
class function CreateTest: TTest; static;
end;
implementation
{ TVaryingRestitution }
constructor TVaryingRestitution.Create;
const
restitution: array[0..6] of float32 = (0.0, 0.1, 0.3, 0.5, 0.75, 0.9, 1.0);
var
ground, body: b2BodyWrapper;
bd: b2BodyDef;
shape: b2EdgeShapeWrapper;
circleShape: b2CircleShapeWrapper;
fd: b2FixtureDef;
i: Integer;
begin
inherited;
bd := b2BodyDef.Create;
ground := m_world.CreateBody(@bd);
shape := b2EdgeShapeWrapper.Create;
shape.&Set(b2Vec2.Create(-40.0, 0.0), b2Vec2.Create(40.0, 0.0));
ground.CreateFixture(shape, 0.0);
circleShape := b2CircleShapeWrapper.Create;
circleShape.Set_m_radius(1.0);
fd := b2FixtureDef.Create;
fd.shape := circleShape;
fd.density := 1.0;
for i := Low(restitution) to High(restitution) do
begin
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position.&Set(-10.0 + 3.0 * i, 20.0);
body := m_world.CreateBody(@bd);
fd.restitution := restitution[i];
body.CreateFixture(@fd);
end;
shape.Destroy;
circleShape.Destroy;
end;
class function TVaryingRestitution.CreateTest: TTest;
begin
Result := TVaryingRestitution.Create;
end;
initialization
RegisterTest(TestEntry.Create('VaryingRestitution', @TVaryingRestitution.CreateTest));
end.
|
{ //************************************************************// }
{ // // }
{ // Código gerado pelo assistente // }
{ // // }
{ // Projeto MVCBr // }
{ // tireideletra.com.br / amarildo lacerda // }
{ //************************************************************// }
{ // Data: 05/05/2017 14:43:07 // }
{ //************************************************************// }
/// <summary>
/// Uma View representa a camada de apresentação ao usuário
/// deve esta associado a um controller onde ocorrerá
/// a troca de informações e comunicação com os Models
/// </summary>
unit SuiteCRMSampleView;
interface
uses
{$IFDEF FMX}FMX.Forms, {$ELSE}VCL.Forms, {$ENDIF}
System.SysUtils, System.Classes, MVCBr.Interf,
MVCBr.View, MVCBr.FormView, MVCBr.Controller, VCL.Controls, VCL.StdCtrls,
SuiteCRMSample.Controller.Interf,
SuiteCRM.Model,
VCL.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
REST.Response.Adapter, REST.FDSocial;
type
/// Interface para a VIEW
ISugarCRMSampleView = interface(IView)
['{6D69CBAB-65F6-433A-951B-EBD7CAD2C9CA}']
// incluir especializacoes aqui
end;
/// Object Factory que implementa a interface da VIEW
TSugarCRMSampleView = class(TFormFactory { TFORM } , IView,
IThisAs<TSugarCRMSampleView>, ISugarCRMSampleView,
IViewAs<ISugarCRMSampleView>)
LabeledEdit1: TLabeledEdit;
LabeledEdit2: TLabeledEdit;
LabeledEdit3: TLabeledEdit;
LabeledEdit4: TLabeledEdit;
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
Button4: TButton;
Button5: TButton;
Button6: TButton;
FDMemTable1: TFDMemTable;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
RESTSocialMemTableAdapter1: TRESTSocialMemTableAdapter;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
FInited: Boolean;
procedure InitCRMParmas;
procedure msg(a1, a2: string);
protected
FSuiteCRM: ISuiteCRMModel;
procedure Init;
function Controller(const aController: IController): IView; override;
public
{ Public declarations }
class function New(aController: IController): IView;
function This: TObject; override;
function ThisAs: TSugarCRMSampleView;
function ViewAs: ISugarCRMSampleView;
function ShowView(const AProc: TProc<IView>): integer; override;
function Update: IView; override;
end;
Implementation
{$R *.DFM}
uses System.JSON;
function TSugarCRMSampleView.Update: IView;
begin
result := self;
{ codigo para atualizar a View vai aqui... }
end;
function TSugarCRMSampleView.ViewAs: ISugarCRMSampleView;
begin
result := self;
end;
class function TSugarCRMSampleView.New(aController: IController): IView;
begin
result := TSugarCRMSampleView.create(nil);
result.Controller(aController);
end;
procedure TSugarCRMSampleView.Button1Click(Sender: TObject);
begin
InitCRMParmas;
try
FSuiteCRM.Login(LabeledEdit3.Text, LabeledEdit4.Text);
except
end;
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
end;
procedure TSugarCRMSampleView.Button2Click(Sender: TObject);
var
r: TSuiteCRMAccount;
begin
InitCRMParmas;
assert(FSuiteCRM.sessionID > '', 'Falta login');
r.id := '999'; //TGuid.NewGuid.ToString; // nao funcionou - da erro no insert.
// r.assigned_user_name := 'teste novo account';
r.name := 'teste novo account';
// r.nome := r.name;
FSuiteCRM.Accounts.CreateID(r);
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
Edit1.Text := FSuiteCRM.Accounts.CurrentID;
end;
procedure TSugarCRMSampleView.Button3Click(Sender: TObject);
begin
InitCRMParmas;
FSuiteCRM.Accounts.Get(Edit1.Text);
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
Edit1.Text := FSuiteCRM.Accounts.CurrentID;
end;
procedure TSugarCRMSampleView.Button4Click(Sender: TObject);
begin
InitCRMParmas;
FSuiteCRM.Accounts.GetCount('');
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
end;
procedure TSugarCRMSampleView.Button5Click(Sender: TObject);
var rst:string;
a:TJsonArray;
begin
InitCRMParmas;
FSuiteCRM.Accounts.Get_Entry_List('', '');
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
rst := FSuiteCRM.ToJson;
//TJSONObject.ParseJSONValue(rst).TryGetValue<TJsonArray>(a) ;
RESTSocialMemTableAdapter1.FromJson(rst); //FromJsonArray(a);
Memo1.lines.add(FSuiteCRM.ToJson);
end;
procedure TSugarCRMSampleView.Button6Click(Sender: TObject);
begin
InitCRMParmas;
FSuiteCRM.Users.get_user_id;
msg(FSuiteCRM.RequestText, FSuiteCRM.ResponseText);
end;
function TSugarCRMSampleView.Controller(const aController: IController): IView;
begin
result := inherited Controller(aController);
if not FInited then
begin
Init;
FInited := true;
end;
end;
procedure TSugarCRMSampleView.InitCRMParmas;
begin
// FSuiteCRM.Init( LabeledEdit1.text, LabeledEdit2.text, LabeledEdit3.text, LabeledEdit4.text );
FSuiteCRM.BaseURL := LabeledEdit1.Text;
FSuiteCRM.PathURL := LabeledEdit2.Text;
end;
procedure TSugarCRMSampleView.msg(a1, a2: string);
begin
Memo1.lines.clear;
Memo1.lines.add(a1);
Memo1.lines.add('-----------------');
Memo1.lines.add(a2);
end;
procedure TSugarCRMSampleView.Init;
begin
// incluir incializações aqui
FSuiteCRM := getModel<ISuiteCRMModel>;
end;
function TSugarCRMSampleView.This: TObject;
begin
result := inherited This;
end;
function TSugarCRMSampleView.ThisAs: TSugarCRMSampleView;
begin
result := self;
end;
function TSugarCRMSampleView.ShowView(const AProc: TProc<IView>): integer;
begin
inherited;
end;
end.
|
unit fmuCommon;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList,
JvComponentBase, JvFormPlacement, JvAppStorage, JvAppRegistryStorage, cxClasses,
cxPropertiesStore;
type
TfmCommon = class(TForm)
ActionList: TActionList;
FormStorage: TJvFormStorage;
AppRegistryStorage: TJvAppRegistryStorage;
cxPropertiesStore: TcxPropertiesStore;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActivate(Sender: TObject);
private
protected
procedure CreateViews(); virtual;
{определение и настройка доступа к компонентам формы}
procedure SetAccessValue(); virtual;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
{получение индекса изображения для кнопки на панели быстрого доступа}
function GetShortCutImageIndex(): Integer; virtual;
procedure Show;
end;
implementation
{$R *.dfm}
uses
dmuSysImages {$IFDEF CARDS}, fmuMain, uAccessManager{$ENDIF};
{ TfmCommon }
constructor TfmCommon.Create(Owner: TComponent);
begin
inherited;
CreateViews();
{определение и настройка доступа к компонентам формы}
SetAccessValue();
{$IFNDEF RESOURCE}
{устанавливаем иконку форме}
dmSysImages.ImagesList16.GetIcon(GetShortCutImageIndex(), Self.Icon);
{$IFDEF CARDS}
{создаем кнопку на панеле быстрого доступа главной формы}
fmMain.CreateShortCutBarButton(Self, GetShortCutImageIndex());
{добавляем наименование формы в список открытых форм главного меню}
fmMain.AddWindowsToMenu(Self);
{$ENDIF}
{$ENDIF}
end;
destructor TfmCommon.Destroy;
begin
inherited;
end;
procedure TfmCommon.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{$IFNDEF RESOURCE}
{$IFDEF CARDS}
{удаляем наименование формы из списока открытых форм главного меню}
fmMain.DeleteWindowsFromMenu(Self);
{удаляем кнопку из панели быстрого доступа главной формы}
fmMain.DeleteShortCutBarButton(Self);
{$ENDIF}
{$ENDIF}
Action:= CaFree;
end;
procedure TfmCommon.FormActivate(Sender: TObject);
begin
{$IFDEF CARDS}
{$IFNDEF RESOURCE}
fmMain.SetDownShortCutBarButton(Self);
{$ENDIF}
{$ENDIF}
end;
procedure TfmCommon.CreateViews;
begin
end;
procedure TfmCommon.SetAccessValue;
begin
{$IFDEF CARDS}
{проверка разрещений доступа роли к ресурсам приложения}
AccessManager.CheckFormPermission(Self, True);
{$ENDIF}
end;
function TfmCommon.GetShortCutImageIndex: Integer;
begin
Result := -1;
end;
procedure TfmCommon.Show;
begin
if Self.WindowState = wsMinimized then
Self.WindowState := wsNormal;
inherited;
end;
end.
|
unit fList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, iStart, rtti_broker_iBroker, rtti_idebinder_Lib, rtti_idebinder_iBindings;
type
{ TListForm }
TListForm = class(TForm, IStartContextConnectable)
btnAdd: TButton;
btnDelete: TButton;
btnEdit: TButton;
lbList: TListBox;
pnRunEdit: TPanel;
procedure btnAddClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
private
fContext: IStartContext;
fListField: string;
fEditForm: TFormClass;
fObjectClass: string;
fDirty: Boolean;
fBinder: IRBTallyBinder;
protected
procedure Actualize;
procedure Connect(const AContext: IStartContext);
public
constructor Create(TheOwner: TComponent; const AObjectClass, AListField: string;
AEditForm: TFormClass);
end;
implementation
{$R *.lfm}
{ TListForm }
procedure TListForm.btnAddClick(Sender: TObject);
var
mData: IRBData;
begin
mData := fContext.SerialFactory.CreateObject(fObjectClass) as IRBData;
if TIDE.Edit(fEditFOrm, mData, fContext.DataQuery) then
begin
fContext.DataStore.Save(mData);
fContext.DataStore.Flush;
fDirty := True;
Actualize;
end;
end;
procedure TListForm.btnEditClick(Sender: TObject);
var
mData, mNewData: IRBData;
begin
mData := fBinder.CurrentData;
if mData = nil then
Exit;
mNewData := fContext.SerialFactory.CreateObject(mData.ClassName) as IRBData;
mNewData.Assign(mData);
if TIDE.Edit(fEditFOrm, mNewData, fContext.DataQuery) then
begin
mData.Assign(mNewData);
fContext.DataStore.Save(mData);
fContext.DataStore.Flush;
fDirty := True;
Actualize;
end;
end;
procedure TListForm.Actualize;
begin
fBinder.Reload;
end;
procedure TListForm.Connect(const AContext: IStartContext);
var
mClass: TClass;
begin
fContext := AContext;
mClass := fContext.SerialFactory.FindClass(fObjectClass);
lbList.Items.Add(fListField);
fBinder := TLib.NewListBinder(lbList, fContext.BinderContext, mClass);
end;
constructor TListForm.Create(TheOwner: TComponent; const AObjectClass,
AListField: string; AEditForm: TFormClass);
begin
inherited Create(TheOwner);
fObjectClass := AObjectClass;
fListField := AListField;
fEditForm := AEditForm;
end;
end.
|
{
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
}
unit pas2js.Application;
{$mode objfpc}{$H+}
{$modeswitch externalclass}
interface
uses
Classes, SysUtils, types, JS, Web, pas2js.Element, pas2js.Form;
(* ╔═══════════════════════════════════════════════════════════════════════╗
║ JSwiper ║
╚═══════════════════════════════════════════════════════════════════════╝ *)
type
JSwiper = class external name 'Swiper'
constructor New(targetRef: String); overload;
function _slideNext: JSwiper;
function swipeNext: JSwiper;
function _slideTo(form: integer): JSwiper;
function swipeTo(form: integer): JSwiper; overload;
function swipeTo(form: integer; speed: Integer): JSwiper; overload;
function swipeTo(form: integer; speed: Integer; callbackFn: TProcedure): JSwiper; overload;
end;
type
{ TWApplication }
TWApplication = class
private
FOldForm: Integer;
FForm: TCustomControl;
protected
procedure ApplicationStarting; virtual;
public
FormNames: Array of String;
FormsClasses: Array of TFormClass; //TFormClass = class of TWForm;
FormsInstances: Array of TWForm;
Swiper: JSwiper;
constructor Create; virtual;
procedure CreateForm(FormName: String; aClassType: TFormClass);
//procedure GoToForm(FormName: String);
procedure GoToForm(aFormName: String; speed: integer = 350; aCallBackFn: TProcedure = nil);
procedure RunApp;
property CurrentForm: Integer read FOldForm write FOldForm;
end;
var
Application : TWApplication;
implementation
{ TWApplication }
procedure TWApplication.ApplicationStarting;
begin
// empty
end;
constructor TWApplication.Create; //(parent: TCustomControl);
var
docFragment: TJSDocumentFragment;
div_, div_0: TJSElement;
procedure doOnReadyExecute;
begin
console.log('onReadyExecute');
(* swiper enabled after forms created... *)
if not Assigned(Swiper) then
Swiper := JSwiper.New('.swiper-container');
end;
begin
docFragment := document.createDocumentFragment(); // contains all gathered nodes
div_ := document.createElement('DIV');
div_.setAttribute('class', 'swiper-container');
div_.setAttribute('style', 'width:100%; height:'+IntToStr(window.screen.height)+'px;');
//div_.setAttribute("style", 'width:100%; height:'+window.screen.height+'px;'+ ' position:relative;');
docFragment.appendChild(div_);
div_0 := document.createElement('DIV');
div_0.setAttribute('class', 'swiper-wrapper');
div_0.setAttribute('style', 'width:100%; height:100%;');
div_.appendChild(div_0);
document.body.appendChild( docFragment );
// inherited Create('div', parent);
// Self.Handle.classList.add('swiper-container');
// Self.Handle.setAttribute('style', 'width:100%; height:'+IntToStr(window.screen.height)+'px;');
//setProperty('width','100%');
//setProperty('height','100%');
//setProperty('background-color','white');
(* set class instance variable to Display *)
// if not Assigned(FForm) then
FForm := TCustomControl.Create;
TJSElement(FForm.Handle) := TJSHTMLElement( document.querySelector('.swiper-container')).firstElementChild;
window.setTimeout(@doOnReadyExecute, 250);
(* swiper enabled after forms created... *)
// if not Assigned(Swiper) then
// Swiper := JSwiper.New('.swiper-container');
// (* set class instance variable *)
// if not Assigned(Instance) then
// Instance := Self;
end;
procedure TWApplication.CreateForm(FormName: String; aClassType: TFormClass);
var
k: integer;
begin
TJSArray(FormNames).push(FormName);
TJSArray(FormsClasses).push(aClassType);
TJSArray(FormsInstances).push(nil);
for k := 0 to TJSArray(FormNames).Length -1 do begin
If FormsInstances[k] = nil then begin
FormsInstances[k] := FormsClasses[k].Create(FForm); // create the form instances
(FormsInstances[k]).FormIndex := k; // set Form Index
(FormsInstances[k]).Name := formName;
(FormsInstances[k]).FormActivated; // invoke initializeForm method --> invoke FormActivated method
(FormsInstances[k]).InitializeObject;
end;
end;
end;
(*
,Show:function(Self, FormName$1) {
var i = 0;
var $temp1;
for(i=0,$temp1=Self.FormNames.length;i<$temp1;i++) {
if (Self.FormsInstances[i]!==null) {
TCustomControl.SetProperty(Self.FormsInstances[i],"display","none");
}
if (Self.FormNames[i]==FormName$1) {
if (Self.FormsInstances[i]===null) {
Self.FormsInstances[i]=TWForm.Create$5($NewDyn(Self.FormsClasses[i],""),Self);
TWForm.ShowForm$(Self.FormsInstances[i]);
} else {
TWForm.ClearForm(Self.FormsInstances[i]);
TWForm.ShowForm$(Self.FormsInstances[i]);
TCustomControl.SetProperty(Self.FormsInstances[i],"display","inline-block");
}
}
}
}
*)
//procedure TWApplication.GoToForm(FormName: String);
procedure TWApplication.GoToForm(aFormName: String; speed: integer;
aCallBackFn: TProcedure);
var
i: integer;
(* ╔═════════════════════════════════════════════════════════════╗
║ pass the FormName parameter and return the FormIndex ║
╚═════════════════════════════════════════════════════════════╝ *)
function IndexOfFormName(aformName: String): Integer;
var
lcName: String;
i: Integer;
begin
lcName := Trim(LowerCase(aformName));
for i := 0 to TJSArray(FormNames).Length - 1 do
if LowerCase(FormsInstances[i].Name) = lcName then
exit(FormsInstances[i].FormIndex);
end;
(* ╔═════════════════════════════════════════════════════════════╗
║ pass the FormIndex parameter and return the form instance ║
╚═════════════════════════════════════════════════════════════╝ *)
function getForm(index: Integer): TWForm;
begin
Result := TWForm(FormsInstances[index]);
end;
var
n: String;
begin
// for i := 0 to TJSArray(FormNames).Length - 1 do
// console.log(IndexOfFormName('Form2'));
(* ╔══════════════════════════════════════════════════════════╗
║ Invoke FormDeactivate event before SwipeTo/slideTo page ║
╚══════════════════════════════════════════════════════════╝ *)
for i := 0 to TJSArray(FormNames).Length - 1 do begin
if Trim(LowerCase(FormsInstances[i].Name)) = Trim(LowerCase(getForm(FOldForm).Name)) then begin
FormsInstances[i].FormDeactivated; // ---> invoke FormDeactivated
end;
end;
If assigned(Swiper) then
Application.Swiper.swipeTo(IndexOfFormName(aFormName), speed, aCallBackFn);
(* ╔══════════════════════════════════════════════════════════╗
║ Invoke FormActivate event after SwipeTo/slideTo page ║
╚══════════════════════════════════════════════════════════╝ *)
n := Trim(LowerCase(aFormName));
for i := 0 to TJSArray(FormNames).Length - 1 do begin
if Trim(LowerCase(FormsInstances[i].Name)) = Trim(LowerCase(aFormName)) then begin
FormsInstances[i].FormActivated; // ---> invoke FormActivated
FOldForm := FormsInstances[i].FormIndex;
end;
end;
(*
For i := 0 to TJSArray(FormNames).length -1 do begin
If FormsInstances[i] <> nil then
FormsInstances[i].SetProperty('display','none');
If FormNames[i] = aFormName then begin
If FormsInstances[i] = nil then //form has never been displayed yet
FormsInstances[i] := FormsClasses[i].Create(FForm) else
FormsInstances[i].SetProperty('display','inline-block');
//TW3Form(FormsInstances[i]).InitializeForm; //ClearForm;
//*this.FormsClasses[i](this.FormsInstances[i])
TWForm(FormsInstances[i]).InitializeForm;
TWForm(FormsInstances[i]).InitializeObject;
//(FormsInstances[i] as FormsClasses[i]).InitializeForm; //ClearForm;
//(FormsInstances[i] as FormsClasses[i]).InitializeObject; //ShowForm;
end;
end;
*)
end;
procedure TWApplication.RunApp;
begin
console.log('TWApplication.RunApp');
ApplicationStarting;
end;
initialization
//Application := TWApplication.Create(nil);
//Application.RunApp;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Classe VO padrão de onde herdam todas as classes de VO
The MIT License
Copyright: Copyright (C) 2010 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</p>
@author Albert Eije (T2Ti.COM)
@version 2.0
******************************************************************************* }
unit VO;
{$mode objfpc}{$H+}
interface
uses
TypInfo, SysUtils, Classes, FPJSON, FGL, fpjsonrtti;
type
{ TVO }
TVO = class(TPersistent)
public
constructor Create; overload; virtual;
function ToObject(pObjetoJsonString: TJSONStringType): TVO; virtual;
function ToJSON: TJSONObject; virtual;
function ToJSONString: string;
end;
TListaVO = specialize TFPGObjectList<TVO>;
implementation
{$Region 'TVO'}
constructor TVO.Create;
begin
inherited Create;
end;
function TVO.ToObject(pObjetoJsonString: TJSONStringType): TVO;
var
DeSerializa: TJSONDeStreamer;
begin
DeSerializa := TJSONDeStreamer.Create(nil);
try
DeSerializa.JSONToObject(pObjetoJsonString, Self);
Result := Self;
finally
DeSerializa.Free;
end;
end;
function TVO.ToJSON: TJSONObject;
//var
//Serializa: TJSONStreamer;
begin
(*
Serializa := TJSONMarshal.Create(TJSONConverter.Create);
try
Exit(Serializa.Marshal(Self));
finally
Serializa.Free;
end;
*)
end;
function TVO.ToJSONString: String;
var
Serializa: TJSONStreamer;
begin
Serializa := TJSONStreamer.Create(nil);
try
Serializa.Options := Serializa.Options + [jsoTStringsAsArray];
Serializa.Options := Serializa.Options + [jsoComponentsInline];
Serializa.Options := Serializa.Options + [jsoDateTimeAsString];
Serializa.Options := Serializa.Options + [jsoStreamChildren];
// JSON convert and output
Result := Serializa.ObjectToJSONString(Self);
finally
Serializa.Free;
end;
end;
{$EndRegion 'TVO'}
end.
|
unit nsappkitext;
{$mode objfpc}{$H+}
{$modeswitch objectivec2}
interface
uses
CocoaAll, LCLType;
type
NSAppearance = objcclass external (NSObject, NSCodingProtocol)
private
_name : NSString;
_bundle : NSBundle;
_private : Pointer;
_reserved : id;
_auxilary : id;
{$ifdef CPU32}
_extra : array [0..1] of id;
{$endif}
public
procedure encodeWithCoder(aCoder: NSCoder); message 'encodeWithCoder:';
function initWithCoder(aDecoder: NSCoder): id; message 'initWithCoder:';
function name: NSString; message 'name';
// Setting and identifying the current appearance in the thread.
class function currentAppearance: NSAppearance; message 'currentAppearance';
// nil is valid and indicates the default appearance.
class procedure setCurrentAppearance(appearance: NSAppearance); message 'setCurrentAppearance:';
// Finds and returns an NSAppearance based on the name.
// For standard appearances such as NSAppearanceNameAqua, a built-in appearance is returned.
// For other names, the main bundle is searched.
class function appearanceNamed(aname: NSString): NSAppearance; message 'appearanceNamed:';
{/* Creates an NSAppearance by searching the specified bundle for a file with the specified name (without path extension).
If bundle is nil, the main bundle is assumed.
*/
#if NS_APPEARANCE_DECLARES_DESIGNATED_INITIALIZERS
- (nullable instancetype)initWithAppearanceNamed:(NSString *)name bundle:(nullable NSBundle *)bundle NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
#endif}
// Query allowsVibrancy to see if the given appearance actually needs vibrant drawing.
// You may want to draw differently if the current apperance is vibrant.
function allowsVibrancy: Boolean; message 'allowsVibrancy';
end;
procedure setThemeMode(FormHandle: HWND; isDarkMode: boolean);
var
NSAppearanceNameAqua: NSString; cvar; external;
// Light content should use the default Aqua apppearance.
NSAppearanceNameLightContent: NSString; cvar; external; // deprecated
// The following two Vibrant appearances should only be set on an NSVisualEffectView, or one of its container subviews.
NSAppearanceNameVibrantDark : NSString; cvar; external;
NSAppearanceNameVibrantLight: NSString; cvar; external;
type
//it's actually a protocol!
NSAppearanceCustomization = objccategory external (NSObject)
procedure setAppearance(aappearance: NSAppearance); message 'setAppearance:';
function appearance: NSAppearance; message 'appearance';
// This returns the appearance that would be used when drawing the receiver, taking inherited appearances into account.
//
function effectiveAppearance: NSAppearance; message 'effectiveAppearance';
end;
implementation
procedure setThemeMode(FormHandle: HWND; isDarkMode: boolean);
var
theWindow : CocoaAll.NSWindow;
begin
theWindow := NSView(FormHandle).window;
if isDarkMode then
theWindow.setAppearance (NSAppearance.appearanceNamed(NSAppearanceNameVibrantDark))
else
theWindow.setAppearance (NSAppearance.appearanceNamed(NSAppearanceNameAqua));
theWindow.invalidateShadow;
//window.invalidateShadow()
end;
(*{$IFDEF LCLCocoa}
{$mode objfpc}{$H+}
{$modeswitch objectivec2}
{$ENDIF} *)
end.
|
unit PDB.uVCLRewriters;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.CommCtrl,
System.UITypes,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.ComCtrls;
type
TPageControlNoBorder = class(Vcl.ComCtrls.TPageControl)
private
FCanUpdateActivePage: Boolean;
FIsUpdatingPage: Boolean;
procedure TCMAdjustRect(var Msg: TMessage); message TCM_ADJUSTRECT;
protected
procedure ShowControl(AControl: TControl); override;
procedure UpdateActivePage; override;
public
constructor Create(AOwner: TComponent); override;
procedure ShowTab(TabIndex: Integer);
procedure HideTab(TabIndex: Integer);
procedure DisableTabChanging;
procedure EnableTabChanging;
property IsUpdatingPage: Boolean read FIsUpdatingPage;
end;
TShapeWithTransparentBorder = class(Vcl.ExtCtrls.TShape)
protected
procedure Paint; override;
end;
implementation
{ TPageControlNoBorder }
constructor TPageControlNoBorder.Create(AOwner: TComponent);
begin
FCanUpdateActivePage := True;
FIsUpdatingPage := False;
inherited;
end;
procedure TPageControlNoBorder.DisableTabChanging;
begin
FCanUpdateActivePage := False;
end;
procedure TPageControlNoBorder.EnableTabChanging;
begin
FCanUpdateActivePage := True;
end;
procedure TPageControlNoBorder.HideTab(TabIndex: Integer);
begin
Pages[TabIndex].TabVisible := False;
end;
procedure TPageControlNoBorder.ShowControl(AControl: TControl);
begin
//do nothing - it preventing from flicking
end;
procedure TPageControlNoBorder.ShowTab(TabIndex: Integer);
begin
Pages[TabIndex].TabVisible := True;
end;
procedure TPageControlNoBorder.TCMAdjustRect(var Msg: TMessage);
begin
inherited;
if Msg.WParam = 0 then
InflateRect(PRect(Msg.LParam)^, 4, 4)
else
InflateRect(PRect(Msg.LParam)^, -4, -4);
end;
procedure TPageControlNoBorder.UpdateActivePage;
begin
FIsUpdatingPage := True;
try
if FCanUpdateActivePage then
inherited;
finally
FIsUpdatingPage := False;
end;
end;
{ TShapeWithTransparentBorder }
procedure TShapeWithTransparentBorder.Paint;
var
X, Y, W, H, S: Integer;
procedure RectangleEx(X1, Y1, X2, Y2: Integer);
begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := Pen.Color;
Canvas.Pen.Width := Pen.Width;
Canvas.Rectangle(X1, Y1, X2, Y2);
Canvas.Brush.Style := bsSolid;
Canvas.Pen.Color := Brush.Color;
Canvas.Brush.Color := Brush.Color;
Inc(X1, 1 + Pen.Width);
Inc(Y1, 1 + Pen.Width);
Dec(X2, 1 + Pen.Width);
Dec(Y2, 1 + Pen.Width);
Canvas.Rectangle(X1, Y1, X2, Y2);
end;
begin
Canvas.Pen := Pen;
Canvas.Brush := Brush;
X := Pen.Width div 2;
Y := X;
W := Width - Pen.Width + 1;
H := Height - Pen.Width + 1;
if Pen.Width = 0 then
begin
Dec(W);
Dec(H);
end;
if W < H then S := W else S := H;
if Shape in [stSquare, stRoundSquare, stCircle] then
begin
Inc(X, (W - S) div 2);
Inc(Y, (H - S) div 2);
W := S;
H := S;
end;
case Shape of
stRectangle, stSquare:
RectangleEx(X, Y, X + W, Y + H);
stRoundRect, stRoundSquare:
Canvas.RoundRect(X, Y, X + W, Y + H, S div 4, S div 4);
stCircle, stEllipse:
Canvas.Ellipse(X, Y, X + W, Y + H);
end;
end;
end.
|
(*
Category: SWAG Title: 16/32 BIT CRC ROUTINES
Original name: 0018.PAS
Description: RemoteAccess CRC Routine
Author: MARTIN WOODS
Date: 02-21-96 21:04
*)
(*
unit racrc;
interface
procedure makecrc32table;
function updatecrc32(c : byte; crc : longint) : longint;
function calccrc(pass1: string) : longint;
implementation
*)
var
crc32table : array [byte] of longint;
crcval : longint;
j : integer;
procedure makeCRC32table;
var crc : longint;
i,n : byte;
begin
for i := 0 to 255 do
begin
crc := i;
for n := 1 to 8 do
if odd(crc) then
crc := (crc shr 1) xor $EDB88320
else
crc := crc shr 1;
crc32table[i] := crc;
end;
end;
function updateCRC32(c : byte; crc : longint) : longint;
begin
updateCRC32 := crc32table[lo(crc) xor c] xor (crc shr 8);
end;
function calccrc(pass1 : string) : longint;
begin
makecrc32table;
crcval := $FFFFFFF(*F*);
for j := 1 to length(pass1) do
begin
crcval := updateCRC32(ord(pass1[j]),crcval);
end;
calccrc := crcval;
end;
(*Use like this:*)
var
password: string;
i: longint;
begin
password := 'REMOTEACCSS';
i := calccrc(password);
writeLn(i);
readln;
end.
|
unit U_FormatConverter;
interface
uses
System.SysUtils, System.Classes,
U_JSON.XML, U_XML.JSON;
type
TFormatConverter = class(TComponent)
private
fJSONtoXML : TJSONtoXML;
fXMLtoJSON : TXMLtoJSON;
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
published
property JSONtoXML : TJSONtoXML read fJSONtoXML write fJSONtoXML;
property XMLtoJSON : TXMLtoJSON read fXMLtoJSON write fXMLtoJSON;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Ridge Dynamics', [TFormatConverter]);
end;
{ TFormatConverter }
constructor TFormatConverter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fJSONtoXML := TJSONtoXML.Create();
fXMLtoJSON := TXMLtoJSON.Create();
end;
end.
|
{*******************************************************************************
* uCharControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа со строковым полем ввода (TqFCharControl) *
* Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uCharControl;
interface
uses
SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl,
Registry, Variants;
type
TqFCharControl = class(TqFLabeledControl)
protected
FEdit: TEdit;
procedure SetValue(Val: Variant); override;
function GetValue: Variant; override;
procedure SetMaxLength(Len: Integer);
function GetMaxLength: Integer;
procedure PrepareRest; override;
procedure Change(Sender: TObject); virtual;
procedure Loaded; override;
function GetKeyDown: TKeyEvent;
procedure SetKeyDown(e: TKeyEvent);
function GetKeyUp: TKeyEvent;
procedure SetKeyUp(e: TKeyEvent);
public
constructor Create(AOwner: TComponent); override;
function Check: string; override;
procedure Block(Flag: Boolean); override;
procedure Highlight(HighlightOn: Boolean); override;
procedure ShowFocus; override;
function ToString: string; override;
procedure LoadFromRegistry(reg: TRegistry); override; // vallkor
procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor
published
property MaxLength: Integer read GetMaxLength write SetMaxLength;
property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown;
property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp;
end;
procedure Register;
{$R *.res}
implementation
uses qFStrings, qFTools;
function TqFCharControl.GetKeyDown: TKeyEvent;
begin
Result := FEdit.OnKeyDown;
end;
procedure TqFCharControl.SetKeyDown(e: TKeyEvent);
begin
FEdit.OnKeyDown := e;
end;
function TqFCharControl.GetKeyUp: TKeyEvent;
begin
Result := FEdit.OnKeyUp;
end;
procedure TqFCharControl.SetKeyUp(e: TKeyEvent);
begin
FEdit.OnKeyUp := e;
end;
procedure TqFCharControl.Block(Flag: Boolean);
begin
inherited Block(Flag);
FEdit.ReadOnly := Flag;
if Flag then
FEdit.Color := qFBlockedColor
else
FEdit.Color := FOldColor;
end;
procedure TqFCharControl.Change(Sender: TObject);
begin
if (Trim(FEdit.Text) <> '') and Asterisk then
Asterisk := False;
if Assigned(FOnChange) then
FOnChange(Sender);
end;
procedure TqFCharControl.Loaded;
begin
FEdit.OnChange := Change;
inherited Loaded;
end;
procedure TqFCharControl.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if HighlightOn then
FEdit.Color := qFHighlightColor
else
if FOldColor <> 0 then
FEdit.Color := FOldColor;
Repaint;
end;
procedure TqFCharControl.ShowFocus;
begin
inherited ShowFocus;
qFSafeFocusControl(FEdit);
end;
procedure TqFCharControl.SetMaxLength(Len: Integer);
begin
FEdit.MaxLength := Len;
end;
function TqFCharControl.GetMaxLength: Integer;
begin
Result := FEdit.MaxLength;
end;
function TqFCharControl.ToString: string;
begin
Result := QuotedStr(FEdit.Text);
end;
function TqFCharControl.Check: string;
begin
if Required then
if Trim(Value) = '' then
Check := qFFieldIsEmpty + '"' + DisplayName + '"!'
else
Check := ''
else
Check := '';
end;
procedure TqFCharControl.SetValue(Val: Variant);
begin
inherited SetValue(Val);
FEdit.Text := Coalesce(Val, '');
end;
function TqFCharControl.GetValue: Variant;
begin
Result := FEdit.Text;
end;
constructor TqFCharControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEdit := TEdit.Create(Self);
FEdit.Parent := Self;
PrepareRest;
FOldColor := FEdit.Color;
end;
procedure TqFCharControl.PrepareRest;
begin
inherited;
if FEdit <> nil then
begin
FEdit.Width := Width - Interval - 3;
FEdit.Left := Interval;
FEdit.Top := (Height - FEdit.Height) div 2;
end;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFCharControl]);
end;
procedure TqFCharControl.LoadFromRegistry(reg: TRegistry); // vallkor
begin
inherited LoadFromRegistry(reg);
Value := Reg.ReadString('Value');
end;
procedure TqFCharControl.SaveIntoRegistry(reg: TRegistry); // vallkor
begin
inherited SaveIntoRegistry(reg);
Reg.WriteString('Value', VarToStr(Value));
end;
end.
|
{/*!
Provides interface and base class for developing TransModeler plugins.
\modified 2019-07-17 17:46pm
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl,
RemObjects.Elements.RTL;
[SymbolName('__tsm_user_plugin_factory_')]
method CreateUserPlugin(const aPluginDirectory: not nullable String): ITsmPlugin; external;
type
[COM, Guid('{D2B4B617-A1EB-46D1-9E8D-FC88B6E4DDFE}')]
ITsmPlugin = public interface(IUnknown)
method Initialize: Boolean;
method OpenParameterEditor;
property Enabled: Boolean read write;
property PluginDirectory: String read;
property PluginInfo: String read;
property PluginName: String read;
property PluginVersion: String read;
property VehicleFactory: UserVehicleFactory read;
end;
PluginEnabledEventHandler = public block();
PluginDisabledEventHandler = public block();
TsmPlugin = public abstract class(ITsmPlugin)
private
const PmlFileExtension : String = '.xml'; public;
const UiDbFileExtension : String = '.dbd'; public;
const AddPluginUiMacroName : String = 'AddPluginUI'; public;
const RemovePluginUiMacroName : String = 'RemovePluginUI'; public;
const UiRscCompilerName : String = 'rscc.exe'; public;
const TsmUserPrefFolderName : String = 'User Preference'; public;
var fEnabled: Boolean;
var fEventSinkManager: ITsmEventSinkManager;
var fUiDbFilePath, fPluginDirectory, fBasePmlFilePath, fUserPmlFilePath: String;
var fTsmApp: ITsmApplication;
var fPmEditor: IParameterEditor;
class var fSingleton: ITsmPlugin := nil;
private
constructor; empty;
finalizer;
begin
fEventSinkManager := nil;
fPmEditor := nil;
fTsmApp := nil;
end;
method OnPluginEnabled;
begin
if assigned(PluginEnabled) then PluginEnabled();
end;
method OnPluginDisabled;
begin
if assigned(PluginDisabled) then PluginDisabled();
end;
method DoEnablePlugin;
begin
fEventSinkManager.Connect(SupportedEventSinkTypes);
AddPluginUI;
OnPluginEnabled;
end;
method DoDisablePlugin;
begin
fEventSinkManager.Disconnect(SupportedEventSinkTypes);
RemovePluginUI;
OnPluginDisabled;
end;
method AddPluginUI;
begin
var lArgs, lRetVal: VARIANT;
var lMacroName: OleString := AddPluginUiMacroName;
var lDb: OleString := fUiDbFilePath;
rtl.VariantInit(@lArgs);
rtl.VariantInit(@lRetVal);
fTsmApp.Macro(lMacroName, lDb, lArgs, out lRetVal);
rtl.VariantClear(@lRetVal);
end;
method RemovePluginUI;
begin
var lArgs, lRetVal: VARIANT;
var lMacroName: OleString := RemovePluginUiMacroName;
var lDb: OleString := fUiDbFilePath;
rtl.VariantInit(@lArgs);
rtl.VariantInit(@lRetVal);
fTsmApp.Macro(lMacroName, lDb, lArgs, out lRetVal);
rtl.VariantClear(@lRetVal);
end;
method SubscribeEvents;
begin
for lType: TsmEventSinkType := TsmEventSinkType.Undefined to TsmEventSinkType.All do
if (lType in SupportedEventSinkTypes) then Subscribe(fEventSinkManager.GetEventSink(lType));
end;
method ValidatePmlBaseFile;
begin
var lPmlBaseContent: String := GeneratePmlBaseContent;
if lPmlBaseContent <> String.Empty then
if not File.Exists(fBasePmlFilePath) then File.WriteText(fBasePmlFilePath, lPmlBaseContent);
end;
method ValidateUiDatabase;
begin
method GisdkCompilerPath: String;
begin
var lTsmProgramFolder: OleString;
fTsmApp.Get_ProgramFolder(out lTsmProgramFolder);
result := Path.Combine(lTsmProgramFolder.ToString, UiRscCompilerName);
end;
if not File.Exists(fUiDbFilePath) then begin
var lCompileResult := CaliperScriptCompiler.Compile(
GenerateUiScriptContent,
GisdkCompilerPath,
Path.GetPathWithoutExtension(fUiDbFilePath));
if not lCompileResult.Success then
raise new EUiScriptCompileErrorException(lCompileResult.Errors.JoinedString(Environment.LineBreak));
end;
end;
protected
[Conditional('DEBUG')]
method Log(const aMessage: String);
begin
rtl.OutputDebugString(rtl.LPCWSTR(aMessage.ToCharArray));
end;
method ParameterParser: TsmPluginParameterParser;
begin
result := new TsmPluginParameterParser(fBasePmlFilePath, fUserPmlFilePath, ProjectPmlFilePath);
end;
{$REGION 'Protected methods that must be implemented by a sub class.'}
method GeneratePmlBaseContent: String; virtual; abstract;
method GenerateUiScriptContent: String; virtual; abstract;
method GetPluginInfo: String; virtual; abstract;
method GetPluginName: String; virtual; abstract;
method GetSupportedEventSinkTypes: TsmEventSinkTypes; virtual; abstract;
method GetPluginVersion: String; virtual; abstract;
method Subscribe(aEventSink: ITsmEventSink); virtual; abstract;
{$ENDREGION}
method GetUserVehicleFactory: UserVehicleFactory; virtual;
begin
result := nil;
end;
public
constructor(const aPluginDirectory: String);
begin
fTsmApp := CoTsmApplication.Create;
fPmEditor := CoParameterEditor.Create;
fEventSinkManager := new TsmEventSinkManager(fTsmApp);
fEnabled := false;
fPluginDirectory := aPluginDirectory;
fBasePmlFilePath := Path.Combine(fPluginDirectory, PluginName + PmlFileExtension);
var lTsmUserPrefFolder: OleString;
fTsmApp.GetFolder(TsmUserPrefFolderName, out lTsmUserPrefFolder);
fUserPmlFilePath := Path.Combine(lTsmUserPrefFolder.ToString, PluginName + PmlFileExtension);
fUiDbFilePath := Path.Combine(fPluginDirectory, PluginName + UiDbFileExtension);
// Attach event handlers to each permissible event sinks as specified in sub class.
SubscribeEvents;
end;
class method CreateSingleton(const aPluginDirectory: String): Boolean;
begin
if assigned(fSingleton) then exit true;
fSingleton := CreateUserPlugin(aPluginDirectory);
result := fSingleton.Initialize;
if not result then fSingleton := nil;
end;
method Initialize: Boolean;
begin
try
ValidatePmlBaseFile;
ValidateUiDatabase;
except
on E: EUiScriptCompileErrorException do begin
result := false;
Log(E.Message + E.Errors);
end;
on E: EDllModuleLoadingException do begin
result := false;
Log(E.Message);
end;
on E: Exception do begin
result := false;
Log(E.Message);
end;
end;
end;
method OpenParameterEditor;
begin
fPmEditor.Edit(fBasePmlFilePath, fUserPmlFilePath, ProjectPmlFilePath);
end;
public
property Enabled: Boolean
read begin
result := fEnabled;
end
write begin
if fEnabled <> value then begin
fEnabled := value;
if fEnabled then DoEnablePlugin else DoDisablePlugin;
end;
end;
property PluginInfo: String
read GetPluginInfo;
property PluginDirectory: String
read fPluginDirectory;
property PluginName: String
read begin
result := GetPluginName;
ensure
not result.Contains(' ');
end;
property ProjectPmlFilePath: String
read begin
var lProjectFolder: OleString;
fTsmApp.Get_ProjectFolder(out lProjectFolder);
result := if lProjectFolder.Length > 0 then Path.Combine(lProjectFolder.ToString, PluginName + PmlFileExtension) else String.Empty;
end;
property SupportedEventSinkTypes: TsmEventSinkTypes
read GetSupportedEventSinkTypes;
property VehicleFactory: UserVehicleFactory
read GetUserVehicleFactory;
property PluginVersion: String
read begin
exit GetPluginVersion;
end;
property TsmApplication: ITsmApplication
read fTsmApp;
class property Singleton: ITsmPlugin
read fSingleton;
event PluginEnabled: PluginEnabledEventHandler;
event PluginDisabled: PluginDisabledEventHandler;
end;
end. |
{-----------------------------------------------------------------------------
Unit Name: uVehicle
Author: Panagiotis Kakaletris (Orchestraman)
Purpose:
Implements Object Steerining Behaviours for GLScene OpenGL library.
Bibliography:
Based on "Steering Behaviors For Autonomous Characters" by Craig Reynolds.
Visit http://www.red3d.com/cwr/steer/ for more information.
Notes: Collision Code is based in GLFPSCollision unit part of GLScene OGL Library.
History:
5/jul/2004 - Orchestraman - First Creation
-----------------------------------------------------------------------------}
unit uVehicle;
interface
uses
Classes, Contnrs,
GLVectorGeometry, GLVectorTypes, GLScene, GLXCollection, GLCoordinates,
GLBehaviours, GLCollision, GLCadencer, GLVectorFileObjects, GLBaseClasses,
GLManager;
type
TSteeringBehaviours = (sbhSeek, sbhFlee, sbhPursuit, sbhEvasion,
sbhOffsetPursuit, sbhArrival, sbhObstacleAvoidance,
sbhWander);
TGLSteeringBehaviours = set of TSteeringBehaviours;
TGLBVehicle = class;
TGLVehicleManager = class;
TBaseSteerBehaviour = class;
TSteerBehaviourClass = class of TBaseSteerBehaviour;
// TBaseSteerBehaviour
//
{ Base Class for implementing Steering Behaviours}
TBaseSteerBehaviour = class(TComponent)
private
FVehicle: TGLBVehicle;
FSteerRatio: Single;
protected
procedure SetVehicle(const AValue: TGLBVehicle); virtual;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; virtual; abstract;
property Vehicle: TGLBVehicle read FVehicle write SetVehicle;
property Ratio: Single read FSteerRatio write FSteerRatio;
end;
// TWanderSteer
//
{ Implementation of Wander Steering Behaviour}
TWanderSteer = class(TBaseSteerBehaviour)
private
FWanderModifier: TVector;
FRate,
FStrength: Double;
protected
procedure SetVehicle(const AValue: TGLBVehicle); override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; override;
property Rate: Double read FRate write FRate;
property Strength: Double read FStrength write FStrength;
property WanderModifier: TVector read FWanderModifier write FWanderModifier;
end;
// TSeekSteer
//
{ Implementation of Seek Steering Behaviour}
TSeekSteer = class(TBaseSteerBehaviour)
private
FTarget: TGLBaseSceneObject;
FTurnRate: Single;
procedure SetTarget(const Value: TGLBaseSceneObject);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; override;
property Target: TGLBaseSceneObject read FTarget write SetTarget;
end;
// TFleeSteer
//
TFleeSteer = class(TBaseSteerBehaviour)
private
FTarget: TGLBaseSceneObject;
procedure SetTarget(const Value: TGLBaseSceneObject);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; override;
property Target: TGLBaseSceneObject read FTarget write SetTarget;
end;
// TPursueSteer
//
TPursueSteer = class(TBaseSteerBehaviour)
private
FTarget: TGLBaseSceneObject;
procedure SetTarget(const Value: TGLBaseSceneObject);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; override;
property Target: TGLBaseSceneObject read FTarget write SetTarget;
end;
// TWorldCollisionSteer
//
TWorldCollisionSteer = class(TBaseSteerBehaviour)
private
FMap: TGLFreeForm;
FCollided: Boolean;
oldPosition,
velocity: TVector;
FTurnRate: Single;
procedure SetMap(const Value: TGLFreeForm);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
function SphereSweepAndSlide(freeform:TGLFreeform; SphereStart: TVector;
var Velocity, newPosition: TVector; sphereRadius: single): boolean;
procedure SetVehicle(const AValue: TGLBVehicle); override;
public
constructor Create(AOwner: TComponent); override;
procedure ApplySteerForce; override;
property Map: TGLFreeForm read FMap write SetMap;
property Collided: Boolean read FCollided;
property TurnRate: Single read FTurnRate write FTurnRate;
end;
// TGLBVehicle
//
TGLBVehicle = class(TGLBehaviour)
private
FSteerUpdateInterval: Double;
FMass: Integer;
FSpeed,
FMaxForce,
FMaxSpeed: Double;
FUp,
FVelocity,
FAccumulator: TGLCoordinates;
FProgressTime: TProgressTimes;
FAccumulatedTime: Double;
FManager: TGLVehicleManager;
FGroupIndex: Integer;
FManagerName: String; // NOT persistent, temporarily used for persistence
FSteerBehaviours: TObjectList;
FGLSteeringBehaviours: TGLSteeringBehaviours;
FSeekSteer: TSeekSteer;
FWanderSteer: TWanderSteer;
FPursueSteer: TPursueSteer;
FFleeSteer: TFleeSteer;
FWorldCollisionSteer: TWorldCollisionSteer;
FCollisionObject: TGLBaseSceneObject;
protected
{ Protected Declarations }
procedure SetGLSteeringBehaviours(const Value: TGLSteeringBehaviours);
procedure SetManager(const Value: TGLVehicleManager);
procedure SetGroupIndex(const Value: Integer);
function GetVelocity: TGLCoordinates;
procedure SetVelocity(const Value: TGLCoordinates);
function GetSpeed: Double;
procedure SetSpeed(const Value: Double);
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
procedure Loaded; override;
public
constructor Create(aOwner : TGLXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName : String; override;
class function FriendlyDescription : String; override;
procedure DoProgress(const progressTime : TProgressTimes); override;
procedure DoSteering;
property ProgressTime: TProgressTimes read FProgressTime write FProgressTime;
property AccumulatedTime: Double read FAccumulatedTime write FAccumulatedTime;
property CollisionObject: TGLBaseSceneObject read FCollisionObject write FCollisionObject;
property Accumulator: TGLCoordinates read FAccumulator;
property Flee: TFleeSteer read FFleeSteer write FFleeSteer;
property Seek: TSeekSteer read FSeekSteer write FSeekSteer;
property Pursue: TPursueSteer read FPursueSteer write FPursueSteer;
property Wander: TWanderSteer read FWanderSteer write FWanderSteer;
property WorldCollision: TWorldCollisionSteer read FWorldCollisionSteer write FWorldCollisionSteer;
published
property Manager: TGLVehicleManager read FManager write SetManager;
property GroupIndex: Integer read FGroupIndex write SetGroupIndex;
property Mass: Integer read FMass write FMass;
// property Velocity: TGLCoordinates read GetVelocity write SetVelocity;
property MaxForce: Double read FMaxForce write FMaxForce;
property MaxSpeed: Double read FMaxSpeed write FMaxSpeed;
property Speed: Double read GetSpeed write SetSpeed;
property SteeringBehaviours: TGLSteeringBehaviours read FGLSteeringBehaviours
write SetGLSteeringBehaviours;
property SteerUpdateInterval: Double read FSteerUpdateInterval write FSteerUpdateInterval;
property SteerBehaviours: TObjectList read FSteerBehaviours write FSteerBehaviours;
property Up: TGLCoordinates read FUp write FUp;
end;
// TGLVehicleManager
//
{ Manager που διαχειρίζεται τα Vehicles}
TGLVehicleManager = class(TComponent)
private
FSteerInterval: Double;
FClients: TList;
FCadencer: TGLCadencer;
FWorldCollisionMap: TGLFreeForm;
procedure SetCadencer(const Value: TGLCadencer);
function GetCadencer: TGLCadencer;
procedure SetSteerInterval(const Value: Double);
procedure SetWorldCollisionMap(const Value: TGLFreeForm);
protected
{ Protected Declarations }
procedure RegisterClient(aClient: TGLBVehicle);
procedure DeRegisterClient(aClient: TGLBVehicle);
procedure DeRegisterAllClients;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoSteering;
property Clients: TList read FClients;
published
property Cadencer: TGLCadencer read GetCadencer write SetCadencer;
property SteerInterval: Double read FSteerInterval write SetSteerInterval;
property WorldCollisionMap: TGLFreeForm read FWorldCollisionMap write SetWorldCollisionMap;
end;
{: Returns or creates the TGLBVehicle within the given behaviours.<p>
This helper function is convenient way to access a TGLBVehicle. }
function GetOrCreateVehicle(behaviours: TGLBehaviours): TGLBVehicle; overload;
{: Returns or creates the TGLBVehicle within the given object's behaviours.<p>
This helper function is convenient way to access a TGLBVehicle. }
function GetOrCreateVehicle(obj: TGLBaseSceneObject): TGLBVehicle; overload;
implementation
uses
SysUtils, Math;
// GetOrCreateVehicle (TGLBehaviours)
//
function GetOrCreateVehicle(behaviours: TGLBehaviours): TGLBVehicle;
var
i: Integer;
begin
i := behaviours.IndexOfClass(TGLBVehicle);
if i >= 0 then
Result := TGLBVehicle(behaviours[i])
else Result := TGLBVehicle.Create(behaviours);
end;
// GetOrCreateVehicle (TGLBaseSceneObject)
//
function GetOrCreateVehicle(obj: TGLBaseSceneObject): TGLBVehicle;
begin
Result := GetOrCreateVehicle(obj.Behaviours);
end;
{ TGLVehicleManager }
// TGLVehicleManager.Create
//
constructor TGLVehicleManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClients := TList.Create;
RegisterManager(Self);
FSteerInterval := 0;
end;
// TGLVehicleManager.Destroy
//
destructor TGLVehicleManager.Destroy;
begin
if Assigned(FCadencer) then
FCadencer.RemoveFreeNotification(Self);
FCadencer := nil;
DeRegisterAllClients;
DeRegisterManager(Self);
FClients.Free;
inherited Destroy;
end;
// TGLVehicleManager.DeRegisterAllClients
//
procedure TGLVehicleManager.DeRegisterAllClients;
var
i: Integer;
begin
// Fast deregistration
for i:=0 to FClients.Count-1 do
TGLBVehicle(FClients[i]).FManager := nil;
FClients.Clear;
end;
// TGLVehicleManager.DeRegisterClient
//
procedure TGLVehicleManager.DeRegisterClient(aClient: TGLBVehicle);
begin
if Assigned(aClient) then begin
aClient.FManager := nil;
FClients.Remove(aClient);
end;
end;
// TGLVehicleManager.RegisterClient
//
procedure TGLVehicleManager.RegisterClient(aClient: TGLBVehicle);
begin
if Assigned(aClient) then
if FClients.IndexOf(aClient) < 0 then begin
FClients.Add(aClient);
aClient.FManager := Self;
end;
end;
// TGLVehicleManager.DoSteering
//
procedure TGLVehicleManager.DoSteering;
var
I: Integer;
begin
for I := 0 to FClients.Count-1 do
TGLBVehicle(FClients[I]).DoSteering;
end;
{ TGLBVehicle }
// TGLBVehicle.Create
//
constructor TGLBVehicle.Create(aOwner: TGLXCollection);
begin
inherited Create(aOwner);
FSteerUpdateInterval := 0;
FAccumulatedTime := 0;
FMass := 10;
FSpeed := 1;
FMaxForce := 1;
FMaxSpeed := 1;
FUp := TGLCoordinates.CreateInitialized(Self, VectorMake(0, 1, 0), csVector);
FVelocity := TGLCoordinates.CreateInitialized(Self, VectorMake(1, 0, 1), csVector);
FVelocity.Normalize;
FAccumulator := TGLCoordinates.CreateInitialized(Self, VectorMake(1, 0, 1), csVector);
FSteerBehaviours := TObjectList.Create(True);
FWanderSteer := TWanderSteer.Create(nil);
FWanderSteer.Vehicle := Self;
FSteerBehaviours.Add(FWanderSteer);
FSeekSteer := TSeekSteer.Create(nil);
FSeekSteer.Vehicle := Self;
FSteerBehaviours.Add(FSeekSteer);
FFleeSteer := TFleeSteer.Create(nil);
FFleeSteer.Vehicle := Self;
FSteerBehaviours.Add(FFleeSteer);
FPursueSteer := TPursueSteer.Create(nil);
FFleeSteer.Vehicle := Self;
FSteerBehaviours.Add(FPursueSteer);
end;
// TGLBVehicle.Destroy
//
destructor TGLBVehicle.Destroy;
begin
Manager := nil;
FreeAndNil(FSteerBehaviours);
FWanderSteer := nil;
FSeekSteer := nil;
FPursueSteer := nil;
FWorldCollisionSteer := nil;
FreeAndNil(FAccumulator);
FreeAndNil(FUp);
inherited Destroy;
end;
// TGLBVehicle.SetManager
//
procedure TGLBVehicle.SetManager(const Value: TGLVehicleManager);
begin
if Value <> FManager then begin
if Assigned(FManager) then
FManager.DeRegisterClient(Self);
if Assigned(Value) then begin
Value.RegisterClient(Self);
Self.SteerUpdateInterval := Value.SteerInterval;
FWorldCollisionSteer := TWorldCollisionSteer.Create(nil);
FWorldCollisionSteer.Vehicle := Self;
FWorldCollisionSteer.Map := Value.WorldCollisionMap;
FSteerBehaviours.Add(FWorldCollisionSteer);
end;
end;
end;
// TGLBVehicle.SetGroupIndex
//
procedure TGLBVehicle.SetGroupIndex(const Value: Integer);
begin
FGroupIndex := Value;
end;
// TGLBVehicle.FriendlyName
//
class function TGLBVehicle.FriendlyName: String;
begin
Result := 'Steering';
end;
class function TGLBVehicle.FriendlyDescription: String;
begin
Result:='Steering-behaviour registration';
end;
// TGLBVehicle.Assign
//
procedure TGLBVehicle.Assign(Source: TPersistent);
begin
if Source is TGLBVehicle then begin
Manager := TGLBVehicle(Source).Manager;
Mass := TGLBVehicle(Source).Mass;
Speed := TGLBVehicle(Source).Speed;
MaxForce := TGLBVehicle(Source).MaxForce;
MaxSpeed := TGLBVehicle(Source).MaxSpeed;
GroupIndex := TGLBVehicle(Source).GroupIndex;
end;
inherited Assign(Source);
end;
// TGLBVehicle.Loaded
//
{ Κάνει register το steering behaviour στον πρώτο διαθέσιμο steering Manager που
θα βρεί στην φόρμα.}
procedure TGLBVehicle.Loaded;
var
mng: TComponent;
begin
inherited;
if FManagerName <> '' then begin
mng := FindManager(TGLVehicleManager, FManagerName);
if Assigned(mng) then
Manager := TGLVehicleManager(mng);
FManagerName:='';
end;
end;
// TGLBVehicle.WriteToFiler
//
procedure TGLBVehicle.WriteToFiler(writer: TWriter);
begin
with writer do begin
WriteInteger(1); // ArchiveVersion 1, added FGroupIndex
if Assigned(FManager) then
WriteString(FManager.GetNamePath)
else WriteString('');
WriteInteger(FGroupIndex);
WriteInteger(FMass);
WriteFloat(FSpeed);
WriteFloat(FMaxForce);
WriteFloat(FMaxSpeed);
FVelocity.WriteToFiler(writer);
end;
end;
// TGLBVehicle.ReadFromFiler
//
procedure TGLBVehicle.ReadFromFiler(reader: TReader);
var
archiveVersion: Integer;
begin
with reader do begin
archiveVersion := ReadInteger;
Assert(archiveVersion in [0..1]);
FManagerName := ReadString;
Manager:=nil;
if archiveVersion >= 1 then
FGroupIndex := ReadInteger
else FGroupIndex := 0;
FMass := ReadInteger;
FSpeed := ReadFloat;
FMaxForce := ReadFloat;
FMaxSpeed := ReadFloat;
FVelocity.ReadFromFiler(reader);
end;
end;
// TGLBVehicle.GetVelocity
//
function TGLBVehicle.GetVelocity: TGLCoordinates;
begin
Result := FVelocity;
end;
// TGLBVehicle.SetVelocity
//
procedure TGLBVehicle.SetVelocity(const Value: TGLCoordinates);
begin
FVelocity := Value;
end;
// TGLBVehicle.GetSpeed
//
function TGLBVehicle.GetSpeed: Double;
begin
Result := FSpeed;
end;
// TGLBVehicle.SetSpeed
//
procedure TGLBVehicle.SetSpeed(const Value: Double);
begin
FSpeed := Value;
end;
// TGLBVehicle.DoSteering
//
procedure TGLBVehicle.DoSteering;
var
acceleration: Double;
newLeft: TVector;
begin
if AccumulatedTime < SteerUpdateInterval then exit;
FAccumulator.SetVector(OwnerBaseSceneObject.Direction.AsVector);
FAccumulator.Normalize;
//FAccumulator.AsVector := NullHmgVector;
//FAccumulator.Scale(Speed * AccumulatedTime);
with OwnerBaseSceneObject do begin
//Εκτελώ το Collision.
FWorldCollisionSteer.ApplySteerForce;
if not FWorldCollisionSteer.Collided then begin
FSeekSteer.ApplySteerForce;
FWanderSteer.ApplySteerForce;
FFleeSteer.ApplySteerForce;
end
else begin
FWanderSteer.WanderModifier := OwnerBaseSceneObject.Direction.AsVector;
end;
Direction.AddScaledVector(AccumulatedTime, FAccumulator.AsVector);
//Υπολογίζω τη δνση του Up Vector για να μήν γέρνει το αντικείμενο κατά τη στροφή του.
VectorCrossProduct(VectorNormalize(Direction.DirectVector), FUp.DirectVector, newLeft);
Up.AsVector := VectorCrossProduct(VectorNormalize(Direction.DirectVector), newLeft);
acceleration := 1 / Mass;
speed := Lerp(speed, MaxSpeed, acceleration);
Move(speed * AccumulatedTime);
end;
AccumulatedTime := 0;
end;
// TGLVehicleManager.Notification
//
procedure TGLVehicleManager.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = Cadencer) then
Cadencer := nil
else
if (Operation = opRemove) and (AComponent = FWorldCollisionMap) then begin
FWorldCollisionMap.RemoveFreeNotification(Self);
FWorldCollisionMap := nil;
end
else inherited;
end;
procedure TGLVehicleManager.SetCadencer(const Value: TGLCadencer);
begin
if FCadencer = Value then exit;
if Assigned(FCadencer) then
FCadencer.RemoveFreeNotification(Self);
FCadencer := Value;
if FCadencer <> nil then
FCadencer.FreeNotification(Self);
end;
function TGLVehicleManager.GetCadencer: TGLCadencer;
begin
Result := FCadencer;
end;
{ TBaseSteerBehaviour }
constructor TBaseSteerBehaviour.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FVehicle := nil;
FSteerRatio := 1;
end;
procedure TBaseSteerBehaviour.SetVehicle(const AValue: TGLBVehicle);
begin
FVehicle := AValue;
end;
{ TWanderSteer }
procedure TWanderSteer.ApplySteerForce;
var
vWander: TVector;
vStrength: TVector;
vDesiredDirection: TVector;
const
c2PI = 2 * pi;
begin
with vehicle do begin
MakeVector(vWander, VectorAdd(VectorMake(cos(random * c2PI) * FRate,
ClampValue(cos(random * c2Pi) * FRate, -0.01 * FRate, 0.01 * FRate), cos(random * c2PI) * FRate), FWanderModifier)); // Φτιάχνω τυχαίο δ/σμα μετατόπισης.
NormalizeVector(vWander); // Κανονικοποιώ στην μονάδα.
ScaleVector(vWander, 10); // Κάνω scale στο WanderRate.
FWanderModifier := vWander;
MakeVector(vStrength, OwnerBaseSceneObject.Direction.AsVector);
NormalizeVector(vStrength);
ScaleVector(vStrength, FStrength);
VectorAdd(vStrength, vWander, vDesiredDirection);
NormalizeVector(vDesiredDirection);
VectorSubtract(vDesiredDirection, OwnerBaseSceneObject.Direction.AsVector, vDesiredDirection);
//NormalizeVector(vDesiredDirection);
FAccumulator.AddScaledVector(Ratio, vDesiredDirection);
end;
end;
// TGLBVehicle.SetGLSteeringBehaviours
//
procedure TGLBVehicle.SetGLSteeringBehaviours(
const Value: TGLSteeringBehaviours);
begin
FGLSteeringBehaviours := Value;
end;
// TGLVehicleManager.SetSteerInterval
//
procedure TGLVehicleManager.SetSteerInterval(const Value: Double);
var
I: Integer;
begin
FSteerInterval := Value;
for I := 0 to FClients.Count - 1 do
TGLBVehicle(FClients.Items[I]).SteerUpdateInterval := FSteerInterval;
end;
// TGLBVehicle.DoProgress
//
procedure TGLBVehicle.DoProgress(const progressTime: TProgressTimes);
begin
FProgressTime := progressTime;
AccumulatedTime := AccumulatedTime + progressTime.deltaTime;
end;
constructor TWanderSteer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRate := 1;
FStrength := 1;
end;
{ TSeekSteer }
// TSeekSteer.ApplySteerForce
//
procedure TSeekSteer.ApplySteerForce;
var
vDesiredDirection: TVector;
vDistance: TVector;
lDistance: Single;
begin
if Assigned(FTarget) then
with FVehicle do begin
vDesiredDirection := VectorNormalize(VectorSubtract(OwnerBaseSceneObject.Position.AsVector,
FTarget.Position.AsVector));
vDistance := VectorSubtract(OwnerBaseSceneObject.Direction.AsVector,
vDesiredDirection);
lDistance := VectorLength(vDistance);
FAccumulator.AddScaledVector(10 * FTurnRate * lDistance * Ratio, VectorNormalize(vDistance));
end;
end;
// TSeekSteer.Create
//
constructor TSeekSteer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTurnRate := 0.3;
end;
// TSeekSteer.Notification
//
procedure TSeekSteer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FTarget) then begin
AComponent.RemoveFreeNotification(Self);
FTarget := nil;
end
else
inherited;
end;
// TSeekSteer.SetTarget
//
procedure TSeekSteer.SetTarget(const Value: TGLBaseSceneObject);
begin
if Assigned(FTarget) then
FTarget.RemoveFreeNotification(Self);
FTarget := Value;
if Assigned(FTarget) then
FTarget.FreeNotification(Self);
end;
// TWanderSteer.SetVehicle
//
procedure TWanderSteer.SetVehicle(const AValue: TGLBVehicle);
begin
inherited SetVehicle(AValue);
SetVector(FWanderModifier, Vehicle.OwnerBaseSceneObject.Direction.AsVector);
end;
{ TFleeSteer }
// TFleeSteer.ApplySteerForce
//
procedure TFleeSteer.ApplySteerForce;
var
vDesiredDirection: TVector;
begin
if Assigned(FTarget) then
with FVehicle do begin
vDesiredDirection := VectorNegate(VectorNormalize(VectorSubtract(
OwnerBaseSceneObject.Position.AsVector,
FTarget.Position.AsVector)));
FAccumulator.AddScaledVector(0.3 * Speed * Ratio * VectorLength(VectorSubtract(
OwnerBaseSceneObject.Direction.AsVector,
vDesiredDirection)),
VectorNormalize(
VectorSubtract(
OwnerBaseSceneObject.Direction.AsVector,
vDesiredDirection)));
end;
end;
// TFleeSteer.Create
//
constructor TFleeSteer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
// TFleeSteer.Notification
//
procedure TFleeSteer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FTarget) then begin
AComponent.RemoveFreeNotification(Self);
FTarget := nil;
end
else
inherited;
end;
// TFleeSteer.SetTarget
//
procedure TFleeSteer.SetTarget(const Value: TGLBaseSceneObject);
begin
if Assigned(FTarget) then
FTarget.RemoveFreeNotification(Self);
FTarget := Value;
if Assigned(FTarget) then
FTarget.FreeNotification(Self);
end;
{ TPursueSteer }
// TPursueSteer.ApplySteerForce
//
procedure TPursueSteer.ApplySteerForce;
var
vDesiredDirection: TVector;
vDistance: TVector;
lDistance: Single;
begin
if Assigned(FTarget) then
with FVehicle do begin
vDesiredDirection := VectorNormalize(VectorSubtract(OwnerBaseSceneObject.Position.AsVector,
FTarget.LocalToAbsolute(FTarget.FindChild('GLDummyCube2', true).Position.AsVector)));
FTarget.FindChild('GLDummyCube2', true).Position.Z := 1 - 1 * VectorDotProduct(OwnerBaseSceneObject.Direction.AsVector, FTarget.Direction.AsVector) / VectorDistance(OwnerBaseSceneObject.Position.AsVector, FTarget.Position.AsVector);
vDistance := VectorSubtract(OwnerBaseSceneObject.Direction.AsVector,
vDesiredDirection);
lDistance := VectorLength(vDistance);
FAccumulator.AddScaledVector(Speed * Ratio * lDistance, VectorNormalize(vDistance));
//Ratio := Ratio - 0.00005;
end;
end;
// TPursueSteer.Create
//
constructor TPursueSteer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
// TPursueSteer.Notification
//
procedure TPursueSteer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FTarget) then begin
AComponent.RemoveFreeNotification(Self);
FTarget := nil;
end
else
inherited;
end;
// TPursueSteer.SetTarget
//
procedure TPursueSteer.SetTarget(const Value: TGLBaseSceneObject);
begin
if Assigned(FTarget) then
FTarget.RemoveFreeNotification(Self);
FTarget := Value;
if Assigned(FTarget) then
FTarget.FreeNotification(Self);
end;
{ TWorldCollisionSteer }
function TWorldCollisionSteer.SphereSweepAndSlide(freeform:TGLFreeform;
SphereStart:TVector;
var Velocity,newPosition:TVector; sphereRadius: single): boolean;
var
oldPosition, ray:TVector;
vel,slidedistance:Single;
intPoint,intNormal:TVector;
newDirection, newRay,collisionPosition, pointOnSphere,point2OnSphere:TVector;
i:integer;
SphereRadiusRel: single;
begin
SphereRadiusRel := SphereRadius/freeform.Scale.x; // μπορεί να γίνει Scale.y, or Scale.z Υποθέτοντας ότι είναι τα ίδια.
oldPosition := SphereStart;
result := true;
//Δ/νση στην οποία κινείται η σφάιρα.
ray := VectorSubtract(newPosition,oldPosition);
// ray := Velocity;
// newPosition := VectorAdd(newPosition,ray);
//Ταχύτητα της σφαίρας. Μέτρο του διανύσματος της θέσης με την προηγούμενη θέση.
//Το κάνω έτσι για να μήν εξαρτώνται οι υπολογισμοί απο την ταχύτητα του επεξεργαστή.
vel := VectorLength(ray);
//αν η σφαίρα δεν κινείται τότε δεν χρειάζεται να κάνω τίποτα.
// διαφορετικά εκτελώ μέχρι 7 loops
if vel > 0 then
for i := 0 to 6 do
begin
//Αν υπάρχει intersection χρειάζονται επιπλέον υπολογισμοί.
if (freeform.OctreeSphereSweepIntersect(oldPosition,ray,vel,SphereRadiusRel,@intPoint,@intNormal)) then
begin
if VectorDistance2(oldPosition,intPoint) <= sqr(SphereRadius) then
begin
//Η σφαίρα διασταυρώνεται με κάποιο τρίγωνο.
intNormal := VectorScale(VectorSubtract(oldPosition, intPoint), 1.0001);
end
else
begin
//αν η σφαίρα δεν διασταυρώνεται με κάποιο τρίγωνο.
//intNormal := VectorSubtract(oldPosition,intPoint); //Δεν είναι σωστό αλλά δουλεύει καλά για μικρά time steps.
//intNormal := VectorScale(VectorNormalize(intNormal), SphereRadius + 0.0001);
if RayCastSphereInterSect(intPoint,VectorNormalize(VectorNegate(ray)), oldPosition,SphereRadius,PointOnSphere, Point2OnSphere) > 0 then
intNormal := VectorScale(VectorSubtract(oldPosition, PointOnSphere), 1.0001)
//intNormal := VectorScale(VectorNormalize(VectorSubtract(oldPosition, PointOnSphere)), SphereRadius + 0.001) //VectorDistance(oldPosition, PointOnSphere));
else
begin
// Assert(False); //Αυτό δεν θα συμβεί ποτέ, μόνο για debuging.
intNormal := VectorScale(VectorSubtract(oldPosition,intPoint), 1.0001);
end;
end;
//υπολογισμός του κέντρου της σφαίρας όταν συμβεί collision.
collisionPosition := VectorAdd(intPoint, intNormal);
oldPosition := collisionPosition;
//Υπολογισμός της απόστασης που δεν διανύθηκε εξαιτίας του εμποδίου.
newRay := VectorSubtract(newPosition, collisionPosition);
//Υπολογισμός της νέας δ/νσης αν χτυπησει σε κάποιο εμπόδιο.
newDirection := VectorCrossProduct(intNormal, VectorCrossProduct(newRay, intNormal));
if VectorNorm(NewDirection) > 0 then
NormalizeVector(newDirection);
//υπολογισμός της απόστασης που πρέπει να κυλίσει (εξαρτάται απο το collision plane και το collision ray)
SlideDistance := vectorDotProduct(newRay, newDirection);
//υπολογισμός τριβής κατά την κίνηση με το εμπόδιο. (δεν είναι σωστό φυσικά)
// if abs(SlideDistance) < 10 * deltaTime then SlideDistance := 0;
ScaleVector(newDirection, SlideDistance);
//υπολογισμός της νέας θέσης στην οποία κατευθύνεται η σφαίρα.
newPosition := VectorAdd(collisionPosition, newDirection);
ray := newDirection;
vel := VectorLength(ray);
if i=6 then
begin
newPosition := oldPosition;
break;
end;
//ελέγχω για πολύ μικρές κινήσεις (πχ. όταν κολήσει σε μιά γωνία)
if vel < 1E-10 then
begin
newPosition := oldPosition;
break;
end;
end
else //δεν έγινε collision οπότε τερματίζω το loop.
begin
if i = 0 then result:= false;
Break;
end;
end; //τέλος i loop
Velocity := Ray; //η δ/νση της νέας ταχύτητας.
end;
// TWorldCollisionSteer.ApplySteerForce
//
procedure TWorldCollisionSteer.ApplySteerForce;
var
vDesiredDirection,
vDistance,
newPosition: TVector;
lDistance: single;
begin
FCollided := False;
if not Assigned(FMap) then exit;
newPosition := FVehicle.OwnerBaseSceneObject.Position.AsVector;
FCollided := SphereSweepAndSlide(FMap, oldPosition, velocity, newPosition,
FVehicle.OwnerBaseSceneObject.boundingSphereRadius + 2.3);
oldPosition := newPosition;
if FCollided then
with FVehicle do begin
vDesiredDirection := VectorNormalize(VectorSubtract(OwnerBaseSceneObject.Position.AsVector,
newPosition));
vDistance := VectorSubtract(OwnerBaseSceneObject.Direction.AsVector,
vDesiredDirection);
lDistance := VectorLength(vDistance);
//Οταν γίνεται collision αφαιρώ 5% απο την ταχύτητα της σφαίρας.
Speed := Speed * 0.9;
FAccumulator.AddScaledVector(10 * FTurnRate * VectorLength(VectorSubtract(newPosition, FVehicle.OwnerBaseSceneObject.Position.AsVector)), VectorNormalize(VectorSubtract(newPosition, FVehicle.OwnerBaseSceneObject.Position.AsVector)));
end;
// if FCollided then begin
// FVehicle.FAccumulator.AddScaledVector(4, VectorNormalize(VectorSubtract(newPosition, FVehicle.OwnerBaseSceneObject.Position.AsVector)));
// FVehicle.Speed := FVehicle.Speed * 0.95;
// end;
end;
// TWorldCollisionSteer.Create
//
constructor TWorldCollisionSteer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMap := nil;
velocity := NullHmgVector;
FTurnRate := 0.3;
end;
// TWorldCollisionSteer.Notification
//
procedure TWorldCollisionSteer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FMap) then begin
AComponent.RemoveFreeNotification(Self);
FMap := nil;
end
else
inherited;
end;
// TWorldCollisionSteer.SetMap
//
procedure TWorldCollisionSteer.SetMap(const Value: TGLFreeForm);
begin
if Assigned(FMap) then
FMap.RemoveFreeNotification(Self);
FMap := Value;
if Assigned(FMap) and (FMap <> nil) then
FMap.FreeNotification(Self);
end;
// TGLVehicleManager.SetWorldCollisionMap
//
procedure TGLVehicleManager.SetWorldCollisionMap(const Value: TGLFreeForm);
begin
if Assigned(FWorldCollisionMap) then begin
FWorldCollisionMap.RemoveFreeNotification(Self);
FWorldCollisionMap := nil;
end;
FWorldCollisionMap := Value;
if FWorldCollisionMap <> nil then
FWorldCollisionMap.FreeNotification(Self);
end;
procedure TWorldCollisionSteer.SetVehicle(const AValue: TGLBVehicle);
begin
inherited;
oldPosition := FVehicle.OwnerBaseSceneObject.Position.AsVector;
end;
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterXCollectionItemClass(TGLBVehicle);
end.
|
unit Demo.BarChart.ColoringBars;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_BarChart_ColoringBars = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_BarChart_ColoringBars.GenerateChart;
var
// Defined as TInterfacedObject No need try..finally
DefaultChart: IcfsGChartProducer;
ChartColors: IcfsGChartProducer;
begin
// DefaultChart
DefaultChart := TcfsGChartProducer.Create;
DefaultChart.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
DefaultChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Element'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Density')
]);
DefaultChart.Data.AddRow(['Copper', 8.94]);
DefaultChart.Data.AddRow(['Silver', 10.49]);
DefaultChart.Data.AddRow(['Gold', 19.30]);
DefaultChart.Data.AddRow(['Platinum', 21.45]);
DefaultChart.Options.Title('Density of Precious Metals, in g/cm^3');
DefaultChart.Options.Legend('position', 'none');
DefaultChart.Options.Bar('groupWidth', '90%');
// ChartColors
ChartColors := TcfsGChartProducer.Create;
ChartColors.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
ChartColors.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Element'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Density'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE)
]);
ChartColors.Data.AddRow(['Copper', 8.94, '#b87333']); // RGB value
ChartColors.Data.AddRow(['Silver', 10.49, 'silver']); // English color name
ChartColors.Data.AddRow(['Gold', 19.30, 'gold']);
ChartColors.Data.AddRow(['Platinum', 21.45, 'color: #e5e4e2' ]); // CSS-style declaration ChartColors.Data.AddRow(['New York City, NY', 8175000, 8008000]);
ChartColors.Options.Title('Density of Precious Metals, in g/cm^3');
ChartColors.Options.Legend('position', 'none');
ChartColors.Options.Bar('groupWidth', '90%');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div id="DefaultChart" style="width: 100%;height: 50%;"></div>'
+ '<div id="ChartColors" style="width: 100%;height: 50%;">'
);
GChartsFrame.DocumentGenerate('DefaultChart', DefaultChart);
GChartsFrame.DocumentGenerate('ChartColors', ChartColors);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_BarChart_ColoringBars);
end.
|
unit brMcuU;
interface
uses Dialogs, Classes, brCommonsU, System.SysUtils, System.StrUtils, synautil;
type
brMcu = class(bridgeCommon)
private
// procedure masukkanGetPendaftaranUrut;
is_post : Boolean;
//no_kartu : string;
// no_kunjungan : string;
procedure masukkanPostMcu(id : string);
procedure masukkanPutMcu(id : string);
procedure masukkanDelMcu(id : string);
function StrToPostgesDate (strDate : string) : string;
public
aScript : TStringList;
function ambilJsonMcu(id : string) : string;
function postMcu(id : string) : Boolean;
function delMcu(id : string) : Boolean;
constructor Create;
destructor destroy;
// property Uri : string;
end;
implementation
uses SynCommons;
{ brKunjungan }
function brMcu.ambilJsonMcu(id : string): String;
var sql0, sql1 : string;
tglStr, tglPulangStr, noKunjungan, noKartu : string;
i : Integer;
V1 : Variant;
begin
Result := '';
parameter_bridging('MCU', 'POST');
V1 := _Json(FormatJson);
sql0 := 'select * from jkn.mcu_view where id = %s and bpjs_kunjungan is not null and adl_isi > 0;';
sql1 := Format(sql0,[QuotedStr(id)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
if not fdQuery.IsEmpty then
begin
//ShowMessage('not empty');
DateTimeToString(tglStr, 'DD-MM-YYYY', fdQuery.FieldByName('tanggal').AsDateTime);
//DateTimeToString(tglPulangStr, 'DD-MM-YYYY', fdQuery.FieldByName('pulang_tanggal').AsDateTime);
if fdQuery.FieldByName('kd_mcu').AsInteger = 0 then is_post := true else
begin
is_post := False;
end;
V1.kdMCU := fdQuery.FieldByName('kd_mcu').AsInteger;
V1.noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString;
V1.kdProvider := fdQuery.FieldByName('provider_bpjs').AsString;
V1.tglPelayanan := tglStr;
V1.tekananDarahSistole := fdQuery.FieldByName('tekanan_darah_sistole').AsInteger;
V1.tekananDarahDiastole := fdQuery.FieldByName('tekanan_darah_diastole').AsInteger;
V1.darahRutinHemo := fdQuery.FieldByName('darah_rutin_hemo').AsFloat;
V1.darahRutinLeu := fdQuery.FieldByName('darah_rutin_leu').AsFloat;
V1.darahRutinErit := fdQuery.FieldByName('darah_rutin_erit').AsFloat;
V1.darahRutinLaju := fdQuery.FieldByName('darah_rutin_laju').AsFloat;
V1.darahRutinHema := fdQuery.FieldByName('darah_rutin_hema').AsFloat;
V1.darahRutinTrom := fdQuery.FieldByName('darah_rutin_trom').AsFloat;
V1.lemakDarahHdl := fdQuery.FieldByName('lemak_darah_hdl').AsFloat;
V1.lemakDarahLdl := fdQuery.FieldByName('lemak_darah_ldl').AsFloat;
V1.lemakDarahChol := fdQuery.FieldByName('lemak_darah_chol').AsFloat;
V1.lemakDarahTrigli := fdQuery.FieldByName('lemak_darah_trigli').AsFloat;
V1.gulaDarahSewaktu := fdQuery.FieldByName('gula_darah_sewaktu').AsFloat;
V1.gulaDarahPuasa := fdQuery.FieldByName('gula_darah_puasa').AsFloat;
V1.gulaDarahPostPrandial := fdQuery.FieldByName('gula_darah_post_prandial').AsFloat;
V1.gulaDarahHbA1c := fdQuery.FieldByName('gula_darah_hba1c').AsFloat;
V1.fungsiHatiSGOT := fdQuery.FieldByName('fungsi_hati_sgot').AsFloat;
V1.fungsiHatiSGPT := fdQuery.FieldByName('fungsi_hati_sgpt').AsFloat;
V1.fungsiHatiGamma := fdQuery.FieldByName('fungsi_hati_gamma').AsFloat;
V1.fungsiHatiProtKual := fdQuery.FieldByName('fungsi_hati_prot_kual').AsFloat;
V1.fungsiHatiAlbumin := fdQuery.FieldByName('fungsi_hati_albumin').AsFloat;
V1.fungsiGinjalCrea := fdQuery.FieldByName('fungsi_ginjal_crea').AsFloat;
V1.fungsiGinjalUreum := fdQuery.FieldByName('fungsi_ginjal_ureum').AsFloat;
V1.fungsiGinjalAsam := fdQuery.FieldByName('fungsi_ginjal_asam').AsFloat;
V1.fungsiJantungABI := fdQuery.FieldByName('fungsi_jantung_abi').AsFloat;
{
if not fdQuery.FieldByName('kd_provider').IsNull then
V1.kdProviderRujukLanjut := fdQuery.FieldByName('kd_provider').AsString;
}
V1.pemeriksaanLain := fdQuery.FieldByName('pemeriksaan_lain').AsString;
V1.keterangan := fdQuery.FieldByName('keterangan').AsString;
fdQuery.Close;
Result := VariantSaveJSON(V1);
end else fdQuery.Close;
//FileFromString(Result, 'kunjunganxxx.json');
//ShowMessage(Result);
end;
constructor brMcu.Create;
begin
inherited Create;
aScript := TStringList.Create;
//no_kunjungan := '';
end;
function brMcu.delMcu(id: string): Boolean;
var sql0, sql1 : string;
tglStr, jejak : string;
kdMCU, noKunjungan : string;
ts : TMemoryStream;
begin
Result := False;
parameter_bridging('MCU', 'DELETE');
// mencari parameter pendaftaran
//ShowMessage('awal del');
sql0 := 'select kd_mcu, bpjs_kunjungan from jkn.mcu_view where id = %s;';
sql1 := Format(sql0, [quotedStr(id)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
//jejak := id_tindakan;
kdMCU := fdQuery.FieldByName('kd_mcu').AsString;
noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString;
fdQuery.Close;
Uri := StringReplace( Uri, '{kdmcu}', kdMCU, []);
Uri := StringReplace( Uri, '{noKunjungan}', noKunjungan, []);
//Uri := StringReplace(Uri, '{noUrut}', noUrut, []);
//showMessage(kdTindakanSk);
if StrToIntDef(kdMCU, 0) > 0 then
begin
//showMessage('tes');
Result := httpDelete(Uri);
jejakIdxstr := id;
if Result then masukkanDelMCU(id);
end;
FDConn.Close;
end;
destructor brMcu.destroy;
begin
aScript.Free;
inherited;
end;
procedure brMcu.masukkanDelMcu(id: string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
kdTindakanSk : integer;
kdRacikan : string;
begin
// ShowMessage('awal masukkan get');
if logRest('DEL', 'MCU', tsResponse.Text) then
begin
// DateTimeToString(tglStr, 'YYYY-MM-DD', tgl);
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
sqlDel0 := 'update jkn.bpjs_mcu set kd_mcu = 0 where id = %s;';
sqlDel1 := Format(sqlDel0, [quotedStr(id)]);
tSl.Add(sqlDel1);
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brMcu.masukkanPostMcu(id : string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
kdMcu : integer;
noKunjungan : string;
begin
// ShowMessage(tsResponse.Text);
if logRest('POST', 'MCU', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
kdMcu := dataResp.response.message;
sqlDel0 := 'update jkn.bpjs_mcu set kd_mcu = %s where id = %s;';
sqlDel1 := Format(sqlDel0, [intToStr(kdMcu), quotedStr(id)]);
tSl.Add(sqlDel1);
jalankanScript(tSl);
finally
FreeAndNil(tSl);
end;
end;
end;
procedure brMcu.masukkanPutMcu(id : string);
begin
logRest('PUT', 'MCU', tsResponse.Text);
end;
function brMcu.postMcu(id : string): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
js := ambilJsonMcu(id);
if Length(js) > 10 then
begin
mStream := TMemoryStream.Create;
try
Result := False;
WriteStrToStream(mStream, js);
if is_post then
begin
//Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas);
Result:= httpPost(Uri, mStream);
jejakIdxstr := id;
FormatJson := js;
if Result then masukkanPostMcu(id);
end else
begin
//Uri := ReplaceStr(Uri, '{nokartu}', no_kartu);
Result := httpPut(Uri, mStream);
jejakIdxstr := id;
FormatJson := js;
if Result then masukkanPutMcu(id);
end;
finally
mStream.Free;
end;
end;
FDConn.Close;
end;
function brMcu.StrToPostgesDate(strDate: string): string;
var
formatAsli : Char;
myDate : TDateTime;
myDateStr : string;
begin
formatAsli := FormatSettings.DateSeparator;
FormatSettings.DateSeparator := '-';
myDate := StrToDate(strDate);
DateTimeToString(myDateStr, 'YYYY-MM-DD', myDate);
FormatSettings.DateSeparator := formatAsli;
Result := myDateStr;
end;
end.
|
unit frmShowScript;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TfShowScript = class(TForm)
Panel1: TPanel;
bbtnSave: TBitBtn;
bbtnClose: TBitBtn;
Memo1: TMemo;
lstScripts: TListBox;
Splitter1: TSplitter;
bbtnRefresh: TBitBtn;
procedure bbtnRefreshClick(Sender: TObject);
procedure lstScriptsDblClick(Sender: TObject);
procedure bbtnSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FLoadFileName: WideString;
procedure RefreshScriptsList;
public
{ Public declarations }
end;
var
fShowScript: TfShowScript;
implementation
uses
UnitConsts;
{$R *.dfm}
procedure TfShowScript.RefreshScriptsList;
var
sr: TSearchRec;
begin
lstScripts.Items.Clear;
if FindFirst(IDS_ScriptFilesPath + '*.ini', faAnyFile, sr) = 0 then
repeat
lstScripts.Items.Add(sr.Name);
until FindNext(sr) <> 0;
FindClose(sr);
end;
procedure TfShowScript.FormCreate(Sender: TObject);
begin
RefreshScriptsList;
end;
procedure TfShowScript.bbtnRefreshClick(Sender: TObject);
begin
RefreshScriptsList;
end;
procedure TfShowScript.lstScriptsDblClick(Sender: TObject);
begin
FLoadFileName := IDS_ScriptFilesPath + lstScripts.Items[lstScripts.ItemIndex];
self.Memo1.Lines.LoadFromFile(FLoadFileName);
end;
procedure TfShowScript.bbtnSaveClick(Sender: TObject);
begin
if Length(FLoadFileName) > 0 then
self.Memo1.Lines.SaveToFile(FLoadFileName);
end;
procedure TfShowScript.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) and (Key = Ord('A')) then
Memo1.SelectAll;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uMainForm;
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
System.UITypes,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs,
{$ENDIF}
uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFTypes, uCEFConstants,
Vcl.ExtCtrls;
type
TMainForm = class(TForm)
CEFWindowParent1: TCEFWindowParent;
Chromium1: TChromium;
Timer1: TTimer;
procedure Chromium1PreKeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out isKeyboardShortcut, Result: Boolean);
procedure Chromium1KeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out Result: Boolean);
procedure FormShow(Sender: TObject);
procedure Chromium1AfterCreated(Sender: TObject;
const browser: ICefBrowser);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
protected
procedure WMMove(var aMessage : TWMMove); message WM_MOVE;
procedure WMMoving(var aMessage : TMessage); message WM_MOVING;
procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP;
procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP;
procedure BrowserCreatedMsg(var aMessage : TMessage); message CEF_AFTERCREATED;
procedure HandleKeyUp(const aMsg : TMsg; var aHandled : boolean);
procedure HandleKeyDown(const aMsg : TMsg; var aHandled : boolean);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
uCEFApplication;
procedure TMainForm.HandleKeyUp(const aMsg : TMsg; var aHandled : boolean);
var
TempMessage : TMessage;
TempKeyMsg : TWMKey;
begin
TempMessage.Msg := aMsg.message;
TempMessage.wParam := aMsg.wParam;
TempMessage.lParam := aMsg.lParam;
TempKeyMsg := TWMKey(TempMessage);
if (TempKeyMsg.CharCode = VK_ESCAPE) then
begin
aHandled := True;
PostMessage(Handle, WM_CLOSE, 0, 0);
end;
end;
procedure TMainForm.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) and not(Chromium1.Initialized) then
Timer1.Enabled := True;
end;
procedure TMainForm.HandleKeyDown(const aMsg : TMsg; var aHandled : boolean);
var
TempMessage : TMessage;
TempKeyMsg : TWMKey;
begin
TempMessage.Msg := aMsg.message;
TempMessage.wParam := aMsg.wParam;
TempMessage.lParam := aMsg.lParam;
TempKeyMsg := TWMKey(TempMessage);
if (TempKeyMsg.CharCode = VK_ESCAPE) then aHandled := True;
end;
procedure TMainForm.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser);
begin
PostMessage(Handle, CEF_AFTERCREATED, 0, 0);
end;
procedure TMainForm.BrowserCreatedMsg(var aMessage : TMessage);
begin
CEFWindowParent1.UpdateSize;
end;
procedure TMainForm.Chromium1KeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out Result: Boolean);
var
TempMsg : TMsg;
begin
Result := False;
if (event <> nil) and (osEvent <> nil) then
case osEvent.Message of
WM_KEYUP :
begin
TempMsg := osEvent^;
HandleKeyUp(TempMsg, Result);
end;
WM_KEYDOWN :
begin
TempMsg := osEvent^;
HandleKeyDown(TempMsg, Result);
end;
end;
end;
procedure TMainForm.Chromium1PreKeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out isKeyboardShortcut, Result: Boolean);
begin
Result := False;
if (event <> nil) and
(event.kind in [KEYEVENT_KEYDOWN, KEYEVENT_KEYUP]) and
(event.windows_key_code = VK_ESCAPE) then
isKeyboardShortcut := True;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
Chromium1.DefaultUrl := 'https://www.google.com';
// GlobalCEFApp.GlobalContextInitialized has to be TRUE before creating any browser
// If it's not initialized yet, we use a simple timer to create the browser later.
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) then Timer1.Enabled := True;
end;
procedure TMainForm.WMMove(var aMessage : TWMMove);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TMainForm.WMMoving(var aMessage : TMessage);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TMainForm.WMEnterMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True;
end;
procedure TMainForm.WMExitMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False;
end;
end.
|
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* EXSMSPG0.PAS 4.06 *}
{*********************************************************}
{**********************Description************************}
{* Demonstrates how to use a GSM phone to send an SMS *)
(* message *}
{*********************************************************}
unit ExSMSPg0;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, AdPort, OoMisc, AdGSM, AdPacket;
type
TForm1 = class(TForm)
btnSend: TButton;
ApdGSMPhone1: TApdGSMPhone;
ApdComPort1: TApdComPort;
edtDestAddr: TEdit;
Label1: TLabel;
Label2: TLabel;
ListBox1: TListBox;
lblStatus: TLabel;
memMessage: TMemo;
Label3: TLabel;
btnConnect: TButton;
procedure btnSendClick(Sender: TObject);
procedure ApdGSMPhone1GSMComplete(Pager: TApdCustomGSMPhone;
State: TGSMStates; ErrorCode: Integer);
procedure memMessageChange(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnSendClick(Sender: TObject);
begin
ApdGSMPhone1.SMSAddress := edtDestAddr.Text;
ApdGSMPhone1.SMSMessage := memMessage.Text;
ListBox1.Items.Add('Preparing to send message');
ApdGSMPhone1.SendMessage;
end;
procedure TForm1.ApdGSMPhone1GSMComplete(Pager: TApdCustomGSMPhone;
State: TGSMStates; ErrorCode: Integer);
begin
if ErrorCode <> 0 then begin
ListBox1.Items.Add('Error number ' + IntToStr(ErrorCode));
exit;
end;
case State of
gsConfig: ListBox1.Items.Add('Configuration finished');
gsSend: ListBox1.Items.Add('Message was sent');
gsListAll: ListBox1.Items.Add('List all messages finished');
end;
end;
procedure TForm1.memMessageChange(Sender: TObject);
begin
Label3.Caption := 'Character count: ' + IntToStr(Length(memMessage.Text));
end;
procedure TForm1.btnConnectClick(Sender: TObject);
begin
ApdGSMPhone1.Connect;
end;
end.
|
unit UnitRegEdit;
interface
uses
StrUtils,windows,
MiniReg,
UnitFuncoesDiversas;
function ListarChaves(Str: widestring): widestring;
function ListarDados(Str: widestring): widestring;
function AdicionarDados(Str: widestring): boolean;
function AdicionarChave(Str: widestring): boolean;
function DeletarRegistro(Str: widestring): boolean;
function DeletarChave(Str: widestring): boolean;
function StrToHKEY(sKey: wideString): HKEY;
function RenameRegistryItem(AKey: HKEY; Old, New: wideString): boolean;
function RenameRegistryValue(AKey,
SubKey,
KeyType,
OldName,
ValueData,
NewName: widestring): boolean;
function RegWriteString(Key: HKey; SubKey: widestring; DataType: integer; Data: widestring; Value: widestring): boolean;
implementation
uses
UnitConstantes;
function StrToHKEY(sKey: wideString): HKEY;
begin
if sKey = 'HKEY_CLASSES_ROOT' then Result := HKEY_CLASSES_ROOT;
if sKey = 'HKEY_CURRENT_USER' then Result := HKEY_CURRENT_USER;
if sKey = 'HKEY_LOCAL_MACHINE' then Result := HKEY_LOCAL_MACHINE;
if sKey = 'HKEY_USERS' then Result := HKEY_USERS;
if sKey = 'HKEY_CURRENT_CONFIG' then Result := HKEY_CURRENT_CONFIG;
end;
function StrToKeyType(sKey: wideString): integer;
begin
if sKey = 'REG_DWORD' then Result := REG_DWORD;
if sKey = 'REG_BINARY' then Result := REG_BINARY;
if sKey = 'REG_EXPAND_SZ' then Result := REG_EXPAND_SZ;
if sKey = 'REG_MULTI_SZ' then Result := REG_MULTI_SZ;
if sKey = 'REG_SZ' then Result := REG_SZ;
end;
function RegWriteString(Key: HKey; SubKey: widestring; DataType: integer; Data: widestring; Value: widestring): boolean;
var
RegKey: HKey;
Arr: array of Byte;
i: integer;
begin
if DataType = REG_BINARY then
begin
setlength(arr, length(value));
for I := 0 to length(value) - 1 do
arr[i] := byte(value[i + 1]);
RegCreateKeyW(Key, pwidechar(SubKey), RegKey);
result := RegSetValueExW(RegKey, pwidechar(Data), 0, DataType, arr, Length(Value)) = 0;
RegCloseKey(RegKey);
end else
begin
RegCreateKeyW(Key, pwidechar(SubKey), RegKey);
result := RegSetValueExW(RegKey, pwidechar(Data), 0, DataType, pWideChar(Value), Length(Value) * 2) = 0;
RegCloseKey(RegKey);
end;
end;
function ListarChaves(Str: widestring): widestring;
var
Hkey, SubKey: widestring;
begin
result := '';
Hkey := Copy(Str, 1, posex('\', Str) - 1);
delete(str, 1, posex('\', Str));
SubKey := Str;
if RegEnumKeys(strtohkey(HKEY), SubKey, Result) = false then result := '';
end;
function ListarDados(Str: widestring): widestring;
var
Hkey, SubKey: widestring;
begin
result := '';
Hkey := Copy(Str, 1, posex('\', Str) - 1);
delete(str, 1, posex('\', Str));
SubKey := Str;
if RegEnumValues(strtohkey(HKEY), SubKey, Result) = false then result := '';
end;
function IntToStr(i: Int64): wideString;
begin
Str(i, Result);
end;
function StrToInt(S: wideString): Int64;
var
E: integer;
begin
Val(S, Result, E);
end;
function AdicionarDados(Str: widestring): boolean;
var
TempStr: widestring;
Hkey, SubKey, Nome, Tipo, Dados: widestring;
begin
Result := false;
TempStr := Copy(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, length(delimitadorComandos));
Hkey := Copy(TempStr, 1, posex('\', TempStr) - 1);
delete(TempStr, 1, posex('\', TempStr));
SubKey := TempStr;
if SubKey[length(subkey)] <> '\' then SubKey := SubKey + '\';
Nome := Copy(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, length(delimitadorComandos));
Tipo := Copy(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, length(delimitadorComandos));
Dados := Str;
if StrToKeyType(Tipo) = REG_DWORD then
begin
result := MiniReg.RegSetDWORD(strtohkey(HKEY), SubKey + Nome, strtoint(Dados));
Exit;
end;
result := RegWriteString(strtohkey(HKEY), SubKey, StrToKeyType(Tipo), Nome, Dados);
end;
function AdicionarChave(Str: widestring): boolean;
var
TempStr: widestring;
Hkey, SubKey, Nome: widestring;
begin
Result := false;
TempStr := Copy(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, length(delimitadorComandos));
Hkey := Copy(TempStr, 1, posex('\', TempStr) - 1);
delete(TempStr, 1, posex('\', TempStr));
SubKey := TempStr;
Nome := Str;
Result := MiniReg._regCreateKey(strtohkey(HKEY), pwidechar(SubKey + Nome));
end;
function SHDeleteKey(key: HKEY; SubKey: Pwidechar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW';
function SHDeleteValue(key: HKEY; SubKey, value :Pwidechar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteValueW';
function DeletarRegistro(Str: widestring): boolean;
var
TempStr: widestring;
Hkey, SubKey, Nome: widestring;
begin
Result := false;
TempStr := Copy(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, posex(delimitadorComandos, str) - 1);
Delete(Str, 1, length(delimitadorComandos));
Hkey := Copy(TempStr, 1, posex('\', TempStr) - 1);
delete(TempStr, 1, posex('\', TempStr));
SubKey := TempStr;
Nome := Str;
Result := SHDeleteValue(strtohkey(HKEY), pwidechar(SubKey), Pwidechar(Nome)) = ERROR_SUCCESS;
end;
function DeletarChave(Str: widestring): boolean;
var
Hkey, SubKey: widestring;
begin
Result := false;
Hkey := Copy(Str, 1, posex('\', Str) - 1);
delete(Str, 1, posex('\', Str));
SubKey := Str;
result := SHDeleteKey(strtohkey(HKEY), pwidechar(SubKey)) = ERROR_SUCCESS;
end;
function AllocMem(Size: Cardinal): Pointer;
begin
GetMem(Result, Size);
FillChar(Result^, Size, 0);
end;
function RegEnumValueW(hKey: HKEY; dwIndex: DWORD; lpValueName: PWideChar;
var lpcbValueName: DWORD; lpReserved: Pointer; lpType: PDWORD;
lpData: PByte; lpcbData: PDWORD): Longint; stdcall; external 'advapi32.dll' name 'RegEnumValueW';
procedure CopyRegistryKey(Source, Dest: HKEY);
const
DefValueSize = 512;
DefBufferSize = 8192;
var
Status: Integer;
Key: Integer;
ValueSize,
BufferSize: Cardinal;
KeyType: Integer;
ValueName: wideString;
Buffer: Pointer;
NewTo,
NewFrom: HKEY;
begin
SetLength(ValueName, DefValueSize);
Buffer := AllocMem(DefBufferSize);
try
Key := 0;
repeat
ValueSize := DefValueSize;
BufferSize := DefBufferSize;
// enumerate data values at current key
Status := RegEnumValueW(Source, Key, PWideChar(ValueName), ValueSize, nil, @KeyType, Buffer, @BufferSize);
if Status = ERROR_SUCCESS then
begin
// move each value to new place
Status := RegSetValueExW(Dest, PWideChar(ValueName), 0, KeyType, Buffer, BufferSize);
// delete old value
RegDeleteValueW(Source, PWideChar(ValueName));
end;
until Status <> ERROR_SUCCESS; // Loop until all values found
// start over, looking for keys now instead of values
Key := 0;
repeat
ValueSize := DefValueSize;
BufferSize := DefBufferSize;
Status := RegEnumKeyExW(Source, Key, PWideChar(ValueName), ValueSize, nil, Buffer, @BufferSize, nil);
// was a valid key found?
if Status = ERROR_SUCCESS then
begin
// open the key if found
Status := RegCreateKeyW(Dest, PWideChar(ValueName), NewTo);
if Status = ERROR_SUCCESS then
begin // Create new key of old name
Status := RegCreateKeyW(Source, PWideChar(ValueName), NewFrom);
if Status = ERROR_SUCCESS then
begin
// if that worked, recurse back here
CopyRegistryKey(NewFrom, NewTo);
RegCloseKey(NewFrom);
RegDeleteKeyW(Source, PWideChar(ValueName));
end;
RegCloseKey(NewTo);
end;
end;
until Status <> ERROR_SUCCESS; // loop until key enum fails
finally
FreeMem(Buffer);
end;
end;
function RenameRegistryItem(AKey: HKEY; Old, New: wideString): boolean;
var
OldKey,
NewKey: HKEY;
Status: Integer;
begin
Result := false;
// Open Source key
Status := RegOpenKeyW(AKey,PwideChar(Old), OldKey);
if Status = ERROR_SUCCESS then
begin
// Create Destination key
Status := RegCreateKeyW(AKey,PwideChar(New), NewKey);
if Status = ERROR_SUCCESS then
begin
CopyRegistryKey(OldKey, NewKey);
Result := true;
end;
RegCloseKey(OldKey);
RegCloseKey(NewKey);
// Delete last top-level key
RegDeleteKeyW(AKey, PWideChar(Old));
end;
end;
function RenameRegistryValue(AKey,
SubKey,
KeyType,
OldName,
ValueData,
NewName: widestring): boolean;
var
TempStr: widestring;
begin
result := false;
if SHDeleteValue(strtohkey(AKey), pwidechar(SubKey), Pwidechar(OldName)) <> ERROR_SUCCESS then exit;
if AKey[length(AKey)] <> '\' then AKey := AKey + '\';
TempStr := AKey + SubKey + delimitadorComandos +
NewName + delimitadorComandos +
KeyType + delimitadorComandos +
ValueData;
result := AdicionarDados(TempStr);
end;
initialization
LoadLibrary('shlwapi.dll');
end.
|
unit Lib.HTTPConsts;
interface
const
HTTP_PORT = 80;
HTTPS_PORT = 443;
CRLF = #13#10;
CRLF2 = CRLF+CRLF;
PROTOCOL_HTTP11 = 'HTTP/1.1';
METHOD_GET = 'GET';
METHOD_POST = 'POST';
SCHEME_HTTP = 'http';
SCHEME_HTTPS = 'https';
HTTPCODE_SUCCESS = 200;
HTTPCODE_MOVED_PERMANENTLY = 301;
HTTPCODE_FOUND = 302;
HTTPCODE_BAD_REQUEST = 400;
HTTPCODE_NOT_FOUND = 404;
HTTPCODE_METHOD_NOT_ALLOWED = 405;
HTTPCODE_NOT_SUPPORTED = 505;
content_404 =
'<html>'+CRLF+
'<head><title>404 Not Found</title></head>'+CRLF+
'<body bgcolor="white">'+CRLF+
'<center><h1>404 Not Found</h1></center>'+CRLF+
'<hr><center>server</center>'+CRLF+
'</body>'+CRLF+
'</html>';
MIME_Types: array of string = [
'.txt' ,'text/plain',
'.html','text/html',
'.css' ,'text/css',
'.csv' ,'text/csv',
'.xml' ,'text/xml',
'.jpeg','image/jpeg',
'.jpg' ,'image/jpeg',
'.gif' ,'image/gif',
'.svg' ,'image/svg+xml',
'.png' ,'image/png',
'.ico' ,'image/vnd.microsoft.icon',
'.json','application/json',
'.pdf' ,'application/pdf',
'.zip' ,'application/zip',
'.js' ,'application/javascript',
'' ,'application/octet-stream',
'' ,'application/x-www-form-urlencoded',
'.mpeg','video/mpeg',
'.mp4' ,'video/mp4',
'.wmv' ,'video/x-ms-wmv',
'.flv' ,'video/x-flv',
'.avi' ,'video/x-msvideo'];
implementation
end.
|
unit GraphObjects;
{
Graphical objects and modification routines as part of my Voronoi algorithm
Copyright (C) 2002 Christian Huettig
Released: 08/08/2002
Restrictions: None
Contact: snakers@gmx.net
This source is free; you can redistribute it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This source is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program;
if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
interface
uses
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Dialogs,
Vcl.Forms,
Vcl.Graphics;
type
TRGB = packed record // Varianten record to mix colors fast
case boolean of
true:
(Color: LongWord); // 32bit Color value (like TColor)
false:
(R, G, B, A: Byte); // 8bit RGBA split, alpha isn't used
end;
TGLineState = (TwoPoint, OnePoint, Vector);
// |------|, |----->, <---|------|----> (Vector isn't the right name, its an endless line in both directions marked through two point)
// Graphical Objects
TGraphObject = class // Base object for all drawable elements + management
private
orig_index: integer;
// Index of list at create time (movetolist and clonetolist don't change this index, only set on create
index: integer; // Index of current list
List: TList;
// Current list, can only be changed through movetolist or clonetolist
Canvas: TCanvas;
protected
constructor Create(L: TList; C: TCanvas);
public
Color: TRGB;
procedure MoveToList(L: TList);
procedure CopyToList(L: TList);
// same as move, but now the object is on more than one list. careful, because index is left on old list !
function CloneToList(L: TList): TGraphObject;
// Creates a new object and moves it to L
function GetIndex: integer;
function GetOrigIndex: integer;
// returns the index of the list were it was created
procedure Delete(orig: boolean);
// orig=true means that the object is in its "original" list. now reindexes also orig_index
procedure SetCanvas(C: TCanvas);
function GetCanvas: TCanvas;
procedure ReIndex(orig: boolean); overload;
// slow reindex by searching the list for "self"
procedure ReIndex(orig: boolean; i: integer); overload;
// fast reindex with validation
procedure Draw; virtual; abstract;
procedure Clear; virtual; abstract;
function Clone: TGraphObject; virtual; abstract;
end;
TGPoint = class; // forward declaration, with seperate units impossible !
TGLine = class(TGraphObject)
private
state: TGLineState; // see above
d, dx, dy: extended; // d=distance, dx,dy=delta
ix, iy, t, R: extended;
// ex,ey=unity vector, ix,iy=crosspoint(set after Intersect), t,r=distances to ipoint
procedure initialize; // evaluates all constants if line has changed
public
p1, p2: TGPoint;
ex, ey: extended; // Unity vector of the line
BisectorOf: array [1 .. 2] of integer;
// The orig_index of the points from which this line is the bisector. -1 if none
constructor Create(p1_, p2_: TGPoint; s: TGLineState; L: TList; C: TCanvas);
function Clone: TGraphObject; override;
procedure Draw; override;
procedure Clear; override;
function GetState: TGLineState;
function Intersect(ln: TGLine): boolean;
procedure GetCurrentIPoint(var x, y: extended); overload;
// copies ix and iy. only valid after intersect() call !
procedure GetCurrentIPoint(var p: TGPoint); overload;
// copies ix and iy to a point. only valid after intersect() call !
procedure CutRight(ln: TGLine); // Cuts the line right on ln
procedure CutLeft(ln: TGLine);
procedure CutBoth(ln: TGLine);
end;
TGPoint = class(TGraphObject)
private
x, y: extended;
public
closeDist: extended;
// distance to point for MatchPoint=true (0=exact match)
constructor Create(x_, y_: extended; L: TList; C: TCanvas);
function Clone: TGraphObject; override;
procedure Draw; override;
procedure Clear; override;
function getX: extended;
function getY: extended;
function DistanceTo(p: TGPoint): extended; overload;
function DistanceTo(x_, y_: extended): extended; overload;
procedure MoveTo(x_, y_: extended);
function Match(p: TGPoint): boolean; overload;
function Match(x_, y_: extended): boolean; overload;
function Angle(p: TGPoint): extended;
// required for the convex hull (preparata-hong)
function IsRightTurn(p1, p2: TGPoint): boolean;
// required for Graham scan (discarded, but left for further use)
function areCollinear(A, B: TGPoint): boolean;
function Bisector(p: TGPoint): TGLine;
// Creates a line and sets BisectorOf[1..2]
function CircleCenter(A, B: TGPoint): TGPoint; // never used
end;
implementation
uses
main;
// to keep me from getting insane, i splitted this giant.
// Hint: Press Ctrl+Enter while the cursor is on the filename to open it.
{$I GraphObject.pas}
{$I Line.pas}
{$I Point.pas}
end.
|
unit Chat_Frm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, SIPVoipSDK_TLB, Vcl.ImgList;
type
TFrameChat = class(TFrame)
pnl1: TPanel;
Grid: TGridPanel;
ButtonSend: TSpeedButton;
SpeedButtonRead: TSpeedButton;
SpeedButtonWrite: TSpeedButton;
ListBoxMessages: TListBox;
MemoMessage: TMemo;
Panel2: TPanel;
ImageList: TImageList;
ButtonClose: TSpeedButton;
procedure ButtonCloseClick(Sender: TObject);
private
pUserName : string;
pUserId : string;
procedure CMRelease(var Message: TMessage); message CM_RELEASE;
public
procedure Release;
procedure Load(Phone: TCAbtoPhone);
constructor Create(AOwner: TComponent); override;
property gUserName : string read pUserName write pUserName;
property gUserId : string read pUserId write pUserName;
end;
var
AbtoPhone : TCAbtoPhone;
implementation
{$R *.dfm}
procedure TFrameChat.ButtonCloseClick(Sender: TObject);
begin
//
end;
procedure TFrameChat.CMRelease(var Message: TMessage);
begin
Free;
end;
constructor TFrameChat.Create(AOwner: TComponent);
var
Bitmap : TBitmap;
begin
inherited;
ButtonClose.Caption := '';
Bitmap := TBitmap.Create();
ImageList.GetBitmap(0,Bitmap);
ButtonClose.Glyph.Assign(Bitmap);
end;
procedure TFrameChat.Load(Phone: TCAbtoPhone);
begin
AbtoPhone := Phone;
end;
procedure TFrameChat.Release;
begin
PostMessage(Handle, CM_RELEASE, 0, 0);
end;
end.
|
unit Objekt.Ini;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
Allgemein.SysFolderlocation, Allgemein.Types, Allgemein.RegIni, shellapi;
type
TIni = class
private
fUserPfad: string;
fIniFilename: string;
function getUserPfad: string;
function getIniFilename: string;
function getAuthentication_User: string;
procedure setAuthentication_User(const Value: string);
function getAuthentication_Password: string;
procedure setAuthentication_Password(const Value: string);
function getcis_User: string;
procedure setcis_User(const Value: string);
function getcis_Password: string;
procedure setcis_Password(const Value: string);
function getUrl: string;
procedure setUrl(const Value: string);
public
property UserPfad: string read getUserPfad;
property IniFilename: string read getIniFilename;
constructor Create;
destructor Destroy; override;
property Authentication_User: string read getAuthentication_User write setAuthentication_User;
property Authentication_Password: string read getAuthentication_Password write setAuthentication_Password;
property cis_User: string read getcis_User write setcis_User;
property cis_Password: string read getcis_Password write setcis_Password;
property Url: string read getUrl write setUrl;
end;
implementation
{ TIni }
constructor TIni.Create;
begin
fUserPfad := '';
fIniFilename := '';
end;
destructor TIni.Destroy;
begin
inherited;
end;
function TIni.getIniFilename: string;
begin
Result := fIniFilename;
if Result = '' then
Result := getUserPfad + 'Paketversand.Ini';
fIniFilename := Result;
end;
function TIni.getUserPfad: string;
begin
Result := fUserPfad;
if Result = '' then
begin
Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
fUserPfad := Result;
if not DirectoryExists(fUserPfad) then
ForceDirectories(fUserPfad);
end;
end;
procedure TIni.setAuthentication_User(const Value: string);
begin
writeIni(IniFilename, 'Einstellung', 'Authentication_User', Value);
end;
function TIni.getAuthentication_User: string;
begin
Result := ReadIni(IniFilename, 'Einstellung', 'Authentication_User', '');
end;
procedure TIni.setAuthentication_Password(const Value: string);
begin
writeIni(IniFilename, 'Einstellung', 'Authentication_Password', Value);
end;
function TIni.getAuthentication_Password: string;
begin
Result := ReadIni(IniFilename, 'Einstellung', 'Authentication_Password', '');
end;
procedure TIni.setcis_User(const Value: string);
begin
writeIni(IniFilename, 'Einstellung', 'cis_User', Value);
end;
function TIni.getcis_User: string;
begin
Result := ReadIni(IniFilename, 'Einstellung', 'cis_User', '');
end;
procedure TIni.setcis_Password(const Value: string);
begin
writeIni(IniFilename, 'Einstellung', 'cis_Password', Value);
end;
function TIni.getcis_Password: string;
begin
Result := ReadIni(IniFilename, 'Einstellung', 'cis_Password', '');
end;
procedure TIni.setUrl(const Value: string);
begin
writeIni(IniFilename, 'Einstellung', 'Url', Value);
end;
function TIni.getUrl: string;
begin
Result := ReadIni(IniFilename, 'Einstellung', 'Url', '');
end;
end.
|
unit View.Samples;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Mail4Delphi.Intf, Mail4Delphi.Default;
type
TFrmSamples = class(TForm)
Panel2: TPanel;
Label3: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label16: TLabel;
Label17: TLabel;
Label1: TLabel;
Label4: TLabel;
cbCriptocrafia: TComboBox;
edtUserName: TEdit;
edtPassword: TEdit;
edtHost: TEdit;
edtPort: TEdit;
edtFrom: TEdit;
cbAuth: TComboBox;
edtNameFrom: TEdit;
chkReceiptRecipient: TCheckBox;
pnlHeaderConfiguracaoEmail: TPanel;
Panel3: TPanel;
Label2: TLabel;
Label18: TLabel;
Label19: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
edtTo: TEdit;
mmBody: TMemo;
edtNameTo: TEdit;
edtSubject: TEdit;
Panel1: TPanel;
edtCc: TEdit;
edtNomeCc: TEdit;
edtCco: TEdit;
edtNomeCco: TEdit;
lbAnexo: TListBox;
btnEnviar: TButton;
btnAnexar: TButton;
procedure btnAnexarClick(Sender: TObject);
procedure btnEnviarClick(Sender: TObject);
procedure lbAnexoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
end;
implementation
{$R *.dfm}
procedure TFrmSamples.btnAnexarClick(Sender: TObject);
var
LOpenDialog: TFileOpenDialog;
begin
LOpenDialog := TFileOpenDialog.Create(Self);
try
LOpenDialog.Options := [fdoAllowMultiSelect];
LOpenDialog.DefaultFolder := ExtractFilePath(Application.ExeName);
if LOpenDialog.Execute then
lbAnexo.Items.AddStrings(LOpenDialog.Files);
finally
LOpenDialog.Free;
end;
end;
procedure TFrmSamples.btnEnviarClick(Sender: TObject);
var
LMail: IMail;
I: Integer;
begin
LMail := TMail.New
.AddFrom(edtFrom.Text, edtNameFrom.Text)
.SSL(cbCriptocrafia.ItemIndex = 0)
.Host(edtHost.Text)
.Port(StrToInt(edtPort.Text))
.Auth(cbAuth.ItemIndex = 1)
.UserName(edtUserName.Text)
.Password(edtPassword.Text)
.ReceiptRecipient(chkReceiptRecipient.Checked)
.AddCC(edtCc.Text, edtNomeCc.Text)
.AddBCC(edtCco.Text, edtNomeCco.Text)
.AddTo(edtTo.Text, edtNameTo.Text)
.AddSubject(edtSubject.Text)
.AddBody(mmBody.Text);
if lbAnexo.Items.Count > 0 then
for I := 0 to Pred(lbAnexo.Items.Count) do
LMail.AddAttachment(lbAnexo.Items[I]);
if LMail.SendMail then
ShowMessage('Email enviado com sucesso!');
end;
procedure TFrmSamples.lbAnexoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
I: Integer;
begin
if Key = VK_DELETE then
begin
for I := Pred(lbAnexo.Items.Count) downto 0 do
if lbAnexo.Selected[I] then
lbAnexo.Items.Delete(I);
end;
end;
end.
|
Unit uDownloadFunctions;
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
IdComponent, idFTP, IdTCPConnection, IdTCPClient,
StdCtrls, UrlMon, Forms, ComCtrls, ShellApi, ActiveX;
Type
{ Types }
EServerType = ( stNone, stFTP, stHTTP );
{ Exceções }
EServerTypeNotSet = class( Exception );
EDirectoryDoesNotExist = class( Exception );
{ Fazer interface de callback para o download }
TDownloadInterface = class(TInterfacedObject, IBindStatusCallback)
private
Public
FCallBackProgressBar : TProgressBar;
FCallBackLabel: TLabel;
Function OnStartBinding(dwReserved: DWORD; pib: IBinding): HResult; stdcall;
Function GetPriority(out nPriority): HResult; stdcall;
Function OnLowResource(reserved: DWORD): HResult; stdcall;
Function OnProgress(ulProgress, ulProgressMax, ulStatusCode: ULONG;szStatusText: LPCWSTR): HResult; stdcall;
Function OnStopBinding(hresult: HResult; szError: LPCWSTR): HResult; stdcall;
Function GetBindInfo(out grfBINDF: DWORD; var bindinfo: TBindInfo): HResult; stdcall;
Function OnDataAvailable(grfBSCF: DWORD; dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium): HResult; stdcall;
Function OnObjectAvailable(const iid: TGUID; punk: IUnknown): HResult; stdcall;
End;
TDownloadFile = class( TObject )
Private
FCallBackProgressBar : TProgressBar;
FCallBackLabel: TLabel;
FSource: String;
FDestination: String;
FServerType: EServerType;
FUserName: String;
FHost: String;
FPassword: String;
procedure SetCallBackProgressBar( const Value : TProgressBar );
procedure SetCallBackLabel(const Value: TLabel);
procedure SetSource(const Value: String);
procedure SetDestination(const Value: String);
procedure SetServerType(const Value: EServerType);
Procedure OnFTPClientWorkBegin( Sender : TObject; AWorkMode : TWorkMode; Const AWorkCountMax : Integer );
Procedure OnFTPClientWork( ASender: TObject; AWorkMode: TWorkMode; Const AWorkCount : Integer );
Procedure Validate();
Function DownloadFileFromFTP() : Boolean;
procedure SetHost(const Value: String);
procedure SetPassword(const Value: String);
procedure SetUserName(const Value: String);
Public
Property ServerType : EServerType read FServerType write SetServerType;
Property Source : String read FSource write SetSource;
Property Destination : String read FDestination write SetDestination;
Property Host : String read FHost write SetHost;
Property UserName : String read FUserName write SetUserName;
Property Password : String read FPassword write SetPassword;
Property CallBackLabel : TLabel read FCallBackLabel write SetCallBackLabel;
Property CallBackProgressBar : TProgressBar read FCallBackProgressBar write SetCallBackProgressBar;
Constructor Create(); OverLoad;
Destructor Destroy(); OverLoad;
Function Start() : Boolean;
End;
Implementation
{==============================================================================}
{ TDownloadInterface }
Function TDownloadInterface.GetBindInfo(out grfBINDF: DWORD; var bindinfo: TBindInfo): HResult;
Begin
End;
Function TDownloadInterface.GetPriority(out nPriority): HResult;
Begin
End;
Function TDownloadInterface.OnDataAvailable(grfBSCF, dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium): HResult;
Begin
End;
Function TDownloadInterface.OnLowResource(reserved: DWORD): HResult;
Begin
End;
Function TDownloadInterface.OnObjectAvailable(const iid: TGUID; punk: IInterface): HResult;
Begin
End;
Function TDownloadInterface.OnProgress(ulProgress, ulProgressMax, ulStatusCode: ULONG; szStatusText: LPCWSTR): HResult;
Begin
If ( Assigned( FCallBackProgressBar ) ) Then Begin
Application.ProcessMessages;
Case ulStatusCode Of
// 1: FrPrincipal.StaticText1.Caption := 'Conectando em: ' + szStatusText;
// 2: FrPrincipal.StaticText1.Caption := 'Conectado em: ' + szStatusText;
// 3: FrPrincipal.StaticText1.Caption := 'Redirecionando para: ' + szStatusText;
4: Begin
//FrPrincipal.StaticText1.Caption := 'Fazendo Download: ' + szStatusText;
//FrPrincipal.barra.MaxValue := ulProgressMax;
//FrPrincipal.barra.Progress := ulProgressMax - ulProgress;
FCallBackProgressBar.Max := ulProgressMax;
End;
5: Begin
FCallBackProgressBar.Position := ulProgress;
//FrPrincipal.StaticText2.Caption := 'Baixando: ' + FormatFloat('#.#,', ulProgress div 1024) + ' de ' +
// FormatFloat('#.#,', ulProgressMax div 1024) + 'Kb';
//FrPrincipal.barra.MaxValue := ulProgressMax;
//// FrPrincipal.barra.Progress := ulProgressMax - ulProgress; // descomente este para fazer decrecente
//FrPrincipal.barra.Progress := ulProgress;
End;
6: Begin
FCallBackProgressBar.Position := 0;
//FrPrincipal.StaticText1.Caption := 'Final de Download: ' + szStatusText;
//
//FrPrincipal.StaticText2.Caption := 'Baixando: ' +
// FormatFloat('#.#,', ulProgressMax div 1024) + ' de ' +
// FormatFloat('#.#,', ulProgressMax div 1024) + 'Kb';
End;
End; { Case }
End; { If ( Assigned( FCallBackProgressBar ) ) Then Begin }
End; { TDownloadInterface.OnProgress }
Function TDownloadInterface.OnStartBinding(dwReserved: DWORD; pib: IBinding): HResult;
Begin
End;
Function TDownloadInterface.OnStopBinding(hresult: HResult; szError: LPCWSTR): HResult;
Begin
End;
{==============================================================================}
{ TDownloadFile }
Constructor TDownloadFile.Create();
Begin
Inherited;
FServerType := stNone;
End; { Create }
Destructor TDownloadFile.Destroy;
Begin
Inherited;
End; { Destroy }
Procedure TDownloadFile.SetCallBackLabel(const Value: TLabel);
Begin
FCallBackLabel := Value;
End;
Procedure TDownloadFile.SetCallBackProgressBar( const Value: TProgressBar );
Begin
FCallBackProgressBar := Value;
End;
Procedure TDownloadFile.SetSource(const Value: String);
Begin
FSource := Value;
End;
Procedure TDownloadFile.SetServerType(const Value: EServerType);
Begin
FServerType := Value;
End;
Procedure TDownloadFile.SetDestination(const Value: String);
Begin
FDestination := Value;
End;
Procedure TDownloadFile.SetHost(const Value: String);
Begin
FHost := Value;
End;
Procedure TDownloadFile.SetPassword(const Value: String);
Begin
FPassword := Value;
End;
Procedure TDownloadFile.SetUserName(const Value: String);
Begin
FUserName := Value;
End;
Procedure TDownloadFile.OnFTPClientWorkBegin( Sender : TObject; AWorkMode : TWorkMode; Const AWorkCountMax : Integer );
Begin
If ( Assigned( FCallBackProgressBar ) ) Then FCallBackProgressBar.Max := AWorkCountMax;
End; { OnFTPClientWorkBegin }
Procedure TDownloadFile.OnFTPClientWork( ASender: TObject; AWorkMode : TWorkMode; Const AWorkCount : Integer );
Begin
If ( Assigned( FCallBackProgressBar ) ) Then Begin
Application.ProcessMessages;
FCallBackProgressBar.Position := AWorkCount;
End; { If ( Assigned( FCallBackProgressBar ) ) Then Begin }
End; { OnFTPClientWork( }
Procedure TDownloadFile.Validate;
Begin
If ( ServerType = stNone ) Then Raise EServerTypeNotSet.Create( 'Server type not set' );
If ( Not DirectoryExists( ExtractFilePath( FDestination ) ) ) Then Raise EDirectoryDoesNotExist.Create( 'Destination folder does not exist' );
End; { Validate }
Function TDownloadFile.Start() : Boolean;
Var
DownloadInterface : TDownloadInterface;
lpszFile : Array [0..MAX_PATH] of Char;
Begin
//If Pos('MANIF', FSource ) <= 0 Then Begin
// Result := True;
// Exit;
//End;
Result := False;
DownloadInterface := TDownloadInterface.Create();
DownloadInterface.FCallBackProgressBar := Self.FCallBackProgressBar;
Validate();
If ( FServerType = stHTTP ) Then Begin
{ Use URLDownloadToCacheFile function to ignore the cache with BINDF_GETNEWESTVERSION option }
//Result := UrlDownloadToFile( Nil, PChar( FSource ), PChar( FDestination ), 0, DownloadInterface ) = 0
If ( URLDownloadToCacheFile( Nil, PChar( FSource ), @lpszFile, MAX_PATH, BINDF_GETNEWESTVERSION, DownloadInterface ) = S_OK )
Then Result := CopyFile( @lpszFile, PChar( FDestination ), False )
End Else Begin
Result := DownloadFileFromFTP();
End;
DownloadInterface.FCallBackLabel := Nil;
DownloadInterface.FCallBackProgressBar := Nil;
Try If ( DownloadInterface <> Nil ) Then FreeAndNil( DownloadInterface ) Except End;
End;
Function TDownloadFile.DownloadFileFromFTP : Boolean;
Var
idFTPClient : TIdFTP;
Begin
idFTPClient := TIdFTP.Create( TComponent( Self ) );
idFTPClient.OnWorkBegin := OnFTPClientWorkBegin;
idFTPClient.OnWork := OnFTPClientWork;
idFTPClient.Disconnect();
idFTPClient.Host := FHost;
idFTPClient.Port := 21;
idFTPClient.Username := FUserName;
idFTPClient.Password := FPassword;
idFTPClient.Passive := false; { usa modo ativo }
idFTPClient.Connect();
idFTPClient.ChangeDir( ExtractFilePath( FSource ) );
idFTPClient.Get( FSource, FDestination, True);
idFTPClient.Disconnect();
FreeAndNil( idFTPClient );
Result := True;
End; { DownloadFileFromFTP }
End.
|
unit uHTTPReader;
interface
uses
Classes, IdHTTP;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
type
tHTTPReaderThread = class(TThread)
private
fHTTP : TIdHTTP;
fURL : string;
fRunning : Boolean;
fFrequency : Cardinal;
fOutput : string;
procedure SetFrequency( Value : Cardinal );
procedure OutputText;
protected
procedure Execute; override;
public
constructor Create( CreateSuspended : boolean = false ); reintroduce;
destructor Destroy; override;
property URL : string read fURL write fURL;
property Running : boolean read fRunning write fRunning;
property Frequency : Cardinal read fFrequency write SetFrequency;
end;
var
HTTPReaderThread : tHTTPReaderThread;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
implementation
uses
Windows,
uTest;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
constructor tHTTPReaderThread.Create( CreateSuspended : boolean = false );
begin
fURL := '';
fRunning := false;
fOutput := '';
fFrequency := 250;
inherited;
fHTTP := TIdHTTP.Create;
fHTTP.ConnectTimeout := 500;
end;
destructor tHTTPReaderThread.Destroy;
begin
fHTTP.free;
inherited;
end;
procedure tHTTPReaderThread.Execute;
var
S : string;
begin
while NOT Terminated do
begin
if NOT fRunning OR ( fURL = '' ) then
begin
Sleep( 500 );
Continue;
end;
try
S := fHTTP.Get( fURL );
except
S := '';
end;
if ( s <> '' ) then
begin
fOutput := s;
Synchronize( OutputText );
end;
Sleep( fFrequency );
end;
end;
procedure tHTTPReaderThread.SetFrequency( Value : Cardinal );
begin
if NOT Assigned( self ) then
Exit;
if ( fFrequency = Value ) then
Exit;
if ( fFrequency < 1 ) OR ( fFrequency > 5*60000 ) then
Exit;
fFrequency := Value;
end;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
procedure tHTTPReaderThread.OutputText; // Synchronized since its probably accessing VCL ..
begin
Form1.Memo1.Lines.Add( fOutput );
fOutput := '';
end;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TerminateAndFree;
begin
if NOT Assigned( HTTPReaderThread ) then
Exit;
if NOT HTTPReaderThread.Terminated then
begin
HTTPReaderThread.Terminate;
while NOT HTTPReaderThread.Terminated do
Sleep( 10 );
HTTPReaderThread.free;
end;
end;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
initialization
HTTPReaderThread := tHTTPReaderThread.Create( false );
finalization
TerminateAndFree;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
end.
|
{ Wsynchro contient
- syncObjs de Delphi version 4
- l'objet TMultiReadExclusiveWriteSynchronizer qui se trouve
dans sysutils de Delphi version 4
}
unit Wsynchro;
interface
uses Sysutils, Windows, Messages, Classes;
type
TSynchroObject = class(TObject)
public
procedure Acquire; virtual;
procedure Release; virtual;
end;
THandleObject = class(TSynchroObject)
private
FHandle: THandle;
FLastError: Integer;
public
destructor Destroy; override;
property LastError: Integer read FLastError;
property Handle: THandle read FHandle;
end;
TWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError);
TEvent = class(THandleObject)
public
constructor Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string);
function WaitFor(Timeout: DWORD): TWaitResult;
procedure SetEvent;
procedure ResetEvent;
end;
TSimpleEvent = class(TEvent)
public
constructor Create;
end;
TCriticalSection = class(TSynchroObject)
private
FSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Acquire; override;
procedure Release; override;
procedure Enter;
procedure Leave;
end;
{ Thread synchronization }
{ TMultiReadExclusiveWriteSynchronizer minimizes thread serialization to gain
read access to a resource shared among threads while still providing complete
exclusivity to callers needing write access to the shared resource.
(multithread shared reads, single thread exclusive write)
Reading is allowed while owning a write lock.
Read locks can be promoted to write locks.}
type
TActiveThreadRecord = record
ThreadID: Integer;
RecursionCount: Integer;
end;
TActiveThreadArray = array[0..99] of TActiveThreadRecord;
{ ŕ l'origine, on avait array of TActiveThreadRecord; }
TMultiReadExclusiveWriteSynchronizer = class
private
FLock: TRTLCriticalSection;
FReadExit: THandle;
FCount: Integer;
FSaveReadCount: Integer;
FActiveThreads: TActiveThreadArray;
FWriteRequestorID: Integer;
FReallocFlag: Integer;
FWriting: Boolean;
FTlen:integer; {ajouté}
function WriterIsOnlyReader: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure BeginRead;
procedure EndRead;
procedure BeginWrite;
procedure EndWrite;
end;
implementation
{ TSynchroObject }
procedure TSynchroObject.Acquire;
begin
end;
procedure TSynchroObject.Release;
begin
end;
{ THandleObject }
destructor THandleObject.Destroy;
begin
CloseHandle(FHandle);
inherited Destroy;
end;
{ TEvent }
constructor TEvent.Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string);
begin
FHandle := CreateEvent(EventAttributes, ManualReset, InitialState, PChar(Name));
end;
function TEvent.WaitFor(Timeout: DWORD): TWaitResult;
begin
case WaitForSingleObject(Handle, Timeout) of
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_OBJECT_0: Result := wrSignaled;
WAIT_TIMEOUT: Result := wrTimeout;
WAIT_FAILED:
begin
Result := wrError;
FLastError := GetLastError;
end;
else
Result := wrError;
end;
end;
procedure TEvent.SetEvent;
begin
Windows.SetEvent(Handle);
end;
procedure TEvent.ResetEvent;
begin
Windows.ResetEvent(Handle);
end;
{ TSimpleEvent }
constructor TSimpleEvent.Create;
begin
FHandle := CreateEvent(nil, True, False, nil);
end;
{ TCriticalSection }
constructor TCriticalSection.Create;
begin
inherited Create;
InitializeCriticalSection(FSection);
end;
destructor TCriticalSection.Destroy;
begin
DeleteCriticalSection(FSection);
inherited Destroy;
end;
procedure TCriticalSection.Acquire;
begin
EnterCriticalSection(FSection);
end;
procedure TCriticalSection.Release;
begin
LeaveCriticalSection(FSection);
end;
procedure TCriticalSection.Enter;
begin
Acquire;
end;
procedure TCriticalSection.Leave;
begin
Release;
end;
{ TMultiReadExclusiveWriteSynchronizer }
constructor TMultiReadExclusiveWriteSynchronizer.Create;
begin
inherited Create;
InitializeCriticalSection(FLock);
FReadExit := CreateEvent(nil, True, True, nil); // manual reset, start signaled
FTlen:=4;
end;
destructor TMultiReadExclusiveWriteSynchronizer.Destroy;
begin
BeginWrite;
inherited Destroy;
CloseHandle(FReadExit);
DeleteCriticalSection(FLock);
end;
function TMultiReadExclusiveWriteSynchronizer.WriterIsOnlyReader: Boolean;
var
I, Len: Integer;
begin
Result := False;
if FWriteRequestorID = 0 then Exit;
// We know a writer is waiting for entry with the FLock locked,
// so FActiveThreads is stable - no BeginRead could be resizing it now
I := 0;
Len := FTlen; {High(FActiveThreads);}
while (I < Len) and
((FActiveThreads[I].ThreadID = 0) or (FActiveThreads[I].ThreadID = FWriteRequestorID)) do
Inc(I);
Result := I >= Len;
end;
procedure TMultiReadExclusiveWriteSynchronizer.BeginWrite;
begin
EnterCriticalSection(FLock); // Block new read or write ops from starting
if not FWriting then
begin
FWriteRequestorID := GetCurrentThreadID; // Indicate that writer is waiting for entry
if not WriterIsOnlyReader then // See if any other thread is reading
WaitForSingleObject(FReadExit, INFINITE); // Wait for current readers to finish
FSaveReadCount := FCount; // record prior read recursions for this thread
FCount := 0;
FWriteRequestorID := 0;
FWriting := True;
end;
Inc(FCount); // allow read recursions during write without signalling FReadExit event
end;
procedure TMultiReadExclusiveWriteSynchronizer.EndWrite;
begin
Dec(FCount);
if FCount = 0 then
begin
FCount := FSaveReadCount; // restore read recursion count
FSaveReadCount := 0;
FWriting := False;
end;
LeaveCriticalSection(FLock);
end;
procedure TMultiReadExclusiveWriteSynchronizer.BeginRead;
var
I: Integer;
ThreadID: Integer;
ZeroSlot: Integer;
begin
EnterCriticalSection(FLock);
try
if not FWriting then
begin
// This will call ResetEvent more than necessary on win95, but still work
if InterlockedIncrement(FCount) = 1 then
ResetEvent(FReadExit); // Make writer wait until all readers are finished.
I := 0; // scan for empty slot in activethreads list
ThreadID := GetCurrentThreadID;
ZeroSlot := -1;
while (I < FTlen {High(FActiveThreads)}) and (FActiveThreads[I].ThreadID <> ThreadID) do
begin
if (FActiveThreads[I].ThreadID = 0) and (ZeroSlot < 0) then ZeroSlot := I;
Inc(I);
end;
if I >= FTlen {High(FActiveThreads)} then // didn't find our threadid slot
begin
if ZeroSlot < 0 then // no slots available. Grow array to make room
begin // spin loop. wait for EndRead to put zero back into FReallocFlag
while InterlockedExchange(FReallocFlag, ThreadID) <> 0 do Sleep(0);
try
{SetLength(FActiveThreads, High(FActiveThreads) + 3);}
FTlen:=FTlen+3;
finally
FReallocFlag := 0;
end;
end
else // use an empty slot
I := ZeroSlot;
// no concurrency issue here. We're the only thread interested in this record.
FActiveThreads[I].ThreadID := ThreadID;
FActiveThreads[I].RecursionCount := 1;
end
else // found our threadid slot.
Inc(FActiveThreads[I].RecursionCount); // thread safe = unique to threadid
end;
finally
LeaveCriticalSection(FLock);
end;
end;
procedure TMultiReadExclusiveWriteSynchronizer.EndRead;
var
I, ThreadID, Len: Integer;
begin
if not FWriting then
begin
// Remove our threadid from the list of active threads
I := 0;
ThreadID := GetCurrentThreadID;
// wait for BeginRead to finish any pending realloc of FActiveThreads
while InterlockedExchange(FReallocFlag, ThreadID) <> 0 do Sleep(0);
try
Len := High(FActiveThreads);
while (I < Len) and (FActiveThreads[I].ThreadID <> ThreadID) do Inc(I);
{assert(I < Len);}
if I>=Len
then raise Exception.Create ('TMultiReadExclusiveWriteSynchronizer error');
// no concurrency issues here. We're the only thread interested in this record.
Dec(FActiveThreads[I].RecursionCount); // threadsafe = unique to threadid
if FActiveThreads[I].RecursionCount = 0 then
FActiveThreads[I].ThreadID := 0; // must do this last!
finally
FReallocFlag := 0;
end;
if (InterlockedDecrement(FCount) = 0) or WriterIsOnlyReader then
SetEvent(FReadExit); // release next writer
end;
end;
end.
|
unit frmTigerTest_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, HashAlg_U, HashAlgTiger_U;
type
TfrmTigerTest = class(TForm)
reResults: TRichEdit;
HashAlgTiger: THashAlgTiger;
pbClear: TButton;
pbClose: TButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
pbNESSIETestSet1: TButton;
pbNESSIETestSet2: TButton;
pbStdTest: TButton;
pbNESSIETestSet4: TButton;
pbNESSIETestSet3: TButton;
procedure pbCloseClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure pbStdTestClick(Sender: TObject);
procedure pbNESSIETestSet1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbNESSIETestSet2Click(Sender: TObject);
procedure pbNESSIETestSet3Click(Sender: TObject);
procedure pbNESSIETestSet4Click(Sender: TObject);
private
CountSuccess: integer;
CountFailure: integer;
procedure CommentStd();
procedure CommentNESSIE();
procedure TestInit(testSetDesc: string; isNESSIE: boolean);
procedure Test(description, testVector, expectedResult: string);
procedure TestFinish();
public
{ Public declarations }
end;
var
frmTigerTest: TfrmTigerTest;
implementation
{$R *.DFM}
uses
HashValue_U,
NESSIESet2,
NESSIESet3;
procedure TfrmTigerTest.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TfrmTigerTest.pbClearClick(Sender: TObject);
begin
reResults.Lines.Clear();
end;
procedure TfrmTigerTest.CommentStd();
begin
reResults.Lines.Add('Note: The standard test vectors found on the Tiger WWW site are laid out using the following byte order:');
reResults.Lines.Add('');
reResults.Lines.Add('7 6 5 4 3 2 1 0 space 15 14 13 12 11 10 9 8 space 23 22 21 20 19 18 17');
reResults.Lines.Add('');
reResults.Lines.Add('This tool uses the standard THash layout, which displays hashes in the following byte order:');
reResults.Lines.Add('');
reResults.Lines.Add('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23');
reResults.Lines.Add('');
reResults.Lines.Add('Note: The Tiger WWW site states quite clearly that there is *no* standard layout for displaying hashes generated by Tiger.');
reResults.Lines.Add('');
reResults.Lines.Add('');
end;
procedure TfrmTigerTest.CommentNESSIE();
begin
reResults.Lines.Add('Note: The NESSIE test vectors are laid out using the following byte order:');
reResults.Lines.Add('');
reResults.Lines.Add('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23');
reResults.Lines.Add('');
reResults.Lines.Add('This tool uses the standard THash layout, which displays hashes in the same byte order as NESSIE.');
reResults.Lines.Add('');
reResults.Lines.Add('Note: The Tiger WWW site states quite clearly that there is *no* standard layout for displaying hashes generated by Tiger.');
reResults.Lines.Add('');
reResults.Lines.Add('');
end;
procedure TfrmTigerTest.pbStdTestClick(Sender: TObject);
var
str64K: string;
i: integer;
begin
TestInit('Standard Tiger Test Vectors', FALSE);
Test(
'""',
'',
'3293AC630C13F0245F92BBB1766E16167A4E58492DDE73F3'
);
Test(
'"abc"',
'abc',
'2AAB1484E8C158F2BFB8C5FF41B57A525129131C957B5F93'
);
Test(
'"Tiger"',
'Tiger',
'DD00230799F5009FEC6DEBC838BB6A27DF2B9D6F110C7937'
);
Test(
'"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-',
'F71C8583902AFB879EDFE610F82C0D4786A3A534504486B5'
);
Test(
'"ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdefghijklmnopqrstuvwxyz+0123456789"',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdefghijklmnopqrstuvwxyz+0123456789',
'48CEEB6308B87D46E95D656112CDF18D97915F9765658957'
);
Test(
'"Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham"',
'Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham',
'8A866829040A410C729AD23F5ADA711603B3CDD357E4C15E'
);
Test(
'"Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge."',
'Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge.',
'CE55A6AFD591F5EBAC547FF84F89227F9331DAB0B611C889'
);
Test(
'"Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge, 1996."',
'Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge, 1996.',
'631ABDD103EB9A3D245B6DFD4D77B257FC7439501D1568DD'
);
Test(
'"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-',
'C54034E5B43EB8005848A7E0AE6AAC76E4FF590AE715FD25'
);
str64K := '';
for i:=0 to 65535 do
begin
str64K := str64K + char(i and $FF);
end;
Test(
'a 64K-byte string',
str64K,
'FDF4F5B35139F48E710E421BE5AF411DE1A8AAC333F26204'
);
TestFinish();
end;
procedure TfrmTigerTest.pbNESSIETestSet1Click(Sender: TObject);
begin
TestInit('NESSIE Tiger Test vectors -- set 1', TRUE);
Test(
'Set 1, vector# 0: "" (empty string)',
'',
'3293AC630C13F0245F92BBB1766E16167A4E58492DDE73F3'
);
Test(
'Set 1, vector# 1: "a"',
'a',
'77BEFBEF2E7EF8AB2EC8F93BF587A7FC613E247F5F247809'
);
Test(
'Set 1, vector# 2: "abc"',
'abc',
'2AAB1484E8C158F2BFB8C5FF41B57A525129131C957B5F93'
);
Test(
'Set 1, vector# 3: "message digest"',
'message digest',
'D981F8CB78201A950DCF3048751E441C517FCA1AA55A29F6'
);
Test(
'Set 1, vector# 4: "abcdefghijklmnopqrstuvwxyz"',
'abcdefghijklmnopqrstuvwxyz',
'1714A472EEE57D30040412BFCC55032A0B11602FF37BEEE9'
);
Test(
'Set 1, vector# 5: "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
'0F7BF9A19B9C58F2B7610DF7E84F0AC3A71C631E7B53F78E'
);
Test(
'Set 1, vector# 6: "A...Za...z0...9"',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'8DCEA680A17583EE502BA38A3C368651890FFBCCDC49A8CC'
);
Test(
'Set 1, vector# 7: 8 times "1234567890"',
'12345678901234567890123456789012345678901234567890123456789012345678901234567890',
'1C14795529FD9F207A958F84C52F11E887FA0CABDFD91BFD'
);
Test(
'Set 1, vector# 8: 1 million times "a"',
StringOfChar('a', 1000000),
'6DB0E2729CBEAD93D715C6A7D36302E9B3CEE0D2BC314B41'
);
TestFinish();
end;
procedure TfrmTigerTest.TestInit(testSetDesc: string; isNESSIE: boolean);
begin
CountSuccess:= 0;
CountFailure:= 0;
reResults.Lines.Add('Running test set: '+testSetDesc);
reResults.Lines.Add('====================================');
reResults.Lines.Add('');
if (isNESSIE) then
begin
CommentNESSIE();
end
else
begin
CommentStd();
end;
end;
procedure TfrmTigerTest.Test(description, testVector, expectedResult: string);
var
ha: THashArray;
strHashGenerated: string;
strStatus: string;
begin
ha := HashAlgTiger.HashString(testVector);
strHashGenerated := HashAlgTiger.HashToDisplay(ha);
strStatus := '';
if (strHashGenerated = expectedResult) then
begin
strStatus := 'Pass';
CountSuccess := CountSuccess + 1;
end
else
begin
strStatus := 'FAIL.';
CountFailure := CountFailure + 1;
end;
reResults.lines.add('Test description: '+description);
reResults.lines.add('Expected hash: '+expectedResult);
reResults.lines.add('Generated hash: '+strHashGenerated);
reResults.lines.add('Result: '+strStatus);
reResults.lines.add('');
end;
procedure TfrmTigerTest.TestFinish();
begin
reResults.Lines.Add('');
reResults.Lines.Add('Results');
reResults.Lines.Add('-------');
reResults.Lines.Add('Tests run: '+inttostr(CountSuccess+CountFailure));
reResults.Lines.Add('Passed: '+inttostr(CountSuccess));
reResults.Lines.Add('Failed: '+inttostr(CountFailure));
if (CountFailure > 0) then
begin
reResults.lines.add('');
reResults.lines.add('!!!!!!!!!!!!!!!!');
reResults.lines.add('ONE OR MORE OF THE TEST VECTORS FAILED.');
reResults.lines.add('!!!!!!!!!!!!!!!!');
MessageDlg('One or more of the test vectors failed!', mtError, [mbOK], 0);
end
else if (CountFailure = 0) then
begin
reResults.lines.add('');
reResults.lines.add('All tests passed successfully.');
end;
reResults.lines.add('');
end;
procedure TfrmTigerTest.FormShow(Sender: TObject);
begin
self.Caption := Application.Title;
reResults.Lines.Clear();
end;
procedure TfrmTigerTest.pbNESSIETestSet2Click(Sender: TObject);
var
i: integer;
begin
TestInit('NESSIE Tiger Test vectors -- set 2', TRUE);
reResults.Lines.Add('Note: Because THash only operates on bytes, not bits, only every 8th NESSIE test set 2 test will be carried out.');
reResults.Lines.Add('');
for i:=0 to 1023 do
begin
if ((i mod 8) = 0) then
begin
Test(
'Set 2, vector# '+inttostr(i)+': '+inttostr(i)+' zero bits',
StringOfChar(#0, i div 8),
NESSIE_SET_2_EXPECTED[i]
);
end;
end;
TestFinish();
end;
procedure TfrmTigerTest.pbNESSIETestSet3Click(Sender: TObject);
var
testID: integer;
testString: string;
bit: byte;
i: integer;
j: integer;
begin
TestInit('NESSIE Tiger Test vectors -- set 3', TRUE);
testID := 0;
for i:=0 to 63 do
begin
bit := $80;
for j:=1 to 8 do
begin
if (j <> 1) then
begin
bit := bit shr 1;
end;
testString := StringOfChar(#0, i);
testString := testString + char(bit);
testString := testString + StringOfChar(#0, (63-i));
Test(
'Set 3, vector# '+inttostr(testID)+': 512-bit string: '+inttostr(i)+'*00,'+inttohex(bit, 2)+','+inttostr(63-i)+'*00',
testString,
NESSIE_SET_3_EXPECTED[testID]
);
// Increment, ready for next...
inc(testID);
end;
end;
TestFinish();
end;
procedure TfrmTigerTest.pbNESSIETestSet4Click(Sender: TObject);
const
expectedFirst: string = 'CDDDCACFEA7B70B485655BA3DC3F60DEE4F6B8F861069E33';
expectedLast: string = '35C4F594F7E827FFC68BFECEBEDA314EDC6FE917BDF00B66';
var
ha: THashArray;
strHashGeneratedFirst: string;
strHashGeneratedLast: string;
i: integer;
strStatus: string;
begin
TestInit('NESSIE Tiger Test vectors -- set 4', TRUE);
ha := HashAlgTiger.HashString(StringOfChar(#0, (192 div 8)));
strHashGeneratedFirst := HashAlgTiger.HashToDisplay(ha);
reResults.lines.add('Test description: Set 4, vector# 0: 192 zero bits; iterated 100000 times');
// We continue the loop from 2, as we've already done the first
for i:=2 to 100000 do
begin
ha := HashAlgTiger.HashString(HashAlgTiger.HashToDataString(ha));
end;
strHashGeneratedLast := HashAlgTiger.HashToDisplay(ha);
reResults.lines.add('Expected first hash: '+expectedFirst);
reResults.lines.add('Generated first hash: '+strHashGeneratedFirst);
reResults.lines.add('Expected last hash: '+expectedLast);
reResults.lines.add('Generated last hash: '+strHashGeneratedLast);
strStatus := '';
if ((expectedFirst = strHashGeneratedFirst) and (expectedLast = strHashGeneratedLast)) then
begin
strStatus := 'Pass';
CountSuccess := CountSuccess + 1;
end
else
begin
strStatus := 'FAIL.';
CountFailure := CountFailure + 1;
end;
reResults.lines.add('Result: '+strStatus);
reResults.lines.add('');
TestFinish();
end;
END.
|
namespace NameSpaces;
interface
uses
{ Notice the use of the wildcard "*" below, which results in the automatic
inclusion of all children of the namespaces "System" and "Namespaces" }
System.*,
Namespaces.*;
type
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
button1: System.Windows.Forms.Button;
components: System.ComponentModel.Container := nil;
method button1_Click(sender: System.Object; e: System.EventArgs);
method InitializeComponent;
{$ENDREGION}
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
class method Main;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.button1 := new System.Windows.Forms.Button();
self.SuspendLayout();
//
// button1
//
self.button1.Location := new System.Drawing.Point(47, 50);
self.button1.Name := 'button1';
self.button1.Size := new System.Drawing.Size(150, 23);
self.button1.TabIndex := 0;
self.button1.Text := 'Test Classes';
self.button1.Click += new System.EventHandler(@self.button1_Click);
//
// MainForm
//
self.AutoScaleBaseSize := new System.Drawing.Size(5, 13);
self.ClientSize := new System.Drawing.Size(244, 122);
self.Controls.Add(self.button1);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.MaximizeBox := false;
self.Name := 'MainForm';
self.Text := 'Namespaces Sample';
self.ResumeLayout(false);
end;
{$ENDREGION}
{$REGION Application Entry Point}
[STAThread]
class method MainForm.Main;
begin
Application.EnableVisualStyles();
try
with lForm := new MainForm() do
Application.Run(lForm);
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
{$ENDREGION}
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
var
lEmployee : Employee;
lPresident : President;
begin
lPresident := new President;
lEmployee := new Employee;
{ The following code will perform a few type tests to verify everything works as expected }
if (lPresident is Employee)
then MessageBox.Show('President is an Employee');
if (lEmployee is Person)
then MessageBox.Show('Employee is a Person');
if (lEmployee is not President)
then MessageBox.Show('Employee is not a President');
end;
end. |
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
DelphiWebScript implementation
}
unit VXS.ScriptDWS;
interface
uses
System.Classes,
System.SysUtils,
DwsComp,
DwsExprs,
DwsSymbols,
VXS.XCollection,
VXS.ScriptBase,
VXS.Manager;
type
{ This class only adds manager registration logic to the TDelphiWebScriptII
class to enable the XCollection items (ie. TVXScriptDWS) retain it's
assigned compiler from design to run -time. }
TVXDelphiWebScriptII = class(TDelphiWebScriptII)
public
constructor Create(AOnwer : TComponent); override;
destructor Destroy; override;
end;
{ Implements DelphiWebScriptII scripting functionality through the
abstracted VXS.ScriptBase . }
TVXScriptDWS = class(TVXScriptBase)
private
FDWS2Program : TProgram;
FCompiler : TVXDelphiWebScriptII;
FCompilerName : String;
protected
procedure SetCompiler(const Value : TVXDelphiWebScriptII);
procedure ReadFromFiler(reader : TReader); override;
procedure WriteToFiler(writer : TWriter); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetState : TVXScriptState; override;
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Compile; override;
procedure Start; override;
procedure Stop; override;
procedure Execute; override;
procedure Invalidate; override;
function Call(aName : String;
aParams : array of Variant) : Variant; override;
class function FriendlyName : String; override;
class function FriendlyDescription : String; override;
class function ItemCategory : String; override;
property DWS2Program : TProgram read FDWS2Program;
published
property Compiler : TVXDelphiWebScriptII read FCompiler write SetCompiler;
end;
procedure Register;
// --------------------------------------------------
implementation
// --------------------------------------------------
// ---------------
// --------------- Miscellaneous ---------------
// ---------------
procedure Register;
begin
RegisterClasses([TVXDelphiWebScriptII, TVXScriptDWS]);
RegisterComponents('VXScene DWS2', [TVXDelphiWebScriptII]);
end;
// ----------
// ---------- TVXDelphiWebScriptII ----------
// ----------
constructor TVXDelphiWebScriptII.Create(AOnwer : TComponent);
begin
inherited;
RegisterManager(Self);
end;
destructor TVXDelphiWebScriptII.Destroy;
begin
DeregisterManager(Self);
inherited;
end;
// ---------------
// --------------- TVXScriptDWS ---------------
// ---------------
destructor TVXScriptDWS.Destroy;
begin
Invalidate;
inherited;
end;
procedure TVXScriptDWS.Assign(Source: TPersistent);
begin
inherited;
if Source is TVXScriptDWS then begin
Compiler:=TVXScriptDWS(Source).Compiler;
end;
end;
procedure TVXScriptDWS.ReadFromFiler(reader : TReader);
var
archiveVersion : Integer;
begin
inherited;
archiveVersion:=reader.ReadInteger;
Assert(archiveVersion = 0);
with reader do begin
FCompilerName:=ReadString;
end;
end;
procedure TVXScriptDWS.WriteToFiler(writer : TWriter);
begin
inherited;
writer.WriteInteger(0); // archiveVersion
with writer do begin
if Assigned(FCompiler) then
WriteString(FCompiler.GetNamePath)
else
WriteString('');
end;
end;
procedure TVXScriptDWS.Loaded;
var
temp : TComponent;
begin
inherited;
if FCompilerName<>'' then begin
temp:=FindManager(TVXDelphiWebScript, FCompilerName);
if Assigned(temp) then
Compiler:=TVXDelphiWebScript(temp);
FCompilerName:='';
end;
end;
procedure TVXScriptDWS.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (AComponent = Compiler) and (Operation = opRemove) then
Compiler:=nil;
end;
class function TVXScriptDWS.FriendlyName : String;
begin
Result:='VXS.ScriptDWS';
end;
class function TVXScriptDWS.FriendlyDescription : String;
begin
Result:='DelphiWebScript script';
end;
class function TVXScriptDWS.ItemCategory : String;
begin
Result:='';
end;
procedure TVXScriptDWS.Compile;
begin
Invalidate;
if Assigned(Compiler) then
FDWS2Program:=Compiler.Compile(Text.Text)
else
raise Exception.Create('No compiler assigned!');
end;
procedure TVXScriptDWS.Execute;
begin
if (State = ssUncompiled) then
Compile
else if (State = ssRunning) then
Stop;
if (State = ssCompiled) then
FDWS2Program.Execute;
end;
procedure TVXScriptDWS.Invalidate;
begin
if (State <> ssUncompiled) or Assigned(FDWSProgram) then begin
Stop;
FreeAndNil(FDWSProgram);
end;
end;
procedure TVXScriptDWS.Start;
begin
if (State = ssUncompiled) then
Compile;
if (State = ssCompiled) then
FDWS2Program.BeginProgram(False);
end;
procedure TVXScriptDWS.Stop;
begin
if (State = ssRunning) then
FDWS2Program.EndProgram;
end;
function TVXScriptDWS.Call(aName: String; aParams: array of Variant) : Variant;
var
Symbol : TSymbol;
Output : IInfo;
begin
if (State <> ssRunning) then
Start;
if State = ssRunning then begin
Symbol:=FDWSProgram.Table.FindSymbol(aName);
if Assigned(Symbol) then begin
if Symbol is TFuncSymbol then begin
Output:=FDWSProgram.Info.Func[aName].Call(aParams);
if Assigned(Output) then
Result:=Output.Value;
end else
raise Exception.Create('Expected TFuncSymbol but found '+Symbol.ClassName+' for '+aName);
end else
raise Exception.Create('Symbol not found for '+aName);
end;
end;
procedure TVXScriptDWS.SetCompiler(const Value : TVXDelphiWebScript);
begin
if Value<>FCompiler then begin
FCompiler:=Value;
Invalidate;
end;
end;
function TVXScriptDWS.GetState : TVXScriptState;
begin
Result:=ssUncompiled;
if Assigned(FDWSProgram) then begin
case FDWSProgram.ProgramState of
psReadyToRun : Result:=ssCompiled;
psRunning : Result:=ssRunning;
else
if FDWSProgram.Msgs.HasErrors then begin
if FDWSProgram.Msgs.HasCompilerErrors then
Result:=ssCompileErrors
else if FDWS2Program.Msgs.HasExecutionErrors then
Result:=ssRunningErrors;
Errors.Text:=FDWS2Program.Msgs.AsInfo;
end;
end;
end;
end;
// --------------------------------------------------
initialization
// --------------------------------------------------
RegisterXCollectionItemClass(TVXScriptDWS);
// --------------------------------------------------
finalization
// --------------------------------------------------
UnregisterXCollectionItemClass(TVXScriptDWS);
end. |
unit DP.EventSystemMove;
//------------------------------------------------------------------------------
// модуль кэша таблицы eventsystem_move
//------------------------------------------------------------------------------
// содержит:
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
System.Generics.Collections,
DP.Root,
JsonDataObjects,
ZConnection, ZDataset,
Geo.Pos, Event.Cnst, Ils.MySql.Conf, Ils.Utils, Ils.Logger;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! класс данных событий движения
//------------------------------------------------------------------------------
TClassEventSystemMove = class(TDataObj)
private
//! свойства изменены
FChanged: Boolean;
//! IMEI
FIMEI: Int64;
//! с какого времени
FDTMark: TDateTime;
//! длительность
FDuration: Double;
//! до какого времени
FTill: TDateTime;
//! гео-координаты
FGeoPos: TGeoPos;
//! радиус чего-то там
FRadius: Double;
//! разброс чего-то там
FDispertion: Double;
//! тип события
FEventType: TEventSystemType;
//!
procedure SetDuration(const Value: Double);
procedure SetTill(const Value: TDateTime);
procedure SetLatitude(const Value: Double);
procedure SetLongitude(const Value: Double);
procedure SetRadius(const Value: Double);
procedure SetDispertion(const Value: Double);
procedure SetEventType(const Value: TEventSystemType);
protected
//!
function GetDTMark(): TDateTime; override;
public
class function CreateFromJSON(
const AJSON: TJsonObject;
out RObject: TClassEventSystemMove
): Boolean;
constructor Create(
const IMEI: Int64;
const DTMark: TDateTime;
const EventType: TEventSystemType;
const Duration: Double;
const Latitude: Double;
const Longitude: Double;
const Radius: Double;
const Dispertion: Double
);
//!
property IMEI: Int64 read FIMEI;
property Duration: Double read FDuration write SetDuration;
property Till: TDateTime read FTill write SetTill;
property Latitude: Double read FGeoPos.Latitude write SetLatitude;
property Longitude: Double read FGeoPos.Longitude write SetLongitude;
property Radius: Double read FRadius write SetRadius;
property Dispertion: Double read FDispertion write SetDispertion;
property EventType: TEventSystemType read FEventType write SetEventType;
end;
//------------------------------------------------------------------------------
//! класс кэша данных событий движения
//------------------------------------------------------------------------------
TCacheEventSystemMove = class(TCacheRoot)
protected
//! вставить запись в БД
procedure ExecDBInsert(
const AObj: IDataObj
); override;
//! обновить запись в БД
procedure ExecDBUpdate(
const AObj: IDataObj
); override;
//! преобразователь из записи БД в объект
function MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj; override;
public
constructor Create(
const IMEI: Int64;
const ReadConnection: TZConnection;
const WriteConnection: TZConnection;
const DBWriteback: Boolean;
const MaxKeepCount: Integer;
const LoadDelta: Double
);
end;
//------------------------------------------------------------------------------
//! класс списка кэшей событий движения
//------------------------------------------------------------------------------
TEventSystemMoveDictionary = class(TCacheDictionaryRoot<Int64>);
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
// запросы к БД
//------------------------------------------------------------------------------
CSQLReadRange = 'SELECT *'
+ ' FROM eventsystem_move'
+ ' WHERE imei = :imei'
+ ' AND dt >= :dt_from'
+ ' AND dt <= :dt_to';
CSQLReadBefore = 'SELECT *'
+ ' FROM eventsystem_move'
+ ' WHERE IMEI = :imei'
+ ' AND DT < :dt'
+ ' ORDER BY DT DESC'
+ ' LIMIT 1';
CSQLReadAfter = 'SELECT *'
+ ' FROM eventsystem_move'
+ ' WHERE IMEI = :imei'
+ ' AND DT > :dt'
+ ' ORDER BY DT'
+ ' LIMIT 1';
CSQLInsert = 'INSERT INTO eventsystem_move'
+ ' (IMEI, DT, EventTypeID, Duration, Latitude, Longitude, Radius, Dispersion)'
+ ' VALUES (:imei, :dt, :event_type, :dur, :la, :lo, :radius, :dispersion)';
CSQLUpdate = 'UPDATE eventsystem_move SET'
+ ' EventTypeID = :event_type, Duration = :dur, Latitude = :la, Longitude = :lo, Radius = :radius, Dispersion = :dispersion'
+ ' WHERE IMEI = :imei'
+ ' AND DT = :dt';
CSQLDeleteRange = 'DELETE FROM eventsystem_move'
+ ' WHERE imei = :imei'
+ ' AND dt >= :dt_from'
+ ' AND dt <= :dt_to';
CSQLLastPresentDT = 'SELECT MAX(DT) AS DT'
+ ' FROM eventsystem_move'
+ ' WHERE imei = :imei';
//------------------------------------------------------------------------------
// TSystemMoveEventClass
//------------------------------------------------------------------------------
class function TClassEventSystemMove.CreateFromJSON(
const AJSON: TJsonObject;
out RObject: TClassEventSystemMove
): Boolean;
begin
Result := False;
try
RObject := TClassEventSystemMove.Create(
AJSON.L['IMEI'],
IlsToDateTime(AJSON.S['DT']),
TEventSystemType(AJSON.I['EventTypeID']),
AJSON.F['Duration'],
AJSON.F['la'],
AJSON.F['lo'],
AJSON.F['Radius'],
AJSON.F['Dispersion']
);
Result := True;
except
on Ex: Exception do
begin
ToLog(Format(
'При создании класса TClassEventSystemMove из JSON'#13#10'%s'#13#10'возникла ошибка:'#13#10'%s',
[AJSON.ToJSON(True), Ex.Message]
));
end;
end;
end;
constructor TClassEventSystemMove.Create(
const IMEI: Int64;
const DTMark: TDateTime;
const EventType: TEventSystemType;
const Duration: Double;
const Latitude: Double;
const Longitude: Double;
const Radius: Double;
const Dispertion: Double
);
begin
inherited Create();
//
FIMEI := IMEI;
FDTMark := DTMark;
FDuration := Duration;
FTill := DTMark + Duration;
FGeoPos.Latitude := Latitude;
FGeoPos.Longitude := Longitude;
FRadius := Radius;
FDispertion := Dispertion;
FEventType := EventType;
end;
function TClassEventSystemMove.GetDTMark(): TDateTime;
begin
Result := FDTMark;
end;
procedure TClassEventSystemMove.SetDuration(
const Value: Double
);
begin
if (FDuration <> Value) then
begin
FDuration := Value;
FTill := Value + FDTMark;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetTill(
const Value: TDateTime
);
begin
if (FTill <> Value) then
begin
FTill := Value;
FDuration := Value - FDTMark;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetLatitude(
const Value: Double
);
begin
if (FGeoPos.Latitude <> Value) then
begin
FGeoPos.Latitude := Value;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetLongitude(
const Value: Double
);
begin
if (FGeoPos.Longitude <> Value) then
begin
FGeoPos.Longitude := Value;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetRadius(
const Value: Double
);
begin
if (FRadius <> Value) then
begin
FRadius := Value;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetDispertion(
const Value: Double
);
begin
if (FDispertion <> Value) then
begin
FDispertion := Value;
FChanged := True;
end;
end;
procedure TClassEventSystemMove.SetEventType(
const Value: TEventSystemType
);
begin
if (FEventType <> Value) then
begin
FEventType := Value;
FChanged := True;
end;
end;
//------------------------------------------------------------------------------
// TCacheEventSystemMove
//------------------------------------------------------------------------------
constructor TCacheEventSystemMove.Create(
const IMEI: Int64;
const ReadConnection: TZConnection;
const WriteConnection: TZConnection;
const DBWriteback: Boolean;
const MaxKeepCount: Integer;
const LoadDelta: Double
);
begin
inherited Create(
ReadConnection, WriteConnection, DBWriteback, MaxKeepCount, LoadDelta,
CSQLReadRange, CSQLReadBefore, CSQLReadAfter, CSQLInsert, CSQLUpdate, CSQLDeleteRange, CSQLLastPresentDT
);
//
FQueryReadRange.ParamByName('imei').AsLargeInt := IMEI;
FQueryReadBefore.ParamByName('imei').AsLargeInt := IMEI;
FQueryReadAfter.ParamByName('imei').AsLargeInt := IMEI;
FQueryInsert.ParamByName('imei').AsLargeInt := IMEI;
FQueryUpdate.ParamByName('imei').AsLargeInt := IMEI;
FQueryDeleteRange.ParamByName('imei').AsLargeInt := IMEI;
FQueryLastPresentDT.ParamByName('imei').AsLargeInt := IMEI;
end;
procedure TCacheEventSystemMove.ExecDBInsert(
const AObj: IDataObj
);
begin
with (AObj as TClassEventSystemMove), FQueryInsert do
begin
Active := False;
ParamByName('dt').AsFloat := DTMark;
ParamByName('event_type').AsFloat := Ord(EventType);
ParamByName('dur').AsFloat := Duration;
ParamByName('la').AsFloat := Latitude;
ParamByName('lo').AsFloat := Longitude;
ParamByName('radius').AsFloat := Radius;
ParamByName('dispersion').AsFloat := Dispertion;
ExecSQL();
end;
end;
procedure TCacheEventSystemMove.ExecDBUpdate(
const AObj: IDataObj
);
begin
with (AObj as TClassEventSystemMove), FQueryUpdate do
begin
Active := False;
ParamByName('dt').AsFloat := DTMark;
ParamByName('event_type').AsFloat := Ord(EventType);
ParamByName('dur').AsFloat := Duration;
ParamByName('la').AsFloat := Latitude;
ParamByName('lo').AsFloat := Longitude;
ParamByName('radius').AsFloat := Radius;
ParamByName('dispersion').AsFloat := Dispertion;
ExecSQL();
end;
end;
function TCacheEventSystemMove.MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj;
begin
with AQuery do
begin
Result := TClassEventSystemMove.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
);
end;
end;
end.
|
unit DbExplorerView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, VirtualTrees, Grids, DBGrids, ComCtrls, ImgList;
type
TDbExplorerForm = class(TForm)
MySql: TADOConnection;
DataSource1: TDataSource;
MySqlDbsQuery: TADOQuery;
Tree: TTreeView;
MySqlTablesQuery: TADOQuery;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function Connect(const inConnectionString: string): Boolean;
procedure InitTree;
procedure ListAllTables(inNode: TTreeNode);
procedure ListTables(inNode: TTreeNode);
public
{ Public declarations }
end;
var
DbExplorerForm: TDbExplorerForm;
implementation
uses
TpDbConnectionStrings;
{$R *.dfm}
procedure TDbExplorerForm.FormCreate(Sender: TObject);
begin
//Ado.ConnectionString := BuildMySqlConnectionString('', '', '', '');
InitTree;
end;
function TDbExplorerForm.Connect(const inConnectionString: string): Boolean;
begin
MySql.Connected := false;
try
MySql.ConnectionString := inConnectionString;
MySql.Connected := true;
except
end;
Result := MySql.Connected;
end;
procedure TDbExplorerForm.ListTables(inNode: TTreeNode);
begin
if Connect(BuildMySqlConnectionString('', inNode.Text, '', '')) then
try
MySqlTablesQuery.Active := true;
while not MySqlTablesQuery.Eof do
begin
Tree.Items.AddChild(inNode, MySqlTablesQuery.Fields[0].AsString)
.ImageIndex := 2;
MySqlTablesQuery.Next;
end;
finally
end;
end;
procedure TDbExplorerForm.ListAllTables(inNode: TTreeNode);
var
i: Integer;
begin
for i := 0 to Pred(inNode.Count) do
ListTables(inNode[i]);
end;
procedure TDbExplorerForm.InitTree;
var
root: TTreeNode;
begin
try
Tree.Items.BeginUpdate;
try
Tree.Items.Clear;
root := Tree.Items.Add(nil, 'MySql Databases');
if Connect(BuildMySqlConnectionString('', '', '', '')) then
try
MySqlDbsQuery.Active := true;
while not MySqlDbsQuery.Eof do
begin
Tree.Items.AddChild(root, MySqlDbsQuery.Fields[0].AsString)
.ImageIndex := 1;
MySqlDbsQuery.Next;
end;
except
end;
root.Expanded := true;
ListAllTables(root);
finally
Tree.Items.EndUpdate;
end;
except
end;
end;
end.
|
{*******************************************************************************
* uLogicCheck *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Компонент для проверки (TqFLogicCheck) *
* Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uLogicCheck;
interface
uses
SysUtils, Classes, Controls, uFControl;
type
TCheckEvent = procedure(Sender: TObject; var Error: string) of object;
TqFLogicCheck = class(TGraphicControl)
protected
FCheckEnabled: Boolean;
FOnCheck: TCheckEvent;
FError: string;
FLightControl: TqFControl;
public
function Check: Boolean; virtual;
procedure Highlight(HighlightOn: Boolean); virtual;
procedure Paint; override;
constructor Create(AOwner: TComponent); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
published
property OnCheck: TCheckEvent read FOnCheck write FOnCheck;
property Error: string read FError;
property LightControl: TqFControl read FLightControl write FLightControl;
property CheckEnabled: Boolean read FCheckEnabled write FCheckEnabled default True;
end;
procedure Register;
{$R *.res}
implementation
function TqFLogicCheck.Check: Boolean;
begin
FError := '';
if FCheckEnabled then
if Assigned(FOnCheck) then FOnCheck(Self, FError);
Result := FError = '';
end;
procedure TqFLogicCheck.Highlight(HighlightOn: Boolean);
begin
if LightControl <> nil then LightControl.Highlight(HighlightOn);
end;
constructor TqFLogicCheck.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FError := '';
Height := 21;
Width := 36;
Visible := False;
FCheckEnabled := True;
end;
procedure TqFLogicCheck.Paint;
begin
inherited;
with Canvas do
begin
Rectangle(0, 0, Width, Height);
Font.Color := $FF;
TextOut(1, 3, 'Check!');
end;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFLogicCheck]);
end;
procedure TqFLogicCheck.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if ( AComponent = LightControl ) and ( Operation = opRemove ) then
FLightControl := nil;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient, IdSNTP;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Image1: TImage;
lblIp: TLabel;
IdSNTP1: TIdSNTP;
lblHorario: TLabel;
Timer1: TTimer;
lblInfo: TLabel;
Timer2: TTimer;
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
private
Lista:TStringList;
procedure ShowImageFromStream(AImage: TImage; AData: TStream);
function retornaImagem:TBytes; overload;
function retornaImagem(vsId:String):TBytes; overload;
function retornaInfoImagem(vsId:String):string;
function retornaListaImagem:TStringList;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
Response, Request, JPEG, System.NetEncoding, Jsons;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Resposta: IResponse;
begin
Timer2.Enabled := False;
Resposta := TRequest.New
.BaseURL('https://ident.me/')
.Get;
Memo1.Lines.Clear;
Memo1.Lines.Add(Resposta.Content);
lblIp.Visible := True;
lblIp.Caption := Resposta.Content;
retornaImagem;
if not Timer1.Enabled then
Timer1.Enabled := True;
Timer2.Enabled := True;
end;
function TForm1.retornaImagem: TBytes;
var
Resposta : IResponse;
Recebido : TStringStream;
Foto : TMemoryStream;
begin
try
Recebido := TStringStream.Create;
Foto := TMemoryStream.Create;
try
Resposta := TRequest.New
.BaseURL('https://picsum.photos/548/217.jpg')
.Get;
Recebido.WriteData(Resposta.RawBytes, Length(Resposta.RawBytes));
Recebido.Position := 0;
Foto := TMemoryStream.Create;
Foto.LoadFromStream(Recebido);
Image1.Picture.Assign(nil);
ShowImageFromStream(Image1, Foto);
lblInfo.Visible := True;
lblInfo.Caption := retornaInfoImagem(Resposta.Headers.Values['Picsum-Id']);
retornaListaImagem;
except
on E: Exception do
ShowMessage('Erro: ' + e.Message)
end;
finally
FreeAndNil(Recebido);
FreeAndNil(Foto);
end;
end;
function TForm1.retornaImagem(vsId: String): TBytes;
var
Resposta : IResponse;
Recebido : TStringStream;
Foto : TMemoryStream;
begin
try
Recebido := TStringStream.Create;
Foto := TMemoryStream.Create;
try
Resposta := TRequest.New
.BaseURL(Format('https://picsum.photos/id/%s/548/217', [vsId]))
.Get;
Recebido.WriteData(Resposta.RawBytes, Length(Resposta.RawBytes));
Recebido.Position := 0;
Foto := TMemoryStream.Create;
Foto.LoadFromStream(Recebido);
Image1.Picture.Assign(nil);
ShowImageFromStream(Image1, Foto);
lblInfo.Visible := True;
lblInfo.Caption := retornaInfoImagem(Resposta.Headers.Values['Picsum-Id']);
except
on E: Exception do
ShowMessage('Erro: ' + e.Message)
end;
finally
FreeAndNil(Recebido);
FreeAndNil(Foto);
end;
end;
function TForm1.retornaInfoImagem(vsId: String): string;
var
JsonResposta:TJson;
Resposta:IResponse;
begin
try
JsonResposta := TJson.Create;
Resposta := TRequest.New
.BaseURL(Format('https://picsum.photos/id/%s/info', [vsId]))
.Get;
JsonResposta.Parse(Resposta.JSONText);
Result := 'Autor: ' + JsonResposta.Values['author'].AsString;
finally
FreeAndNil(JsonResposta);
end;
end;
procedure TForm1.ShowImageFromStream(AImage: TImage; AData: TStream);
var
JPEGImage: TJPEGImage;
begin
AData.Position := 0;
JPEGImage := TJPEGImage.Create;
try
JPEGImage.LoadFromStream(AData);
AImage.Picture.Assign(JPEGImage);
finally
JPEGImage.Free;
end;
end;
function TForm1.retornaListaImagem: TStringList;
var
vnIdx, vnIdxJson: Integer;
Resposta: IResponse;
JsonResposta: TJsonArray;
begin
try
JsonResposta := TJsonArray.Create;
Result := TStringList.Create;
try
for vnIdx := 1 to 10 do
begin
Resposta := TRequest.New
.BaseURL(Format('https://picsum.photos/v2/list?page=%d&limit=100', [vnidx]))
.Get;
JsonResposta.Clear;
JsonResposta.Parse(Resposta.JSONValue.ToJSON);
for vnIdxJson := 0 to JsonResposta.Count - 1 do
Result.Add(JsonResposta.Items[vnIdxJson].AsObject.Values['id'].AsString)
end;
except
on E: Exception do
ShowMessage('Erro: ' + e.Message)
end;
finally
FreeAndNil(JsonResposta);
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
IdSNTP1.Connect;
lblHorario.Visible := True;
lblHorario.Caption := DateTimeToStr(IdSNTP1.DateTime);
Application.ProcessMessages;
end;
procedure TForm1.Timer2Timer(Sender: TObject);
var
vnId:Integer;
begin
if not Assigned(Lista) then
begin
Lista := TStringList.Create;
Lista := retornaListaImagem;
end;
Randomize;
vnId := Random(Lista.Count);
retornaImagem(Lista.Strings[vnId]);
Memo1.Lines.Add('Buscando uma imagem Random ID: ' + IntToStr(vnId));
end;
end.
|
program SaveBitmaps;
//{IFNDEF UNIX} {r GameLauncher.res} {ENDIF}
uses
sysutils,
SwinGame;
procedure Main();
var
bmp, rot, zoom: Bitmap;
begin
OpenAudio();
OpenGraphicsWindow('Save Bitmap', 640, 480);
LoadDefaultColors();
bmp := CreateBitmap(100, 100);
ClearSurface(bmp, ColorYellow);
FillRectangle(bmp, ColorWhite, 1, 1, 98, 98);
FillRectangle(bmp, ColorRed, 2, 2, 96, 96);
FillRectangle(bmp, ColorGreen, 3, 3, 94, 94);
FillRectangle(bmp, ColorBlue, 4, 4, 92, 92);
rot := RotateScaleBitmap(bmp, 45, 1);
zoom := RotateScaleBitmap(bmp, 0, 2);
WriteLn(HexStr(rot), ' = ', HexStr(zoom));
SaveToPNG(bmp, GetUserDir() + PathDelim + 'Desktop/test.png');
SaveToPNG(rot, GetUserDir() + PathDelim + 'Desktop/test_rot.png');
SaveToPNG(zoom, GetUserDir() + PathDelim + 'Desktop/test_zoom.png');
ReleaseAllResources();
CloseAudio();
end;
begin
Main();
end.
|
unit IdResourceStringsSSPI;
interface
resourcestring
//SSPI Authentication
{
Note: CompleteToken is an API function Name:
}
RSHTTPSSPISuccess = 'API 呼び出し成功';
RSHTTPSSPINotEnoughMem = 'この要求を完了するのに使用できるメモリが十分にありません';
RSHTTPSSPIInvalidHandle = '指定されたハンドルが不正です';
RSHTTPSSPIFuncNotSupported = '要求された関数はサポートされていません';
RSHTTPSSPIUnknownTarget = '指定されたターゲットが不明か,アクセスできません';
RSHTTPSSPIInternalError = 'ローカルセキュリティ機関と連絡が取れません';
RSHTTPSSPISecPackageNotFound = '要求されたセキュリティパッケージがありません';
RSHTTPSSPINotOwner = '呼び出し元は希望の証明書の所有者ではありません';
RSHTTPSSPIPackageCannotBeInstalled = 'セキュリティパッケージは初期化できないため,インストールできません';
RSHTTPSSPIInvalidToken = '関数に提供されたトークンは正しくありません';
RSHTTPSSPICannotPack = 'セキュリティパッケージがログオンバッファをマーシャリングできないため,ログオンができませんでした';
RSHTTPSSPIQOPNotSupported = 'メッセージごとの保護品質は,セキュリティパッケージによってサポートされていません';
RSHTTPSSPINoImpersonation = 'セキュリティコンテキストによってクライアントのインパーソネーションが許可されていません';
RSHTTPSSPILoginDenied = 'ログオンができません';
RSHTTPSSPIUnknownCredentials = 'パッケージに提供された証明書は認識できません';
RSHTTPSSPINoCredentials = '証明書がセキュリティパッケージで使用できません';
RSHTTPSSPIMessageAltered = '確認用に提供されたメッセージやシグネチャが変更されています';
RSHTTPSSPIOutOfSequence = '確認用に提供されたメッセージがシーケンス外です';
RSHTTPSSPINoAuthAuthority = '認証について届出がありません。';
RSHTTPSSPIContinueNeeded = '関数は無事終了しましたが,もう一度呼び出してコンテキストを完了する必要があります';
RSHTTPSSPICompleteNeeded = '関数は無事終了しましたが,CompleteToken を呼び出す必要があります';
RSHTTPSSPICompleteContinueNeeded = '関数は無事終了しましたが,CompleteToken およびこの関数を呼び出してコンテキストを完了する必要があります';
RSHTTPSSPILocalLogin = 'ログオンは終了しましたが,ネットワーク許可がありません。ログオンはローカルで得られる情報を使って行われました';
RSHTTPSSPIBadPackageID = '要求されたセキュリティパッケージがありません';
RSHTTPSSPIContextExpired = 'コンテキストが期限切れのため,使用できません。';
RSHTTPSSPIIncompleteMessage = '提供されたメッセージが不完全です。シグネチャが確認できませんでした。';
RSHTTPSSPIIncompleteCredentialNotInit = '提供された証明書は完全ではないため,確認できません。コンテキストが初期化できません。';
RSHTTPSSPIBufferTooSmall = '関数に提供されたバッファは小さすぎます。';
RSHTTPSSPIIncompleteCredentialsInit = '提供された証明書は完全ではないため,確認できません。コンテキストより追加情報が返されます。';
RSHTTPSSPIRengotiate = 'コンテキストデータはピアとやり取りされなければなりません。';
RSHTTPSSPIWrongPrincipal = 'ターゲット一次名が正しくありません。';
RSHTTPSSPINoLSACode = 'このコンテキストと関連する LSA モードコンテキストがありません。';
RSHTTPSSPITimeScew = 'クライアントとサーバーマシンのクロックがずれています。';
RSHTTPSSPIUntrustedRoot = '証明書チェインは,信用されない機関によって発行されています。';
RSHTTPSSPIIllegalMessage = '受信されたメッセージは不要か,形式が正しくありません。';
RSHTTPSSPICertUnknown = '証明書の処理中に不明なエラーが発生しました。';
RSHTTPSSPICertExpired = '受信した証明書は期限切れです。';
RSHTTPSSPIEncryptionFailure = '指定されたデータが暗号化できません。';
RSHTTPSSPIDecryptionFailure = '指定されたデータが暗号解読できません。';
RSHTTPSSPIAlgorithmMismatch = '共通のアルゴリズムがないので,クライアントとサーバーが通信できません。';
RSHTTPSSPISecurityQOSFailure = '要求されたサービス品質におけるエラーのため,セキュリティコンテキストが確立できませんでした(たとえば相互認証やデリゲーション)。';
RSHTTPSSPISecCtxWasDelBeforeUpdated = 'セキュリティ コンテキストが完了前に削除されました。これはログオンの失敗であると考えられます。';
RSHTTPSSPIClientNoTGTReply = 'クライアントはコンテキストをネゴシエートしようとしており、サーバーはユーザー対ユーザー認証を要求していますが、TGT 応答を送信しませんでした。';
RSHTTPSSPILocalNoIPAddr = 'ローカル マシンに IP アドレスがないため、要求されたタスクを遂行できません。';
RSHTTPSSPIWrongCredHandle = '与えられた資格情報ハンドルは、セキュリティ コンテキストに関連付けられている資格情報と一致しません。';
RSHTTPSSPICryptoSysInvalid = '必要な関数が使用不能なため、暗号システムまたはチェックサム機能が無効です。';
RSHTTPSSPIMaxTicketRef = 'チケット参照の最大回数を超えました。';
RSHTTPSSPIMustBeKDC = 'ローカル マシンは Kerberos KDC (ドメイン コントローラ) でなければなりませんが、そうなっていません。';
RSHTTPSSPIStrongCryptoNotSupported = 'セキュリティ ネゴシエーションの相手側では強力な暗号が必要ですが、それはローカル マシンではサポートされていません。';
RSHTTPSSPIKDCReplyTooManyPrincipals = 'KDC の応答に複数のプリンシパル名が含まれていました。';
RSHTTPSSPINoPAData = '使用する暗号化タイプ (etype) のヒントとなる PA データが見つかるはずですが、見つかりませんでした。';
RSHTTPSSPIPKInitNameMismatch = 'クライアント証明書に有効な UPN が含まれていないか、クライアント証明書がログオン要求のクライアント名と一致しません。管理者に連絡してください。';
RSHTTPSSPISmartcardLogonReq = 'スマートカード ログオンが必要ですが、使用されませんでした。';
RSHTTPSSPISysShutdownInProg = 'システムを停止中です。';
RSHTTPSSPIKDCInvalidRequest = '無効な要求が KDC に送信されました。';
RSHTTPSSPIKDCUnableToRefer = '要求されたサービスの参照を KDC が生成できませんでした。';
RSHTTPSSPIKDCETypeUnknown = '要求された暗号化タイプは KDC ではサポートされていません。';
RSHTTPSSPIUnsupPreauth = 'サポートされていない認証前メカニズムが Kerberos パッケージに提供されました。';
RSHTTPSSPIDeligationReq = '要求された操作を完了できません。コンピュータは委任に対して信頼されている必要があり、現在のユーザー アカウントは委任可能なように構成されている必要があります。';
RSHTTPSSPIBadBindings = 'クライアントに提供された SSPI チャネル バインディングが正しくありませんでした。';
RSHTTPSSPIMultipleAccounts = '受信した証明書は複数のアカウントにマッピングされました。';
RSHTTPSSPINoKerbKey = 'SEC_E_NO_KERB_KEY';
RSHTTPSSPICertWrongUsage = '証明書は要求された用途には無効です。';
RSHTTPSSPIDowngradeDetected = 'セキュリティを脅かすおそれのある試みをシステムが検出しました。認証を行ったサーバーに必ず接続できるようにしてください。';
RSHTTPSSPISmartcardCertRevoked = '認証に使用されたスマートカード証明書が取り消されました。システム管理者に連絡してください。イベント ログに追加情報が記載されている可能性があります。';
RSHTTPSSPIIssuingCAUntrusted = '認証に使用されたスマートカード証明書の処理中に、信頼できない認証局が検出されました。システム管理者に連絡してください。';
RSHTTPSSPIRevocationOffline = '認証に使用されたスマートカード証明書の取り消し状態を判定できませんでした。システム管理者に連絡してください。';
RSHTTPSSPIPKInitClientFailure = '認証に使用されたスマートカード証明書は信頼できませんでした。システム管理者に連絡してください。';
RSHTTPSSPISmartcardExpired = '認証に使用されたスマートカード証明書の有効期限が切れました。システム管理者に連絡してください。';
RSHTTPSSPINoS4UProtSupport = 'Kerberos サブシステムでエラーが発生しました。ユーザー向けのサービスをサポートしていないドメイン コントローラーに対して、ユーザー プロトコルのサービスが要求されました。';
RSHTTPSSPICrossRealmDeligationFailure = 'このサーバーは、サーバー領域外のターゲットについての Kerberos 制約付き委任要求を行おうとしました。これはサポートされておらず、このサーバーの Allowed-to-Delegate-to リストに構成ミスがあることを示しています。管理者に連絡してください。';
RSHTTPSSPIRevocationOfflineKDC = 'スマートカード認証に使用されたドメイン コントローラ証明書の取り消し状態を判定できませんでした。システム イベント ログに追加情報が記載されています。システム管理者に連絡してください。';
RSHTTPSSPICAUntrustedKDC = '認証に使用されたドメイン コントローラ証明書の処理中に、信頼できない認証局が検出されました。システム イベント ログに追加情報が記載されています。システム管理者に連絡してください。';
RSHTTPSSPIKDCCertExpired = 'スマートカード ログオンに使用されたドメイン コントローラ証明書の有効期限が切れました。システム管理者に連絡し、システム イベント ログの内容を知らせてください。';
RSHTTPSSPIKDCCertRevoked = 'スマートカード ログオンに使用されたドメイン コントローラ証明書が取り消されました。システム管理者に連絡し、システム イベント ログの内容を知らせてください。';
RSHTTPSSPISignatureNeeded = 'ユーザーが認証を行うには、まず、署名操作を行う必要があります。';
RSHTTPSSPIInvalidParameter = '関数に渡されたパラメータのうち 1 つ以上が無効でした。';
RSHTTPSSPIDeligationPolicy = 'クライアント ポリシーにより、ターゲット サーバーに対する資格情報の委譲は許されていません。';
RSHTTPSSPIPolicyNTLMOnly = 'クライアント ポリシーにより、NLTM 認証のみを使用したターゲット サーバーに対する資格情報の委譲は許されていません。';
RSHTTPSSPINoRenegotiation = '受信側が再ネゴシエーション要求を拒否しました。';
RSHTTPSSPINoContext = '必要なセキュリティ コンテキストが存在しません。';
RSHTTPSSPIPKU2UCertFailure = '関連する証明書を利用しようとしたときに、PKU2U プロトコルでエラーが発生しました。';
RSHTTPSSPIMutualAuthFailed = 'サーバー コンピュータの ID を確認できませんでした。';
RSHTTPSSPIUnknwonError = '原因不明のエラー';
{
Note to translators - the parameters for the next message are below:
Failed Function Name
Error Number
Error Number
Error Message by Number
}
RSHTTPSSPIErrorMsg = 'SSPI %s がエラー #%d(0x%x) を返します: %s';
RSHTTPSSPIInterfaceInitFailed = 'SSPI インターフェイスが正しく初期化できません';
RSHTTPSSPINoPkgInfoSpecified = 'PSecPkgInfo が指定されていません';
RSHTTPSSPINoCredentialHandle = '証明書ハンドルが取得されていません';
RSHTTPSSPICanNotChangeCredentials = 'ハンドル取得後は証明書ファイルを変更できません。Release を先に使用してください';
RSHTTPSSPIUnknwonCredentialUse = '不明な証明書の使用';
RSHTTPSSPIDoAuquireCredentialHandle = 'AcquireCredentialsHandle を最初に実行';
RSHTTPSSPICompleteTokenNotSupported = 'CompleteAuthToken はサポートされていません';
implementation
end.
|
unit uFrmMDIBill;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmMDI, ComCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, dxBar, dxBarExtItems, cxClasses,
ImgList, ActnList, DB, DBClient, cxGridLevel, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGrid,
cxContainer, cxTreeView, ExtCtrls, cxLabel, cxDropDownEdit, cxCalendar,
cxTextEdit, cxMaskEdit, cxButtonEdit, uDefCom, uBillData, uPackData,
uModelBaseIntf, uModelFunIntf, uModelFlowIntf;
type
TfrmMDIBill = class(TfrmMDI)
pnlBillTitle: TPanel;
pnlBillMaster: TPanel;
lblBillTitle: TcxLabel;
edtBillNumber: TcxButtonEdit;
deBillDate: TcxDateEdit;
lblBillDate: TcxLabel;
lblBillNumber: TcxLabel;
btnNewBill: TdxBarLargeButton;
actNewBill: TAction;
bpmSave: TdxBarPopupMenu;
btnSaveDraft: TdxBarButton;
btnSaveSettle: TdxBarButton;
btnSave: TdxBarLargeButton;
actSaveDraft: TAction;
actSaveSettle: TAction;
actSelectBill: TAction;
btnSelectBill: TdxBarLargeButton;
btnFlow: TdxBarLargeButton;
actFlow: TAction;
procedure actSaveDraftExecute(Sender: TObject);
procedure actSaveSettleExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actFlowExecute(Sender: TObject);
private
{ Private declarations }
FBillSaveState: TBillSaveState; //单据保存类型状态
FBillOpenState: TBillOpenState; //单据是以什么状态打开
FBillCurrState: TBillCurrState; //当前单据变成了什么状态
protected
FVchCode, FVchType, FNewVchCode: Integer;//单据ID,单据类型
FModelBill: IModelBill;
FModelFlow: IModelFlow;//审批相关
FReadOnlyFlag: boolean;//是否能够修改单据
procedure BeforeFormShow; override;
procedure BeforeFormDestroy; override;
procedure InitParamList; override;//对MoudleNo点赋值应该放在此函数里面才会判断是否有查看单据点权限
procedure SetTitle(const Value: string); override;
function LoadBillData: Boolean; virtual;//加载单据
function LoadBillDataMaster: Boolean; virtual;//加载表头数据
function LoadBillDataGrid: Boolean; virtual;//加载表格数据
function GetLoadDSign: string; virtual; abstract;//得到获取单据明细的标志
procedure InitMasterTitles(Sender: TObject); virtual; //初始化表头
procedure InitGrids(Sender: TObject); virtual; //初始化表体
procedure InitMenuItem(Sender: TObject); virtual; //初始化右建菜单
procedure InitOthers(Sender: TObject); virtual; ////初始化其它
function BeforeSaveBill(ASaveState: TBillSaveState): Boolean; virtual;
procedure SetReadOnly(AReadOnly: Boolean = True); virtual;//设置单据是否只读
function CheckSaveBillData(ASaveState: TBillSaveState): Boolean; virtual;//保存前检查数据
function SaveBillData(ASaveState: TBillSaveState; APrint: Boolean = false): Boolean; virtual;
function SaveRecBillData(ABillSaveType: TBillSaveState): Integer; //保存单据
function SaveToDraft: Boolean; virtual; //存草稿
function SaveToSettle: Boolean; virtual; //存过账
function SaveDraftData(ADraft: TBillSaveState): Integer; virtual;//保存草稿或过账
function SaveMasterData(const ABillMasterData: TBillData): Integer; virtual; //保存主表信息
function SaveDetailData(const ABillDetailData: TPackData): Integer; virtual; //保存从表信息
function SaveDetailAccount(const ADetailAccountData: TPackData): integer; virtual; //保存财务信息
function LoadOnePtype(ARow: Integer; AData: TSelectBasicData; IsImport: Boolean = False): Boolean; virtual;//加载一条记录
procedure GetBillNumber;
procedure SetQtyPriceTotal(ATotal, AQty, APrice: string);//设置数量单价金额的公式
function AuditState: Integer; //此单据的审批状态 0没有审批,-1审批中,1审批完成, 2终止
public
{ Public declarations }
property BillSaveState: TBillSaveState read FBillSaveState write FBillSaveState;
property BillOpenState: TBillOpenState read FBillOpenState write FBillOpenState;
property BillCurrState: TBillCurrState read FBillCurrState write FBillCurrState;
end;
var
frmMDIBill: TfrmMDIBill;
implementation
uses uSysSvc, uBaseFormPlugin, uMoudleNoDef, uParamObject, uModelControlIntf, uMainFormIntf,
uBaseInfoDef, uGridConfig, uFrmApp, uVchTypeDef, uOtherIntf, uFunApp, uModelLimitIntf;
{$R *.dfm}
{ TfrmMDIBill }
procedure TfrmMDIBill.BeforeFormDestroy;
begin
inherited;
end;
procedure TfrmMDIBill.BeforeFormShow;
begin
inherited;
FGridItem.SetGridCellSelect(True);
FModelFlow := IModelFlow((SysService as IModelControl).GetModelIntf(IModelFlow));
InitMasterTitles(Self);
InitGrids(self);
InitMenuItem(self);
InitOthers(self);
LoadBillData();
if not FReadOnlyFlag then
begin
FReadOnlyFlag := not CheckLimit(MoudleNo, Limit_Bill_Input, False);
SetReadOnly(FReadOnlyFlag);
end;
end;
function TfrmMDIBill.BeforeSaveBill(ASaveState: TBillSaveState): Boolean;
var
aList: TParamObject;
aRet: Integer;
aErrorMsg: string;
begin
Result := False;
// 具体单据中检查
if not CheckSaveBillData(ASaveState) then Exit;
aList := TParamObject.Create;
try
aList.Add('@DoWork', 1);
aList.Add('@VchType', FVchType);
aList.Add('@OldVchCode', FVchcode);
aList.Add('@NewVchCode', 0);
aList.Add('@BillDate', '');
aList.Add('@VchNumberIn', edtBillNumber.Text);
if FModelBill.GetVchNumber(aList) <> 0 then Exit
finally
aList.Free;
end;
Result := True;
end;
procedure TfrmMDIBill.InitGrids(Sender: TObject);
begin
end;
procedure TfrmMDIBill.InitMasterTitles(Sender: TObject);
begin
deBillDate.Text := FormatdateTime('YYYY-MM-DD', Now);
end;
procedure TfrmMDIBill.InitMenuItem(Sender: TObject);
begin
end;
procedure TfrmMDIBill.InitOthers(Sender: TObject);
var
aCdsTmp: TClientDataSet;
aParam: TParamObject;
aState: Integer;
begin
aState := AuditState();
if (BillOpenState <> bosAudit) and (aState = 0) then
begin
actFlow.Caption := '提交审批';
aCdsTmp := TClientDataSet.Create(nil);
try
aParam := TParamObject.Create;
try
aParam.Add('@QryType', Flow_TaskProc);
aParam.Add('@Custom', '');
FModelFlow.FlowData(aParam, aCdsTmp);
actFlow.Enabled := False;
aCdsTmp.First;
while not aCdsTmp.Eof do
begin
if aCdsTmp.FieldByName('WorkID').AsString = IntToStr(MoudleNo) then
begin
actFlow.Enabled := True;
Exit;
end;
aCdsTmp.Next;
end
finally
aParam.Free;
end;
finally
aCdsTmp.Free;
end;
end
else
begin
BillOpenState := bosAudit;
actFlow.Caption := '审批';
if aState = 1 then
begin
actFlow.Caption := '审批完成';
actFlow.Enabled := False;
actSaveDraft.Enabled := False;
actSaveSettle.Enabled := False;
end
else if aState = 2 then
begin
actFlow.Caption := '审批终止';
actFlow.Enabled := False;
actSaveDraft.Enabled := False;
actSaveSettle.Enabled := False;
end;
end;
end;
procedure TfrmMDIBill.InitParamList;
begin
BillSaveState := sbNone;
if ParamList.Count = 0 then
begin
FVchtype := VchType_Order_Sale;
FVchcode := 0;
BillOpenState := bosNew;
end
else
begin
FVchtype := ParamList.AsInteger('Vchtype');
FVchcode := ParamList.AsInteger('Vchcode');
BillOpenState := TBillOpenState(ParamList.AsInteger('bosState'));
end;
inherited;
end;
function TfrmMDIBill.LoadBillDataGrid: Boolean;
var
aInList: TParamObject;
aCdsD: TClientDataSet;
aBillState: Integer;
begin
if FVchcode = 0 then //新单据
begin
FGridItem.ClearData;
end
else
begin
//加载单据
aInList := TParamObject.Create;
aCdsD := TClientDataSet.Create(nil);
try
aInList.Add('VchCode', FVchCode);
aInList.Add('VchType', FVchType);
aBillState := Ord(BillOpenState);
aInList.Add('BillState', Ord(BillOpenState));
FModelBill.LoadBillDataDetail(aInList, aCdsD);
FGridItem.LoadData(aCdsD);
finally
aCdsD.Free;
aInList.Free;
end;
end;
end;
function TfrmMDIBill.LoadBillDataMaster: Boolean;
var
aInList, aMasterList: TParamObject;
begin
DBComItem.ClearItemData();
if FVchCode = 0 then
begin
GetBillNumber();
end
else
begin
aInList := TParamObject.Create;
aMasterList := TParamObject.Create;
try
aInList.Add('VchCode', FVchCode);
aInList.Add('VchType', FVchType);
FModelBill.LoadBillDataMaster(aInList, aMasterList);
if aMasterList.Count = 0 then
begin
(SysService as IMsgBox).MsgBox('该单据不存在,可能已经被删除!');
FrmClose();
end;
DBComItem.GetDataFormParam(aMasterList);
finally
aMasterList.Free;
aInList.Free;
end;
end;
end;
function TfrmMDIBill.SaveBillData(ASaveState: TBillSaveState;
APrint: Boolean): Boolean;
begin
if not BeforeSaveBill(ASaveState) then Exit;
if ASaveState = soDraft then
begin
if not SaveToDraft() then Exit
end
else if ASaveState = soSettle then
begin
if not SaveToSettle() then Exit;
end;
if (BillOpenState = bosNew)then
begin
FVchcode := 0;
LoadBillData();
end;
end;
function TfrmMDIBill.SaveDetailAccount(
const ADetailAccountData: TPackData): integer;
begin
end;
function TfrmMDIBill.SaveDetailData(
const ABillDetailData: TPackData): Integer;
begin
end;
function TfrmMDIBill.SaveMasterData(
const ABillMasterData: TBillData): Integer;
begin
end;
function TfrmMDIBill.SaveRecBillData(
ABillSaveType: TBillSaveState): Integer;
begin
end;
function TfrmMDIBill.SaveToDraft: Boolean;
begin
Result := False;
if SaveDraftData(soDraft) = 0 then
begin
Result := True;
end;
end;
function TfrmMDIBill.SaveToSettle: Boolean;
begin
Result := False;
if SaveDraftData(soSettle) = 0 then
begin
Result := True;
end;
end;
procedure TfrmMDIBill.actSaveDraftExecute(Sender: TObject);
begin
inherited;
SaveBillData(soDraft);
end;
procedure TfrmMDIBill.actSaveSettleExecute(Sender: TObject);
begin
inherited;
CheckLimit(MoudleNo, Limit_Bill_Settle);
SaveBillData(soSettle);
end;
function TfrmMDIBill.LoadOnePtype(ARow: Integer; AData: TSelectBasicData;
IsImport: Boolean): Boolean;
begin
end;
procedure TfrmMDIBill.SetTitle(const Value: string);
begin
inherited;
lblBillTitle.Caption := Value;
end;
function TfrmMDIBill.SaveDraftData(ADraft: TBillSaveState): Integer;
var
aBillData: TBillData;
aOutPutData: TParamObject;
aNewVchcode: Integer;
begin
FGridItem.GridPost();
Result := -1;
aBillData := TBillData.Create;
aOutPutData := TParamObject.Create;
try
aBillData.PRODUCT_TRADE := 0;
aBillData.Draft := ADraft;
aBillData.IsModi := false;
aBillData.VchCode := FVchcode;
aBillData.VchType := FVchtype;
SaveMasterData(aBillData);
SaveDetailData(aBillData.DetailData);
SaveDetailAccount(aBillData.AccountData);
aNewVchcode := FModelBill.SaveBill(aBillData, aOutPutData);
if aNewVchcode >= 0 then
begin
Result := FModelBill.BillCreate(0, FVchType, aNewVchcode, aBillData.VchCode, aBillData.Draft, aOutPutData);
if Result = 0 then FNewVchCode := aNewVchcode;
end;
finally
aOutPutData.Free;
aBillData.Free;
end;
end;
function TfrmMDIBill.LoadBillData: Boolean;
begin
//加载单据
if BillOpenState = bosNew then
begin
BillCurrState := bcsEdit;
FReadOnlyFlag := False;
end
else if BillOpenState = bosEdit then
begin
BillCurrState := bcsEdit;
FReadOnlyFlag := False;
end
else if (BillOpenState in [bosEdit, bosSett, bosModi]) then
begin
if BillOpenState <> bosSett then
begin
BillCurrState := bcsEdit;
FReadOnlyFlag := False;
end
else
begin
BillCurrState := bcsView;
FReadOnlyFlag := True;
end;
end
else if BillOpenState in [bosView, bosAudit] then
begin
BillCurrState := bcsView; //查看凭证
FReadOnlyFlag := True;
actSaveDraft.Enabled := False;
actSaveSettle.Enabled := False;
actSelectBill.Enabled := False;
end
else Exit; //错误参数
LoadBillDataMaster();
LoadBillDataGrid();
SetReadOnly(FReadOnlyFlag);
end;
procedure TfrmMDIBill.GetBillNumber;
var
aList: TParamObject;
aRet: Integer;
aErrorMsg: string;
begin
aList := TParamObject.Create;
try
aList.Add('@DoWork', 2);
aList.Add('@VchType', FVchType);
aList.Add('@OldVchCode', 0);
aList.Add('@NewVchCode', 0);
aList.Add('@BillDate', FormatDateTime('YYYY-MM-DD', deBillDate.Date));
aList.Add('@VchNumberIn', '');
if FModelBill.GetVchNumber(aList) = 0 then
begin
edtBillNumber.Text := aList.AsString('@VchNumber');
end;
finally
aList.Free;
end;
end;
function TfrmMDIBill.CheckSaveBillData(
ASaveState: TBillSaveState): Boolean;
var
aCdsTmp: TClientDataSet;
aParam: TParamObject;
begin
Result := False;
if AuditState() <> 0 then
begin
(SysService as IMsgBox).MsgBox('存在审批流程,不能修改!');
Exit;
end;
Result := True;
end;
procedure TfrmMDIBill.SetQtyPriceTotal(ATotal, AQty, APrice: string);
var
aColInfo: TColInfo;
begin
aColInfo := FGridItem.FindColByFieldName(ATotal);
aColInfo.AddExpression(AQty + '=[' + ATotal + ']/[' + APrice + ']');
aColInfo := FGridItem.FindColByFieldName(AQty);
aColInfo.AddExpression(ATotal + '=[' + AQty + ']*[' + APrice + ']');
aColInfo := FGridItem.FindColByFieldName(APrice);
aColInfo.AddExpression(ATotal + '=[' + AQty + ']*[' + APrice + ']');
end;
procedure TfrmMDIBill.SetReadOnly(AReadOnly: Boolean);
begin
DBComItem.SetReadOnly(nil, AReadOnly);
FGridItem.SetGridCellSelect(not AReadOnly);
end;
procedure TfrmMDIBill.FormCreate(Sender: TObject);
begin
inherited;
try
CheckLimit(MoudleNo, Limit_Bill_View);
except
on e:Exception do
begin
(SysService as IMsgBox).MsgBox(e.Message);
ShowStyle := fssClose;
end;
end;
end;
procedure TfrmMDIBill.actFlowExecute(Sender: TObject);
var
aParam: TParamObject;
begin
inherited;
aParam := TParamObject.Create;
try
aParam.Add('BillType', FVchType);
aParam.Add('BillID', FVchCode);
aParam.Add('WorkID', MoudleNo);
if BillOpenState <> bosAudit then
begin
if (FVchType = 0) or (FVchCode = 0) then
begin
(SysService as IMsgBox).MsgBox('请先保存单据,在提交审批!');
Exit;
end;
aParam.Add('Info', '单据类型:' + Title + ',单据号:' + edtBillNumber.Text);
if FModelFlow.SaveOneFlow(aParam) <> 0 then
begin
aParam.Add('ProcePathID', ParamList.AsInteger('ProcePathID'));
end;
end
else
begin
aParam.Add('ProcePathID', ParamList.AsInteger('ProcePathID'));
(SysService as IMainForm).CallFormClass(fnFlowWork, aParam);
end;
finally
aParam.Free;
end;
end;
function TfrmMDIBill.AuditState: Integer;
var
aCdsTmp: TClientDataSet;
aParam: TParamObject;
begin
Result := -99;
if FVchCode <> 0 then
begin
aCdsTmp := TClientDataSet.Create(nil);
try
aParam := TParamObject.Create;
try
aParam.Add('@QryType', Flow_OneWork);
aParam.Add('@BillID', FVchCode);
aParam.Add('@BillType', FVchType);
aParam.Add('@WorkID', MoudleNo);
FModelFlow.FlowData(aParam, aCdsTmp);
if aCdsTmp.RecordCount > 0 then
begin
aCdsTmp.First;
while not aCdsTmp.Eof do
begin
if aCdsTmp.FieldByName('ProceResult').AsInteger = Flow_State_Stop then
begin
Result := 2;
Exit;
end
else if aCdsTmp.FieldByName('ProceResult').AsInteger = 0 then
begin
Result := -1;
if aCdsTmp.FieldByName('FlowETypeID').AsString = OperatorID then
begin
ParamList.Add('ProcePathID', aCdsTmp.FieldByName('ProcePathID').AsInteger);
end;
end;
aCdsTmp.Next;
end;
if Result = -99 then Result := 1;
Exit;
end;
finally
aParam.Free;
end;
finally
aCdsTmp.Free;
end;
end;
Result := 0;
end;
end.
|
unit SSLDemo.UnpackPKCS7Frame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TUnpackPKCS7Frame = class(TFrame)
lblPKCS7File: TLabel;
edtInputFileName: TEdit;
lblOutputFile: TLabel;
edtOutputFileName: TEdit;
btnUnpack: TButton;
chkVerify: TCheckBox;
chkNoVerify: TCheckBox;
procedure btnUnpackClick(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
Winapi.ShellAPI,
OpenSSL.SMIMEUtils;
{$R *.dfm}
procedure TUnpackPKCS7Frame.btnUnpackClick(Sender: TObject);
var
SMIME: TSMIMEUtil;
Verify: Integer;
InputStream, OutputStream: TMemoryStream;
begin
SMIME := TSMIMEUtil.Create;
InputStream := TMemoryStream.Create;
OutputStream := TMemoryStream.Create;
try
InputStream.LoadFromFile(edtInputFileName.Text);
Verify := SMIME.Decrypt(InputStream, OutputStream, chkVerify.Checked, chkNoVerify.Checked);
if chkVerify.Checked then
begin
if Verify = 1 then
ShowMessage('Verification Successfull')
else
ShowMessage('Verification Failure')
end;
OutputStream.SaveToFile(edtOutputFileName.Text);
ShellExecute(Handle, 'open', PChar(edtOutputFileName.Text), '', '', SW_SHOWDEFAULT);
finally
InputStream.Free;
OutputStream.Free;
SMIME.Free;
end;
end;
constructor TUnpackPKCS7Frame.Create(AOwner: TComponent);
var
TestFolder: string;
begin
inherited;
TestFolder := StringReplace(ExtractFilePath(ParamStr(0)), 'Samples\SSLDemo', 'TestData', [rfReplaceAll, rfIgnoreCase]);
edtInputFileName.Text := TestFolder + 'TestPKCS7.pdf.p7m';
edtOutputFileName.Text := TestFolder + 'TestPKCS7-out.pdf';
end;
end.
|
unit SDUExtCtrls;
// TSDFileDropPanel: A panel onto which files can be dropped.
// Example usage: Place a TSDFileDropPanel onto a form, place a list control
// on top of the panel; the list control may not have files (and
// directories) dragged and dropped onto it.
interface
uses
ExtCtrls, Classes, Messages;
type
TNotifyFileDirectoryDropEvent = procedure (Sender: TObject; filename: string) of object;
TSDFileDropPanel = class(TPanel)
private
FOnFileDrop: TNotifyFileDirectoryDropEvent;
FOnDirectoryDrop: TNotifyFileDirectoryDropEvent;
procedure DoOnFileDrop(filename: string);
procedure DoOnDirectoryDrop(dirname: string);
public
constructor Create(AOwner: TComponent); override;
procedure AcceptFiles(var msg: TMessage); message WM_DROPFILES;
published
property OnFileDrop: TNotifyFileDirectoryDropEvent read FOnFileDrop write FOnFileDrop;
property OnDirectoryDrop: TNotifyFileDirectoryDropEvent read FOnDirectoryDrop write FOnDirectoryDrop;
end;
procedure Register;
implementation
uses
ShellAPI, SysUtils;
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDFileDropPanel]);
end;
constructor TSDFileDropPanel.Create(AOwner: TComponent);
begin
inherited;
if not(csDesigning in ComponentState) then
begin
DragAcceptFiles(self.Handle, TRUE);
end;
end;
procedure TSDFileDropPanel.AcceptFiles(var msg: TMessage);
const
MAX_PATH_LENGTH = 2048;
var
i,
cntDrop: integer;
tmpFilename: array [0..(MAX_PATH_LENGTH-1)] of char;
begin
cntDrop := DragQueryFile(
msg.WParam,
$FFFFFFFF,
tmpFilename,
length(tmpFilename)
);
// query Windows one at a time for the file name
for i := 0 to (cntDrop-1) do
begin
DragQueryFile(
msg.WParam,
i,
tmpFilename,
length(tmpFilename)
);
if DirectoryExists(tmpFilename) then
begin
DoOnDirectoryDrop(tmpFilename);
end
else
begin
DoOnFileDrop(tmpFilename);
end;
end;
DragFinish(msg.WParam);
end;
procedure TSDFileDropPanel.DoOnFileDrop(filename: string);
begin
if assigned(FOnFileDrop) then
begin
FOnFileDrop(self, filename);
end;
end;
procedure TSDFileDropPanel.DoOnDirectoryDrop(dirname: string);
begin
if assigned(FOnDirectoryDrop) then
begin
FOnDirectoryDrop(self, dirname);
end;
end;
END.
|
{
SuperMaximo GameLibrary : Display unit
by Max Foster
License : http://creativecommons.org/licenses/by/3.0/
}
unit Display;
{$mode objfpc}{$H+}
interface
uses dglOpenGL, ShaderClass;
const
//Texture unit constants
TEXTURE0 = GL_TEXTURE0;
TEXTURE1 = GL_TEXTURE1;
TEXTURE2 = GL_TEXTURE2;
TEXTURE3 = GL_TEXTURE3;
TEXTURE4 = GL_TEXTURE4;
TEXTURE5 = GL_TEXTURE5;
TEXTURE6 = GL_TEXTURE6;
TEXTURE7 = GL_TEXTURE7;
TEXTURE8 = GL_TEXTURE8;
TEXTURE9 = GL_TEXTURE9;
TEXTURE10 = GL_TEXTURE10;
TEXTURE11 = GL_TEXTURE11;
TEXTURE12 = GL_TEXTURE12;
TEXTURE13 = GL_TEXTURE13;
TEXTURE14 = GL_TEXTURE14;
TEXTURE15 = GL_TEXTURE15;
//Matrix constants
MODELVIEW_MATRIX = 0;
PERSPECTIVE_MATRIX = 1;
ORTHOGRAPHIC_MATRIX = 2;
PROJECTION_MATRIX = 3;
IDENTITY_MATRIX = 4; //Make sure IDENTITY_MATRIX is last
//Blend function constants
ZERO = GL_ZERO;
ONE = GL_ONE;
SRC_COLOR = GL_SRC_COLOR;
ONE_MINUS_SRC_COLOR = GL_ONE_MINUS_SRC_COLOR;
DST_COLOR = GL_DST_COLOR;
ONE_MINUS_DST_COLOR = GL_ONE_MINUS_DST_COLOR;
SRC_ALPHA = GL_SRC_ALPHA;
ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA;
DST_ALPHA = GL_DST_ALPHA;
ONE_MINUS_DST_ALPHA = GL_ONE_MINUS_DST_ALPHA;
CONSTANT_COLOR = GL_CONSTANT_COLOR_EXT;
ONE_MINUS_CONSTANT_COLOR = GL_ONE_MINUS_CONSTANT_COLOR;
CONSTANT_ALPHA = GL_CONSTANT_ALPHA;
ONE_MINUS_CONSTANT_ALPHA = GL_ONE_MINUS_CONSTANT_ALPHA;
SRC_ALPHA_SATURATE = GL_SRC_ALPHA_SATURATE;
//Blend function equation constants
FUNC_ADD = GL_FUNC_ADD;
FUNC_SUBTRACT = GL_FUNC_SUBTRACT;
FUNC_REVERSE_SUBTRACT = GL_FUNC_REVERSE_SUBTRACT;
MIN = GL_MIN;
MAX = GL_MAX;
type
customDrawFunctionType = procedure(pClass : Pointer; shader : PShader; data : Pointer);
//Create a window to draw on with the specified dimentions. ('depth' is the depth in 3D space). 'maxFramerate' is the maximum framerate the game
//is allowed to run at. The library automatically compensates for framerate issues. Set maxFramrate to 0 to go at full pelt!
function initDisplay(width, height, depth : word; maxFramerate : word = 0; fullScreen : boolean = false; windowTitle : string = 'My Game') : boolean;
procedure quitDisplay;
//Get the window dimentions and resize it
function screenWidth : integer;
function screenHeight : integer;
function resizeScreen(width, height : word; fullScreen : boolean = false) : boolean;
//Get projection matrices for both perspective and orthographic projection
function getPerspectiveMatrix(left, right, bottom, top, front, back : real) : matrix4d;
function getPerspectiveMatrix(angle, aspectRatio, front, back : real) : matrix4d;
function getOrthographicMatrix(left, right, bottom, top, front, back : real) : matrix4d;
//Bind a shader to be used when an object is drawn (has the same effect as TShader.bind)
procedure globalBindShader(shader : PShader);
function globalBoundShader : PShader;
//Overwrite a sprite the default sprite drawing procedure with your own
procedure globalBindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType);
function globalBoundCustomDrawFunction : customDrawFunctionType;
//Binds the OpenGL texture unit specified so that you can bind multiple textures at once
//Is equivalent to calling glActiveTexture
procedure bindTextureUnit(textureUnit : GLenum);
function boundTextureUnit : GLenum;
//Bind the matrix stack that you want to manipulate
procedure setMatrix(matrixId : integer);
function currentMatrix : integer;
//Copy the data from the top of one matrix stack to another
procedure copyMatrix(srcMatrixId, dstMatrixId : integer);
//Copy your own matrix data to the top of a matrix stack
procedure copyMatrix(srcMatrix : matrix4d; dstMatrixId : integer);
//Return the matrix data on the top of the matrix stack
function getMatrix(matrixId : integer) : matrix4d;
//Push the current matrix data onto the stack, which effectively 'saves' the matrix data
//and gives you another copy of the matrix to use
procedure pushMatrix;
//Pop the current matrix of the stack and go back to the matrix state that you were using before
procedure popMatrix;
//Perform a translation with the specified amounts in each axis
procedure translateMatrix(x, y, z : real);
//Perform a rotation with the specified angle, and ratios of that angle in each axis
procedure rotateMatrix(angle, x, y, z : real);
//Scale the matrix up or down in each axis
procedure scaleMatrix(xScale, yScale, zScale : real);
//Multiply two 4x4 matrices together
function multiplyMatrix(operandMatrix, multiplierMatrix : matrix4d) : matrix4d;
//Set a 4x4 matrix to the identity matrix
procedure initIdentityMatrix(var dstMatrix : matrix4d);
//Swaps the framebuffers and tells the Input unit that it can gather input data again. This procedure MUST be called at least once
//in a game loop!
procedure refreshScreen;
function getFramerate : word;
function getTickDifference : word; //Get the time difference between frames
//Set the 'ideal' framerate. This is the speed that the game will simulate, independently of what framerate the game is actually at
//This means that people with slower computers will not have the gameplay slowed down, and people with faster computers
//will not have the gameplay sped up. This can also be useful for slow motion effects!
procedure setIdealFramerate(newIdealFramerate : word);
function getIdealFramerate : word;
//Multiply values that you want to increment by independently of the framerate to the return value of this function.
//I.e. if you want A to equal 60 (starting from 0) in exactly one second when the idealFramerate is set to 60, just do:
//A += compensation;
//And A will equal 60 in one second (with an idealFramerate of 60) on any computer! For 120 in one second just use 2.0*compensation, etc.
function compensation : real;
//Enable/disable colour blending (have a look at some OpenGL documentation on glBlendFunc and glBlendEquation for a detailed explanation)
procedure enableBlending(srcBlendFunc : GLenum = ONE; dstBlendFunc : GLenum = ZERO; blendFuncEquation : GLenum = FUNC_ADD);
procedure disableBlending;
function blendingEnabled : boolean;
//Enable/disable depth testing in 3D space
procedure enableDepthTesting;
procedure disableDepthTesting;
function depthTestingEnabled : boolean;
//Return the OpenGL and GLSL version
function openGlVersion : real;
function glSlVersion : real;
//Return whether Vertex Array Objects are supported
function vertexArrayObjectSupported : boolean;
implementation
uses SDL, math, SysUtils, Input, GraphicalAssetClasses;
const
STACK_SIZE = 64;
var
screen : PSDL_Surface;
screenW, screenH, screenD, currentMatrixId, maximumFramerate, tickDifference, idealFramerate, framerate : word;
matrix : array[0..IDENTITY_MATRIX] of matrix4d;
matrixStack : array[0..IDENTITY_MATRIX-1] of array[0..STACK_SIZE-1] of matrix4d;
matrixLevel : array[0..IDENTITY_MATRIX-1] of integer;
blendingEnabled_, depthTestingEnabled_, vertexArrayObjectSupported_ : boolean;
boundShader_ : PShader = nil;
customDrawFunction : customDrawFunctionType = nil;
boundTextureUnit_ : GLenum = TEXTURE0;
ticks, lastTicks : Uint32;
openGlVersion_, glSlVersion_, compensation_ : real;
function initDisplay(width, height, depth : word; maxFramerate : word = 0; fullScreen : boolean = false; windowTitle : string = 'My Game') : boolean;
var
i : integer;
begin
if ((width > 0) and (height > 0)) then
begin
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
if (fullScreen) then screen := SDL_SetVideoMode(width, height, 32, SDL_OPENGL or SDL_FULLSCREEN) else screen := SDL_SetVideoMode(width, height, 32, SDL_OPENGL);
if (screen = nil) then
begin
result := false;
exit;
end;
initOpenGL;
readExtensions;
vertexArrayObjectSupported_ := (dglCheckExtension('GL_ARB_vertex_array_object') or dglCheckExtension('GL_ATI_vertex_array_object') or dglCheckExtension('GL_APPLE_vertex_array_object')
or (openGlVersion >= 3.0));
SDL_WM_SetCaption(pchar(windowTitle), pchar(windowTitle));
screenW := width;
screenH := height;
screenD := depth;
framerate := 0;
maximumFramerate := maxFramerate;
if (maxFramerate > 0) then idealFramerate := maxFramerate;
ticks := SDL_GetTicks;
lastTicks := 0;
tickDifference := 1;
idealFramerate := 60;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
depthTestingEnabled_ := true;
glDisable(GL_BLEND);
blendingEnabled_ := false;
initIdentityMatrix(matrix[IDENTITY_MATRIX]);
initIdentityMatrix(matrix[MODELVIEW_MATRIX]);
initIdentityMatrix(matrix[PROJECTION_MATRIX]);
matrix[PERSPECTIVE_MATRIX] := getPerspectiveMatrix(45.0, width/height, 1.0, depth);
matrix[ORTHOGRAPHIC_MATRIX] := getOrthographicMatrix(0.0, screenW, screenH, 0.0, 1.0, depth);
matrixStack[MODELVIEW_MATRIX][0] := matrix[MODELVIEW_MATRIX];
matrixStack[PERSPECTIVE_MATRIX][0] := matrix[PERSPECTIVE_MATRIX];
matrixStack[ORTHOGRAPHIC_MATRIX][0] := matrix[ORTHOGRAPHIC_MATRIX];
matrixStack[PROJECTION_MATRIX][0] := matrix[PROJECTION_MATRIX];
for i := 0 to IDENTITY_MATRIX-1 do matrixLevel[i] := 0;
currentMatrixId := MODELVIEW_MATRIX;
glViewport(0, 0, width, height);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
result := true;
end else result := false;
end;
procedure quitDisplay;
begin
end;
function screenWidth : integer;
begin
result := screenW;
end;
function screenHeight : integer;
begin
result := screenH;
end;
function screenDepth : integer;
begin
result := screenD;
end;
function resizeScreen(width, height : word; fullScreen : boolean = false) : boolean;
begin
if ((width > 0) and (height > 0) and (length(matrixStack[ORTHOGRAPHIC_MATRIX]) = 1)) then
begin
SDL_FreeSurface(screen);
if (fullScreen) then screen := SDL_SetVideoMode(width, height, 32, SDL_OPENGL or SDL_FULLSCREEN) else screen := SDL_SetVideoMode(width, height, 32, SDL_OPENGL);
if (screen = nil) then
begin
result := false;
end;
screenW := width;
screenH := height;
matrix[ORTHOGRAPHIC_MATRIX] := getOrthographicMatrix(0.0, screenW, screenH, 0.0, 1.0, screenD);
matrix[PERSPECTIVE_MATRIX] := getPerspectiveMatrix(45.0, screenW/screenH, 1.0, screenD);
glViewport(0, 0, width, height);
result := true;
end else result := false;
end;
function getPerspectiveMatrix(left, right, bottom, top, front, back : real) : matrix4d;
var
returnMatrix : matrix4d;
begin
returnMatrix[0] := (2.0*front)/(right-left);
returnMatrix[1] := 0.0;
returnMatrix[2] := 0.0;
returnMatrix[3] := 0.0;
returnMatrix[4] := 0.0;
returnMatrix[5] := (2.0*front)/(top-bottom);
returnMatrix[6] := 0.0;
returnMatrix[7] := 0.0;
returnMatrix[8] := (right+left)/(right-left);
returnMatrix[9] := (top+bottom)/(top-bottom);
returnMatrix[10] := (-(back+front))/(back-front);
returnMatrix[11] := -1.0;
returnMatrix[12] := 0.0;
returnMatrix[13] := 0.0;
returnMatrix[14] := (-2.0*back*front)/(back-front);
returnMatrix[15] := 0.0;
result := returnMatrix;
end;
function getPerspectiveMatrix(angle, aspectRatio, front, back : real) : matrix4d;
var
returnMatrix : matrix4d;
tangent, height, width : real;
begin
tangent := tan(degToRad(angle/2));
height := front*tangent;
width := height*aspectRatio;
returnMatrix := getPerspectiveMatrix(-width, width, -height, height, front, back);
result := returnMatrix;
end;
function getOrthographicMatrix(left, right, bottom, top, front, back : real) : matrix4d;
var
returnMatrix : matrix4d;
begin
returnMatrix[0] := 2.0/(right-left);
returnMatrix[1] := 0.0;
returnMatrix[2] := 0.0;
returnMatrix[3] := 0.0;
returnMatrix[4] := 0.0;
returnMatrix[5] := 2.0/(top-bottom);
returnMatrix[6] := 0.0;
returnMatrix[7] := 0.0;
returnMatrix[8] := 0.0;
returnMatrix[9] := 0.0;
returnMatrix[10] := -2.0/(back-front);
returnMatrix[11] := 0.0;
returnMatrix[12] := -((right+left)/(right-left));
returnMatrix[13] := -((top+bottom)/(top-bottom));
returnMatrix[14] := -((back+front)/(back-front));
returnMatrix[15] := 1.0;
result := returnMatrix;
end;
procedure globalBindShader(shader : PShader);
begin
glUseProgram(shader^.getProgram);
boundShader_ := shader;
end;
function globalBoundShader : PShader;
begin
result := boundShader_;
end;
procedure globalBindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType);
begin
customDrawFunction := newCustomDrawFunction;
end;
function globalBoundCustomDrawFunction : customDrawFunctionType;
begin
result := customDrawFunction;
end;
procedure bindTextureUnit(textureUnit : GLenum);
begin
glActiveTexture(textureUnit);
boundTextureUnit_ := textureUnit;
end;
function boundTextureUnit : GLenum;
begin
result := boundTextureUnit_;
end;
procedure setMatrix(matrixId : integer);
begin
if (currentMatrixId <> IDENTITY_MATRIX) then currentMatrixId := matrixId;
end;
function currentMatrix : integer;
begin
result := currentMatrixId;
end;
procedure copyMatrix(srcMatrixId, dstMatrixId : integer);
begin
if (dstMatrixId <> IDENTITY_MATRIX) then matrix[dstMatrixId] := matrix[srcMatrixId];
end;
procedure copyMatrix(srcMatrix : matrix4d; dstMatrixId : integer);
begin
if (dstMatrixId <> IDENTITY_MATRIX) then matrix[dstMatrixId] := srcMatrix;
end;
function getMatrix(matrixId : integer) : matrix4d;
begin
result := matrix[matrixId];
end;
procedure pushMatrix;
begin
if (matrixLevel[currentMatrixId] < STACK_SIZE) then
begin
matrixLevel[currentMatrixId] += 1;
matrixStack[currentMatrixId][matrixLevel[currentMatrixId]] := matrix[currentMatrixId];
end else writeln('Matrix stack full!');
end;
procedure popMatrix;
begin
if (matrixLevel[currentMatrixId] > 0) then
begin
matrix[currentMatrixId] := matrixStack[currentMatrixId][matrixLevel[currentMatrixId]];
matrixLevel[currentMatrixId] -= 1;
end else writeln('Matrix stack empty!');
end;
procedure translateMatrix(x, y, z : real);
var
transformationMatrix : matrix4d;
begin
initIdentityMatrix(transformationMatrix);
transformationMatrix[12] := x;
transformationMatrix[13] := y;
transformationMatrix[14] := z;
matrix[currentMatrixId] := multiplyMatrix(matrix[currentMatrixId], transformationMatrix);
end;
procedure rotateMatrix(angle, x, y, z : real);
var
len, c, s, x2, y2, z2, t : real;
transformationMatrix : matrix4d;
begin
angle := degToRad(angle);
len := sqrt((x*x)+(y*y)+(z*z));
x /= len;
y /= len;
z /= len;
c := cos(angle);
s := sin(angle);
x2 := x*x;
y2 := y*y;
z2 := z*z;
t := 1.0-c;
transformationMatrix[0] := (x2*t)+c;
transformationMatrix[1] := (y*x*t)+z*s;
transformationMatrix[2] := (x*z*t)-(y*s);
transformationMatrix[3] := 0.0;
transformationMatrix[4] := (x*y*t)-(z*s);
transformationMatrix[5] := (y2*t)+c;
transformationMatrix[6] := (y*z*t)+(x*s);
transformationMatrix[7] := 0.0;
transformationMatrix[8] := (x*z*t)+(y*s);
transformationMatrix[9] := (y*z*t)-(x*s);
transformationMatrix[10] := (z2*t)+c;
transformationMatrix[11] := 0.0;
transformationMatrix[12] := 0.0;
transformationMatrix[13] := 0.0;
transformationMatrix[14] := 0.0;
transformationMatrix[15] := 1.0;
matrix[currentMatrixId] := multiplyMatrix(matrix[currentMatrixId], transformationMatrix);
end;
procedure scaleMatrix(xScale, yScale, zScale : real);
var
transformationMatrix : matrix4d;
begin
initIdentityMatrix(transformationMatrix);
transformationMatrix[0] := xScale;
transformationMatrix[5] := yScale;
transformationMatrix[10] := zScale;
matrix[currentMatrixId] := multiplyMatrix(matrix[currentMatrixId], transformationMatrix);
end;
function multiplyMatrix(operandMatrix, multiplierMatrix : matrix4d) : matrix4d;
var
returnMatrix: matrix4d;
begin
returnMatrix[0] := (operandMatrix[0]*multiplierMatrix[0])+(operandMatrix[4]*multiplierMatrix[1])+(operandMatrix[8]*multiplierMatrix[2])+(operandMatrix[12]*multiplierMatrix[3]);
returnMatrix[1] := (operandMatrix[1]*multiplierMatrix[0])+(operandMatrix[5]*multiplierMatrix[1])+(operandMatrix[9]*multiplierMatrix[2])+(operandMatrix[13]*multiplierMatrix[3]);
returnMatrix[2] := (operandMatrix[2]*multiplierMatrix[0])+(operandMatrix[6]*multiplierMatrix[1])+(operandMatrix[10]*multiplierMatrix[2])+(operandMatrix[14]*multiplierMatrix[3]);
returnMatrix[3] := (operandMatrix[3]*multiplierMatrix[0])+(operandMatrix[7]*multiplierMatrix[1])+(operandMatrix[11]*multiplierMatrix[2])+(operandMatrix[15]*multiplierMatrix[3]);
returnMatrix[4] := (operandMatrix[0]*multiplierMatrix[4])+(operandMatrix[4]*multiplierMatrix[5])+(operandMatrix[8]*multiplierMatrix[6])+(operandMatrix[12]*multiplierMatrix[7]);
returnMatrix[5] := (operandMatrix[1]*multiplierMatrix[4])+(operandMatrix[5]*multiplierMatrix[5])+(operandMatrix[9]*multiplierMatrix[6])+(operandMatrix[13]*multiplierMatrix[7]);
returnMatrix[6] := (operandMatrix[2]*multiplierMatrix[4])+(operandMatrix[6]*multiplierMatrix[5])+(operandMatrix[10]*multiplierMatrix[6])+(operandMatrix[14]*multiplierMatrix[7]);
returnMatrix[7] := (operandMatrix[3]*multiplierMatrix[4])+(operandMatrix[7]*multiplierMatrix[5])+(operandMatrix[11]*multiplierMatrix[6])+(operandMatrix[15]*multiplierMatrix[7]);
returnMatrix[8] := (operandMatrix[0]*multiplierMatrix[8])+(operandMatrix[4]*multiplierMatrix[9])+(operandMatrix[8]*multiplierMatrix[10])+(operandMatrix[12]*multiplierMatrix[11]);
returnMatrix[9] := (operandMatrix[1]*multiplierMatrix[8])+(operandMatrix[5]*multiplierMatrix[9])+(operandMatrix[9]*multiplierMatrix[10])+(operandMatrix[13]*multiplierMatrix[11]);
returnMatrix[10] := (operandMatrix[2]*multiplierMatrix[8])+(operandMatrix[6]*multiplierMatrix[9])+(operandMatrix[10]*multiplierMatrix[10])+(operandMatrix[14]*multiplierMatrix[11]);
returnMatrix[11] := (operandMatrix[3]*multiplierMatrix[8])+(operandMatrix[7]*multiplierMatrix[9])+(operandMatrix[11]*multiplierMatrix[10])+(operandMatrix[15]*multiplierMatrix[11]);
returnMatrix[12] := (operandMatrix[0]*multiplierMatrix[12])+(operandMatrix[4]*multiplierMatrix[13])+(operandMatrix[8]*multiplierMatrix[14])+(operandMatrix[12]*multiplierMatrix[15]);
returnMatrix[13] := (operandMatrix[1]*multiplierMatrix[12])+(operandMatrix[5]*multiplierMatrix[13])+(operandMatrix[9]*multiplierMatrix[14])+(operandMatrix[13]*multiplierMatrix[15]);
returnMatrix[14] := (operandMatrix[2]*multiplierMatrix[12])+(operandMatrix[6]*multiplierMatrix[13])+(operandMatrix[10]*multiplierMatrix[14])+(operandMatrix[14]*multiplierMatrix[15]);
returnMatrix[15] := (operandMatrix[3]*multiplierMatrix[12])+(operandMatrix[7]*multiplierMatrix[13])+(operandMatrix[11]*multiplierMatrix[14])+(operandMatrix[15]*multiplierMatrix[15]);
result := returnMatrix;
end;
procedure initIdentityMatrix(var dstMatrix : matrix4d);
var
i : byte;
begin
for i := 0 to 15 do dstMatrix[i] := 0.0;
dstMatrix[0] := 1.0;
dstMatrix[5] := 1.0;
dstMatrix[10] := 1.0;
dstMatrix[15] := 1.0;
end;
procedure refreshScreen;
var
delay : integer;
begin
SDL_GL_SwapBuffers;
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
resetEvents;
lastTicks := ticks;
ticks := SDL_GetTicks;
tickDifference := ticks-lastTicks;
if (tickDifference = 0) then tickDifference := 1;
framerate := round(1000/tickDifference);
delay := 0;
if (maximumFramerate > 0) then delay := round(1000/maximumFramerate)-tickDifference;
if (delay >= 0) then SDL_Delay(delay);
compensation_ := tickDifference/(1000.0/idealFramerate);
end;
function getFramerate : word;
begin
result := framerate;
end;
function getTickDifference : word;
begin
result := tickDifference;
end;
procedure setIdealFramerate(newIdealFramerate : word);
begin
idealFramerate := newIdealFramerate;
if (idealFramerate = 0) then idealFramerate := 60;
end;
function getIdealFramerate : word;
begin
result := idealFramerate;
end;
function compensation : real;
begin
result := compensation_;
end;
procedure enableBlending(srcBlendFunc : GLenum = ONE; dstBlendFunc : GLenum = ZERO; blendFuncEquation : GLenum = FUNC_ADD);
begin
if (not blendingEnabled_) then
begin
glEnable(GL_BLEND);
blendingEnabled_ := true;
end;
glBlendEquation(blendFuncEquation);
glBlendFunc(srcBlendFunc, dstBlendFunc);
end;
procedure disableBlending;
begin
if (blendingEnabled_) then
begin
glDisable(GL_BLEND);
blendingEnabled_ := false;
end;
end;
function blendingEnabled : boolean;
begin
result := blendingEnabled_;
end;
procedure enableDepthTesting;
begin
if (not depthTestingEnabled_) then
begin
glEnable(GL_DEPTH_TEST);
depthTestingEnabled_ := true;
end;
end;
procedure disableDepthTesting;
begin
if (depthTestingEnabled_) then
begin
glDisable(GL_DEPTH_TEST);
depthTestingEnabled_ := false;
end;
end;
function depthTestingEnabled : boolean;
begin
result := depthTestingEnabled_;
end;
function openGlVersion : real;
var
str : string;
null : integer;
begin
if (openGlVersion_ = 0.0) then
begin
str := leftStr(glGetString(GL_VERSION), 3);
val(str, openGlVersion_, null);
end;
result := openGlVersion_;
end;
function glSlVersion : real;
var
str : string;
null : integer;
begin
if (glSlVersion_ = 0.0) then
begin
str := leftStr(glGetString(GL_SHADING_LANGUAGE_VERSION), 3);
val(str, glSlVersion_, null);
end;
result := glSlVersion_;
end;
function vertexArrayObjectSupported : boolean;
begin
result := vertexArrayObjectSupported_;
end;
initialization
openGlVersion_ := 0.0;
glSlVersion_ := 0.0;
compensation_ := 1.0;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Button7: TButton;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Memo1: TMemo;
StringGrid1: TStringGrid;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure ComboBox1Select(Sender: TObject);
procedure FormCreate(Sender: TObject);
//procedure StringGrid1DrawCell(Sender: TObject; aCol, aRow: Integer;
// aRect: TRect; aState: TGridDrawState);
procedure StringGrid1PrepareCanvas(sender: TObject; aCol, aRow: Integer;
aState: TGridDrawState);
procedure StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer;
var CanSelect: Boolean);
private
{ private declarations }
public
{ public declarations }
end;
type
Data = record
Kod:integer;
Nazov:string;
end;
const N = 50;
var
Subor, Subor2: textfile;
Tovar, AktualnaTab: array[1..N] of Data;
Kategorie: array[1..10] of string;
PocetRiadkov, AktualnyRiadok, ComboPrepinac: integer;
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var Riadok, PoziciaZnaku: integer;
Pomocna: string;
begin
{=============== FORM 1 ==============}
{-*- DEAKTIVACIA COMPONENTOV/NASTAVENIA -*-}
Randomize;
Memo1.Clear;
Button2.enabled := false; //Tlacidlo pre pridavanie tovaru
Button5.Enabled := false; //Tlacidlo pre editovanie poloziek
Edit1.Enabled := false;
Edit2.Enabled := false;
ComboBox1.Enabled := false;
ComboBox1.Items.Clear;
{゚*✫.-*- NACITANIE DO RECORDU -*-.✫*゚ }
Riadok := 0;
AssignFile(Subor, 'data.txt');
Reset(Subor);
Readln(Subor, PocetRiadkov);
For Riadok := 1 to PocetRiadkov do
begin
Readln(Subor, Pomocna);
Tovar[Riadok].Kod := strtoint(copy(Pomocna, 1, 3));
Delete(Pomocna, 1, 4);
Tovar[Riadok].Nazov := Pomocna;
end;
{While not eof(Subor) do
begin
inc(Riadok);
Readln(Subor, Pomocna);
Tovar[Riadok].Kod := strtoint(copy(Pomocna, 1, 3));
Delete(Pomocna, 1, 4);
//PoziciaZnaku := pos(']', Pomocna);
//Delete(Pomocna, PoziciaZnaku, 1);
Tovar[Riadok].Nazov := Pomocna;
end;}
{-*- NACITANIE KATEGORIE -*-}
Riadok := 0;
AssignFile(Subor, 'kategorie.txt');
Reset(Subor);
While not eof(Subor) do
begin
inc(Riadok);
Readln(Subor, Kategorie[Riadok]);
ComboBox1.Items.Add(Kategorie[Riadok]);
end;
{゚*✫.-*- VPISOVANIE DO TABULKY/COMBOBOXU -*-.✫*゚}
//plus kontrola
StringGrid1.Rowcount := PocetRiadkov + 1; //Pocet Riadkov + Header
StringGrid1.Cells[1, 0] := 'Kod Tovaru'; //[Stlpec, Riadok]
StringGrid1.Cells[2, 0] := 'Nazov Tovaru';
For Riadok := 1 to PocetRiadkov do
begin
StringGrid1.Cells[1, Riadok] := inttostr(Tovar[Riadok].Kod);
StringGrid1.Cells[2, Riadok] := Tovar[Riadok].Nazov;
StringGrid1.Cells[0, Riadok] := inttostr(Riadok);
end;
end;
{procedure TForm1.StringGrid1DrawCell(Sender: TObject; aCol, aRow: Integer;
aRect: TRect; aState: TGridDrawState);
begin
{-*- ZAFARBENIE AKTUALNEHO POLICKA -*-}
//chyba Zafarbenie celeho riadku
If (gdfocused in astate) then
begin
stringgrid1.canvas.brush.color:=clyellow;
stringgrid1.canvas.fillrect(arect);
stringgrid1.canvas.drawfocusrect(arect);
stringgrid1.canvas.font.color:=clblack;
stringgrid1.canvas.TextOut(arect.left+3,arect.top+3,stringgrid1.Cells[acol,arow]);
end;
end; }
procedure TForm1.StringGrid1PrepareCanvas(sender: TObject; aCol, aRow: Integer;
aState: TGridDrawState);
begin
If (Gdfixed in aState) then
exit;
If (aRow = StringGrid1.Row) then
StringGrid1.Canvas.Brush.Color := rgbtocolor(255,255,200);
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer;
var CanSelect: Boolean);
begin
//AktualnyRiadok := aRow;
AktualnyRiadok := strtoint(StringGrid1.Cells[0,aRow]);
StringGrid1.Invalidate;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
{===== BUTTON - VYTVORIT POLOZKU =====}
{-*- AKTIVACIA COMPONENTOV -*-}
Button2.enabled := true;
Button5.Enabled := false;
Edit1.Enabled := true;
Edit2.Enabled := true;
ComboBox1.Enabled := true;
Label4.caption := 'Vytvorenie Novej Polozky';
ComboPrepinac := 1;
{-*- EDITY -*-}
Edit1.Text := '';
Edit2.Text := '100';
ComboBox1.Text := 'Ovocie';
end;
procedure TForm1.Button2Click(Sender: TObject);
var I, KodEdit, Zhoda: integer;
NazovEdit: string;
begin
{-*- KONTROLA HODNOT -*-}
Zhoda := 0;
NazovEdit := Edit1.text;
KodEdit := strtoint(Edit2.text);
For I := 1 to PocetRiadkov do
Begin
If (NazovEdit = Tovar[I].Nazov) or (KodEdit = Tovar[I].Kod) then
begin
Memo1.Append('Tento Tovar/Kod Tovaru uz existuje');
Zhoda := 1;
end;
end;
If (NazovEdit = '') or ((KodEdit > 499) or (KodEdit < 100)) or (Length(NazovEdit) > 25) then
begin
Memo1.Append('Nepovoleny Nazov/Kod Tovaru');
Zhoda := 1;
end;
{-*- PRIDANIE DO RECORDU -*-}
If Zhoda = 0 then
begin
Inc(PocetRiadkov, 1);
Tovar[PocetRiadkov].Nazov := NazovEdit;
Tovar[PocetRiadkov].Kod := KodEdit;
Memo1.Append('Nova polozka ( ' + Tovar[PocetRiadkov].Nazov + ' : ' + inttostr(Tovar[PocetRiadkov].Kod) + ' ) uspesne pridana.');
end;
{-*- VPISOVANIE DO TABULKY -*-}
StringGrid1.Rowcount := PocetRiadkov + 1;
For I := 1 to PocetRiadkov do
begin
StringGrid1.Cells[1, I] := inttostr(Tovar[I].Kod);
StringGrid1.Cells[2, I] := Tovar[I].Nazov;
StringGrid1.Cells[0, I] := inttostr(I);
end;
StringGrid1.CheckPosition;
end;
procedure TForm1.Button3Click(Sender: TObject);
var KodPom, I: integer;
NazovPom, NazovMessage: string;
begin
{===== BUTTON - ODSTRANIT OZNACENE =====}
{-*- AKTIVACIA COMPONENTOV/NASTAVENIA -*-}
Button5.enabled := false;
Button2.Enabled := false;
Edit1.Enabled := false;
Edit2.Enabled := false;
ComboBox1.Enabled := false;
Label4.caption := '';
Edit1.Text := '';
Edit2.Text := '100';
ComboBox1.Text := 'Ovocie';
{-*- DIALOGOVE OKNO -*-}
If MessageDlg('Chces naozaj odstranit '+ Tovar[AktualnyRiadok].Nazov +' ?', MTConfirmation, [mbYES, mbNO], 0) = mrYES then
Begin
{-*- ODSTRANENIE A POSUN -*-}
NazovMessage := Tovar[AktualnyRiadok].Nazov;
For I := AktualnyRiadok to (PocetRiadkov - 1) do
Begin
KodPom := Tovar[I+1].Kod;
NazovPom := Tovar[I+1].Nazov;
Tovar[I].Kod := KodPom;
Tovar[I].Nazov := NazovPom;
End;
Dec(PocetRiadkov, 1);
Memo1.Append('Polozka ( '+NazovMessage+' ) bola odstranena.');
End
Else
Begin
Memo1.Append('Polozka nebola odstranena');
Exit;
End;
{-*- VPISOVANIE DO TABULKY -*-}
StringGrid1.Rowcount := PocetRiadkov + 1;
For I := 1 to PocetRiadkov do
begin
StringGrid1.Cells[1, I] := inttostr(Tovar[I].Kod);
StringGrid1.Cells[2, I] := Tovar[I].Nazov;
StringGrid1.Cells[0, I] := inttostr(I);
end;
StringGrid1.CheckPosition;
end;
procedure TForm1.Button4Click(Sender: TObject);
var KodPomocna: String;
begin
{===== BUTTON - EDITOVAT OZNACENE =====}
{-*- AKTIVACIA COMPONENTOV -*-}
Button5.enabled := true;
Button2.Enabled := false;
Edit1.Enabled := true;
Edit2.Enabled := true;
ComboBox1.Enabled := true;
Label4.caption := 'Editovanie Existujucej Polozky';
ComboPrepinac := 0;
{-*- NASTAVENIE EDITOV -*-}
Edit1.text := Tovar[AktualnyRiadok].Nazov;
Edit2.text := inttostr(Tovar[AktualnyRiadok].Kod);
{-*- NASTAVENIE EDITOV -*-}
Edit1.text := Tovar[AktualnyRiadok].Nazov;
Edit2.text := inttostr(Tovar[AktualnyRiadok].Kod);
KodPomocna := Edit2.text;
ComboBox1.text := Kategorie[strtoint(KodPomocna[1])];
end;
procedure TForm1.Button5Click(Sender: TObject);
var I, KodEdit, KodPom, Zhoda: integer;
NazovEdit, NazovPom: string;
begin
{============ BUTTON - ZMENIT ============}
NazovPom := Tovar[AktualnyRiadok].Nazov;
KodPom := Tovar[AktualnyRiadok].Kod;
{-*- KONTROLA HODNOT -*-}
Zhoda := 0;
NazovEdit := Edit1.text;
KodEdit := strtoint(Edit2.text);
If (NazovEdit = '') or ((KodEdit > 499) or (KodEdit < 100)) or (Length(NazovEdit) > 25) then
begin
Memo1.Append('Nepovoleny Nazov/Kod Tovaru.');
Zhoda := 1;
end;
{-*- PRIDANIE DO RECORDU -*-}
If Zhoda = 0 then
begin
Tovar[AktualnyRiadok].Nazov := NazovEdit;
Tovar[AktualnyRiadok].Kod := KodEdit;
Memo1.Append('Zmena polozky ' + NazovPom + ' : ' + inttostr(KodPom) + ' >>> '+ Tovar[AktualnyRiadok].Nazov + ' : ' + inttostr(Tovar[AktualnyRiadok].Kod));
end;
{-*- VPISOVANIE DO TABULKY -*-}
StringGrid1.Rowcount := PocetRiadkov + 1;
For I := 1 to PocetRiadkov do
begin
StringGrid1.Cells[1, I] := inttostr(Tovar[I].Kod);
StringGrid1.Cells[2, I] := Tovar[I].Nazov;
StringGrid1.Cells[0, I] := inttostr(I);
end;
StringGrid1.CheckPosition;
end;
procedure TForm1.Button6Click(Sender: TObject);
var Riadok: integer;
begin
{-*- VPISOVANIE DO SUBORU -*-}
If MessageDlg('Chces naozaj ulozit zmeny ?', MTConfirmation, [mbYES, mbNO], 0) = mrYES then
Begin
Riadok := 0;
AssignFile(Subor2, 'data_2.txt');
Rewrite(Subor2);
Writeln(Subor2, inttostr(PocetRiadkov));
For Riadok := 1 to PocetRiadkov do
Begin
Writeln(Subor2, inttostr(Tovar[Riadok].Kod)+';'+Tovar[Riadok].Nazov);
end;
Memo1.Append('Zmeny boli ulozene do suboru.');
//plus kontrola
Closefile( Subor2 );
End
Else
Exit;
end;
procedure TForm1.ComboBox1Select(Sender: TObject);
var ZaciatokKodu, KoniecKodu: string;
PomocneCislo, I: integer;
begin
Case ComboBox1.text of
'Ovocie' : ZaciatokKodu := '1';
'Zelenina' : ZaciatokKodu := '2';
'Pecivo' : ZaciatokKodu := '3';
'Ine' : ZaciatokKodu := '4';
end;
If ComboPrepinac = 1 then
begin
KoniecKodu := '';
For I := 1 to 2 do
begin
PomocneCislo := Random(10);
KoniecKodu := (inttostr(PomocneCislo) + KoniecKodu);
end;
Edit2.text := (ZaciatokKodu + KoniecKodu);
end
Else
begin
KoniecKodu := Edit2.text;
Delete (KoniecKodu, 1, 1);
Edit2.text := (ZaciatokKodu + KoniecKodu);
end;
end;
end.
{NEDOSTATKY:
> Oznacenie viacerych poloziek (na vymazanie)
> Filtrovanie/Zoradenie (StringGrid?)
> Automaticke zobrazenie selected Polozky v upravovacom panely
> Farebne odlisenie Varovnych/ Informacnych Sprav
> Moznost Ulozenia Zmien do Suboru/Automaticke ukladanie
> Kategotie
}
|
program pastasks;
{$mode objfpc}
uses sysutils;
const
SAVEFILE = 'pastasks.dat';
type
TaskRecord = record
id: integer;
title: string;
done: boolean;
end;
var
inp: string;
taskIndex: integer;
Task: TaskRecord;
f: file of TaskRecord;
procedure printTitle();
begin
writeln('--------');
writeln('pastasks');
writeln('--------');
end;
procedure setTaskIndex();
begin
taskIndex := 0;
while not eof(f) do
begin
read(f, Task);
taskIndex := taskIndex + 1;
end;
end;
procedure printOptions();
begin
writeln('(a)dd task, (l)ist tasks, task (d)one, print (i)nfo, (q)uit');
end;
procedure addTask();
var
inp: string;
begin
write('what to you want to do? ');
readln(inp);
Task.id := taskIndex;
Task.title := inp;
Task.done := false;
write(f, Task);
taskIndex := taskIndex + 1;
writeln('"', Task.title, '" added.');
end;
procedure listTasks();
begin
writeln('you currently have ', taskIndex, ' tasks.');
reset(f);
while not eof(f) do
begin
read(f, Task);
if Task.done then
writeln('[', Task.id, ']: ', Task.title, ' (done)')
else
writeln('[', Task.id, ']: ', Task.title);
end;
end;
procedure setTaskToDone();
var
tmpTasks: array of TaskRecord;
tmpIndex: integer;
inp: integer;
i: integer;
begin
tmpIndex := 0;
setlength(tmpTasks, taskIndex);
write('nice, enter index of done task: ');
readln(inp);
reset(f);
while not eof(f) do
begin
read(f, Task);
if (Task.id = inp) then
begin
Task.done := true;
writeln('task "', Task.title, '" done!');
end;
tmpTasks[tmpIndex].id := Task.id;
tmpTasks[tmpIndex].title := Task.title;
tmpTasks[tmpIndex].done := Task.done;
tmpIndex := tmpIndex + 1;
end;
rewrite(f);
for i := 0 to taskIndex - 1 do
begin
Task.id := tmpTasks[i].id;
Task.title := tmpTasks[i].title;
Task.done := tmpTasks[i].done;
write(f, Task);
end;
end;
procedure enterMainLoop();
begin
repeat
readln(inp);
case inp of
'A','a':
begin
addTask();
end;
'l', 'L':
begin
listTasks();
end;
'd', 'D':
begin
setTaskToDone();
end;
'i', 'I':
begin
printOptions();
end;
'q', 'Q':
begin
writeln('dying ...');
end;
else if (inp = 'q') then
begin
writeln('dying ...');
end
else
begin
writeln('i do not understand ...');
end;
end;
until inp = 'q';
end;
begin
assign(f, SAVEFILE);
try
reset(f, 1)
except
begin
rewrite(f);
end;
end;
setTaskIndex();
seek(f, filesize(f)); { move pointer to the end of the file }
printTitle();
printOptions();
writeln;
enterMainLoop();
close(f);
end.
|
namespace RegExpression;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
System.RegularExpressions;
type
TForm1 = class(TForm)
published
EditText: TEdit;
Button1: TButton;
lbType: TLabel;
Label1: TLabel;
lbRegExp: TListBox;
MemoRegEx: TMemo;
method Button1Click(Sender: TObject);
method lbRegExpClick(Sender: TObject);
method FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
implementation
method TForm1.Button1Click(Sender: TObject);
begin
if TRegEx.IsMatch(EditText.Text, MemoRegEx.Lines.Text) then
ShowMessage('Text DOES match the regular expression')
else
ShowMessage('Text DOES NOT match the regular expression');
end;
method TForm1.FormCreate(Sender: TObject);
begin
lbRegExp.ItemIndex := 0;
lbRegExpClick(lbRegExp);
end;
method TForm1.lbRegExpClick(Sender: TObject);
begin
case lbRegExp.ItemIndex of
0: begin
lbType.Caption := 'Email for validation';
MemoRegEx.Lines.Text := '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*' +
'|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\' +
'x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!' +
'#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])' +
'[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\' +
'-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)' +
'(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\' +
'd\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|' +
'\\[\x01-\x7f])+)\])(?(angle)>)$';
end;
1: begin
// Accept IP address between 0..255
lbType.Caption := 'IP address for validation (0..255)';
MemoRegEx.Lines.Text := '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\' +
'.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' +
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' +
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b';
end;
2: begin
// Data interval format mm-dd-yyyy
lbType.Caption :=
'Date in mm-dd-yyyy format from between 01-01-1900 and 12-31-2099';
MemoRegEx.Lines.Text := '^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[' +
'01])[- /.](19|20)\d\d$';
end;
3: begin
// Data interval format mm-dd-yyyy
lbType.Caption :=
'Date in dd-mm-yyyy format from between 01-01-1900 and 31-12-2099';
MemoRegEx.Lines.Text := '^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[01' +
'2])[- /.](19|20)\d\d$';
end;
end;
end;
end. |
unit Cache.EventGeo;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
Cache.Root,
Adapter.MySQL,
ZConnection, ZDataset,
Event.Cnst;
//------------------------------------------------------------------------------
type
TGeoEventType = (etDepot, etZone, etTrip, etWaypoint);
//------------------------------------------------------------------------------
//! ключ списка кэшей гео-событий
//------------------------------------------------------------------------------
TEventGeoKey = packed record
IMEI: Int64;
ID: Integer;
// EventType: TGeoEventType;
end;
//------------------------------------------------------------------------------
//! класс данных гео-событий
//------------------------------------------------------------------------------
TEventGeo = class(TCacheDataObjectAbstract)
private
FKey: TEventGeoKey;
FDTMark: TDateTime;
FEventType: TEventUserType;
FDuration: Double;
FTill: TDateTime;
FChanged: Boolean;
procedure SetDuration(const Value: Double);
procedure SetTill(const Value: TDateTime);
protected
//!
function GetDTMark(): TDateTime; override;
public
constructor Create(
const AIMEI: Int64;
const ADTMark: TDateTime;
const AEventType: TEventUserType;
const AID: Integer;
const ADuration: Double
); overload;
constructor Create(
const AKey: TEventGeoKey;
const ADTMark: TDateTime;
const AEventType: TEventUserType;
const ADuration: Double
); overload;
constructor Create(
ASource: TEventGeo
); overload;
function Clone(): TCacheDataObjectAbstract; override;
procedure ClearChanged();
property Key: TEventGeoKey read FKey;
property IMEI: Int64 read FKey.IMEI;
property ID: Integer read FKey.ID;
property EventType: TEventUserType read FEventType;
property Duration: Double read FDuration write SetDuration;
property Till: TDateTime read FTill write SetTill;
property Changed: Boolean read FChanged;
end;
//------------------------------------------------------------------------------
//! класс кэша гео-событий
//------------------------------------------------------------------------------
TEventGeoCacheDataAdapter = class(TCacheAdapterMySQL)
private
FTableName: string;
FIdFieldName: string;
FGeoCacheType: TGeoEventType;
FCheckWaypointHasEventQuery: TZQuery;
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;
function Exists(
const AEventKey: TEventGeoKey;
const AEventGeoType: TEventUserType
): Boolean;
constructor Create(
const AReadConnection, AWriteConnection: TZConnection;
const AEventType: TGeoEventType
);
end;
//------------------------------------------------------------------------------
//! класс списка кэшей гео-событий
//------------------------------------------------------------------------------
TEventGeoHash = TCacheDictionary<TEventGeoKey>;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// TEventGeo
//------------------------------------------------------------------------------
constructor TEventGeo.Create(
const AIMEI: Int64;
const ADTMark: TDateTime;
const AEventType: TEventUserType;
const AID: Integer;
const ADuration: Double
);
function MakeGeoEventType(AEventType: TEventUserType): TGeoEventType;
begin
Result := etDepot;
case AEventType of
egzEnterZone,
egzLeaveZone: Result := etZone;
end;
end;
begin
inherited Create();
//
FKey.IMEI := AIMEI;
FKey.ID := AID;
FDTMark := ADTMark;
FEventType := AEventType;
FDuration := ADuration;
FTill := ADuration + ADTMark;
end;
constructor TEventGeo.Create(
const AKey: TEventGeoKey;
const ADTMark: TDateTime;
const AEventType: TEventUserType;
const ADuration: Double
);
begin
inherited Create();
//
FKey := AKey;
FDTMark := ADTMark;
FEventType := AEventType;
FDuration := ADuration;
FTill := ADuration + ADTMark;
end;
constructor TEventGeo.Create(
ASource: TEventGeo
);
begin
inherited Create();
//
FKey := ASource.Key;
FDTMark := ASource.DTMark;
FEventType := ASource.EventType;
FDuration := ASource.Duration;
FTill := ASource.Till;
end;
function TEventGeo.Clone(): TCacheDataObjectAbstract;
begin
Result := TEventGeo.Create(Self);
end;
function TEventGeo.GetDTMark(): TDateTime;
begin
Result := FDTMark;
end;
procedure TEventGeo.SetDuration(
const Value: Double
);
begin
if (FDuration <> Value) then
begin
FDuration := Value;
FTill := Value + DTMark;
FChanged := True;
end;
end;
procedure TEventGeo.SetTill(
const Value: TDateTime
);
begin
if (FTill <> Value) then
begin
FTill := Value;
FDuration := Value - DTMark;
FChanged := True;
end;
end;
procedure TEventGeo.ClearChanged();
begin
FChanged := False;
end;
{ TEventGeoCacheDataAdapter }
constructor TEventGeoCacheDataAdapter.Create(const AReadConnection,
AWriteConnection: TZConnection; const AEventType: TGeoEventType);
var
InsertSQL: string;
UpdateSQL: string;
ReadBeforeSQL: string;
ReadAfterSQL: string;
ReadRangeSQL: string;
DeleteOneSQL: string;
CheckWaypointHasEventSQL: string;
begin
case AEventType of
etDepot: begin
FTableName := 'event_geodepot';
FIdFieldName := 'DepotID';
end;
etZone: begin
FTableName := 'event_geozone';
FIdFieldName := 'ZoneID';
end;
etTrip: begin
FTableName := 'event_geotrip';
FIdFieldName := 'TripID';
end;
etWaypoint: begin
FTableName := 'event_geowaypoint';
FIdFieldName := 'WaypointID';
end;
else
raise Exception.Create('unknown adapter type!');
end;
FGeoCacheType := AEventType;
ReadRangeSQL :=
'SELECT *'
+ ' FROM ' + FTableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to';
ReadBeforeSQL :=
'SELECT MAX(DT) as DT'
+ ' FROM ' + FTableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT < :dt';
ReadAfterSQL :=
'SELECT MIN(DT) as DT'
+ ' FROM ' + FTableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT > :dt';
InsertSQL :=
'INSERT IGNORE INTO ' + FTableName
+ ' (IMEI, DT, ' + FIdFieldName + ', EventTypeID, Duration)'
+ ' VALUES (:imei, :dt, :id, :t_id, :dur)'
+ ' ON DUPLICATE KEY UPDATE Duration = :dur';
UpdateSQL :=
'UPDATE ' + FTableName
+ ' SET Duration = :dur'
+ ' ,EventTypeID = :t_id'
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT = :dt';
DeleteOneSQL :=
'DELETE FROM ' + FTableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT = :dt';
inherited Create(
AReadConnection, AWriteConnection,
InsertSQL, UpdateSQL, ReadBeforeSQL, ReadAfterSQL, ReadRangeSQL, DeleteOneSQL);
CheckWaypointHasEventSQL :=
'SELECT count(1) as CNT'
+ ' FROM ' + FTableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND EventTypeID = :EventTypeID'
;
FCheckWaypointHasEventQuery := TZQuery.Create(nil);
FCheckWaypointHasEventQuery.Connection := AWriteConnection;
FCheckWaypointHasEventQuery.SQL.Text := CheckWaypointHasEventSQL;
end;
procedure TEventGeoCacheDataAdapter.Flush(
const ACache: TCache
);
begin
end;
procedure TEventGeoCacheDataAdapter.Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
with TEventGeo(AObj) do
begin
FillParamsFromKey(ACache.Key, FInsertQry);
FInsertQry.ParamByName(CSQLParamDT).AsDateTime := DTMark;
FInsertQry.ParamByName('dur').AsFloat := Duration;
FInsertQry.ParamByName('t_id').AsInteger := Ord(EventType);
FInsertQry.ExecSQL();
end;
end;
procedure TEventGeoCacheDataAdapter.Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
with TEventGeo(AObj) do
begin
FillParamsFromKey(ACache.Key, FUpdateQry);
FUpdateQry.ParamByName(CSQLParamDT).AsDateTime := DTMark;
FUpdateQry.ParamByName('dur').AsFloat := Duration;
FUpdateQry.ParamByName('t_id').AsInteger := Ord(EventType);
FUpdateQry.ExecSQL();
end;
end;
function TEventGeoCacheDataAdapter.Exists(
const AEventKey: TEventGeoKey;
const AEventGeoType: TEventUserType
): Boolean;
begin
FCheckWaypointHasEventQuery.Close;
FCheckWaypointHasEventQuery.ParamByName('imei').AsLargeInt := AEventKey.IMEI;
FCheckWaypointHasEventQuery.ParamByName('id').AsInteger := AEventKey.ID;
FCheckWaypointHasEventQuery.ParamByName('EventTypeID').AsInteger := Ord(AEventGeoType);
FCheckWaypointHasEventQuery.Open;
Result := FCheckWaypointHasEventQuery.FieldByName('CNT').AsInteger > 0;
FCheckWaypointHasEventQuery.Close;
end;
function TEventGeoCacheDataAdapter.MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract;
begin
with AQuery do
begin
Result := TEventGeo.Create(
FieldByName('IMEI').AsLargeInt,
FieldByName('DT').AsDateTime,
TEventUserType(FieldByName('EventTypeID').AsInteger),
FieldByName(FIdFieldName).AsInteger,
FieldByName('Duration').AsFloat
);
end;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: EmptyUnit.pas,v 1.18 2007/02/05 22:21:05 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: EmptyProject.cpp
//
// Empty starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit EmptyUnit;
interface
uses
Windows, Messages, SysUtils,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTSettingsDlg, DXUTenum, DXUTmisc, DXUTgui;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
if FAILED(DXUTGetD3DObject.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// Before a device is created, modify the device settings as needed
//--------------------------------------------------------------------------------------
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
Result:= True;
end;
//--------------------------------------------------------------------------------------
// Create any D3DPOOL_MANAGED resources here
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
begin
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Create any D3DPOOL_DEFAULT resources here
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
begin
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Handle updates to the scene
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
end;
//--------------------------------------------------------------------------------------
// Render the scene
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
end;
//--------------------------------------------------------------------------------------
// Release resources created in the OnResetDevice callback here
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
end;
//--------------------------------------------------------------------------------------
// Release resources created in the OnCreateDevice callback here
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
end;
procedure CreateCustomDXUTobjects;
begin
end;
procedure DestroyCustomDXUTobjects;
begin
end;
end.
|
unit gr_FilterDate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, gr_uCommonProc, IBase, dates, cxLabel;
type
TFFilterDate = class(TForm)
EditDateBeg: TcxDateEdit;
EditDateEnd: TcxDateEdit;
Panel1: TPanel;
ButtonYes: TcxButton;
ButtonCancel: TcxButton;
Actions: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
ActionEnter: TAction;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
procedure ActionEnterExecute(Sender: TObject);
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);reintroduce;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FFilterDate: TFFilterDate;
implementation
{$R *.dfm}
procedure TFFilterDate.ActionYesExecute(Sender: TObject);
begin
if EditDateBeg.Date>EditDateEnd.Date then
begin
showmessage('Дата початку більше дати кінця!');
exit;
end;
ModalResult:=mrOk;
end;
procedure TFFilterDate.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFFilterDate.ActionEnterExecute(Sender: TObject);
begin
if ButtonYes.Focused then
begin
ActionYesExecute(Sender);
exit;
end;
keybd_event(VK_TAB,0,0,0);
end;
constructor TFFilterDate.Create(AOwner: TComponent;Db_Handle:TISC_DB_HANDLE);
begin
inherited create(AOwner);
EditDateBeg.Date:= ConvertKodToDate(grKodSetup(Db_Handle));
EditDateEND.Date:= ConvertKodToDate(grKodSetup(Db_Handle)+1)-1;
end;
end.
|
program bmp2lcd;
uses
bmp;
procedure PrintHelp;
begin
WriteLn('usage: bmp2lcd <type> <bmp_file>');
WriteLn;
WriteLn('LCD Types Available:');
WriteLn(' - [pcd8544] PCD8544 (aka Nokia 5110 LCD)');
WriteLn;
WriteLn('The bitmap files must be saved as monochrome (1-bit color depth) and have no compression applied. The simplest way to achieve this is to use MS Paint, go to File->Save As... and select "Monochrome Bitmap"');
WriteLn;
WriteLn('Built by Nathan Campos <http://nathancampos.me/>');
Halt;
end;
begin
if ParamCount < 2 then
PrintHelp;
OpenBitmapFile(ParamStr(2));
PrintHeaders;
WriteLn;
WriteLn('Image:');
PrintImage;
CloseBitmapFile;
end.
|
unit TpGenericComponent;
interface
uses
SysUtils, Classes,
ThHeaderComponent, ThTag,
TpControls;
type
TTpGenericComponent = class(TThHeaderComponent)
private
FTpClassName: string;
FParams: TStringList;
protected
procedure SetParams(const Value: TStringList);
procedure SetTpClassName(const Value: string);
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
published
property TpClassName: string read FTpClassName write SetTpClassName;
property Params: TStringList read FParams write SetParams;
end;
implementation
constructor TTpGenericComponent.Create(inOwner: TComponent);
begin
inherited;
FParams := TStringList.Create;
end;
destructor TTpGenericComponent.Destroy;
begin
FParams.Free;
inherited;
end;
procedure TTpGenericComponent.SetParams(const Value: TStringList);
begin
FParams.Assign(Value);
end;
procedure TTpGenericComponent.SetTpClassName(const Value: string);
begin
FTpClassName := Value;
end;
procedure TTpGenericComponent.Tag(inTag: TThTag);
begin
with inTag do
begin
Add(tpClass, TpClassName);
Add('tpName', Name);
Attributes.AddStrings(Params);
end;
end;
end.
|
namespace FunWithFutures;
interface
type
ConsoleApp = static class
private
method Fast: String;
method Medium: String;
method Slow: String;
public
method Main(args: array of String);
end;
implementation
method ConsoleApp.Main(args: array of String);
begin
Console.OutputEncoding := System.Text.Encoding.UTF8;
writeLn('Welcome to the Future.');
writeLn();
var f, m, s: future String;
writeLn('Test 1: Sync Futures');
writeLn();
writeLn('In this first and simples case, two variables will be initialized to regular NON-ASYNC');
writeLn('futures. As a result, "m" and "s" will be evaluated one after the other:');
writeLn();
s := Slow();
m := Medium();
writeLn(s+m);
writeLn('Test 2: One Async Future');
writeLn();
writeLn('Now, we use an ASYNC future for the second value. This way, while "s" is being evaluated');
writeLn('inline, "m" can alreasdy start processing in the background and will, in fact, br ready');
writeLn('by the time it is needed');
writeLn();
s := Slow();
m := async Medium();
writeLn(s+m);
writeLn('Test 3: More Async Future');
writeLn();
writeLn('In fact, several async futures can run in parallel, CPU cores permitting, so that in the');
writeLn('following scenario, both "s" and "m" evakluate in the backgorund.');
writeLn();
writeLn('Note that "f" of course finishes first, and execution will then block to wait for "s"');
writeLn('and then "m" to be finished');
writeLn();
f := Fast();
s := async Slow();
m := async Medium();
writeLn(f+s+m);
writeLn('Test 4: Futures wirth Anonymous methods and Lambdas');
writeLn();
writeLn('Instead of calling methods, we can also provide a value to a future via an anonymous method');
writeLn('or a lambda expression (which really are just two syntaxes for the same underlying thing.');
writeLn();
writeLn('Note also that since we do not reassign "m", but do reuse it, the "Medium" method will not');
writeLn('be called again. Futures are only evalauted ones, and their value is then available immediately,');
writeLn('any time you reference the future.');
writeLn();
f := -> begin writeLn('-> fast λ'); result:= 'Fast λ '; writeLn('<- Fast λ'); end;
s := async method: String begin
writeLn('-> Slow λ');
Thread.Sleep(3000);
result := 'Slow λ ';
writeLn('<- Slow λ');
end;
writeLn(f+s+m);
writeLn();
writeLn("That's it. press enter to quit.");
Console.ReadLine();
end;
method ConsoleApp.Fast: String;
begin
writeLn('-> Fast');
Thread.Sleep(10);
result := 'Fast ';
writeLn('<- Fast');
end;
method ConsoleApp.Medium: String;
begin
writeLn('-> Medium');
Thread.Sleep(1000);
result := 'Medium ';
writeLn('<- Medium');
end;
method ConsoleApp.Slow: String;
begin
writeLn('-> Slow');
Thread.Sleep(3000);
result := 'Slow ';
writeLn('<- Slow');
end;
end.
|
unit LA.Matrix;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
interface
uses
Classes,
SysUtils,
LA.Vector;
type
TShape = record
Row, Col: integer;
function EqualTo(x: TShape): boolean;
function ToString: string;
end;
TList2D = array of array of double;
TVectorArr = array of TVector;
PMatrix = ^TMatrix;
TMatrix = record
private
__data: TList2D;
public
class function Create(list2D: TList2D): TMatrix; static;
class function Create(vecArr: TVectorArr): TMatrix; static;
/// <summary> 零矩阵 </summary>
class function Zero(row, col: integer): TMatrix; static;
/// <summary> 返回一个n行n列的单位矩阵 </summary>
class function Identity(n: integer): TMatrix; static;
/// <summary> 返回矩阵 pos 位置的元素 </summary>
function __getItem(i, j: integer): double;
/// <summary> 设置矩阵 pos 位置元素的值 </summary>
procedure __setItem(i, j: integer; val: double);
/// <summary> 返回矩阵的第index个行向量 </summary>
function Get_Row_vector(index: integer): TVector;
/// <summary> 返回矩阵的第index个列向量 </summary>
function Get_Col_vector(index: integer): TVector;
/// <summary> 设置矩阵的第index个行向量 </summary>
procedure Set_Row(index: integer; vec: TVector);
/// <summary> 设置矩阵的第index个列向量 </summary>
procedure Set_Col(index: integer; Vec: TVector);
/// <summary> 返回矩阵的元素个数 </summary>
function Size: integer;
/// <summary> 返回矩阵的行数 </summary>
function Row_num: integer;
/// <summary> 返回矩阵的列数 </summary>
function Col_num: integer;
/// <summary> 返回矩阵的形状: (行数, 列数) </summary>
function Shape: TShape;
/// <summary> 返回矩阵乘法的结果 </summary>
function Dot(const a: TVector): TVector;
/// <summary> 返回矩阵乘法的结果 </summary>
function Dot(const a: TMatrix): TMatrix;
/// <summary> 矩阵转置 </summary>
function Transpose: TMatrix;
function ToString: string;
property Item[row, col: integer]: double read __getItem write __setItem; default;
class operator +(const a, b: TMatrix): TMatrix;
class operator -(const a, b: TMatrix): TMatrix;
class operator * (const a: double; const b: TMatrix): TMatrix;
class operator * (const a: TMatrix; const b: double): TMatrix;
class operator / (const a: TMatrix; const b: double): TMatrix;
class operator +(const a: TMatrix): TMatrix;
class operator -(const a: TMatrix): TMatrix;
end;
implementation
{ TShape }
function TShape.EqualTo(x: TShape): boolean;
begin
Result := True;
if Self.Col <> x.Col then
Result := False;
if Self.Row <> x.Row then
Result := False;
end;
function TShape.ToString: string;
var
sb: TAnsiStringBuilder;
begin
sb := TAnsiStringBuilder.Create;
try
sb.Append('(');
sb.Append(Self.Col);
sb.Append(', ');
sb.Append(Self.Row);
sb.Append(')');
Result := sb.ToString;
finally
FreeAndNil(sb);
end;
end;
{ TMatrix }
class operator TMatrix. +(const a, b: TMatrix): TMatrix;
var
i, j: integer;
ret: TMatrix;
begin
if a.Shape.EqualTo(b.Shape) = False then
raise Exception.Create('Error in adding. Shape of matrix must be same.');
ret := TMatrix.Zero(a.Row_num, a.Col_num);
for i := 0 to ret.Shape.Col - 1 do
begin
for j := 0 to ret.Shape.Row - 1 do
begin
ret[i, j] := a[i, j] + b[i, j];
end;
end;
Result := ret;
end;
class operator TMatrix. -(const a, b: TMatrix): TMatrix;
var
i, j: integer;
ret: TMatrix;
begin
if a.Shape.EqualTo(b.Shape) = False then
raise Exception.Create('Error in subtracting. Shape of matrix must be same.');
ret := TMatrix.Zero(a.Row_num, a.Col_num);
for i := 0 to ret.Shape.Col - 1 do
begin
for j := 0 to ret.Shape.Row - 1 do
begin
ret.__data[i, j] := a[i, j] - b[i, j];
end;
end;
Result := ret;
end;
class operator TMatrix. * (const a: double; const b: TMatrix): TMatrix;
var
i, j: integer;
ret: TMatrix;
begin
ret := TMatrix.Zero(b.Row_num, b.Col_num);
for i := 0 to ret.Row_num - 1 do
begin
for j := 0 to ret.Col_num - 1 do
begin
ret[i, j] := a * b[i, j];
end;
end;
Result := ret;
end;
class operator TMatrix. * (const a: TMatrix; const b: double): TMatrix;
begin
Result := b * a;
end;
class operator TMatrix. / (const a: TMatrix; const b: double): TMatrix;
begin
Result := (1 / b) * a;
end;
class operator TMatrix. +(const a: TMatrix): TMatrix;
begin
Result := 1 * a;
end;
class operator TMatrix. -(const a: TMatrix): TMatrix;
begin
Result := -1 * a;
end;
function TMatrix.Col_num: integer;
begin
Result := Self.Shape.Col;
end;
class function TMatrix.Create(list2D: TList2D): TMatrix;
begin
Result.__data := Copy(list2D);
end;
class function TMatrix.Create(vecArr: TVectorArr): TMatrix;
var
n, i: integer;
ret: LA.Matrix.TList2D;
begin
n := Length(vecArr);
SetLength(ret, n);
for i := 0 to n - 1 do
begin
ret[i] := vecArr[i].UnderlyingList;
end;
Result.__data := Copy(ret);
end;
function TMatrix.Dot(const a: TMatrix): TMatrix;
var
ret: TMatrix;
tmp: TVector;
i, j: integer;
begin
if Self.Col_num <> a.Row_num then
raise Exception.Create('Error in Matrix-Matrix Multiplication.');
ret := TMatrix.Zero(Self.Row_num, a.Col_num);
for j := 0 to a.Col_num - 1 do
begin
tmp := Self.Dot(a.Get_Col_vector(j));
for i := 0 to tmp.Len - 1 do
ret[i, j] := tmp[i];
end;
Result := ret;
end;
function TMatrix.Dot(const a: TVector): TVector;
var
ret: TVector;
i: integer;
begin
if Self.Col_num <> a.Len then
raise Exception.Create('Error in Matrix-Vector Multiplication.');
ret := TVector.Zero(Self.Row_num);
for i := 0 to ret.Len - 1 do
begin
ret[i] := Self.Get_Row_vector(i).Dot(a);
end;
Result := ret;
end;
function TMatrix.Get_Col_vector(index: integer): TVector;
var
ret: TVector;
i: integer;
begin
ret := TVector.Zero(Self.Row_num);
for i := 0 to ret.Len - 1 do
ret[i] := Self[i, index];
Result := ret;
end;
function TMatrix.Get_Row_vector(index: integer): TVector;
var
tmp: TVector;
i: integer;
begin
tmp := TVector.Zero(Self.Col_num);
for i := 0 to tmp.Len - 1 do
tmp[i] := Self.__data[index, i];
Result := tmp;
end;
class function TMatrix.Identity(n: integer): TMatrix;
var
tmp: TList2D;
i: integer;
begin
SetLength(tmp, n, n);
for i := 0 to Length(tmp) - 1 do
tmp[i, i] := 1;
Result := TMatrix.Create(tmp);
end;
function TMatrix.Row_num: integer;
begin
Result := Self.Shape.Row;
end;
procedure TMatrix.Set_Col(index: integer; Vec: TVector);
var
tmp: TVector;
i: integer;
begin
tmp := Get_Col_vector(index);
if tmp.Len <> Vec.Len then
raise Exception.Create('Error. Length of vectors must be same.');
for i := 0 to Col_num - 1 do
begin
__data[i, index] := Vec[i];
end;
end;
procedure TMatrix.Set_Row(index: integer; vec: TVector);
var
tmp: TVector;
i: integer;
begin
tmp := Get_Row_vector(index);
if tmp.Len <> Vec.Len then
raise Exception.Create('Error. Length of vectors must be same.');
for i := 0 to Row_num - 1 do
begin
__data[index, i] := Vec[i];
end;
end;
function TMatrix.Shape: TShape;
begin
Result.Row := Length(__data);
Result.col := Length(__data[0]);
end;
function TMatrix.Size: integer;
begin
Result := Self.Row_num * Self.Col_num;
end;
function TMatrix.ToString: string;
var
sb: TAnsiStringBuilder;
i, j: integer;
begin
sb := TAnsiStringBuilder.Create;
try
for i := 0 to High(__data) do
begin
sb.Append('[');
for j := 0 to High(__data[0]) do
begin
sb.Append(__data[i, j]);
if (j = High(__data[0])) and (i <> High(__data)) then
sb.Append('],')
else if (j = High(__data[0])) and (i = High(__data)) then
sb.Append(']')
else
sb.Append(', ');
end;
end;
Result := sb.ToString;
finally
FreeAndNil(sb);
end;
end;
function TMatrix.Transpose: TMatrix;
var
tmp: TList2D;
i, j: integer;
begin
SetLength(tmp, Self.Col_num, Row_num);
for i := 0 to self.Row_num - 1 do
begin
for j := 0 to self.Col_num - 1 do
tmp[j, i] := Self[i, j];
end;
Result := TMatrix.Create(tmp);
end;
class function TMatrix.Zero(row, col: integer): TMatrix;
var
ret: TMatrix;
begin
SetLength(ret.__data, row, col);
Result := ret;
end;
function TMatrix.__getItem(i, j: integer): double;
begin
Result := __data[i, j];
end;
procedure TMatrix.__setItem(i, j: integer; val: double);
begin
__data[i, j] := val;
end;
end.
|
unit Player;
interface
uses myTypes, sgTypes, SwinGame, Chunk;
procedure RenderPlayer(myPlayer: PlayerType; blocks: BlockArray);
procedure HandleGravity(var myPlayer: PlayerType; world: WorldArray);
procedure HandleMovement(var myPlayer: PlayerType; world: WorldArray);
implementation
procedure RenderPlayer(myPlayer: PlayerType; blocks: BlockArray);
begin
//Draw the player on the screen. Hardcoded to block item 2 with a size of 16 * 16, and always in the center of the screen.
DrawBitmapPartOnScreen(blocks.block[2].image, blocks.block[2].x, blocks.block[2].y, 16, 16, Round(ScreenWidth() / 2), Round(ScreenHeight() / 2));
end;
procedure HandleGravity(var myPlayer: PlayerType; world: WorldArray);
var
tempY: integer;
collided: boolean;
radiusx, radiusy, x, y, b: integer;
rectA, rectB: Rectangle;
begin
if myPlayer.jumping then
begin
//Increase players velocity
if myPlayer.vertVelocity < 12 then
begin
myPlayer.vertVelocity += 1;
myPlayer.speedVertical += 1.6;
end;
end;
//Take the amount of speed so if it is still going up, it goes up by .6, but then starts to go down resulting in an arc.
myPlayer.speedVertical -= 1;
//Limit the speed the player can go (it will start clipping through blocks if going to fast)
if myPlayer.speedVertical < -8 then
begin
myPlayer.speedVertical := -8;
end;
collided := false;
//Get the players location after falling to check if there is a block there
tempY := Round(myPlayer.y - myPlayer.speedVertical);
//Check for blocks in a 2*2 (could be a 1*1 but this is just to make sure for edge cases)
for radiusx := 0 to 2 do
begin
for radiusy := 0 to 2 do
begin
x := myPlayer.X + (radiusx * 16);
y := tempY + (radiusy * 16);
b := Chunk.GetBlock(world, x, y);
if (b >= 0) and (b <> 10) then
begin
rectA.x := x;
rectA.y := y;
rectA.width := 16;
rectA.height := 16;
rectB.x := myPlayer.x;
rectB.y := tempY;
rectB.width := 16;
rectB.height := 16;
if RectanglesIntersect(rectA, rectB) then
begin
//Stop falling and don't set the location since that location contains a block.
myPlayer.jumping := false;
myPlayer.speedVertical := 0;
myPlayer.vertVelocity := 0;
collided := true;
Break;
end;
end;
end;
end;
if not collided then
begin
myPlayer.y := tempY;
end;
end;
procedure HandleMovement(var myPlayer: PlayerType; world: WorldArray);
var
tempX: integer;
collided: boolean;
radiusx, radiusy, x, y, b: integer;
rectA, rectB: Rectangle;
begin
//Acceleration slowly by the ACCELERATION constant, limited to 7 pixels in either direction
if myPlayer.leftMovement then
begin
myPlayer.speedHorizontal -= ACCELERATION;
if myPlayer.speedHorizontal < -7 then
begin
myPlayer.speedHorizontal := -7;
end;
end
else if myPlayer.rightMovement then
begin
myPlayer.speedHorizontal += ACCELERATION;
if myPlayer.speedHorizontal > 7 then
begin
myPlayer.speedHorizontal := 7;
end;
end
else
begin
//Slow down slowly instead of stopping abruptly
if myPlayer.speedHorizontal > 0.2 then
begin
myPlayer.speedHorizontal -= ACCELERATION;
end
else if myPlayer.speedHorizontal < -0.2 then
begin
myPlayer.speedHorizontal += ACCELERATION;
end
else
begin
//Stop moving when slow enough
myPlayer.speedHorizontal := 0;
end;
end;
collided := false;
tempX := myPlayer.x - Round(myPlayer.speedHorizontal * -1);
for radiusx := 0 to 2 do
begin
for radiusy := 0 to 2 do
begin
x := tempX + (radiusx * 16);
y := myPlayer.y + (radiusy * 16);
b := Chunk.GetBlock(world, x, y);
if (b >= 0) and (b <> 10) then
begin
rectA.x := x;
rectA.y := y;
rectA.width := 16;
rectA.height := 16;
rectB.x := tempX;
rectB.y := myPlayer.y;
rectB.width := 16;
rectB.height := 16;
if RectanglesIntersect(rectA, rectB) then
begin
//Don't move if the location moving to contains a block.
myPlayer.speedHorizontal := 0;
collided := true;
Break;
end;
end;
end;
end;
if not collided then
begin
myPlayer.x := tempX;
end;
end;
end. |
unit glTools;
interface
uses
SysUtils, Classes, Windows, WinSvc;
type
TglTools = class(TComponent)
private
{ Private declarations }
protected
procedure SrvRegTool(FileName, Path: string; Start: boolean);
public
function Stop(ServiceName: string): boolean;
function Start(ServiceName: string): boolean;
function Restart(ServiceName: string): boolean;
procedure Install(FileName, Path: string);
procedure Uninstall(FileName, Path: string);
procedure FullRestart(ServiceName, FileName, Path: string);
function Working(ServiceName: string): DWord;
published
function GetStartParam: string;
end;
procedure Register;
implementation
//{$R glTools}
procedure Register;
begin
RegisterComponents('Golden Line', [TglTools]);
end;
function ServiceGetStatus(sMachine, sService: string): DWord;
var
h_manager, h_service: SC_Handle;
service_status: TServiceStatus;
hStat: DWord;
begin
hStat := 1;
h_manager := OpenSCManager(PChar(sMachine), nil, SC_MANAGER_CONNECT);
if h_manager > 0 then
begin
h_service := OpenService(h_manager, PChar(sService), SERVICE_QUERY_STATUS);
if h_service > 0 then
begin
if (QueryServiceStatus(h_service, service_status)) then
hStat := service_status.dwCurrentState;
CloseServiceHandle(h_service);
end;
CloseServiceHandle(h_manager);
end;
Result := hStat;
end;
function ServiceStart(aMachine, aServiceName: string): boolean;
// aMachine это UNC путь, либо локальный компьютер если пусто
var
h_manager, h_svc: SC_Handle;
svc_status: TServiceStatus;
Temp: PChar;
dwCheckPoint: DWord;
begin
svc_status.dwCurrentState := 1;
h_manager := OpenSCManager(PChar(aMachine), nil, SC_MANAGER_CONNECT);
if h_manager > 0 then
begin
h_svc := OpenService(h_manager, PChar(aServiceName), SERVICE_START or
SERVICE_QUERY_STATUS);
if h_svc > 0 then
begin
Temp := nil;
if (StartService(h_svc, 0, Temp)) then
if (QueryServiceStatus(h_svc, svc_status)) then
begin
while (SERVICE_RUNNING <> svc_status.dwCurrentState) do
begin
dwCheckPoint := svc_status.dwCheckPoint;
Sleep(svc_status.dwWaitHint);
if (not QueryServiceStatus(h_svc, svc_status)) then
break;
if (svc_status.dwCheckPoint < dwCheckPoint) then
begin
// QueryServiceStatus не увеличивает dwCheckPoint
break;
end;
end;
end;
CloseServiceHandle(h_svc);
end;
CloseServiceHandle(h_manager);
end;
Result := SERVICE_RUNNING = svc_status.dwCurrentState;
end;
function ServiceStop(aMachine, aServiceName: string): boolean;
// aMachine это UNC путь, либо локальный компьютер если пусто
var
h_manager, h_svc: SC_Handle;
svc_status: TServiceStatus;
dwCheckPoint: DWord;
begin
h_manager := OpenSCManager(PChar(aMachine), nil, SC_MANAGER_CONNECT);
if h_manager > 0 then
begin
h_svc := OpenService(h_manager, PChar(aServiceName), SERVICE_STOP or
SERVICE_QUERY_STATUS);
if h_svc > 0 then
begin
if (ControlService(h_svc, SERVICE_CONTROL_STOP, svc_status)) then
begin
if (QueryServiceStatus(h_svc, svc_status)) then
begin
while (SERVICE_STOPPED <> svc_status.dwCurrentState) do
begin
dwCheckPoint := svc_status.dwCheckPoint;
Sleep(svc_status.dwWaitHint);
if (not QueryServiceStatus(h_svc, svc_status)) then
begin
// couldn't check status
break;
end;
if (svc_status.dwCheckPoint < dwCheckPoint) then
break;
end;
end;
end;
CloseServiceHandle(h_svc);
end;
CloseServiceHandle(h_manager);
end;
Result := SERVICE_STOPPED = svc_status.dwCurrentState;
end;
{ TglTools }
procedure TglTools.FullRestart(ServiceName, FileName, Path: string);
begin
Stop(ServiceName);
Uninstall(FileName, Path);
Install(FileName, Path);
Start(ServiceName);
end;
function TglTools.GetStartParam: string;
begin
Result := trim(paramstr(1));
end;
procedure TglTools.Install(FileName, Path: string);
begin
SrvRegTool(FileName, Path, true);
end;
function TglTools.Restart(ServiceName: string): boolean;
begin
Result := false;
if ServiceStop('', ServiceName) then
if ServiceStart('', ServiceName) then
Result := true;
end;
procedure TglTools.SrvRegTool(FileName, Path: string; Start: boolean);
var
Action: string;
begin
if Start then
Action := ' /silent /install'
else
Action := ' /silent /uninstall';
if trim(Path) = '' then
WinExec(PAnsiChar(FileName + Action), SW_HIDE)
else
WinExec(PAnsiChar(Path + FileName + Action), SW_HIDE);
end;
function TglTools.Start(ServiceName: string): boolean;
begin
if ServiceStart('', ServiceName) then
Result := true
else
Result := false;
end;
function TglTools.Stop(ServiceName: string): boolean;
begin
if ServiceStop('', ServiceName) then
Result := true
else
Result := false;
end;
procedure TglTools.Uninstall(FileName, Path: string);
begin
SrvRegTool(FileName, Path, false);
end;
function TglTools.Working(ServiceName: string): DWord;
begin
Result := ServiceGetStatus('', ServiceName);
end;
end.
|
unit InflatablesList_HTML_Download;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
InflatablesList_Types;
Function IL_WGETDownloadURL(const URL: String; Stream: TStream; out ResultCode: Integer; StaticSettings: TILStaticManagerSettings): Boolean;
Function IL_SYNDownloadURL(const URL: String; Stream: TStream; out ResultCode: Integer; StaticSettings: TILStaticManagerSettings): Boolean;
implementation
uses
Windows, SysUtils, SyncObjs,
HTTPSend, blcksock, ssl_openssl, ssl_openssl_lib, // synapse
CRC32, StrRect,
InflatablesList_Utils;
// resource file with the binaries (DLLs, wget.exe)
{$R '..\resources\down_bins.res'}
const
IL_PREP_DOWN_BINS_TAG_WGET = 1;
IL_PREP_DOWN_BINS_TAG_OSSL = 2;
var
ILPrepFlag_WGET: Integer = 0;
ILPrepFlag_OSSL: Integer = 0;
ILDiskAccessSection: TCriticalSection;
//------------------------------------------------------------------------------
procedure IL_PrepDownloadBinaries(Tag: Integer; StaticSettings: TILStaticManagerSettings);
procedure ExtractResToFile(const ResName,FileName: String);
var
ResStream: TResourceStream;
begin
ILDiskAccessSection.Enter;
try
// extract files to program folder
If not IL_FileExists(StaticSettings.DefaultPath + FileName) then
begin
ResStream := TResourceStream.Create(hInstance,StrToRTL(ResName),PChar(10));
try
ResStream.SaveToFile(StrToRTL(StaticSettings.DefaultPath + FileName));
finally
ResStream.Free;
end;
end;
finally
ILDiskAccessSection.Leave;
end;
end;
begin
case Tag of
IL_PREP_DOWN_BINS_TAG_WGET:
If InterlockedExchangeAdd(ILPrepFlag_WGET,0) <= 0 then
begin
ExtractResToFile('wget','wget.exe');
InterlockedExchangeAdd(ILPrepFlag_WGET,1);
end;
IL_PREP_DOWN_BINS_TAG_OSSL:
If InterlockedExchangeAdd(ILPrepFlag_OSSL,0) <= 0 then
begin
ExtractResToFile('libeay32','libeay32.dll');
ExtractResToFile('ssleay32','ssleay32.dll');
InterlockedExchangeAdd(ILPrepFlag_OSSL,1);
ssl_openssl_lib.DestroySSLInterface;
ssl_openssl_lib.InitSSLInterface;
// follwing is discouraged, but it is the only way if you want to defer extraction
blcksock.SSLImplementation := ssl_openssl.TSSLOpenSSL;
end;
end;
end;
//==============================================================================
Function IL_WGETDownloadURL(const URL: String; Stream: TStream; out ResultCode: Integer; StaticSettings: TILStaticManagerSettings): Boolean;
const
BELOW_NORMAL_PRIORITY_CLASS = $00004000;
var
CommandLine: String;
OutFileName: String;
SecurityAttr: TSecurityAttributes;
StartInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
ExitCode: DWORD;
FileStream: TFileStream;
begin
Randomize;
Result := False;
ResultCode := -1;
IL_PrepDownloadBinaries(IL_PREP_DOWN_BINS_TAG_WGET,StaticSettings);
// prepare name for the temp file
OutFileName := StaticSettings.TempPath + CRC32ToStr(StringCRC32(URL) + TCRC32(Random($10000)));
// prepare command line
{
used wget options:
-q quiet
-T ... timeout [s]
-O ... output file
}
CommandLine := IL_Format('"%s" -q -T 5 -O "%s" "%s"',[StaticSettings.DefaultPath + 'wget.exe',OutFileName,URL]);
// init security attributes
FillChar(SecurityAttr,SizeOf(TSecurityAttributes),0);
SecurityAttr.nLength := SizeOf(TSecurityAttributes);
SecurityAttr.lpSecurityDescriptor := nil;
SecurityAttr.bInheritHandle := True;
// init startinfo
FillChar(StartInfo,SizeOf(TStartUpInfo),0);
StartInfo.cb := SizeOf(TStartupInfo);
StartInfo.dwFlags := STARTF_USESHOWWINDOW;
StartInfo.wShowWindow := SW_HIDE;
// run the wget
If CreateProcess(nil,PChar(StrToWin(CommandLine)),@SecurityAttr,@SecurityAttr,True,
BELOW_NORMAL_PRIORITY_CLASS,nil,nil,StartInfo,ProcessInfo) then
begin
WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess,ExitCode);
ResultCode := Integer(ExitCode);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
If ResultCode = 0 then
begin
FileStream := TFileStream.Create(StrToRTL(OutFileName),fmOpenRead or fmShareDenyWrite);
try
Stream.CopyFrom(FileStream,0);
Result := True;
finally
FileStream.Free;
end;
end;
end;
If IL_FileExists(OutFileName) then
IL_DeleteFile(OutFileName);
end;
//------------------------------------------------------------------------------
Function IL_SYNDownloadURL(const URL: String; Stream: TStream; out ResultCode: Integer; StaticSettings: TILStaticManagerSettings): Boolean;
var
HTTPClient: THTTPSend;
begin
Result := False;
ResultCode := -1;
IL_PrepDownloadBinaries(IL_PREP_DOWN_BINS_TAG_OSSL,StaticSettings);
HTTPClient := THTTPSend.Create;
try
// user agent must be set to something sensible, otherwise some webs refuse to send anything
HTTPClient.UserAgent := 'Mozilla/5.0 (Windows NT 5.1; rv:62.0) Gecko/20100101 Firefox/62.0';
HTTPClient.Timeout := 5000;
If HTTPClient.HTTPMethod('GET',URL) then
begin
HTTPClient.Document.SaveToStream(Stream);
Result := Stream.Size > 0;
end;
ResultCode := HTTPClient.ResultCode;
finally
HTTPClient.Free;
end;
end;
//==============================================================================
initialization
ILDiskAccessSection := TCriticalSection.Create;
finalization
FreeAndNil(ILDiskAccessSection);
end.
|
unit Invoice.Model.Entity.Product;
interface
uses System.SysUtils, Data.DB, Invoice.Model.Interfaces, Invoice.Controller.Interfaces, Invoice.Controller.Query.Factory;
type
TModelEntityProduct = class(TInterfacedObject, iEntity)
private
FQuery: iQuery;
//
procedure PreparateFields;
public
constructor Create(Connection: iModelConnection);
destructor Destroy; Override;
class function New(Connection: iModelConnection): iEntity;
function List: iEntity;
function ListWhere(aSQL: String): iEntity;
function DataSet: TDataSet;
function OrderBy(aFieldName: String): iEntity;
end;
implementation
{ TModelEntityProduct }
constructor TModelEntityProduct.Create(Connection: iModelConnection);
begin
FQuery := TControllerQueryFactory.New.Query(Connection)
end;
function TModelEntityProduct.DataSet: TDataSet;
begin
Result := FQuery.DataSet;
end;
destructor TModelEntityProduct.Destroy;
begin
if FQuery.DataSet.Active then FQuery.Close;
//
inherited;
end;
function TModelEntityProduct.List: iEntity;
begin
Result := Self;
//
FQuery.SQL('SELECT * FROM tbProduct WHERE idProduct = 0');
//
FQuery.Open;
//
PreparateFields;
end;
function TModelEntityProduct.ListWhere(aSQL: String): iEntity;
begin
Result := Self;
//
FQuery.SQL('SELECT * FROM tbProduct WHERE ' + aSQL);
//
FQuery.Open;
//
PreparateFields;
end;
class function TModelEntityProduct.New(Connection: iModelConnection): iEntity;
begin
Result := Self.Create(Connection);
end;
function TModelEntityProduct.OrderBy(aFieldName: String): iEntity;
begin
FQuery.Order(aFieldName);
end;
procedure TModelEntityProduct.PreparateFields;
begin
if (FQuery.DataSet.Fields.Count > 0) then
begin
FQuery.DataSet.Fields.FieldByName('idProduct').ProviderFlags := [pfInWhere,pfInKey];
FQuery.DataSet.Fields.FieldByName('idProduct').ReadOnly := True;
FQuery.DataSet.Fields.FieldByName('idProduct').DisplayWidth := 20;
//
FQuery.DataSet.Fields.FieldByName('nameProduct').ProviderFlags := [pfInUpdate];
FQuery.DataSet.Fields.FieldByName('nameProduct').ReadOnly := False;
FQuery.DataSet.Fields.FieldByName('nameProduct').DisplayWidth := 100;
//
FQuery.DataSet.Fields.FieldByName('priceProduct').ProviderFlags := [pfInUpdate];
FQuery.DataSet.Fields.FieldByName('priceProduct').ReadOnly := False;
//FQuery.DataSet.Fields.FieldByName('priceProduct').DisplayWidth := 100;
end;
end;
end.
|
{ Русификация: 1998-2001 Polaris Software }
{ http://polesoft.da.ru }
unit IBConst;
interface
resourcestring
srSamples = 'Samples';
SNoEventsRegistered = 'Вы должны зарегистрировать события перед их запросом';
SInvalidDBConnection = 'Компонент не подключен к открытой Database';
SInvalidDatabase = '''''%s'''' не подключен к базе данных InterBase';
SInvalidCancellation = 'Нельзя вызвать CancelEvents внутри OnEventAlert';
SInvalidEvent = 'Неверное пустое событие добавлено в список событий EventAlerter';
SInvalidQueueing = 'Нельзя вызвать QueueEvents внутри OnEventAlert';
SInvalidRegistration = 'Нельзя вызвать Register или Unregister для событий внутри OnEventAlert';
{$IFNDEF VER100}
SMaximumEvents = 'Можно зарегистрировать только 15 событий в EventAlerter';
{$ENDIF}
implementation
end.
|
unit Situation;
interface
uses
Errors;
type
TSituationInfo = record
wID_Situation:word;
sSitText:string[256];
sVRSs:string[30];
end;
TSituationFile = file of TSituationInfo;
TSituation = class
private
siCurSituation:TSituationInfo;
fSitFile:TSituationFile;
isFileAssigned:boolean;
isFileOpened:boolean;
public
constructor Create;
function OpenFile(psFName:string):byte;
function CreateFile(psFName:string; isRewriteIfExists:boolean):byte;
function LoadSituation(pwSitId:word):byte; //Done
function AddSituation(psSitText,
psVRSs:string;
CurOverwrite:boolean):byte;
function GetFileOpened:boolean;
function GetFileAssigned:boolean;
function GetSitID:word;
function GetSitText:string;
function GetSitVRSs:string;
procedure SetSitText(psNewText:string[256]);
procedure SetSitVRSs(psNewVRSs:string[30]);
end;
implementation
constructor TSituation.Create;
begin
siCurSituation.sSitText:='';
siCurSituation.sVRSs:='';
siCurSituation.wID_Situation:=0;
end;
function TSituation.OpenFile(psFName:string):byte;
begin
result:=ERROR_SUCCESS;
//Checking if file exists. If not - ERROR_NOT_EXISTS
if not FileExists(psFName) then begin
result:=ERROR_NOT_EXISTS;
exit;
end;{if}
AssignFile(fSitFile, psFName);
isFileAssigned:=true;
end;{LoadPlayerFromFile}
function TSituation.LoadSituation(pwSitId:word):byte;
var
siCurSit:TSituationInfo;
begin
//Если мы не открыли или не создали до сих пор игрока.
if not isFileAssigned then begin
result:=ERROR_FILE_NOT_ASSIGNED;
exit;
end;{if}
//Если мы не открыли или не создали до сих пор игрока.
if isFileOpened then begin
result:=ERROR_FILE_BUSY;
exit;
end;{if}
//If something goes worng - set result to ERROR_UNKNOWN and exit;
try
Reset(fSitFile);
isFileOpened:=true;
except
on e:Exception do begin
result:=ERROR_UNKNOWN;
exit;
end;{on}
end;{try}
result:=ERROR_SIT_NOT_FOUND;
//Если файл пуст - выходим из ф-ции, возвращая SIT_NOT_FOUND
if FileSize(fSitFile) = 0 then exit;
while not EOF(fSitFile) do begin
read(fSitFile, siCurSit);
//Found!
if siCurSit.wID_Situation = pwSitId then begin
result:=ERROR_SIT_FOUND;
siCurSituation:=siCurSit;
exit;
end;
end;
try
CloseFile(fSitFile);
isFileOpened:=false
except
on Exception do begin
result:=ERROR_UNKNOWN;
exit;
end;
end;
end;
function TSituation.AddSituation(psSitText,
psVRSs:string;
CurOverwrite:boolean):byte;
var
lsiBufSit:TSituationInfo;
lwSitID:word;
begin
result:=ERROR_SUCCESS;
//Если мы не открыли или не создали до сих пор игрока.
if not isFileAssigned then begin
result:=ERROR_FILE_NOT_ASSIGNED;
exit;
end;{if}
//Если мы не открыли или не создали до сих пор игрока.
if isFileOpened then begin
result:=ERROR_FILE_BUSY;
exit;
end;{if}
//If something goes worng - set result to ERROR_UNKNOWN and exit;
try
Reset(fSitFile);
isFileOpened:=true;
except
on e:Exception do begin
result:=ERROR_UNKNOWN;
exit;
end;{on}
end;{try}
Randomize;
lwSitID:=Random(Word.MaxValue);
{#Разкомментировать,когда будет написана isSitExists
while isSitExists(lwSitID) do begin
lwSitId:=Random(Word.MaxValue);
end;
}
lsiBufSit.wID_Situation:=lwSitID;
lsiBufSit.sVRSs:=psVRSs;
lsiBufSit.sSitText:=psSitText;
if FileSize(fSitFile)<>0 then
Seek(fSitFile, FileSize(fSitFile));
Write(fSitFile, lsiBufSit);
try
CloseFile(fSitFile);
isFileOpened:=false
except
on Exception do begin
result:=ERROR_UNKNOWN;
exit;
end;
end;
if CurOverwrite then siCurSituation:=lsiBufSit;
end;
function TSituation.CreateFile(psFName:string; isRewriteIfExists:boolean):byte;
begin
//Если программист передал нам true во второй параметр и файл уже существует - выходим с ошибкой
if not isRewriteIfExists and FileExists(psFName) then begin
result:=ERROR_FILE_EXISTS;
exit;
end;
AssignFile(fSitFile, psFName);
isFileAssigned:=true;
try
Rewrite(fSitFile);
isFileOpened:=true;
except
//In case of wtf emergencie
on e:Exception do begin
result:=ERROR_UNKNOWN;
exit;
end
end;
try
CloseFile(fSitFile);
isFileOpened:=false;
except
on Exception do begin
result:=ERROR_UNKNOWN;
exit;
end;
end;
end;
function TSituation.GetFileOpened:boolean;
begin
result:=isFileOpened;
end;
function TSituation.GetFileAssigned:boolean;
begin
result:=isFileAssigned;
end;
function TSituation.GetSitID:word;
begin
result:=self.siCurSituation.wID_Situation;
end;
function TSituation.GetSitText:string;
begin
result:=self.siCurSituation.sSitText;
end;
function TSituation.GetSitVRSs:string;
begin
result:=self.siCurSituation.sVRSs;
end;
procedure TSituation.SetSitText(psNewText:string[256]);
begin
siCurSituation.sSitText:=psNewText;
end;
procedure TSituation.SetSitVRSs(psNewVRSs:string[30]);
begin
siCurSituation.sVRSs:=psNewVRSs;
end;
end. |
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2020, Michael R. . All rights reserved.
// ####
// #### 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 authData;
interface
uses SysUtils, Types, cbor;
type
TFidoRPIDHash = Array[0..31] of byte;
EAuthDataException = class(Exception);
// ###########################################
// #### Decodes the Authenticator buffer for both the enrolling process and
// assertion process (with less data)
type
TAuthData = class(TObject)
private
// minimum
frpIDHash : TFidoRPIDHash;
fflags : byte; // bit 0: user present
// bit 2: user verification
// bit 6: attested credential data included
// bit 7: extension included
fsignCnt : LongWord;
// attested credential data (optional)
faaGUID : TGuid;
fcredIDLend : word;
fCredID : TBytes;
fCred : TCborMap;
fExtensions : TCborItem;
public
function UserPresent : boolean;
function UserVerified : boolean;
function HasAttestedData : boolean;
function HasExtensions : boolean;
function RPIDHash : TFidoRPIDHash;
function SigCount : LongWord;
function AAUID : TGuid;
function ToString : string; override;
constructor Create( fromData : TBytes ); overload;
constructor Create( data : PByte; len : integer); overload;
destructor Destroy; override;
end;
implementation
uses SuperObject;
{ TAuthData }
function TAuthData.UserPresent: boolean;
begin
Result := (fflags and $01) <> 0;
end;
function TAuthData.UserVerified: boolean;
begin
Result := (fflags and $04) <> 0;
end;
function TAuthData.HasAttestedData: boolean;
begin
Result := (fflags and $40) <> 0;
end;
function TAuthData.HasExtensions: boolean;
begin
Result := (fflags and $80) <> 0;
end;
function TAuthData.RPIDHash: TFidoRPIDHash;
begin
Result := frpIDHash;
end;
function TAuthData.SigCount: LongWord;
begin
Result := fsignCnt;
end;
procedure RevertByteOrder( stream : PByte; numBytes : integer);
var i: Integer;
pEnd : PByte;
tmp : byte;
begin
pEnd := stream;
inc(pEnd, numBytes - 1);
for i := 0 to numBytes div 2 - 1 do
begin
tmp := stream^;
stream^ := pEnd^;
pEnd^ := tmp;
inc(stream);
dec(pEnd);
end;
end;
constructor TAuthData.Create(fromData: TBytes);
var idx : integer;
numDecoded : integer;
coseIdx1, coseIdx2, coseIdx3 : integer;
cose1 : TCborUINTItem;
cose2 : TCborNegIntItem;
begin
// according to https://www.w3.org/TR/webauthn/#sctn-attestation
// the attestation object subtype authData is:
// 32 bytes of rpIDHash
// 1 byte flags:
// 4 bytess counter. -> a total of 37 bytes minimum
// if AttestedData flag is set then
// 16 bytes AAUID of the key
// 2 bytes Credential id length
// followed this number of bytes credential id
// followed by the credential public key (variable length COSE_key)
// this data is cbor encoded
// if extended flag is set the rest is
// a cbor map of extended flags
if Length(fromData) < 37 then
raise EAuthDataException.Create('Error at least 37 bytes required');
Move( fromData[0], frpIDHash, sizeof(frpIDHash));
fflags := fromData[32];
fsignCnt := PLongWord( @fromData[33] )^;
RevertByteOrder( @fsignCnt, sizeof(fsignCnt));
idx := 37;
if HasAttestedData then
begin
if Length(fromData) < idx + sizeof(word) + sizeof(TGuid) then
raise EAuthDataException.Create('Error no memory for attestation data');
Move( fromData[idx], faaGUID, sizeof(faaGUID));
idx := idx + sizeof(TGUID);
fcredIDLend := PWord(@fromData[idx])^;
RevertByteOrder(@fcredIDLend, sizeof(fcredIDLend));
inc(idx, sizeof(word));
if Length(fromData) < idx + fcredIDLend then
raise EAuthDataException.Create('Bad attestation data - data too short');
SetLength(fCredID, fcredIDLend);
if fcredIDLend > 0 then
Move(fromData[idx], fCredID[0], fcredIDLend);
inc(idx, fcredIDLend);
numDecoded := 0;
if idx < Length(fromData) then
begin
fCred := TCborDecoding.DecodeData(@fromData[idx], Length(fromData) - idx, numDecoded) as TCborMap;
// for now we just check if fields 1, 3, -2 and -3 are available and the
// key type is in in the range of the ones supported from the fido dll
coseIdx1 := fCred.IndexOfName('1');
coseIdx2 := fCred.IndexOfName('3');
coseIdx3 := fCred.IndexOfName('-1');
if (coseIdx1 < 0) or (coseIdx2 < 0) or (coseIdx3 < 0) then
raise EAuthDataException.Create('Credential public key does not contain the fields "1", "3" or "-1"');
cose1 := fCred.Values[coseIdx1] as TCborUINTItem;
// COSE_KTY_OKP = 1;
// COSE_KTY_EC2 = 2;
// COSE_KTY_RSA = 3;
if not (cose1.Value in [1, 2, 3]) then
raise EAuthDataException.Create('Cose type not in the expected range');
// COSE_ES256 = -7;
// COSE_EDDSA = -8;
// COSE_RS256 = -257;
cose2 := fCred.Values[coseIdx2] as TCborNegIntItem;
if (cose2.Value <> -7) and (cose2.Value <> -8) and (cose2.Value <> -257) then
raise EAuthDataException.Create('Cose algorithm not recognized');
end;
idx := idx + numDecoded;
end;
if HasExtensions then
begin
// cbor encoded extensions
fExtensions := TCborDecoding.DecodeData( @fromData[idx], Length(fromData) - idx);
end;
end;
function TAuthData.AAUID: TGuid;
begin
Result := faaGUID;
end;
constructor TAuthData.Create(data: PByte; len: integer);
var fromData : TBytes;
begin
SetLength(fromData, len);
if len > 0 then
Move( data^, fromData[0], len);
Create( fromData );
end;
destructor TAuthData.Destroy;
begin
fExtensions.Free;
fCred.Free;
inherited;
end;
function TAuthData.ToString: string;
var res : ISuperObject;
begin
res := SO;
res.S['aauid'] := GUIDToString( faaGUID );
res.B['UserPresent'] := UserPresent;
res.B['UserVerified'] := UserVerified;
res.I['sigCnt'] := fsignCnt;
res.S['hash'] := Base64URLEncode( @frpIDHash[0], Length(frpIDHash) );
if Assigned(fCred) then
res.S['cred'] := fCred.ToString;
Result := res.AsJSon;
end;
end.
|
unit System.Tether.IniFileStorage;
interface
uses
System.Generics.Collections, System.IniFiles, System.SysUtils, System.Classes,
System.Tether.Manager;
type
TTetheringIniFileStorage = class(TTetheringCustomStorage)
private
const RemoteSection = 'Remote Managers'; // do not localize
const LocalSection = 'Local Managers'; // do not localize
const KeyIdentifier = 'Identifier'; // do not localize
private
FIniFile: TIniFile;
public
constructor Create(const AStorage: TFileName);
destructor Destroy; override;
function LoadManagerGUID: string; override;
procedure SaveManagerGUID(const AIdentifier: string); override;
procedure LoadRemoteManagersGUIDs(const AGUIDPassList: TStringList); override;
procedure SaveRemoteManagersGUIDs(const AGUIDPassList: TStringList); override;
end;
implementation
uses
System.IOUtils;
{ TTetheringIniFileStorage }
constructor TTetheringIniFileStorage.Create(const AStorage: TFileName);
begin
FIniFile := TIniFile.Create(string(AStorage));
end;
destructor TTetheringIniFileStorage.Destroy;
begin
FIniFile.Free;
end;
function TTetheringIniFileStorage.LoadManagerGUID: string;
begin
Result := FIniFile.ReadString(LocalSection, KeyIdentifier, ''); // do not localize
if Result = '' then
begin
Result := TGUID.NewGuid.ToString;
SaveManagerGUID(Result);
end;
end;
procedure TTetheringIniFileStorage.LoadRemoteManagersGUIDs(const AGUIDPassList: TStringList);
begin
FIniFile.ReadSectionValues(RemoteSection, AGUIDPassList);
end;
procedure TTetheringIniFileStorage.SaveManagerGUID(const AIdentifier: string);
begin
FIniFile.WriteString(LocalSection, KeyIdentifier, AIdentifier); // do not localize
FIniFile.UpdateFile;
end;
procedure TTetheringIniFileStorage.SaveRemoteManagersGUIDs(const AGUIDPassList: TStringList);
var
I: Integer;
begin
if AGUIDPassList <> nil then
begin
FIniFile.EraseSection(RemoteSection);
for I := 0 to AGUIDPassList.Count - 1 do
if AGUIDPassList.Names[I] <> '' then
FIniFile.WriteString(RemoteSection, AGUIDPassList.Names[I], AGUIDPassList.ValueFromIndex[I]);
FIniFile.UpdateFile;
end;
end;
end.
|
unit mainunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, LCLIntf;
{ TMainForm }
type
TMainForm = class(TForm)
Button1: TButton;
Image1: TImage;
Image2: TImage;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
procedure Lightness;
public
{ public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
uses Math;
procedure TMainForm.Lightness;
var
p: TColor;
x, y: Integer;
r,g,b: Byte;
t: Double;
l: Byte;
begin
Image2.Picture.Clear;
y := 0;
while y < Image1.Height do
begin
x := 0;
while x < Image1.Width do
begin
p := Image1.Canvas.Pixels[x,y];
r := GetRValue(p);
g := GetGValue(p);
b := GetBValue(p);
t := (0.2126 * r + 0.7152 * g + 0.0722 * b)/255;
if t > Power(6/29, 3)
then t := Power(t, 1/3)
else t := (1/3 * 29/6 * 29/6 * t) + (4/29);
l := Byte(Trunc(2.55 * (116 * t - 16)));
Image2.Canvas.Pixels[x,y] := RGBToColor(l, l, l);
Inc(x);
end;
Inc(y);
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
Lightness;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Image1.Picture.LoadFromFile(Application.Location + '/test.jpg');
end;
end.
|
unit Dmitry.Controls.DmProgress;
interface
uses
Dmitry.Memory,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Controls,
Vcl.Forms,
Vcl.Themes,
Vcl.ExtCtrls,
Vcl.Graphics;
type
ARGB = array [0..32677] of TRGBTriple;
PARGB = ^ARGB;
TDmPforress_view = (dm_pr_normal, dm_pr_cool);
type
TDmProgress = class(TWinControl)
private
FCanvas: TCanvas;
FPosition: Int64;
FMinValue: Int64;
FMaxValue: Int64;
FNPicture: TBitmap;
fText: string;
fBorderColor: TColor;
FCoolColor: TColor;
fBackGroundColor: TColor;
FColor: TColor;
FView: TDmPforress_view;
FFont: TFont;
FInverse: Boolean;
FCurrentProgressPercent: Byte;
Timer: TTimer;
FStep: Integer;
procedure SetMaxValue(const Value: Int64);
procedure SetMinValue(const Value: Int64);
procedure SetPosition(const Value: Int64);
procedure settext(const Value: string);
procedure setBorderColor(const Value: TColor);
procedure setCoolColor(const Value: TColor);
procedure fonrchanged(var Message: TMessage); message CM_FONTCHANGED;
procedure Paint(var msg : Tmessage); message WM_PAINT;
procedure WMSize(var Msg : TMessage); message WM_SIZE;
procedure Setcolor(const Value: TColor);
procedure SetView(const Value: TDmPforress_view);
procedure SetFont(const Value: TFont);
procedure SetInverse(const Value: boolean);
{ Private declarations }
protected
{ Protected declarations }
procedure TimerAction(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoPaint;
procedure Redraw;
procedure DoPaintOnXY(Canvas: TCanvas; x, y: Integer);
procedure DoDraw(Canvas: THandle; x, y: Integer);
{ Public declarations }
published
property Visible;
property OnMouseMove;
property OnMouseDown;
property OnMouseUp;
property Align;
property Anchors;
property Enabled;
property Cursor;
property Hint;
property ShowHint;
property Position: Int64 read FPosition write SetPosition;
property MinValue: Int64 Read FMinValue write SetMinValue;
property MaxValue: Int64 Read FMaxValue write SetMaxValue;
property Font: TFont read FFont write SetFont;
property Text: string read fText write settext;
property BorderColor: TColor read fBorderColor write setBorderColor;
Property CoolColor: TColor read FCoolColor write setCoolColor;
Property Color: TColor read FColor write Setcolor;
property View: TDmPforress_view read FView write SetView;
property Inverse: Boolean read FInverse write SetInverse;
{ Published declarations }
end;
procedure Register;
implementation
uses Types;
procedure Register;
begin
RegisterComponents('Dm', [TDmProgress]);
end;
{ TDmProgress }
constructor TDmProgress.Create(AOwner : TComponent);
begin
inherited;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FInverse := False;
FnPicture := TBitmap.create;
FNPicture.PixelFormat := pf24bit;
FFont := TFont.create;
FMinvalue := 0;
FMaxValue := 100;
FPosition := 0;
Ftext := 'Progress... (&%%)';
FBorderColor := RGB(0,150,0);
FcoolColor := RGB(0,150,0);
FbackGroundColor := RGB(0,0,0);
FColor := RGB(0,0,0);
FView := dm_pr_cool;
FFont.Color := $00FF0080;
Width := 100;
Height := 18;
FCurrentProgressPercent := 255;
FStep := 0;
Timer := TTimer.Create(nil);
Timer.Interval := 10;
Timer.OnTimer := TimerAction;
Timer.Enabled := True;
if AOwner is TWinCOntrol then
Parent:= AOwner as TWinCOntrol;
end;
destructor TDmProgress.destroy;
begin
F(FNPicture);
F(FCanvas);
F(FFont);
F(Timer);
inherited;
end;
procedure TDmProgress.Paint(var msg: Tmessage);
begin
inherited;
DoPaint;
end;
procedure TDmProgress.setBorderColor(const Value: Tcolor);
begin
FBorderColor := Value;
Redraw;
end;
procedure TDmProgress.setCoolColor(const Value: Tcolor);
begin
FCoolColor := Value;
Redraw;
end;
procedure TDmProgress.SetMaxValue(const Value: Int64);
begin
FMaxValue := Value;
If FMaxvalue < FMinvalue then
FMaxvalue := FMinvalue + 1;
if FMaxValue = 0 then
FMaxValue := 1;
SetPosition(fposition);
end;
procedure TDmProgress.SetMinValue(const Value: Int64);
begin
FMinValue := Value;
If FMaxvalue < FMinvalue then
FMinvalue := FMaxvalue - 1;
SetPosition(FPosition);
end;
procedure TDmProgress.SetText(const Value: string);
begin
FText := Value;
Redraw;
end;
procedure TDmProgress.WMSize(var Msg: TMessage);
begin
Fnpicture.Width := Width;
Fnpicture.Height := Height;
Redraw;
end;
procedure TDmProgress.fonrchanged(var Message: TMessage);
begin
SetPosition(fposition);
end;
procedure TDmProgress.SetView(const Value: TDmPforress_view);
begin
FView := Value;
SetPosition(fposition);
end;
procedure TDmProgress.TimerAction(Sender: TObject);
var
Canvas: TCanvas;
begin
if StyleServices.Available and (Inverse) and Visible then
begin
Inc(FStep, 1);
if FStep mod 100 = 0 then
FStep := 0;
Canvas := TCanvas.Create;
try
Canvas.Handle := GetWindowDC(Handle);
DoDraw(Canvas.Handle, 0, 0);
finally
ReleaseDC(Handle, Canvas.Handle);
Canvas.Handle := 0;
F(Canvas);
end;
end else
Timer.Enabled := False;
end;
procedure TDmProgress.Setcolor(const Value: TColor);
begin
FColor := Value;
SetPosition(fposition);
end;
procedure TDmProgress.SetFont(const Value: TFont);
begin
FFont.assign(Value);
SetPosition(fposition);
end;
procedure TDmProgress.SetInverse(const Value: boolean);
begin
FInverse := Value;
end;
procedure TDmProgress.DoPaint;
begin
Redraw;
end;
procedure TDmProgress.DoPaintOnXY(Canvas : TCanvas; X, Y : integer);
begin
DoDraw(Canvas.Handle, X ,Y);
end;
procedure TDmProgress.SetPosition(const Value: Int64);
var
FNewProgressPercent : Byte;
begin
if (Value > FMaxValue) or (Value < FMinValue) then
FPosition := FMaxValue
else
FPosition := Value;
FNewProgressPercent := Round(100 * ((FPosition - FMinValue)/(FMaxValue - FMinValue)));
if (FNewProgressPercent <> FCurrentProgressPercent) then
begin
FCurrentProgressPercent := FNewProgressPercent;
Redraw;
end;
end;
procedure TDmProgress.Redraw;
begin
if Visible or (csDesigning in ComponentState) then
DoDraw(FCanvas.Handle, 0, 0);
end;
procedure TDmProgress.DoDraw(Canvas: THandle; X, Y: Integer);
var
P: PARGB;
I, J, W, C: Integer;
DrawRect: TRect;
Text: string;
R, G, B: Byte;
RB, GB, BB: Byte;
RC, GC, BC: Byte;
function TextHeight(DC: HDC; const Text: string): Integer;
var
Size: TSize;
begin
Size.cx := 0;
Size.cy := 0;
GetTextExtentPoint32(Canvas, PChar(Text), Length(Text), Size);
Result := Size.cy;
end;
function GetPercent: Single;
var
LMin, LMax, LPos: Int64;
begin
LMin := MinValue;
LMax := MaxValue;
LPos := Position;
if (LMin >= 0) and (LPos >= LMin) and (LMax >= LPos) and (LMax - LMin <> 0) then
Result := (LPos - LMin) / (LMax - LMin)
else
Result := 0;
end;
function BarRect: TRect;
begin
Result := TRect.Create(0, 0, Width, Height);
InflateRect(Result, -BorderWidth, -BorderWidth);
end;
procedure PaintFrame(Canvas: TCanvas);
var
R: TRect;
Details: TThemedElementDetails;
begin
if not StyleServices.Available then Exit;
R := BarRect;
//if Orientation = pbHorizontal then
Details := StyleServices.GetElementDetails(tpBar);
//else
// Details := StyleServices.GetElementDetails(tpBarVert);
StyleServices.DrawElement(Canvas.Handle, Details, R);
end;
procedure DrawInverseBar(Canvas: TCanvas);
var
FillR, R: TRect;
W, Pos: Integer;
Details: TThemedElementDetails;
begin
if StyleServices.Enabled then
begin
R := BarRect;
InflateRect(R, -1, -1);
//if Orientation = pbHorizontal then
W := R.Width;
//else
// W := R.Height;
Pos := Round(W * 0.1);
FillR := R;
//if Orientation = pbHorizontal then
begin
FillR.Right := FillR.Left + Pos;
Details := StyleServices.GetElementDetails(tpChunk);
end;// else
//begin
// FillR.Top := FillR.Bottom - Pos;
// Details := StyleServices.GetElementDetails(tpChunkVert);
// end;
FillR.SetLocation(Round((FStep / 10) * FillR.Width), FillR.Top);
StyleServices.DrawElement(Canvas.Handle, Details, FillR);
end;
end;
procedure PaintBar(Canvas: TCanvas);
var
FillR, R: TRect;
W, Pos: Integer;
Details: TThemedElementDetails;
begin
if not StyleServices.Available then
Exit;
if Inverse then
begin
DrawInverseBar(Canvas);
Exit;
end;
R := BarRect;
InflateRect(R, -1, -1);
//if Orientation = pbHorizontal then
W := R.Width;
//else
// W := R.Height;
Pos := Round(W * GetPercent);
FillR := R;
//if Orientation = pbHorizontal then
begin
FillR.Right := FillR.Left + Pos;
Details := StyleServices.GetElementDetails(tpChunk);
end;
//else
//begin
// FillR.Top := FillR.Bottom - Pos;
// Details := StyleServices.GetElementDetails(tpChunkVert);
//end;
StyleServices.DrawElement(Canvas.Handle, Details, FillR);
end;
procedure DrawStyledProgress(Canvas: TCanvas);
var
Details: TThemedElementDetails;
begin
if StyleServices.Available then
begin
Details.Element := teProgress;
if StyleServices.HasTransparentParts(Details) then
begin
if Parent is TForm then
begin
Canvas.Brush.Color := StyleServices.GetSystemColor(clBtnFace);
Canvas.Pen.Color := StyleServices.GetSystemColor(clBtnFace);
Canvas.Rectangle(0, 0, Width, Height);
end else
StyleServices.DrawParentBackground(Handle, Canvas.Handle, Details, False);
end;
end;
PaintFrame(Canvas);
PaintBar(Canvas);
end;
procedure DtawProgressText(Canvas: TCanvas);
begin
Text := StringReplace(FText, '&%', IntToStr(FCurrentProgressPercent), [rfReplaceAll]);
SetBkMode(Canvas.Handle, TRANSPARENT);
SetBkColor(Canvas.Handle, Color);
if StyleServices.Enabled then
SetTextColor(Canvas.Handle, StyleServices.GetStyleFontColor(sfPopupMenuItemTextNormal))
else
SetTextColor(Canvas.Handle, FFont.Color);
SelectObject(Canvas.Handle, FFont.Handle);
DrawRect := Rect(0, 0, Width - 1, Height - 1);
Drawrect.Top := Drawrect.Bottom div 2 - TextHeight(FNPicture.Canvas.Handle, Text) div 2;
DrawText(Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_CENTER or DT_VCENTER);
end;
begin
FNPicture.Width := Width;
FNPicture.Height := Height;
try
if StyleServices.Enabled and TStyleManager.IsCustomStyleActive then
begin
DrawStyledProgress(FNPicture.Canvas);
DtawProgressText(FNPicture.Canvas);
Exit;
end;
R := GetRValue(ColorToRGB(Color));
G := GetGValue(ColorToRGB(Color));
B := GetBValue(ColorToRGB(Color));
rb := GetRValue(ColorToRGB(FBorderColor));
gb := GetGValue(ColorToRGB(FBorderColor));
bb := GetBValue(ColorToRGB(FBorderColor));
rc := GetRValue(ColorToRGB(FCoolColor));
gc := GetGValue(ColorToRGB(FCoolColor));
bc := GetBValue(ColorToRGB(FCoolColor));
for I := 0 to Height - 1 do
begin
P := FNPicture.ScanLine[i];
for J := 0 to Width-1 do
begin
P[J].rgbtRed := R;
P[J].rgbtGreen := G;
P[J].rgbtBlue := B;
end;
P[0].rgbtRed := RB;
P[0].rgbtGreen := GB;
P[0].rgbtBlue := BB;
P[Width - 1].rgbtRed := RB;
P[Width - 1].rgbtGreen := GB;
P[Width - 1].rgbtBlue := BB;
end;
P := FNPicture.ScanLine[Height - 1];
for J := 0 to Width - 1 do
begin
P[J].rgbtRed := RB;
P[J].rgbtGreen := GB;
P[J].rgbtBlue := BB;
end;
P := FNPicture.ScanLine[0];
for J := 0 to Width - 1 do
begin
P[J].rgbtRed := RB;
P[J].rgbtGreen := GB;
P[J].rgbtBlue := BB;
end;
if fview = dm_pr_cool then
begin
for I := 2 to Height - 3 do
begin
P := FNPicture.ScanLine[I];
W := Round((Width - 1) * ((FPosition - FMinValue) / (FMaxValue - FMinValue)));
for J := 2 to W - 2 do
begin
if FInverse then
C := W - 2 - J
else
C := J;
P[C].rgbtRed := RC * J div W;
P[C].rgbtGreen := GC * J div W;
P[C].rgbtBlue := BC * J div W;
end;
end;
end else
begin
for I := 2 to Height - 3 do
begin
P := FNPicture.ScanLine[I];
W := Round((Width - 1) * ((FPosition - FMinValue) / (FMaxValue - FMinValue)));
for J := 2 to W - 2 do
begin
P[J].rgbtRed := RC;
P[J].rgbtGreen := GC;
P[J].rgbtBlue := BC
end;
end;
end;
DtawProgressText(FNPicture.Canvas);
finally
BitBlt(Canvas, X, Y, FNPicture.Width, FNPicture.Height, FNPicture.Canvas.Handle, 0, 0, SRCCOPY);
end;
end;
end.
|
(* Handles player inventory and associated functions *)
unit player_inventory;
{$mode objfpc}{$H+}
interface
uses
Graphics, SysUtils, entities, items, ui, globalutils;
type
(* Items in inventory *)
Equipment = record
id, useID: smallint;
Name, description, itemType: shortstring;
glyph: char;
(* Is the item still in the inventory *)
inInventory: boolean;
(* Is the item being worn or wielded *)
equipped: boolean;
end;
var
inventory: array[0..9] of Equipment;
(* 0 - main menu, 1 - drop menu, 2 - quaff menu, 3 - wear/wield menu *)
menuState: byte;
(* Initialise empty player inventory *)
procedure initialiseInventory;
(* Setup equipped items when loading a saved game *)
procedure loadEquippedItems;
(* Add to inventory *)
function addToInventory(itemNumber: smallint): boolean;
(* Display the inventory screen *)
procedure showInventory;
(* Show menu at bottom of screen *)
procedure bottomMenu(style: byte);
(* Show hint at bottom of screen *)
procedure showHint(message: shortstring);
(* Highlight inventory slots *)
procedure highlightSlots(i, x: smallint);
(* Dim inventory slots *)
procedure dimSlots(i, x: smallint);
(* Accept menu input *)
procedure menu(selection: word);
(* Drop menu *)
procedure drop(dropItem: byte);
(* Quaff menu *)
procedure quaff(quaffItem: byte);
(* Wear / Wield menu *)
procedure wield(wieldItem: byte);
implementation
uses
main;
procedure initialiseInventory;
var
i: byte;
begin
for i := 0 to 9 do
begin
inventory[i].id := i;
inventory[i].Name := 'Empty';
inventory[i].equipped := False;
inventory[i].description := 'x';
inventory[i].itemType := 'x';
inventory[i].glyph := 'x';
inventory[i].inInventory := False;
inventory[i].useID := 0;
end;
end;
procedure loadEquippedItems;
var
i: smallint;
begin
for i := 0 to 9 do
begin
if (inventory[i].equipped = True) then
begin
(* Check for weapons *)
if (inventory[i].itemType = 'weapon') then
ui.updateWeapon(inventory[i].Name)
(* Check for armour *)
else if (inventory[i].itemType = 'armour') then
ui.updateArmour(inventory[i].Name);
end;
end;
end;
(* Returns TRUE if successfully added, FALSE if the inventory is full *)
function addToInventory(itemNumber: smallint): boolean;
var
i: smallint;
begin
Result := False;
for i := 0 to 9 do
begin
if (inventory[i].Name = 'Empty') then
begin
itemList[itemNumber].onMap := False;
(* Populate inventory with item description *)
inventory[i].id := i;
inventory[i].Name := itemList[itemNumber].itemname;
inventory[i].description := itemList[itemNumber].itemDescription;
inventory[i].itemType := itemList[itemNumber].itemType;
inventory[i].useID := itemList[itemNumber].useID;
inventory[i].glyph := itemList[itemNumber].glyph;
inventory[i].inInventory := True;
ui.displayMessage('You pick up the ' + inventory[i].Name);
Result := True;
exit;
end
end;
end;
procedure showInventory;
var
i, x: smallint;
begin
main.gameState := 2; // Accept keyboard commands for inventory screen
menuState := 0;
currentScreen := inventoryScreen; // Display inventory screen
(* Clear the screen *)
inventoryScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
inventoryScreen.Canvas.FillRect(0, 0, inventoryScreen.Width, inventoryScreen.Height);
(* Draw title bar *)
inventoryScreen.Canvas.Brush.Color := globalutils.MESSAGEFADE6;
inventoryScreen.Canvas.Rectangle(50, 40, 785, 80);
(* Draw title *)
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.Font.Size := 12;
inventoryScreen.Canvas.TextOut(100, 50, 'Inventory slots');
inventoryScreen.Canvas.Font.Size := 10;
(* List inventory *)
x := 90; // x is position of each new line
for i := 0 to 9 do
begin
x := x + 20;
if (inventory[i].Name = 'Empty') then
dimSlots(i, x)
else
highlightSlots(i, x);
end;
bottomMenu(0);
end;
procedure bottomMenu(style: byte);
(* 0 - main menu, 1 - inventory slots, exit *)
begin
(* Draw menu bar *)
inventoryScreen.Canvas.Brush.Color := globalutils.MESSAGEFADE6;
inventoryScreen.Canvas.Rectangle(50, 345, 785, 375);
(* Show menu options at bottom of screen *)
case style of
0: // Main menu
begin
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.TextOut(100, 350,
'D key for drop menu | Q key for quaff/drink menu | W key to equip armour/weapons | ESC key to exit');
end;
1: // Select Inventory slot
begin
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.TextOut(100, 350,
'0..9 to select an inventory slot | ESC key to go back');
end;
end;
end;
procedure showHint(message: shortstring);
begin
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.TextOut(100, 480, message);
end;
procedure highlightSlots(i, x: smallint);
begin
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.TextOut(50, x, '[' + IntToStr(i) + '] ' +
inventory[i].Name + ' - ' + inventory[i].description);
end;
procedure dimSlots(i, x: smallint);
begin
inventoryScreen.Canvas.Font.Color := MESSAGEFADE1;
inventoryScreen.Canvas.TextOut(50, x, '[' + IntToStr(i) + '] <empty slot>');
end;
procedure menu(selection: word);
begin
case selection of
0: // ESC key i pressed
begin
if (menuState = 0) then
begin
main.gameState := 1;
main.currentScreen := tempScreen;
exit;
end
else if (menuState = 1) then // In the Drop screen
showInventory
else if (menuState = 2) then // In the Quaff screen
showInventory
else if (menuState = 3) then // In the Wear / Wield screen
showInventory;
end;
1: drop(10); // Drop menu
2: // 0 slot
begin
if (menuState = 1) then
drop(0)
else if (menuState = 2) then
quaff(0)
else if (menuState = 3) then
wield(0);
end;
3: // 1 slot
begin
if (menuState = 1) then
drop(1)
else if (menuState = 2) then
quaff(1)
else if (menuState = 3) then
wield(1);
end;
4: // 2 slot
begin
if (menuState = 1) then
drop(2)
else if (menuState = 2) then
quaff(2)
else if (menuState = 3) then
wield(2);
end;
5: // 3 slot
begin
if (menuState = 1) then
drop(3)
else if (menuState = 2) then
quaff(3)
else if (menuState = 3) then
wield(3);
end;
6: // 4 slot
begin
if (menuState = 1) then
drop(4)
else if (menuState = 2) then
quaff(4)
else if (menuState = 3) then
wield(4);
end;
7: // 5 slot
begin
if (menuState = 1) then
drop(5)
else if (menuState = 2) then
quaff(5)
else if (menuState = 3) then
wield(5);
end;
8: // 6 slot
begin
if (menuState = 1) then
drop(6)
else if (menuState = 2) then
quaff(6)
else if (menuState = 3) then
wield(6);
end;
9: // 7 slot
begin
if (menuState = 1) then
drop(7)
else if (menuState = 2) then
quaff(7)
else if (menuState = 3) then
wield(7);
end;
10: // 8 slot
begin
if (menuState = 1) then
drop(8)
else if (menuState = 2) then
quaff(8)
else if (menuState = 3) then
wield(8);
end;
11: // 9 slot
begin
if (menuState = 1) then
drop(9)
else if (menuState = 2) then
quaff(9)
else if (menuState = 3) then
wield(9);
end;
12: quaff(10); // Quaff menu
13: wield(10); // Wear / Wield menu
end;
end;
procedure drop(dropItem: byte);
var
i, x: smallint;
begin
menuState := 1;
(* Clear the screen *)
inventoryScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
inventoryScreen.Canvas.FillRect(0, 0, inventoryScreen.Width, inventoryScreen.Height);
(* Draw title bar *)
inventoryScreen.Canvas.Brush.Color := globalutils.MESSAGEFADE6;
inventoryScreen.Canvas.Rectangle(50, 40, 785, 80);
(* Draw title *)
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.Font.Size := 12;
inventoryScreen.Canvas.TextOut(100, 50, 'Select item to drop');
inventoryScreen.Canvas.Font.Size := 10;
(* List inventory *)
x := 90; // x is position of each new line
for i := 0 to 9 do
begin
x := x + 20;
if (inventory[i].Name = 'Empty') or (inventory[i].equipped = True) then
dimSlots(i, x)
else
highlightSlots(i, x);
end;
(* Bottom menu *)
bottomMenu(1);
if (dropItem <> 10) then
begin
if (inventory[dropItem].Name <> 'Empty') and
(inventory[dropItem].equipped <> True) then
begin { TODO : First search for a space in the itemList that has the onMap flag set to false and use that slot }
(* Create a new entry in item list and copy item description *)
Inc(items.itemAmount);
items.listLength := length(items.itemList);
SetLength(items.itemList, items.listLength + 1);
with items.itemList[items.listLength] do
begin
itemID := items.listLength;
itemName := inventory[dropItem].Name;
itemDescription := inventory[dropItem].description;
itemType := inventory[dropItem].itemType;
glyph := inventory[dropItem].glyph;
inView := True;
posX := entities.entityList[0].posX;
posY := entities.entityList[0].posY;
onMap := True;
discovered := True;
end;
ui.displayMessage('You drop the ' + inventory[dropItem].Name);
Inc(playerTurn);
(* Remove from inventory *)
inventory[dropItem].Name := 'Empty';
showInventory;
end;
end;
end;
procedure quaff(quaffItem: byte);
var
i, x: smallint;
begin
menuState := 2;
(* Clear the screen *)
inventoryScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
inventoryScreen.Canvas.FillRect(0, 0, inventoryScreen.Width, inventoryScreen.Height);
(* Draw title bar *)
inventoryScreen.Canvas.Brush.Color := globalutils.MESSAGEFADE6;
inventoryScreen.Canvas.Rectangle(50, 40, 785, 80);
(* Draw title *)
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.Font.Size := 12;
inventoryScreen.Canvas.TextOut(100, 50, 'Select item to drink');
inventoryScreen.Canvas.Font.Size := 10;
(* List inventory *)
x := 90; // x is position of each new line
for i := 0 to 9 do
begin
x := x + 20;
if (inventory[i].Name = 'Empty') or (inventory[i].itemType <> 'drink') then
// dimSlots(i, x)
else
highlightSlots(i, x);
end;
(* Bottom menu *)
bottomMenu(1);
if (quaffItem <> 10) then
begin
if (inventory[quaffItem].Name <> 'Empty') and
(inventory[quaffItem].itemType = 'drink') then
begin
ui.writeBufferedMessages;
ui.bufferMessage('You quaff the ' + inventory[quaffItem].Name);
items.lookupUse(inventory[quaffItem].useID, False);
Inc(playerTurn);
(* Remove from inventory *)
inventory[quaffItem].Name := 'Empty';
showInventory;
end;
end;
end;
procedure wield(wieldItem: byte);
var
i, x: smallint;
begin
menuState := 3;
(* Clear the screen *)
inventoryScreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR;
inventoryScreen.Canvas.FillRect(0, 0, inventoryScreen.Width, inventoryScreen.Height);
(* Draw title bar *)
inventoryScreen.Canvas.Brush.Color := globalutils.MESSAGEFADE6;
inventoryScreen.Canvas.Rectangle(50, 40, 785, 80);
(* Draw title *)
inventoryScreen.Canvas.Font.Color := UITEXTCOLOUR;
inventoryScreen.Canvas.Brush.Style := bsClear;
inventoryScreen.Canvas.Font.Size := 12;
inventoryScreen.Canvas.TextOut(100, 50, 'Select item to wear / wield');
inventoryScreen.Canvas.Font.Size := 10;
(* List inventory *)
x := 90; // x is position of each new line
for i := 0 to 9 do
begin
x := x + 20;
if (inventory[i].Name = 'Empty') or (inventory[i].itemType = 'drink')then
// dimSlots(i, x)
else
highlightSlots(i, x);
end;
(* Bottom menu *)
bottomMenu(1);
if (wieldItem <> 10) then
begin
if (inventory[wieldItem].Name <> 'Empty') then
begin
(* If the item is an unequipped weapon, and the player already has a weapon equipped
prompt the player to unequip their weapon first *)
if (inventory[wieldItem].equipped = False) and
(inventory[wieldItem].itemType = 'weapon') and
(entityList[0].weaponEquipped = True) then
begin
showHint('You must first unequip the weapon you already hold');
end
(* If the item is unworn armour, and the player is already wearing armour
prompt the player to unequip their armour first *)
else if (inventory[wieldItem].equipped = False) and
(inventory[wieldItem].itemType = 'armour') and
(entityList[0].armourEquipped = True) then
begin
showHint('You must first remove the armour you already wear');
end
(* Check whether the item is already equipped or not *)
else if (inventory[wieldItem].equipped = False) then
begin
ui.writeBufferedMessages;
if (inventory[wieldItem].itemType = 'weapon') then
ui.bufferMessage('You equip the ' + inventory[wieldItem].Name)
else
ui.bufferMessage('You put on the ' + inventory[wieldItem].Name);
items.lookupUse(inventory[wieldItem].useID, False);
inventory[wieldItem].equipped := True;
(* Add equipped suffix *)
inventory[wieldItem].description :=
inventory[wieldItem].description + ' [equipped]';
Inc(playerTurn);
showInventory;
end
else
begin
ui.writeBufferedMessages;
if (inventory[wieldItem].itemType = 'weapon') then
ui.bufferMessage('You unequip the ' + inventory[wieldItem].Name)
else
ui.bufferMessage('You take off the ' + inventory[wieldItem].Name);
items.lookupUse(inventory[wieldItem].useID, True);
inventory[wieldItem].equipped := False;
(* Remove equipped suffix *)
SetLength(inventory[wieldItem].description,
Length(inventory[wieldItem].description) - 11);
Inc(playerTurn);
showInventory;
end;
end;
end;
end;
end.
|
unit TestAccounts;
interface
uses
Generics.Collections
, DelphiSpec.StepDefinitions;
type
TAccountsTestContext = class(TStepDefinitions)
protected type
TUserInfo = class
public
Name: string;
Password: string;
Id: Integer;
end;
protected
FName, FPassword: string;
FUsers: TObjectList<TUserInfo>;
FAccessGranted: Boolean;
public
procedure SetUp; override;
procedure TearDown; override;
end;
implementation
uses
System.SysUtils
, DelphiSpec.Core
, DelphiSpec.Assert
, DelphiSpec.Parser
, DelphiSpec.Attributes;
{$I TestAccounts.inc}
{ TAccountsTestContext }
procedure TAccountsTestContext.SetUp;
begin
FUsers := TObjectList<TUserInfo>.Create;
FAccessGranted := False;
end;
procedure TAccountsTestContext.TearDown;
begin
FreeAndNil(FUsers);
end;
{ TAccountsTest }
procedure TAccountsTest.Given_my_name_is_value(const value: String);
begin
FName := value;
end;
procedure TAccountsTest.Given_my_password_is_value(const value: String);
begin
FPassword := value;
end;
procedure TAccountsTest.Given_users_exist(const data: TArray<t_data>);
var
I: Integer;
LUserInfo: TUserInfo;
begin
for I := Low(data) to High(data) do
begin
LUserInfo := TUserInfo.Create;
with data[I] do
begin
LUserInfo.Name := name;
LUserInfo.Password := password;
LUserInfo.Id := id;
end;
FUsers.Add(LUserInfo);
end;
end;
procedure TAccountsTest.Given_user_value_has_been_removed(const value: String);
var
I: Integer;
begin
for I := 0 to FUsers.Count - 1 do
if FUsers[I].Name = value then
begin
FUsers.Delete(I);
Break;
end;
end;
procedure TAccountsTest.Then_access_denied;
begin
Assert.IsFalse(FAccessGranted, 'Access granted');
end;
procedure TAccountsTest.Then_I_have_access_to_private_messages;
begin
Assert.IsTrue(FAccessGranted, 'Access denied');
end;
procedure TAccountsTest.When_I_login;
var
I: Integer;
begin
for I := 0 to FUsers.Count - 1 do
if (FUsers[I].Name = FName) and (FUsers[I].Password = FPassword) then
begin
FAccessGranted := True;
Break;
end;
end;
initialization
RegisterAccountsTest;
end.
|
Program PaperFiles (Input,Output);
{****************************************************************************
Author: Scott Janousek
Username: ScottJ
Student ID: 4361106
Program Assignment 2
Instructor: Cris Pedregal MWF 1:25
Due Date: March 8, 1993
Program Description:
This program implements an ADT called PaperPiles. This Data Structure uses
a stack to keep track of four separate "Piles" of papers upon a desk. These
are labeled Urgent (Read ASAP), NotUrgent (Read when you have the time),
File (store papers into a filing cabinet), and Trash (Dispose of papers).
The papers are stored by their titles (strings which will be no more than 16
characters in length). PaperPiles is stored in DMA but is an array based stack.
The following commands can be used with these piles:
CREATEPILES: creates four empty piles. Creates the desk.
MOVE: move the top paper of Pile1 to Pile2.
TRANSFER: move all papers from Pile1 to Pile2.
SWITCH: Put papers of Pile1 into Pile2 and viceversa.
CLEANUP: Delete all papers in the Trash pile. Make room on desk.
ADDPaper: make top paper from Pile and add a Paper.
PRINTPile: print all papers of a Pile to the screen.
****************************************************************************}
CONST
MaxStack = 25;
TYPE
Papertitle = packed array [1..16] of char;
Piletypes = (Urgent, NotUrgent, Files, Trash, Switch); {* Enumerated Piles *}
NodePtrType = ^Stacktype; {* Pointer to PaperPiles *}
Piles = NodePtrType; {* Pointer to Node *}
PaperPiles = ARRAY [Piletypes] of Piles; {* PaperPiles ADT type *}
Stacktype = RECORD
Title : ARRAY [1 .. MaxStack] OF Papertitle; {* Array of Papers *}
Top : 0 .. Maxstack; {* Top of Stack *}
END; {* Stacktype *}
{***************************************************************************}
VAR
P : PaperPiles; {* PaperPiles ADT *}
Paper : Papertitle; {* Papers name *}
{***************************************************************************}
PROCEDURE CreatePiles (VAR P : PaperPiles);
{* Initializes Four Piles to their empty states, by allocating *}
{* the space in memory needed from each of them *}
BEGIN {* Creates the Piles *}
writeln('DESK CREATED: Piles are empty.');
writeln;
New (P [Urgent]); New (P [NotUrgent]);
New (P [Files]); New (P [Trash]);
END; {* Creates the Piles *}
{***************************************************************************}
PROCEDURE Pilename (VAR Pile: Piletypes);
{* This procedure will determine which Pile should be printed for program *}
{* operations. These will include URGENT, NOTURGENT, TRASH, and FILES *}
{* This is done through a case statement of the enumerated type of Pile. *}
VAR
whichpile : Piletypes;
BEGIN {* Determine the name of a Pile *}
whichpile:= Pile;
CASE whichpile OF {* Case of Pile *}
Urgent : write ('URGENT');
NotUrgent : write ('NOTURGENT'); {* Piles *}
Files : write ('FILES');
Trash : write ('TRASH');
END
END; {* Determine the name of a Pile *}
{***************************************************************************}
PROCEDURE Cleanup (VAR P : PaperPiles; Pile : Piletypes);
{* Destroys all Papers in pile, leaving a Pile empty. *}
{* This "cleans" the desk so more piles can be added. *}
BEGIN {* Cleanup Desk *}
write('CLEANUP: Pile ');
Pilename (Pile); writeln(' is cleaned up.');
writeln;
Dispose (P [Pile]);
New (P [Pile]);
P [Pile]^.Top:= 0;
END; {* Cleanup Desk *}
{***************************************************************************}
FUNCTION EmptyPile (Pile : Piletypes) : Boolean;
{* Returns True if Pile is empty; returns False otherwise. *}
BEGIN {* EmptyPile *}
EmptyPile := P [Pile]^.top = 0
END; {* EmptyPile *}
{***************************************************************************}
FUNCTION FullPile (Pile : Piletypes) : Boolean;
{* Returns True if Stack is full; returns False otherwise. *}
BEGIN {* FullStack *}
FullPile := P [Pile]^.top = MaxStack
END; {* FullStack *}
{***************************************************************************}
PROCEDURE PUSHpaper (VAR P : PaperPiles; Pile : Piletypes;
NewTitle : PaperTitle);
{* Pushes NewElement to the top of a Pile. Assumes that the *}
{* stack is not full. *}
BEGIN {* Push Paper unto top of a Pile *}
P [Pile]^.Top := P [Pile]^.Top + 1;
P [Pile]^.Title [P [Pile]^.Top] := NewTitle;
END; {* Push Paper unto top of a Pile *}
{***************************************************************************}
PROCEDURE ADDPaper (VAR P : PaperPiles; Pile : Piletypes;
NewTitle : Papertitle);
{* Adds a paper to the Top of Pile. If the Pile is FULL then *}
{* no paper can be added to that Pile. *}
BEGIN {* Add a paper to a pile *}
IF FullPile (Pile) THEN
BEGIN
writeln('Sorry. Pile ');
Pilename (Pile); writeln(' is FULL.');
writeln;
END
ELSE
BEGIN {* Push a paper on *}
PUSHpaper (P, Pile, NewTitle);
write ('ADD Paper : Paper ', NewTitle,' has been added to Pile ');
Pilename (Pile); writeln;
END {* Push a paper on *}
END; {* Add a paper to a pile *}
{***************************************************************************}
PROCEDURE POPpaper (VAR P : PaperPiles; Pile : Piletypes;
VAR PoppedElement : PaperTitle);
{* Removes the top element from a Pile and returns its *}
{* value in PoppedElement. Assumes that the a pile is *}
{* not empty. *}
BEGIN {* Pop *}
PoppedElement := P [Pile]^.Title [P [Pile]^.Top];
P [Pile]^.Top := P [Pile]^.Top - 1;
END; {* Pop *}
{***************************************************************************}
PROCEDURE REMOVEpaper (VAR P : PaperPiles; Pile : Piletypes;
PoppedElement : PaperTitle);
{* Removes the Paper from the Top of a Pile. *}
BEGIN {* Remove a paper from Pile *}
IF EmptyPile (Pile) THEN
BEGIN {* Empty Pile Error *}
write('REMOVE: Pile ');
Pilename (Pile); writeln(' is EMPTY. No Papers can be removed.');
writeln;
END
ELSE
BEGIN {* Remove Paper *}
POPpaper (P, Pile, Paper);
write('REMOVE: Paper ', Paper, ' removed from Pile ');
Pilename (Pile); writeln;
writeln;
END {* Remove Paper *}
END; {* Remove a paper from Pile *}
{***************************************************************************}
PROCEDURE MOVEPaper (VAR P : PaperPiles; Pile1, Pile2: Piletypes);
{* Moves the Paper on top of one Pile and adds it to the top of *}
{* another Pile. If the Pile is empty then no move is made. *}
VAR
PopElement : Papertitle;
BEGIN {* Move a Paper *}
IF EmptyPile (Pile1) THEN
BEGIN
write('MOVE: Pile ');
Pilename (Pile1);
write (' is EMPTY. Cannot preform the move Paper to Pile ');
Pilename (Pile2); writeln;
writeln
END
ELSE IF FullPile (Pile2) THEN
BEGIN
writeln ('MOVE: Pile is FULL. Cannot move Paper to Pile ');
Pilename (Pile2); writeln;
writeln
END
ELSE {* Move Top paper to the other Pile *}
BEGIN
PopElement := P [Pile1]^.Title [ P [Pile1]^.Top];
P [Pile1]^.Top := P [Pile1]^.Top - 1;
P [Pile2]^.Top := P [Pile2]^.Top + 1;
P [Pile2]^.Title [ P [Pile2]^.Top]:= PopElement;
write('MOVE Paper: ', PopElement, ' moved from Pile ');
Pilename (Pile1); write (' to '); Pilename (Pile2);
writeln; writeln;
END;
END; {* Move a Paper *}
{***************************************************************************}
PROCEDURE TransferPiles (VAR P : PaperPiles; Pile1, Pile2: Piletypes);
{* Takes the contents of one Pile and pushes them into another *}
{* Pile. The papers of the first paper are then erased, the Transfer *}
{* will contain all values for both of the Piles. Error conditions *}
{* include Empty and Full states of Piles. *}
VAR
Top: integer;
TempPile : PaperPiles;
BEGIN {* Transfer Piles *}
IF EmptyPile (Pile1) THEN
BEGIN
write('TRANSFER: Pile ');
Pilename (Pile1); writeln (' is EMPTY.');
writeln;
END
ELSE IF FullPile(Pile2) THEN
BEGIN
write('TRANSFER: Pile ');
Pilename (Pile2); writeln(' is FULL.');
writeln;
END
ELSE (* Transfer Piles *}
BEGIN
write('TRANSFER: All papers moved from Pile '); Pilename (Pile1);
write(' into Pile '); Pilename (Pile2); writeln;
writeln;
New (TempPile [switch]);
TempPile [Switch]^.Top := 0;
WHILE P [Pile1]^.Top > 0 DO {* Transfer by popping papers *}
BEGIN {* Transfer the Piles *}
POPpaper (P, Pile1, Paper);
PUSHPaper (TempPile, Switch, Paper);
END; {* Transfer the Piles *}
WHILE TempPile [Switch]^.Top > 0 DO {* Transfer back to proper Pile *}
BEGIN
POPpaper (TempPile, Switch, Paper);
PUSHpaper (P, Pile2, Paper);
END;
END; {* Transfer Piles *}
END; {* Transfer Piles *}
{***************************************************************************}
PROCEDURE SwitchPiles (VAR P : PaperPiles; Pile1, Pile2 : Piletypes);
{* Two Piles can be "switched" by the swopping the pointers of the *}
{* Piles. These memory locations are then switched and the first *}
{* Pile becomes the second Pile, and vice versa. A temporary Pile *}
{* is implemented to accomplish the switch. *}
VAR
TempPile : PaperPiles;
BEGIN {* Switch the Piles *}
IF EmptyPile (Pile1) AND EmptyPile (Pile2) THEN
BEGIN {* Empty Pile *}
write('SWITCH: Pile '); Pilename (Pile1);
write(' and Pile '); Pilename (Pile2);
writeln(' are both Empty. No Switch made. ');
writeln;
END {* Empty Pile *}
ELSE
BEGIN {* Switch *}
TempPile [Switch] := P [Pile1]; {* Switch Pointers *}
P [Pile1] := P [Pile2];
P [Pile2] := TempPile [Switch];
write('SWITCH: Pile '); Pilename (Pile1);
write(' switched with Pile '); Pilename (Pile2);
writeln; writeln;
END; {* Switch *}
END; {* Switch the Piles *}
{***************************************************************************}
PROCEDURE PrintPile (P : PaperPiles; Pile : Piletypes);
{* Prints the Papers held within a Pile. In order of entry. *}
{* one paper at a time until the Top of that Pile is reached *}
VAR
Top : integer;
BEGIN {* Print the contents of a Pile *}
IF EmptyPile (pile) THEN
BEGIN {* Empty Pile *}
write('PRINTPILE: Pile '); Pilename (Pile);
writeln(' is empty.');
writeln;
END {* Empty Pile *}
ELSE
BEGIN {* Print the Pile *}
writeln;
write('PRINTPILE : Pile ');
Pilename (Pile); writeln;
writeln('----------------------------');
Top:= 0;
Top := P [Pile]^.Top;
BEGIN {* Print papers *}
WHILE Top > 0 DO
BEGIN {* Each Element in stack *}
writeln ('Paper ', ' : ', P [Pile]^.Title [ Top ]);
Top := Top - 1;
END; {* Each Element in stack *}
END; {* Print papers *}
writeln('----------------------------');
writeln;
END; {* Print the Pile *}
END; {* Print the contents of a Pile *}
{***************************************************************************}
PROCEDURE TestDriver (VAR P : PaperPiles);
{* This procedure tests all the cases for the program *}
BEGIN {* Test Driver *}
CreatePiles (P); {* Creates the Piles *}
ADDpaper (P, Urgent, 'Urgent1');
ADDpaper (P, Urgent, 'Urgent2'); {* Papers are added to Desk *}
ADDpaper (P, Urgent, 'Urgent3');
ADDpaper (P, Urgent, 'Urgent4');
ADDpaper (P, NotUrgent, 'NotUrgent1');
ADDpaper (P, NotUrgent, 'NotUrgent2');
ADDpaper (P, NotUrgent, 'NotUrgent3');
ADDpaper (P, NotUrgent, 'NotUrgent4');
ADDpaper (P, NotUrgent, 'NotUrgent5');
ADDpaper (P, Files, 'Files1');
ADDpaper (P, Files, 'Files2');
ADDpaper (P, Trash, 'Trash1');
PrintPile (P, Urgent); {* Print Pile Urgent *}
Printpile (P, NotUrgent);
PrintPile (P, Files);
PrintPile (P, Trash);
SwitchPiles (P, Urgent, NotUrgent); (* Implement the Switch Piles *}
PrintPile (P, Urgent);
SwitchPiles (P, Urgent, NotUrgent);
RemovePaper (P, Trash, Paper); {* Remove a paper from Trash *}
RemovePaper (P, Trash, Paper);
MovePaper (P, NotUrgent, Files); {* Move a paper from Trash to Files *}
PrintPile (P, NotUrgent);
Printpile (P, Files);
MovePaper (P, Trash, NotUrgent);
MovePaper (P, Files, Trash);
TransferPiles (P, Urgent, NotUrgent); {* Transfer from Urgent to NotUrgent *}
PrintPile (P, Urgent);
PrintPile (P, NotUrgent);
PrintPile (P, Files);
PrintPile (P, Trash);
MovePaper (P, Trash, Urgent); {* Move Paper from Trash to Urgent *}
TransferPiles (P, Trash, Files);
TransferPiles (P, Files, Trash);
SwitchPiles (P, Files, Urgent); {* A switch of Files and Urgent *}
PrintPile (P, Files);
PrintPile (P, Urgent);
PrintPile (P, NotUrgent);
PrintPile (P, Files);
PrintPile (P, Trash);
Cleanup (P, Trash); {* Cleans Trash Up *}
Cleanup (P, Files);
Cleanup (P, Urgent);
Cleanup (P, NotUrgent);
PrintPile (P, Trash);
END; {* Test Driver *}
{***************************************************************************}
BEGIN {* Main Program *}
writeln; writeln('Welcome to program PAPERPILES: ADT');
writeln('Written by: Scott Janousek'); writeln;
TestDriver (P); {* Run the Test Cases for the Program *}
writeln('END PROGRAM : Thanks for using this program.');
writeln; writeln ('Good Bye');
writeln;
END. {* Main Program *}
|
unit CardLTE;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TLTECard = class(TFrame)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
lbTextTitle: TLabel;
lbTextValue: TLabel;
Label3: TLabel;
Shape1: TShape;
Shape2: TShape;
Image1: TImage;
private
FTextTitle: String;
FTextValue: Currency;
FProgressValue: Integer;
FBackgroundPanel1: TColor;
FBackgroundPanel2: TColor;
FIcoImage: TPicture;
procedure SetTextTitle(const Value: String);
procedure SetTextValue(const Value: Currency);
procedure SetProgressValue(const Value: Integer);
procedure SetBackgroundPanel1(const Value: TColor);
procedure SetBackgroundPanel2(const Value: TColor);
procedure SetIcoImage(const Value: TPicture);
{ Private declarations }
public
{ Public declarations }
published
property IcoImage : TPicture read FIcoImage write SetIcoImage;
property TextTitle : String read FTextTitle write SetTextTitle;
property TextValue : Currency read FTextValue write SetTextValue;
property ProgressValue : Integer read FProgressValue write SetProgressValue;
property BackgroundPanel1 : TColor read FBackgroundPanel1 write SetBackgroundPanel1;
property BackgroundPanel2 : TColor read FBackgroundPanel2 write SetBackgroundPanel2;
end;
procedure Register;
implementation
{$R *.dfm}
procedure Register;
begin
RegisterComponents('LTE Components', [TLTECard]);
end;
{ TLTECard }
procedure TLTECard.SetBackgroundPanel1(const Value: TColor);
begin
FBackgroundPanel1 := Value;
Panel2.Color := FBackgroundPanel1;
end;
procedure TLTECard.SetBackgroundPanel2(const Value: TColor);
begin
FBackgroundPanel2 := Value;
Panel3.Color := FBackgroundPanel2;
end;
procedure TLTECard.SetIcoImage(const Value: TPicture);
begin
try
FIcoImage := Value;
Image1.Picture.Assign(FIcoImage);
except
on e:Exception do
begin
raise Exception.Create(e.Message);
Image1.Picture := nil;
end;
end;
end;
procedure TLTECard.SetProgressValue(const Value: Integer);
begin
FProgressValue := Value;
Shape2.Width := Round(Value * (Shape1.Width / 100));
end;
procedure TLTECard.SetTextTitle(const Value: String);
begin
FTextTitle := Value;
lbTextTitle.Caption := FTextTitle;
end;
procedure TLTECard.SetTextValue(const Value: Currency);
begin
FTextValue := Value;
lbTextValue.Caption := FormatCurr('#,##0.00', FTextValue);
end;
end.
|
unit uFaceAnalyzer;
interface
uses
Winapi.Windows,
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Imaging.pngImage,
Dmitry.Utils.System,
Dmitry.Graphics.Types,
OpenCV.Core,
OpenCV.ImgProc,
OpenCV.Utils,
uMemory,
uDBEntities,
u2DUtils,
uBitmapUtils,
uResources,
uFaceDetection;
{
Core_c,
Core.types_c,
imgproc_c,
imgproc.types_c
}
type
TFaceScoreResults = class
private
FFace: TFaceDetectionResultItem;
FMouth: TFaceDetectionResultItem;
FLeftEye: TFaceDetectionResultItem;
FNose: TFaceDetectionResultItem;
FRightEye: TFaceDetectionResultItem;
FFaceImage: TBitmap;
function GetTotalScore: Byte;
function GetHasBothEyes: Boolean;
function GetEyesAngle: Double;
function GetHasSingleEye: Boolean;
function GetHasMouth: Boolean;
function GetHasNose: Boolean;
function GetMouseNouseAngle: Double;
function GetEyeMouthAngle: Double;
function GetFaceAngle: Double;
public
constructor Create(FaceImage: pIplImage; AFace, ALeftEye, ARightEye, ANose, AMouth: TFaceDetectionResultItem);
destructor Destroy; override;
procedure GenerateSample(Bitmap: TBitmap; Width, Height: Integer);
property FaceImage: TBitmap read FFaceImage;
property Face: TFaceDetectionResultItem read FFace;
property LeftEye: TFaceDetectionResultItem read FLeftEye;
property RightEye: TFaceDetectionResultItem read FRightEye;
property Nose: TFaceDetectionResultItem read FNose;
property Mouth: TFaceDetectionResultItem read FMouth;
property TotalScore: Byte read GetTotalScore;
property HasBothEyes: Boolean read GetHasBothEyes;
property HasSingleEye: Boolean read GetHasSingleEye;
property HasMouth: Boolean read GetHasMouth;
property HasNose: Boolean read GetHasNose;
//all angles in Rad
property FaceAngle: Double read GetFaceAngle;
property EyesAngle: Double read GetEyesAngle;
//should be about 25% (statistics) - canculate difference
property EyeMouthAngle: Double read GetEyeMouthAngle;
property MouseNouseAngle: Double read GetMouseNouseAngle;
end;
function ProcessFaceAreaOnImage(MI: TMediaItem; Bitmap: TBitmap; Area: TPersonArea; Detector: TFaceDetectionManager; MinScore: Byte): TFaceScoreResults;
function CalculateRectOnImage(Area: TPersonArea; ImageSize: TSize): TRect;
implementation
procedure TrimResultsToRect(Rect: TRect; Results: TFaceDetectionResult);
var
I: Integer;
begin
for I := Results.Count - 1 downto 0 do
begin
if not RectInRect(Rect, Results[I].Rect) then
Results.DeleteAt(I);
end;
end;
function ProcessFaceOnImage(FaceImage: PIplImage; Detector: TFaceDetectionManager): TFaceScoreResults;
var
I: Integer;
D, DMin, DMax: Double;
FaceRect, MouthRect, MouthRectShouldBe, EyeRect: TRect;
FaceItem, NoseRectItem, MouthRectItem, LeftEyeItem, RightEyeItem: TFaceDetectionResultItem;
FaceRects, NoseRects, MouthRects, EyeRects: TFaceDetectionResult;
function Distance(P1, P2: TPoint): Double;
begin
Result := Sqrt(Sqr(P1.X - P2.X) + Sqr(P1.Y - P2.Y));
end;
function FindEyeToCenterDistance(FaceAreaRect: TRect; Eye: TRect): double;
var
D: Double;
procedure ProcessPoint(P: TPoint);
begin
if PtInRect(FaceAreaRect, Eye.CenterPoint) then
begin
D := Distance(P, FaceAreaRect.CenterPoint);
if D < Result then
Result := D;
end;
end;
begin
Result := MaxDouble;
ProcessPoint(Eye.TopLeft);
ProcessPoint(Point(Eye.Top, Eye.Right));
ProcessPoint(Eye.BottomRight);
ProcessPoint(Point(Eye.Bottom, Eye.Left));
end;
begin
Result := nil;
NoseRectItem := nil;
MouthRectItem := nil;
LeftEyeItem := nil;
RightEyeItem := nil;
FaceRects := TFaceDetectionResult.Create;
NoseRects := TFaceDetectionResult.Create;
MouthRects := TFaceDetectionResult.Create;
EyeRects := TFaceDetectionResult.Create;
try
Detector.FacesDetection(FaceImage, 1, FaceRects, 'haarcascade_frontalface_alt.xml');
if (FaceRects.Count = 0) then
Exit;
FaceItem := FaceRects[0];
for I := 1 to FaceRects.Count - 1 do
begin
if (FaceRects[I].Width > FaceItem.Rect.Width) or (FaceRects[I].Height > FaceItem.Rect.Height) then
FaceItem := FaceRects[I];
end;
FaceRect := FaceItem.Rect;
Detector.FacesDetection(FaceImage, 1, NoseRects, 'haarcascade_mcs_nose.xml');
TrimResultsToRect(FaceRect, NoseRects);
if NoseRects.Count > 0 then
begin
//search for nose in the center
NoseRectItem := NoseRects[0];
DMin := Distance(FaceRect.CenterPoint, NoseRectItem.Rect.CenterPoint);
for I := 1 to NoseRects.Count - 1 do
begin
D := Distance(FaceRect.CenterPoint, NoseRects[I].Rect.CenterPoint);
if D < DMin then
begin
DMin := D;
NoseRectItem := NoseRects[I];
end;
end;
for I := NoseRects.Count - 1 downto 0 do
if NoseRects[I] <> NoseRectItem then
NoseRects.DeleteAt(I);
end;
Detector.FacesDetection(FaceImage, 1, MouthRects, 'haarcascade_mcs_mouth.xml');
MouthRect := Rect(FaceRect.Left, FaceRect.Top + FaceRect.Height div 2, FaceRect.Right, FaceRect.Bottom);
TrimResultsToRect(MouthRect, MouthRects);
//select mouth
if MouthRects.Count > 0 then
begin
MouthRectShouldBe := Rect(
FaceRect.Left + (FaceRect.Width * 2) div 5, FaceRect.Top + (FaceRect.Height * 5) div 7,
FaceRect.Left + (FaceRect.Width * 3) div 5, FaceRect.Top + (FaceRect.Height * 6) div 7);
MouthRectItem := MouthRects[0];
DMax := RectIntersectWithRectPercent(MouthRectShouldBe, MouthRectItem.Rect);
for I := 1 to MouthRects.Count - 1 do
begin
D := RectIntersectWithRectPercent(MouthRectShouldBe, MouthRects[I].Rect);
if D > DMax then
begin
DMax := D;
MouthRectItem := MouthRects[I];
end;
end;
for I := MouthRects.Count - 1 downto 0 do
if MouthRects[I] <> MouthRectItem then
MouthRects.DeleteAt(I);
end;
Detector.FacesDetection(FaceImage, 1, EyeRects, 'haarcascade_eye.xml');
EyeRect := Rect(FaceRect.Left, FaceRect.Top, FaceRect.Right, FaceRect.Top + Round((FaceRect.Height * 5.5) / 7));
TrimResultsToRect(EyeRect, EyeRects);
//remove eyes in nose
if NoseRectItem <> nil then
begin
for I := EyeRects.Count - 1 downto 0 do
if PtInRect(NoseRectItem.Rect, EyeRects[I].Rect.CenterPoint) then
EyeRects.DeleteAt(I);
end;
if EyeRects.Count > 0 then
begin
//left eye (actually right)
EyeRect := Rect(FaceRect.Left, FaceRect.Top, FaceRect.Left + FaceRect.Height div 2, FaceRect.Top + FaceRect.Height div 2);
DMin := MaxDouble;
for I := 0 to EyeRects.Count - 1 do
begin
D := FindEyeToCenterDistance(EyeRect, EyeRects[I].Rect);
if D < DMin then
begin
DMin := D;
LeftEyeItem := EyeRects[I];
end;
end;
//right eye (actually left)
EyeRect := Rect(FaceRect.Left + FaceRect.Width div 2, FaceRect.Top, FaceRect.Right, FaceRect.Top + FaceRect.Height div 2);
DMin := MaxDouble;
for I := 0 to EyeRects.Count - 1 do
begin
D := FindEyeToCenterDistance(EyeRect, EyeRects[I].Rect);
if D < DMin then
begin
DMin := D;
RightEyeItem := EyeRects[I];
end;
end;
for I := EyeRects.Count - 1 downto 0 do
if (EyeRects[I] <> RightEyeItem) and (EyeRects[I] <> LeftEyeItem) then
EyeRects.DeleteAt(I);
end;
Result := TFaceScoreResults.Create(FaceImage, FaceItem, LeftEyeItem, RightEyeItem, NoseRectItem, MouthRectItem);
finally
F(FaceRects);
F(NoseRects);
F(MouthRects);
F(EyeRects);
end;
end;
procedure ApplyMask(Image, Mask: TBitmap);
var
SmallMask: TBitmap;
I, J: Integer;
CvImage: pIplImage;
PO, PM: PARGB;
W, W1: Byte;
begin
SmallMask := TBitmap.Create;
try
SmallMask.PixelFormat := pf24bit;
DoResize(Image.Width, Image.Height, Mask, SmallMask);
CvImage := cvCreateImage(CvSize(Image.Width, Image.Height), IPL_DEPTH_8U, 3);
try
Bitmap2IplImage(CvImage, Image);
for I := 0 to Image.Height - 1 do
begin
PO := Image.ScanLine[I];
PM := SmallMask.ScanLine[I];
for J := 0 to Image.Width - 1 do
begin
W := PM[J].B;
W1 := 255 - W;
PO[J].R := (PO[J].R * W1 + 255 * W + $7F) div $FF;
PO[J].G := (PO[J].G * W1 + 255 * W + $7F) div $FF;
PO[J].B := (PO[J].B * W1 + 255 * W + $7F) div $FF;
end;
end;
finally
cvReleaseImage(CvImage);
end;
finally
F(SmallMask);
end;
end;
function CalculateRectOnImage(Area: TPersonArea; ImageSize: TSize): TRect;
var
P1, P2: TPoint;
S: TSize;
begin
Result := Rect(Area.X, Area.Y, Area.X + Area.Width, Area.Y + Area.Height);
P1 := Result.TopLeft;
P2 := Result.BottomRight;
S.cx := Area.FullWidth;
S.cy := Area.FullHeight;
P1 := PxMultiply(P1, S, ImageSize);
P2 := PxMultiply(P2, S, ImageSize);
Result := Rect(P1, P2);
end;
function ClipRectToRect(RectToClip, Rect: TRect): TRect;
begin
if RectToClip.Top < Rect.Top then
RectToClip.Top := Rect.Top;
if RectToClip.Left < Rect.Left then
RectToClip.Left := Rect.Left;
if RectToClip.Right > Rect.Right then
RectToClip.Right := Rect.Right;
if RectToClip.Bottom > Rect.Bottom then
RectToClip.Bottom := Rect.Bottom;
Result := RectToClip;
end;
procedure DrawDetectRect(Bitmap: TBitmap; Rect: TFaceDetectionResultItem; Color: TColor);
begin
if Rect = nil then
Exit;
Bitmap.Canvas.Pen.Color := Color;
Bitmap.Canvas.Brush.Style := bsClear;
Bitmap.Canvas.Rectangle(Rect.Rect);
end;
procedure DrawDetectRects(Bitmap: TBitmap; Rects: TFaceDetectionResult; Color: TColor);
var
I: Integer;
begin
for I := 0 to Rects.Count - 1 do
DrawDetectRect(Bitmap, Rects[I], Color);
end;
procedure DrawDetectRectFace(Bitmap: TBitmap; Rect: TFaceDetectionResultItem; Color: TColor);
const
W = 5;
H = 7;
var
I: Integer;
R: TRect;
begin
R := Rect.Rect;
Bitmap.Canvas.Pen.Color := Color;
Bitmap.Canvas.Brush.Style := bsClear;
Bitmap.Canvas.Rectangle(R);
for I := 1 to W - 1 do
begin
Bitmap.Canvas.MoveTo(R.Left + (I * R.Width) div W, R.Top);
Bitmap.Canvas.LineTo(R.Left + (I * R.Width) div W, R.Height + R.Top);
end;
for I := 1 to H - 1 do
begin
Bitmap.Canvas.MoveTo(R.Left, (I * R.Height) div H + R.Top);
Bitmap.Canvas.LineTo(R.Left + R.Width, (I * R.Height) div H + R.Top);
end;
Bitmap.Canvas.MoveTo(R.Left + (R.Width) div 2, R.Top);
Bitmap.Canvas.LineTo(R.Left + (R.Width) div 2, R.Height + R.Top);
Bitmap.Canvas.MoveTo(R.Left, (R.Height) div 2 + R.Top);
Bitmap.Canvas.LineTo(R.Left + R.Width, (R.Height) div 2 + R.Top);
end;
procedure DrawDetectRectsFace(Bitmap: TBitmap; Rects: TFaceDetectionResult; Color: TColor);
var
I: Integer;
begin
for I := 0 to Rects.Count - 1 do
DrawDetectRectFace(Bitmap, Rects[I], Color);
end;
procedure Swap(var P1, P2: Pointer);
var
X: Pointer;
begin
X := P1;
P1 := P2;
P2 := X;
end;
function ProcessFaceAreaOnImage(MI: TMediaItem; Bitmap: TBitmap; Area: TPersonArea; Detector: TFaceDetectionManager; MinScore: Byte): TFaceScoreResults;
const
LoadFaceCf = 1.5;
var
ImageRect, R: TRect;
FaceBitmap: TBitmap;
FaceImage: pIplImage;
ImageSize: TSize;
FaceSize: TCvSize;
DetectionResult, DR: TFaceScoreResults;
Angle: Double;
RotMat: pCvMat;
RotCenter: TcvPoint2D32f;
Scale: Double;
RotatedImage: pIplImage;
//FileName: string;
procedure DrawDetectionDebugInfo(Bitmap: TBitmap; DetectionInfo: TFaceScoreResults);
begin
DrawTransparentColor(Bitmap, clWhite, 0, 0, Bitmap.Width, Bitmap.Height, 127);
DrawDetectRectFace(Bitmap, DetectionInfo.Face, clRed);
DrawDetectRect(Bitmap, DetectionInfo.Nose, clWhite);
DrawDetectRect(Bitmap, DetectionInfo.Mouth, clGreen);
DrawDetectRect(Bitmap, DetectionInfo.LeftEye, clBlue);
DrawDetectRect(Bitmap, DetectionInfo.RightEye, clBlue);
Bitmap.Canvas.TextOut(10, 10, IntToStr(DetectionInfo.TotalScore));
end;
begin
Result := nil;
FaceBitmap := TBitmap.Create;
try
FaceBitmap.PixelFormat := pf24bit;
ImageSize.Width := Bitmap.Width;
ImageSize.Height := Bitmap.Height;
ImageRect := Rect(0, 0, ImageSize.Width, ImageSize.Height);
R := CalculateRectOnImage(Area, ImageSize);
InflateRect(R, Round(R.Width / (2 * LoadFaceCf)), Round(R.Height / (2 * LoadFaceCf)));
R := ClipRectToRect(R, ImageRect);
FaceBitmap.SetSize(R.Width, R.Height);
DrawImageExRect(FaceBitmap, Bitmap, R.Left, R.Top, R.Width, R.Height, 0, 0);
KeepProportions(FaceBitmap, 128, 128);
FaceSize.width := FaceBitmap.Width;
FaceSize.height := FaceBitmap.Height;
FaceImage := cvCreateImage(FaceSize, IPL_DEPTH_8U, 3);
try
Bitmap2IplImage(FaceImage, FaceBitmap);
DetectionResult := ProcessFaceOnImage(FaceImage, Detector);
try
if DetectionResult = nil then
Exit;
if (MinScore > 0) and (DetectionResult.TotalScore < MinScore) then
Exit;
//try to rotate
Angle := DetectionResult.FaceAngle;
if Angle <> 0 then
begin
// Rotate image
RotMat := cvCreateMat(2, 3, CV_32FC1);
// Rotate with base in center
RotCenter.x := FaceImage.width div 2;
RotCenter.y := FaceImage.height div 2;
Scale := 1;
cv2DRotationMatrix(RotCenter, Angle * 180 / PI, Scale, RotMat);
RotatedImage := cvCreateImage(cvSize(FaceImage.width, FaceImage.height), FaceImage.depth, FaceImage.nChannels);
try
// Apply rotation
cvWarpAffine(FaceImage, RotatedImage, RotMat, CV_INTER_LINEAR or CV_WARP_FILL_OUTLIERS, cvScalarAll(0));
DR := ProcessFaceOnImage(RotatedImage, Detector);
try
if (DR <> nil) and (DR.TotalScore > DetectionResult.TotalScore) then
begin
Swap(Pointer(DetectionResult), Pointer(DR));
IplImage2Bitmap(RotatedImage, FaceBitmap);
end;
finally
F(DR);
end;
finally
cvReleaseImage(RotatedImage);
end;
end;
(*
DrawDetectionDebugInfo(FaceBitmap, DetectionResult);
FaceBitmap.Canvas.TextOut(10, 30, FloatToStrEx(DetectionResult.FaceAngle * 180 / PI, 2));
FileName := FormatEx('d:\Faces\{0}', [Area.PersonID]);
CreateDirA(FileName);
FileName := FileName + FormatEx('\Face_{0}_{1}_{2}_dbg.bmp', [DetectionResult.TotalScore, Area.ID, Area.ImageID]);
FaceBitmap.SaveToFile(FileName);
*)
Swap(Pointer(Result), Pointer(DetectionResult));
finally
F(DetectionResult);
end;
finally
cvReleaseImage(FaceImage);
end;
finally
F(FaceBitmap);
end;
end;
{ TFaceScoreResults }
constructor TFaceScoreResults.Create(FaceImage: pIplImage; AFace, ALeftEye, ARightEye, ANose,
AMouth: TFaceDetectionResultItem);
var
R: TRect;
B: TBitmap;
begin
FFace := AFace.Copy;
B := TBitmap.Create;
try
B.PixelFormat := pf24bit;
B.SetSize(FaceImage.width, FaceImage.height);
IplImage2Bitmap(FaceImage, B);
FFaceImage := TBitmap.Create;
FFaceImage.PixelFormat := pf24Bit;
FFaceImage.SetSize(AFace.Width, AFace.Height);
R := FFace.Rect;
DrawImageExRect(FFaceImage, B, R.Left, R.Top, R.Width, R.Height, 0, 0);
finally
F(B);
end;
FLeftEye := nil;
FRightEye := nil;
FNose := nil;
FMouth := nil;
if ALeftEye <> nil then
FLeftEye := ALeftEye.Copy;
if ARightEye <> nil then
FRightEye := ARightEye.Copy;
if ANose <> nil then
FNose := ANose.Copy;
if AMouth <> nil then
FMouth := AMouth.Copy;
end;
destructor TFaceScoreResults.Destroy;
begin
F(FFaceImage);
F(FFace);
F(FLeftEye);
F(FRightEye);
F(FNose);
F(FMouth);
inherited;
end;
function TFaceScoreResults.GetEyeMouthAngle: Double;
const
SHOULD_BE_ANGLE = 25 * PI / 180;
var
P1, P2: TPoint;
begin
Result := 0;
if HasSingleEye and HasMouth then
begin
if FLeftEye <> nil then
begin
P1 := LeftEye.Rect.CenterPoint;
P2 := FMouth.Rect.CenterPoint;
if (P1.X <> P2.X) then
Result := SHOULD_BE_ANGLE - ArcTan((P1.X - P2.X) / (P1.Y - P2.Y));
end;
if FRightEye <> nil then
begin
P1 := FRightEye.Rect.CenterPoint;
P2 := FMouth.Rect.CenterPoint;
if (P1.X <> P2.X) then
Result := - SHOULD_BE_ANGLE - ArcTan((P1.X - P2.X) / (P1.Y - P2.Y));
end;
end;
end;
function TFaceScoreResults.GetEyesAngle: Double;
var
P1, P2: TPoint;
begin
Result := 0;
if HasBothEyes then
begin
P1 := LeftEye.Rect.CenterPoint;
P2 := RightEye.Rect.CenterPoint;
if (P1.Y <> P2.Y) then
Result := ArcTan((P1.Y - P2.Y) / (P1.X - P2.X));
end;
end;
function TFaceScoreResults.GetFaceAngle: Double;
begin
Result := 0;
if (HasBothEyes) then
Result := EyesAngle
else if HasSingleEye and HasMouth then
Result := EyeMouthAngle
else if HasMouth and HasNose then
Result := MouseNouseAngle;
end;
function TFaceScoreResults.GetMouseNouseAngle: Double;
var
P1, P2: TPoint;
begin
Result := 0;
if HasMouth and HasNose then
begin
P1 := FNose.Rect.CenterPoint;
P2 := FMouth.Rect.CenterPoint;
if (P1.X <> P2.X) then
Result := ArcTan((P1.X - P2.X) / (P1.Y - P2.Y));
end;
end;
function TFaceScoreResults.GetHasBothEyes: Boolean;
begin
Result := (FLeftEye <> nil) and (FRightEye <> nil);
end;
function TFaceScoreResults.GetHasMouth: Boolean;
begin
Result := FMouth <> nil;
end;
function TFaceScoreResults.GetHasNose: Boolean;
begin
Result := FNose <> nil;
end;
function TFaceScoreResults.GetHasSingleEye: Boolean;
begin
Result := not HasBothEyes and ((FLeftEye <> nil) or (FRightEye <> nil));
end;
function TFaceScoreResults.GetTotalScore: Byte;
begin
Result := 0;
if FLeftEye <> nil then
Inc(Result, 30);
if FRightEye <> nil then
Inc(Result, 30);
if FMouth <> nil then
Inc(Result, 20);
if FNose <> nil then
Inc(Result, 20);
Result := Round(Result / (1 + Abs(FaceAngle)));
end;
procedure TFaceScoreResults.GenerateSample(Bitmap: TBitmap; Width, Height: Integer);
var
FaceMask: TBitmap;
{ Face: TBitmap;
R: TRect;
Dx, Dy: Integer;
Proportions: Double; }
procedure UpdateBitmap(Source: TBitmap);
var
MaskPng: TPngImage;
begin
DoResize(Width, Height, Source, Bitmap);
FaceMask := TBitmap.Create;
try
MaskPng := GetFaceMaskImage;
try
FaceMask.Assign(MaskPng);
FaceMask.PixelFormat := pf24bit;
ApplyMask(Bitmap, FaceMask);
finally
F(MaskPng);
end;
finally
F(FaceMask);
end;
end;
begin
{if TotalScore >= 80 then
begin
R := Rect(FFaceImage.Width div 2, FFaceImage.Height div 2, FFaceImage.Width div 2, FFaceImage.Height div 2);
if FLeftEye <> nil then
UnionRect(R, R, FLeftEye.Rect);
if FRightEye <> nil then
UnionRect(R, R, FRightEye.Rect);
if FNose <> nil then
UnionRect(R, R, FNose.Rect);
if FMouth <> nil then
UnionRect(R, R, FNose.Rect);
Face := TBitmap.Create;
try
Proportions := Width / Height;
if R.Width / R.Height > Proportions then
begin
Dy := Round(R.Width / Proportions - R.Height);
InflateRect(R, 0, Dy div 2);
end else
begin
Dx := Round(R.Height * Proportions - R.Width);
InflateRect(R, Dx div 2, 0);
end;
Face.SetSize(R.Width, R.Height);
Face.PixelFormat := pf24bit;
DrawImageExRect(Face, FFaceImage, R.Left, R.Top, R.Width, R.Height, 0, 0);
UpdateBitmap(Face);
finally
F(Face);
end;
Exit;
end;}
UpdateBitmap(FFaceImage);
end;
end.
|
{/*!
Provides a light weight parser class for TransModeler pml file.
\modified 2019-07-03 10:20am
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
RemObjects.Elements.RTL;
type
XmlDocumentHelper = public extension class(XmlDocument)
public
method AllElementsWithName(aLocalName: not nullable String; aNamespace: nullable XmlNamespace := nil; aXmlElement: XmlElement := nil): not nullable sequence of XmlElement;
begin
var lXmlElement := if assigned(aXmlElement) then aXmlElement else Root;
if lXmlElement.Elements.Count = 0 then exit(new List<XmlElement>);
result := lXmlElement.ElementsWithName(aLocalName, aNamespace);
for each el in lXmlElement.Elements do
result := (not nullable sequence of XmlElement)(result.Concat(AllElementsWithName(aLocalName, aNamespace, el)));
end;
end;
TsmPluginParameterParser = public class
private
fBasePmlDoc, fUserPmlDoc, fProjectPmlDoc: XmlDocument;
fPmlValueAttribute: XmlAttribute;
fPmlValueTag: String;
fBaseParamItems, fUserParamItems, fProjectParamItems: ISequence<XmlElement>;
private
method FindParameterItem(const aName: not nullable String; const aItems: not nullable ISequence<XmlElement>): XmlElement;
begin
var lparamItems: ISequence<XmlElement> :=
from
p in aItems
where
(assigned(p.Attribute['name']) and (p.Attribute['name'].FullName = aName))
select
p;
if (lparamItems.Count > 1) then
raise new EParameterItemNameNotUniqueException(aName);
result := if lparamItems.Count > 0 then lparamItems.First;
end;
method FindPluginParameterItem(const aName: not nullable String): XmlElement;
begin
// Param item must exist in base Pml
var lparamItem_base := FindParameterItem(aName, fBaseParamItems);
if not assigned(lparamItem_base) then
raise new EParameterItemMissingException(aName);
result := lparamItem_base;
if assigned(fUserParamItems) then begin
var lparamItem_user := FindParameterItem(aName, fUserParamItems);
result := if assigned(lparamItem_user) then lparamItem_user else result;
end;
if assigned(fProjectParamItems) then begin
var lparamItem_proj := FindParameterItem(aName, fProjectParamItems);
result := if assigned(lparamItem_proj) then lparamItem_proj else result;
end;
end;
public
constructor(const aBasePmlFilePath, aUserPmlFilePath, aProjectPmlFilePath: not nullable String);
begin
fBasePmlDoc := XmlDocument.FromFile(aBasePmlFilePath);
// Get the value tag. It could be "value", or "v", or anything.
fPmlValueAttribute := fBasePmlDoc.Root.Attribute['value'];
fPmlValueTag := if assigned(fPmlValueAttribute) then fPmlValueAttribute.Value else 'value';
fBaseParamItems := fBasePmlDoc.AllElementsWithName('item');
if File.Exists(aUserPmlFilePath) then begin
fUserPmlDoc := XmlDocument.FromFile(aUserPmlFilePath);
fUserParamItems := fUserPmlDoc.AllElementsWithName('item');
end;
if File.Exists(aProjectPmlFilePath) then begin
fProjectPmlDoc := XmlDocument.FromFile(aProjectPmlFilePath);
fProjectParamItems := fProjectPmlDoc.AllElementsWithName('item');
end;
end;
method Item(const aName: not nullable String): ISequence<String>;
begin
var lparamItem: XmlElement := FindPluginParameterItem(aName);
result := from v in lparamItem.ElementsWithName(fPmlValueTag) select v.Value;
end;
method TableItem(const aName: not nullable String; aColumn, aRow: UInt32): String;
begin
var lparamItem: XmlElement := FindPluginParameterItem(aName);
if lparamItem.Attribute['type'].Value <> 'table' then
raise new EInvalidParameterItemTypeException(aName, lparamItem.Attribute['type'].Value);
var lCell := lparamItem.ElementsWithName('rows')
.First // Only one element named "rows".
.ElementsWithName('row')
.ToArray[aRow]
.ElementsWithName(fPmlValueTag)
.ToArray[aColumn];
result := lCell.Value;
end;
end;
end. |
unit uDM;
interface
uses
SysUtils, Classes, DB, ADODB, Dialogs, IniFiles, uDados, Forms, ufrmServerInfo;
const
INI_FILE = 'Info.ini';
type
TMRDatabase = class
private
fDatabaseName : String;
fServer : String;
fUser : String;
fPW : String;
public
property DatabaseName : String read fDatabaseName write fDatabaseName;
property Server : String read fServer write fServer;
property User : String read fUser write fUser;
property PW : String read fPW write fPW;
end;
TCaixa = class
private
fNumSequencia: Integer;
public
property NumSequencia : Integer read fNumSequencia write fNumSequencia;
end;
TEmpresa = class
private
fRazaoSocial : String;
fCNPJ : String;
fInscEstadual : String;
fEndereco : String;
fNumero : String;
fComplemento : String;
fBairro : String;
fMunicipio : String;
fCEP : String;
fUF : String;
fFax : String;
fFone : String;
fResponsavel : String;
fTributario : String;
fIPI : String;
public
property RazaoSocial : String read fRazaoSocial write fRazaoSocial;
property CNPJ : String read fCNPJ write fCNPJ;
property InscEstadual : String read fInscEstadual write fInscEstadual;
property Endereco : String read fEndereco write fEndereco;
property Numero : String read fNumero write fNumero ;
property Complemento : String read fComplemento write fComplemento;
property Bairro : String read fBairro write fBairro ;
property Municipio : String read fMunicipio write fMunicipio;
property CEP : String read fCEP write fCEP ;
property UF : String read fUF write fUF ;
property Fax : String read fFax write fFax ;
property Fone : String read fFone write fFone ;
property Responsavel : String read fResponsavel write fResponsavel ;
property Tributario : String read fTributario write fTributario;
property IPI : String read fIPI write fIPI ;
end;
TDM = class(TDataModule)
MRDBConnection: TADOConnection;
quProduto: TADODataSet;
quProdutoInvoiceDate: TDateTimeField;
quProdutoQty: TIntegerField;
quProdutoMovDate: TDateTimeField;
quProdutoModelID: TIntegerField;
quProdutoTaxValue: TBCDField;
quProdutoExtSubTotal: TBCDField;
quProdutoCupomFiscal: TStringField;
quProdutoSituacaoTributaria: TIntegerField;
quProdutoNumeroSeriePrinter: TStringField;
quProdutoTax: TBCDField;
quProdutoModel: TStringField;
quProdutoDescription: TStringField;
quImpSerial: TADODataSet;
quImpSerialNumeroSeriePrinter: TStringField;
quVendaBruta: TADODataSet;
quHasSale: TADODataSet;
quProdutoSalePrice: TBCDField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
fLocalPath : String;
fMRDatabase : TMRDatabase;
fEmpresa : TEmpresa;
fCaixa : TCaixa;
fInfo : TInifile;
Dados : TDados;
fFrmServrInfo : TFrmServerInfo;
property LocalPath : String read fLocalPath;
function MRConnectionOpen: Boolean;
function MRConnectionClose:Boolean;
procedure BuildConnection;
procedure ReadCompany;
procedure WriteCompany;
function HasSale(fIni, fEnd : TDateTime):Boolean;
end;
var
DM: TDM;
implementation
uses uParamFunctions;
{$R *.dfm}
{ TDM }
function TDM.MRConnectionClose: Boolean;
begin
with MRDBConnection do
if Connected then
try
Close;
Result := True;
except
on E: Exception do
begin
Result := False;
//ShowMessage(E.Message);
end;
end;
end;
function TDM.MRConnectionOpen: Boolean;
begin
with MRDBConnection do
if not Connected then
try
ConnectionString := SetConnectionStr(fMRDatabase.User,
fMRDatabase.PW,
fMRDatabase.DatabaseName,
fMRDatabase.Server);
Open;
Result := True;
except
on E: Exception do
begin
Result := False;
//ShowMessage(E.Message);
end;
end;
end;
procedure TDM.DataModuleCreate(Sender: TObject);
begin
fMRDatabase := TMRDatabase.Create;
fEmpresa := TEmpresa.Create;
fCaixa := TCaixa.Create;
fLocalPath := ExtractFilePath(Application.ExeName);
fInfo := TIniFile.Create(fLocalPath + INI_FILE);
ShortDateFormat := 'dd/mm/yyyy';
fFrmServrInfo := TFrmServerInfo.Create(self);
ReadCompany;
BuildConnection;
MRConnectionOpen;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
MRConnectionClose;
FreeAndNil(fMRDatabase);
FreeAndNil(fFrmServrInfo);
FreeAndNil(fEmpresa);
FreeAndNil(fCaixa);
end;
procedure TDM.BuildConnection;
var
sUser, sPW, sDB, sServer, sResult : string;
cStartType : Char;
bAbort : Boolean;
begin
cStartType := '4';
sResult := fFrmServrInfo.Start(cStartType, False, '', bAbort);
fMRDatabase.Server := ParseParam(sResult, '#SRV#');
fMRDatabase.User := ParseParam(sResult, '#USER#');
fMRDatabase.PW := ParseParam(sResult, '#PW#');
fMRDatabase.DatabaseName := ParseParam(sResult, '#DB#');
end;
procedure TDM.ReadCompany;
begin
fEmpresa.RazaoSocial := fInfo.ReadString('Empresa', 'RazaoSocial', '');
fEmpresa.CNPJ := fInfo.ReadString('Empresa', 'CNPJ', '');
fEmpresa.InscEstadual := fInfo.ReadString('Empresa', 'InscEstadual', '');
fEmpresa.Endereco := fInfo.ReadString('Empresa', 'Endereco', '');
fEmpresa.Numero := fInfo.ReadString('Empresa', 'Numero', '');
fEmpresa.Complemento := fInfo.ReadString('Empresa', 'Complemento', '');
fEmpresa.Bairro := fInfo.ReadString('Empresa', 'Bairro', '');
fEmpresa.Municipio := fInfo.ReadString('Empresa', 'Municipio', '');
fEmpresa.CEP := fInfo.ReadString('Empresa', 'CEP', '');
fEmpresa.UF := fInfo.ReadString('Empresa', 'UF', '');
fEmpresa.Fax := fInfo.ReadString('Empresa', 'Fax', '');
fEmpresa.Fone := fInfo.ReadString('Empresa', 'Fone', '');
fEmpresa.Responsavel := fInfo.ReadString('Empresa', 'Responsavel', '');
fEmpresa.Tributario := fInfo.ReadString('Empresa', 'Tributario', '');
fEmpresa.IPI := fInfo.ReadString('Empresa', 'IPI', '');
end;
procedure TDM.WriteCompany;
begin
fInfo.WriteString('Empresa', 'RazaoSocial', fEmpresa.RazaoSocial);
fInfo.WriteString('Empresa', 'CNPJ', fEmpresa.CNPJ);
fInfo.WriteString('Empresa', 'InscEstadual', fEmpresa.InscEstadual);
fInfo.WriteString('Empresa', 'Endereco', fEmpresa.Endereco);
fInfo.WriteString('Empresa', 'Numero', fEmpresa.Numero);
fInfo.WriteString('Empresa', 'Complemento', fEmpresa.Complemento);
fInfo.WriteString('Empresa', 'Bairro', fEmpresa.Bairro);
fInfo.WriteString('Empresa', 'Municipio', fEmpresa.Municipio);
fInfo.WriteString('Empresa', 'CEP', fEmpresa.CEP);
fInfo.WriteString('Empresa', 'UF', fEmpresa.UF);
fInfo.WriteString('Empresa', 'Fax', fEmpresa.Fax );
fInfo.WriteString('Empresa', 'Fone', fEmpresa.Fone);
fInfo.WriteString('Empresa', 'Responsavel', fEmpresa.Responsavel);
fInfo.WriteString('Empresa', 'Tributario', fEmpresa.Tributario);
fInfo.WriteString('Empresa', 'IPI', fEmpresa.IPI);
end;
function TDM.HasSale(fIni, fEnd: TDateTime): Boolean;
begin
with quHasSale do
try
Parameters.ParamByName('Data_Inicial').Value := fIni;
Parameters.ParamByName('Data_Final').Value := fEnd;
Open;
Result := (RecordCount>0);
finally
Close;
end;
end;
end.
|
unit ufrmMerchandiseGroup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMaster, StdCtrls, ExtCtrls,
ufraFooter5Button, ActnList, SUIDlg, uNewMerchandize, uRetnoUnit;
type
TfrmMerchandiseGroup = class(TfrmMaster)
fraFooter5Button1: TfraFooter5Button;
strgGrid: TAdvStringGrid;
actlstMerchandiseGroup: TActionList;
actAddMerchanGroup: TAction;
actEditMerchanGroup: TAction;
actDeleteMerchanGroup: TAction;
actRefreshMerchanGroup: TAction;
// FMerchanGroupId: integer;
procedure actAddMerchanGroupExecute(Sender: TObject);
procedure actEditMerchanGroupExecute(Sender: TObject);
procedure actDeleteMerchanGroupExecute(Sender: TObject);
procedure actRefreshMerchanGroupExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure fraFooter5Button1btnCloseClick(Sender: TObject);
private
FNewMerchandize: TNewMerchadize;
{ Private declarations }
public
{ Public declarations }
end;
var
frmMerchandiseGroup: TfrmMerchandiseGroup;
implementation
uses ufrmDialogMerchandiseGroup, uTSCommonDlg, uMerchandiseGroup, uConn,
uConstanta;
{$R *.dfm}
const
_kolNo : Integer = 0;
_kolMerCd : Integer = 1;
_kolMerNm : Integer = 2;
_kolMerPjk : Integer = 3;
_kolMerId : Integer = 4;
procedure TfrmMerchandiseGroup.actAddMerchanGroupExecute(
Sender: TObject);
begin
if MasterNewUnit.ID=0 then
begin
CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
////frmMain.cbbUnit.SetFocus;
Exit;
end;
if not Assigned(frmDialogMerchandiseGroup) then
Application.CreateForm(TfrmDialogMerchandiseGroup, frmDialogMerchandiseGroup);
frmDialogMerchandiseGroup.frmSuiMasterDialog.Caption := 'Add Merchandise';
frmDialogMerchandiseGroup.FormMode := fmAdd;
SetFormPropertyAndShowDialog(frmDialogMerchandiseGroup);
if (frmDialogMerchandiseGroup.IsProcessSuccessfull) then
begin
actRefreshMerchanGroupExecute(Self);
CommonDlg.ShowConfirm(atAdd);
end;
frmDialogMerchandiseGroup.Free;
end;
procedure TfrmMerchandiseGroup.actEditMerchanGroupExecute(
Sender: TObject);
begin
if strgGrid.Cells[_kolMerId,strgGrid.row] = '0' then Exit;
if MasterNewUnit.ID = 0 then
begin
CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
////frmMain.cbbUnit.SetFocus;
Exit;
end;
if not Assigned(frmDialogMerchandiseGroup) then
Application.CreateForm(TfrmDialogMerchandiseGroup, frmDialogMerchandiseGroup);
frmDialogMerchandiseGroup.frmSuiMasterDialog.Caption := 'Edit Merchandise';
frmDialogMerchandiseGroup.FormMode := fmEdit;
frmDialogMerchandiseGroup.MerchanGroupId := StrToInt(strgGrid.Cells[_kolMerId,strgGrid.Row]);// put your merchan group id that won be edit
SetFormPropertyAndShowDialog(frmDialogMerchandiseGroup);
if (frmDialogMerchandiseGroup.IsProcessSuccessfull) then
begin
actRefreshMerchanGroupExecute(Self);
CommonDlg.ShowConfirm(atEdit);
end;
frmDialogMerchandiseGroup.Free;
end;
procedure TfrmMerchandiseGroup.actDeleteMerchanGroupExecute(
Sender: TObject);
begin
if strgGrid.Cells[_kolMerId,strgGrid.row]='0' then Exit;
if MasterNewUnit.ID=0 then
begin
CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
////frmMain.cbbUnit.SetFocus;
Exit;
end;
if (CommonDlg.Confirm('Are you sure you wish to delete Merchandise (Code: '+strgGrid.Cells[0,strgGrid.row]+')?') = mrYes) then
begin
{if not assigned(MerchandiseGroup) then
MerchandiseGroup := TMerchandiseGroup.Create;
if MerchandiseGroup.DeleteDataMerchandiseGroup(StrToInt(strgGrid.Cells[2,strgGrid.Row]),MasterNewUnit.ID) then
begin
actRefreshMerchanGroupExecute(Self);
CommonDlg.ShowConfirm(atDelete);
end;
}
if FNewMerchandize.LoadByID(StrToInt(strgGrid.Cells[_kolMerId,strgGrid.Row])) then
begin
if FNewMerchandize.RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Data Berhail DiHapus');
frmMerchandiseGroup.fraFooter5Button1.btnRefresh.Click;
exit;
end
else
begin
cRollbackTrans;
CommonDlg.ShowMessage('Data Gagal Dihapus');
end;
end;
end;
end;
procedure TfrmMerchandiseGroup.actRefreshMerchanGroupExecute(
Sender: TObject);
var data: TDataSet;
i: Integer;
begin
inherited;
if not assigned(MerchandiseGroup) then
MerchandiseGroup := TMerchandiseGroup.Create;
data := MerchandiseGroup.GetDataMerchandiseGroup();
with strgGrid do
begin
Clear;
ColCount := 4;
RowCount := data.RecordCount+1;
Cells[_kolNo, 0] := 'NO';
Cells[_kolMerCd, 0] := 'CODE';
Cells[_kolMerNm, 0] := 'NAME';
Cells[_kolMerPjk, 0] := 'PAJAK';
i:=1;
if RowCount>1 then
begin
with data do
begin
while not Eof do
begin
Cells[_kolNo, i] := IntToStr(i);
Cells[_kolMerCd, i] := FieldByName('MERCHAN_CODE').AsString;
Cells[_kolMerNm, i] := FieldByName('MERCHAN_NAME').AsString;
Cells[_kolMerPjk, i] := FieldByName('PJK_NAME').AsString;
Cells[_kolMerId, i] := IntToStr(FieldByName('MERCHAN_ID').AsInteger);
i:=i+1;
Application.ProcessMessages;
Next;
end
end
end
else
begin
RowCount:=2;
Cells[_kolNo, 1] := ' ';
Cells[_kolMerCd, 1] := ' ';
Cells[_kolMerNm, 1] := ' ';
Cells[_kolMerPjk, 1] := ' ';
Cells[_kolMerId, 1] := '0';
end;
FixedRows := 1;
AutoSize := true;
end;
strgGrid.SetFocus;
end;
procedure TfrmMerchandiseGroup.FormDestroy(Sender: TObject);
begin
inherited;
frmMerchandiseGroup := nil;
end;
procedure TfrmMerchandiseGroup.FormShow(Sender: TObject);
begin
inherited;
lblHeader.Caption:='MERCHANDISE';
actRefreshMerchanGroupExecute(Self);
end;
procedure TfrmMerchandiseGroup.FormActivate(Sender: TObject);
begin
inherited;
//frmMain.CreateMenu((sender as TForm));
end;
procedure TfrmMerchandiseGroup.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
//frmMain.DestroyMenu((sender as TForm));
end;
procedure TfrmMerchandiseGroup.FormCreate(Sender: TObject);
begin
inherited;
FNewMerchandize := TNewMerchadize.Create(Self);
{if FNewMerchandize.LoadByID(StrToInt(strgGrid.Cells[2,strgGrid.Row]),MasterNewUnit.ID) then
begin
if FNewMerchandize.RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Data Berhail DiHapus');
exit;
end
else
begin
cRollbackTrans;
CommonDlg.ShowMessage('Data Gagal Dihapus');
end;
end }
end;
procedure TfrmMerchandiseGroup.fraFooter5Button1btnCloseClick(
Sender: TObject);
begin
inherited;
fraFooter5Button1.btnCloseClick(Sender);
end;
end.
|
unit uTCPIP;
(*
======================
Delphi TCP/IP MONITOR
======================
Developed on: D4.03
Tested on : WIN-NT4/SP6, WIN98se, WIN95/OSR1
================================================================
This software is FREEWARE
-------------------------
If this software works, it was surely written by Dirk Claessens
<dirk.claessens16@yucom.be>
<dirk.claessens.dc@belgium.agfa.com>
(If it doesn't, I don't know anything about it.)
================================================================
*)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, IPHelper, StdCtrls, ComCtrls, Buttons, jpeg;
const
version = '1.2';
type
TIPForm = class( TForm )
Timer1: TTimer;
PageControl1: TPageControl;
ARPSheet: TTabSheet;
ConnSheet: TTabSheet;
IP1Sheet: TTabSheet;
ARPMemo: TMemo;
StaticText1: TStaticText;
TCPMemo: TMemo;
StaticText2: TStaticText;
IPAddrMemo: TMemo;
StaticText6: TStaticText;
IP2Sheet: TTabSheet;
IPForwMemo: TMemo;
StaticText8: TStaticText;
AdaptSheet: TTabSheet;
AdaptMemo: TMemo;
SpeedButton1: TSpeedButton;
cbTimer: TCheckBox;
StaticText9: TStaticText;
NwMemo: TMemo;
StaticText10: TStaticText;
TabSheet1: TTabSheet;
ICMPInMemo: TMemo;
ICMPOutMemo: TMemo;
StaticText12: TStaticText;
btRTTI: TSpeedButton;
cbRecentIPs: TComboBox;
edtRTTI: TEdit;
StaticText14: TStaticText;
IfMemo: TMemo;
StaticText15: TStaticText;
TCPStatMemo: TMemo;
StaticText7: TStaticText;
UDPStatsMemo: TMemo;
StaticText4: TStaticText;
IPStatsMemo: TMemo;
StaticText5: TStaticText;
UDPMemo: TMemo;
StaticText3: TStaticText;
Image1: TImage;
procedure Timer1Timer( Sender: TObject );
procedure FormCreate( Sender: TObject );
procedure SpeedButton1Click( Sender: TObject );
procedure cbTimerClick( Sender: TObject );
procedure btRTTIClick( Sender: TObject );
procedure cbRecentIPsClick( Sender: TObject );
private
{ Private declarations }
procedure DOIpStuff;
public
{ Public declarations }
end;
var
IPForm : TIPForm;
implementation
{$R *.DFM}
//------------------------------------------------------------------------------
procedure TIPForm.FormCreate( Sender: TObject );
begin
PageControl1.ActivePage := ConnSheet;
Caption := Caption + ' ' + Version;
DOIpStuff;
Timer1.Enabled := true;
end;
//------------------------------------------------------------------------------
procedure TIPForm.DOIpStuff;
begin
Get_NetworkParams( NwMemo.Lines );
Get_ARPTable( ARPMemo.Lines );
Get_TCPTable( TCPMemo.Lines );
Get_TCPStatistics( TCPStatMemo.Lines );
Get_UDPTable( UDPMemo.Lines );
Get_IPStatistics( IPStatsMemo.Lines );
Get_IPAddrTable( IPAddrMemo.Lines );
Get_IPForwardTable( IPForwMemo.Lines );
Get_UDPStatistics( UDPStatsMemo.Lines );
Get_AdaptersInfo( AdaptMemo.Lines );
Get_ICMPStats( ICMPInMemo.Lines, ICMPOutMemo.Lines );
Get_IfTable( IfMemo.Lines );
Get_RecentDestIPs( cbRecentIPs.Items );
end;
//------------------------------------------------------------------------------
procedure TIPForm.cbTimerClick( Sender: TObject );
begin
Timer1.Enabled := cbTimer.State = cbCHECKED;
end;
//------------------------------------------------------------------------------
procedure TIPForm.Timer1Timer( Sender: TObject );
begin
if cbTimer.State = cbCHECKED then
begin
Timer1.Enabled := false;
DoIPStuff;
Timer1.Enabled := true;
end;
end;
//------------------------------------------------------------------------------
procedure TIPForm.SpeedButton1Click( Sender: TObject );
begin
Speedbutton1.Enabled := false;
DoIPStuff;
Speedbutton1.Enabled := true;
end;
//------------------------------------------------------------------------------
procedure TIPForm.btRTTIClick( Sender: TObject );
var
IPadr : dword;
Rtt, HopCount : longint;
Res : integer;
begin
btRTTI.Enabled := false;
Screen.Cursor := crHOURGLASS;
IPadr := Str2IPAddr( edtRTTI.Text );
Res := Get_RTTAndHopCount( IPadr, 128, RTT, HopCount );
if Res = NO_ERROR then
ShowMessage( ' Round Trip Time '
+ inttostr( rtt ) + ' ms, '
+ inttostr( HopCount )
+ ' hops to : ' + edtRTTI.Text
)
else
ShowMessage( 'Error occurred:' + #13
+ ICMPErr2Str( Res ) ) ;
btRTTI.Enabled := true;
Screen.Cursor := crDEFAULT;
end;
//------------------------------------------------------------------------------
procedure TIPForm.cbRecentIPsClick( Sender: TObject );
begin
edtRTTI.Text := cbRecentIPs.Items[cbRecentIPs.ItemIndex];
end;
end.
|
unit ColorWheel2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, GDIPAPI, GDIPOBJ, math, extctrls;
type
TColorPaletteStyle = (tcpsMonochromatic, tcpsComplementary, tcpsAnalogous,
tcpsTriad, tcpsSplitComplementary, tcpsRectangle, tcpsSquare,
tcpsFreeForm2, tcpsFreeForm3, tcpsFreeform4);
TColorWheel2 = class(TCustomPanel)
private
{ Private declarations }
// control bounds used to detect mouse down
FControlBoundRects : array[0..3] of TRect;
// size of the control border
FBorderSize: integer;
// selected control
FSelectedControl : integer;
// Colors changed event
FColorsChanged: TNotifyEvent;
// radius of the controls location
FRadius : integer;
// hue of the controls
FHueArray : Array[0..4] of double;
// number of active controls
FNumColors : Integer;
// Type of the color controls
FSwatchType : TColorPaletteStyle;
// Paint routines
procedure PaintControls;
procedure DrawCircle(x, y: integer; c: TRGBTriple; center : Tpoint;Marked : boolean);
procedure PaintCircle(Bitmap: TBitmap);
// control functions
function getAngle(x, y: integer): double;
procedure MoveBigControl(controlIndex: integer; angle: double);
function getJoinedControls(selected, test: integer): integer;
function hsv2rgb(hue, sat, value: double): TRGBTriple;
procedure HueSaturationAtPoint(positionx, positiony: Integer; size: Integer; var hue, sat: double);
function ConvertHSVToColor(h, s, v: double): TColor;
// interface functions
procedure SetNumControls(const Value: integer);
procedure SetBorderSize(const Value: integer);
procedure SetColorsChanged(const Value: TNotifyEvent);
procedure DoColorsChanged;
function getNumControls: integer;
procedure SetSwatchType(const Value: TColorPaletteStyle);
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
function getColor(index : Integer) : TColor;
published
{ Published declarations }
property NumControls : integer read getNumControls write SetNumControls;
property BorderSize : integer read FBorderSize write SetBorderSize;
property ColorsChanged : TNotifyEvent read FColorsChanged write SetColorsChanged;
property SwatchType : TColorPaletteStyle read FSwatchType write SetSwatchType;
property Color;
end;
PRGBTripleArray = ^TRGBTripleArray;
TRGBTripleArray = array [Byte] of TRGBTriple;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MTS', [TColorWheel2]);
end;
{ TColorWheel2 }
function TColorWheel2.ConvertHSVToColor(h, s, v: double): TColor;
var
f,p,q,t : double;
r,g,b : byte;
i : integer;
begin
while h < 0 do
begin
h := h + 360;
end;
if h = 360 then
h := 0.0;
h := h/60.0;
i := floor(h);
f := h - i;
p := v*(1.0 - s);
q := v*(1.0 - s * f);
t := v*(1.0 - (s * (1.0-f)));
case i of
0: begin
r := round(v*255);
g := round(t*255);
b := round(p*255);
end;
1: begin
r := round(q*255);
g := round(v*255);
b := round(p*255);
end;
2: begin
r := round(p*255);
g := round(v*255);
b := round(t*255);
end;
3: begin
r := round(p*255);
g := round(q*255);
b := round(v*255);
end;
4: begin
r := round(t*255);
g := round(p*255);
b := round(v*255);
end;
5: begin
r := round(v*255);
g := round(p*255);
b := round(q*255);
end;
else
begin
r := 0;
g := 0;
b := 0;
end;
end;
result := r + g shl 8 + b shl 16;
end;
constructor TColorWheel2.Create(AOwner: TComponent);
begin
inherited;
Width := 250;
Height := 250;
FBorderSize := 10;
FSelectedControl := -1;
ControlStyle := ControlStyle + [csOpaque];
DoubleBuffered := true;
end;
destructor TColorWheel2.destroy;
begin
inherited;
end;
procedure TColorWheel2.DrawCircle(x,y : integer; c : TRGBTriple; center : Tpoint; Marked : boolean);
var
graphics : TGPGraphics;
Pen : TGPPen;
Brush : TGPSolidBrush;
begin
graphics := TGPGraphics.Create(Canvas.Handle);
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
pen := TGPPen.Create(makeColor(190,0,0,0));
brush := TGPSolidBrush.Create(makeColor(255, c.rgbtRed, c.rgbtGreen, c.rgbtBlue));
try
graphics.DrawLine(pen, center.X, center.Y, x, y);
brush.SetColor(makeColor(255,255,255,255));
graphics.FillEllipse(Brush, x-9, y-9, 18, 18);
brush.SetColor(makeColor(255, c.rgbtRed, c.rgbtGreen, c.rgbtBlue));
graphics.FillEllipse(Brush, x-6, y-6, 12, 12);
if Marked then
Pen.SetWidth(2.0)
else
Pen.SetWidth(1.0);
graphics.DrawEllipse(Pen, x-9, y-9, 18, 18);
finally
pen.free;
brush.free;
graphics.free;
end;
end;
//
// For the selected integer that is passed in
// if it's one of the controls that moves other
// controls then if test is moved with this one then
// it returns true, otherwise false.
//
function TColorWheel2.getJoinedControls(selected, test : integer) : integer;
begin
result := 0;
case FSwatchType of
tcpsMonochromatic, tcpsComplementary, tcpsAnalogous: result := 1;
tcpsTriad, tcpsSplitComplementary :
begin
if selected = 0 then
result := 1
else if (selected in [1,2]) and (test in [1, 2]) then
begin
result := 1;
if ((selected = 1) and (test = 2)) or ((selected = 2) and (test = 1)) then
result := -1
end
else
result := 0;
end;
tcpsFreeForm2, tcpsFreeForm3, tcpsFreeForm4:
begin
if selected = 0 then
result := 1
else if selected = test then
result := 1
else
result := 0;
end;
tcpsRectangle, tcpsSquare:
begin
if selected in [0,2] then
result := 1
else if (selected in [1,3]) and (test in [1,3]) then
result := 1
else
result := 0;
end;
end;
end;
function TColorWheel2.getNumControls: integer;
begin
result := FNumColors;
end;
procedure TColorWheel2.PaintControls;
var
center : TPoint;
i : integer;
x,y : double;
c : TRGBTriple;
hue, sat : double;
begin
center := Point(width div 2, height div 2);
for i := 0 to NumControls - 1 do
begin
x := Fradius * cos(FHueArray[i] * PI/180);
y := Fradius * sin(FHueArray[i] * PI/180);
x := x + center.x;
y := y + center.y;
HueSaturationAtPoint(round(x), round(y) ,min(width,height), hue,sat);
c := hsv2rgb(hue, sat, 1.0);
drawCircle(round(x),round(y),c, center, i=0);
FControlBoundRects[i] := rect(round(x)-10,
round(y)-10, round(x)+ 10, round(y)+10);
end;
end;
function TColorWheel2.getAngle(x, y : integer) : double;
begin
if x = 0 then
begin
if y <0 then
result := 270
else
result := 90;
end
else
begin
if x < 0 then
result := (arctan(y/x)-PI)*(180/PI) // calc the angle and conver to degrees
else
result := (arctan(y/x))*(180/PI); // calc the angle and conver to degrees
if result <0 then
result := result + 360;
end;
end;
function TColorWheel2.hsv2rgb(hue, sat, value : double) : TRGBTriple;
var
i, f, p, q,t : double;
s : integer;
begin
i := Floor(hue * 6);
f := hue * 6 - i;
p := value * (1-sat);
q := value * (1 - f * sat);
t := value * (1 - (1-f) * sat);
s := round(i) mod 6;
case s of
0: begin
result.rgbtRed := round(value * 255);
result.rgbtGreen := round(t * 255);
result.rgbtBlue := round(p * 255);
end;
1: begin
result.rgbtRed := round(q * 255);
result.rgbtGreen := round(value * 255);
result.rgbtBlue := round(p * 255);
end;
2: begin
result.rgbtRed := round(p * 255);
result.rgbtGreen := round(value * 255);
result.rgbtBlue := round(t * 255);
end;
3: begin
result.rgbtRed := round(p * 255);
result.rgbtGreen := round(q * 255);
result.rgbtBlue := round(value * 255);
end;
4: begin
result.rgbtRed := round(t * 255);
result.rgbtGreen := round(p * 255);
result.rgbtBlue := round(value * 255);
end;
5: begin
result.rgbtRed := round(value * 255);
result.rgbtGreen := round(p * 255);
result.rgbtBlue := round(q * 255);
end;
else
begin
result.rgbtRed := round(value * 255);
result.rgbtGreen := round(t * 255);
result.rgbtBlue := round(p * 255);
end;
end;
end;
procedure TColorWheel2.PaintCircle(Bitmap : TBitmap);
var
center : Tpoint;
i, j : integer;
p : PRGBTripleArray;
x, y : integer;
theta : double;
lng : double;
h, w : integer;
c : TRGBTriple;
radius : double;
graphics : TGPGraphics;
Pen : TGPPen;
hue, sat : double;
begin
h := bitmap.height;
w := bitmap.width;
center := Point(w div 2, h div 2);
radius := min(w,h) div 2;
for j := 0 to h - 1 do
begin
p := bitmap.scanline[j];
for i := 0 to w - 1 do
begin
x := i - center.x;
y := j - center.y;
lng := sqrt(x*x + y * y);
if lng > (min(w,h) div 2) then
begin
p[i].rgbtRed := color and $FF;
p[i].rgbtGreen := (color and $FF00) shr 8;
p[i].rgbtBlue := (color and $FF0000) shr 16;
continue;
end;
HueSaturationAtPoint(i,j,min(w,h), hue,sat);
c := hsv2rgb(hue, sat, 1.0);
p[i] := c;
end;
end;
graphics := TGPGraphics.Create(Bitmap.Canvas.Handle);
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
pen := TGPPen.Create(makeColor(190,0,0,0));
pen.setwidth(2.0);
try
graphics.DrawEllipse(Pen,
center.x-radius+1, center.y-radius+1,
2*radius-2, 2*radius-2);
finally
pen.free;
graphics.free;
end;
end;
procedure TColorWheel2.Paint;
var
w, h : integer;
bitmap : TBitmap;
begin
canvas.brush.Color := clWhite;
canvas.framerect(clientrect);
canvas.Brush.color := clWhite;
canvas.fillrect(rect(0,0,width, height));
w := width - 2 * FBorderSize;
h := height - 2 * FBorderSize;
bitmap := Tbitmap.Create;
try
bitmap.width := w;
bitmap.height := h;
bitmap.pixelformat := pf24bit;
PaintCircle(bitmap);
Canvas.Draw(FBorderSize, FBorderSize, Bitmap);
PaintControls;
finally
Bitmap.free;
end;
end;
procedure TColorWheel2.SetNumControls(const Value: integer);
begin
FNumColors := Value;
end;
procedure TColorWheel2.SetBorderSize(const Value: integer);
begin
FBorderSize := Value;
end;
procedure TColorWheel2.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
Fradius := min(width div 2 - FBorderSize, height div 2 - FBorderSize);
end;
procedure TColorWheel2.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i : integer;
begin
// is the mouse down in the band of the knobs
for i := 0 to FNumColors - 1 do
begin
if PtInRect(FControlBoundRects[i], point(x,y)) then
begin
FSelectedControl := i;
break;
end;
end;
end;
procedure TColorWheel2.MoveBigControl(controlIndex : integer; angle : double);
begin
FHueArray[controlIndex] := FHueArray[controlIndex] + angle;
while FHueArray[controlIndex] > 360 do
FHueArray[controlIndex] := FHueArray[controlIndex] - 360;
while FHueArray[controlIndex] < 0 do
FHueArray[controlIndex] := FHueArray[controlIndex] + 360;
end;
procedure TColorWheel2.HueSaturationAtPoint(positionx, positiony : integer; size : Integer; var hue, sat : double);
var
c, dx, dy, d : double;
begin
c := size / 2;
dx := (positionx - c) / c;
dy := (positiony - c) / c;
d := sqrt(dx*dx + dy*dy);
sat := d;
if d = 0 then
hue := 0
else
begin
hue := Math.ArcCos(dx / d) / 3.1417 / 2;
if dy < 0 then
hue := 1 - hue;
end;
end;
procedure TColorWheel2.MouseMove(Shift: TShiftState; X, Y: Integer);
var
center : TPoint;
w, h : integer;
newAngle, angleDelta : double;
i, diff : integer;
begin
if FSelectedControl <> -1 then
begin
w := width - 2 * FBorderSize;
h := height - 2 * FBorderSize;
center := Point(w div 2, h div 2);
x := x - center.x;
y := y - center.y;
newAngle := getAngle(x, y);
if FSelectedControl = 0 then
begin
FRadius := round(sqrt(x*x + y*y));
FRadius := min(FRadius, min(width div 2 - FBorderSize, height div 2 - FBorderSize));
end;
angleDelta := newAngle - FHueArray[FSelectedControl];
for i := 0 to FNumColors - 1 do
begin
diff := getJoinedControls(FSelectedControl, i);
if diff = 1 then
MoveBigControl(i, angleDelta)
else if diff = -1 then
MoveBigControl(i, -angleDelta);
end;
invalidate;
DoColorsChanged;
end;
end;
procedure TColorWheel2.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
FSelectedControl := -1;
end;
procedure TColorWheel2.SetColorsChanged(const Value: TNotifyEvent);
begin
FColorsChanged := Value;
end;
procedure TColorWheel2.SetSwatchType(const Value: TColorPaletteStyle);
begin
if FSwatchType <> Value then
begin
FSwatchType := Value;
if not (csLoading in componentState) then
begin
case FSwatchType of
tcpsMonochromatic:
begin
FNumColors := 1;
FHueArray[0] := 0;
end;
tcpsComplementary, tcpsFreeForm2:
begin
FNumColors := 2;
FHueArray[0] := 0;
FHueArray[1] := 180;
end;
tcpsAnalogous:
begin
FNumColors := 3;
FHueArray[0] := -20;
FHueArray[1] := 0;
FHueArray[2] := 20;
end;
tcpsTriad, tcpsFreeForm3:
begin
FNumColors := 3;
FHueArray[0] := 0;
FHueArray[1] := 120;
FHueArray[2] := 240;
end;
tcpsSplitComplementary:
begin
FNumColors := 3;
FHueArray[0] := 0;
FHueArray[1] := 160;
FHueArray[2] := 200;
end;
tcpsRectangle, tcpsFreeform4:
begin
FNumColors := 4;
FHueArray[0] := 0;
FHueArray[1] := 45;
FHueArray[2] := 180;
FHueArray[3] := 220;
end;
tcpsSquare:
begin
FNumColors := 4;
FHueArray[0] := 0;
FHueArray[1] := 90;
FHueArray[2] := 180;
FHueArray[3] := 270;
end;
end;
invalidate;
DoColorsChanged;
end;
end;
end;
procedure TColorWheel2.DoColorsChanged;
begin
if assigned(FColorsChanged) then
FColorsChanged(self);
end;
function TColorWheel2.getColor(index: Integer): TColor;
var
hue, sat : double;
c : TRGBTriple;
begin
sat := FRadius / min(width div 2 - FBorderSize, height div 2 - FBorderSize);
hue := FHueArray[index];
result := ConvertHSVToColor(hue, sat, 1.0);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.