text
stringlengths
14
6.51M
unit uimpl; interface uses types, ctypes, sysutils, xlib, x, xutil, xatom; const { MessageBox() Flags } {$EXTERNALSYM MB_OK} MB_OK = $00000000; {$EXTERNALSYM MB_OKCANCEL} MB_OKCANCEL = $00000001; {$EXTERNALSYM MB_ABORTRETRYIGNORE} MB_ABORTRETRYIGNORE = $00000002; {$EXTERNALSYM MB_YESNOCANCEL} MB_YESNOCANCEL = $00000003; {$EXTERNALSYM MB_YESNO} MB_YESNO = $00000004; {$EXTERNALSYM MB_RETRYCANCEL} MB_RETRYCANCEL = $00000005; {$EXTERNALSYM MB_ICONHAND} MB_ICONHAND = $00000010; {$EXTERNALSYM MB_ICONQUESTION} MB_ICONQUESTION = $00000020; {$EXTERNALSYM MB_ICONEXCLAMATION} MB_ICONEXCLAMATION = $00000030; {$EXTERNALSYM MB_ICONASTERISK} MB_ICONASTERISK = $00000040; {$EXTERNALSYM MB_USERICON} MB_USERICON = $00000080; {$EXTERNALSYM MB_ICONWARNING} MB_ICONWARNING = MB_ICONEXCLAMATION; {$EXTERNALSYM MB_ICONERROR} MB_ICONERROR = MB_ICONHAND; {$EXTERNALSYM MB_ICONINFORMATION} MB_ICONINFORMATION = MB_ICONASTERISK; {$EXTERNALSYM MB_ICONSTOP} MB_ICONSTOP = MB_ICONHAND; WS_EX_CONTROLPARENT = $10000; WS_CHILD = $40000000; WS_VISIBLE = $10000000; WM_XBUTTONDOWN = $020B; WM_XBUTTONUP = $020C; WM_XBUTTONDBLCLK = $020D; SW_SHOWNORMAL = 1; SW_SHOWMINIMIZED = 2; SW_SHOWMAXIMIZED = 3; CUSTOM_WIN = 'CustomWindow'; CUSTOM_COMP = 'CustomComponent'; DC_BRUSH = 18; DC_PEN = 19; MR_NONE = 0; // no close MR_OK = 1; // ok close MR_CANCEL = 2; // cancel close MR_CLOSE = 3; // just close DT_TOP = 0; DT_LEFT = 0; DT_CENTER = 1; DT_RIGHT = 2; DT_VCENTER = 4; DT_BOTTOM = 8; DT_WORDBREAK = $10; DT_SINGLELINE = $20; DT_EXPANDTABS = $40; DT_TABSTOP = $80; DT_NOCLIP = $100; DT_EXTERNALLEADING = $200; DT_CALCRECT = $400; DT_NOPREFIX = $800; DT_INTERNAL = $1000; DT_HIDEPREFIX = $00100000; DT_PREFIXONLY = $00200000; type TPoint = Types.TPoint; TRect = Types.TRect; TMouseButton = (mbLeft, mbMiddle, mbRight, mbX1, mbX2); HWND = type LongWord; HFONT = type LongWord; HBITMAP = type LongWord; HDC = type LongWord; UINT = type LongWord; COLORREF=longword; TWinHandleImpl=class private wm_delete_window:TAtom; protected hWindow:HWnd; wParent:TWinHandleImpl; wStyle,wExStyle:cardinal; wText:string; hLeft, hTop, hWidth, hHeight : integer; wBitmap, wMask : HBITMAP; wCursor:TCursor; KeyCursorX, KeyCursorY : integer; // hTrackMouseEvent:TTrackMouseEvent; wTrackingMouse:boolean; wEnabled:boolean; wModalResult:integer; Win: TWindow; GC: TGC; // dc : hdc; // ps : paintstruct; procedure CreateFormStyle; procedure CreateFormWindow; procedure CreateModalStyle; procedure CreateModalWindow; procedure CreateCompStyle; procedure CreateCompWindow; procedure CreatePopupStyle; procedure RegisterMouseLeave; public procedure Show(nCmdShow:integer = SW_SHOWNORMAL);virtual; procedure Hide;virtual; procedure RedrawPerform; procedure SetPosPerform; procedure SetFocusPerform;virtual; procedure CustomPaint;virtual; function SetCapture(hWnd: HWND): HWND; function ReleaseCapture: BOOLEAN; function GetCursorPos(var lpPoint: TPoint): BOOLEAN; function GetClientRect:TRect; procedure BeginPaint; procedure EndPaint; procedure DrawText(var r:TRect; const text:string; font:HFONT; color, bkcolor:cardinal; mode:integer; style:cardinal); procedure Polygon(color, bkcolor:cardinal; Left, Top, Right, Bottom:integer); procedure Polyline(color:cardinal; start, count:integer; Left, Top, Right, Bottom:integer); function ShowModalWindow:integer; procedure CloseModalWindow; procedure EnableWindow; procedure CloseModalPerform; procedure SetFocus; procedure HideKeyCursor; procedure ShowKeyCursor; procedure CreateImagePerform; procedure CustomImagePaint; procedure SetCursor; procedure SizePerform;virtual; procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);virtual; procedure MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);virtual; procedure MouseLeavePerform;virtual; procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual; procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual; procedure MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);virtual; procedure KillFocusPerform(handle:HWND);virtual; procedure ClosePerform;virtual; procedure KeyCharPerform(keychar:cardinal);virtual; procedure CapturePerform(AWindow:HWND);virtual; procedure CalcTextSize(const AText:string; var AWidth, AHeight:integer); property Cursor:TCursor read wCursor write wCursor; end; var crArrow, crHand, crIBeam, crHourGlass, crSizeNS, crSizeWE : TCursor; // will be initialalized fntRegular,fntBold:HFONT; // will be initialalized var MainWinForm:TWinHandleImpl; clBlack, clWhite, clDkGray, clPanelBackground1, clPanelBackground2, clFaceBook1, clFaceBook2 : culong; procedure InitUI; procedure ProcessMessages; procedure FreeUI; implementation var Display: PDisplay; ScreenNum: Integer; ProgName: String; procedure CheckMemory(P: Pointer); begin if P = nil then begin Writeln(ProgName,': Failure Allocating Memory'); Halt(0); end; end; procedure TWinHandleImpl.CreateFormStyle; begin end; procedure GetDC(Win: TWindow;var GC: TGC; FontInfo: PXFontStruct); const DashList: packed array[1..2] of Byte = (12, 24); var ValueMask: Cardinal; Values: TXGCValues; LineWidth: Cardinal; LineStyle: Integer; CapStyle: Integer; JoinStyle: Integer; DashOffset: Integer; ListLength: Integer; begin ValueMask := 0; LineWidth := 1; LineStyle := LineSolid; //LineOnOffDash; CapStyle := CapRound; JoinStyle := JoinRound; DashOffset := 0; ListLength := 2; FillChar(Values, SizeOf(Values), 0); GC := XCreateGC(Display, Win, ValueMask, @Values); XSetFont(Display, GC, FontInfo^.fid); //XSetForeground(Display, GC, green);//XBlackPixel(Display, ScreenNum)); // XSetBackground(Display, GC, grey); XSetLineAttributes(Display, GC, LineWidth, LineStyle, CapStyle, JoinStyle); //XSetDashes(Display, GC, DashOffSet, @DashList, ListLength); end; procedure LoadFont(var FontInfo: PXFontStruct); const FontName: PChar = '9x18'; begin Writeln('Font Struct:', SizeOf(TXFontStruct)); FontInfo := XLoadQueryFont(Display, FontName); if FontInfo = nil then begin Writeln(Progname, ': Cannot open '+FontName+' font.'); Halt(1); end; end; procedure PlaceText(Win: TWindow; GC: TGC; FontInfo: PXFontStruct; WinWidth, WinHeight: Cardinal); const String1: PChar = 'Hi! I''m a window, who are you?'; String2: PChar = 'To terminate program; Press any key'; String3: PChar = 'or button while in this window.'; String4: PChar = 'Screen dimensions:'; var Len1, Len2, Len3, Len4: Integer; Width1, Width2, Width3: Integer; CDHeight, CDWidth, CDDepth: PChar; // array[0..49] of Char; FontHeight: Integer; InitialYOffset, XOffset: Integer; Top, Left: Integer; begin Writeln('#1'); Len1 := StrLen(String1); Len2 := StrLen(String2); Len3 := StrLen(String3); Writeln('#2'); Width1 := XTextWidth(FontInfo, String1, Len1); Width2 := XTextWidth(FontInfo, String2, Len2); Width3 := XTextWidth(FontInfo, String3, Len3); FontHeight := FontInfo^.Ascent + FontInfo^.Descent; XDrawString(Display, Win, GC, (WinWidth - Width1) div 2, FontHeight+10, String1, Len1); Writeln('#2.2 ', Len2, ' ', String2); Left := (WinWidth - Width2); Writeln('#2.2.5 Here'); Left := Left div 2; Top := WinHeight - FontHeight * 2; Writeln('#2.3 Top:', Top, ' Left:', Left); XDrawString(Display, Win, GC, Left, Top, String2, Len2); Writeln('#2.3'); XDrawString(Display, Win, GC, (WinWidth - Width3) div 2, WinHeight - FontHeight, String3, Len3); Writeln('#3'); CDHeight := PChar(Format(' Height = %d pixels', [XDisplayHeight(Display, ScreenNum)])); CDWidth := PChar(Format(' Width = %d pixels', [XDisplayWidth(Display, ScreenNum)])); CDDepth := PChar(Format(' Depth = %d plane(s)', [XDefaultDepth(Display, ScreenNum)])); Len4 := StrLen(String4); Len1 := StrLen(CDHeight); Len2 := StrLen(CDWidth); Len3 := StrLen(CDDepth); Writeln('#4'); InitialYOffset := WinHeight div 2 - FontHeight - FontInfo^.descent; XOffset := WinWidth div 4; XDrawString(Display, Win, GC, XOffset, InitialYOffset, String4, Len4); XDrawString(Display, Win, GC, XOffset, InitialYOffset + FontHeight, CDHeight, Len1); XDrawString(Display, Win, GC, XOffset, InitialYOffset + 2 * FontHeight, CDWidth, Len2); XDrawString(Display, Win, GC, XOffset, InitialYOffset + 3 * FontHeight, CDDepth, Len3); Writeln('#5'); end; procedure PlaceGraphics(Win: TWindow; GC: TGC; WindowWidth, WindowHeight: Cardinal); var X, Y: Integer; Width, Height: Integer; begin Writeln('Window: ', Integer(Win)); Writeln('GC: ', INteger(GC)); Height := WindowHeight div 2; Width := 3 * WindowWidth div 4; X := WindowWidth div 2 - Width div 2; Y := WindowHeight div 2 - Height div 2; //XDrawRectangle(Display, Win, GC, X, Y, Width, Height); XDrawRectangle(Display, Win, GC, 0, 0, WindowWidth-1, WindowHeight-1); end; var // Width, Height: Word; // Left, Top: Integer; BorderWidth: Word = 4; DisplayWidth, DisplayHeight: Word; // IconWidth, IconHeight: Word; WindowNameStr: PChar = 'Basic Window Program'; IconNameStr: PChar = 'basicWin'; IconPixmap: TPixmap; SizeHints: PXSizeHints; SizeList: PXIconSize; WMHints: PXWMHints; ClassHints: PXClassHint; WindowName, IconName: TXTextProperty; Count: Integer; Report: TXEvent; FontInfo: PXFontStruct; DisplayName: PChar = nil; WindowSize: Integer = 0; b0,b1,b2,b3,b4:integer; xcolo,colorcell:TXColor; cmap:TColormap; ArrWinCount:integer=0; ArrWin:array[1..10000] of record Win:TWindow; Obj:TWinHandleImpl; end; procedure SetWinObj(Win:TWindow; Obj:TWinHandleImpl); begin inc(ArrWinCount); ArrWin[ArrWinCount].Win:=Win; ArrWin[ArrWinCount].Obj:=Obj; end; function GetWinObj(Win:TWindow):TWinHandleImpl; var i:integer; begin i:=1; while(i<=ArrWinCount) do begin if ArrWin[i].Win=Win then begin result:=ArrWin[i].Obj; exit; end; inc(i); end; result:=nil; end; procedure TWinHandleImpl.CreateFormWindow; begin Win := XCreateSimpleWindow(Display, XRootWindow(Display, ScreenNum), hLeft, hTop, hWidth, hHeight, BorderWidth, XBlackPixel(Display, ScreenNum), XWhitePixel(Display, ScreenNum)); SetWinObj(Win, self); SizeHints^.flags := PPosition or PSize or PMinSize; SizeHints^.min_width := 400; SizeHints^.min_height:= 300; if XStringListToTextProperty(@WindowNameStr, 1, @WindowName) = 0 then begin Writeln(Progname, ': structure allocation for window name failed.'); Halt(1); end; if XStringListToTextProperty(@IconNameStr, 1, @IconName) = 0 then begin Writeln(Progname, ': structure allocqation for icon name failed.'); Halt(1); end; WMHints^.flags := StateHint or InputHint or IconWindowHint; WMHints^.initial_state := NormalState; WMHints^.input := 1; //True; //WMHints^.icon_pixmap := IconPixmap; WMHints^.icon_window := IconPixmap; WMHints^.icon_x:=0; WMHints^.icon_y:=0; ClassHints^.res_name := PChar(ProgName); ClassHints^.res_class := 'BasicWin!'; XSetWMProperties(Display, Win, @WindowName, @IconName, nil, 0, SizeHints, WMHints, ClassHints); XSelectInput(Display, Win, ExposureMask or KeyPressMask or ButtonPressMask or ButtonReleaseMask or StructureNotifyMask or PointerMotionMask or LeaveWindowMask); LoadFont(FontInfo); GetDC(win, GC, FontInfo); XMapWindow(Display, Win); end; procedure InitUI; begin ProgName := ParamStr(0); // ProgName := 'BasicWin'; //JJS Remove when 80999 is fixed. SizeHints := XAllocSizeHints; CheckMemory(SizeHints); WMHints := XAllocWMHints; CheckMemory(WMHints); ClassHints := XAllocClassHint; CheckMemory(ClassHints); Display := XOpenDisplay(DisplayName); if Display = nil then begin Writeln(ProgName,': cannot connect to XServer', XDisplayName(DisplayName)); Halt(1); end; ScreenNum := XDefaultScreen(Display); DisplayWidth := XDisplayWidth(Display, ScreenNum); DisplayHeight := XDisplayHeight(Display, ScreenNum); //Left := 100; Top := 200; //Width := DisplayWidth div 4; Height := DisplayHeight div 4; if XGetIconSizes(Display, XRootWindow(Display, ScreenNum), @SizeList, @Count) = 0 then Writeln('Window Manager didn''t set icon sizes - using default') else begin end; cmap:=DefaultColormap(Display, ScreenNum); XAllocNamedColor(display,cmap,'white',@colorcell,@xcolo); clWhite:=colorcell.pixel; XAllocNamedColor(display,cmap,'black',@colorcell,@xcolo); clBlack:=colorcell.pixel; XParseColor(display, cmap, '#808080', @colorcell); XAllocColor(display,cmap,@colorcell); clDkGray:=colorcell.pixel; XParseColor(display, cmap, '#3B5998', @colorcell); XAllocColor(display,cmap,@colorcell); clFaceBook1:=colorcell.pixel; XParseColor(display, cmap, '#8b9dc3', @colorcell); XAllocColor(display,cmap,@colorcell); clFaceBook2:=colorcell.pixel; XParseColor(display, cmap, '#eeeeee', @colorcell); XAllocColor(display,cmap,@colorcell); clPanelBackground1:=colorcell.pixel; XParseColor(display, cmap, '#d4d0c8', @colorcell); XAllocColor(display,cmap,@colorcell); clPanelBackground2:=colorcell.pixel; (* XAllocNamedColor(display,cmap,'salmon',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'wheat',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'red',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'blue',@colorcell,@xcolo); green:=colorcell.pixel; XAllocNamedColor(display,cmap,'green',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'cyan',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'orange',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'purple',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'yellow',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'pink',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'brown',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'grey',@colorcell,@xcolo); grey:=colorcell.pixel; XAllocNamedColor(display,cmap,'turquoise',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'gold',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'magenta',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'navy',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'tan',@colorcell,@xcolo); XAllocNamedColor(display,cmap,'violet',@colorcell,@xcolo); *) crArrow:=XCreateFontCursor(display, 2); crHand:=XCreateFontCursor(display, 60); crIBeam:=XCreateFontCursor(display, 152); crHourGlass:=XCreateFontCursor(display, 26); crSizeNS:=XCreateFontCursor(display, 116); crSizeWE:=XCreateFontCursor(display, 108); end; procedure MouseCustomProc(obj:TWinHandleImpl; _type:cint; button:cuint; x, y:cint); var b:TMouseButton; begin if(button=1)or(button=2)or(button=3) then begin if button=1 then b:=mbLeft; if button=2 then b:=mbMiddle; if button=3 then b:=mbRight; if _type = ButtonPress then begin Obj.MouseButtonDownPerform(b, 0, x, y); end; if _type = ButtonRelease then begin Obj.MouseButtonUpPerform(b, 0, x, y); end; end; if (_type = ButtonPress)and(button=4) then begin Obj.MouseWheelPerform(0, 1, x, y); end; if (_type = ButtonPress)and(button=5) then begin Obj.MouseWheelPerform(0, -1, x, y); end; end; procedure ProcessMessages; var Obj:TWinHandleImpl; k:TKeySym; begin while True do begin XNextEvent(Display, @Report); case Report._type of Expose: begin //Writeln('Expose'); if Report.xexpose.count = 0 then begin Obj:=GetWinObj(report.xexpose.window); Obj.CustomPaint; // PlaceText(Obj.Win, Obj.GC, FontInfo, Obj.hWidth, Obj.hHeight); // PlaceGraphics(Obj.Win, Obj.GC, Obj.hWidth, Obj.hHeight); end; end; ConfigureNotify: begin //Writeln('Configure Notify'); Obj:=GetWinObj(report.xconfigure.window); Obj.hWidth := Report.xconfigure.Width; Obj.hHeight := Report.xconfigure.Height; Obj.SizePerform; //Writeln(' Width: ', Obj.hWidth); //Writeln(' Height: ', Obj.hHeight); (* if (width <= SizeHints^.min_width) and (Height <= SizeHints^.min_height) then WindowSize := TOO_SMALL else WindowSize := BIG_ENOUGH;*) end; ButtonPress: begin //Writeln('ButtonPress ',Report.xbutton.button,' ',Report.xbutton.window); Obj:=GetWinObj(report.xbutton.window); MouseCustomProc(Obj, Report._type, Report.xbutton.button, Report.xbutton.x, Report.xbutton.y); end; ButtonRelease: begin //Writeln('ButtonRelease ',Report.xbutton.button,' ',Report.xbutton.window); Obj:=GetWinObj(report.xbutton.window); MouseCustomProc(Obj, Report._type, Report.xbutton.button, Report.xbutton.x, Report.xbutton.y); end; LeaveNotify:begin //writeln('mouse leave'); Obj:=GetWinObj(report.xmotion.window); Obj.MouseLeavePerform; end; MotionNotify:begin //writeln('mouse move',report.xmotion.x,' ',report.xmotion.y); Obj:=GetWinObj(report.xmotion.window); Obj.MouseMovePerform(0,report.xmotion.x,report.xmotion.y); end; KeyPress: begin //Writeln('KeyProcess'); case report.xkey.keycode of 22:k:=8; // vk_back else k:=XLookupKeysym(@report.xkey, 0); end; Obj:=GetWinObj(report.xkey.window); Obj.KeyCharPerform(k); (* XUnloadFont(Display, FontInfo^.fid); XFreeGC(Display, Obj.GC); XCloseDisplay(Display); halt(0);*) end; ClientMessage:begin break; // if Report.xclient.data.l[0] = wmDeleteMessage // then begin // XCloseDisplay(Display); // end; end else end; end; Writeln('End.'); end; procedure FreeUI; begin end; procedure TWinHandleImpl.CreateCompStyle; begin end; procedure TWinHandleImpl.CreateCompWindow; begin Win := XCreateSimpleWindow(Display, wParent.Win, hLeft, hTop, hWidth, hHeight, 0, XBlackPixel(Display, ScreenNum), XWhitePixel(Display, ScreenNum)); SetWinObj(Win, self); XSelectInput(Display, Win, ExposureMask or KeyPressMask or ButtonPressMask or ButtonReleaseMask or PointerMotionMask or LeaveWindowMask); GetDC(win, GC, FontInfo); XMapWindow(Display, Win); end; procedure TWinHandleImpl.Show(nCmdShow:integer=SW_SHOWNORMAL); begin XMapWindow(Display, Win); // ShowWindow(hWindow, nCmdShow); end; procedure TWinHandleImpl.Hide; begin XUnMapWindow(Display, Win); // Show(SW_HIDE) end; procedure TWinHandleImpl.RedrawPerform; //var r:TRect; begin //r:=GetClientRect; // XFillRectangle(Display, win, GC, r.Left, r.Top, r.Width, r.Height); XClearWindow(Display, win); CustomPaint; // InvalidateRect(hWindow, nil, TRUE); end; procedure TWinHandleImpl.SetPosPerform; begin XMoveResizeWindow(display, win, hLeft, hTop, hWidth, hHeight); end; procedure TWinHandleImpl.RegisterMouseLeave; begin if not wTrackingMouse then begin wTrackingMouse:=true; (* hTrackMouseEvent.cbSize:=SizeOf(hTrackMouseEvent); hTrackMouseEvent.dwFlags:=TME_LEAVE or TME_HOVER; hTrackMouseEvent.hwndTrack:=hWindow; hTrackMouseEvent.dwHoverTime:=HOVER_DEFAULT; if not TrackMouseEvent(hTrackMouseEvent) then wTrackingMouse:=false*) end; end; // custompaint support function TWinHandleImpl.GetClientRect:TRect; begin result:=rect(0,0,hWidth,hHeight); end; procedure TWinHandleImpl.BeginPaint; begin end; procedure TWinHandleImpl.EndPaint; begin end; procedure TWinHandleImpl.DrawText(var r:TRect; const text:string; font:HFONT; color, bkcolor:cardinal; mode:integer; style:cardinal); var FontHeight,Width1:integer; L, B:cardinal; begin Width1 := XTextWidth(FontInfo, pchar(text), Length(Text)); FontHeight := FontInfo^.Ascent + FontInfo^.Descent; L:=r.Left; B:=r.Bottom; if (style and DT_CENTER) = DT_CENTER then L:=r.Left+(r.Right-r.Left) div 2-Width1 div 2; if (style and DT_VCENTER) = DT_VCENTER then B:=r.Top+(r.Bottom-r.Top) div 2+FontHeight div 2 - 3; XSetForeground(Display, GC, color); XSetBackground(Display, GC, bkcolor); XDrawString(Display, Win, GC, L, B, pchar(text), Length(Text)); end; procedure TWinHandleImpl.Polygon(color, bkcolor:cardinal; Left, Top, Right, Bottom:integer); begin XSetForeground(Display, GC, bkcolor); XFillRectangle(Display, Win, GC, Left, Top, Right, Bottom); XSetForeground(Display, GC, color); XDrawRectangle(Display, Win, GC, Left, Top, Right, Bottom); end; procedure TWinHandleImpl.Polyline(color:cardinal; start, count:integer; Left, Top, Right, Bottom:integer); var p : array[-1..4] of txpoint; begin XSetForeground(Display, GC, color); p[-1].X:=Left; p[-1].Y:=Bottom; p[0].X:=Left; p[0].Y:=Top; p[1].X:=Right; p[1].Y:=Top; p[2].X:=Right; p[2].Y:=Bottom; p[3].X:=Left; p[3].Y:=Bottom; p[4].X:=Left; p[4].Y:=Top; XDrawLines(Display, Win, GC, @p[start], count, CoordModeOrigin); end; function TWinHandleImpl.GetCursorPos(var lpPoint: TPoint): BOOLEAN; var p:TWinHandleImpl; var rx, ry, x, y, m:integer; chld, root:TWindow; begin // disp:=display^; // root:=XRootWindow(Display, ScreenNum); // chld:=win; XQueryPointer(display, win, @root, @chld, @rx, @ry, @x, @y, @m); // XTranslateCoordinates(display, win, XRootWindow(Display, ScreenNum), lpPoint.X, lpPoint.Y, @x, @y, @chld); lpPoint.X:=rx; lpPoint.Y:=ry; writeln('get ',rX,' ',rY,' ',X,' ',Y); (* p:=wParent; lpPoint.x:=hLeft+lpPoint.x; lpPoint.y:=hTop+lpPoint.y; while p<>nil do begin lpPoint.x:=lpPoint.x+p.hLeft; lpPoint.y:=lpPoint.y+p.hTop; p:=p.wParent; end; *) result:=true; //windows.GetCursorPos(lpPoint); end; function TWinHandleImpl.SetCapture(hWnd: HWND): HWND; begin // result:=windows.SetCapture(hWnd); XGrabPointer(display, win, false, PointerMotionMask or LeaveWindowMask or ButtonReleaseMask, GrabModeAsync, GrabModeAsync, win, none, CurrentTime); result:=win; end; function TWinHandleImpl.ReleaseCapture: BOOLEAN; begin // result:=windows.ReleaseCapture; XUngrabPointer(display, CurrentTime); result:=true end; function TWinHandleImpl.ShowModalWindow:integer; begin XMapWindow(display, win); wm_delete_window := XInternAtom(display, 'WM_DELETE_WINDOW', true); XSetWMProtocols(display, win, @wm_delete_window, 1); ProcessMessages; XUnmapWindow(display, win); //XFreeGC(display, GC); //XDestroyWindow(display, win); (* // result:=inherited ShowModal; wParent.wEnabled:=false; windows.EnableWindow(wParent.hWindow, FALSE); Show; // ProcessMessages; wModalResult:=MR_NONE; repeat ret:=GetMessage(AMessage, 0, 0, 0); if integer(ret) = -1 then break; TranslateMessage(AMessage); DispatchMessage(AMessage) until not ret and (wModalResult<>MR_NONE); result:=wModalResult*) end; procedure TWinHandleImpl.CloseModalWindow; begin //PostMessage(hWindow, wm_close, 0, 0); end; procedure TWinHandleImpl.EnableWindow; begin // windows.EnableWindow(hWindow, TRUE); end; procedure TWinHandleImpl.CloseModalPerform; begin (* if wModalResult=MR_NONE then wModalResult:=MR_CLOSE; PostMessage(hWindow, WM_QUIT, 0, 0); wParent.wEnabled:=true; windows.EnableWindow(wParent.hWindow, TRUE);*) end; procedure TWinHandleImpl.SetFocus; //var h:HWND; begin XSetInputFocus(display, win, RevertToParent, 0); (* h:=GetFocus; if h<>0 then SendMessage(h, WM_KILLFOCUS, 0, 0); windows.SetFocus(hWindow);*) SetFocusPerform; end; procedure TWinHandleImpl.SetFocusPerform; begin end; procedure TWinHandleImpl.HideKeyCursor; begin // HideCaret(hWindow); end; procedure TWinHandleImpl.ShowKeyCursor; begin (* HideCaret(hWindow); CreateCaret(hWindow, 0, 2, 17); SetCaretPos(KeyCursorX, KeyCursorY); ShowCaret(hWindow);*) end; procedure TWinHandleImpl.CreateImagePerform; begin // wBitmap:=LoadBitmap(system.MainInstance, 'BAD'); //todo deleteobject // wMask:=CreateBitmapMask(wBitmap, $ffffff{clWhite}); end; procedure TWinHandleImpl.CustomImagePaint; //var //img : hdc; begin (* BeginPaint; img:=CreateCompatibleDC(dc); SelectObject(img, wMask); BitBlt(dc,0,0,50,50,img,0,0,SRCAND); SelectObject(img, wBitmap); BitBlt(dc,0,0,50,50,img,0,0,SRCPAINT); DeleteDC(img); EndPaint; *) end; procedure TWinHandleImpl.SetCursor; begin //windows.SetCursor(wCursor); XDefineCursor(display, win, wCursor); end; procedure TWinHandleImpl.CreateModalStyle; begin (* wExStyle:=WS_EX_COMPOSITED or WS_EX_LAYERED or WS_EX_DLGMODALFRAME; wStyle:=WS_BORDER or WS_POPUP or WS_SYSMENU or WS_DLGFRAME or WS_SIZEBOX or WS_MINIMIZEBOX or WS_MAXIMIZEBOX; *) end; procedure TWinHandleImpl.CreateModalWindow; var attr:TXSetWindowAttributes; modal,state:TAtom; hints:TXSizeHints; begin state := XInternAtom(display, '_NET_WM_STATE', True); modal := XInternAtom(display, '_NET_WM_STATE_MODAL', True); attr.background_pixel := XWhitePixel(Display, ScreenNum); attr.override_redirect:=1; Win := XCreateWindow(Display, XRootWindow(Display, ScreenNum), hLeft, hTop, hWidth, hHeight, 0, DefaultDepth(display,ScreenNum), InputOutput, DefaultVisual(display,ScreenNum), CWBackPixel or CWOverrideRedirect, @attr); // wm_delete_window := XInternAtom(display, 'WM_DELETE_WINDOW', true); //XSetWMProtocols(display, win, @wm_delete_window, 1); (* no resize *) //XUnmapWindow(Display, win); hints.flags:=PSize or PMinsize or PMaxSize; hints.min_width:=hWidth; hints.base_width:=hWidth; hints.max_width:=hWidth; hints.min_height:=hHeight; hints.base_height:=hHeight; hints.max_height:=hHeight; XsetWMNormalHints(Display, win, @hints); XChangeProperty(display, win, state, XA_ATOM, 32, PropModeReplace, @modal, 1); SetWinObj(Win, self); XStoreName(Display, Win, pchar('Modal')); XSetTransientForHint(display, win, MainWinForm.win); XSelectInput(Display, Win, ExposureMask or KeyPressMask or ButtonPressMask or ButtonReleaseMask); GetDC(win, GC, FontInfo); //XMapRaised(Display, Win); (* hWindow := CreateWindowEx(wExStyle, CUSTOM_WIN, pchar(wText), wStyle, hLeft, hTop, hWidth, hHeight, wParent.hWindow, 0, system.MainInstance, nil); SetWindowLongPtr(hWindow, GWL_USERDATA, self); *) end; procedure TWinHandleImpl.CreatePopupStyle; begin // wExStyle:=WS_EX_COMPOSITED or WS_EX_LAYERED; // wStyle:=WS_POPUP; end; procedure TWinHandleImpl.CustomPaint; begin end; procedure TWinHandleImpl.SizePerform; begin end; procedure TWinHandleImpl.MouseMovePerform(AButtonControl:cardinal; x,y:integer); begin end; procedure TWinHandleImpl.MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer); begin end; procedure TWinHandleImpl.MouseLeavePerform; begin RedrawPerform; end; procedure TWinHandleImpl.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin end; procedure TWinHandleImpl.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin end; procedure TWinHandleImpl.MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin end; procedure TWinHandleImpl.KillFocusPerform(handle:HWND); begin end; procedure TWinHandleImpl.ClosePerform; begin end; procedure TWinHandleImpl.KeyCharPerform(keychar:cardinal); begin end; procedure TWinHandleImpl.CapturePerform(AWindow:HWND); begin end; procedure TWinHandleImpl.CalcTextSize(const AText:string; var AWidth, AHeight:integer); begin AWidth := XTextWidth(FontInfo, pchar(AText), Length(AText)); AHeight := FontInfo^.Ascent + FontInfo^.Descent; end; end.
// 移植自Delphi组件,在lcl中算第三方组件了吧 unit Gauges; interface uses SysUtils, Classes, Graphics, Controls, StdCtrls, Types; type TGaugeKind = (gkText, gkHorizontalBar, gkVerticalBar, gkPie, gkNeedle); TGauge = class(TGraphicControl) private FMinValue: Longint; FMaxValue: Longint; FCurValue: Longint; FKind: TGaugeKind; FShowText: Boolean; FBorderStyle: TBorderStyle; FForeColor: TColor; FBackColor: TColor; procedure PaintBackground(AnImage: TBitmap); procedure PaintAsText(AnImage: TBitmap; PaintRect: TRect); procedure PaintAsNothing(AnImage: TBitmap; PaintRect: TRect); procedure PaintAsBar(AnImage: TBitmap; PaintRect: TRect); procedure PaintAsPie(AnImage: TBitmap; PaintRect: TRect); procedure PaintAsNeedle(AnImage: TBitmap; PaintRect: TRect); procedure SetGaugeKind(Value: TGaugeKind); procedure SetShowText(Value: Boolean); procedure SetBorderStyle(Value: TBorderStyle); procedure SetForeColor(Value: TColor); procedure SetBackColor(Value: TColor); procedure SetMinValue(Value: Longint); procedure SetMaxValue(Value: Longint); procedure SetProgress(Value: Longint); function GetPercentDone: Longint; protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure AddProgress(Value: Longint); property PercentDone: Longint read GetPercentDone; published property Align; property Anchors; property BackColor: TColor read FBackColor write SetBackColor default clWhite; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Color; property Constraints; property Enabled; property ForeColor: TColor read FForeColor write SetForeColor default clBlack; property Font; property Kind: TGaugeKind read FKind write SetGaugeKind default gkHorizontalBar; property MinValue: Longint read FMinValue write SetMinValue default 0; property MaxValue: Longint read FMaxValue write SetMaxValue default 100; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property Progress: Longint read FCurValue write SetProgress; property ShowHint; property ShowText: Boolean read FShowText write SetShowText default True; property Visible; end; implementation const SOutOfRange = 'Value must be between %d and %d'; type TBltBitmap = class(TBitmap) procedure MakeLike(ATemplate: TBitmap); end; { TBltBitmap } procedure TBltBitmap.MakeLike(ATemplate: TBitmap); begin Width := ATemplate.Width; Height := ATemplate.Height; Canvas.Brush.Color := clWindowFrame; Canvas.Brush.Style := bsSolid; Canvas.FillRect(Rect(0, 0, Width, Height)); end; { This function solves for x in the equation "x is y% of z". } function SolveForX(Y, Z: Longint): Longint; begin Result := Longint(Trunc( Z * (Y * 0.01) )); end; { This function solves for y in the equation "x is y% of z". } function SolveForY(X, Z: Longint): Longint; begin if Z = 0 then Result := 0 else Result := Longint(Trunc( (X * 100.0) / Z )); end; { TGauge } constructor TGauge.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csFramed, csOpaque]; { default values } FMinValue := 0; FMaxValue := 100; FCurValue := 0; FKind := gkHorizontalBar; FShowText := True; FBorderStyle := bsSingle; FForeColor := clBlack; FBackColor := clWhite; Width := 100; Height := 100; end; function TGauge.GetPercentDone: Longint; begin Result := SolveForY(FCurValue - FMinValue, FMaxValue - FMinValue); end; procedure TGauge.Paint; var TheImage: TBitmap; OverlayImage: TBltBitmap; PaintRect: TRect; begin with Canvas do begin TheImage := TBitmap.Create; try TheImage.Height := Height; TheImage.Width := Width; PaintBackground(TheImage); PaintRect := ClientRect; if FBorderStyle = bsSingle then InflateRect(PaintRect, -1, -1); OverlayImage := TBltBitmap.Create; try OverlayImage.MakeLike(TheImage); PaintBackground(OverlayImage); case FKind of gkText: PaintAsNothing(OverlayImage, PaintRect); gkHorizontalBar, gkVerticalBar: PaintAsBar(OverlayImage, PaintRect); gkPie: PaintAsPie(OverlayImage, PaintRect); gkNeedle: PaintAsNeedle(OverlayImage, PaintRect); end; TheImage.Canvas.CopyMode := cmSrcInvert; TheImage.Canvas.Draw(0, 0, OverlayImage); TheImage.Canvas.CopyMode := cmSrcCopy; if ShowText then PaintAsText(TheImage, PaintRect); finally OverlayImage.Free; end; Canvas.CopyMode := cmSrcCopy; Canvas.Draw(0, 0, TheImage); finally TheImage.Destroy; end; end; end; procedure TGauge.PaintBackground(AnImage: TBitmap); var ARect: TRect; begin with AnImage.Canvas do begin CopyMode := cmBlackness; ARect := Rect(0, 0, Width, Height); CopyRect(ARect, Animage.Canvas, ARect); CopyMode := cmSrcCopy; end; end; procedure TGauge.PaintAsText(AnImage: TBitmap; PaintRect: TRect); var S: string; X, Y: Integer; OverRect: TBltBitmap; begin OverRect := TBltBitmap.Create; try OverRect.MakeLike(AnImage); PaintBackground(OverRect); S := Format('%d%%', [PercentDone]); with OverRect.Canvas do begin Brush.Style := bsClear; Font := Self.Font; Font.Color := clWhite; with PaintRect do begin X := (Right - Left + 1 - TextWidth(S)) div 2; Y := (Bottom - Top + 1 - TextHeight(S)) div 2; end; TextRect(PaintRect, X, Y, S); end; AnImage.Canvas.CopyMode := cmSrcInvert; AnImage.Canvas.Draw(0, 0, OverRect); finally OverRect.Free; end; end; procedure TGauge.PaintAsNothing(AnImage: TBitmap; PaintRect: TRect); begin with AnImage do begin Canvas.Brush.Color := BackColor; Canvas.FillRect(PaintRect); end; end; procedure TGauge.PaintAsBar(AnImage: TBitmap; PaintRect: TRect); var FillSize: Longint; W, H: Integer; begin W := PaintRect.Right - PaintRect.Left + 1; H := PaintRect.Bottom - PaintRect.Top + 1; with AnImage.Canvas do begin Brush.Color := BackColor; FillRect(PaintRect); Pen.Color := ForeColor; Pen.Width := 1; Brush.Color := ForeColor; case FKind of gkHorizontalBar: begin FillSize := SolveForX(PercentDone, W); if FillSize > W then FillSize := W; if FillSize > 0 then FillRect(Rect(PaintRect.Left, PaintRect.Top, FillSize, H)); end; gkVerticalBar: begin FillSize := SolveForX(PercentDone, H); if FillSize >= H then FillSize := H - 1; FillRect(Rect(PaintRect.Left, H - FillSize, W, H)); end; end; end; end; procedure TGauge.PaintAsPie(AnImage: TBitmap; PaintRect: TRect); var MiddleX, MiddleY: Integer; Angle: Double; W, H: Integer; begin W := PaintRect.Right - PaintRect.Left; H := PaintRect.Bottom - PaintRect.Top; if FBorderStyle = bsSingle then begin Inc(W); Inc(H); end; with AnImage.Canvas do begin Brush.Color := Color; FillRect(PaintRect); Brush.Color := BackColor; Pen.Color := ForeColor; Pen.Width := 1; Ellipse(PaintRect.Left, PaintRect.Top, W, H); if PercentDone > 0 then begin Brush.Color := ForeColor; MiddleX := W div 2; MiddleY := H div 2; Angle := (Pi * ((PercentDone / 50) + 0.5)); Pie(PaintRect.Left, PaintRect.Top, W, H, Integer(Round(MiddleX * (1 - Cos(Angle)))), Integer(Round(MiddleY * (1 - Sin(Angle)))), MiddleX, 0); end; end; end; procedure TGauge.PaintAsNeedle(AnImage: TBitmap; PaintRect: TRect); var MiddleX: Integer; Angle: Double; X, Y, W, H: Integer; begin with PaintRect do begin X := Left; Y := Top; W := Right - Left; H := Bottom - Top; if FBorderStyle = bsSingle then begin Inc(W); Inc(H); end; end; with AnImage.Canvas do begin Brush.Color := Color; FillRect(PaintRect); Brush.Color := BackColor; Pen.Color := ForeColor; Pen.Width := 1; Pie(X, Y, W, H * 2 - 1, X + W, PaintRect.Bottom - 1, X, PaintRect.Bottom - 1); MoveTo(X, PaintRect.Bottom); LineTo(X + W, PaintRect.Bottom); if PercentDone > 0 then begin Pen.Color := ForeColor; MiddleX := Width div 2; MoveTo(MiddleX, PaintRect.Bottom - 1); Angle := (Pi * ((PercentDone / 100))); LineTo(Integer(Round(MiddleX * (1 - Cos(Angle)))), Integer(Round((PaintRect.Bottom - 1) * (1 - Sin(Angle))))); end; end; end; procedure TGauge.SetGaugeKind(Value: TGaugeKind); begin if Value <> FKind then begin FKind := Value; Refresh; end; end; procedure TGauge.SetShowText(Value: Boolean); begin if Value <> FShowText then begin FShowText := Value; Refresh; end; end; procedure TGauge.SetBorderStyle(Value: TBorderStyle); begin if Value <> FBorderStyle then begin FBorderStyle := Value; Refresh; end; end; procedure TGauge.SetForeColor(Value: TColor); begin if Value <> FForeColor then begin FForeColor := Value; Refresh; end; end; procedure TGauge.SetBackColor(Value: TColor); begin if Value <> FBackColor then begin FBackColor := Value; Refresh; end; end; procedure TGauge.SetMinValue(Value: Longint); begin if Value <> FMinValue then begin if Value > FMaxValue then if not (csLoading in ComponentState) then raise EInvalidOperation.CreateFmt(SOutOfRange, [-MaxInt, FMaxValue - 1]); FMinValue := Value; if FCurValue < Value then FCurValue := Value; Refresh; end; end; procedure TGauge.SetMaxValue(Value: Longint); begin if Value <> FMaxValue then begin if Value < FMinValue then if not (csLoading in ComponentState) then raise EInvalidOperation.CreateFmt(SOutOfRange, [FMinValue + 1, MaxInt]); FMaxValue := Value; if FCurValue > Value then FCurValue := Value; Refresh; end; end; procedure TGauge.SetProgress(Value: Longint); var TempPercent: Longint; begin TempPercent := GetPercentDone; { remember where we were } if Value < FMinValue then Value := FMinValue else if Value > FMaxValue then Value := FMaxValue; if FCurValue <> Value then begin FCurValue := Value; if TempPercent <> GetPercentDone then { only refresh if percentage changed } Refresh; end; end; procedure TGauge.AddProgress(Value: Longint); begin Progress := FCurValue + Value; Refresh; end; end.
{ File: HIToolbox/IBCarbonRuntime.h Contains: Nib support for Carbon Version: HIToolbox-219.4.81~2 Copyright: © 2000-2005 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit IBCarbonRuntime; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,Quickdraw,Menus,CFString,CFBundle,MacWindows,ControlDefinitions; {$ALIGN POWER} const kIBCarbonRuntimeCantFindNibFile = -10960; kIBCarbonRuntimeObjectNotOfRequestedType = -10961; kIBCarbonRuntimeCantFindObject = -10962; { ----- typedef ------ } type IBNibRef = ^SInt32; { an opaque 32-bit type } { ----- Create & Dispose NIB References ------ } { * CreateNibReference() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateNibReference( inNibName: CFStringRef; var outNibRef: IBNibRef ): OSStatus; external name '_CreateNibReference'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreateNibReferenceWithCFBundle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateNibReferenceWithCFBundle( inBundle: CFBundleRef; inNibName: CFStringRef; var outNibRef: IBNibRef ): OSStatus; external name '_CreateNibReferenceWithCFBundle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeNibReference() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeNibReference( inNibRef: IBNibRef ); external name '_DisposeNibReference'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { ----- Window ------ } { * CreateWindowFromNib() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateWindowFromNib( inNibRef: IBNibRef; inName: CFStringRef; var outWindow: WindowRef ): OSStatus; external name '_CreateWindowFromNib'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { ----- Menu -----} { * CreateMenuFromNib() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateMenuFromNib( inNibRef: IBNibRef; inName: CFStringRef; var outMenuRef: MenuRef ): OSStatus; external name '_CreateMenuFromNib'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { ----- MenuBar ------} { * CreateMenuBarFromNib() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateMenuBarFromNib( inNibRef: IBNibRef; inName: CFStringRef; var outMenuBar: Handle ): OSStatus; external name '_CreateMenuBarFromNib'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetMenuBarFromNib() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetMenuBarFromNib( inNibRef: IBNibRef; inName: CFStringRef ): OSStatus; external name '_SetMenuBarFromNib'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) end.
unit OSFuncHelper; interface uses SysUtils, Classes, Windows, SysConst, AnsiStrings, Registry, SyncObjs, DataHelper; const c_SystemSays = 'Система каже:'; c_ObjectSays = 'Об''єкт каже:'; c_Warning = 'Warning'; c_Error = 'Error'; sc_FallenOnError = ' упав, через помилку:'; sc_StartsItsWork=' починає роботу...'; sc_FinishedItsWork=' завершив роботу...'; cs_ErrorInProcessor = ': сталася помилка в обробнику '; cs_ReportedAnError = ' повідомило про помилку... '; sc_CantReadEnvironmentVariable = 'не вдалося прочитати змінну середовища:'; cs_CantAddNetworkShare = 'не вдалося під''єднати мережеву папку'; cs_CantRemoveNetworkShare = 'не вдалося від''єднати мережеву папку'; cs_CantLoadLibrary = 'не вдалося завантажити бібліотеку'; cs_CantUnloadLibrary = 'не вдалося вивантажити бібліотеку'; cs_CantGetLibraryHandle = 'Не вдалося отримати важіль на бібіліотеку'; cs_WillTryToLoadIt = 'спробую її завантажити'; cs_CantGetProcAddress = 'Не вдалося отримати адресу процедури'; //cs_IsWow64ProcessFailed = 'Функція IsWow64Process відмовила'; cs_Function = 'Функція'; cs_fFailed = 'відмовила'; cs_Returned = 'повернуло'; cs_fReturned = 'повернула'; cs_CantOpenRegKey = 'не вдалося відкрити ключ реєстра'; cs_CantWriteRegValue = 'не вдалося записати змінну в реестр'; cs_ThisDir = '.'; cs_SuperiorDir = '..'; cs_AllFilesMask = '*'; // Ascii-коди клавіш...: ci_SpaceKey = 32; ci_EnterKey = 13; c_EmergencySleepTime = 5000; // при неочікуваних помилках перед продовженням роботи, мс c_WaitForGoodWindSleepTime = 7000; COPY_FILE_ALLOW_DECRYPTED_DESTINATION = $00000008; PROCESS_QUERY_LIMITED_INFORMATION = $1000; STATUS_SUCCESS = 0; // wProductType: VER_NT_WORKSTATION = $0000001; VER_NT_DOMAIN_CONTROLLER = $0000002; VER_NT_SERVER = $0000003; // wSuiteMask: VER_SUITE_WH_SERVER = $00008000; VER_SUITE_TERMINAL = $00000010; VER_SUITE_STORAGE_SERVER = $00002000; VER_SUITE_SMALLBUSINESS_RESTRICTED = $00000020; VER_SUITE_SMALLBUSINESS = $00000001; VER_SUITE_SINGLEUSERTS = $00000100; VER_SUITE_PERSONAL = $00000200; VER_SUITE_EMBEDDEDNT = $00000040; VER_SUITE_ENTERPRISE = $00000002; VER_SUITE_DATACENTER = $00000080; VER_SUITE_COMPUTE_SERVER = $00004000; VER_SUITE_BLADE = $00000400; VER_SUITE_BACKOFFICE = $00000004; cs_Advapi32Name = 'advapi32.dll'; cs_RegGetValueProcName = {$IFDEF UNICODE}'RegGetValueW'{$ELSE}'RegGetValueA'{$ENDIF}; MB_TIMEDOUT = 32000; MB_AllMessageBoxButtonsMask = Windows.MB_TYPEMASK; // $0F; MB_AllMessageBoxIconsMask = Windows.MB_ICONMASK; // $F0; MB_AllMessageBoxWndTypeMask = $00FF0000; ci_DefOkMsgBoxType = MB_OK or MB_TOPMOST; ic_MessageSpeedTimeUnit = 1000; // 1000 мс. type TNTSTATUS = DWord; // --- Описи типів функцій і процедур що не знайдені у модулі Windows.pas --- //TIsWow64Process = function(hProcess: THandle; var Wow64Process: BOOL): BOOL; // stdcall; // ntdll.dll TRtlGetVersion = function( Var lpVersionInformation:Windows.RTL_OSVERSIONINFOEXW): TNTSTATUS; stdcall; //можливо cdecl?.. в NTOSKrnl.exe може й так.. //advapi32.dll //TRegGetValue = function(hkey:HKEY; lpSubKey:LPCTSTR; // lpValue:LPCTSTR; dwFlags:DWORD; Var pdwType: DWORD; // pvData: PByte; Var pcbData: DWORD): LongInt; stdcall; TRegGetValue = function(hkey:HKEY; lpSubKey:LPCTSTR; lpValue:LPCTSTR; dwFlags:DWORD; pdwType: LPDWORD; pvData: PByte; pcbData: LPDWORD): LongInt; stdcall; { LONG WINAPI RegGetValue( _In_ HKEY hkey, _In_opt_ LPCTSTR lpSubKey, _In_opt_ LPCTSTR lpValue, _In_opt_ DWORD dwFlags, _Out_opt_ LPDWORD pdwType, _Out_opt_ PVOID pvData, _Inout_opt_ LPDWORD pcbData );} type // TFilePathsArray = array of String; TDLLLoader = class(TObject) private cDLLHandle: THandle; cDLLName:String; cLogFile: TLogFile; cNeedNoFreeHandle: Boolean; public constructor Create(Const sDLLName:String; sLogFile:TLogFile = Nil); destructor Destroy; override; Function GetDLLProcOrFuncAddr(sProcOrFuncName:String):Pointer; property DLLHandle: THandle read cDLLHandle; property DLLName: String read cDllName; property LogFile: TLogFile read cLogFile write cLogFile; end; TAdvancedTerminatedThread = class(TThread) Public Procedure TerminateAndWaitForFinish; procedure Terminate; virtual; // override; тут, на жаль, не можна override, бо у TThread Terminate не є віртуальною... procedure Suspend;// virtual; //тут, на жаль, не можна override, бо у TThread Suspend не є віртуальною... end; function FormatOSError(sCommentToError:String; LastError: Integer):SysUtils.EOSError; function FormatLastOSError(sCommentToError:String):SysUtils.EOSError; procedure RaiseLastOSError(sCommentToError:String); overload; procedure RaiseLastOSError(sCommentToError:String; LastError: Integer); overload; procedure LogLastOSError(sCommentToError:String; LastError: Integer; sLogFile:TLogFile); overload; procedure LogLastOSError(sCommentToError:String; sLogFile:TLogFile); overload; // Управління об'єктами подій (Windows.CreateEvent): Function ProcCreateEvent(Const sMessageOnError:String; bManualReset: Windows.BOOL = True; bInitialState: Windows.BOOL = True; lpName: PWideChar = Nil; sLogFile:TLogFile = Nil):Windows.THandle; Function ProcSetEvent(sEvent:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil):Boolean; function ProcResetEvent(sEvent:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil):Boolean; Procedure ProcCloseHandle(Var sHandle:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil); function GetEnvironmentVariableWithLogErrors(const Name: string; sLogFile:TLogFile; const sMessageOnError:String = ''): string; // Функції роботи із мережевими папками: function ConnectShare(Drive, RemotePath, UserName, Password : String; sLogFile: TLogFile = Nil; sWindow: HWND = 0):Integer; function DisconnectShare(Drive : String; sLogFile:TlogFile = Nil):Integer; Procedure FindFiles(Const sDir, sMask:String; Var sdPathList:TStrings; sSearchSubdirs:Boolean = False; sAttr:Integer = faHidden or faSysFile; // or faDirectory // якщо sStrictAttr=False то незалежно від sAttr повертаються і // звичайні файли (без атрибутів): sStrictAttr:Boolean = False; sLogFile:TLogFile = Nil); Function CopyFile(Const sSourceDir, sDestDir, sFileName:String; sLogFile:TLogFile = Nil):Boolean; overload; Function CopyFile(Const sSourcePath, sDestPath:String; sLogFile:TLogFile = Nil):Boolean; overload; Function CopyFileToDir(Const sSourcePath, sDestDir:String; sLogFile:TLogFile = Nil):Boolean; Function CopyListOfFiles(sList:TStrings; Const sDestDir:String; sBreakOnError:Boolean = True; sLogFile:TLogFile = Nil):Boolean; {//------------------ Робота із реєстром //Function ReadRegValue(sKey:String; ) Function WriteRegValue(Const sRegistry:TRegistry; Const sKey, sValueName:String; Const sValue:String; Const sLogFile:TLogFile):Boolean; overload; Function ReadRegValue(Const sRegistry:TRegistry; Const sKey, sValueName:String; Var sValue:String; Const sLogFile:TLogFile):Boolean; overload;} //OpenKey(const Key: string; // Is64BitWindows взята із http://stackoverflow.com/questions/2523957/how-to-get-information-about-the-computer-32bit-or-64bit // Перероблена. function Is64BitWindows(sLogFile:TLogFile = Nil): boolean; Function GetOSVersion(Var dMinor, dMajor, dBuildNumber, dSPMajor, dSPMinor: DWord; Var dSuiteMask:Word; Var dProductType: Byte; Var dVerName, dSuiteFeatures:String; sLogFile:TLogFile = Nil):Boolean; function MessageBoxTimeOut(hWnd: HWND; lpText: PChar; lpCaption: PChar; uType: UINT; wLanguageId: WORD; dwMilliseconds: DWORD): Integer; stdcall; function MessageBoxTimeOutA(hWnd: HWND; lpText: PChar; lpCaption: PChar; uType: UINT; wLanguageId: WORD; dwMilliseconds: DWORD): Integer; stdcall; function MessageBoxTimeOutW(hWnd: HWND; lpText: PWideChar; lpCaption: PWideChar; uType: UINT; wLanguageId: WORD; dwMilliseconds: DWORD): Integer; stdcall; implementation function FormatOSError(sCommentToError:String; LastError: Integer):SysUtils.EOSError; var Error: SysUtils.EOSError; Begin //if LastError <> 0 then Error := SysUtils.EOSError.CreateResFmt(@SysConst.SOSError, [LastError, sCommentToError + SysUtils.SysErrorMessage(LastError)]); //else // Error := SysUtils.EOSError.CreateResFmt(@SysConst.SUnkOSError, [LastError, // sCommentToError + SysUtils.SysErrorMessage(LastError)]); Error.ErrorCode := LastError; FormatOSError:= Error; End; function FormatLastOSError(sCommentToError:String):SysUtils.EOSError; Begin Result:= FormatOSError(sCommentToError, GetLastError); End; procedure RaiseLastOSError(sCommentToError:String; LastError: Integer); begin raise FormatOSError(sCommentToError, LastError); end; procedure LogLastOSError(sCommentToError:String; LastError: Integer; sLogFile:TLogFile); Var cError: SysUtils.EOSError; begin cError:= FormatOSError(sCommentToError, LastError); if sLogFile<>Nil then sLogFile.WriteMessage(cError.Message) else begin raise cError; end; end; procedure RaiseLastOSError(sCommentToError:String); begin RaiseLastOSError(sCommentToError, Windows.GetLastError); end; procedure LogLastOSError(sCommentToError:String; sLogFile:TLogFile); Begin LogLastOSError(sCommentToError, Windows.GetLastError, sLogFile); End; Function ProcCreateEvent(Const sMessageOnError:String; bManualReset: Windows.BOOL = True; bInitialState: Windows.BOOL = True; lpName: PWideChar = Nil; sLogFile:TLogFile = Nil):Windows.THandle; Var cEvent: THandle; Begin cEvent:= Windows.CreateEvent(Nil, // у спадок іншим процесам подію не передаємо bManualReset, bInitialState, lpName); if cEvent = 0 then LogLastOsError(sMessageOnError, sLogFile); ProcCreateEvent:= cEvent; End; Function ProcSetEvent(sEvent:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil):Boolean; Var Res:Boolean; Begin // Встановлюємо сигнал події: If Not(Windows.SetEvent(sEvent)) then Begin LogLastOsError(sMessageOnError, sLogFile); Res:= False; End Else Res:=True; ProcSetEvent:= Res; End; function ProcResetEvent(sEvent:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil):Boolean; Var Res:Boolean; Begin // Знімаємо сигнал події: If Not(Windows.ResetEvent(sEvent)) then Begin LogLastOsError(sMessageOnError, sLogFile); Res:= False; End Else Res:=True; ProcResetEvent:= Res; End; Procedure ProcCloseHandle(Var sHandle:THandle; Const sMessageOnError:String; sLogFile:TLogFile = Nil); Begin if sHandle <> 0 then Begin If Not(Windows.CloseHandle(sHandle)) then LogLastOSError(sMessageOnError, sLogFile); sHandle:= 0; End; End; // Перероблено із SysUtils.GetEnvironmentVariable: function GetEnvironmentVariableWithLogErrors(const Name: string; sLogFile:TLogFile; const sMessageOnError:String = ''): string; const BufSize = 1024; cs_ProcName = 'GetEnvironmentVariableWithLogErrors'; var Len: Integer; Buffer: array[0..BufSize - 1] of Char; ccMessageOnError:String; begin Result := ''; Len := Windows.GetEnvironmentVariable(PChar(Name), @Buffer, BufSize); if Len = 0 then Begin ccMessageOnError:= cs_ProcName+ c_DoubleDot+c_Space+sMessageOnError+ sc_CantReadEnvironmentVariable+Name+c_Dot+c_SystemSays; if System.Assigned(sLogFile) then LogLastOSError(ccMessageOnError, sLogFile) Else RaiseLastOSError(ccMessageOnError); Result := ''; End Else if Len < BufSize then SetString(Result, PChar(@Buffer), Len) else begin SetLength(Result, Len - 1); Len:= Windows.GetEnvironmentVariable(PChar(Name), PChar(Result), Len); if Len = 0 then Begin ccMessageOnError:= cs_ProcName+ c_DoubleDot+c_Space+sMessageOnError+ sc_CantReadEnvironmentVariable+Name+c_Dot+c_SystemSays; if System.Assigned(sLogFile) then LogLastOSError(ccMessageOnError, sLogFile) Else RaiseLastOSError(ccMessageOnError); Result := ''; End; end; end; function ConnectShare(Drive, RemotePath, UserName, Password : String; sLogFile: TLogFile = Nil; sWindow: HWND = 0):Integer; const cs_ProcName = 'ConnectShare'; var NRW : TNetResource; ccFlags: DWord; begin with NRW do begin dwType := RESOURCETYPE_ANY; if Drive <> '' then lpLocalName := PChar(Drive) else lpLocalName := nil; lpRemoteName := PChar(RemotePath); lpProvider := ''; end; ccFlags:= 0; if sWindow<>0 then ccFlags:= ccFlags or Windows.CONNECT_INTERACTIVE; Result := Windows.WNetAddConnection3(sWindow, NRW, PChar(Password), PChar(UserName), ccFlags); // function WNetAddConnection3(hwndOwner: HWND; var lpNetResource: TNetResource; // lpPassword, lpUserName: PWideChar; dwFlags: DWORD): DWORD; stdcall; if Assigned(sLogFile) and (Result <> Windows.NO_ERROR) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantAddNetworkShare+ c_Space + c_SystemSays, Result, sLogFile); End; end; function DisconnectShare(Drive : String; sLogFile:TlogFile = Nil):Integer; const cs_ProcName = 'DisconnectShare'; begin Result := Windows.WNetCancelConnection2(PChar(Drive), 0, false); if Assigned(sLogFile) and (Result <> Windows.NO_ERROR) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantRemoveNetworkShare+ c_Space + c_SystemSays, Result, sLogFile); End; end; Procedure FindFiles(Const sDir, sMask:String; Var sdPathList:TStrings; sSearchSubdirs:Boolean = False; sAttr:Integer = faHidden or faSysFile; // or faDirectory // якщо sStrictAttr=False то незалежно від sAttr повертаються і // звичайні файли (без атрибутів): sStrictAttr:Boolean = False; sLogFile:TLogFile = Nil); const cs_ProcName = 'FindFiles'; var ccResult: Integer; ccShRec: SysUtils.TSearchRec; ccPath, ccDirAndSlash:String; ccAttr: Integer; Begin ccDirAndSlash:= SysUtils.IncludeTrailingPathDelimiter(sDir); ccPath:= ccDirAndSlash + sMask; ccAttr:= sAttr; // if sSearchSubdirs = True then // ccAttr:= ccAttr or faDirectory; ccResult:= SysUtils.FindFirst(ccPath, ccAttr, ccShRec); // function FindFirst(const Path: string; Attr: Integer; // var F: TSearchRec): Integer; while ccResult = 0 do Begin if (NOT(SStrictAttr)) or ((ccShRec.Attr and sAttr) = ccShRec.Attr) then sdPathList.Add(ccDirAndSlash + ccShRec.Name); ccResult:= SysUtils.FindNext(ccShRec); End; if ccResult <> 0 then Begin if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName + c_DoubleDot+c_Space+ c_SystemSays, ccResult, sLogFile); End; End; SysUtils.FindClose(ccShRec); if sSearchSubdirs then Begin //Windows.ZeroMemory(ccShRec, SizeOf(ccShRec)); ccPath:= ccDirAndSlash + cs_AllFilesMask; ccAttr:= sAttr or faDirectory; ccResult:= SysUtils.FindFirst(ccPath, ccAttr, ccShRec); while ccResult = 0 do Begin if ((ccShRec.Attr and faDirectory) = faDirectory) then Begin if Not((ccShRec.Name = cs_ThisDir) or (ccShRec.Name = cs_SuperiorDir)) then Begin FindFiles(ccDirAndSlash + ccShRec.Name, sMask, sdPathList, sSearchSubdirs, sAttr, sStrictAttr, sLogFile); End; End; ccResult:= SysUtils.FindNext(ccShRec); End; SysUtils.FindClose(ccShRec); End; End; Function CopyFile(Const sSourceDir, sDestDir, sFileName:String; sLogFile:TLogFile = Nil):Boolean; Var ccSourcePath, ccDestPath:String; Begin ccSourcePath:= SysUtils.IncludeTrailingPathDelimiter(sSourceDir)+ sFileName; ccDestPath:= SysUtils.IncludeTrailingPathDelimiter(sDestDir)+ sFileName; Result:= CopyFile(ccSourcePath, ccDestPath, sLogFile); End; Function CopyFileToDir(Const sSourcePath, sDestDir:String; sLogFile:TLogFile = Nil):Boolean; Var ccDestPath, ccFileName:String; Begin ccFileName:= SysUtils.ExtractFileName(sSourcePath); ccDestPath:= SysUtils.IncludeTrailingPathDelimiter(sDestDir)+ ccFileName; Result:= CopyFile(sSourcePath, ccDestPath, sLogFile); End; Function CopyFile(Const sSourcePath, sDestPath:String; sLogFile:TLogFile = Nil):Boolean; overload; const cs_ProcName = 'CopyFile'; Var ccCancel: BOOL; Begin ccCancel:= False; if Not(Windows.CopyFileEx(PWideChar(sSourcePath), PWideChar(sDestPath), Nil, //lpProgressRoutine: TFNProgressRoutine Nil, //lpData: Pointer Addr(ccCancel), //pbCancel: PBool; COPY_FILE_ALLOW_DECRYPTED_DESTINATION //dwCopyFlags: DWORD )) then Begin if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName + c_DoubleDot+c_Space+ c_SystemSays, sLogFile); End; Result:= False; End Else Result:= True; //function CopyFileEx(lpExistingFileName, lpNewFileName: PWideChar; //lpProgressRoutine: TFNProgressRoutine; lpData: Pointer; pbCancel: PBool; //dwCopyFlags: DWORD): BOOL; stdcall; End; Function CopyListOfFiles(sList:TStrings; Const sDestDir:String; sBreakOnError:Boolean = True; sLogFile:TLogFile = Nil):Boolean; var ccFileNum:Integer; ccResult:Boolean; Begin ccResult:= True; for ccFileNum := 0 to sList.Count - 1 do Begin If Not(CopyFileToDir(sList[ccFileNum], sDestDir, sLogFile)) then Begin ccResult:= False; if sBreakOnError then Break; End; End; Result:= ccResult; End; //------------------------------------------------------ // Is64BitWindows взята із http://stackoverflow.com/questions/2523957/how-to-get-information-about-the-computer-32bit-or-64bit // Перероблена. function Is64BitWindows(sLogFile:TLogFile = Nil): boolean; {$IFDEF CPUX64} {$DEFINE CPU64} {$ENDIF} {$IFDEF CPU64} begin // IsWow64Process повертає false, якщо і сама програма 64-бітна, // тому якщо компілятор каже що він компілює в x64 то це буде x64: Result := True; End; {$ELSE} const cs_ProcName = 'Is64BitWindows'; cs_BaseProcName = 'IsWow64Process'; cs_KernelLibFileName = 'kernel32.dll'; type TIsWow64Process = function(hProcess: THandle; var Wow64Process: BOOL): BOOL; stdcall; var DLLHandle: THandle; pIsWow64Process: TIsWow64Process; IsWow64: BOOL; begin Result := False; DllHandle := LoadLibrary(cs_KernelLibFileName); if DLLHandle <> 0 then begin try pIsWow64Process := GetProcAddress(DLLHandle, cs_BaseProcName); if Assigned(pIsWow64Process) then Begin Result := pIsWow64Process(GetCurrentProcess, IsWow64); if Result then Result:= IsWow64 Else if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_Function+c_Space+cs_BaseProcName+c_Space+cs_fFailed+ c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); End; End else if Assigned(sLogFile) then LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantGetProcAddress+c_DoubleDot+c_Space+c_Quotes+ cs_BaseProcName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); finally FreeLibrary(DLLHandle); end; end Else if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantLoadLibrary+c_DoubleDot+c_Space+c_Quotes+ cs_KernelLibFileName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); End; end; {$ENDIF} Procedure AddMessage(Var sdString:String; Const sMessage:String; sDelimiter:String = c_Comma + c_Space); Begin if sdString = '' then sdString:= sMessage Else sdString:= sdString + sDelimiter + sMessage; End; { TDLLLoader = class(TObject) private cDLLHandle: THandle; cLogFile: TLogFile; cNeedNoFreeHandle: Boolean; public constructor Create(Const sDLLName:String; sLogFile:TLogFile = Nil); destructor Destroy; override; Function GetDLLProcOrFuncAddr(sProcOrFuncName:String):Pointer; property DLLHandle: THandle read cDLLHandle; end; } constructor TDLLLoader.Create(Const sDLLName:String; sLogFile:TLogFile = Nil); const cs_ProcName = 'TDLLLoader.Create'; Var ccMessage:String; Begin Inherited Create; Self.cNeedNoFreeHandle:= False; Self.cLogFile:= sLogFile; Self.cDLLHandle:= Windows.GetModuleHandle(PChar(sDLLName)); if (Self.cDLLHandle = 0) then Begin if Assigned(Self.cLogFile) then LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantGetLibraryHandle+c_DoubleDot+c_Space+c_Quotes+ sDLLName+c_Quotes+c_Dot+c_Space+cs_WillTryToLoadIt+c_Dot+ c_Space+c_SystemSays+ c_Space, sLogFile); Self.cDLLHandle:= Windows.LoadLibrary(PChar(sDLLName)); if Self.cDLLHandle = 0 then begin ccMessage:= cs_ProcName+c_DoubleDot+c_Space+ cs_CantLoadLibrary+c_DoubleDot+c_Space+c_Quotes+ sDLLName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space; if Assigned(Self.cLogFile) then LogLastOSError(ccMessage, sLogFile); LogLastOSError(ccMessage, Nil); // raise exception end Else Self.cNeedNoFreeHandle:= True; End; Self.cDllName:= sDLLName; End; destructor TDLLLoader.Destroy; const cs_ProcName = 'TDLLLoader.Destroy'; Var ccResult:Boolean; Begin if Self.cNeedNoFreeHandle then Begin ccResult:= Windows.FreeLibrary(Self.cDLLHandle); if ccResult then Self.cDLLHandle:= 0 Else if Assigned(Self.cLogFile) then LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantUnloadLibrary+c_DoubleDot+c_Space+c_Quotes+ Self.DLLName+c_Quotes+c_Dot+ c_Space+c_SystemSays+ c_Space, Self.cLogFile); End; Self.cLogFile:= Nil; Self.cDLLName:= ''; Inherited Destroy; End; Function TDLLLoader.GetDLLProcOrFuncAddr(sProcOrFuncName:String):Pointer; const cs_ProcName = 'TDLLLoader.GetDLLProcOrFuncAddr'; Begin Result:= Windows.GetProcAddress(Self.cDLLHandle, PChar(sProcOrFuncName)); if Not(System.Assigned(Result)) then Begin if System.Assigned(Self.cLogFile) then LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantGetProcAddress+c_DoubleDot+c_Space+c_Quotes+ sProcOrFuncName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space, Self.cLogFile); End; End; Procedure TAdvancedTerminatedThread.TerminateAndWaitForFinish; Begin if Not(Self.Finished) then Begin Self.Terminate; while Self.Suspended do Self.Resume; Self.WaitFor; End; End; procedure TAdvancedTerminatedThread.Terminate; Begin Inherited Terminate; End; procedure TAdvancedTerminatedThread.Suspend; {Const c_EventCount = 2; c_TerminateEventIndex = 0; c_ResumeEventIndex = 1; Var cHandleArray: array [0..c_EventCount - 1] of THandle; cSignal:DWord;} Begin // 2019.03.13. Після виконаної роботи перед тим як заснути ще раз перевіримо, чи не просили закритися... if Not Self.Terminated then Inherited Suspend; End; //------------------------------------------------------ Function GetOSVersion(Var dMinor, dMajor, dBuildNumber, dSPMajor, dSPMinor: DWord; Var dSuiteMask:Word; Var dProductType: Byte; Var dVerName, dSuiteFeatures:String; sLogFile:TLogFile = Nil):Boolean; const cs_ProcName = 'GetOSVersion'; cs_BaseProcName = 'RtlGetVersion'; cs_KernelLibFileName = 'ntdll.dll'; cs_Windows='Windows'; cs_Server = 'Server'; cs_NT_DOMAIN_CONTROLLER = 'Domain Controller'; //ci_MajorKoef = 1000; ci_MajorShl = 16; ci_Windows2000 = $50000; ci_WindowsXP = $50001; ci_WindowsXPx64ProfOrServer2003OrHomeServer = $50002; ci_WindowsVistaOrServer2008 = $60000; ci_Windows7OrServer2008R2 = $60001; ci_Windows80OrServer2012 = $60002; ci_Windows81 = $60003; var DLLHandle: THandle; ccVersionInfo:Windows.RTL_OSVERSIONINFOEXW; PRtlGetVersion: TRtlGetVersion; ccStatus: TNTSTATUS; ccVersionMinorAndMajor:Cardinal; ccCSDVersion:String; //IsWow64: BOOL; Begin dMinor:= 0; dMajor:= 0; dBuildNumber:= 0; dSPMajor:= 0; dSPMinor:= 0; dVerName:= ''; dSuiteFeatures:= ''; dSuiteMask:= 0; dProductType:= 0; Result := False; DllHandle := Windows.GetModuleHandle(cs_KernelLibFileName); if DLLHandle <> 0 then Begin Windows.ZeroMemory(Addr(ccVersionInfo), SizeOf(ccVersionInfo)); ccVersionInfo.dwOSVersionInfoSize:= SizeOf(ccVersionInfo); PRtlGetVersion := GetProcAddress(DLLHandle, cs_BaseProcName); if Assigned(PRtlGetVersion) then Begin ccStatus:= PRtlGetVersion(ccVersionInfo); if ccStatus = STATUS_SUCCESS then Begin dMinor:= ccVersionInfo.dwMinorVersion; dMajor:= ccVersionInfo.dwMajorVersion; dBuildNumber:= ccVersionInfo.dwBuildNumber; dSPMajor:= ccVersionInfo.wServicePackMajor; dSPMinor:= ccVersionInfo.wServicePackMinor; dSuiteMask:= ccVersionInfo.wSuiteMask; dProductType:= ccVersionInfo.wProductType; //ccVersionMinorAndMajor:= (dMajor*ci_MajorKoef) + dMinor; ccVersionMinorAndMajor:= (dMajor shl ci_MajorShl) or dMinor; dVerName:= cs_Windows+c_Space; case ccVersionMinorAndMajor of ci_Windows2000: Begin dVerName:= dVerName+'2000'; case dProductType of VER_NT_SERVER: dVerName:= dVerName + c_Space + cs_Server; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + c_Space + cs_NT_DOMAIN_CONTROLLER; end; End; ci_WindowsXP: Begin dVerName:= dVerName+'XP'; case dProductType of VER_NT_SERVER: dVerName:= dVerName + c_Space + cs_Server; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + c_Space + cs_NT_DOMAIN_CONTROLLER; end; End; ci_WindowsXPx64ProfOrServer2003OrHomeServer: Begin if dProductType = VER_NT_WORKSTATION then dVerName:= dVerName+'XP x64' else if (dSuiteMask and VER_SUITE_WH_SERVER) = VER_SUITE_WH_SERVER then dVerName:= dVerName+'XP Home server' else dVerName:= dVerName + c_Space + cs_Server + '2003'; End; ci_WindowsVistaOrServer2008: Begin case dProductType of VER_NT_SERVER: dVerName:= dVerName + cs_Server + ' 2008'; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + cs_Server + ' 2008' + c_Space + cs_NT_DOMAIN_CONTROLLER; else dVerName:= dVerName+'Vista'; end; End; ci_Windows7OrServer2008R2: Begin case dProductType of VER_NT_SERVER: dVerName:= dVerName + cs_Server + ' 2008 R2'; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + cs_Server + ' 2008 R2' + c_Space + cs_NT_DOMAIN_CONTROLLER; else dVerName:= dVerName+'7'; end; End; ci_Windows80OrServer2012: Begin case dProductType of VER_NT_SERVER: dVerName:= dVerName + cs_Server + ' 2012'; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + cs_Server + ' 2012' + c_Space + cs_NT_DOMAIN_CONTROLLER; else dVerName:= dVerName+'8'; end; End; ci_Windows81: Begin case dProductType of VER_NT_SERVER: dVerName:= dVerName + cs_Server + ' 2012 R2'; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + cs_Server + ' 2012 R2' + c_Space + cs_NT_DOMAIN_CONTROLLER; else dVerName:= dVerName+'8.1'; end; End; Else Begin dVerName:= dVerName + SysUtils.IntToStr(dMajor) +c_Dot+ SysUtils.IntToStr(dMinor); case dProductType of VER_NT_SERVER: dVerName:= dVerName + c_Space + cs_Server; VER_NT_DOMAIN_CONTROLLER: dVerName:= dVerName + c_Space + cs_NT_DOMAIN_CONTROLLER; end; End; end; ccCSDVersion:= SysUtils.StrPas(PWideChar(Addr(ccVersionInfo.szCSDVersion))); if ccCSDVersion<>'' then dVerName:= dVerName + c_Space + ccCSDVersion; dSuiteFeatures:= ''; if (dSuiteMask and VER_SUITE_WH_SERVER) = VER_SUITE_WH_SERVER then Begin AddMessage(dSuiteFeatures, 'Home server'); End; if (dSuiteMask and VER_SUITE_TERMINAL) = VER_SUITE_TERMINAL then Begin if (dSuiteMask and VER_SUITE_SINGLEUSERTS) = VER_SUITE_SINGLEUSERTS then Begin AddMessage(dSuiteFeatures, 'One remote desktop'); End Else AddMessage(dSuiteFeatures, 'Terminal (remote desktop server)'); End; if (dSuiteMask and VER_SUITE_STORAGE_SERVER) = VER_SUITE_STORAGE_SERVER then Begin AddMessage(dSuiteFeatures, 'Storage server'); End; if (dSuiteMask and VER_SUITE_SMALLBUSINESS) = VER_SUITE_SMALLBUSINESS then Begin if (dSuiteMask and VER_SUITE_SMALLBUSINESS_RESTRICTED) = VER_SUITE_SMALLBUSINESS_RESTRICTED then AddMessage(dSuiteFeatures, 'Small business') else AddMessage(dSuiteFeatures, 'Small business in past'); End; if (dSuiteMask and VER_SUITE_PERSONAL) = VER_SUITE_PERSONAL then Begin AddMessage(dSuiteFeatures, 'Home') End; if (dSuiteMask and VER_SUITE_EMBEDDEDNT) = VER_SUITE_EMBEDDEDNT then Begin AddMessage(dSuiteFeatures, 'Embedded') End; if (dSuiteMask and VER_SUITE_ENTERPRISE) = VER_SUITE_ENTERPRISE then Begin AddMessage(dSuiteFeatures, 'Enterprise') End; if (dSuiteMask and VER_SUITE_DATACENTER) = VER_SUITE_DATACENTER then Begin AddMessage(dSuiteFeatures, 'Datacenter') End; if (dSuiteMask and VER_SUITE_COMPUTE_SERVER) = VER_SUITE_COMPUTE_SERVER then Begin AddMessage(dSuiteFeatures, 'Compute cluster') End; if (dSuiteMask and VER_SUITE_BLADE) = VER_SUITE_BLADE then Begin AddMessage(dSuiteFeatures, 'Web') End; if (dSuiteMask and VER_SUITE_BACKOFFICE) = VER_SUITE_BACKOFFICE then Begin AddMessage(dSuiteFeatures, 'BackOffice') End; End Else if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_Function+c_Space+cs_BaseProcName+c_Space+cs_fFailed+ '('+cs_fReturned+c_Space+SysUtils.IntToStr(ccStatus)+')'+ c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); End; End else if Assigned(sLogFile) then LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantGetProcAddress+c_DoubleDot+c_Space+c_Quotes+ cs_BaseProcName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); End Else if Assigned(sLogFile) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+ cs_CantGetLibraryHandle+c_DoubleDot+c_Space+c_Quotes+ cs_KernelLibFileName+c_Quotes+c_Dot+c_Space+c_SystemSays+ c_Space, sLogFile); End; //function GetModuleHandle(lpModuleName: PWideChar): HMODULE; stdcall; End; //RTL_OSVERSIONINFOEXW { VER_NT_WORKSTATION = $0000001; VER_NT_DOMAIN_CONTROLLER = $0000002; VER_NT_SERVER = $0000003;} { взято із http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe?msg=5080848#xx5080848xx // RTL_OSVERSIONINFOEXW is defined in winnt.h BOOL GetOsVersion(RTL_OSVERSIONINFOEXW* pk_OsVer)} { typedef LONG (WINAPI* tRtlGetVersion)(RTL_OSVERSIONINFOEXW*); memset(pk_OsVer, 0, sizeof(RTL_OSVERSIONINFOEXW)); pk_OsVer->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); HMODULE h_NtDll = GetModuleHandleW(L"ntdll.dll"); tRtlGetVersion f_RtlGetVersion = (tRtlGetVersion)GetProcAddress(h_NtDll, "RtlGetVersion"); if (!f_RtlGetVersion) return FALSE; // This will never happen (all processes load ntdll.dll) LONG Status = f_RtlGetVersion(pk_OsVer); return Status == 0; // STATUS_SUCCESS; } {Function OpenRegKeyInObject(Const sRegistry:TRegistry; Const sKey:String; Const sLogFile:TLogFile):Boolean; const cs_ProcName = 'OpenRegKeyInObject'; Begin Result:= sRegistry.OpenKey(sKey, True); If Not(Result) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+cs_CantOpenRegKey+ c_Space+c_Quotes+sKey+c_Quotes+c_Space+c_SystemSays+c_Space, sLogFile); End Else Begin End; End; Function WriteRegValue(Const sRegistry:TRegistry; Const sKey, sValueName:String; Const sValue:String; Const sLogFile:TLogFile):Boolean; const cs_ProcName = 'WriteRegValueString'; Begin Result:= sRegistry.OpenKey(sKey, True); If Not(Result) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+cs_CantOpenRegKey+ c_Space+c_Quotes+sKey+c_Quotes+c_Space+c_SystemSays+c_Space, sLogFile); End Else Begin try sRegistry.WriteString(sValueName, sValue); except on E:ERegistryException do Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+cs_CantWriteRegValue+ c_Space+c_Quotes+sValueName+c_Quotes+c_Equal+ c_Quotes+sValue+c_Quotes+c_Space+ c_ObjectSays+c_Space+c_Quotes+E.Message+c_Quotes+ c_Space+c_SystemSays+c_Space, sLogFile); Result:= False; End; end; End; End; Function ReadRegValue(Const sRegistry:TRegistry; Const sKey, sValueName:String; Var sValue:String; Const sLogFile:TLogFile):Boolean; const cs_ProcName = 'ReadRegValueString'; Begin Result:= sRegistry.OpenKey(sKey, False); If Not(Result) then Begin LogLastOSError(cs_ProcName+c_DoubleDot+c_Space+cs_CantOpenRegKey+ c_Space+c_Quotes+sKey+c_Quotes+c_Space+c_SystemSays+c_Space, sLogFile); End Else Begin End; End;} function MessageBoxTimeOut; external user32 name 'MessageBoxTimeoutW'; function MessageBoxTimeOutA; external user32 name 'MessageBoxTimeoutA'; function MessageBoxTimeOutW; external user32 name 'MessageBoxTimeoutW'; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIndefiniteLengthInputStream; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes, ClpLimitedInputStream; resourcestring SMalformedContent = 'Malformed End-of-Contents Marker'; type TIndefiniteLengthInputStream = class(TLimitedInputStream) strict private var F_lookAhead: Int32; F_eofOn00: Boolean; function CheckForEof(): Boolean; inline; function RequireByte(): Int32; inline; public constructor Create(inStream: TStream; limit: Int32); procedure SetEofOn00(eofOn00: Boolean); function Read(buffer: TCryptoLibByteArray; offset, count: LongInt) : LongInt; override; function ReadByte(): Int32; override; end; implementation uses ClpStreamSorter; // included here to avoid circular dependency :) { TIndefiniteLengthInputStream } function TIndefiniteLengthInputStream.RequireByte: Int32; begin // result := F_in.ReadByte(); result := TStreamSorter.ReadByte(F_in); if (result < 0) then begin // Corrupted stream raise EEndOfStreamCryptoLibException.Create(''); end; end; function TIndefiniteLengthInputStream.CheckForEof: Boolean; var extra: Int32; begin if (F_lookAhead = $00) then begin extra := RequireByte(); if (extra <> 0) then begin raise EIOCryptoLibException.CreateRes(@SMalformedContent); end; F_lookAhead := -1; SetParentEofDetect(true); result := true; Exit; end; result := F_lookAhead < 0; end; constructor TIndefiniteLengthInputStream.Create(inStream: TStream; limit: Int32); begin Inherited Create(inStream, limit); F_lookAhead := RequireByte(); CheckForEof(); end; function TIndefiniteLengthInputStream.Read(buffer: TCryptoLibByteArray; offset, count: LongInt): LongInt; var numRead: Int32; begin // Only use this optimisation if we aren't checking for 00 if ((F_eofOn00) or (count <= 1)) then begin result := (Inherited Read(buffer, offset, count)); Exit; end; if (F_lookAhead < 0) then begin result := 0; Exit; end; numRead := TStreamSorter.Read(F_in, buffer, offset + 1, count - 1); if (numRead <= 0) then begin // Corrupted stream raise EEndOfStreamCryptoLibException.Create(''); end; buffer[offset] := Byte(F_lookAhead); F_lookAhead := RequireByte(); result := numRead + 1; end; function TIndefiniteLengthInputStream.ReadByte: Int32; begin if (F_eofOn00 and CheckForEof()) then begin result := -1; Exit; end; result := F_lookAhead; F_lookAhead := RequireByte(); end; procedure TIndefiniteLengthInputStream.SetEofOn00(eofOn00: Boolean); begin F_eofOn00 := eofOn00; if (F_eofOn00) then begin CheckForEof(); end; end; end.
unit BaiduMapAPI.LocationService.Android; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 定位服务 单元 //官方链接:http://lbsyun.baidu.com/ //TAndroidBaiduMapLocationService 百度地图 安卓定位服务 interface uses System.Classes, System.Types, FMX.Maps, Androidapi.JNI.JavaTypes, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.baidu.location, BaiduMapAPI.LocationService; type TAndroidBaiduMapLocationService = class; TBDLocationListenner = class(TJavaLocal, JBDLocationListener) private [weak]FLocationService: TAndroidBaiduMapLocationService; public procedure onReceiveLocation(P1: JBDLocation); cdecl; procedure onConnectHotSpotMessage(P1: JString; P2: Integer); cdecl; constructor Create(LocationService: TAndroidBaiduMapLocationService); end; TAndroidBaiduMapLocationService = class(TBaiduMapLocationService) private FScanSpan:Integer; FLocationClient:JLocationClient; FLocationListener:TBDLocationListenner; LocOption:JLocationClientOption; protected procedure DoInitLocation; override; procedure DoStarLocation; override; procedure DoStopLocation; override; public constructor Create; override; destructor Destroy; override; end; implementation uses Androidapi.Helpers, FMX.Helpers.Android; { TAndroidBaiduMapLocationService } constructor TAndroidBaiduMapLocationService.Create; begin inherited; // CallInUIThreadAndWaitFinishing( // procedure // begin FLocationClient:=TJLocationClient.JavaClass.init(SharedActivityContext); FLocationListener:=TBDLocationListenner.Create(Self); FLocationClient.registerLocationListener(FLocationListener); // end); end; destructor TAndroidBaiduMapLocationService.Destroy; begin FLocationListener.Free; FLocationClient:=nil; inherited; end; procedure TAndroidBaiduMapLocationService.DoInitLocation; begin // CallInUIThreadAndWaitFinishing( // procedure // begin LocOption:=TJLocationClientOption.JavaClass.init; LocOption.setLocationMode(TJLocationClientOption_LocationMode.JavaClass.Hight_Accuracy); LocOption.setCoorType(StringToJString('bd09ll')); FScanSpan:=1000; LocOption.setScanSpan(FScanSpan); FLocationClient.setLocOption(LocOption); // end); end; procedure TAndroidBaiduMapLocationService.DoStarLocation; begin FLocationClient.start; end; procedure TAndroidBaiduMapLocationService.DoStopLocation; begin FLocationClient.stop; end; { TBDLocationListenner } constructor TBDLocationListenner.Create( LocationService: TAndroidBaiduMapLocationService); begin inherited Create; FLocationService:=LocationService; end; procedure TBDLocationListenner.onConnectHotSpotMessage(P1: JString; P2: Integer); begin end; procedure TBDLocationListenner.onReceiveLocation(P1: JBDLocation); var Coordinate:TMapCoordinate; begin //位置更新 if FLocationService<>nil then begin Coordinate:= TMapCoordinate.Create(P1.getLatitude, P1.getLongitude); FLocationService.UserLocationWillChanged(Coordinate); end; end; end.
unit DAO.Tiragem; interface uses DAO.Base, Model.Tiragem, Generics.Collections, System.Classes, Vcl.Forms, System.UITypes, Vcl.Dialogs; type TTiragemDAO = class(TDAO) public function Insert(aTiragem: Model.Tiragem.TTiragem): Boolean; function Update(aTiragem: Model.Tiragem.TTiragem): Boolean; function Delete(sFiltro: String): Boolean; function FindTiragem(sFiltro: String): TObjectList<Model.Tiragem.TTiragem>; function ImportTiragem(sFile: String): TObjectList<Model.Tiragem.TTiragem>; function RetornaID(sData: String; sRoteiro: String; sProduto: String): Integer; end; const TABLENAME = 'JOR_TIRAGEM'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB, ufrmProcesso, clUtil; function TTiragemDAO.Insert(aTiragem: TTiragem): Boolean; var sSQL : System.string; begin Result := False; aTiragem.ID := GetKeyValue(TABLENAME,'ID_TIRAGEM'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(ID_TIRAGEM, DAT_TIRAGEM, COD_ROTEIRO, COD_ENTREGADOR, COD_PRODUTO, QTD_TIRAGEM) ' + 'VALUES ' + '(:ID, :DATA, :ROTEIRO, :ENTREGADOR, :PRODUTO, :TIRAGEM);'; Connection.ExecSQL(sSQL,[aTiragem.ID, aTiragem.Data, aTiragem.Roteiro, aTiragem.Entregador, aTiragem.Produto, aTiragem.Tiragem], [ftInteger, ftDate, ftString, ftInteger, ftString, ftInteger]); Result := True; end; function TTiragemDAO.Update(aTiragem: TTiragem): Boolean; var sSQL: System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DAT_TIRAGEM = :DATA, COD_ROTEIRO = :ROTEIRO, COD_ENTREGADOR = :ENTREGADOR, COD_PRODUTO = :PRODUTO, ' + ' QTD_TIRAGEM = :TIRAGEM WHERE ID_TIRAGEM = :ID;'; Connection.ExecSQL(sSQL,[aTiragem.Data, aTiragem.Roteiro, aTiragem.Entregador, aTiragem.Produto, aTiragem.Tiragem, aTiragem.ID], [ftDate, ftString, ftInteger, ftString, ftInteger, ftInteger]); Result := True; end; function TTiragemDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Connection.ExecSQL(sSQL); Result := True; end; function TTiragemDAO.FindTiragem(sFiltro: string): TObjectList<Model.Tiragem.TTiragem>; var FDQuery: TFDQuery; tiragens: TObjectList<TTiragem>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); tiragens := TObjectList<TTiragem>.Create(); while not FDQuery.Eof do begin tiragens.Add(TTiragem.Create(FDQuery.FieldByName('ID_TIRAGEM').AsInteger, FDQuery.FieldByName('DAT_TIRAGEM').AsDateTime, FDQuery.FieldByName('COD_ROTEIRO').AsString, FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('COD_PRODUTO').AsString, FDQuery.FieldByName('QTD_TIRAGEM').AsInteger)); FDQuery.Next; end; finally FDQuery.Free; end; Result := tiragens; end; function TTiragemDAO.RetornaID(sData: String; sRoteiro: String; sProduto: String): Integer; var FDQuery: TFDQuery; begin Result := 0; FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE DAT_TIRAGEM = :DATA AND COD_ROTEIRO = :ROTEIRO AND COD_PRODUTO = :PRODUTO'); FDQuery.ParamByName('DATA').AsDate := StrToDate(sData); FDQuery.ParamByName('ROTEIRO').AsString := sRoteiro; FDQuery.ParamByName('PRODUTO').AsString := sProduto; FDQuery.Open(); if FDQuery.IsEmpty then begin Exit; end; Result := FDQuery.FieldByName('ID_TIRAGEM').AsInteger; finally FDQuery.Free; end; end; function TTiragemDAO.ImportTiragem(sFile: string): TObjectList<Model.Tiragem.TTiragem>; var sArquivo : TextFile; sLinha, sData : String; Str : TStringList; Cab : TStringList; Contador, LinhasTotal, i: Integer; dPosicao: Double; tiragens: TObjectList<TTiragem>; bFlagFile: Boolean; bFlagLoop: Boolean; begin try Cab := TStringList.Create; Cab.StrictDelimiter := True; Cab.Delimiter := ';'; Str := TStringList.Create; Str.StrictDelimiter := True; Str.Delimiter := ';'; AssignFile(sArquivo, sFile); tiragens := TObjectList<TTiragem>.Create(); dPosicao := 0; bFlagFile := False; bFlagLoop := False; if not Assigned(frmProcesso) then begin frmProcesso := TfrmProcesso.Create(Application); end; Screen.Cursor := crHourGlass; frmProcesso.Show; frmProcesso.cxGroupBox1.Caption := 'Importando Planilha. Aguarde...'; frmProcesso.cxGroupBox1.Refresh; LinhasTotal := TUtil.NumeroDeLinhasTXT(sFile); AssignFile(sArquivo, sFile); Reset(sArquivo); sLinha := ''; while not bFlagLoop do begin Readln(sArquivo, sLinha); if Copy(sLinha,0,22) = 'TABELA DE CARREGAMENTO' then begin sData := Copy(sLinha,23,11); bFlagFile := True; end; if Copy(sLinha,0,6) = 'AGENTE' then begin Cab.DelimitedText := sLinha; Readln(sArquivo, sLinha); bFlagLoop := True; end; end; if not bFlagFile then begin MessageDlg('Arquivo informado não é de TABELA DE CARREGAMENTO.',mtWarning,[mbOK],0); Exit; end; Contador := 4; while not Eoln(sArquivo) do begin for i := 2 to Cab.Count - 1 do begin if Cab[i] <> 'TOTAL' then begin Str.DelimitedText := sLinha; tiragens.Add(TTiragem.Create(0,StrtoDate(sData),Str[0],0,Cab[i],StrtoIntDef(Str[i],0))); end; end; Readln(sArquivo, sLinha); dPosicao := (Contador / LinhasTotal) * 100; Inc(Contador); frmProcesso.cxProgressBar1.Position := dPosicao; frmProcesso.cxProgressBar1.Properties.Text := FormatFloat('0.00%',dPosicao); frmProcesso.cxProgressBar1.Refresh; end; finally Result := tiragens; Screen.Cursor := crDefault; frmProcesso.Close; FreeAndNil(frmProcesso); CloseFile(sArquivo); sLinha := ''; FreeAndNil(Str); FreeAndNil(Cab); end; end; end.
unit f2Utils; interface uses Windows; function OpenFileDlg(aHandle: HWND; aTitle: PChar; aFilter: PChar): string; function SaveFileDlg(aHandle: HWND; aTitle: PChar; aFilter: PChar; aDefExt: PChar): string; function IsDirWritable(const aDir: AnsiString): Boolean; implementation uses SysUtils, CommDlg; function OpenFileDlg(aHandle: HWND; aTitle: PChar; aFilter: PChar): string; const cBufSize = 10240; var l_OFN: TOpenFilename; l_Buf: string; begin Result := ''; SetLength(l_Buf, cBufSize); l_Buf[1] := #0; FillChar(l_OFN, SizeOf(TOpenFilename), 0); l_OFN.lStructSize := SizeOf(TOpenFilename); l_OFN.hWndOwner := aHandle; l_OFN.lpstrFilter := aFilter; l_OFN.lpstrFile := PChar(@l_Buf[1]); l_OFN.nMaxFile := cBufSize; l_OFN.lpstrTitle := aTitle; l_OFN.Flags := OFN_ENABLESIZING or OFN_FILEMUSTEXIST or OFN_LONGNAMES; if GetOpenFileName(l_OFN) then begin SetLength(l_Buf, Pos(#0, l_Buf)-1); Result := l_Buf; end; end; function SaveFileDlg(aHandle: HWND; aTitle: PChar; aFilter: PChar; aDefExt: PChar): string; const cBufSize = 10240; var l_OFN: TOpenFilename; l_Buf: string; begin Result := ''; SetLength(l_Buf, cBufSize); l_Buf[1] := #0; FillChar(l_OFN, SizeOf(TOpenFilename), 0); l_OFN.lStructSize := SizeOf(TOpenFilename); l_OFN.hWndOwner := aHandle; l_OFN.lpstrFilter := aFilter; l_OFN.lpstrFile := PChar(@l_Buf[1]); l_OFN.nMaxFile := cBufSize; l_OFN.lpstrTitle := aTitle; l_OFN.lpstrDefExt := aDefExt; l_OFN.Flags := OFN_ENABLESIZING or OFN_LONGNAMES or OFN_OVERWRITEPROMPT; if GetOpenFileName(l_OFN) then begin SetLength(l_Buf, Pos(#0, l_Buf)-1); Result := l_Buf; end; end; function IsDirWritable(const aDir: AnsiString): Boolean; var l_F: TextFile; l_FN: AnsiString; begin {$I-} l_FN := IncludeTrailingPathDelimiter(aDir) + '$furqch$.$$$'; AssignFile(l_F, l_FN); Rewrite(l_F); try Result := (IOResult = 0); if Result then begin Writeln(l_F, 'write test'); Result := (IOResult = 0); end; finally CloseFile(l_F); end; DeleteFile(l_FN); {$I+} end; end.
unit cmdlinecfgui; interface uses Classes, SysUtils, contnrs, cmdlinecfg; type { TCmdLineLayoutInfo } // Section names are assumed to be . separated. // Anything after to . is expected to be a "sub section" of the section. { TLayoutSection } TLayoutElementType = (letSwitch, letSection); TLayoutElementTypes = set of TLayoutElementType; TLayoutSection = class(TObject) //level : integer; // number of "dots" in the name public fName : string; fElementType: TLayoutElementType; public Display : string; GUIHint : string; Elements : array of TLayoutSection; ElemCount : integer; function AddElement(const AName: string; AElementType: TLayoutElementType): TLayoutSection; constructor Create(const AName: string = ''; AElementType: TLayoutElementType = letSection); destructor Destroy; override; property Name: string read fName; property ElementType: TLayoutElementType read fElementType; end; TCmdLineLayoutInfo = class(TObject) public RootElement : TLayoutSection; constructor Create; destructor Destroy; override; end; { TCmdLineUIControl } TCmdLineUIControl = class(TObject) private FValueChanged: TNotifyEvent; protected procedure ValueChanged; virtual; public procedure Init(cfg: TCmdLineCfg; layout: TCmdLineLayoutInfo; const ASection : string = ''); virtual; abstract; procedure SetValues(list: TList {of TCmdLineOptionValue}); virtual; abstract; procedure Serialize(list: TList {of TCmdLineOptionValue}); virtual; abstract; property OnValueChanged: TNotifyEvent read FValueChanged write fValueChanged; end; function LayoutFindElement(aparent: TLayoutSection; const Name: string; LookFor: TLayoutElementTypes = [letSection] ): TLayoutSection; procedure LayoutEnumElement(aparent: TLayoutSection; list: TList; LookFor: TLayoutElementTypes = [letSection] ); procedure LayoutGetUnused(cmd: TCmdLineCfg; layout: TLayoutSection; list: TList); implementation procedure LayoutGetSwitches(root: TLayoutSection; hash: TFPHashObjectList); var sct : TList; i : Integer; j : Integer; el : TLayoutSection; sel : TLayoutSection; begin sct:=TList.Create; try sct.Add(root); j:=0; while j<sct.Count do begin el:=TLayoutSection(sct[j]); for i:=0 to el.ElemCount-1 do begin sel:=el.Elements[i]; if sel.ElementType = letSection then sct.Add(sel) else begin hash.Add(sel.Name, sel); end; end; inc(j); end; finally sct.Free; end; end; procedure LayoutEnumElement(aparent: TLayoutSection; list: TList; LookFor: TLayoutElementTypes); var i : integer; begin if not Assigned(list) or not Assigned(aparent) or (LookFor = []) then Exit; for i:=0 to aparent.ElemCount-1 do begin if aparent.Elements[i].ElementType in LookFor then list.Add(aparent.Elements[i]); end; end; procedure LayoutGetUnused(cmd: TCmdLineCfg; layout: TLayoutSection; list: TList); var i : Integer; hash : TFPHashObjectList; opt : TCmdLineCfgOption; begin if not Assigned(cmd) or not Assigned(layout) or not Assigned(list) then Exit; hash := TFPHashObjectList.Create(false); try LayoutGetSwitches(layout, hash); for i:=0 to cmd.Options.Count-1 do begin opt:=TCmdLineCfgOption(cmd.Options[i]); if not Assigned(hash.Find(opt.Name)) then begin list.Add(opt); end; end; finally hash.Free; end; end; function LayoutFindElement(aparent: TLayoutSection; const Name: string; LookFor: TLayoutElementTypes = [letSection]): TLayoutSection; var i : integer; nm : string; begin Result:=nil; if not Assigned(aparent) or (LookFor = []) then Exit; nm:=AnsiLowerCase(Name); for i:=0 to aparent.ElemCount-1 do if (aparent.Elements[i].fElementType in LookFor) and (AnsiLowerCase(aparent.Elements[i].Name)=nm) then Result:=aparent.Elements[i]; end; { TLayoutSection } function TLayoutSection.AddElement(const AName: string; AElementType: TLayoutElementType): TLayoutSection; begin if ElemCount = length(Elements) then begin if ElemCount=0 then SetLength(Elements, 2) else SetLength(Elements, ElemCount*2); end; Result:=TLayoutSection.Create(AName, AElementType); Result.Display:=Aname; Elements[ElemCount]:=Result; inc(ElemCount); end; constructor TLayoutSection.Create(const AName: string; AElementType: TLayoutElementType); begin inherited Create; fName:=AName; fElementType:=AElementType; end; destructor TLayoutSection.Destroy; var i : integer; begin for i:=0 to ElemCount-1 do Elements[i].Free; inherited Destroy; end; { TCmdLineLayoutInfo } { function TCmdLineLayoutInfo.DoGetSection(const SectName: String; Forced: Boolean): TLayoutSection; var i : integer; begin i:=fSections.IndexOf(SectName); if (i<0) and Forced then begin Result:=TLayoutSection.Create; fSections.AddObject(SectName, Result); fValidOrder:=false; // a new section has been added, it might ruin the order end else if (i<0) and not Forced then begin Result:=nil; end else Result:=TLayoutSection(fSections.Objects[i]); end; } constructor TCmdLineLayoutInfo.Create; begin RootElement:=TLayoutSection.Create; RootElement.fName:=''; RootElement.fElementType:=letSection; end; destructor TCmdLineLayoutInfo.Destroy; begin RootElement.Free; inherited Destroy; end; {procedure TCmdLineLayoutInfo.AddSwitch(const Section: string; const SwitchOrName: string); begin GetSection(Section).fswitches.Add(SwitchOrName); end;} { function TCmdLineLayoutInfo.AddSection(const Section: string): TLayoutSection; begin Result:=DoGetSection(Section, true); end; function TCmdLineLayoutInfo.GetSection(const Section: string): TLayoutSection; begin Result:=DoGetSection(Section, false); end; } {function TCmdLineLayoutInfo.GetSections(Dst: TStrings): Boolean; var i : Integer; begin if not fValidOrder then begin SortSections; fValidOrder:=true; end; Dst.BeginUpdate; try for i:=0 to fSections.Count-1 do Dst.Add(fSections[i]); finally Dst.EndUpdate; end; Result:=True; end;} {function TCmdLineLayoutInfo.GetSwitches(const Section: string; Dst: TStrings): Boolean; var sct : TLayoutSection; begin sct:=GetSection(Section); Result:=Assigned(Sct); if not Result then Exit; Dst.AddStrings(sct.fswitches); end;} { TCmdLineUIControl } procedure TCmdLineUIControl.ValueChanged; begin if Assigned(fValueChanged) then fValueChanged(Self); end; end.
{ Subroutine SST_SET_DTYPES_COMBINE (DT_IN1,DT_IN2,DT_OUT_P) * * Make a composite data type, if possible, from two SET data types. * DT_IN1 and DT_IN2 are the data type descriptors for the two sets. * DT_OUT_P will be returned pointing to a composite data type that is a * superset of both SET data types. DT_OUT_P will be returned NIL if no * superset exists. * * It is assumed that DT_IN1 and DT_IN2 are SET data types. Results are * undefined when they are not. } module sst_SET_DTYPES_COMBINE; define sst_set_dtypes_combine; %include 'sst2.ins.pas'; procedure sst_set_dtypes_combine ( {make composite data type from two set dtypes} in dt_in1: sst_dtype_t; {data type descriptor for first set} in dt_in2: sst_dtype_t; {data type descriptor for second set} out dt_out_p: sst_dtype_p_t); {pnt to combined dtype, NIL = incompatible} var dt1s_p, dt2s_p: sst_dtype_p_t; {point to set base data types} dt1_p, dt2_p: sst_dtype_p_t; {point to set element base data types} dt1, dt2: sst_dtype_k_t; {set elements base data type ID} ord_min, ord_max: sys_int_max_t; {min/max ordinal value of all set elements} o1_min, o1_max: sys_int_max_t; {ordinal value limits for set 1} o2_min, o2_max: sys_int_max_t; {ordinal value limits for set 2} { ************************************************************ * * Local subroutine FIND_ORD (D,OMIN,OMAX) * * Find the ordinal value limits of the data type D. } procedure find_ord ( in d: sst_dtype_t; {data type descriptor} out omin, omax: sys_int_max_t); {returned ordinal value limits} begin case d.dtype of sst_dtype_int_k: begin omax := rshft(~0, 1); omin := ~omax; end; sst_dtype_enum_k: begin omin := 0; omax := d.enum_last_p^.enum_ordval; end; sst_dtype_bool_k: begin omin := 0; omax := 1; end; sst_dtype_char_k: begin omin := 0; omax := 255; end; sst_dtype_range_k: begin omin := d.range_ord_first; omax := omin + d.range_n_vals - 1; end; otherwise sys_message_bomb ('sst', 'dtype_not_ordinal', nil, 0); end; end; { ************************************************************ * * Start of main routine. } begin dt_out_p := nil; {init to set data types are incompatible} sst_dtype_resolve (dt_in1, dt1s_p, dt1); {resolve base data types of set elements} sst_dtype_resolve (dt1s_p^.set_dtype_p^, dt1_p, dt1); sst_dtype_resolve (dt_in2, dt2s_p, dt2); sst_dtype_resolve (dt2s_p^.set_dtype_p^, dt2_p, dt2); if dt1_p = dt2_p then begin {both sets have same base element data type ?} if dt2s_p^.set_dtype_final {pass back hard dtype if there is a choice} then dt_out_p := addr(dt_in2) else dt_out_p := addr(dt_in1); return; end; if dt_in1.set_dtype_final and dt_in2.set_dtype_final {both set dtypes hard fixed ?} then return; if {set 1 is NULL with unknown data type ?} (dt_in1.set_n_ent = 0) and (not dt_in1.set_dtype_final) then begin dt_out_p := addr(dt_in2); return; end; if {set 2 is NULL with unknown data type ?} (dt_in2.set_n_ent = 0) and (not dt_in2.set_dtype_final) then begin dt_out_p := addr(dt_in2); return; end; if dt1 <> dt2 then return; {base element data types incompatible ?} { * At this point we know that both sets have different data types, but that * the base data type IDs of the set elements are the same. Also, at least * one of the sets' data type is not hard-wired, so that there is still the * possibility of a combined data type. Each set is either the complete * set of the base data type, or a subrange of it. * * Now find the combined min and max ordinal values of all the possible elements * in both sets. } find_ord (dt1_p^, o1_min, o1_max); {get ordinal value limits of first set} find_ord (dt2_p^, o2_min, o2_max); {get ordinal value limits of second set} ord_min := min(o1_min, o2_min); {combine min/max ranges of both sets} ord_max := max(o1_max, o2_max); { * The ordinal value min/max limits for both sets, and the combined min/max * limits have been found. Now check for either set having a hard-wired * data type. This is OK as long as the combined ordinal value limit matches * the ordinal value limit for that set. } if dt_in1.set_dtype_final then begin {set 1 has hard wired data type ?} if (ord_min = o1_min) and (ord_max = o1_max) then begin {this set exactly matches combined limits} dt_out_p := addr(dt_in1); {use data type for this set directly} end else begin {other set is not a subset of this one} return; end ; end; if dt_in2.set_dtype_final then begin {set 2 has hard wired data type ?} if (ord_min = o2_min) and (ord_max = o2_max) then begin {this set exactly matches combined limits} dt_out_p := addr(dt_in2); {use data type for this set directly} end else begin {other set is not a subset of this one} return; end ; end; { * No conflict exists. We now know there definately exists a valid combined * data type. First check that one of the sets is a superset of the other, * in which case its data type is the combined data type. } if (o1_min = ord_min) and (o1_max = ord_max) then begin {set 1 is superset ?} dt_out_p := addr(dt_in1); return; end; if (o2_min = ord_min) and (o2_max = ord_max) then begin {set 2 is superset ?} dt_out_p := addr(dt_in2); return; end; { * Neither set is a complete superset of the other. This means we will need * to create our own data type. If the ordinal max range exactly matches the * base data type, then we will use it directly. Otherwise we will create * a subrange of it. } sst_dtype_new_subrange ( {create new data type, if necessary} dt1_p^, {base data type} ord_min, ord_max, {ordinal range of desired data type} dt2_p); {returned data type} sst_dtype_new (dt_out_p); {create and init new SET data type} dt_out_p^.dtype := sst_dtype_set_k; dt_out_p^.bits_min := ord_max - ord_min + 1; dt_out_p^.align_nat := sst_config.int_machine_p^.align_nat; dt_out_p^.align := dt_out_p^.align_nat; dt_out_p^.size_used := (dt_out_p^.bits_min + sst_config.bits_adr - 1) div sst_config.bits_adr; dt_out_p^.size_align := ((dt_out_p^.size_used + dt_out_p^.align - 1) div dt_out_p^.align) * dt_out_p^.align; dt_out_p^.set_dtype_p := dt2_p; dt_out_p^.set_n_ent := (dt_out_p^.bits_min + sst_set_ele_per_word -1) div sst_set_ele_per_word; dt_out_p^.set_dtype_final := false; end;
unit GX_IdeToolPropertiesEnhancer; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, StdCtrls, Forms; type TGxIdeToolPropertiesEnhancer = class public class function GetEnabled: Boolean; // static; class procedure SetEnabled(const Value: Boolean); //static; end; implementation uses GX_IdeFormEnhancer, GX_dzVclUtils, Controls, Messages; type TToolPropertiesEnhancer = class private FCallbackHandle: TFormChangeHandle; FIsAutocompleteEnabled: Boolean; // FControlChangedHandle: TControlChangeHandle; ///<summary> /// frm can be nil </summary> procedure HandleFormChanged(_Sender: TObject; _Form: TCustomForm); function IsToolPropertiesForm(_Form: TCustomForm): Boolean; procedure HandleFilesDropped(_Sender: TObject; _Files: TStrings); function TryFindEdit(_Form: TCustomForm; const _Name: string; out _ed: TEdit): Boolean; // procedure HandleControlChanged(_Sender: TObject; _Form: TCustomForm; _Control: TWinControl); public constructor Create; destructor Destroy; override; end; var TheToolPropertiesEnhancer: TToolPropertiesEnhancer = nil; { TGxIdeToolPropertiesEnhancer } class function TGxIdeToolPropertiesEnhancer.GetEnabled: Boolean; begin Result := Assigned(TheToolPropertiesEnhancer); end; class procedure TGxIdeToolPropertiesEnhancer.SetEnabled(const Value: Boolean); begin if Value then begin if not Assigned(TheToolPropertiesEnhancer) then TheToolPropertiesEnhancer := TToolPropertiesEnhancer.Create end else FreeAndNil(TheToolPropertiesEnhancer); end; { TToolPropertiesEnhancer } constructor TToolPropertiesEnhancer.Create; begin inherited Create; FCallbackHandle := TIDEFormEnhancements.RegisterFormChangeCallback(HandleFormChanged); end; destructor TToolPropertiesEnhancer.Destroy; begin TIDEFormEnhancements.UnregisterFormChangeCallback(FCallbackHandle); inherited; end; procedure TToolPropertiesEnhancer.HandleFilesDropped(_Sender: TObject; _Files: TStrings); var frm: TCustomForm; ed: TEdit; begin frm := Screen.ActiveCustomForm; if not IsToolPropertiesForm(frm) then Exit; ed := _Sender as TEdit; ed.Text := _Files[0]; if ed.Name = 'edProgram' then if TryFindEdit(frm, 'edWorkingDir', ed) then ed.Text := ExtractFileDir(_Files[0]); end; function TToolPropertiesEnhancer.IsToolPropertiesForm(_Form: TCustomForm): Boolean; begin Result := False; if not Assigned(_Form) then Exit; if not _Form.ClassNameIs('TTransEditDlg') or not SameText(_Form.Name, 'TransEditDlg') then Exit; Result := True; end; function TToolPropertiesEnhancer.TryFindEdit(_Form: TCustomForm; const _Name: string; out _ed: TEdit): Boolean; begin _ed := TEdit(_Form.FindComponent(_Name)); Result := Assigned(_ed); end; procedure TToolPropertiesEnhancer.HandleFormChanged(_Sender: TObject; _Form: TCustomForm); var ed: TEdit; begin if not IsToolPropertiesForm(_Form) then begin // TIDEFormEnhancements.UnregisterControlChangeCallback(FControlChangedHandle); // FControlChangedHandle := nil; FIsAutocompleteEnabled := False; Exit; end; // Drop files only works in Delphi 6 and 7 while autocomplete works in all versions. // The "new" IDE apparently does something to TEdits that prevent them to receive WM_DROPFILES // messages. // I tried to use this for re-registering the drop files handler but it did not help: // FControlChangedHandle := TIDEFormEnhancements.RegisterControlChangeCallback(HandleControlChanged); if TryFindEdit(_Form, 'edProgram', ed) then begin TWinControl_ActivateDropFiles(ed, HandleFilesDropped); TEdit_ActivateAutoComplete(ed, [acsFileSystem], [actSuggest]); end; if TryFindEdit(_Form, 'edWorkingDir', ed) then begin TWinControl_ActivateDropFiles(ed, HandleFilesDropped); TEdit_ActivateAutoComplete(ed, [acsFileSystem], [actSuggest]); end; if TryFindEdit(_Form, 'edParameters', ed) then begin TWinControl_ActivateDropFiles(ed, HandleFilesDropped); TEdit_ActivateAutoComplete(ed, [acsFileSystem], [actSuggest]); end; end; //procedure TToolPropertiesEnhancer.HandleControlChanged(_Sender: TObject; _Form: TCustomForm; _Control: TWinControl); //var // i: Integer; //begin // if not IsToolPropertiesForm(_Form) then begin // FIsAutocompleteEnabled := False; // Exit; // end; // if not (_Control is TEdit) then // Exit; // for i := _Control.ComponentCount-1 downto 0 do begin // if _Control.Components[i].ClassNameIs('TDropFilesActivator') then begin // _Control.Components[i].Free; // TWinControl_ActivateDropFiles2(_Control, HandleFilesDropped); // end; // end; //end; initialization finalization TGxIdeToolPropertiesEnhancer.SetEnabled(False); end.
unit uActions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Menus, StdCtrls, ActnList, XPStyleActnCtrls, ActnMan, Grids, uOperations, uHi, uSound; procedure SaveTable(Table : TStringGrid; str : string); procedure SaveEditDet(Edit : TEdit); procedure SaveEditSled(Edit : TEdit); procedure CheckString(var Table : TStringGrid; i , j :integer; var flag : boolean); procedure CheckEdit(var Edit : TEdit; var flag : boolean); procedure SetEdit(Edit : TEdit; var size : integer; var sch1 : Byte; var sch2 : Byte);//sch1, sch2 для отслеживания числа некорретных эдитов procedure SetEditPow(Edit : TEdit;var flag : Boolean; var size : Integer); procedure Clean(Table : TStringGrid); procedure Add; procedure Determinate; function Det(arr : TMatrix; r : integer; c : TColumn; const n : integer) : real; procedure Sub; procedure MultMatrix; procedure MultNumb; procedure Pow; procedure Transpose; procedure ObrTranspose; procedure Music(s : string); procedure Sled; implementation procedure Music(s : string); begin fmOper.MediaPlayer1.FileName := way + s; fmOper.MediaPlayer1.Open; fmOper.MediaPlayer1.Play; end; //процедура сохранения информации из таблицы в файл procedure SaveTable(Table: TStringGrid; str : string); var i, j: integer; begin if n = 0 then assignfile(f, way + 'Результаты вычислений.txt') //если уже создан документ ('Результаты вычислений.txt') else assignfile(f, fmOper.SaveDialog1.FileName); append(f); write(f, 'Результат ' + str + ':'); with Table do for i:=0 to RowCount-1 do begin for j:=0 to ColCount-1 do write(f, Table.cells[j, i] + ' '); writeln(f, #13 + #13); end; closefile(f); end; //процедура сохранения данных из поля в файл procedure SaveEditDet(Edit : TEdit); begin if n = 0 then assignfile(f, way + 'Результаты вычислений.txt') else assignfile(f, fmOper.SaveDialog1.FileName); append(f); writeln(f, 'Результат нахождения определителя:'); writeln(f, Edit.Text); writeln(f, #13 + #13); closefile(f); end; //процедура сохранения данных из поля в файл procedure SaveEditSled(Edit : TEdit); begin if n = 0 then assignfile(f, way + 'Результаты вычислений.txt') else assignfile(f, fmOper.SaveDialog1.FileName); append(f); writeln(f, 'Результат нахождения следа матрицы:'); writeln(f, Edit.Text); writeln(f, #13 + #13); closefile(f); end; //процедура проверки ячеек таблицы на корректность procedure CheckString(var Table : TStringGrid; i, j: integer; var flag : boolean); var k, x : integer; curr : string; begin flag := true; x := 0; curr := Table.Cells[j+1, i+1]; for k := 1 to length(curr) do begin if curr[k] = ',' then inc(x); if curr[k] = '.' then curr[k] := ','; if not(curr[k] in ['0','1','2','3','4','5','6','7','8','9', ',','-']) or (length(curr) = 1) and (curr[1] = '-') or (length(curr) > 1) and (k >= 2) and (curr[k] = '-') or (curr[1] = ',') or (x > 1) then begin messagebox(fmoper.Handle, pchar('Некорректные данные! Результаты также неверны!'), pchar('Ошибка'), mb_ok+mb_iconerror); flag := false; break; end; end; Table.Cells[j+1, i+1] := curr; end; //процедура проверки поля на корректность procedure CheckEdit(var Edit : TEdit; var flag : boolean); var k, x : integer; curr : string; begin flag := true; x := 0; curr := Edit.Text; for k := 1 to length(curr) do begin if curr[k] = ',' then inc(x); if curr[k] = '.' then curr[k] := ','; if not(curr[k] in ['0','1','2','3','4','5','6','7','8','9', ',','-']) or (length(curr) = 1) and (curr[1] = '-') or (length(curr) > 1) and (k >= 2) and (curr[k] = '-') or (curr[1] = ',') or (x > 1) then begin messagebox(fmoper.Handle, pchar('Некорректные данные! Результаты также неверны!'), pchar('Ошибка!'), mb_ok+mb_iconerror); flag := false; break; end; end; Edit.Text := curr; end; //процедура очистки всех ячеек таблицы procedure Clean(Table : TStringGrid); var i :integer; begin with Table do for i := 0 to ColCount-1 do Cols[i].Clear; end; //процедура преобразования информации из поля в нужный тип procedure SetEdit(Edit : TEdit; var size : Integer; var sch1 : Byte; var sch2 : Byte); //sch1, sch2 для отслеживания числа некорретных эдитов begin try if (strtofloat(Edit.Text) <= 0) then begin size := 1; if sch1=0 then messagebox(fmoper.Handle, pchar('Некорректные данные! Размерность матрицы должна быть целым положительным числом. Произведена автоматическая замена на 1. Для подтверждения нажмите OK.'), pchar('Ошибка!'), mb_ok+mb_iconerror); inc(sch1); size := 1; Edit.Text := '1'; Exit; end else size := trunc(strtofloat(Edit.Text)); except if sch2=0 then messagebox(fmoper.Handle, pchar('Некорректные данные! Вы не ввели параметр(-ы) размерности матрицы. Произведена автоматическая замена на 1. Для подтверждения нажмите OK.'), pchar('Ошибка!'), mb_ok+mb_iconerror); inc(sch2); size := 1; Edit.Text := '1'; end; if size > 10 then size := 10; Edit.Text := inttostr(size); end; //процедура преобразования информации из edNumbPow в нужный тип procedure SetEditPow(Edit : TEdit; var flag : Boolean; var size : Integer); //numb для отслеживания числа некорретных эдитов begin flag := True; try if (strtofloat(Edit.Text) <= 0) then begin size := 1; messagebox(fmoper.Handle, pchar('Некорректные данные! В качестве степени матрицы можно вводить лишь целые положительные числа! Произведена автоматическая замена степени на 1. Для подтверждения нажмите OK.'), pchar('Ошибка!'), mb_ok+mb_iconerror); Edit.Text := '1'; flag := False; Exit; end else size := trunc(strtofloat(Edit.Text)); if size > 10 then size := 10; Edit.Text := inttostr(size); except messagebox(fmoper.Handle, pchar('Некорректные данные! Вы не ввели степень! Произведена автоматическая замена степени на 1. Для подтверждения нажмите OK.'), pchar('Ошибка!'), mb_ok+mb_iconerror); Edit.Text := '1'; size :=1 ; flag := False; Exit; end; end; /////////////////////////////////////////////////////////////////////////////// // раздел описания процедур и функций над матрицами(1) //процедура сложения procedure Add; var i, j, k:integer; arr1, arr2, arr3: TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1, size2); setlength(arr2, size1, size2); setlength(arr3, size1, size2); for i := 0 to size1-1 do for j := 0 to size2-1 do begin CheckString(fmOper.strFirstAdd, i, j, flag); if flag = false then exit; if fmOper.strFirstAdd.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strFirstAdd.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strFirstAdd.Cells[j+1, i+1]); if iden = 0 then //матрица begin CheckString(fmOper.strSecondAdd, i, j, flag); if flag = false then exit; if fmOper.strSecondAdd.Cells[j+1, i+1] = '' then begin arr2[i, j] := 0; fmOper.strSecondAdd.Cells[j+1, i+1] := '0'; end else arr2[i, j] := strtofloat(fmOper.strSecondAdd.Cells[j+1, i+1]); end else arr2[i, j] := numb; arr3[i, j] := arr1[i, j] + arr2[i, j]; fmOper.strResultAdd.Cells[j+1, i+1] := floattostr(arr3[i, j]); end; SaveTable(fmOper.strResultAdd, 'сложения'); end; //процедура вычитания procedure Sub; var i, j:integer; arr1, arr2, arr3: TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1, size2); setlength(arr2, size1, size2); setlength(arr3, size1, size2); for i := 0 to size1-1 do for j := 0 to size2-1 do begin CheckString(fmOper.strFirstSub, i, j, flag); if flag = false then exit; if fmOper.strFirstSub.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strFirstSub.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strFirstSub.Cells[j+1, i+1]); if iden = 0 then begin CheckString(fmOper.strSecondSub, i, j, flag); if flag = false then exit; if fmOper.strSecondSub.Cells[j+1, i+1] = '' then begin arr2[i, j] := 0; fmOper.strSecondSub.Cells[j+1, i+1] := '0'; end else arr2[i, j] := strtofloat(fmOper.strSecondSub.Cells[j+1, i+1]) end else arr2[i, j] := numb ; if sign = 1 then arr3[i, j] := arr1[i, j] - arr2[i, j] else arr3[i, j] := -arr1[i, j] + arr2[i, j]; fmOper.strResultSub.Cells[j+1, i+1] := floattostr(arr3[i, j]); end; SaveTable(fmOper.strResultSub, 'вычитания'); end; //процедура умножения матрицы на число procedure MultNumb; var i, j: integer; arr1, arr2: TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1, size2); setlength(arr2, size1, size2); for i := 0 to size1-1 do for j := 0 to size2-1 do begin CheckString(fmOper.strMultNumb, i, j, flag); if flag = false then exit; if fmOper.strMultNumb.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strMultNumb.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strMultNumb.Cells[j+1, i+1]); arr2[i, j] := arr1[i, j] * numb ; fmOper.strResultMultNumb.Cells[j+1, i+1] := floattostrf(arr2[i, j], ffGeneral, 8, 4); end; SaveTable(fmOper.strResultMultNumb, 'умножения на число'); end; //процедура возведения матрицы в степень procedure Pow; var ia, ib, ja, jb, k, i, j: integer; s : real; arr1, arr2, arr3: TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1 ,size1); setlength(arr2, size1 ,size1); setlength(arr3, size1 ,size1); for i:=0 to size1-1 do for j:=0 to size1-1 do begin CheckString(fmOper.strPow, i, j, flag); if flag = false then exit; if fmOper.strPow.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strPow.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strPow.cells[j+1, i+1]); arr2[i, j] := arr1[i, j]; end; if numb1 = 1 then for i := 1 to size1 do for j := 1 to size1 do fmOper.strResultPow.Cells[j, i] := fmOper.strPow.Cells[j, i] else begin k:=1; while k <= numb1-1 do begin for ia:=0 to size1-1 do for jb:=0 to size1-1 do begin s := 0; ja := 0; ib := 0; while (ja <= size1-1) do begin s := s + arr1[iA, jA] * arr2[iB,jB]; inc(ja); inc(ib); end; arr3[ia,jb] := s; end; inc(k); for i:=0 to size1-1 do for j:=0 to size1-1 do arr2[i, j] := arr3[i, j]; end; for i := 0 to size1-1 do for j := 0 to size1-1 do fmOper.strResultPow.cells[j+1, i+1] := floattostrf(arr3[i, j], ffGeneral, 8, 4); end; SaveTable(fmOper.strResultPow, 'возведения в степень'); end; //функция вычисления определителя function Det(arr : TMatrix; r : integer; c: TColumn; const n : integer) : real; var i : integer; sum : real; minusflag : boolean; begin sum := 0; minusflag := false; if r = n then begin for i := 0 to n-1 do if not(i in c) then sum := arr [i, r-1]; end else for i := 0 to n-1 do if not(i in c) then begin include(c, i); if not minusflag then sum := sum + arr[i, r-1] * Det(arr, r+1, c, n) else sum := sum - arr[i, r-1] * Det(arr, r+1, c, n); exclude(c, i); minusflag := not minusflag; end; result := sum; end; //процедура нахождения определителя procedure Determinate; var arr : TMatrix; i, j : integer; flag : boolean; begin flag := true; setlength(arr, size1, size1); for i := 0 to size1-1 do for j := 0 to size1-1 do begin CheckString(fmOper.strDet, i, j, flag); if flag = false then exit; if fmOper.strDet.Cells[j+1, i+1] = '' then begin arr[i, j] := 0; fmOper.strDet.Cells[j+1, i+1] := '0'; end else arr[i, j] := strtofloat(fmOper.strDet.Cells[j+1, i+1]); end; fmOper.edResultDet.Text := floattostr(det(arr, 1, [], size1)); SaveEditDet(fmOper.edResultDet); end; //процедура перемножения матриц procedure MultMatrix; var arr1, arr2, arr3 : TMatrix; iA, jA, iB, jB, i, j : integer; sum : real; flag : boolean; begin flag := true; setlength(arr1, size1, size2); setlength(arr2, size1mult, size2mult); setlength(arr3, sizeresmult1, sizeresmult2); for i := 0 to size1-1 do for j := 0 to size2-1 do begin CheckString(fmOper.strFirstMultMatr, i, j, flag); if flag = false then exit; if fmOper.strFirstMultMatr.cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strFirstMultMatr.cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strFirstMultMatr.Cells[j+1, i+1]); end; for i := 0 to size1mult-1 do for j := 0 to size2mult-1 do begin CheckString(fmOper.strSecondMultMatr, i, j, flag); if flag = false then exit; if fmOper.strSecondMultMatr.cells[j+1, i+1] = '' then begin arr2[i, j] := 0; fmOper.strSecondMultMatr.cells[j+1, i+1] := '0'; end else arr2[i, j] := strtofloat(fmOper.strSecondMultMatr.Cells[j+1, i+1]); end; for iA := 0 to size1-1 do for jB := 0 to size2mult-1 do begin sum := 0; jA := 0; iB := 0; while (jA <= size2-1) and (iB <= size1mult-1) do begin sum := sum + arr1[iA, jA] * arr2[iB, jB]; inc(jA); inc(iB); end; arr3[iA, jB] := sum; end; for i := 0 to sizeresmult1-1 do for j := 0 to sizeresmult2-1 do fmOper.strResultMultMatr.Cells[j+1, i+1] := floattostrf(arr3[i, j], ffGeneral, 8, 4); SaveTable(fmOper.strResultMultMatr, 'перемножения матриц'); end; //процедура транспонирования матрицы procedure Transpose; var i, j : integer; k : real; arr1, arr2 : TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1, size2); setlength(arr2, size2, size1); for i := 0 to size1-1 do for j := 0 to size2-1 do begin CheckString(fmOper.strTranspose, i, j, flag); if flag = false then exit; if fmOper.strTranspose.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strTranspose.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strTranspose.Cells[j+1, i+1]); end; for i := 0 to size2-1 do for j := 0 to size1-1 do arr2[i, j] := arr1[j, i]; for i := 0 to size2-1 do for j := 0 to size1-1 do fmOper.strResultTranspose.Cells[j+1, i+1] := floattostr(arr2[i, j]); SaveTable(fmOper.strResultTranspose, 'транспонирования'); end; //процедура транспонирования матрицы относительно побочной диагонали procedure ObrTranspose; var i, j : integer; tmp, k : real; arr1, arr2 : TMatrix; flag : boolean; begin flag := true; setlength(arr1, size1, size1); setlength(arr2, size1+1, size1+1); for i := 0 to size1-1 do for j := 0 to size1-1 do begin CheckString(fmOper.strObrTranspose, i, j, flag); if flag = false then exit; if fmOper.strObrTranspose.Cells[j+1, i+1] = '' then begin arr1[i, j] := 0; fmOper.strObrTranspose.Cells[j+1, i+1] := '0'; end else arr1[i, j] := strtofloat(fmOper.strObrTranspose.Cells[j+1, i+1]); end; for i := 1 to (size1) do for j := 1 to (size1) do arr2[i, j] := arr1[i-1, j-1]; for i:=1 to size1-1 do for j:=1 to size1-i do begin tmp:=arr2[i,j]; arr2[i,j]:=arr2[size1-j+1,size1-i+1]; arr2[size1-j+1,size1-i+1]:=tmp; end; for i := 1 to size1 do for j := 1 to size1 do fmOper.strResultObrTranspose.Cells[j, i] := floattostr(arr2[i, j]); SaveTable(fmOper.strResultTranspose, 'транспонирования относительно побочной диагонали'); end; //процедура нахождения следа матрицы procedure Sled; var arr : TMatrix; i, j : integer; sum : Real; flag : boolean; begin flag := true; setlength(arr, size1, size1); for i := 0 to size1-1 do for j := 0 to size1-1 do begin CheckString(fmOper.strSled, i, j, flag); if flag = false then exit; if fmOper.strSled.Cells[j+1, i+1] = '' then begin arr[i, j] := 0; fmOper.strSled.Cells[j+1, i+1] := '0'; end else arr[i, j] := strtofloat(fmOper.strSled.Cells[j+1, i+1]); end; sum:=0; for i:=0 to (size1-1) do for j:=0 to (size1-1) do if i=j then sum := sum + arr[i,j]; fmOper.edResultSled.Text := floattostr(sum); SaveEditSled(fmOper.edResultSled); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2017 * } { *********************************************************** } unit tfHashes; interface {$I TFL.inc} uses SysUtils, Classes, tfTypes, tfArrays, tfConsts, tfExceptions, {$IFDEF TFL_DLL} tfImport {$ELSE} tfHashServ, tfHMAC {$ENDIF}; type THMAC = record private FInstance: IHMACAlgorithm; public // class function Create(const HMACAlg: IHMACAlgorithm): THMAC; static; procedure Free; function IsAssigned: Boolean; procedure Init(const AKey: ByteArray); inline; procedure Update(const Data; DataSize: LongWord); inline; procedure Done(var Digest); inline; procedure Burn; inline; function DigestSize: LongInt; inline; procedure GetDigest(var Buffer; BufSize: Cardinal); function Digest: ByteArray; class function Copy(Instance: THMAC): THMAC; static; class function MD5: THMAC; static; class function SHA1: THMAC; static; class function SHA256: THMAC; static; class function SHA512: THMAC; static; class function SHA224: THMAC; static; class function SHA384: THMAC; static; // class function GetInstance(const Name: string): THMAC; overload; static; class function GetInstance(AlgID: TAlgID): THMAC; overload; static; // class operator Explicit(const Name: string): THMAC; // class operator Explicit(AlgID: Integer): THMAC; function ExpandKey(const Key; KeySize: LongWord): THMAC; overload; function ExpandKey(const Key: ByteArray): THMAC; overload; function UpdateData(const Data; DataSize: LongWord): THMAC; function UpdateByteArray(const Bytes: ByteArray): THMAC; function UpdateStream(Stream: TStream; BufSize: Integer = 0): THMAC; function UpdateFile(const AFileName: string; BufSize: Integer = 0): THMAC; function DeriveKey(const Password, Salt: ByteArray; Rounds, DKLen: Integer): ByteArray; // property Algorithm: IHMACAlgorithm read FAlgorithm; end; THash = record // private // class var FServer: IHashServer; private FInstance: IHash; public // class function Create(const HashAlg: IHashAlgorithm): THash; static; procedure Free; function IsAssigned: Boolean; procedure Burn; function Clone: THash; procedure Init; inline; procedure Update(const Data; DataSize: Cardinal); inline; procedure Done(var Digest); inline; procedure GetDigest(var Buffer; BufSize: Cardinal); function DigestSize: LongInt; inline; function BlockSize: LongInt; inline; function Digest: ByteArray; class function CRC32: THash; static; class function Jenkins1: THash; static; class function MD5: THash; static; class function SHA1: THash; static; class function SHA256: THash; static; class function SHA512: THash; static; class function SHA224: THash; static; class function SHA384: THash; static; // class function Copy(Instance: THash): THash; static; class function GetCount: Integer; static; class function GetID(Index: Integer): TAlgID; static; class function GetName(Index: Integer): string; static; class function GetIDByName(const Name: string): TAlgID; static; class function GetNameByID(AlgID: TAlgID): string; static; // class function GetInstance(const Name: string): THash; overload; static; class function GetInstance(AlgID: TAlgID): THash; overload; static; // class operator Explicit(const Name: string): THash; // class operator Explicit(AlgID: Integer): THash; function UpdateData(const Data; DataSize: LongWord): THash; function UpdateByteArray(const Bytes: ByteArray): THash; function UpdateStream(Stream: TStream; BufSize: Integer = 0): THash; function UpdateFile(const AFileName: string; BufSize: Integer = 0): THash; function DeriveKey(const Password, Salt: ByteArray; Rounds, DKLen: Integer): ByteArray; // property Algorithm: IHashAlgorithm read FInstance; end; type EHashError = class(EForgeError); implementation procedure HashError(ACode: TF_RESULT; const Msg: string = ''); begin raise EHashError.Create(ACode, Msg); end; procedure HResCheck(Value: TF_RESULT); inline; begin if Value <> TF_S_OK then HashError(Value); end; // FServer is a singleton, no memory leak because of global intf ref var FServer: IHashServer; function GetServer: IHashServer; begin if FServer = nil then HResCheck(GetHashServerInstance(FServer)); Result:= FServer; end; { THash } (* class function THash.Create(const HashAlg: IHashAlgorithm): THash; begin Result.FInstance:= HashAlg; end; *) procedure THash.Free; begin FInstance:= nil; end; procedure THash.GetDigest(var Buffer; BufSize: Cardinal); begin if BufSize <> Cardinal(DigestSize) then HashError(TF_E_INVALIDARG); FInstance.Done(@Buffer); end; (* class function THash.GetInstance(const Name: string): THash; begin HResCheck(FServer.GetByName(Pointer(Name), SizeOf(Char), Result.FAlgorithm)); end; *) class function THash.GetID(Index: Integer): TAlgID; begin HResCheck(GetServer.GetID(Index, Result)); end; class function THash.GetInstance(AlgID: TAlgID): THash; begin HResCheck(GetHashInstance(AlgID, Result.FInstance)); end; function THash.IsAssigned: Boolean; begin Result:= FInstance <> nil; end; procedure THash.Init; begin FInstance.Init; end; procedure THash.Update(const Data; DataSize: Cardinal); begin FInstance.Update(@Data, DataSize); end; procedure THash.Done(var Digest); begin FInstance.Done(@Digest); end; (* class operator THash.Explicit(const Name: string): THash; begin HResCheck(FServer.GetByName(Pointer(Name), SizeOf(Char), Result.FAlgorithm)); end; class operator THash.Explicit(AlgID: Integer): THash; begin HResCheck(FServer.GetByAlgID(AlgID, Result.FAlgorithm)); end; *) procedure THash.Burn; begin FInstance.Burn; end; function THash.DigestSize: LongInt; begin Result:= FInstance.GetDigestSize; end; function THash.BlockSize: LongInt; begin Result:= FInstance.GetBlockSize; end; function THash.Digest: ByteArray; begin Result:= ByteArray.Allocate(DigestSize); FInstance.Done(Result.GetRawData); end; function THash.Clone: THash; begin HResCheck(FInstance.Duplicate(Result.FInstance)); end; (* class function THash.Copy(Instance: THash): THash; begin HResCheck(Instance.FInstance.Duplicate(Result.FInstance)); end; *) class function THash.GetCount: Integer; begin Result:= GetServer.GetCount; end; class function THash.CRC32: THash; begin HResCheck(GetHashInstance(TF_ALG_CRC32, Result.FInstance)); end; class function THash.Jenkins1: THash; begin HResCheck(GetHashInstance(TF_ALG_JENKINS1, Result.FInstance)); end; class function THash.MD5: THash; begin HResCheck(GetHashInstance(TF_ALG_MD5, Result.FInstance)); end; class function THash.SHA1: THash; begin HResCheck(GetHashInstance(TF_ALG_SHA1, Result.FInstance)); end; class function THash.SHA224: THash; begin HResCheck(GetHashInstance(TF_ALG_SHA224, Result.FInstance)); end; class function THash.SHA256: THash; begin HResCheck(GetHashInstance(TF_ALG_SHA256, Result.FInstance)); end; class function THash.SHA384: THash; begin HResCheck(GetHashInstance(TF_ALG_SHA384, Result.FInstance)); end; class function THash.SHA512: THash; begin HResCheck(GetHashInstance(TF_ALG_SHA512, Result.FInstance)); end; function THash.DeriveKey(const Password, Salt: ByteArray; Rounds, DKLen: Integer): ByteArray; begin HResCheck(GetServer.PBKDF1(FInstance, Password.GetRawData, Password.GetLen, Salt.GetRawData, Salt.GetLen, Rounds, DKLen, IBytes(Result))); end; class function THash.GetName(Index: Integer): string; var P: Pointer; // Bytes: IBytes; // I, L: Integer; // P: PByte; begin HResCheck(GetServer.GetName(Index, P)); Result:= string(UTF8String(PAnsiChar(P))); // Result:= string(PUTF8String(P)^); { L:= Bytes.GetLen; P:= Bytes.GetRawData; SetLength(Result, L); for I:= 1 to L do begin Result[I]:= Char(P^); Inc(P); end; } end; class function THash.GetIDByName(const Name: string): TAlgID; begin HResCheck(GetServer.GetIDByName(Pointer(Name), SizeOf(Char), Result)); end; class function THash.GetNameByID(AlgID: TAlgID): string; var P: Pointer; begin HResCheck(GetServer.GetNameByID(AlgID, P)); Result:= string(PUTF8String(P)^); end; function THash.UpdateData(const Data; DataSize: LongWord): THash; begin FInstance.Update(@Data, DataSize); Result.FInstance:= FInstance; end; function THash.UpdateByteArray(const Bytes: ByteArray): THash; begin FInstance.Update(Bytes.RawData, Bytes.Len); Result.FInstance:= FInstance; end; function THash.UpdateStream(Stream: TStream; BufSize: Integer): THash; const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; var Buffer: Pointer; N: Integer; begin if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE; GetMem(Buffer, BufSize); try repeat N:= Stream.Read(Buffer^, BufSize); if N <= 0 then Break else FInstance.Update(Buffer, N); until False; Result.FInstance:= FInstance; finally FreeMem(Buffer); end; end; function THash.UpdateFile(const AFileName: string; BufSize: Integer): THash; var Stream: TStream; begin Stream:= TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result:= UpdateStream(Stream, BufSize); finally Stream.Free; end; end; { THMAC } (* class function THMAC.Create(const HMACAlg: IHMACAlgorithm): THMAC; begin Result.FInstance:= HMACAlg; end; *) procedure THMAC.Free; begin FInstance:= nil; end; function THMAC.IsAssigned: Boolean; begin Result:= FInstance <> nil; end; procedure THMAC.Init(const AKey: ByteArray); begin FInstance.Init(AKey.GetRawData, AKey.GetLen); end; procedure THMAC.Update(const Data; DataSize: LongWord); begin FInstance.Update(@Data, DataSize); end; procedure THMAC.Done(var Digest); begin FInstance.Done(@Digest); end; (* class function THMAC.GetInstance(const Name: string): THMAC; var HashAlgorithm: IHashAlgorithm; begin HResCheck(THash.FServer.GetByName(Pointer(Name), SizeOf(Char), HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FAlgorithm), HashAlgorithm)); end; *) class function THMAC.GetInstance(AlgID: TAlgID): THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(AlgID, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; (* class operator THMAC.Explicit(const Name: string): THMAC; var HashAlgorithm: IHashAlgorithm; begin HResCheck(THash.FServer.GetByName(Pointer(Name), SizeOf(Char), HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FAlgorithm), HashAlgorithm)); end; class operator THMAC.Explicit(AlgID: Integer): THMAC; var HashAlgorithm: IHashAlgorithm; begin HResCheck(THash.FServer.GetByAlgID(AlgID, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FAlgorithm), HashAlgorithm)); end; *) procedure THMAC.Burn; begin FInstance.Burn; end; function THMAC.DigestSize: LongInt; begin Result:= FInstance.GetDigestSize; end; procedure THMAC.GetDigest(var Buffer; BufSize: Cardinal); begin if BufSize <> Cardinal(DigestSize) then HashError(TF_E_INVALIDARG); FInstance.Done(@Buffer); end; function THMAC.Digest: ByteArray; begin Result:= ByteArray.Allocate(DigestSize); FInstance.Done(Result.GetRawData); end; class function THMAC.Copy(Instance: THMAC): THMAC; begin HResCheck(Instance.FInstance.Duplicate(Result.FInstance)); end; class function THMAC.MD5: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_MD5, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; class function THMAC.SHA1: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_SHA1, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; class function THMAC.SHA224: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_SHA224, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; class function THMAC.SHA256: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_SHA256, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; class function THMAC.SHA384: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_SHA384, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; class function THMAC.SHA512: THMAC; var HashAlgorithm: IHash; begin HResCheck(GetHashInstance(TF_ALG_SHA512, HashAlgorithm)); HResCheck(GetHMACAlgorithm(PHMACAlg(Result.FInstance), HashAlgorithm)); end; function THMAC.DeriveKey(const Password, Salt: ByteArray; Rounds, DKLen: Integer): ByteArray; begin HResCheck(FInstance.PBKDF2( Password.GetRawData, Password.GetLen, Salt.GetRawData, Salt.GetLen, Rounds, DKLen, IBytes(Result))); end; function THMAC.ExpandKey(const Key; KeySize: LongWord): THMAC; begin FInstance.Init(@Key, KeySize); Result.FInstance:= FInstance; end; function THMAC.ExpandKey(const Key: ByteArray): THMAC; begin FInstance.Init(Key.GetRawData, Key.GetLen); Result.FInstance:= FInstance; end; function THMAC.UpdateData(const Data; DataSize: LongWord): THMAC; begin FInstance.Update(@Data, DataSize); Result.FInstance:= FInstance; end; function THMAC.UpdateByteArray(const Bytes: ByteArray): THMAC; begin FInstance.Update(Bytes.RawData, Bytes.Len); Result.FInstance:= FInstance; end; function THMAC.UpdateStream(Stream: TStream; BufSize: Integer): THMAC; const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; var Buffer: Pointer; N: Integer; begin if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE; GetMem(Buffer, BufSize); try repeat N:= Stream.Read(Buffer^, BufSize); if N <= 0 then Break else FInstance.Update(Buffer, N); until False; Result.FInstance:= FInstance; finally FreeMem(Buffer); end; end; function THMAC.UpdateFile(const AFileName: string; BufSize: Integer): THMAC; var Stream: TStream; begin Stream:= TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result:= UpdateStream(Stream, BufSize); finally Stream.Free; end; end; (* {$IFNDEF TFL_DLL} initialization GetHashServerInstance(THash.FServer); {$ENDIF} *) end.
{----------------------------------------------------------------------------- Unit Name: dataMod Author: J. L. Vasser (FMCSA) Date: 2017-10-02 Purpose: Data Module for Data Pull. Provides the bridge between the SAFER Oracle-based database and the Firedbird-based Local Aspen / ISS database History: 2018-02-05 JLV - Removed "where MCMIS_STATUS = 'A'" clause from all child table SAFER queries. Due to the time lag involved after creating the parent table (CARRIERS), many records had become inactive. This then caused the child record to not be found 2018-02-07 JLV - Modifed query on UCR to limit the amount of (useless) data returned. See frmMain.DoUCRLoad function 2018-02-20 JLV - Removed unused data objects and related code. 2019-02-03 JLV - Added a data module for using SQLite database for the local database. This is much smaller and MUCH MUCH faster. Then moved the Firebird database to its own data module to allow keeping the database components the same. -----------------------------------------------------------------------------} unit dataMod; interface uses System.SysUtils, System.Classes, DALoader, UniLoader, Uni, Data.DB, MemDS, DBAccess, InterBaseUniProvider, UniProvider, OracleUniProvider, UniScript, CRBatchMove, DAScript, System.UITypes, Dialogs, Vcl.Forms, System.StrUtils, VirtualTable; type TdmPull = class(TDataModule) providerSAFER: TOracleUniProvider; dbSAFER: TUniConnection; qryISS: TUniQuery; qryCarrier: TUniQuery; qryUCR: TUniQuery; qryNAME: TUniQuery; qryNAME2: TUniQuery; qryHMPermit: TUniQuery; qryINS: TUniQuery; qryBASICS: TUniQuery; qryNAMEUSDOTNUM: TStringField; qryNAMENAME: TStringField; qryNAMECITY: TStringField; qryNAMESTATE: TStringField; qryNAMENAME_TYPE_ID: TStringField; //procedure tblCarriersCalcFields(DataSet: TDataSet); //procedure tblUCRCalcFields(DataSet: TDataSet); //procedure tblISSCalcFields(DataSet: TDataSet); //procedure tblUpdateStatusCalcFields(DataSet: TDataSet); private { Private declarations } public { Public declarations } //function GetCountryDesc(const CountryCode: string): string; //function RebuildIdx: Boolean; end; var dmPull: TdmPull; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses formMain; {$R *.dfm} { procedure TdmPull.tblCarriersCalcFields(DataSet: TDataSet); begin TblCarriersCountryCalc.AsString := GetCountryDesc(tblCarriers.FieldByName('COUNTRY').AsString); end; procedure TdmPull.tblISSCalcFields(DataSet: TDataSet); begin if (qryIss.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsInteger = 0) then tblIssVehicleOOSRate.AsInteger := qryIss.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsInteger else tblIssVehicleOOSRate.AsFloat := qryIss.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsInteger / qryIss.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsInteger; if (tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger = 0) then tblIssDriverOOSRate.Value := tblIss.FieldByName('OOS_DRIVER').AsFloat else tblIssDriverOOSRate.Value := tblIss.FieldByName('OOS_DRIVER').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat; tblIssVehicleOOSPercent.Value := tblIssVehicleOOSRate.AsFloat * 100; tblIssDriverOOSPercent.Value := tblIssDriverOOSRate.AsFLoat * 100; if (tblCarriers.FieldByName('TOTAL_VEHICLES').AsInteger = 0) then tblIssInspPerVehicle.Value := tblIss.FieldByName('VEHICLE_INSPECTIONS').AsFloat else tblIssInspPerVehicle.Value := tblIss.FieldByName('VEHICLE_INSPECTIONS').AsFloat / tblCarriers.FieldByName('TOTAL_VEHICLES').AsFloat; if (tblCarriers.FieldByName('TOTAL_DRIVERS').AsInteger = 0) then tblIssInspPerDriver.Value := tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat else tblIssInspPerDriver.Value := tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat / tblCarriers.FieldByName('TOTAL_DRIVERS').AsFloat; if (tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger = 0) then begin tblISSv1BrakesRate.AsFloat := tblIss.FieldByName('VIOL_BRAKES').AsFloat; tblIssv1WheelRate.AsFloat := tblIss.FieldByName('VIOL_WHEELS').AsFloat; tblIssv1SteerRate.AsFloat := tblIss.FieldByName('Viol_STEERING').AsFloat; end else begin tblISSv1BrakesRate.AsFloat := tblIss.FieldByName('VIOL_BRAKES').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger; tblIssv1WheelRate.AsFloat := tblIss.FieldByName('VIOL_WHEELS').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger; tblIssv1SteerRate.AsFloat := tblIss.FieldByName('VIOL_STEERING').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger; end; if (tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger = 0) then begin tblIssv1MedicalRate.AsFloat := tblIss.FieldByName('VIOL_MEDICAL').AsFloat; tblIssv1LogsRate.AsFloat := tblIss.FieldByName('VIOL_LOGS').AsFloat; tblIssv1HoursRate.AsFloat := tblIss.FieldByName('VIOL_HOURS').AsFloat; tblIssv1DQRate.AsFloat := tblIss.FieldByName('VIOL_DISQUAL').AsFloat; tblIssv1DrugsRate.AsFloat := tblIss.FieldByName('VIOL_DRUGS').AsFloat; tblIssv1TrafficRate.AsFloat := tblIss.FieldByName('VIOL_TRAFFIC').AsFloat; end else begin tblIssv1MedicalRate.AsFloat := tblIss.FieldByName('VIOL_MEDICAL').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; tblIssv1LogsRate.AsFloat := tblIss.FieldByName('VIOL_LOGS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; tblIssv1HoursRate.AsFloat := tblIss.FieldByName('VIOL_HOURS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; tblIssv1DQRate.AsFloat := tblIss.FieldByName('VIOL_DISQUAL').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; tblIssv1DrugsRate.AsFloat := tblIss.FieldByName('VIOL_DRUGS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; tblIssv1TrafficRate.AsFloat := tblIss.FieldByName('VIOL_TRAFFIC').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger; end; if (tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger = 0) then begin tblIssv1HMPaperRate.asFloat := tblIss.FieldByName('VIOL_HMPAPER').AsFloat; tblIssv1HMPlacRate.AsFloat := tblIss.FieldByName('VIOL_HMPLAC').AsFloat; tblIssv1HMOperRate.AsFloat := tblIss.FieldByName('VIOL_HMOPER').AsFloat; tblIssv1HMTankRate.AsFloat := tblIss.FieldByName('VIOL_HMTANK').AsFloat; tblIssv1HMOthrRate.AsFloat := tblIss.FieldByName('VIOL_HMOTHR').AsFloat; end else begin tblIssv1HMPaperRate.AsFloat := tblIss.FieldByName('VIOL_HMPAPER').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger; tblIssv1HMPlacRate.AsFloat := tblIss.FieldByName('VIOL_HMPLAC').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger; tblIssv1HMOperRate.AsFloat := tblIss.FieldByName('VIOL_HMOPER').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger; tblIssv1HMTankRate.AsFloat := tblIss.FieldByName('VIOL_HMTANK').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger; tblIssv1HMOthrRate.AsFloat := tblIss.FieldByName('VIOL_HMOTHR').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger; end; end; procedure TdmPull.tblUCRCalcFields(DataSet: TDataSet); begin if tblUCR.FieldByName('PAYMENT_FLAG').AsString = 'Y' then tblUCRPAY_FLAG_TEXT.AsString := 'YES' else if tblUCR.FieldByName('PAYMENT_FLAG').AsString = 'N' then tblUCRPAY_FLAG_TEXT.AsString := 'NO'; if tblUCR.FieldByName('INTRASTATE_VEHICLES').AsString = 'Y' then tblUCRINTRA_VEH_TEXT.AsString := 'YES' else if tblUCR.FieldByName('INTRASTATE_VEHICLES').AsString = 'N' then tblUCRINTRA_VEH_TEXT.AsString := 'NO'; end; } (* {----------------------------------------------------------------------------- Function: GetCountryDesc Author: J. L. Vasser, FMCSA Date: 2017-08-05 Arguments: const CountryCode: string Return: string Comments: Translates SAFER's strange country codes to the country name -----------------------------------------------------------------------------} function TdmPull.GetCountryDesc(const CountryCode: string): string; begin case IndexStr('CountryCode',['A','C','M','P','S']) of 0 : Result := 'UNITED STATES'; 1 : Result := 'CANADA'; 2 : Result := 'MEXICO'; 3 : Result := 'UNITED STATES'; // Puerto Rico // Don't know why its separate 4 : Result := 'Central America'; else Result := CountryCode; end; end; procedure TdmPull.tblUpdateStatusCalcFields(DataSet: TDataSet); begin case tblUpdateStatus.FieldByName('UpdtStatus').asInteger of 0 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Not Begun'; 1 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Pending'; 2 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Complete'; end; end; function TdmPull.RebuildIdx: Boolean; begin Result := False; try Result := True; except on E: Exception do ShowMessage('Reactivating and rebuilding Indexes Failed:'+#13#10+E.Message); end; end; *) end.
unit vcmRepOperationsCollectionItem; {* Элемент коллекции операций. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmRepOperationsCollectionItem - } { Начат: 19.11.2003 13:44 } { $Id: vcmRepOperationsCollectionItem.pas,v 1.53 2015/09/24 14:29:20 kostitsin Exp $ } // $Log: vcmRepOperationsCollectionItem.pas,v $ // Revision 1.53 2015/09/24 14:29:20 kostitsin // {requestlink: 605157327 } // // Revision 1.52 2015/03/16 16:53:07 lulin // - делаем стереотипы Service и ServiceImplementation. // // Revision 1.51 2014/08/22 09:45:24 kostitsin // чиню библиотеки компонент // // Revision 1.50 2014/02/17 08:40:35 lulin // - избавляемся от ошибок молодости. // // Revision 1.49 2014/02/04 09:33:09 morozov // {RequestLink: 515841696} // // Revision 1.48 2013/08/28 16:38:01 lulin // - чистка кода. // // Revision 1.47 2013/08/28 14:29:35 lulin // - чистка кода. // // Revision 1.46 2013/04/25 14:22:38 lulin // - портируем. // // Revision 1.45 2012/08/07 14:37:42 lulin // {RequestLink:358352265} // // Revision 1.44 2012/07/10 12:27:05 lulin // {RequestLink:237994598} // // Revision 1.43 2012/03/22 06:40:09 lulin // - чистим код от мусора. // // Revision 1.42 2011/12/08 16:30:03 lulin // {RequestLink:273590436} // - чистка кода. // // Revision 1.41 2011/05/19 12:21:15 lulin // {RequestLink:266409354}. // // Revision 1.40 2010/09/15 18:15:01 lulin // {RequestLink:235047275}. // // Revision 1.39 2010/09/10 16:12:44 lulin // {RequestLink:197496539}. // // Revision 1.38 2009/09/28 17:12:48 lulin // {RequestLink:159360578}. №31. // // Revision 1.37 2009/09/25 12:09:14 lulin // - выкидываем ненужное. // // Revision 1.36 2009/08/11 14:24:03 lulin // {RequestLink:129240934}. №16. // // Revision 1.35 2009/08/07 13:47:32 lulin // - делаем возможность централизованно запретить показ операций в контекстном меню. // // Revision 1.34 2009/08/06 13:27:16 lulin // {RequestLink:129240934}. №26. // // Revision 1.33 2009/02/12 17:09:15 lulin // - <K>: 135604584. Выделен модуль с внутренними константами. // // Revision 1.32 2008/03/20 09:48:19 lulin // - cleanup. // // Revision 1.31 2007/05/31 13:53:18 oman // - fix: Вкладка с галкой на повторную активацию теперь закрывается, // а не просто переключает навигатор на предыдущую активную // - переименовано свойство в соответствии со смыслом (cq25230) // // Revision 1.30 2007/01/18 11:47:36 oman // - new: Локализация библиотек - vcm (cq24078) // // Revision 1.29 2006/03/15 11:09:48 lulin // - new behavior: выливаем не заголовки категорий, а их идентификаторы. // // Revision 1.28 2006/03/13 12:33:31 lulin // - теперь если возможно получаем категорию из пункта меню. // // Revision 1.26 2005/09/22 11:06:03 mmorozov // - работа с историей в контексте сборок; // // Revision 1.25 2005/07/14 16:02:48 lulin // - new behavior: в run-time получаем ID операции по ее имени из информации, содержащейся в MenuManager'е. // // Revision 1.24 2005/02/02 14:47:35 mmorozov // change: название метода; // // Revision 1.23 2005/02/02 14:44:37 mmorozov // new: в _Handled используем IsFormActivateDefine; // // Revision 1.22 2005/02/02 14:42:38 mmorozov // new: property TvcmRepOperationsCollectionItem.IsFormActivateDefine; // // Revision 1.21 2005/02/02 14:36:23 lulin // - добавлен комментарий. // // Revision 1.20 2005/02/02 14:23:17 lulin // - bug fix: было неправильное условие - вылезали ненужные операции. // // Revision 1.19 2005/02/02 12:53:56 am // change: правки, связанные с переделками TvcmBaseOperationCollectionItem._Handled() // // Revision 1.18 2005/01/20 13:25:19 lulin // - new consts: _vcm_otModuleInternal, _vcm_otFormConstructor. // // Revision 1.17 2005/01/14 14:03:25 lulin // - вызываем "правильный" Free. // // Revision 1.16 2005/01/14 10:48:03 mmorozov // change: _TvcmFormActivate наследник от _TvcmBase; // change: _FormActivate в TvcmRepOperationsCollectionItem создаётся по требованию; // // Revision 1.15 2005/01/14 10:42:30 lulin // - методы Get*ParentForm переехали в библиотеку AFW. // // Revision 1.14 2004/12/07 14:56:50 mmorozov // - не компилировалась библиотека; // // Revision 1.13 2004/12/07 11:54:19 lulin // - new method: _Tl3LongintList.IndexOf. // // Revision 1.12 2004/09/11 11:55:47 lulin // - cleanup: избавляемся от прямого использования деструкторов. // // Revision 1.11 2004/07/30 13:07:18 law // - cleanup. // // Revision 1.10 2004/07/30 10:00:05 nikitin75 // корректно мержим предустановленные (disigntime) шорткаты и прочитанные из настроек, bugfix // // Revision 1.9 2004/06/01 14:56:35 law // - удалены конструкторы Tl3VList.MakeLongint, MakeLongintSorted - пользуйтесь _Tl3LongintList. // // Revision 1.8 2004/03/20 15:26:51 mmorozov // new: type TvcmFormActivateType; // new: array vcmFormActivateTypeName; // new: property _TvcmFormActivate.TypeActivate; // // Revision 1.7 2004/03/20 09:49:10 mmorozov // - переименовано свойство _TvcmFormActivate._FormName -> Name; // new: properties _TvcmFormActivate.__DoExecuteIfExists; // new: property _TvcmFormActivate.Caption; // // Revision 1.6 2004/03/19 15:03:19 mmorozov // new: в метод _HasForm добавлен параметр (UserType : Integer = vcm_utAny); // // Revision 1.5 2004/03/19 13:23:22 mmorozov // new: класс _TvcmFormActivate; // new: property TvcmRepOperationsCollectionItem._FormActivate; // // Revision 1.4 2003/11/24 17:23:48 law // - new behavior: не регестрируем операцию больше одного раза. // // Revision 1.3 2003/11/19 17:24:13 law // - new prop: TvcmRepOperationsCollectionItem.RealizedIn - показывает в каких формах реализована (или по крайней мере описана) данная операция. // // Revision 1.2 2003/11/19 12:56:52 law // - new behavior: отобразил свойства операций на формах на централизованное хранилище (Caption, ImageIndex, _GroupID, _Category, OperationType). // // Revision 1.1 2003/11/19 11:38:25 law // - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано. // {$Include vcmDefine.inc } interface uses Classes, ActnList, l3Base, l3ProtoPersistent, vcmExternalInterfaces, vcmInterfaces, vcmUserControls, vcmBase, vcmBaseOperationsCollectionItem, vcmMenuItemsCollectionItem, vcmOperationsCollectionItem, vcmOperationsCollectionItemList ; type TvcmRepeatedActivationBehaviour = (vcm_rabNone, vcm_rabClose, vcm_rabInactivate, vcm_rabJustExecuteIfActive); type TvcmRepOperationsCollectionItem = class; TvcmFormActivate = class(Tl3ProtoPersistent) {* Класс описывающий форму, которой необходимо управлять. } private f_Name : AnsiString; f_Caption : AnsiString; f_UserType : Integer; f_DoExecuteIfExists : Boolean; f_ZoneType : TvcmZoneType; f_RepeatedActivationBehaviour: TvcmRepeatedActivationBehaviour; f_Operation : TvcmRepOperationsCollectionItem; protected //property methods procedure SetName(const Value: AnsiString); {-} procedure SetUserType(const Value: Integer); {-} procedure SetZoneType(const Value: TvcmZoneType); {-} procedure SetCaption(const Value: AnsiString); {-} procedure SetDoExecuteIfExists(const Value: Boolean); {-} //interanl methods procedure SetDefault; {-} public constructor Create(aOperation : TvcmRepOperationsCollectionItem); reintroduce; {-} procedure Assign(Source : TPersistent); override; {* - копируем из потока объект. } property Operation : TvcmRepOperationsCollectionItem read f_Operation; {-} published property Name : AnsiString read f_Name write SetName; {* - имя формы с которой связана операция. } property UserType : Integer read f_UserType write SetUserType default vcm_utAny; {* - идентификатор пользовательского типа на форме. } property ZoneType : TvcmZoneType read f_ZoneType write SetZoneType default vcm_ztAny; {* - тип зоны в которой находится форма. } property Caption : AnsiString read f_Caption write SetCaption; property DoExecuteIfExists : Boolean read f_DoExecuteIfExists write SetDoExecuteIfExists default False; {* - вызывать обработчик операции. } property RepeatedActivationBehaviour: TvcmRepeatedActivationBehaviour read f_RepeatedActivationBehaviour write f_RepeatedActivationBehaviour default vcm_rabClose; {* - тип активации. } end;//TvcmFormActivate TvcmRepOperationsCollectionItem = class(TvcmBaseOperationsCollectionItem) {* Элемент коллекции операций. } private // internal fields f_Holders : TvcmOperationsCollectionItemList; f_FormActivate : TvcmFormActivate; f_MenuItem : TvcmMenuItemsCollectionItem; f_RestrictOptions : TvcmOperationOptions; protected // property methods function GetDefaultOptions: TvcmOperationOptions; override; {-} {$IfNDef DesignTimeLibrary} function pm_GetCategory: AnsiString; override; {-} {$EndIf DesignTimeLibrary} function pm_GetCategoryID: Integer; procedure pm_SetCategoryID(const aValue: Integer); {-} function pm_GetIsFormActivateDefined : Boolean; {-} function pm_GetOperationType: TvcmOperationType; override; procedure pm_SetOperationType(aValue: TvcmOperationType); override; {-} procedure pm_SetShortCut(aValue: TShortCut); override; {-} procedure pm_SetSecondaryShortCuts(aValue: TShortCutList); override; {-} function pm_GetFormActivate: TvcmFormActivate; {-} procedure pm_SetFormActivate(const Value: TvcmFormActivate); {-} procedure SetShortCuts(aShortCut: TShortCut; aSecondaryShortCuts: TShortCutList); override; {-} procedure Cleanup; override; {-} public // public methods constructor Create(Collection: TCollection); override; {-} procedure AddHolder(aHolder: TvcmOperationsCollectionItem); {-} procedure RemoveHolder(aHolder: TvcmOperationsCollectionItem); {-} procedure RemoveShortCut(aShortCut: TShortCut); override; {-} function Handled(aTypes: TvcmHandleTypes): Boolean; override; {-} {$IfNDef DesignTimeLibrary} function MakeID(const aName: AnsiString): Integer; override; {-} {$EndIf DesignTimeLibrary} published // published properties property OperationType; {-} property GroupID; {-} property Options default []; {-} property IsDefault; {-} property FormActivate : TvcmFormActivate read pm_GetFormActivate write pm_SetFormActivate; {* - идентификатор формы, состояниями активации (деактивации) которой необходимо управлять. } property IsFormActivateDefined : Boolean read pm_GetIsFormActivateDefined; {* - определяет определена ли у операции форма, которой нужно управлять. } property CategoryID: Integer read pm_GetCategoryID write pm_SetCategoryID default 0; {-} property RestrictOptions: TvcmOperationOptions read f_RestrictOptions write f_RestrictOptions default []; {-} end;{ Описатель операции } implementation uses Forms, SysUtils, Menus, afwFacade, vcmForm, vcmBaseMenuManager, vcmMenuManager, vcmInternalConst ; // start class TvcmRepOperationsCollectionItem { TvcmRepOperationsCollectionItem } constructor TvcmRepOperationsCollectionItem.Create( Collection: TCollection); begin inherited Create(Collection); end; procedure TvcmRepOperationsCollectionItem.Cleanup; //override; {-} var l_Index : Integer; begin vcmFree(f_FormActivate); if (f_Holders <> nil) then with f_Holders do for l_Index := 0 to Pred(Count) do Items[l_Index].SetRep(nil); vcmFree(f_Holders); inherited; end; {$IfNDef DesignTimeLibrary} function TvcmRepOperationsCollectionItem.MakeID(const aName: AnsiString): Integer; //override; {-} begin Result := Succ(Index); end; {$EndIf DesignTimeLibrary} procedure TvcmRepOperationsCollectionItem.AddHolder(aHolder: TvcmOperationsCollectionItem); {-} begin //if (aHolder Is TvcmOperationsCollectionItem) then begin if (f_Holders = nil) then f_Holders := TvcmOperationsCollectionItemList.Create; if (f_Holders.IndexOf(aHolder) < 0) then begin f_Holders.Add(aHolder); aHolder.SetRep(Self); end;//f_Holders.IndexOf(Pointer(aHolder) < 0 end;//aHolder Is TvcmOperationsCollectionItem end; procedure TvcmRepOperationsCollectionItem.RemoveHolder(aHolder: TvcmOperationsCollectionItem); {-} begin //if (aHolder Is TvcmOperationsCollectionItem) then begin if (f_Holders <> nil) then f_Holders.Remove(aHolder); aHolder.SetRep(nil); end;//aHolder Is TvcmOperationsCollectionItem end; procedure TvcmRepOperationsCollectionItem.RemoveShortCut(aShortCut: TShortCut); {-} //override; var l_ShortCut : TShortCut; procedure l_RemoveSecondaryShortcut(aIndex: Integer); var l_ShortCuts : TShortCutList; begin//l_RemoveSecondaryShortcut l_ShortCuts := TShortCutList.Create; try l_ShortCuts.Assign(SecondaryShortCuts); l_ShortCuts.Delete(aIndex); SecondaryShortCuts := l_ShortCuts; finally FreeAndNil(l_ShortCuts); end;//try..finally end;//l_RemoveSecondaryShortcut var i : Integer; begin if (aShortCut = 0) then Exit; SecondaryShortCuts.OnChange := nil; try if ShortCut = aShortCut then begin if SecondaryShortCuts.Count > 0 then begin l_ShortCut := SecondaryShortCuts.ShortCuts[0]; l_RemoveSecondaryShortcut(0); ShortCut := l_ShortCut; end else ShortCut := 0; end else begin for i := 0 to SecondaryShortCuts.Count - 1 do if SecondaryShortCuts.ShortCuts[i] = aShortCut then begin l_RemoveSecondaryShortcut(i); break; end; end; finally SecondaryShortCuts.OnChange := OnSecondaryShortCutsChange; end;//try..finally end; function TvcmRepOperationsCollectionItem.GetDefaultOptions: TvcmOperationOptions; //override; {-} begin Result := []; end; {$IfNDef DesignTimeLibrary} function TvcmRepOperationsCollectionItem.pm_GetCategory: AnsiString; //override; {-} begin if (f_MenuItem = nil) then Result := inherited pm_GetCategory else Result := f_MenuItem.Caption; end; {$EndIf DesignTimeLibrary} function TvcmRepOperationsCollectionItem.pm_GetCategoryID: Integer; {-} begin if (f_MenuItem = nil) then Result := 0 else Result := f_MenuItem.LinkID; end; procedure TvcmRepOperationsCollectionItem.pm_SetCategoryID(const aValue: Integer); {-} begin if (g_MenuManager <> nil) AND (g_MenuManager Is TvcmCustomMenuManager) then begin if (aValue = 0) then f_MenuItem := nil else f_MenuItem := TvcmCustomMenuManager(g_MenuManager).MainMenuItems.FindItemByID(aValue) As TvcmMenuItemsCollectionItem; end;//g_MenuManager <> nil end; function TvcmRepOperationsCollectionItem.pm_GetIsFormActivateDefined : Boolean; begin Result := Assigned(f_FormActivate) and (f_FormActivate.Name <> ''); end; function TvcmRepOperationsCollectionItem.pm_GetOperationType: TvcmOperationType; //override; {-} begin Result := inherited pm_GetOperationType; if (Result = vcm_otInternal) then begin if IsLinkedToModule then begin {$IfNDef DesignTimeLibrary} Assert(false); {$EndIf DesignTimeLibrary} // Result := vcm_otModuleInternal; // f_OperationType := Result; end;//IsLinkedToModule end;//Result = vcm_otInternal end; procedure TvcmRepOperationsCollectionItem.pm_SetOperationType(aValue: TvcmOperationType); //override; {-} begin if (aValue = vcm_otInternal) AND IsLinkedToModule then begin {$IfNDef DesignTimeLibrary} Assert(false); {$EndIf DesignTimeLibrary} Exit; end;//aValue in vcm_otInternal inherited; end; procedure TvcmRepOperationsCollectionItem.pm_SetShortCut(aValue: TShortCut); //virtual; {-} begin SetShortCuts(aValue, SecondaryShortCuts); end; procedure TvcmRepOperationsCollectionItem.pm_SetSecondaryShortCuts(aValue: TShortCutList); //override; {-} begin SetShortCuts(ShortCut, aValue); end; procedure TvcmRepOperationsCollectionItem.pm_SetFormActivate(const Value: TvcmFormActivate); {-} begin f_FormActivate.Assign(Value); end; procedure TvcmRepOperationsCollectionItem.SetShortCuts(aShortCut: TShortCut; aSecondaryShortCuts: TShortCutList); //override; {-} var i, j : Integer; l_ShortCut : TShortCut; l_ShortCuts : TShortCutList; l_IsExistFlag : Boolean; procedure l_ClearShortCuts; var i : Integer; l_ShortCut : TShortCut; begin if SecondaryShortCuts.Count > 0 then begin for i := 0 to SecondaryShortCuts.Count - 1 do begin l_ShortCut := SecondaryShortCuts.ShortCuts[i]; ResetShortCutHandler(l_ShortCut); end; inherited pm_SetSecondaryShortCuts(nil); end; if ShortCut <> 0 then begin l_ShortCut := ShortCut; ResetShortCutHandler(l_ShortCut); inherited pm_SetShortCut(0); end; end; begin SecondaryShortCuts.OnChange := nil; try l_ShortCuts := TShortCutList.Create; try if aShortCut <> 0 then l_ShortCuts.Add(ShortCutToText(aShortCut)); if Assigned(aSecondaryShortCuts) and (aSecondaryShortCuts.Count > 0) then for i := 0 to aSecondaryShortCuts.Count - 1 do begin l_IsExistFlag := false; l_ShortCut := aSecondaryShortCuts.ShortCuts[i]; if l_ShortCut <> 0 then begin for j := 0 to l_ShortCuts.Count - 1 do if l_ShortCuts.ShortCuts[j] = l_ShortCut then begin l_IsExistFlag := true; break; end; if not l_IsExistFlag then l_ShortCuts.Add(ShortCutToText(l_ShortCut)); end; end; l_ClearShortCuts; if (l_ShortCuts.Count > 0) then begin l_ShortCut := l_ShortCuts.ShortCuts[0]; ResetShortCutHandler(l_ShortCut, ControllerCommand); inherited pm_SetShortCut(l_ShortCut); l_ShortCuts.Delete(0); for i := 0 to l_ShortCuts.Count - 1 do begin l_ShortCut := l_ShortCuts.ShortCuts[i]; ResetShortCutHandler(l_ShortCut, ControllerCommand); end;//for i inherited pm_SetSecondaryShortCuts(l_ShortCuts); end;//l_ShortCuts.Count > 0 finally l_ShortCuts.Free; end;//try..finally finally SecondaryShortCuts.OnChange := OnSecondaryShortCutsChange; end;//try..finally end; function TvcmRepOperationsCollectionItem.pm_GetFormActivate: TvcmFormActivate; begin if not Assigned(f_FormActivate) then f_FormActivate := TvcmFormActivate.Create(Self); Result := f_FormActivate; end; function TvcmRepOperationsCollectionItem.Handled(aTypes: TvcmHandleTypes): Boolean; begin Result := inherited Handled(aTypes); if not Result AND (([vcm_htContext, vcm_htGlobal] * aTypes) <> []) then Result := IsFormActivateDefined; end; { TvcmFormActivate } procedure TvcmFormActivate.Assign(Source : TPersistent); var lLink : TvcmFormActivate; begin if not (Source is TvcmFormActivate) then Exit; lLink := TvcmFormActivate(Source); f_ZoneType := lLink.ZoneType; f_Name := lLink.Name; f_UserType := lLink.UserType; f_Caption := lLink.Caption; f_RepeatedActivationBehaviour := lLink.RepeatedActivationBehaviour; end; constructor TvcmFormActivate.Create(aOperation : TvcmRepOperationsCollectionItem); begin inherited Create; f_Operation := aOperation; SetDefault; end; procedure TvcmFormActivate.SetDefault; begin f_ZoneType := vcm_ztAny; f_UserType := vcm_utAny; f_DoExecuteIfExists := False; f_RepeatedActivationBehaviour := vcm_rabClose; f_Caption := ''; end; procedure TvcmFormActivate.SetCaption(const Value: AnsiString); begin f_Caption := Value; end; procedure TvcmFormActivate.SetDoExecuteIfExists(const Value: Boolean); begin f_DoExecuteIfExists := Value; end; procedure TvcmFormActivate.SetName(const Value: AnsiString); begin f_Name := Value; if f_Name = '' then SetDefault; end; procedure TvcmFormActivate.SetUserType(const Value: Integer); begin f_UserType := Value; end; procedure TvcmFormActivate.SetZoneType(const Value: TvcmZoneType); begin f_ZoneType := Value; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type ConvertTest = public class (Test) public method ToStringByte; method ToStringInt32; method ToStringInt64; method ToStringDouble; method ToStringChar; method ToStringObject; method ToInt32Byte; method ToInt32Int64; method ToInt32Double; method ToInt32Char; method ToInt32String; method ToInt64Byte; method ToInt64Int32; method ToInt64Double; method ToInt64Char; method ToInt64String; method ToDoubleByte; method ToDoubleInt32; method ToDoubleInt64; method ToDoubleString; method ToByteDouble; method ToByteInt32; method ToByteInt64; method ToByteChar; method ToByteString; method ToCharInt32; method ToCharInt64; method ToCharByte; method ToCharString; method ToBooleanDouble; method ToBooleanInt32; method ToBooleanInt64; method ToBooleanByte; method ToBooleanString; end; implementation method ConvertTest.ToStringByte; begin Assert.AreEqual(Convert.ToString(Byte(0)), "0"); Assert.AreEqual(Convert.ToString(Byte(255)), "255"); end; method ConvertTest.ToStringInt32; begin Assert.AreEqual(Convert.ToString(Consts.MaxInteger), "2147483647"); Assert.AreEqual(Convert.ToString(Consts.MinInteger), "-2147483648"); Assert.AreEqual(Convert.ToString(Int32(0)), "0"); end; method ConvertTest.ToStringInt64; begin Assert.AreEqual(Convert.ToString(Consts.MaxInt64), "9223372036854775807"); Assert.AreEqual(Convert.ToString(Consts.MinInt64), "-9223372036854775808"); Assert.AreEqual(Convert.ToString(Int64(0)), "0"); end; method ConvertTest.ToStringDouble; begin Assert.AreEqual(Convert.ToString(Double(1.797693134862E+308)), "1.797693134862E+308"); Assert.AreEqual(Convert.ToString(Double(-1.797693134862E+308)), "-1.797693134862E+308"); Assert.AreEqual(Convert.ToString(Double(0.000000001)), "1E-09"); Assert.AreEqual(Convert.ToString(Consts.NaN), "NaN"); Assert.AreEqual(Convert.ToString(Consts.NegativeInfinity), "-Infinity"); Assert.AreEqual(Convert.ToString(Consts.PositiveInfinity), "Infinity"); Assert.AreEqual(Convert.ToString(Double(0.1)), "0.1"); Assert.AreEqual(Convert.ToString(Double(-4.2)), "-4.2"); end; method ConvertTest.ToStringChar; begin Assert.AreEqual(Convert.ToString(Char('x')), "x"); Assert.AreEqual(Convert.ToString(Char(0)), #0); end; method ConvertTest.ToStringObject; begin Assert.AreEqual(Convert.ToString(new CodeClass(42)), "42"); end; method ConvertTest.ToInt32Byte; begin Assert.AreEqual(Convert.ToInt32(Byte(0)), 0); Assert.AreEqual(Convert.ToInt32(Byte(255)), 255); end; method ConvertTest.ToInt32Int64; begin Assert.AreEqual(Convert.ToInt32(Int64(0)), 0); Assert.AreEqual(Convert.ToInt32(Int64(45678942)), 45678942); Assert.Throws(->Convert.ToInt32(Consts.MaxInt64)); Assert.Throws(->Convert.ToInt32(Consts.MinInt64)); end; method ConvertTest.ToInt32Double; begin Assert.AreEqual(Convert.ToInt32(Double(1.0)), 1); Assert.AreEqual(Convert.ToInt32(Double(1.1)), 1); Assert.AreEqual(Convert.ToInt32(Double(1.2)), 1); Assert.AreEqual(Convert.ToInt32(Double(1.3)), 1); Assert.AreEqual(Convert.ToInt32(Double(1.4)), 1); Assert.AreEqual(Convert.ToInt32(Double(1.5)), 2); Assert.AreEqual(Convert.ToInt32(Double(1.6)), 2); Assert.AreEqual(Convert.ToInt32(Double(1.7)), 2); Assert.AreEqual(Convert.ToInt32(Double(1.8)), 2); Assert.AreEqual(Convert.ToInt32(Double(1.9)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.0)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.1)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.2)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.3)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.4)), 2); Assert.AreEqual(Convert.ToInt32(Double(2.5)), 3); Assert.AreEqual(Convert.ToInt32(Double(2.6)), 3); Assert.AreEqual(Convert.ToInt32(Double(2.7)), 3); Assert.AreEqual(Convert.ToInt32(Double(2.8)), 3); Assert.AreEqual(Convert.ToInt32(Double(2.9)), 3); Assert.Throws(->Convert.ToInt32(Double(21474836483.15))); Assert.Throws(->Convert.ToInt32(Double(-21474836483.15))); Assert.Throws(->Convert.ToInt32(Consts.NaN)); Assert.Throws(->Convert.ToInt32(Consts.PositiveInfinity)); Assert.Throws(->Convert.ToInt32(Consts.NegativeInfinity)); end; method ConvertTest.ToInt32Char; begin Assert.AreEqual(Convert.ToInt32(Char(#13)), 13); Assert.AreEqual(Convert.ToInt32(Char(#0)), 0); end; method ConvertTest.ToInt32String; begin Assert.AreEqual(Convert.ToInt32("42"), 42); Assert.AreEqual(Convert.ToInt32("-42"), -42); Assert.Throws(->Convert.ToInt32("")); Assert.Throws(->Convert.ToInt32("9223372036854775807")); Assert.Throws(->Convert.ToInt32("4.2")); Assert.Throws(->Convert.ToInt32("1F")); end; method ConvertTest.ToInt64Byte; begin Assert.AreEqual(Convert.ToInt64(Byte(0)), 0); Assert.AreEqual(Convert.ToInt64(Byte(255)), 255); end; method ConvertTest.ToInt64Int32; begin Assert.AreEqual(Convert.ToInt64(Consts.MaxInteger), 2147483647); Assert.AreEqual(Convert.ToInt64(Consts.MinInteger), -2147483648); end; method ConvertTest.ToInt64Double; begin Assert.AreEqual(Convert.ToInt64(Double(1.0)), 1); Assert.AreEqual(Convert.ToInt64(Double(1.1)), 1); Assert.AreEqual(Convert.ToInt64(Double(1.2)), 1); Assert.AreEqual(Convert.ToInt64(Double(1.3)), 1); Assert.AreEqual(Convert.ToInt64(Double(1.4)), 1); Assert.AreEqual(Convert.ToInt64(Double(1.5)), 2); Assert.AreEqual(Convert.ToInt64(Double(1.6)), 2); Assert.AreEqual(Convert.ToInt64(Double(1.7)), 2); Assert.AreEqual(Convert.ToInt64(Double(1.8)), 2); Assert.AreEqual(Convert.ToInt64(Double(1.9)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.0)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.1)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.2)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.3)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.4)), 2); Assert.AreEqual(Convert.ToInt64(Double(2.5)), 3); Assert.AreEqual(Convert.ToInt64(Double(2.6)), 3); Assert.AreEqual(Convert.ToInt64(Double(2.7)), 3); Assert.AreEqual(Convert.ToInt64(Double(2.8)), 3); Assert.AreEqual(Convert.ToInt64(Double(2.9)), 3); Assert.Throws(->Convert.ToInt64(Double(Consts.MaxDouble))); Assert.Throws(->Convert.ToInt64(Double(Consts.MinDouble))); Assert.Throws(->Convert.ToInt64(Consts.NaN)); Assert.Throws(->Convert.ToInt64(Consts.PositiveInfinity)); Assert.Throws(->Convert.ToInt64(Consts.NegativeInfinity)); end; method ConvertTest.ToInt64Char; begin Assert.AreEqual(Convert.ToInt64(Char(#13)), 13); Assert.AreEqual(Convert.ToInt64(Char(#0)), 0); end; method ConvertTest.ToInt64String; begin Assert.AreEqual(Convert.ToInt64("42"), 42); Assert.AreEqual(Convert.ToInt64("-42"), -42); Assert.AreEqual(Convert.ToInt64("9223372036854775807"), Consts.MaxInt64); Assert.AreEqual(Convert.ToInt64("-9223372036854775808"), Consts.MinInt64); Assert.AreEqual(Convert.ToInt64(nil), 0); Assert.Throws(->Convert.ToInt64(""), typeOf(SugarFormatException)); Assert.Throws(->Convert.ToInt64("92233720368547758071")); Assert.Throws(->Convert.ToInt64("4.2")); Assert.Throws(->Convert.ToInt64("1F")); end; method ConvertTest.ToDoubleByte; begin Assert.AreEqual(Convert.ToDouble(Byte(1)), 1.0); Assert.AreEqual(Convert.ToDouble(Byte(255)), 255.0); end; method ConvertTest.ToDoubleInt32; begin Assert.AreEqual(Convert.ToDouble(Consts.MaxInteger), 2147483647.0); Assert.AreEqual(Convert.ToDouble(Consts.MinInteger), -2147483648.0); end; method ConvertTest.ToDoubleInt64; begin Assert.AreEqual(Convert.ToDouble(Consts.MaxInt64), 9223372036854775807.0); Assert.AreEqual(Convert.ToDouble(Consts.MinInt64), Double(-9223372036854775808.0)); end; method ConvertTest.ToDoubleString; begin Assert.AreEqual(Convert.ToDouble("1.1"), 1.1); // '.' - decimal separator Assert.AreEqual(Convert.ToDouble("1,1"), 11); // ',' - group separator Assert.AreEqual(Convert.ToDouble("1024,1.5"), 10241.5); Assert.AreEqual(Convert.ToDouble("-1.38e10"), -1.38e10); Assert.AreEqual(Convert.ToDouble(nil), 0.0); Assert.Throws(->Convert.ToDouble(""), typeOf(SugarFormatException)); Assert.Throws(->Convert.ToDouble("1.29e325")); Assert.Throws(->Convert.ToDouble("1F")); Assert.Throws(->Convert.ToDouble("1024.1,5")); end; method ConvertTest.ToByteDouble; begin Assert.AreEqual(Convert.ToByte(Double(1.0)), 1); Assert.AreEqual(Convert.ToByte(Double(1.1)), 1); Assert.AreEqual(Convert.ToByte(Double(1.2)), 1); Assert.AreEqual(Convert.ToByte(Double(1.3)), 1); Assert.AreEqual(Convert.ToByte(Double(1.4)), 1); Assert.AreEqual(Convert.ToByte(Double(1.5)), 2); Assert.AreEqual(Convert.ToByte(Double(1.6)), 2); Assert.AreEqual(Convert.ToByte(Double(1.7)), 2); Assert.AreEqual(Convert.ToByte(Double(1.8)), 2); Assert.AreEqual(Convert.ToByte(Double(1.9)), 2); Assert.AreEqual(Convert.ToByte(Double(2.0)), 2); Assert.AreEqual(Convert.ToByte(Double(2.1)), 2); Assert.AreEqual(Convert.ToByte(Double(2.2)), 2); Assert.AreEqual(Convert.ToByte(Double(2.3)), 2); Assert.AreEqual(Convert.ToByte(Double(2.4)), 2); Assert.AreEqual(Convert.ToByte(Double(2.5)), 3); Assert.AreEqual(Convert.ToByte(Double(2.6)), 3); Assert.AreEqual(Convert.ToByte(Double(2.7)), 3); Assert.AreEqual(Convert.ToByte(Double(2.8)), 3); Assert.AreEqual(Convert.ToByte(Double(2.9)), 3); Assert.Throws(->Convert.ToByte(Double(Consts.MaxDouble))); Assert.Throws(->Convert.ToByte(Double(Consts.MinDouble))); Assert.Throws(->Convert.ToByte(Consts.NaN)); Assert.Throws(->Convert.ToByte(Consts.PositiveInfinity)); Assert.Throws(->Convert.ToByte(Consts.NegativeInfinity)); end; method ConvertTest.ToByteInt32; begin Assert.AreEqual(Convert.ToByte(Int32(0)), 0); Assert.AreEqual(Convert.ToByte(Int32(42)), 42); Assert.Throws(->Convert.ToByte(Int32(259))); Assert.Throws(->Convert.ToByte(Int32(-1))); end; method ConvertTest.ToByteInt64; begin Assert.AreEqual(Convert.ToByte(Int64(0)), 0); Assert.AreEqual(Convert.ToByte(Int64(42)), 42); Assert.Throws(->Convert.ToByte(Int64(259))); Assert.Throws(->Convert.ToByte(Int64(-1))); end; method ConvertTest.ToByteChar; begin Assert.AreEqual(Convert.ToByte(Char(#0)), 0); Assert.AreEqual(Convert.ToByte(Char(#13)), 13); Assert.Throws(->Convert.ToByte(Char(#388))); end; method ConvertTest.ToByteString; begin Assert.AreEqual(Convert.ToByte(nil), 0); Assert.AreEqual(Convert.ToByte("0"), 0); Assert.AreEqual(Convert.ToByte("255"), 255); Assert.Throws(->Convert.ToByte(""), typeOf(SugarFormatException)); Assert.Throws(->Convert.ToByte("-1")); Assert.Throws(->Convert.ToByte("5.25")); Assert.Throws(->Convert.ToByte("FF")); end; method ConvertTest.ToCharInt32; begin Assert.AreEqual(Convert.ToChar(Int32(13)), #13); Assert.AreEqual(Convert.ToChar(Int32(0)), #0); Assert.Throws(->Convert.ToChar(Consts.MaxInteger)); Assert.Throws(->Convert.ToChar(Consts.MinInteger)); end; method ConvertTest.ToCharInt64; begin Assert.AreEqual(Convert.ToChar(Int64(13)), #13); Assert.AreEqual(Convert.ToChar(Int64(0)), #0); Assert.Throws(->Convert.ToChar(Consts.MaxInt64)); Assert.Throws(->Convert.ToChar(Consts.MinInt64)); end; method ConvertTest.ToCharByte; begin Assert.AreEqual(Convert.ToChar(Byte(13)), #13); Assert.AreEqual(Convert.ToChar(Byte(0)), #0); Assert.AreEqual(Convert.ToChar(Byte(255)), #255); end; method ConvertTest.ToCharString; begin Assert.AreEqual(Convert.ToChar(" "), #32); Assert.Throws(->Convert.ToChar("")); Assert.Throws(->Convert.ToChar(nil)); Assert.Throws(->Convert.ToChar("xx")); end; method ConvertTest.ToBooleanDouble; begin Assert.IsFalse(Convert.ToBoolean(Double(0.0))); Assert.IsTrue(Convert.ToBoolean(Double(0.1))); Assert.IsTrue(Convert.ToBoolean(Double(-1.1))); Assert.IsTrue(Convert.ToBoolean(Consts.NaN)); Assert.IsTrue(Convert.ToBoolean(Consts.NegativeInfinity)); Assert.IsTrue(Convert.ToBoolean(Consts.PositiveInfinity)); end; method ConvertTest.ToBooleanInt32; begin Assert.IsFalse(Convert.ToBoolean(Int32(0))); Assert.IsTrue(Convert.ToBoolean(Int32(1))); Assert.IsTrue(Convert.ToBoolean(Int32(-1))); end; method ConvertTest.ToBooleanInt64; begin Assert.IsFalse(Convert.ToBoolean(Int64(0))); Assert.IsTrue(Convert.ToBoolean(Int64(1))); Assert.IsTrue(Convert.ToBoolean(Int64(-1))); end; method ConvertTest.ToBooleanByte; begin Assert.IsFalse(Convert.ToBoolean(Byte(0))); Assert.IsTrue(Convert.ToBoolean(Byte(1))); Assert.IsTrue(Convert.ToBoolean(Byte(-1))); end; method ConvertTest.ToBooleanString; begin Assert.IsTrue(Convert.ToBoolean(Consts.TrueString)); Assert.IsFalse(Convert.ToBoolean(Consts.FalseString)); Assert.IsFalse(Convert.ToBoolean(nil)); Assert.Throws(->Convert.ToBoolean("")); Assert.Throws(->Convert.ToBoolean("a")); Assert.Throws(->Convert.ToBoolean("yes")); Assert.Throws(->Convert.ToBoolean("no")); end; end.
unit TTSCODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCODERecord = record PLenderNum: String[4]; PCode: String[2]; PPrimary: String[8]; PData1: String[40]; PData2: String[40]; PData3: String[40]; PData4: String[40]; PData5: String[40]; PData6: String[80]; End; TTTSCODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCODERecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCODE = (TTSCODEPrimaryKey); TTTSCODETable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCode: TStringField; FDFPrimary: TStringField; FDFData1: TStringField; FDFData2: TStringField; FDFData3: TStringField; FDFData4: TStringField; FDFData5: TStringField; FDFData6: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPPrimary(const Value: String); function GetPPrimary:String; procedure SetPData1(const Value: String); function GetPData1:String; procedure SetPData2(const Value: String); function GetPData2:String; procedure SetPData3(const Value: String); function GetPData3:String; procedure SetPData4(const Value: String); function GetPData4:String; procedure SetPData5(const Value: String); function GetPData5:String; procedure SetPData6(const Value: String); function GetPData6:String; procedure SetEnumIndex(Value: TEITTSCODE); function GetEnumIndex: TEITTSCODE; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCODERecord; procedure StoreDataBuffer(ABuffer:TTTSCODERecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCode: TStringField read FDFCode; property DFPrimary: TStringField read FDFPrimary; property DFData1: TStringField read FDFData1; property DFData2: TStringField read FDFData2; property DFData3: TStringField read FDFData3; property DFData4: TStringField read FDFData4; property DFData5: TStringField read FDFData5; property DFData6: TStringField read FDFData6; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCode: String read GetPCode write SetPCode; property PPrimary: String read GetPPrimary write SetPPrimary; property PData1: String read GetPData1 write SetPData1; property PData2: String read GetPData2 write SetPData2; property PData3: String read GetPData3 write SetPData3; property PData4: String read GetPData4 write SetPData4; property PData5: String read GetPData5 write SetPData5; property PData6: String read GetPData6 write SetPData6; published property Active write SetActive; property EnumIndex: TEITTSCODE read GetEnumIndex write SetEnumIndex; end; { TTTSCODETable } procedure Register; implementation procedure TTTSCODETable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCode := CreateField( 'Code' ) as TStringField; FDFPrimary := CreateField( 'Primary' ) as TStringField; FDFData1 := CreateField( 'Data1' ) as TStringField; FDFData2 := CreateField( 'Data2' ) as TStringField; FDFData3 := CreateField( 'Data3' ) as TStringField; FDFData4 := CreateField( 'Data4' ) as TStringField; FDFData5 := CreateField( 'Data5' ) as TStringField; FDFData6 := CreateField( 'Data6' ) as TStringField; end; { TTTSCODETable.CreateFields } procedure TTTSCODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCODETable.SetActive } procedure TTTSCODETable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCODETable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TTTSCODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TTTSCODETable.SetPPrimary(const Value: String); begin DFPrimary.Value := Value; end; function TTTSCODETable.GetPPrimary:String; begin result := DFPrimary.Value; end; procedure TTTSCODETable.SetPData1(const Value: String); begin DFData1.Value := Value; end; function TTTSCODETable.GetPData1:String; begin result := DFData1.Value; end; procedure TTTSCODETable.SetPData2(const Value: String); begin DFData2.Value := Value; end; function TTTSCODETable.GetPData2:String; begin result := DFData2.Value; end; procedure TTTSCODETable.SetPData3(const Value: String); begin DFData3.Value := Value; end; function TTTSCODETable.GetPData3:String; begin result := DFData3.Value; end; procedure TTTSCODETable.SetPData4(const Value: String); begin DFData4.Value := Value; end; function TTTSCODETable.GetPData4:String; begin result := DFData4.Value; end; procedure TTTSCODETable.SetPData5(const Value: String); begin DFData5.Value := Value; end; function TTTSCODETable.GetPData5:String; begin result := DFData5.Value; end; procedure TTTSCODETable.SetPData6(const Value: String); begin DFData6.Value := Value; end; function TTTSCODETable.GetPData6:String; begin result := DFData6.Value; end; procedure TTTSCODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('Code, String, 2, N'); Add('Primary, String, 8, N'); Add('Data1, String, 40, N'); Add('Data2, String, 40, N'); Add('Data3, String, 40, N'); Add('Data4, String, 40, N'); Add('Data5, String, 40, N'); Add('Data6, String, 80, N'); end; end; procedure TTTSCODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;Code;Primary, Y, Y, N, N'); end; end; procedure TTTSCODETable.SetEnumIndex(Value: TEITTSCODE); begin case Value of TTSCODEPrimaryKey : IndexName := ''; end; end; function TTTSCODETable.GetDataBuffer:TTTSCODERecord; var buf: TTTSCODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCode := DFCode.Value; buf.PPrimary := DFPrimary.Value; buf.PData1 := DFData1.Value; buf.PData2 := DFData2.Value; buf.PData3 := DFData3.Value; buf.PData4 := DFData4.Value; buf.PData5 := DFData5.Value; buf.PData6 := DFData6.Value; result := buf; end; procedure TTTSCODETable.StoreDataBuffer(ABuffer:TTTSCODERecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCode.Value := ABuffer.PCode; DFPrimary.Value := ABuffer.PPrimary; DFData1.Value := ABuffer.PData1; DFData2.Value := ABuffer.PData2; DFData3.Value := ABuffer.PData3; DFData4.Value := ABuffer.PData4; DFData5.Value := ABuffer.PData5; DFData6.Value := ABuffer.PData6; end; function TTTSCODETable.GetEnumIndex: TEITTSCODE; var iname : string; begin result := TTSCODEPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCODEPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCODETable, TTTSCODEBuffer ] ); end; { Register } function TTTSCODEBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..9] of string = ('LENDERNUM','CODE','PRIMARY','DATA1','DATA2','DATA3' ,'DATA4','DATA5','DATA6' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 9) and (flist[x] <> s) do inc(x); if x <= 9 then result := x else result := 0; end; function TTTSCODEBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; end; end; function TTTSCODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCode; 3 : result := @Data.PPrimary; 4 : result := @Data.PData1; 5 : result := @Data.PData2; 6 : result := @Data.PData3; 7 : result := @Data.PData4; 8 : result := @Data.PData5; 9 : result := @Data.PData6; end; end; end.
unit l3Tool; // Модуль: "w:\common\components\rtl\Garant\L3\l3Tool.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3Tool" MUID: (48E233B00094) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3ProtoObjectWithCOMQI , l3Interfaces ; type Tl3Tool = class(Tl3ProtoObjectWithCOMQI, Il3Tool) protected f_Owner: Pointer; protected procedure OwnerDead; {* Нотификация о смерти родителя. } procedure Cleanup; override; {* Функция очистки полей объекта. } {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) public constructor Create(const anOwner: Il3ToolOwner); reintroduce; end;//Tl3Tool implementation uses l3ImplUses //#UC START# *48E233B00094impl_uses* //#UC END# *48E233B00094impl_uses* ; constructor Tl3Tool.Create(const anOwner: Il3ToolOwner); //#UC START# *48E2343E007B_48E233B00094_var* //#UC END# *48E2343E007B_48E233B00094_var* begin //#UC START# *48E2343E007B_48E233B00094_impl* inherited Create; f_Owner := Pointer(anOwner); if (f_Owner <> nil) then Il3ToolOwner(f_Owner).AddTool(Self); //#UC END# *48E2343E007B_48E233B00094_impl* end;//Tl3Tool.Create procedure Tl3Tool.OwnerDead; {* Нотификация о смерти родителя. } //#UC START# *46A5D4220369_48E233B00094_var* //#UC END# *46A5D4220369_48E233B00094_var* begin //#UC START# *46A5D4220369_48E233B00094_impl* f_Owner := nil; //#UC END# *46A5D4220369_48E233B00094_impl* end;//Tl3Tool.OwnerDead procedure Tl3Tool.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48E233B00094_var* //#UC END# *479731C50290_48E233B00094_var* begin //#UC START# *479731C50290_48E233B00094_impl* if (f_Owner <> nil) then Il3ToolOwner(f_Owner).RemoveTool(Self); f_Owner := nil; inherited; //#UC END# *479731C50290_48E233B00094_impl* end;//Tl3Tool.Cleanup {$If NOT Defined(DesignTimeLibrary)} class function Tl3Tool.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_48E233B00094_var* //#UC END# *47A6FEE600FC_48E233B00094_var* begin //#UC START# *47A6FEE600FC_48E233B00094_impl* Result := true; //#UC END# *47A6FEE600FC_48E233B00094_impl* end;//Tl3Tool.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) end.
unit fmuPrintLine; interface uses // VCL Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, // This untPages, untUtil, ComCtrls, untDriver; type TfmPrintLine = class(TPage) Bevel1: TBevel; lblPrintLine: TLabel; lblLineData: TLabel; lblLineNumber: TLabel; edtLineData: TEdit; edtLineNumber: TEdit; btnPrintLine: TButton; lblBlackLine: TLabel; Bevel2: TBevel; lblLineCount: TLabel; lblByteCount: TLabel; edtLineCount: TEdit; edtByteCount: TEdit; btnBlackLine: TButton; procedure btnPrintLineClick(Sender: TObject); procedure btnBlackLineClick(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure btnPrintLineMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure btnBlackLineMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); end; implementation {$R *.DFM} { TfmPrintLine } procedure TfmPrintLine.btnPrintLineClick(Sender: TObject); begin EnableButtons(False); try Driver.LineData := HexToStr(edtLineData.Text); Driver.LineNumber := StrToInt(edtLineNumber.Text); Driver.PrintLine; UpdatePage; finally EnableButtons(True); end; end; procedure TfmPrintLine.btnBlackLineClick(Sender: TObject); begin EnableButtons(False); try Driver.LineData := StringOfChar(#$FF, StrToInt(edtByteCount.Text)); Driver.LineNumber := StrToInt(edtLineCount.Text); Driver.PrintLine; UpdatePage; finally EnableButtons(True); end; end; procedure TfmPrintLine.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if HighLighting then begin edtLineData.Color := clWindow; edtLineNumber.Color := clWindow; edtLineCount.Color := clWindow; edtByteCount.Color := clWindow; end; end; procedure TfmPrintLine.btnPrintLineMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if HighLighting then begin edtLineData.Color := InColor; edtLineNumber.Color := InColor; end; end; procedure TfmPrintLine.btnBlackLineMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if HighLighting then begin edtLineCount.Color := InColor; edtByteCount.Color := InColor; end; end; end.
unit nsWindowNode; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "UserInteraction" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VCM/UserInteraction/nsWindowNode.pas" // Начат: 20.10.2009 21:05 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Operations::OfficeLike::UserInteraction::WindowsListSupport::TnsWindowNode // // Нода используемая для построения дерева окон системы // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses l3Interfaces {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , l3Tree_TLB, l3Nodes, OfficeLikeAppInterfaces ; type TnsWindowNode = class(Tl3UsualNode, InsWindow) {* Нода используемая для построения дерева окон системы } private // private fields fForm : IvcmEntityForm; protected // realized methods function Get_Form: IvcmEntityForm; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor Create(const aForm: IvcmEntityForm; const aText: Tl3WString); reintroduce; class function Make(const aForm: IvcmEntityForm; const aText: Tl3WString): Il3Node; reintroduce; end;//TnsWindowNode implementation uses l3String ; // start class TnsWindowNode constructor TnsWindowNode.Create(const aForm: IvcmEntityForm; const aText: Tl3WString); //#UC START# *4ADDE38A00B3_4ADC5E7C0264_var* //#UC END# *4ADDE38A00B3_4ADC5E7C0264_var* begin //#UC START# *4ADDE38A00B3_4ADC5E7C0264_impl* inherited Create{(nil, -1, -1)}; fForm := aForm; if l3IsNil(aText) and Assigned(aForm) then Text := l3PCharLen(aForm.Caption) else Text := aText; //#UC END# *4ADDE38A00B3_4ADC5E7C0264_impl* end;//TnsWindowNode.Create class function TnsWindowNode.Make(const aForm: IvcmEntityForm; const aText: Tl3WString): Il3Node; var l_Inst : TnsWindowNode; begin l_Inst := Create(aForm, aText); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TnsWindowNode.Get_Form: IvcmEntityForm; //#UC START# *4991A633007F_4ADC5E7C0264get_var* //#UC END# *4991A633007F_4ADC5E7C0264get_var* begin //#UC START# *4991A633007F_4ADC5E7C0264get_impl* Result := fForm; //#UC END# *4991A633007F_4ADC5E7C0264get_impl* end;//TnsWindowNode.Get_Form procedure TnsWindowNode.Cleanup; //#UC START# *479731C50290_4ADC5E7C0264_var* //#UC END# *479731C50290_4ADC5E7C0264_var* begin //#UC START# *479731C50290_4ADC5E7C0264_impl* fForm := nil; inherited; //#UC END# *479731C50290_4ADC5E7C0264_impl* end;//TnsWindowNode.Cleanup end.
unit xn.grid; interface uses Generics.Collections, Vcl.Styles, Vcl.Controls, Vcl.Grids, Vcl.Themes, Vcl.Graphics, Vcl.GraphUtil, Vcl.ExtCtrls, System.SysUtils, System.Classes, System.Math, System.UITypes, Windows, xn.grid.data, xn.grid.common; type TxnGridColumn = class(TCollectionItem) strict private fAlignment: TAlignment; fCaption: string; fWidth: Integer; protected procedure SetIndex(aIndex: Integer); override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; published property Alignment: TAlignment read fAlignment write fAlignment; property Width: Integer read fWidth write fWidth; property Caption: String read fCaption write fCaption; end; TxnGridColumns = class(TOwnedCollection) strict private function ItemGet(aIndex: Integer): TxnGridColumn; procedure ItemSet(aIndex: Integer; aValue: TxnGridColumn); private fNotify: TxnGridColNotify; function CaptionGet(aIndex: Integer): string; public constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); property Items[aIndex: Integer]: TxnGridColumn read ItemGet write ItemSet; default; end; TxnGrid = class(TCustomDrawGrid) private fLink: IxnGridLink; fLog: TStrings; fColumns: TxnGridColumns; procedure OptionsEditingSet(aValue: Boolean); function OptionsEditingGet: Boolean; procedure ColumnsSet(aValue: TxnGridColumns); function ColumnsGet: TxnGridColumns; procedure LogSet(aValue: TStrings); function LogGet: TStrings; procedure LogString(aString: String); procedure NotifyCol(fData: TxnGridLinkNotifyData); procedure NotifyRow(fData: TxnGridLinkNotifyData); procedure OnSelectCell_(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); procedure RowCountSet(aValue: Integer); procedure ColCountSet(aValue: Integer); procedure LinkSet(aValue: IxnGridLink); function LinkGet: IxnGridLink; protected procedure InvalidateRowsFrom(aIndex: Integer); procedure InvalidateColsFrom(aIndex: Integer); procedure DrawCell(aCol, aRow: Integer; ARect: TRect; AState: TGridDrawState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InvalidateGrid; procedure InvalidateRow(aRow: Integer); procedure InvalidateCol(aCol: Integer); procedure InvalidateCell(aCol, aRow: Integer); procedure OnRecNo(aIndex: Integer); published property Log: TStrings read LogGet write LogSet; property Columns: TxnGridColumns read ColumnsGet write ColumnsSet; property OptionsEditing: Boolean read OptionsEditingGet write OptionsEditingSet; property link: IxnGridLink read LinkGet write LinkSet; end; implementation { TxnGrid } function TxnGrid.ColumnsGet: TxnGridColumns; begin Result := fColumns; end; procedure TxnGrid.ColumnsSet(aValue: TxnGridColumns); begin fColumns.Assign(aValue); end; // function TxnGrid.ColCountGet: Integer; // begin // Result := inherited ColCount // end; procedure TxnGrid.ColCountSet(aValue: Integer); begin if aValue <> RowCount then begin if aValue < 1 then aValue := 1; inherited ColCount := aValue; FixedCols := IfThen(aValue > 1, 1, 0); ColWidths[0] := 11; end; end; constructor TxnGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); OnSelectCell := OnSelectCell_; DefaultDrawing := True; fLog := nil; fLink := nil; fColumns := TxnGridColumns.Create(Self, TxnGridColumn); Font.Size := 10; DefaultColWidth := 40; DefaultRowHeight := 20; // Canvas.TextHeight('Wg') * 2 ; ColCountSet(1); if fLink = nil then RowCountSet(1) else RowCountSet(fLink.RowCountGet); fColumns.fNotify := NotifyCol; end; destructor TxnGrid.Destroy; begin fColumns.Free; inherited Destroy; end; function StyleServices: TCustomStyleServices; begin Result := TStyleManager.ActiveStyle; end; procedure TxnGrid.DrawCell(aCol, aRow: Integer; ARect: TRect; AState: TGridDrawState); var r: TRect; v: string; s: Integer; f: Cardinal; pc: TColor; bc: TColor; triangle: array [0 .. 2] of TPoint; const spacing = 4; // LStyle: TCustomStyleServices; // LColor: TColor; // LineColor: TColor; // LFixedColor: TColor; // LFixedBorderColor: TColor; begin if aCol < 0 then exit; if aRow < 0 then exit; if fLink = nil then v := '' else begin if aRow = 0 then v := fColumns.CaptionGet(aCol - 1) else v := fLink.ValueString(aCol - 1, aRow - 1); end; { FInternalColor := Color; LStyle := StyleServices; if (FInternalDrawingStyle = gdsThemed) then begin LStyle.GetElementColor(LStyle.GetElementDetails(tgCellNormal), ecBorderColor, LineColor); if seClient in StyleElements then LStyle.GetElementColor(LStyle.GetElementDetails(tgCellNormal), ecFillColor, FInternalColor); LStyle.GetElementColor(LStyle.GetElementDetails(tgFixedCellNormal), ecBorderColor, LFixedBorderColor); LStyle.GetElementColor(LStyle.GetElementDetails(tgFixedCellNormal), ecFillColor, LFixedColor); end else begin if FInternalDrawingStyle = gdsGradient then begin LineColor := $F0F0F0; LFixedColor := Color; LFixedBorderColor := GetShadowColor($F0F0F0, -45); if LStyle.Enabled then begin if LStyle.GetElementColor(LStyle.GetElementDetails(tgGradientCellNormal), ecBorderColor, LColor) and (LColor <> clNone) then LineColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgGradientCellNormal), ecFillColor, LColor) and (LColor <> clNone) then FInternalColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgGradientFixedCellNormal), ecBorderColor, LColor) and (LColor <> clNone) then LFixedBorderColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgGradientFixedCellNormal), ecFillColor, LColor) and (LColor <> clNone) then LFixedColor := LColor; end; end else begin LineColor := clSilver; LFixedColor := FixedColor; LFixedBorderColor := clBlack; if LStyle.Enabled then begin if LStyle.GetElementColor(LStyle.GetElementDetails(tgClassicCellNormal), ecBorderColor, LColor) and (LColor <> clNone) then LineColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgClassicCellNormal), ecFillColor, LColor) and (LColor <> clNone) then FInternalColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgClassicFixedCellNormal), ecBorderColor, LColor) and (LColor <> clNone) then LFixedBorderColor := LColor; if LStyle.GetElementColor(LStyle.GetElementDetails(tgClassicFixedCellNormal), ecFillColor, LColor) and (LColor <> clNone) then LFixedColor := LColor; end; end; end; } if False then f := DT_WORDBREAK else f := DT_SINGLELINE; // or DT_VCENTER; if aRow = 0 then Canvas.Font.Size := Font.Size - 2; r := ARect; r.Top := r.Top + 2; r.Left := r.Left + 3; r.Right := r.Right - 2; r.Bottom := r.Bottom - 3; // case ColsDefaultAlignment[aCol] of // taLeftJustify: // f := f or DT_LEFT; // taRightJustify: // f := f or DT_RIGHT; // taCenter: // f := f or DT_CENTER; // end; // if aRow = 0 then // begin // // end; // Canvas.Brush.Color := clRed; // Canvas.FillRect(r) ; // DrawCellBackground(ARect, clGray, [gdFixed], aCol, aRow); if fLink = nil then s := -1 else s := fLink.RecNoGet + 1; if aCol = 0 then if aRow = 0 then v := '' else if aRow = s then v := '>' else v := ''; // begin // bc := Canvas.Brush.Color; // pc := Canvas.Pen.Color; // triangle[0] := TPoint.Create(ARect.Left + spacing, ARect.Top + spacing); // triangle[1] := TPoint.Create(ARect.Left + spacing, ARect.Top + ARect.Height - spacing); // triangle[2] := TPoint.Create(ARect.Left + ARect.Width - spacing, ARect.Top + ARect.Height div 2); // // Canvas.Pen.Color := clBlack; // Canvas.Brush.Color := clBlack; // Canvas.Polygon(triangle); // Canvas.FloodFill(ARect.Left + ARect.Width div 2, ARect.Top + ARect.Height div 2, clBlack, fsSurface); // // Canvas.Pen.Color := pc; // Canvas.Brush.Color := bc; // end // end // else // if aCol = 0 then DrawText(Canvas.Handle, PChar(v), Length(v), r, f); end; procedure TxnGrid.InvalidateCell(aCol, aRow: Integer); begin LogString(Format('TxnGrid.InvalidateCell(%d,%d);', [aCol, aRow])); inherited InvalidateCell(aCol, aRow); end; procedure TxnGrid.InvalidateCol(aCol: Integer); begin LogString(Format('TxnGrid.InvalidateCol(%d);', [aCol])); inherited InvalidateCol(aCol); end; procedure TxnGrid.InvalidateGrid; begin LogString(Format('TxnGrid.InvalidateGrid();', [])); inherited InvalidateGrid; end; procedure TxnGrid.InvalidateRow(aRow: Integer); begin LogString(Format('TxnGrid.InvalidateRow(%d);', [aRow])); inherited InvalidateRow(aRow); end; procedure TxnGrid.InvalidateColsFrom(aIndex: Integer); var c: Integer; begin LogString(Format('TxnGrid.InvalidateColsFrom(%d);', [aIndex])); if aIndex >= LeftCol then if aIndex <= LeftCol + VisibleColCount - 1 then for c := aIndex to LeftCol + VisibleColCount - 1 do InvalidateCol(c); end; procedure TxnGrid.InvalidateRowsFrom(aIndex: Integer); var r: Integer; begin LogString(Format('TxnGrid.InvalidateRowsFrom(%d);', [aIndex])); if aIndex >= TopRow then if aIndex <= TopRow + VisibleRowCount - 1 then for r := aIndex to TopRow + VisibleRowCount - 1 do InvalidateRow(r); end; procedure TxnGrid.LogString(aString: String); begin if fLog <> nil then fLog.add(aString); end; function TxnGrid.LinkGet: IxnGridLink; begin Result := fLink; end; procedure TxnGrid.LinkSet(aValue: IxnGridLink); begin LogString(Format('TxnGrid.LinkSet();', [])); fLink := aValue; fLink.NotifySet(NotifyRow); end; function TxnGrid.LogGet: TStrings; begin Result := fLog end; procedure TxnGrid.LogSet(aValue: TStrings); begin fLog := aValue end; procedure TxnGrid.NotifyCol(fData: TxnGridLinkNotifyData); begin LogString(Format('TxnGrid.Col.%s(%d);', [xnGridEventKindDes(fData.Kind), fData.Col])); case fData.Kind of gekAdd: ColCountSet(fColumns.Count + 1); gekDel: FixedCols := 0; // IfThen(fColumns.Count > 0, 1, 0); gekEdit: ; gekMove: ; end; end; procedure TxnGrid.OnRecNo(aIndex: Integer); begin LogString(Format('zzz TxnGrid.OnRecNo(%d);', [aIndex])); if fLink = nil then exit; if aIndex + 1 <> Row then Row := aIndex + 1; end; procedure TxnGrid.NotifyRow(fData: TxnGridLinkNotifyData); begin LogString(Format('TxnGrid.NotifyRow.%s(%d,%d);', [xnGridEventKindDes(fData.Kind), fData.Row, fData.Col])); if fLink = nil then exit; case fData.Kind of gekAdd: begin RowCountSet(fLink.RowCountGet + 1); InvalidateRowsFrom(fData.Row + 1); OnRecNo(fData.Row); end; gekDel: begin RowCountSet(fLink.RowCountGet + 1); InvalidateRowsFrom(fData.Row + 1); end; gekEdit: begin InvalidateRow(fData.Row + 1); end; gekMove: begin InvalidateRow(fData.Row); OnRecNo(fData.Row); end; end; end; function TxnGrid.OptionsEditingGet: Boolean; begin Result := goEditing in Options; end; procedure TxnGrid.OptionsEditingSet(aValue: Boolean); begin if aValue then Options := Options + [goEditing] else Options := Options - [goEditing]; end; // function TxnGrid.RowCountGet: Integer; // begin // Result := inherited RowCount // end; procedure TxnGrid.RowCountSet(aValue: Integer); begin LogString(Format('TxnGrid.RowCountSet(%d);', [aValue])); if aValue <> RowCount then begin if aValue < 2 then aValue := 2; inherited RowCount := aValue; FixedRows := IfThen(aValue > 1, 1, 0); RowHeights[0] := 17; end; end; procedure TxnGrid.OnSelectCell_(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); begin LogString(Format('TxnGrid.OnSelectCell(%d.%d).Outer', [aCol, aRow])); if fLink = nil then exit; if aRow - 1 <> fLink.RecNoGet() then begin LogString(Format('TxnGrid.OnSelectCell(%d,%d,%d).Inner', [aCol, aRow, fLink.RecNoGet()])); InvalidateCell(0, Row); InvalidateCell(0, aRow); fLink.RecNoSet(aRow - 1); end; end; { TxnGridColumns } function TxnGridColumns.CaptionGet(aIndex: Integer): string; begin if aIndex < 0 then exit(''); if aIndex >= Count then exit(''); Result := TxnGridColumn(inherited GetItem(aIndex)).Caption; end; constructor TxnGridColumns.Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); begin inherited Create(AOwner, ItemClass); fNotify := nil; end; function TxnGridColumns.ItemGet(aIndex: Integer): TxnGridColumn; begin Result := TxnGridColumn(inherited GetItem(aIndex)); end; procedure TxnGridColumns.ItemSet(aIndex: Integer; aValue: TxnGridColumn); begin inherited SetItem(aIndex, aValue); end; { TxnGridColumn } constructor TxnGridColumn.Create(Collection: TCollection); begin inherited Create(Collection); if Collection <> nil then if Collection is TxnGridColumns then if Assigned(TxnGridColumns(Collection).fNotify) then TxnGridColumns(Collection).fNotify(xnGridNotifyDataCreateColEvent(Self.Index, gekAdd)); end; destructor TxnGridColumn.Destroy; begin if Collection <> nil then if Collection is TxnGridColumns then if Assigned(TxnGridColumns(Collection).fNotify) then TxnGridColumns(Collection).fNotify(xnGridNotifyDataCreateColEvent(Self.Index, gekDel)); inherited Destroy; end; procedure TxnGridColumn.SetIndex(aIndex: Integer); var IndexOld: Integer; IndexNew: Integer; begin IndexOld := Index; IndexNew := aIndex; if (IndexOld >= 0) and (IndexOld <> IndexNew) then begin inherited SetIndex(IndexNew); if Collection <> nil then if Collection is TxnGridColumns then if Assigned(TxnGridColumns(Collection).fNotify) then begin TxnGridColumns(Collection).fNotify(xnGridNotifyDataCreateColEvent(IndexOld, gekEdit)); TxnGridColumns(Collection).fNotify(xnGridNotifyDataCreateColEvent(IndexNew, gekEdit)); end; end; end; end.
unit np.value; interface uses sysUtils, rtti, Math, np.common, Generics.Collections; const objectId = 'object'; arrayId = 'array'; booleanId = 'boolean'; undefinedId = 'undefined'; nullId = 'null'; numberId = 'number'; exceptionId = 'exception'; stringId = 'string'; spreadId = '...'; type IValue = interface ['{D95206A4-BAB8-4ADC-882E-DA66B20FDA82}'] function RTTI: TValue; function ToString : string; function GetTypeId : string; property TypeId: string read GetTypeId; end; IValue<T> = interface(IValue) ['{3B7468EC-B921-43A7-BBFC-6D6CAE9D5943}'] function this : T; end; TSelfValue = class(TInterfacedObject, IValue) public typeId : string; constructor Create(); function RTTI: TValue; virtual; function GetTypeID: string; end; TValue<T> = class(TSelfValue, IValue<T>) public Value : T; constructor Create(const AValue: T; const AtypeName: string = ''); function RTTI: TValue; override; function this: T; function ToString : String; override; function Equals(Obj: TObject) : Boolean; override; end; TArrayValue = class(TValue<TArray<IValue>>); TObjectValue<T:class> = class(TValue<T>) public function ToString : string; override; destructor Destroy; override; end; TExceptionValue = class(TObjectValue<Exception>) public constructor Create; procedure throw; end; TRecordValue<T:record> = class(TValue<T>) type PRef = ^T; function Ref : PRef; end; TAnyObject = class(TObjectValue<TDictionary<string,IValue>>, IValue<TAnyObject>) public function ToString : String; override; constructor Create(); reintroduce; procedure setValue(const key:string; const Avalue : IValue); function getValue(const Key: string) : IValue; function GetKeys : TArray<String>; procedure DeleteKey(const AKey:String); function EnumKeys : TEnumerable<String>; function this: TAnyObject; property ValueOf[const key: string] : IValue read GetValue write SetValue; default; end; TAnyArray = class(TAnyObject, IValue<TAnyArray>) private FLength: int64; FShift: int64; public constructor Create( elemNum: int64 ); overload; constructor Create(initialValues : array of const ); overload; constructor Create(); reintroduce; overload; destructor Destroy; override; function GetValueAt( Index: Int64 ) : IValue; procedure SetValueAt( Index: Int64; AValue: IValue ); function ToString: String; override; function GetLength : Int64; procedure SetLength(const AValue: int64); function Pop : IValue; function Push(AValue: IValue) : Int64; overload; function Push(AValues : array of const) : int64; overload; function Map( func : TFunc<IValue,IValue>) : IValue<TAnyArray>; procedure forEach( func : TProc<IValue,int64,TAnyArray> ); overload; procedure forEach( func : TProc<IValue,int64> ); overload; procedure forEach( func : TProc<IValue> ); overload; function find( func : TFunc<IValue,int64,TAnyArray,Boolean> ) : IValue; overload; function find( func : TFunc<IValue,int64,Boolean> ) : IValue; overload; function find( func : TFunc<IValue,Boolean> ): IValue; overload; function Includes(const value : IValue; AFromIndex:int64=0 ) : Boolean; procedure fill( value: IValue; start: int64=0; end_:int64 =High(Int64)); function join(const separator : string=',') : string; function splice(start:int64; deleteCount: int64; insert : array of const) : IValue; function shift : IValue; function unshift(AValue: IValue) : int64; overload; function unshift(AValues: array of const) : int64; overload; function this: TAnyArray; property ValueAt[ Index: int64] : IValue read GetValueAt write SetValueAt; default; property Length : int64 read GetLength write SetLength; end; TJSONNumber = class(TValue<Double>) constructor Create(AValue: Double); function ToString : String; override; function Equals(Obj: TObject): Boolean; override; end; TJSONBoolean = class(TValue<Boolean>) constructor Create(AValue: Boolean); function ToString : String; override; function Equals(Obj: TObject): Boolean; override; end; TJSONString = class(TValue<String>) constructor Create(const AValue: String); function ToString : String; override; function Equals(Obj: TObject): Boolean; override; end; ObjectWalker = record this : IValue; function isObject : Boolean; function isArray : Boolean; function asNumber: Double; function asTrunc: int64; function asObject : TAnyObject; function asArray : TAnyArray; procedure walk(const prop: string); overload; procedure walk(const path: array of string); overload; end; function JSONNull : IValue; function void_0 : IValue; function spread : IValue; function JSONParse(const JSON:String) : IValue; overload; function JSONParse(const JSON:String; var I:Integer) : IValue; overload; function mkValue( i : int64 ): IValue; overload; function mkValue(const s : string): IValue; overload; function mkValue(a: TVarRec): IValue; overload; function mkValuesOLD(values: array of const) : IValue; deprecated; function mkValues(values: array of const) : IValue; function TryToJSValue(const AFrom: IValue; out ATo: IValue) : Boolean; function IsJSType(const AValue : IValue) : Boolean; function JSEquals(const value1, value2 : IValue) : Boolean; function II( values: array of const ) : IValue; implementation uses np.ut, Generics.Defaults; { TValue<T> } constructor TValue<T>.Create(const AValue: T; const ATypeName : string); begin inherited Create; if AtypeName <> '' then TypeId := ATypeName; Value := AValue; end; function TValue<T>.Equals(Obj: TObject): Boolean; begin result := inherited Equals(Obj); if not result then begin if obj is TValue<T> then result := TComparer<T>.Default.Compare(value, TValue<T>(obj).Value) = 0; end end; function TValue<T>.RTTI: TValue; begin result := TValue.From<T>(Value); end; function TValue<T>.this : T; begin result := value; end; function TValue<T>.ToString: String; begin try result := RTTI.ToString; except result := inherited ToString; end; end; { TOBjectValue } destructor TOBjectValue<T>.Destroy; begin if assigned(value) then FreeAndNil(Value); inherited; end; function mkValue(i : int64): IValue; overload; begin Result := TValue<int64>.Create(i,'int64'); end; function mkValue(const s : string): IValue; overload; begin Result := TValue<string>.Create(s,stringId ); end; { TRecordValue<T> } function TRecordValue<T>.Ref: PRef; begin result := @Value; end; function mkValuesOLD(values: array of const) : IValue; var i : integer; arr : TArray<IValue>; begin SetLength(arr,High(values)+1); for I := 0 to length(Values)-1 do begin try arr[i] := mkValue(values[i]); except arr[i] := TExceptionValue.Create; end; end; result := TArrayValue.Create(arr); end; function mkValues(values: array of const) : IValue; begin result := TAnyArray.Create(values); end; function mkValue(a: TVarRec): IValue; overload; begin case a.VType of vtInteger: result := TJSONNumber.Create(a.VInteger);//TValue<integer>.Create(a.VInteger); vtBoolean: result := TJSONBoolean.Create(a.VBoolean);// TValue<Boolean>.Create(a.VBoolean); vtExtended: result := TJSONNumber.Create(a.VExtended^); // TValue<Extended>.Create(a.VExtended^); {$IFNDEF NEXTGEN} vtString: result := TJSONString.Create(a.VString^); // mkValue(a.VString^); vtWideString: result := TJSONString.Create(WideString(a.VWideString)); //TValue<string>.Create(WideString(a.VWideString)); {$ENDIF} vtPointer: begin if a.VPointer = nil then result := void_0 else result := TValue<Pointer>.Create(a.VPointer); end; vtPChar: result := TJSONString.Create( String(a.VPChar) ); //TValue<Char>.Create(char(a.VPChar^)); vtChar: result := TJSONString.Create( char(a.VChar) + ''); //TValue<Char>.Create(char(a.VChar)); vtObject: begin if a.VObject = nil then result := void_0 else if TObject(a.VObject) is TSelfValue then result := TSelfValue(a.VObject) else result := TValue<TObject>.Create(a.VObject); end; vtClass: result := TValue<TClass>.Create(a.VClass); vtWideChar: result := TJSONString.Create(Char(a.VWideChar)+''); //TValue<Char>.Create(a.VWideChar); vtPWideChar: result := TJSONString.Create(String(PChar(a.VPWideChar))); //TValue<Char>.Create(a.VPWideChar^); vtAnsiString: result := TJSONString.Create(AnsiString(a.VAnsiString));// mkValue( AnsiString(a.VAnsiString)); vtCurrency: result := TValue<Currency>.Create(a.VCurrency^); vtVariant: result := TValue<Variant>.Create(a.VVariant^); vtInterface: if a.VInterface = nil then result := void_0 else if IInterface(a.VInterface).QueryInterface(IValue,result) <> S_OK then result := TValue<IInterface>.Create(IInterface( a.VInterface )); vtInt64: result := TJSONNumber.Create(a.VInt64^); //result := mkValue(a.VInt64^); vtUnicodeString: result := TJSONString.Create(string(a.VUnicodeString)); // mkValue(string(a.VUnicodeString)); else result := nil; end; end; { TAnyValue } function TAnyObject.getValue(const Key: string): IValue; begin if not Value.TryGetValue(Key, result) then result := void_0; end; constructor TAnyObject.Create(); begin inherited Create(TDictionary<String,IValue>.Create, objectId ); end; procedure TAnyObject.setValue(const key: string; const Avalue: IValue); begin Value.AddOrSetValue(key,AValue); end; function TAnyObject.this: TAnyObject; begin result := self; end; function TAnyObject.ToString: String; var sb : TStringBuilder; i : int64; ar : TArray<TPair<String,IValue>>; s : string; begin ar := Value.ToArray; if Length(ar) = 0 then exit('{}'); sb := TStringBuilder.Create; try sb.Append('{'); for I := 0 to Length(ar)-1 do begin sb.Append('"').Append( ar[i].Key ).Append('"').Append(':'); if ar[i].Value = nil then sb.Append('null') else if (ar[i].Value is TJSONNumber) or (ar[i].Value is TJSONBoolean) or // (ar[i].Value is TJSONString) or (ar[i].Value is TAnyObject) or (ar[i].Value is TValue<Integer>) or (ar[i].Value is TValue<Int64>) or (ar[i].Value is TValue<UInt64>) or (ar[i].Value is TValue<Cardinal>) or (ar[i].Value is TValue<Double>) or (ar[i].Value is TValue<Extended>) then sb.Append(ar[i].Value.ToString) else sb.AppendFormat('"%s"',[ JSONText( ar[i].Value.ToString, true) ]); if i < Length(ar)-1 then sb.Append(',') end; sb.Append('}'); result := sb.ToString; finally sb.Free; end; end; procedure TAnyObject.DeleteKey(const AKey: String); begin value.Remove(AKey); end; function TAnyObject.EnumKeys: TEnumerable<String>; begin result := value.Keys; end; function TAnyObject.GetKeys: TArray<String>; begin result := value.Keys.ToArray; end; { TAnyArray } procedure TAnyArray.forEach(func: TProc<IValue, int64, TAnyArray>); var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin func(GetValueAt(i),i,self); end; end; procedure TAnyArray.forEach(func: TProc<IValue, int64>); var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin func(GetValueAt(i),i); end; end; constructor TAnyArray.Create(elemNum: int64); begin Create; if elemNum < 0 then elemNum := 0;// raise EInvalidArgument.Create('Invalid array length'); FLength := elemNum; end; destructor TAnyArray.Destroy; begin inherited; end; function TAnyArray.find(func: TFunc<IValue, int64, TAnyArray, Boolean>): IValue; var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin if func(GetValueAt(i),i,self) then exit( GetValueAt(i) ); end; exit(void_0); end; function TAnyArray.find(func: TFunc<IValue, int64, Boolean>): IValue; var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin if func(GetValueAt(i),i) then exit( GetValueAt(i) ); end; exit(void_0); end; procedure TAnyArray.fill(value: IValue; start: int64; end_:int64); begin if Start < 0 then start := Max(FLength + start, 0) else start := Min(start,FLength); if end_ > FLength then end_ := FLength; if end_ < 0 then end_ := Max(Flength + end_,0) else end_ := Min(end_, FLength ); while start < end_ do begin SetValueAt(start, value ); inc(start); end; end; function TAnyArray.find(func: TFunc<IValue, Boolean>): IValue; var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin if func(GetValueAt(i)) then exit( GetValueAt(i) ); end; exit(void_0); end; procedure TAnyArray.forEach(func: TProc<IValue>); var i : integer; begin if assigned(func) then for i := 0 to FLength-1 do begin func(GetValueAt(i)); end; end; function TAnyArray.GetLength: Int64; begin result := FLength; end; function TAnyArray.GetValueAt(Index: Int64): IValue; begin if Index >= 0 then Inc(Index,FShift); if not Value.TryGetValue(IntToStr(Index),result) then result := nil; end; function TAnyArray.Includes(const value: IValue; AFromIndex:int64): Boolean; var i : int64; begin result := false; if AFromIndex < 0 then AFromIndex := 0 else if AFromIndex >= FLength then exit(false); for i := AFromIndex to FLength-1 do begin if JSEquals( GetValueAt(i), value ) then exit(true); end; end; function TAnyArray.join(const separator: string): string; var i : int64; begin if FLength = 0 then exit(''); result := GetValueAt(0).ToString; for i := 1 to FLength-1 do begin result := result + separator + GetValueAt(i).ToString; end; end; function TAnyArray.Map(func: TFunc<IValue, IValue>): IValue<TAnyArray>; var i : int64; begin result := TAnyArray.Create(); if not assigned(func) then exit; for i := 0 to FLength-1 do begin result.this.SetValueAt(i, func(GetValueAt(i))); end; end; constructor TAnyArray.Create(initialValues: array of const); var i : int64; spredFlag : Boolean; tmp : IValue; tmpAsArray: TAnyArray; begin Create; spredFlag := false; for I := 0 to System.length(InitialValues)-1 do begin try tmp := mkValue(initialValues[i]); if tmp = spread then begin spredFlag := true; continue; end; if spredFlag and (tmp is TAnyArray) then begin tmpAsArray := tmp as TAnyArray; tmpAsArray.forEach( procedure (value: IValue) begin Push( value ); end ); end else Push( tmp ); except push( TExceptionValue.Create ); end; spredFlag := false; end; end; constructor TAnyArray.Create; begin inherited Create(); typeId := arrayId; end; function TAnyArray.Pop: IValue; var key : string; begin if FLength <= 0 then exit(nil); key := IntToStr( FLength-1+FShift); if value.TryGetValue( key, result) then value.Remove( key ) else result := nil; Dec(FLength); end; function TAnyArray.Push(AValues: array of const): int64; var i : integer; begin for I := 0 to System.length(AValues)-1 do begin Push( mkValue(Avalues[i]) ); end; result := FLength; end; function TAnyArray.Push(AValue: IValue): Int64; begin SetValueAt(FLength,AValue); result := FLength; end; procedure TAnyArray.SetLength(const AValue: int64); begin if AValue > FLength then FLength := AValue else begin if AValue <= 0 then begin FLength := 0; FShift := 0; Value.Clear; end else while FLength > AValue do begin SetValueAt(FLength-1,nil); Dec(FLength); end; end; end; procedure TAnyArray.SetValueAt(Index: Int64; AValue: IValue); begin if (Index < 0) then begin Value.AddOrSetValue(IntToStr(Index), AValue); exit; end; Value.AddOrSetValue(IntToStr(Index+FShift), AValue); if (Index >= FLength) then FLength := Index+1; end; function TAnyArray.shift: IValue; begin if FLength <= 0 then exit(nil); result := GetValueAt(0); SetValueAt(0,nil); inc(FShift); dec(FLength); end; function TAnyArray.splice(start: int64; deleteCount: int64; insert: array of const): IValue; var insertArray, removeArray: TAnyArray; i,k : int64; resultLength,actualLength: int64; begin insertArray := TAnyArray.Create( insert ); removeArray := TAnyArray.Create( ); try if start < 0 then start := FLength+start; if start < 0 then start := 0; if start >= FLength then begin deleteCount := 0; start := FLength; end; if deleteCount < 0 then deleteCount := 0; if start + deleteCount > FLength then deleteCount := FLength-start; actualLength := FLength; resultLength := FLength + InsertArray.Length - deleteCount; if (deleteCount > 0) or (InsertArray.Length > 0) then begin k := start+deleteCount; for I := start to actualLength-1 do begin if i < k then removeArray.Push( getValueAt(i) ) else insertArray.Push( getValueAt(i) ); SetValueAt(i, nil ); end; for i := 0 to insertArray.Length-1 do begin SetValueAt( start+i, insertArray.GetValueAt(i) ); end; end; FLength := resultLength; finally freeAndNil(insertArray); result := removeArray; end; end; function TAnyArray.this: TAnyArray; begin result := self; end; function TAnyArray.ToString: String; var sb : TStringBuilder; i : int64; s : string; value : IValue; begin if FLength <= 0 then exit(''); sb := TStringBuilder.Create; try sb.Append('['); for I := 0 to FLength-1 do begin value := GetValueAt(i); if (Value is TJSONNumber) or (Value is TJSONBoolean) or //(Value is TJSONString) or (Value is TAnyObject) or (Value is TValue<Integer>) or (Value is TValue<Int64>) or (Value is TValue<UInt64>) or (Value is TValue<Cardinal>) or (Value is TValue<Double>) or (Value is TValue<Extended>) then sb.Append(Value.ToString) else sb.AppendFormat('"%s"',[Value.ToString]); sb.Append( s ); if i <> FLength-1 then sb.Append(','); end; sb.Append(']'); result := sb.ToString; finally sb.Free; end; end; function TAnyArray.unshift(AValues: array of const): int64; var i : integer; begin for I := System.length(AValues)-1 downto 0 do begin unshift(mkValue( AValues[i] )); end; result := FLength; end; function TAnyArray.unshift(AValue: IValue): int64; begin if FLength <= 0 then begin SetValueAt(0,AValue); result := FLength; end else begin Dec(FShift); Inc(FLength); SetValueAt(0,AValue); result := FLength; end; end; function JSONParse(const JSON: string; var I: integer) : IValue; VAR L : INTEGER; J:INTEGER; K,V: String; &object : TAnyObject; &array : TAnyArray; LCount : integer; Float: Double; function ReadToken : String; var J : Integer; begin J := I; While (I<=L) and not ((JSON[I] in [',','}',']']) or (JSON[I] <= #20)) DO INC(I); result := Copy(JSON,J,I-J); end; begin result := nil; if I < 1 then I := 1; L := Length(JSON); LCount := 0; While I<=L DO BEGIN CASE JSON[I] OF '{': begin INC(I); &object := TAnyObject.Create; result := &object; repeat K := DecodeJSONText(JSON,I); While (I<=L) and (JSON[I] <> ':') DO INC(I); INC(I); &object[K] := JSONParse(JSON,I); //outputdebugStr(K); While (I<=L) and not (JSON[I] in [',','}']) DO INC(I); INC(I); until not((I<=L) and (I>1) and (JSON[I-1]=',')); end; '[': begin INC(I); &array := TAnyArray.Create; result := &array; repeat &array[LCount] := JSONParse( JSON,I ); inc(LCount); While (I<=L) and not (JSON[I] in [',',']']) DO INC(I); INC(I); until not((I<=L) and (I>1) and (JSON[I-1]=',')); // if (LCount = 1) and (&array[0] = nil) then // &array.pop(); end; '"': begin result := TJSONString.Create( DecodeJSONText(JSON,I) ); end; #0..#$20: begin INC(I); continue; end else begin V := ReadToken; if V = 'null' then result := JSONNull else if V = 'true' then result := TJSONBoolean.Create(True) else if V = 'false' then result := TJSONBoolean.Create(False) else if TryStrToFloat(V,Float, g_FormatUs) then result := TJSONNumber.Create(Float) else result := mkValue(V); end; END; break; END; // if value = nil then // OutputDebugStr('null'); end; function JSONParse(const JSON : string) : IValue; var i : integer; begin i := 1; result := JSONParse(JSON,I); end; { TJSONNumber } constructor TJSONNumber.Create(AValue: Double); begin inherited Create(AValue,numberId); end; function TJSONNumber.Equals(Obj: TObject): Boolean; begin result := Obj = self; if (not result) and (Obj is TJSONNumber) then begin result := TJSONNumber(Obj).Value = Value; end; end; function TJSONNumber.ToString: String; begin if Frac(Value) = 0 then result := IntToStr( Trunc(Value) ) else result := FloatToStr( Value,g_FormatUS ); end; { TJSONBoolean } constructor TJSONBoolean.Create(AValue: Boolean); begin inherited Create(AValue,booleanId); end; function TJSONBoolean.Equals(Obj: TObject): Boolean; begin result := Obj = Self; if (not result) and (Obj is TJSONBoolean) then begin result := TJSONBoolean(Obj).Value = Value; end; end; function TJSONBoolean.ToString: String; begin result := JSONBoolean(value); end; type TJSONNull = class(TSelfValue) constructor Create(); function ToString : String; override; end; TVoid_0 = class(TSelfValue) constructor Create(); function ToString : String; override; end; TSpreadOperator = class(TSelfValue) constructor Create(); function ToString : String; override; end; { TJSONNull } constructor TJSONNull.Create; begin inherited Create; typeid := nullId; end; function TJSONNull.ToString: String; begin result := nullId; end; var g_null : IValue; g_spread : IValue; g_void_0 : IValue; function JSONNull : IValue; begin result := g_null; end; function spread : IValue; begin result := g_spread; end; function void_0 : IValue; begin result := g_void_0; end; { TJSONString } constructor TJSONString.Create(const AValue: String); begin inherited Create(AValue,stringId); end; function TJSONString.Equals(Obj: TObject): Boolean; begin result := assigned(Obj) and (Obj is TValue<String>) and (TValue<String>(obj).Value = Value); end; function TJSONString.ToString: String; begin result := value;// Format('"%s"',[value{TBoxValue.EncodeJSONText(Value)}]); end; { TExceptionValue } constructor TExceptionValue.Create; begin inherited Create( Exception(AcquireExceptionObject), exceptionId); end; procedure TExceptionValue.throw; begin if assigned(value) then begin try raise value; finally value := nil; end; end else raise Exception.Create('Exception is ready raised! The reference exception was lost!'); end; function TObjectValue<T>.ToString: string; begin if assigned(value) then result := value.ToString else result := inherited; end; { TVoid_0 } constructor TVoid_0.Create; begin inherited Create; typeId := undefinedId; end; function TVoid_0.ToString: String; begin result := undefinedId; end; { ObjectWalker } function ObjectWalker.asArray: TAnyArray; begin result := this as TAnyArray; end; function ObjectWalker.asNumber: Double; begin if this is TValue<integer> then result := TValue<integer>(this).value else if this is TValue<Cardinal> then result := TValue<Cardinal>(this).value else if this is TValue<int64> then result := TValue<int64>(this).value else if this is TValue<uint64> then result := TValue<uint64>(this).value else if this is TValue<word> then result := TValue<word>(this).value else if this is TValue<String> then begin if not TryStrToFloat(TValue<String>(this).value, result) then result := NaN; end else result := NaN; end; function ObjectWalker.asObject: TAnyObject; begin result := this as TAnyObject; end; function ObjectWalker.asTrunc: int64; begin if isNaN( asNumber ) then result := 0 else result := trunc( asNumber ); end; function ObjectWalker.isArray: Boolean; begin result := this is TAnyArray; end; function ObjectWalker.isObject: Boolean; begin result := this is TAnyObject; end; type EWalkError = class(Exception); procedure ObjectWalker.walk(const path: array of string); var i : integer; begin for I := Low(Path) to High(Path) do begin walk(path[i]); end; end; procedure ObjectWalker.walk(const prop: string); begin this := asObject[prop]; end; { TSelfValue } constructor TSelfValue.Create; begin TypeId := ClassName; end; function TSelfValue.GetTypeID: string; begin result := typeId; end; function TSelfValue.RTTI: TValue; begin result := self; end; function IsJSType(const AValue : IValue) : Boolean; begin if AValue = nil then result := IsJsType(void_0) else begin result := (AValue.TypeId = objectId) or (AValue.TypeId = booleanId) or (AValue.TypeId = undefinedId) or (AValue.TypeId = nullId) or (AValue.TypeId = numberId) or (AValue.TypeId = stringId); end; end; function TryToJSValue(const AFrom: IValue; out ATo: IValue) : Boolean; var i64: int64; v : TValue; begin if AFrom = nil then exit( TryToJSValue(void_0,Ato) ); OutputDebugStr(AFrom.TypeId+' '+AFrom.ToString); if IsJSType(AFrom) then begin ATo := AFrom; exit(true); end; v := AFrom.RTTI; case AFrom.RTTI.Kind of tkEnumeration: if v.IsType<Boolean> then begin ATo := TJSONBoolean.Create(v.AsBoolean); exit(true); end; tkFloat: begin ATo := TJSONNumber.Create(v.AsExtended); exit(true); end; {$IFNDEF NEXTGEN} tkWString, tkString, {$ENDIF} tkLString, tkUString: begin ATo := TJSONString.Create( v.AsString ); exit(true); end; end; if v.TryAsOrdinal(i64) then begin ATo := TJSONNumber.Create(i64); exit(true); end; result := false; end; function JSEquals(const value1, value2 : IValue) : Boolean; var v1,v2: IValue; begin if not tryToJSValue(value1,v1) then v1 := value1; if not tryToJSValue(value2,v2) then v2 := value2; exit( (v1 as TObject).Equals( v2 as TObject ) and (v2 as TObject).Equals( v1 as TObject ) ); end; { TSpreadOperator } constructor TSpreadOperator.Create; begin inherited Create; typeid := spreadId; end; function TSpreadOperator.ToString: String; begin result := spreadId; end; function II(values: array of const ) : IValue; var i : integer; begin result := Void_0; for i := low(values) to High(values) do begin result := mkValue(values[i]); if result <> void_0 then exit; end; end; initialization g_null := TJSONNull.Create; g_spread := TSpreadOperator.Create; g_void_0 := TVoid_0.Create; finalization g_null := nil; g_spread := nil; g_void_0 := nil; end.
program FeldSort3 (input,output); {sortiert ein einzulesendes Feld von integer-Zahlen} const FELDGROESSE = 5; type tIndex = 1..FELDGROESSE; tFeld = array [tIndex] of integer; var EingabeFeld : tFeld; idx : tIndex; procedure FeldSortieren (var SortFeld : tFeld); var i : tIndex; function FeldMinimumPos (Feld:tFeld; von,bis:tIndex) : tIndex; var MinimumPos, j : tIndex; begin MinimumPos := von; for j := von+1 to bis do begin if Feld[j] < Feld[MinimumPos] then MinimumPos := j end; FeldMinimumPos := MinimumPos; end; procedure vertauschen (var hin, her : integer); var Tausch : integer; begin Tausch := hin; hin := her; her := Tausch; end; begin for i := 1 to FELDGROESSE do begin vertauschen(SortFeld[i],SortFeld[FeldMinimumPos(SortFeld,i,FELDGROESSE)]); end; end; begin {Feld wird eingelesen} writeln('Das Feld der Groesse ',FELDGROESSE,' wird eingelesen.'); writeln; for idx := 1 to FELDGROESSE do begin write('Bitte ',idx,'. Wert eingeben: '); readln(EingabeFeld[idx]); end; {Feld wird sortiert} FeldSortieren(EingabeFeld); {Feld wird ausgegeben} writeln; writeln('Das sortierte Feld lautet:'); writeln; for idx := 1 to FELDGROESSE do begin write(Eingabefeld[idx]:6); end end.
unit Sample.Platform.Windows; {$INCLUDE 'Sample.inc'} interface uses System.Classes, Winapi.Windows, Sample.Platform; type { Implements Windows-specific functionality. } TPlatformWindows = class(TPlatformBase) {$REGION 'Internal Declarations'} private const WINDOW_CLASS_NAME = 'SampleWindow'; private class var FWindow: HWND; FWindowDC: HDC; FContext: HGLRC; FInitialized: Boolean; private class procedure RegisterWindowClass; static; class procedure SetupWindow; static; class procedure SetupOpenGLContext; static; class procedure RunLoop; static; class procedure Shutdown; static; private class function GetKeyShiftState(const ALParam: Integer): TShiftState; static; class function GetMouseShiftState(const AWParam: Integer): TShiftState; static; class procedure MouseCapture(const AWnd: HWND; const ACapture: Boolean); static; class function GetPointFromLParam(const ALParam: LPARAM): TPoint; static; private class function WndProc(Wnd: HWND; Msg: UINT; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall; static; {$ENDREGION 'Internal Declarations'} protected class procedure DoRun; override; end; implementation uses System.Types, System.UITypes, System.SysUtils, Winapi.OpenGLExt, Winapi.Messages, Neslib.Ooogles; { TPlatformWindows } class procedure TPlatformWindows.DoRun; { Main entry point on Windows } begin { Register and create main window and initialize the app } FInitialized := False; RegisterWindowClass; SetupWindow; App.Initialize; App.Resize(App.Width, App.Height); FInitialized := True; { Run and update until terminated } RunLoop; { Cleanup } App.Shutdown; Shutdown; end; class function TPlatformWindows.GetPointFromLParam( const ALParam: LPARAM): TPoint; begin { Extracts the X and Y coordinates from a Windows message } Result.X := Int16(ALParam and $FFFF); Result.Y := Int16(ALParam shr 16); end; class function TPlatformWindows.GetKeyShiftState( const ALParam: Integer): TShiftState; const ALT_MASK = $20000000; begin Result := []; if (GetKeyState(VK_SHIFT) < 0) then Include(Result, ssShift); if (GetKeyState(VK_CONTROL) < 0) then Include(Result, ssCtrl); if (ALParam and ALT_MASK <> 0) then Include(Result, ssAlt); end; class function TPlatformWindows.GetMouseShiftState( const AWParam: Integer): TShiftState; begin Result := []; if ((AWParam and MK_CONTROL) <> 0) then Include(Result, ssCtrl); if ((AWParam and MK_SHIFT) <> 0) then Include(Result, ssShift); end; class procedure TPlatformWindows.MouseCapture(const AWnd: HWND; const ACapture: Boolean); begin if (ACapture) then SetCapture(AWnd) else ReleaseCapture; end; class procedure TPlatformWindows.RegisterWindowClass; var WindowClass: TWndClassEx; begin { Before we can create a window, we need to register a window class that defines the behavior of all instances of this window class. The most important field here is lpfnWndProc, which handles all Windows messages for windows of this class. We point it to our WndProc method. } FillChar(WindowClass, SizeOf(WindowClass), 0); WindowClass.cbSize := SizeOf(WindowClass); WindowClass.style := CS_HREDRAW or CS_VREDRAW; WindowClass.lpfnWndProc := @WndProc; WindowClass.hInstance := HInstance; WindowClass.hIcon := LoadIcon(0, IDI_APPLICATION); WindowClass.hIconSm := LoadIcon(0, IDI_APPLICATION); WindowClass.hCursor := LoadCursor(0, IDC_ARROW); WindowClass.lpszClassName := WINDOW_CLASS_NAME; RegisterClassEx(WindowClass); end; class procedure TPlatformWindows.RunLoop; var Msg: TMsg; begin { Run the Windows message pump } StartClock; while (not Terminated) do begin while (PeekMessage(Msg, 0, 0, 0, PM_REMOVE)) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; { Update app and render frame to back buffer } Update; { Swap backbuffer to front to display it } SwapBuffers(FWindowDC); end; end; class procedure TPlatformWindows.SetupOpenGLContext; var PFD: TPixelFormatDescriptor; PixelFormat: Integer; begin FillChar(PFD, SizeOf(PFD), 0); PFD.nSize := SizeOf(PFD); PFD.nVersion := 1; PFD.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; PFD.iPixelType := PFD_TYPE_RGBA; PFD.cColorBits := 24; PFD.cAlphaBits := 0; // 8; PFD.cDepthBits := 16; if (TPlatformWindows.App.NeedStencilBuffer) then PFD.cStencilBits := 8; PFD.iLayerType := PFD_MAIN_PLANE; PixelFormat := ChoosePixelFormat(FWindowDC, @PFD); SetPixelFormat(FWindowDC, PixelFormat, @PFD); FContext := wglCreateContext(FWindowDC); if (FContext = 0) then raise Exception.Create('Unable to create OpenGL context'); if (not wglMakeCurrent(FWindowDC, FContext)) then raise Exception.Create('Unable to activate OpenGL context'); InitOpenGLext; // Must be called after wglMakeCurrent { Initialize Ooogle to make OpenGL on Windows compatible with OpenGL-ES } InitOoogles; end; class procedure TPlatformWindows.SetupWindow; const STYLE = WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_MINIMIZEBOX; STYLE_EX = WS_EX_APPWINDOW or WS_EX_WINDOWEDGE; var R: TRect; ScreenX, ScreenY: Integer; begin { Calculate the actual Window size (including borders) we need so the client area of the window equals our specifications. } R := Rect(0, 0, App.Width, App.Height); AdjustWindowRectEx(R, STYLE, False, STYLE_EX); { Create main window and use it to create an OpenGL context } FWindow := CreateWindowEx(STYLE_EX, WINDOW_CLASS_NAME, PChar(App.Title), STYLE, 0, 0, R.Width, R.Height, 0, 0, HInstance, nil); if (FWindow = 0) then raise Exception.Create('Unable to create main window'); FWindowDC := GetDC(FWindow); if (FWindowDC = 0) then raise Exception.Create('Unable to retrieve device context for main window'); SetupOpenGLContext; { Center the window on the main screen } GetWindowRect(FWindow, R); ScreenX := (GetSystemMetrics(SM_CXSCREEN) - R.Width) div 2; ScreenY := (GetSystemMetrics(SM_CYSCREEN) - R.Height) div 2; SetWindowPos(FWindow, FWindow, ScreenX, ScreenY, -1, -1, SWP_NOSIZE or SWP_NOZORDER or SWP_NOACTIVATE); { Show the window } ShowWindow(FWindow, SW_SHOW); end; class procedure TPlatformWindows.Shutdown; begin wglMakeCurrent(0, 0); if (FContext <> 0) then wglDeleteContext(FContext); if (FWindow <> 0) then begin if (FWindowDC <> 0) then ReleaseDC(FWindow, FWindowDC); DestroyWindow(FWindow); end; end; class function TPlatformWindows.WndProc(Wnd: HWND; Msg: UINT; WParam: WPARAM; LParam: LPARAM): LRESULT; var P: TPoint; begin { This method gets called for each message for our window. For messages we are interested in, we convert these to cross-platform events } if (FInitialized) then begin case Msg of WM_QUIT, WM_CLOSE: Terminated := True; WM_MOUSEMOVE: begin P := GetPointFromLParam(LParam); App.MouseMove(GetMouseShiftState(WParam), P.X, P.Y); end; WM_MOUSEWHEEL: App.MouseWheel(GetMouseShiftState(WParam), Int16(WParam shr 16) div WHEEL_DELTA); WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK: begin MouseCapture(Wnd, (Msg = WM_LBUTTONDOWN)); P := GetPointFromLParam(LParam); if (Msg = WM_LBUTTONDOWN) then App.MouseDown(TMouseButton.mbLeft, GetMouseShiftState(WParam), P.X, P.Y) else App.MouseUp(TMouseButton.mbLeft, GetMouseShiftState(WParam), P.X, P.Y); end; WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDBLCLK: begin MouseCapture(Wnd, (Msg = WM_MBUTTONDOWN)); P := GetPointFromLParam(LParam); if (Msg = WM_MBUTTONDOWN) then App.MouseDown(TMouseButton.mbMiddle, GetMouseShiftState(WParam), P.X, P.Y) else App.MouseUp(TMouseButton.mbMiddle, GetMouseShiftState(WParam), P.X, P.Y); end; WM_RBUTTONDOWN, WM_RBUTTONUP, WM_RBUTTONDBLCLK: begin MouseCapture(Wnd, (Msg = WM_RBUTTONDOWN)); P := GetPointFromLParam(LParam); if (Msg = WM_RBUTTONDOWN) then App.MouseDown(TMouseButton.mbRight, GetMouseShiftState(WParam), P.X, P.Y) else App.MouseUp(TMouseButton.mbRight, GetMouseShiftState(WParam), P.X, P.Y); end; WM_KEYDOWN, WM_SYSKEYDOWN: App.KeyDown(WParam and $FF, GetKeyShiftState(LParam)); WM_KEYUP, WM_SYSKEYUP: App.KeyUp(WParam and $FF, GetKeyShiftState(LParam)); end; end; Result := DefWindowProc(Wnd, Msg, WParam, LParam); end; end.
unit StockDayData_Parse_Sina_Html1; interface uses win.iobuffer, define_stockday_sina, define_stock_quotes, StockDayDataAccess; function DataParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AResultData: PIOBuffer): Boolean; overload; implementation uses Sysutils, StockDayData_Parse_Sina, UtilsHttp, UtilsLog, UtilsHtmlParser; type PParseRecord = ^TParseRecord; TParseRecord = record HtmlRoot: IHtmlElement; IsInTable: Integer; IsTableHeadReady: Boolean; TableHeader: TRT_DealDayData_HeaderSina; DealDayData: TRT_Quote_M1_Day; end; procedure ParseStockDealDataTableRow(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: IHtmlElement); var i: integer; tmpChild: IHtmlElement; tmpHeadColName: TDealDayDataHeadName_Sina; tmpStr: string; tmpTDIndex: integer; tmpIsHead: Boolean; begin FillChar(AParseRecord.DealDayData, SizeOf(AParseRecord.DealDayData), 0); tmpTDIndex := -1; tmpIsHead := false; for i := 0 to ANode.ChildrenCount - 1 do begin tmpChild := ANode[i]; if SameText(tmpChild.TagName, 'td') then begin inc (tmpTDIndex); // 处理 行数据 tmpStr := trim(tmpChild.InnerText); if (not AParseRecord.IsTableHeadReady) then begin for tmpHeadColName := Low(TDealDayDataHeadName_Sina) to High(TDealDayDataHeadName_Sina) do begin if SameText(tmpStr, DealDayDataHeadNames_Sina[tmpHeadColName]) or (Pos(DealDayDataHeadNames_Sina[tmpHeadColName], tmpStr) > 0) then begin AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] := tmpTDIndex; tmpIsHead := true; end; end; end else begin for tmpHeadColName := Low(TDealDayDataHeadName_Sina) to High(TDealDayDataHeadName_Sina) do begin if AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] = tmpTDIndex then begin ParseCellData(tmpHeadColName, @AParseRecord.DealDayData, tmpStr); end; end; end; end; end; if not AParseRecord.IsTableHeadReady then begin AParseRecord.IsTableHeadReady := tmpIsHead; end else begin AddDealDayData(ADataAccess, @AParseRecord.DealDayData); end; end; function HtmlParse_DayData_Sina_Table(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: IHtmlElement): Boolean; var i, j: integer; tmpNode1: IHtmlElement; tmpcnt1: integer; tmpcnt2: integer; tmpRow: integer; tmpTagName: string; var tmpHeadColName: TDealDayDataHeadName_Sina; begin Result := false; AParseRecord.IsTableHeadReady := false; for tmpHeadColName := low(TDealDayDataHeadName_Sina) to high(TDealDayDataHeadName_Sina) do begin AParseRecord.TableHeader.HeadNameIndex[tmpHeadColName] := -1; end; tmpcnt1 := ANode.ChildrenCount; tmpRow := 0; for i := 0 to tmpcnt1 - 1 do begin tmpTagName := lowercase(ANode[i].TagName); if SameText(tmpTagName, 'tr') then begin ParseStockDealDataTableRow(ADataAccess, AParseRecord, ANode[i]); end; if SameText(tmpTagName, 'tbody') then begin tmpNode1 := ANode[i]; tmpcnt2 := tmpNode1.ChildrenCount; for j := 0 to tmpcnt2 - 1 do begin if SameText(tmpNode1[j].TagName, 'tr') then begin ParseStockDealDataTableRow(ADataAccess, AParseRecord, ANode[i]); end; end; continue; end; end; if AParseRecord.IsTableHeadReady then begin Result := true; end; end; function HtmlParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AParseRecord: PParseRecord; ANode: IHtmlElement): Boolean; var i: integer; tmpcnt: integer; tmpTableId: WideString; tmpIsHandledNode: Boolean; begin result := false; if nil = ANode then exit; tmpIsHandledNode := false; if SameText(string(lowercase(ANode.TagName)), 'table') then begin Inc(AParseRecord.IsInTable); tmpcnt := ANode.ChildrenCount; tmpTableId := ANode.Attributes['id']; if '' <> tmpTableId then begin if SameText('FundHoldSharesTable', tmpTableId) then begin tmpIsHandledNode := true; end else begin if Pos('fundholdsharestable', lowercase(tmpTableId)) = 1 then begin tmpIsHandledNode := true; end; end; end; end; if tmpIsHandledNode then begin result := HtmlParse_DayData_Sina_Table(ADataAccess, AParseRecord, ANode); end else begin tmpcnt := ANode.ChildrenCount; for i := 0 to tmpcnt - 1 do begin if not result then begin result := HtmlParse_DayData_Sina(ADataAccess, AParseRecord, ANode[i]); end else begin HtmlParse_DayData_Sina(ADataAccess, AParseRecord, ANode[i]); end; end; end; if SameText(string(lowercase(ANode.TagName)), 'table') then begin Dec(AParseRecord.IsInTable); end; end; function DataParse_DayData_Sina(ADataAccess: TStockDayDataAccess; AResultData: PIOBuffer): Boolean; overload; var tmpParseRec: TParseRecord; // 168k 的数据太大 不能这样设置 tmpHttpHeadSession: THttpHeadParseSession; begin Result := False; if nil = AResultData then exit; FillChar(tmpParseRec, SizeOf(tmpParseRec), 0); FIllChar(tmpHttpHeadSession, SizeOf(tmpHttpHeadSession), 0); HttpBufferHeader_Parser(AResultData, @tmpHttpHeadSession); if (199 < tmpHttpHeadSession.RetCode) and (300 > tmpHttpHeadSession.RetCode)then begin try tmpParseRec.HtmlRoot := UtilsHtmlParser.ParserHtml(AnsiString(PAnsiChar(@AResultData.Data[tmpHttpHeadSession.HeadEndPos + 1]))); except Log('ParserSinaDataError:', ADataAccess.StockItem.sCode + 'error html');// + AnsiString(PAnsiChar(@AResultData.Data[tmpHttpHeadSession.HeadEndPos + 1]))); end; if tmpParseRec.HtmlRoot <> nil then begin Result := HtmlParse_DayData_Sina(ADataAccess, @tmpParseRec, tmpParseRec.HtmlRoot); end; end; end; end.
unit HighScore; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type THighScoreForm = class(TForm) PageControl: TPageControl; RemainingTab: TTabSheet; TimeTab: TTabSheet; RemainingList: TListView; ScoreTab: TTabSheet; PPMTab: TTabSheet; TimeList: TListView; ScoreList: TListView; PPMList: TListView; CloseBtn: TButton; ClearBtn: TButton; procedure CompareDesc(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure CompareAsc(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure CloseBtnClick(Sender: TObject); procedure ClearBtnClick(Sender: TObject); private FLevelName: String; procedure Parse(JournalEntry: String); procedure ReadOutJournal; procedure ClearLists; public procedure Execute(LevelName: String); end; var HighScoreForm: THighScoreForm; implementation {$R *.dfm} uses Functions, Constants; procedure THighScoreForm.CompareDesc(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var n1, n2: integer; begin if item1.SubItems.Count < 1 then exit; if item2.SubItems.Count < 1 then exit; n1 := StrToIntDef(Item1.SubItems[1], 0); n2 := StrToIntDef(Item2.SubItems[1], 0); if (n1 = n2) then Compare := 0 else if (n1 > n2) then Compare := 1 else Compare := -1; end; procedure THighScoreForm.Parse(JournalEntry: String); var res: TStringList; Date, Name: String; Score, Seconds, Removed, Total: Integer; Remaining, PPM: integer; begin res := Explode(JNL_SEP, JournalEntry); // VARIABLES Date := res.Strings[0]; Name := res.Strings[1]; Score := StrToIntDef(res.Strings[2], 0); Seconds := StrToIntDef(res.Strings[3], 0); Removed := StrToIntDef(res.Strings[4], 0); Total := StrToIntDef(res.Strings[5], 0); Remaining := Total - Removed; PPM := Round(Score / Seconds * 60); // CATEGORY A - LOWEST REMAINING STONES RemainingList.SortType := stNone; with RemainingList.Items.Add do begin Caption := Name; SubItems.Add(Date); SubItems.Add(IntToStr(Remaining)); end; RemainingList.SortType := stText; // CATEGORY B - HIGHEST SCORE ScoreList.SortType := stNone; with ScoreList.Items.Add do begin Caption := Name; SubItems.Add(Date); SubItems.Add(IntToStr(Score)); end; ScoreList.SortType := stText; // CATEGORY C - LOWEST TIME TimeList.SortType := stNone; with TimeList.Items.Add do begin Caption := Name; SubItems.Add(Date); SubItems.Add(IntToStr(Seconds)); end; TimeList.SortType := stText; // CATEGORY D - HIGHEST POINTS PER MINUTE PPMList.SortType := stNone; with PPMList.Items.Add do begin Caption := Name; SubItems.Add(Date); SubItems.Add(IntToStr(PPM)); end; PPMList.SortType := stText; end; procedure THighScoreForm.ReadOutJournal; var f: textfile; tmp: string; begin ClearLists; tmp := Format(JNL_FILE, [FLevelName]); if FileExists(tmp) then begin AssignFile(f, tmp); Reset(f); while not eof(f) do begin ReadLn(f, tmp); Parse(tmp); end; CloseFile(f); end; end; procedure THighScoreForm.Execute(LevelName: String); begin FLevelName := LevelName; ReadOutJournal; ShowModal; end; procedure THighScoreForm.CompareAsc(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); var n1, n2: integer; begin if item1.SubItems.Count < 1 then exit; if item2.SubItems.Count < 1 then exit; n1 := StrToIntDef(Item1.SubItems[1], 0); n2 := StrToIntDef(Item2.SubItems[1], 0); if (n1 = n2) then Compare := 0 else if (n1 > n2) then Compare := -1 else Compare := 1; end; procedure THighScoreForm.CloseBtnClick(Sender: TObject); begin Close(); end; procedure THighScoreForm.ClearBtnClick(Sender: TObject); resourcestring LNG_ARE_YOU_SURE = 'Are you really sure you want to clear the high score list?'; begin if MessageDlg(LNG_ARE_YOU_SURE, mtConfirmation, mbYesNoCancel, 0) = mrYes then begin DeleteFile(Format(JNL_FILE, [FLevelName])); ClearLists; end; end; procedure THighScoreForm.ClearLists; begin RemainingList.Clear; ScoreList.Clear; TimeList.Clear; PPMList.Clear; end; end.
unit NotificationLayoutData; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, System.uiTypes, FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, FMX.graphics, System.Types, StrUtils, FMX.Dialogs, crossplatformHeaders, System.Generics.Collections, FMX.VirtualKeyboard; type PasswordDialog = class(TLayout) public // protectWord : AnsiString; _protectLayout: TLayout; _staticInfoLabel: TLabel; _edit: TEdit; // _ProtectWordLabel : TLAbel; _lblMessage: TLabel; _ImageLayout: TLayout; _Image: TImage; _ButtonLayout: TLayout; _YesButton: TButton; _NoButton: TButton; _onYesPress: TProc<AnsiString>; _onNoPress: TProc<AnsiString>; procedure _onYesClick(sender: TObject); procedure _onNoClick(sender: TObject); //procedure _OnExit(sender: TObject); //procedure checkProtect(Sender : TObject ); procedure OnKeybaordPress(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); constructor create(Owner: TComponent; Yes, No: TProc<AnsiString>; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); destructor destroy(); Override; end; type ProtectedConfirmDialog = class(TLayout) public protectWord: AnsiString; _protectLayout: TLayout; _staticInfoLabel: TLabel; _edit: TEdit; _ProtectWordLabel: TLabel; _lblMessage: TLabel; _ImageLayout: TLayout; _Image: TImage; _ButtonLayout: TLayout; _YesButton: TButton; _NoButton: TButton; _onYesPress: TProc; _onNoPress: TProc; procedure _onYesClick(sender: TObject); procedure _onNoClick(sender: TObject); // procedure _OnExit(sender: TObject); procedure checkProtect(sender: TObject); procedure OnKeybaordPress(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); constructor create( Owner : TComponent ; Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); destructor destroy(); Override; end; type YesNoDialog = class(TLayout) private _lblMessage: TLabel; _ImageLayout: TLayout; _Image: TImage; _ButtonLayout: TLayout; _YesButton: TButton; _NoButton: TButton; _onYesPress: TProc; _onNoPress: TProc; procedure _onYesClick(sender: TObject); procedure _onNoClick(sender: TObject); // procedure _OnExit(sender: TObject); public constructor create(Owner: TComponent; Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); destructor destroy(); Override; end; type TNotificationLayout = class(TLayout) popupStack: TStack<TLayout>; notificationStack: TStack<TLayout>; CurrentPOpup: TLayout; PopupQueue: TQueue<TLayout>; backGround: TRectangle; inThinking: Tpanel; constructor create(Owner: TComponent); override; destructor destroy(); Override; procedure backGroundClick(sender: TObject); procedure ClosePopup(); procedure moveCurrentPopupToTop(); procedure centerCurrentPopup(); procedure addPopupToStack( popup :TLayout ); //procedure layoutClick(Sender : TObject); // procedure AddNotification( msg : AnsiString ; time : integer = 15 ); procedure popupProtectedConfirm(Yes: TProc; No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); procedure popupPasswordConfirm(Yes: TProc<AnsiString>; No: TProc<AnsiString>; mess: AnsiString; YesText: AnsiString = 'OK'; NoText: AnsiString = 'Cancel'; icon: integer = 2); procedure popupConfirm(Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); procedure RunInThinkingWindow(proc: TProc); procedure ShowThinkingWindow(); procedure CloseThinkingWindow(); procedure TryShowBackground(); procedure TryHideBackGround(); // procedure popup( msg : AnsiString ); // procedure popup( end; implementation uses uhome , misc; procedure TNotificationLayout.TryShowBackground(); begin backGround.HitTest := true; backGround.Visible := true; backGround.AnimateFloat('opacity', 1, 0.2); end; procedure TNotificationLayout.TryHideBackGround(); begin if inthinking.isVisible then exit(); if CurrentPOpup <> nil then exit(); backGround.AnimateFloat('opacity', 0, 0.2); backGround.HitTest := false; end; procedure TNotificationLayout.RunInThinkingWindow(proc: TProc); begin tthread.CreateAnonymousThread( procedure begin ShowThinkingWindow(); tthread.Synchronize( tthread.Current , procedure begin proc(); end); CloseThinkingWindow(); end).Start; end; procedure TNotificationLayout.ShowThinkingWindow(); begin tthread.Synchronize( tthread.current, procedure begin TryShowBackground(); inThinking.Visible := true; end); end; procedure TNotificationLayout.CloseThinkingWindow(); begin tthread.Synchronize( tthread.current, procedure begin inThinking.Visible := false; TryHideBackGround(); end); end; procedure TNotificationLayout.addPopupToStack( popup :TLayout ); begin if (popupStack.Count = 0) and (CurrentPOpup = nil) then begin CurrentPOpup := popup; self.BringToFront; //popup.AnimateFloat( 'position.x' , (Self.Width /2 ) - (popup.width /2 ) , 0.2 ); popup.Position.X := (Self.Width /2 ) - (popup.width /2 ) ; backGround.HitTest := true; background.Visible := true; //backGround.AnimateFloat( 'opacity' , 1 , 0.2 ); backGround.Opacity := 1; popup.bringTofront(); end else begin popupStack.Push( popup ); //popup.Position.X := (Self.Width /2 ) - (popup.width /2 ) ; end; end; procedure TNotificationLayout.moveCurrentPopupToTop(); begin try if CurrentPOpup <> nil then CurrentPOpup.AnimateFloat('position.y', 0, 0.2); except on E: Exception do begin end; end; end; procedure TNotificationLayout.centerCurrentPopup(); begin try if CurrentPOpup <> nil then CurrentPOpup.AnimateFloat('position.y', (Self.Height / 2) - (CurrentPOpup.Height / 2), 0.2); Except on E: Exception do begin end; end; end; procedure TNotificationLayout.ClosePopup; var KeyboardService: IFMXVirtualKeyboardService; begin try {$IFDEF ANDROID} if TPlatformServices.Current.SupportsPlatformService (IFMXVirtualKeyboardService, IInterface(KeyboardService)) then if KeyboardService <> nil then KeyboardService.HideVirtualKeyboard; {$ENDIF} //Currentpopup.AnimateFloat( 'position.x' , self.width + currentpopup.width , 0.2 ); CurrentPOpup.Position.X := self.width + currentpopup.width; if popupStack.Count <> 0 then begin currentPopup := popupStack.Pop; currentpopup.position.X := (Self.Width /2 ) - (currentpopup.width /2 ); end else begin //backGround.AnimateFloat( 'opacity' , 0 , 0.2 ); backGround.Opacity := 0; background.HitTest :=false; tthread.CreateAnonymousThread(procedure var del : TLayout; begin del := CurrentPOpup; CurrentPOpup := nil; sleep(1000); del.DisposeOf; del := nil; end).Start; end; except on E:Exception do begin end; end; end; procedure TNotificationLayout.backGroundClick(sender: TObject); begin ClosePopup; end; procedure TNotificationLayout.popupPasswordConfirm(Yes, No: TProc<String>; mess: AnsiString; YesText: AnsiString = 'OK'; NoText: AnsiString = 'Cancel'; icon: integer = 2); var popup: TLayout; begin popup := PasswordDialog.create(Self, Yes, No, mess, YesText, NoText, icon); popup.Parent := Self; popup.Align := TAlignLayout.None; popup.Position.Y := (Self.Height / 2) - (popup.Height / 2); popup.Position.X := -popup.width; popup.Visible := true; addPopupToStack( popup ); {CurrentPOpup := popup; Self.BringToFront; popup.AnimateFloat('position.x', (Self.width / 2) - (popup.width / 2), 0.2); backGround.HitTest := true; background.Visible := true; backGround.AnimateFloat( 'opacity' , 1 , 0.2 ) } end; procedure TNotificationLayout.popupConfirm(Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var popup: TLayout; begin popup := YesNoDialog.create(Self, Yes, No, mess, YesText, NoText, icon); popup.Parent := Self; popup.Align := TAlignLayout.None; popup.Position.Y := (Self.Height / 2) - (popup.Height / 2); popup.Position.X := -popup.width; popup.Visible := true; addPopupToStack( popup ); {CurrentPOpup := popup; Self.BringToFront; popup.AnimateFloat('position.x', (Self.width / 2) - (popup.width / 2), 0.2); backGround.HitTest := true; background.Visible := true; backGround.AnimateFloat( 'opacity' , 1 , 0.2 )} end; procedure TNotificationLayout.popupProtectedConfirm(Yes: TProc; No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var popup: TLayout; begin popup := ProtectedConfirmDialog.create(Self, Yes, No, mess, YesText, NoText, icon); popup.Parent := Self; popup.Align := TAlignLayout.None; popup.Position.Y := (Self.Height / 2) - (popup.Height / 2); popup.Position.X := -popup.width; popup.Visible := true; addPopupToStack( popup ); {CurrentPOpup := popup; Self.BringToFront; popup.AnimateFloat('position.x', (Self.width / 2) - (popup.width / 2), 0.2); backGround.HitTest := true; background.Visible := true; backGround.AnimateFloat( 'opacity' , 1 , 0.2 ) } end; constructor TNotificationLayout.create(Owner: TComponent); var locGradient: TGradient; aniInd: TAniIndicator; lbl: TLabel; begin inherited create(Owner); popupStack := TStack<TLayout>.create(); backGround := TRectangle.create(Self); backGround.Visible := false; backGround.Opacity := 0; backGround.Parent := Self; backGround.Align := TAlignLayout.Contents; backGround.Fill.Color := TAlphaColorF.create(0, 0, 0, 0.5).ToAlphaColor; backGround.OnClick := backGroundClick; inThinking := Tpanel.create(Self); inThinking.Parent := Self; inThinking.Visible := false; inThinking.Height := 350; inThinking.width := 350; inThinking.Align := TAlignLayout.Center; aniInd := TAniIndicator.create(inThinking); aniInd.Parent := inThinking; aniInd.Align := TAlignLayout.Top; aniInd.Height := 250; aniInd.Enabled := true; lbl := TLabel.create(inThinking); lbl.Parent := inThinking; lbl.Text := 'Thinking... Please wait.'; lbl.Align := TAlignLayout.client; lbl.TextSettings.HorzAlign := TTextAlign.Center; end; destructor TNotificationLayout.destroy; begin inherited; popupStack.Free; end; procedure ProtectedConfirmDialog._onYesClick(sender: TObject); begin if _edit.Text = protectWord then begin _onYesPress(); TNotificationLayout(Owner).ClosePopup; end; end; procedure ProtectedConfirmDialog._onNoClick(sender: TObject); begin _onNoPress(); TNotificationLayout(Owner).ClosePopup; end; procedure ProtectedConfirmDialog.checkProtect(sender: TObject); begin if _edit.Text = protectWord then begin _onYesClick(sender); end else begin // popupWindow.Create('wrong word'); end; end; constructor ProtectedConfirmDialog.create(Owner: TComponent; Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var panel: Tpanel; begin inherited create(Owner); _onYesPress := Yes; _onNoPress := No; // parent := TfmxObject ( owner ); Self.Height := 350; Self.width := 350; // min( 400 , owner.Width ); Self.protectWord := frmhome.wordlist.Lines[Random(2000)] + ' ' + frmhome.wordlist.Lines[Random(2000)]; // Align := TAlignLayout.None; // position.Y := ( TControl( owner ).Height / 2 ) - ( height / 2); // position.X := - Width; // AnimateFloat('position.x' , ( TControl( owner ).Width / 2 ) - ( width / 2 )); panel := Tpanel.create(Self); panel.Parent := Self; panel.Align := TAlignLayout.Contents; panel.Visible := true; _protectLayout := TLayout.create(panel); _protectLayout.Parent := panel; _protectLayout.Align := TAlignLayout.Bottom; _protectLayout.Height := 48 * 2 + 24; _protectLayout.Visible := true; _staticInfoLabel := TLabel.create(_protectLayout); _staticInfoLabel.Parent := _protectLayout; _staticInfoLabel.Visible := true; _staticInfoLabel.Align := TAlignLayout.Top; _staticInfoLabel.Text := 'Rewrite text to confirm'; _staticInfoLabel.Height := 24; _staticInfoLabel.TextAlign := TTextAlign.Center; _ProtectWordLabel := TLabel.create(_protectLayout); _ProtectWordLabel.Parent := _protectLayout; _ProtectWordLabel.Text := protectWord; _ProtectWordLabel.Align := TAlignLayout.Bottom; _ProtectWordLabel.Height := 48; _ProtectWordLabel.StyledSettings := _ProtectWordLabel.StyledSettings - [TStyledSetting.size]; { adrLabel.StyledSettings := adrLabel.StyledSettings - [TStyledSetting.size]; adrLabel.TextSettings.Font.size := dashBoardFontSize; } _ProtectWordLabel.TextSettings.Font.size := 24; _ProtectWordLabel.TextAlign := TTextAlign.Center; _ProtectWordLabel.Visible := true; _edit := TEdit.create(_protectLayout); _edit.Parent := _protectLayout; _edit.Align := TAlignLayout.MostBottom; _edit.Visible := true; _edit.Height := 48; _edit.TextAlign := TTextAlign.Center; _ImageLayout := TLayout.create(panel); _ImageLayout.Visible := true; _ImageLayout.Align := TAlignLayout.MostTop; _ImageLayout.Parent := panel; _ImageLayout.Height := 96; _Image := TImage.create(_ImageLayout); _Image.Align := TAlignLayout.Center; _Image.width := 64; _Image.Height := 64; _Image.Visible := true; _Image.Parent := _ImageLayout; case icon of 0: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('OK_IMAGE') ); // := frmhome.OKImage.Bitmap; 1: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('INFO_IMAGE') ); // := frmhome.InfoImage.Bitmap; 2: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('WARNING_IMAGE') ); // := frmhome.warningImage.Bitmap; 3: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('ERROR_IMAGE') ); // := frmhome.ErrorImage.Bitmap; end; _lblMessage := TLabel.create(panel); _lblMessage.Align := TAlignLayout.client; _lblMessage.Visible := true; _lblMessage.Parent := panel; _lblMessage.Text := mess; _lblMessage.TextSettings.HorzAlign := TTextAlign.Center; _lblMessage.Margins.Left := 10; _lblMessage.Margins.Right := 10; _ButtonLayout := TLayout.create(panel); _ButtonLayout.Visible := true; _ButtonLayout.Align := TAlignLayout.MostBottom; _ButtonLayout.Parent := panel; _ButtonLayout.Height := 48; _YesButton := TButton.create(_ButtonLayout); _YesButton.Align := TAlignLayout.Right; _YesButton.width := _ButtonLayout.width / 2; _YesButton.Visible := true; _YesButton.Parent := _ButtonLayout; _YesButton.Text := YesText; _YesButton.OnClick := checkProtect; _NoButton := TButton.create(_ButtonLayout); _NoButton.Align := TAlignLayout.Left; _NoButton.width := _ButtonLayout.width / 2; _NoButton.Visible := true; _NoButton.Parent := _ButtonLayout; _NoButton.Text := NoText; _NoButton.OnClick := _onNoClick; _edit.OnKeyUp := OnKeybaordPress; end; procedure ProtectedConfirmDialog.OnKeybaordPress(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then begin checkProtect(nil); end; end; destructor ProtectedConfirmDialog.destroy; begin inherited; end; /// ///////////////////////////////// procedure YesNoDialog._onYesClick(sender: TObject); begin _onYesPress(); TNotificationLayout(Owner).ClosePopup; end; procedure YesNoDialog._onNoClick(sender: TObject); begin _onNoPress(); TNotificationLayout(Owner).ClosePopup; end; constructor YesNoDialog.create(Owner: TComponent; Yes, No: TProc; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var panel: Tpanel; begin inherited create(Owner); _onYesPress := Yes; _onNoPress := No; // parent := TfmxObject ( owner ); Self.Height := 250; Self.width := 350; // min( 400 , owner.Width ); // Align := TAlignLayout.None; // position.Y := ( TControl( owner ).Height / 2 ) - ( height / 2); // position.X := - Width; // AnimateFloat('position.x' , ( TControl( owner ).Width / 2 ) - ( width / 2 )); panel := Tpanel.create(Self); panel.Parent := Self; panel.Align := TAlignLayout.Contents; panel.Visible := true; _ImageLayout := TLayout.create(panel); _ImageLayout.Visible := true; _ImageLayout.Align := TAlignLayout.MostTop; _ImageLayout.Parent := panel; _ImageLayout.Height := 96; _Image := TImage.create(_ImageLayout); _Image.Align := TAlignLayout.Center; _Image.width := 64; _Image.Height := 64; _Image.Visible := true; _Image.Parent := _ImageLayout; case icon of 0: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('OK_IMAGE') ); // := frmhome.OKImage.Bitmap; 1: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('INFO_IMAGE') ); // := frmhome.InfoImage.Bitmap; 2: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('WARNING_IMAGE') ); // := frmhome.warningImage.Bitmap; 3: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('ERROR_IMAGE') ); // := frmhome.ErrorImage.Bitmap; end; _lblMessage := TLabel.create(panel); _lblMessage.Align := TAlignLayout.client; _lblMessage.Visible := true; _lblMessage.Parent := panel; _lblMessage.Text := mess; _lblMessage.TextSettings.HorzAlign := TTextAlign.Center; _lblMessage.Margins.Left := 10; _lblMessage.Margins.Right := 10; _ButtonLayout := TLayout.create(panel); _ButtonLayout.Visible := true; _ButtonLayout.Align := TAlignLayout.MostBottom; _ButtonLayout.Parent := panel; _ButtonLayout.Height := 48; _YesButton := TButton.create(_ButtonLayout); _YesButton.Align := TAlignLayout.Right; _YesButton.width := _ButtonLayout.width / 2; _YesButton.Visible := true; _YesButton.Parent := _ButtonLayout; _YesButton.Text := YesText; _YesButton.OnClick := _onYesClick; _NoButton := TButton.create(_ButtonLayout); _NoButton.Align := TAlignLayout.Left; _NoButton.width := _ButtonLayout.width / 2; _NoButton.Visible := true; _NoButton.Parent := _ButtonLayout; _NoButton.Text := NoText; _NoButton.OnClick := _onNoClick; end; destructor YesNoDialog.destroy; begin inherited; end; /// ////////////////////////////////////////////////////////////////////////////// procedure PasswordDialog._onYesClick(sender: TObject); begin TNotificationLayout(Owner).RunInThinkingWindow( procedure begin _onYesPress(_edit.Text); end); TNotificationLayout(Owner).ClosePopup; end; procedure PasswordDialog._onNoClick(sender: TObject); begin _onNoPress(_edit.Text); TNotificationLayout(Owner).ClosePopup; end; constructor PasswordDialog.create(Owner: TComponent; Yes, No: TProc<AnsiString>; mess: AnsiString; YesText: AnsiString = 'Yes'; NoText: AnsiString = 'No'; icon: integer = 2); var panel: Tpanel; begin inherited create(Owner); _onYesPress := Yes; _onNoPress := No; // parent := TfmxObject ( owner ); Self.Height := 250; Self.width := 350; // min( 400 , owner.Width ); // Align := TAlignLayout.None; // position.Y := ( TControl( owner ).Height / 2 ) - ( height / 2); // position.X := - Width; // AnimateFloat('position.x' , ( TControl( owner ).Width / 2 ) - ( width / 2 )); panel := Tpanel.create(Self); panel.Parent := Self; panel.Align := TAlignLayout.Contents; panel.Visible := true; _protectLayout := TLayout.create(panel); _protectLayout.Parent := panel; _protectLayout.Align := TAlignLayout.Bottom; _protectLayout.Height := 48; _protectLayout.Visible := true; { _staticInfoLabel := TLabel.Create(_protectLayout); _staticInfoLabel.Parent := _protectLayout; _staticInfoLabel.Visible := true; _staticInfoLabel.Align := TAlignLayout.Top; _staticInfoLabel.Text := 'Rewrite text to confirm'; _staticInfoLabel.Height := 24; _staticInfoLabel.TextAlign := TTextAlign.Center; } _edit := TEdit.create(_protectLayout); _edit.Parent := _protectLayout; _edit.Align := TAlignLayout.MostBottom; _edit.Visible := true; _edit.Height := 48; _edit.TextAlign := TTextAlign.Center; _edit.Password := true; _ImageLayout := TLayout.create(panel); _ImageLayout.Visible := true; _ImageLayout.Align := TAlignLayout.MostTop; _ImageLayout.Parent := panel; _ImageLayout.Height := 96; _Image := TImage.create(_ImageLayout); _Image.Align := TAlignLayout.Center; _Image.width := 64; _Image.Height := 64; _Image.Visible := true; _Image.Parent := _ImageLayout; case icon of 0: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('OK_IMAGE') ); // := frmhome.OKImage.Bitmap; 1: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('INFO_IMAGE') ); // := frmhome.InfoImage.Bitmap; 2: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('WARNING_IMAGE') ); // := frmhome.warningImage.Bitmap; 3: _Image.Bitmap.LoadFromStream( resourceMenager.getAssets('ERROR_IMAGE') ); // := frmhome.ErrorImage.Bitmap; end; _lblMessage := TLabel.create(panel); _lblMessage.Align := TAlignLayout.client; _lblMessage.Visible := true; _lblMessage.Parent := panel; _lblMessage.Text := mess; _lblMessage.TextSettings.HorzAlign := TTextAlign.Center; _lblMessage.Margins.Left := 10; _lblMessage.Margins.Right := 10; _ButtonLayout := TLayout.create(panel); _ButtonLayout.Visible := true; _ButtonLayout.Align := TAlignLayout.MostBottom; _ButtonLayout.Parent := panel; _ButtonLayout.Height := 48; _YesButton := TButton.create(_ButtonLayout); _YesButton.Align := TAlignLayout.Right; _YesButton.width := _ButtonLayout.width / 2; _YesButton.Visible := true; _YesButton.Parent := _ButtonLayout; _YesButton.Text := YesText; _YesButton.OnClick := _onYesClick; _NoButton := TButton.create(_ButtonLayout); _NoButton.Align := TAlignLayout.Left; _NoButton.width := _ButtonLayout.width / 2; _NoButton.Visible := true; _NoButton.Parent := _ButtonLayout; _NoButton.Text := NoText; _NoButton.OnClick := _onNoClick; _edit.OnKeyUp := OnkeyBaordPress; end; procedure PasswordDialog.OnKeybaordPress(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then begin _onyesClick(nil); end; end; destructor PasswordDialog.destroy; begin inherited; end; end.
{************************************************************************************************************************** * Classe/Objeto : TFinanceiroPrazosExtratosControl * Finalidade : Módulo controller da classe TFinanceiroPrazosExtratos * Nível : Controller * Autor : Celso Mutti * Data : 01/06/2021 * Versão : 1 * Histórico : 01/06/2021 - Criação - Celso Mutti (1) **************************************************************************************************************************} unit Control.FinanceiroPrazosExtratos; interface uses Model.FinanceiroPrazosExtratos, System.SysUtils, FireDAC.Comp.Client, Common.ENum; type TFinanceiroPrazosExtratosControl = class private FPrazos : TFinanceiroPrazosExtratos; public constructor Create; destructor Destroy; override; function Search(aParam : array of variant) : boolean; // realiza pesquisa em banco de dados function Save() : Boolean; // salva, exclue dados no banco de dados function GetField(sField : String; sKey : String; sKeyValue : String) : String; // localiza e retorna o valor de um campo de uma tabela function MountPeriod(iAno, iMes: integer): boolean; // monta as data do período e a data do pagamento; procedure SetupSelf(fdQuery : TFDQuery); // atribui os valores dos campos de uma query às propriedades da classe procedure ClearSelf(); // limpa as propriedades da dos campos da tabela da classe property Prazos: TFinanceiroPrazosExtratos read FPrazos write FPrazos; end; implementation { TFinanceiroPrazosExtratosControl } procedure TFinanceiroPrazosExtratosControl.ClearSelf; begin FPrazos.ClearSelf; end; constructor TFinanceiroPrazosExtratosControl.Create; begin FPrazos := TFinanceiroPrazosExtratos.Create; end; destructor TFinanceiroPrazosExtratosControl.Destroy; begin FPrazos.Free; inherited; end; function TFinanceiroPrazosExtratosControl.GetField(sField, sKey, sKeyValue: String): String; begin Result := FPRazos.GetField(sField, sKey, sKeyValue); end; function TFinanceiroPrazosExtratosControl.MountPeriod(iAno, iMes: integer): boolean; begin Result := FPrazos.MountPeriod(iAno, iMes); end; function TFinanceiroPrazosExtratosControl.Save: Boolean; begin Result := FPrazos.Save(); end; function TFinanceiroPrazosExtratosControl.Search(aParam: array of variant): boolean; begin Result := FPrazos.Search(aParam); end; procedure TFinanceiroPrazosExtratosControl.SetupSelf(fdQuery: TFDQuery); begin FPrazos.SetupSelf(fdQuery); end; end.
unit App; { Based on Simple_VertexShader.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.Geometry, Sample.App; type TSimpleVSApp = class(TApplication) private FProgram: TGLProgram; FAttrPosition: TGLVertexAttrib; FAttrTexCoord: TGLVertexAttrib; FUniMVPMatrix: TGLUniform; FCube: TCubeGeometry; FRotation: Single; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes; { TSimpleVSApp } procedure TSimpleVSApp.Initialize; var VertexShader, FragmentShader: TGLShader; begin { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'uniform mat4 u_mvpMatrix;'#10+ 'attribute vec4 a_position;'#10+ 'attribute vec2 a_texcoord;'#10+ 'varying vec2 v_texcoord;'#10+ 'void main()'#10+ '{'#10+ ' gl_Position = u_mvpMatrix * a_position;'#10+ ' v_texcoord = a_texcoord;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'varying vec2 v_texcoord;'#10+ 'void main()'#10+ '{'#10+ ' gl_FragColor = vec4(v_texcoord.x, v_texcoord.y, 1.0, 1.0);'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attributes } FAttrPosition.Init(FProgram, 'a_position'); FAttrTexCoord.Init(FProgram, 'a_texcoord'); { Initialize uniform } FUniMVPMatrix.Init(FProgram, 'u_mvpMatrix'); { Generate the geometry data } FCube.Generate(0.5); { Set initial rotation } FRotation := 45; { Set clear color to black } gl.ClearColor(0, 0, 0, 0); { Enable culling of back-facing polygons } gl.CullFace(TGLFace.Back); gl.Enable(TGLCapability.CullFace); end; procedure TSimpleVSApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TSimpleVSApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); var Perspective, Rotate, Translate, Model, MVP: TMatrix4; begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Set the data for the vertex attributes } FAttrPosition.SetData<TVector3>(FCube.Positions); FAttrPosition.Enable; FAttrTexCoord.SetData<TVector2>(FCube.TexCoords); FAttrTexCoord.Enable; { Calculate and set MVP matrix } FRotation := FMod(FRotation + (ADeltaTimeSec * 40), 360); Perspective.InitPerspectiveFovRH(Radians(60), Width / Height, 1, 20); Translate.InitTranslation(0, 0, -2); Rotate.InitRotation(Vector3(1, 0, 1), Radians(FRotation)); Model := Translate * Rotate; MVP := Perspective * Model; FUniMVPMatrix.SetValue(MVP); { Draw the cube } gl.DrawElements(TGLPrimitiveType.Triangles, FCube.Indices); end; procedure TSimpleVSApp.Shutdown; begin { Release resources } FProgram.Delete; end; end.
unit System.uDebug; { manter aqui somente funções e debug.. objetivo } interface {$I delphi.inc} uses {$IFDEF MSWINDOWS} windows, {$ENDIF} {$IFDEF FMX} FMX.Dialogs, FMX.Forms, {$ELSE} VCL.Dialogs, VCL.Forms, {$ENDIF} System.IOUtils, System.Classes, System.Sysutils, System.Rtti; type TDebugOptions = record db_params_in: boolean; db_params_out: boolean; db_params_prepare: boolean; db_params_unprepare: boolean; db_execute: boolean; db_dbparams: boolean; db_transaction: boolean; messages: boolean; end; TActionOnApplicationError = (actErrContinue, actErrHalt, actErrTerminate); procedure DebugLog(ATexto: string; AComando: string = ''; AArquivo: string = ''; nomeRotina: string = ''; AForcar: boolean = false); //procedure WriteLogError(const ATexto: string); // nao usar.. substituir por ErrorLog( procedure ErrorLog(ATexto: string); procedure WriteLog(AArquivo: string; ATexto: string; AComando: string = ''); procedure WriteLogText(AArquivo: string; ATexto: string; revisaArquivoDestino: boolean = True); procedure DoAppExceptionEvent(Sender: TObject; E: Exception; AShow: boolean = True); function DebugOn: boolean; procedure SetDebugOn(ligar: boolean); procedure SuspendDebugOn(susp: boolean); procedure SetDebugFileName(nome: string); function GetDebugFileName(): string; function LogsFilesDir(s: string = ''): string; procedure eCheckTrue(b: boolean; texto: string); var DebugOptions: TDebugOptions; ActionOnApplicationError: TActionOnApplicationError; implementation // Calixto - nao usar o Forms para dll aumenta muito o tamanho uses {$IFDEF MSWINDOWS} DllFunctions, {$ENDIF} System.iniFiles, System.IniFilesEx, SyncObjs, System.Threading; var FNoLog: boolean; FIsDebugActive: boolean = false; LErrorLogPath: String; LogCount: integer = 1; FDebugFileName: string = ''; FLockEscrita, FLockEntrada: TCriticalSection; LEncerrou: boolean; FSuspended: boolean = false; procedure eCheckTrue(b: boolean; texto: string); begin if not b then raise Exception.Create(texto); end; function AppDir: String; begin result := ExtractFilePath(ParamStr(0)); end; function GetTempDir: string; var s: array [0 .. 255] of char; begin {$IFDEF MSWINDOWS} GetTempPath(255, s); result := s; {$ELSE} result := TPath.GetDocumentsPath; {$ENDIF} end; function CurDir: string; begin result := GetCurrentDir; end; function LogsFilesDir(s: string = ''): string; var n: integer; begin if s <> '' then begin n := length(s); if s[n] = '\' then s := copy(s, 1, n - 1); LErrorLogPath := s; try if not DirectoryExists(LErrorLogPath) then mkDir(LErrorLogPath); except LErrorLogPath := GetTempDir; end; end; if LErrorLogPath = '' then begin LErrorLogPath := CurDir + '\Logs'; if pos('system', LErrorLogPath) > 0 then LErrorLogPath := AppDir + '\Logs'; end; result := LErrorLogPath; end; procedure SuspendDebugOn(susp: boolean); begin FSuspended := susp; end; procedure SetDebugFileName(nome: string); begin FDebugFileName := nome; {$IFNDEF BPL} add_LogFileConfig(nome); {$ENDIF} if LErrorLogPath = '' then LErrorLogPath := ExtractFilePath(nome); end; function GetDebugFileName(): string; begin result := FDebugFileName; end; function DebugOn: boolean; begin result := FIsDebugActive; end; procedure SetDebugOn(ligar: boolean); begin FIsDebugActive := ligar; end; {$WARN SYMBOL_DEPRECATED OFF} procedure SlashDir(var ADiretorio: string); var Ld: String; begin if ADiretorio = '' then ADiretorio := PathDelim else if ADiretorio[length(ADiretorio)] <> PathDelim then begin Ld := ADiretorio + PathDelim; ADiretorio := Ld; end; end; {$WARN SYMBOL_DEPRECATED ON} function SlashDirEx(ADiretorio: string): string; begin result := ADiretorio; SlashDir(result); end; function GetNomeArquivoDebug: string; begin result := format('Debug_%s.log', [formatDateTime('ddmmyyyy', date)]); end; procedure WriteLogText(AArquivo: string; ATexto: string; revisaArquivoDestino: boolean = True); var Lf: textfile; Ls: string; begin try FLockEscrita.Acquire; try if LEncerrou then exit; // grava dados de texto no disco.... para usar somente para log usar a função DebugLog if revisaArquivoDestino then begin Ls := formatDateTime('DDMMYYYY', date); // DDMMYYYY(date); AArquivo := StringReplace(AArquivo, Ls, { YYYYMMDD } formatDateTime('YYYYMMDD', date), [rfReplaceAll]); // troca a data para ordem crescente no disco. try Ls := LErrorLogPath; if ExtractFileName(AArquivo) = AArquivo then if Ls[1] <> '\' then AArquivo := SlashDirEx(Ls) + AArquivo; except end; end; try ForceDirectories(ExtractFilePath(AArquivo)); except end; AssignFile(Lf, AArquivo); try {$I-} Append(Lf); {$I+} if IOResult <> 0 then // se o arquivo nao existe, criar um novo; Rewrite(Lf); WriteLn(Lf, ATexto); finally CloseFile(Lf); end; finally FLockEscrita.Release; end; except if GetNomeArquivoDebug <> ExtractFileName(AArquivo) then /// evitar loop ErrorLog('Erro em: ' + AArquivo + ': ' + ATexto); end; end; function LowS(s: string): integer; begin result := low(s); // pega base 0 quando for o caso end; function HighS(s: String): integer; begin result := high(s); end; // Procura a posição de pelo menos um item da lista se esta presente no texto (como POS() - para um lista separado por virgula/ponto-virgula) // Retorno: 0 - não encontrou; maior 0 -> indica a posição onde se inicia; // exemplo: n := PosA( 'windows,system', 'c:\windows\system32'); -> retorna a posição encontrada para a palavra "windows" function PosA(lista: String; texto: string): integer; var i: integer; s: string; begin result := 0; lista := lowercase(lista); texto := lowercase(texto); s := ''; for i := LowS(lista) to HighS(lista) do begin case lista[i] of ',', ';': begin result := pos(s, texto); if result > 0 then exit; s := ''; end; else s := s + lista[i]; end; end; if s <> '' then result := pos(s, texto); end; var LUltimoErro: String; procedure WriteLogError( const ATexto: string); begin if LUltimoErro <> ATexto then begin try WriteLogText('Erros_' + formatDateTime('yyyymmdd', date) + '.log', ExtractFileName(ParamStr(0)) + ' ' + ATexto); OutputDebugString({$IFDEF UNICODE}PWideChar{$ELSE}PAnsiChar{$ENDIF}(ExtractFileName(ParamStr(0)) + ':' + ATexto)); except end; LUltimoErro := ATexto; end; end; procedure WriteLog(AArquivo: string; ATexto: string; AComando: string = ''); var ArqVazio: boolean; begin FLockEntrada.Acquire; try if LEncerrou then exit; // if FNoLog then exit; ArqVazio := false; if AArquivo = '' then begin ArqVazio := True; AArquivo := ExtractFileName(ParamStr(0)); AArquivo := copy(AArquivo, 1, pos('.', AArquivo) - 1) + '_' + formatDateTime('yyyymmdd', date) + '.log'; end; if LErrorLogPath = '' then begin { DONE -oAL -cImportante : Quando Utiliza Serviços, o diretorio CURDIR padrão é o c:\windows\system32. Para caso de serviços, indicar o diretório de LOG ao entrar no aplicativo. } LErrorLogPath := CurDir + '\logs'; if PosA('windows,system', LErrorLogPath) > 0 then LErrorLogPath := ExtractFilePath(ParamStr(0)) + 'Logs'; end; if ExtractFileName(AArquivo) = AArquivo then AArquivo := LErrorLogPath + '\' + AArquivo; // controle em diretorio diferente os arquivos de logs if AComando = '' then AComando := 'Vendor : Logs'; AComando := ' ' + AComando; if ((ArqVazio) and (pos('ERRO', ATexto) > 0)) then WriteLogError(ATexto) else try WriteLogText(AArquivo, copy(intToStr(LogCount) + ' ', 1, 8) + formatDateTime('hh:nn:ss.zzz', Now) + AComando + ' - ' + ATexto); {$IFDEF MSWINDOWS} if DebugOn and (not FNoLog) then OutputDebugString({$IFDEF UNICODE}PWideChar{$ELSE}PAnsiChar{$ENDIF}(ExtractFileName(ParamStr(0)) + ':' + ATexto)); InterlockedIncrement(LogCount); {$ELSE} inc(LogCount); {$ENDIF} except end; finally FLockEntrada.Release end; end; procedure ErrorLog(ATexto: string); begin FLockEntrada.Acquire; try WriteLogError(copy(intToStr(LogCount) + ' ', 1, 8) + formatDateTime('hh:nn:ss.zzz', Now) + ' Error - ' + ATexto + #13#10 + '--------------------------'); finally FLockEntrada.Release; end; end; procedure DebugLog(ATexto: string; AComando: string = ''; AArquivo: string = ''; nomeRotina: string = ''; AForcar: boolean = false); begin // so grava quando estiver com DEBUG.ON ativo if LEncerrou then exit; if (not FIsDebugActive) or (FSuspended) then begin exit; end; if AComando = '' then AComando := 'FD'; AComando := AComando + ' : Logs'; if AArquivo = '' then AArquivo := FDebugFileName; if AArquivo = '' then AArquivo := GetNomeArquivoDebug; if not AForcar then if DebugOptions.db_params_out = false then begin if (pos('Data Out', ATexto) > 0) or (pos('_fetch', ATexto) > 0) then exit; end; if nomeRotina <> '' then TThread.NameThreadForDebugging(nomeRotina); WriteLog(AArquivo, ATexto, AComando); end; function GetRTTILog(snd: TObject; LNivel: integer): string; var LNome: string; LContext: TRttiContext; LType: TRttiType; LProp: TRttiProperty; LVar: TValue; txt: String; LNivelLocal: integer; begin dec(LNivel); if LNivel < 0 then exit; if not assigned(snd) then begin result :='';// 'ClassName: NIL'; exit; end; LContext := TRttiContext.Create; try LType := LContext.GetType(snd.ClassType); result := 'ClassName: ' + LType.QualifiedName+ #13#10; for LProp in LType.GetProperties do begin try LVar := LProp.GetValue(snd); txt := LVar.AsString; if txt <> '' then result := result + LProp.Name + ': ' + txt + #13#10; if LVar.IsObject then begin txt := GetRTTILog(LVar.AsObject, LNivel); if txt<>'' then result := result + #13#10 + txt; end; except end; end; finally LContext.Free; end; end; procedure DoAppExceptionEvent(Sender: TObject; E: Exception; AShow: boolean = True); var s: string; sbase: string; begin TThread.Synchronize(nil, procedure begin try try sbase := E.Message; try s := ''; if assigned(Sender) then begin s := GetRTTILog(Sender, 2); end; s := s + ' Message: ' + E.Message; s := s+#13#10+'---StackTrace----'#13#10+ e.StackTrace; if ActionOnApplicationError = actErrHalt then s := s+ #13#10+'Halt'; if ActionOnApplicationError = actErrTerminate then s := s+ #13#10+'Terminate'; ErrorLog(s); except on ee: Exception do ErrorLog(ee.Message); end; {$IFNDEF SERVICO} if AShow then begin Application.ShowException(E); end; {$ENDIF} finally if ActionOnApplicationError = actErrHalt then halt(0); if ActionOnApplicationError = actErrTerminate then Application.Terminate; end; except end; end); end; var LDebugOn: string; LAppName: string; LApagarArquivo: boolean; initialization ActionOnApplicationError := actErrContinue; FLockEscrita := TCriticalSection.Create; FLockEntrada := TCriticalSection.Create; LDebugOn := ExtractFilePath(ParamStr(0)) + 'debug.on'; FIsDebugActive := FileExists(LDebugOn) or FindCmdLineSwitch('D', ['-', '\', '/'], True); FNoLog := FindCmdLineSwitch('-D', ['-', '\', '/'], True); LEncerrou := false; {$IFDEF MSWINDOWS} System.ReportMemoryLeaksOnShutdown := isDelphiRunning and FIsDebugActive; System.NeverSleepOnMMThreadContention := True; {$ENDIF} FDebugFileName := lowercase(GetCurrentDir); if PosA('system,window', FDebugFileName) > 0 then FDebugFileName := ExtractFileDir(ParamStr(0)); // FDebugFileName := FDebugFileName + '\logs\Debug_' + formatDateTime('yyyymmdd', date) + '.log'; LAppName := ExtractFileName(ParamStr(0)); LAppName := ChangeFileExt(LAppName, ''); FDebugFileName := FDebugFileName + '\logs\' + LAppName + '_Debug_' + formatDateTime('yyyymmdd', date) + '.log'; LogsFilesDir(ExtractFilePath(FDebugFileName)); {$IFNDEF BPL} add_LogFileConfig(FDebugFileName); LApagarArquivo := not FileExists('debug.on'); {$ENDIF} if FIsDebugActive then begin with TIniFile.Create(LDebugOn) do try if SectionExists('Options') = false then begin WriteBool('Options', 'Active', True); WriteBool('Database', 'ParamsIN', True); WriteBool('Database', 'ParamsOUT', false); WriteBool('Database', 'Prepare', True); WriteBool('Database', 'Unprepare', True); WriteBool('Database', 'Execute', True); WriteBool('Database', 'DbParams', false); WriteBool('Database', 'Transaction', false); WriteBool('Options', 'Messages', false); end; DebugOptions.db_params_in := readBool('Database', 'ParamsIN', True); DebugOptions.db_params_out := readBool('Database', 'ParamsOUT', false); DebugOptions.db_params_prepare := readBool('Database', 'Prepare', True); DebugOptions.db_params_unprepare := readBool('Database', 'Unprepare', True); DebugOptions.db_execute := readBool('Database', 'Execute', True); DebugOptions.db_dbparams := readBool('Database', 'DbParams', false); DebugOptions.db_transaction := readBool('Database', 'Transaction', false); DebugOptions.messages := readBool('Database', 'messages', false); FIsDebugActive := readBool('Options', 'Active', false); if FIsDebugActive then begin DebugLog('Debug Ligado. (' + FDebugFileName + ') App: ' + ParamStr(0)); DebugLog('-----------------------------------------------------'); end; finally Free; end; end; Finalization LEncerrou := True; FLockEscrita.Free; FLockEntrada.Free; if LApagarArquivo then deletefile('debug.on'); end.
unit GenericReporter; interface uses News, Classes, Collection, SysUtils, Windows; type IContext = interface function SolveIdentifier( Id : string ) : string; end; type TDefinition = class public constructor Create( filename : string ); destructor Destroy; override; private fRules : TCollection; public function Evaluate( Context : IContext ) : single; end; TGenericReporter = class( TMetaReporter, IContext ) public constructor Create( aName, filename : string; aLog : ILog ); override; destructor Destroy; override; private fDefinition : TDefinition; protected function StoryStrength( aNewspaper : TNewspaper ) : integer; override; // IContext private fNewspaper : TNewspaper; private function SolveIdentifier( Id : string ) : string; // IUknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; end; type EExpressionError = class( Exception ) public constructor Create( const Msg : string; pos : integer ); private fPos : integer; public property Position : integer read fPos; end; ERuleError = class( Exception ); procedure RegisterReporters; implementation uses CompStringsParser; // EExpressionError constructor EExpressionError.Create( const Msg : string; pos : integer ); begin inherited Create( Msg ); fPos := pos; end; type TSymbol = class private fPos : integer; public property Position : integer read fPos; end; // Identifiers type CIdentifier = class of TIdentifier; TIdentifier = class( TSymbol ) end; TVariable = class( TIdentifier ) public constructor Create( anId : string ); private fId : string; public property Id : string read fId; public function Evaluate( Context : IContext ) : string; end; constructor TVariable.Create( anId : string ); begin inherited Create; fId := uppercase(anId); end; function TVariable.Evaluate( Context : IContext ) : string; begin result := Context.SolveIdentifier( fId ); end; type TNumericConstant = class( TIdentifier ) public constructor Create( aValue : single ); private fValue : single; public property Value : single read fValue; end; constructor TNumericConstant.Create( aValue : single ); begin inherited Create; fValue := aValue; end; type TStringConstant = class( TIdentifier ) public constructor Create( aValue : string ); private fValue : string; public property Value : string read fValue; end; constructor TStringConstant.Create( aValue : string ); begin inherited Create; fValue := aValue; if fValue <> '' then begin if fValue[1] = '''' then delete( fValue, 1, 1 ); if fValue[length(fValue)] = '''' then delete( fValue, length(fValue), 1 ); end; end; type TBooleanConstant = class( TIdentifier ) public constructor Create( aValue : boolean ); private fValue : boolean; public property Value : boolean read fValue; end; constructor TBooleanConstant.Create( aValue : boolean ); begin inherited Create; fValue := aValue; end; function GetRealValOfIdentifier( Identifier : TIdentifier; Context : IContext ) : single; var tmpIdentifier : TStringConstant; begin if Identifier is TNumericConstant then result := TNumericConstant(Identifier).Value else if Identifier is TBooleanConstant then result := ord(TBooleanConstant(Identifier).Value) else if Identifier is TVariable then if TVariable(Identifier).Id = 'RND' then result := random else begin tmpIdentifier := TStringConstant.Create( TVariable(Identifier).Evaluate( Context ) ); try result := GetRealValOfIdentifier( tmpIdentifier, Context ); finally tmpIdentifier.Free; end; end else if Identifier is TStringConstant then try result := StrToFloat( TStringConstant(Identifier).Value ); except raise EExpressionError.Create( 'Numeric value expected', Identifier.Position ); end else result := 0; end; function GetStringValOfIdentifier( Identifier : TIdentifier; Context : IContext ) : string; begin if Identifier is TStringConstant then result := TStringConstant(Identifier).Value else if Identifier is TVariable then result := TVariable(Identifier).Evaluate( Context ) else if Identifier is TNumericConstant then result := FloatToStr(TNumericConstant(Identifier).Value) else if Identifier is TBooleanConstant then if TBooleanConstant(Identifier).Value then result := 'TRUE' else result := 'FALSE' else result := ''; end; function GetBooleanValOfIdentifier( Identifier : TIdentifier; Context : IContext ) : boolean; var tmpIdentifier : TNumericConstant; begin if Identifier is TBooleanConstant then result := TBooleanConstant(Identifier).Value else if Identifier is TNumericConstant then result := TNumericConstant(Identifier).Value <> 0 else if Identifier is TVariable then if TVariable(Identifier).Id = 'TRUE' then result := true else if TVariable(Identifier).Id = 'FALSE' then result := false else try tmpIdentifier := TNumericConstant.Create( StrToFloat( TVariable(Identifier).Evaluate( Context ))); try result := GetBooleanValOfIdentifier( tmpIdentifier, Context ); finally tmpIdentifier.Free; end except result := false; end else result := false; end; // Operators type COperator = class of TOperator; TOperator = class( TSymbol ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; virtual; abstract; end; type TNumericOperator = class( TOperator ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; override; protected function CombineRealValues( valA, valB : single ) : single; virtual; abstract; end; function TNumericOperator.Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; var valA : single; valB : single; opResult : single; begin valA := GetRealValOfIdentifier( IdentifierA, Context ); valB := GetRealValOfIdentifier( IdentifierB, Context ); opResult := CombineRealValues( valA, valB ); result := TNumericConstant.Create( opResult ); result.fPos := Position; end; type TAditionOperator = class( TNumericOperator ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; override; protected function CombineRealValues( valA, valB : single ) : single; override; end; function TAditionOperator.Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; var valA : string; valB : string; begin try result := inherited Combine( IdentifierA, IdentifierB, Context ); result.fPos := Position; except valA := GetStringValOfIdentifier( IdentifierA, Context ); valB := GetStringValOfIdentifier( IdentifierB, Context ); result := TStringConstant.Create( valA + valB ); result.fPos := Position; end; end; function TAditionOperator.CombineRealValues( valA, valB : single ) : single; begin result := valA + valB end; type TSubstractionOperator = class( TNumericOperator ) protected function CombineRealValues( valA, valB : single ) : single; override; end; function TSubstractionOperator.CombineRealValues( valA, valB : single ) : single; begin result := valA - valB; end; type TMultOperator = class( TNumericOperator ) protected function CombineRealValues( valA, valB : single ) : single; override; end; function TMultOperator.CombineRealValues( valA, valB : single ) : single; begin result := valA*valB; end; type TDivOperator = class( TNumericOperator ) protected function CombineRealValues( valA, valB : single ) : single; override; end; function TDivOperator.CombineRealValues( valA, valB : single ) : single; begin if valB <> 0 then result := valA/valB else result := 0; end; type TComparisonOperator = class( TOperator ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; override; protected function CombineRealValues ( valA, valB : single ) : boolean; virtual; abstract; function CombineStringValues( valA, valB : string ) : boolean; virtual; abstract; end; function TComparisonOperator.Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; var realA, realB : single; strA, strB : string; opResult : boolean; begin if (IdentifierA is TStringConstant) or (IdentifierB is TStringConstant) then begin strA := GetStringValOfIdentifier( IdentifierA, Context ); strB := GetStringValOfIdentifier( IdentifierB, Context ); opResult := CombineStringValues( strA, strB ); end else begin realA := GetRealValOfIdentifier( IdentifierA, Context ); realB := GetRealValOfIdentifier( IdentifierB, Context ); opResult := CombineRealValues( realA, realB ); end; result := TBooleanConstant.Create( opResult ); result.fPos := Position; end; type TEqualOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TEqualOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA = valB end; function TEqualOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA = valB end; type TNotEqualOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TNotEqualOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA <> valB end; function TNotEqualOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA <> valB end; type TGreaterOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TGreaterOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA > valB end; function TGreaterOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA > valB end; type TGreaterEqualOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TGreaterEqualOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA >= valB end; function TGreaterEqualOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA >= valB end; type TLesserOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TLesserOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA < valB end; function TLesserOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA < valB end; type TLesserEqualOperator = class( TComparisonOperator ) protected function CombineRealValues ( valA, valB : single ) : boolean; override; function CombineStringValues( valA, valB : string ) : boolean; override; end; function TLesserEqualOperator.CombineRealValues( valA, valB : single ) : boolean; begin result := valA <= valB end; function TLesserEqualOperator.CombineStringValues( valA, valB : string ) : boolean; begin result := valA <= valB end; type TBooleanOperator = class( TOperator ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; override; protected function CombineBooleanValues( valA, valB : boolean ) : boolean; virtual; abstract; end; function TBooleanOperator.Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; var valA : boolean; valB : boolean; opResult : boolean; begin valA := GetBooleanValOfIdentifier( IdentifierA, Context ); valB := GetBooleanValOfIdentifier( IdentifierB, Context ); opResult := CombineBooleanValues( valA, valB ); result := TBooleanConstant.Create( opResult ); result.fPos := Position; end; type TBoolOrOperator = class( TBooleanOperator ) protected function CombineBooleanValues( valA, valB : boolean ) : boolean; override; end; function TBoolOrOperator.CombineBooleanValues( valA, valB : boolean ) : boolean; begin result := valA or valB; end; type TBoolAndOperator = class( TBooleanOperator ) protected function CombineBooleanValues( valA, valB : boolean ) : boolean; override; end; function TBoolAndOperator.CombineBooleanValues( valA, valB : boolean ) : boolean; begin result := valA and valB; end; const RuleUndefined = -1; type TRuleOperator = class( TOperator ) public function Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; override; end; function TRuleOperator.Combine( IdentifierA, IdentifierB : TIdentifier; Context : IContext ) : TIdentifier; var condition : boolean; value : single; opResult : single; begin condition := GetBooleanValOfIdentifier( IdentifierA, Context ); value := GetRealValOfIdentifier( IdentifierB, Context ); if condition then opResult := value else opResult := RuleUndefined; result := TNumericConstant.Create( opResult ); result.fPos := Position; end; var OperatorTypes : TStringList = nil; procedure InitOperatorTypes; begin OperatorTypes := TStringList.Create; with OperatorTypes do begin AddObject( '+', TObject(TAditionOperator) ); AddObject( '-', TObject(TSubstractionOperator) ); AddObject( '*', TObject(TMultOperator) ); AddObject( '/', TObject(TDivOperator) ); AddObject( '=', TObject(TEqualOperator) ); AddObject( '<>', TObject(TNotEqualOperator) ); AddObject( '>', TObject(TGreaterOperator) ); AddObject( '>=', TObject(TGreaterEqualOperator) ); AddObject( '<', TObject(TLesserOperator) ); AddObject( '<=', TObject(TLesserEqualOperator) ); AddObject( '|', TObject(TBoolOrOperator) ); AddObject( '&', TObject(TBoolAndOperator) ); AddObject( ':', TObject(TRuleOperator) ); end; end; procedure DoneOperatorTypes; begin OperatorTypes.Free; end; function GetOperatorType( token : string ) : COperator; var idx : integer; begin idx := OperatorTypes.IndexOf( token ); if idx <> NoIndex then result := COperator(OperatorTypes.Objects[idx]) else result := nil; end; // Operation type TOperation = class public constructor Create( expression : string ); destructor Destroy; override; private fItems : TCollection; public function Evaluate( Context : IContext ) : TIdentifier; private class function CreateIdentifier( token : string; pos : integer ) : TIdentifier; class function CreateOperator( token : string; pos : integer ) : TOperator; end; constructor TOperation.Create( expression : string ); function GetSubExpression( expression : string; var pos : integer ) : string; var parcount : integer; begin parcount := 0; result := ''; repeat case expression[pos] of '(' : inc( parcount ); ')' : dec( parcount ); end; result := result + expression[pos]; inc( pos ); until (parcount = 0) or (pos > length(expression)); if (result[1] = '(') and (result[length(result)] = ')') and (parcount = 0) then result := copy( result, 2, length(result) - 2 ) else raise EExpressionError.Create( 'Error in parethesis', pos ); end; procedure RenderToPolish( expression : string; Items : TCollection ); type TParsingState = (stSeekLeftIdentifier, stSeekOperator, stSeekRightIdentifier); const BlankChars = [' ', #9, #10, #13]; Operators = ['+', '-', '*', '/', '&', '|', '=', ':', '<', '>']; var p : integer; state : TParsingState; token : string; Left : TIdentifier; Right : TIdentifier; Op : TOperator; begin state := stSeekLeftIdentifier; p := 1; Op := nil; while (p <= length(expression)) and (expression[p] in BlankChars) do inc( p ); while p <= length(expression) do begin case state of stSeekLeftIdentifier, stSeekRightIdentifier : begin case expression[p] of '(' : begin token := GetSubExpression( expression, p ); RenderToPolish( token, Items ); if state = stSeekRightIdentifier then Items.Insert( Op ); end; '+', '*', '/', '&', '|', ':' : raise EExpressionError.Create( 'Identifier expected', p ); else begin if expression[p] = '''' then begin token := '''' + GetNextString( expression, p, [''''] ) + ''''; inc( p ); end else token := GetNextString( expression, p, BlankChars + Operators ); if state = stSeekLeftIdentifier then begin Left := CreateIdentifier( token, p ); Items.Insert( Left ); end else begin Right := CreateIdentifier( token, p ); Items.Insert( Right ); Items.Insert( Op ); end; end end; state := stSeekOperator; end; stSeekOperator : if expression[p] in Operators then begin token := ''; while (expression[p] in Operators) and (p <= length(expression)) do begin token := token + expression[p]; inc( p ); end; Op := CreateOperator( token, p ); state := stSeekRightIdentifier; end else raise EExpressionError.Create( 'Operator expected', p ); end; while (p <= length(expression)) and (expression[p] in BlankChars) do inc( p ); end; end; begin inherited Create; fItems := TCollection.Create( 0, rkBelonguer ); RenderToPolish( expression, fItems ); end; destructor TOperation.Destroy; begin fItems.Free; inherited; end; function TOperation.Evaluate( Context : IContext ) : TIdentifier; var EvaluationStack : TCollection; Left, Right, Res : TIdentifier; i, j : integer; begin EvaluationStack := TCollection.Create( 0, rkUse ); try EvaluationStack.InsertColl( fItems ); i := 0; repeat if EvaluationStack[i] is TOperator then begin Left := TIdentifier(EvaluationStack[i - 2]); Right := TIdentifier(EvaluationStack[i - 1]); Res := TOperator(EvaluationStack[i]).Combine( Left, Right, Context ); for j := 0 to 2 do begin if fItems.IndexOf( EvaluationStack[i - 2] ) = NoIndex then EvaluationStack[i - 2].Free; EvaluationStack.AtDelete( i - 2 ); end; EvaluationStack.AtInsert( i - 2, Res ); i := i - 1; end else inc( i ); until EvaluationStack.Count = 1; result := TIdentifier(EvaluationStack[0]); finally EvaluationStack.Free; end; end; class function TOperation.CreateIdentifier( token : string; pos : integer ) : TIdentifier; function IsNumeric( token : string ) : boolean; const NumChars = ['-', '0'..'9', '.']; var i : integer; begin result := true; i := 1; while (i <= length(token)) and result do begin result := token[i] in NumChars; inc( i ); end; end; begin if token[1] = '''' then result := TStringConstant.Create( token ) else try if IsNumeric( token ) // to avoid annoying exception then result := TNumericConstant.Create( StrToFloat(token) ) else result := TVariable.Create( token ); except result := TVariable.Create( token ); end; result.fPos := pos; end; class function TOperation.CreateOperator( token : string; pos : integer ) : TOperator; var OperatorType : COperator; begin OperatorType := GetOperatorType( token ); if OperatorType <> nil then begin result := OperatorType.Create; result.fPos := pos; end else raise EExpressionError.Create( 'Unknown operator "' + token + '"', pos ); end; // Rule type TRule = class public constructor Create( expression : string; pos : integer ); private fBody : TOperation; fPos : integer; public property Position : integer read fPos; public function Evaluate( Context : IContext ) : single; end; constructor TRule.Create( expression : string; pos : integer ); begin inherited Create; fPos := pos; try fBody := TOperation.Create( expression ); except on E : EExpressionError do raise ERuleError.Create( E.Message + ' (' + IntToStr(Position) + ',' + IntToStr(E.Position) + ')' ); on E : Exception do raise ERuleError.Create( 'Unknown error.' ); end; end; function TRule.Evaluate( Context : IContext ) : single; var opResult : TIdentifier; begin try opResult := fBody.Evaluate( Context ); if opResult is TNumericConstant then result := TNumericConstant(opResult).Value else raise ERuleError.Create( 'Rule must evaluate to numeric value (line ' + IntToStr(Position) + ')' ); except on E : EExpressionError do raise ERuleError.Create( E.Message + ' (line ' + IntToStr(Position) + ', char ' + IntToStr(E.Position) + ')' ); on E : Exception do raise ERuleError.Create( 'Unknown error ' + ' (line ' + IntToStr(Position) + ')' ); end; end; // Definition constructor TDefinition.Create( filename : string ); var Lines : TStringList; i : integer; Rule : TRule; begin inherited Create; Lines := TStringList.Create; try Lines.LoadFromFile( filename ); fRules := TCollection.Create( 0, rkBelonguer ); for i := 0 to pred(Lines.Count) do begin Rule := TRule.Create( Lines[i], i + 1 ); fRules.Insert( Rule ); end; finally Lines.Free; end; end; destructor TDefinition.Destroy; begin fRules.Free; inherited; end; function TDefinition.Evaluate( Context : IContext ) : single; var i : integer; begin i := 0; repeat result := TRule(fRules[i]).Evaluate( Context ); inc( i ); until (i = fRules.Count) or (result <> RuleUndefined); if result = RuleUndefined then result := 0; end; // Generic Reporter constructor TGenericReporter.Create( aName, filename : string; aLog : ILog ); begin inherited; try fDefinition := TDefinition.Create( filename + 'reporter.def' ); except on E : Exception do Log.LogThis( ' (' + name + ') ' + E.Message ); end; end; destructor TGenericReporter.Destroy; begin fDefinition.Free; inherited; end; function TGenericReporter.StoryStrength( aNewspaper : TNewspaper ) : integer; begin fNewspaper := aNewspaper; try if fDefinition <> nil then result := round(fDefinition.Evaluate( self )) else result := 0; except on E : Exception do begin Log.LogThis( ' (' + name + ') ' + E.Message ); result := 0; end end; end; function TGenericReporter.SolveIdentifier( Id : string ) : string; begin result := SolveSymbol( Id, '0', fNewspaper ); end; function TGenericReporter.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TGenericReporter._AddRef : integer; stdcall; begin result := 1; end; function TGenericReporter._Release : integer; stdcall; begin result := 1; end; // RegisterReporters procedure RegisterReporters; begin RegisterMetaReporterType( 'Auto', TGenericReporter ); end; initialization InitOperatorTypes; finalization DoneOperatorTypes; end.
unit uRichEditor; interface uses uEditorBase, Classes, SysUtils, StdCtrls, Controls, Graphics, Dialogs, ComCtrls; type TRichEditor = class(TEditorBase) private FRichEditor: TRichEdit; function GetWordCount: Integer; protected procedure DoLoadFromFile(FileName: string); function DoSaveFile(FileName: string): Boolean; function GetText: string; override; public constructor Create(ParentComponent: TComponent); destructor Destroy; override; function GetWordWarp: Boolean; // 是否分行 procedure SetWordWarp(WordWarp: Boolean); // 判断是否需要保存,通过当前编辑器的状态来判断 // 如果编辑其状态处于编辑状态,那么就需要保存,否则就处于已保存状态。 function GetSaved: Boolean; function CanUndo: Boolean; procedure Undo; function CanRedo: Boolean; procedure Redo; function CanCopy: Boolean; procedure Copy; function CanCut: Boolean; procedure Cut; function CanPaster: Boolean; procedure Paster; function CanDeleteSelection: Boolean; procedure DelectSelection; procedure SetFont(Font: TFont); function FindNext(Text: String; Option: TFindOptions): Boolean; function Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; // 获得Memo中选中的文本 function GetSelectText: String; end; implementation { TRichEditor } function TRichEditor.CanCopy: Boolean; begin end; function TRichEditor.CanCut: Boolean; begin end; function TRichEditor.CanDeleteSelection: Boolean; begin end; function TRichEditor.CanPaster: Boolean; begin end; function TRichEditor.CanRedo: Boolean; begin end; function TRichEditor.CanUndo: Boolean; begin end; procedure TRichEditor.Copy; begin end; constructor TRichEditor.Create(ParentComponent: TComponent); begin end; procedure TRichEditor.Cut; begin end; procedure TRichEditor.DelectSelection; begin end; destructor TRichEditor.Destroy; begin inherited; end; procedure TRichEditor.DoLoadFromFile(FileName: string); begin end; function TRichEditor.DoSaveFile(FileName: string): Boolean; begin end; function TRichEditor.FindNext(Text: String; Option: TFindOptions): Boolean; begin end; function TRichEditor.GetSaved: Boolean; begin end; function TRichEditor.GetSelectText: String; begin end; function TRichEditor.GetText: string; begin end; function TRichEditor.GetWordCount: Integer; begin end; function TRichEditor.GetWordWarp: Boolean; begin end; procedure TRichEditor.Paster; begin end; procedure TRichEditor.Redo; begin end; function TRichEditor.Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; begin end; procedure TRichEditor.SetFont(Font: TFont); begin end; procedure TRichEditor.SetWordWarp(WordWarp: Boolean); begin end; procedure TRichEditor.Undo; begin end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clDownLoader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clDCUtils, clUtils, clSingleDC, clMultiDC, clMultiDownLoader; type TclOnSingleDataTextProceed = procedure (Sender: TObject; Text: TStrings) of object; TclDownLoader = class; TclSingleDownLoadItem = class(TclDownLoadItem) private function GetDownLoader: TclDownLoader; protected procedure DoDataTextProceed(Text: TStrings); override; function GetCorrectResourceTime: Boolean; override; function GetPreviewCharCount: Integer; override; function GetLocalFolder: string; override; function GetControl: TclCustomInternetControl; override; end; TclDownLoader = class(TclSingleInternetControl) private FLocalFolder: string; FOnDataTextProceed: TclOnSingleDataTextProceed; FCorrectResourceTime: Boolean; FPreviewCharCount: Integer; procedure SetLocalFolder(const Value: string); function GetPreview: TStrings; procedure SetPreviewCharCount(const Value: Integer); function GetDownloadItem(): TclSingleDownLoadItem; function GetAllowCompression: Boolean; procedure SetAllowCompression(const Value: Boolean); protected function GetInternetItemClass(): TclInternetItemClass; override; procedure DoDataTextProceed(Text: TStrings); dynamic; public constructor Create(AOwner: TComponent); override; property Preview: TStrings read GetPreview; published property LocalFolder: string read FLocalFolder write SetLocalFolder; property PreviewCharCount: Integer read FPreviewCharCount write SetPreviewCharCount default DefaultPreviewCharCount; property CorrectResourceTime: Boolean read FCorrectResourceTime write FCorrectResourceTime default True; property AllowCompression: Boolean read GetAllowCompression write SetAllowCompression default True; property OnDataTextProceed: TclOnSingleDataTextProceed read FOnDataTextProceed write FOnDataTextProceed; end; implementation { TclDownLoader } constructor TclDownLoader.Create(AOwner: TComponent); begin inherited Create(AOwner); FPreviewCharCount := DefaultPreviewCharCount; FCorrectResourceTime := True; end; procedure TclDownLoader.DoDataTextProceed(Text: TStrings); begin if Assigned(FOnDataTextProceed) then begin FOnDataTextProceed(Self, Text); end; end; function TclDownLoader.GetAllowCompression: Boolean; begin Result := GetDownloadItem().AllowCompression; end; function TclDownLoader.GetDownloadItem(): TclSingleDownLoadItem; begin Result := (GetInternetItem() as TclSingleDownLoadItem); end; function TclDownLoader.GetInternetItemClass(): TclInternetItemClass; begin Result := TclSingleDownLoadItem; end; function TclDownLoader.GetPreview(): TStrings; begin Result := GetDownloadItem().Preview; end; procedure TclDownLoader.SetAllowCompression(const Value: Boolean); begin GetDownloadItem().AllowCompression := Value; end; procedure TclDownLoader.SetLocalFolder(const Value: string); begin if (FLocalFolder = Value) then Exit; FLocalFolder := Value; if (csLoading in ComponentState) then Exit; LocalFile := GetFullFileName(LocalFile, FLocalFolder); Changed(GetInternetItem()); end; procedure TclDownLoader.SetPreviewCharCount(const Value: Integer); begin if (FPreviewCharCount <> Value) and (Value > - 1) then begin FPreviewCharCount := Value; end; end; { TclSingleDownLoadItem } procedure TclSingleDownLoadItem.DoDataTextProceed(Text: TStrings); begin GetDownLoader().DoDataTextProceed(Text); end; type TCollectionAccess = class(TCollection); function TclSingleDownLoadItem.GetControl: TclCustomInternetControl; begin Result := (TCollectionAccess(Collection).GetOwner() as TclCustomInternetControl); end; function TclSingleDownLoadItem.GetCorrectResourceTime: Boolean; begin Result := GetDownLoader().CorrectResourceTime; end; function TclSingleDownLoadItem.GetDownLoader: TclDownLoader; begin Result := (Control as TclDownLoader); end; function TclSingleDownLoadItem.GetLocalFolder: string; begin Result := GetDownloader().LocalFolder; end; function TclSingleDownLoadItem.GetPreviewCharCount: Integer; begin Result := GetDownloader().PreviewCharCount; end; end.
{ Subroutine SST_R_SYO_DOIT (FNAM, GNAM, STAT) * * Process one top level SYN language input file. FNAM is the input file * name. GNAM is returned as the generic name of FNAM. } module sst_r_syo_doit; define sst_r_syo_doit; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_doit ( {do SYN language front end phase} in fnam: univ string_var_arg_t; {raw input file name} in out gnam: univ string_var_arg_t; {returned as generic name of input file} out stat: sys_err_t); {completion status code} var mflag: syo_mflag_k_t; {syntax matched yes/no flag} eflag: syo_mflag_k_t; {scratch flag for error re-parse} hpos: string_hash_pos_t; {position handle into our hash table} found: boolean; {TRUE when hash table entry found} name_p: string_var_p_t; {pointer to name in hash table entry} data_p: symbol_data_p_t; {pointer to our data in hash table entry} undefined_syms: boolean; {TRUE if undefined symbols found} unused_syms: boolean; {TRUE after first unused symbol encountered} label loop_cmd, eod; { *********************************************************** * * Local subroutine FOLLOW_SYM (DATA) * * Propagate USED flag to all symbols ultimately referenced by this symbol. } procedure follow_sym ( in data: symbol_data_t); {data about symbol to follow} val_param; var call_p: call_p_t; {points to data about called symbol} begin data.sym_p^.flags := {set FOLLOWED flag to prevent recursive calls} data.sym_p^.flags + [sst_symflag_followed_k]; call_p := data.call_p; {init to first entry in called chain} while call_p <> nil do begin {once for each entry in called chain} call_p^.data_p^.sym_p^.flags := {set USED flag} call_p^.data_p^.sym_p^.flags + [sst_symflag_used_k]; if not (sst_symflag_followed_k in call_p^.data_p^.sym_p^.flags) then begin follow_sym (call_p^.data_p^); {follow this nested symbol} end; call_p := call_p^.next_p; {advance to next called symbol in list} end; end; { *********************************************************** * * Start of main routine. } begin string_generic_fnam (fnam, '.syo', gnam); {make generic input file name} string_copy (gnam, prefix); {use generic name as subroutine prefix} syo_infile_top_set (fnam, '.syo'); {set name of top level input file} string_hash_create ( {create hash table for SYN file symbols} table_sym, {hash table to initialize} 64, {number of buckets in hash table} 32, {max length of any entry name} sizeof(symbol_data_t), {amount of user data per entry} [string_hashcre_nodel_k], {won't need to deallocate individual entries} sst_scope_root_p^.mem_p^); {parent memory context for hash table} seq_subr := 1; {init sequence num for next default subr name} def_syo_p := nil; {init to no syntax currently being defined} { * Main loop. Come back here each new command from SYO file. This loop * terminates either on an error or end of data. } loop_cmd: syo_tree_clear; {set up for parsing} sst_r_syo_sy_command (mflag); {try to parse one top level syntax} if mflag <> syo_mflag_yes_k then begin {syntax didn't match ?} syo_tree_err; {set up for error re-parse} sst_r_syo_sy_command (eflag); {do error re-parse} end; syo_tree_setup; {set up syntax tree for getting tags} sst_r_syo_command (stat); {process this SYO file command} if sys_stat_match (sst_subsys_k, sst_stat_eod_k, stat) {hit end of input data ?} then goto eod; if sys_error(stat) then return; {encountered hard error ?} if mflag <> syo_mflag_yes_k then begin {syntax error not caught as content error ?} syo_error_print ('', '', nil, 0); {complain about syntax error} sys_exit_error; {exit program with error condition} end; goto loop_cmd; {back for next command from SYO file} eod: { * End of input data encountered. * * Propagate used flags to all appropriate SYO file symbols. } string_hash_pos_first (table_sym, hpos, found); {go to first entry in hash table} while found do begin {once for each entry in hash table} string_hash_ent_atpos ( {get info about this hash table entry} hpos, {handle to hash table position} name_p, {returned pointing to name in table entry} data_p); {returned pointing to our data area in entry} if {this symbol used but not followed yet ?} (sst_symflag_used_k in data_p^.sym_p^.flags) and (not (sst_symflag_followed_k in data_p^.sym_p^.flags)) then begin follow_sym (data_p^); {propagate USED flag for this symbol} end; string_hash_pos_next (hpos, found); {advance to next hash table entry} end; {back and process this new hash table entry} { * List any unused SYO symbols and clear FOLLOWED flags left from previous * pass over all the symbols. } unused_syms := false; {init to no unused symbols found} string_hash_pos_first (table_sym, hpos, found); {go to first entry in hash table} while found do begin {once for each entry in hash table} string_hash_ent_atpos ( {get info about this hash table entry} hpos, {handle to hash table position} name_p, {returned pointing to name in table entry} data_p); {returned pointing to our data area in entry} data_p^.sym_p^.flags := {clear FOLLOWED flag} data_p^.sym_p^.flags - [sst_symflag_followed_k]; if {this symbol was never used ?} not (sst_symflag_used_k in data_p^.sym_p^.flags) then begin if not unused_syms then begin {this is first unused symbol ?} sys_message ('sst_syo_read', 'symbols_unused_show'); unused_syms := true; {flag that unused symbols were encountered} end; writeln (' ', name_p^.str:name_p^.len); {write name of unused symbol} end; string_hash_pos_next (hpos, found); {advance to next hash table entry} end; {back and process this new hash table entry} { * Check for undefined SYO symbols. } undefined_syms := false; {init to no undefined symbols found} string_hash_pos_first (table_sym, hpos, found); {go to first entry in hash table} while found do begin {once for each entry in hash table} string_hash_ent_atpos ( {get info about this hash table entry} hpos, {handle to hash table position} name_p, {returned pointing to name in table entry} data_p); {returned pointing to our data area in entry} if {used but undefined symbol ?} (sst_symflag_used_k in data_p^.sym_p^.flags) and {symbol used ?} (not (sst_symflag_def_k in data_p^.sym_p^.flags)) and {not defined here?} (not (sst_symflag_extern_k in data_p^.sym_p^.flags)) {not external ?} then begin if not undefined_syms then begin {this is first undefined symbol ?} sys_message ('sst_syo_read', 'symbols_undefined_show'); undefined_syms := true; {flag that undefined symbols were encountered} end; writeln (' ', name_p^.str:name_p^.len); {write name of undefined symbol} end; string_hash_pos_next (hpos, found); {advance to next hash table entry} end; {back and process this new hash table entry} string_hash_delete (table_sym); {delete table for this SYO file symbols} if undefined_syms then begin {some undefined symbols were found ?} sys_message_bomb ('sst_syo_read', 'symbols_undefined_abort', nil, 0); end; end;
unit VehicleUnit; interface uses REST.Json.Types, System.Generics.Collections, SysUtils, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit; type /// <summary> /// Vehicles in the user's account /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Vehicle.dtd /// </remarks> TVehicle = class(TGenericParameters) private [JSONName('vehicle_id')] [Nullable] FId: NullableString; [JSONName('created_time')] [Nullable] FCreatedTime: NullableString; [JSONName('member_id')] [Nullable] FMemberId: NullableInteger; [JSONName('vehicle_alias')] [Nullable] FAlias: NullableString; [JSONName('vehicle_reg_state')] [Nullable] FRegState: NullableString; [JSONName('vehicle_reg_state_id')] [Nullable] FRegStateId: NullableString; [JSONName('vehicle_reg_country')] [Nullable] FRegCountry: NullableString; [JSONName('vehicle_reg_country_id')] [Nullable] FRegCountryId: NullableString; [JSONName('vehicle_license_plate')] [Nullable] FLicensePlate: NullableString; [JSONName('vehicle_make')] [Nullable] FMaker: NullableString; [JSONName('vehicle_model_year')] [Nullable] FModelYear: NullableString; [JSONName('vehicle_model')] [Nullable] FModel: NullableString; [JSONName('vehicle_year_acquired')] [Nullable] FYearAcquired: NullableString; [JSONName('vehicle_cost_new')] [Nullable] FCostNew: NullableDouble; [JSONName('license_start_date')] [Nullable] FLicenseStartDate: NullableString; [JSONName('license_end_date')] [Nullable] FLicenseEndDate: NullableString; [JSONName('vehicle_axle_count')] [Nullable] FAxleCount: NullableString; [JSONName('mpg_city')] [Nullable] FMpgCity: NullableString; [JSONName('mpg_highway')] [Nullable] FMpgHighway: NullableString; [JSONName('fuel_type')] [Nullable] FFuelType: NullableString; [JSONName('height_inches')] [Nullable] FHeightInches: NullableString; [JSONName('weight_lb')] [Nullable] FWeightLb: NullableString; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// A unique identifcation 32-char string of the vehicle /// </summary> property Id: NullableString read FId write FId; /// <summary> /// Created time of the record about vehicle /// </summary> property CreatedTime: NullableString read FCreatedTime write FCreatedTime; /// <summary> /// An unique identification number of the member /// </summary> property MemberId: NullableInteger read FMemberId write FMemberId; /// <summary> /// Internal name of the vehicle /// </summary> property Alias: NullableString read FAlias write FAlias; /// <summary> /// A state where vehicle was registered /// </summary> property RegistrationState: NullableString read FRegState write FRegState; /// <summary> /// An ID of the state, where vehicle was registered /// </summary> property RegistrationStateId: NullableString read FRegStateId write FRegStateId; /// <summary> /// A country where vehicle was registered /// </summary> property RegistrationCountry: NullableString read FRegCountry write FRegCountry; /// <summary> /// An ID of the country, where vehicle was registered /// </summary> property RegistrationCountryId: NullableString read FRegCountryId write FRegCountryId; /// <summary> /// A license plate of the vehicle /// </summary> property LicensePlate: NullableString read FLicensePlate write FLicensePlate; /// <summary> /// Vehicle maker brend /// </summary> property Maker: NullableString read FMaker write FMaker; /// <summary> /// A year of the vehicle model /// </summary> property ModelYear: NullableString read FModelYear write FModelYear; /// <summary> /// A model of the vehicle /// </summary> property Model: NullableString read FModel write FModel; /// <summary> /// A year the vehicle was acquired /// </summary> property YearAcquired: NullableString read FYearAcquired write FYearAcquired; /// <summary> /// A cost of the new vehicle /// </summary> property CostNew: NullableDouble read FCostNew write FCostNew; /// <summary> /// A start date of the license /// </summary> property LicenseStartDate: NullableString read FLicenseStartDate write FLicenseStartDate; /// <summary> /// An end date of the license /// </summary> property LicenseEndDate: NullableString read FLicenseEndDate write FLicenseEndDate; /// <summary> /// A number of the vehicle's axles /// </summary> property AxleCount: NullableString read FAxleCount write FAxleCount; /// <summary> /// Miles per gallon in the city area /// </summary> property MpgCity: NullableString read FMpgCity write FMpgCity; /// <summary> /// Miles per gallon in the highway area /// </summary> property MpgHighway: NullableString read FMpgHighway write FMpgHighway; /// <summary> /// A type of the fuel /// </summary> property FuelType: NullableString read FFuelType write FFuelType; /// <summary> /// A height of the vehicle in the inches /// </summary> property HeightInches: NullableString read FHeightInches write FHeightInches; /// <summary> /// A weight of the vehicle in the pounds /// </summary> property WeightLb: NullableString read FWeightLb write FWeightLb; end; TVehicleList = TObjectList<TVehicle>; implementation { TVehicle } constructor TVehicle.Create; begin Inherited Create; FId := NullableString.Null; FCreatedTime := NullableString.Null; FMemberId := NullableInteger.Null; FAlias := NullableString.Null; FRegState := NullableString.Null; FRegStateId := NullableString.Null; FRegCountry := NullableString.Null; FRegCountryId := NullableString.Null; FLicensePlate := NullableString.Null; FMaker := NullableString.Null; FModelYear := NullableString.Null; FModel := NullableString.Null; FYearAcquired := NullableString.Null; FCostNew := NullableDouble.Null; FLicenseStartDate := NullableString.Null; FLicenseEndDate := NullableString.Null; FAxleCount := NullableString.Null; FMpgCity := NullableString.Null; FMpgHighway := NullableString.Null; FFuelType := NullableString.Null; FHeightInches := NullableString.Null; FWeightLb := NullableString.Null; end; function TVehicle.Equals(Obj: TObject): Boolean; var Other: TVehicle; begin Result := False; if not (Obj is TVehicle) then Exit; Other := TVehicle(Obj); Result := (FId = Other.FId) and (FCreatedTime = Other.FCreatedTime) and (FMemberId = Other.FMemberId) and (FAlias = Other.FAlias) and (FRegState = Other.FRegState) and (FRegStateId = Other.FRegStateId) and (FRegCountry = Other.FRegCountry) and (FRegCountryId = Other.FRegCountryId) and (FLicensePlate = Other.FLicensePlate) and (FMaker = Other.FMaker) and (FModelYear = Other.FModelYear) and (FModel = Other.FModel) and (FYearAcquired = Other.FYearAcquired) and (FCostNew = Other.FCostNew) and (FLicenseStartDate = Other.FLicenseStartDate) and (FLicenseEndDate = Other.FLicenseEndDate) and (FAxleCount = Other.FAxleCount) and (FMpgCity = Other.FMpgCity) and (FMpgHighway = Other.FMpgHighway) and (FFuelType = Other.FFuelType) and (FHeightInches = Other.FHeightInches) and (FWeightLb = Other.FWeightLb); end; end.
{ The unit is part of Lazarus Chelper package Copyright (C) 2010 Dmitry Boyarintsev skalogryz dot lists at gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit TextParsingUtils; {$ifdef fpc}{$mode delphi}{$h+}{$endif} interface uses Types; type TCharSet = set of Char; const EoLnChars = [#10,#13]; SpaceChars = [#32,#9]; InvsChars = [#0..#32]; WhiteSpaceChars = SpaceChars; SpaceEolnChars = EoLnChars+SpaceChars; NumericChars = ['0'..'9']; AlphabetChars = ['a'..'z','A'..'Z']; AlphaNumChars = AlphabetChars+NumericChars; function ScanWhile(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; overload; function ScanBackWhile(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; function ScanTo(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; function ScanBackTo(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; procedure SkipTo(const s: AnsiString; var index: Integer; const ch: TCharSet); procedure SkipWhile(const s: AnsiString; var index: Integer; const ch: TCharSet); procedure SkipToEoln(const s: AnsiString; var index: Integer); // returns #10, #13, #10#13 or #13#10, if s[index] is end-of-line sequence // otherwise returns empty string function EolnStr(const s: AnsiString; index: Integer): String; function IsSubStr(const sbs, s: AnsiString; index: Integer): Boolean; // todo: not used? function SkipCommentBlock(const s: AnsiString; var index: Integer; const closecmt: AnsiString): AnsiString; function SkipLine(const s: AnsiString; var index: Integer): AnsiString; procedure OffsetToLinePos(const t: AnsiString; Offset: Integer; var P: TPoint); type TRange = record stofs, endofs : Integer; end; { TSubBuffer } TSubBuffer = class(TObject) Ranges : array of TRange; RangesCount : Integer; Name : string; Tag : TObject; constructor Create(const AName: string; ATag: TObject); end; { TTextBuffer } TTextBuffer = class(TObject) private function GetSubBuffer(i: Integer): TSubBuffer; protected function GetCount: Integer; public buffer: String; constructor Create(const Abuffer: String=''; const aname: string = ''; aobj: TObject = nil); procedure InsertSubBuffer(pos: Integer; const ABuffer: string; const AName: string = ''; ATag: TObject = ''); property SubBuffer[i: Integer]: TSubBuffer read GetSubBuffer; property Count: Integer read GetCount; end; type TFileOfsInfo = record origOfs : Integer; // original 1-based index in the file delta : Integer; // the new delta that should be used starting this file end; { TFileOffsets } TFileOffsets = class(TObject) public Ofs : array of TFileOfsInfo; Count : Integer; procedure AddOffset(origOfs, delta: integer); function OrigOffset(tempOfs: integer): Integer; end; implementation function ScanWhile(const s: AnsiString; var index: Integer; const ch: TCharSet ): string; var i : Integer; begin Result := ''; if (index <= 0) or (index > length(s)) then Exit; for i := index to length(s) do if not (s[i] in ch) then begin if i = index then Result := '' else Result := Copy(s, index, i - index); index := i; Exit; end; Result := Copy(s, index, length(s) - index + 1); index := length(s) + 1; end; function ScanBackWhile(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; var j : integer; begin Result:=''; if (index <= 0) or (index > length(s)) then Exit; j:=index; while (index>0) and (s[index] in ch) do dec(index); Result:=Copy(s, index+1, j-index); end; procedure SkipTo(const s: AnsiString; var index: Integer; const ch: TCharSet); begin if (index <= 0) or (index > length(s)) then Exit; while (index<=length(s)) and not (s[index] in ch) do inc(index); end; procedure SkipWhile(const s: AnsiString; var index: Integer; const ch: TCharSet); begin if (index <= 0) or (index > length(s)) then Exit; while (index<=length(s)) and (s[index] in ch) do inc(index); end; function ScanBackTo(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; var j : integer; begin Result:=''; if (index <= 0) or (index > length(s)) then Exit; j:=index; while (index>0) and not (s[index] in ch) do dec(index); Result:=Copy(s, index+1, j-index); end; function ScanTo(const s: AnsiString; var index: Integer; const ch: TCharSet): AnsiString; var i : Integer; begin Result := ''; if (index <= 0) or (index > length(s)) then Exit; for i := index to length(s) do if (s[i] in ch) then begin if i = index then Result := '' else Result := Copy(s, index, i - index); index := i; Exit; end; Result := Copy(s, index, length(s) - index + 1); index := length(s) + 1; end; function EolnStr(const s: AnsiString; index: Integer): String; begin if (index<=0) or (index>length(s)) or (not (s[index] in EoLnChars)) then Result:='' else begin if (index<length(s)) and (s[index+1] in EolnChars) and (s[index]<>s[index+1]) then Result:=Copy(s, index, 2) else Result:=s[index]; end; end; procedure SkipToEoln(const s: AnsiString; var index: Integer); begin SkipTo(s, index, EoLnChars); end; function IsSubStr(const sbs, s: AnsiString; index: Integer): Boolean; var i : Integer; j : Integer; begin Result := false; if (sbs = '') or (length(sbs) > length(s) - index) then Exit; j := index; for i := 1 to length(sbs) do begin if sbs[i] <> s[j] then Exit; inc(j); end; Result := true; end; function SkipCommentBlock(const s: AnsiString; var index: Integer; const closecmt: AnsiString): AnsiString; begin Result := ''; if closecmt = '' then begin index := length(s) + 1; Exit; end; while index <= length(s) do begin Result := Result + ScanTo(s, index, [closecmt[1]]+EoLnChars); //if (index<=length(s)) and (s in EoLnChars( if IsSubStr(closecmt, s, index) then begin inc(index, length(closecmt)); Exit; end else begin Result := Result + s[index]; inc(index); end; end; end; function SkipLine(const s: AnsiString; var index: Integer): AnsiString; begin Result:=ScanTo(s, index, EoLnChars); if (index<length(s)) and (s[index+1] in EoLnChars) and (s[index]<>s[index+1]) then inc(index); inc(index); end; procedure OffsetToLinePos(const t: AnsiString; Offset: Integer; var P: TPoint); var i, le : Integer; begin i := 1; le := 0; P.X := 0; P.Y := 0; while i < Offset do begin Inc(P.Y); le := i; SkipLine(t, i); end; P.X := Offset - le + 1; end; { TTextBuffer } function TTextBuffer.GetSubBuffer(i: Integer): TSubBuffer; begin Result:=nil; end; function TTextBuffer.GetCount: Integer; begin Result:=0; end; constructor TTextBuffer.Create(const Abuffer: String; const aname: string; aobj: TObject); begin if abuffer<>'' then InsertSubBuffer(1, abuffer, aname, aobj); end; procedure TTextBuffer.InsertSubBuffer(pos: Integer; const ABuffer: string; const AName: string; ATag: TObject); begin end; { TSubBuffer } constructor TSubBuffer.Create(const AName: string; ATag: TObject); begin inherited Create; Name:=AName; Tag:=ATag; end; procedure TFileOffsets.AddOffset(origOfs, delta: integer); begin if Count=length(Ofs) then begin if Count=0 then SetLength(Ofs, 4) else SetLength(Ofs, Count*2); end; Ofs[Count].origOfs:=origOfs; Ofs[Count].delta:=delta; inc(Count); end; function TFileOffsets.OrigOffset(tempOfs: integer): Integer; var i : Integer; begin Result:=tempOfs; for i:=0 to Count-1 do begin if (Ofs[i].origOfs <= tempOfs) then inc(Result, Ofs[i].delta); end; end; end.
unit PE.Types.Directories; interface type TImageDataDirectory = packed record RVA: uint32; Size: uint32; function IsEmpty: boolean; inline; function Contain(rva: uint32): boolean; inline; // todo: VirtualAddress is deprecated, use RVA instead. property VirtualAddress: uint32 read RVA write RVA; end; PImageDataDirectory = ^TImageDataDirectory; type // 2.4.3. Optional Header Data Directories (Image Only) // variant #1 TImageDataDirectories = packed record ExportTable: TImageDataDirectory; // The export table address and size. ImportTable: TImageDataDirectory; // The import table address and size. ResourceTable: TImageDataDirectory; // The resource table address and size. ExceptionTable: TImageDataDirectory; // The exception table address and size. CertificateTable: TImageDataDirectory; // The attribute certificate table address and size. BaseRelocationTable: TImageDataDirectory; // The base relocation table address and size. Debug: TImageDataDirectory; // The debug data starting address and size. Architecture: TImageDataDirectory; // Reserved, must be 0 GlobalPtr: TImageDataDirectory; // The RVA of the value to be stored in the global pointer register. // The size member of this structure must be set to zero. TLSTable: TImageDataDirectory; // The thread local storage (TLS) table address and size. LoadConfigTable: TImageDataDirectory; // The load configuration table address and size. BoundImport: TImageDataDirectory; // The bound import table address and size. IAT: TImageDataDirectory; // The import address table address and size. DelayImportDescriptor: TImageDataDirectory; // The delay import descriptor address and size. CLRRuntimeHeader: TImageDataDirectory; // The CLR runtime header address and size. RESERVED: TImageDataDirectory; // Reserved, must be zero end; PImageDataDirectories = ^TImageDataDirectories; const NULL_IMAGE_DATA_DIRECTORY: TImageDataDirectory = (RVA: 0; Size: 0); IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16; TYPICAL_NUMBER_OF_DIRECTORIES = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; // variant #2 // TImageDataDirectories = packed array [0 .. IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of TImageDataDirectory; // Get directory name by index or format index as a string (like dir_0001) if // it's not in range of known names. function GetDirectoryName(Index: integer): string; implementation uses System.SysUtils; function TImageDataDirectory.Contain(rva: uint32): boolean; begin Result := (rva >= Self.VirtualAddress) and (rva < Self.VirtualAddress + Self.Size); end; function TImageDataDirectory.IsEmpty: boolean; begin // In some cases Size can be 0, but VirtualAddress will point to valid data. Result := (VirtualAddress = 0); end; const DirectoryNames: array [0 .. IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of string = ( 'Export', 'Import', 'Resource', 'Exception', 'Certificate', 'Base Relocation', 'Debug', 'Architecture', 'Global Pointer', 'Thread Local Storage', 'Load Config', 'Bound Import', 'Import Address Table', 'Delay Import Descriptor', 'CLR Runtime Header', '' ); function GetDirectoryName(Index: integer): string; begin if (Index >= 0) and (Index < Length(DirectoryNames)) then Result := DirectoryNames[Index] else Result := format('dir_%4.4d', [index]); end; end.
unit steParser; (* +--------------------------+ | ┏━┓╺┳╸┏━╸ Simple | | ┗━┓ ┃ ┣╸ Template | | ┃ ┃ ┃ Engine | | ┗━┛ ╹ ┗━╸ for Free Pascal | + -------------------------+ *) {$mode objfpc}{$H+} // load, tokenize and check template interface uses Classes, SysUtils; // Tokens are both plain text and tags. type TSTEParserTokenKind = (tkPlainText, tkCustomTag, tkFor, tkEndFor, tkIf, tkEndIf, tkElse, tkSet, tkEndSet); type TSTEParserToken = record Kind : TSTEParserTokenKind; Tag : string; Param : string; StartPos : integer; Size : integer; LinkedToken : pointer; //for<->endfor; if->(endif/else); else->endif; endif->if; set<->endset Index : integer; end; PSTEParserToken = ^TSTEParserToken; type TSTEParsedTemplateData = class protected function NewToken(AStartPos : integer; AKind : TSTEParserTokenKind = tkPlainText) : PSTEParserToken; public ChangeDateTime : TDateTime; //used mostly for caching Source : string; Tokens : TList; function TokenKindName(tokenIndex : integer) : string; constructor Create; virtual; destructor Destroy; override; end; type TSTEParser = class private FSourceLen : integer; FCurrentPos : integer; FTagCloseToken : string; FTagOpenToken : string; FTagOpenTokenLen, FTagCloseTokenLen : integer; procedure SetTagCloseToken(AValue : string); procedure SetTagOpenToken(AValue : string); protected class var DefaultTagOpenToken : string; class var DefaultTagCloseToken : string; procedure AddTextToken(template : TSTEParsedTemplateData; aStart, aSize : integer); function GetNextToken(template : TSTEParsedTemplateData) : boolean; procedure ParseToken(token : PSTEParserToken; const tokenText : string); procedure BuildSyntaxTree(template : TSTEParsedTemplateData); public //TagParamSeparator : string; TrimTagLines : boolean; //trim empty line endings after tags - postponed property TagOpenToken : string read FTagOpenToken write SetTagOpenToken; property TagCloseToken : string read FTagCloseToken write SetTagCloseToken; class procedure SetDefaultTokenEnclosing(const AOpen, AClose : string); function Prepare(const ASource : string) : TSTEParsedTemplateData; procedure PrepareTemplate(const ASource : string; var ATemplate : TSTEParsedTemplateData); // prepare external instance constructor Create; destructor Destroy; override; end; implementation uses strutils, contnrs, steCommon; const STETokenTagNames : array[TSTEParserTokenKind] of string = ('text', 'custom', 'for', 'endfor', 'if', 'endif', 'else', 'set', 'endset'); function TSTEParsedTemplateData.NewToken(AStartPos: integer; AKind: TSTEParserTokenKind): PSTEParserToken; begin New(Result); with Result^ do begin Kind := AKind; Tag := ''; Param := ''; StartPos := AStartPos; Size := -1; LinkedToken := nil; Index := -1; end; Tokens.Add(Result); end; function TSTEParsedTemplateData.TokenKindName(tokenIndex: integer): string; begin if (tokenIndex > -1) and (tokenIndex < Tokens.Count) then Result := STETokenTagNames[ PSTEParserToken(Tokens.Items[tokenIndex])^.Kind ] else Result := 'invalid token index'; end; constructor TSTEParsedTemplateData.Create; begin Tokens := TList.Create; end; destructor TSTEParsedTemplateData.Destroy; var i: integer; begin for i := 0 to Tokens.Count-1 do Dispose(PSTEParserToken(Tokens.Items[i])); Tokens.Free; inherited Destroy; end; procedure TSTEParser.SetTagOpenToken(AValue : string); begin if FTagOpenToken = AValue then Exit; FTagOpenToken := AValue; FTagOpenTokenLen := Length(FTagOpenToken); end; procedure TSTEParser.SetTagCloseToken(AValue : string); begin if FTagCloseToken = AValue then Exit; FTagCloseToken := AValue; FTagCloseTokenLen := Length(FTagCloseToken); end; procedure TSTEParser.AddTextToken(template: TSTEParsedTemplateData; aStart, aSize: integer); begin with template.NewToken(aStart, tkPlainText)^ do begin Size := aSize; Tag := ''; Param := ''; end; end; function TSTEParser.GetNextToken(template: TSTEParsedTemplateData): boolean; var iStart, openTagPos, closeTagPos : integer; tokenText : string; token : PSTEParserToken; begin Result := false; iStart := FCurrentPos; openTagPos := PosEx(TagOpenToken, template.Source, FCurrentPos); if openTagPos > 0 then begin // found tag opening FCurrentPos := openTagPos + FTagOpenTokenLen-1; // ------ ???? todo: recheck indicies // search for tag closing closeTagPos := PosEx(TagCloseToken, template.Source, FCurrentPos); if closeTagPos > 0 then begin tokenText := Copy(template.Source, FCurrentPos+1, closeTagPos - FCurrentPos-1); FCurrentPos := closeTagPos + FTagCloseTokenLen; Result := true; // Some text from start - make it text token if openTagPos > iStart then AddTextToken(template, iStart, openTagPos-iStart); // ---- Append new tag token token := template.NewToken(openTagPos, tkCustomTag); ParseToken(token, Trim(tokenText)); { if TrimTagLines then if not ( token^.Kind in [tkPlainText, tkCustomTag] ) then TrimLine(template);} end; end; if not Result then begin // no more tags until end of file AddTextToken(template, iStart, FSourceLen-FCurrentPos+1); end; end; procedure TSTEParser.ParseToken(token: PSTEParserToken; const tokenText: string); var spos : integer = 0; s : string; iKind : TSTEParserTokenKind; begin with token^ do begin if Kind <> tkPlainText then begin s := ExtractWordPos(1, tokenText, steWhiteSpaceChars , spos); if spos > 0 then begin Tag := s; Param := Trim(Copy(tokenText, spos + Length(Tag), Length(tokenText)-spos)); end else begin Tag := tokenText; Param := ''; end; Kind := tkCustomTag; s := LowerCase(Tag); for iKind := tkFor to tkEndSet do begin // ------------ check supported tags if s = STETokenTagNames[iKind] then begin Kind := iKind; Break; end; end; end; end; end; procedure TSTEParser.BuildSyntaxTree(template: TSTEParsedTemplateData); var i: integer; linked, token, elseToken : PSTEParserToken; setTokens, forTokens, ifTokens : TStack; begin setTokens := TStack.Create; forTokens := TStack.Create; ifTokens := TStack.Create; try for i := 0 to template.Tokens.Count-1 do begin token := PSTEParserToken(template.Tokens.Items[i]); token^.Index := i; case token^.Kind of tkFor : begin if Trim(token^.Param) = '' then raise ESTEParserError.CreateFmt('FOR without parameter, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); forTokens.Push(token); end; tkSet : begin if Trim(token^.Param) = '' then raise ESTEParserError.CreateFmt('SET without parameter, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); setTokens.Push(token); end; tkIf : begin if Trim(token^.Param) = '' then raise ESTEParserError.CreateFmt('IF without parameter, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); ifTokens.Push(token); end; tkElse : begin if ifTokens.Count > 0 then begin linked := PSTEParserToken(ifTokens.Peek); if linked^.LinkedToken <> nil then raise ESTEParserError.CreateFmt('ELSE mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); linked^.LinkedToken := token; // if->else end else raise ESTEParserError.CreateFmt('ELSE mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); end; tkEndIf : // if->(endif/else); else->endif; endif->if begin if ifTokens.Count > 0 then begin linked := PSTEParserToken(ifTokens.Pop); if linked^.LinkedToken = nil then // no else linked^.LinkedToken := token else begin // linked^.LinkedToken is else tag elseToken := PSTEParserToken(linked^.LinkedToken); if elseToken^.Kind <> tkElse then // check it raise ESTEParserError.CreateFmt('ELSE mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); elseToken^.LinkedToken := token; //else->endif; token^.LinkedToken := linked; // endif->if end; end else raise ESTEParserError.CreateFmt('ENDIF mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); end; tkEndFor : begin if forTokens.Count > 0 then begin linked := PSTEParserToken(forTokens.Pop); linked^.LinkedToken := token; token^.LinkedToken := linked; end else raise ESTEParserError.CreateFmt('ENDFOR mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); end; tkEndSet : begin if setTokens.Count > 0 then begin linked := PSTEParserToken(setTokens.Pop); linked^.LinkedToken := token; token^.LinkedToken := linked; if token^.Index <> (linked^.Index + 2) then raise ESTEParserError.CreateFmt('SET block: only single text token allowed, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); linked := PSTEParserToken( template.Tokens.Items[ linked^.Index + 1 ] ); // set to contained text if linked^.Kind <> tkPlainText then raise ESTEParserError.CreateFmt('SET block: must not contain other tokens, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); end else raise ESTEParserError.CreateFmt('ENDSET mismatch, line %d', [ STEGetSourceLineNumber(template.Source, token^.StartPos) ]); end; end; // case end; // for // Check for unpaired tags if forTokens.Count > 0 then raise ESTEParserError.CreateFmt('ENDFOR mismatch, line %d', [ STEGetSourceLineNumber(template.Source, PSTEParserToken(forTokens.Peek)^.StartPos) ]); if ifTokens.Count > 0 then raise ESTEParserError.CreateFmt('ENDIF mismatch, line %d', [ STEGetSourceLineNumber(template.Source, PSTEParserToken(ifTokens.Peek)^.StartPos) ]); if setTokens.Count > 0 then raise ESTEParserError.CreateFmt('ENDSET mismatch, line %d', [ STEGetSourceLineNumber(template.Source, PSTEParserToken(setTokens.Peek)^.StartPos) ]); // todo: add second pass to check correct LinkedToken references finally setTokens.Free; ifTokens.Free; forTokens.Free; end; end; class procedure TSTEParser.SetDefaultTokenEnclosing(const AOpen, AClose : string); begin DefaultTagOpenToken := AOpen; DefaultTagCloseToken := AClose; end; procedure TSTEParser.PrepareTemplate(const ASource : string; var ATemplate : TSTEParsedTemplateData); var moreTokens : boolean; begin ATemplate.Source := ASource; FSourceLen := Length(ASource); FCurrentPos := 1; // tokenize repeat moreTokens := GetNextToken(ATemplate); until moreTokens = false; BuildSyntaxTree(ATemplate); end; function TSTEParser.Prepare(const ASource : string) : TSTEParsedTemplateData; begin try Result := TSTEParsedTemplateData.Create; PrepareTemplate(ASource, Result); except Result.Free; raise; end; end; constructor TSTEParser.Create; begin TagOpenToken := DefaultTagOpenToken; TagCloseToken := DefaultTagCloseToken; TrimTagLines := true; end; destructor TSTEParser.Destroy; begin inherited Destroy; end; initialization TSTEParser.SetDefaultTokenEnclosing('<?', '?>'); // defaults end.
// Copyright (c) 2017 Embarcadero Technologies, Inc. All rights reserved. // // This software is the copyrighted property of Embarcadero Technologies, Inc. // ("Embarcadero") and its licensors. You may only use this software if you // are an authorized licensee of Delphi, C++Builder or RAD Studio // (the "Embarcadero Products"). This software is subject to Embarcadero's // standard software license and support agreement that accompanied your // purchase of the Embarcadero Products and is considered a Redistributable, // as such term is defined thereunder. Your use of this software constitutes // your acknowledgement of your agreement to the foregoing software license // and support agreement. //--------------------------------------------------------------------------- unit SetupData; interface uses REST.Backend.EMSApi, System.JSON, IPPeerClient, System.DateUtils, System.SysUtils; procedure SetupTestData(const AHost, APort: string); implementation const _TENANT_ID_1 = 'AB715312-06FF-41AB-BBB5-07FF6F101B49'; _TENANT_SECRET_1 = '1'; _TENANT_ID_2 = '37B3DBCB-A27E-4F89-8947-3AE24317B924'; _TENANT_SECRET_2 = '2'; sTestUser1 = 'John'; sTestUser2 = 'Sam'; sTestUser3 = 'Michael'; sTestUser4 = 'Tina'; sPassword = '1'; sTestGroup1 = 'Managers'; sTestGroup2 = 'Cashiers'; var FClientAPI: TEMSClientApi; FBaseURL: string; procedure SetupUsersAndGroups(AFirstTenant: Boolean); var LUser1, LUser2: TEMSClientAPI.TUser; LGroup1, LGroup2: TEMSClientAPI.TGroup; LUpdatedAt: TEMSClientAPI.TUpdatedAt; begin if AFirstTenant then begin FClientAPI.AddUser(sTestUser1, sPassword, nil, LUser1); FClientAPI.AddUser(sTestUser2, sPassword, nil, LUser2); end else begin FClientAPI.AddUser(sTestUser3, sPassword, nil, LUser1); FClientAPI.AddUser(sTestUser4, sPassword, nil, LUser2); end; FClientAPI.CreateGroup(sTestGroup1, nil, LGroup1); FClientAPI.CreateGroup(sTestGroup2, nil, LGroup2); FClientAPI.AddUsersToGroup(sTestGroup1, [LUser1.UserID], LUpdatedAt); FClientAPI.AddUsersToGroup(sTestGroup2, [LUser2.UserID], LUpdatedAt); end; procedure CheckConnection; var LJSONArray: TJSONArray; LServerFound: Boolean; EndTime: TDateTime; begin LServerFound := False; LJSONArray := TJSONArray.Create; try EndTime := IncSecond(Now, 20); while not LServerFound and (Now < EndTime) do begin try FClientAPI.AppHandshake(LJSONArray); LServerFound := True; except end; end; finally LJSONArray.Free; end; end; procedure SetupByTenant(const ATenantId, ATenantSecret: string); var LConnectionInfo: TEMSClientAPI.TConnectionInfo; LUser, LUser2: TEMSClientAPI.TUser; LFirstTenant: Boolean; begin FClientAPI := TEMSClientAPI.Create(nil); try LConnectionInfo.TenantId := ATenantId; LConnectionInfo.TenantSecret := ATenantSecret; LConnectionInfo.BaseURL := FBaseURL; FClientAPI.ConnectionInfo := LConnectionInfo; CheckConnection; LFirstTenant := ATenantId = _TENANT_ID_1; if LFirstTenant then FClientAPI.QueryUserName(sTestUser1, LUser) else FClientAPI.QueryUserName(sTestUser3, LUser); if LUser.UserID.IsEmpty then SetupUsersAndGroups(LFirstTenant); finally FreeAndNil(FClientAPI); end; end; procedure SetupTestData(const AHost, APort: string); begin FBaseURL := Format('http://%s:%s/', [AHost, APort]); SetupByTenant(_TENANT_ID_1, _TENANT_SECRET_1); SetupByTenant(_TENANT_ID_2, _TENANT_SECRET_2); end; end.
program sorting(input, output); type sequence = array[0 .. 9] of integer; var a, b : sequence; procedure cpy(v : sequence; var w : sequence); var i : 0 .. 9; begin for i := 0 to 9 do w[i] := v[i]; end; procedure randomSequence(var a : sequence); var i : 0 .. 9; begin for i := 9 downto 0 do a[9 - i] := i; end; procedure printSequence(v : sequence); var i : 0 .. 9; begin for i := 0 to 9 do write(v[i], ' '); writeln(); end; procedure swap(var a, b : integer); var temp : 0 .. 9; begin temp := a; a := b; b := temp end; procedure bubbleSort(v : sequence; var ans : sequence); var swapped : boolean; i : integer; begin repeat swapped := false; for i := 0 to 9 do begin if v[i - 1] > v[i] then begin swap(v[i - 1], v[i]); swapped := true; end; end; until not swapped; cpy(v, ans); end; procedure selectionSort(v : sequence; var ans : sequence); var i, j : 0 .. 9; begin for i := 0 to 9 do begin for j := i + 1 to 9 do begin if v[j] < v[i] then swap(v[i], v[j]) end; end; cpy(v, ans); end; procedure insertionSort(v : sequence; var ans : sequence); var i, j : 0 .. 9; begin for i := 1 to 9 do begin j := i; while ((j > 0) and (v[j - 1] > v[j])) do begin swap(v[j], v[j - 1]); j := j - 1 end; end; cpy(v, ans); end; procedure shellSort(v : sequence; var ans : sequence); var i, jump, n, m : 0 .. 9; swapped : boolean; begin jump := 9; while jump > 1 do begin jump := jump div 2; repeat swapped := false; for m := 0 to (9 - jump) do begin n := m + jump; if v[m] > v[n] then begin {v[m] < v[n] for ascending} swap(v[m], v[n]); swapped := true; end; end; until not swapped; end; cpy(v, ans); end; begin a[0] := 9; a[1] := 8; a[2] := 1; a[3] := 7; a[4] := 6; a[5] := 3; a[6] := 4; a[7] := 5; a[8] := 4; a[9] := 1; writeln('Original list: '); printSequence(a); randomSequence(b); bubbleSort(a, b); printSequence(b); randomSequence(b); selectionSort(a, b); printSequence(b); randomSequence(b); insertionSort(a, b); printSequence(b); randomSequence(b); shellSort(a, b); printSequence(b); end.
unit vcmComponent; { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmComponent - } { Начат: 11.09.2004 16:03 } { $Id: vcmComponent.pas,v 1.6 2014/07/16 15:56:56 lulin Exp $ } // $Log: vcmComponent.pas,v $ // Revision 1.6 2014/07/16 15:56:56 lulin // - чистим код и упрощаем наследование. // // Revision 1.5 2004/09/13 08:56:10 lulin // - new behavior: TvcmPrimCollectionItem теперь может кешироваться и распределяться в пуле объектов. // // Revision 1.4 2004/09/13 07:33:02 lulin // - new behavior: _Tl3InterfacedComponent теперь может распределять свою память в пуле объектов. // // Revision 1.3 2004/09/11 13:43:14 lulin // - еще один шаг к кешируемости _Tl3InterfacedComponent. // // Revision 1.2 2004/09/11 12:46:34 lulin // - bug fix: не компилировался VCM. // // Revision 1.1 2004/09/11 12:29:09 lulin // - cleanup: избавляемся от прямого использования деструкторов. // - new unit: vcmComponent. // {$I vcmDefine.inc } interface uses Classes {$IfDef vcmNeedL3} , l3InterfacedComponent {$EndIf vcmNeedL3} ; type TvcmComponent = class({$IfDef vcmNeedL3} Tl3InterfacedComponent {$Else vcmNeedL3} TComponent {$EndIf vcmNeedL3} ) protected // internal methods class function IsCacheable: Boolean; {$IfDef vcmNeedL3} override; {$Else vcmNeedL3} virtual; {$EndIf vcmNeedL3} {-} {$IfNDef vcmNeedL3} procedure Cleanup; virtual; {-} procedure Release; virtual; {-} public // public methods destructor Destroy; override; {-} {$EndIf vcmNeedL3} end;//TvcmComponent implementation // start class TvcmComponent class function TvcmComponent.IsCacheable: Boolean; {$IfDef vcmNeedL3} //override; {$Else vcmNeedL3} //virtual; {$EndIf vcmNeedL3} {-} begin Result := true; end; {$IfNDef vcmNeedL3} destructor TvcmComponent.Destroy; //override; {-} begin Release; inherited; end; procedure TvcmComponent.Cleanup; //virtual; {-} begin end; procedure TvcmComponent.Release; //virtual; {-} begin Cleanup; end; {$EndIf vcmNeedL3} end.
// ********************************************************************** // // Copyright (c) 2001 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** unit disp_int; interface uses orbtypes,SysUtils,Classes,{$IFDEF WIN32}winsock{$ENDIF} {$IFDEF LINUX}Libc{$ENDIF}; type IORBDispCallback = interface; IORBDispatcher = interface(IUnknown) ['{094BE463-218A-11d4-9CCE-204C4F4F5020}'] procedure socketevent(const cb: IORBDispCallback; fd: TSocket;evt: TDispEvent); procedure timeevent(const cb: IORBDispCallback; timeout: longint); procedure run(infinite :Boolean); procedure move(const disp: IORBDispatcher); procedure remove(const cb: IORBDispCallback;evt: TDispEvent); function idle(): Boolean; procedure block(b: boolean); function isblocking: boolean; end; IORBDispCallback = interface(IUnknown) ['{094BE464-218A-11d4-9CCE-204C4F4F5020}'] procedure callback(const disp: IORBDispatcher;event: TDispEvent); end; ISelectDispatcher = interface(IORBDispatcher) ['{094BE465-218A-11d4-9CCE-204C4F4F5020}'] procedure handle_fevents(rset: TFDSet;wset: TFDSet;xset: TFDSet); procedure update_fevents(var rset,wset,xset: TFDSet; var nfds: integer); procedure interrupt_dispatch(); function dispatch_one_event(const timeout: long): boolean; end; implementation end.
unit ddSectionWithSub2Para; { Удаляет разрывы разделов, преобразует разрывы разлеов с метками в абзацы } interface uses evdLeafParaFilter, k2Interfaces, L3Types, k2Base ; type TddSectionWithSub2ParaFilter = class(TevdLeafParaFilter) protected {* Summary Определяет нужно ли фильтровать переданный абзац. } procedure DoWritePara(aLeaf: Tl3Variant); override; {-} function ParaTypeForFiltering: Tk2Type; override; end; implementation uses SectionBreak_Const, k2Tags, TextPara_Const, k2BaseTypes; procedure TddSectionWithSub2ParaFilter.DoWritePara(aLeaf: Tl3Variant); //virtual; {-} begin if aLeaf.Attr[k2_tiSubs].IsValid then begin Generator.StartChild(k2_typTextPara); try aLeaf.AsObject.WriteTag(Generator, l3_spfInner, [k2_tiParas]); finally Generator.Finish; end;//try..finally end end; function TddSectionWithSub2ParaFilter.ParaTypeForFiltering: Tk2Type; //virtual; {-} begin Result := k2_typSectionBreak; end; end.
unit journent; interface uses lstr; const JOURNENT_FIRST_REC = 4; JOURNENT_MAX_CACHE_SIZE = 800; JOURNENT_DEFAULT_CACHE_SIZE = 100; type journalentrytype = record blockextent:longint; date:integer; title:string[65] end; journalfilecachetype=record posit:longint; data:journalentrytype end; journalfilecacheatype=array[0..JOURNENT_MAX_CACHE_SIZE-1] of journalfilecachetype; journalfilecacheptype=^journalfilecacheatype; journalfiletype = record f:file; key:string; cache:journalfilecacheptype; cachesize:longint end; Procedure journentinit(var je:journalentrytype); Procedure journentmarkdeleted(var je:journalentrytype); Function journentisdeleted(var je:journalentrytype):boolean; Procedure journentfilecreate(pathname:string;key:string); Function journentfileopen(var jf:journalfiletype;pathname:string; key:string):boolean; Procedure journentfileget(var jf:journalfiletype;recno:longint;var je:journalentrytype); Procedure journentfilegetall(var jf:journalfiletype;recno:longint; var je:journalentrytype;var content:longstr); Procedure journentfilesave(var jf:journalfiletype;recno:longint; var je:journalentrytype); Procedure journentfilesaveall(var jf:journalfiletype;var recno:longint; var je:journalentrytype;var content:longstr); Procedure journentfilechangekey(var jf:journalfiletype;newkey:string;var content:longstr); Procedure journentfileclose(var jf:journalfiletype); Procedure journentsetcachesize(var jf:journalfiletype;newsize:longint); implementation uses dos,dates,crc,encunit; const SEED = 314159265; { initializes journal entry. Date initialized to current day, title set to untitled. } Procedure journentinit(var je:journalentrytype); var year,month,day,dayofweek:word; begin je.blockextent := 0; getdate(year,month,day,dayofweek); je.date := packit(month,day,year mod 100); je.title := 'untitled' end; { Marks a journal entry as deleted } Procedure journentmarkdeleted(var je:journalentrytype); begin je.date := -10517 end; { Returns true if a journal entry is deleted } Function journentisdeleted(var je:journalentrytype):boolean; begin journentisdeleted := (je.date = -10517) end; { Creates a new journal file pathname - the path of new file key - the password for the new file } Procedure journentfilecreate(pathname:string;key:string); var f:file; checksum:longint; numwritten:word; begin assign(f,pathname); rewrite(f,1); checksum := crc32(key,SEED); blockwrite(f,checksum,sizeof(longint),numwritten); close(f) end; Procedure journentfileinitcache(var jf:journalfiletype); var cnt:integer; begin for cnt := 0 to jf.cachesize-1 do jf.cache^[cnt].posit := -1 end; { Opens a journal file. jf - journal file object pathname - the path name of file to open key - the password for file returns true if file successfully opened, false otherwise } Function journentfileopen(var jf:journalfiletype;pathname:string; key:string):boolean; var checksum:longint; numread:word; result:boolean; begin assign(jf.f,pathname); reset(jf.f,1); blockread(jf.f,checksum,sizeof(longint),numread); if (checksum <> crc32(key,SEED)) then begin result := false; close(jf.f) end else begin result := true; jf.key := key; jf.cachesize := JOURNENT_DEFAULT_CACHE_SIZE; getmem(jf.cache,jf.cachesize*sizeof(journalfilecachetype)); journentfileinitcache(jf) end; journentfileopen := result end; { Gets the journal entry at the given position in the file. jf - journal file recno - position in file to get entry je - journal entry returned here } Procedure journentfileget(var jf:journalfiletype;recno:longint; var je:journalentrytype); var numread:word; cacheindex:integer; begin cacheindex := recno mod jf.cachesize; if (jf.cache^[cacheindex].posit <> recno) then begin seek(jf.f,recno); blockread(jf.f, jf.cache^[cacheindex].data, sizeof(journalentrytype),numread); encdecode(jf.cache^[cacheindex].data,sizeof(journalentrytype),jf.key); jf.cache^[cacheindex].posit := recno end; je := jf.cache^[cacheindex].data end; { Gets the journal entry and the content of it at the given position in the file. jf - journal file recno - position in file to get entry je - journal entry returned here content - content of journal entry returned here } Procedure journentfilegetall(var jf:journalfiletype;recno:longint; var je:journalentrytype;var content:longstr); var numread:word; strsize:word; begin journentfileget(jf,recno,je); seek(jf.f,recno+sizeof(journalentrytype)); blockread(jf.f,strsize,sizeof(word),numread); lstradjustforsize(content,strsize); blockread(jf.f,content.ptr^,strsize,numread); content.size := strsize; encdecodels(content,jf.key) end; { updates a journal entry at a given position in the file jf - journal file recno - position to save the journal entry je - the journal entry to be saved } Procedure journentfilesave(var jf:journalfiletype;recno:longint; var je:journalentrytype); var numwritten:word; tempje:journalentrytype; cacheindex:integer; begin tempje := je; enccode(tempje,sizeof(journalentrytype),jf.key); seek(jf.f,recno); blockwrite(jf.f,tempje,sizeof(journalentrytype),numwritten); cacheindex := recno mod jf.cachesize; jf.cache^[cacheindex].data := je; jf.cache^[cacheindex].posit := recno end; { Saves a journal entry and the content of that journal entry at a given position in the file. jf - journal file recno - position to save the journal entry je - the journal entry to be saved content - content to be saved } Procedure journentfilesaveall(var jf:journalfiletype;var recno:longint; var je:journalentrytype;var content:longstr); var numwritten:word; tempje:journalentrytype; newblocksize:longint; strsize:word; thefsize:longint; begin strsize := lstrlen(content); newblocksize := sizeof(journalentrytype); newblocksize := newblocksize + strsize; newblocksize := newblocksize + sizeof(word); thefsize := filesize(jf.f); if (je.blockextent < newblocksize) and (recno + je.blockextent < thefsize) then begin tempje := je; journentmarkdeleted(tempje); journentfilesave(jf,recno,tempje); recno := thefsize end; if (je.blockextent < newblocksize) then je.blockextent := newblocksize; journentfilesave(jf,recno,je); blockwrite(jf.f,strsize,sizeof(word),numwritten); enccodels(content,jf.key); blockwrite(jf.f,content.ptr^,strsize,numwritten) end; { Changes the password for a journal file jf - journal file newkey - the new password } Procedure journentfilechangekey(var jf:journalfiletype;newkey:string;var content:longstr); var checksum:longint; numwritten:word; oldkey:string; posit:longint; maxsize:longint; je:journalentrytype; begin checksum := crc32(newkey,SEED); seek(jf.f,0); blockwrite(jf.f,checksum,sizeof(longint),numwritten); oldkey := jf.key; posit := JOURNENT_FIRST_REC; maxsize := filesize(jf.f); while (posit < maxsize) do begin jf.key := oldkey; journentfilegetall(jf,posit,je,content); jf.key := newkey; journentfilesaveall(jf,posit,je,content); posit := posit + je.blockextent end; jf.key := newkey end; { closes a journal file } Procedure journentfileclose(var jf:journalfiletype); begin close(jf.f); freemem(jf.cache,jf.cachesize*sizeof(journalfilecachetype)) end; Procedure journentsetcachesize(var jf:journalfiletype;newsize:longint); begin freemem(jf.cache,jf.cachesize*sizeof(journalfilecachetype)); jf.cachesize := newsize; getmem(jf.cache,jf.cachesize*sizeof(journalfilecachetype)); journentfileinitcache(jf) end; begin end. 
unit FlatPopupMenu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus; type TFlatPopupMenu = class(TPopupMenu) procedure DrawMenu(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); procedure MeasureMenu(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); procedure MenuPopup(Sender: TObject); private { Private declarations } FExtraWidth : integer; FMenuColor : TColor; FItemSelectedColor : TColor; FMenuBorderColor : TColor; FTextColor : TColor; protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property ExtraWidth : integer read FExtraWidth write FExtraWidth; property MenuColor : TColor read FMenuColor write FMenuColor; property ItemSelectedColor : TColor read FItemSelectedColor write FItemSelectedColor; property MenuBorderColor : TColor read FMenuBorderColor write FMenuBorderColor; property TextColor : TColor read FTextColor write FTextColor; end; procedure Register; implementation procedure Register; begin RegisterComponents('Voyager', [TFlatPopupMenu]); end; { TFlatPopupMenu } constructor TFlatPopupMenu.Create(AOwner: TComponent); begin inherited Create(AOwner); MenuAnimation := [maNone]; AutoPopup := true; OwnerDraw := true; OnPopup := MenuPopup; MenuColor := RGB(240, 240, 240); ItemSelectedColor := RGB(110, 131, 184); MenuBorderColor := RGB(240, 240, 240); end; procedure TFlatPopupMenu.DrawMenu(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); var cTemp: TCanvas; sText: String; mWnd: HWND; rMenu: TRect; begin sText := TMenuItem(Sender).Caption; with ACanvas do begin // Clear if odSelected in State then begin Brush.Color := FItemSelectedColor;//RGB(110, 131, 184); Pen.Color := RGB(47, 60, 93); end else begin Brush.Color := FMenuColor;//RGB(240, 240, 240); Pen.Color := FMenuColor;//RGB(240, 240, 240); end; Rectangle(ARect); if sText = '-' then begin // Draw line ACanvas.Pen.Color := RGB(0, 0, 0); MoveTo(ARect.Left, ARect.Top + ((ARect.Bottom - ARect.Top) div 2)); LineTo(ARect.Right, ARect.Top + ((ARect.Bottom - ARect.Top) div 2)); end else begin // Draw text ACanvas.Font.Color := FTextColor; Inc(ARect.Left, 12); DrawText(Handle, PChar(sText), Length(sText), ARect, DT_LEFT or DT_VCENTER or DT_SINGLELINE); end; end; // menu border mWnd := WindowFromDC(ACanvas.Handle); //SendMessage(mWnd, WM_NCPAINT, 1, 0); if mWnd <> Self.Handle then begin cTemp := TCanvas.Create(); cTemp.Handle := GetDC(0); Windows.GetWindowRect(mWnd, rMenu); cTemp.Brush.Color := RGB(20, 20, 20); cTemp.FrameRect(rMenu); InflateRect(rMenu, -1, -1); cTemp.Brush.Color := FMenuBorderColor;//RGB(240, 240, 240); cTemp.FrameRect(rMenu); InflateRect(rMenu, -1, -1); cTemp.FrameRect(rMenu); ReleaseDC(0, cTemp.Handle); cTemp.Free(); end; end; procedure TFlatPopupMenu.MeasureMenu(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); begin Inc(Width, 25); end; procedure TFlatPopupMenu.MenuPopup(Sender: TObject); var i : integer; begin for i := 0 to Items.Count-1 do begin TMenuItem(Items[i]).OnMeasureItem := MeasureMenu; TMenuItem(Items[i]).OnAdvancedDrawItem := DrawMenu; end; end; end.
unit RiffIO; interface implementation end. (* /*----------------------------------------------------------------------------*\ rlefile.c - file handling for RLEAPP \*----------------------------------------------------------------------------*/ // COPYRIGHT: // // (C) Copyright Microsoft Corp. 1993. All rights reserved. // // You have a royalty-free right to use, modify, reproduce and // distribute the Sample Files (and/or any modified version) in // any way you find useful, provided that you agree that // Microsoft has no warranty obligations or liability for any // Sample Application Files which are modified. // #include <windows.h> #include <mmsystem.h> #include "rleapp.h" #include "gmem.h" #include "dib.h" #include "rle.h" /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ #define FOURCC( ch0, ch1, ch2, ch3 ) \ ( (DWORD)(BYTE)(ch0) | ( (DWORD)(BYTE)(ch1) << 8 ) | \ ( (DWORD)(BYTE)(ch2) << 16 ) | ( (DWORD)(BYTE)(ch3) << 24 ) ) #define RIFF_RIFF FOURCC('R','I','F','F') #define RIFF_LIST FOURCC('L','I','S','T') #define RIFF_RLE0 FOURCC('R','L','E','0') #define RIFF_RLEh FOURCC('R','L','E','h') #define RIFF_DIBh FOURCC('D','I','B','h') #define RIFF_WAVh FOURCC('W','A','V','h') #define RIFF_RGBq FOURCC('r','g','b','q') #define RIFF_DIBb FOURCC('D','I','B','b') #define RIFF_WAVb FOURCC('W','A','V','b') #define RIFF_PALb FOURCC('P','A','L','b') #define RIFF_PAD FOURCC('p','a','d','d') #define RIFF_WAVE FOURCC('W','A','V','E') #define RIFF_DATA FOURCC('d','a','t','a') #define RIFF_FMT FOURCC('f','m','t',' ') typedef struct { DWORD dwType; DWORD dwSize; } RIFF, *PRIFF, FAR *LPRIFF; typedef struct { DWORD dwRiff; DWORD dwSize; DWORD dwType; } RIFFHDR; typedef struct { DWORD dwFlags; DWORD dwNumFrames; DWORD dwMaxBuffer; DWORD dwFrameRate; } RLEHDR; /* stats about RLE frames */ /* flags for _lseek */ #define SEEK_CUR 1 #define SEEK_END 2 #define SEEK_SET 0 DWORD FAR PASCAL lread(int fh, LPVOID p, DWORD len); DWORD FAR PASCAL lwrite(int fh, LPVOID p, DWORD len); DWORD FAR PASCAL lseek(int fh, DWORD off, WORD w); int FAR PASCAL lopen(LPSTR sz, WORD acc); int FAR PASCAL lclose(int fh); #define LWRITE(fh, p, len) {if (lwrite(fh,p,len) != (len)) goto error;} #define LREAD(fh, p, len) {if (lread(fh,p,len) != (len)) goto error;} #define WRITERIFF(fh,dwType,p,len) {if (WriteRiff(fh,dwType,p,len) != (len)) goto error;} /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ DWORD WriteRiff(int fh, DWORD dwType, LPVOID p, DWORD dwSize) { RIFF riff; riff.dwType = dwType; riff.dwSize = dwSize; LWRITE(fh, &riff, sizeof(riff)); if (p != NULL) LWRITE(fh, p, (dwSize+1)&~1); return dwSize; error: return (UINT)-1L; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ DWORD WriteList(int fh, DWORD dwList, DWORD dwType) { DWORD off; RIFFHDR riff; if (!(dwList == RIFF_RIFF || dwList == RIFF_LIST)) return (UINT)-1; off = lseek(fh, 0L, SEEK_CUR); riff.dwRiff = dwList; riff.dwSize = 0L; riff.dwType = dwType; LWRITE(fh, &riff, sizeof(riff)); return off; error: return (UINT)-1L; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL EndList(int fh, DWORD offList) { DWORD off; DWORD dwLen; off = lseek(fh, 0L, SEEK_CUR); dwLen = off - offList - sizeof(RIFF); lseek(fh, offList+sizeof(DWORD), SEEK_SET); LWRITE(fh, &dwLen, sizeof(DWORD)); lseek(fh, off, SEEK_SET); return TRUE; error: return FALSE; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL OpenRiffFile(LPSTR szFile, int iFrame, DWORD dwType) { unsigned fh; HANDLE hdib; BITMAPINFOHEADER bi; RGBQUAD argbq[256]; LPBITMAPINFOHEADER lpbi; DWORD off; RIFF riff; RIFFHDR riffhdr; LPSTR pbits; LPSTR prgb; int wWaveRead = 0; DWORD dwWaveSize = 0L; // Total size of all wave data int i; LPWAVEHDR pwh; RLEHDR rlehdr; totFrames = 0; // length of movie; displayed on status bar fh = lopen(szFile, OF_READ); if (fh == -1) return FALSE; LREAD(fh,(LPVOID)&riffhdr,sizeof(riffhdr)); if (riffhdr.dwRiff != RIFF_RIFF || riffhdr.dwType != dwType) goto exit; rlehdr.dwFlags = 0L; rlehdr.dwNumFrames = 0L; rlehdr.dwMaxBuffer = 0L; rlehdr.dwFrameRate = 0L; if (pWaveFormat) // Free the movie's wave header GFreePtr(pWaveFormat); if (pwhMovie) // Free the movie's wave data GFreePtr(pwhMovie); pWaveFormat = NULL; pwhMovie = NULL; for (;;) { if (lread(fh,(LPVOID)&riff,sizeof(riff)) != sizeof(riff)) break; off = lseek(fh, 0L, SEEK_CUR); switch (riff.dwType) { case RIFF_RLEh: LREAD(fh,(LPVOID)&rlehdr,sizeof(RLEHDR)); totFrames = (WORD)rlehdr.dwNumFrames; break; case RIFF_DIBh: LREAD(fh,(LPVOID)&bi,sizeof(bi)); if (bi.biClrUsed == 0) bi.biClrUsed = 1 << bi.biBitCount; bi.biSizeImage = (DWORD)DIBWIDTHBYTES(bi) * bi.biHeight; if (riff.dwSize > sizeof(bi)) LREAD(fh,(LPVOID)argbq,bi.biClrUsed*sizeof(RGBQUAD)); break; case RIFF_RGBq: LREAD(fh,(LPVOID)argbq,bi.biClrUsed*sizeof(RGBQUAD)); break; case RIFF_DIBb: hdib = GAlloc(bi.biSize+bi.biClrUsed*sizeof(RGBQUAD)+riff.dwSize); if (!hdib) goto errormem; lpbi = GLock(hdib); prgb = (LPSTR)lpbi + bi.biSize; pbits = (LPSTR)prgb + bi.biClrUsed * sizeof(RGBQUAD); bi.biSizeImage = riff.dwSize; MemCopy((LPVOID)lpbi,(LPVOID)&bi,sizeof(bi)); MemCopy((LPVOID)prgb,(LPVOID)argbq,(int)bi.biClrUsed*sizeof(RGBQUAD)); LREAD(fh,pbits,riff.dwSize); InsertFrame(hdib,iFrame,TRUE); if (iFrame == -1) // What frame was that? i = numFrames - 1; else i = iFrame; if (iFrame >= 0) iFrame++; break; case RIFF_WAVh: pWaveFormat = GAllocPtr(riff.dwSize); if (pWaveFormat == NULL) goto errormem; LREAD(fh,(LPVOID)pWaveFormat,(WORD)riff.dwSize); gSamplesPerSec = pWaveFormat->nSamplesPerSec; gChannels = pWaveFormat->nChannels; break; case RIFF_WAVb: if (pwhMovie) { pwh = GReAllocPtr(pwhMovie, sizeof(WAVEHDR)+pwhMovie->dwBufferLength+riff.dwSize); if (!pwh) { pwh = GAllocPtr(sizeof(WAVEHDR)+pwhMovie->dwBufferLength+riff.dwSize); if (!pwh) goto errormem; MemCopy(pwh,pwhMovie,pwhMovie->dwBufferLength); GFreePtr(pwhMovie); } pwhMovie = pwh; pwhMovie->lpData = (LPVOID)(pwhMovie+1); } else { pwh = GAllocPtr(riff.dwSize + sizeof(WAVEHDR)); if (!pwh) goto errormem; pwh->lpData = (LPVOID)(pwh+1); pwh->dwBufferLength = 0; pwh->dwBytesRecorded = 0; pwh->dwUser = 0; pwh->dwFlags = WHDR_DONE; pwh->dwLoops = 0; pwhMovie = pwh; } LREAD(fh, (BYTE huge * )(pwh->lpData) + pwh->dwBufferLength, riff.dwSize); dwWaveSize += riff.dwSize; pwh->dwBufferLength += riff.dwSize; break; case RIFF_LIST: // // we want to desend into all list chunks, so treat // the list chunk as a small bogus chunk. // riff.dwSize = sizeof(DWORD); // LIST form type. break; default: case RIFF_PALb: case RIFF_PAD: // ignore break; } lseek(fh, off + (riff.dwSize+1)&~1L, SEEK_SET); if (WinYield()) break; } exit1: if ((rlehdr.dwFrameRate > 1*FramesSecScale) && (rlehdr.dwFrameRate < 32*FramesSecScale)) FramesSec = rlehdr.dwFrameRate; else if (dwWaveSize && numFrames) FramesSec = muldiv32(numFrames,(long)gChannels*gSamplesPerSec*FramesSecScale,dwWaveSize); else FramesSec = 15 * FramesSecScale; /* HACK!! Remember the start and size of the wave data */ if (pwhMovie) { glpData = pwhMovie->lpData; gdwBufferLength = pwhMovie->dwBufferLength; } lclose(fh); return TRUE; errormem: ErrMsg("Out of Memory Error"); goto exit1; error: ErrMsg("Read Error"); goto exit1; exit: lclose(fh); return FALSE; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL OpenRl0File(LPSTR szFile, int iFrame) { return OpenRiffFile(szFile, iFrame, RIFF_RLE0); } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ void SaveRl0File(LPSTR szFile,int startFrame,int nFrames) { unsigned fh; int i; HANDLE hdib; HPALETTE hpal; int curSave = curFrame; LPBITMAPINFOHEADER lpbi; BITMAPINFOHEADER bi; #if 0 RIFF riff; #endif RIFFHDR riffhdr; RLEHDR rlehdr; fh = lopen(szFile, OF_READWRITE|OF_CREATE); if (fh == -1) { ErrMsg("Error Creating File"); return; } StartWait(); // // write the RIFF header. // riffhdr.dwRiff = RIFF_RIFF; riffhdr.dwType = RIFF_RLE0; riffhdr.dwSize = 0; // patch later LWRITE(fh, (LPVOID)&riffhdr, sizeof(RIFFHDR)); // // write the RLE header. // rlehdr.dwFlags = 0L; rlehdr.dwNumFrames = (DWORD)numFrames; rlehdr.dwMaxBuffer = 0L; rlehdr.dwFrameRate = FramesSec; for (i=startFrame; i<startFrame+nFrames; i++) { lpbi = GLock(FrameRle(i)); rlehdr.dwMaxBuffer = max(rlehdr.dwMaxBuffer,lpbi->biSizeImage); } WriteRiff(fh, RIFF_RLEh, (LPVOID)&rlehdr, sizeof(RLEHDR)); #if 0 riff.dwType = RIFF_RLEh; riff.dwSize = sizeof(RLEHDR); LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, (LPVOID)&rlehdr, sizeof(RLEHDR)); #endif // // write the WAV header. // if (pWaveFormat) { WriteRiff( fh, RIFF_WAVh, (LPVOID)pWaveFormat, GSize(HIWORD(pWaveFormat))); #if 0 riff.dwType = RIFF_WAVh; riff.dwSize = GSize(HIWORD(pWaveFormat)); //!!! LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, (LPVOID)pWaveFormat, (WORD)riff.dwSize); #endif } // // write the WAV bits? // if (pwhMovie) { pwhMovie->dwBufferLength = gdwBufferLength; pwhMovie->lpData = glpData; WriteRiff(fh, RIFF_WAVb, pwhMovie->lpData, ALIGNULONG(pwhMovie->dwBufferLength)); #if 0 riff.dwType = RIFF_WAVb; riff.dwSize = pwhMovie->dwBufferLength; riff.dwSize = ALIGNULONG(riff.dwSize); LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, pwhMovie->lpData, riff.dwSize); #endif } // // write all the frames. // for (i=startFrame; i<startFrame+nFrames; i++) { hdib = FrameRle(i); hpal = FramePalette(i); lpbi = GLock(hdib); // // write a DIB header. (if needed) // if (i==startFrame || bi.biWidth != lpbi->biWidth || bi.biHeight != lpbi->biHeight || bi.biCompression != lpbi->biCompression) { bi = *lpbi; WriteRiff(fh, RIFF_DIBh, (LPVOID)lpbi, lpbi->biSize); #if 0 riff.dwType = RIFF_DIBh; riff.dwSize = lpbi->biSize; LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, (LPVOID)lpbi, (WORD)riff.dwSize); #endif } // // write a palette if needed // if (!(FrameFlags(i) & F_PALSHARED)) { SetDibUsage(hdib,hpal,DIB_RGB_COLORS); WriteRiff(fh, RIFF_RGBq, (LPSTR)lpbi+lpbi->biSize, lpbi->biClrUsed * sizeof(RGBQUAD)); #if 0 riff.dwType = RIFF_RGBq; riff.dwSize = lpbi->biClrUsed * sizeof(RGBQUAD); LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, (LPSTR)lpbi+lpbi->biSize, (WORD)riff.dwSize); #endif SetDibUsage(hdib,hpal,DIB_PAL_COLORS); } // // write the DIB bits // WriteRiff(fh, RIFF_DIBb, DibXY(lpbi,0,0), lpbi->biSizeImage); #if 0 riff.dwType = RIFF_DIBb; riff.dwSize = lpbi->biSizeImage; LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, DibXY(lpbi,0,0), riff.dwSize); #endif ShowFrame(i); if (WinYield()) break; } // // patch the RIFFHDR // riffhdr.dwRiff = RIFF_RIFF; riffhdr.dwType = RIFF_RLE0; riffhdr.dwSize = lseek(fh, 0L, SEEK_CUR) - sizeof(RIFF); lseek(fh, 0L, SEEK_SET); LWRITE(fh, (LPVOID)&riffhdr, sizeof(RIFFHDR)); lclose(fh); ShowFrame(curSave); EndWait(); return; error: lclose(fh); ShowFrame(curSave); EndWait(); ErrMsg("Error Writing file"); return; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL SaveWavFile(LPSTR szFile,int startFrame,int nFrames) { unsigned fh; #if 0 DWORD dwSize; RIFF riff; #endif RIFFHDR riffhdr; if (!pWaveFormat || !pwhMovie) return FALSE; fh = lopen(szFile, OF_READWRITE|OF_CREATE); if (fh == -1) { ErrMsg("Error Creating File"); return FALSE; } StartWait(); // // write the RIFF header. // riffhdr.dwRiff = RIFF_RIFF; riffhdr.dwType = RIFF_WAVE; riffhdr.dwSize = 0; // patch it later LWRITE(fh, (LPVOID)&riffhdr, sizeof(RIFFHDR)); // // write the WAV header. // WriteRiff(fh, RIFF_FMT, (LPVOID)pWaveFormat, GSize(HIWORD(pWaveFormat))); #if 0 riff.dwType = RIFF_FMT; riff.dwSize = GSize(HIWORD(pWaveFormat)); //!!! LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, (LPVOID)pWaveFormat, (WORD)riff.dwSize); #endif // // write the WAV bits? // pwhMovie->dwBufferLength = gdwBufferLength; pwhMovie->lpData = glpData; WriteRiff(fh, RIFF_DATA, pwhMovie->lpData, pwhMovie->dwBufferLength); #if 0 riff.dwSize = pwhMovie->dwBufferLength; riff.dwType = RIFF_DATA; LWRITE(fh, (LPVOID)&riff, sizeof(RIFF)); LWRITE(fh, pwhMovie->lpData, dwSize); // // word align // if (riff.dwSize & 1) LWRITE(fh, (LPVOID)&riff, 1); #endif // // patch the RIFFHDR // riffhdr.dwRiff = RIFF_RIFF; riffhdr.dwType = RIFF_WAVE; riffhdr.dwSize = lseek(fh, 0L, SEEK_CUR) - sizeof(RIFF); lseek(fh, 0L, SEEK_SET); LWRITE(fh, (LPVOID)&riffhdr, sizeof(RIFFHDR)); lclose(fh); EndWait(); return TRUE; error: ErrMsg("Error writing file"); lclose(fh); EndWait(); return FALSE; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ #define BUFSIZE 2048 #define BUFALIGN(ul) (((ul)+BUFSIZE-1) & ~(BUFSIZE-1)) /*----------------------------------------------------------------------------*\ // ********************************************************************* // BAD CODE WARNING: // ********************************************************************* // // This code requires that the header be the first thing // followed by data. THIS IS NOT CORRECT!!!!!! // This code will be fixed in a next version. // // Do not use this code!!!!! // \*----------------------------------------------------------------------------*/ BOOL OpenWavFile(LPSTR szFile) { unsigned fh; RIFF riff; RIFFHDR riffhdr; LPWAVEHDR pwh; DWORD dwWaveSize; fh = lopen(szFile, OF_READ); if (fh == -1) return FALSE; // // read the RIFF header. // LREAD(fh, (LPVOID)&riffhdr, sizeof(RIFFHDR)); if (riffhdr.dwRiff != RIFF_RIFF || riffhdr.dwType != RIFF_WAVE) { lclose(fh); return FALSE; } if (numFrames == 0) { ErrMsg("Can't Open Wave File onto Empty Movie"); lclose(fh); return FALSE; } StartWait(); // // read the WAVE header // LREAD(fh, (LPVOID)&riff, sizeof(RIFF)); if (riff.dwType != RIFF_FMT) { ErrMsg("File Corrupted"); goto openwave_barf; } /* Destroy the current waves of this movie */ if (pWaveFormat) GFreePtr(pWaveFormat); if (pwhMovie) GFreePtr(pwhMovie); pWaveFormat = NULL; pwhMovie = NULL; /* Load the wave header in */ pWaveFormat = GAllocPtr(riff.dwSize); if (pWaveFormat == NULL) { ErrMsg("Out of Memory Error"); goto openwave_barf; } LREAD(fh,(LPVOID)pWaveFormat,(WORD)riff.dwSize); gSamplesPerSec = pWaveFormat->nSamplesPerSec; gChannels = pWaveFormat->nChannels; // // read the DATA header // LREAD(fh, (LPVOID)&riff, sizeof(RIFF)); if (riff.dwType != RIFF_DATA) { ErrMsg("File Corrupted"); goto openwave_barf; } // // read the actual wave data // pwh = GAllocPtr(riff.dwSize + sizeof(WAVEHDR)); if (!pwh) { ErrMsg("Out of Memory Error"); goto openwave_barf; } pwh->lpData = (LPVOID)(pwh+1); pwh->dwBufferLength = riff.dwSize; pwh->dwBytesRecorded = 0; pwh->dwUser = 0; pwh->dwFlags = WHDR_DONE; pwh->dwLoops = 0; LREAD(fh,pwh->lpData,riff.dwSize); dwWaveSize = pwh->dwBufferLength; if (dwWaveSize && numFrames) FramesSec = muldiv32(numFrames,(long)gChannels*gSamplesPerSec*FramesSecScale,dwWaveSize); else FramesSec = 15 * FramesSecScale; pwhMovie = pwh; glpData = pwh->lpData; gdwBufferLength = pwh->dwBufferLength; lclose(fh); EndWait(); return TRUE; error: openwave_barf: lclose(fh); EndWait(); return FALSE; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL NEAR OpenRleFile(LPSTR szFile, int iFrame) { unsigned fh; HANDLE hdib; BOOL fValidDibRead = FALSE; totFrames = 0; fh = lopen(szFile, OF_READ); if (fh == -1) return FALSE; while (hdib = OpenDIB((LPSTR)MAKEINTATOM(fh))) { fValidDibRead = TRUE; InsertFrame(hdib, iFrame, TRUE); if (iFrame >= 0) iFrame++; if (WinYield()) break; } lclose(fh); FramesSec = 15 * FramesSecScale; return fValidDibRead; } /*----------------------------------------------------------------------------*\ Load in a whole slew of frames one at a time if they are called foo000.dib foo001.dib foo002.dib ...etc.... in this case you would use a filename of foo%03d.dib to load in this sequence. The sequence can start with 0 or 1, and go arbitrarily high as long as every filename can be generated with some printf statement. \*----------------------------------------------------------------------------*/ BOOL OpenFrames(LPSTR szFrame, int iFrame) { char buf[80]; int i; BOOL fFileFound = FALSE; totFrames = 0; // length of movie; displayed on status bar // or wsprintf in the "load a slew of frames" won't work AnsiLower(szFrame); for (i=0; (wsprintf(buf,szFrame,i) && (fFileFound = OpenRleFile(buf,iFrame)) && !WinYield()) || i==0; i++) ; return fFileFound; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ BOOL OpenMovieFile(LPSTR szFrame, int iFrame) { BOOL f; StartWait(); fLoading++; f = OpenWavFile(szFrame) || OpenRl0File(szFrame, iFrame) || OpenRleFile(szFrame, iFrame) || OpenFrames (szFrame, iFrame); fLoading--; EndWait(); if (!f) // We never did load a valid file! ErrMsg("File Open Error"); return f; } /*----------------------------------------------------------------------------*\ \*----------------------------------------------------------------------------*/ void SaveRleFile(LPSTR szFile,int startFrame,int nFrames) { unsigned fh; int i; HANDLE hdib; HPALETTE hpal; int curSave = curFrame; fh = lopen(szFile, OF_READWRITE|OF_CREATE); if (fh == -1) return; if (startFrame > 0) // Validate the first frame of movie RenderFrame(startFrame); StartWait(); for (i=startFrame; i<startFrame+nFrames; i++) { hdib = FrameDib(i); hpal = FramePalette(i); SetDibUsage(hdib,hpal,DIB_RGB_COLORS); WriteDIB((LPSTR)MAKEINTATOM(fh),hdib); SetDibUsage(hdib,hpal,DIB_PAL_COLORS); ShowFrame(i); if (WinYield()) break; } PurgeFrames(); ShowFrame(curSave); EndWait(); lclose(fh); return; } /***************************************************************************\ * * routines for file I/O * \***************************************************************************/ DWORD FAR PASCAL lread(int fh, LPVOID p, DWORD len) { return mmioRead((HMMIO)fh, p, len); } DWORD FAR PASCAL lwrite(int fh, LPVOID p, DWORD len) { return mmioWrite((HMMIO)fh, p, len); } DWORD FAR PASCAL lseek(int fh, DWORD off, WORD w) { return mmioSeek((HMMIO)fh,off,w); } int FAR PASCAL lopen(LPSTR sz, WORD acc) { HMMIO hmmio; hmmio = mmioOpen(sz, NULL, acc | MMIO_ALLOCBUF); if (hmmio == NULL) return -1; return (int)hmmio; } int FAR PASCAL lclose(int fh) { return mmioClose((HMMIO)fh, 0); } *)
unit NtUtils.ErrorMsg; interface uses Ntapi.ntdef; // Converts common error codes to strings, for example: // 1314 => "ERROR_PRIVILEGE_NOT_HELD" // $C00000BB => "STATUS_NOT_SUPPORTED" // Returns empty string if the name is not found. function NtxpWin32ErrorToString(Code: Cardinal): String; function NtxpStatusToString(Status: NTSTATUS): String; // The same as above, but on unknown errors returns their decimal/hexadecimal // representations. function NtxWin32ErrorToString(Code: Cardinal): String; function NtxStatusToString(Status: NTSTATUS): String; // Converts common error codes to their short descriptions, for example: // 1314 => "Privilege not held" // $C00000BB => "Not supported" // Returns empty string if the name is not found. function NtxWin32ErrorDescription(Code: Cardinal): String; function NtxStatusDescription(Status: NTSTATUS): String; // Retrieves a full description of a native error. function NtxFormatErrorMessage(Status: NTSTATUS): String; implementation uses Ntapi.ntldr, Winapi.WinBase, System.SysUtils, DelphiUtils.Strings; {$R 'NtUtils.ErrorMsg.res' 'NtUtils.ErrorMsg.rc'} const { The resource file contains the names of some common Win32 Errors and NTSTATUS values. To fit into the format of the .rc file each category (i.e. Win32, NT Success, NT Information, NT Warning, and NT Error) was shifted, so it starts from the values listed above. Each group of values can contain the maximum count of RC_STATUS_EACH_MAX - 1 items to make sure they don't overlap. } RC_STATUS_SIFT_WIN32 = $8000; RC_STATUS_SIFT_NT_SUCCESS = $9000; // See ERROR_SEVERITY_SUCCESS RC_STATUS_SIFT_NT_INFO = $A000; // See ERROR_SEVERITY_INFORMATIONAL RC_STATUS_SIFT_NT_WARNING = $B000; // See ERROR_SEVERITY_WARNING RC_STATUS_SIFT_NT_ERROR = $C000; // See ERROR_SEVERITY_ERRORW RC_STATUS_EACH_MAX = $1000; function NtxpWin32ErrorToString(Code: Cardinal): String; var Buf: PWideChar; begin // Make sure the error is within the range if Code >= RC_STATUS_EACH_MAX then Exit(''); // Shift it to obtain the resource index Code := Code or RC_STATUS_SIFT_WIN32; // Extract the string representation SetString(Result, Buf, LoadStringW(HInstance, Code, Buf)); end; function NtxpStatusToString(Status: NTSTATUS): String; var ResIndex: Cardinal; Buf: PWideChar; begin // Clear high bits that indicate status category ResIndex := Status and $3FFFFFFF; // Make sure the substatus is within the range if ResIndex >= RC_STATUS_EACH_MAX then Exit(''); // Shift it to obtain the resource index case (Status shr 30) of 0: ResIndex := ResIndex or RC_STATUS_SIFT_NT_SUCCESS; 1: ResIndex := ResIndex or RC_STATUS_SIFT_NT_INFO; 2: ResIndex := ResIndex or RC_STATUS_SIFT_NT_WARNING; 3: ResIndex := ResIndex or RC_STATUS_SIFT_NT_ERROR; else Assert(False); end; // Extract the string representation SetString(Result, Buf, LoadStringW(HInstance, ResIndex, Buf)); end; function NtxWin32ErrorToString(Code: Cardinal): String; begin Result := NtxpWin32ErrorToString(Code); if Result = '' then Result := IntToStr(Code); end; function NtxStatusToString(Status: NTSTATUS): String; begin // Check if it's a fake status based on a Win32 error. // In this case use "ERROR_SOMETHING_WENT_WRONG" messages. if NT_NTWIN32(Status) then Result := NtxpWin32ErrorToString(WIN32_FROM_NTSTATUS(Status)) else Result := NtxpStatusToString(Status); if Result = '' then Result := IntToHexEx(Status, 8); end; function NtxWin32ErrorDescription(Code: Cardinal): String; begin // We query the code name which looks like "ERROR_SOMETHING_WENT_WRONG" // and prettify it so it appears like "Something went wrong" Result := NtxpWin32ErrorToString(Code); if Result = '' then Exit; Result := PrettifyCapsUnderscore('ERROR_', Result); end; function NtxStatusDescription(Status: NTSTATUS): String; begin if NT_NTWIN32(Status) then begin // This status was converted from a Win32 error. Result := NtxWin32ErrorDescription(WIN32_FROM_NTSTATUS(Status)); end else begin // We query the status name which looks like "STATUS_SOMETHING_WENT_WRONG" // and prettify it so it appears like "Something went wrong" Result := NtxpStatusToString(Status); if Result = '' then Exit; Result := PrettifyCapsUnderscore('STATUS_', Result); end; end; function NtxFormatErrorMessage(Status: NTSTATUS): String; var StartFrom: Integer; begin if NT_NTWIN32(Status) then begin // This status was converted from a Win32 errors. Result := SysErrorMessage(WIN32_FROM_NTSTATUS(Status)); end else begin // Get error message from ntdll Result := SysErrorMessage(Status, hNtdll); // Fix those messages which are formatted like: // {Asdf} // Asdf asdf asdf... if (Length(Result) > 0) and (Result[Low(Result)] = '{') then begin StartFrom := Pos('}'#$D#$A, Result); if StartFrom >= Low(Result) then Delete(Result, Low(Result), StartFrom + 2); end; end; if Result = '' then Result := '<No description available>'; end; end.
unit float_expression_lib; interface uses classes,expression_lib; type TFloatExpression=class(TAbstractExpression) protected procedure MakeEvaluationTree; override; procedure PlusMinus(s: string; var treeNode: TEvaluationTreeNode); procedure MulDiv(s: string; var treeNode: TEvaluationTreeNode); procedure Pow(s: string; var treeNode: TEvaluationTreeNode); procedure BracketsAndFuncs(s: string; var treeNode: TEvaluationTreeNode); public function getValue: Real; override; function getVariantValue: Variant; override; end; TStandAloneFloatExpression = class (TFloatExpression) public constructor Create(Owner: TComponent); override; end; implementation uses SysUtils, StrUtils; procedure TFloatExpression.PlusMinus(s: string; var treeNode: TEvaluationTreeNode); //treenode - это var-переменная, в которую мы должны положить адрес созданного узла var i,last_plus: Integer; brCount: Integer; children: array of TEvaluationTreeNode; signCount: Integer; temp: TEvaluationTreeNode; isNeg: boolean; begin try brCount:=0; last_plus:=1; isNeg:=false; signCount:=0; temp:=nil; for i:=1 to Length(s) do begin if brCount=0 then begin if ((s[i]='+') or (s[i]='-')) and ((i<=1) or (uppercase(s[i-1])<>'E')) then begin if i>1 then begin SetLength(children,Length(children)+1); MulDiv(MidStr(s,last_plus,i-last_plus),temp); if isNeg then begin children[Length(children)-1]:=TUnaryMinusNode.Create(nil); //позже закрепим children[Length(children)-1].InsertComponent(temp); end else children[length(children)-1]:=temp; end; temp:=nil; last_plus:=i+1; //сразу за плюсом isNeg:=(s[i]='-'); inc(signCount); end end; if s[i]='(' then inc(brCount) else if s[i]=')' then dec(brCount); if brCount<0 then Raise ESyntaxErr.CreateFMT(TooManyClosingBracketsStr,[s]); end; if signCount=0 then MulDiv(s,treeNode) else begin SetLength(children,Length(children)+1); MulDiv(RightStr(s,Length(s)-last_plus+1),temp); if isNeg then begin children[Length(children)-1]:=TUnaryMinusNode.Create(nil); //позже закрепим children[Length(children)-1].InsertComponent(temp); end else children[length(children)-1]:=temp; temp:=nil; //вот, все "дети" в сборе! treeNode:=TAdditionNode.Create(nil); //позже нас прикрепят, если надо for i:=0 to Length(children)-1 do begin treeNode.InsertComponent(children[i]); children[i]:=nil; end; end; finally for i:=0 to Length(children)-1 do children[i].Free; temp.Free; end; end; procedure TFloatExpression.MulDiv(s: string; var treeNode: TEvaluationTreeNode); var i,last_plus: Integer; brCount: Integer; children: array of TEvaluationTreeNode; temp: TEvaluationTreeNode; isNeg: boolean; begin // try brCount:=0; last_plus:=1; isNeg:=false; for i:=1 to Length(s) do begin if brCount=0 then begin if (s[i]='*') or (s[i]='/') then begin SetLength(children,Length(children)+1); Pow(MidStr(s,last_plus,i-last_plus),temp); if isNeg then begin children[Length(children)-1]:=TInverseNode.Create(nil); //позже закрепим children[Length(children)-1].InsertComponent(temp); end else children[length(children)-1]:=temp; last_plus:=i+1; //сразу за плюсом isNeg:=(s[i]='/'); end end; if s[i]='(' then inc(brCount) else if s[i]=')' then dec(brCount); if brCount<0 then Raise EsyntaxErr.CreateFMT(TooManyClosingBracketsStr,[s]); end; if Length(children)=0 then Pow(s,treeNode) else begin treeNode:=TMultiplicationNode.Create(nil); //позже нас прикрепят, если надо for i:=0 to Length(children)-1 do begin treeNode.InsertComponent(children[i]); children[i]:=nil; end; Pow(RightStr(s,Length(s)-last_plus+1),temp); if isNeg then begin children[0]:=TInverseNode.Create(nil); children[0].InsertComponent(temp); end else children[0]:=temp; treeNode.InsertComponent(children[0]); children[0]:=nil; end; (* finally for i:=0 to Length(children)-1 do children[i].Free; end; *) end; procedure TFloatExpression.Pow(s: string; var treeNode: TEvaluationTreeNode); var i: Integer; brCount: Integer; term: TEvaluationTreeNode; begin brCount:=0; for i:=1 to Length(s) do begin if (s[i]='^') and (brCount=0) then begin treeNode:=TPowNode.Create(nil); BracketsAndFuncs(LeftStr(s,i-1),term); treeNode.InsertComponent(term); BracketsAndFuncs(RightStr(s,Length(s)-i),term); treeNode.insertComponent(term); Exit; end; if s[i]='(' then inc(brCount); if s[i]=')' then dec(brCount); if brCount<0 then Raise EsyntaxErr.CreateFMT(TooManyClosingBracketsStr,[s]); end; //если выполнение дошло досюда, значит, так и не встретили символа ^ BracketsAndFuncs(s,treeNode); end; procedure TFloatExpression.BracketsAndFuncs(s: string; var treeNode: TEvaluationTreeNode); var f: string; i: Integer; temp: TEvaluationTreeNode; begin if Length(s)=0 then raise ESyntaxErr.Create(EmptyStringErrStr); if s[Length(s)]=')' then begin if s[1]='(' then PlusMinus(MidStr(s,2,Length(s)-2),treeNode) else begin for i:=2 to Length(s)-1 do if s[i]='(' then begin f:=LeftStr(s,i-1); treeNode:=TMathFuncNode.Create(f,nil); PlusMinus(MidStr(s,i+1,Length(s)-i-1),temp); treeNode.InsertComponent(temp); Exit; end; Raise ESyntaxErr.Create(TooManyClosingBracketsStr); end; end else ConstsAndVars(s,treeNode); end; function TFloatExpression.getValue: Real; begin if fchanged then MakeEvaluationTree; if fCorrect then begin Assert(Assigned(fEvaluationTreeRoot),EmptyEvaluationTreeErrStr); if fworking then Raise Exception.CreateFMT(CircularReferenceErrStr,[fstring]); fworking:=true; Result:=fEvaluationTreeRoot.getValue; fworking:=false; end else Raise Exception.Create(fLastErrorMsg); end; procedure TFloatExpression.MakeEvaluationTree; begin FreeAndNil(fEvaluationTreeRoot); //все дерево целиком сносится try PlusMinus(fstring,fEvaluationTreeRoot); fcorrect:=true; fIndependent:=fEvaluationTreeRoot.isIndependent; except on Ex: ESyntaxErr do begin fLastErrorMsg:=Ex.message; fcorrect:=false; end; else raise; end; fchanged:=false; end; function TFloatExpression.getVariantValue: Variant; begin Result:=getValue; end; (* TStandAloneFloatExpression *) constructor TStandAloneFloatExpression.Create(Owner: TComponent); begin inherited Create(Owner); SetSubComponent(false); end; initialization RegisterClasses([TFloatExpression, TStandAloneFloatExpression]); end.
unit ScrollListBox; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls; type TScrollListBox = class(TListBox) private FHorizontalWidth: Integer; procedure SetHorizontalWidth(const Value: Integer); { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } property HorizontalWidth : Integer read FHorizontalWidth write SetHorizontalWidth; end; procedure Register; implementation uses Winapi.Windows, Messages; procedure Register; begin RegisterComponents('componenteOW', [TScrollListBox]); end; { TScrollListBox } procedure TScrollListBox.SetHorizontalWidth(const Value: Integer); begin FHorizontalWidth := Value; SendMessage(Handle,LB_SETHORIZONTALEXTENT,Value, 0); end; end.
unit pang_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,kabuki_decript,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,oki6295,sound_engine,eeprom; function iniciar_pang:boolean; implementation const //Pang pang_rom:array[0..1] of tipo_roms=( (n:'pang6.bin';l:$8000;p:0;crc:$68be52cd),(n:'pang7.bin';l:$20000;p:$10000;crc:$4a2e70f6)); pang_oki:tipo_roms=(n:'bb1.bin';l:$20000;p:0;crc:$c52e5b8e); pang_sprites:array[0..1] of tipo_roms=( (n:'bb10.bin';l:$20000;p:0;crc:$fdba4f6e),(n:'bb9.bin';l:$20000;p:$20000;crc:$39f47a63)); pang_char:array[0..3] of tipo_roms=( (n:'pang_09.bin';l:$20000;p:0;crc:$3a5883f5),(n:'bb3.bin';l:$20000;p:$20000;crc:$79a8ed08), (n:'pang_11.bin';l:$20000;p:$80000;crc:$166a16ae),(n:'bb5.bin';l:$20000;p:$a0000;crc:$2fb3db6c)); //Super Pang spang_rom:array[0..2] of tipo_roms=( (n:'spe_06.rom';l:$8000;p:0;crc:$1af106fb),(n:'spe_07.rom';l:$20000;p:$10000;crc:$208b5f54), (n:'spe_08.rom';l:$20000;p:$30000;crc:$2bc03ade)); spang_oki:tipo_roms=(n:'spe_01.rom';l:$20000;p:0;crc:$2d19c133); spang_sprites:array[0..1] of tipo_roms=( (n:'spj10_2k.bin';l:$20000;p:0;crc:$eedd0ade),(n:'spj09_1k.bin';l:$20000;p:$20000;crc:$04b41b75)); spang_char:array[0..3] of tipo_roms=( (n:'spe_02.rom';l:$20000;p:0;crc:$63c9dfd2),(n:'03.f2';l:$20000;p:$20000;crc:$3ae28bc1), (n:'spe_04.rom';l:$20000;p:$80000;crc:$9d7b225b),(n:'05.g2';l:$20000;p:$a0000;crc:$4a060884)); spang_eeprom:tipo_roms=(n:'eeprom-spang.bin';l:$80;p:0;crc:$deae1291); var mem_rom_op,mem_rom_dat:array[0..$f,0..$3fff] of byte; mem_dat:array[0..$7fff] of byte; rom_nbank,video_bank:byte; obj_ram:array[0..$fff] of byte; vblank,irq_source:byte; pal_bank:word; procedure update_video_pang; var x,y,f,color,nchar:word; atrib:byte; begin fill_full_screen(2,0); for f:=$0 to $7ff do begin atrib:=memoria[$c800+f]; color:=atrib and $7f; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f and $3f; y:=f shr 6; nchar:=(memoria[$d000+(f*2)]+(memoria[$d001+(f*2)] shl 8)) and $7fff; put_gfx_trans_flip(x*8,y*8,nchar,color shl 4,1,0,(atrib and $80)<>0,false); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,512,256,1,0,0,512,256,2); for f:=$7d downto 0 do begin atrib:=obj_ram[(f*$20)+1]; nchar:=obj_ram[f*$20]+((atrib and $e0) shl 3); color:=(atrib and $f) shl 4; x:=obj_ram[(f*$20)+3]+((atrib and $10) shl 4); y:=((obj_ram[(f*$20)+2]+8) and $ff)-8; put_gfx_sprite(nchar,color,false,false,1); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(64,8,384,240,2); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_pang; begin if event.arcade then begin //IN1 if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); //IN2 if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $7f) else marcade.in2:=(marcade.in2 or $80); //IN0 if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); end; end; procedure pang_principal; var frame_m:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; case f of $ef:begin z80_0.change_irq(HOLD_LINE); irq_source:=1; end; $f7:vblank:=8; $ff:begin z80_0.change_irq(HOLD_LINE); vblank:=0; irq_source:=0; end; end; end; update_video_pang; eventos_pang; video_sync; end; end; function pang_getbyte(direccion:word):byte; begin case direccion of $0..$7fff:if z80_0.opcode then pang_getbyte:=memoria[direccion] else pang_getbyte:=mem_dat[direccion]; $8000..$bfff:if z80_0.opcode then pang_getbyte:=mem_rom_op[rom_nbank,direccion and $3fff] else pang_getbyte:=mem_rom_dat[rom_nbank,direccion and $3fff]; $c000..$c7ff:pang_getbyte:=buffer_paleta[(direccion and $7ff)+pal_bank]; $d000..$dfff:if (video_bank<>0) then pang_getbyte:=obj_ram[direccion and $fff] else pang_getbyte:=memoria[direccion]; $c800..$cfff,$e000..$ffff:pang_getbyte:=memoria[direccion]; end; end; procedure pang_putbyte(direccion:word;valor:byte); procedure cambiar_color(pos:word); var tmp_color:byte; color:tcolor; begin tmp_color:=buffer_paleta[$1+pos]; color.r:=pal4bit(tmp_color); tmp_color:=buffer_paleta[pos]; color.g:=pal4bit(tmp_color shr 4); color.b:=pal4bit(tmp_color); set_pal_color(color,pos shr 1); buffer_color[(pos shr 5) and $7f]:=true; end; begin case direccion of 0..$bfff:; $c000..$c7ff:if buffer_paleta[(direccion and $7ff)+pal_bank]<>valor then begin buffer_paleta[(direccion and $7ff)+pal_bank]:=valor; cambiar_color((direccion and $7fe)+pal_bank); end; $c800..$cfff:begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $d000..$dfff:if (video_bank<>0) then obj_ram[direccion and $fff]:=valor else begin memoria[direccion]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; $e000..$ffff:memoria[direccion]:=valor; end; end; function pang_inbyte(puerto:word):byte; begin case (puerto and $ff) of 0:pang_inbyte:=marcade.in0; 1:pang_inbyte:=marcade.in1; 2:pang_inbyte:=marcade.in2; 5:pang_inbyte:=(eeprom_0.readbit shl 7) or vblank or 2 or irq_source; end; end; procedure pang_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $0:begin main_screen.flip_main_screen:=(valor and $4)<>0; pal_bank:=(valor and $20) shl 6; end; $2:rom_nbank:=valor and $f; $5:oki_6295_0.write(valor); $7:video_bank:=valor; $8:if valor<>0 then eeprom_0.set_cs_line(CLEAR_LINE) else eeprom_0.set_cs_line(ASSERT_LINE); //eeprom_cs_w $10:if (valor<>0) then eeprom_0.set_clock_line(CLEAR_LINE) else eeprom_0.set_clock_line(ASSERT_LINE); //eeprom_clock_w $18:eeprom_0.write_bit(valor); //eeprom_serial_w end; end; procedure pang_sound_update; begin oki_6295_0.update; end; //Main procedure reset_pang; begin z80_0.reset; reset_audio; oki_6295_0.reset; eeprom_0.reset; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; rom_nbank:=0; video_bank:=0; pal_bank:=0; vblank:=0; irq_source:=0; end; function iniciar_pang:boolean; var f:byte; memoria_temp:array[0..$4ffff] of byte; ptemp,mem_temp2,mem_temp3,mem_temp4:pbyte; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); procedure convert_chars; begin init_gfx(0,8,8,$8000); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,16*8,$8000*16*8+4,$8000*16*8+0,4,0); convert_gfx(0,0,ptemp,@ps_x[0],@ps_y[0],false,false); end; procedure convert_sprites; begin init_gfx(1,16,16,$800); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,64*8,$800*64*8+4,$800*64*8+0,4,0); convert_gfx(1,0,ptemp,@ps_x[0],@ps_y[0],false,false); end; begin iniciar_pang:=false; llamadas_maquina.bucle_general:=pang_principal; llamadas_maquina.reset:=reset_pang; llamadas_maquina.fps_max:=57.42; iniciar_audio(false); //Pantallas screen_init(1,512,256,true); screen_init(2,512,256,false,true); iniciar_video(384,240); //Main CPU z80_0:=cpu_z80.create(8000000,256); z80_0.change_ram_calls(pang_getbyte,pang_putbyte); z80_0.change_io_calls(pang_inbyte,pang_outbyte); z80_0.init_sound(pang_sound_update); //eeprom eeprom_0:=eeprom_class.create(6,16,'0110','0101','0111'); //Sound Chips //YM2413 --> Falta! oki_6295_0:=snd_okim6295.Create(1000000,OKIM6295_PIN7_HIGH,2); getmem(ptemp,$100000); getmem(mem_temp2,$50000); getmem(mem_temp3,$50000); case main_vars.tipo_maquina of 119:begin //Pang if not(roms_load(oki_6295_0.get_rom_addr,pang_oki)) then exit; //Cargar roms, desencriptar y poner en su sitio las ROMS if not(roms_load(@memoria_temp,pang_rom)) then exit; kabuki_mitchell_decode(@memoria_temp[0],mem_temp2,mem_temp3,8,$01234567,$76543210,$6548,$24); copymemory(@memoria[0],mem_temp2,$8000); copymemory(@mem_dat[0],mem_temp3,$8000); for f:=0 to 7 do copymemory(@mem_rom_op[f,0],@mem_temp2[$10000+(f*$4000)],$4000); for f:=0 to 7 do copymemory(@mem_rom_dat[f,0],@mem_temp3[$10000+(f*$4000)],$4000); //convertir chars fillchar(ptemp^,$100000,$ff); if not(roms_load(ptemp,pang_char)) then exit; convert_chars; //convertir sprites if not(roms_load(ptemp,pang_sprites)) then exit; convert_sprites; end; 183:begin //Super Pang if not(roms_load(oki_6295_0.get_rom_addr,spang_oki)) then exit; //Cargar roms, desencriptar y poner en su sitio las ROMS if not(roms_load(@memoria_temp,spang_rom)) then exit; kabuki_mitchell_decode(@memoria_temp[0],mem_temp2,mem_temp3,$10,$45670123,$45670123,$5852,$43); copymemory(@memoria[0],mem_temp2,$8000); copymemory(@mem_dat[0],mem_temp3,$8000); for f:=0 to $f do copymemory(@mem_rom_op[f,0],@mem_temp2[$10000+(f*$4000)],$4000); for f:=0 to $f do copymemory(@mem_rom_dat[f,0],@mem_temp3[$10000+(f*$4000)],$4000); //convertir chars fillchar(ptemp^,$100000,$ff); if not(roms_load(ptemp,spang_char)) then exit; convert_chars; //convertir sprites if not(roms_load(ptemp,spang_sprites)) then exit; convert_sprites; //load eeprom si no lo esta ya... mem_temp4:=eeprom_0.get_rom_addr; inc(mem_temp4); if mem_temp4^<>0 then if not(roms_load(eeprom_0.get_rom_addr,spang_eeprom)) then exit; end; end; freemem(mem_temp3); freemem(mem_temp2); freemem(ptemp); //final reset_pang; iniciar_pang:=true; end; end.
unit m3StorageInterfaces; {* Интерфейсы для работы с хранилищем. } // Модуль: "w:\common\components\rtl\Garant\m3\m3StorageInterfaces.pas" // Стереотип: "Interfaces" // Элемент модели: "m3StorageInterfaces" MUID: (4720862F0238) {$Include w:\common\components\rtl\Garant\m3\m3Define.inc} interface uses l3IntfUses , l3Interfaces , l3Types , ActiveX , l3Core , l3PureMixIns , m3StorageTypes ; const {* Режимы доступа к хранилищу. } m3_saRead = Tm3StoreAccess(STGM_READ or STGM_SHARE_EXCLUSIVE); {* чтение. } m3_saReadWrite = Tm3StoreAccess(STGM_READWRITE or STGM_SHARE_EXCLUSIVE); {* чтение и запись. } m3_saCreate = Tm3StoreAccess(STGM_READWRITE or STGM_SHARE_EXCLUSIVE or STGM_CREATE); {* чтение и запись или создание. } {* Типы хранилищ. } m3_stNone = Pred(STGTY_STORAGE); {* Не определен. } m3_stStream = STGTY_STREAM; {* Хранилище. } m3_stStorage = STGTY_Storage; {* Поток. } type Pm3StoreType = ^Tm3StoreType; {* Указатель на Tm3StoreType. } Tm3StoreAccess = m3StorageTypes.Tm3StoreAccess; {* тип доступа к хранилищу. } Tm3StoreType = m3_stNone .. m3_stStream; {* Тип элемента хранилища. } Tm3StoreMode = ( {* Режим открытия элемента каталога. } m3_smCreate , m3_smOpen );//Tm3StoreMode Tm3StoreInfo = packed record {* Информация об элементе хранилища. } rPosition: Int64; rStoreType: Tm3StoreType; end;//Tm3StoreInfo Tm3StorageElementID = Integer; Tm3StorageElementInfo = record rInfo: Tm3StoreInfo; rName: Tl3WString; end;//Tm3StorageElementInfo //_ItemType_ = Tm3StorageElementID; Im3StorageElementIDList = interface ['{DDD05DF7-3219-4A89-88A3-AD2A21566229}'] function pm_GetEmpty: Boolean; function pm_GetFirst: Tm3StorageElementID; function pm_GetLast: Tm3StorageElementID; function pm_GetItems(anIndex: Integer): Tm3StorageElementID; function pm_GetCount: Integer; function IndexOf(const anItem: Tm3StorageElementID): Integer; function Add(const anItem: Tm3StorageElementID): Integer; property Empty: Boolean read pm_GetEmpty; property First: Tm3StorageElementID read pm_GetFirst; {* Первый элемент. } property Last: Tm3StorageElementID read pm_GetLast; {* Последний элемент. } property Items[anIndex: Integer]: Tm3StorageElementID read pm_GetItems; default; property Count: Integer read pm_GetCount; {* Число элементов. } end;//Im3StorageElementIDList TStatStg = ActiveX.TStatStg; Tm3StorageType = ( m3_stArchive , m3_stPlugin , m3_stPlain );//Tm3StorageType Mm3StorageIterators_IterateIndexedF_Action = function(const anItem: Tm3StoreInfo; anIndex: Integer): Boolean; {* Тип подитеративной функции для Mm3StorageIterators.IterateIndexedF } Mm3StorageIterators_IterateAllF_Action = function(const anItem: Tm3StorageElementInfo): Boolean; {* Тип подитеративной функции для Mm3StorageIterators.IterateAllF } (* Mm3StorageIterators = interface procedure IterateIndexedF(anAction: Mm3StorageIterators_IterateIndexedF_Action); procedure IterateAllF(anAction: Mm3StorageIterators_IterateAllF_Action); end;//Mm3StorageIterators *) Tm3StoreElementIndex = Tm3StorageElementID; Im3IndexedStorage = interface; Tm3Store = {$IfDef XE4}record{$Else}object{$EndIf} public rStream: IStream; rStorage: Im3IndexedStorage; rResult: HResult; public function AsIStorage: IStorage; end;//Tm3Store Im3IndexedStorage = interface(IUnknown) {* Хранилище с возможностью доступа по индексу. } ['{1962E532-4615-4D4A-9FAC-0F1E3402F097}'] procedure ClearAll; procedure CopyFrom(const aSource: Im3IndexedStorage); function SetIndexParam(aBits: byte; aMaxBits: byte): Boolean; {* устанавливает параметры "размазывания" индекса. } function DeleteStore(anIndex: Tm3StoreElementIndex): hResult; {* удаляет элемент хранилища. } function CreateStore(anIndex: Tm3StoreElementIndex; anAccess: Tm3StoreAccess; aStoreType: Tm3StoreType; out aStore: Tm3Store; aUseCompression: Boolean): hResult; overload; {* создает элемент хранилища. } function OpenStore(anIndex: Tm3StoreElementIndex; anAccess: Tm3StoreAccess; aStoreType: Tm3StoreType; out aStore: Tm3Store; aUseCompression: Boolean): hResult; overload; {* открывает элемент хранилища. } function CreateStore(const aName: Tl3WString; anAccess: Tm3StoreAccess; aStoreType: Tm3StoreType; out aStore: Tm3Store; aUseCompression: Boolean): hResult; overload; {* создает элемент хранилища } function OpenStore(const aName: Tl3WString; anAccess: Tm3StoreAccess; aStoreType: Tm3StoreType; out aStore: Tm3Store; aUseCompression: Boolean): hResult; overload; {* открывает элемент хранилища } function OpenStore(const aStoreInfo: Tm3StorageElementInfo; anAccess: Tm3StoreAccess; aUseCompression: Boolean): Tm3Store; overload; {* открывает элемент хранилища. } function OpenStore(const aStoreInfo: Tm3StoreInfo; anAccess: Tm3StoreAccess; anIndex: Tm3StoreElementIndex; aUseCompression: Boolean): Tm3Store; overload; {* открывает элемент хранилища } function RenameElementA(const aOldName: Tl3WString; const aNewName: Tl3WString): hResult; {* Переименовывает элемент хранилища } function ElementExists(const aName: Tl3WString): Boolean; {* Проверяет существование элемента с указанным именем } function As_IStorage: IStorage; {* Метод приведения нашего интерфейса к IStorage } function DestroyElement(aName: PWideChar): HResult; stdcall; function EnumElements(unused1: Integer; unused2: Pointer; unused3: Integer; out theStatStg: IEnumStatStg): HResult; stdcall; function Stat(out theStatStg: TStatStg; aStatFlag: Integer): HResult; stdcall; procedure IterateIndexedF(anAction: Mm3StorageIterators_IterateIndexedF_Action); procedure IterateAllF(anAction: Mm3StorageIterators_IterateAllF_Action); end;//Im3IndexedStorage Im3StorageHolder = interface ['{0B097519-7C33-4780-AAAA-94D5ADD3FB09}'] function Get_Storage: Im3IndexedStorage; function StoreToCache(const aFileName: WideString; aSharedMode: Cardinal): Im3IndexedStorage; property Storage: Im3IndexedStorage read Get_Storage; end;//Im3StorageHolder function Tm3StoreInfo_C(aPosition: Int64; aType: Tm3StoreType): Tm3StoreInfo; function Tm3StorageElementInfo_C(const anInfo: Tm3StoreInfo; const aName: Tl3WString): Tm3StorageElementInfo; function L2Mm3StorageIteratorsIterateIndexedFAction(anAction: Pointer): Mm3StorageIterators_IterateIndexedF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Mm3StorageIterators.IterateIndexedF } function L2Mm3StorageIteratorsIterateAllFAction(anAction: Pointer): Mm3StorageIterators_IterateAllF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Mm3StorageIterators.IterateAllF } function Tm3Store_C(const aStream: IStream): Tm3Store; overload; function Tm3Store_C(const aStorage: Im3IndexedStorage): Tm3Store; overload; function Tm3Store_E: Tm3Store; overload; function Tm3Store_E(aResult: hResult): Tm3Store; overload; implementation uses l3ImplUses , l3Base ; function Tm3StoreInfo_C(aPosition: Int64; aType: Tm3StoreType): Tm3StoreInfo; //#UC START# *5451F543029B_47208CA50237_var* //#UC END# *5451F543029B_47208CA50237_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *5451F543029B_47208CA50237_impl* Assert((aType = m3_stNone) OR (aType = m3_stStream) OR (aType = m3_stStorage)); Assert(aPosition >= -1); Result.rPosition := aPosition; Result.rStoreType := aType; //#UC END# *5451F543029B_47208CA50237_impl* end;//Tm3StoreInfo_C function Tm3StorageElementInfo_C(const anInfo: Tm3StoreInfo; const aName: Tl3WString): Tm3StorageElementInfo; //#UC START# *5451F57B0181_5451F4E50226_var* //#UC END# *5451F57B0181_5451F4E50226_var* begin Finalize(Result); System.FillChar(Result, SizeOf(Result), 0); //#UC START# *5451F57B0181_5451F4E50226_impl* Result.rInfo := anInfo; Result.rName := aName; //#UC END# *5451F57B0181_5451F4E50226_impl* end;//Tm3StorageElementInfo_C function L2Mm3StorageIteratorsIterateIndexedFAction(anAction: Pointer): Mm3StorageIterators_IterateIndexedF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Mm3StorageIterators.IterateIndexedF } asm jmp l3LocalStub end;//L2Mm3StorageIteratorsIterateIndexedFAction function L2Mm3StorageIteratorsIterateAllFAction(anAction: Pointer): Mm3StorageIterators_IterateAllF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для Mm3StorageIterators.IterateAllF } asm jmp l3LocalStub end;//L2Mm3StorageIteratorsIterateAllFAction function Tm3Store_C(const aStream: IStream): Tm3Store; //#UC START# *5452154901F5_545210E8021B_var* //#UC END# *5452154901F5_545210E8021B_var* begin Finalize(Result); System.FillChar(Result, SizeOf(Result), 0); //#UC START# *5452154901F5_545210E8021B_impl* Result.rStream := aStream; if (aStream = nil) then Result.rResult := E_NoInterface else Result.rResult := S_Ok; //#UC END# *5452154901F5_545210E8021B_impl* end;//Tm3Store_C function Tm3Store_C(const aStorage: Im3IndexedStorage): Tm3Store; //#UC START# *5452156A0229_545210E8021B_var* //#UC END# *5452156A0229_545210E8021B_var* begin Finalize(Result); System.FillChar(Result, SizeOf(Result), 0); //#UC START# *5452156A0229_545210E8021B_impl* Result.rStorage := aStorage; if (aStorage = nil) then Result.rResult := E_NoInterface else Result.rResult := S_Ok; //#UC END# *5452156A0229_545210E8021B_impl* end;//Tm3Store_C function Tm3Store_E: Tm3Store; //#UC START# *545221CD0019_545210E8021B_var* //#UC END# *545221CD0019_545210E8021B_var* begin Finalize(Result); System.FillChar(Result, SizeOf(Result), 0); //#UC START# *545221CD0019_545210E8021B_impl* Result.rResult := E_NoInterface; //#UC END# *545221CD0019_545210E8021B_impl* end;//Tm3Store_E function Tm3Store_E(aResult: hResult): Tm3Store; //#UC START# *545227580181_545210E8021B_var* //#UC END# *545227580181_545210E8021B_var* begin Finalize(Result); System.FillChar(Result, SizeOf(Result), 0); //#UC START# *545227580181_545210E8021B_impl* Result.rResult := aResult; //#UC END# *545227580181_545210E8021B_impl* end;//Tm3Store_E function Tm3Store.AsIStorage: IStorage; //#UC START# *5452198301A0_545210E8021B_var* //#UC END# *5452198301A0_545210E8021B_var* begin //#UC START# *5452198301A0_545210E8021B_impl* if (rStorage = nil) then Result := nil else Result := rStorage.As_IStorage; //#UC END# *5452198301A0_545210E8021B_impl* end;//Tm3Store.AsIStorage end.
// PGMtoBMP Command Line Utility // efg, 4 August 1998 {$APPTYPE CONSOLE} PROGRAM PGMtoBMP; USES Windows, // TRGBTriple Classes, // TFileStream Graphics, // TBitmap SysUtils; // FindFirst, FindNext, FindLast VAR Bitmap : TBitmap; FileName : STRING; FilePath : STRING; FileSpec : STRING; i : INTEGER; ReturnCode: INTEGER; SearchRec : TSearchRec; FUNCTION ReadPortableGrayMapP5(CONST filename: STRING): TBitmap; CONST MaxPixelCount = 65536; TYPE TRGBArray = ARRAY[0..MaxPixelCount-1] OF TRGBTriple; pRGBArray = ^TRGBArray; VAR i : CARDINAL; j : CARDINAL; Row : pRGBArray; s : STRING; PGMBuffer: ARRAY[0..MaxPixelCount-1] OF BYTE; PGMStream: TFileStream; PGMWidth : CARDINAL; PGMHeight: CARDINAL; FUNCTION GetNextPGMLine: STRING; VAR c: CHAR; BEGIN Result := ''; REPEAT PGMStream.Read(c, 1); IF c <> #$0A THEN RESULT := RESULT + c UNTIL c = #$0A; // Look for Line Feed used in UNIX file END {GetNextPGMLine}; BEGIN PGMStream := TFileStream.Create(filename, fmOpenRead); TRY PGMStream.Seek(0, soFromBeginning); s := GetNextPGMLine; ASSERT (s = 'P5'); // "Magic Number" for special PGM files s := GetNextPGMLine; PGMWidth := StrToInt(COPY(s,1,POS(' ',s)-1)); Delete(s, 1, POS(' ',s)); PGMHeight := StrToInt(s); RESULT := TBitmap.Create; RESULT.Width := PGMWidth; RESULT.Height := PGMHeight; RESULT.PixelFormat := pf24bit; // Easiest way to avoid palettes and // get 256 shades of gray, since Windows // reserves 20 of 256 colors in 256-color // mode. // Skip over file header by starting at the end and backing up by the // number of pixel bytes. PGMStream.Seek(PGMStream.Size - PGMHeight*PGMWidth, soFromBeginning); FOR j := 0 TO PGMHeight - 1 DO BEGIN PGMStream.Read(PGMBuffer, PGMWidth); Row := RESULT.Scanline[j]; FOR i := 0 TO PGMWidth -1 DO BEGIN WITH Row[i] DO BEGIN rgbtRed := PGMBuffer[i]; rgbtGreen := PGMBuffer[i]; rgbtBlue := PGMBuffer[i] END END END FINALLY PGMStream.Free END END {ReadPortableGrayMapP5}; BEGIN IF ParamCount = 0 THEN BEGIN WRITELN ('PGMtoBMP Command Line Utility'); WRITELN; WRITELN ('Syntax: PGMtoBMP filespec1 [filespec2 ...]'); WRITELN; WRITELN ('Any number of input files (with wildcards) are allowed.'); WRITELN ('".PGM" is appended to file specifications if absent.'); WRITELN ('Output files will have the same name as input files but with a .BMP extension.') END ELSE BEGIN FOR i := 1 TO ParamCount DO BEGIN FileSpec := ParamStr(i); IF POS('.PGM',UpperCase(ParamStr(i))) = 0 THEN FileSpec := FileSpec + '.PGM'; FilePath := ExtractFilePath(FileSpec); ReturnCode := FindFirst(FileSpec, faAnyFile, SearchRec); TRY WHILE ReturnCode = 0 DO BEGIN Filename := FilePath + SearchRec.Name; WRITE (Filename, ' -> '); Bitmap := ReadPortableGrayMapP5(Filename); TRY Filename := ChangeFileExt(Filename, '.BMP'); Bitmap.SaveToFile(Filename); WRITELN (Filename) FINALLY Bitmap.Free END; ReturnCode := FindNext(SearchRec) END FINALLY FindClose(SearchRec) END END END END {PGMtoBMP}.
unit DelayValuesParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, ValuesParsingBaseTest, WpcScriptCommons, WpcStatements, WpcStatementProperties, WpcCommonTypes, WpcScriptParser; type { TDelayValuesParsingTest } TDelayValuesParsingTest = class(TValuesParsingBaseTest) private const DELAY_MEASUREMENT_UNITS_STRINGS : Array[1..5] of String = ('s', 'm', 'h', 'd', 'ms'); DELAY_MEASUREMENT_UNITS : Array[1..5] of TWpcTimeMeasurementUnits = (SECONDS, MINUTES, HOURS, DAYS, MILLISECONDS); ZERO_DELAY = 0; MINIMAL_DELAY = 1; REGULAR_DELAY = 4; protected function ParseAndGetWaitValue(DelayString : String) : LongWord; procedure ParseAndEnsureScriptParseException(DelayString : String); published procedure ShouldParseDelayValueWithDefaultTimeunit(); procedure ShoudParseZeroDelayValueWithEachMeasurementUnit(); procedure ShoudParseMinimalDelayValueWithEachMeasurementUnit(); procedure ShoudParseRegularDelayValueWithEachMeasurementUnit(); procedure ShoudParseBigDelayValueWithEachMeasurementUnit(); procedure ShouldRaiseScriptParseExceptionIfNoDelayValueGiven(); procedure ShouldRaiseScriptParseExceptionIfInvalidMeasurementUnitGiven(); procedure ShouldRaiseScriptParseExceptionIfInvalidDelayValueGiven(); procedure ShouldRaiseScriptParseExceptionIfNegativeValueGivenForEachMeasurementUnit(); procedure ShouldRaiseScriptParseExceptionIfFractionValueGivenForEachMeasurementUnit(); procedure ShouldRaiseScriptParseExceptionIfMaximumValueExceededForEachMeasurementUnit(); end; implementation { TDelayValuesParsingTest } // WAIT <DelayString> function TDelayValuesParsingTest.ParseAndGetWaitValue(DelayString : String) : LongWord; var WaitStatement : TWpcWaitStatement; begin if (ScriptLines <> nil) then FreeAndNil(ScriptLines); ScriptLines := TStringList.Create(); try ScriptLines.Add(WAIT_KEYWORD + ' ' + DelayString); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WAIT_STATEMENT_ID = MainBranchStatements[0].GetId()); WaitStatement := TWpcWaitStatement(MainBranchStatements[0]); Result := WaitStatement.GetDelay(); finally FreeAndNil(ScriptLines); FreeAndNil(Script); end; end; // WAIT <DelayString> procedure TDelayValuesParsingTest.ParseAndEnsureScriptParseException(DelayString : String); begin if (ScriptLines <> nil) then FreeAndNil(ScriptLines); ScriptLines := TStringList.Create(); try ScriptLines.Add(WAIT_KEYWORD + ' ' + DelayString); WrapInMainBranch(ScriptLines); // TODO improve parser to give information about word number AssertScriptParseExceptionOnParse(1); finally FreeAndNil(ScriptLines); end; end; procedure TDelayValuesParsingTest.ShouldParseDelayValueWithDefaultTimeunit(); begin AssertEquals(FAILED_TO_PARSE + IntToStr(REGULAR_DELAY) + ' with default measurement units.', TWpcDelayStatementProperty.ConvertToMilliseconds(REGULAR_DELAY, MINUTES), ParseAndGetWaitValue(IntToStr(REGULAR_DELAY))); // minutes is default units end; procedure TDelayValuesParsingTest.ShoudParseZeroDelayValueWithEachMeasurementUnit(); var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin AssertEquals(FAILED_TO_PARSE + IntToStr(ZERO_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i], ZERO_DELAY, ParseAndGetWaitValue(IntToStr(ZERO_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i])); end; end; procedure TDelayValuesParsingTest.ShoudParseMinimalDelayValueWithEachMeasurementUnit(); var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin AssertEquals(FAILED_TO_PARSE + IntToStr(MINIMAL_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i], TWpcDelayStatementProperty.ConvertToMilliseconds(MINIMAL_DELAY, DELAY_MEASUREMENT_UNITS[i]), ParseAndGetWaitValue(IntToStr(MINIMAL_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i])); end; end; procedure TDelayValuesParsingTest.ShoudParseRegularDelayValueWithEachMeasurementUnit(); var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin AssertEquals(FAILED_TO_PARSE + IntToStr(REGULAR_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i], TWpcDelayStatementProperty.ConvertToMilliseconds(REGULAR_DELAY, DELAY_MEASUREMENT_UNITS[i]), ParseAndGetWaitValue(IntToStr(REGULAR_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i])); end; end; procedure TDelayValuesParsingTest.ShoudParseBigDelayValueWithEachMeasurementUnit(); const BIG_DELAY_VALUES : Array[1..5] of LongWord = (2592000, 43200, 720, 30, 2592000000); var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin AssertEquals(FAILED_TO_PARSE + IntToStr(BIG_DELAY_VALUES[i]) + DELAY_MEASUREMENT_UNITS_STRINGS[i], TWpcDelayStatementProperty.ConvertToMilliseconds(BIG_DELAY_VALUES[i], DELAY_MEASUREMENT_UNITS[i]), ParseAndGetWaitValue(IntToStr(BIG_DELAY_VALUES[i]) + DELAY_MEASUREMENT_UNITS_STRINGS[i])); end; end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfNoDelayValueGiven(); begin ScriptLines.Add(WAIT_KEYWORD + ' ' + FOR_KEYWORD + ' '); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 2); end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfInvalidMeasurementUnitGiven(); const WRONG_MEASUREMENT_UNITS : Array[1..5] of String = ('us', 'ps', 'Ms', 'ns', 'ds'); var i : Integer; begin for i:=1 to Length(WRONG_MEASUREMENT_UNITS) do begin ParseAndEnsureScriptParseException(IntToStr(REGULAR_DELAY) + WRONG_MEASUREMENT_UNITS[i]); end; end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfInvalidDelayValueGiven(); const WRONG_DELAY_VALUES : Array[1..5] of String = ('x', 's5', '-', '0x5', '10b'); var i : Integer; begin for i:=1 to Length(WRONG_DELAY_VALUES) do begin ParseAndEnsureScriptParseException(WRONG_DELAY_VALUES[i] + DELAY_MEASUREMENT_UNITS_STRINGS[2]); end; end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfNegativeValueGivenForEachMeasurementUnit(); const NEGATIVE_DELAY = -2; var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin ParseAndEnsureScriptParseException(IntToStr(NEGATIVE_DELAY) + DELAY_MEASUREMENT_UNITS_STRINGS[i]); end; end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfFractionValueGivenForEachMeasurementUnit(); const FRACTION_DELAY_STRING = '2.5'; var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin ParseAndEnsureScriptParseException(FRACTION_DELAY_STRING + DELAY_MEASUREMENT_UNITS_STRINGS[i]); end; end; procedure TDelayValuesParsingTest.ShouldRaiseScriptParseExceptionIfMaximumValueExceededForEachMeasurementUnit(); const EXCEEDED_DELAY_VALUES : Array[1..5] of String = ('2764801', '46081', '769', '33', '2764800001'); var i : Integer; begin for i:=1 to Length(DELAY_MEASUREMENT_UNITS_STRINGS) do begin ParseAndEnsureScriptParseException(EXCEEDED_DELAY_VALUES[i] + DELAY_MEASUREMENT_UNITS_STRINGS[i]); end; end; initialization RegisterTest(VALUES_PARSER_TEST_SUITE_NAME, TDelayValuesParsingTest); end.
unit ExtAIStates; interface uses Classes, SysUtils, ExtAIMsgStates, ExtAINetClient, ExtAISharedInterface; // States of the ExtAI type TExtAIStates = class private fStates: TExtAIMsgStates; fClient: TExtAINetClient; // Game variables //fTerrain: TExtAITerrain; //fHands: TExtAIHands; // Triggers //fOnGroupOrderAttackUnit: TGroupOrderAttackUnit; // Send state via client procedure SendState(aData: Pointer; aLength: Cardinal); public constructor Create(aClient: TExtAINetClient); destructor Destroy(); override; // Connect Msg directly with creator of ExtAI so he can type Actions.XY instead of Actions.Msg.XY property Msg: TExtAIMsgStates read fStates; // States from perspective of the ExtAI { function MapHeight(): Word; function MapWidth(): Word; TTerrainSize = procedure(aX, aY: Word); TTerrainPassability = procedure(aPassability: array of Boolean); TTerrainFertility = procedure(aFertility: array of Boolean); TPlayerGroups = procedure(aHandIndex: SmallInt; aGroups: array of Integer); TPlayerUnits = procedure(aHandIndex: SmallInt; aUnits: array of Integer); } //property GroupOrderAttackUnit: TGroupOrderAttackUnit read fOnGroupOrderAttackUnit; end; implementation { TExtAIStates } constructor TExtAIStates.Create(aClient: TExtAINetClient); begin Inherited Create; fClient := aClient; fStates := TExtAIMsgStates.Create(); // Connect callbacks fStates.OnSendState := SendState; // Connect properties //fOnGroupOrderAttackUnit := fActions.GroupOrderAttackUnitW; end; destructor TExtAIStates.Destroy(); begin //fOnGroupOrderAttackUnit := nil; fStates.Free; fClient := nil; Inherited; end; procedure TExtAIStates.SendState(aData: Pointer; aLength: Cardinal); begin Assert(fClient <> nil, 'State cannot be send because client = nil'); fClient.SendMessage(aData, aLength); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpPlainSchnorrEncoding; {$I ..\..\Include\CryptoLib.inc} interface uses Math, ClpBigInteger, ClpISchnorrEncoding, ClpIPlainSchnorrEncoding, ClpBigIntegers, ClpArrayUtils, ClpCryptoLibTypes; resourcestring SInvalidEncodingLength = 'Encoding has incorrect length, "%s"'; SValueOutOfRange = 'Value out of range, "%s"'; type TPlainSchnorrEncoding = class(TInterfacedObject, ISchnorrEncoding, IPlainSchnorrEncoding) strict private class var FInstance: IPlainSchnorrEncoding; class function GetInstance: IPlainSchnorrEncoding; static; inline; class constructor PlainSchnorrEncoding(); strict protected function CheckValue(const n, x: TBigInteger): TBigInteger; virtual; function DecodeValue(const n: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32): TBigInteger; virtual; procedure EncodeValue(const n, x: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32); virtual; public function Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray) : TCryptoLibGenericArray<TBigInteger>; virtual; function Encode(const n, r, s: TBigInteger): TCryptoLibByteArray; virtual; class property Instance: IPlainSchnorrEncoding read GetInstance; end; implementation { TPlainDsaEncoding } function TPlainSchnorrEncoding.CheckValue(const n, x: TBigInteger): TBigInteger; begin if ((x.SignValue < 0) or ((x.CompareTo(n) >= 0))) then begin raise EArgumentCryptoLibException.CreateResFmt(@SValueOutOfRange, ['x']); end; result := x; end; function TPlainSchnorrEncoding.Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray): TCryptoLibGenericArray<TBigInteger>; var valueLength: Int32; begin valueLength := TBigIntegers.GetUnsignedByteLength(n); if (System.Length(encoding) <> (valueLength * 2)) then begin raise EArgumentCryptoLibException.CreateResFmt(@SInvalidEncodingLength, ['encoding']); end; result := TCryptoLibGenericArray<TBigInteger>.Create (DecodeValue(n, encoding, 0, valueLength), DecodeValue(n, encoding, valueLength, valueLength)); end; function TPlainSchnorrEncoding.DecodeValue(const n: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32): TBigInteger; begin result := CheckValue(n, TBigInteger.Create(1, buf, off, len)); end; function TPlainSchnorrEncoding.Encode(const n, r, s: TBigInteger) : TCryptoLibByteArray; var valueLength: Int32; begin valueLength := TBigIntegers.GetUnsignedByteLength(n); System.SetLength(result, valueLength * 2); EncodeValue(n, r, result, 0, valueLength); EncodeValue(n, s, result, valueLength, valueLength); end; procedure TPlainSchnorrEncoding.EncodeValue(const n, x: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32); var bs: TCryptoLibByteArray; bsOff, bsLen, pos: Int32; begin bs := CheckValue(n, x).ToByteArrayUnsigned(); bsOff := Max(0, System.Length(bs) - len); bsLen := System.Length(bs) - bsOff; pos := len - bsLen; TArrayUtils.Fill(buf, off, off + pos, Byte(0)); System.Move(bs[bsOff], buf[off + pos], bsLen * System.SizeOf(Byte)); end; class function TPlainSchnorrEncoding.GetInstance: IPlainSchnorrEncoding; begin result := FInstance; end; class constructor TPlainSchnorrEncoding.PlainSchnorrEncoding; begin FInstance := TPlainSchnorrEncoding.Create(); end; end.
unit kwPopEditorSetStyle2Table; {* [code] aStyle anEditor pop:editor:SetStyle2Table [code] aStyle - номер стиля из таблицы стилей. anEditor - редактор, в котором производятся изменения. } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwPopEditorSetStyle2Table.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "pop_editor_SetStyle2Table" MUID: (52B17C50008A) // Имя типа: "TkwPopEditorSetStyle2Table" {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , kwEditorFromStackWord , tfwScriptingInterfaces , evCustomEditorWindow ; type TkwPopEditorSetStyle2Table = {final} class(TkwEditorFromStackWord) {* [code] aStyle anEditor pop:editor:SetStyle2Table [code] aStyle - номер стиля из таблицы стилей. anEditor - редактор, в котором производятся изменения. } protected procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorSetStyle2Table {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , evCommonUtils , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *52B17C50008Aimpl_uses* //#UC END# *52B17C50008Aimpl_uses* ; procedure TkwPopEditorSetStyle2Table.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_52B17C50008A_var* var l_StyleID: Integer; //#UC END# *4F4CB81200CA_52B17C50008A_var* begin //#UC START# *4F4CB81200CA_52B17C50008A_impl* if aCtx.rEngine.IsTopInt then l_StyleID := aCtx.rEngine.PopInt else Assert(False, 'Не задан стиль для установки!'); aCtx.rCaller.Check(evSetTableStyle(anEditor), 'Не удалось поставить стиль на таблицу!'); //#UC END# *4F4CB81200CA_52B17C50008A_impl* end;//TkwPopEditorSetStyle2Table.DoWithEditor class function TkwPopEditorSetStyle2Table.GetWordNameForRegister: AnsiString; begin Result := 'pop:editor:SetStyle2Table'; end;//TkwPopEditorSetStyle2Table.GetWordNameForRegister initialization TkwPopEditorSetStyle2Table.RegisterInEngine; {* Регистрация pop_editor_SetStyle2Table } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
unit DAO.EnderecosEmpresa; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.EnderecosEmpresa; type TEnderecosEmpresaDAO = class private FConexao : TConexao; public constructor Create(); function GetID(iID: Integer): Integer; function Insert(aEnderecos: TEnderecosEmpresa): Boolean; function Update(aEnderecos: TEnderecosEmpresa): Boolean; function Delete(aEnderecos: TEnderecosEmpresa): Boolean; function Localizar(aParam: Array of variant): TFDQuery; end; const TABLENAME = 'cadastro_enderecos_empresa'; implementation function TEnderecosEmpresaDAO.Insert(aEnderecos: TEnderecosEmpresa): Boolean; var sSQL: String; FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; aEnderecos.Sequencia := GetID(aEnderecos.ID); sSQL := 'INSERT INTO ' + TABLENAME + '(' + 'ID_EMPRESA, SEQ_ENDERECO, DES_TIPO_ENDERECO, NUM_CEP, DES_LOGRADOURO, NUM_LOGRADOURO, DES_COMPLEMENTO, NOM_BAIRRO, ' + 'NOM_CIDADE, UF_ESTADO, NUM_CNPJ, NUM_IE, NUM_IEST, NUM_IM) ' + 'VALUES (' + ':pID_EMPRESA, :pSEQ_ENDERECO, :pDES_TIPO_ENDERECO, :pNUM_CEP, :pDES_LOGRADOURO, :pNUM_LOGRADOURO, :pDES_COMPLEMENTO, ' + ':pNOM_BAIRRO, :pNOM_CIDADE, :pUF_ESTADO, :pNUM_CNPJ, :pNUM_IE, :pNUM_IEST, :pNUM_IM);'; FDQuery.ExecSQL(sSQL,[aEnderecos.ID, aEnderecos.Sequencia, aEnderecos.Tipo, aEnderecos.CEP, aEnderecos.Logradouro, aEnderecos.Numero, aEnderecos.Complemento, aEnderecos.Bairro, aEnderecos.Cidade, aEnderecos.UF, aEnderecos.CNPJ, aEnderecos.IE, aEnderecos.IEST, aEnderecos.IM]); Result := True; finally FDQuery.Free; end; end; function TEnderecosEmpresaDAO.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA'); FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA AND SEQ_ENDERECO = :SEQ_ENDERECO'); FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1]; FDQuery.ParamByName('SEQ_ENDERECO').AsInteger := aParam[2]; end; if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ'); FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1]; end; if aParam[0] = 'IE' then begin FDQuery.SQL.Add('WHERE NUM_IE = :NUM_IE'); FDQuery.ParamByName('NUM_IE').AsString := aParam[1]; end; if aParam[0] = 'IM' then begin FDQuery.SQL.Add('WHERE NUM_IM = :NUM_IM'); FDQuery.ParamByName('NUM_IM').AsString := aParam[1]; end; if aParam[0] = 'TIPO' then begin FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA AND DES_TIPO_ENDERECO = :DES_TIPO_ENDERECO'); FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1]; FDQuery.ParamByName('DES_TIPO_ENDERECO').AsString := aParam[2]; end; if aParam[0] = 'CEP' then begin FDQuery.SQL.Add('WHERE NUM_CEP LIKE :NUM_CEP'); FDQuery.ParamByName('NUM_CEP').AsString := aParam[1]; end; if aParam[0] = 'ENDERECO' then begin FDQuery.SQL.Add('WHERE DES_LOGRADOURO LIKE :DES_LOGRADOURO'); FDQuery.ParamByName('DES_LOGRADOURO').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TEnderecosEmpresaDAO.Update(aEnderecos: TEnderecosEmpresa): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO_ENDERECO = :pDES_TIPO_ENDERECO, NUM_CEP = :pNUM_CEP, DES_LOGRADOURO := :pDES_LOGRADOURO, ' + 'NUM_LOGRADOURO = :pNUM_LOGRADOURO, DES_COMPLEMENTO = :pDES_COMPLEMENTO, ' + 'NOM_BAIRRO = :pNOM_BAIRRO, NOM_CIDADE = :pNOM_CIDADE, ' + 'UF_ESTADO = :pUF_ESTADO, NUM_CNPJ = :pNUM_CNPJ, NUM_IE = :pNUM_IE, NUM_IEST = :pNUM_IEST, NUM_IM = :pNUM_IM ' + 'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_ENDERECO = :pSEQ_ENDERECO;'; FDQuery.ExecSQL(sSQL,[aEnderecos.Tipo, aEnderecos.CEP, aEnderecos.Logradouro, aEnderecos.Numero, aEnderecos.Complemento, aEnderecos.Bairro, aEnderecos.Cidade, aEnderecos.UF, aEnderecos.CNPJ, aEnderecos.IE, aEnderecos.IEST, aEnderecos.IM, aEnderecos.ID, aEnderecos.Sequencia]); Result := True; finally FDQuery.Free; end; end; constructor TEnderecosEmpresaDAO.Create; begin Fconexao := TConexao.Create; end; function TEnderecosEmpresaDAO.Delete(aEnderecos: TEnderecosEmpresa): Boolean; var FDQuery: TFDQuery; sSQL: String; begin try Result := False; sSQL := ''; FDQuery := FConexao.ReturnQuery(); if aEnderecos.Sequencia = -1 then begin sSQL := 'DELETE FROM ' + TABLENAME + ' ' + 'WHERE ID_EMPRESA = :pID_EMPRESA;'; FDQuery.ExecSQL(sSQL,[aEnderecos.ID]); end else begin sSQL := 'DELETE FROM ' + TABLENAME + ' ' + 'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_ENDERECO = :pSEQ_ENDERECO;'; FDQuery.ExecSQL(sSQL,[aEnderecos.ID, aEnderecos.Sequencia]); end; Result := True; finally FDquery.Free; end; end; function TEnderecosEmpresaDAO.GetID(iID: Integer): Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(SEQ_ENDERECO),0) + 1 from ' + TABLENAME + ' WHERE ID_EMPRESA = ' + iID.toString); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Free; end; end; end.
unit Unit2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Bluetooth, System.Bluetooth.Components, FMX.Objects, FMX.ListView.Types, FMX.ListView, FMX.StdCtrls, FMX.TabControl, BluetoothStream, FMX.Layouts, FMX.Memo, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions; type TForm2 = class(TForm) BluetoothLE1: TBluetoothLE; Image1: TImage; StyleBook1: TStyleBook; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; ListView1: TListView; Image3: TImage; Button1: TButton; Timer1: TTimer; ReceiveProgressLabel: TLabel; SecondsLabel: TLabel; ReceiveProgressBar: TProgressBar; SendProgressBar: TProgressBar; SendProgressLabel: TLabel; ActionList1: TActionList; TakePhotoFromLibraryAction1: TTakePhotoFromLibraryAction; Button2: TButton; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1CharacteristicReadRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); procedure Timer1Timer(Sender: TObject); procedure BluetoothLE1CharacteristicWriteRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const AValue: TArray<System.Byte>); procedure BluetoothLE1CharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); private { Private declarations } procedure OnSendProgress(Sender: TObject; Progress: Integer; BytesProcessed: Int64); procedure OnReceiveProgress(Sender: TObject; Progress: Integer; BytesProcessed: Int64); procedure ClientRequestTransfer; procedure ClienteStartTransfer; procedure ServerPrepareTransfer; public { Public declarations } end; const ServiceUUIDPattern: string = '56829860-6B1E-4830-8073-9C77889E'; // XXXX CharacteristicStreamUUID: TBluetoothUUID = '{90EB5B5C-7673-4856-8894-A71D43CA8A4C}'; CharacteristicControlUUID: TBluetoothUUID = '{CF985997-5C38-48AD-BFF4-2D10C4AA5A30}'; var Form2: TForm2; GattServer: TBluetoothGattServer; ServerService: TBluetoothGattService; ServerStreamCharacteristic: TBluetoothGattCharacteristic; ServerControlCharacteristic: TBluetoothGattCharacteristic; ClientService: TBluetoothGattService; ClientStreamCharacteristic: TBluetoothGattCharacteristic; ClientControlCharacteristic: TBluetoothGattCharacteristic; ClientDeviceList: TBluetoothLEDeviceList; ClientDevice: TBluetoothLEDevice; StreamReceiver: TBluetoothStreamReceiver; StreamSender: TBluetoothStreamSender; implementation {$R *.fmx} uses System.IOUtils; function GenerateServiceUUID: TBluetoothUUID; const Hex: array[0..15] of Char = '0123456789ABCDEF'; var LStr: string; begin LStr := ''; repeat LStr := LStr + Hex[Random(Length(Hex))]; until (Length(LStr) = 4); Result := TBluetoothUUID.Create('{' + ServiceUUIDPattern + LStr + '}'); end; function GetStreamService(ADevice: TBluetoothLEDevice): TBluetoothGattService; var LService: TBluetoothGattService; Str: string; begin for LService in ADevice.Services do begin Str := LService.UUID.ToString; if Str.StartsWith('{' + ServiceUUIDPattern) then Exit(LService); end; Result := nil; end; function BytesToString(const B: TBytes): string; var I: Integer; begin if Length(B) > 0 then begin Result := Format('%0.2X', [B[0]]); for I := 1 to High(B) do Result := Result + Format(' %0.2X', [B[I]]); end else Result := ''; end; procedure TForm2.BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var LStream: TStream; LBytes: TBytes; begin LBytes := ACharacteristic.Value; StreamReceiver.ProcessPacket(LBytes); if StreamReceiver.Finished then begin LStream := StreamReceiver.Stream; LStream.Position := 0; Image3.Bitmap.LoadFromStream(LStream) end else BluetoothLE1.ReadCharacteristic(ClientDevice, ClientStreamCharacteristic); end; procedure TForm2.BluetoothLE1CharacteristicReadRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); var LStream: TBytesStream; LBytes: TBytes; begin if ACharacteristic.UUID = ServerStreamCharacteristic.UUID then ACharacteristic.Value := StreamSender.CreatePacket; end; procedure TForm2.BluetoothLE1CharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin ClienteStartTransfer; end; procedure TForm2.BluetoothLE1CharacteristicWriteRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const AValue: TArray<System.Byte>); begin if ACharacteristic.UUID = ServerControlCharacteristic.UUID then ServerPrepareTransfer; end; procedure TForm2.BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); var LDevice: TBluetoothLEDevice; LItem: TListViewItem; LService: TBluetoothGattService; begin if ClientDeviceList <> nil then ClientDeviceList.Free; // Filter by services ClientDeviceList := TBluetoothLEDeviceList.Create; for LDevice in ADeviceList do begin if LDevice.DiscoverServices then if GetStreamService(LDevice) <> nil then begin ClientDeviceList.Add(LDevice); Break; end; end; // Update list ListView1.BeginUpdate; ListView1.ClearItems; for LDevice in ClientDeviceList do begin LItem := ListView1.Items.Add; LItem.Text := LDevice.DeviceName; end; ListView1.EndUpdate; Button1.Enabled := True; end; procedure TForm2.Button1Click(Sender: TObject); var B: TBluetoothConnectionState; begin BluetoothLE1.DiscoverDevices(1000); Button1.Enabled := False; end; procedure TForm2.ClienteStartTransfer; var LStream: TStream; begin LStream := TBytesStream.Create; StreamReceiver := TBluetoothStreamReceiver.Create(LStream); StreamReceiver.OnBluetoothStreamProgressEvent := OnReceiveProgress; BluetoothLE1.ReadCharacteristic(ClientDevice, ClientStreamCharacteristic); // Start read end; procedure TForm2.ClientRequestTransfer; var LBytes: TBytes; begin // Tell the server to reset the transfer SetLength(LBytes, 1); LBytes[0] := 0; ClientControlCharacteristic.Value := LBytes; BluetoothLE1.WriteCharacteristic(ClientDevice, ClientControlCharacteristic); end; procedure TForm2.FormShow(Sender: TObject); var LBytes: TBytes; begin if BluetoothLE1.SupportsGattServer then begin GattServer := BluetoothLE1.GetGattServer; ServerService := GattServer.CreateService(GenerateServiceUUID, TBluetoothServiceType.Primary); ServerService.AdvertiseData := 'Stream Service'; ServerStreamCharacteristic := GattServer.CreateCharacteristic(ServerService, CharacteristicStreamUUID,[TBluetoothProperty.Read], 'Stream file'); ServerControlCharacteristic := GattServer.CreateCharacteristic(ServerService, CharacteristicControlUUID,[TBluetoothProperty.Write], 'Stream control'); GattServer.AddService(ServerService); end end; procedure TForm2.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); var I, J: Integer; LBytes: TBytes; begin ClientDevice := ClientDeviceList[AItem.Index]; ClientService := GetStreamService(ClientDevice); BluetoothLE1.GetCharacteristics(ClientService); ClientStreamCharacteristic := BluetoothLE1.GetCharacteristic(ClientService, CharacteristicStreamUUID); ClientControlCharacteristic := BluetoothLE1.GetCharacteristic(ClientService, CharacteristicControlUUID); ClientRequestTransfer; end; procedure TForm2.OnReceiveProgress(Sender: TObject; Progress: Integer; BytesProcessed: Int64); begin ReceiveProgressBar.Value := Progress; ReceiveProgressLabel.Text := BytesProcessed.ToString + ' bytes'; Timer1.Enabled := True; end; procedure TForm2.OnSendProgress(Sender: TObject; Progress: Integer; BytesProcessed: Int64); begin SendProgressBar.Value := Progress; SendProgressLabel.Text := BytesProcessed.ToString + ' bytes'; end; procedure TForm2.ServerPrepareTransfer; var LStream: TStream; begin LStream := TBytesStream.Create; Image1.Bitmap.SaveToStream(LStream); StreamSender := TBluetoothStreamSender.Create(LStream); StreamSender.OnBluetoothStreamProgressEvent := OnSendProgress; end; procedure TForm2.TakePhotoFromLibraryAction1DidFinishTaking(Image: TBitmap); begin Image1.Bitmap.Assign(Image); end; procedure TForm2.Timer1Timer(Sender: TObject); begin SecondsLabel.Text := (StrToInt(SecondsLabel.Text) + 1).toString; end; end.
unit MdiChilds.SetNotNormResources; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls, MdiChilds.ProgressForm, MdiChilds.Reg, GsDocument, MdiChilds.DocList, GlobalData, Math, ActionHandler; type TFmSetNotNormResourses = class(TFmProcess) gpSettings: TGroupBox; edtCode: TLabeledEdit; edtCaption: TLabeledEdit; edtPercent: TLabeledEdit; Label1: TLabel; seDigits: TSpinEdit; edtPrecision: TLabeledEdit; mLog: TMemo; Label2: TLabel; Label3: TLabel; lblDocCount: TLabel; btnLoadDocs: TButton; CheckDocCount: TTimer; procedure btnLoadDocsClick(Sender: TObject); procedure CheckDocCountTimer(Sender: TObject); private procedure ExecuteDocument(D: TGsDocument); function GetCalculatedCost(Row: TGsRow; Cost: TGsCostKind; Zone: Integer): Real; protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure DoCancel(Sender: TObject); override; procedure DoResize(Sender: TObject); override; class function GetDataProcessorKind: TDataProcessorKind; override; procedure BeforeExecute; override; procedure AfterExecute; override; public function GetPercent: Real; function GetDigits: Integer; function GetResourceCode: string; function GetResourceCaption: string; function GetPrecision: Real; end; TSetNotNormResourcesActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmSetNotNormResourses: TFmSetNotNormResourses; implementation {$R *.dfm} function SelfRoundTo(const AValue: Double; const ADigit: TRoundToRange): Double; var LFactor: Double; begin LFactor := IntPower(10, ADigit); Result := Round(AValue / LFactor) * LFactor; end; procedure TFmSetNotNormResourses.AfterExecute; var I: Integer; begin for I := 0 to Documents.Count - 1 do Documents[I].Save; end; procedure TFmSetNotNormResourses.BeforeExecute; begin inherited; end; procedure TFmSetNotNormResourses.btnLoadDocsClick(Sender: TObject); var F: TFmProcess; begin F := TFmDocList.CreateForm(True); F.Show; end; procedure TFmSetNotNormResourses.CheckDocCountTimer(Sender: TObject); begin lblDocCount.Caption := IntToStr(Documents.Count); end; procedure TFmSetNotNormResourses.DoCancel(Sender: TObject); begin inherited; end; procedure TFmSetNotNormResourses.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; begin ShowMessage := True; ProgressForm.InitPB(Documents.Count); ProgressForm.Show; for I := 0 to Documents.Count - 1 do begin if ProgressForm.InProcess then ExecuteDocument(Documents[I]) else Exit; ProgressForm.StepIt(ExtractFileName(Documents[I].FileName)); end; end; procedure TFmSetNotNormResourses.DoResize(Sender: TObject); begin inherited; end; procedure TFmSetNotNormResourses.ExecuteDocument(D: TGsDocument); var L: TList; I: Integer; Row: TGsRow; Zone: TZoneNum; MT, OZ: Real; NormValue: Real; Resource: TGsResource; Outlay: TGsOutlay; S: TStringList; begin S := TStringList.Create; S.Sorted := True; S.Duplicates := dupIgnore; L := TList.Create; try D.Chapters.EnumItems(L, TGsRow, True); for I := 0 to L.Count - 1 do begin Row := TGsRow(L[I]); Resource := Row.ResourceByCode(getResourceCode); if Resource = nil then begin Resource := TGsResource.Create(D); Outlay := TGsOutlay.Create(D); Row.MaterialList.Add(Outlay); Outlay.Add(Resource); end; Resource.Code := GetResourceCode; Resource.Caption := GetResourceCaption; Resource.Measure := 'руб.'; Resource.Outlay.Options := []; for Zone := 1 to D.Zones.Count do begin MT := Row.GetCostValue(cstMT, Zone); OZ := Row.GetCostValue(cstOZ, Zone); NormValue := GetPercent * OZ / 100; Resource.Outlay.Count.Value[Zone] := NormValue; Resource.SetCostValue(cstPrice, 1, Zone); if Abs(MT - GetCalculatedCost(Row, cstPrice, Zone)) > getPrecision then S.Add(Row.Number(True)); end; end; finally L.Free; end; mLog.Lines.AddStrings(S); S.Free; end; function TFmSetNotNormResourses.GetCalculatedCost(Row: TGsRow; Cost: TGsCostKind; Zone: Integer): Real; var L: TList; I: Integer; Resource: TGsResource; begin L := TList.Create; try Result := 0; Row.MaterialList.EnumItems(L, TGsResource, True); for I := 0 to L.Count - 1 do begin Resource := TGsResource(L[I]); if not (ooNotCount in Resource.Outlay.Options) then begin if Resource.Outlay.Count.IsCommon then Result := Result + Resource.GetCostValue(Cost, Zone) * Resource.Outlay.Count.CommonValue else Result := Result + Resource.GetCostValue(Cost, Zone) * Resource.Outlay.Count.Value[Zone]; end; end; Result := SelfRoundTo(Result, -GetDigits); finally L.Free; end; end; class function TFmSetNotNormResourses.GetDataProcessorKind: TDataProcessorKind; begin Result := dpkCustom; end; function TFmSetNotNormResourses.GetDigits: Integer; begin Result := seDigits.Value; end; function TFmSetNotNormResourses.GetPercent: Real; var V: string; begin V := StringReplace(edtPercent.Text, '.', ',', []); V := StringReplace(V, ' ', '', [rfReplaceAll]); Result := StrToFloatDef(V, 0); end; function TFmSetNotNormResourses.GetPrecision: Real; var V: string; begin V := StringReplace(edtPrecision.Text, '.', ',', []); V := StringReplace(V, ' ', '', [rfReplaceAll]); Result := StrToFloatDef(V, 0); end; function TFmSetNotNormResourses.GetResourceCaption: string; begin Result := edtCaption.Text; end; function TFmSetNotNormResourses.GetResourceCode: string; begin Result := edtCode.Text; end; { TSetNotNormResourcesActionHandler } procedure TSetNotNormResourcesActionHandler.ExecuteAction; begin TFmSetNotNormResourses.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Установка ненормируемых ресурсов', hkDefault, TSetNotNormResourcesActionHandler); end.
unit ServerHorse.Controller; interface uses ServerHorse.Model.Entity.USERS, ServerHorse.Controller.Generic, ServerHorse.Controller.Interfaces, ServerHorse.Model.Entity.CUSTOMERS, ServerHorse.Model.Entity.OCCUPATION, ServerHorse.Model.Entity.COUNTRIES, ServerHorse.Model.Entity.STATES, ServerHorse.Model.Entity.CITIES, ServerHorse.Model.Entity.COMPANIES, ServerHorse.Model.Entity.AREASEXPERTISE, ServerHorse.Model.Entity.BANKACCOUNTS, ServerHorse.Model.Entity.TYPESBANKACCOUNTS; type TController = class(TInterfacedObject, iController) private FUsers : iControllerEntity<TUSERS>; FCustomers : iControllerEntity<TCUSTOMERS>; FOccupations : iControllerEntity<TOCCUPATION>; FCountries : iControllerEntity<TCOUNTRIES>; FStates : iControllerEntity<TSTATES>; FCities : iControllerEntity<TCITIES>; FCompanies : iControllerEntity<TCOMPANIES>; FAreasExpertise : iControllerEntity<TAREASEXPERTISE>; FBankAccounts : iControllerEntity<TBANKACCOUNTS>; FTYPESBANKACCOUNTS : iControllerEntity<TTYPESBANKACCOUNTS>; public constructor Create; destructor Destroy; override; class function New : iController; function AREASEXPERTISE : iControllerEntity<TAREASEXPERTISE>; function BANKACCOUNTS : iControllerEntity<TBANKACCOUNTS>; function CITIES : iControllerEntity<TCITIES>; function COMPANIES : iControllerEntity<TCOMPANIES>; function COUNTRIES : iControllerEntity<TCOUNTRIES>; function CUSTOMERS : iControllerEntity<TCUSTOMERS>; function OCCUPATION : iControllerEntity<TOCCUPATION>; function STATES : iControllerEntity<TSTATES>; function TYPESBANKACCOUNTS : iControllerEntity<TTYPESBANKACCOUNTS>; function USERS : iControllerEntity<TUSERS>; end; implementation { TController } function TController.AREASEXPERTISE: iControllerEntity<TAREASEXPERTISE>; begin if not Assigned(FAreasExpertise) then FAreasExpertise := TControllerGeneric<TAREASEXPERTISE>.New(Self); Result := FAreasExpertise; end; function TController.BANKACCOUNTS: iControllerEntity<TBANKACCOUNTS>; begin if not Assigned(FBankAccounts) then FBankAccounts := TControllerGeneric<TBANKACCOUNTS>.New(Self); Result := FBankAccounts; end; function TController.CITIES: iControllerEntity<TCITIES>; begin if not Assigned(FCities) then FCities := TControllerGeneric<TCITIES>.New(Self); Result := FCities; end; function TController.COMPANIES: iControllerEntity<TCOMPANIES>; begin if not Assigned(FCompanies) then FCompanies := TControllerGeneric<TCOMPANIES>.New(Self); Result := FCompanies; end; function TController.COUNTRIES: iControllerEntity<TCOUNTRIES>; begin if not Assigned(FCountries) then FCountries := TControllerGeneric<TCOUNTRIES>.New(Self); Result := FCountries; end; constructor TController.Create; begin end; function TController.CUSTOMERS: iControllerEntity<TCUSTOMERS>; begin if not Assigned(FCustomers) then FCustomers := TControllerGeneric<TCUSTOMERS>.New(Self); Result := FCustomers; end; destructor TController.Destroy; begin inherited; end; class function TController.New: iController; begin Result := Self.Create; end; function TController.OCCUPATION: iControllerEntity<TOCCUPATION>; begin if not Assigned(FOccupations) then FOccupations := TControllerGeneric<TOCCUPATION>.New(Self); Result := FOccupations; end; function TController.STATES: iControllerEntity<TSTATES>; begin if not Assigned(FStates) then FStates := TControllerGeneric<TSTATES>.New(Self); Result := FStates; end; function TController.TYPESBANKACCOUNTS: iControllerEntity<TTYPESBANKACCOUNTS>; begin if not Assigned(FTYPESBANKACCOUNTS) then FTYPESBANKACCOUNTS := TControllerGeneric<TTYPESBANKACCOUNTS>.New(Self); Result := FTYPESBANKACCOUNTS; end; function TController.USERS: iControllerEntity<TUSERS>; begin if not Assigned(FUsers) then FUsers := TControllerGeneric<TUSERS>.New(Self); Result := FUsers; end; end.
program case1; Type TRoomP=object length, width:real; {поля: длина и ширина комнаты} function Square:real; virtual; {метод определения площади} procedure Print; {метод вывода результата на экран} constructor Init(l,w:real); {коснтруктор} end; function TRoomP.Square:real; {тело метода определения площади} begin Square:=length*width; end; procedure TRoomP.Print; {тело метода вывода результатов} begin writeln('Plotshad= ',Square:6:2); {теперь вызов метода происходит через ТВМ класса} end; Constructor TRoomP.Init(l,w:real); {тело конструктора} begin length:=l; width:=w; end; Type TVRoomP=object(TRoomP) height:real; {дополнительное поле класса} function Square:real; virtual; {виртуальный полиморфный метод} constructor Init(l,w,h:real); {конструктор} end; Constructor TVRoomP.Init(l,w,h:real); begin inherited Init(l,w); {инициализируем поля базового класса} height:=h; {инициализируем собственное поле класса} end; function TVRoomP.Square:real; begin Square:=inherited Square+2*height*(length+width); end; var A:TRoomP; B:TVRoomP; {объявляем объекты-переменные} begin A.Init(3.5,5.1); {конструируем объект А} A.Print; {выведет "Площадь = 17.85"} B.Init(3.5,5.1,2.7); {конструируем объект В} B.Print; {выведе "Площадь = 94.64" - верно!!!} readln; end.
unit uCadastroInterface; interface uses System.SysUtils, System.Classes, FireDAC.Comp.Client; type ICadastroInterface = interface ['{F5D013E3-84EE-4D5A-A11F-B960155C8BD4}'] procedure Novo(Programa, IdUsuario: Integer); function Editar(Programa, IdUsuario: Integer): Boolean; procedure Excluir(Programa, IdUsuario, Id: Integer); function Filtrar(Campo, Texto, Ativo: string; Contem: Boolean = True): string; function FiltrarCodigo(Codigo: integer): string; function LocalizarId(var Qry: TFDQuery; Id: integer): Boolean; procedure LocalizarCodigo(var Qry: TFDQuery; Codigo: integer); procedure Salvar(Programa, IdUsuario: Integer); function ProximoCodigo: Integer; function ProximoId: Integer; procedure Relatorio(Programa, IdUsuario: Integer); end; implementation end.
unit GetAvoidanceZonesUnit; interface uses SysUtils, BaseExampleUnit; type TGetAvoidanceZones = class(TBaseExample) public procedure Execute; end; implementation uses AvoidanceZoneUnit; procedure TGetAvoidanceZones.Execute; var ErrorString: String; AvoidanceZones: TAvoidanceZoneList; begin AvoidanceZones := Route4MeManager.AvoidanceZone.GetList(ErrorString); try WriteLn(''); if (AvoidanceZones.Count > 0) then WriteLn(Format('GetAvoidanceZones executed successfully, %d zones returned', [AvoidanceZones.Count])) else WriteLn(Format('GetAvoidanceZones error: "%s"', [ErrorString])); finally FreeAndNil(AvoidanceZones); end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } unit IdSysWin32; interface uses IdSysNativeVCL, SysUtils; type TIdDateTimeBase = TDateTime; TIdSysWin32 = class(TIdSysNativeVCL) public class function Win32Platform: Integer; class function Win32MajorVersion : Integer; class function Win32MinorVersion : Integer; class function Win32BuildNumber : Integer; class function OffsetFromUTC: TIdDateTimeBase;// override; end; implementation uses IdException, IdResourceStrings, Windows; //EIdException is only in IdSys and that causes a circular reference //if IdException is the interface section so we have to move the declaration //of our exception type down here. type //This is called whenever there is a failure to retreive the time zone information EIdFailedToRetreiveTimeZoneInfo = class(EIdException); class function TIdSysWin32.OffsetFromUTC: TIdDateTimeBase; var iBias: Integer; tmez: TTimeZoneInformation; begin Case GetTimeZoneInformation(tmez) of TIME_ZONE_ID_INVALID: begin raise EIdFailedToRetreiveTimeZoneInfo.Create(RSFailedTimeZoneInfo); end; TIME_ZONE_ID_UNKNOWN : iBias := tmez.Bias; TIME_ZONE_ID_DAYLIGHT : iBias := tmez.Bias + tmez.DaylightBias; TIME_ZONE_ID_STANDARD : iBias := tmez.Bias + tmez.StandardBias; else begin raise EIdFailedToRetreiveTimeZoneInfo.Create(RSFailedTimeZoneInfo); end; end; {We use ABS because EncodeTime will only accept positve values} Result := EncodeTime(Abs(iBias) div 60, Abs(iBias) mod 60, 0, 0); {The GetTimeZone function returns values oriented towards convertin a GMT time into a local time. We wish to do the do the opposit by returning the difference between the local time and GMT. So I just make a positive value negative and leave a negative value as positive} if iBias > 0 then begin Result := 0 - Result; end; end; class function TIdSysWin32.Win32MinorVersion: Integer; begin Result := SysUtils.Win32MinorVersion; end; class function TIdSysWin32.Win32BuildNumber: Integer; begin // for this, you need to strip off some junk to do comparisons Result := SysUtils.Win32BuildNumber and $FFFF; end; class function TIdSysWin32.Win32Platform: Integer; begin Result := SysUtils.Win32Platform; end; class function TIdSysWin32.Win32MajorVersion: Integer; begin Result := SysUtils.Win32MajorVersion; end; end.
unit ce_optionseditor; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, RTTIGrids, Forms, Controls, Graphics, ExtCtrls, Menus, ComCtrls, Buttons, ce_common, ce_widget, ce_interfaces, ce_observer, PropEdits, ObjectInspector; type // store the information about the obsever // exposing some editable options. PCategoryData = ^TCategoryData; TCategoryData = record kind: TOptionEditorKind; container: TPersistent; observer: ICEEditableOptions; end; { TCEOptionEditorWidget } TCEOptionEditorWidget = class(TCEWidget) btnCancel: TSpeedButton; btnAccept: TSpeedButton; pnlEd: TPanel; pnlBody: TPanel; pnlFooter: TPanel; Splitter1: TSplitter; inspector: TTIPropertyGrid; selCat: TTreeView; procedure btnAcceptClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure inspectorEditorFilter(Sender: TObject; aEditor: TPropertyEditor; var aShow: boolean); procedure inspectorModified(Sender: TObject); procedure selCatChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure selCatDeletion(Sender: TObject; Node: TTreeNode); procedure selCatSelectionChanged(Sender: TObject); protected procedure UpdateShowing; override; private fCatChanged: boolean; fEdOptsSubj: TCEEditableOptionsSubject; procedure updateCategories; function allowCategoryChange: boolean; function sortCategories(Cat1, Cat2: TTreeNode): integer; public constructor create(aOwner: TComponent); override; destructor destroy; override; end; implementation {$R *.lfm} const msg_mod = 'The current category modifications are not validated, discard them and continue ?'; {$REGION Standard Comp/Obj------------------------------------------------------} constructor TCEOptionEditorWidget.create(aOwner: TComponent); var png: TPortableNetworkGraphic; begin inherited; fDockable := false; fModal:= true; fEdOptsSubj := TCEEditableOptionsSubject.create; inspector.CheckboxForBoolean := true; inspector.PropertyEditorHook.AddHandlerModified(@inspectorModified); // png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('cancel'); btnCancel.Glyph.Assign(png); png.LoadFromLazarusResource('accept'); btnAccept.Glyph.Assign(png); finally png.Free; end; end; destructor TCEOptionEditorWidget.destroy; begin fCatChanged := false; fEdOptsSubj.Free; inherited; end; procedure TCEOptionEditorWidget.UpdateShowing; begin inherited; if Visible then updateCategories; end; {$ENDREGION} {$REGION Option editor things --------------------------------------------------} procedure TCEOptionEditorWidget.updateCategories; var i: Integer; dt: PCategoryData; ed: ICEEditableOptions; begin inspector.TIObject := nil; selCat.Items.Clear; for i:= 0 to fEdOptsSubj.observersCount-1 do begin dt := new(PCategoryData); ed := fEdOptsSubj.observers[i] as ICEEditableOptions; selCat.Items.AddObject(nil, ed.optionedWantCategory, dt); dt^.container := ed.optionedWantContainer; dt^.kind := ed.optionedWantEditorKind; dt^.observer := ed; end; selCat.Items.SortTopLevelNodes(@sortCategories); end; function TCEOptionEditorWidget.sortCategories(Cat1, Cat2: TTreeNode): integer; begin result := CompareText(Cat1.Text, Cat2.Text); end; procedure TCEOptionEditorWidget.selCatDeletion(Sender: TObject; Node: TTreeNode); begin if node.Data <> nil then Dispose(PCategoryData(node.Data)); end; function TCEOptionEditorWidget.allowCategoryChange: boolean; var dt: PCategoryData; begin result := true; if selCat.Selected = nil then exit; if selCat.Selected.Data = nil then exit; // accept/cancel is relative to a single category dt := PCategoryData(selCat.Selected.Data); // generic editor, changes are tracked directly here if dt^.kind = oekGeneric then begin if fCatChanged then begin result := dlgOkCancel(msg_mod) = mrOk; fCatChanged := not result; if result then btnCancelClick(nil); end; // custom editor, changes are notified by optionedOptionsModified() end else begin dt := PCategoryData(selCat.Selected.Data); if dt^.container = nil then exit; if dt^.observer.optionedOptionsModified() then begin result := dlgOkCancel(msg_mod) = mrOk; if result then btnCancelClick(nil); end; end; end; procedure TCEOptionEditorWidget.selCatChanging(Sender: TObject;Node: TTreeNode; var AllowChange: Boolean); begin AllowChange := allowCategoryChange; end; procedure TCEOptionEditorWidget.selCatSelectionChanged(Sender: TObject); var dt: PCategoryData; begin // remove either the control, the form or the inspector used as editor. inspector.TIObject := nil; if pnlEd.ControlCount > 0 then pnlEd.Controls[0].Parent := nil; // if selCat.Selected = nil then exit; if selCat.Selected.Data = nil then exit; // dt := PCategoryData(selCat.Selected.Data); if dt^.container = nil then exit; case dt^.kind of oekControl: begin TWinControl(dt^.container).Parent := pnlEd; TWinControl(dt^.container).Align := alClient; end; oekForm: begin TCustomForm(dt^.container).Parent := pnlEd; TCustomForm(dt^.container).Align := alClient; TCustomForm(dt^.container).BorderIcons:= []; TCustomForm(dt^.container).BorderStyle:= bsNone; end; oekGeneric: begin inspector.Parent := pnlEd; inspector.Align := alClient; inspector.TIObject := dt^.container; end; end; // PCategoryData(selCat.Selected.Data)^ .observer .optionedEvent(oeeSelectCat); end; procedure TCEOptionEditorWidget.inspectorModified(Sender: TObject); begin if selCat.Selected = nil then exit; if selcat.Selected.Data = nil then exit; // fCatChanged := true; PCategoryData(selCat.Selected.Data)^ .observer .optionedEvent(oeeChange); end; procedure TCEOptionEditorWidget.btnCancelClick(Sender: TObject); begin if selCat.Selected = nil then exit; if selcat.Selected.Data = nil then exit; // fCatChanged := false; if inspector.Parent <> nil then inspector.ItemIndex := -1; PCategoryData(selCat.Selected.Data)^ .observer .optionedEvent(oeeCancel); end; procedure TCEOptionEditorWidget.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin canClose := allowCategoryChange; end; procedure TCEOptionEditorWidget.inspectorEditorFilter(Sender: TObject;aEditor: TPropertyEditor; var aShow: boolean); begin if aEditor.GetComponent(0) is TComponent then begin if aEditor.GetPropInfo^.Name = 'Tag' then aShow := false else if aEditor.GetPropInfo^.Name = 'Name' then aShow := false else if aEditor.GetPropInfo^.PropType = TypeInfo(TCollection) then aShow := false; end; end; procedure TCEOptionEditorWidget.btnAcceptClick(Sender: TObject); begin if selCat.Selected = nil then exit; if selcat.Selected.Data = nil then exit; // fCatChanged := false; if inspector.Parent <> nil then inspector.ItemIndex := -1; PCategoryData(selCat.Selected.Data)^ .observer .optionedEvent(oeeAccept); end; {$ENDREGION} end.
unit sSkinProps; {$I sDefs.inc} interface uses StdCtrls, sConst; const // Images s_BordersMask = 'BORDERSMASK'; s_OuterMask = 'OUTERMASK'; s_ExBorder = 'EXBORDER'; s_LightRegion = 'LRGN'; s_Glow = 'GLOW'; s_GlowMargin = 'GLOWMARGIN'; s_BorderRadius = 'BORDERRADIUS'; s_GripImage = 'GRIPIMAGE'; s_GripHorz = 'GRIPHORZ'; s_GripVert = 'GRIPVERT'; s_StatusPanelMask = 'STATUSPANELMASK'; s_ImgTopLeft = 'IMGTOPLEFT'; s_ImgTopRight = 'IMGTOPRIGHT'; s_ImgBottomLeft = 'IMGBTMLEFT'; s_ImgBottomRight = 'IMGBTMRIGHT'; s_NormalTitleBar = 'TITLEBAR'; s_BorderIconClose = 'BICONCLOSE'; s_BorderIconCloseAlone = 'BICLOSEALONE'; s_BorderIconMaximize = 'BICONMAX'; s_BorderIconNormalize = 'BICONNORM'; s_BorderIconMinimize = 'BICONMIN'; s_BorderIconHelp = 'BICONHELP'; s_TitleButtonMask = 'TITLEBUTTON'; s_SmallIconNormalize = 'SICONNORM'; s_SmallIconMinimize = 'SICONMIN'; s_SmallIconMaximize = 'SICONMAX'; s_SmallIconClose = 'SICONCLOSE'; s_SmallIconHelp = 'SICONHELP'; s_SliderChannelMask = 'SLIDERCHANNEL'; s_ItemGlyph = 'GLYPHMASK'; s_SliderHorzMask = 'SLIDERMASK'; s_SliderVertMask = 'SLIDERVMASK'; s_TickVert = 'TICKVERT'; s_TickHorz = 'TICKHORZ'; s_ProgVert = 'PROGVERT'; s_ProgHorz = 'PROGHORZ'; s_NA = 'N/A'; // Properties common for SkinSections <<<<<<<<< s_ParentClass = 'PARENTCLASS'; s_ReservedBoolean = 'RESERVEDBOOLEAN'; s_GiveOwnFont = 'GIVEOWNFONT'; s_ShiftOnClick = 'SHIFTCLICK'; s_ShowFocus = 'SHOWFOCUS'; s_UseState2 = 'USESTATE2'; // State 0 s_FontColor = 'FONTCOLOR'; s_TCLeft = 'TCLEFT'; s_TCTop = 'TCTOP'; s_TCRight = 'TCRIGHT'; s_TCBottom = 'TCBOTTOM'; s_Color = 'COLOR'; s_Transparency = 'TRANSPARENCY'; s_GradientPercent = 'GRADIENTPERCENT'; s_GradientData = 'GRADIENTDATA'; s_ImagePercent = 'IMAGEPERCENT'; s_Pattern = 'PATTERN'; s_GlowColor = 'GCOL'; s_GlowSize = 'GSIZE'; s_LightColor0 = 'LIGHT0'; // State 1 s_HotFontColor = 'HOT' + s_FontColor; s_HotTCLeft = 'HOT' + s_TCLeft; s_HotTCTop = 'HOT' + s_TCTop; s_HotTCRight = 'HOT' + s_TCRight; s_HotTCBottom = 'HOT' + s_TCBottom; s_HotColor = 'HOT' + s_Color; s_HotTransparency = 'HOT' + s_Transparency; s_HotGradientPercent = 'HOT' + s_GradientPercent; s_HotGradientData = 'HOT' + s_GradientData; s_HotImagePercent = 'HOT' + s_ImagePercent; s_HotPattern = 'HOT' + s_Pattern; s_HotGlowColor = 'H' + s_GlowColor; s_HotGlowSize = 'H' + s_GlowSize; s_LightColor1 = 'LIGHT1'; // State 2 s_FontColor2 = s_FontColor + '2'; s_TCLeft2 = s_TCLeft + '2'; s_TCTop2 = s_TCTop + '2'; s_TCRight2 = s_TCRight + '2'; s_TCBottom2 = s_TCBottom + '2'; s_Color2 = s_Color + '2'; s_Transparency2 = s_Transparency + '2'; s_GradientPercent2 = s_GradientPercent + '2'; s_GradientData2 = s_GradientData + '2'; s_ImagePercent2 = s_ImagePercent + '2'; s_Pattern2 = s_Pattern + '2'; s_GlowColor2 = s_GLOWCOLOR + '2'; s_GlowSize2 = s_GLOWSIZE + '2'; s_LightColor2 = 'LIGHT2'; // End of common props >>>>>>>>>>>>>>>>>>>>>>>> s_BorderColor0 = 'BORDERCOLOR0'; s_BorderColor1 = 'BORDERCOLOR1'; s_BorderColor2 = 'BORDERCOLOR2'; s_BorderWidth = 'BORDERWIDTH'; s_TitleHeight = 'TITLEHEIGHT'; s_FormOffset = 'FORMOFFSET'; // Content offset s_ShadowOffset = 'ALIGNOFFSET'; // Additional offset for a shadow s_ShadowOffsetR = 'ALIGNOFFSETR'; s_ShadowOffsetT = 'ALIGNOFFSETT'; s_ShadowOffsetB = 'ALIGNOFFSETB'; s_WndShadowRadius = 'WSHRAD'; s_WndShadowOffset = 'WSHOFFS'; s_WndShadowSize = 'WSHSIZE'; s_WndShadowColorN = 'WSHCOLN'; s_WndShadowColorA = 'WSHCOLA'; s_CenterOffset = 'CENTEROFFSET'; s_MaxTitleHeight = 'MAXHEIGHT'; s_BorderMode = 'BORDERMODE'; s_BrightMin = 'BRIGHTMIN'; s_BrightMax = 'BRIGHTMAX'; // Global Colors s_BorderColor = 'BORDERCOLOR'; s_EditTextOk = 'EDITTEXT_OK'; s_EditTextWarning = 'EDITTEXT_WARN'; s_EditTextAlert = 'EDITTEXT_ALERT'; s_EditTextHighlight1 = 'EDITTEXT_H1'; s_EditTextHighlight2 = 'EDITTEXT_H2'; s_EditTextHighlight3 = 'EDITTEXT_H3'; s_EditText_Inverted = 'EDITTEXT_INV'; s_EditBG_Inverted = 'EDITBG_INV'; s_EditBG_OddRow = 'EDITBG_ODD'; s_EditBG_EvenRow = 'EDITBG_EVEN'; s_EditBGOk = 'EDITBG_OK'; s_EditBGWarning = 'EDITBG_WARN'; s_EditBGAlert = 'EDITBG_ALERT'; s_EditGridLine = 'GRIDLINE'; s_MainColor = 'MAINCOLOR'; // Just filled by main skin color s_BtnColor1Active = 'BTNCOLOR1ACTIVE'; s_BtnColor2Active = 'BTNCOLOR2ACTIVE'; s_BtnBorderActive = 'BTNBORDERACTIVE'; s_BtnFontActive = 'BTNFONTACTIVE'; s_BtnColor1Normal = 'BTNCOLOR1NORMAL'; s_BtnColor2Normal = 'BTNCOLOR2NORMAL'; s_BtnBorderNormal = 'BTNBORDERNORMAL'; s_BtnFontNormal = 'BTNFONTNORMAL'; s_BtnColor1Pressed = 'BTNCOLOR1PRESSED'; s_BtnColor2Pressed = 'BTNCOLOR2PRESSED'; s_BtnBorderPressed = 'BTNBORDERPRESSED'; s_BtnFontPressed = 'BTNFONTPRESSED'; // Standard mandatory SkinSections s_GlobalInfo = 'GLOBALINFO'; s_Transparent = 'TRANSPARENT'; // Special fully transparent section s_Caption = 'CAPTION'; s_FormTitle = 'FORMTITLE'; s_Form = 'FORM'; s_Dialog = 'DIALOG'; s_Hint = 'HINT'; s_MDIArea = 'MDIAREA'; s_MainMenu = 'MAINMENU'; s_MenuItem = 'MENUITEM'; s_Selection = 'SELECTION'; s_MenuIcoLine = 'ICOLINE'; s_MenuExtraLine = 'EXTRALINE'; s_ScrollBar1H = 'SCROLLBAR1H'; s_ScrollBar1V = 'SCROLLBAR1V'; s_ScrollBar2H = 'SCROLLBAR2H'; s_ScrollBar2V = 'SCROLLBAR2V'; s_ScrollSliderV = 'SCROLLSLIDERV'; s_ScrollSliderH = 'SCROLLSLIDERH'; s_ScrollBtnLeft = 'SCROLLBTNLEFT'; s_ScrollBtnTop = 'SCROLLBTNTOP'; s_ScrollBtnRight = 'SCROLLBTNRIGHT'; s_ScrollBtnBottom = 'SCROLLBTNBOTTOM'; s_Divider = 'DIVIDER'; s_DividerV = 'DIVIDERV'; s_ColHeader = 'COLHEADER'; s_ProgressH = 'PROGRESSH'; s_ProgressV = 'PROGRESSV'; s_AlphaEdit = 'ALPHAEDIT'; s_TabTop = 'TABTOP'; s_RibbonTab = 'RIBBONTAB'; s_TabBottom = 'TABBOTTOM'; s_TabLeft = 'TABLEFT'; s_TabRight = 'TABRIGHT'; s_Edit = 'EDIT'; s_ToolButton = 'TOOLBUTTON'; s_ComboBox = 'COMBOBOX'; s_ComboBtn = 'COMBOBTN'; s_AlphaComboBox = 'ALPHACOMBOBOX'; s_ComboNoEdit = 'COMBONOEDIT'; s_UpDown = 'UPDOWNBTN'; s_Button = 'BUTTON'; s_ButtonBig = 'BUTTON_BIG'; s_ButtonHuge = 'BUTTON_HUGE'; s_SpeedButton = 'SPEEDBUTTON'; s_SpeedButton_Small = 'SPEEDBUTTON_SMALL'; s_Panel = 'PANEL'; s_PanelLow = 'PANEL_LOW'; s_TabControl = 'TABCONTROL'; s_PageControl = 'PAGECONTROL'; s_RibbonPage = 'RIBBONPAGE'; s_TabSheet = 'TABSHEET'; s_StatusBar = 'STATUSBAR'; s_ToolBar = 'TOOLBAR'; s_Splitter = 'SPLITTER'; s_GroupBox = 'GROUPBOX'; s_Gauge = 'GAUGE'; s_TrackBar = 'TRACKBAR'; s_CheckBox = 'CHECKBOX'; s_RadioButton = 'CHECKBOX'; s_DragBar = 'DRAGBAR'; s_Bar = 'BAR'; s_BarTitle = 'BARTITLE'; s_BarPanel = 'BARPANEL'; s_WebBtn = 'WEBBUTTON'; s_GripH = 'GRIPH'; s_GripV = 'GRIPV'; // Standard auxiliary SkinSections s_MenuCaption = 'MENUCAPTION'; s_DialogTitle = 'DIALOGTITLE'; s_MenuButton = 'MENUBTN'; s_MenuLine = 'MENULINE'; s_FormHeader = 'FORMHEADER'; s_TBBtn = 'TB_BTN'; s_TBMenuBtn = 'TB_MENUBTN'; s_TBTab = 'TB_TAB'; s_ColHeaderA = 'COLHEADERA'; // Alone column skin s_ColHeaderL = 'COLHEADERL'; s_ColHeaderR = 'COLHEADERR'; s_Slider_Off = 'SLIDER_OFF'; s_Slider_On = 'SLIDER_ON'; s_Thumb_Off = 'THUMB_OFF'; s_Thumb_On = 'THUMB_ON'; s_TabLeftFirst = 'TABLEFTFIRST'; s_TabTopFirst = 'TABTOPFIRST'; s_TabRightFirst = 'TABRIGHTFIRST'; s_TabBottomFirst = 'TABBOTTOMFIRST'; s_TabLeftLast = 'TABLEFTLAST'; s_TabTopLast = 'TABTOPLAST'; s_TabRightLast = 'TABRIGHTLAST'; s_TabBottomLast = 'TABBOTTOMLAST'; s_TabLeftMiddle = 'TABLEFTMIDDLE'; s_TabTopMiddle = 'TABTOPMIDDLE'; s_TabRightMiddle = 'TABRIGHTMIDDLE'; s_TabBottomMiddle = 'TABBOTTOMMIDDLE'; // Reserved words s_MasterBitmap = 'MASTERBITMAP'; s_Preview = 'PREVIEW'; s_CheckGlyph = 'CHECK'; s_CheckBoxChecked = 'BOXCHECKED'; s_CheckBoxUnChecked = 'BOXUNCHECKED'; s_CheckBoxGrayed = 'BOXGRAYED'; s_RadioButtonChecked = 'RADIOCHECKED'; s_RadioButtonUnChecked = 'RADIOUNCHECKED'; s_SmallBoxChecked = 'SMALLCHECKED'; s_SmallBoxUnChecked = 'SMALLUNCHECKED'; s_SmallBoxGrayed = 'SMALLGRAYED'; s_Version = 'VERSION'; s_Author = 'AUTHOR'; s_Description = 'DESCRIPTION'; s_ColorToneRed = 'COLORTONERED'; s_ColorToneGreen = 'COLORTONEGREEN'; s_ColorToneBlue = 'COLORTONEBLUE'; s_ColorToneYellow = 'COLORTONEYELLOW'; s_ColorToneRedActive = 'COLORTONEREDACTIVE'; s_ColorToneGreenActive = 'COLORTONEGREENACTIVE'; s_ColorToneBlueActive = 'COLORTONEBLUEACTIVE'; s_ColorToneYellowActive = 'COLORTONEYELLOWACTIVE'; s_ColorRedText = 'COLORTONEREDTEXT'; s_ColorGreenText = 'COLORTONEGREENTEXT'; s_ColorBlueText = 'COLORTONEBLUETEXT'; s_ColorYellowText = 'COLORTONEYELLOWTEXT'; s_ColorRedTextActive = 'COLORTONEREDTEXTACTIVE'; s_ColorGreenTextActive = 'COLORTONEGREENTEXTACTIVE'; s_ColorBlueTextActive = 'COLORTONEBLUETEXTActive'; s_ColorYellowTextActive = 'COLORTONEYELLOWTEXTActive'; s_Shadow1Color = 'SHADOW1COLOR'; s_Shadow1Offset = 'SHADOW1OFFSET'; s_Shadow1Blur = 'SHADOW1BLUR'; s_Shadow1Transparency = 'SHADOW1TRANSPARENCY'; s_DefLight = 'DEFLIGHT'; s_BISpacing = 'BISPACE'; s_BIVAlign = 'BIVALIGN'; s_BIRightMargin = 'BIRIGHT'; s_BILeftMargin = 'BILEFT'; s_BITopMargin = 'BITOP'; s_BIKeepHUE = 'BIKEEPHUE'; s_TabsCovering = 'TABSCOVERING'; s_ArrowLineWidth = 'ARROWLINE'; s_ArrowStyle = 'ARROWSTYLE'; s_States = 'STATES'; s_UseAeroBluring = 'AEROBLUR'; s_ScrollsArrows = 'SCROLLSARROWS'; s_ScrollsWidth = 'SCROLLSWIDTH'; s_ThumbWidth = 'THUMBWIDTH'; s_ComboMargin = 'COMBOMARGIN'; s_SliderMargin = 'SLIDERMARGIN'; // Outer effects s_OuterOffsL = 'OUTOFFSL'; s_OuterOffsT = 'OUTOFFST'; s_OuterOffsR = 'OUTOFFSR'; s_OuterOffsB = 'OUTOFFSB'; s_OuterMode = 'OUTERMODE'; // 0 - None, 1 - Lowered (work if OUTERMASK is empty), 2 - Shadow, 3 - Custom (calculated or raster) s_OuterOpacity = 'OUTOPACITY'; s_OuterColorL = 'OUTCOLL'; s_OuterColorT = 'OUTCOLT'; s_OuterColorR = 'OUTCOLR'; s_OuterColorB = 'OUTCOLB'; s_OuterBlur = 'OUTBLUR'; s_OuterRadius = 'OUTRADIUS'; s_ShOERadius = 'SH_RADIUS_OE'; s_LoOERadius = 'LO_RADIUS_OE'; s_ShOEBlur = 'SH_BLUR_OE'; s_LoOEBlur = 'LO_BLUR_OE'; s_ShadowColorL = 'SH_COLORL'; // Main shadow { s_ShadowColorT = 'SH_COLORT'; s_ShadowColorR = 'SH_COLORR'; s_ShadowColorB = 'SH_COLORB'; } s_ShadowWidthL = 'SH_WIDTHL'; s_ShadowWidthT = 'SH_WIDTHT'; s_ShadowWidthR = 'SH_WIDTHR'; s_ShadowWidthB = 'SH_WIDTHB'; s_ShadowOffsL = 'SH_OFFSETL'; s_ShadowOffsT = 'SH_OFFSETT'; s_ShadowOffsR = 'SH_OFFSETR'; s_ShadowOffsB = 'SH_OFFSETB'; s_ShadowSource = 'SH_SOURCE'; s_ShadowOpacity = 'SH_OPACITY'; s_ShadowMask = 'SH_MASK'; s_LowColorL = 'LO_COLORL'; // Main lowered s_LowColorT = 'LO_COLORT'; s_LowColorR = 'LO_COLORR'; s_LowColorB = 'LO_COLORB'; s_LowWidthL = 'LO_WIDTHL'; s_LowWidthT = 'LO_WIDTHT'; s_LowWidthR = 'LO_WIDTHR'; s_LowWidthB = 'LO_WIDTHB'; s_LowOffsL = 'LO_OFFSETL'; s_LowOffsT = 'LO_OFFSETT'; s_LowOffsR = 'LO_OFFSETR'; s_LowOffsB = 'LO_OFFSETB'; s_LowSource = 'LO_SOURCE'; s_LowOpacity = 'LO_OPACITY'; s_LowMask = 'LO_MASK'; acTabSections: array [TacTabLayout, TacSide] of string = ( (s_TabLeftFirst, s_TabTopFirst, s_TabRightFirst, s_TabBottomFirst), // tpFirst (s_TabLeftLast, s_TabTopLast, s_TabRightLast, s_TabBottomLast), // tpLast (s_TabLeftMiddle, s_TabTopMiddle, s_TabRightMiddle, s_TabBottomMiddle), // tpMiddle (s_TabLeft, s_TabTop, s_TabRight, s_TabBottom) // tpSingle ); acScrollBtns: array [TacSide] of string = (s_ScrollBtnLeft, s_ScrollBtnTop, s_ScrollBtnRight, s_ScrollBtnBottom); acScrollParts: array [TacSide] of string = (s_ScrollBar1H, s_ScrollBar1V, s_ScrollBar2H, s_ScrollBar2V); acUpDownBtns: array [TacSide] of string = (s_UpDown + '_LEFT', s_UpDown + '_TOP', s_UpDown + 'RIGHT', s_UpDown + '_BOTTOM'); acScrollSliders: array [boolean] of string = (s_ScrollSliderH, s_ScrollSliderV); acRadioGlyphs: array [boolean] of string = (s_RadioButtonUnChecked, s_RadioButtonChecked); acCheckGlyphs: array [TCheckBoxState] of string = (s_CheckBoxUnChecked, s_CheckBoxChecked, s_CheckBoxGrayed); acSmallChecks: array [TCheckBoxState] of string = (s_SmallBoxUnChecked, s_SmallBoxChecked, s_SmallBoxGrayed); implementation end.
unit AnimationArchive; interface uses SysUtils, Math, PngFunctions, Contnrs, Generics.Collections, Graphics, PositionRecord, SizeRecord, pngimage, Classes, Windows, Animation, Frame; type TAnimationArchive = class protected fImageArchive: TObjectList; fAnimations: TObjectDictionary<string, TAnimation>; function AddImagesFromJoinedFile(fileName : string; Columns, Rows: Integer) : Integer; function AddImage(fileName : string) : integer; public constructor Create(fileName : string; Columns, Rows: Integer); destructor Destroy(); procedure DrawImage(canvas : TCanvas; x,y : Integer; imageIndex : integer); function AddAnimation(Name : string) : TAnimation; function GetAnimation(Name : string) : TAnimation; procedure DrawAnimation(Name : string; canvas : TCanvas; x,y : Integer; totalElapsedSeconds : Double); end; implementation constructor TAnimationArchive.Create(fileName : string; Columns, Rows: Integer); begin fImageArchive := TObjectList.Create(True); fAnimations := TObjectDictionary<string, TAnimation>.Create([doOwnsValues]); AddImagesFromJoinedFile(fileName,Columns, Rows); end; destructor TAnimationArchive.Destroy(); begin fImageArchive.Free(); fAnimations.Free(); end; function TAnimationArchive.AddAnimation(Name: string): TAnimation; begin fAnimations.Add(Name, TAnimation.Create()); Result := fAnimations[Name]; end; function TAnimationArchive.GetAnimation(Name: string): TAnimation; begin Result := fAnimations[Name]; end; function TAnimationArchive.AddImage(fileName : string) : integer; var image : TPngImage; begin image := TPngImage.Create(); image.LoadFromFile(fileName); fImageArchive.Add(image); Result := fImageArchive.Count - 1; end; function TAnimationArchive.AddImagesFromJoinedFile(fileName : string; Columns, Rows: Integer) : Integer; var image : TPngImage; begin image := TPngImage.Create(); image.LoadFromFile(fileName); SlicePNG(image,Columns,Rows,fImageArchive); Result := fImageArchive.Count - 1; end; procedure TAnimationArchive.DrawAnimation(Name: string; canvas: TCanvas; x, y: Integer; totalElapsedSeconds: Double); var frame : TFrame; image : TPngImage; begin frame := fAnimations[Name].GetCurrentFrame(totalElapsedSeconds); image := fImageArchive[frame.GetImageIndex()] as TPngImage; x := x + Frame.GetOffset().X; y := y + Frame.GetOffset().Y; image.Draw(canvas,Rect(x,y,x + image.Width, y + image.Height)); end; procedure TAnimationArchive.DrawImage(canvas : TCanvas; x,y : Integer; imageIndex : Integer); var image : TPngImage; begin //if((x > - image.Width) and (x < clientSize.Width)) and ((y > - image.Height) and (y < clientSize.Height)) then image := fImageArchive[imageIndex] as TPngImage; image.Draw(canvas,Rect(x,y,x + image.Width, y + image.Height)); end; end.
unit kwF1BaseDate; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "F1 Words" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/F1_Words/kwF1BaseDate.pas" // Начат: 14.11.2011 19:32 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> F1 Поддержка тестов::F1 Words::Words::f1_BaseDate // // Кладёт на стек дату базы в строковом формате // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\GbaNemesis\nsDefine.inc} interface uses Classes {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts ; type {$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwF1BaseDate = class(_tfwAutoregisteringWord_) {* Кладёт на стек дату базы в строковом формате } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts public // overridden public methods {$If not defined(NoScripts)} class function GetWordNameForRegister: AnsiString; override; {$IfEnd} //not NoScripts end;//TkwF1BaseDate implementation uses bsUtils {$If not defined(NoScripts)} , tfwAutoregisteredDiction {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts ; type _Instance_R_ = TkwF1BaseDate; {$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwF1BaseDate {$If not defined(NoScripts)} procedure TkwF1BaseDate.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4EC134690154_var* //#UC END# *4DAEEDE10285_4EC134690154_var* begin //#UC START# *4DAEEDE10285_4EC134690154_impl* aCtx.rEngine.PushString(bsBaseDateStr); //#UC END# *4DAEEDE10285_4EC134690154_impl* end;//TkwF1BaseDate.DoDoIt {$IfEnd} //not NoScripts {$If not defined(NoScripts)} class function TkwF1BaseDate.GetWordNameForRegister: AnsiString; {-} begin Result := 'f1:BaseDate'; end;//TkwF1BaseDate.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$Include w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteringWord.imp.pas} end.
unit GetOrdersWithCustomFieldsResponseUnit; interface uses REST.Json.Types, SysUtils, GenericParametersUnit, OrderUnit, CommonTypesUnit; type TGetOrdersWithCustomFieldsResponse = class(TGenericParameters) private [JSONName('results')] FResults: TArray<TArray<string>>; [JSONName('total')] FTotal: integer; [JSONName('fields')] FFields: TStringArray; function GetResults(index: integer): TStringArray; function GetResultCount: Integer; public constructor Create; override; function GetResult(index: integer; Field: String): String; property Total: integer read FTotal; property Fields: TStringArray read FFields; property Results[index: integer]: TStringArray read GetResults; property ResultCount: Integer read GetResultCount; end; implementation { TGetOrdersWithCustomFieldsResponse } constructor TGetOrdersWithCustomFieldsResponse.Create; begin inherited; SetLength(FResults, 0); SetLength(FFields, 0); end; function TGetOrdersWithCustomFieldsResponse.GetResult(index: integer; Field: String): String; var Results: TStringArray; i: Integer; begin Result := EmptyStr; Results := FResults[index]; for i := 0 to High(FFields) do if (FFields[i] = Field) then begin Result := Results[i]; Break end; end; function TGetOrdersWithCustomFieldsResponse.GetResultCount: Integer; begin Result := Length(FResults); end; function TGetOrdersWithCustomFieldsResponse.GetResults(index: integer): TStringArray; begin Result := FResults[index]; end; end.
unit Control.CadastroGR; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.CadastroGR; type TCadastroGRControl = class private FGR : TCadastroGR; public constructor Create; destructor Destroy; override; property GR: TCadastroGR read FGR write FGR; function Localizar(aParam: array of variant): boolean; function Gravar(): Boolean; function SetupClass(FDquery: TFDQuery): Boolean; function ClearClass(): Boolean; end; implementation { TCadastroGRControl } function TCadastroGRControl.ClearClass: Boolean; begin Result := FGR.ClearClass(); end; constructor TCadastroGRControl.Create; begin FGR := TCadastroGR.Create; end; destructor TCadastroGRControl.Destroy; begin FGR.Free; inherited; end; function TCadastroGRControl.Gravar: Boolean; begin Result := False; Result := FGR.Gravar; end; function TCadastroGRControl.Localizar(aParam: array of variant): boolean; begin Result := FGR.Localizar(aParam); end; function TCadastroGRControl.SetupClass(FDquery: TFDQuery): Boolean; begin Result := FGR.SetupClass(FDQuery); end; end.
unit CanvasBmp; interface uses Classes, Consts, Windows, SysUtils, Graphics, MemUtils, Gdi, GdiExt, Buffer; // TCanvasedBuffer =============================================================================== const csAllValid = [csHandleValid..csBrushValid]; type TStretchBltMode = type integer; type TBufferCanvas = class; TCanvasedBitmap = class( TBuffer ) protected fCanvas : TBufferCanvas; fStretchBltMode : TStretchBltMode; fShared : boolean; protected function GetCanvas : TBufferCanvas; virtual; abstract; procedure FreeContext; override; function GetPixels( x, y : integer ) : TColor; override; procedure SetPixels( x, y : integer; Value : TColor ); override; public property Canvas : TBufferCanvas read GetCanvas; procedure SnapshotDC( dc : HDC; x, y : integer; UseColors : boolean ); virtual; abstract; procedure StretchSnapshotDC( dc : HDC; const Rect : TRect; UseColors : boolean ); virtual; abstract; procedure ClipSnapshotDC( dc : HDC; x, y : integer; const ClippingRect : TRect; UseColors : boolean ); virtual; abstract; procedure ClipStretchSnapshotDC( dc : HDC; const Rect, ClippingRect : TRect; UseColors : boolean ); virtual; abstract; procedure TileOnDC( dc : HDC; x, y : integer; const ClippingRect : TRect; aCopyMode : dword ); virtual; abstract; procedure DrawOnDC( dc : HDC; x, y : integer; aCopyMode : dword ); virtual; abstract; procedure StretchDrawOnDC( dc : HDC; const Rect : TRect; aCopyMode : dword ); virtual; abstract; procedure ClipDrawOnDC( dc : HDC; x, y : integer; const ClippingRect : TRect; aCopyMode : dword ); virtual; abstract; procedure ClipStretchDrawOnDC( dc : HDC; const Rect, ClippingRect : TRect; aCopyMode : dword ); virtual; abstract; procedure Tile( aCanvas : TCanvas; x, y : integer; const ClippingRect : TRect ); virtual; procedure Draw( aCanvas : TCanvas; x, y : integer ); virtual; procedure StretchDraw( aCanvas : TCanvas; const Rect : TRect ); virtual; procedure ClipDraw( aCanvas : TCanvas; x, y : integer; const ClippingRect : TRect ); virtual; procedure ClipStretchDraw( aCanvas : TCanvas; const Rect, ClippingRect : TRect ); virtual; public constructor Create; override; destructor Destroy; override; property Shared : boolean read fShared write fShared; published property StretchBltMode : TStretchBltMode read fStretchBltMode write fStretchBltMode; end; TBufferCanvas = class( TPersistent ) protected fHandle : HDC; fBitmap : TCanvasedBitmap; fFont : TFont; fPen : TPen; fBrush : TBrush; fPenPos : TPoint; fCopyMode : TCopyMode; State : TCanvasState; protected procedure CreateBrush; procedure SetBrush( Value : TBrush ); procedure BrushChanged( aBrush : TObject ); procedure CreateFont; procedure SetFont( Value : TFont ); procedure FontChanged( aFont : TObject ); procedure CreatePen; procedure SetPen( Value : TPen ); procedure PenChanged( aPen : TObject ); function GetClipRect : TRect; function GetPenPos : TPoint; procedure SetPenPos( const Value : TPoint ); function GetPixels( x, y : integer ) : TColor; procedure SetPixels( x, y : integer; Value : TColor ); function GetScanLines : pointer; function GetPixelAddr(x, y : integer ) : pointer; function GetHandle : HDC; procedure SetHandle( Value : HDC ); procedure DeselectHandles; protected procedure CreateHandle; virtual; abstract; procedure FreeContext; virtual; public procedure RequiredState( ReqState : TCanvasState ); public constructor Create( aBitmap : TCanvasedBitmap ); destructor Destroy; override; procedure Assign( Source : TPersistent ); override; procedure CopyRect( const Dest : TRect; Canvas : TBufferCanvas; const Source : TRect ); procedure Draw( x, y : integer; Graphic : TGraphic ); procedure StretchDraw( const Rect : TRect; Graphic : TGraphic ); procedure LineTo( x, y : integer ); procedure MoveTo( x, y : integer ); procedure Arc( x1, y1, x2, y2, X3, Y3, X4, Y4 : integer ); procedure Chord( x1, y1, x2, y2, X3, Y3, X4, Y4 : integer ); procedure Ellipse( x1, y1, x2, y2 : integer ); procedure Pie( x1, y1, x2, y2, x3, y3, x4, y4 : integer ); procedure Polygon( const Points : array of TPoint ); procedure PolyLine( const Points : array of TPoint ); procedure Rectangle( x1, y1, x2, y2 : integer ); procedure RoundRect( x1, y1, x2, y2, x3, y3 : integer ); procedure FrameRect( const Rect : TRect ); procedure FrameRgn( Region : HRGN; FrameWidth, FrameHeight : integer ); procedure DrawFocusRect( const Rect : TRect ); procedure FillRect( const Rect : TRect ); procedure PaintRgn( Region : HRGN ); procedure FillRgn( Region : HRGN; aBrush : HBRUSH ); procedure FloodFill( x, y : integer; Color : TColor; FillStyle : TFillStyle ); procedure Refresh; function TextHeight( const Text : string ) : integer; function TextWidth( const Text : string ) : integer; function TextExtent( const Text : string ) : TSize; procedure TextOut( x, y : integer; const Text : string ); procedure TextRect( const Rect : TRect; x, y : integer; const Text : string ); public property Pixels[x, y : integer] : TColor read GetPixels write SetPixels; default; property Handle : HDC read GetHandle write SetHandle; property PenPos : TPoint read GetPenPos write SetPenPos; property ClipRect : TRect read GetClipRect; public property CanvasHandle : HDC read fHandle; property ScanLines : pointer read GetScanLines; property PixelAddr[x, y : integer] : pointer read GetPixelAddr; published property Owner : TCanvasedBitmap read fBitmap; property CopyMode : TCopyMode read fCopyMode write fCopyMode default cmSrcCopy; property Brush : TBrush read fBrush write SetBrush; property Font : TFont read fFont write SetFont; property Pen : TPen read fPen write SetPen; end; function TransparentStretchBlt( DstDC : HDC; DstX, DstY, DstWidth, DstHeight : integer; SrcDC : HDC; SrcX, SrcY, SrcWidth, SrcHeight : integer; Mask : HBITMAP; SourceMasked : boolean ) : BOOL; // Internal helpers // ============================================================================ var BitmapCanvasList : TList = nil; implementation // GDI Stuff function SetBrushOrgEx( DC: HDC; X, Y: Integer; Points : pointer ): BOOL; stdcall; external 'GDI32.DLL' name 'SetBrushOrgEx'; function TransparentStretchBlt( DstDC : HDC; DstX, DstY, DstWidth, DstHeight : integer; SrcDC : HDC; SrcX, SrcY, SrcWidth, SrcHeight : integer; Mask : HBITMAP; SourceMasked : boolean ) : BOOL; var MaskDC : HDC; OldBitmap : HBITMAP; OldOffScrBmp : HBITMAP; OldForeColor : integer; OldBackColor : integer; OffScrBitmap : HBITMAP; OffScrDC : HDC; const ROP_DstCopy = $00AA0029; begin Result := true; MaskDC := GetBitmapDC( Mask, OldBitmap ); try if (Win32Platform = VER_PLATFORM_WIN32_NT) and (SrcWidth = DstWidth) and (SrcHeight = DstHeight) then MaskBlt( DstDC, DstX, DstY, DstWidth, DstHeight, SrcDC, SrcX, SrcY, Mask, SrcX, SrcY, MakeRop4( ROP_DstCopy, SRCCOPY ) ) else if SourceMasked then begin SetGdiColorsEx( DstDC, clBlack, clWhite, OldForeColor, OldBackColor ); try StretchBlt( DstDC, DstX, DstY, DstWidth, DstHeight, MaskDC, SrcX, SrcY, SrcWidth, SrcHeight, SRCAND ); StretchBlt( DstDC, DstX, DstY, DstWidth, DstHeight, SrcDC, SrcX, SrcY, SrcWidth, SrcHeight, SRCPAINT ); finally SetGdiColors( DstDC, OldForeColor, OldBackColor ); end; end else begin OffScrBitmap := CreateCompatibleBitmap( SrcDC, SrcWidth, SrcHeight ); OffScrDC := GetBitmapDC( OffScrBitmap, OldOffScrBmp ); try SetGdiColors( OffScrDC, clWhite, clBlack ); StretchBlt( OffScrDC, 0, 0, SrcWidth, SrcHeight, SrcDC, SrcX, SrcY, SrcWidth, SrcHeight, SRCCOPY ); StretchBlt( OffScrDC, 0, 0, SrcWidth, SrcHeight, MaskDC, SrcX, SrcY, SrcWidth, SrcHeight, SRCAND ); try SetGdiColorsEx( DstDC, clBlack, clWhite, OldForeColor, OldBackColor ); StretchBlt( DstDC, DstX, DstY, DstWidth, DstHeight, MaskDC, SrcX, SrcY, SrcWidth, SrcHeight, SRCAND ); StretchBlt( DstDC, DstX, DstY, DstWidth, DstHeight, OffScrDC, 0, 0, SrcWidth, SrcHeight, SRCPAINT ); finally SetGdiColors( DstDC, OldForeColor, OldBackColor ); end; finally ReleaseBitmapDC( OffScrDC, OldOffScrBmp ); DeleteObject( OffScrBitmap ); end; end; finally ReleaseBitmapDC( MaskDC, OldBitmap ); end; end; // TCanvasedBitmap ===================================================================== constructor TCanvasedBitmap.Create; begin inherited; fStretchBltMode := STRETCH_DELETESCANS; end; destructor TCanvasedBitmap.Destroy; begin FreeObject( fCanvas ); inherited; end; procedure TCanvasedBitmap.FreeContext; begin if Assigned( fCanvas ) then fCanvas.FreeContext; end; function TCanvasedBitmap.GetPixels( x, y : integer ) : TColor; begin Result := Canvas.GetPixels( x, y ); end; procedure TCanvasedBitmap.SetPixels( x, y : integer; Value : TColor ); begin Canvas.SetPixels( x, y, Value ); end; // Draw on VCL canvas methods -------------------- procedure TCanvasedBitmap.Tile( aCanvas : TCanvas; x, y : integer; const ClippingRect : TRect ); begin TileOnDC( aCanvas.Handle, x, y, ClippingRect, aCanvas.CopyMode ); end; procedure TCanvasedBitmap.Draw( aCanvas : TCanvas; x, y : integer ); begin DrawOnDC( aCanvas.Handle, x, y, aCanvas.CopyMode ); end; procedure TCanvasedBitmap.StretchDraw( aCanvas : TCanvas; const Rect : TRect ); begin StretchDrawOnDC( aCanvas.Handle, Rect, aCanvas.CopyMode ); end; procedure TCanvasedBitmap.ClipDraw( aCanvas : TCanvas; x, y : integer; const ClippingRect : TRect ); begin ClipDrawOnDC( aCanvas.Handle, x, y, ClippingRect, aCanvas.CopyMode ); end; procedure TCanvasedBitmap.ClipStretchDraw( aCanvas : TCanvas; const Rect, ClippingRect : TRect ); begin ClipStretchDrawOnDC( aCanvas.Handle, Rect, ClippingRect, aCanvas.CopyMode ); end; // TBufferCanvas ====================================================================== constructor TBufferCanvas.Create( aBitmap : TCanvasedBitmap ); begin inherited Create; fFont := TFont.Create; fFont.OnChange := FontChanged; fPen := TPen.Create; fPen.OnChange := PenChanged; fBrush := TBrush.Create; fBrush.OnChange := BrushChanged; fBitmap := aBitmap; fCopyMode := cmSrcCopy; State := []; end; destructor TBufferCanvas.Destroy; begin FreeContext; fFont.Free; fPen.Free; fBrush.Free; inherited; end; procedure TBufferCanvas.Assign( Source : TPersistent ); begin if Source is TBufferCanvas then with Source do begin Self.fCopyMode := fCopyMode; Self.fPen.Assign( fPen ); Self.fFont.Assign( fFont ); Self.fBrush.Assign( fBrush ); end else if Source is TCanvas then begin Self.fCopyMode := fCopyMode; Self.fPen.Assign( fPen ); Self.fFont.Assign( fFont ); Self.fBrush.Assign( fBrush ); end else inherited; end; procedure TBufferCanvas.Arc( x1, y1, x2, y2, X3, Y3, X4, Y4 : integer ); begin RequiredState( [csHandleValid, csPenValid] ); Windows.Arc( fHandle, x1, y1, x2, y2, X3, Y3, X4, Y4 ); end; procedure TBufferCanvas.Chord( x1, y1, x2, y2, X3, Y3, X4, Y4 : integer ); begin RequiredState( [csHandleValid, csPenValid, csBrushValid] ); Windows.Chord( fHandle, x1, y1, x2, y2, X3, Y3, X4, Y4 ); end; procedure TBufferCanvas.CopyRect( const Dest : TRect; Canvas : TBufferCanvas; const Source : TRect ); begin RequiredState( [csHandleValid] ); Canvas.RequiredState( [csHandleValid] ); StretchBlt( fHandle, Dest.Left, Dest.Top, Dest.Right - Dest.Left, Dest.Bottom - Dest.Top, Canvas.fHandle, Source.Left, Source.Top, Source.Right - Source.Left, Source.Bottom - Source.Top, CopyMode ); end; {$WARNINGS OFF} procedure DrawGraphic( Graphic : TGraphic; Rect : TRect; aCanvas : TBufferCanvas ); var MetaPalette : HPALETTE; OldPalette : HPALETTE; ChgPalette : boolean; dc : HDC; R : TRect; begin if Graphic is TBitmap then with TBitmap( Graphic ), Rect, aCanvas do begin assert( Assigned(aCanvas) and (not Graphic.Empty), 'Null Graphic in Buffer.DrawGraphic' ); dc := Canvas.Handle; with fBitmap do begin SetStretchBltMode( dc, StretchBltMode ); if StretchBltMode = STRETCH_HALFTONE then SetBrushOrgEx( dc, 0, 0, nil ); end; ChgPalette := (not IgnorePalette) and (Palette <> 0); if ChgPalette then begin OldPalette := SelectPalette( fHandle, Palette, false ); RealizePalette( fHandle ); end; try if Transparent then if GdiExtAvailable then TransparentBlt( fHandle, Left, Top, Right - Left, Bottom - Top, dc, 0, 0, Width, Height, TransparentColor ) else TransparentStretchBlt( fHandle, Left, Top, Right - Left, Bottom - Top, dc, 0, 0, Width, Height, MaskHandle, false ) else StretchBlt( fHandle, Left, Top, Right - Left, Bottom - Top, dc, 0, 0, Width, Height, CopyMode ); finally if ChgPalette then SelectPalette( fHandle, OldPalette, false ); end; end else if Graphic is TIcon then with Rect.TopLeft do DrawIcon( aCanvas.fHandle, x, y, TIcon(Graphic).Handle ) else if Graphic is TMetafile then with aCanvas, TMetafile( Graphic ) do begin MetaPalette := Palette; OldPalette := 0; if MetaPalette <> 0 then begin OldPalette := SelectPalette( fHandle, MetaPalette, true ); RealizePalette( fHandle ); end; R := Rect; Dec( R.Right ); // Metafile rect includes right and bottom coords Dec( R.Bottom ); PlayEnhMetaFile( fHandle, Handle, R); if MetaPalette <> 0 then SelectPalette( fHandle, OldPalette, true ); end; end; {$WARNINGS ON} procedure TBufferCanvas.Draw( x, y : integer; Graphic : TGraphic ); begin assert( Assigned(Graphic) and not Graphic.Empty, 'Empty graphic in Buffer.TSpeedCanvas.Draw!!' ); RequiredState( csAllValid ); SetBkColor( fHandle, ColorToRGB( fBrush.Color ) ); SetTextColor( fHandle, ColorToRGB( fFont.Color ) ); DrawGraphic( Graphic, Rect( x, y, x + Graphic.Width, y + Graphic.Height), Self ); end; procedure TBufferCanvas.StretchDraw( const Rect : TRect; Graphic : TGraphic ); begin assert( Assigned( Graphic ) and not Graphic.Empty, 'Empty graphic in Buffer.TSpeedCanvas.StretchDraw!!' ); RequiredState( csAllValid ); DrawGraphic( Graphic, Rect, Self ); end; procedure TBufferCanvas.DrawFocusRect( const Rect : TRect ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.DrawFocusRect( fHandle, Rect ); end; procedure TBufferCanvas.Ellipse( x1, y1, x2, y2 : integer ); begin RequiredState( [csHandleValid, csPenValid, csBrushValid] ); Windows.Ellipse( fHandle, x1, y1, x2, y2 ); end; procedure TBufferCanvas.FillRect( const Rect : TRect ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.FillRect( fHandle, Rect, Brush.Handle ); end; procedure TBufferCanvas.FillRgn( Region : HRGN; aBrush : HBRUSH ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.FillRgn( fHandle, Region, aBrush ); end; procedure TBufferCanvas.PaintRgn( Region : HRGN ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.PaintRgn( fHandle, Region ); end; procedure TBufferCanvas.FloodFill( x, y : integer; Color : TColor; FillStyle : TFillStyle ); const FillStyles : array[TFillStyle] of word = ( FLOODFILLSURFACE, FLOODFILLBORDER ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.ExtFloodFill( fHandle, x, y, Color, FillStyles[FillStyle] ); end; procedure TBufferCanvas.FrameRect( const Rect : TRect ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.FrameRect( fHandle, Rect, Brush.Handle ); end; procedure TBufferCanvas.FrameRgn( Region : HRGN; FrameWidth, FrameHeight : integer ); begin RequiredState( [csHandleValid, csBrushValid] ); Windows.FrameRgn( fHandle, Region, Brush.Handle, FrameWidth, FrameHeight ); end; procedure TBufferCanvas.LineTo( x, y : integer ); begin RequiredState( [csHandleValid, csPenValid] ); Windows.LineTo( fHandle, x, y ); end; procedure TBufferCanvas.MoveTo( x, y : integer ); begin RequiredState( [csHandleValid] ); Windows.MoveToEx( fHandle, x, y, nil ); end; procedure TBufferCanvas.Pie( x1, y1, x2, y2, X3, Y3, X4, Y4 : integer ); begin RequiredState( [csHandleValid, csPenValid, csBrushValid] ); Windows.Pie( fHandle, x1, y1, x2, y2, X3, Y3, X4, Y4 ); end; type PPoints = ^TPoints; TPoints = array[0..0] of TPoint; procedure TBufferCanvas.Polygon( const Points : array of TPoint ); begin RequiredState( [csHandleValid, csPenValid, csBrushValid] ); Windows.Polygon( fHandle, PPoints( @Points)^, High( Points) + 1 ); end; procedure TBufferCanvas.Polyline( const Points : array of TPoint ); begin RequiredState( [csHandleValid, csPenValid, csBrushValid] ); Windows.Polyline( fHandle, PPoints( @Points)^, High( Points) + 1 ); end; procedure TBufferCanvas.Rectangle( x1, y1, x2, y2 : integer ); begin RequiredState( [csHandleValid, csBrushValid, csPenValid] ); Windows.Rectangle( fHandle, x1, y1, x2, y2 ); end; procedure TBufferCanvas.Refresh; begin DeselectHandles; end; procedure TBufferCanvas.RoundRect( x1, y1, x2, y2, X3, Y3 : integer ); begin RequiredState( [csHandleValid, csBrushValid, csPenValid] ); Windows.RoundRect( fHandle, x1, y1, x2, y2, X3, Y3 ); end; procedure TBufferCanvas.TextOut( x, y : integer; const Text : string ); begin RequiredState( [csHandleValid, csFontValid, csBrushValid] ); Windows.TextOut( fHandle, x, y, pchar(Text), Length( Text) ); Windows.MoveToEx( fHandle, x + TextWidth( Text), y, nil ); end; procedure TBufferCanvas.TextRect( const Rect : TRect; x, y : integer; const Text : string ); var Options : integer; begin RequiredState( [csHandleValid, csFontValid, csBrushValid] ); Options := ETO_CLIPPED; if Brush.Style <> bsClear then Inc( Options, ETO_OPAQUE ); Windows.ExtTextOut( fHandle, x, y, Options, @Rect, pchar(Text), length(Text), nil ); end; function TBufferCanvas.TextWidth( const Text : String ) : integer; var Extent : TSize; begin RequiredState( [csHandleValid, csFontValid] ); if Windows.GetTextExtentPoint( fHandle, pchar( Text), Length( Text), Extent) then Result := Extent.cX else Result := 0; end; function TBufferCanvas.TextHeight( const Text : String ) : integer; var Extent : TSize; begin RequiredState( [csHandleValid, csFontValid] ); if Windows.GetTextExtentPoint( fHandle, pchar( Text), Length( Text), Extent) then Result := Extent.cY else Result := 0; end; function TBufferCanvas.TextExtent( const Text : string ) : TSize; begin RequiredState( [csHandleValid, csFontValid] ); Windows.GetTextExtentPoint( fHandle, pchar( Text), Length( Text), result ) end; procedure TBufferCanvas.SetFont( Value : TFont ); begin fFont.Assign( Value ); end; procedure TBufferCanvas.SetPen( Value : TPen ); begin fPen.Assign( Value ); end; procedure TBufferCanvas.SetBrush( Value : TBrush ); begin fBrush.Assign( Value ); end; function TBufferCanvas.GetPenPos : TPoint; begin RequiredState( [csHandleValid] ); Windows.GetCurrentPositionEx( fHandle, @Result ); end; procedure TBufferCanvas.SetPenPos( const Value : TPoint ); begin MoveTo( Value.x, Value.y ); end; function TBufferCanvas.GetScanLines : pointer; begin Result := fBitmap.ScanLines; end; function TBufferCanvas.GetPixelAddr(x, y : integer ) : pointer; begin Result := fBitmap.GetPixelAddr( x, y ); end; function TBufferCanvas.GetPixels( x, y : integer ) : TColor; begin RequiredState( [csHandleValid] ); Result := Windows.GetPixel( fHandle, x, y ); end; procedure TBufferCanvas.SetPixels( x, y : integer; Value : TColor ); begin RequiredState( [csHandleValid, csPenValid] ); Windows.SetPixel( fHandle, x, y, ColorToRGB( Value) ); end; function TBufferCanvas.GetClipRect : TRect; begin RequiredState( [csHandleValid] ); Windows.GetClipBox( fHandle, Result ); end; function TBufferCanvas.GetHandle : HDC; begin RequiredState( csAllValid ); Result := fHandle; end; procedure TBufferCanvas.DeselectHandles; begin if (fHandle <> 0) and (State - [csPenValid, csBrushValid, csFontValid] <> State) then begin SelectObject( fHandle, fStockPen ); SelectObject( fHandle, fStockBrush ); SelectObject( fHandle, fStockFont ); State := State - [csPenValid, csBrushValid, csFontValid]; end; end; procedure TBufferCanvas.FreeContext; var dc : HDC; begin if fHandle <> 0 then begin dc := fHandle; SetHandle( 0 ); DeleteDC( dc ); BitmapCanvasList.Remove( Self ); end; end; procedure TBufferCanvas.SetHandle( Value : HDC ); begin if fHandle <> Value then begin if fHandle <> 0 then begin DeselectHandles; fPenPos := GetPenPos; fHandle := 0; Exclude( State, csHandleValid ); end; if Value <> 0 then begin Include( State, csHandleValid ); fHandle := Value; SetPenPos( fPenPos ); end; end; end; procedure TBufferCanvas.RequiredState( ReqState : TCanvasState ); var NeededState : TCanvasState; begin NeededState := ReqState - State; if NeededState <> [] then begin if csHandleValid in NeededState then begin CreateHandle; if fHandle = 0 then raise EInvalidGraphicOperation.Create( SNoCanvasHandle ); end; if csFontValid in NeededState then CreateFont; if csPenValid in NeededState then CreatePen; if csBrushValid in NeededState then CreateBrush; State := State + NeededState; end; end; procedure TBufferCanvas.CreateFont; begin SelectObject( fHandle, Font.Handle ); SetTextColor( fHandle, ColorToRGB( Font.Color) ); end; procedure TBufferCanvas.CreatePen; const PenModes : array[TPenMode] of word = ( R2_BLACK, R2_WHITE, R2_NOP, R2_NOT, R2_COPYPEN, R2_NOTCOPYPEN, R2_MERGEPENNOT, R2_MASKPENNOT, R2_MERGENOTPEN, R2_MASKNOTPEN, R2_MERGEPEN, R2_NOTMERGEPEN, R2_MASKPEN, R2_NOTMASKPEN, R2_XORPEN, R2_NOTXORPEN ); begin SelectObject( fHandle, Pen.Handle ); SetROP2( fHandle, PenModes[Pen.Mode] ); end; procedure TBufferCanvas.CreateBrush; begin UnrealizeObject( Brush.Handle ); SelectObject( fHandle, Brush.Handle ); if Brush.Style = bsSolid then begin SetBkColor( fHandle, ColorToRGB( Brush.Color) ); SetBkMode( fHandle, OPAQUE ); end else begin // Win95 doesn't draw brush hatches if bkcolor = brush color // Since bkmode is transparent, nothing should use bkcolor anyway SetBkColor( fHandle, not ColorToRGB( Brush.Color) ); SetBkMode( fHandle, TRANSPARENT ); end; end; procedure TBufferCanvas.FontChanged( AFont : TObject ); begin if csFontValid in State then begin Exclude( State, csFontValid ); SelectObject( fHandle, fStockFont ); end; end; procedure TBufferCanvas.PenChanged( APen : TObject ); begin if csPenValid in State then begin Exclude( State, csPenValid ); SelectObject( fHandle, fStockPen ); end; end; procedure TBufferCanvas.BrushChanged( ABrush : TObject ); begin if csBrushValid in State then begin Exclude( State, csBrushValid ); SelectObject( fHandle, fStockBrush ); end; end; initialization BitmapCanvasList := TList.Create; finalization BitmapCanvasList.Free; end.
unit FontWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\FontWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "FontWordsPack" MUID: (5190B264037C) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , l3Core , l3Interfaces ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwPropertyLike , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwAxiomaticsResNameGetter , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *5190B264037Cimpl_uses* //#UC END# *5190B264037Cimpl_uses* ; type TkwFontColor = {final} class(TtfwPropertyLike) {* Слово скрипта Font:Color } private function Color(const aCtx: TtfwContext; const aFont: Il3FontInfo): Tl3Color; {* Реализация слова скрипта Font:Color } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontColor TkwFontBackColor = {final} class(TtfwPropertyLike) {* Слово скрипта Font:BackColor } private function BackColor(const aCtx: TtfwContext; const aFont: Il3FontInfo): Tl3Color; {* Реализация слова скрипта Font:BackColor } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontBackColor TkwFontIsBold = {final} class(TtfwPropertyLike) {* Слово скрипта Font:IsBold } private function IsBold(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsBold } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontIsBold TkwFontIsItalic = {final} class(TtfwPropertyLike) {* Слово скрипта Font:IsItalic } private function IsItalic(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsItalic } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontIsItalic TkwFontIsUnderline = {final} class(TtfwPropertyLike) {* Слово скрипта Font:IsUnderline } private function IsUnderline(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsUnderline } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontIsUnderline TkwFontIsStrikeOut = {final} class(TtfwPropertyLike) {* Слово скрипта Font:IsStrikeOut } private function IsStrikeOut(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsStrikeOut } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontIsStrikeOut TkwFontName = {final} class(TtfwPropertyLike) {* Слово скрипта Font:Name } private function Name(const aCtx: TtfwContext; const aFont: Il3FontInfo): AnsiString; {* Реализация слова скрипта Font:Name } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontName TkwFontSize = {final} class(TtfwPropertyLike) {* Слово скрипта Font:Size } private function Size(const aCtx: TtfwContext; const aFont: Il3FontInfo): Integer; {* Реализация слова скрипта Font:Size } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFontSize TFontWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TFontWordsPackResNameGetter function TkwFontColor.Color(const aCtx: TtfwContext; const aFont: Il3FontInfo): Tl3Color; {* Реализация слова скрипта Font:Color } //#UC START# *556F27CA0030_556F27CA0030_46A60B17028B_Word_var* //#UC END# *556F27CA0030_556F27CA0030_46A60B17028B_Word_var* begin //#UC START# *556F27CA0030_556F27CA0030_46A60B17028B_Word_impl* Result := aFont.ForeColor; //#UC END# *556F27CA0030_556F27CA0030_46A60B17028B_Word_impl* end;//TkwFontColor.Color class function TkwFontColor.GetWordNameForRegister: AnsiString; begin Result := 'Font:Color'; end;//TkwFontColor.GetWordNameForRegister function TkwFontColor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Tl3Color); end;//TkwFontColor.GetResultTypeInfo function TkwFontColor.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontColor.GetAllParamsCount function TkwFontColor.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontColor.ParamsTypes procedure TkwFontColor.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Color', aCtx); end;//TkwFontColor.SetValuePrim procedure TkwFontColor.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(Integer(Color(aCtx, l_aFont))); end;//TkwFontColor.DoDoIt function TkwFontBackColor.BackColor(const aCtx: TtfwContext; const aFont: Il3FontInfo): Tl3Color; {* Реализация слова скрипта Font:BackColor } //#UC START# *556F27D901F0_556F27D901F0_46A60B17028B_Word_var* //#UC END# *556F27D901F0_556F27D901F0_46A60B17028B_Word_var* begin //#UC START# *556F27D901F0_556F27D901F0_46A60B17028B_Word_impl* Result := aFont.BackColor; //#UC END# *556F27D901F0_556F27D901F0_46A60B17028B_Word_impl* end;//TkwFontBackColor.BackColor class function TkwFontBackColor.GetWordNameForRegister: AnsiString; begin Result := 'Font:BackColor'; end;//TkwFontBackColor.GetWordNameForRegister function TkwFontBackColor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Tl3Color); end;//TkwFontBackColor.GetResultTypeInfo function TkwFontBackColor.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontBackColor.GetAllParamsCount function TkwFontBackColor.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontBackColor.ParamsTypes procedure TkwFontBackColor.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackColor', aCtx); end;//TkwFontBackColor.SetValuePrim procedure TkwFontBackColor.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(Integer(BackColor(aCtx, l_aFont))); end;//TkwFontBackColor.DoDoIt function TkwFontIsBold.IsBold(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsBold } //#UC START# *556F27FE01C0_556F27FE01C0_46A60B17028B_Word_var* //#UC END# *556F27FE01C0_556F27FE01C0_46A60B17028B_Word_var* begin //#UC START# *556F27FE01C0_556F27FE01C0_46A60B17028B_Word_impl* Result := aFont.Bold; //#UC END# *556F27FE01C0_556F27FE01C0_46A60B17028B_Word_impl* end;//TkwFontIsBold.IsBold class function TkwFontIsBold.GetWordNameForRegister: AnsiString; begin Result := 'Font:IsBold'; end;//TkwFontIsBold.GetWordNameForRegister function TkwFontIsBold.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFontIsBold.GetResultTypeInfo function TkwFontIsBold.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontIsBold.GetAllParamsCount function TkwFontIsBold.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontIsBold.ParamsTypes procedure TkwFontIsBold.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsBold', aCtx); end;//TkwFontIsBold.SetValuePrim procedure TkwFontIsBold.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsBold(aCtx, l_aFont)); end;//TkwFontIsBold.DoDoIt function TkwFontIsItalic.IsItalic(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsItalic } //#UC START# *556F280F0160_556F280F0160_46A60B17028B_Word_var* //#UC END# *556F280F0160_556F280F0160_46A60B17028B_Word_var* begin //#UC START# *556F280F0160_556F280F0160_46A60B17028B_Word_impl* Result := aFont.Italic; //#UC END# *556F280F0160_556F280F0160_46A60B17028B_Word_impl* end;//TkwFontIsItalic.IsItalic class function TkwFontIsItalic.GetWordNameForRegister: AnsiString; begin Result := 'Font:IsItalic'; end;//TkwFontIsItalic.GetWordNameForRegister function TkwFontIsItalic.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFontIsItalic.GetResultTypeInfo function TkwFontIsItalic.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontIsItalic.GetAllParamsCount function TkwFontIsItalic.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontIsItalic.ParamsTypes procedure TkwFontIsItalic.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsItalic', aCtx); end;//TkwFontIsItalic.SetValuePrim procedure TkwFontIsItalic.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsItalic(aCtx, l_aFont)); end;//TkwFontIsItalic.DoDoIt function TkwFontIsUnderline.IsUnderline(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsUnderline } //#UC START# *556F281A0381_556F281A0381_46A60B17028B_Word_var* //#UC END# *556F281A0381_556F281A0381_46A60B17028B_Word_var* begin //#UC START# *556F281A0381_556F281A0381_46A60B17028B_Word_impl* Result := aFont.Underline; //#UC END# *556F281A0381_556F281A0381_46A60B17028B_Word_impl* end;//TkwFontIsUnderline.IsUnderline class function TkwFontIsUnderline.GetWordNameForRegister: AnsiString; begin Result := 'Font:IsUnderline'; end;//TkwFontIsUnderline.GetWordNameForRegister function TkwFontIsUnderline.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFontIsUnderline.GetResultTypeInfo function TkwFontIsUnderline.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontIsUnderline.GetAllParamsCount function TkwFontIsUnderline.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontIsUnderline.ParamsTypes procedure TkwFontIsUnderline.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsUnderline', aCtx); end;//TkwFontIsUnderline.SetValuePrim procedure TkwFontIsUnderline.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsUnderline(aCtx, l_aFont)); end;//TkwFontIsUnderline.DoDoIt function TkwFontIsStrikeOut.IsStrikeOut(const aCtx: TtfwContext; const aFont: Il3FontInfo): Boolean; {* Реализация слова скрипта Font:IsStrikeOut } //#UC START# *556F282902E9_556F282902E9_46A60B17028B_Word_var* //#UC END# *556F282902E9_556F282902E9_46A60B17028B_Word_var* begin //#UC START# *556F282902E9_556F282902E9_46A60B17028B_Word_impl* Result := aFont.Strikeout; //#UC END# *556F282902E9_556F282902E9_46A60B17028B_Word_impl* end;//TkwFontIsStrikeOut.IsStrikeOut class function TkwFontIsStrikeOut.GetWordNameForRegister: AnsiString; begin Result := 'Font:IsStrikeOut'; end;//TkwFontIsStrikeOut.GetWordNameForRegister function TkwFontIsStrikeOut.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFontIsStrikeOut.GetResultTypeInfo function TkwFontIsStrikeOut.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontIsStrikeOut.GetAllParamsCount function TkwFontIsStrikeOut.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontIsStrikeOut.ParamsTypes procedure TkwFontIsStrikeOut.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsStrikeOut', aCtx); end;//TkwFontIsStrikeOut.SetValuePrim procedure TkwFontIsStrikeOut.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsStrikeOut(aCtx, l_aFont)); end;//TkwFontIsStrikeOut.DoDoIt function TkwFontName.Name(const aCtx: TtfwContext; const aFont: Il3FontInfo): AnsiString; {* Реализация слова скрипта Font:Name } //#UC START# *556F2856019F_556F2856019F_46A60B17028B_Word_var* //#UC END# *556F2856019F_556F2856019F_46A60B17028B_Word_var* begin //#UC START# *556F2856019F_556F2856019F_46A60B17028B_Word_impl* Result := aFont.Name; //#UC END# *556F2856019F_556F2856019F_46A60B17028B_Word_impl* end;//TkwFontName.Name class function TkwFontName.GetWordNameForRegister: AnsiString; begin Result := 'Font:Name'; end;//TkwFontName.GetWordNameForRegister function TkwFontName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwFontName.GetResultTypeInfo function TkwFontName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontName.GetAllParamsCount function TkwFontName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontName.ParamsTypes procedure TkwFontName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Name', aCtx); end;//TkwFontName.SetValuePrim procedure TkwFontName.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(Name(aCtx, l_aFont)); end;//TkwFontName.DoDoIt function TkwFontSize.Size(const aCtx: TtfwContext; const aFont: Il3FontInfo): Integer; {* Реализация слова скрипта Font:Size } //#UC START# *556F2867022F_556F2867022F_46A60B17028B_Word_var* //#UC END# *556F2867022F_556F2867022F_46A60B17028B_Word_var* begin //#UC START# *556F2867022F_556F2867022F_46A60B17028B_Word_impl* Result := aFont.Size; //#UC END# *556F2867022F_556F2867022F_46A60B17028B_Word_impl* end;//TkwFontSize.Size class function TkwFontSize.GetWordNameForRegister: AnsiString; begin Result := 'Font:Size'; end;//TkwFontSize.GetWordNameForRegister function TkwFontSize.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwFontSize.GetResultTypeInfo function TkwFontSize.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFontSize.GetAllParamsCount function TkwFontSize.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Il3FontInfo)]); end;//TkwFontSize.ParamsTypes procedure TkwFontSize.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Size', aCtx); end;//TkwFontSize.SetValuePrim procedure TkwFontSize.DoDoIt(const aCtx: TtfwContext); var l_aFont: Il3FontInfo; begin try l_aFont := Il3FontInfo(aCtx.rEngine.PopIntf(Il3FontInfo)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFont: Il3FontInfo : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(Size(aCtx, l_aFont)); end;//TkwFontSize.DoDoIt class function TFontWordsPackResNameGetter.ResName: AnsiString; begin Result := 'FontWordsPack'; end;//TFontWordsPackResNameGetter.ResName {$R FontWordsPack.res} initialization TkwFontColor.RegisterInEngine; {* Регистрация Font_Color } TkwFontBackColor.RegisterInEngine; {* Регистрация Font_BackColor } TkwFontIsBold.RegisterInEngine; {* Регистрация Font_IsBold } TkwFontIsItalic.RegisterInEngine; {* Регистрация Font_IsItalic } TkwFontIsUnderline.RegisterInEngine; {* Регистрация Font_IsUnderline } TkwFontIsStrikeOut.RegisterInEngine; {* Регистрация Font_IsStrikeOut } TkwFontName.RegisterInEngine; {* Регистрация Font_Name } TkwFontSize.RegisterInEngine; {* Регистрация Font_Size } TFontWordsPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(Il3FontInfo)); {* Регистрация типа Il3FontInfo } TtfwTypeRegistrator.RegisterType(TypeInfo(Tl3Color)); {* Регистрация типа Tl3Color } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } {$IfEnd} // NOT Defined(NoScripts) end.
unit uArquivoTexto; interface uses System.SysUtils; type TTipo = (tpExportar, tpImportar); TArquivoTexto = class private FArquivo: TextFile; FRegistro: string; function Posicao(ATamanho: integer; AValor: string): string; function PosicaoImp(APosicaoIni, ATamanho: Integer; AValor: string): string; public procedure ExportarString(AValor: string; APosicaoIni, ATamanho: Integer); procedure ExportarInt(AValor: Integer; APosicaoIni, ATamanho: Integer); procedure ExportarBool(AValor: Boolean); procedure NovaLinha; procedure ProximoRegistro(); function FimArquivo(): Boolean; function ImportarString(APosicaoIni, ATamanho: Integer): string; function ImportarInt(APosicaoIni, ATamanho: Integer): Integer; function ImportarBool(APosicaoIni, ATamanho: Integer): Boolean; constructor Create(AArquivo: string; ATipo: TTipo); overload; destructor Destroy; override; end; implementation { TArquivoTexto } constructor TArquivoTexto.Create(AArquivo: string; ATipo: TTipo); begin inherited Create; AssignFile(FArquivo, AArquivo); if ATipo = tpExportar then Rewrite(FArquivo) else Reset(FArquivo); end; destructor TArquivoTexto.Destroy; begin CloseFile(FArquivo); inherited; end; procedure TArquivoTexto.NovaLinha; begin Writeln(FArquivo,''); end; function TArquivoTexto.Posicao(ATamanho: integer; AValor: string): string; begin Result := Copy(AValor + StringOfChar(' ', ATamanho + 1), 1, ATamanho); end; function TArquivoTexto.PosicaoImp(APosicaoIni, ATamanho: Integer; AValor: string): string; begin Result := Copy(AValor, APosicaoIni, ATamanho); end; procedure TArquivoTexto.ProximoRegistro; begin Readln(FArquivo, FRegistro); end; procedure TArquivoTexto.ExportarBool(AValor: Boolean); begin if AValor then write(FArquivo,'1') else write(FArquivo,'0'); end; procedure TArquivoTexto.ExportarInt(AValor, APosicaoIni, ATamanho: Integer); begin write(FArquivo, Posicao(ATamanho, IntToStr(AValor))); end; procedure TArquivoTexto.ExportarString(AValor: string; APosicaoIni, ATamanho: Integer); begin write(FArquivo, Posicao(ATamanho, AValor)); end; function TArquivoTexto.FimArquivo: Boolean; begin Result := Eof(FArquivo); end; function TArquivoTexto.ImportarBool(APosicaoIni, ATamanho: Integer): Boolean; var Resultado: Integer; begin Resultado := StrToIntDef(Trim(PosicaoImp(APosicaoIni, ATamanho, FRegistro)),0); Result := (Resultado = 1); end; function TArquivoTexto.ImportarInt(APosicaoIni, ATamanho: Integer): Integer; begin Result := StrToIntDef(Trim(PosicaoImp(APosicaoIni, ATamanho, FRegistro)),0); end; function TArquivoTexto.ImportarString(APosicaoIni, ATamanho: Integer): string; begin Result := Trim(PosicaoImp(APosicaoIni, ATamanho, FRegistro)); end; end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls; type TFormMain = class(TForm) ButtonCreatePdf: TButton; procedure ButtonCreatePdfClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation uses Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.Helpers, System.IOUtils; {$R *.fmx} function FileNameToUri(const FileName: string): Jnet_Uri; var JavaFile: JFile; begin JavaFile := TJFile.JavaClass.init(StringToJString(FileName)); Result := TJnet_Uri.JavaClass.fromFile(JavaFile); end; procedure TFormMain.ButtonCreatePdfClick(Sender: TObject); var Document: JPdfDocument; PageInfo: JPdfDocument_PageInfo; Page: JPdfDocument_Page; Canvas: JCanvas; Paint: JPaint; Rect: JRectF; FileName: string; OutputStream: JFileOutputStream; Intent: JIntent; begin // create Pdf document Document := TJPdfDocument.JavaClass.init; try // create page 1 PageInfo := TJPageInfo_Builder.JavaClass.init(100, 100, 1).create; Page := Document.startPage(PageInfo); Canvas := Page.getCanvas; Paint := TJPaint.JavaClass.init; Paint.setARGB($FF, 0, 0, $FF); Canvas.drawText(StringToJString('Hello, world!'), 10, 50, Paint); Document.finishPage(Page); // create page 2 PageInfo := TJPageInfo_Builder.JavaClass.init(100, 100, 2).create; Page := Document.startPage(PageInfo); Canvas := Page.getCanvas; Paint := TJPaint.JavaClass.init; Paint.setARGB($FF, $FF, 0, 0); Canvas.drawLine(10, 10, 90, 10, Paint); Paint.setStrokeWidth(1); Paint.setARGB($FF, 0, $FF, 0); Canvas.drawLine(10, 20, 90, 20, Paint); Paint.setStrokeWidth(2); Paint.setARGB($FF, 0, 0, $FF); Canvas.drawLine(10, 30, 90, 30, Paint); Paint.setARGB($FF, $FF, $FF, 0); Canvas.drawRect(10, 40, 90, 60, Paint); Rect := TJRectF.JavaClass.init; Rect.&set(10, 70, 90, 90); Paint.setARGB($FF, $FF, 0, $FF); Canvas.drawRoundRect(Rect, 5, 5, Paint); Document.finishPage(Page); // write PDF document to file FileName := TPath.GetSharedDocumentsPath + PathDelim + 'demo.pdf'; OutputStream := TJFileOutputStream.JavaClass.init(StringToJString(FileName)); try Document.writeTo(OutputStream); finally OutputStream.close; end; finally Document.close; end; // start PDF viewer Intent := TJIntent.JavaClass.init; Intent.setAction(TJIntent.JavaClass.ACTION_VIEW); Intent.setDataAndType(FileNameToUri(FileName), StringToJString('application/pdf')); Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NO_HISTORY or TJIntent.JavaClass.FLAG_ACTIVITY_CLEAR_TOP); SharedActivity.StartActivity(Intent); end; end.
unit tcChangedToolBar; interface uses l3Interfaces, tcInterfaces, tcItem ; type TtcChangedToolBar = class(TtcItem, ItcChangedToolBar) private f_EditableChange: TtcEditableChange; f_DeletedChildren: ItcToolBarsList; f_AddedChildren: ItcToolBarsList; f_DeletedOperations: ItcOperationsList; f_AddedOperations: ItcOperationsList; f_ToolBar: ItcToolBar; f_OldCaption: Il3CString; protected // ItcChangedToolBar function pm_GetOldCaption: Il3CString; procedure pm_SetOldCaption(const aValue: Il3CString); function pm_GetEditableChange: TtcEditableChange; procedure pm_SetEditableChange(aValue: TtcEditableChange); function pm_GetDeletedChildren: ItcToolBarsList; function pm_GetAddedChildren: ItcToolBarsList; function pm_GetDeletedOperations: ItcOperationsList; function pm_GetAddedOperations: ItcOperationsList; function pm_GetToolBar: ItcToolBar; procedure pm_SetToolBar(const aToolBar: ItcToolBar); protected procedure Cleanup; override; public class function Make(const anID: Il3CString): ItcChangedToolBar; end; implementation uses SysUtils, tcOperationsList, tcToolBarsList ; { TtcChangedToolBar } procedure TtcChangedToolBar.Cleanup; begin f_DeletedChildren := nil; f_AddedChildren := nil; f_DeletedOperations := nil; f_AddedOperations := nil; f_ToolBar := nil; f_OldCaption := nil; inherited Cleanup; end; class function TtcChangedToolBar.Make( const anID: Il3CString): ItcChangedToolBar; var l_Instance: TtcChangedToolBar; begin l_Instance := Create(anID); try Result := l_Instance; finally FreeAndNil(l_Instance); end; end; function TtcChangedToolBar.pm_GetAddedChildren: ItcToolBarsList; begin if f_AddedChildren = nil then f_AddedChildren := TtcToolBarsList.Make; Result := f_AddedChildren; end; function TtcChangedToolBar.pm_GetAddedOperations: ItcOperationsList; begin if f_AddedOperations = nil then f_AddedOperations := TtcOperationsList.Make; Result := f_AddedOperations; end; function TtcChangedToolBar.pm_GetDeletedChildren: ItcToolBarsList; begin if f_DeletedChildren = nil then f_DeletedChildren := TtcToolBarsList.Make; Result := f_DeletedChildren; end; function TtcChangedToolBar.pm_GetDeletedOperations: ItcOperationsList; begin if f_DeletedOperations = nil then f_DeletedOperations := TtcOperationsList.Make; Result := f_DeletedOperations; end; function TtcChangedToolBar.pm_GetEditableChange: TtcEditableChange; begin Result := f_EditableChange; end; function TtcChangedToolBar.pm_GetOldCaption: Il3CString; begin Result := f_OldCaption; end; function TtcChangedToolBar.pm_GetToolBar: ItcToolBar; begin Result := f_ToolBar; end; procedure TtcChangedToolBar.pm_SetEditableChange( aValue: TtcEditableChange); begin f_EditableChange := aValue; end; procedure TtcChangedToolBar.pm_SetOldCaption(const aValue: Il3CString); begin f_OldCaption := aValue; end; procedure TtcChangedToolBar.pm_SetToolBar(const aToolBar: ItcToolBar); begin f_ToolBar := aToolBar; end; end.
unit BaseTestOnlineExamplesUnit; interface uses TestFramework, SysUtils, ConnectionUnit, Route4MeManagerUnit, IConnectionUnit; type TTestOnlineExamples = class(TTestCase) private const c_ApiKey = '11111111111111111111111111111111'; protected FRoute4MeManager: TRoute4MeManager; FConnection: IConnection; public procedure SetUp; override; procedure TearDown; override; end; implementation { TTestOnlineExamples } procedure TTestOnlineExamples.SetUp; begin inherited; FConnection := TConnection.Create(c_ApiKey); FRoute4MeManager := TRoute4MeManager.Create(FConnection); end; procedure TTestOnlineExamples.TearDown; begin FreeAndNil(FRoute4MeManager); inherited; end; end.
{Version 9.45} { Copyright (c) 1995-2008 by L. David Baldwin 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. Note that the source modules, HTMLGIF1.PAS, PNGZLIB1.PAS, DITHERUNIT.PAS, and URLCON.PAS are covered by separate copyright notices located in those modules. } {$i htmlcons.inc} unit HTMLGif2; interface uses SysUtils, Classes, {$IFNDEF LCL} Windows, mmSystem, {$ELSE} LclIntf, LMessages, Types, LclType, HtmlMisc, {$ENDIF} Graphics, Controls, ExtCtrls, htmlUN2, htmlgif1; type TRGBColor = packed Record Red, Green, Blue: Byte; end; TDisposalType = (dtUndefined, {Take no action} dtDoNothing, {Leave graphic, next frame goes on top of it} dtToBackground,{restore original background for next frame} dtToPrevious); {restore image as it existed before this frame} type ThtBitmap=class(TBitmap) protected htMask: TBitmap; htTransparent: boolean; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; procedure StretchDraw(ACanvas: TCanvas; const DestRect, SrcRect: TRect); public destructor Destroy; override; end; TGIFImage = class; TgfFrame = class private { private declarations } frLeft: Integer; frTop: Integer; frWidth: Integer; frHeight: Integer; frDelay: Integer; frDisposalMethod: TDisposalType; TheEnd: boolean; {end of what gets copied} IsCopy: boolean; Public constructor Create; constructor CreateCopy(Item: TgfFrame); destructor Destroy; override; end; TgfFrameList = class(TList) private function GetFrame(I: integer): TgfFrame; public {note: Frames is 1 based, goes from [1..Count]} property Frames[I: integer]: TgfFrame read GetFrame; default; end; TGIFImage = class(TPersistent) private { Private declarations } FAnimated: Boolean; FCurrentFrame: Integer; FImageWidth: Integer; FImageHeight: Integer; FNumFrames: Integer; FNumIterations: Integer; FTransparent: Boolean; FVisible: Boolean; Strip: ThtBitmap; TheEnd: boolean; {copy to here} FBitmap: TBitmap; FMaskedBitmap, FMask: TBitmap; FAnimate: Boolean; FStretchedRect: TRect; WasDisposal: TDisposalType; Frames: TgfFrameList; CurrentIteration: Integer; LastTime: DWord; CurrentInterval: DWord; procedure SetAnimate(AAnimate: Boolean); procedure SetCurrentFrame(AFrame: Integer); function GetMaskedBitmap: TBitmap; function GetMask: TBitmap; function GetBitMap: TBitmap; procedure NextFrame(OldFrame: Integer); public ShowIt: boolean; IsCopy: boolean; {set if this is a copy of one in Cache} { Public declarations } constructor Create; constructor CreateCopy(Item: TGIFImage); destructor Destroy; override; procedure Draw(Canvas: TCanvas; X, Y, Wid, Ht: integer); property Bitmap: TBitmap read GetBitmap; property MaskedBitmap: TBitmap read GetMaskedBitmap; property Mask: TBitmap read GetMask; property IsAnimated: Boolean read FAnimated; property IsTransparent: Boolean read FTransparent; property NumFrames: Integer read FNumFrames; property NumIterations: Integer read FNumIterations; procedure CheckTime(WinControl: TWinControl); property Width: integer read FImageWidth; property Height: integer read FImageHeight; property Animate: Boolean read FAnimate write SetAnimate; property CurrentFrame: Integer read FCurrentFrame write SetCurrentFrame; property Visible: Boolean read FVisible write FVisible; end; function CreateAGifFromStream(var NonAnimated: boolean; Stream: TStream): TGifImage; function CreateAGif(const Name: string; var NonAnimated: boolean): TGifImage; implementation uses Styleun, htmlsubs; function CreateBitmap(Width, Height: integer): TBitmap; begin Result := TBitmap.Create; Result.Width := Width; Result.Height := Height; end; function CreateAGifFromStream(var NonAnimated: boolean; Stream: TStream): TGifImage; var AGif: TGif; Frame: TgfFrame; I: integer; ABitmap, AMask: TBitmap; begin Result := Nil; try NonAnimated := True; AGif := TGif.Create; Try AGif.LoadFromStream(Stream); Result := TGifImage.Create; Result.FNumFrames := AGif.ImageCount; Result.FAnimated := Result.FNumFrames > 1; NonAnimated := not Result.FAnimated; Result.FImageWidth := AGif.Width; Result.FImageHeight := AGif.Height; Result.FNumIterations:= AGif.LoopCount; if Result.FNumIterations < 0 then {-1 means no loop block} Result.FNumIterations := 1 else if Result.FNumIterations > 0 then Inc(Result.FNumIterations); {apparently this is the convention} Result.FTransparent := AGif.Transparent; with Result do begin Strip := ThtBitmap.Create; ABitmap := AGif.GetStripBitmap(AMask); try Strip.Assign(ABitmap); Strip.htMask := AMask; Strip.htTransparent := Assigned(AMask); finally ABitmap.Free; end; if Result.Strip.Palette <> 0 then DeleteObject(Result.Strip.ReleasePalette); Result.Strip.Palette := CopyPalette(ThePalette); end; for I := 0 to Result.FNumFrames-1 do begin Frame := TgfFrame.Create; try Frame.frDisposalMethod := TDisposalType(AGif.ImageDisposal[I]); Frame.frLeft := AGif.ImageLeft[I]; Frame.frTop := AGif.ImageTop[I]; Frame.frWidth := AGif.ImageWidth[I]; Frame.frHeight := AGif.ImageHeight[I]; Frame.frDelay := IntMax(30, AGif.ImageDelay[I] * 10); except Frame.Free; Raise; end; Result.Frames.Add(Frame); end; if Result.IsAnimated then Result.WasDisposal := dtToBackground; finally AGif.Free; end; except FreeAndNil(Result); end; end; function CreateAGif(const Name: string; var NonAnimated: boolean): TGifImage; var Stream: TFileStream; begin Result := Nil; try Stream := TFileStream.Create(Name, fmOpenRead or fmShareDenyWrite); try Result := CreateAGifFromStream(NonAnimated, Stream); finally Stream.Free; end; except end; end; {----------------TgfFrame.Create} constructor TgfFrame.Create; begin inherited Create; end; constructor TgfFrame.CreateCopy(Item: TgfFrame); begin inherited Create; {$IFNDEF FPC} System.Move(Item.frLeft, frLeft, DWord(@TheEnd)-DWord(@frLeft)); {$ELSE} System.Move(Item.frLeft, frLeft, PtrUInt(@TheEnd)-PtrUInt(@frLeft)); {$ENDIF} IsCopy := True; end; {----------------TgfFrame.Destroy} destructor TgfFrame.Destroy; begin inherited Destroy; end; {----------------TGIFImage.Create} constructor TGIFImage.Create; begin inherited Create; FVisible := True; FCurrentFrame := 1; Frames := TgfFrameList.Create; CurrentIteration := 1; end; constructor TGIFImage.CreateCopy(Item: TGIFImage); var I: integer; begin inherited Create; FImageWidth := Item.Width; FimageHeight := Item.Height; {$IFNDEF FPC} System.Move(Item.FAnimated, FAnimated, DWord(@TheEnd)-DWord(@FAnimated)); {$ELSE} System.Move(Item.FAnimated, FAnimated, PtrUInt(@TheEnd)-PtrUInt(@FAnimated)); {$ENDIF} IsCopy := True; Frames := TgfFrameList.Create; for I := 1 to FNumFrames do Frames.Add(TgfFrame.CreateCopy(Item.Frames[I])); FCurrentFrame := 1; CurrentIteration := 1; if FAnimated then WasDisposal := dtToBackground; end; {----------------TGIFImage.Destroy} destructor TGIFImage.Destroy; var I: Integer; begin for I := Frames.Count downto 1 do Frames[I].Free; Frames.Free; FreeAndNil(FBitmap); if not IsCopy then FreeAndNil(Strip); FMaskedBitmap.Free; FreeAndNil(FMask); inherited Destroy; end; {----------------TGIFImage.Draw} procedure TGIFImage.Draw(Canvas: TCanvas; X, Y, Wid, Ht: integer); var SRect: TRect; ALeft: integer; begin FStretchedRect := Rect(X, Y, X+Wid, Y+Ht); SetStretchBltMode(Canvas.Handle, ColorOnColor); if (FVisible) and (FNumFrames > 0) then begin with Frames[FCurrentFrame] do begin ALeft := (FCurrentFrame-1)*Width; SRect := Rect(ALeft, 0, ALeft+Width, Height); {current frame location in Strip bitmap} end; Canvas.CopyMode := cmSrcCopy; {draw the correct portion of the strip} Strip.StretchDraw(Canvas, FStretchedRect, SRect); end; end; {----------------TGifImage.CheckTime} procedure TGifImage.CheckTime(WinControl: TWinControl); var ThisTime: DWord; begin if not FAnimate then Exit; ThisTime := timeGetTime; if ThisTime - LastTime < CurrentInterval then Exit; LastTime := ThisTime; if (FCurrentFrame = FNumFrames) then begin if (FNumIterations > 0) and (CurrentIteration >= FNumIterations) then begin SetAnimate(False); Exit; end; Inc(CurrentIteration); end; NextFrame(FCurrentFrame); Inc(FCurrentFrame); if (FCurrentFrame > FNumFrames) or (FCurrentFrame <= 0) then FCurrentFrame := 1; InvalidateRect(WinControl.Handle, @FStretchedRect, True); CurrentInterval := IntMax(Frames[FCurrentFrame].frDelay, 1); end; {----------------TGIFImage.SetAnimate} procedure TGIFImage.SetAnimate(AAnimate: Boolean); begin if AAnimate = FAnimate then Exit; FAnimate := AAnimate; if AAnimate and (FNumFrames > 1) then begin CurrentInterval := IntMax(Frames[FCurrentFrame].frDelay, 1); LastTime := timeGetTime; end; end; {----------------TGIFImage.SetCurrentFrame} procedure TGIFImage.SetCurrentFrame(AFrame: Integer); begin if AFrame = FCurrentFrame then Exit; NextFrame(FCurrentFrame); if AFrame > FNumFrames then FCurrentFrame := 1 else if AFrame < 1 then FCurrentFrame := FNumFrames else FCurrentFrame := AFrame; if FAnimated then WasDisposal := dtToBackground; end; {----------------TGIFImage.GetBitmap} function TGIFImage.GetBitmap: TBitmap; begin Result := GetMaskedBitmap; end; {----------------TGIFImage.GetMaskedBitmap:} function TGIFImage.GetMaskedBitmap: TBitmap; {This returns frame 1} begin if not Assigned(FMaskedBitmap) then begin FMaskedBitmap := TBitmap.Create; FMaskedBitmap.Assign(Strip); FMaskedBitmap.Width := FImageWidth; if Strip.htTransparent then begin FMask := TBitmap.Create; FMask.Assign(Strip.htMask); FMask.Width := FImageWidth; end; FMaskedBitmap.Transparent := False; end; Result := FMaskedBitmap; end; {----------------TGIFImage.GetMask:} function TGIFImage.GetMask: TBitmap; {This returns mask for frame 1. Content is black, background is white} begin if not FTransparent then Result := nil else begin if not Assigned(FMask) then GetMaskedBitmap; Result := FMask; end; end; {----------------TGIFImage.NextFrame} procedure TGIFImage.NextFrame(OldFrame: Integer); begin WasDisposal := Frames[OldFrame].frDisposalMethod; end; {----------------TgfFrameList.GetFrame} function TgfFrameList.GetFrame(I: integer): TgfFrame; begin Assert((I <= Count) and (I >= 1 ), 'Frame index out of range'); Result := TgfFrame(Items[I-1]); end; { ThtBitmap } var AHandle: THandle; destructor ThtBitmap.Destroy; begin htMask.Free; inherited; end; {----------------ThtBitmap.Draw} procedure ThtBitmap.Draw(ACanvas: TCanvas; const Rect: TRect); var OldPalette: HPalette; RestorePalette: Boolean; DoHalftone: Boolean; Pt: TPoint; BPP: Integer; MaskDC: HDC; Save: THandle; begin with Rect do begin AHandle := ACanvas.Handle; {LDB} PaletteNeeded; OldPalette := 0; RestorePalette := False; if Palette <> 0 then begin OldPalette := SelectPalette(ACanvas.Handle, Palette, True); RealizePalette(ACanvas.Handle); RestorePalette := True; end; BPP := GetDeviceCaps(ACanvas.Handle, BITSPIXEL) * GetDeviceCaps(ACanvas.Handle, PLANES); DoHalftone := (BPP <= 8) and (PixelFormat in [pf15bit, pf16bit, pf24bit]); if DoHalftone then begin GetBrushOrgEx(ACanvas.Handle, pt); SetStretchBltMode(ACanvas.Handle, HALFTONE); SetBrushOrgEx(ACanvas.Handle, pt.x, pt.y, @pt); end else if not Monochrome then SetStretchBltMode(ACanvas.Handle, STRETCH_DELETESCANS); try AHandle := Canvas.Handle; {LDB} if htTransparent then begin Save := 0; MaskDC := 0; try MaskDC := CreateCompatibleDC(0); {LDB} Save := SelectObject(MaskDC, MaskHandle); TransparentStretchBlt(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, Canvas.Handle, 0, 0, Width, Height, htMask.Canvas.Handle, 0, 0); {LDB} finally if Save <> 0 then SelectObject(MaskDC, Save); if MaskDC <> 0 then DeleteDC(MaskDC); end; end else StretchBlt(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, Canvas.Handle, 0, 0, Width, Height, ACanvas.CopyMode); finally if RestorePalette then SelectPalette(ACanvas.Handle, OldPalette, True); end; end; end; procedure ThtBitmap.StretchDraw(ACanvas: TCanvas; const DestRect, SrcRect: TRect); {Draw parts of this bitmap on ACanvas} var OldPalette: HPalette; RestorePalette: Boolean; DoHalftone: Boolean; Pt: TPoint; BPP: Integer; begin with DestRect do begin AHandle := ACanvas.Handle; {LDB} PaletteNeeded; OldPalette := 0; RestorePalette := False; if Palette <> 0 then begin OldPalette := SelectPalette(ACanvas.Handle, Palette, True); RealizePalette(ACanvas.Handle); RestorePalette := True; end; BPP := GetDeviceCaps(ACanvas.Handle, BITSPIXEL) * GetDeviceCaps(ACanvas.Handle, PLANES); DoHalftone := (BPP <= 8) and (PixelFormat in [pf15bit, pf16bit, pf24bit]); if DoHalftone then begin GetBrushOrgEx(ACanvas.Handle, pt); SetStretchBltMode(ACanvas.Handle, HALFTONE); SetBrushOrgEx(ACanvas.Handle, pt.x, pt.y, @pt); end else if not Monochrome then SetStretchBltMode(ACanvas.Handle, STRETCH_DELETESCANS); try AHandle := Canvas.Handle; {LDB} if htTransparent then TransparentStretchBlt(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, Canvas.Handle, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top, htMask.Canvas.Handle, SrcRect.Left, SrcRect.Top) {LDB} else StretchBlt(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, Canvas.Handle, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top, ACanvas.CopyMode); finally if RestorePalette then SelectPalette(ACanvas.Handle, OldPalette, True); end; end; end; end.
// stores the breakpoints while the source code is being formatted // Original Author: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterBreakpoints; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, ToolsApi; type TSourceBreakpoint = class private FDoHandleExceptions: Boolean; FStackFramesToLog: Integer; FDoIgnoreExceptions: Boolean; FDoBreak: Boolean; FDisableGroup: string; FEvalExpression: string; FLogResult: Boolean; FEnableGroup: string; FLogMessage: string; FGroupName: string; FFileName: string; FEnabled: Boolean; FLineNumber: Integer; FExpression: string; FPassCount: Integer; FThreadCondition: string; public // IOTABreakpoint (Delphi >=2010) property ThreadCondition: string read FThreadCondition write FThreadCondition; // IOTABreakpoint120 (Delphi 2005) property StackFramesToLog: Integer read FStackFramesToLog write FStackFramesToLog; // IOTABreakpoint80 property DoHandleExceptions: Boolean read FDoHandleExceptions write FDoHandleExceptions; property DoIgnoreExceptions: Boolean read FDoIgnoreExceptions write FDoIgnoreExceptions; // IOTABreakpoint50 property GroupName: string read FGroupName write FGroupName; property DoBreak: Boolean read FDoBreak write FDoBreak; property LogMessage: string read FLogMessage write FLogMessage; property EvalExpression: string read FEvalExpression write FEvalExpression; property LogResult: Boolean read FLogResult write FLogResult; property EnableGroup: string read FEnableGroup write FEnableGroup; property DisableGroup: string read FDisableGroup write FDisableGroup; // IOTABreakpoint40 property Enabled: Boolean read FEnabled write FEnabled; property Expression: string read FExpression write FExpression; property FileName: string read FFileName write FFileName; property LineNumber: Integer read FLineNumber write FLineNumber; property PassCount: Integer read FPassCount write FPassCount; end; type TBreakpoints = class private FList: TList; function GetItems(_Idx: Integer): TSourceBreakpoint; public constructor Create; destructor Destroy; override; procedure Add(Item: TSourceBreakpoint); function Count: Integer; procedure Clear; function Find(const _Filename: string; _LineNumber: Integer; out _Idx: Integer): Boolean; property Items[_Idx: Integer]: TSourceBreakpoint read GetItems; default; end; type TBreakpointHandler = class private FBreakpoints: TBreakpoints; protected public constructor Create; destructor Destroy; override; procedure RestoreItems; procedure SaveItems; procedure Dump(const _Filename: string); end; implementation uses IniFiles, Math; { TBreakpoints } constructor TBreakpoints.Create; begin inherited; FList := TList.Create; end; destructor TBreakpoints.Destroy; var i: Integer; begin for i := 0 to Count - 1 do TSourceBreakpoint(FList[i]).Free; FreeAndNil(FList); inherited; end; function TBreakpoints.Find(const _Filename: string; _LineNumber: Integer; out _Idx: Integer): Boolean; var i: Integer; begin for i := 0 to FList.Count - 1 do begin if SameText(Items[i].FileName, _Filename) and (Items[i].LineNumber = _LineNumber) then begin _Idx := i; Result := True; Exit; end; end; Result := False; end; function TBreakpoints.GetItems(_Idx: Integer): TSourceBreakpoint; begin Assert((_Idx > -1) and (_Idx < FList.Count)); Result := FList[_Idx]; end; procedure TBreakpoints.Add(Item: TSourceBreakpoint); begin Assert(Assigned(FList)); FList.Add(Item); end; function TBreakpoints.Count: Integer; begin Assert(Assigned(FList)); Result := FList.Count; end; procedure TBreakpoints.Clear; var i: Integer; begin for i := 0 to Count - 1 do TSourceBreakpoint(FList[i]).Free; FList.Clear; end; { TBreakpointHandler } constructor TBreakpointHandler.Create; begin inherited; FBreakpoints := TBreakpoints.Create; end; destructor TBreakpointHandler.Destroy; begin FreeAndNil(FBreakpoints); inherited; end; procedure TBreakpointHandler.RestoreItems; var DebuggerServices: IOTADebuggerServices; i: Integer; SrcBrkPtInt: IOTABreakpoint; SrcBreakpoint: TSourceBreakpoint; Idx: Integer; begin if BorlandIDEServices.QueryInterface(IOTADebuggerServices, DebuggerServices) <> S_OK then Exit; for i := 0 to DebuggerServices.SourceBkptCount - 1 do begin SrcBrkPtInt := DebuggerServices.SourceBkpts[i]; if FBreakpoints.Find(SrcBrkPtInt.FileName, SrcBrkPtInt.LineNumber, Idx) then FBreakpoints.FList.Delete(Idx); end; for i := 0 to FBreakpoints.Count - 1 do begin SrcBreakpoint := FBreakpoints[i]; try SrcBrkPtInt := DebuggerServices.NewSourceBreakpoint( SrcBreakpoint.FileName, SrcBreakpoint.LineNumber, DebuggerServices.CurrentProcess); except Break; // FIXME: Delphi 6/7 do not support recreation of source breakpoints at designtime (EListError: List index out of bounds (-1)) end; {$IFDEF GX_VER210_up} SrcBrkPtInt.ThreadCondition := SrcBreakpoint.ThreadCondition; {$ENDIF} {$IFDEF GX_VER170_up} SrcBrkPtInt.StackFramesToLog := SrcBreakpoint.StackFramesToLog; {$ENDIF} {$IFDEF GX_VER160_up} SrcBrkPtInt.DoHandleExceptions := SrcBreakpoint.DoHandleExceptions; SrcBrkPtInt.DoIgnoreExceptions := SrcBreakpoint.DoIgnoreExceptions; {$ENDIF} SrcBrkPtInt.GroupName := SrcBreakpoint.GroupName; SrcBrkPtInt.DoBreak := SrcBreakpoint.DoBreak; SrcBrkPtInt.LogMessage := SrcBreakpoint.LogMessage; SrcBrkPtInt.EvalExpression := SrcBreakpoint.EvalExpression; SrcBrkPtInt.LogResult := SrcBreakpoint.LogResult; SrcBrkPtInt.EnableGroup := SrcBreakpoint.EnableGroup; SrcBrkPtInt.DisableGroup := SrcBreakpoint.DisableGroup; SrcBrkPtInt.Enabled := SrcBreakpoint.Enabled; SrcBrkPtInt.Expression := SrcBreakpoint.Expression; SrcBrkPtInt.FileName := SrcBreakpoint.FileName; SrcBrkPtInt.LineNumber := SrcBreakpoint.LineNumber; SrcBrkPtInt.PassCount := SrcBreakpoint.PassCount; end; end; procedure TBreakpointHandler.SaveItems; var DebuggerServices: IOTADebuggerServices; i: Integer; SrcBrkPtInt: IOTABreakpoint; SrcBreakpoint: TSourceBreakpoint; begin FBreakpoints.Clear; if BorlandIDEServices.QueryInterface(IOTADebuggerServices, DebuggerServices) <> S_OK then Exit; for i := 0 to DebuggerServices.SourceBkptCount - 1 do begin SrcBrkPtInt := DebuggerServices.SourceBkpts[i]; SrcBreakpoint := TSourceBreakpoint.Create; {$IFDEF GX_VER210_up} SrcBreakpoint.ThreadCondition := SrcBrkPtInt.ThreadCondition; {$ENDIF} {$IFDEF GX_VER170_up} SrcBreakpoint.StackFramesToLog := SrcBrkPtInt.StackFramesToLog; {$ENDIF} {$IFDEF GX_VER160_up} SrcBreakpoint.DoHandleExceptions := SrcBrkPtInt.DoHandleExceptions; SrcBreakpoint.DoIgnoreExceptions := SrcBrkPtInt.DoIgnoreExceptions; {$ENDIF} SrcBreakpoint.GroupName := SrcBrkPtInt.GroupName; SrcBreakpoint.DoBreak := SrcBrkPtInt.DoBreak; SrcBreakpoint.LogMessage := SrcBrkPtInt.LogMessage; SrcBreakpoint.EvalExpression := SrcBrkPtInt.EvalExpression; SrcBreakpoint.LogResult := SrcBrkPtInt.LogResult; SrcBreakpoint.EnableGroup := SrcBrkPtInt.EnableGroup; SrcBreakpoint.DisableGroup := SrcBrkPtInt.DisableGroup; SrcBreakpoint.Enabled := SrcBrkPtInt.Enabled; SrcBreakpoint.Expression := SrcBrkPtInt.Expression; SrcBreakpoint.FileName := SrcBrkPtInt.FileName; SrcBreakpoint.LineNumber := SrcBrkPtInt.LineNumber; SrcBreakpoint.PassCount := SrcBrkPtInt.PassCount; FBreakpoints.Add(SrcBreakpoint); end; // Dump('d:\breakpoints.ini'); end; procedure TBreakpointHandler.Dump(const _Filename: string); var INI: TIniFile; i: Integer; SrcBreakpoint: TSourceBreakpoint; begin INI := TIniFile.Create(_Filename); try for i := 0 to FBreakpoints.Count - 1 do begin SrcBreakpoint := FBreakPoints[i]; INI.WriteString('Breakpoints', 'Breakpoint' + IntToStr(i), '''' + SrcBreakpoint.FFileName + '''' + ',' + IntToStr(SrcBreakpoint.LineNumber) + ',' + '''' + SrcBreakpoint.Expression + '''' + ',' + IntToStr(SrcBreakpoint.PassCount) + ',' + IntToStr(IfThen(SrcBreakpoint.Enabled, 1)) + ',' + '''' + SrcBreakpoint.GroupName + '''' + ',' + IntToStr(IfThen(SrcBreakpoint.DoBreak, 1)) + ',' + IntToStr(IfThen(SrcBreakpoint.DoIgnoreExceptions, 1)) + ',' + IntToStr(IfThen(SrcBreakpoint.DoHandleExceptions, 1)) + ',' + '''' + SrcBreakpoint.LogMessage + '''' + ',' + IntToStr(IfThen(SrcBreakpoint.LogResult, 1)) + ',' + '''' + SrcBreakpoint.EvalExpression + '''' + ',' + '''' + SrcBreakpoint.EnableGroup + '''' + ',' + '''' + SrcBreakpoint.DisableGroup + '''' + ',' + IntToStr(SrcBreakpoint.StackFramesToLog) + ',' + '''' + SrcBreakpoint.ThreadCondition + '''' ); end; finally FreeAndNil(INI); end; end; end.
unit uiscroll; interface uses ui, uimpl, uicomp, uihandle; type TWinScroll=class(TWinComp) private wScrollActive:boolean; last_x_down, last_y_down:integer; protected public procedure CreatePerform;override; procedure CustomPaint;override; procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);override; procedure MouseLeavePerform;override; procedure CapturePerform(AWindow:HWND);override; end; implementation procedure TWinScroll.CreatePerform; begin inherited; wScrollActive:=false; end; procedure TWinScroll.CustomPaint; var r : trect; begin r:=GetClientRect; BeginPaint; Polygon(clPanelBackground1, clPanelBackground1, r.Left, r.Top, r.Right-1, r.Bottom-1); { SetDCPenColor(dc, clWhite); p[0].X:=r.Left; p[0].Y:=r.Bottom-2; p[1].X:=r.Left; p[1].Y:=r.Top; p[2].X:=r.Right-1; p[2].Y:=r.Top; PolyLine(dc, p, 3); SetTextColor(dc, clBlack); SetBkMode(dc, TRANSPARENT);} // DrawText(dc, pchar(name+' '+inttostr(Left)+':'+inttostr(Top)), -1, r, DT_SINGLELINE or DT_CENTER or DT_VCENTER); EndPaint; end; procedure TWinScroll.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); var p:tpoint; begin inherited; if (AButton=mbLeft) then begin GetCursorPos(p); last_x_down:=p.x; last_y_down:=p.y; wScrollActive:=true; SetCapture(window); end; end; procedure TWinScroll.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin inherited; ReleaseCapture(); end; procedure TWinScroll.CapturePerform(AWindow:HWND); begin inherited; wScrollActive := window = AWindow; end; procedure TWinScroll.MouseMovePerform(AButtonControl:cardinal; x,y:integer); var p:tpoint; begin inherited; if wScrollActive then begin GetCursorPos(p); //todo ScrollPerform(last_x_down-p.x, last_y_down-p.y); last_x_down:=p.x; last_y_down:=p.y; end; end; procedure TWinScroll.MouseLeavePerform; begin inherited; end; end.
unit acCollapsePanel; interface uses SysUtils, Classes, Controls, ExtCtrls, Windows, Messages, Graphics, Buttons, Forms, CommCtrl, stdctrls; type TCollapsePanel = class(TPanel) private Fcollapsed: boolean; FcollapsedTitle: TCaption; FexpandedHeight: integer; FexpandedTitle: TCaption; FonCollapse: TNotifyEvent; FOnExpand: TNotifyEvent; procedure Setcollapsed(const Value: boolean); procedure SetcollapsedTitle(const Value: TCaption); procedure SetexpandedHeight(const Value: integer); procedure SetexpandedTitle(const Value: TCaption); procedure SetonCollapse(const Value: TNotifyEvent); procedure SetOnExpand(const Value: TNotifyEvent); { Private declarations } protected Procedure Paint; Override; procedure Resize; override; public { Public declarations } procedure CreateWnd; override; procedure MouseDownOwn(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); published { Published declarations } property collapsed: boolean read Fcollapsed write Setcollapsed; property collapsedTitle: TCaption read FcollapsedTitle write SetcollapsedTitle; property expandedTitle: TCaption read FexpandedTitle write SetexpandedTitle; property expandedHeight: integer read FexpandedHeight write SetexpandedHeight; property OnCollapse: TNotifyEvent read FonCollapse write SetonCollapse; property OnExpand: TNotifyEvent read FOnExpand write SetOnExpand; end; procedure Register; implementation uses Dialogs; procedure Register; begin RegisterComponents('Acras', [TCollapsePanel]); end; { TCollapsePanel } procedure TCollapsePanel.Paint; begin inherited; Canvas.Rectangle(1,1,12,12); Canvas.Rectangle(2,2,11,11); if collapsed then begin Canvas.TextOut(3,-1,'+'); canvas.Font.Style := [fsBold]; Canvas.TextOut(15, -1, FcollapsedTitle); end else begin Canvas.TextOut(4,-1,'-'); canvas.Font.Style := [fsBold]; Canvas.TextOut(15, -1, FexpandedTitle); end; end; procedure TCollapsePanel.Setcollapsed(const Value: boolean); begin if Fcollapsed<>Value then begin if value then begin if Assigned(FonCollapse) then FonCollapse(self); end else begin if Assigned(FonExpand) then FOnExpand(self); end; end; Fcollapsed := Value; if Fcollapsed then Height := 15 else if FexpandedHeight<15 then Height := 15 else Height := FexpandedHeight; Repaint; end; procedure TCollapsePanel.SetcollapsedTitle(const Value: TCaption); begin FcollapsedTitle := Value; end; procedure TCollapsePanel.SetexpandedHeight(const Value: integer); begin FexpandedHeight := Value; end; procedure TCollapsePanel.CreateWnd; begin inherited CreateWnd; OnMouseDown := MouseDownOwn; end; procedure TCollapsePanel.MouseDownOwn(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (x<15) and (y<15) then collapsed := not collapsed; end; procedure TCollapsePanel.SetexpandedTitle(const Value: TCaption); begin FexpandedTitle := Value; end; procedure TCollapsePanel.Resize; begin inherited Resize; if csDesigning in Self.ComponentState then begin if collapsed then height := 15 else begin if Height < 15 then expandedHeight := 15 else expandedHeight := height; end; end; end; procedure TCollapsePanel.SetonCollapse(const Value: TNotifyEvent); begin FonCollapse := Value; end; procedure TCollapsePanel.SetOnExpand(const Value: TNotifyEvent); begin FOnExpand := Value; end; end.
unit fOpenDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, JCLShell,Buttons,shlobj, JvExStdCtrls, JvListBox, JvDriveCtrls, JvCombobox, FileCtrl, cConfiguration; type TfrmOpenDialog = class(TForm) lblFilter: TLabel; cmdOK: TButton; cmdCancel: TButton; cmdMyDocuments: TBitBtn; cmdDesktop: TBitBtn; cmdApplicationDirectory: TBitBtn; lblOpenAs: TLabel; cbDataFile: TComboBox; chkAutoCheckROMType: TCheckBox; DriveCombo: TJvDriveCombo; FileListBox: TJvFileListBox; DirectoryListBox: TJvDirectoryListBox; cbFilter: TComboBox; procedure FormShow(Sender: TObject); procedure FileListBoxDblClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cmdOKClick(Sender: TObject); procedure cmdMyDocumentsClick(Sender: TObject); procedure cmdMyComputerClick(Sender: TObject); procedure cmdDesktopClick(Sender: TObject); procedure cmdApplicationDirectoryClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbFilterChange(Sender: TObject); private _EditorConfig : TRRConfig; _MyDocumentsDir, _DesktopDir, _AppDir : String; procedure LoadDataFiles; { Private declarations } public Filename,OpenDir,DataFile : String; AutoCheck : Boolean; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmOpenDialog: TfrmOpenDialog; implementation {$R *.dfm} procedure TfrmOpenDialog.FormShow(Sender: TObject); begin _MyDocumentsDir := GetSpecialFolderLocation(CSIDL_PERSONAL); _DesktopDir := GetSpecialFolderLocation(CSIDL_DESKTOP); _AppDir := ExtractFileDir(Application.ExeName); LoadDataFiles(); chkAutoCheckROMType.Checked := _EditorConfig.AutoCheck; cbDataFile.ItemIndex := cbDataFile.Items.IndexOf(_EditorConfig.DataFileName); DirectoryListBox.Directory := OpenDir; // sdpOpen.InitialDir := OpenDir; end; procedure TfrmOpenDialog.FileListBoxDblClick(Sender: TObject); begin // Filename := FileListBox.FileName; // modalresult := mrOk; end; procedure TfrmOpenDialog.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then close; end; procedure TfrmOpenDialog.cmdOKClick(Sender: TObject); begin if FileExists(FileListBox.Filename) = true then begin Filename := FileListBox.Filename; DataFile := ExtractFileDir(Application.ExeName) + '\Data\' + cbDataFile.Items[cbDataFile.ItemIndex]; AutoCheck := chkAutoCheckROMType.Checked; modalresult := mrOK; end else messagebox(handle,'Please select a valid file.',PChar(Application.Title),0); end; procedure TfrmOpenDialog.cmdMyDocumentsClick(Sender: TObject); begin DirectoryListBox.Directory := _MyDocumentsDir; end; procedure TfrmOpenDialog.cmdMyComputerClick(Sender: TObject); begin DirectoryListBox.Directory := GetSpecialFolderLocation(CSIDL_DRIVES); end; procedure TfrmOpenDialog.cmdDesktopClick(Sender: TObject); begin DirectoryListBox.Directory := _DesktopDir; end; procedure TfrmOpenDialog.cmdApplicationDirectoryClick(Sender: TObject); begin DirectoryListBox.Directory := _AppDir; end; procedure TfrmOpenDialog.LoadDataFiles(); begin cbDataFile.Items.Clear; cbDataFile.Items.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\data.dat'); end; procedure TfrmOpenDialog.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_F5 then begin DriveCombo.Refresh; directorylistbox.Refresh; FileListBox.Refresh; end; end; procedure TfrmOpenDialog.cbFilterChange(Sender: TObject); begin if cbFilter.ItemIndex = 0 then FileListBox.Mask := '*.nes' else FileListBox.Mask := '*.*'; end; end.
unit nevShapesPaintedSpy; {* Следилка за отрисованными объектами. [RequestLink:235864309] } // Модуль: "w:\common\components\gui\Garant\Everest\new\nevShapesPaintedSpy.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevShapesPaintedSpy" MUID: (4CA5CC2C03CF) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , l3Filer , nevTools , nevShapesPainted ; type TnevShapesPaintedSpy = class; InevShapesLogger = interface {* Лог отрисованных объектов } ['{D33CDAF3-2F4B-422C-879E-56B02F0686F9}'] function OpenLog(const aView: InevView): AnsiString; procedure CloseLog(const aLogName: AnsiString); function LogScreen(const aView: InevView): Boolean; end;//InevShapesLogger TnevShapesPaintedSpy = class(Tl3ProtoObject) {* Следилка за отрисованными объектами. [RequestLink:235864309] } private f_Logger: InevShapesLogger; f_Filer: Tl3CustomFiler; protected procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public procedure LogShapes(const aView: InevView; aShapes: TnevBaseTopShape); {* Логирует отрисованные объекты } procedure SetLogger(const aLogger: InevShapesLogger); procedure RemoveLogger(const aLogger: InevShapesLogger); class function Exists: Boolean; function LogScreen(const aView: InevView): Boolean; class function Instance: TnevShapesPaintedSpy; {* Метод получения экземпляра синглетона TnevShapesPaintedSpy } end;//TnevShapesPaintedSpy implementation uses l3ImplUses , SysUtils , l3Types , k2Tags , l3String {$If Defined(k2ForEditor)} , evParaTools {$IfEnd} // Defined(k2ForEditor) , nevBase , l3MinMax , l3Base //#UC START# *4CA5CC2C03CFimpl_uses* //#UC END# *4CA5CC2C03CFimpl_uses* ; var g_TnevShapesPaintedSpy: TnevShapesPaintedSpy = nil; {* Экземпляр синглетона TnevShapesPaintedSpy } procedure TnevShapesPaintedSpyFree; {* Метод освобождения экземпляра синглетона TnevShapesPaintedSpy } begin l3Free(g_TnevShapesPaintedSpy); end;//TnevShapesPaintedSpyFree procedure TnevShapesPaintedSpy.LogShapes(const aView: InevView; aShapes: TnevBaseTopShape); {* Логирует отрисованные объекты } //#UC START# *4CA5CCF900D5_4CA5CC2C03CF_var* procedure LogShape(aShape : TnevShape); function MangleCoord(aValue : Integer): Integer; function EpsilonIt(aValue : Integer): Integer; begin//EpsilonIt if (aValue > 0) then Result := Max(0, aValue - 20) else if (aValue < 0) then Result := Min(0, aValue + 20) else Result := aValue; end;//EpsilonIt begin//MangleCoord Result := (EpsilonIt(aValue) div 100) * 100; end;//MangleCoord var l_Index : Integer; l_ImageInfo : PnevControlImageInfo; begin//LogShape if (aShape <> nil) then begin f_Filer.WriteLn('----'); with aShape.__Obj do begin f_Filer.WriteLn(Format('Obj type = %s', [AsObject.TagType.AsString])); if AsObject.HasSubAtom(k2_tiText) then f_Filer.WriteLn(Format('Text = ''%s''', [l3ReplaceNonReadable(AsObject.StrA[k2_tiText])])); end;//with aShape.__Obj if (aShape.Count <> 0) then f_Filer.WriteLn(Format('Count = %d', [aShape.Count])); with aShape.Bounds do f_Filer.WriteLn(Format('Rect = (%d, %d, %d, %d)', [MangleCoord(Top), MangleCoord(Left), MangleCoord(Bottom), MangleCoord(Right)])); Assert(aShape.__FI <> nil); with aShape.__FI do begin if (Width <> 0) OR (Height <> 0) then f_Filer.WriteLn(Format('Dim = (%d, %d)', [MangleCoord(Width), MangleCoord(Height)])); if Hidden then f_Filer.WriteLn(Format('Hidden = %d', [Ord(Hidden)])); if (MaxLinesCount <> 0) then f_Filer.WriteLn(Format('MaxLinesCount = %d', [MaxLinesCount])); if (DeltaHeight <> 0) then f_Filer.WriteLn(Format('DeltaHeight = %d', [MangleCoord(DeltaHeight)])); if (Zoom <> 100) then f_Filer.WriteLn(Format('Zoom = %d', [Zoom])); if (Lines <> nil) then if (Lines.Count <> 1) then f_Filer.WriteLn(Format('LinesCount = %d', [Lines.Count])); end;//with aShape.__FI if LogScreen(aView) and evHasOwnStyle(aShape.__Obj) then begin l_ImageInfo := aShape.__FI.ImageInfo; if (l_ImageInfo.rFirstIndex > -1) or (l_ImageInfo.rLastIndex > -1) then begin f_Filer.WriteLn('----'); f_Filer.WriteLn(Format('ImageInfo FirstIndex = %d, LastIndex = %d', [l_ImageInfo.rFirstIndex, l_ImageInfo.rLastIndex])); end; // if EvHasOwnStyle(aShape.__Obj) then end; // if EvHasOwnStyle(aShape.__Obj) then for l_Index := 0 to Pred(aShape.Count) do LogShape(aShape.Items[l_Index]); end;//aShape <> nil end;//LogShape var l_LogName : String; //#UC END# *4CA5CCF900D5_4CA5CC2C03CF_var* begin //#UC START# *4CA5CCF900D5_4CA5CC2C03CF_impl* if (f_Logger <> nil) then begin l_LogName := f_Logger.OpenLog(aView); try f_Filer := Tl3CustomDOSFiler.Make(l_LogName, l3_fmWrite); try f_Filer.Open; try LogShape(aShapes); finally f_Filer.Close; end;//try..finally finally FreeAndNil(f_Filer); end;//try..finally finally f_Logger.CloseLog(l_LogName); end;//try..finally end;//f_Logger <> nil //#UC END# *4CA5CCF900D5_4CA5CC2C03CF_impl* end;//TnevShapesPaintedSpy.LogShapes procedure TnevShapesPaintedSpy.SetLogger(const aLogger: InevShapesLogger); //#UC START# *4CA5CD6801F6_4CA5CC2C03CF_var* //#UC END# *4CA5CD6801F6_4CA5CC2C03CF_var* begin //#UC START# *4CA5CD6801F6_4CA5CC2C03CF_impl* Assert(f_Logger = nil); f_Logger := aLogger; //#UC END# *4CA5CD6801F6_4CA5CC2C03CF_impl* end;//TnevShapesPaintedSpy.SetLogger procedure TnevShapesPaintedSpy.RemoveLogger(const aLogger: InevShapesLogger); //#UC START# *4CA5CD92028D_4CA5CC2C03CF_var* //#UC END# *4CA5CD92028D_4CA5CC2C03CF_var* begin //#UC START# *4CA5CD92028D_4CA5CC2C03CF_impl* Assert(f_Logger = aLogger); f_Logger := nil; //#UC END# *4CA5CD92028D_4CA5CC2C03CF_impl* end;//TnevShapesPaintedSpy.RemoveLogger class function TnevShapesPaintedSpy.Exists: Boolean; begin Result := g_TnevShapesPaintedSpy <> nil; end;//TnevShapesPaintedSpy.Exists function TnevShapesPaintedSpy.LogScreen(const aView: InevView): Boolean; //#UC START# *4CACAF8A0297_4CA5CC2C03CF_var* //#UC END# *4CACAF8A0297_4CA5CC2C03CF_var* begin //#UC START# *4CACAF8A0297_4CA5CC2C03CF_impl* Result := (f_Logger <> nil) AND f_Logger.LogScreen(aView); //#UC END# *4CACAF8A0297_4CA5CC2C03CF_impl* end;//TnevShapesPaintedSpy.LogScreen class function TnevShapesPaintedSpy.Instance: TnevShapesPaintedSpy; {* Метод получения экземпляра синглетона TnevShapesPaintedSpy } begin if (g_TnevShapesPaintedSpy = nil) then begin l3System.AddExitProc(TnevShapesPaintedSpyFree); g_TnevShapesPaintedSpy := Create; end; Result := g_TnevShapesPaintedSpy; end;//TnevShapesPaintedSpy.Instance procedure TnevShapesPaintedSpy.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4CA5CC2C03CF_var* //#UC END# *479731C50290_4CA5CC2C03CF_var* begin //#UC START# *479731C50290_4CA5CC2C03CF_impl* FreeAndNil(f_Filer); inherited; //#UC END# *479731C50290_4CA5CC2C03CF_impl* end;//TnevShapesPaintedSpy.Cleanup procedure TnevShapesPaintedSpy.ClearFields; begin f_Logger := nil; inherited; end;//TnevShapesPaintedSpy.ClearFields end.
unit mcr_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,ay_8910,gfx_engine,rom_engine, pal_engine,sound_engine,z80daisy,z80ctc,timer_engine,file_engine; function iniciar_mcr:boolean; implementation const tapper_rom:array[0..3] of tipo_roms=( (n:'tapper_c.p.u._pg_0_1c_1-27-84.1c';l:$4000;p:0;crc:$bb060bb0),(n:'tapper_c.p.u._pg_1_2c_1-27-84.2c';l:$4000;p:$4000;crc:$fd9acc22), (n:'tapper_c.p.u._pg_2_3c_1-27-84.3c';l:$4000;p:$8000;crc:$b3755d41),(n:'tapper_c.p.u._pg_3_4c_1-27-84.4c';l:$2000;p:$c000;crc:$77273096)); tapper_snd:array[0..3] of tipo_roms=( (n:'tapper_sound_snd_0_a7_12-7-83.a7';l:$1000;p:0;crc:$0e8bb9d5),(n:'tapper_sound_snd_1_a8_12-7-83.a8';l:$1000;p:$1000;crc:$0cf0e29b), (n:'tapper_sound_snd_2_a9_12-7-83.a9';l:$1000;p:$2000;crc:$31eb6dc6),(n:'tapper_sound_snd_3_a10_12-7-83.a10';l:$1000;p:$3000;crc:$01a9be6a)); tapper_char:array[0..1] of tipo_roms=( (n:'tapper_c.p.u._bg_1_6f_12-7-83.6f';l:$4000;p:0;crc:$2a30238c),(n:'tapper_c.p.u._bg_0_5f_12-7-83.5f';l:$4000;p:$4000;crc:$394ab576)); tapper_sprites:array[0..7] of tipo_roms=( (n:'tapper_video_fg_1_a7_12-7-83.a7';l:$4000;p:0;crc:$32509011),(n:'tapper_video_fg_0_a8_12-7-83.a8';l:$4000;p:$4000;crc:$8412c808), (n:'tapper_video_fg_3_a5_12-7-83.a5';l:$4000;p:$8000;crc:$818fffd4),(n:'tapper_video_fg_2_a6_12-7-83.a6';l:$4000;p:$c000;crc:$67e37690), (n:'tapper_video_fg_5_a3_12-7-83.a3';l:$4000;p:$10000;crc:$800f7c8a),(n:'tapper_video_fg_4_a4_12-7-83.a4';l:$4000;p:$14000;crc:$32674ee6), (n:'tapper_video_fg_7_a1_12-7-83.a1';l:$4000;p:$18000;crc:$070b4c81),(n:'tapper_video_fg_6_a2_12-7-83.a2';l:$4000;p:$1c000;crc:$a37aef36)); //DIP tapper_dipa:array [0..3] of def_dip=( (mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Coin Meters';number:2;dip:((dip_val:$80;dip_name:'1'),(dip_val:$0;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); CPU_SYNC=8; var nvram:array[0..$7ff] of byte; //Sonido ssio_status:byte; ssio_data:array[0..3] of byte; ssio_14024_count:byte; procedure update_video_tapper; procedure put_sprite_mcr(pri:byte); var prioridad,f,color,atrib,x,y,pos_y:byte; temp,temp2:pword; pos:pbyte; dir_x,dir_y:integer; nchar,sx,sy:word; //prio:array[0..$1ff,0..$1ff] of boolean; begin //fillchar(prio,512*512,0); for f:=0 to $7f do begin sx:=((memoria[$e803+(f*4)]-3)*2) and $1ff; sy:=((241-memoria[$e800+(f*4)])*2) and $1ff; nchar:=memoria[$e802+(f*4)]+(((memoria[$e801+(f*4)] shr 3) and $1) shl 8); atrib:=memoria[$e801+(f*4)]; color:=(not(memoria[$e801+(f*4)]) and 3) shl 4; pos:=gfx[1].datos; inc(pos,nchar*32*32); if (atrib and $20)<>0 then begin pos_y:=31; dir_y:=-1; end else begin pos_y:=0; dir_y:=1; end; if (atrib and $10)<>0 then begin temp2:=punbuf; inc(temp2,31); dir_x:=-1; end else begin temp2:=punbuf; dir_x:=1; end; for y:=0 to 31 do begin temp:=temp2; for x:=0 to 31 do begin //if not(prio[(sx+x) and $1ff,(sy+y) and $1ff]) then begin if (gfx[1].colores[pos^+color] and $7)<>0 then temp^:=paleta[gfx[1].colores[pos^+color]] else temp^:=paleta[MAX_COLORES]; // prio[(sx+x) and $1ff,(sy+y) and $1ff]:=true; //end else temp^:=paleta[MAX_COLORES]; inc(temp,dir_x); inc(pos); end; putpixel_gfx_int(0,pos_y,32,PANT_SPRITES); pos_y:=pos_y+dir_y; end; actualiza_gfx_sprite(sx,sy,2,1); end; end; var x,y,h,atrib2:byte; atrib,f,nchar,color:word; begin //fill_full_screen(5,$100); for f:=0 to $3bf do begin atrib:=memoria[$f000+(f*2)] or (memoria[$f001+(f*2)] shl 8); color:=(atrib shr 12) and 3; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f and $1f; y:=f shr 5; nchar:=atrib and $3ff; put_gfx_flip(x*16,y*16,nchar,color shl 4,1,0,(atrib and $400)<>0,(atrib and $800)<>0); //atrib2:=((atrib shr 14) and 3)+1; //prio[x,y]:=atrib2; //for h:=1 to 4 do begin // if h=atrib2 then put_gfx_flip(x*16,y*16,nchar,color shl 4,h,0,(atrib and $400)<>0,(atrib and $800)<>0) // else put_gfx_block_trans(x*16,y*16,h,16,16); //end; gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,512,480,1,0,0,512,480,2); put_sprite_mcr(1); //actualiza_trozo(0,0,512,480,2,0,0,512,480,5); //put_sprite_mcr(2); //actualiza_trozo(0,0,512,480,3,0,0,512,480,5); //put_sprite_mcr(3); //actualiza_trozo(0,0,512,480,4,0,0,512,480,5); //put_sprite_mcr(4); actualiza_trozo_final(0,0,512,480,2); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_tapper; begin if event.arcade then begin //ip0 if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or 4); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or 8); //ip1 if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or 1); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or 2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or 4); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or 8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); //ip2 if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or 1); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or 2); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or 4); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or 8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); end; end; procedure tapper_principal; var frame_m,frame_s:single; f:word; h:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to 479 do begin for h:=1 to CPU_SYNC do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; end; if ((f=0) or (f=239)) then begin ctc_0.trigger(2,true); ctc_0.trigger(2,false); end; if (f=0) then begin update_video_tapper; ctc_0.trigger(3,true); ctc_0.trigger(3,false); end; end; eventos_tapper; video_sync; end; end; function tapper_getbyte(direccion:word):byte; begin case direccion of 0..$dfff,$f000..$f7ff:tapper_getbyte:=memoria[direccion]; $e000..$e7ff:tapper_getbyte:=nvram[direccion and $7ff]; $e800..$ebff:tapper_getbyte:=memoria[$e800+(direccion and $1ff)]; else tapper_getbyte:=$ff; end; end; procedure cambiar_color(pos:byte;tmp_color:word); var color:tcolor; begin color.r:=pal3bit(tmp_color shr 6); color.g:=pal3bit(tmp_color shr 0); color.b:=pal3bit(tmp_color shr 3); set_pal_color(color,pos); buffer_color[(pos shr 4) and 3]:=true; end; procedure tapper_putbyte(direccion:word;valor:byte); begin case direccion of 0..$dfff:; //ROM $e000..$e7ff:nvram[direccion and $7ff]:=valor; $e800..$ebff:memoria[$e800+(direccion and $1ff)]:=valor; $f000..$f7ff:begin memoria[direccion]:=valor; gfx[0].buffer[(direccion and $7ff) shr 1]:=true; end; $f800..$ffff:cambiar_color((direccion and $7f) shr 1,valor or ((direccion and 1) shl 8)); end; end; function tapper_inbyte(puerto:word):byte; begin case (puerto and $ff) of $0..$1f:case (puerto and 7) of $0:tapper_inbyte:=marcade.in0; $1:tapper_inbyte:=marcade.in1; $2:tapper_inbyte:=marcade.in2; $3:tapper_inbyte:=marcade.dswa; $4:tapper_inbyte:=$ff; $7:tapper_inbyte:=ssio_status; //ssio_device_read; end; $f0..$f3:tapper_inbyte:=ctc_0.read(puerto and $3); end; end; procedure tapper_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $0..$7:;//ssio_ioport_write; $1c..$1f:ssio_data[puerto and 3]:=valor; //ssio_write; $e0:; //wathcdog $e8:; $f0..$f3:ctc_0.write(puerto and $3,valor); end; end; function snd_getbyte(direccion:word):byte; begin case direccion of 0..$3fff:snd_getbyte:=mem_snd[direccion]; $8000..$8fff:snd_getbyte:=mem_snd[$8000 or (direccion and $3ff)]; $9000..$9fff:snd_getbyte:=ssio_data[direccion and $3]; $a000..$afff:if (direccion and 3)=1 then snd_getbyte:=ay8910_0.Read; $b000..$bfff:if (direccion and 3)=1 then snd_getbyte:=ay8910_1.Read; $e000..$efff:begin ssio_14024_count:=0; z80_1.change_irq(CLEAR_LINE); end; $f000..$ffff:snd_getbyte:=$ff; //DIP end; end; procedure snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $8000..$8fff:mem_snd[$8000 or (direccion and $3ff)]:=valor; $a000..$afff:case (direccion and 3) of $0:ay8910_0.Control(valor); $2:ay8910_0.Write(valor); end; $b000..$bfff:case (direccion and 3) of $0:ay8910_1.Control(valor); $2:ay8910_1.Write(valor); end; $c000..$cfff:ssio_status:=valor; end; end; procedure z80ctc_int(state:byte); begin z80_0.change_irq(state); end; procedure tapper_snd_irq; begin // // /SINT is generated as follows: // // Starts with a 16MHz oscillator // /2 via 7474 flip-flop @ F11 // /16 via 74161 binary counter @ E11 // /10 via 74190 decade counter @ D11 // // Bit 3 of the decade counter clocks a 14024 7-bit async counter @ C12. // This routine is called to clock this 7-bit counter. // Bit 6 of the output is inverted and connected to /SINT. // ssio_14024_count:=(ssio_14024_count+1) and $7f; // if the low 5 bits clocked to 0, bit 6 has changed state if ((ssio_14024_count and $3f)=0) then if (ssio_14024_count and $40)<>0 then z80_1.change_irq(ASSERT_LINE) else z80_1.change_irq(CLEAR_LINE); end; procedure tapper_update_sound; begin tsample[ay8910_0.get_sample_num,sound_status.posicion_sonido]:=ay8910_0.update_internal^; tsample[ay8910_0.get_sample_num,sound_status.posicion_sonido+1]:=ay8910_1.update_internal^; end; //Main procedure mcr_reset; begin z80_0.reset; z80_1.reset; ctc_0.reset; ay8910_0.reset; ay8910_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; //Sonido ssio_status:=0; fillchar(ssio_data[0],4,0); fillchar(nvram[0],$800,1); ssio_14024_count:=0; end; procedure close_tapper; begin write_file(Directory.Arcade_nvram+'tapper.nv',@nvram,$800); end; function iniciar_mcr:boolean; const pc_x:array[0..15] of dword=(0*2, 0*2, 1*2, 1*2, 2*2, 2*2, 3*2, 3*2, 4*2, 4*2, 5*2, 5*2, 6*2, 6*2, 7*2, 7*2); pc_y:array[0..15] of dword=(0*16, 0*16, 1*16, 1*16, 2*16, 2*16, 3*16, 3*16, 4*16, 4*16, 5*16, 5*16, 6*16, 6*16, 7*16, 7*16); ps_x:array[0..31] of dword=(0, 4, $100*32*32, $100*32*32+4, $200*32*32, $200*32*32+4, $300*32*32, $300*32*32+4, 8, 12, $100*32*32+8, $100*32*32+12, $200*32*32+8, $200*32*32+12, $300*32*32+8, $300*32*32+12, 16, 20, $100*32*32+16, $100*32*32+20, $200*32*32+16, $200*32*32+20, $300*32*32+16, $300*32*32+20, 24, 28, $100*32*32+24, $100*32*32+28, $200*32*32+24, $200*32*32+28, $300*32*32+24, $300*32*32+28); ps_y:array[0..31] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32, 16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32, 24*32, 25*32, 26*32, 27*32, 28*32, 29*32, 30*32, 31*32); var memoria_temp:array[0..$1ffff] of byte; longitud:integer; begin llamadas_maquina.bucle_general:=tapper_principal; llamadas_maquina.reset:=mcr_reset; llamadas_maquina.fps_max:=30; llamadas_maquina.close:=close_tapper; iniciar_mcr:=false; iniciar_audio(true); screen_init(1,512,480,true); //screen_init(2,512,480,true); //screen_init(3,512,480,true); //screen_init(4,512,480,true); screen_init(2,512,512,false,true); iniciar_video(512,480); //Main CPU z80_0:=cpu_z80.create(5000000,480*CPU_SYNC); z80_0.change_ram_calls(tapper_getbyte,tapper_putbyte); z80_0.change_io_calls(tapper_inbyte,tapper_outbyte); z80_0.daisy:=true; ctc_0:=tz80ctc.create(z80_0.numero_cpu,5000000,z80_0.clock,0,CTC0_TRG01); ctc_0.change_calls(z80ctc_int); z80daisy_init(Z80_CTC0_TYPE,Z80_DAISY_NONE); //Sound CPU z80_1:=cpu_z80.create(2000000,480*CPU_SYNC); z80_1.change_ram_calls(snd_getbyte,snd_putbyte); z80_1.init_sound(tapper_update_sound); timers.init(z80_1.numero_cpu,2000000/(160*2*16*10),tapper_snd_irq,nil,true); //Sound Chip ay8910_0:=ay8910_chip.create(2000000,AY8910,1); ay8910_1:=ay8910_chip.create(2000000,AY8910,1,true); //cargar roms if not(roms_load(@memoria,tapper_rom)) then exit; //cargar roms sonido if not(roms_load(@mem_snd,tapper_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,tapper_char)) then exit; init_gfx(0,16,16,$400); gfx_set_desc_data(4,0,16*8,$400*16*8,($400*16*8)+1,0,1); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //sprites if not(roms_load(@memoria_temp,tapper_sprites)) then exit; init_gfx(1,32,32,$100); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,32*32,0,1,2,3); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //Cargar NVRam if read_file_size(Directory.Arcade_nvram+'tapper.nv',longitud) then read_file(Directory.Arcade_nvram+'tapper.nv',@nvram,longitud); //DIP marcade.dswa:=$c0; marcade.dswa_val:=@tapper_dipa; //final mcr_reset; iniciar_mcr:=true; end; end.
unit OSUtils; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {$mode objfpc}{$H+} {$macro on} {$inline on} interface uses SysUtils,CoreTypes; function GetEnviron(const Varname:String): String; Cdecl; function SetEnviron(const Varname, Value:String): Boolean; Cdecl; procedure ListDir(Path:String; out contents:TStringArray); Cdecl; function FileRemove(Path:String): Boolean; Cdecl; function DirRemove(Path:String): Boolean; Cdecl; function FileRename(Src, Dest:String): Boolean; Cdecl; function FileCopy(Src, Dest:String): Boolean; Cdecl; function FileSize2(Path: String): Int64; Cdecl; function ReadFile(FileName: String): String; Cdecl; function UTime(Path:String; Times:TIntArray): Boolean; Cdecl; procedure TouchFile(Path:String); Cdecl; //os.path function NormPath(Path:String): String; Cdecl; function AbsPath(Path:String): String; cdecl; function DirName(Path:String): String; Cdecl; function PathExists(Path:String): Boolean; Cdecl; function IsAbsPath(path:String): Boolean; Cdecl; function IsFile(path:String): Boolean; Cdecl; function IsDir(path:String): Boolean; Cdecl; //----------------------------------------------------------------------------\\ implementation uses Classes, {$IFDEF WINDOWS}Windows,{$ENDIF} FileUtil, DateUtils, TimeUtils, StringTools; function GetCWD: string; var tmp:TStringArray; i: Int32; begin (* SimbaPath = ModuleDirectory - \incudes\WhatEver\plugin.dll *) Result := LowerCase(GetModuleName(hInstance)); tmp := StrExplode(Result, '\'); Result := ''; for i:=0 to (High(tmp) - 3) do Result := Result + tmp[i] + '\'; end; function FixDirPath(path:String): String; begin if DirectoryExists(Path) and (Path[length(path)] <> '\') then Path := Path + '\'; Result := Path; end; (* OS.Path.* and whatnots *******************************************************) // os.path.normpath(path) function NormPath(Path:String): String; cdecl; var i,j,slash:Int32; fold:TStringArray; tmp:String; NotBack: Boolean; begin Path := StringReplace(Path, '/', '\', [rfReplaceAll]); tmp := ''; slash := 0; for i:=1 to Length(path) do begin if path[i] = '\' then inc(slash) else slash := 0; if not(slash > 1) then tmp := tmp + path[i]; end; fold := StrExplode(tmp,'\'); j := 0; Result := ''; for i:=0 to High(fold) do begin notback := True; if (i < High(fold)) then notback := (fold[i+1] <> '..'); if notback and (fold[i] <> '..') and (fold[i] <> '.') then begin if j > 0 then Result := Result + '\' + fold[i] else Result := Result + Fold[i]; inc(j); end; end; end; // os.path.abspath(path) function AbsPath(Path:String): String; cdecl; begin if length(path) > 2 then begin if not((lowercase(path[1]) in ['a'..'z']) and (path[2] = ':')) then Result := NormPath(GetCWD() + Path); end else Result := NormPath(GetCWD() + Path); end; // os.path.basename(path) // os.path.dirname(path) function DirName(Path:String): String; Cdecl; var a:TStrArray; i:Int32; begin Path := FixDirPath(NormPath(Path)); a := StrExplode(Path,'\'); if Length(a) > 0 then begin Result := a[0]; for i:=1 to High(a)-1 do Result := Result + '\' + a[i]; end; end; // os.path.exists(path) function PathExists(Path:String): Boolean; Cdecl; begin Result := IsFile(Path) or IsDir(Path); end; // os.path.getatime(path) // os.path.getmtime(path) // os.path.getsize(path) // os.path.isabs(path) function IsAbsPath(path:String): Boolean; Cdecl; begin if Length(path) > 2 then Result := (lowercase(path[1]) in ['a'..'z']) and (path[2] = ':') else Result := False; //if not(Result) and ((path[1] = '\') or (path[1] = '/')) then // Result := True; end; // os.path.isfile(path) function IsFile(path:String): Boolean; Cdecl; begin Result := FileExists(Path); end; // os.path.isdir(path) function IsDir(path:String): Boolean; Cdecl; begin Result := DirectoryExists(Path); end; // os.path.search(path, file) (* OS.* and whatnots **********************************************************) { OS.GetEnv(Varname:String): String; } function GetEnviron(const Varname:String): String; Cdecl; begin Result := GetEnvironmentVariableUTF8(Varname); end; { OS.SetEnv(Varname, Value:String): Boolean; } function SetEnviron(const Varname, Value:String): Boolean; Cdecl; begin Result := SetEnvironmentVariableW(PWChar(Varname), PWChar(Value)); end; { OS.ListDir(Path:String): TStringArray } procedure ListDir(Path:String; out contents:TStringArray); Cdecl; var l: Int32; SR : TSearchRec; begin Path := FixDirPath(NormPath(Path)); l := 0; if FindFirst(Path + '*', faAnyFile and faDirectory, SR) = 0 then begin repeat if (SR.Name <> '.') and (SR.Name <> '..') then begin inc(l); SetLength(contents, l); contents[l-1] := SR.Name; end; until FindNext(SR) <> 0; FindClose(SR); end; end; { OS.Remove(Path:String): Boolean; } function FileRemove(Path:String): Boolean; Cdecl; begin Result := DeleteFileUTF8(Path); end; { OS.Rmdir(Path:String): Boolean; } function DirRemove(Path:String): Boolean; Cdecl; var Files:TStringArray; i:Int32; begin Path := FixDirPath(NormPath(Path)); ListDir(Path, Files); for i:=0 to High(Files) do begin if not IsDir(Path + Files[i]) then DeleteFileUTF8(Path + Files[i]) else DirRemove(Path + Files[i]); end; Result := RemoveDirUTF8(Path); end; { OS.Rename(Src, Dest:String) } function FileRename(Src, Dest:String): Boolean; Cdecl; begin Result := RenameFileUTF8(Src, Dest); end; { OS.CopyFile(Src, Dest:String) } function FileCopy(Src, Dest:String): Boolean; Cdecl; begin Result := CopyFile(Src, Dest); end; { OS.Size(Path:String) } function FileSize2(Path: String): Int64; Cdecl; var i:Int32; list: TStringList; size: Int64; begin Size := 0; if IsFile(path) then Size := FileSize(Path) else begin List := FindAllFiles(Path, '', True); for i:=0 to List.Count-1 do Inc(Size, FileSize(List[i])); List.Free; end; Result := Size; end; { OS.ReadFile(FileName:String): String } function ReadFile(FileName: String): String; Cdecl; var FileStream : TFileStream; begin FileStream := TFileStream.Create(FileName, fmOpenRead); try if (FileStream.Size > 0) then begin SetLength(Result, FileStream.Size); FileStream.Read(Pointer(Result)^, FileStream.Size); end; finally FileStream.Free; end; end; { OS.UTime(Path:String; Times:TIntArray = [CreationTime, LastAccessTime, LastWriteTime] } function UTime(Path:String; Times:TIntArray): Boolean; Cdecl; var {$IFDEF WINDOWS} H:THandle; ST1,ST2,ST3: TSystemTime; FT1,FT2,FT3: TFileTime; {$ENDIF} begin {$IFDEF WINDOWS} if not Length(Times) = 3 then Exit; H := FileOpen(Path, fmOpenReadWrite); ST1 := EpochTimeToSysTime(Times[0]); ST2 := EpochTimeToSysTime(Times[1]); ST3 := EpochTimeToSysTime(Times[2]); SystemTimeToFileTime(ST1,FT1); SystemTimeToFileTime(ST2,FT2); SystemTimeToFileTime(ST3,FT3); try if (Times[0] > 0) and (Times[1] > 0) and (Times[2] > 0) then Result := SetFileTime(H, @FT1, @FT2, @FT3) else if (Times[0] <= 0) and (Times[1] > 0) and (Times[2] > 0) then Result := SetFileTime(H, nil, @FT2, @FT3) else if (Times[0] > 0) and (Times[1] <= 0) and (Times[2] > 0) then Result := SetFileTime(H, @FT1, nil, @FT3) else if (Times[0] > 0) and (Times[1] > 0) and (Times[2] <= 0) then Result := SetFileTime(H, @FT1, @FT2, nil) else if (Times[0] > 0) and (Times[1] <= 0) and (Times[2] <= 0) then Result := SetFileTime(H, @FT1, nil, nil) else if (Times[0] <= 0) and (Times[1] > 0) and (Times[2] <= 0) then Result := SetFileTime(H, nil, @FT2, nil) else if (Times[0] <= 0) and (Times[1] <= 0) and (Times[2] > 0) then Result := SetFileTime(H, nil, nil, @FT3); if not(Result) then RaiseLastOSError; finally CloseHandle(H); end; {$ENDIF} end; procedure TouchFile(Path:String); Cdecl; var {$IFDEF WINDOWS} H:THandle; ST: TSystemTime; FT: TFileTime; {$ENDIF} begin {$IFDEF WINDOWS} H := FileOpen(Path, fmOpenReadWrite); GetSystemTime(ST); SystemTimeToFileTime(ST, FT); SetFileTime(H, nil, @FT, nil); CloseHandle(H); {$ENDIF} end; end.
unit tipoCombustivelDao_DUnit; interface uses Forms, IBDataBase, IBCustomDataSet, dm, TestFrameWork, TipoCombustivelDao, AbastecimentoDao, Abastecimento, Classes, SysUtils; type T_TipoCombustivelDao_Tester = class(TTestCase) protected db: TIBDataBase; tr: TIBTransaction; procedure SetUp(); override; procedure TearDown(); override; published procedure TipoCombustivel_listAll(); procedure Abastecimento_Incluir(); end; implementation procedure T_TipoCombustivelDao_Tester.SetUp(); begin inherited; // Configurando uma conexão com o banco de dados db := TIBDatabase.Create(nil); tr := TIBTransaction.Create(nil); db.DefaultTransaction := tr; db.DatabaseName := ExtractFilePath(Application.ExeName) + '..\POSTO.GDB'; db.Params.Add('user_name=sysdba'); db.Params.Add('password=masterkey'); db.Params.Add('lc_ctype=UTF-8'); db.LoginPrompt := False; db.AllowStreamedConnected := False; db.Connected := True; end; procedure T_TipoCombustivelDao_Tester.TearDown(); begin inherited; db.Close(); db.Free(); end; procedure T_TipoCombustivelDao_Tester.TipoCombustivel_listAll(); var dao: T_TipoCombustivelDao; lista: TList; begin dao := T_TipoCombustivelDao.Create(db); lista := dao.listarTudo; check(lista.Count > 0, 'Tipos de combustível: ' + IntToStr(lista.Count)); end; procedure T_TipoCombustivelDao_Tester.Abastecimento_Incluir(); var dao: T_AbastecimentoDao; abastecimento: T_Abastecimento; lista: TList; begin dao := T_AbastecimentoDao.Create(db); abastecimento := T_Abastecimento.Create(now, 1, 23, 3.989, 13); dao.incluir(abastecimento); lista := dao.listarTudo(); check(lista.Count > 0, 'Não há dados inclusos ' + IntToStr(lista.Count)); end; initialization TestFramework.RegisterTest(T_TipoCombustivelDao_Tester.Suite); end.
unit ncsTaskProgress; // Модуль: "w:\common\components\rtl\Garant\cs\ncsTaskProgress.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsTaskProgress" MUID: (54746A670337) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , ncsMessage , k2Base ; type TncsTaskProgress = class(TncsMessage) protected function pm_GetTaskID: AnsiString; procedure pm_SetTaskID(const aValue: AnsiString); function pm_GetDescription: AnsiString; procedure pm_SetDescription(const aValue: AnsiString); function pm_GetPercent: Integer; procedure pm_SetPercent(aValue: Integer); public class function GetTaggedDataType: Tk2Type; override; public property TaskID: AnsiString read pm_GetTaskID write pm_SetTaskID; property Description: AnsiString read pm_GetDescription write pm_SetDescription; property Percent: Integer read pm_GetPercent write pm_SetPercent; end;//TncsTaskProgress {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , csTaskProgress_Const //#UC START# *54746A670337impl_uses* //#UC END# *54746A670337impl_uses* ; function TncsTaskProgress.pm_GetTaskID: AnsiString; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.StrA[k2_attrTaskID]); end;//TncsTaskProgress.pm_GetTaskID procedure TncsTaskProgress.pm_SetTaskID(const aValue: AnsiString); begin TaggedData.StrW[k2_attrTaskID, nil] := (aValue); end;//TncsTaskProgress.pm_SetTaskID function TncsTaskProgress.pm_GetDescription: AnsiString; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.StrA[k2_attrDescription]); end;//TncsTaskProgress.pm_GetDescription procedure TncsTaskProgress.pm_SetDescription(const aValue: AnsiString); begin TaggedData.StrW[k2_attrDescription, nil] := (aValue); end;//TncsTaskProgress.pm_SetDescription function TncsTaskProgress.pm_GetPercent: Integer; begin Assert(Self <> nil); Assert(TaggedData <> nil); Result := (TaggedData.IntA[k2_attrPercent]); end;//TncsTaskProgress.pm_GetPercent procedure TncsTaskProgress.pm_SetPercent(aValue: Integer); begin TaggedData.IntW[k2_attrPercent, nil] := (aValue); end;//TncsTaskProgress.pm_SetPercent class function TncsTaskProgress.GetTaggedDataType: Tk2Type; begin Result := k2_typcsTaskProgress; end;//TncsTaskProgress.GetTaggedDataType {$IfEnd} // NOT Defined(Nemesis) end.
{ In short its a method that creates a product, the method must be overriden by decendents to extend the base (or sometimes fail-over) product range. } unit FactoryMethod; interface type IProduct = interface // definition not important for illustration end; TAbstractProductCreator = class abstract public function CreateProduct(AProductID: integer): IProduct; virtual; end; // The function that creates the products is virtual and can be overridden // The abstract creator may have an implementation or we may also have // a base product creator defined. The design pattern really only centers // around the method. It must be virtual, Descendents implement and fall throug // is handled via inheritence implementation uses System.SysUtils; Type TBaseProductA = class(TInterfacedObject, IProduct) // definition not important for illustration end; TBaseProductB = class(TInterfacedObject, IProduct) // definition not important for illustration end; function TAbstractProductCreator.CreateProduct(AProductID: integer): IProduct; begin // Case statement against AProductID. Descendants should add their own // cases and call inherited as a fall through Case AProductID of 1: result := TBaseProductA.Create; 2: result := TBaseProductB.Create; else raise Exception.Create('Error Message'); end; end; end.
{$IfNDef vcmUserInteractiveForm_imp} // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Visual\vcmUserInteractiveForm.imp.pas" // Стереотип: "Impurity" // Элемент модели: "vcmUserInteractiveForm" MUID: (4E01D5E50001) // Имя типа: "_vcmUserInteractiveForm_" {$Define vcmUserInteractiveForm_imp} {$If NOT Defined(NoVCM)} _vcmUserInteractiveForm_ = class(_vcmUserInteractiveForm_Parent_, IvcmUserInteraction) protected function MessageDlg(const aMsg: IvcmCString; const aKey: AnsiString; aDlgType: TMsgDlgType = Dialogs.mtCustom; aButtons: TMsgDlgButtons = [mbOK]): Integer; overload; function MessageDlg(const aMsg: TvcmMessageID): Integer; overload; procedure Say(const aMsg: TvcmMessageID); overload; procedure Say(const aMsg: TvcmMessageID; const aData: array of const); overload; function Ask(const aMsg: TvcmMessageID): Boolean; overload; function Ask(const aMsg: TvcmMessageID; const aData: array of const): Boolean; overload; function Ask(const aMsg: Tl3MessageID; const aData: array of const): Boolean; overload; function MessageDlg(const aMsg: Tl3MessageID; const aData: array of const): Integer; overload; function MessageDlg(const aMsg: Tl3MessageID): Integer; overload; end;//_vcmUserInteractiveForm_ {$Else NOT Defined(NoVCM)} _vcmUserInteractiveForm_ = _vcmUserInteractiveForm_Parent_; {$IfEnd} // NOT Defined(NoVCM) {$Else vcmUserInteractiveForm_imp} {$IfNDef vcmUserInteractiveForm_imp_impl} {$Define vcmUserInteractiveForm_imp_impl} {$If NOT Defined(NoVCM)} function _vcmUserInteractiveForm_.MessageDlg(const aMsg: IvcmCString; const aKey: AnsiString; aDlgType: TMsgDlgType = Dialogs.mtCustom; aButtons: TMsgDlgButtons = [mbOK]): Integer; //#UC START# *4993085402D8_4E01D5E50001_var* //#UC END# *4993085402D8_4E01D5E50001_var* begin //#UC START# *4993085402D8_4E01D5E50001_impl* Result := vcmShowMessageDlg(Tl3Message_C(aMsg, aKey, aDlgType, aButtons)); //#UC END# *4993085402D8_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.MessageDlg function _vcmUserInteractiveForm_.MessageDlg(const aMsg: TvcmMessageID): Integer; //#UC START# *4993088901F8_4E01D5E50001_var* //#UC END# *4993088901F8_4E01D5E50001_var* begin //#UC START# *4993088901F8_4E01D5E50001_impl* Result := vcmMessageDlg(aMsg); //#UC END# *4993088901F8_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.MessageDlg procedure _vcmUserInteractiveForm_.Say(const aMsg: TvcmMessageID); //#UC START# *4993090C039C_4E01D5E50001_var* //#UC END# *4993090C039C_4E01D5E50001_var* begin //#UC START# *4993090C039C_4E01D5E50001_impl* vcmSay(aMsg); //#UC END# *4993090C039C_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.Say procedure _vcmUserInteractiveForm_.Say(const aMsg: TvcmMessageID; const aData: array of const); //#UC START# *499309240368_4E01D5E50001_var* //#UC END# *499309240368_4E01D5E50001_var* begin //#UC START# *499309240368_4E01D5E50001_impl* vcmSay(aMsg, aData); //#UC END# *499309240368_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.Say function _vcmUserInteractiveForm_.Ask(const aMsg: TvcmMessageID): Boolean; //#UC START# *4993093502E9_4E01D5E50001_var* //#UC END# *4993093502E9_4E01D5E50001_var* begin //#UC START# *4993093502E9_4E01D5E50001_impl* Result := vcmAsk(aMsg); //#UC END# *4993093502E9_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.Ask function _vcmUserInteractiveForm_.Ask(const aMsg: TvcmMessageID; const aData: array of const): Boolean; //#UC START# *49930942035E_4E01D5E50001_var* //#UC END# *49930942035E_4E01D5E50001_var* begin //#UC START# *49930942035E_4E01D5E50001_impl* Result := vcmAsk(aMsg, aData); //#UC END# *49930942035E_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.Ask function _vcmUserInteractiveForm_.Ask(const aMsg: Tl3MessageID; const aData: array of const): Boolean; //#UC START# *4E7CA605012E_4E01D5E50001_var* //#UC END# *4E7CA605012E_4E01D5E50001_var* begin //#UC START# *4E7CA605012E_4E01D5E50001_impl* Result := vcmAsk(aMsg, aData); //#UC END# *4E7CA605012E_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.Ask function _vcmUserInteractiveForm_.MessageDlg(const aMsg: Tl3MessageID; const aData: array of const): Integer; //#UC START# *4E9E89E9006D_4E01D5E50001_var* //#UC END# *4E9E89E9006D_4E01D5E50001_var* begin //#UC START# *4E9E89E9006D_4E01D5E50001_impl* Result := vcmMessageDlg(aMsg, aData); //#UC END# *4E9E89E9006D_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.MessageDlg function _vcmUserInteractiveForm_.MessageDlg(const aMsg: Tl3MessageID): Integer; //#UC START# *4F9AB5AF01F9_4E01D5E50001_var* //#UC END# *4F9AB5AF01F9_4E01D5E50001_var* begin //#UC START# *4F9AB5AF01F9_4E01D5E50001_impl* Result := vcmMessageDlg(aMsg, []); //#UC END# *4F9AB5AF01F9_4E01D5E50001_impl* end;//_vcmUserInteractiveForm_.MessageDlg {$IfEnd} // NOT Defined(NoVCM) {$EndIf vcmUserInteractiveForm_imp_impl} {$EndIf vcmUserInteractiveForm_imp}
unit ConvertImpl; interface uses Classes, SysUtils, InvokeRegistry, ConvertIntf; type TConvert = class (TInvokableClass, IConvert) protected function ConvertCurrency (Source, Dest: string; Amount: Double): Double; stdcall; function ToEuro (Source: string; Amount: Double): Double; stdcall; function FromEuro (Dest: string; Amount: Double): Double; stdcall; function TypesList: string; stdcall; end; implementation uses ConvUtils, EuroConvConst; { TConvert } function TConvert.ConvertCurrency(Source, Dest: string; Amount: Double): Double; var BaseType, DestType: TConvType; begin if DescriptionToConvType (cbEuroCurrency, Source, BaseType) and DescriptionToConvType (cbEuroCurrency, Dest, DestType) then Result := EuroConvert (Amount, BaseType, DestType, 4) else raise Exception.Create ('Undefined currency types'); end; function TConvert.FromEuro(Dest: string; Amount: Double): Double; var DestType: TConvType; begin Result := 0; if DescriptionToConvType (cbEuroCurrency, Dest, DestType) then Result := EuroConvert (Amount, cuEUR, DestType, 4); end; function TConvert.ToEuro(Source: string; Amount: Double): Double; var BaseType: TConvType; begin Result := 0; if DescriptionToConvType (cbEuroCurrency, Source, BaseType) then Result := EuroConvert (Amount, BaseType, cuEUR, 4); end; function TConvert.TypesList: string; var i: Integer; ATypes: TConvTypeArray; begin Result := ''; GetConvTypes(cbEuroCurrency, ATypes); for i := Low(aTypes) to High(aTypes) do Result := Result + ConvTypeToDescription (aTypes[i]) + ';'; end; initialization InvRegistry.RegisterInvokableClass (TConvert); end.
unit clContasReceber; interface uses clCliente, clEntrega, clOrdemServico, clConexao; type TContasReceber = Class(TObject) private function getBaixado: String; function getData: TDate; function getDescricao: String; function getDocumento: String; function getExecutor: String; function getManutencao: TDateTime; function getNossoNumero: String; function getNumero: Integer; function getOs: Integer; function getPago: TDate; procedure setBaixado(const Value: String); procedure setData(const Value: TDate); procedure setDescricao(const Value: String); procedure setDocumento(const Value: String); procedure setExecutor(const Value: String); procedure setManutencao(const Value: TDateTime); procedure setNossoNumero(const Value: String); procedure setNumero(const Value: Integer); procedure setOs(const Value: Integer); procedure setPago(const Value: TDate); function getCliente: Integer; function getVencimento: TDate; procedure setCliente(const Value: Integer); procedure setVencimento(const Value: TDate); function getValor: Double; procedure setValor(const Value: Double); protected _numero: Integer; _data: TDate; _descricao: String; _valor: Double; _cliente: Integer; _vencimento: TDate; _os: Integer; _nossonumero: String; _baixado: String; _pago: TDate; _documento: String; _executor: String; _manutencao: TDateTime; _clCliente: TCliente; _clEntrega: TEntrega; _clOs: TOrdemServico; _conexao: TConexao; public constructor Create; destructor Destroy; property Numero: Integer read getNumero write setNumero; property Data: TDate read getData write setData; property Descricao: String read getDescricao write setDescricao; property Valor: Double read getValor write setValor; property Cliente: Integer read getCliente write setCliente; property Vencimento: TDate read getVencimento write setVencimento; property Os: Integer read getOs write setOs; property NossoNumero: String read getNossoNumero write setNossoNumero; property Baixado: String read getBaixado write setBaixado; property Pago: TDate read getPago write setPago; property Documento: String read getDocumento write setDocumento; property Executor: String read getExecutor write setExecutor; property Manutencao: TDateTime read getManutencao write setManutencao; procedure MaxNum; function Validar(): Boolean; function getObject(id, filtro: String): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; function Insert(): Boolean; function Update(): Boolean; function Delete(filtro: String): Boolean; end; const TABLENAME = 'TBCONTASRECEBER'; implementation { TContasReceber } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB; constructor TContasReceber.Create; begin _clCliente := TCliente.Create; _clEntrega := TEntrega.Create; _clOs := TOrdemServico.Create; _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TContasReceber.Destroy; begin _clCliente.Free; _clEntrega.Free; _clOs.Free; _conexao.Free; end; function TContasReceber.getBaixado: String; begin Result := _baixado; end; function TContasReceber.getCliente: Integer; begin Result := _cliente; end; function TContasReceber.getData: TDate; begin Result := _data; end; function TContasReceber.getDescricao: String; begin Result := _descricao; end; function TContasReceber.getDocumento: String; begin Result := _documento; end; function TContasReceber.getExecutor: String; begin Result := _executor; end; function TContasReceber.getManutencao: TDateTime; begin Result := _manutencao; end; function TContasReceber.getNossoNumero: String; begin Result := _nossonumero; end; function TContasReceber.getNumero: Integer; begin Result := _numero; end; function TContasReceber.getOs: Integer; begin Result := _os; end; function TContasReceber.getPago: TDate; begin Result := _pago; end; function TContasReceber.getValor: Double; begin Result := _valor; end; function TContasReceber.getVencimento: TDate; begin Result := _vencimento; end; procedure TContasReceber.MaxNum; begin try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(NUM_LANCAMENTO) AS CODIGO FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Numero := (dm.QryGetObject.FieldByName('CODIGO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.Validar(): Boolean; begin Result := False; if Self.Data = 0 then begin MessageDlg('Informe a Data do Lançamento!', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Descricao) then begin MessageDlg('Informe a Descrição do Lançamento!', mtWarning, [mbOK], 0); Exit; end; if Self.Cliente = 0 then begin MessageDlg('Informe o Cliente!', mtWarning, [mbOK], 0); Exit; end else if Self.Valor = 0 then begin MessageDlg('Informe o Valor!', mtWarning, [mbOK], 0); Exit; end else begin if not(_clCliente.getObject(IntToStr(Self.Cliente), 'CODIGO')) then begin MessageDlg('Código de Cliente não cadastrado!', mtWarning, [mbOK], 0); Exit; end; end; if Self.Vencimento = 0 then begin MessageDlg('Informe a Data do Vencimento!', mtWarning, [mbOK], 0); Exit; end; if Self.Os <> 0 then begin if not(_clOs.getObject(IntToStr(Self.Os), 'NUMERO')) then begin MessageDlg('Número de OS não cadastrado!', mtWarning, [mbOK], 0); Exit; end; end; { if not (TUtil.Empty(Self.NossoNumero)) then begin if not (_clEntrega.getObject(Self.NossoNumero,'NOSSONUMERO')) then begin MessageDlg('Entrega não cadastrada!',mtWarning,[mbOK],0); Exit; end; end; } Result := True; end; function TContasReceber.getObject(id: string; filtro: string): Boolean; begin try Result := False; if TUtil.Empty(id) then begin Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'NUMERO' then begin SQL.Add('WHERE NUM_LANCAMENTO = :NUMERO'); ParamByName('NUMERO').AsInteger := StrToInt(id); end else if filtro = 'DATA' then begin SQL.Add('WHERE DAT_LANCAMENTO = :DATA'); ParamByName('DATA').AsDate := StrToDate(id); end else if filtro = 'DESCRICAO' then begin if Pos('%', Self.Descricao) = 0 then begin ParamByName('DESCRICAO').AsString := '%' + id + '%'; end else begin ParamByName('DESCRICAO').AsString := id; end; SQL.Add('WHERE DES_LANCAMENTO LIKE :DESCRICAO'); end else if filtro = 'CLIENTE' then begin SQL.Add('WHERE COD_CLIENTE = :CLIENTE'); ParamByName('CLIENTE').AsInteger := StrToInt(id); end else if filtro = 'VENCIMENTO' then begin SQL.Add('WHERE DAT_VENCIMENTO = :VENCIMENTO'); ParamByName('VENCIMENTO').AsDate := StrToDate(id); end else if filtro = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := StrToInt(id); end else if filtro = 'NOSSONUMERO' then begin SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); ParamByName('NOSSONUMERO').AsString := id; end else if filtro = 'DOCUMENTO' then begin if Pos('%', Self.Documento) = 0 then begin ParamByName('DOCUMENTO').AsString := '%' + id + '%'; end else begin ParamByName('DOCUMENTO').AsString := id; end; SQL.Add('WHERE ID_DOCUMENTO LIKE :DOCUMENTO'); end; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; Self.Numero := FieldByName('NUM_LANCAMENTO').AsInteger; Self.Data := FieldByName('DAT_LANCAMENTO').AsDateTime; Self.Descricao := FieldByName('DES_LANCAMENTO').AsString; Self.Valor := FieldByName('VAL_LANCAMENTO').AsFloat; Self.Cliente := FieldByName('COD_CLIENTE').AsInteger; Self.Vencimento := FieldByName('DAT_VENCIMENTO').AsDateTime; Self.Os := FieldByName('NUM_OS').AsInteger; Self.NossoNumero := FieldByName('NUM_NOSSONUMERO').AsString; Self.Baixado := FieldByName('DOM_BAIXADO').AsString; Self.Pago := FieldByName('DAT_PAGO').AsDateTime; Self.Documento := FieldByName('ID_DOCUMENTO').AsString; Self.Executor := FieldByName('NOM_EXECUTOR').AsString; Self.Manutencao := FieldByName('DAT_MANUTENCAO').AsDateTime; if RecordCount = 1 then begin Close; SQL.Clear; end; end; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if IsEmpty then begin Close; SQL.Clear; Exit; end; First; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.getField(campo: string; coluna: string): String; begin try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT ' + campo + ' FROM ' + TABLENAME); if coluna = 'NUMERO' then begin SQL.Add('WHERE NUM_LANCAMENTO = :NUMERO'); ParamByName('NUMERO').AsInteger := Self.Numero; end else if coluna = 'DATA' then begin SQL.Add('WHERE DAT_LANCAMENTO = :DATA'); ParamByName('DATA').AsDate := Self.Data; end else if coluna = 'CLIENTE' then begin SQL.Add('WHERE COD_CLIENTE = :CLIENTE'); ParamByName('CLIENTE').AsInteger := Self.Cliente; end else if coluna = 'VENCIMENTO' then begin SQL.Add('WHERE DAT_VENCIMENTO = :VENCIMENTO'); ParamByName('VENCIMENTO').AsDate := Self.Vencimento; end else if coluna = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := Self.Os; end else if coluna = 'NOSSONUMERO' then begin SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; end else if coluna = 'DOCUMENTO' then begin ParamByName('DOCUMENTO').AsString := Self.Documento; SQL.Add('WHERE ID_DOCUMENTO = :DOCUMENTO'); end; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin Result := FieldByName(campo).AsString; end; Close; SQL.Clear; end; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.Insert(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'NUM_LANCAMENTO, ' + 'DAT_LANCAMENTO, ' + 'DES_LANCAMENTO, ' + 'VAL_LANCAMENTO, ' + 'COD_CLIENTE, ' + 'DAT_VENCIMENTO, ' + 'NUM_OS, ' + 'NUM_NOSSONUMERO, ' + 'DOM_BAIXADO, ' + 'DAT_PAGO, ' + 'ID_DOCUMENTO, ' + 'NOM_EXECUTOR, ' + 'DAT_MANUTENCAO) ' + 'VALUES (' + ':NUMERO, ' + ':DATA, ' + ':DESCRICAO, ' + ':VALOR, ' + ':CLIENTE, ' + ':VENCIMENTO, ' + ':OS, ' + ':NOSSONUMERO, ' + ':BAIXADO, ' + ':PAGO, ' + ':DOCUMENTO, ' + ':EXECUTOR, ' + ':MANUTENCAO)'; MaxNum; ParamByName('NUMERO').AsInteger := Self.Numero; ParamByName('DATA').AsDate := Self.Data; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('CLIENTE').AsInteger := Self.Cliente; ParamByName('VENCIMENTO').AsDate := Self.Vencimento; ParamByName('OS').AsInteger := Self.Os; ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; ParamByName('BAIXADO').AsString := Self.Baixado; ParamByName('PAGO').AsDate := Self.Pago; ParamByName('DOCUMENTO').AsString := Self.Documento; ParamByName('EXECUTOR').AsString := Self.Executor; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.Update(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_LANCAMENTO = :DATA, ' + 'DES_LANCAMENTO = :DESCRICAO, ' + 'VAL_LANCAMENTO = :VALOR, ' + 'COD_CLIENTE = :CLIENTE, ' + 'DAT_VENCIMENTO = :VENCIMENTO, ' + 'NUM_OS = :OS, ' + 'NUM_NOSSONUMERO = :NOSSONUMERO, ' + 'DOM_BAIXADO = :BAIXADO, ' + 'DAT_PAGO = :PAGO, ' + 'ID_DOCUMENTO = :DOCUMENTO, ' + 'NOM_EXECUTOR = :EXECUTOR, ' + 'DAT_MANUTENCAO = :MANUTENCAO ' + 'WHERE NUM_LANCAMENTO = :NUMERO'; ParamByName('NUMERO').AsInteger := Self.Numero; ParamByName('DATA').AsDate := Self.Data; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('CLIENTE').AsInteger := Self.Cliente; ParamByName('VENCIMENTO').AsDate := Self.Vencimento; ParamByName('OS').AsInteger := Self.Os; ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; ParamByName('BAIXADO').AsString := Self.Baixado; ParamByName('PAGO').AsDate := Self.Pago; ParamByName('DOCUMENTO').AsString := Self.Documento; ParamByName('EXECUTOR').AsString := Self.Executor; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TContasReceber.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'NUMERO' then begin SQL.Add('WHERE NUM_LANCAMENTO = :NUMERO'); ParamByName('NUMERO').AsInteger := Self.Numero; end else if filtro = 'DATA' then begin SQL.Add('WHERE DAT_LANCAMENTO = :DATA'); ParamByName('DATA').AsDate := Self.Data; end else if filtro = 'CLIENTE' then begin SQL.Add('WHERE COD_CLIENTE = :CLIENTE'); ParamByName('CLIENTE').AsInteger := Self.Cliente; end else if filtro = 'VENCIMENTO' then begin SQL.Add('WHERE DAT_VENCIMENTO = :VENCIMENTO'); ParamByName('VENCIMENTO').AsDate := Self.Vencimento; end else if filtro = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := Self.Os; end else if filtro = 'NOSSONUMERO' then begin SQL.Add('WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; end else if filtro = 'DOCUMENTO' then begin SQL.Add('WHERE ID_DOCUMENTO = :DOCUMENTO'); ParamByName('DOCUMENTO').AsString := Self.Documento; end; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; procedure TContasReceber.setBaixado(const Value: String); begin _baixado := Value; end; procedure TContasReceber.setCliente(const Value: Integer); begin _cliente := Value; end; procedure TContasReceber.setData(const Value: TDate); begin _data := Value; end; procedure TContasReceber.setDescricao(const Value: String); begin _descricao := Value; end; procedure TContasReceber.setDocumento(const Value: String); begin _documento := Value; end; procedure TContasReceber.setExecutor(const Value: String); begin _executor := Value; end; procedure TContasReceber.setManutencao(const Value: TDateTime); begin _manutencao := Value; end; procedure TContasReceber.setNossoNumero(const Value: String); begin _nossonumero := Value; end; procedure TContasReceber.setNumero(const Value: Integer); begin _numero := Value; end; procedure TContasReceber.setOs(const Value: Integer); begin _os := Value; end; procedure TContasReceber.setPago(const Value: TDate); begin _pago := Value; end; procedure TContasReceber.setValor(const Value: Double); begin _valor := Value; end; procedure TContasReceber.setVencimento(const Value: TDate); begin _vencimento := Value; end; end.
unit ThreadJobs; interface uses Classes,SyncObjs,Generics.Collections; type TThreadJob=class Job : TThreadProcedure; constructor Create(J : TThreadProcedure); end; TJobThread = class; TJobThreadList = TObjectList<TJobThread>; TThreadJobQueue = class(TObjectQueue<TThreadJob>) WakeUp,AllPause : TEvent; Lock : TMutex; ThreadList : TJobThreadList; RunningThread : integer; clearing : boolean; needpause : boolean; pauseLock : TMutex; procedure Run(J : TThreadProcedure); constructor Create(ThreadCount : integer); destructor Destroy; override; procedure ClearJobs; procedure PauseAll; procedure ResumeAll; end; TJobThread = class(TThread) JQ : TThreadJobQueue; procedure Execute; override; constructor Create(Q : TThreadJobQueue); end; implementation uses SysUtils; { TThreadJobQueue } procedure TThreadJobQueue.ClearJobs; begin clearing := true; Lock.Acquire; Clear; Lock.Release; AllPause.WaitFor; clearing := false; end; constructor TThreadJobQueue.Create(ThreadCount : integer); var i : integer; begin inherited Create; clearing := false; AllPause := TEvent.Create; WakeUp := TEvent.Create; Lock := TMutex.Create; ThreadList := TJobThreadList.Create; for i := 1 to ThreadCount do begin ThreadList.Add(TJobThread.Create(self)); end; end; destructor TThreadJobQueue.Destroy; var J : TJobThread; begin for J in ThreadList do begin J.Terminate; end; Lock.Acquire; WakeUp.SetEvent; Lock.Release; for J in ThreadList do begin J.WaitFor; end; ThreadList.Free; WakeUp.Free; Lock.Free; AllPause.Free; inherited; end; procedure TThreadJobQueue.PauseAll; begin PauseLock.Acquire; NeedPause := true; AllPause.WaitFor; PauseLock.Release; end; procedure TThreadJobQueue.ResumeAll; begin PauseLock.Acquire; NeedPause := false; PauseLock.Release; WakeUp.SetEvent; end; procedure TThreadJobQueue.Run(J: TThreadProcedure); begin if clearing then exit; Lock.Acquire; if not clearing then begin Enqueue(TThreadJob.Create(J)); if Count=1 then WakeUp.SetEvent; end; Lock.Release; end; { TJobThread } constructor TJobThread.Create(Q: TThreadJobQueue); begin JQ := Q; inherited Create; end; procedure TJobThread.Execute; var J : TThreadJob; begin if TInterlocked.Increment(JQ.RunningThread)=1 then JQ.AllPause.ResetEvent; try while not Terminated do begin J :=nil; if not JQ.needpause then begin JQ.Lock.Acquire; try if not(Terminated or JQ.needpause) then if JQ.Count=0 then JQ.WakeUp.ResetEvent else J := JQ.Extract; finally JQ.Lock.Release; end; end; if assigned(J) then begin try J.Job(); except on E: Exception do end; J.Free; end else if not Terminated then begin if TInterLocked.Decrement(JQ.RunningThread)=0 then JQ.AllPause.SetEvent; JQ.WakeUp.WaitFor; if TInterlocked.Increment(JQ.RunningThread)=1 then JQ.AllPause.ResetEvent; end; end; finally if TInterLocked.Decrement(JQ.RunningThread)=0 then JQ.AllPause.SetEvent; end; end; { TThreadJob } constructor TThreadJob.Create(J: TThreadProcedure); begin Job := J; end; end.
unit aeSceneGraph; interface uses types, windows, aeSceneNode, System.Generics.Collections, aeGeometry, aeMaths; type TaeSceneGraph = class(TaeSceneNode) constructor Create; function GetTriangleCount: cardinal; function Intersect(ray: TaeRay3): boolean; function GetChildByName(n: String): TaeSceneNode; end; implementation { TaeSceneGraph } constructor TaeSceneGraph.Create; begin inherited; end; function TaeSceneGraph.GetChildByName(n: String): TaeSceneNode; var l: TList<TaeSceneNode>; i: Integer; begin l := self.ListChildren; for i := 0 to l.Count - 1 do if (l[i].GetNodeName = n) then begin result := l[i]; exit; end; l.Free; end; function TaeSceneGraph.GetTriangleCount: cardinal; var l: TList<TaeSceneNode>; i: Integer; begin result := 0; l := self.ListChildren; for i := 0 to l.Count - 1 do begin case l[i].getType of AE_SCENENODE_TYPE_GEOMETRY: result := result + TaeGeometry(l[i]).GetTriangleCount; end; end; l.Free; end; function TaeSceneGraph.Intersect(ray: TaeRay3): boolean; var l: TList<TaeSceneNode>; geo: TaeGeometry; i: Integer; begin l := self.ListChildren; for i := 0 to l.Count - 1 do begin case l[i].getType() of AE_SCENENODE_TYPE_GEOMETRY: begin geo := TaeGeometry(l[i]); result := geo.Intersect(ray); if (result) then exit; end; end; end; l.Free; end; end.
unit untConnection; interface uses System.IniFiles, FireDAC.Comp.Client; type TConnection = class private FIniFile: TIniFile; procedure escreverIni; public constructor create(AExeName: String); destructor destroy; procedure conectar(var AFDConnection: TFDConnection); end; implementation uses System.SysUtils, Vcl.Forms; const Secao: String = 'Dados'; { TConnection } procedure TConnection.conectar(var AFDConnection: TFDConnection); begin try with AFDConnection.Params do begin Values['Database'] := FIniFile.ReadString(Secao, 'Database', ''); Values['User_Name'] := FIniFile.ReadString(Secao, 'User_Name', ''); Values['Password'] := FIniFile.ReadString(Secao, 'Password', ''); Values['DriverID'] := FIniFile.ReadString(Secao, 'DriverID', ''); Values['Server'] := FIniFile.ReadString(Secao, 'Server', ''); Values['Port'] := FIniFile.ReadString(Secao, 'Port', ''); end; AFDConnection.Connected := true; except on e: Exception do raise Exception.create(e.Message); end; end; constructor TConnection.create(AExeName: String); var diretorioArquivo: String; begin diretorioArquivo := ExtractFilePath(AExeName); FIniFile := TIniFile.create(diretorioArquivo + 'dbConn.ini'); if not FileExists(FIniFile.FileName) then escreverIni; end; destructor TConnection.destroy; begin FIniFile.Free; end; procedure TConnection.escreverIni; begin try FIniFile.WriteString(Secao, 'Database', ExtractFilePath(FIniFile.FileName) + 'Database\GAT.FDB'); FIniFile.WriteString(Secao, 'User_Name', 'sysdba'); FIniFile.WriteString(Secao, 'Password', 'masterkey'); FIniFile.WriteString(Secao, 'DriverID', 'FB'); FIniFile.WriteString(Secao, 'Server', 'localhost'); FIniFile.WriteString(Secao, 'Port', '3050'); except on e: Exception do raise Exception.create(e.Message); end; end; end.
{ rxfilterby unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxfilterby; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, rxdbgrid, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, db; type { TrxFilterByForm } TrxFilterByForm = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; ComboBox1: TComboBox; ComboBox10: TComboBox; ComboBox11: TComboBox; ComboBox12: TComboBox; ComboBox13: TComboBox; ComboBox14: TComboBox; ComboBox15: TComboBox; ComboBox16: TComboBox; ComboBox17: TComboBox; ComboBox18: TComboBox; ComboBox19: TComboBox; ComboBox2: TComboBox; ComboBox20: TComboBox; ComboBox21: TComboBox; ComboBox22: TComboBox; ComboBox23: TComboBox; ComboBox24: TComboBox; ComboBox25: TComboBox; ComboBox26: TComboBox; ComboBox27: TComboBox; ComboBox3: TComboBox; ComboBox4: TComboBox; ComboBox5: TComboBox; ComboBox6: TComboBox; ComboBox7: TComboBox; ComboBox8: TComboBox; ComboBox9: TComboBox; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; Edit5: TEdit; Edit6: TEdit; Edit7: TEdit; Edit8: TEdit; Edit9: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure ComboBoxChange(Sender: TObject); procedure EditChange(Sender: TObject); procedure FormCreate(Sender: TObject); private Combo_1 : Array[1..9] of TComboBox; Combo_2 : Array[1..9] of TComboBox; Edit_1 : Array[1..9] of TEdit; Combo_3 : Array[1..9] of TComboBox; FGrid : TRxDBGrid; procedure ClearALL(AGrid : TRxDBGrid); function FindCombo(CB:TComboBox):Integer; function FindEdit(ED:TEdit):Integer; public function Execute(AGrid : TRxDBGrid; var FilterStr : String; var LastFilter : TstringList):Boolean; end; var rxFilterByForm: TrxFilterByForm; implementation uses rxdconst, rxstrutils, DBGrids; {$R *.lfm} { TrxFilterByForm } procedure TrxFilterByForm.Button2Click(Sender: TObject); begin ModalResult := mrCancel; end; procedure TrxFilterByForm.Button3Click(Sender: TObject); begin ClearALL(FGrid); end; procedure TrxFilterByForm.ComboBoxChange(Sender: TObject); Var CBN : Integer; CB : TComboBox; begin CB := (Sender AS TComboBox); CBN := FindCombo(CB); if CBN=0 Then Exit; if (CB.Text=' IS NULL ') Or (CB.Text=' IS NOT NULL ') Then Begin Edit_1[CBN].Text := ''; Edit_1[CBN].Enabled := False; Edit_1[CBN].Color := clInactiveCaption; End Else Begin Edit_1[CBN].Enabled := True; Edit_1[CBN].Color := clWindow; End; end; procedure TrxFilterByForm.EditChange(Sender: TObject); Var EDN : Integer; ED : TEdit; begin ED := (Sender AS TEdit); EDN := FindEdit(ED); if EDN=0 Then Exit; if ED.Text='' Then Combo_1[EDN].ItemIndex:=-1; end; procedure TrxFilterByForm.FormCreate(Sender: TObject); begin Label1.Caption:=sRxFilterFormSelectExp; Label2.Caption:=sRxFilterFormOnField; Label3.Caption:=sRxFilterFormOperaion; Label4.Caption:=sRxFilterFormCondition; Label5.Caption:=sRxFilterFormOperand; Label6.Caption:=sRxFilterFormEnd; Button3.Caption:=sRxFilterFormClear; Button2.Caption:=sRxFilterFormCancel; Button1.Caption:=sRxFilterFormApply; end; procedure TrxFilterByForm.Button1Click(Sender: TObject); begin ModalResult := mrOK; end; procedure TrxFilterByForm.ClearALL(AGrid: TRxDBGrid); var i : Integer; begin //***************************************************************************** Combo_1[1].Items.Clear; Combo_1[1].Items.Add(''); for i := 0 To AGrid.Columns.Count-1 do begin if (AGrid.Columns[i].Field.FieldKind=fkData) and (AGrid.Columns[i].Visible) then Combo_1[1].Items.Objects[Combo_1[1].Items.Add(AGrid.Columns[i].Title.Caption)]:=AGrid.Columns[i].Field; end; Combo_1[1].ItemIndex := 0; for i := 2 To 9 do Begin Combo_1[i].Items.Assign(Combo_1[1].Items); Combo_1[i].ItemIndex := 0; End; Combo_2[1].Items.Clear; Combo_2[1].Items.Add(' = '); Combo_2[1].Items.Add(' > '); Combo_2[1].Items.Add(' < '); Combo_2[1].Items.Add(' >= '); Combo_2[1].Items.Add(' <= '); Combo_2[1].Items.Add(' <> '); Combo_2[1].Items.Add(' LIKE '); Combo_2[1].Items.Add(' IS NULL '); Combo_2[1].Items.Add(' IS NOT NULL '); Combo_2[1].ItemIndex := 0; for i := 2 To 9 do begin Combo_2[i].Items.Assign(Combo_2[1].Items); Combo_2[i].ItemIndex := 0; end; for i := 1 To 9 do begin Combo_3[i].ItemIndex := 0; end; for i := 1 To 9 do Edit_1[i].Text := ''; //***************************************************************************** end; function TrxFilterByForm.Execute(AGrid: TRxDBGrid; var FilterStr: String; var LastFilter: TstringList): Boolean; Var X : Integer; P : Integer; S, S1 : String; SD : String; C : TColumn; Begin Result := False; //***************************************************************************** Combo_1[1]:= ComboBox1; Combo_1[2]:= ComboBox4; Combo_1[3]:= ComboBox7; Combo_1[4]:= ComboBox10; Combo_1[5]:= ComboBox13; Combo_1[6]:= ComboBox16; Combo_1[7]:= ComboBox19; Combo_1[8]:= ComboBox22; Combo_1[9]:= ComboBox25; Combo_2[1]:= ComboBox2; Combo_2[2]:= ComboBox5; Combo_2[3]:= ComboBox8; Combo_2[4]:= ComboBox11; Combo_2[5]:= ComboBox14; Combo_2[6]:= ComboBox17; Combo_2[7]:= ComboBox20; Combo_2[8]:= ComboBox23; Combo_2[9]:= ComboBox26; Combo_3[1]:= ComboBox3; Combo_3[2]:= ComboBox6; Combo_3[3]:= ComboBox9; Combo_3[4]:= ComboBox12; Combo_3[5]:= ComboBox15; Combo_3[6]:= ComboBox18; Combo_3[7]:= ComboBox21; Combo_3[8]:= ComboBox24; Combo_3[9]:= ComboBox27; Combo_3[9].Visible := False; Edit_1[1] := Edit1; Edit_1[2] := Edit2; Edit_1[3] := Edit3; Edit_1[4] := Edit4; Edit_1[5] := Edit5; Edit_1[6] := Edit6; Edit_1[7] := Edit7; Edit_1[8] := Edit8; Edit_1[9] := Edit9; //***************************************************************************** FGrid := AGrid; ClearALL(FGrid); if LastFilter.Count > 0 Then begin for X := 0 To LastFilter.Count-1 do begin S := LastFilter.Strings[X]; P := Pos('|||',S); if P > 0 Then begin S1:=System.Copy(S,1,P-1); C:=FGrid.ColumnByFieldName(S1); Combo_1[X+1].ItemIndex := Combo_1[X+1].Items.IndexOf(C.Title.Caption); System.Delete(S,1,P+2); end; P := Pos('|||',S); if P > 0 Then begin SD:=System.Copy(S,1,P-1); Combo_2[X+1].ItemIndex := Combo_2[X+1].Items.IndexOf(System.Copy(S,1,P-1)); System.Delete(S,1,P+2); if (SD=' IS NULL ') or (SD=' IS NOT NULL ') Then Begin Edit_1[X+1].Text:= ''; Edit_1[X+1].Enabled := False; Edit_1[X+1].Color := clInactiveCaption; End; end; P := Pos('|||',S); if P > 0 then begin Edit_1[X+1].Text := System.Copy(S,1,P-1); System.Delete(S,1,P+2); end; Combo_3[X+1].ItemIndex := Combo_3[X+1].Items.IndexOf(S); if Combo_3[X+1].ItemIndex = -1 Then Combo_3[X+1].ItemIndex := 0; end; end; if ShowModal = mrOK Then begin Result := True; FilterStr := ''; LastFilter.Clear; for X := 1 to 9 Do begin if (Combo_1[X].Text <> '') and (Combo_2[X].Text <> '') then begin if (Edit_1[X].Enabled=False) or (Edit_1[X].Text <> '') Then begin if X>1 Then FilterStr := FilterStr+Combo_3[X-1].Text+' '; C:=FGrid.ColumnByCaption(Combo_1[X].Text); case C.Field.DataType of ftDateTime , ftDate : FilterStr := FilterStr+'('+C.FieldName+Combo_2[X].Text+Char(39)+Copy(Edit_1[X].Text,7,4)+Copy(Edit_1[X].Text,3,4)+Copy(Edit_1[X].Text,1,2)+Copy(Edit_1[X].Text,11,9)+Char(39)+') '; ftUnknown : FilterStr := FilterStr+'('+C.FieldName+Combo_2[X].Text+Edit_1[X].Text+') '; ftTime, ftString, ftMemo : FilterStr := FilterStr+'('+C.FieldName+Combo_2[X].Text+QuotedString(Edit_1[X].Text, '''')+') '; else FilterStr := FilterStr+'('+C.FieldName+Combo_2[X].Text+Edit_1[X].Text+') '; end; LastFilter.Add(C.FieldName+'|||'+Combo_2[X].Text+'|||'+Edit_1[X].Text+'|||'+Combo_3[X].Text); end; end; end; end; end; Function TrxFilterByForm.FindCombo(CB:TComboBox):Integer; var X : Integer; begin Result :=0; for X := 1 to 9 do begin if Combo_2[X]=CB Then begin Result := X; Exit; end; end; end; function TrxFilterByForm.FindEdit(ED:TEdit):Integer; var X : Integer; begin Result :=0; for X := 1 to 9 do begin if Edit_1[X]=ED then begin Result := X; Exit; end; end; end; end.
unit a2bUserProfile; { $Id: a2bUserProfile.pas,v 1.41 2016/08/11 10:41:53 lukyanets Exp $} // $Log: a2bUserProfile.pas,v $ // Revision 1.41 2016/08/11 10:41:53 lukyanets // Полчищаем dt_user // // Revision 1.40 2016/07/12 13:26:26 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.39 2016/07/11 12:59:53 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.38 2016/06/21 05:08:37 lukyanets // Недокоммител // // Revision 1.37 2016/06/20 15:48:29 fireton // - не собиралось // // Revision 1.36 2016/06/17 09:03:05 lukyanets // Отладка // // Revision 1.35 2016/06/17 06:20:10 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.34 2016/06/16 05:38:36 lukyanets // Пересаживаем UserManager на новые рельсы // // Revision 1.33 2016/05/18 06:02:39 lukyanets // Выключаем удаленную отладку // // Revision 1.32 2016/04/25 11:23:20 lukyanets // Пересаживаем UserManager на новые рельсы // Committed on the Free edition of March Hare Software CVSNT Server. // Upgrade to CVS Suite for more features and support: // http://march-hare.com/cvsnt/ // // Revision 1.31 2016/04/20 11:57:00 lukyanets // Пересаживаем UserManager на новые рельсы // Committed on the Free edition of March Hare Software CVSNT Server. // Upgrade to CVS Suite for more features and support: // http://march-hare.com/cvsnt/ // // Revision 1.30 2015/04/07 07:35:52 lukyanets // Изолируем HT // // Revision 1.29 2015/01/22 14:31:11 lukyanets // Переносим отсылку задачи в более правильное место // // Revision 1.28 2014/10/08 13:07:32 lukyanets // Переносим процедуры в правильное место // // Revision 1.27 2014/06/23 07:55:19 fireton // - не собиралось // // Revision 1.26 2014/03/04 08:58:38 fireton // - не собиралось // // Revision 1.25 2011/02/07 14:26:09 fireton // - даём сохранить пользователя, если логин не поменялся (хотя редактировался) // // Revision 1.24 2010/10/19 08:52:59 fireton // - не теряем стек ошибки // // Revision 1.23 2010/02/24 11:10:47 narry // - удаление зависимости проектов от парня // // Revision 1.22 2009/04/21 14:19:33 fireton // - пересборка // // Revision 1.21 2009/04/02 13:11:30 fireton // - [$137470683]. Правка огрехов в отрисовке дерева пользователей. // // Revision 1.20 2008/10/03 11:57:53 fireton // - принудительно инициализируем Большого Брата // // Revision 1.19 2008/09/29 08:08:37 narry // - рефакторинг механизма подключения к базе // // Revision 1.18 2008/02/19 15:05:30 lulin // - переводим сортировку списков на новые, менее виртуальные, рельсы. // // Revision 1.17 2007/05/14 12:26:04 fireton // - проверка подтверждения пароля пользователя уехала с БО на формы // // Revision 1.16 2007/04/19 12:01:57 fireton // - более корректное сообщение об ошибках при добавлении/редактировании пользователя // // Revision 1.15 2007/03/26 13:16:30 fireton // - мелкий багфикс там и сям // // Revision 1.14 2007/03/15 14:11:08 fireton // - тип групп пользователей теперь не TDictID, а TUserGrID // // Revision 1.13 2007/03/13 09:09:07 fireton // - не-админ теперь не сможет пользоваться программой // - мелкие правки // - чистка кода // // Revision 1.12 2007/02/08 14:22:09 fireton // - bug fix // - доработан экспорт и импорт // // Revision 1.11 2006/11/30 15:37:31 fireton // - багфикс и доработка // // Revision 1.10 2006/11/27 16:24:39 fireton // - bugfix // // Revision 1.9 2005/09/14 10:51:31 fireton // - bug fix: неправильное присвоение (и как следствие - AV) // // Revision 1.8 2005/08/20 11:01:53 fireton // - промежуточный коммит (реализация визуальной части и подгонка под сборки) // // Revision 1.7 2005/08/17 14:10:58 fireton // - промежуточный коммит (подгонка под систему сборок) // // Revision 1.6 2005/08/15 07:58:28 fireton // - введение служебного интерфейса: Ia2Service // // Revision 1.5 2005/08/09 13:03:24 fireton // - реализация бизнес-объектов // // Revision 1.4 2005/08/05 14:58:24 fireton // - реализация бизнес-объектов // // Revision 1.3 2005/08/04 16:30:54 fireton // - реализация бизнес-объектов // // Revision 1.2 2005/08/02 15:14:20 fireton // - реализация бизнес-объектов // // Revision 1.1 2005/07/29 16:53:07 fireton // - первый коммит // interface uses l3Base, daTypes, a2Interfaces, a2Base, a2bBase, vcmInterfaces; type Ta2UserProfile = class(Ta2Profile, Ia2UserProfile) private f_GroupsList: Ta2MarkedList; f_PasswordChanged: Boolean; f_UEM: TdaUserEditMask; procedure ReloadGroupStates; protected f_Login : string; f_Email : string; f_IsActive : Boolean; f_IsAdmin : Boolean; f_Password : string; f_OldLogin : string; { - Ia2Profile overrided methods - } procedure pm_SetName(const Value: string); override; { - Ia2UserProfile property methods -} function pm_GetEmail: string; function pm_GetIsActive: Boolean; function pm_GetIsAdmin: Boolean; function pm_GetIsReadonly: Boolean; function pm_GetLogin: string; procedure pm_SetEmail(const Value: string); procedure pm_SetIsActive(const Value: Boolean); procedure pm_SetIsAdmin(const Value: Boolean); procedure pm_SetLogin(const Value: string); { - Ia2UserProfile methods - } procedure SetPassword(aPassword: string); function GetGroupStates: Ia2MarkedList; { - overrided methods -} procedure DoRevert; override; procedure DoSave; override; public { - Ia2UserProfile properties - } property Login: string read pm_GetLogin write pm_SetLogin; property Email: string read pm_GetEmail write pm_SetEmail; property IsActive: Boolean read pm_GetIsActive write pm_SetIsActive; property IsAdmin: Boolean read pm_GetIsAdmin write pm_SetIsAdmin; property IsReadonly: Boolean read pm_GetIsReadonly; { - methods - } constructor Create; procedure Cleanup; override; procedure IncludeInGroup(aGroup: TdaUserGroupID); end; implementation uses SysUtils, l3DatLst, daInterfaces, daDataProvider, daSchemeConsts, csQueryTypes, ddClientBaseEngine, csUserRequestManager, CsClient, csServerTaskTypes; constructor Ta2UserProfile.Create; begin inherited; f_GroupsList := nil; GetGroupStates; ReloadGroupStates; end; procedure Ta2UserProfile.Cleanup; begin l3Free(f_GroupsList); inherited; end; procedure Ta2UserProfile.DoRevert; var l_Flags: Byte; l_Name, l_Login: String; begin if f_ID <> a2cNewItemID then begin GlobalDataProvider.UserManager.GetUserInfo(f_ID, l_Name, l_Login, l_Flags); f_Name := l_Name; f_Login := l_Login; f_OldLogin := f_Login; f_IsActive := ((l_Flags and $01) > 0); f_IsAdmin := ((l_Flags and $02) > 0); end else begin f_Name := ''; f_Login := ''; f_OldLogin := ''; f_IsActive := True; f_IsAdmin := False; end; f_PasswordChanged := False; f_Modified := False; with f_UEM do begin ActivFlag := False; LoginName := False; Name := False; end; if Assigned(f_GroupsList) then ReloadGroupStates; end; procedure Ta2UserProfile.DoSave; var l_Flags: Byte; l_Task: TUserEditQuery; l_TmpStr: string; begin if not f_Modified then Exit; CheckBBUserID; if f_Login = '' then raise Ea2UserDataSaveError.Create('Не задан логин пользователя.'); l_Flags := 0; if f_IsActive then l_Flags := $01; if f_IsAdmin then l_Flags := l_Flags or $02; if f_Name = '' then f_Name := f_Login; if f_ID = a2cNewItemID then begin try f_ID:= GlobalDataProvider.UserManager.AddUser(f_Name, f_Login, f_Password, l_Flags) except on E: Exception do begin l_TmpStr := Format('Не удалось добавить пользователя: %s', [E.Message]); l3System.Stack2Log(l_TmpStr); raise Ea2UserDataSaveError.Create(l_TmpStr); end; end; end else try GlobalDataProvider.UserManager.EditUser(f_ID, f_Name, f_Login, l_Flags, f_UEM); except on E: Exception do begin l_TmpStr := Format('Не удалось изменить данные пользователя: %s', [E.Message]); l3System.Stack2Log(l_TmpStr); raise Ea2UserDataSaveError.Create(l_TmpStr); end; end; if f_PasswordChanged then begin GlobalDataProvider.UserManager.AdminChangePassWord(f_ID, f_Password); f_PasswordChanged := False; end; if Assigned(f_GroupsList) and f_GroupsList.Modified then begin GlobalDataProvider.UserManager.SetUserGroupsList(f_ID, f_GroupsList); f_GroupsList.Modified := False; end; if g_BaseEngine.CSClient.IsStarted then begin l_Task := TUserEditQuery.Create(g_BaseEngine.CSClient.ClientId); try l_Task.IsGroup := False; l_Task.ID := ID; UserRequestManager.SendTask(l_Task); finally l3Free(l_Task); end; end; //Revert; f_Modified := False; end; function Ta2UserProfile.GetGroupStates: Ia2MarkedList; begin if not Assigned(f_GroupsList) then f_GroupsList := Ta2MarkedList.Create(Self as Ia2Persistent, cGroupIDSize); if f_ID <> a2cNewItemID then ReloadGroupStates; Result := f_GroupsList; end; procedure Ta2UserProfile.IncludeInGroup(aGroup: TdaUserGroupID); var l_Idx: Integer; begin GetGroupStates; l_Idx := f_GroupsList.IndexOfData(aGroup, SizeOf(aGroup)); if l_Idx <> -1 then begin f_GroupsList.Select[l_Idx] := True; f_GroupsList.DataInt[l_Idx] := 1; f_GroupsList.Modified := True; end; end; function Ta2UserProfile.pm_GetEmail: string; begin Result := f_Email; end; function Ta2UserProfile.pm_GetIsActive: Boolean; begin Result := f_IsActive; end; function Ta2UserProfile.pm_GetIsAdmin: Boolean; begin Result := f_IsAdmin; end; function Ta2UserProfile.pm_GetIsReadonly: Boolean; begin Result := (f_ID = usSupervisor){ or (f_ID >= usAdminReserved)}; end; function Ta2UserProfile.pm_GetLogin: string; begin Result := f_Login; end; procedure Ta2UserProfile.pm_SetEmail(const Value: string); begin if Value <> f_Email then begin f_Email := Value; f_Modified := True; end; end; procedure Ta2UserProfile.pm_SetIsActive(const Value: Boolean); begin if f_IsActive <> Value then begin f_IsActive := Value; f_Modified := True; f_UEM.ActivFlag := True; end; end; procedure Ta2UserProfile.pm_SetIsAdmin(const Value: Boolean); begin if f_IsAdmin <> Value then begin f_IsAdmin := Value; f_Modified := True; f_UEM.ActivFlag := True; end; end; procedure Ta2UserProfile.pm_SetLogin(const Value: string); begin if Value <> f_Login then begin f_Login := Value; f_Modified := True; f_UEM.LoginName := not AnsiSameText(f_Login, f_OldLogin); end; end; procedure Ta2UserProfile.pm_SetName(const Value: string); begin if f_Name <> Value then f_UEM.Name := True; inherited; end; procedure Ta2UserProfile.ReloadGroupStates; var I: Integer; begin f_GroupsList.HostDataList := nil; if f_ID <> a2cNewItemID then GlobalDataProvider.UserManager.GetUserGroupsList(f_ID, f_GroupsList) else begin // если новый пользователь просто копируем список групп... if f_GroupsList.HostDataList <> GlobalDataProvider.UserManager.AllGroups then begin f_GroupsList.Clear; f_GroupsList.HostDataList := GlobalDataProvider.UserManager.AllGroups; end; for I := 0 to GlobalDataProvider.UserManager.AllGroups.Count-1 do f_GroupsList.Select[I] := False; end; f_GroupsList.Modified := False; end; procedure Ta2UserProfile.SetPassword(aPassword: string); begin f_Password := aPassword; f_PasswordChanged := True; f_Modified := True; end; end.
unit Item; interface uses Engine, DGLE, DGLE_Types, Entity; const ITEM_AMP = 3; ItemFName: array [0..ITEMS_COUNT - 1] of AnsiString = ( 'Shield.png', 'WShield.png', 'TShield.png', 'Dirk.png', 'Iceball.png' ); type TItem = class(TEntity) private Angle: Integer; Dir: Boolean; Top: Real; Left: Integer; FActive: Boolean; procedure SetActive(const Value: Boolean); public constructor Create(X, Y, ID: Integer); destructor Destroy; override; property Active: Boolean read FActive write SetActive; end; type TIBase = class(TObject) private public constructor Create; destructor Destroy; override; function Count: Integer; end; type TAItem = array of TItem; type TItems = class(TObject) private FItem: TAItem; FBase: TIBase; procedure SetItem(const Value: TAItem); procedure SetBase(const Value: TIBase); public constructor Create; destructor Destroy; override; property Base: TIBase read FBase write SetBase; property Item: TAItem read FItem write SetItem; procedure Add(X, Y, ID: Integer); function Count: Integer; procedure RenderItem(X, Y, I: Integer); procedure Render(); procedure Update(); end; implementation uses SysUtils, Tile; { TItem } constructor TItem.Create(X, Y, ID: Integer); begin inherited Create(X, Y, ID, 'Resources\Sprites\Items\' + ItemFName[ID], pResMan); Self.Active := True; Self.Dir := True; Self.Top := Rand(-ITEM_AMP, ITEM_AMP); Self.Left := Rand(0, TILE_SIZE - ITEM_SIZE); Self.Angle := Rand(0, 360); end; destructor TItem.Destroy; begin inherited; end; procedure TItem.SetActive(const Value: Boolean); begin FActive := Value; end; { TIBase } function TIBase.Count: Integer; begin Result := ITEMS_COUNT; end; constructor TIBase.Create; begin end; destructor TIBase.Destroy; begin inherited; end; { TItems } procedure TItems.Add(X, Y, ID: Integer); var I: Integer; begin if (Count <> 0) then for I := 0 to Count - 1 do if not Item[I].Active then begin Item[I].Create(X, Y, ID); Exit; end; SetLength(FItem, Count + 1); Item[Count - 1] := TItem.Create(X, Y, ID); end; function TItems.Count: Integer; begin Result := System.Length(Item); end; constructor TItems.Create; begin Base := TIBase.Create; end; destructor TItems.Destroy; var I: Integer; begin for I := 0 to Count - 1 do Item[I].Free; Base.Free; inherited; end; procedure TItems.Render; var I: Integer; begin for I := 0 to Count - 1 do if Item[I].Active then begin pRender2D.DrawTexture(Item[I].Texture, Point2((Item[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT + Item[I].Left, (Item[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP + (TILE_SIZE - ITEM_SIZE) + Round(Item[I].Top) - ITEM_AMP), Point2(ITEM_SIZE, ITEM_SIZE), Item[I].Angle, EF_BLEND); end; end; procedure TItems.RenderItem(X, Y, I: Integer); begin if (I < Base.Count) then pRender2D.DrawTexture(Item[I].Texture, Point2(X, Y), Point2(ITEM_SIZE, ITEM_SIZE)); end; procedure TItems.SetBase(const Value: TIBase); begin FBase := Value; end; procedure TItems.SetItem(const Value: TAItem); begin FItem := Value; end; procedure TItems.Update; var I: Integer; begin for I := 0 to Count - 1 do if Item[I].Active then begin if Item[i].Dir then Item[i].Top := Item[i].Top + 0.2 else Item[i].Top := Item[i].Top - 0.2; if (Item[i].Top >= ITEM_AMP) then Item[i].Dir := False; if (Item[i].Top <= -ITEM_AMP) then Item[i].Dir := True; Item[i].Angle := Item[i].Angle + 1; end; end; end.
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit ooFactory_test; interface uses SysUtils, StdCtrls, Controls, Forms, ooFactory.List, ooControlClass.Factory, ooControlClass.Item, {$IFDEF FPC} fpcunit, testregistry {$ELSE} TestFramework {$ENDIF}; type TFactoryTest = class(TTestCase) private ControlClassFactory: TControlClassFactory; protected procedure SetUp; override; procedure TearDown; override; published procedure TestAdd; procedure TestAddRepeated; procedure TestIndexOf; procedure TestExists; procedure TestFind; procedure TestFindError; procedure TestRegisteredClass; procedure TestFindByClass; procedure TestCreateControl; end; implementation procedure TFactoryTest.TestExists; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); CheckTrue(ControlClassFactory.Exists(TButton.ClassName)); CheckFalse(ControlClassFactory.Exists(TLabel.ClassName)); end; procedure TFactoryTest.TestFind; var ControlClass: TControlClass; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); ControlClass := ControlClassFactory.Find(TButton.ClassName); CheckTrue(Assigned(ControlClass)); end; procedure TFactoryTest.TestFindByClass; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); CheckTrue(Assigned(ControlClassFactory.FindByClass(TButton))); end; procedure TFactoryTest.TestFindError; var HasError: Boolean; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); HasError := False; try ControlClassFactory.Find(TLabel.ClassName); except on E: EFactoryList do HasError := True; end; CheckTrue(HasError); end; procedure TFactoryTest.TestIndexOf; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); ControlClassFactory.Add(TControlClassItem.New(TLabel)); CheckEquals(0, ControlClassFactory.IndexOf(TButton.ClassName)); CheckEquals(1, ControlClassFactory.IndexOf(TLabel.ClassName)); CheckEquals( - 1, ControlClassFactory.IndexOf(TListBox.ClassName)); end; procedure TFactoryTest.TestRegisteredClass; var ControlClass: TControlClass; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); ControlClass := ControlClassFactory.Find(TButton.ClassName); CheckTrue(ControlClass = TButton); end; procedure TFactoryTest.TestAdd; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); CheckEquals(1, ControlClassFactory.Count); end; procedure TFactoryTest.TestAddRepeated; var HasError: Boolean; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); HasError := False; try ControlClassFactory.Add(TControlClassItem.New(TButton)); except on E: EFactoryList do HasError := True; end; CheckTrue(HasError); CheckEquals(1, ControlClassFactory.Count); end; procedure TFactoryTest.TestCreateControl; var Control: TControl; begin ControlClassFactory.Add(TControlClassItem.New(TButton)); Control := ControlClassFactory.CreateControl(Application, TButton); CheckTrue(Assigned(Control)); CheckTrue(Control.ClassType = TButton); CheckTrue(Control.Owner = Application); end; procedure TFactoryTest.SetUp; begin inherited; ControlClassFactory := TControlClassFactory.Create; end; procedure TFactoryTest.TearDown; begin inherited; ControlClassFactory.Free; end; initialization RegisterTest(TFactoryTest {$IFNDEF FPC}.Suite {$ENDIF}); end.
unit uAgendamentoMotivo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, uEnumerador, Vcl.ComCtrls; const COR_PADRAO: Integer = clBlack; COR_TITULO: Integer = clRed; type TfrmAgendamentoMotivo = class(TForm) lblData: TLabel; edtData: TMaskEdit; lblHora: TLabel; edtHora: TMaskEdit; lblMotivo: TLabel; Panel1: TPanel; btnConfirmar: TBitBtn; btnCancelar: TBitBtn; mmoTexto: TRichEdit; procedure btnCancelarClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure btnConfirmarClick(Sender: TObject); procedure RichEdit1Enter(Sender: TObject); procedure RichEdit1Exit(Sender: TObject); private { Private declarations } FIdAgendamento: Integer; FTipo: TEnumAgendamento; procedure Motivos; procedure FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean = False); procedure BuscarDataAgendamento; public { Public declarations } constructor create(AIdAgendamento: integer; ATipo: TEnumAgendamento); overload; constructor create(AIdAgendamento: Integer; ADetalhe: Boolean=False); overload; end; var frmAgendamentoMotivo: TfrmAgendamentoMotivo; implementation {$R *.dfm} uses uImagens, uAgendamentoController; procedure TfrmAgendamentoMotivo.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmAgendamentoMotivo.btnConfirmarClick(Sender: TObject); begin try StrToDate(edtData.Text); except raise Exception.Create('Data Inválida!'); end; try StrToTime(edtHora.Text); except raise Exception.Create('Hora Inválida!'); end; Motivos(); Close; ModalResult := mrOk; end; procedure TfrmAgendamentoMotivo.BuscarDataAgendamento; var Controller: TAgendamentoController; begin Controller := TAgendamentoController.Create; try Controller.LocalizarId(FIdAgendamento); edtData.Text := Controller.Model.CDSCadastroAge_Data.AsString; finally FreeAndNil(Controller); end; end; constructor TfrmAgendamentoMotivo.create(AIdAgendamento: Integer; ADetalhe: Boolean); var Controller: TAgendamentoController; sTipo: string; iComp: Integer; begin inherited create(nil); Controller := TAgendamentoController.Create; FIdAgendamento := AIdAgendamento; try Controller.LocalizarId(AIdAgendamento); iComp := 69; if ADetalhe then begin mmoTexto.Align := alClient; mmoTexto.ReadOnly := True; lblMotivo.Visible := False; sTipo := 'Visita'; if Controller.Model.CDSCadastroAge_Programa.AsInteger = 7 then sTipo := 'Atividade Interna'; FormatarLinha(mmoTexto,COR_PADRAO, ''); FormatarLinha(mmoTexto,COR_TITULO, 'Cabeçalho', True); FormatarLinha(mmoTexto,COR_PADRAO, 'Id: ' + Controller.Model.CDSCadastroAge_Id.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Data: ' + Controller.Model.CDSCadastroAge_Data.AsString + ' - HORA: ' + FormatDateTime('hh:mm', Controller.Model.CDSCadastroAge_Hora.AsDateTime)); FormatarLinha(mmoTexto,COR_PADRAO, 'Usuário: ' + Controller.Model.CDSCadastroUsu_Nome.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Cliente: ' + Controller.Model.CDSCadastroAge_NomeCliente.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Contato: ' + Controller.Model.CDSCadastroAge_Contato.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Tipo: ' + Controller.Model.CDSCadastroTip_Nome.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Status: ' + Controller.Model.CDSCadastroSta_Nome.AsString); FormatarLinha(mmoTexto,COR_PADRAO, 'Programa: ' + sTipo); FormatarLinha(mmoTexto,COR_PADRAO, StringOfChar('_', iComp)); mmoTexto.Lines.Add(''); FormatarLinha(mmoTexto,COR_TITULO, 'Descrição', True); FormatarLinha(mmoTexto,COR_PADRAO, Controller.Model.CDSCadastroAge_Descricao.AsString); if Controller.Model.CDSCadastroAge_Motivo.AsString <> '' then begin FormatarLinha(mmoTexto,COR_PADRAO, StringOfChar('_', iComp)); mmoTexto.Lines.Add(''); FormatarLinha(mmoTexto,COR_TITULO, 'Motivos', True); FormatarLinha(mmoTexto,COR_PADRAO, Controller.Model.CDSCadastroAge_Motivo.AsString); end; end else mmoTexto.Text := Controller.Model.CDSCadastroAge_Motivo.AsString; finally FreeAndNil(Controller); end; if ADetalhe then Self.Caption := 'Detalhes' else Self.Caption := 'Motivo'; btnConfirmar.Visible := False; lblData.Visible := False; lblHora.Visible := False; edtData.Visible := False; edtHora.Visible := False; mmoTexto.ReadOnly := True; lblMotivo.Caption := 'Descrição'; end; procedure TfrmAgendamentoMotivo.Motivos; var Controller: TAgendamentoController; begin Controller := TAgendamentoController.Create; try if edtData.Text = DataEmBranco then raise Exception.Create('Informe a Data!'); if edtHora.Text = HoraEmBranco then raise Exception.Create('Informe a Hora!'); if Trim(mmoTexto.Text) = '' then raise Exception.Create('Informe o Motivo!'); if FTipo = ageCancelamento then Controller.Cancelamento(FIdAgendamento, StrToDate(edtData.Text), StrToTime(edtHora.Text), mmoTexto.Text) else if FTipo = ageReagendamento then Controller.Reagendamento(FIdAgendamento, StrToDate(edtData.Text), StrToTime(edtHora.Text), mmoTexto.Text); // else // Controller.Encerrar(FIdAgendamento, ); finally FreeAndNil(Controller); end; end; procedure TfrmAgendamentoMotivo.RichEdit1Enter(Sender: TObject); begin Self.KeyPreview := False; end; procedure TfrmAgendamentoMotivo.RichEdit1Exit(Sender: TObject); begin Self.KeyPreview := True; end; constructor TfrmAgendamentoMotivo.create(AIdAgendamento: integer; ATipo: TEnumAgendamento); begin inherited create(nil); FIdAgendamento := AIdAgendamento; FTipo := ATipo; if ATipo = ageCancelamento then Self.Caption := 'Motivo do Cancelamento' else if ATipo = ageReagendamento then Self.Caption := 'Motivo do Reagendamento'; end; procedure TfrmAgendamentoMotivo.FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean); begin AMemo.SelAttributes.Color := ACor; if ANegrito then AMemo.SelAttributes.Style:=[fsBold]; AMemo.Lines.Add(ATexto); AMemo.SelAttributes.Color:=Color; end; procedure TfrmAgendamentoMotivo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; if btnConfirmar.Visible then begin if Key = VK_F8 then btnConfirmarClick(Self); end; end; procedure TfrmAgendamentoMotivo.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin key:=#0; perform(Wm_NextDlgCtl,0,0); end; end; procedure TfrmAgendamentoMotivo.FormShow(Sender: TObject); var img: TfrmImagens; begin img := TfrmImagens.Create(Self); try btnConfirmar.Glyph := img.btnConfirmar.Glyph; btnCancelar.Glyph := img.btnCancelar.Glyph; finally FreeAndNil(img); end; BuscarDataAgendamento(); edtHora.Text := FormatDateTime('hh:mm', Time); end; end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit ts.Editor.Preview.ToolView; {$MODE DELPHI} interface uses Classes, SysUtils, Menus, RichMemo, ts.Editor.Interfaces, ts.Components.ExportRTF, ts.Editor.ToolView.Base; type TfrmPreview = class(TCustomEditorToolView, IEditorToolView) mniSelectAll : TMenuItem; mniOpenSelectionInNewEditor : TMenuItem; mmoPreview : TRichMemo; ppmPreview : TPopupMenu; strict private FSynExporterRTF: TSynExporterRTF; strict protected procedure EditorCaretPositionChange(Sender: TObject; X, Y: Integer); override; procedure UpdateView; override; public procedure AfterConstruction; override; end; implementation {$R *.lfm} {$REGION 'construction and destruction'} procedure TfrmPreview.AfterConstruction; begin inherited AfterConstruction; FSynExporterRTF := TSynExporterRTF.Create(Self); mmoPreview.DoubleBuffered := True; end; {$ENDREGION} {$REGION 'event handlers'} procedure TfrmPreview.EditorCaretPositionChange(Sender: TObject; X, Y: Integer); begin UpdateView; end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmPreview.UpdateView; var SS : TStringStream; S : string; SL : TStringList; begin BeginFormUpdate; try mmoPreview.Clear; S := View.PreviewText; if (S <> '') and (View.Editor.Highlighter <> nil) then begin SL := TStringList.Create; try SL.Text := S; S := ''; SS := TStringStream.Create(S); try SL.BeginUpdate; FSynExporterRTF.UseBackground := True; FSynExporterRTF.Font := View.Editor.Font; FSynExporterRTF.Highlighter := View.Editor.Highlighter; FSynExporterRTF.ExportAsText := True; FSynExporterRTF.ExportAll(SL); FSynExporterRTF.SaveToStream(SS); SS.Position := 0; mmoPreview.LoadRichText(SS); finally SL.EndUpdate; FreeAndNil(SS); end; finally FreeAndNil(SL); end; end; finally EndFormUpdate; end; end; {$ENDREGION} end.
{***************************************************************************} { TMacroRecorder component } { for Delphi & C++Builder } { } { written by TMS Software } { copyright © 2005 - 2012 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {***************************************************************************} unit MacroRecorder; interface uses Windows, Messages, SysUtils, Classes, AppEvnts, Dialogs, Forms, Types; const MAXMSG = 20000; MAJ_VER = 1; // Major version nr. MIN_VER = 2; // Minor version nr. REL_VER = 1; // Release nr. BLD_VER = 0; // Build nr. // version history // 1.1.0.0 : New : event OnRecordCancelled added // : New : event OnPlaybackCancelled added // 1.2.0.0 : New : functions IsPlaying, IsRecording added // New : procedure StopPlayback added // 1.2.1.0 : New : exposed public property ElapsedTime type PEventMsg = ^TEventMsg; TMsgBuff = array[0..MAXMSG] of TEventMsg; TcbPlaybackFinishedProc = procedure(AppData: Longint) of object; TcbRecordFinishedProc = procedure(Sender: TObject) of object; TRecordOption = (roMouseMove, roMouseRelative); TRecordOptions = set of TRecordOption; TPlaybackSpeed = (pbNormal, pbFast); TRecordingRange = (rrSystem, rrApplication); {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TMacroRecorder = class(TComponent) private FElapsedTime: longint; FOwner: TComponent; FPlayback: boolean; FFileName: string; FOnPlaybackFinished: TcbPlaybackFinishedProc; FPlaybackSpeed: TPlaybackSpeed; FApplicationEvents: TApplicationEvents; FApplicationOnActivate: TNotifyEvent; FApplicationOnDeActivate: TNotifyEvent; FRecordingRange: TRecordingRange; FOptions: TRecordOptions; FOnRecordFinished: TcbRecordFinishedProc; FOnRecordCancelled: TNotifyEvent; FOnPlaybackCancelled: TNotifyEvent; procedure SetFileName(value: string); procedure SetPlaybackSpeed(value: TPlaybackSpeed); procedure PlaybackFinished(AppData: Longint); procedure ApplicationOnActivate(Sender: TObject); procedure ApplicationOnDeActivate(Sender: TObject); procedure SetRecordingRange(value: TRecordingRange); procedure ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); function KeyToString(aCode: Cardinal): string; function StringToKey(S: string): Cardinal; function GetVersion: string; procedure SetVersion(const Value: string); protected function GetVersionNr: Integer; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IsPlaying: boolean; function IsRecording: boolean; procedure RecordMacro; procedure StopRecording; procedure StopPlayback; procedure PlayMacro; procedure SaveMacro; procedure LoadMacro; property ElapsedTime: longint read FElapsedTime write FElapsedTime; published property FileName: string read FFileName write SetFileName; property PlaybackSpeed: TPlaybackSpeed read FPlaybackSpeed write SetPlaybackSpeed; property RecordingRange: TRecordingRange read FRecordingRange write SetRecordingRange; property OnPlaybackFinished: TcbPlaybackFinishedProc read FOnPlaybackFinished write FOnPlaybackFinished; property OnPlaybackCancelled: TNotifyEvent read FOnPlayBackCancelled write FOnPlayBackCancelled; property OnRecordFinished: TcbRecordFinishedProc read FOnRecordFinished write FOnRecordFinished; property OnRecordCancelled: TNotifyEvent read FOnRecordCancelled write FOnRecordCancelled; property Options: TRecordOptions read FOptions write FOptions; property Version: string read GetVersion write SetVersion; end; function JournalProc(Code, wParam: Integer; var EventStrut: TEventMsg): Integer; stdcall; function JournalPlaybackProc(Code: Integer; wParam: integer; var EventStrut: TEventMsg): integer; stdcall; var JHook: THandle; PMsgBuff: ^TMsgBuff; StartTime: Longint; MsgCount: Longint; CurrentMsg: Longint; ReportDelayTime: Bool; SysModalOn: Bool; cbPlaybackFinishedProc: TcbPlaybackFinishedProc; cbAppData: Longint; DoMouseMove: Boolean; DoRelative: Boolean; FHookStarted: Boolean; gPlaybackSpeed: TPlaybackSpeed; gRecordingRange: TRecordingRange; gOutOfRange: Boolean; gFirstEvent: Boolean; RecorderInstance: TMacroRecorder; pt: TPoint; implementation { this is the JournalRecordProc The lParam parameter contains a pointer to a TEventMsg structure containing information on the message removed from the system message queue. } function JournalProc(Code, wParam: Integer; var EventStrut: TEventMsg): Integer; stdcall; var Evnt: TEventMsg; begin Result := CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); {the CallNextHookEX is not really needed for journal hook since it it not really in a hook chain, but it's standard for a Hook} if Code < 0 then Exit; {cancel operation if get HC_SYSMODALON} if Code = HC_SYSMODALON then begin SysModalOn := True; CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); Exit; end; if Code = HC_SYSMODALOFF then begin SysModalOn := False; CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); Exit; end; if Code = HC_ACTION then begin if SysModalOn then Exit; Evnt := EventStrut; if MsgCount > MAXMSG then Exit; if (EventStrut.message = WM_MOUSEMOVE) and DoMouseMove then Exit; if (EventStrut.message = WM_MOUSEMOVE) or (EventStrut.message = WM_LBUTTONDOWN) or (EventStrut.message = WM_LBUTTONDBLCLK) or (EventStrut.message = WM_LBUTTONUP) or (EventStrut.message = WM_RBUTTONDOWN) or (EventStrut.message = WM_RBUTTONUP) or (EventStrut.message = WM_RBUTTONDBLCLK) or (EventStrut.message = WM_MBUTTONDOWN) or (EventStrut.message = WM_MBUTTONUP) or (EventStrut.message = WM_MBUTTONDBLCLK) or (EventStrut.message = WM_MOUSEWHEEL) then begin if (DoRelative) then begin pt := Point(Evnt.paramL, Evnt.paramH); Windows.ScreenToClient(GetActiveWindow,pt); Evnt.paramL := pt.X; Evnt.paramH := pt.Y; end; end; if (EventStrut.message = WM_KEYDOWN) then begin if (eventstrut.paraml and $FF = VK_CANCEL) then begin RecorderInstance.StopRecording; Exit; end; end; if (gRecordingRange = rrApplication) and gOutOfRange then Exit; {record the message} // PMsgBuff^[MsgCount] := PEventMsg(Longint(@EventStrut))^; PMsgBuff^[MsgCount] := Evnt; {set the delta time of the message} //Dec(PMsgBuff^[MsgCount].Time, StartTime); if gFirstEvent then begin StartTime := PMsgBuff^[MsgCount].Time; PMsgBuff^[MsgCount].Time := 0; gFirstEvent := false; end else Dec(PMsgBuff^[MsgCount].Time, StartTime); Inc(MsgCount); end; end; procedure TMacroRecorder.ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); begin {the journal hook is automaticly cancelled if the Task manager (Ctrl-Alt-Del) or the Ctrl-Esc keys are pressed, restart it when the WM_CANCELJOURNAL is sent to the parent window, Application} Handled := False; if (Msg.message = WM_CANCELJOURNAL) and FPlayback then begin FPlayback := false; if Assigned(FOnPlayBackCancelled) then FOnPlayBackCancelled(self); end; if (Msg.message = WM_CANCELJOURNAL) and FHookStarted then begin if Assigned(OnRecordCancelled) then OnRecordCancelled(Self); StopRecording; //JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, 0, 0); end; end; function JournalPlaybackProc(Code: Integer; wParam: integer; var EventStrut: TEventMsg): integer; stdcall; var TimeToFire: Longint; Evnt: TEventMsg; pt: TPoint; begin Result := 0; case Code of HC_SKIP: begin {get the next message} Inc(CurrentMsg); ReportDelayTime := True; {Is finished?} if CurrentMsg >= (MsgCount - 1) then if JHook <> 0 then if UnHookWindowsHookEx(JHook) = True then begin JHook := 0; FreeMem(PMsgBuff, Sizeof(TMsgBuff)); PMsgBuff := nil; {callback to the application announcing we are finished} cbPlaybackFinishedProc(cbAppData); end; exit; end; HC_GETNEXT: begin {play the current message} Evnt := PMsgBuff^[CurrentMsg]; if (Evnt.message = WM_MOUSEMOVE) or (Evnt.message = WM_LBUTTONDOWN) or (Evnt.message = WM_LBUTTONUP) or (Evnt.message = WM_LBUTTONDBLCLK) or (Evnt.message = WM_RBUTTONDOWN) or (Evnt.message = WM_RBUTTONUP) or (Evnt.message = WM_RBUTTONDBLCLK) or (Evnt.message = WM_MBUTTONDOWN) or (Evnt.message = WM_MBUTTONUP) or (Evnt.message = WM_MBUTTONDBLCLK) or (Evnt.message = WM_MOUSEWHEEL) then begin pt := Point(Evnt.paraml, Evnt.paramH); ClientToScreen(GetActiveWindow,pt); Evnt.paramL := pt.X; Evnt.paramH := pt.Y; end; PEventMsg(Longint(@EventStrut))^ := Evnt; // PEventMsg(Longint(@EventStrut))^ := PMsgBuff^[CurrentMsg]; if gPlaybackSpeed = pbNormal then PEventMsg(Longint(@EventStrut))^.Time := longint(StartTime) + longint(PMsgBuff^[CurrentMsg].Time); RecorderInstance.ElapsedTime := longint(PEventMsg(Longint(@EventStrut))^.Time) - longint(StartTime); {if first time this message has played - report the delay time} if ReportDelayTime then begin ReportDelayTime := False; TimeToFire := PEventMsg(Longint(@EventStrut))^.Time - GetTickCount; if TimeToFire > 0 then Result := TimeToFire; end; Exit; end; HC_SYSMODALON: begin {something is wrong} SysModalOn := True; CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); exit; end; HC_SYSMODALOFF: begin {we have been hosed by the system - our hook has been pulled!} SysModalOn := False; JHook := 0; FreeMem(PMsgBuff, Sizeof(TMsgBuff)); PMsgBuff := nil; {callback to the application announcing we are finished} cbPlaybackFinishedProc(cbAppData); CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); exit; end; end; if code < 0 then Result := CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut)); end; constructor TMacroRecorder.Create(AOwner: TComponent); begin inherited Create(AOwner); if not (Owner is TForm) then raise exception.Create('Control parent must be a form!'); FOwner := AOwner; FApplicationOnActivate := Application.OnActivate; Application.OnActivate := ApplicationOnActivate; FApplicationOnDeActivate := Application.OnDeActivate; Application.OnDeActivate := ApplicationOnDeActivate; cbPlaybackFinishedProc := PlaybackFinished; DoMouseMove := True; DoRelative := True; FPlaybackSpeed := pbNormal; gPlaybackSpeed := FPlaybackSpeed; FRecordingRange := rrSystem; gRecordingRange := FRecordingRange; gOutOfRange := false; FOptions := [roMouseMove, roMouseRelative]; FApplicationEvents := TApplicationEvents.Create(self); FApplicationEvents.OnMessage := ApplicationEventsMessage; end; destructor TMacroRecorder.Destroy; begin {unhook on app closes} if FHookStarted then UnhookWindowsHookEx(JHook); Application.OnActivate := FApplicationOnActivate; Application.OnDeActivate := FApplicationOnDeActivate; inherited; end; procedure TMacroRecorder.RecordMacro; begin if FHookStarted then begin ShowMessage('Mouse is already being Journaled, can not restart'); Exit; end; RecorderInstance := self; if FFileName = '' then raise exception.Create('Invalid FileName'); if pMsgBuff <> nil then Exit; GetMem(PMsgBuff, Sizeof(TMsgBuff)); if PMsgBuff = nil then exit; SysModalOn := False; MsgCount := 0; gFirstEvent := true; StartTime := GetTickCount; DoMouseMove := not (roMouseMove in Options); DoRelative := (roMouseRelative in Options); JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, hInstance, 0); {SetWindowsHookEx starts the Hook} if JHook > 0 then begin FHookStarted := True; end else begin FreeMem(PMsgBuff, Sizeof(TMsgBuff)); PMsgBuff := nil; ShowMessage('No Journal Hook available'); end; end; procedure TMacroRecorder.StopPlayback; begin if FPlayback then begin FPlayback := false; UnhookWindowsHookEx(JHook); JHook := 0; end; end; procedure TMacroRecorder.StopRecording; begin FHookStarted := False; if PMsgBuff = nil then Exit; UnhookWindowsHookEx(JHook); JHook := 0; SaveMacro; FreeMem(PMsgBuff, Sizeof(TMsgBuff)); PMsgBuff := nil; if Assigned(OnRecordFinished) then OnRecordFinished(Self); end; function TMacroRecorder.IsPlaying: boolean; begin Result := FPlayback; end; function TMacroRecorder.IsRecording: boolean; begin Result := FHookStarted; end; procedure TMacroRecorder.PlayMacro; begin if FFileName = '' then raise exception.Create('Invalid FileName'); if PMsgBuff <> nil then Exit; GetMem(PMsgBuff, Sizeof(TMsgBuff)); if PMsgBuff = nil then Exit; LoadMacro; CurrentMsg := 0; ReportDelayTime := True; SysModalOn := False; cbAppData := 0; StartTime := GetTickCount; FElapsedTime := 0; RecorderInstance := self; FPlayback := true; JHook := SetWindowsHookEx(WH_JOURNALPLAYBACK, @JournalPlayBackProc, hInstance, 0); if JHook = 0 then begin FreeMem(PMsgBuff, Sizeof(TMsgBuff)); PMsgBuff := nil; FPlayback := false; Exit; end; end; procedure TMacroRecorder.PlaybackFinished(AppData: Longint); begin StopPlayback; if Assigned(FOnPlaybackFinished) then FOnPlaybackFinished(AppData); end; procedure TMacroRecorder.LoadMacro; var ST1, ST2: TStringList; i: integer; begin //if PMsgBuff <> nil then exit; if not FileExists (FFileName) then Exit; ST1 := TStringList.Create; ST2 := TStringList.Create; try ST2.LoadFromFile(FFileName); ST1.CommaText := ST2[0]; MsgCount := strtoint(ST1.Values['MessageCount']); for i := 1 to ST2.Count - 1 do begin ST1.Clear; ST1.CommaText := ST2[i]; PMsgBuff[i - 1].message := StrToInt(ST1.Values[ST1.Names[0]]); if (PMsgBuff[i - 1].message = WM_KEYDOWN) or (PMsgBuff[i - 1].message = WM_KEYUP) then PMsgBuff[i - 1].paramL := StringToKey(ST1.Values['ParamL']) else PMsgBuff[i - 1].paramL := StrToInt(ST1.Values['ParamL']); PMsgBuff[i - 1].paramH := StrToInt(ST1.Values['ParamH']); PMsgBuff[i - 1].time := StrToInt(ST1.Values['Time']); PMsgBuff[i - 1].hwnd := StrToInt(ST1.Values['hwnd']); end; finally ST1.Free; ST2.Free; end; end; function TMacroRecorder.KeyToString(aCode: Cardinal): string; begin case aCode of 7745: Result := 'a'; 12354: Result := 'b'; 11843: Result := 'c'; 8260: Result := 'd'; 4677: Result := 'e'; 8518: Result := 'f'; 8775: Result := 'g'; 9032: Result := 'h'; 5961: Result := 'i'; 9290: Result := 'j'; 9547: Result := 'k'; 9804: Result := 'l'; 12877: Result := 'm'; 12622: Result := 'n'; 6223: Result := 'o'; 6480: Result := 'p'; 4177: Result := 'q'; 4946: Result := 'r'; 8019: Result := 's'; 5204: Result := 't'; 5717: Result := 'u'; 12118: Result := 'v'; 4439: Result := 'w'; 11608: Result := 'x'; 5465: Result := 'y'; 11354: Result := 'z'; else Result := IntToStr(aCode); end; end; function TMacroRecorder.StringToKey(S: string): Cardinal; var c: Char; begin if length(S) = 1 then begin c := S[1]; case c of 'a': Result := 7745; 'b': Result := 12354; 'c': Result := 11843; 'd': Result := 8260; 'e': Result := 4677; 'f': Result := 8518; 'g': Result := 8775; 'h': Result := 9032; 'i': Result := 5961; 'j': Result := 9290; 'k': Result := 9547; 'l': Result := 9804; 'm': Result := 12877; 'n': Result := 12622; 'o': Result := 6223; 'p': Result := 6480; 'q': Result := 4177; 'r': Result := 4946; 's': Result := 8019; 't': Result := 5204; 'u': Result := 5717; 'v': Result := 12118; 'w': Result := 4439; 'x': Result := 11608; 'y': Result := 5465; 'z': Result := 11354; else Result := StrToInt(S); end; end else begin Result := StrToInt(S); end; end; procedure TMacroRecorder.SaveMacro; var ST1, ST2: TStringList; i,p: integer; S: string; begin if PMsgBuff = nil then Exit; if MsgCount > 0 then begin ST1 := TStringList.Create; ST2 := TStringList.Create; try ST1.Values['MessageCount'] := inttostr(MsgCount); ST2.Add(ST1.CommaText); S := ''; for i := 0 to MsgCount do begin ST1.Clear; case PMsgBuff[i].message of WM_MOUSEMOVE: S := 'MOUSEMOVE'; WM_LBUTTONDOWN: S := 'LBUTTONDOWN'; WM_LBUTTONUP: S := 'LBUTTONUP'; WM_LBUTTONDBLCLK: S := 'LBUTTONDBLCLK'; WM_RBUTTONDOWN: S := 'RBUTTONDOWN'; WM_RBUTTONUP: S := 'RBUTTONUP'; WM_RBUTTONDBLCLK: S := 'RBUTTONDBLCLK'; WM_MBUTTONDOWN: S := 'MBUTTONDOWN'; WM_MBUTTONUP: S := 'MBUTTONUP'; WM_MBUTTONDBLCLK: S := 'MBUTTONDBLCLK'; WM_MOUSEWHEEL: S := 'MOUSEWHEEL'; WM_KEYDOWN: S := 'KEYDOWN'; WM_KEYUP: S := 'KEYUP'; WM_CHAR: S := 'CHAR'; WM_DEADCHAR: S := 'DEADCHAR'; WM_SYSKEYDOWN: S := 'SYSKEYDOWN'; WM_SYSKEYUP: S := 'SYSKEYUP'; WM_SYSCHAR: S := 'SYSCHAR'; WM_SYSDEADCHAR: S := 'SYSDEADCHAR'; WM_KEYLAST: S := 'KEYLAST'; else S := 'UnKnown'; end; p := PMsgBuff[i].paramL; ST1.Values[S] := IntToStr(PMsgBuff[i].message); if (S = 'KEYDOWN') or (S = 'KEYUP') then ST1.Values['ParamL'] := KeyToString(p) else ST1.Values['ParamL'] := IntToStr(p); p := PMsgBuff[i].paramH; ST1.Values['ParamH'] := IntToStr(p); ST1.Values['Time'] := InttoStr(PMsgBuff[i].time); ST1.Values['hwnd'] := inttoStr(PMsgBuff[i].hwnd); ST2.Add(ST1.CommaText); end; ST2.SaveToFile(FFileName); finally ST1.Free; ST2.Free; end; end; end; procedure TMacroRecorder.SetFileName(value: string); begin if FHookStarted then raise exception.Create('Can not modify file name while recording Macro.'); FFileName := value end; procedure TMacroRecorder.SetPlaybackSpeed(value: TPlaybackSpeed); begin FPlaybackSpeed := value; GPlaybackSpeed := FPlaybackSpeed; end; procedure TMacroRecorder.ApplicationOnActivate(Sender: TObject); begin gOutOfRange := false; if Assigned(FApplicationOnActivate) then FApplicationOnActivate(Sender); end; procedure TMacroRecorder.ApplicationOnDeActivate(Sender: TObject); begin if FRecordingRange = rrApplication then gOutOfRange := true; if Assigned(FApplicationOnDeActivate) then FApplicationOnDeActivate(Sender); end; procedure TMacroRecorder.SetRecordingRange(value: TRecordingRange); begin if FHookStarted then raise exception.Create('Can not change property while recording macro.'); FRecordingRange := value; gRecordingRange := FRecordingRange; end; function TMacroRecorder.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TMacroRecorder.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TMacroRecorder.SetVersion(const Value: string); begin end; end.