text
stringlengths
14
6.51M
unit UnitMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, System.IOUtils, FMX.StdCtrls, SG.ScriptGate, FMX.Controls.Presentation; type TfrmMain = class(TForm) wbWebBrowser: TWebBrowser; tDemoDeviceToken: TTimer; Panel1: TPanel; Label1: TLabel; lblSomeText: TLabel; lblValueFromJavaScript: TLabel; procedure FormCreate(Sender: TObject); procedure tDemoDeviceTokenTimer(Sender: TObject); private var FScriptGate: TScriptGate; { Private declarations } public { Public declarations } // Procedure called from JavaScript code. procedure SendToHost; // Procedure receives data from JavaScript code. procedure SendToHostValue(Value: String); end; var frmMain: TfrmMain; implementation {$R *.fmx} procedure TfrmMain.FormCreate(Sender: TObject); begin var url := {$IFDEF MSWINDOWS} ExtractFilePath(ParamStr(0)) + 'www\index.html'; {$ENDIF} {$IFDEF ANDROID} 'file:///' + System.IOUtils.TPath.GetTempPath + PathDelim + 'www' + 'index.html'; FPermission := JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE); {$ENDIF} wbWebBrowser.URL := url; FScriptGate := TScriptGate.Create(Self, wbWebBrowser,'fmx-js'); wbWebBrowser.Navigate; end; procedure TfrmMain.SendToHost; begin lblSomeText.Text := '"SendToHost" method called.'; end; procedure TfrmMain.SendToHostValue(Value: String); begin lblValueFromJavaScript.Text := 'Value from JavaScript: ' + Value; end; procedure TfrmMain.tDemoDeviceTokenTimer(Sender: TObject); begin // Here we will generate some fake data for demonstration. // Imagine, we retrieved here Push Notifications token, which we want to // send to the server using JavaScript REST API calls implementation. var deviceToken := 'KGKYHHGHHJ76KGHKGHG7'; FScriptGate.CallScript('document.getElementById("text1").innerText = "Device token: ' + deviceToken + '";' ,nil); end; end.
unit uPathProvideTreeView; interface uses Generics.Collections, Winapi.Windows, Winapi.Messages, Winapi.ActiveX, System.SysUtils, System.Classes, System.DateUtils, Vcl.Forms, Vcl.Dialogs, Vcl.Controls, Vcl.Graphics, VirtualTrees, Vcl.Themes, Vcl.ImgList, Dmitry.Graphics.Types, Dmitry.PathProviders, Dmitry.PathProviders.MyComputer, Dmitry.PathProviders.Network, UnitBitmapImageList, uMemory, uThreadForm, uGOM, uThreadTask, uMachMask, uConstants, uGUIDUtils, {$IFDEF PHOTODB} uThemesUtils, uExplorerDateStackProviders, {$ENDIF} uVCLHelpers; type PData = ^TData; TData = record Data: TPathItem; end; TOnSelectPathItem = procedure(Sender: TCustomVirtualDrawTree; PathItem: TPathItem) of object; TPathProvideTreeView = class(TCustomVirtualDrawTree) private FHomeItems: TPathItemCollection; FWaitOperationCount: Integer; FImTreeImages: TImageList; FImImages: TImageList; FForm: TThreadForm; FStartPathItem: TPathItem; FOnSelectPathItem: TOnSelectPathItem; FIsStarted: Boolean; FIsInitialized: Boolean; FIsInternalSelection: Boolean; FNodesToDelete: TList<TPathItem>; FImageList: TBitmapImageList; FBlockMouseMove: Boolean; FPopupItem: TPathItem; FOnlyFileSystem: Boolean; FState: TGUID; procedure LoadBitmaps; procedure StartControl; procedure InternalSelectNode(Node: PVirtualNode); protected procedure WndProc(var Message: TMessage); override; procedure DoPaintNode(var PaintInfo: TVTPaintInfo); override; procedure DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); override; function DoGetNodeWidth(Node: PVirtualNode; Column: TColumnIndex; Canvas: TCanvas = nil): Integer; override; procedure DoFreeNode(Node: PVirtualNode); override; procedure AddToSelection(Node: PVirtualNode); override; function DoInitChildren(Node: PVirtualNode; var ChildCount: Cardinal): Boolean; override; function DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer): TCustomImageList; override; function InitControl: Boolean; procedure DoPopupMenu(Node: PVirtualNode; Column: TColumnIndex; Position: TPoint); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadColorScheme; procedure LoadHomeDirectory(Form: TThreadForm); procedure SelectPathItem(PathItem: TPathItem); procedure SelectPath(Path: string); procedure DeletePath(Path: string); procedure AddItemToCalendar(Date: TDateTime); procedure SetFilter(Filter: string; Match: Boolean); procedure Reload; procedure RefreshPathItem(PathItem: TPathItem); property OnSelectPathItem: TOnSelectPathItem read FOnSelectPathItem write FOnSelectPathItem; property OnGetPopupMenu; property OnKeyAction; property OnNodeDblClick; property PopupItem: TPathItem read FPopupItem; property OnlyFileSystem: Boolean read FOnlyFileSystem write FOnlyFileSystem default False; end; {$R TreeView.res} implementation { TPathProvideTreeView } function FilterTree(Tree: TCustomVirtualDrawTree; Node: PVirtualNode; const Filter: string; Match: Boolean): Boolean; var Data: PData; S: string; HideNode: Boolean; begin Result := False; repeat Data := Tree.GetNodeData(Node); if Assigned(Data) and Assigned(Data.Data) then begin HideNode := True; S := Data.Data.DisplayName; if not Match then S := AnsiLowerCase(S); if (Filter = '') or IsMatchMask(S, Filter, False) then begin Result := True; HideNode := False; end; if (Node.ChildCount > 0) and (Tree.GetFirstChild(Node) <> nil) then begin if FilterTree(Tree, Tree.GetFirstChild(Node), Filter, Match) then begin Result := True; HideNode := False; end; end; Tree.IsFiltered[Node] := HideNode; Node := Node.NextSibling; end; until Node = nil; end; procedure TPathProvideTreeView.SetFilter(Filter: string; Match: Boolean); begin BeginUpdate; try if not Match then Filter := AnsiLowerCase(Filter); FilterTree(Self, GetFirstChild(nil), Filter, Match); finally EndUpdate; end; end; function FindPathInTree(Tree: TCustomVirtualDrawTree; Node: PVirtualNode; Path: string): PVirtualNode; var Data: PData; begin Result := nil; if Node = nil then Exit(Result); repeat if ( Node.ChildCount > 0 ) and ( Tree.GetFirstChild( Node ) <> nil ) then begin Result := FindPathInTree( Tree, Tree.GetFirstChild( Node ), Path); if Result <> nil then Exit; end; Data := Tree.GetNodeData(Node); if (Data <> nil) and (Data.Data <> nil) and (AnsiLowerCase(ExcludeTrailingPathDelimiter(Data.Data.Path)) = Path) then begin Result := Node; Exit; end; Node := Node.NextSibling; until Node = nil; end; function FindInsertPlace(Tree: TCustomVirtualDrawTree; Node: PVirtualNode; PI: TPathItem): PVirtualNode; var Data: PData; function FirstPathItemBiggerThenSecond(Item1, Item2: TPathItem): Boolean; begin Result := False; if (Item1 is TCalendarItem) and (Item2 is TCalendarItem) then Result := TCalendarItem(Item1).Order > TCalendarItem(Item2).Order; end; begin Result := nil; repeat Data := Tree.GetNodeData(Node); if (Data <> nil) and (Data.Data <> nil) then begin if FirstPathItemBiggerThenSecond(PI, TPathItem(Data.Data)) then Exit; end; Result := Node; if Node <> nil then Node := Node.NextSibling; until Node = nil; end; procedure TPathProvideTreeView.AddItemToCalendar(Date: TDateTime); var NeedRepainting: Boolean; Calendar: PVirtualNode; PrevNode: PVirtualNode; PI: TPathItem; function UpdateNode(Path: string): Boolean; var InsertPlaceNode, Node: PVirtualNode; Data: PData; ChildData: TData; begin Result := False; Node := FindPathInTree(Self, GetFirstChild( nil ), AnsiLowerCase(Path)); if Node <> nil then begin Data := GetNodeData(Node); TCalendarItem(Data.Data).IntCount; NeedRepainting := True; Result := (vsHasChildren in Node.States) and (Node.ChildCount > 0); PrevNode := Node; end else begin PI := PathProviderManager.CreatePathItem(Path); if PI <> nil then begin TCalendarItem(PI).SetCount(1); ChildData.Data := PI; //image is required ChildData.Data.LoadImage(PATH_LOAD_FOR_IMAGE_LIST, 16); ChildData.Data.Tag := FImageList.AddPathImage(ChildData.Data.ExtractImage, True); InsertPlaceNode := FindInsertPlace(Self, GetFirstChild( PrevNode ), PI); if InsertPlaceNode = nil then Node := AddChild(PrevNode, Pointer(ChildData)) else Node := InsertNode(InsertPlaceNode, amInsertAfter, Pointer(ChildData)); ValidateNode(PrevNode, False); PrevNode := Node; end; end; end; begin NeedRepainting := False; Calendar := FindPathInTree(Self, GetFirstChild( nil ), AnsiLowerCase(cDatesPath)); if Calendar = nil then Exit; PrevNode := Calendar; if ((vsHasChildren in Calendar.States) and (Calendar.ChildCount > 0)) or (not (vsHasChildren in Calendar.States) and (Calendar.ChildCount = 0)) then begin if UpdateNode(cDatesPath + '\' + IntToStr(YearOf(Date))) then begin if UpdateNode(cDatesPath + '\' + IntToStr(YearOf(Date)) + '\' + IntToStr(MonthOf(Date))) then begin UpdateNode(cDatesPath + '\' + IntToStr(YearOf(Date)) + '\' + IntToStr(MonthOf(Date)) + '\' + IntToStr(DayOf(Date))); end; end; end; if NeedRepainting then Repaint; end; procedure TPathProvideTreeView.AddToSelection(Node: PVirtualNode); var Data: PData; begin inherited; Expanded[Node] := True; Repaint; if not FIsInternalSelection and Assigned(FOnSelectPathItem) then begin Data := GetNodeData(Node); FOnSelectPathItem(Self, Data.Data); end; end; type TCustomVirtualTreeOptionsEx = class(TCustomVirtualTreeOptions); constructor TPathProvideTreeView.Create(AOwner: TComponent); begin inherited Create(AOwner); FState := GetGUID; FOnlyFileSystem := False; FPopupItem := nil; FOnSelectPathItem := nil; FStartPathItem := nil; FNodesToDelete := TList<TPathItem>.Create; FImageList := TBitmapImageList.Create; AnimationDuration := 0; FIsStarted := False; FIsInitialized := False; FIsInternalSelection := False; FWaitOperationCount := 0; FHomeItems := TPathItemCollection.Create; FImImages := TImageList.Create(nil); FImTreeImages := TImageList.Create(nil); FImTreeImages.ColorDepth := cd32Bit; Images := FImImages; end; procedure TPathProvideTreeView.DeletePath(Path: string); var Node: PVirtualNode; begin Path := AnsiLowerCase(ExcludeTrailingPathDelimiter(Path)); Node := FindPathInTree(Self, GetFirstChild( nil ), Path); if Node <> nil then DeleteNode(Node); end; destructor TPathProvideTreeView.Destroy; begin Clear; FHomeItems.FreeItems; F(FHomeItems); F(FStartPathItem); F(FImTreeImages); F(FImImages); FreeList(FNodesToDelete); F(FImageList); F(FPopupItem); inherited; end; type TLoadChildsInfo = class Node: PVirtualNode; Data: PData; State: TGUID; end; procedure TPathProvideTreeView.DoFreeNode(Node: PVirtualNode); var Data: PData; begin Data := GetNodeData(Node); Data.Data.Free; inherited; end; function TPathProvideTreeView.DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer): TCustomImageList; var Data: PData; begin Result := inherited DoGetImageIndex(Node, Kind, Column, Ghosted, Index); if Result <> nil then Exit; Data := GetNodeData(Node); FImTreeImages.Clear; Result := FImTreeImages; if (Data.Data <> nil) and (Data.Data.Tag > -1) and (Data.Data.Tag < FImageList.Count) then FImageList[Data.Data.Tag].AddToImageList(FImTreeImages); Index := FImTreeImages.Count - 1; end; function TPathProvideTreeView.DoGetNodeWidth(Node: PVirtualNode; Column: TColumnIndex; Canvas: TCanvas): Integer; var Data: PData; AMargin: Integer; begin AMargin := TextMargin; Data := GetNodeData(Node); Result := Self.Canvas.TextWidth(Data.Data.DisplayName) + 2 * AMargin; end; procedure TPathProvideTreeView.DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); var TreeData: PData; begin inherited; TreeData := GetNodeData(Node); if Parent = nil then begin if Node.Index < FHomeItems.Count then begin TreeData.Data := FHomeItems[Node.Index].Copy; TreeData.Data.Tag := FImageList.AddPathImage(TreeData.Data.ExtractImage, True); end; end; if TreeData.Data.IsDirectory and TreeData.Data.CanHaveChildren then Include(InitStates, ivsHasChildren); end; procedure TPathProvideTreeView.DoPaintNode(var PaintInfo: TVTPaintInfo); var Data: PData; S: string; R: TRect; begin inherited; with PaintInfo do begin Data := GetNodeData(Node); if (Column = FocusedColumn) and (Node = FocusedNode) then Canvas.Font.Color := Theme.GradientText else Canvas.Font.Color := Theme.ListViewFontColor; SetBKMode(Canvas.Handle, TRANSPARENT); R := ContentRect; InflateRect(R, -TextMargin, 0); Dec(R.Right); Dec(R.Bottom); S := Data.Data.DisplayName; if Length(S) > 0 then begin with R do begin if (NodeWidth - 2 * Margin) > (Right - Left) then S := ShortenString(Canvas.Handle, S, Right - Left); end; DrawTextW(Canvas.Handle, PWideChar(S), Length(S), R, DT_TOP or DT_LEFT or DT_VCENTER or DT_SINGLELINE); end; end; end; procedure TPathProvideTreeView.DoPopupMenu(Node: PVirtualNode; Column: TColumnIndex; Position: TPoint); var Data: PData; begin FBlockMouseMove := True; try Data := GetNodeData(Node); F(FPopupItem); if Data <> nil then FPopupItem := Data.Data.Copy; inherited; finally FBlockMouseMove := False; end; end; function TPathProvideTreeView.InitControl: Boolean; begin Result := not FIsInitialized; if FIsInitialized then Exit; FIsInitialized := True; NodeDataSize := SizeOf(TData); DrawSelectionMode := smBlendedRectangle; LineMode := lmBands; TCustomVirtualTreeOptionsEx(TreeOptions).AnimationOptions := [toAnimatedToggle, toAdvancedAnimatedToggle]; TCustomVirtualTreeOptionsEx(TreeOptions).PaintOptions := [toHotTrack, toShowButtons, toShowDropmark, toShowRoot, toUseBlendedImages, toUseBlendedSelection, toStaticBackground, toHideTreeLinesIfThemed]; TCustomVirtualTreeOptionsEx(TreeOptions).SelectionOptions := [toExtendedFocus, toFullRowSelect]; LoadBitmaps; end; procedure TPathProvideTreeView.InternalSelectNode(Node: PVirtualNode); begin FIsInternalSelection := True; try Selected[Node] := True; finally FIsInternalSelection := False; end; end; procedure TPathProvideTreeView.LoadBitmaps; procedure ApplyColor(Bitmap: TBitmap; Color: TColor); var I, J: Integer; P: PARGB32; R, G, B: Byte; begin Color := ColorToRGB(Color); R := GetRValue(Color); G := GetGValue(Color); B := GetBValue(Color); for I := 0 to Bitmap.Height - 1 do begin P := Bitmap.ScanLine[I]; for J := 0 to Bitmap.Width - 1 do begin P[J].R := R; P[J].G := G; P[J].B := B; end; end; end; procedure LoadFromRes(Bitmap: TBitmap; Name: string; Color: TColor); begin Bitmap.AlphaFormat := afIgnored; Bitmap.LoadFromResourceName(hInstance, Name); ApplyColor(Bitmap, Color); Bitmap.AlphaFormat := afDefined; end; begin LoadFromRes(HotMinusBM, 'TREE_VIEW_OPEN_HOT', StyleServices.GetSystemColor(clHighlight)); LoadFromRes(HotPlusBM, 'TREE_VIEW_CLOSE_HOT', StyleServices.GetSystemColor(clHighlight)); LoadFromRes(MinusBM, 'TREE_VIEW_OPEN', StyleServices.GetStyleFontColor(sfTreeItemTextNormal)); LoadFromRes(PlusBM, 'TREE_VIEW_CLOSE', StyleServices.GetStyleFontColor(sfTreeItemTextNormal)); end; procedure TPathProvideTreeView.LoadColorScheme; begin {$IFDEF PHOTODB} Color := Theme.ListViewColor; Font.Color := StyleServices.GetStyleFontColor(sfListItemTextNormal); Colors.BorderColor := StyleServices.GetSystemColor(clBtnFace); Colors.DisabledColor := StyleServices.GetSystemColor(clBtnShadow); Colors.DropMarkColor := StyleServices.GetSystemColor(clHighlight); Colors.FocusedSelectionBorderColor := Theme.GradientToColor; Colors.FocusedSelectionColor := Theme.GradientFromColor; Colors.GridLineColor := StyleServices.GetSystemColor(clBtnFace); Colors.HotColor := StyleServices.GetSystemColor(clWindowText); Colors.SelectionRectangleBlendColor := StyleServices.GetSystemColor(clHighlight); Colors.SelectionRectangleBorderColor := StyleServices.GetSystemColor(clHighlight); Colors.SelectionTextColor := Theme.GradientText; Colors.TreeLineColor := StyleServices.GetSystemColor(clBtnShadow); Colors.UnfocusedSelectionBorderColor := Theme.GradientToColor; Colors.UnfocusedSelectionColor := Theme.GradientFromColor; {$ENDIF} {$IFNDEF PHOTODB} Color := StyleServices.GetStyleColor(scTreeView); Font.Color := StyleServices.GetStyleFontColor(sfTreeItemTextNormal); Colors.BorderColor := StyleServices.GetSystemColor(clBtnFace); Colors.DisabledColor := StyleServices.GetSystemColor(clBtnShadow); Colors.DropMarkColor := StyleServices.GetSystemColor(clHighlight); Colors.FocusedSelectionBorderColor := StyleServices.GetSystemColor(clHighlight); Colors.FocusedSelectionColor := StyleServices.GetSystemColor(clHighlight); Colors.GridLineColor := StyleServices.GetSystemColor(clBtnFace); Colors.HotColor := StyleServices.GetSystemColor(clWindowText); Colors.SelectionRectangleBlendColor := StyleServices.GetSystemColor(clHighlight); Colors.SelectionRectangleBorderColor := StyleServices.GetSystemColor(clHighlight); Colors.SelectionTextColor := StyleServices.GetStyleFontColor(sfTreeItemTextSelected); Colors.TreeLineColor := StyleServices.GetSystemColor(clBtnShadow); Colors.UnfocusedSelectionColor := StyleServices.GetSystemColor(clBtnFace); Colors.UnfocusedSelectionBorderColor := StyleServices.GetSystemColor(clBtnFace); {$ENDIF} end; procedure TPathProvideTreeView.SelectPath(Path: string); var PI: TPathItem; begin PI := PathProviderManager.CreatePathItem(Path); try if PI <> nil then SelectPathItem(PI); finally F(PI); end; end; procedure TPathProvideTreeView.SelectPathItem(PathItem: TPathItem); var Data: PData; PathParts: TList<TPathItem>; PathPart: TPathItem; I: Integer; R: TRect; Node, ChildNode, SelectedNode: PVirtualNode; ChildData: TData; function FindChild(Node: PVirtualNode; PathItem: TPathItem): PVirtualNode; var Data: PData; S: string; begin Result := nil; S := ExcludeTrailingPathDelimiter(AnsiLowerCase(PathItem.Path)); Node := Node.FirstChild; while Node <> nil do begin Data := GetNodeData(Node); if ExcludeTrailingPathDelimiter(AnsiLowerCase(Data.Data.Path)) = S then Exit(Node); Node := Node.NextSibling; end; end; begin if not FIsStarted then begin F(FStartPathItem); FStartPathItem := PathItem.Copy; Exit; end; SelectedNode := GetFirstSelected; if SelectedNode <> nil then begin Data := GetNodeData(SelectedNode); if ExcludeTrailingPathDelimiter(AnsiLowerCase(Data.Data.Path)) = ExcludeTrailingPathDelimiter(AnsiLowerCase(PathItem.Path)) then Exit; end; if PathItem is THomeItem then begin ClearSelection; Exit; end; PathPart := PathItem; PathParts := TList<TPathItem>.Create; try while (PathPart <> nil) do begin PathParts.Insert(0, PathPart.Copy); PathPart := PathPart.Parent; end; Node := RootNode; BeginUpdate; try //skip home item for I := 1 to PathParts.Count - 1 do begin ChildNode := FindChild(Node, PathParts[I]); if ChildNode <> nil then begin Expanded[ChildNode] := True; if I = PathParts.Count - 1 then begin InternalSelectNode(ChildNode); R := GetDisplayRect(ChildNode, -1, False); InflateRect(R, -1, -1); if not (PtInRect(ClientRect, R.TopLeft) and PtInRect(ClientRect, R.BottomRight)) then TopNode := ChildNode; end; end else begin ChildData.Data := PathParts[I].Copy; ChildData.Data.Tag := FImageList.AddPathImage(ChildData.Data.ExtractImage, True); ChildNode := AddChild(Node, Pointer(ChildData)); ValidateNode(Node, False); InternalSelectNode(ChildNode); end; Node := ChildNode; end; finally EndUpdate; end; finally FreeList(PathParts); end; end; procedure TPathProvideTreeView.StartControl; begin if FStartPathItem <> nil then begin FIsStarted := True; SelectPathItem(FStartPathItem); F(FStartPathItem); end; end; procedure TPathProvideTreeView.WndProc(var Message: TMessage); begin if FBlockMouseMove then begin //popup hover fix if (Message.Msg = WM_ENABLE) or (Message.Msg = WM_SETFOCUS) or (Message.Msg = WM_KILLFOCUS) or (Message.Msg = WM_MOUSEMOVE) or (Message.Msg = WM_RBUTTONDOWN) or (Message.Msg = WM_RBUTTONUP) or (Message.Msg = WM_MOUSELEAVE) then Message.Msg := 0; end; inherited; end; procedure TPathProvideTreeView.LoadHomeDirectory(Form: TThreadForm); begin if not InitControl then Exit; FForm := Form; TThreadTask<TGUID>.Create(FForm, FState, False, procedure(Thread: TThreadTask<TGUID>; Data: TGUID) var Home: THomeItem; Roots: TPathItemCollection; Options: Integer; begin CoInitialize(nil); try Home := THomeItem.Create; try Roots := TPathItemCollection.Create; try Options := PATH_LOAD_DIRECTORIES_ONLY or PATH_LOAD_FOR_IMAGE_LIST or PATH_LOAD_CHECK_CHILDREN; if FOnlyFileSystem then Options := Options or PATH_LOAD_ONLY_FILE_SYSTEM; Home.Provider.FillChildList(Thread, Home, Roots, Options, 16, 2, procedure(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean) begin TThread.Synchronize(nil, procedure var I: Integer; begin if GOM.IsObj(Thread.ThreadForm) and (Data = FState) then begin for I := 0 to CurrentItems.Count - 1 do FHomeItems.Add(CurrentItems[I]); RootNodeCount := FHomeItems.Count; end; end ); CurrentItems.Clear; end ); TThread.Synchronize(nil, procedure begin if GOM.IsObj(Thread.ThreadForm) then StartControl; end ); finally F(Roots); end; finally F(Home); end; finally CoUninitialize; end; end ); end; procedure TPathProvideTreeView.RefreshPathItem(PathItem: TPathItem); var Node: PVirtualNode; begin Node := FindPathInTree(Self, GetFirstChild( nil ), AnsiLowerCase(ExcludeTrailingPathDelimiter(PathItem.Path))); if Node <> nil then begin DeleteChildren(Node, True); ReinitNode(Node, False); Expanded[Node] := True; end; end; procedure TPathProvideTreeView.Reload; begin FState := GetGUID; FIsStarted := False; FIsInitialized := False; Clear; RootNodeCount := 0; FHomeItems.FreeItems; FreeList(FNodesToDelete, False); LoadHomeDirectory(FForm); end; function TPathProvideTreeView.DoInitChildren(Node: PVirtualNode; var ChildCount: Cardinal): Boolean; var AInfo: TLoadChildsInfo; begin Result := inherited; AInfo := TLoadChildsInfo.Create; AInfo.Node := Node; AInfo.Data := GetNodeData(Node); AInfo.State := FState; Cursor := crAppStart; TThreadTask.Create(FForm, AInfo, procedure(Thread: TThreadTask; Data: Pointer) var Roots: TPathItemCollection; Info: TLoadChildsInfo; ParentItem: TPathItem; IsFirstItem: Boolean; Options: Integer; begin CoInitialize(nil); try Inc(FWaitOperationCount); Info := TLoadChildsInfo(Data); IsFirstItem := True; try Roots := TPathItemCollection.Create; try //copy item because this item could be freed on form close ParentItem := Info.Data.Data.Copy; try Options := PATH_LOAD_DIRECTORIES_ONLY or PATH_LOAD_FOR_IMAGE_LIST or PATH_LOAD_CHECK_CHILDREN; if FOnlyFileSystem then Options := Options or PATH_LOAD_ONLY_FILE_SYSTEM; ParentItem.Provider.FillChildList(Thread, ParentItem, Roots, Options, 16, 10, procedure(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean) begin Thread.Synchronize(nil, procedure var I: Integer; ChildData: TData; SearchPath: string; NodeData: PData; begin if GOM.IsObj(Thread.ThreadForm) and (Info.State = FState) then begin SearchPath := ''; if Info.Node.ChildCount > 0 then SearchPath := ExcludeTrailingPathDelimiter(AnsiLowerCase(PData(GetNodeData(Info.Node.FirstChild)).Data.Path)); //InterruptValidation; BeginUpdate; try for I := 0 to CurrentItems.Count - 1 do begin if SearchPath = ExcludeTrailingPathDelimiter(AnsiLowerCase(CurrentItems[I].Path)) then begin MoveTo(Info.Node.FirstChild, Info.Node, amAddChildLast, False); ValidateCache; NodeData := GetNodeData(Info.Node.LastChild); //node without image, shouldn't affect to GDI counter //this list will be deleted on destroy //without this line will be AV :( FNodesToDelete.Add(NodeData.Data); NodeData.Data := CurrentItems[I]; //image is required NodeData.Data.Image; NodeData.Data.Tag := FImageList.AddPathImage(NodeData.Data.ExtractImage, True); TopNode := GetFirstSelected; end else begin ChildData.Data := CurrentItems[I]; //image is required ChildData.Data.Image; ChildData.Data.Tag := FImageList.AddPathImage(ChildData.Data.ExtractImage, True); AddChild(Info.Node, Pointer(ChildData)); ValidateNode(Info.Node, False); end; end; if (CurrentItems.Count > 0) and IsFirstItem then begin IsFirstItem := False; Expanded[Node] := True; end; finally EndUpdate; end; end; end ); CurrentItems.Clear; end ); finally F(ParentItem); end; finally F(Roots); end; finally F(Info); TThread.Synchronize(nil, procedure begin if GOM.IsObj(Thread.ThreadForm) then begin Dec(FWaitOperationCount); if FWaitOperationCount = 0 then Cursor := crDefault; end; end ); end; finally CoUninitialize; end; end ); end; initialization TCustomStyleEngine.RegisterStyleHook(TPathProvideTreeView, TScrollingStyleHook); end.
unit Chapter05._04_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, AI.ListNode, DeepStar.Utils; // 24. Swap Nodes in Pairs // https://leetcode.com/problems/swap-nodes-in-pairs/description/ // 时间复杂度: O(n) // 空间复杂度: O(1) type TSolution = class(TObject) public function swapPairs(var head: TListNode): TListNode; end; procedure Main; implementation procedure Main; var head: TListNode; a: TArr_int; begin a := [1, 2, 3, 4]; head := TListNode.Create(a); WriteLn(head.ToString); with TSolution.Create do begin head := swapPairs(head); WriteLn(head.ToString); Free; end; head.CLearAndFree; end; { TSolution } function TSolution.swapPairs(var head: TListNode): TListNode; var dummyHead: TListNode; p, node1, node2, Next: TListNode; begin dummyHead := TListNode.Create(0); dummyHead.Next := head; p := dummyHead; while (p.Next <> nil) and (p.Next.Next <> nil) do begin node1 := p.Next; node2 := node1.Next; Next := node2.Next; node2.Next := node1; node1.Next := Next; p.Next := node2; p := node1; end; Result := dummyHead.Next; FreeAndNil(dummyHead); end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, uAssociativeArray, luaAssociativeArray, LuaWrapper; type { TfrmMain } TfrmMain = class(TForm) btnRead: TButton; btnWrite: TButton; edName: TEdit; edValue: TEdit; lblName: TLabel; lblValue: TLabel; procedure btnReadClick(Sender: TObject); procedure btnWriteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { private declarations } public { public declarations } ar : TAssociativeArray; lua: TLua; end; var frmMain: TfrmMain; implementation { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); begin ar := TAssociativeArray.Create; lua := TLua.Create(self); if FileExists(ExtractFilePath(ParamStr(0))+'script.lua') then begin RegisterAssociativeArray(Lua.LuaState); RegisterExistingAssociativeArray(lua.LuaState, ar, 'ar'); lua.LoadFile(ExtractFilePath(ParamStr(0))+'script.lua'); lua.Execute; end; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin ar.Free; end; procedure TfrmMain.btnReadClick(Sender: TObject); var v : Variant; begin if trim(edName.Text) = '' then exit; v := ar.Values[edName.Text]; if v <> NULL then edValue.Text := AnsiString(v) else edValue.Text := ''; end; procedure TfrmMain.btnWriteClick(Sender: TObject); begin if trim(edName.Text) = '' then exit; ar.Values[edName.Text] := edValue.Text; end; initialization {$I MainForm.lrs} end.
unit uOilQuery; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, MemDs, DBAccess, Ora,uOilStoredProc; type TOilQuery = class(TOraQuery) private FDatabaseName : String; FDataSrc: TDataSource; FRequestLive : Boolean; FUpdateMode : TUpdateMode; procedure SetDataSource(Value:TDataSource); protected public constructor Create(AOwner: TComponent); reintroduce; destructor Destroy; reintroduce; //procedure FetchAll; procedure Open; reintroduce; procedure GotoBookmark(Bookmark: TBookmark); reintroduce; published property DatabaseName : string read FDatabaseName write FDataBaseName; property DataSource : TDataSource read FDataSrc write SetDataSource; property RequestLive : boolean read FRequestLive write FRequestLive; property UpdateMode : TUpdateMode read FUpdateMode write FUpdateMode; end; procedure Register; implementation procedure Register; begin RegisterComponents('Oil', [TOilQuery]); RegisterComponents('Oil', [TOilStoredProc]); end; { TOilQuery } constructor TOilQuery.Create(AOwner: TComponent); begin inherited Create(AOwner); //FDataSrc := TOraDataSource.Create(Self); end; destructor TOilQuery.Destroy; begin FDataSrc.Free; inherited Destroy; end; {procedure TOilQuery.FetchAll; begin /// end;} procedure TOilQuery.GotoBookmark(Bookmark: TBookmark); begin if not IsEmpty then inherited GotoBookmark(Bookmark); end; procedure TOilQuery.Open; begin try Screen.Cursor := crSQLWait; //Application.ProcessMessages;//отпускает форму inherited Open; finally Screen.Cursor := crDefault; end; end; procedure TOilQuery.SetDataSource(Value : TDataSource); begin MasterSource := Value; FDataSrc :=Value; end; end.
unit uOilPanel; interface uses SysUtils, Classes, Controls, ExtCtrls, Messages; type TOilPanel = class(TPanel) private { Private declarations } FOnMouseLeave: TNotifyEvent; FOnMouseEnter: TNotifyEvent; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; protected { Protected declarations } public { Public declarations } published { Published declarations } property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; end; procedure Register; implementation procedure Register; begin RegisterComponents('Oil', [TOilPanel]); end; { TOilPanel } procedure TOilPanel.CMMouseEnter(var Message: TMessage); begin if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TOilPanel.CMMouseLeave(var Message: TMessage); begin if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; end.
Unit MTYPES; INTERFACE Var InitDef, HangDef : String; ComPort, ComPars : Byte; Const CR = #13+#10; COM1 = 0; { Communication ports } COM2 = 1; C110 = 0; { Speed in BPS of COMs } C150 = 32; C300 = 64; C600 = 96; C1200 = 128; C2400 = 160; C4800 = 192; C9600 = 224; CNON = 0; { Parity } CODD = 8; CEVEN = 24; CSTOP1 = 0; { Stop bits } CSTOP2 = 4; CDATA7 = 2; { Word length } CDATA8 = 3; EMPTY = -1; { Empty sign } OFF = 0; { Sign when DTR is off } ON = 1; { Sign when DTR is on } PAUSE = '~'; { Pause sign } HALFSEC = 500; { Pause length - HALF Second } lnTOUT = 128; { Time out } lnTSRE = 64; { Trans shift register empty } lnTHRE = 32; { Trans hold register empty } lnBREAK = 16; { Break detected } lnFRAME = 8; { Framing error } lnPRTYE = 4; { Parity error } lnOVRNE = 2; { Overrun error } lnDTRDY = 1; { Data ready status } mdCARR = 128; { Recived line signal detected (CARRIER)} mdRING = 64; { Ring indicator } mdDSR = 32; { Data set ready } mdCTS = 16; { Clear to send } mdDRLSD = 8; { Delta recived line signal detected } mdTERD = 4; { Trailing edge ring detector } mdDDSR = 2; { Delta data set ready } mdDCTS = 1; { Delta clear to send } msTOUT = 'Time out'; msTSRE = 'Trans shift register empty'; msTHRE = 'Trans hold register empty'; msBREAK = 'Break detected'; msFRAME = 'Framing error'; msPRTYE = 'Parity error'; msOVRNE = 'Overrun error'; msDTRDY = 'Data ready status'; msCARR = 'Carrier detected'; msRIGN = 'Ring indicator'; msDSR = 'Data set ready'; msCTS = 'Clear to send'; msDRLSD = 'Delta recived line signal detected'; msTERD = 'Trailing edge ring detector'; msDDSR = 'Delta data set ready'; msDCTS = 'Delta clear to send'; eiEXIST = 1; eiUNREG = 2; eiOK = 0; miEXIST = 'Already installed'; miUNREG = 'Unknow port'; miOK = 'Successful installed'; erREMOV = 1; erOK = 0; mrREMOV = 'Already removed or not installed'; mrOK = 'Successfule removed'; errmsg = 'Unknow error - Please contact author'; NULL = #0; BS = #8; { BacksSpace ( <- ) } FORMFEED= #12; ESC = #27; intc_mreg = $21; intc_creg = $20; EOI = $20; rcv_bufsize = 8192; snd_bufsize = 256; com1_port = $03f8; com2_port = $02f8; com1_int = $0c; com2_int = $0b; com1_mask = $10; com2_mask = $08; IMPLEMENTATION End.
unit uFrmBaseBtypeInput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmBaseInput, Menus, cxLookAndFeelPainters, ActnList, cxLabel, cxControls, cxContainer, cxEdit, cxCheckBox, StdCtrls, cxButtons, ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics, cxDropDownEdit, uParamObject, ComCtrls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, uDBComConfig, cxMemo; type TfrmBaseBtypeInput = class(TfrmBaseInput) edtFullname: TcxButtonEdit; edtUsercode: TcxButtonEdit; edtName: TcxButtonEdit; edtPYM: TcxButtonEdit; lbl2: TLabel; lbl1: TLabel; Label1: TLabel; lbl3: TLabel; edtAddress: TcxButtonEdit; lbl4: TLabel; edtTel: TcxButtonEdit; lbl5: TLabel; edtEMail: TcxButtonEdit; edtContact1: TcxButtonEdit; edtLinkerTel1: TcxButtonEdit; lbl6: TLabel; lbl7: TLabel; lbl8: TLabel; lbl15: TLabel; lbl16: TLabel; lbl17: TLabel; edtContact2: TcxButtonEdit; edtLinkerTel2: TcxButtonEdit; edtDefEtype: TcxButtonEdit; lbl18: TLabel; lbl19: TLabel; lbl20: TLabel; edtBankOfDeposit: TcxButtonEdit; edtBankAccounts: TcxButtonEdit; edtPostCode: TcxButtonEdit; lbl24: TLabel; lbl25: TLabel; lbl26: TLabel; edtFax: TcxButtonEdit; edtTaxNumber: TcxButtonEdit; edtRtypeid: TcxButtonEdit; chkStop: TcxCheckBox; grpComment: TGroupBox; mmComment: TcxMemo; protected { Private declarations } procedure SetFrmData(ASender: TObject; AList: TParamObject); override; procedure GetFrmData(ASender: TObject; AList: TParamObject); override; procedure ClearFrmData; override; public { Public declarations } procedure BeforeFormShow; override; class function GetMdlDisName: string; override; //得到模块显示名称 end; var frmBaseBtypeInput: TfrmBaseBtypeInput; implementation {$R *.dfm} uses uSysSvc, uBaseFormPlugin, uBaseInfoDef, uModelBaseTypeIntf, uModelControlIntf, uOtherIntf, uDefCom; { TfrmBasePtypeInput } procedure TfrmBaseBtypeInput.BeforeFormShow; begin SetTitle('单位信息'); FModelBaseType := IModelBaseTypePtype((SysService as IModelControl).GetModelIntf(IModelBaseTypeBtype)); FModelBaseType.SetParamList(ParamList); FModelBaseType.SetBasicType(btBtype); DBComItem.AddItem(edtFullname, 'Fullname', 'BFullname'); DBComItem.AddItem(edtUsercode, 'Usercode', 'BUsercode'); DBComItem.AddItem(edtName, 'Name', 'Name'); DBComItem.AddItem(edtPYM, 'Namepy', 'Bnamepy'); DBComItem.AddItem(mmComment, 'Comment', 'BComment'); DBComItem.AddItem(edtAddress, 'Address', 'Address'); DBComItem.AddItem(edtTel, 'Tel', 'Tel'); DBComItem.AddItem(edtEMail, 'EMail', 'EMail'); DBComItem.AddItem(edtContact1, 'Contact1', 'Contact1'); DBComItem.AddItem(edtContact2, 'Contact2', 'Contact2'); DBComItem.AddItem(edtLinkerTel1, 'LinkerTel1', 'LinkerTel1'); DBComItem.AddItem(edtLinkerTel2, 'LinkerTel2', 'LinkerTel2'); DBComItem.AddItem(edtDefEtype, 'DefEtype', 'DefEtype'); DBComItem.AddItem(edtBankOfDeposit, 'BankOfDeposit', 'BankOfDeposit'); DBComItem.AddItem(edtBankAccounts, 'BankAccounts', 'BankAccounts'); DBComItem.AddItem(edtPostCode, 'PostCode', 'PostCode'); DBComItem.AddItem(edtFax, 'Fax', 'Fax'); DBComItem.AddItem(edtTaxNumber, 'TaxNumber', 'TaxNumber'); DBComItem.AddItem(edtRtypeid, 'Rtypeid', 'Rtypeid'); DBComItem.AddItem(chkStop, 'IsStop', 'IsStop'); inherited; end; procedure TfrmBaseBtypeInput.ClearFrmData; begin inherited; end; procedure TfrmBaseBtypeInput.GetFrmData(ASender: TObject; AList: TParamObject); begin inherited; AList.Add('@Parid', ParamList.AsString('ParId')); DBComItem.SetDataToParam(AList); if FModelBaseType.DataChangeType in [dctModif] then begin AList.Add('@typeId', ParamList.AsString('CurTypeid')); end; end; class function TfrmBaseBtypeInput.GetMdlDisName: string; begin Result := '单位信息'; end; procedure TfrmBaseBtypeInput.SetFrmData(ASender: TObject; AList: TParamObject); begin inherited; DBComItem.GetDataFormParam(AList); end; end.
unit DSA.Tree.SetCompare; interface uses System.SysUtils, System.Classes, DSA.Interfaces.DataStructure, DSA.Tree.BSTSet, DSA.Tree.LinkedListSet, DSA.Utils, DSA.Tree.AVLTreeSet; procedure Main; implementation function testTime(newSet: ISet<string>; fileName: string): string; var startTime, endTime: Cardinal; words: TArrayList_str; i: Integer; begin startTime := TThread.GetTickCount; words := TArrayList_str.Create; Writeln(fileName + ':'); if TDsaUtils.ReadFile(FILE_PATH + fileName, words) then begin Writeln('Total words: ', words.GetSize); end; for i := 0 to words.GetSize - 1 do begin newSet.Add(words[i]); end; Writeln('Total different words: ', newSet.GetSize); endTime := TThread.GetTickCount; Result := FloatToStr((endTime - startTime) / 1000); end; type TBSTSet_str = TBSTSet<string>; TLinkListSet_str = TLinkedListSet<string>; TAVLTreeSet_str = TAVLTreeSet<string>; procedure Main; var vBSTSet: TBSTSet_str; vLinkListSet: TLinkListSet_str; vAVLTreeSet: TAVLTreeSet_str; fileName: string; vTime: string; begin fileName := A_FILE_NAME; vBSTSet := TBSTSet_str.Create; vTime := testTime(vBSTSet, fileName); Writeln('BSTSet, time: ' + vTime + ' s'); TDsaUtils.DrawLine; vLinkListSet := TLinkListSet_str.Create; vTime := testTime(vLinkListSet, fileName); Writeln('LinkedListSet, time: ' + vTime + ' s'); TDsaUtils.DrawLine; vAVLTreeSet := TAVLTreeSet_str.Create; vTime := testTime(vAVLTreeSet, fileName); Writeln('AVLTreeSet, time: ' + vTime + ' s'); end; end.
unit Pospolite.View.HTML.Layout; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.HTML.Document; type { TPLHTMLObjectLayouter } TPLHTMLObjectLayouter = packed class private FBody: TPLHTMLObject; procedure UpdateLayout; public constructor Create; destructor Destroy; override; property Body: TPLHTMLObject read FBody write FBody; end; TPLHTMLObjectLayoutManager = class; { TPLHTMLObjectLayoutThread } TPLHTMLObjectLayoutThread = class(TThread) private FManager: TPLHTMLObjectLayoutManager; FChange: TPLBool; public constructor Create(AManager: TPLHTMLObjectLayoutManager); procedure Execute; override; procedure UpdateLayout; procedure Annihilate; end; { TPLHTMLObjectLayoutManager } TPLHTMLObjectLayoutManager = class private FThread: TPLHTMLObjectLayoutThread; FDocument: TPLHTMLDocument; public constructor Create(const ADocument: TPLHTMLDocument); destructor Destroy; override; procedure StartLayouting; procedure StopLayouting; procedure Change; function IsWorking: TPLBool; inline; end; implementation { TPLHTMLObjectLayouter } procedure TPLHTMLObjectLayouter.UpdateLayout; begin if Assigned(FBody) then FBody.UpdateLayout; end; constructor TPLHTMLObjectLayouter.Create; begin inherited Create; // end; destructor TPLHTMLObjectLayouter.Destroy; begin // inherited Destroy; end; { TPLHTMLObjectLayoutThread } constructor TPLHTMLObjectLayoutThread.Create(AManager: TPLHTMLObjectLayoutManager); begin inherited Create(true); FManager := AManager; end; procedure TPLHTMLObjectLayoutThread.Execute; var delay: Cardinal = 500; begin FChange := true; while not Terminated and not Suspended do begin if FChange then begin FChange := false; Synchronize(@UpdateLayout); end; Sleep(delay); end; end; procedure TPLHTMLObjectLayoutThread.UpdateLayout; var lt: TPLHTMLObjectLayouter; begin lt := TPLHTMLObjectLayouter.Create; try lt.Body := FManager.FDocument.Body; lt.UpdateLayout; finally lt.Free; end; end; procedure TPLHTMLObjectLayoutThread.Annihilate; begin Suspended := true; Free; end; { TPLHTMLObjectLayoutManager } constructor TPLHTMLObjectLayoutManager.Create(const ADocument: TPLHTMLDocument); begin inherited Create; FThread := TPLHTMLObjectLayoutThread.Create(self); FDocument := ADocument; end; destructor TPLHTMLObjectLayoutManager.Destroy; begin FThread.Annihilate; inherited Destroy; end; procedure TPLHTMLObjectLayoutManager.StartLayouting; begin FThread.Start; end; procedure TPLHTMLObjectLayoutManager.StopLayouting; begin FThread.Annihilate; FThread := TPLHTMLObjectLayoutThread.Create(self); end; procedure TPLHTMLObjectLayoutManager.Change; begin FThread.FChange := true; end; function TPLHTMLObjectLayoutManager.IsWorking: TPLBool; begin Result := Assigned(FThread) and not FThread.Suspended; end; end.
unit LrGraphics; interface uses Types, Classes, Graphics; type TLrHAlign = ( haDefault, haLeft, haCenter, haRight ); TLrVAlign = ( vaDefault, vaTop, vaMiddle, vaBottom {, vaBaseline} ); function LrCalcPaintPosition( inW, inH, inPictureW, inPictureH: Integer; inHAlign: TLrHAlign; inVAlign: TLrVAlign): TPoint; procedure LrPaintPicture(inCanvas: TCanvas; inPicture: TPicture; inRect: TRect; inHAlign: TLrHAlign; inVAlign: TLrVAlign); procedure LrAspectPaintPicture(inCanvas: TCanvas; inPicture: TPicture; const inRect: TRect; inHAlign: TLrHAlign; inVAlign: TLrVAlign); function LrCalcAspectSize(inW, inH, inPictureW, inPictureH: Integer): TPoint; procedure LrBitmapToJpgStream(inBitmap: TBitmap; outStream: TStream); procedure LrTileGraphic(inCanvas: TCanvas; inR: TRect; inGraphic: TGraphic); procedure LrPaintRules(inCanvas: TCanvas; const inRect: TRect; inDivs: Integer = 32; inSubDivs: Boolean = true); implementation uses Jpeg, LrVclUtils; function LrCalcPaintPosition( inW, inH, inPictureW, inPictureH: Integer; inHAlign: TLrHAlign; inVAlign: TLrVAlign): TPoint; begin case inHAlign of haLeft: Result.x := 0; haDefault, haCenter: Result.x := (inW - inPictureW) div 2; haRight: Result.x := inW - inPictureW; end; case inVAlign of vaDefault, vaTop: Result.y := 0; vaMiddle: Result.y := (inH - inPictureH) div 2; vaBottom: Result.y := inH - inPictureH; end; end; procedure LrPaintPicture(inCanvas: TCanvas; inPicture: TPicture; inRect: TRect; inHAlign: TLrHAlign; inVAlign: TLrVAlign); var w, h: Integer; begin w := LrWidth(inRect); h := LrHeight(inRect); with LrCalcPaintPosition(w, h, inPicture.Width, inPicture.Height, inHAlign, inVAlign) do inCanvas.Draw(inRect.Left + X, inRect.Top + Y, inPicture.Graphic) end; procedure LrAspectPaintPicture(inCanvas: TCanvas; inPicture: TPicture; const inRect: TRect; inHAlign: TLrHAlign; inVAlign: TLrVAlign); var w, h: Integer; a: TPoint; r: TRect; begin w := LrWidth(inRect); h := LrHeight(inRect); a := LrCalcAspectSize(w, h, inPicture.Width, inPicture.Height); r := Rect(0, 0, a.X, a.Y); //inRect.Bottom := LrMin(inRect.Bottom, h + inRect.Top); with LrCalcPaintPosition(w, h, a.X, a.Y, inHAlign, inVAlign) do OffsetRect(r, inRect.Left + X, inRect.Top + Y); inCanvas.StretchDraw(r, inPicture.Graphic); end; function LrCalcAspectSize(inW, inH, inPictureW, inPictureH: Integer): TPoint; begin Result.X := inW; if (inPictureW = 0) or (inPictureH = 0) then Result.Y := 0 else begin Result.Y := inW * inPictureH div inPictureW; if Result.Y > inH then begin Result.Y := inH; Result.X := inH * inPictureW div inPictureH; end; end; end; procedure LrBitmapToJpgStream(inBitmap: TBitmap; outStream: TStream); var j: TJpegImage; begin j := TJpegImage.Create; with j do try Assign(inBitmap); SaveToStream(outStream); outStream.Position := 0; finally Free; end; end; procedure LrTileGraphic(inCanvas: TCanvas; inR: TRect; inGraphic: TGraphic); var i, j, l, t, w, h: Integer; begin if (inGraphic <> nil) and (not inGraphic.Empty) then with inR, inGraphic do begin w := (Right - Left + Width) div Width; h := (Bottom - Top + Height) div Height; t := Top; for j := 0 to h - 1 do begin l := Left; for i := 0 to w - 1 do begin inCanvas.Draw(l, t, inGraphic); Inc(l, Width); end; Inc(t, Height); end; end; end; procedure LrPaintRules(inCanvas: TCanvas; const inRect: TRect; inDivs: Integer; inSubDivs: Boolean); var d, d2, w, h, i: Integer; begin d := inDivs; d2 := inDivs div 2; w := (inRect.Right - inRect.Left + d - 1) div d; h := (inRect.Bottom - inRect.Top + d - 1) div d; with inCanvas do begin Pen.Style := psDot; for i := 0 to w do begin Pen.Color := $DDDDDD; MoveTo(i * d, inRect.Top); LineTo(i * d, inRect.Bottom); if inSubDivs then begin Pen.Color := $F0F0F0; MoveTo(i * d + d2, inRect.Top); LineTo(i * d + d2, inRect.Bottom); end; end; for i := 0 to h do begin Pen.Color := $DDDDDD; MoveTo(inRect.Left, i * d); LineTo(inRect.Right, i * d); if inSubDivs then begin Pen.Color := $F0F0F0; MoveTo(inRect.Left, i * d + d2); LineTo(inRect.Right, i * d + d2); end; end; end; end; end.
unit abApplication; interface uses Windows; type TProcedure = procedure; TApplication = class(TObject) private FStartup: TProcedure; FMain: TProcedure; FShutdown: TProcedure; FTerminated: boolean; function ProcessMessage(var Msg: TMsg): Boolean; protected public property Startup: TProcedure read FStartup write FStartup; property Main: TProcedure read FMain write FMain; property Shutdown: TProcedure read FShutdown write FShutdown; property Terminated: boolean read FTerminated write FTerminated; procedure StayResident; procedure Terminate; procedure ProcessMessages; end; implementation function TApplication.ProcessMessage(var Msg: TMsg): Boolean; begin Result := False; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := True; if Msg.Message <> $0012 then begin TranslateMessage(Msg); DispatchMessage(Msg); end else begin FTerminated := True; end; end; end; procedure TApplication.ProcessMessages; var Msg: TMsg; begin while ProcessMessage(Msg) do; end; procedure TApplication.Terminate; begin FTerminated := True; end; procedure TApplication.StayResident; var Msg: TMsg; begin if Assigned(FStartup) then FStartup; while not FTerminated do begin while ProcessMessage(Msg) do; Sleep(100); if Assigned(FMain) then FMain; end; if Assigned(FShutdown) then FShutdown; end; end.
unit DPM.IDE.SearchBarFrame; interface {$I ..\DPMIDE.inc} uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Themes, {$IFDEF USEIMAGECOLLECTION} Vcl.VirtualImageList, {$ENDIF} DPM.Core.Types, DPM.Core.Configuration.Interfaces, DPM.IDE.Types, DPM.IDE.Logger, DPM.IDE.Options, DPM.Controls.ButtonedEdit; type TConfigChangedEvent = procedure(const configuration : IConfiguration) of object; TPlatformChangedEvent = procedure(const newPlatform : TDPMPlatform) of object; TProjectSelectedEvent = procedure(const projectFile : string) of object; TSearchEvent = procedure(const searchText : string; const searchOptions : TDPMSearchOptions; const source : string; const platform : TDPMPlatform; const refresh : boolean) of object; TDPMSearchBarFrame = class(TFrame) DPMEditorViewImages: TImageList; DebounceTimer: TTimer; Panel1: TPanel; btnAbout: TButton; btnRefresh: TButton; btnSettings: TButton; cbPlatforms: TComboBox; cbSources: TComboBox; chkIncludeCommercial: TCheckBox; chkIncludePrerelease: TCheckBox; chkIncludeTrial: TCheckBox; lblPlatform: TLabel; lblSources: TLabel; txtSearch: TButtonedEdit; procedure txtSearchChange(Sender: TObject); procedure txtSearchRightButtonClick(Sender: TObject); procedure DebounceTimerTimer(Sender: TObject); procedure txtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnRefreshClick(Sender: TObject); procedure btnSettingsClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure chkIncludePrereleaseClick(Sender: TObject); procedure chkIncludeCommercialClick(Sender: TObject); procedure chkIncludeTrialClick(Sender: TObject); procedure cbSourcesChange(Sender: TObject); procedure cbPlatformsChange(Sender: TObject); private FDPMIDEOptions : IDPMIDEOptions; FConfigurationManager : IConfigurationManager; FConfiguration : IConfiguration; FLogger : IDPMIDELogger; FSearchHistFile : string; FConfigFile : string; FHasSources : boolean; FLoading : boolean; FPlatforms : TDPMPlatforms; FPlatform : TDPMPlatform; FProjects : TStringList; //events FOnSearchEvent : TSearchEvent; FOnConfigChanged : TConfigChangedEvent; FOnPlatformChangedEvent : TPlatformChangedEvent; FOnFocusList : TNotifyEvent; {$IFDEF USEIMAGECOLLECTION } FImageList : TVirtualImageList; {$ELSE} FImageList : TImageList; {$ENDIF} function GetSearchText: string; function GetIncludePreRelease: boolean; protected procedure AddDefaultSearchHistory; procedure ReloadSourcesCombo; procedure DoSearchEvent(const refresh : boolean); procedure DoPlatformChangedEvent(const newPlatform : TDPMPlatform); procedure Loaded; override; procedure SetImageList(const value : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF}); public constructor Create(AOwner : TComponent);override; destructor Destroy;override; procedure Configure(const logger : IDPMIDELogger; const ideOptions : IDPMIDEOptions; const config : IConfiguration; const configurationManager : IConfigurationManager; const configFile : string; const platforms : TDPMPlatforms); procedure UpdatePlatforms(const platforms : TDPMPlatforms); procedure SetPlatform(const platform : TDPMPlatform); function GetPlatform : TDPMPlatform; procedure ThemeChanged(const ideStyleServices : TCustomStyleServices); property HasSources : boolean read FHasSources; property SearchText : string read GetSearchText; property IncludePrerelease : boolean read GetIncludePreRelease; property Platform : TDPMPlatform read GetPlatform; property OnConfigChanged : TConfigChangedEvent read FOnConfigChanged write FOnConfigChanged; property OnSearch : TSearchEvent read FOnSearchEvent write FOnSearchEvent; property OnPlatformChanged : TPlatformChangedEvent read FOnPlatformChangedEvent write FOnPlatformChangedEvent; property OnFocusList : TNotifyEvent read FOnFocusList write FOnFocusList; property ImageList : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF} read FImageList write SetImageList; end; implementation {$R *.dfm} uses DPM.Core.Utils.Config, DPM.IDE.AddInOptionsHostForm, DPM.IDE.AboutForm; const cDMPSearchHistoryFile = 'packagesearch.txt'; procedure TDPMSearchBarFrame.AddDefaultSearchHistory; begin //some commonly used open source libs to get people started. txtSearch.ACStrings.Add('Spring4D.Core'); txtSearch.ACStrings.Add('Spring4D.Base'); txtSearch.ACStrings.Add('VSoft'); txtSearch.ACStrings.Add('VSoft.DUnitX'); txtSearch.ACStrings.Add('VSoft.DelphiMocks'); txtSearch.ACStrings.Add('Gabr42.OmniThreadLibrary'); end; procedure TDPMSearchBarFrame.btnAboutClick(Sender: TObject); var aboutForm : TDPMAboutForm; begin aboutForm := TDPMAboutForm.Create(nil); try aboutForm.ShowModal; finally aboutForm.Free; end; end; procedure TDPMSearchBarFrame.btnRefreshClick(Sender: TObject); begin DoSearchEvent(true); end; procedure TDPMSearchBarFrame.btnSettingsClick(Sender: TObject); var bReload : boolean; optionsHost : TDPMOptionsHostForm; begin optionsHost := TDPMOptionsHostForm.Create(Self, FConfigurationManager, FLogger, FDPMIDEOptions, FConfigFile); try bReload := optionsHost.ShowModal = mrOk; finally optionsHost.Free; end; if bReload then begin FConfiguration := FConfigurationManager.LoadConfig(FConfigFile); ReloadSourcesCombo; //Trigger onconfigchanged if Assigned(FOnConfigChanged) then FOnConfigChanged(FConfiguration); // // PackageDetailsFrame.Init(FContainer, FIconCache, FConfiguration, Self, FProject.FileName); // //populate the sources combo. end; end; procedure TDPMSearchBarFrame.cbPlatformsChange(Sender: TObject); begin if not FLoading then DoPlatformChangedEvent(StringToDPMPlatform(cbPlatforms.Items[cbPlatforms.ItemIndex])); end; procedure TDPMSearchBarFrame.cbSourcesChange(Sender: TObject); begin if not FLoading then DoSearchEvent(true); end; procedure TDPMSearchBarFrame.chkIncludeCommercialClick(Sender: TObject); begin DoSearchEvent(true); end; procedure TDPMSearchBarFrame.chkIncludePrereleaseClick(Sender: TObject); begin DoSearchEvent(true); end; procedure TDPMSearchBarFrame.chkIncludeTrialClick(Sender: TObject); begin DoSearchEvent(true); end; procedure TDPMSearchBarFrame.Configure(const logger: IDPMIDELogger; const ideOptions: IDPMIDEOptions; const config : IConfiguration; const configurationManager: IConfigurationManager; const configFile : string; const platforms : TDPMPlatforms); begin FLoading := true; FLogger := logger; FDPMIDEOptions := ideOptions; FConfiguration := config; FConfigurationManager := configurationManager; FConfigFile := configFile; FPlatforms := platforms; ReloadSourcesCombo; lblPlatform.Visible := true; UpdatePlatforms(FPlatforms); FLoading := false; end; constructor TDPMSearchBarFrame.Create(AOwner: TComponent); begin inherited; FProjects := TStringList.Create; ParentColor := false; ParentBackground := false; //not published in older versions, so get removed when we edit in older versions. {$IFDEF STYLEELEMENTS} StyleElements := [seFont]; chkIncludePrerelease.StyleElements := [seFont,seClient, seBorder]; {$ENDIF} Align := alTop; txtSearch.ACEnabled := true; txtSearch.ACOptions := [acAutoAppend, acAutoSuggest{, acUseArrowKey}]; txtSearch.ACSource := acsList; FSearchHistFile := TConfigUtils.GetDefaultDMPFolder + '\' + cDMPSearchHistoryFile; if FileExists(FSearchHistFile) then txtSearch.ACStrings.LoadFromFile(FSearchHistFile) else //some common packages to help with the search AddDefaultSearchHistory; FHasSources := false; end; procedure TDPMSearchBarFrame.DebounceTimerTimer(Sender: TObject); begin DebounceTimer.Enabled := false; DoSearchEvent(false); end; destructor TDPMSearchBarFrame.Destroy; begin FProjects.Free; inherited; end; procedure TDPMSearchBarFrame.DoPlatformChangedEvent(const newPlatform: TDPMPlatform); begin FPlatform := newPlatform; if Assigned(FOnPlatformChangedEvent) then FOnPlatformChangedEvent(newPlatform); end; procedure TDPMSearchBarFrame.DoSearchEvent(const refresh : boolean); var options : TDPMSearchOptions; source : string; platform : TDPMPlatform; begin if Assigned(FOnSearchEvent) then begin options := []; if chkIncludePrerelease.Checked then Include(options, TDPMSearchOption.IncludePrerelease); if chkIncludeCommercial.Checked then Include(options, TDPMSearchOption.IncludeCommercial); if chkIncludeTrial.Checked then Include(options, TDPMSearchOption.IncludeTrial); if cbSources.Items.Count > 0 then source := cbSources.Items[cbSources.ItemIndex] else source := 'All'; platform := StringToDPMPlatform(cbPlatforms.Items[cbPlatforms.ItemIndex]); FOnSearchEvent(txtSearch.Text, options, source, platform, refresh); end; end; function TDPMSearchBarFrame.GetIncludePreRelease: boolean; begin result := chkIncludePrerelease.Checked; end; function TDPMSearchBarFrame.GetPlatform: TDPMPlatform; begin if FPlatform = TDPMPlatform.UnknownPlatform then begin if cbPlatforms.Items.Count > 0 then FPlatform := StringToDPMPlatform(cbPlatforms.Items[cbPlatforms.ItemIndex]); end; result := FPlatform; end; function TDPMSearchBarFrame.GetSearchText: string; begin result := Trim(txtSearch.Text); end; procedure TDPMSearchBarFrame.Loaded; begin inherited; {$IF CompilerVersion >= 34.0 } // ParentBackground := false; // ParentColor := false; {$IFEND} end; procedure TDPMSearchBarFrame.ReloadSourcesCombo; var sCurrent : string; source : ISourceConfig; idx : integer; begin FLoading := true; try if cbSources.Items.Count > 0 then sCurrent := cbSources.Items[cbSources.ItemIndex]; cbSources.Clear; cbSources.Items.Add('All'); if FConfiguration.Sources.Any then begin for source in FConfiguration.Sources do begin if source.IsEnabled then begin cbSources.Items.Add(source.Name); FHasSources := true; end; end; end else FHasSources := false; if sCurrent <> '' then begin idx := cbSources.Items.IndexOf(sCurrent); if idx <> -1 then cbSources.ItemIndex := idx else cbSources.ItemIndex := 0; end; finally FLoading := false; end; end; procedure TDPMSearchBarFrame.SetImageList(const value : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF}); begin FImageList := value; if FImageList <> nil then begin // txtSearch.RightButton.DisabledImageIndex = 0 txtSearch.RightButton.ImageIndex := 7; txtSearch.RightButton.HotImageIndex := 8; txtSearch.Images := FImageList; btnRefresh.ImageIndex := 4; btnRefresh.Images := FImageList; btnSettings.ImageIndex := 6; btnSettings.Images := FImageList; btnAbout.ImageIndex := 5; btnAbout.Images := FImageList; end; end; procedure TDPMSearchBarFrame.SetPlatform(const platform: TDPMPlatform); begin FPlatform := platform; end; procedure TDPMSearchBarFrame.ThemeChanged(const ideStyleServices : TCustomStyleServices); begin //{$IF CompilerVersion < 34.0 } Self.Color := ideStyleServices.GetSystemColor(clBtnFace); Self.Font.Color := ideStyleServices.GetSystemColor(clWindowText); //{$IFEND} end; procedure TDPMSearchBarFrame.txtSearchChange(Sender: TObject); begin txtSearch.RightButton.Visible := txtSearch.Text <> ''; end; procedure TDPMSearchBarFrame.txtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i : integer; begin DebounceTimer.Enabled := false; case key of VK_RETURN : begin i := txtSearch.ACStrings.IndexOf(txtSearch.Text); if i = -1 then txtSearch.ACStrings.Insert(0, txtSearch.Text) else txtSearch.ACStrings.Move(i, 0); try txtSearch.ACStrings.SaveToFile(FSearchHistFile); except //ignore the error, not much we can do? //perhaps log it? end; DebounceTimerTimer(DebounceTimer); end; VK_ESCAPE : begin if txtSearch.Text <> '' then begin txtSearch.Text := ''; DebounceTimerTimer(DebounceTimer); end; end; VK_DOWN : begin //send focus to list if Assigned(FOnFocusList) then begin FOnFocusList(self); Key := 0; end; end else DebounceTimer.Enabled := true; end; end; procedure TDPMSearchBarFrame.txtSearchRightButtonClick(Sender: TObject); begin txtSearch.Text := ''; DoSearchEvent(true); end; procedure TDPMSearchBarFrame.UpdatePlatforms(const platforms: TDPMPlatforms); var platform : TDPMPlatform; currentPlatform : TDPMPlatform; i : integer; begin //preserve the currently selected platform if cbPlatforms.Items.Count > 0 then currentPlatform := TDPMPlatform(Integer(cbPlatforms.Items.Objects[cbPlatforms.ItemIndex])) else currentPlatform := TDPMPlatform.UnknownPlatform; cbPlatforms.Items.Clear; for platform in FPlatforms do cbPlatforms.Items.AddObject(DPMPlatformToString(platform), TObject(Ord(platform))); i := 0; if currentPlatform <> TDPMPlatform.UnknownPlatform then i := cbPlatforms.Items.IndexOfObject(TObject(Ord(currentPlatform))); if cbPlatforms.Items.Count > 0 then cbPlatforms.ItemIndex := i; end; end.
unit uModSetupPOS; interface uses uModApp, uModUnit; type TModSetupPOS = class(TModApp) private FAUTUNIT: TModUnit; FSETUPPOS_COUNTER_NO: Integer; FSETUPPOS_DATE: TDateTime; FSETUPPOS_IP: string; FSETUPPOS_IS_ACTIVE: Integer; FSETUPPOS_IS_RESET: Integer; FSETUPPOS_NO_TRANSAKSI: string; FSETUPPOS_TERMINAL_CODE: string; published [AttributeOfForeign('AUT$UNIT_ID')] property AUTUNIT: TModUnit read FAUTUNIT write FAUTUNIT; property SETUPPOS_COUNTER_NO: Integer read FSETUPPOS_COUNTER_NO write FSETUPPOS_COUNTER_NO; property SETUPPOS_DATE: TDateTime read FSETUPPOS_DATE write FSETUPPOS_DATE; property SETUPPOS_IP: string read FSETUPPOS_IP write FSETUPPOS_IP; property SETUPPOS_IS_ACTIVE: Integer read FSETUPPOS_IS_ACTIVE write FSETUPPOS_IS_ACTIVE; property SETUPPOS_IS_RESET: Integer read FSETUPPOS_IS_RESET write FSETUPPOS_IS_RESET; property SETUPPOS_NO_TRANSAKSI: string read FSETUPPOS_NO_TRANSAKSI write FSETUPPOS_NO_TRANSAKSI; property SETUPPOS_TERMINAL_CODE: string read FSETUPPOS_TERMINAL_CODE write FSETUPPOS_TERMINAL_CODE; end; implementation initialization TModSetupPOS.RegisterRTTI; end.
unit HCEmrViewLite; interface uses Classes, SysUtils, HCViewLite, HCCustomData, HCItem; type THCImportAsTextEvent = procedure (const AText: string) of object; THCEmrViewLite = class(THCViewLite) private FPropertys: TStringList; protected /// <summary> 当有新Item创建时触发 </summary> /// <param name="AData">创建Item的Data</param> /// <param name="AStyleNo">要创建的Item样式</param> /// <returns>创建好的Item</returns> function DoSectionCreateStyleItem(const AData: THCCustomData; const AStyleNo: Integer): THCCustomItem; override; /// <summary> 读取文档前触发事件,便于确认订制特征数据 </summary> procedure DoLoadStreamBefor(const AStream: TStream; const AFileVersion: Word); override; /// <summary> 保存文档前触发事件,便于订制特征数据 </summary> procedure DoSaveStreamBefor(const AStream: TStream); override; procedure DoSaveMutMargin(const AStream: TStream); override; procedure DoLoadMutMargin(const AStream: TStream; const AStyle: THCStyle; const AFileVersion: Word); override; public constructor Create; override; destructor Destroy; override; /// <summary> 遍历Item </summary> /// <param name="ATraverse">遍历时信息</param> procedure TraverseItem(const ATraverse: THCItemTraverse); end; implementation uses HCEmrElementItem, HCEmrGroupItem, HCTextItem, HCRectItem, HCCommon, HCSectionData; { THCEmrViewLite } constructor THCEmrViewLite.Create; begin HCDefaultTextItemClass := TDeItem; HCDefaultDomainItemClass := TDeGroup; inherited Create; FPropertys := TStringList.Create; end; destructor THCEmrViewLite.Destroy; begin FreeAndNil(FPropertys); inherited Destroy; end; procedure THCEmrViewLite.DoLoadMutMargin(const AStream: TStream; const AStyle: THCStyle; const AFileVersion: Word); var vByte: Byte; i: Integer; begin if AFileVersion > 61 then begin AStream.ReadBuffer(i, SizeOf(i)); AStream.ReadBuffer(i, SizeOf(i)); AStream.ReadBuffer(i, SizeOf(i)); AStream.ReadBuffer(vByte, SizeOf(vByte)); end; end; procedure THCEmrViewLite.DoLoadStreamBefor(const AStream: TStream; const AFileVersion: Word); var vVersion: Byte; vS: string; begin if AFileVersion > 43 then AStream.ReadBuffer(vVersion, 1) else vVersion := 0; if vVersion > 0 then begin HCLoadTextFromStream(AStream, vS, AFileVersion); if Self.Style.States.Contain(hosLoading) then // 加载病历时才处理,插入文件流时不覆盖 FPropertys.Text := vS; end else if Self.Style.States.Contain(hosLoading) then // 加载病历时才处理,插入文件流时不覆盖 FPropertys.Clear; inherited DoLoadStreamBefor(AStream, AFileVersion); end; procedure THCEmrViewLite.DoSaveMutMargin(const AStream: TStream); var vByte: Byte; i: Integer; begin i := -1; AStream.WriteBuffer(i, SizeOf(i)); AStream.WriteBuffer(i, SizeOf(i)); AStream.WriteBuffer(i, SizeOf(i)); vByte := 0; AStream.WriteBuffer(vByte, SizeOf(vByte)); end; procedure THCEmrViewLite.DoSaveStreamBefor(const AStream: TStream); var vByte: Byte; begin vByte := EmrViewVersion; AStream.WriteBuffer(vByte, SizeOf(vByte)); HCSaveTextToStream(AStream, FPropertys.Text); inherited DoSaveStreamBefor(AStream); end; function THCEmrViewLite.DoSectionCreateStyleItem(const AData: THCCustomData; const AStyleNo: Integer): THCCustomItem; begin Result := HCEmrElementItem.CreateEmrStyleItem(aData, aStyleNo); end; procedure THCEmrViewLite.TraverseItem(const ATraverse: THCItemTraverse); var i: Integer; begin if ATraverse.Areas = [] then Exit; for i := 0 to Self.Sections.Count - 1 do begin if not ATraverse.Stop then begin with Self.Sections[i] do begin if saHeader in ATraverse.Areas then Header.TraverseItem(ATraverse); if (not ATraverse.Stop) and (saPage in ATraverse.Areas) then Page.TraverseItem(ATraverse); if (not ATraverse.Stop) and (saFooter in ATraverse.Areas) then Footer.TraverseItem(ATraverse); end; end; end; end; end.
unit Embedded_GUI_ARM_Common; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, LCLType, Controls, ProjectIntf, Embedded_GUI_Common, Embedded_GUI_Embedded_List_Const; // Unit wird von "./Tools/Ebedded_List_to_const" generiert. type { TARM_ProjectOptions } TARM_ProjectOptions = class stlink_Command: record Path, FlashBase: string; end; ARM_SubArch, ARM_FPC_Typ: string; AsmFile: boolean; procedure Save_to_Project(AProject: TLazProject); procedure Load_from_Project(AProject: TLazProject); end; type TARM_TemplatesPara = record Name, ARM_SubArch, ARM_FPC_Typ, FlashBase: string; end; const ARM_TemplatesPara: array of TARM_TemplatesPara = (( Name: 'STM32F103X8'; ARM_SubArch: 'ARMV7M'; ARM_FPC_Typ: 'STM32F103X8'; FlashBase: '0x08000000'; ), ( Name: 'Arduino DUE'; ARM_SubArch: 'ARMV7M'; ARM_FPC_Typ: 'ATSAM3X8E'; FlashBase: '0x080000')); var ARM_ProjectOptions: TARM_ProjectOptions; implementation { TARM_ProjectOptions } procedure TARM_ProjectOptions.Save_to_Project(AProject: TLazProject); var s: string; begin with AProject.LazCompilerOptions do begin TargetCPU := 'arm'; TargetOS := 'embedded'; TargetProcessor := ARM_SubArch; CustomOptions := '-Wp' + ARM_FPC_Typ; if AsmFile then begin CustomOptions := CustomOptions + LineEnding + '-al'; end; end; s := stlink_Command.Path + ' write ' + AProject.LazCompilerOptions.TargetFilename + '.bin ' + stlink_Command.FlashBase; AProject.LazCompilerOptions.ExecuteAfter.Command := s; end; procedure TARM_ProjectOptions.Load_from_Project(AProject: TLazProject); var s: string; function Find(const Source: string; const Sub: string): string; var p, Index: integer; begin p := pos(Sub, Source); Result := ''; if p > 0 then begin p += Length(Sub); Index := p; while (Index <= Length(Source)) and (s[Index] > #32) do begin Result += Source[Index]; Inc(Index); end; end; end; begin ARM_SubArch := AProject.LazCompilerOptions.TargetProcessor; s := AProject.LazCompilerOptions.CustomOptions; AsmFile := Pos('-al', s) > 0; ARM_FPC_Typ := Find(s, '-Wp'); s := AProject.LazCompilerOptions.ExecuteAfter.Command; stlink_Command.Path := Copy(s, 0, pos(' ', s) - 1); stlink_Command.FlashBase := '0x' + Find(s, '0x'); end; end.
unit uFuncoes; interface uses Classes, SysUtils, DBXJSON, IdHTTP, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdMessage, IdSSL, IdText, IdAttachmentFile, Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc; procedure ValidaCEP(cep: string); procedure CarregaCep; procedure LimpaDados; procedure EnviaEmail(Path: string); procedure MontaXML(Path: String); var jsonObject: TJsonObject; Logad: string; Comp: string; Bairro: string; Cidade: string; UF: String; Valido: Boolean; implementation uses uCad; procedure ValidaCEP(cep: string); var HTTP: TIdHTTP; IDSSLHandler: TIdSSLIOHandlerSocketOpenSSL; Resp: TStringStream; strRetorno: string; begin Valido := True; try HTTP := TIdHTTP.Create; IDSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create; HTTP.IOHandler := IDSSLHandler; Resp := TStringStream.Create(''); HTTP.Get('https://viacep.com.br/ws/' + cep + '/json', Resp); jsonObject := TJsonObject.Create; if (HTTP.ResponseCode = 200) and not(Utf8ToAnsi(Resp.DataString) = '{'#$A' "erro": true'#$A'}') then begin jsonObject := TJsonObject.ParseJSONValue (TEncoding.ASCII.GetBytes(Utf8ToAnsi(Resp.DataString)), 0) as TJsonObject; CarregaCep; end else begin LimpaDados; end; finally FreeAndNil(HTTP); FreeAndNil(IDSSLHandler); Resp.Destroy end; end; procedure CarregaCep; begin frmCad.edLogad.Text := jsonObject.Get(1).JsonValue.Value; frmCad.edCidade.Text := jsonObject.Get(4).JsonValue.Value; frmCad.edBairro.Text := jsonObject.Get(3).JsonValue.Value; frmCad.edUf.Text := jsonObject.Get(5).JsonValue.Value; frmCad.edComp.Text := jsonObject.Get(2).JsonValue.Value; end; procedure LimpaDados; begin frmCad.edLogad.Clear; frmCad.edCidade.Clear; frmCad.edBairro.Clear; frmCad.edUf.Clear; frmCad.edComp.Clear; end; procedure EnviaEmail(Path: string); var IDSSLHandler: TIdSSLIOHandlerSocketOpenSSL; IdSMTP: TIdSMTP; IdMessage: TIdMessage; IdText: TIdText; sAnexo: string; begin IDSSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create; IdSMTP := TIdSMTP.Create; IdMessage := TIdMessage.Create; try IDSSLHandler.SSLOptions.Method := sslvSSLv23; IDSSLHandler.SSLOptions.Mode := sslmClient; IdSMTP.IOHandler := IDSSLHandler; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Port := 465; IdSMTP.Host := 'smtp.gmail.com'; IdSMTP.Username := 'Usuario@gmai.com'; IdSMTP.Password := 'Senha'; // Configuração da mensagem (TIdMessage) IdMessage.From.Address := 'Usuario@gmail.com'; IdMessage.From.Name := frmCad.edtNome.Text; IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address; IdMessage.Recipients.Add.Text := frmCad.edEmail.Text; IdMessage.Subject := 'Cadstro de Cliente'; IdMessage.Encoding := meMIME; // Configuração do corpo do email (TIdText) IdText := TIdText.Create(IdMessage.MessageParts); IdText.Body.Add('Dados Cadastrais:'); IdText.Body.Add('Nome: ' + frmCad.edtNome.Text); IdText.Body.Add('RG: ' + frmCad.edId.Text); IdText.Body.Add('CPF: ' + frmCad.edCpf.Text); IdText.Body.Add('Celular: ' + frmCad.edTel.Text); IdText.Body.Add('Email: ' + frmCad.edEmail.Text); IdText.Body.Add('CEP: ' + frmCad.edCep.Text); IdText.Body.Add('Logadouro: ' + frmCad.edLogad.Text); IdText.Body.Add('Número: ' + frmCad.edNum.Text); IdText.Body.Add('Complemento: ' + frmCad.edComp.Text); IdText.Body.Add('Bairro: ' + frmCad.edBairro.Text); IdText.Body.Add('Cidade: ' + frmCad.edCidade.Text); IdText.Body.Add('UF: ' + frmCad.edUf.Text); IdText.Body.Add('Pais: ' + frmCad.edPais.Text); IdText.ContentType := 'text/plain; charset=iso-8859-1'; // Anexo da mensagem (TIdAttachmentFile) sAnexo := Path; if FileExists(sAnexo) then begin TIdAttachmentFile.Create(IdMessage.MessageParts, sAnexo); end; // Conexão e autenticação try IdSMTP.Connect; IdSMTP.Authenticate; except on E: Exception do begin MessageDlg('Erro na conexão ou autenticação: ' + E.Message, mtWarning, [mbOK], 0); Exit; end; end; // Envio da mensagem try IdSMTP.Send(IdMessage); MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0); except On E: Exception do begin MessageDlg('Erro ao enviar a mensagem: ' + E.Message, mtWarning, [mbOK], 0); end; end; finally IdSMTP.Disconnect; UnLoadOpenSSLLibrary; FreeAndNil(IdMessage); FreeAndNil(IDSSLHandler); FreeAndNil(IdSMTP); end; end; procedure MontaXML(Path: String); var doc: TXMLDocument; Raiz, Nome, Rg, Cpf, Cel, Email, cep, Logad, Num, Comp, Bairro, Cidade, UF, Pais, Ver, PowerBy: IXMLNode; begin doc.FileName := ''; doc.XML.Text := ''; doc.Active := False; doc.Active := True; doc.Version := '1.0'; doc.Encoding := 'UTF-8'; // RAIZ Raiz := doc.AddChild('Registros'); Nome := doc.CreateNode('NOME', ntElement); Nome.Text := frmCad.edtNome.Text; Raiz.ChildNodes.Add(Nome); Rg := doc.CreateNode('RG', ntElement); Rg.Text := frmCad.edId.Text; Raiz.ChildNodes.Add(Rg); Cpf := doc.CreateNode('CPF', ntElement); Cpf.Text := frmCad.edCpf.Text; Raiz.ChildNodes.Add(Cpf); Cel := doc.CreateNode('CELULAR', ntElement); Cel.Text := frmCad.edTel.Text; Raiz.ChildNodes.Add(Cel); Email := doc.CreateNode('EMAIL', ntElement); Email.Text := frmCad.edEmail.Text; Raiz.ChildNodes.Add(Email); cep := doc.CreateNode('Cep', ntElement); cep.Text := frmCad.edCep.Text; Raiz.ChildNodes.Add(cep); Logad := doc.CreateNode('LOGADOURO', ntAttribute); Logad.Text := frmCad.edLogad.Text; cep.AttributeNodes.Add(Logad); Num := doc.CreateNode('NUMERO', ntAttribute); Num.Text := frmCad.edNum.Text; cep.AttributeNodes.Add(Num); Comp := doc.CreateNode('COMPLEMENTO', ntAttribute); Comp.Text := frmCad.edComp.Text; cep.AttributeNodes.Add(Comp); Bairro := doc.CreateNode('BAIRRO', ntAttribute); Bairro.Text := frmCad.edBairro.Text; cep.AttributeNodes.Add(Bairro); Cidade := doc.CreateNode('CIDADE', ntAttribute); Cidade.Text := frmCad.edCidade.Text; cep.AttributeNodes.Add(Cidade); UF := doc.CreateNode('UF', ntAttribute); UF.Text := frmCad.edUf.Text; cep.AttributeNodes.Add(UF); Pais := doc.CreateNode('PAIS', ntAttribute); Pais.Text := frmCad.edPais.Text; cep.AttributeNodes.Add(Pais); doc.SaveToFile(Path); doc.Active := False; end; end.
unit MobQueries; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} Mob, QueryBase, {3rd Party} ZSqlUpdate ; //------------------------------------------------------------------------------ //TMobQueries CLASS //------------------------------------------------------------------------------ type TMobQueries = class(TQueryBase) protected public function Load( const AnMob : TMob ):Boolean; end; implementation uses GameConstants, ZDataset, DB; //------------------------------------------------------------------------------ //Load PROCEDURE //------------------------------------------------------------------------------ // What it does- // Load mob data by ID/sprite name // // Changes - // [03/24/2008] Aeomin - Forged. // //------------------------------------------------------------------------------ function TMobQueries.Load( const AnMob : TMob ):Boolean; const AQuery = //Changed Query Code slightly to conform with sql. [Spre] 'SELECT `id`, `sprite_name`, `name`, `range` , `LV`, `HP`, `SP`, `str`, `int`, `vit`, `dex`, `agi`, `luk`, '+ '`attack_rating_min`, `attack_rating_max`, `def`, `exp`, `jexp`, `as`, `es`, `move_speed`, `attackedmt`, `attackmt`, ' + '`property`, `scale`, `race`, `mdef`, `taming_item`, `food_item` ' + 'FROM mobs'; var ADataSet : TZQuery; AParam : TParam; WhereClause : String; begin Result := False; if AnMob.JID > 0 then begin WhereClause := ' WHERE id=:ID;'; end else begin WhereClause := ' WHERE sprite_name=:Name;' end; ADataSet := TZQuery.Create(nil); //ID AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput); AParam.AsInteger := AnMob.JID; ADataSet.Params.AddParam( AParam ); //Name AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput); AParam.AsString := AnMob.SpriteName; ADataSet.Params.AddParam( AParam ); try Query(ADataSet, AQuery+WhereClause); ADataSet.First; if NOT ADataSet.Eof then begin with AnMob do begin JID := ADataSet.Fields[0].AsInteger; SpriteName := ADataSet.Fields[1].AsString; Name := ADataSet.Fields[2].AsString; AttackRange := ADataSet.Fields[3].AsInteger; BaseLV := ADataSet.Fields[4].AsInteger; MaxHP := ADataSet.Fields[5].AsInteger; MaxSP := ADataSet.Fields[6].AsInteger; ParamBase[STR] := ADataSet.Fields[7].AsInteger; ParamBase[AGI] := ADataSet.Fields[8].AsInteger; ParamBase[VIT] := ADataSet.Fields[9].AsInteger; ParamBase[INT] := ADataSet.Fields[10].AsInteger; ParamBase[DEX] := ADataSet.Fields[11].AsInteger; ParamBase[LUK] := ADataSet.Fields[12].AsInteger; //Attack_Rating_min and Max Fields below [Spre] MinimumHit := ADataSet.Fields[13].AsInteger; MaximumHit := ADataSet.Fields[14].AsInteger; Defense := ADataSet.Fields[15].AsInteger; BaseExp := ADataSet.Fields[16].AsInteger; JobExp := ADataSet.Fields[17].AsInteger; ASpeed := ADataSet.Fields[18].AsInteger; //as = AttackSpeed [Spre] EnemySight := ADataSet.Fields[19].AsInteger; //es - Reports say Enemy SIGHT Speed := ADataSet.Fields[20].AsInteger; AttackDmgTime := ADataSet.Fields[21].AsInteger; // Attack Damage Delay [Spre] Attack_Motion := ADataSet.Fields[22].AsInteger; // Attack Motion Delay [Spre] Scale := ADataSet.Fields[23].AsInteger; Element := ADataSet.Fields[24].AsInteger; // Monster Property Race := ADataSet.Fields[25].AsInteger; MDef := ADataSet.Fields[26].AsInteger; TamingItem := ADataSet.Fields[27].AsInteger; FoodItem := ADataSet.Fields[28].AsInteger; end; Result := True; end; finally ADataSet.Free; end; end;{Load} //------------------------------------------------------------------------------ end.
// // Generated by JavaToPas v1.4 20140526 - 133246 //////////////////////////////////////////////////////////////////////////////// unit javax.xml.transform.TransformerException; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, javax.xml.transform.SourceLocator; type JTransformerException = interface; JTransformerExceptionClass = interface(JObjectClass) ['{DDBB0319-0DA7-46DA-8FE3-65D3516D1043}'] function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getException : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getLocationAsString : JString; cdecl; // ()Ljava/lang/String; A: $1 function getLocator : JSourceLocator; cdecl; // ()Ljavax/xml/transform/SourceLocator; A: $1 function getMessageAndLocation : JString; cdecl; // ()Ljava/lang/String; A: $1 function init(&message : JString) : JTransformerException; cdecl; overload; // (Ljava/lang/String;)V A: $1 function init(&message : JString; e : JThrowable) : JTransformerException; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Throwable;)V A: $1 function init(&message : JString; locator : JSourceLocator) : JTransformerException; cdecl; overload;// (Ljava/lang/String;Ljavax/xml/transform/SourceLocator;)V A: $1 function init(&message : JString; locator : JSourceLocator; e : JThrowable) : JTransformerException; cdecl; overload;// (Ljava/lang/String;Ljavax/xml/transform/SourceLocator;Ljava/lang/Throwable;)V A: $1 function init(e : JThrowable) : JTransformerException; cdecl; overload; // (Ljava/lang/Throwable;)V A: $1 function initCause(cause : JThrowable) : JThrowable; cdecl; // (Ljava/lang/Throwable;)Ljava/lang/Throwable; A: $21 procedure printStackTrace ; cdecl; overload; // ()V A: $1 procedure printStackTrace(s : JPrintStream) ; cdecl; overload; // (Ljava/io/PrintStream;)V A: $1 procedure printStackTrace(s : JPrintWriter) ; cdecl; overload; // (Ljava/io/PrintWriter;)V A: $1 procedure setLocator(location : JSourceLocator) ; cdecl; // (Ljavax/xml/transform/SourceLocator;)V A: $1 end; [JavaSignature('javax/xml/transform/TransformerException')] JTransformerException = interface(JObject) ['{39CBDE54-CF32-4896-A142-96C98EB952EA}'] function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getException : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1 function getLocationAsString : JString; cdecl; // ()Ljava/lang/String; A: $1 function getLocator : JSourceLocator; cdecl; // ()Ljavax/xml/transform/SourceLocator; A: $1 function getMessageAndLocation : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure printStackTrace ; cdecl; overload; // ()V A: $1 procedure printStackTrace(s : JPrintStream) ; cdecl; overload; // (Ljava/io/PrintStream;)V A: $1 procedure printStackTrace(s : JPrintWriter) ; cdecl; overload; // (Ljava/io/PrintWriter;)V A: $1 procedure setLocator(location : JSourceLocator) ; cdecl; // (Ljavax/xml/transform/SourceLocator;)V A: $1 end; TJTransformerException = class(TJavaGenericImport<JTransformerExceptionClass, JTransformerException>) end; implementation end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Packaging.Archive.Reader; interface uses System.Classes, System.Zip, DPM.Core.Types, DPM.Core.Packaging.Archive; //not used //type // TZipFileArchiveReader = class(TInterfacedObject, IPackageArchiveReader) // private // FFileName : string; // FZipFile : TZipFile; // FPackageMetaFile : string; // FLastError : string; // FVersion : TPackageVersion; // protected // function Exists : Boolean; // function GetArchiveName : string; // function GetArchivePath : string; // function IsArchive : Boolean; // function Open(const fileName : string) : Boolean; // procedure Close; // // function GetLastErrorString : string; // function GetPackageVersion : TPackageVersion; // // function ReadFileNames : TArray<string>; // function ReadMetaDataFile(const stream : TStream) : Boolean; // function ExtractFileTo(const fileName : string; const destFileName : string) : boolean; // function ExtractTo(const path : string) : boolean; // // public // constructor Create; // destructor Destroy; override; // // end; // // TFolderArchiveReader = class(TInterfacedObject, IPackageArchiveReader) // private // FFolderName : string; // FPackageMetaFile : string; // FLastError : string; // FVersion : TPackageVersion; // protected // function Exists : Boolean; // function GetArchiveName : string; // function GetArchivePath : string; // function IsArchive : Boolean; // function Open(const fileName : string) : Boolean; // procedure Close; // function GetLastErrorString : string; // function GetPackageVersion : TPackageVersion; // // function ReadFileNames : System.TArray<System.string>; // function ReadMetaDataFile(const stream : TStream) : Boolean; // function ExtractFileTo(const fileName : string; const destFileName : string) : boolean; // function ExtractTo(const path : string) : Boolean; // // public // constructor Create; // destructor Destroy; override; // // end; // implementation uses System.IOUtils, System.SysUtils, DPM.Core.Constants; //{ TZieFileArchiveReader } // //procedure TZipFileArchiveReader.Close; //begin // if FZipFile <> nil then // begin // FZipFile.Close; // FreeAndNil(FZipFile); // end; //end; // //constructor TZipFileArchiveReader.Create; //begin // inherited; //end; // //destructor TZipFileArchiveReader.Destroy; //begin // if FZipFile <> nil then // begin // FZipFile.Close; // FZipFile.Free; // end; // // inherited; //end; // //function TZipFileArchiveReader.Exists : Boolean; //begin // result := TFile.Exists(FFileName); //end; // //function TZipFileArchiveReader.ExtractFileTo(const fileName, destFileName : string) : boolean; //var // sPath : string; //begin // result := false; // if FZipFile = nil then // begin // FLastError := 'Archive not open'; // exit; // end; // try // sPath := TPath.GetDirectoryName(destFileName); // FZipFile.Extract(fileName, sPath, true); // result := true; // except // on e : Exception do // FLastError := e.ToString; // end; //end; // //function TZipFileArchiveReader.ExtractTo(const path : string) : boolean; //begin // result := false; // if FZipFile = nil then // begin // FLastError := 'Archive not open'; // exit; // end; // // try // //TODO : This isn't overwriting!!! // // FZipFile.ExtractAll(path); // result := true; // except // on e : Exception do // FLastError := e.ToString; // end; // //end; // //function TZipFileArchiveReader.GetArchiveName : string; //begin // result := TPath.GetFileName(FFileName); //end; // //function TZipFileArchiveReader.GetArchivePath : string; //begin // result := TPath.GetDirectoryName(FFileName) //end; // //function TZipFileArchiveReader.GetLastErrorString : string; //begin // result := FLastError; //end; // //function TZipFileArchiveReader.GetPackageVersion : TPackageVersion; //begin // result := FVersion; //end; // //function TZipFileArchiveReader.IsArchive : Boolean; //begin // result := TPath.GetExtension(FFileName) = cPackageFileExt; //end; // //function TZipFileArchiveReader.Open(const fileName : string) : Boolean; //var // sFileName : string; // i : integer; //begin // FFileName := fileName; // FPackageMetaFile := cPackageMetaFile; // sFileName := ExtractFileName(fileName); // sFileName := ChangeFileExt(sFileName, ''); // i := Pos('-', sFileName); // if i <> -1 then // Delete(sFileName, 1, i); // // // FVersion := TPackageVersion.Parse(sFileName); // // result := false; // if FZipFile <> nil then // exit(true); //already open; // // FZipFile := TZipFile.Create; // try // FZipFile.Open(FFileName, TZipMode.zmRead); // result := true; // except // on e : Exception do // begin // FreeAndNil(FZipFile); // FLastError := e.ToString; // end; // end; //end; // //function TZipFileArchiveReader.ReadFileNames : System.TArray<System.string>; //begin // if FZipFile = nil then // begin // SetLength(result, 0); // FLastError := 'Archive not open!'; //todo : resourcestring! // end; // result := FZipFile.FileNames; //end; // //function TZipFileArchiveReader.ReadMetaDataFile(const stream : TStream) : Boolean; //var // localheader : TZipHeader; // localStream : TStream; //begin // result := false; // if FZipFile = nil then // begin // FLastError := 'Archive not open!'; // exit; // end; // try // FZipFile.Read(cPackageMetaFile, localstream, localheader); // try // stream.CopyFrom(localStream, localStream.Size); // result := true; // finally // localStream.Free; // end; // except // on e : Exception do // FLastError := e.ToString; // end; //end; // //{ TFolderArchiveReader } // //procedure TFolderArchiveReader.Close; //begin // //end; // //constructor TFolderArchiveReader.Create(); //begin //end; // //destructor TFolderArchiveReader.Destroy; //begin // // inherited; //end; // //function TFolderArchiveReader.Exists : Boolean; //begin // result := TDirectory.Exists(FFolderName); //end; // //function TFolderArchiveReader.ExtractFileTo(const fileName, destFileName : string) : boolean; //begin // result := False; // try // TFile.Copy(fileName, destFileName); // result := true; // except // on e : Exception do // FLastError := e.ToString; // end; //end; // //function TFolderArchiveReader.ExtractTo(const path : string) : Boolean; //begin // result := False; // try // TDirectory.Copy(FFolderName, path); // result := true; // except // on e : Exception do // FLastError := e.ToString; // end; // //end; // //function TFolderArchiveReader.GetArchiveName : string; //begin // result := FFolderName; //end; // //function TFolderArchiveReader.GetArchivePath : string; //begin // result := FFolderName; //end; // //function TFolderArchiveReader.GetLastErrorString : string; //begin // result := FLastError; //end; // //function TFolderArchiveReader.GetPackageVersion : TPackageVersion; //begin // result := FVersion; //end; // //function TFolderArchiveReader.IsArchive : Boolean; //begin // result := false; //end; // //function TFolderArchiveReader.Open(const fileName : string) : Boolean; //begin // FFolderName := fileName; // FPackageMetaFile := TPath.Combine(FFolderName, cPackageMetaFile); // FVersion := TPackageVersion.Parse(FFolderName); // TODO : This would need to be just the last part of the folder. // // //Nothing to do here really, but we'll do a sanity check! // result := TDirectory.Exists(FFolderName) and TFile.Exists(FPackageMetaFile); //end; // //function TFolderArchiveReader.ReadFileNames : TArray<string>; //begin // result := TArray <string> (TDirectory.GetFiles(FFolderName, '*.*', TSearchOption.soAllDirectories)); //end; // //function TFolderArchiveReader.ReadMetaDataFile(const stream : TStream) : Boolean; //var // fs : TFileStream; //begin // result := false; // try // fs := TFile.OpenRead(FPackageMetaFile); // try // stream.CopyFrom(fs, fs.Size); // stream.Seek(0, soBeginning); // result := true; // finally // fs.Free; // end; // except // on e : Exception do // FLastError := e.Message; // end; //end; end.
unit t_CSSThreads; interface uses Classes, SysUtils, IniFiles, Forms, DateUtils, System.Math, Variants, IdTCPServer, IBDatabase, IBSQL, IdHTTP, IdUri, n_CSSThreads, n_free_functions, n_server_common, v_constants, n_LogThreads, n_DataSetsManager, n_constants, n_DataCacheInMemory, t_function; type TCheckSMSThread = class(TCSSCyclicThread) protected procedure WorkProc; override; public DateMail: double; constructor Create(CreateSuspended: Boolean; AThreadType: integer); procedure DoTerminate; override; end; TControlPayThread = class(TCSSCyclicThread) protected lastControlTime: TDateTime; procedure WorkProc; override; public constructor Create(CreateSuspended: Boolean; AThreadType: integer); procedure DoTerminate; override; end; TControlSMSThread = class(TCSSCyclicThread) protected lastControlTime: TDateTime; procedure WorkProc; override; public constructor Create(CreateSuspended: Boolean; AThreadType: integer); procedure DoTerminate; override; end; procedure prSendSMS(ThreadData: TThreadData); procedure prTestSMS(ThreadData: TThreadData); function fnTestBalance: real; function datCompToDateTime(s: string; descD: string='-'): TDateTime; function TimeSendMess(BeginHour,EndHour: INTEGER): Boolean; implementation function TimeSendMess(BeginHour,EndHour: INTEGER): Boolean; var Hour,Min,Sec,MSec: Word; begin Result:= True; if BeginHour<0 then BeginHour:= 0; if BeginHour>24 then BeginHour:= 24; if EndHour<0 then EndHour:= 0; if EndHour>24 then EndHour:= 24; if (BeginHour=EndHour) or ((BeginHour=0) and (EndHour=24)) or ((EndHour=0) and (BeginHour=24)) then Exit; DecodeTime(Time,Hour,Min,Sec,MSec); if BeginHour<EndHour then Result:= (Hour>(BeginHour-1)) and (Hour<(EndHour+1)) else Result:= (Hour>(BeginHour-1)) or (Hour<(EndHour+1)); end; //============================================================================== function datCompToDateTime(s: string; descD: string='-'): TDateTime; var ss,sdd: string; begin result:= StrToDateTime(copy(s,pos(' ',s)+1,length(s))); s:= StringReplace(s,descD,'.',[rfReplaceAll]); ss:= trim(copy(s,1,pos(' ',s))); while True do begin if pos('.',ss)=0 then break; sdd:= fnIfStr(pos('.',sdd)=0,'.','')+copy(ss,1,pos('.',ss)-1)+sdd; ss:= copy(ss,pos('.',ss)+1,length(ss)) ; end; if (ss<>'') and (sdd<>'') then sdd:= ss+'.'+sdd+' '+copy(s,pos(' ',s)+1,length(s)) else sdd:= copy(s,pos(' ',s)+1,length(s)); result:= StrToDateTime(sdd); end; //============================================================================== //****************************************************************************** // TControlPayThread //****************************************************************************** procedure TControlPayThread.WorkProc; const nmProc = 'TControlPayThread_WorkProc'; // имя процедуры/функции/потока var fOpen: boolean; rIniFile: TINIFile; BeginHour,EndHour, countR, Interval: integer; IBSQL: TIBSQL; IBLog: TIBDatabase; SLBody: TStringList; Addrs, ss: string; DT: TDateTime; begin //DT:= StrToDateTime('20.09.2016')+time; BeginHour:= 0; EndHour:= 0; try rIniFile:= TINIFile.Create(nmIniFileBOB); if rIniFile.ReadInteger('threads', 'ControlPay', 0)=0 then exit; DT:= LastControlTime; LastControlTime:= now; try if (DayOfWeek(date)=1) or (DayOfWeek(date)=7) then begin Interval:= rIniFile.ReadInteger('intervals', 'CheckPayS', 30); BeginHour := rIniFile.ReadInteger('intervals','BeginHourPayS',0); // начало EndHour := rIniFile.ReadInteger('intervals','EndHourPayS',0); // окончание end; if (DayOfWeek(date)<>1) and (DayOfWeek(date)<>7) then begin interval:= rIniFile.ReadInteger('intervals', 'CheckPay', 10); BeginHour := rIniFile.ReadInteger('intervals','BeginHourPay',0); // начало EndHour := rIniFile.ReadInteger('intervals','EndHourPay',0); // окончание end; CycleInterval:= interval*60; fOpen:= (appStatus in [stWork]) and (cntsLOG.BaseConnected); if fOpen and TimeSendMess(BeginHour,EndHour) then begin try IBLog:= CntsLog.GetFreeCnt; IBSQL:= fnCreateNewIBSQL(IBLog,'LOGIBSQL_'+nmProc, -1, tpRead, true); // IBSQL.SQL.Text:= 'SELECT count(THLGCODE) CountR FROM LOGTHREADS where THLGTYPE=22 and THLGBEGINTIME>= :pBEGINTIME '; IBSQL.SQL.Text:= 'SELECT first 1 THLGCODE FROM LOGTHREADS where THLGTYPE=22 and THLGBEGINTIME>= :pBEGINTIME '; IBSQL.ParamByName('pBEGINTIME').AsDateTime:= DT;//IncMinute(now{DT},-Interval); IBSQL.Prepare; IBSQL.ExecQuery; countR:= 0; while not IBSQL.EOF do begin countR:= IBSQL.FieldByName('THLGCODE').AsInteger; IBSQL.Next; end; if countR=0 then begin SLBody:= TStringList.Create; SLBody.Add('Внимание! В течении последних '+IntToStr(Interval)+' мин. система платежей не работала!'); Addrs:= rIniFile.ReadString('mail', 'SysAdresPay',''); ss:= n_SysMailSend(Addrs, 'PAY Error', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'Error' , true); end; finally prFreeIBSQL(IBSQL); CntsLog.SetFreeCnt(IBLog, True); prFree(SLBody); end; end; except on E:Exception do begin prMessageLOGS(nmProc+' Ошибка при проверке работы системы платежей ','Error' , true); end; end; finally prFree(rIniFile); end; end; //============================================================================== constructor TControlPayThread.Create(CreateSuspended: Boolean; AThreadType: integer); const nmProc = 'TControlPayThread_Create'; // имя процедуры/функции/потока var rIniFile: TINIFile; Interval: integer; begin inherited Create(CreateSuspended, AThreadType); try try ThreadName:= 'TControlPayThread'; rIniFile:= TINIFile.Create(nmIniFileBOB); if (DayOfWeek(date)=1) or (DayOfWeek(date)=7) then Interval:= rIniFile.ReadInteger('intervals', 'CheckPayS', 10); if (DayOfWeek(date)<>1) and (DayOfWeek(date)<>7) then Interval:= rIniFile.ReadInteger('intervals', 'CheckPay', 10); CycleInterval:= Interval*60; LastControlTime:= IncMinute(now,-Interval); prMessageLOG(ThreadName+': Запуск потока проверки зависания системы приема платежей'); except on E: Exception do prMessageLOGS(nmProc+': '+E.Message+ #10'Error.'#10+'nmIniFileBOB='+nmIniFileBOB); end; finally prFree(rIniFile); end; end; //============================================================================== procedure TControlPayThread.DoTerminate; begin inherited; prMessageLOG(ThreadName+': Завершение потока проверки зависания системы приема платежей'); end; //****************************************************************************** //****************************************************************************** // TControlSMSThread //****************************************************************************** procedure TControlSMSThread.WorkProc; const nmProc = 'TControlSMSThread_WorkProc'; // имя процедуры/функции/потока //CheckSMSInterval var fOpen: boolean; rIniFile: TINIFile; BeginHour,EndHour, countR, Interval: integer; IBSQL: TIBSQL; IBGB: TIBDatabase; SLBody: TStringList; Addrs, ss: string; DT: TDateTime; begin BeginHour:= 0; EndHour:= 0; try rIniFile:= TINIFile.Create(nmIniFileBOB); if rIniFile.ReadInteger('threads', 'CheckSMS', 0)=0 then exit; if rIniFile.ReadInteger('threads', 'ControlSMS', 0)=0 then exit; DT:= LastControlTime; try // CycleInterval:= rIniFile.ReadInteger('intervals', 'CheckSMS', 30); if (DayOfWeek(date)=1) or (DayOfWeek(date)=7) then begin Interval:= rIniFile.ReadInteger('intervals', 'CheckSMSS', 30); BeginHour := rIniFile.ReadInteger('intervals','BeginHourSMSS',0); // начало EndHour := rIniFile.ReadInteger('intervals','EndHourSMSS',0); // окончание end; if (DayOfWeek(date)<>1) and (DayOfWeek(date)<>7) then begin Interval:= rIniFile.ReadInteger('intervals', 'CheckSMS', 10); BeginHour := rIniFile.ReadInteger('intervals','BeginHourSMS',0); // начало EndHour := rIniFile.ReadInteger('intervals','EndHourSMS',0); // окончание end; CycleInterval:= Interval*60; fOpen:= (appStatus in [stWork]) and (cntsGRB.BaseConnected); if fOpen and TimeSendMess(BeginHour,EndHour) then begin try IBGB:= CntsGRB.GetFreeCnt();//(cDefGBLogin, cDefPassword, cDefGBrole,True); IBSQL:= fnCreateNewIBSQL(IBGB,'IBSQL_'+nmProc, -1, tpRead, true); // IBSQL.SQL.Text:= 'SELECT count(SBCODE) countR FROM SMSBOX where SBURGENCY in (1,2) and (SBCAMPID is null or SBCAMPID=0) and (SBERROR is null or SBERROR="") and '#10 // + 'SBCREATEDATE>= :pBEGINTIME and SBCREATEDATE< :pEndTIME '; IBSQL.SQL.Text:= 'SELECT first 1 SBCODE FROM SMSBOX where SBURGENCY in (1,2) and (SBCAMPID is null or SBCAMPID=0) and (SBERROR is null or SBERROR="") and '#10 + 'SBCREATEDATE>= :pBEGINTIME and SBCREATEDATE< :pEndTIME'; IBSQL.ParamByName('pBEGINTIME').AsDateTime:= DT;//IncMinute({now}DT,-(Interval+2*rIniFile.ReadInteger('intervals','CheckSMSInterval',0))); IBSQL.ParamByName('pEndTIME').AsDateTime:= IncMinute(now,-(2*rIniFile.ReadInteger('intervals','CheckSMSInterval',0)));//IncMinute({now}DT,-(rIniFile.ReadInteger('intervals','CheckSMSInterval',0))); LastControlTime:= IncMinute(now,-(2*rIniFile.ReadInteger('intervals','CheckSMSInterval',0))); IBSQL.Prepare; IBSQL.ExecQuery; countR:= 0; while not IBSQL.EOF do begin countR:= IBSQL.FieldByName('SBCODE').AsInteger; IBSQL.Next; end; if countR>0 then begin SLBody:= TStringList.Create; SLBody.Add('Внимание! В течении последних '+IntToStr(Interval)+' мин. система отправки СМС не работала!'); Addrs:= rIniFile.ReadString('mail', 'SysAdresPay',''); ss:= n_SysMailSend(Addrs, 'SMS Error', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'Error' , true); end; finally prFreeIBSQL(IBSQL); CntsGRB.SetFreeCnt(IBGB, True); prFree(SLBody); end; end; except on E:Exception do begin prMessageLOGS(nmProc+' Ошибка при проверке работы системы отправки СМС ','Error' , true); end; end; finally prFree(rIniFile); end; end; //============================================================================== constructor TControlSMSThread.Create(CreateSuspended: Boolean; AThreadType: integer); const nmProc = 'TControlSMSThread_Create'; // имя процедуры/функции/потока var rIniFile: TINIFile; Interval: integer; begin inherited Create(CreateSuspended, AThreadType); ThreadName:= 'TControlSMSThread'; try rIniFile:= TINIFile.Create(nmIniFileBOB); if (DayOfWeek(date)=1) or (DayOfWeek(date)=7) then Interval:= rIniFile.ReadInteger('intervals', 'CheckSMSS', 30); if (DayOfWeek(date)<>1) and (DayOfWeek(date)<>7) then Interval:= rIniFile.ReadInteger('intervals', 'CheckSMS', 10); CycleInterval:= Interval*60; LastControlTime:= IncMinute(now,-(Interval+(2*rIniFile.ReadInteger('intervals','CheckSMSInterval',0))));; prMessageLOG(ThreadName+': Запуск потока проверки зависания системы отправки СМС'); finally prFree(rIniFile); end; end; //============================================================================== procedure TControlSMSThread.DoTerminate; begin inherited; prMessageLOG(ThreadName+': Завершение потока проверки зависания системы отправки СМС'); end; //****************************************************************************** //============================================================================== function fnTestBalance: real; var jsonToBal, SLBody: TStringList; pIniFile: TINIFile; HTTP: TIDHTTP; Stream: TStringStream; ss: string; // balance: real; begin result:= 0; Stream:= nil; jsonToBal := TStringList.create; jsonToBal.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToBal.Add('<request>'); jsonToBal.Add('<operation>GETBALANCE</operation>'); jsonToBal.Add('</request>'); SLBody:= TStringList.Create; try HTTP:= TIDHTTP.Create(nil); HTTP.HandleRedirects := true; HTTP.ReadTimeout := 5000; HTTP.Request.BasicAuthentication:= true; pIniFile:= TINIFile.Create(nmIniFileBOB); if (pIniFile.ReadString('Proxy', 'Server', '')<>'') and (pIniFile.ReadString('svitSMS', 'login', '')<>'') then begin HTTP.ProxyParams.ProxyServer:=pIniFile.ReadString('Proxy', 'Server', ''); HTTP.ProxyParams.ProxyPort:=pIniFile.ReadInteger('Proxy', 'Port', 8080); HTTP.ProxyParams.ProxyUsername:=pIniFile.ReadString('Proxy', 'login', ''); HTTP.ProxyParams.ProxyPassword:=pIniFile.ReadString('Proxy', 'Password', ''); HTTP.Request.Username:=pIniFile.ReadString('svitSMS', 'login', '380952306161');//'380952306161'; HTTP.Request.Password:=pIniFile.ReadString('svitSMS', 'Password', 'RkbtynGhfd531');//'RkbtynGhfd531'; end else exit; Stream:=TStringStream.Create(jsonToBal.Text, TEncoding.UTF8); ss:= http.Post(TIdUri.UrlEncode('http://svitsms.com/api/api.php'), Stream); Stream.Clear; ss:= fnCutFromTo(ss, '<balance>', '</balance>',false); ss:=StringReplace(ss,'.',DecimalSeparator,[rfReplaceAll]); result:= StrToFloatDef(ss,0); finally if assigned(SLBody) then prFree(SLBody); if assigned(jsonToBal) then prFree(jsonToBal); if assigned(HTTP) then prFree(HTTP); if assigned(pIniFile) then prFree(pIniFile); if assigned(Stream) then prFree(Stream); end; end; //============================================================================== procedure prSendSMS(ThreadData: TThreadData); const nmProc='prSendSMS'; arState: array [0..10] of string = ( 'ACCEPT', // – сообщение принято системой и поставлено в очередь на формирование рассылки. 'XMLERROR', // – Некорректный XML . 'ERRPHONES', //– Неверно задан номер получателя. 'ERRSTARTTIME', //– не корректное время начала отправки. 'ERRENDTIME', //– не корректное время окончания рассылки. 'ERRLIFETIME', //– не корректное время жизни сообщения. 'ERRSPEED', //– не корректная скорость отправки сообщений. 'ERRALFANAME', //– данное альфанумерическое имя использовать запрещено, либо ошибка . 'ERRTEXT', 'ERRMobilePHONES', 'TEST'); arStateR: array [0..10] of string = ( ' сообщение принято системой и поставлено в очередь на формирование рассылки ', ' Некорректный XML ', ' Неверно задан номер получателя ', ' не корректное время начала отправки ', ' не корректное время окончания рассылки ', ' не корректное время жизни сообщения ', ' не корректная скорость отправки сообщений ', ' данное альфанумерическое имя использовать запрещено, либо ошибка ', ' некорректный текст сообщения ', ' Номер не мобильный', ' Проверка работы.'); var GBIBSQL, GBIBSQLUp: TIBSQL; IBGRB, IBGRBUp: TIBDatabase; HTTP: TIDHTTP; Stream: TStringStream; SBCODE, SBURGENCY, i, iState: integer; SBMESSAGE, SBPHONE, SendSS, ss, SBALPHANAME, sError, Err: string; flSend, TestMob: boolean; jsonToSend, jsonToBal, SLBody, SLBodyBal: TStringList; pIniFile: TINIFile; sstat, campaignID, datComp, code, sRec, rec, Addrs: string; balance, tarif: real; SENDTIMECSS, SBCREATEDATE: TDateTime; DS: char; TimeSend: double; countSend: integer; begin GBIBSQL:= nil; GBIBSQLUp:= nil; IBGRB:= nil; IBGRBUp:= nil; Stream:= nil; flSend:= false; SendSS:= ''; SBURGENCY:= 0; SBCODE:= 0; SBPHONE:= ''; SBMESSAGE:= ''; countSend:= 0; jsonToSend := TStringList.create; jsonToBal := TStringList.create; jsonToBal.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToBal.Add('<request>'); jsonToBal.Add('<operation>GETBALANCE</operation>'); jsonToBal.Add('</request>'); SLBody:= TStringList.Create; SLBodyBal:= TStringList.Create; prMessageLOGS(nmProc+' начало ','testSMS' , false); try HTTP:= TIDHTTP.Create(nil); HTTP.HandleRedirects := true; HTTP.ReadTimeout := 5000; HTTP.Request.BasicAuthentication:= true; pIniFile:= TINIFile.Create(nmIniFileBOB); if (pIniFile.ReadString('Proxy', 'Server', '')<>'') and (pIniFile.ReadString('svitSMS', 'login', '')<>'') then begin HTTP.ProxyParams.ProxyServer:=pIniFile.ReadString('Proxy', 'Server', ''); HTTP.ProxyParams.ProxyPort:=pIniFile.ReadInteger('Proxy', 'Port', 8080); HTTP.ProxyParams.ProxyUsername:=pIniFile.ReadString('Proxy', 'login', ''); HTTP.ProxyParams.ProxyPassword:=pIniFile.ReadString('Proxy', 'Password', ''); HTTP.Request.Username:=pIniFile.ReadString('svitSMS', 'login', '380952306161');//'380952306161'; HTTP.Request.Password:=pIniFile.ReadString('svitSMS', 'Password', 'RkbtynGhfd531');//'RkbtynGhfd531'; end else exit; tarif:= pIniFile.ReadFloat('svitSMS', 'tarif', 0.245); IBGRB:= CntsGRB.GetFreeCnt();//(cDefGBLogin, cDefPassword, cDefGBrole,True);; IBGRBUp:=CntsGRB.GetFreeCnt();//(cDefGBLogin, cDefPassword, cDefGBrole); GBIBSQL:= fnCreateNewIBSQL(IBGRB, 'Query_'+nmProc, -1, tpRead, true); GBIBSQLUp:= fnCreateNewIBSQL(IBGRBUp, 'Query_'+nmProc, -1, tpWrite, true); GBIBSQLUp.SQL.Text:='Update SMSBOX set SBSTATE=:pSBSTATE, SBCAMPID=:pSBSENDCode, SBSENDDATE=:pSBSENDDATE, SBERROR=:pSBERROR ' +',SBSENDTIMECSS=:pSBSENDTIMECSS ' +'where SBCODE=:pSBCODE'; GBIBSQL.SQL.Text:= 'SELECT SBCODE, SBPHONE, SBMESSAGE, SBURGENCY, SBSTATE, SBERROR, SBALPHANAME, SBCREATEDATE, RResult TestMob '#10 + 'FROM SMSBOX left join TestMobilePhone(SBPHONE) on 0=0 '#10 + 'where (SBCAMPID is null or SBCAMPID=0) and (SBERROR is null or SBERROR="") order by SBCREATEDATE'; GBIBSQL.Prepare; GBIBSQL.ExecQuery; //prMessageLOGS(nmProc+' GBIBSQL.ExecQuery ','error' , false); try TimeSend:= now; while not GBIBSQL.EOF do begin try SBURGENCY:= GBIBSQL.FieldByName('SBURGENCY').AsInteger; SBCODE:= GBIBSQL.FieldByName('SBCODE').AsInteger; SBCREATEDATE:= GBIBSQL.FieldByName('SBCREATEDATE').AsDateTime; SBPHONE:= GBIBSQL.FieldByName('SBPHONE').AsString; TestMob:= StrToBool(fnIfStr(GBIBSQL.FieldByName('TestMob').AsString='T', 'TRUE', 'FALSE')); //1- сообщение должно быть отправлено немедленно, 2 - отправка в будні - 8:00-20:00, у вихідні - 11:00-17:00; 0 - проверка работы if (SBURGENCY=1) or (SBURGENCY=0) then flSend:= true; if (SBURGENCY=2) and ( ((DayOfWeek(Now)<>1) and (DayOfWeek(Now)<>7) and (HourOf(now)>=8) and (HourOf(Now)<20)) or (((DayOfWeek(Now)=1) or (DayOfWeek(Now)=7)) and (HourOf(now)>=11) and (HourOf(Now)<17))) then flSend:= true; if pos('0999999999', SBPHONE)>0 then flSend:= false; if not TestMob then flSend:= false; if flSend then begin ss:=''; // SBCODE:= GBIBSQL.FieldByName('SBCODE').AsInteger; SBMESSAGE:= GBIBSQL.FieldByName('SBMESSAGE').AsString; SBALPHANAME:= GBIBSQL.FieldByName('SBALPHANAME').AsString; /////////////////////////////////////////////////////////////////////////////// +380730203913 TestCssStopException; //// Stream:=TStringStream.Create(jsonToBal.Text, TEncoding.UTF8); //// ss:= http.Post(TIdUri.UrlEncode('http://svitsms.com/api/api.php'), Stream); //// Stream.Clear; //// ss:= fnCutFromTo(ss, '<balance>', '</balance>',false); //// ss:=StringReplace(ss,'.',DecimalSeparator,[rfReplaceAll]); //// balance:= StrToFloatDef(ss,0); balance:= fnTestBalance; if (balance<tarif) then begin prMessageLOGS(nmProc+ ' Нет средств для отправки СМС. '+'Баланс: '+ FloatToStr(balance), 'testSMS', true) ; //отправка письма на элпочту 1 раз в час if (TCheckSMSThread(thCheckSMSThread).DateMail=0) or (IncHour(TCheckSMSThread(thCheckSMSThread).DateMail)<now) then begin TCheckSMSThread(thCheckSMSThread).DateMail:= now; SLBodyBal.Clear; SLBodyBal.Add(' Нет средств для отправки СМС. '+'Баланс: '+ FloatToStr(balance)); // Addrs:= Cache.GetConstItem(pcUIKdepartmentMail).StrValue; >> 21.09.2016 12:34:30 Чичков Валерий wrote: >> Поменяйте, плз на payment@vladislav.ua Addrs:= IniFile.ReadString('mails', 'svitSMS', ''); ss:= n_SysMailSend(Addrs, 'SMS Error', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'TestSMS' , true); Addrs:= ''; ss:= ''; SLBodyBal.Clear; end; break;//////// balance<tarif end; if (balance>=tarif) then begin if TCheckSMSThread(thCheckSMSThread).DateMail>0 then TCheckSMSThread(thCheckSMSThread).DateMail:= 0; ss:=''; jsonToSend.Clear; jsonToSend.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToSend.Add('<request>'); jsonToSend.Add('<operation>SENDSMS</operation>'); jsonToSend.Add('<message start_time="AUTO" end_time="AUTO" lifetime="24" rate="120" desc="My campaign " source="'+SBALPHANAME+'">'); jsonToSend.Add('<body>'+SBMESSAGE+'</body>'); jsonToSend.Add('<recipient>'+SBPHONE+'</recipient>'); jsonToSend.Add('</message>'); jsonToSend.Add('</request>'); prMessageLOGS(nmProc+' отпр: '+jsonToSend.Text,'testSMS' , false); Stream:=TStringStream.Create(jsonToSend.Text, TEncoding.UTF8); if SBURGENCY<>0 then ss:= http.Post(TIdUri.UrlEncode('http://svitsms.com/api/api.php'), Stream); //sms Application.ProcessMessages; inc(countSend); Stream.Clear; SENDTIMECSS:=now; //ss:='<?xml version="1.0" encoding="utf-8"?><message> <state code="ERRTEXT" date="2016-10-17 09:17:10">STOPWORDS струк </state></message>'; prMessageLOGS(nmProc+' ответ: '+ss,'testSMS' , false); if ss<>'' then begin sstat:= fnCutFromTo(ss, '<state', '</state>',false); //code="ERRSTARTTIME" code:= fnCutFromTo(sstat, 'code="', '"',false); datComp:= fnCutFromTo(sstat, 'date="', '"',false); campaignID:= fnCutFromTo(sstat, 'campaignID="', '"',false); end else begin datComp:= ''; end; iState:= fnInStrArray(code,arState); if SBURGENCY=0 then iState:= 10; if iState=0 then begin while True do begin sRec:= fnCutFromTo(ss, '<to', '/>',true); if sRec='' then break; rec:= fnCutFromTo(sRec, 'recipient="', '"',false); sstat:= fnCutFromTo(sRec, 'status="', '"',false); try with GBIBSQLUp.Transaction do if not InTransaction then StartTransaction; GBIBSQLUp.ParamByName('pSBERROR').AsString:= ''; GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= datCompToDateTime(datComp);//StrToDateTime(datComp); GBIBSQLUp.ParamByName('pSBSENDTIMECSS').AsDateTime:= SENDTIMECSS; GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= -1; GBIBSQLUp.ParamByName('pSBSENDCode').AsString:= campaignID;///////////////////////////// GBIBSQLUp.ParamByName('pSBCODE').AsInteger:= SBCODE; GBIBSQLUp.ExecQuery; GBIBSQLUp.Transaction.Commit; GBIBSQLUp.Close; except on E: Exception do begin GBIBSQLUp.Transaction.Rollback; prMessageLOGS('Ошибка обновления базы '+nmProc+' '+ E.Message, 'TestSMS', true) ; prMessageLOGS('Phone='+SBPHONE+'; campaignID='+campaignID+'date='+datComp, 'TestSMS', true) ; end; end; end; end else begin //error try Err:=''; if length(sstat)<>0 then Err:= copy(sstat,pos('>',sstat)+1, length(sstat)); with GBIBSQLUp.Transaction do if not InTransaction then StartTransaction; SLBody.Add('Ошибка отправки СМС: '+SBPHONE); GBIBSQLUp.ParamByName('pSBERROR').AsString:= arStateR[iState]+fnIfStr(length(Err)>0,'('+Err+')',''); if datComp= '' then GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= SENDTIMECSS else GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= datCompToDateTime(datComp);//StrToDateTime(datComp); // if flDebug then GBIBSQLUp.ParamByName('pSBSENDTIMECSS').AsDateTime:= SENDTIMECSS; GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= -1; GBIBSQLUp.ParamByName('pSBSENDCode').AsInteger:= 0;///////////////////////////// GBIBSQLUp.ParamByName('pSBCODE').AsInteger:= SBCODE; GBIBSQLUp.ExecQuery; GBIBSQLUp.Transaction.Commit; GBIBSQLUp.Close; except on E: Exception do begin GBIBSQLUp.Transaction.Rollback; prMessageLOGS('Ошибка обновления базы '+nmProc+' '+ E.Message, 'TestSMS', true) ; prMessageLOGS('Phone='+SBPHONE+'; campaignID='+campaignID+'date='+datComp, 'TestSMS', true) ; end; end; SLBody.Add('Ошибка при отправке СМС на '+SBPHONE +': '+arStateR[iState]+fnIfStr(length(Err)>0,'('+Err+')','')); end; if (countSend>=8) then begin countSend:= 0; if (now<IncSecond(TimeSend)) then sleep(100); TimeSend:= now;//IncSecond end; end; // else prMessageLOGS('Номер не мобильный: Phone='+SBPHONE, 'TestSMS', true) ; end else if (SBCREATEDATE+1>=now) then begin sError:= ''; if (SBURGENCY<1) or (SBURGENCY>2) then sError:= 'Неизвестное значение "Код срочности": '+IntToStr(SBURGENCY); if pos('0999999999', SBPHONE)>0 then sError:= 'Запрет отправки: '+SBPHONE; if not TestMob then sError:= 'Номер не мобильный: '+SBPHONE; if sError<>'' then begin prMessageLOGS(sError, 'TestSMS', false) ; SENDTIMECSS:=now; try with GBIBSQLUp.Transaction do if not InTransaction then StartTransaction; // SLBody.Add('Ошибка отправки СМС: '+SBPHONE); GBIBSQLUp.ParamByName('pSBERROR').AsString:= sError; if datComp= '' then GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= SENDTIMECSS else GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= datCompToDateTime(datComp);//StrToDateTime(datComp); GBIBSQLUp.ParamByName('pSBSENDTIMECSS').AsDateTime:= SENDTIMECSS; GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= -1; GBIBSQLUp.ParamByName('pSBSENDCode').AsInteger:= 0;///////////////////////////// GBIBSQLUp.ParamByName('pSBCODE').AsInteger:= SBCODE; GBIBSQLUp.ExecQuery; GBIBSQLUp.Transaction.Commit; GBIBSQLUp.Close; except on E: Exception do begin GBIBSQLUp.Transaction.Rollback; prMessageLOGS('Ошибка обновления базы '+nmProc+' '+ E.Message, 'TestSMS', true) ; prMessageLOGS('SBCODE='+IntToStr(SBCODE)+'date='+datComp, 'TestSMS', true) ; end; end; end; end; except on e: exception do begin prMessageLOGS('Ошибка: '+e.Message,'TestSMS' , false); prMessageLOGS('SBCODE= '+IntToStr(SBCODE)+' SBPHONE='+SBPHONE+' SBMESSAGE='+SBMESSAGE,'TestSMS' , false); end; end; SBURGENCY:= 0; SBCODE:= 0; SBPHONE:= ''; SBMESSAGE:= ''; flSend:= false; TestCssStopException; GBIBSQL.Next; end; except on e: exception do begin prMessageLOGS('Ошибка при обработке результатов запроса: '+e.Message,'TestSMS' , false); end; end; finally //prMessageLOGS(nmProc+' finally ','error' , false); if SLBody.Count>0 then begin // Addrs:= Cache.GetConstItem(pcUIKdepartmentMail).StrValue; >> 21.09.2016 12:34:30 Чичков Валерий wrote: >> Поменяйте, плз на payment@vladislav.ua Addrs:= pIniFile.ReadString('svitSMS', 'Mails', ''); ss:= n_SysMailSend(Addrs, 'SMS Error', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'TestSMS' , true); end; prFreeIBSQL(GBIBSQL); prFreeIBSQL(GBIBSQLUp); if assigned(IBGRB) then cntsGRB.SetFreeCnt(IBGRB, True); if assigned(IBGRBUp) then cntsGRB.SetFreeCnt(IBGRBUp, True); if assigned(SLBody) then prFree(SLBody); if assigned(SLBodyBal) then prFree(SLBodyBal); if assigned(jsonToBal) then prFree(jsonToBal); if assigned(jsonToSend) then prFree(jsonToSend); if assigned(HTTP) then prFree(HTTP); if assigned(pIniFile) then prFree(pIniFile); if assigned(Stream) then prFree(Stream); prMessageLOGS(nmProc+' finally end','testSMS' , false); end; end; /////////////////////////////////////////////////////////////////////////////// procedure prTestSMS(ThreadData: TThreadData); const nmProc='prTestSMS'; arState: array [0..10] of string = ( 'PENDING',// - запланировано; 'SENT',// - передано мобильному оператору; 'DELIVERED',// - доставлено; 'EXPIRED',// - истек срок доставки; 'UNDELIV',// - не доставлено; 'STOPED',// - остановлено системой (недостаточно средств); 'ERROR',// - ошибка при отправке; 'USERSTOPED',// - остановлено пользователем; 'ALFANAMELIMITED',// - ограничено альфаименем; 'STOPFLAG', 'NEW'// – временные статусы; ); arStateR: array [0..10] of string = ( 'запланировано', 'передано мобильному оператору', 'доставлено', 'истек срок доставки', 'не доставлено', 'остановлено системой (недостаточно средств)', 'ошибка при отправке', 'остановлено пользователем', 'ограничено альфаименем', 'временные статус', 'временные статус'); var GBIBSQL, GBIBSQLUp: TIBSQL; IBGRB, IBGRBUp: TIBDatabase; HTTP: TIDHTTP; Stream: TStringStream; SBCODE, SBCAMPID, i: integer; SBPHONE, SendSS, ss: string; jsonToSend, SLGroup, SLBody: TStringList; pIniFile: TINIFile; sstat, campaignID, datComp, status, rec, Addrs: string; SBSENDDATE: TDateTime; begin GBIBSQL:= nil; GBIBSQLUp:= nil; IBGRB:= nil; IBGRBUp:= nil; Stream:= nil; SendSS:= ''; SBCAMPID:= 0; SBSENDDATE:= 0; jsonToSend := TStringList.create; SLGroup:= TStringList.create; SLBody:= TStringList.create; prMessageLOGS(nmProc+' начало ','testSMS' , false); try HTTP:= TIDHTTP.Create(nil); HTTP.HandleRedirects := true; HTTP.ReadTimeout := 5000; HTTP.Request.BasicAuthentication:= true; pIniFile:= TINIFile.Create(nmIniFileBOB); if (pIniFile.ReadString('Proxy', 'Server', '')<>'') and (pIniFile.ReadString('svitSMS', 'login', '')<>'') then begin HTTP.ProxyParams.ProxyServer:=pIniFile.ReadString('Proxy', 'Server', ''); HTTP.ProxyParams.ProxyPort:=pIniFile.ReadInteger('Proxy', 'Port', 8080); HTTP.ProxyParams.ProxyUsername:=pIniFile.ReadString('Proxy', 'login', ''); HTTP.ProxyParams.ProxyPassword:=pIniFile.ReadString('Proxy', 'Password', ''); HTTP.Request.Username:=pIniFile.ReadString('svitSMS', 'login', '380952306161');//'380952306161'; HTTP.Request.Password:=pIniFile.ReadString('svitSMS', 'Password', 'RkbtynGhfd531');//'RkbtynGhfd531'; end else exit; //prMessageLOGS(nmProc+' HTTP ','error' , false); IBGRB:= CntsGRB.GetFreeCnt();//(cDefGBLogin, cDefPassword, cDefGBrole,True);; IBGRBUp:=CntsGRB.GetFreeCnt();//(cDefGBLogin, cDefPassword, cDefGBrole); GBIBSQL:= fnCreateNewIBSQL(IBGRB, 'Query_'+nmProc, -1, tpRead, true); GBIBSQLUp:= fnCreateNewIBSQL(IBGRBUp, 'Query_'+nmProc, -1, tpWrite, true); GBIBSQLUp.SQL.Text:='Update SMSBOX set SBSTATE=:pSBSTATE, SBSENDDATE=:pSBSENDDATE, SBERROR=:pSBERROR where SBCODE=:pSBCODE'; GBIBSQL.SQL.Text:='SELECT SBCODE, SBCAMPID, SBPHONE, SBSTATE, SBERROR, SBSENDDATE '#10 + 'FROM SMSBOX '#10 + 'where SBCAMPID>0 and (SBERROR is null or SBERROR="") order by SBCAMPID'; GBIBSQL.Prepare; GBIBSQL.ExecQuery; //prMessageLOGS(nmProc+' GBIBSQL.ExecQuery ','error' , false); try while not GBIBSQL.EOF do begin if (SBCAMPID<>GBIBSQL.FieldByName('SBCAMPID').AsInteger) and (SLGroup.Count>0) then begin if SLGroup.Count>1 then begin jsonToSend.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToSend.Add('<request>'); jsonToSend.Add('<operation>GETCAMPAIGNDETAIL</operation>'); jsonToSend.Add('<message campaignID="'+IntToStr(SBCAMPID)+'" />'); jsonToSend.Add('</request>'); end; if SLGroup.Count=1 then begin jsonToSend.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToSend.Add('<request>'); jsonToSend.Add('<operation>GETMESSAGESTATUS</operation>'); jsonToSend.Add('<message campaignID="'+IntToStr(SBCAMPID)+'" recipient="'+SBPHONE+'" />'); jsonToSend.Add('</request>'); end; prMessageLOGS(nmProc+' отпр: '+jsonToSend.Text,'testSMS' , false); Stream:=TStringStream.Create(jsonToSend.Text, TEncoding.UTF8); ss:= http.Post(TIdUri.UrlEncode('http://svitsms.com/api/api.php'), Stream); Application.ProcessMessages; prMessageLOGS(nmProc+' ответ: '+ss,'testSMS' , false); Stream.Clear; while True do begin sstat:= fnCutFromTo(ss, '<message', '</message>',true); if sstat='' then break; if pos('recipient="',sstat)>0 then SBPHONE:= fnCutFromTo(sstat, 'recipient="', '"',false) else SBPHONE:= fnCutFromTo(sstat, 'phone="', '"',false); status:= fnCutFromTo(sstat, 'status="', '"',false); if pos('date="',sstat)>0 then datComp:= fnCutFromTo(sstat, 'date="', '"',false) else datComp:= fnCutFromTo(sstat, 'modifyDateTime="', '"',false); if datComp='' then datComp:= fnCutFromTo(sstat, 'startDateTime="', '"',false); i:= SLGroup.IndexOf(SBPHONE); if i=-1 then i:= SLGroup.IndexOf(copy(SBPHONE,3,length(SBPHONE))); if i=-1 then i:= SLGroup.IndexOf('+'+SBPHONE); if i>-1 then try SBCODE:= integer(SLGroup.Objects[i]); with GBIBSQLUp.Transaction do if not InTransaction then StartTransaction; if datComp='' then GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= SBSENDDATE else GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= datCompToDateTime(datComp); i:= fnInStrArray(status,arState); if i<9{status='DELIVERED'} then begin GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= i; if (i>=2) or ((datComp<>'') and (Date()-datCompToDateTime(datComp)>2)) then begin if ((datComp<>'') and (Date()-datCompToDateTime(datComp)>2)) then begin GBIBSQLUp.ParamByName('pSBERROR').AsString:= 'VLAD: '+'Сообщение не доставлено.'; SLBody.Add('Vlad. Error of SMS! Phone '+SBPHONE+': '+'Сообщение не доставлено.'); end else GBIBSQLUp.ParamByName('pSBERROR').AsString:= arStateR[i]; if i>2 then SLBody.Add('Error of SMS! Phone '+SBPHONE+': '+arStateR[i]); end else GBIBSQLUp.ParamByName('pSBERROR').AsString:=''; end else if i>8 then begin GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= -1; GBIBSQLUp.ParamByName('pSBERROR').AsString:= '';//arStateR[i]; end; GBIBSQLUp.ParamByName('pSBCODE').AsInteger:= SBCODE; GBIBSQLUp.ExecQuery; GBIBSQLUp.Transaction.Commit; GBIBSQLUp.Close; except on E: Exception do begin GBIBSQLUp.Transaction.Rollback; prMessageLOGS('Ошибка обновления базы '+nmProc+' '+ E.Message, 'error', true) ; prMessageLOGS('Phone='+SBPHONE+'; campaignID='+IntToStr(SBCAMPID)+'date='+datComp, 'error', true) ; end; end; if i>2 then SLBody.Add('Error of SMS! Phone '+SBPHONE+': '+arStateR[i]); end; SLGroup.Clear; jsonToSend.Clear; end; SBCAMPID:= GBIBSQL.FieldByName('SBCAMPID').AsInteger; SBCODE:= GBIBSQL.FieldByName('SBCODE').AsInteger; SBPHONE:= GBIBSQL.FieldByName('SBPHONE').AsString; SBSENDDATE:= GBIBSQL.FieldByName('SBSENDDATE').AsDateTime; SLGroup.AddObject(SBPHONE,Pointer(SBCODE)); TestCssStopException; GBIBSQL.Next; end; //prMessageLOGS(nmProc+' GBIBSQL.ExecQuery 1','error' , false); if (SLGroup.Count>0) then begin if SLGroup.Count>1 then begin jsonToSend.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToSend.Add('<request>'); jsonToSend.Add('<operation>GETCAMPAIGNDETAIL</operation>'); jsonToSend.Add('<message campaignID="'+IntToStr(SBCAMPID)+'" />'); jsonToSend.Add('</request>'); end; if SLGroup.Count=1 then begin jsonToSend.Add('<?xml version="1.0" encoding="utf-8"?>'); jsonToSend.Add('<request>'); jsonToSend.Add('<operation>GETMESSAGESTATUS</operation>'); jsonToSend.Add('<message campaignID="'+IntToStr(SBCAMPID)+'" recipient="'+SBPHONE+'" />'); jsonToSend.Add('</request>'); end; prMessageLOGS(nmProc+' отпр: '+jsonToSend.Text,'testSMS' , false); Stream:=TStringStream.Create(jsonToSend.Text, TEncoding.UTF8); ss:= http.Post(TIdUri.UrlEncode('http://svitsms.com/api/api.php'), Stream); Application.ProcessMessages; prMessageLOGS(nmProc+' ответ: '+ss,'testSMS' , false); Stream.Clear; while True do begin sstat:= fnCutFromTo(ss, '<message', '</message>',true); if sstat='' then break; if pos('recipient="',sstat)>0 then SBPHONE:= fnCutFromTo(sstat, 'recipient="', '"',false) else SBPHONE:= fnCutFromTo(sstat, 'phone="', '"',false); status:= fnCutFromTo(sstat, 'status="', '"',false); if pos('date="',sstat)>0 then datComp:= fnCutFromTo(sstat, 'date="', '"',false) else datComp:= fnCutFromTo(sstat, 'modifyDateTime="', '"',false); if datComp='' then datComp:= fnCutFromTo(sstat, 'startDateTime="', '"',false); i:= SLGroup.IndexOf(SBPHONE); if i=-1 then i:= SLGroup.IndexOf(copy(SBPHONE,3,length(SBPHONE))); if i=-1 then i:= SLGroup.IndexOf('+'+SBPHONE); if i>-1 then try SBCODE:= integer(SLGroup.Objects[i]); with GBIBSQLUp.Transaction do if not InTransaction then StartTransaction; if datComp='' then GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= SBSENDDATE else GBIBSQLUp.ParamByName('pSBSENDDATE').AsDateTime:= datCompToDateTime(datComp); i:= fnInStrArray(status,arState); if i<9{status='DELIVERED'} then begin GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= i; if (i>=2) or ((datComp<>'') and (Date()-datCompToDateTime(datComp)>2)) then begin if ((datComp<>'') and (Date()-datCompToDateTime(datComp)>2)) then begin GBIBSQLUp.ParamByName('pSBERROR').AsString:= 'VLAD: '+'Сообщение не доставлено.'; SLBody.Add('Vlad. Error of SMS! Phone '+SBPHONE+': '+'Сообщение не доставлено.'); end else GBIBSQLUp.ParamByName('pSBERROR').AsString:= arStateR[i]; if i>2 then SLBody.Add('Error of SMS! Phone '+SBPHONE+': '+arStateR[i]); end else GBIBSQLUp.ParamByName('pSBERROR').AsString:=''; end else if i>8 then begin GBIBSQLUp.ParamByName('pSBSTATE').AsInteger:= -1; GBIBSQLUp.ParamByName('pSBERROR').AsString:= '';//arStateR[i]; end; GBIBSQLUp.ParamByName('pSBCODE').AsInteger:= SBCODE; GBIBSQLUp.ExecQuery; GBIBSQLUp.Transaction.Commit; GBIBSQLUp.Close; except on E: Exception do begin GBIBSQLUp.Transaction.Rollback; prMessageLOGS('Ошибка обновления базы '+nmProc+' '+ E.Message, 'error', true) ; prMessageLOGS('Phone='+SBPHONE+'; campaignID='+IntToStr(SBCAMPID)+'date='+datComp, 'error', true) ; end; end; end; SLGroup.Clear; end; except on e: exception do begin prMessageLOGS(nmProc+' Ошибка при обработке результатов запроса: '+e.Message,'error' , true); end; end; finally prMessageLOGS(nmProc+' finally ','testSMS' , false); if SLBody.Count>0 then begin // Addrs:= Cache.GetConstItem(pcUIKdepartmentMail).StrValue; >> 21.09.2016 12:34:30 Чичков Валерий wrote: >> Поменяйте, плз на payment@vladislav.ua Addrs:= pIniFile.ReadString('svitSMS', 'Mails', ''); ss:= n_SysMailSend(Addrs, 'SMS Error', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'error' , true); end; prFreeIBSQL(GBIBSQL); prFreeIBSQL(GBIBSQLUp); if assigned(IBGRB) then cntsGRB.SetFreeCnt(IBGRB, True); if assigned(IBGRBUp) then cntsGRB.SetFreeCnt(IBGRBUp, True); prFree(jsonToSend); prFree(SLGroup); prFree(SLBody); prFree(HTTP); prFree(pIniFile); prFree(Stream); end; end; //****************************************************************************** // TCheckSMSThread //****************************************************************************** procedure TCheckSMSThread.WorkProc; const nmProc = 'TCheckSMSThread_WorkProc'; // имя процедуры/функции/потока var fOpen: boolean; rIniFile: TINIFile; procedure prSleep; var i: Integer; begin for i:= 1 to 3 do begin Application.ProcessMessages; // без этого нельзя завершить процесс TestCssStopException; sleep(331); end; end; begin rIniFile:= TINIFile.Create(nmIniFileBOB); try try CycleInterval:= rIniFile.ReadInteger('intervals', 'CheckSMSInterval', 30)*60; //min to sec if rIniFile.ReadInteger('threads', 'CheckSMS', 0)=0 then exit; fOpen:= (appStatus in [stWork]) and (cntsGRB.BaseConnected); if fOpen then prSendSMS(ThreadData); Application.ProcessMessages; TestCssStopException; sleep(997); //prMessageLOGS(nmProc+'WorkProc prTestSMS начало ','error' , false); if fOpen then prTestSMS(ThreadData); except on E:Exception do prMessageLOG(nmProc+' - внутренний охватывающий try '+E.Message); end; finally prFree(rIniFile); end; end; // WorkProc //============================================================================== constructor TCheckSMSThread.Create(CreateSuspended: Boolean; AThreadType: integer); const nmProc = 'TCheckSMSThread'; // имя процедуры/функции/потока var balance: real; SLBody: TStringList; pIniFile: TINIFile; Addrs,ss : string; UserID: integer; begin inherited Create(CreateSuspended, AThreadType); SLBody:= nil; pIniFile:= nil; ThreadName:= 'thCheckSMSThread'; DateMail:= 0; prSetThLogParams(ThreadData, 0, 0, 0, ThreadName); // логирование в ib_css prMessageLOG(nmProc+': Запуск потока отправки СМС'); (* pIniFile:= TINIFile.Create(nmIniFileBOB); try if pIniFile.ReadFloat('svitSMS', 'minBalance', -1)>0 then if date()> Cache.GetConstItem(pcLastDateTime_SMSerr).DateValue then begin SLBody:= TStringList.Create; balance:= fnTestBalance; if balance<pIniFile.ReadFloat('svitSMS', 'minBalance', 100) then begin SLBody.Add('Баланс на отправку СМС ниже установленного: '+FloatToStr(balance)+ ' Срочно пополните счет!!!'); // Addrs:= Cache.GetConstItem(pcUIKdepartmentMail).StrValue; >> 21.09.2016 12:34:30 Чичков Валерий wrote: >> Поменяйте, плз на payment@vladislav.ua Addrs:= IniFile.ReadString('mails', 'svitSMS', ''); ss:= n_SysMailSend(Addrs, 'SMS Error Balance', SLBody, nil, cNoReplayEmail, '', true); if ss<>'' then prMessageLOGS(nmProc+' Ошибка при отправке email: '+ss,'TestSMS' , true); UserID:= Cache.GetConstItem(pcEmplORDERAUTO).IntValue; Cache.SaveNewConstValue(pcLastDateTime_SMSerr, UserID, System.SysUtils.DateToStr(now)); end; end; finally prFree(SLBody); prFree(pIniFile); end; *) end; //============================================================================== procedure TCheckSMSThread.DoTerminate; begin inherited; prMessageLOG(ThreadName+': Завершение потока отправки СМС'); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { PFX particle effects revolving around the use of Perlin noise. } unit VXS.PerlinPFX; interface {$I VXScene.inc} uses System.Classes, System.Math, VXS.OpenGL, VXS.ParticleFX, VXS.Graphics, VXS.PerlinNoise3D, VXS.VectorGeometry; type { A sprite-based particles FX manager using perlin-based sprites. This PFX manager is more suited for smoke or fire effects, and with proper tweaking of the texture and perlin parameters, may help render a convincing effect with less particles. The sprite generate by this manager is the composition of a distance-based intensity and a perlin noise. } TVXPerlinPFXManager = class(TVXBaseSpritePFXManager) private FTexMapSize: Integer; FNoiseSeed: Integer; FNoiseScale: Integer; FNoiseAmplitude: Integer; FSmoothness: Single; FBrightness, FGamma: Single; protected procedure PrepareImage(bmp32: TVXBitmap32; var texFormat: Integer); override; procedure SetTexMapSize(const val: Integer); procedure SetNoiseSeed(const val: Integer); procedure SetNoiseScale(const val: Integer); procedure SetNoiseAmplitude(const val: Integer); procedure SetSmoothness(const val: Single); procedure SetBrightness(const val: Single); procedure SetGamma(const val: Single); public constructor Create(aOwner: TComponent); override; destructor Destroy; override; published { Underlying texture map size, as a power of two. Min value is 3 (size=8), max value is 9 (size=512). } property TexMapSize: Integer read FTexMapSize write SetTexMapSize default 6; { Smoothness of the distance-based intensity. This value is the exponent applied to the intensity in the texture, basically with a value of 1 (default) the intensity decreases linearly, with higher values, it will remain 'constant' in the center then fade-off more abruptly, and with values below 1, there will be a sharp spike in the center. } property Smoothness: Single read FSmoothness write SetSmoothness; { Brightness factor applied to the perlin texture intensity. Brightness acts as a scaling, non-saturating factor. Examples: Brightness = 1 : intensities in the [0; 1] range Brightness = 2 : intensities in the [0.5; 1] range Brightness = 0.5 : intensities in the [0; 0.5] range Brightness is applied to the final texture (and thus affects the distance based intensity). } property Brightness: Single read FBrightness write SetBrightness; property Gamma: Single read FGamma write SetGamma; { Random seed to use for the perlin noise. } property NoiseSeed: Integer read FNoiseSeed write SetNoiseSeed default 0; { Scale applied to the perlin noise (stretching). } property NoiseScale: Integer read FNoiseScale write SetNoiseScale default 100; { Amplitude applied to the perlin noise (intensity). This value represent the percentage of the sprite luminance affected by the perlin texture. } property NoiseAmplitude: Integer read FNoiseAmplitude write SetNoiseAmplitude default 50; property ColorMode default scmInner; property SpritesPerTexture default sptFour; property ParticleSize; property ColorInner; property ColorOuter; property LifeColors; end; // ------------------------------------------------------------------ implementation // ------------------ // ------------------ TVXPerlinPFXManager ------------------ // ------------------ constructor TVXPerlinPFXManager.Create(aOwner : TComponent); begin inherited; FTexMapSize:=6; FNoiseScale:=100; FNoiseAmplitude:=50; FSmoothness:=1; FBrightness:=1; FGamma:=1; SpritesPerTexture:=sptFour; ColorMode:=scmInner; end; destructor TVXPerlinPFXManager.Destroy; begin inherited Destroy; end; procedure TVXPerlinPFXManager.SetTexMapSize(const val : Integer); begin if val<>FTexMapSize then begin FTexMapSize:=val; if FTexMapSize<3 then FTexMapSize:=3; if FTexMapSize>9 then FTexMapSize:=9; NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetNoiseSeed(const val : Integer); begin if val<>FNoiseSeed then begin FNoiseSeed:=val; NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetNoiseScale(const val : Integer); begin if val<>FNoiseScale then begin FNoiseScale:=val; NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetNoiseAmplitude(const val : Integer); begin if val<>FNoiseAmplitude then begin FNoiseAmplitude:=val; if FNoiseAmplitude<0 then FNoiseAmplitude:=0; if FNoiseAmplitude>100 then FNoiseAmplitude:=100; NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetSmoothness(const val : Single); begin if FSmoothness<>val then begin FSmoothness:=ClampValue(val, 1e-3, 1e3); NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetBrightness(const val : Single); begin if FBrightness<>val then begin FBrightness:=ClampValue(val, 1e-3, 1e3); NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.SetGamma(const val : Single); begin if FGamma<>val then begin FGamma:=ClampValue(val, 0.1, 10); NotifyChange(Self); end; end; procedure TVXPerlinPFXManager.PrepareImage(bmp32 : TVXBitmap32; var texFormat : Integer); procedure PrepareSubImage(dx, dy, s : Integer; noise : TVXPerlin3DNoise); var s2 : Integer; x, y, d : Integer; is2, f, fy, pf, nBase, nAmp, df, dfg : Single; invGamma : Single; scanLine : PPixel32Array; gotIntensityCorrection : Boolean; begin s2:=s shr 1; is2:=1/s2; pf:=FNoiseScale*0.05*is2; nAmp:=FNoiseAmplitude*(0.01); nBase:=1-nAmp*0.5; if Gamma<0.1 then invGamma:=10 else invGamma:=1/Gamma; gotIntensityCorrection:=(Gamma<>1) or (Brightness<>1); for y:=0 to s-1 do begin fy:=Sqr((y+0.5-s2)*is2); scanLine:=bmp32.ScanLine[y+dy]; for x:=0 to s-1 do begin f:=Sqr((x+0.5-s2)*is2)+fy; if f<1 then begin df:=nBase+nAmp*noise.Noise(x*pf, y*pf); if gotIntensityCorrection then df:=ClampValue(Power(df, InvGamma)*Brightness, 0, 1); dfg:=Power((1-Sqrt(f)), FSmoothness); d:=Trunc(df*255); if d > 255 then d:=255; with scanLine^[x+dx] do begin r:=d; g:=d; b:=d; a:=Trunc(dfg*255); end; end else PInteger(@scanLine[x+dx])^:=0; end; end; end; var s, s2 : Integer; noise : TVXPerlin3DNoise; begin s:=(1 shl TexMapSize); bmp32.Width:=s; bmp32.Height:=s; bmp32.Blank := false; texFormat:=GL_LUMINANCE_ALPHA; noise:=TVXPerlin3DNoise.Create(NoiseSeed); try case SpritesPerTexture of sptOne : PrepareSubImage(0, 0, s, noise); sptFour : begin s2:=s div 2; PrepareSubImage(0, 0, s2, noise); noise.Initialize(NoiseSeed+1); PrepareSubImage(s2, 0, s2, noise); noise.Initialize(NoiseSeed+2); PrepareSubImage(0, s2, s2, noise); noise.Initialize(NoiseSeed+3); PrepareSubImage(s2, s2, s2, noise); end; else Assert(False); end; finally noise.Free; end; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ RegisterClasses([TVXPerlinPFXManager]); end.
unit uRegSCH; {******************************************************************************* * * * Название модуля : * * * * uRegSCH * * * * Назначение модуля : * * * * Ведение реестра счетов по заработной плате и стипендии. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, DB, FIBDataSet, pFIBDataSet, cxInplaceContainer, cxTLData, cxDBTL, cxControls, cxSplitter, ExtCtrls, dxBar, cxMaskEdit, dxBarExtItems, cxLookAndFeelPainters, StdCtrls, cxButtons, cxContainer, cxEdit, cxTextEdit, cxDropDownEdit, dxBarExtDBItems, ActnList, cxCheckBox, cxDBEdit, FIBQuery, pFIBQuery, pFIBStoredProc, cxCurrencyEdit, frxClass, frxDBSet, RxMemDS, FIBDatabase, pFIBDatabase, uneClasses, ImgList, uneTypes, uneLibrary; type TfmRegSCH = class(TForm, IneCallExpMethod) brmSchet : TdxBarManager; Splitter1 : TcxSplitter; pnlDescription : TPanel; trlSchet : TcxDBTreeList; dsrSchet : TDataSource; dstSchet : TpFIBDataSet; dstRegUch : TpFIBDataSet; btnAdd : TdxBarLargeButton; btnExit : TdxBarLargeButton; btnEdit : TdxBarLargeButton; btnWatch : TdxBarLargeButton; btnSelect : TdxBarLargeButton; btnFilter : TdxBarLargeButton; btnDelete : TdxBarLargeButton; btnRefresh : TdxBarLargeButton; btnOpenSch : TdxBarLargeButton; btnCloseSch : TdxBarLargeButton; cmnID_SCH : TcxDBTreeListColumn; cmnKR_SUMMA : TcxDBTreeListColumn; cmnDB_SUMMA : TcxDBTreeListColumn; cmnSCH_TITLE : TcxDBTreeListColumn; cmnSCH_NUMBER : TcxDBTreeListColumn; cmnHAS_CHILDREN : TcxDBTreeListColumn; cmnDB_SALDO_CUR : TcxDBTreeListColumn; cmn_KR_SALDO_CUR : TcxDBTreeListColumn; cmnID_PARENT_SCH : TcxDBTreeListColumn; cmnDB_SALDO_INPUT : TcxDBTreeListColumn; cmnKR_SALDO_INPUT : TcxDBTreeListColumn; edtYear : TdxBarCombo; edtMonth : TdxBarCombo; edtRegUch : TdxBarCombo; cbxIsSchClosed : TcxDBCheckBox; cbxIsSchLocked : TcxDBCheckBox; spcSchet : TpFIBStoredProc; btnPrint : TdxBarLargeButton; DBDataset : TfrxDBDataset; dstBuffer : TRxMemoryData; fldSCH_TITLE : TStringField; fldSCH_ERROR : TStringField; fldSCH_NUMBER : TStringField; Report : TfrxReport; imlToolBar : TImageList; dbSchet : TpFIBDatabase; trRead : TpFIBTransaction; trWrite : TpFIBTransaction; srpMain : TcxStyleRepository; cxsHeader : TcxStyle; cxsFooter : TcxStyle; cxsContent : TcxStyle; cxHotTrack : TcxStyle; cxsInactive : TcxStyle; cxsIndicator : TcxStyle; cxsSelection : TcxStyle; cxBackground : TcxStyle; cxsContentOdd : TcxStyle; cxsGroupByBox : TcxStyle; cxsColumnHeader : TcxStyle; cxsContentEvent : TcxStyle; cxsColumnHeaderClassic : TcxStyle; trTmp: TpFIBTransaction; procedure FormClose (Sender: TObject; var Action: TCloseAction); procedure btnExitClick (Sender: TObject); procedure btnPrintClick (Sender: TObject); procedure btnWatchClick (Sender: TObject); procedure btnFilterClick (Sender: TObject); procedure btnSelectClick (Sender: TObject); procedure btnRefreshClick (Sender: TObject); procedure btnOpenSchClick (Sender: TObject); procedure btnCloseSchClick (Sender: TObject); procedure trlSchetKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure trlSchetDblClick (Sender: TObject); procedure ReportGetValue (const VarName: String; var Value: Variant); procedure edtYearCurChange (Sender: TObject); procedure edtMonthCurChange (Sender: TObject); private FKeyField : String; //Поле хранит пазвание поля, содерж. знач. PK FSchParams : TRec_SchParams; //Поле хранит параметры для получения оборотов по счетам FSysOptions : TRec_SysOptions; //Поле хранит параметры для получения оборотов по счетам FResultExpMethod : TneGetExpMethod; //Методы для работы с вышеописаными полями function GetKeyField : String; function GetSchParams : TRec_SchParams; function GetSysOptions : TRec_SysOptions; procedure SetSchParams ( aValue: TRec_SchParams ); public constructor Create( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions ); reintroduce; //Св-ва, соответствующие вышеописанным полям Property pKeyField : String read GetKeyField; Property pSchParams : TRec_SchParams read GetSchParams write SetSchParams; Property pSysOptions : TRec_SysOptions read GetSysOptions; property pResultExpMethod : TneGetExpMethod read FResultExpMethod implements IneCallExpMethod; end; function GetFmRegSCH( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions ): TRec_SysOptions; stdcall; exports GetFmRegSCH; implementation uses DateUtils, uneUtils, {uErrorSch,} Kernel; resourcestring //Ресурсы, сообщения для отчётов + идентификаторы динамических переменных sReportsPath = 'Reports\JO5\'; sRepNameAllSCH = 'JO5_ALL_SCH_INFO.fr3'; sValNameVisa = 'Visa'; sValNamePeriod = 'Period'; sValVisaText = 'ДонНУ'#13; sValPeriodText = ' г.'; sMsgReportNotFound1 = 'Файл отчета '; sMsgReportNotFound2 = ' не найден!'; //Сообщения закрытия(отката) текущего счёта sMsgSchIsAbsent = 'Текущий счёт не найден'; sMsgSchIsOpened = 'Невозможно открыть текущий счёт,'#13'поскольку он был открыт ранее'; sMsgSchIsClosed = 'Невозможно закрыть текущий счёт,'#13'поскольку он был закрыт ранее'; sMsgSchIsParentOp = 'Невозможно открыть текущий счёт,'#13'поскольку он не является субсчётом'; sMsgSchIsParentCl = 'Невозможно закрыть текущий счёт,'#13'поскольку он не является субсчётом'; sMsgDataSetIsEmpty = 'Невозможно распечатать информацию по'#13'счетам, поскольку реестр счетов пуст'; sMsgOKOpenSCH = 'Cчёт успешно переведён в предыдущий период'; sMsgOKCloseSCH = 'Cчёт успешно переведён в следующий период'; sMsgErrOpenSCH = 'Не удалось откатить счёт в предыдущий период...'#13'Показать расшифровку ошибки для неоткатившегося счёта?'; sMsgErrCloseSCH = 'Не удалось перевести счёт в следующий период...'#13'Показать расшифровку ошибки для непереведённого счёта?'; //Сообщения получения корреспонденции sMSG_SelectSubSCH_UA = 'Для того, щоб переглянути кореспонденцію по рахунку,'#13'оберіть, будь ласка, рахунок нижчого рівня'; sMSG_SelectSubSCH_RUS = 'Для того, чтобы просмотреть корреспонденцию по счету,'#13'выберите, пожалуйста, счет нижнего уровня'; sMSG_KorrIsNotFound_UA = 'Неможливо отримати кореспонденцію,'#13'тому що відсутній обраний рахунок'; sMSG_KorrIsNotFound_RUS = 'Невозможно получить корреспонденцию,'#13'поскольку отсутствует выбранный счёт'; {$R *.dfm} function TfmRegSCH.GetKeyField: String; begin Result := FKeyField; end; function TfmRegSCH.GetSchParams: TRec_SchParams; begin Result := FSchParams; end; function TfmRegSCH.GetSysOptions: TRec_SysOptions; begin Result := FSysOptions; end; procedure TfmRegSCH.SetSchParams(aValue: TRec_SchParams); begin FSchParams := aValue; end; procedure TfmRegSCH.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfmRegSCH.btnExitClick(Sender: TObject); begin Close; end; function GetFmRegSCH( const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions ): TRec_SysOptions; begin TfmRegSCH.Create( aDBFMParams, aSysOptions ); end; //Получаем информацию по счетам для текущего периода constructor TfmRegSCH.Create(const aDBFMParams: TRec_DBFMParams; const aSysOptions: TRec_SysOptions); begin try inherited Create( aDBFMParams.Owner ); FKeyField := 'OUT_ID_SCH'; FSysOptions := aSysOptions; try dbSchet.Handle := aDBFMParams.DBHandle; trTmp.StartTransaction; //trRead.StartTransaction; except on E: Exception do begin ShowMessage( E.Message + ' System Error!!!' ); end; end; //Запоминаем параметы для получения оборотов по счетам { with FSchParams do begin KodSystem := pSysOptions.KodSystem; DefRegUch := pSysOptions.DefRegUch; RootTypeObj := pSysOptions.RootTypeObj; KodSysPeriod := pSysOptions.KodCurrPeriod; KodCurrPeriod := pSysOptions.KodCurrPeriod; DateSysPeriod := pSysOptions.DateCurrPeriod; DateCurrPeriod := pSysOptions.DateCurrPeriod; end; with pSchParams do begin //Получаем информацию по счетам для текущего периода if dstSchet.Active then dstSchet.Close; trWrite.StartTransaction; dstSchet.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_OBORT(' + IntToStr( DefRegUch ) + cSEMICOLON + cTICK + DateToStr( DateCurrPeriod ) + cTICK + cSEMICOLON + IntToStr( RootTypeObj ) + cBRAKET_CL; dstSchet.Open; //Получаем множество регистров учёта dstRegUch.Close; dstRegUch.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_REG_UCH(' + IntToStr( KodSystem ) + cBRAKET_CL; dstRegUch.Open; edtYear.CurText := IntToStr( YearOf( DateCurrPeriod ) ); edtMonth.CurItemIndex := MonthOf( DateCurrPeriod ) - 1; end; dstRegUch.First; //Заполняем список регистров учёта while not dstRegUch.Eof do begin edtRegUch.Items.Add( dstRegUch.FBN('OUT_REG_UCH_FULL_NAME').AsString ); dstRegUch.Next; end; dstRegUch.Locate( 'OUT_ID_REG_UCH', pSchParams.DefRegUch, [] ); edtRegUch.CurText := dstRegUch.FBN('OUT_REG_UCH_FULL_NAME').AsString;} except on E: Exception do begin MessageBox( Handle, PChar( E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR ); LogException( pSysOptions.LogFileName ); end; end; end; //Получаем корреспонденцию для выбранного счёта procedure TfmRegSCH.btnWatchClick(Sender: TObject); var vMTDParams : TPtr_MTDParams; vBPLParams : TPtr_BPLParams; begin try if not dstSchet.IsEmpty then begin try New( vBPLParams ); vBPLParams^.MethodName := sMN_GetKorToSCH; vBPLParams^.PackageName := pSysOptions.AppExePath + 'JO5\JO5_GetKorToSCH7.bpl'; New( vMTDParams ); with vMTDParams^ do begin KorParams.IdSch := dstSchet.FBN(pKeyField).AsVariant; KorParams.SchName := dstSchet.FBN(cmnSCH_TITLE.DataBinding.FieldName).AsString; KorParams.IdRegUch := dstRegUch.FBN('OUT_ID_REG_UCH').AsVariant; KorParams.CurrPeriod := pSchParams.DateCurrPeriod; KorParams.HasChildren := dstSchet.FBN('OUT_HAS_CHILDREN_BOOLEAN').AsBoolean; DBFMParams.Owner := Self; DBFMParams.Style := fsModal; DBFMParams.DBHandle := dbSchet.Handle; end; FResultExpMethod := TneGetExpMethod.Create( Self, vBPLParams, vMTDParams ); finally FreeAndNil( FResultExpMethod ); if vBPLParams <> nil then begin Dispose( vBPLParams ); vBPLParams := nil; end; if vMTDParams <> nil then begin Dispose( vMTDParams ); vMTDParams := nil; end; end; end else begin MessageBox( Handle, PChar( sMSG_KorrIsNotFound_UA ), PChar( sMsgCaptionInfUA ), MB_OK or MB_ICONINFORMATION ); end; except on E: Exception do begin ShowMessage('System message'); MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Получаем информацию по счетам для изменившихся критериев фильтрации procedure TfmRegSCH.btnFilterClick(Sender: TObject); var ID : Int64; begin try with pSchParams do begin dstRegUch.Locate('OUT_REG_UCH_FULL_NAME', edtRegUch.CurText, [] ); DefRegUch := dstRegUch.FBN('OUT_ID_REG_UCH').AsVariant; ID := dstSchet.FBN(pKeyField).AsVariant; //Получаем информацию по счетам для текущего периода trlSchet.BeginUpdate; if dstSchet.Active then dstSchet.Close; trWrite.StartTransaction; dstSchet.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_OBORT(' + IntToStr( DefRegUch ) + cSEMICOLON + cTICK + DateToStr( DateCurrPeriod ) + cTICK + cSEMICOLON + IntToStr( RootTypeObj ) + cBRAKET_CL; dstSchet.Open; trlSchet.DataController.BeginLocate; dstSchet.Locate( pKeyField, ID, [] ); trlSchet.DataController.EndLocate; trlSchet.EndUpdate; end; except LogException( pSysOptions.LogFileName ); end; end; //Закрываем текущий счёт procedure TfmRegSCH.btnCloseSchClick(Sender: TObject); var ModRes : Byte; IdSCH : Int64; IsOpen : Boolean; IsClose : Boolean; IsChild : Boolean; NewSaldo : Currency; MonthNum : String; // fmErrorSch : TfmErrorSch; IsSchSingle : Boolean; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin try try if not dstSchet.IsEmpty then begin //Подготавливаем буфер для протоколирования возможных ошибок закрытия счёта if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsOpen := dstSchet.FBN('OUT_IS_OPEN_BOOLEAN').AsBoolean; IsChild := not dstSchet.FBN('OUT_HAS_CHILDREN_BOOLEAN').AsBoolean; IsClose := True; //Проверяем: возможно ли корректное закрытие текущего счёта? if ( IsOpen and IsChild ) then begin try IdSCH := dstSchet.FBN('OUT_ID_SCH').AsVariant; //Заполняем структуру для менеджера счетов New( PKernelSchStr ); trWrite.StartTransaction; PKernelSchStr^.MODE := Ord( mmCloseSch ); PKernelSchStr^.DBHANDLE := dstSchet.Database.Handle; PKernelSchStr^.TRHANDLE := trWrite.Handle; PKernelSchStr^.ID_SCH := IdSCH; PKernelSchStr^.DB_OBOR := dstSchet.FBN('OUT_DB_SUMMA' ).AsCurrency; PKernelSchStr^.KR_OBOR := dstSchet.FBN('OUT_KR_SUMMA' ).AsCurrency; PKernelSchStr^.DB_SALDO_IN := dstSchet.FBN('OUT_DB_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.KR_SALDO_IN := dstSchet.FBN('OUT_KR_SALDO_INPUT' ).AsCurrency; PKernelSchStr^.DB_SALDO_OUT := dstSchet.FBN('OUT_DB_SALDO_CUR' ).AsCurrency; PKernelSchStr^.KR_SALDO_OUT := dstSchet.FBN('OUT_KR_SALDO_CUR' ).AsCurrency; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); trWrite.Commit; //Анализируем результат перевода текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) then begin //Запоминаем информацию для непереведённого счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := dstSchet.FBN('OUT_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := dstSchet.FBN('OUT_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsClose := False; end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil then begin Dispose( PKernelSchStr ); PKernelSchStr := nil; end; end; //Оповещаем пользователя о результатах перевода текущего счёта в следующий период if IsClose then begin //Проверяем: является ли данный счёт единственным незакрытым в текущем периоде? spcSchet.StoredProcName := 'JO5_IS_SCH_SINGLE_IN_CUR_PERIOD'; spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.ParamByName('IN_IS_CLOSE').AsInteger := Ord( smClose ); trWrite.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; trWrite.Commit; //Получаем результат проверки IsSchSingle := Boolean( spcSchet.FN('OUT_SCH_IS_SINGLE_BOOLEAN').AsInteger ); //Удалям существующее вступительное сальдо для следующего периода spcSchet.StoredProcName := 'JO5_DT_SALDO_DEL_EXT'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; trWrite.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; //Добавляем пресчитанное вступительное сальдо для следующего периода spcSchet.StoredProcName := 'JO5_DT_SALDO_INS_EXT'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.Prepare; spcSchet.ExecProc; //Анализируем необходимость переведения всей системы в следующий период if IsSchSingle then begin //Переводим систему в следующий период spcSchet.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose ); spcSchet.Prepare; spcSchet.ExecProc; //Получаем данные для текущего периода системы with pSysOptions do begin KodCurrPeriod := spcSchet.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; DateCurrPeriod := spcSchet.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum := IntToStr( MonthOf( DateCurrPeriod ) ); SetFirstZero( MonthNum ); //fmMain.mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; end; end; trWrite.Commit; MessageBox( Handle, PChar( sMsgOKCloseSCH ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else begin ModRes := MessageBox( Handle, PChar( sMsgErrCloseSCH ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Показываем расшифровку ошибок для текущего счёта if ModRes = ID_YES then begin { try fmErrorSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrorSch.ShowModal; finally FreeAndNil( fmErrorSch ); end;} end; end; dstBuffer.Close; end else begin //Извещаем пользователя о причинах отказа в закрытии текущего счёта if not IsChild then MessageBox( Handle, PChar( sMsgSchIsParentCl ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ) else if not IsOpen then MessageBox( Handle, PChar( sMsgSchIsClosed ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; end else begin MessageBox( Handle, PChar( sMsgSchIsAbsent ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; except //Завершаем транзанкцию if trWrite.InTransaction then trWrite.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС LogException( pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Открываем текущий счёт procedure TfmRegSCH.btnOpenSchClick(Sender: TObject); var ModRes : Byte; IdSCH : Int64; IsOpen : Boolean; IsClose : Boolean; IsChild : Boolean; MonthNum : String; // fmErrSch : TfmErrorSch; IsSchSingle : Boolean; ResultSchStr : RESULT_STRUCTURE; PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE; begin try try if not dstSchet.IsEmpty then begin //Подготавливаем буфер для протоколирования возможных ошибок открытия счёта if dstBuffer.Active then dstBuffer.Close; dstBuffer.Open; IsOpen := True; IsClose := not dstSchet.FBN('OUT_IS_OPEN_BOOLEAN').AsBoolean; IsChild := not dstSchet.FBN('OUT_HAS_CHILDREN_BOOLEAN').AsBoolean; //Проверяем: возможно ли корректное открытие текущего счёта? if ( IsClose and IsChild ) then begin try IdSCH := dstSchet.FBN('OUT_ID_SCH').AsVariant; //Заполняем структуру для менеджера счетов New( PKernelSchStr ); trWrite.StartTransaction; PKernelSchStr^.MODE := Ord( mmOpenSch ); PKernelSchStr^.DBHANDLE := dstSchet.Database.Handle; PKernelSchStr^.TRHANDLE := trWrite.Handle; PKernelSchStr^.ID_SCH := IdSCH; //Вызываем менеджер счетов ResultSchStr := SchManager( PKernelSchStr ); trWrite.Commit; //Анализируем результат перевода текущего счёта if ResultSchStr.RESULT_CODE = Ord( msrError ) then begin //Запоминаем информацию для непереведённого счёта dstBuffer.Insert; dstBuffer.FieldByName('SCH_NUMBER').Value := dstSchet.FBN('OUT_SCH_NUMBER').AsString; dstBuffer.FieldByName('SCH_TITLE' ).Value := dstSchet.FBN('OUT_SCH_TITLE' ).AsString; dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE; dstBuffer.Post; IsOpen := False; end; finally //Освобождаем динамически выделенную память if PKernelSchStr <> nil then begin Dispose( PKernelSchStr ); PKernelSchStr := nil; end; end; //Оповещаем пользователя о результатах перевода текущего счёта в предыдущий период if IsOpen then begin //Проверяем: является ли данный счёт единственным закрытым в текущем периоде? spcSchet.StoredProcName := 'JO5_IS_SCH_SINGLE_IN_CUR_PERIOD'; spcSchet.ParamByName('IN_ID_SCH' ).AsInt64 := IdSCH; spcSchet.ParamByName('IN_IS_CLOSE').AsInteger := Ord( smOpen ); trWrite.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; trWrite.Commit; //Получаем результат проверки IsSchSingle := Boolean( spcSchet.FN('OUT_SCH_IS_SINGLE_BOOLEAN').AsInteger ); //Анализируем необходимость переведения всей системы в предыдущий период if IsSchSingle then begin //Переводим систему в предыдущий период spcSchet.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD'; spcSchet.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smOpen ); trWrite.StartTransaction; spcSchet.Prepare; spcSchet.ExecProc; trWrite.Commit; //Получаем данные для текущего периода системы with pSysOptions do begin KodCurrPeriod := spcSchet.FN('OUT_KOD_CURR_PERIOD' ).AsInteger; DateCurrPeriod := spcSchet.FN('OUT_DATE_CURR_PERIOD').AsDate; //Обновляем значение текущего периода MonthNum := IntToStr( MonthOf( DateCurrPeriod ) ); SetFirstZero( MonthNum ); //fmMain.mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT; end; end; MessageBox( Handle, PChar( sMsgOKOpenSCH ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else begin ModRes := MessageBox( Handle, PChar( sMsgErrOpenSCH ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Показываем расшифровку ошибок для текущего счёта if ModRes = ID_YES then begin { try fmErrSch := TfmErrorSch.Create( Self, dstBuffer ); fmErrSch.ShowModal; finally FreeAndNil( fmErrSch ); end;} end; end; dstBuffer.Close; end else begin //Извещаем пользователя о причинах отказа в открытии текущего счёта if not IsChild then MessageBox( Handle, PChar( sMsgSchIsParentOp ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ) else if not IsClose then MessageBox( Handle, PChar( sMsgSchIsOpened ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; end else begin MessageBox( Handle, PChar( sMsgSchIsAbsent ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; except //Завершаем транзанкцию if trWrite.InTransaction then trWrite.Rollback; //Освобождаем память для НД if dstBuffer.Active then dstBuffer.Close; //Протоколируем ИС LogException( pSysOptions.LogFileName ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Обновляем информацию по всем счётам procedure TfmRegSCH.btnRefreshClick(Sender: TObject); var ID : Int64; IdRec : Integer; CurrDate : TDate; RowIndex : Integer; begin with pSchParams do begin dstRegUch.Locate('OUT_REG_UCH_FULL_NAME', edtRegUch.CurText, [] ); DefRegUch := dstRegUch.FBN('OUT_ID_REG_UCH').AsVariant; if not dstSchet.IsEmpty then begin ID := dstSchet.FBN( pKeyField ).AsVariant; RowIndex := trlSchet.DataController.FocusedRowIndex; trlSchet.BeginUpdate; dstSchet.Close; dstSchet.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_OBORT(' + IntToStr( DefRegUch ) + cSEMICOLON + cTICK + DateToStr( DateCurrPeriod ) + cTICK + cSEMICOLON + IntToStr( RootTypeObj ) + cBRAKET_CL; dstSchet.Open; trlSchet.EndUpdate; trlSchet.DataController.BeginLocate; //Позиционируемся на записи, на которой "стояли" до переоткрытия набора данных if not( dstSchet.IsEmpty OR dstSchet.Locate( pKeyField, ID, [] ) ) then begin //Позиционируемся на близлежащей записи по отношению к //ранее выделенной, если она была удалена с другого клиента trlSchet.DataController.FocusedRowIndex := RowIndex; IdRec := trlSchet.DataController.GetRecordId( trlSchet.DataController.GetFocusedRecordIndex ); dstSchet.Locate( pKeyField, IdRec, [] ); end; trlSchet.DataController.EndLocate; end else begin trlSchet.BeginUpdate; dstSchet.Close; dstSchet.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_OBORT(' + IntToStr( DefRegUch ) + cSEMICOLON + cTICK + DateToStr( DateCurrPeriod ) + cTICK + cSEMICOLON + IntToStr( RootTypeObj ) + cBRAKET_CL; dstSchet.Open; trlSchet.EndUpdate; end; end; end; procedure TfmRegSCH.btnSelectClick(Sender: TObject); var vMTDParams : TPtr_MTDParams; vBPLParams : TPtr_BPLParams; begin try try New( vBPLParams ); vBPLParams^.MethodName := sMN_GetJO5SchSaldo; vBPLParams^.PackageName := pSysOptions.AppExePath + 'JO5\SaldoBySmRzSt.bpl'; New( vMTDParams ); with vMTDParams^ do begin SmRzSt.IdUser := dstSchet.FBN(pKeyField).AsVariant; SmRzSt.ActualDate := pSchParams.DateCurrPeriod; DBFMParams.Owner := Self; DBFMParams.Style := fsModal; DBFMParams.DBHandle := dbSchet.Handle; end; FResultExpMethod := TneGetExpMethod.Create( Self, vBPLParams, vMTDParams ); finally FreeAndNil( FResultExpMethod ); Dispose( vBPLParams ); Dispose( vMTDParams ); vBPLParams := nil; vMTDParams := nil; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; procedure TfmRegSCH.trlSchetDblClick(Sender: TObject); begin btnSelect.Click; end; //Организуем перемещение по дереву с помощью клавиатуры procedure TfmRegSCH.trlSchetKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN : begin btnSelect.Click; end; VK_LEFT : begin if trlSchet.FocusedNode.CanCollapse then trlSchet.FocusedNode.Collapse( False ); end; VK_RIGHT : begin if trlSchet.FocusedNode.CanExpand then trlSchet.FocusedNode.Expand( False ); end; end; end; //Печать информации по всем счета для текущего периода procedure TfmRegSCH.btnPrintClick(Sender: TObject); var ID : Int64; IdRec : Integer; RowIndex : Integer; begin try if not dstSchet.IsEmpty then begin //Выводим отчет на экран if Report.LoadFromFile( sReportsPath + sRepNameAllSCH ) then begin ID := dstSchet.FBN( pKeyField ).AsVariant; RowIndex := trlSchet.DataController.FocusedRowIndex; dstSchet.DisableControls; Report.ShowReport; trlSchet.DataController.BeginLocate; //Позиционируемся на записи, на которой "стояли" до переоткрытия набора данных if not dstSchet.Locate( pKeyField, ID, [] ) then begin //Позиционируемся на близлежащей записи по отношению к //ранее выделенной, если она была удалена с другого клиента trlSchet.DataController.FocusedRowIndex := RowIndex; IdRec := trlSchet.DataController.GetRecordId( trlSchet.DataController.GetFocusedRecordIndex ); dstSchet.Locate( pKeyField, IdRec, [] ); end; trlSchet.DataController.EndLocate; end else begin MessageBox( Handle, PChar( sMsgReportNotFound1 + sReportsPath + sRepNameAllSCH + sMsgReportNotFound2 ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) end; end else begin MessageBox( Handle, PChar( sMsgDataSetIsEmpty ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) end; finally if dstSchet.ControlsDisabled then dstSchet.EnableControls; end; end; //Получаем динамические параметры для печати отчёта procedure TfmRegSCH.ReportGetValue(const VarName: String; var Value: Variant); begin if VarName = sValNamePeriod then Value := GetMonthName( pSchParams.DateCurrPeriod ) + cSPACE + IntToStr( YearOf ( pSchParams.DateCurrPeriod ) ) + cSPACE + sValPeriodText else if VarName = sValNameVisa then Value := sValVisaText + DateToStr( Date ); end; //Получаем актуальное значение для текущего периода при изменениии месяца procedure TfmRegSCH.edtMonthCurChange(Sender: TObject); begin FSchParams.DateCurrPeriod := EncodeDate( StrToInt( edtYear.CurText ), edtMonth.CurItemIndex + 1, cFIRST_DAY_OF_MONTH ); end; //Получаем актуальное значение для текущего периода при изменениии года procedure TfmRegSCH.edtYearCurChange(Sender: TObject); begin FSchParams.DateCurrPeriod := EncodeDate( StrToInt( edtYear.CurText ), edtMonth.CurItemIndex + 1, cFIRST_DAY_OF_MONTH ); end; end.
// ################################## // ###### IT PAT 2018 ####### // ###### GrowCery ####### // ###### Tiaan van der Riel ####### // ################################## unit frmCreateNewAccount_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, pngimage, ExtCtrls, StdCtrls, Spin; type TfrmCreateNewAccount = class(TForm) rbMale: TRadioButton; rbFemale: TRadioButton; lblDateOfBirth: TLabel; spnedtYearOfBirth: TSpinEdit; cbxMonth: TComboBox; spnedtDayOfBirth: TSpinEdit; lblGenderM: TLabel; lblGenderF: TLabel; lblGender: TLabel; lbledtName: TLabeledEdit; lbledtSurname: TLabeledEdit; lbledtID: TLabeledEdit; lbledtEmailAdress: TLabeledEdit; lbledtCellphoneNumber: TLabeledEdit; lbledtPassword: TLabeledEdit; lbledtRetypePassword: TLabeledEdit; btnCreateAccount: TButton; btnBack: TButton; imgCreateNewAccountBackground: TImage; pnlLabels: TPanel; imgCreateNewAccountHeading: TImage; rgpGrantAdminRights: TRadioGroup; spnEdtAssignedTill: TSpinEdit; lblAssighnedTill: TLabel; btnHelp: TButton; procedure btnBackClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCreateAccountClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure rgpGrantAdminRightsClick(Sender: TObject); private { Private declarations } sAccountID: string; sName: string; sSurname: string; bIsAdmin: boolean; iAssighnedTill: integer; iIDNumber: integer; sGender: string; sEmailAdress: string; sCellphoneNumber: string; sPassword: string; sPleaseRetypePassword: string; iEnteredBirthDay: integer; iEnteredBirthMonth: integer; iEnteredBirthYear: integer; iAdminRigthsIndex: integer; sNewAccountID: string; /// ============= Custom Procedures =========/// procedure ResetAll; // Resets form to the way it initially looked procedure ShowHelp; // Shows the user a help file procedure ShowHelpAfterIncorrectAttempt; // // ========= Custom Functions ===============// Function IsAllFieldsPresent: boolean; // 1.) Determines if all fields are entered Function IsNameValid: boolean; // 2.) Determines if name is valid Function IsSurnameValid: boolean; // 3.) Determine if surname is valid Function IsCellphoneNumberValid: boolean; // 4.) Determines if cellphone number is 10 DIGITS long Function IsPasswordValid: boolean; // 5.) Checks that password is at least 8 characters long, and contains at least // one uppercase letter, one lowercase letter and at least one number. // ====== Functions for ID Validation ====== // Function IsIDNumberValidNumbers: boolean; // 6.) Function that checks that the ID Number contains only numbers and is 13 digits long Function IsIDNumberValidBirthDate: boolean; // 7.) Checks that the user`s enterd bithdates match ID Function IsIDNumberValidGender: boolean; // 8. ) Checks that the user`s gender matches his ID`s Function IsIDNumberValidCheckDigit: boolean; // 9.) Checks that the check digit validates according to Luhn`s equation // Function DeterminePlayerAge: integer; // 10.) Determines the user`s age // Function GenerateAccountID: string; // 11.) Generates a new, unique AccountID for the new user. // procedure SaveDataToDatabase; // 12.) Saves all of the new user`s data to the database public { Public declarations } end; var frmCreateNewAccount: TfrmCreateNewAccount; implementation uses frmAdminHomeScreen_u, dmDatabase_u; {$R *.dfm} /// =================== Create New Account Button Click ======================= procedure TfrmCreateNewAccount.btnCreateAccountClick(Sender: TObject); { The function of this code is to initialise the checking of all of the criteria and then, if all criteria are met, initialise the creation of a new account, or, if one is not met, initialise the showing of an error message and a help file } var bAllFieldsEntered: boolean; bNamevalid: boolean; bSurnamevalid: boolean; bCellphoneNumberValid: boolean; bPasswordValid: boolean; // Boolaens calling functions for ID Validation bIDNumberValidNumbers: boolean; bIDNumberValidBirthDate: boolean; bIDNumberValidGender: boolean; bIDNumberValidCheckDigit: boolean; // Gets calculated when user`s account gets created // Determine from function iPlayersAge: integer; begin // 1.) Presence check bAllFieldsEntered := IsAllFieldsPresent; // Calls function if bAllFieldsEntered = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 2.) Name Valid bNamevalid := IsNameValid; // Calls function if bNamevalid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 3.) Surname Valid bSurnamevalid := IsSurnameValid; // Calls function if bSurnamevalid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 4.) Cellphone Number Valid bCellphoneNumberValid := IsCellphoneNumberValid; if bCellphoneNumberValid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 5.) Password Valid bPasswordValid := IsPasswordValid; if bPasswordValid = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // Password Retype sPleaseRetypePassword := lbledtRetypePassword.Text; if NOT(sPleaseRetypePassword = sPassword) then begin ShowMessage( 'One of your passwords was entered incorectly and they don`t match.'); if MessageDlg( 'You entered your information incorrectly. Would you like to veiw help as to how to enter your information ?', mtInformation, [mbYes, mbNo], 0) = mrYes then Begin ShowHelp; End Else Begin Exit; End; end; // ================================================ // 6.) Is ID Numeber valid - Only Numbers + correct lenght bIDNumberValidNumbers := IsIDNumberValidNumbers; if bIDNumberValidNumbers = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 7.) Checks that the user`s enterd bithdates match ID bIDNumberValidBirthDate := IsIDNumberValidBirthDate; if bIDNumberValidBirthDate = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 8.) Checks that the user`s gender matches his ID bIDNumberValidGender := IsIDNumberValidGender; if bIDNumberValidGender = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // ================================================ // 9.) Checks that the check digit matches what it should be according to Luhn`s equation bIDNumberValidCheckDigit := IsIDNumberValidCheckDigit; if bIDNumberValidCheckDigit = False then begin ShowHelpAfterIncorrectAttempt; Exit; end; // Get Gender if rbFemale.Checked = True then sGender := 'F'; if rbMale.Checked = True then sGender := 'M'; // Determine the user`s age and check that he/she is at least 16 years old iPlayersAge := DeterminePlayerAge; if iPlayersAge < 16 then Begin ShowMessage('The applicant is currently ' + IntToStr(iPlayersAge) + ' years of age. Employees need to be at least 16 years of age.'); Exit; End; /// Checks that user entered if the new account is a Admin or not iAdminRigthsIndex := rgpGrantAdminRights.ItemIndex; if (iAdminRigthsIndex < 0) OR (iAdminRigthsIndex > 1) then Begin begin ShowHelpAfterIncorrectAttempt; Exit; end; End; // Generate a new, unique Account ID for the user sAccountID := GenerateAccountID; // ShowMessage('Your new Account ID is: ' + sAccountID + #13 + 'NB Please make sure to remember your Account ID and Password.'); // SaveDataToDatabase; /// Saves all of the data // ResetAll; // Resets all of the fields end; /// 1.) ======== Function to detirmine if all fields are entered ============== function TfrmCreateNewAccount.IsAllFieldsPresent: boolean; { The purpose of this procedure is to determine if all of the fields are entered } begin IsAllFieldsPresent := True; // Name sName := lbledtName.Text; if sName = '' then Begin ShowMessage('Please enter a name.'); lbledtName.EditLabel.Font.Color := clRed; lbledtName.EditLabel.Caption := '*** Name:'; IsAllFieldsPresent := False; End; // Surname sSurname := lbledtSurname.Text; if sSurname = '' then Begin ShowMessage('Please enter a surname.'); lbledtSurname.EditLabel.Font.Color := clRed; lbledtSurname.EditLabel.Caption := '*** Surname:'; IsAllFieldsPresent := False; End; // ID Number if lbledtID.Text = '' then Begin ShowMessage('Please enter a ID'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID:'; IsAllFieldsPresent := False; End; // Gender if (rbMale.Checked = False) AND (rbFemale.Checked = False) then Begin ShowMessage('Please select a gender. '); lblGender.Font.Color := clRed; lblGender.Caption := '*** Gender:'; IsAllFieldsPresent := False; End; // Email sEmailAdress := lbledtEmailAdress.Text; if sEmailAdress = '' then Begin ShowMessage('Please enter a Email Adress.'); lbledtEmailAdress.EditLabel.Font.Color := clRed; lbledtEmailAdress.EditLabel.Caption := '*** Email Aress:'; IsAllFieldsPresent := False; End; // Cellphone Number sCellphoneNumber := lbledtCellphoneNumber.Text; if sCellphoneNumber = '' then Begin ShowMessage('Please enter a Cellphone Number.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsAllFieldsPresent := False; End; // Password sPassword := lbledtPassword.Text; if sPassword = '' then Begin ShowMessage('Please enter a password.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsAllFieldsPresent := False; End; // Please Retype Password sPleaseRetypePassword := lbledtRetypePassword.Text; if sPleaseRetypePassword = '' then Begin ShowMessage('Please retype your password.'); lbledtRetypePassword.EditLabel.Font.Color := clRed; lbledtRetypePassword.EditLabel.Caption := '*** Please Retype Your Password:'; IsAllFieldsPresent := False; End; // Grant Admin Rights if rgpGrantAdminRights.ItemIndex = -1 then begin ShowMessage( 'Please select whether or not you want this user to have admin rights.'); IsAllFieldsPresent := False; end; end; /// 2.) ================ Function to detirmine is name is valid =============== function TfrmCreateNewAccount.IsNameValid: boolean; { This function checks that the name contains only letters and spaces } var i: integer; begin IsNameValid := True; sName := lbledtName.Text; for i := 1 to Length(sName) do Begin sName[i] := Upcase(sName[i]); if not(sName[i] in ['A' .. 'Z']) AND (sName[i] <> ' ') then begin ShowMessage('Your name can only contain letters and spaces.'); lbledtName.EditLabel.Font.Color := clRed; lbledtName.EditLabel.Caption := '*** Name:'; IsNameValid := False; end; End; sName := lbledtName.Text; end; /// 3.) ============= Function to determine if surname is valid =============== function TfrmCreateNewAccount.IsSurnameValid: boolean; { This function checks that the surname contains only letters and spaces } var i: integer; begin IsSurnameValid := True; sSurname := lbledtSurname.Text; for i := 1 to Length(sSurname) do Begin sSurname[i] := Upcase(sSurname[i]); if not(sSurname[i] in ['A' .. 'Z']) AND (sSurname[i] <> ' ') then begin ShowMessage('Your surname can only contain letters and spaces.'); lbledtSurname.EditLabel.Font.Color := clRed; lbledtSurname.EditLabel.Caption := '*** Surname:'; IsSurnameValid := False; end; End; sSurname := lbledtSurname.Text; end; /// 4.) == Function that determines if cellphone number is 10 DIGITS long ===== function TfrmCreateNewAccount.IsCellphoneNumberValid: boolean; { This function checks that the cellphone number is 10 digits long, and contains only numbers } var i: integer; begin IsCellphoneNumberValid := True; sCellphoneNumber := lbledtCellphoneNumber.Text; if Length(sCellphoneNumber) <> 10 then Begin ShowMessage('Your cellphone number is not the correct lenght.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsCellphoneNumberValid := False; End; for i := 1 to Length(sCellphoneNumber) do Begin if NOT(sCellphoneNumber[i] In ['0' .. '9']) then Begin ShowMessage('Your cellphone number can only contain numbers.'); lbledtCellphoneNumber.EditLabel.Font.Color := clRed; lbledtCellphoneNumber.EditLabel.Caption := '*** Cellphone Number:'; IsCellphoneNumberValid := False; end; end; end; /// 5.) ================ Function that validates password ==================== function TfrmCreateNewAccount.IsPasswordValid: boolean; { Checks that password is at least 8 characters long, and contaains at least one uppercase letter, one lowercase letter and at least one number. } var i: integer; bContainsUppercase: boolean; bContainsLowercase: boolean; bContainsNumber: boolean; begin IsPasswordValid := True; sPassword := lbledtPassword.Text; if Length(sPassword) < 8 then Begin ShowMessage('Your password needs to be at least 8 characters long.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsPasswordValid := False; End; bContainsUppercase := False; bContainsLowercase := False; bContainsNumber := False; for i := 1 to Length(sPassword) do Begin if sPassword[i] IN ['a' .. 'z'] then Begin bContainsLowercase := True; End; if sPassword[i] IN ['A' .. 'Z'] then Begin bContainsUppercase := True; End; if sPassword[i] IN ['0' .. '9'] then Begin bContainsNumber := True; End; end; if bContainsUppercase = False then ShowMessage('Your password does not contain an uppercase letter.'); if bContainsLowercase = False then ShowMessage('Your password does not contain a lowercase letter.'); if bContainsNumber = False then ShowMessage('Your password does not contain a number letter.'); if (bContainsUppercase = False) OR (bContainsLowercase = False) OR (bContainsNumber = False) then Begin ShowMessage( 'Your password needs to contain at least one uppercase letter, lowercase letter and number.'); lbledtPassword.EditLabel.Font.Color := clRed; lbledtPassword.EditLabel.Caption := '*** Password:'; IsPasswordValid := False; End; end; /// 6.) ==== Function that checks that the ID Number contains only numbers // and is 13 digits long ===================================================== function TfrmCreateNewAccount.IsIDNumberValidNumbers: boolean; var sEnteredID: string; i: integer; begin IsIDNumberValidNumbers := True; // Checks that ID Number only contains numbers sEnteredID := lbledtID.Text; i := 0; for i := 1 to Length(sEnteredID) do Begin if NOT(sEnteredID[i] In ['0' .. '9']) then Begin ShowMessage('Your ID number can only contain numbers.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidNumbers := False; end; End; if Length(sEnteredID) <> 13 then Begin ShowMessage('Your ID number must be 13 digits long.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidNumbers := False; End; end; // 7.) ============ Checks that the user`s enterd bithdates match ID ========= function TfrmCreateNewAccount.IsIDNumberValidBirthDate: boolean; { This function determines what the user`s bith date is suppose to be according to his ID, and then checks to see that the match } var iIDday: integer; iIDmonth: integer; sIDyear: string; iIDYear: integer; sIDNumber: string; begin IsIDNumberValidBirthDate := True; // Gets User entered birth information iEnteredBirthDay := StrToInt(spnedtDayOfBirth.Text); iEnteredBirthMonth := cbxMonth.ItemIndex + 1; iEnteredBirthYear := StrToInt(spnedtYearOfBirth.Text); // Gets birth dates from ID Number sIDNumber := lbledtID.Text; iIDday := StrToInt(Copy(sIDNumber, 5, 2)); iIDmonth := StrToInt(Copy(sIDNumber, 3, 2)); sIDyear := Copy(sIDNumber, 1, 2); if StrToInt(sIDyear) IN [0 .. 18] then iIDYear := 2000 + StrToInt(sIDyear) else iIDYear := 1900 + StrToInt(sIDyear); // Compares the two // Day if iEnteredBirthDay <> iIDday then Begin ShowMessage('Your ID number`s day of birth does not match your birth day.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; // Month if iEnteredBirthMonth <> iIDmonth then Begin ShowMessage( 'Your ID number`s month of birth does not match your birth month.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; // Year if iEnteredBirthYear <> iIDYear then Begin ShowMessage ('Your ID number`s year of birth does not match your birth year.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidBirthDate := False; End; end; // 8.) =========== Checks that the user`s gender matches his ID`s ============= function TfrmCreateNewAccount.IsIDNumberValidGender: boolean; { This function determines what the user`s gender is suppose to be according to his ID, and then checks to see that the match } var sEnteredID: string; begin IsIDNumberValidGender := True; sEnteredID := lbledtID.Text; if NOT(((StrToInt(sEnteredID[7]) > 4) AND (rbMale.Checked = True)) OR ((StrToInt(sEnteredID[7]) < 4) AND (rbFemale.Checked = True))) then begin ShowMessage('Your ID number does not match your gender.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidGender := False; end; end; // 9.) ============== Function that validates that the check digit matches // what it should be according to Luhn`s equation ================== function TfrmCreateNewAccount.IsIDNumberValidCheckDigit: boolean; { This function calculates the what the user`s check digit is suppose to be according to Luhn`s formula, and then checks to see wheter or not it matches the user`s enered ID check digit } var i: integer; iSumOdds: integer; iSumEvens: integer; iTotal: integer; iCheck: integer; sEvens: string; sNumFromEvens: string; sEnteredID: string; begin IsIDNumberValidCheckDigit := True; sEnteredID := lbledtID.Text; // Calculate the sum of all the odd digits in the Id number - excluding the last one i := 1; iSumOdds := 0; while i <= 11 do begin iSumOdds := iSumOdds + StrToInt(sEnteredID[i]); Inc(i, 2); end; // Create a new number: Using the even positions and multiplying the number by 2 sEvens := ''; i := 2; while i <= 12 do begin sEvens := sEvens + sEnteredID[i]; Inc(i, 2); end; sNumFromEvens := IntToStr(StrToInt(sEvens) * 2); // Add up all the digits in this new number iSumEvens := 0; for i := 1 to Length(sNumFromEvens) do begin iSumEvens := iSumEvens + StrToInt(sNumFromEvens[i]); end; // Add the two numbers iTotal := iSumOdds + iSumEvens; // Subtract the second digit form 10 iCheck := (iTotal MOD 10); if iCheck = 0 then begin iCheck := 10; end; iCheck := 10 - iCheck; // Check if the calculated check digit matches the last digit in the ID Number if Not(iCheck = StrToInt(sEnteredID[13])) then Begin ShowMessage ('Your ID Number is incorrect. Please re-enter it and try again.'); lbledtID.EditLabel.Font.Color := clRed; lbledtID.EditLabel.Caption := '*** ID Number:'; IsIDNumberValidCheckDigit := False; End; end; // 10.) ============ Function that determines the user`s age ================= function TfrmCreateNewAccount.DeterminePlayerAge: integer; var iDay: integer; iMonth: integer; iYear: integer; sToday: string; iThisDay, iThisMonth, iThisYear: integer; iAge: integer; begin // Gets User entered birth information iDay := StrToInt(spnedtDayOfBirth.Text); iMonth := cbxMonth.ItemIndex + 1; iYear := StrToInt(spnedtYearOfBirth.Text); // Determine Today`s date sToday := DateToStr(Date); iThisDay := StrToInt(Copy(sToday, 9, 2)); iThisMonth := StrToInt(Copy(sToday, 6, 2)); iThisYear := StrToInt(Copy(sToday, 1, 4)); // Calculate the age the person will become this year iAge := iThisYear - iYear; // Determine if the person has already had his/her birthday if iMonth > iThisMonth then // birthday will be later this year Dec(iAge) else if iMonth = iThisMonth then // test if birthday is later in the month or has already happened if iDay > iThisDay then // bithday will be later in the MonthDays Dec(iAge); Result := iAge; // ShowMessage(IntToStr(iAge)); end; // 11. ) ============ Create a new account ID for the user ==================== function TfrmCreateNewAccount.GenerateAccountID; { This procedure creates a unique account ID for the new account } var iHighest: integer; iTemp: integer; sHighestWithZeros: string; begin // Determine the highest item index for the day iHighest := 0; iTemp := 0; with dmDatabase Do Begin tblAccounts.First; while NOT tblAccounts.Eof do begin iTemp := StrToInt(Copy(tblAccounts['AccountID'], 3, 3)); if iTemp > iHighest then Begin iHighest := iTemp; End; tblAccounts.Next; end; tblAccounts.First; end; sNewAccountID := Copy(sName, 1, 1) + Copy(sSurname, 1, 1); sHighestWithZeros := IntToStr(iHighest + 1); // Ads zeros if Length(sHighestWithZeros) = 1 then sHighestWithZeros := '00' + sHighestWithZeros; if Length(sHighestWithZeros) = 2 then sHighestWithZeros := '0' + sHighestWithZeros; sNewAccountID := sNewAccountID + sHighestWithZeros; // Checks wether the user is an admin or not if iAdminRigthsIndex = 0 then sNewAccountID := sNewAccountID + 'A'; if iAdminRigthsIndex = 1 then sNewAccountID := sNewAccountID + 'T'; // ShowMessage(sNewAccountID); Result := sNewAccountID; end; // 12.) ========= Save New User`s Date To The Database ======================== procedure TfrmCreateNewAccount.SaveDataToDatabase; begin with dmDatabase do Begin tblAccounts.Open; tblAccounts.Last; tblAccounts.Insert; tblAccounts['AccountID'] := sNewAccountID; tblAccounts['Name'] := sName; tblAccounts['Surname'] := sSurname; if iAdminRigthsIndex = 0 then // User is an Admin Begin tblAccounts['IsAdmin'] := True; tblAccounts['AssignedTill'] := '0'; End; if iAdminRigthsIndex = 1 then // User is a Teller Begin tblAccounts['IsAdmin'] := False; tblAccounts['AssignedTill'] := IntToStr(spnEdtAssignedTill.Value); End; tblAccounts['CellphoneNumber'] := sCellphoneNumber; tblAccounts['EmailAdress'] := sEmailAdress; tblAccounts['Gender'] := sGender; tblAccounts['IDNumber'] := lbledtID.Text; tblAccounts['Password'] := sPassword; tblAccounts.Post; /// Beep; ShowMessage('Details Successfully Saved.' + #13 + 'Welcome To The GrowCery Family'); end; end; /// ========================= Procedure ResetAll ============================== procedure TfrmCreateNewAccount.ResetAll; begin // Name lbledtName.EditLabel.Font.Color := clBlack; lbledtName.EditLabel.Caption := 'Name:'; lbledtName.Text := ''; // Surname lbledtSurname.EditLabel.Font.Color := clBlack; lbledtSurname.EditLabel.Caption := 'Surname:'; lbledtSurname.Text := ''; // ID lbledtID.EditLabel.Font.Color := clBlack; lbledtID.EditLabel.Caption := 'ID Number:'; lbledtID.Text := ''; // Gender lblGender.Font.Color := clBlack; lblGender.Caption := 'Gender: '; rbFemale.Checked := False; rbMale.Checked := False; // Email lbledtEmailAdress.EditLabel.Font.Color := clBlack; lbledtEmailAdress.EditLabel.Caption := 'Email Adress:'; lbledtEmailAdress.Text := ''; // Cellphone Number lbledtCellphoneNumber.EditLabel.Font.Color := clBlack; lbledtCellphoneNumber.EditLabel.Caption := 'Cellphone Number:'; lbledtCellphoneNumber.Text := ''; // Password lbledtPassword.EditLabel.Font.Color := clBlack; lbledtPassword.EditLabel.Caption := 'Password:'; lbledtPassword.Text := ''; // Please Retype Your Password lbledtRetypePassword.EditLabel.Font.Color := clBlack; lbledtRetypePassword.EditLabel.Caption := 'Please Retype Your Password:'; lbledtRetypePassword.Text := ''; // Grant Admin Rights rgpGrantAdminRights.ItemIndex := -1; end; /// =========================== Shows The User A Help File ==================== procedure TfrmCreateNewAccount.ShowHelp; var tHelp: TextFile; sLine: string; sMessage: string; begin sMessage := '========================================'; AssignFile(tHelp, 'Help_CreateNewAccount.txt'); try { Code that checks to see if the file about the sponsors can be opened - displays error if not } reset(tHelp); Except ShowMessage('ERROR: The help file could not be opened.'); Exit; end; while NOT EOF(tHelp) do begin Readln(tHelp, sLine); sMessage := sMessage + #13 + sLine; end; sMessage := sMessage + #13 + '========================================'; CloseFile(tHelp); ShowMessage(sMessage); End; /// =============== Show user help after incorrect attempt =================== procedure TfrmCreateNewAccount.ShowHelpAfterIncorrectAttempt; begin if MessageDlg( 'You entered your information incorrectly. Would you like to veiw help as to how to enter your information ?', mtInformation, [mbYes, mbNo], 0) = mrYes then Begin ShowHelp; End Else Begin Exit; End; end; /// ============================== Back Button ================================ procedure TfrmCreateNewAccount.btnBackClick(Sender: TObject); begin begin if MessageDlg(' Are you sure you want to return to your home page ?', mtConfirmation, [mbYes, mbCancel], 0) = mrYes then begin frmCreateNewAccount.Close; end else Exit end; end; /// ============================= Help Button Click =========================== procedure TfrmCreateNewAccount.btnHelpClick(Sender: TObject); begin ShowHelp; end; /// ========================== Form Gets Closed ============================== procedure TfrmCreateNewAccount.FormClose(Sender: TObject; var Action: TCloseAction); begin ResetAll; frmAdminHomeScreen.Show; end; /// ==================== User Selects Type Of Accout ========================== procedure TfrmCreateNewAccount.rgpGrantAdminRightsClick(Sender: TObject); begin if rgpGrantAdminRights.ItemIndex = 0 then spnEdtAssignedTill.Enabled := False; if rgpGrantAdminRights.ItemIndex = 1 then spnEdtAssignedTill.Enabled := True; end; /// ============================== Form Gets Created ========================== procedure TfrmCreateNewAccount.FormCreate(Sender: TObject); begin pnlLabels.Color := rgb(139, 198, 99); end; end.
unit GLDMaterial; interface uses Classes, GL, GLDConst, GLDTypes, GLDClasses; type TGLDMaterial = class; TGLDMaterialList = class; TGLDMaterial = class(TGLDSysClass) private FAmbient: TGLDColor4fClass; FDiffuse: TGLDColor4fClass; FSpecular: TGLDColor4fClass; FEmission: TGLDColor4fClass; FShininess: GLubyte; FName: string; procedure SetAmbient(Value: TGLDColor4fClass); procedure SetDiffuse(Value: TGLDColor4fClass); procedure SetSpecular(Value: TGLDColor4fClass); procedure SetEmission(Value: TGLDColor4fClass); procedure SetShininess(Value: GLubyte); function GetParams: TGLDMaterialParams; procedure SetParams(AParams: TGLDMaterialParams); procedure SetName(Value: string); protected procedure SetOnChange(Value: TNotifyEvent); override; public constructor Create(AOwner: TPersistent); overload; override; constructor Create(AOwner: TPersistent; const AParams: TGLDMaterialParams); overload; destructor Destroy; override; procedure Apply; procedure Assign(Source: TPersistent); override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function ListIndex: GLuint; class function SysClassType: TGLDSysClassType; override; property Params: TGLDMaterialParams read GetParams; published property Ambient: TGLDColor4fClass read FAmbient write SetAmbient; property Diffuse: TGLDColor4fClass read FDiffuse write SetDiffuse; property Specular: TGLDColor4fClass read FSpecular write SetSpecular; property Emission: TGLDColor4fClass read FEmission write SetEmission; property Shininess: GLubyte read FShininess write SetShininess; property Name: string read FName write SetName; end; PGLDMaterialArray = ^TGLDMaterialArray; TGLDMaterialArray = array[1..GLD_MAX_MATERIALS] of TGLDMaterial; TGLDMaterialList = class(TGLDSysClass) private FCapacity: GLuint; FCount: GLuint; FList: PGLDMaterialArray; procedure SetCapacity(NewCapacity: GLuint); procedure SetCount(NewCount: GLuint); function GetMaterial(Index: GLuint): TGLDMaterial; procedure SetMaterial(Index: GLuint; Material: TGLDMaterial); function GetLast: TGLDMaterial; procedure SetLast(Material: TGLDMaterial); protected procedure DefineProperties(Filer: TFiler); override; procedure SetOnChange(Value: TNotifyEvent); override; public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; function CreateNew: GLuint; function Add(Material: TGLDMaterial): GLuint; overload; function Add(AParams: TGLDMaterialParams): GLuint; overload; function Delete(Index: GLuint): GLuint; overload; function Delete(Material: TGLDMaterial): GLuint; overload; function IndexOf(Material: TGLDMaterial): GLuint; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; class function SysClassType: TGLDSysClassType; override; property Capacity: GLuint read FCapacity write SetCapacity; property Count: GLuint read FCount write SetCount; property List: PGLDMaterialArray read FList; property Items[index: GLuint]: TGLDMaterial read GetMaterial write SetMaterial; property Materials[index: GLuint]: TGLDMaterial read GetMaterial write SetMaterial; default; property Last: TGLDMaterial read GetLast write SetLast; end; function GLDGetStandardMaterial: TGLDMaterial; procedure GLDReleaseStandardMaterial; procedure GLDApplyStandardMaterial; implementation uses SysUtils, GLDX; var vMaterialCounter: GLuint = 0; vStandardMaterial: TGLDMaterial = nil; function GLDGetStandardMaterial: TGLDMaterial; begin if not Assigned(vStandardMaterial) then begin vStandardMaterial := TGLDMaterial.Create(nil); vStandardMaterial.OnChange := nil; vStandardMaterial.Name := GLD_STANDARD_STR; Dec(vMaterialCounter); end; Result := vStandardMaterial; end; procedure GLDReleaseStandardMaterial; begin if Assigned(vStandardMaterial) then vStandardMaterial.Free; vStandardMaterial := nil; end; procedure GLDApplyStandardMaterial; begin vStandardMaterial.Apply; end; constructor TGLDMaterial.Create(AOwner: TPersistent); begin inherited Create(AOwner); FAmbient := TGLDColor4fClass.Create(Self, GLD_MATERIAL_AMBIENT_DEFAULT); FDiffuse := TGLDColor4fClass.Create(Self, GLD_MATERIAL_DIFFUSE_DEFAULT); FSpecular := TGLDColor4fClass.Create(Self, GLD_MATERIAL_SPECULAR_DEFAULT); FEmission := TGLDColor4fClass.Create(Self, GLD_MATERIAL_EMISSION_DEFAULT); FShininess := GLD_MATERIAL_SHININESS_DEFAULT; Inc(vMaterialCounter); FName := GLD_MATERIAL_STR + IntToStr(vMaterialCounter); end; constructor TGLDMaterial.Create(AOwner: TPersistent; const AParams: TGLDMaterialParams); begin inherited Create(AOwner); FAmbient := TGLDColor4fClass.Create(Self, Params.Ambient); FDiffuse := TGLDColor4fClass.Create(Self, Params.Diffuse); FSpecular := TGLDColor4fClass.Create(Self, Params.Specular); FEmission := TGLDColor4fClass.Create(Self, Params.Emission); FShininess := GLD_MATERIAL_SHININESS_DEFAULT; Inc(vMaterialCounter); FName := GLD_MATERIAL_STR + IntToStr(vMaterialCounter); end; destructor TGLDMaterial.Destroy; begin FAmbient.Free; FDiffuse.Free; FSpecular.Free; FEmission.Free; inherited Destroy; end; procedure TGLDMaterial.Apply; begin glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, FAmbient.GetPointer); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, FDiffuse.GetPointer); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, FSpecular.GetPointer); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, FEmission.GetPointer); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, FShininess); glColor4fv(FDiffuse.GetPointer); end; procedure TGLDMaterial.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLDMaterial) then Exit; FAmbient.Assign(TGLDMaterial(Source).FAmbient); FDiffuse.Assign(TGLDMaterial(Source).FDiffuse); FSpecular.Assign(TGLDMaterial(Source).FSpecular); FEmission.Assign(TGLDMaterial(Source).FEmission); FShininess := TGLDMaterial(Source).FShininess; inherited Assign(Source); end; procedure TGLDMaterial.LoadFromStream(Stream: TStream); var Col: TGLDColor4ub; L, i: GLubyte; C: Char; begin Stream.Read(Col, SizeOf(TGLDColor4ub)); PGLDColor4f(FAmbient.GetPointer)^ := GLDXColor4f(Col); Stream.Read(Col, SizeOf(TGLDColor4ub)); PGLDColor4f(FDiffuse.GetPointer)^ := GLDXColor4f(Col); Stream.Read(Col, SizeOf(TGLDColor4ub)); PGLDColor4f(FSpecular.GetPointer)^ := GLDXColor4f(Col); Stream.Read(Col, SizeOf(TGLDColor4ub)); PGLDColor4f(FEmission.GetPointer)^ := GLDXColor4f(Col); Stream.Read(FShininess, SizeOf(GLubyte)); Stream.Read(L, SizeOf(GLubyte)); FName := ''; if L > 0 then for i := 1 to L do begin Stream.Read(C, SizeOf(Char)); FName := FName + C; end; end; procedure TGLDMaterial.SaveToStream(Stream: TStream); var Col: TGLDColor4ub; L, i: GLubyte; begin Col := GLDXColor4ub(FAmbient.Color4f); Stream.Write(Col, SizeOf(TGLDColor4ub)); Col := GLDXColor4ub(FDiffuse.Color4f); Stream.Write(Col, SizeOf(TGLDColor4ub)); Col := GLDXColor4ub(FSpecular.Color4f); Stream.Write(Col, SizeOf(TGLDColor4ub)); Col := GLDXColor4ub(FEmission.Color4f); Stream.Write(Col, SizeOf(TGLDColor4ub)); Stream.Write(FShininess, SizeOf(GLubyte)); L := Length(FName); Stream.Write(L, SizeOf(GLubyte)); if L > 0 then for i := 1 to L do Stream.Write(FName[i], SizeOf(Char)); end; function TGLDMaterial.ListIndex: GLuint; begin Result := 0; if Assigned(FOwner) then if FOwner is TGLDMaterialList then Result := TGLDMaterialList(FOwner).IndexOf(Self); end; class function TGLDMaterial.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_MATERIAL; end; procedure TGLDMaterial.SetOnChange(Value: TNotifyEvent); begin FOnChange := Value; FAmbient.OnChange := FOnChange; FDiffuse.OnChange := FOnChange; FSpecular.OnChange := FOnChange; FEmission.OnChange := FOnChange; end; procedure TGLDMaterial.SetAmbient(Value: TGLDColor4fClass); begin FAmbient.Assign(Value); end; procedure TGLDMaterial.SetDiffuse(Value: TGLDColor4fClass); begin FDiffuse.Assign(Value); end; procedure TGLDMaterial.SetSpecular(Value: TGLDColor4fClass); begin FSpecular.Assign(Value); end; procedure TGLDMaterial.SetEmission(Value: TGLDColor4fClass); begin FEmission.Assign(Value); end; procedure TGLDMaterial.SetShininess(Value: GLubyte); begin if FShininess = Value then Exit; FShininess := Value; end; function TGLDMaterial.GetParams: TGLDMaterialParams; begin Result := GLDXMaterialParams( FAmbient.Color4f, FDiffuse.Color4f, FSpecular.Color4f, FEmission.Color4f, FShininess); end; procedure TGLDMaterial.SetParams(AParams: TGLDMaterialParams); begin if GLDXMaterialParamsEqual(GetParams, AParams) then Exit; PGLDColor4f(FAmbient.GetPointer)^ := AParams.Ambient; PGLDColor4f(FDiffuse.GetPointer)^ := AParams.Diffuse; PGLDColor4f(FSpecular.GetPointer)^ := AParams.Specular; PGLDColor4f(FEmission.GetPointer)^ := AParams.Emission; FShininess := AParams.Shininess; end; procedure TGLDMaterial.SetName(Value: string); begin if FName = Value then Exit; FName := Value; end; constructor TGLDMaterialList.Create(AOwner: TPersistent); begin inherited Create(AOwner); FCapacity := 0; FCount := 0; FList := nil; end; destructor TGLDMaterialList.Destroy; begin Clear; inherited Destroy; end; procedure TGLDMaterialList.Assign(Source: TPersistent); var i: GLuint; begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLDMaterialList) then Exit; Clear; SetCapacity(TGLDMaterialList(Source).FCapacity); FCount := TGLDMaterialList(Source).FCount; if FCount > 0 then for i := 1 to FCount do begin FList^[i] := TGLDMaterial.Create(Self); FList^[i].Assign(TGLDMaterialList(Source).FList^[i]); end; end; procedure TGLDMaterialList.Clear; var i: GLuint; begin if FCount > 0 then for i := FCount downto 1 do FList^[i].Free; ReallocMem(FList, 0); FCapacity := 0; FCount := 0; FList := nil; end; function TGLDMaterialList.CreateNew: GLuint; begin Result := 0; if FCount < GLD_MAX_MATERIALS then begin SetCount(FCount + 1); Result := FCount; end; end; function TGLDMaterialList.Add(Material: TGLDMaterial): GLuint; begin Result := 0; if Material = nil then Exit; Result := CreateNew; if Result > 0 then Last.Assign(Material); end; function TGLDMaterialList.Add(AParams: TGLDMaterialParams): GLuint; begin Result := CreateNew; if Result = 0 then Exit; Last.SetParams(AParams); end; function TGLDMaterialList.Delete(Index: GLuint): GLuint; var i: GLuint; begin Result := 0; if (Index < 1) or (Index > FCount) then Exit; FList^[Index].Free; FList^[Index] := nil; if Index < FCount then for i := Index to FCount - 1 do FList^[i] := FList^[i + 1]; Dec(FCount); Result := Index; end; function TGLDMaterialList.Delete(Material: TGLDMaterial): GLuint; begin Result := Delete(IndexOf(Material)); end; function TGLDMaterialList.IndexOf(Material: TGLDMaterial): GLuint; var i: GLuint; begin Result := 0; if Material = nil then Exit; if FCount > 0 then for i := 1 to FCount do if FList^[i] = Material then begin Result := i; Exit; end; end; procedure TGLDMaterialList.LoadFromStream(Stream: TStream); var ACapacity, ACount, i: GLuint; begin Clear; Stream.Read(ACapacity, SizeOf(GLuint)); Stream.Read(ACount, SizeOf(GLuint)); SetCapacity(ACapacity); if ACount > 0 then begin for i := 1 to ACount do begin FList^[i] := TGLDMaterial.Create(Self); FList^[i].LoadFromStream(Stream); end; FCount := ACount; end; end; procedure TGLDMaterialList.SaveToStream(Stream: TStream); var i: GLuint; begin Stream.Write(FCapacity, SizeOf(GLuint)); Stream.Write(FCount, SizeOf(GLuint)); if FCount > 0 then for i := 1 to FCount do FList^[i].SaveToStream(Stream); end; procedure TGLDMaterialList.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, True); end; procedure TGLDMaterialList.SetOnChange(Value: TNotifyEvent); var i: GLuint; begin if FCount > 0 then for i := 1 to FCount do FList^[i].OnChange := Value; end; class function TGLDMaterialList.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_MATERIALLIST; end; procedure TGLDMaterialList.SetCapacity(NewCapacity: GLuint); var i: GLuint; begin if (FCapacity = NewCapacity) or (NewCapacity > GLD_MAX_MATERIALS) then Exit; if NewCapacity <= 0 then begin Clear; Exit; end else begin if NewCapacity < FCount then SetCount(NewCapacity); ReallocMem(FList, NewCapacity * SizeOf(TGLDMaterial)); if NewCapacity > FCapacity then for i := FCapacity + 1 to NewCapacity do FList^[i] := nil; FCapacity := NewCapacity; end; end; procedure TGLDMaterialList.SetCount(NewCount: GLuint); var i: GLuint; begin if (NewCount = FCount) or (NewCount > GLD_MAX_MATERIALS) then Exit; if NewCount <= 0 then begin Clear; Exit; end else begin if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then for i := FCount + 1 to NewCount do FList^[i] := TGLDMaterial.Create(Self) else if NewCount < FCount then for i := FCount downto NewCount + 1 do begin FList^[i].Free; FList^[i] := nil; end; FCount := NewCount; end; end; function TGLDMaterialList.GetMaterial(Index: GLuint): TGLDMaterial; begin if (Index >= 1) and (Index <= FCount) then Result := FList^[Index] else Result := nil; end; procedure TGLDMaterialList.SetMaterial(Index: GLuint; Material: TGLDMaterial); begin if (Index < 1) or (Index > FCount + 1) then Exit; if Index = FCount + 1 then Add(Material) else if Material = nil then Delete(Index) else FList^[Index].Assign(Material); end; function TGLDMaterialList.GetLast: TGLDMaterial; begin if FCount > 0 then Result := FList^[FCount] else Result := nil; end; procedure TGLDMaterialList.SetLast(Material: TGLDMaterial); begin if FCount > 0 then SetMaterial(FCount, Material) else Add(Material); end; initialization finalization GLDReleaseStandardMaterial; end.
{ Article: System Tray Delphi application - quick and easy http://delphi.about.com/library/weekly/aa121801a.htm Placing Delphi applications in the System Tray in easy steps. The perfect place for programs that are left running for long periods of time with no user interaction. } unit frmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, shellapi, AppEvnts, Vcl.StdCtrls, TimeTrackerLogInterface, Vcl.Menus, Vcl.ExtCtrls, Vcl.ComCtrls; const WM_ICONTRAY = WM_USER + 1; type TMainForm = class(TForm) btOk: TButton; Label1: TLabel; PopupMenu1: TPopupMenu; Exit1: TMenuItem; Timer1: TTimer; btIgnore: TButton; mnuOpenLog: TMenuItem; mnuOpen: TMenuItem; edActivityDescription: TComboBoxEx; mnuShowFolderinExplorer: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btOkClick(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btIgnoreClick(Sender: TObject); procedure mnuOpenLogClick(Sender: TObject); procedure mnuOpenClick(Sender: TObject); procedure mnuShowFolderinExplorerClick(Sender: TObject); procedure FormActivate(Sender: TObject); private TrayIconData: TNotifyIconData; FTimeTrackerLog :ITimeTrackerLog; public procedure TrayMessage(var Msg: TMessage); message WM_ICONTRAY; end; var MainForm: TMainForm; implementation uses TimeTrackerLog.TextFile, FileLoggerInterface; {$R *.dfm} procedure TMainForm.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; MainForm.ShowModal; //default action is caHide Timer1.Enabled := True; end; procedure TMainForm.TrayMessage(var Msg: TMessage); begin case Msg.lParam of WM_LBUTTONDOWN: begin if MainForm.Visible then MainForm.SetFocus else MainForm.ShowModal; end; WM_RBUTTONDOWN: begin PopupMenu1.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y); end; end; end; procedure TMainForm.btOkClick(Sender: TObject); begin FTimeTrackerLog.WriteLogEntry(Now,edActivityDescription.Text); with edActivityDescription.Items do begin Insert(0,edActivityDescription.Text); //only keep 5 items in the MRU list if Count > 5 then Delete(Count - 1); end; edActivityDescription.ItemIndex := 0; //make last entered text current one ModalResult := mrOk; end; procedure TMainForm.btIgnoreClick(Sender: TObject); begin //don't attempt to write a log entry ModalResult := mrOk; end; procedure TMainForm.Exit1Click(Sender: TObject); begin MainForm.Close; end; procedure TMainForm.FormActivate(Sender: TObject); begin //select all text so user can easily replace last description with current one edActivityDescription.SetFocus; edActivityDescription.SelectAll; end; procedure TMainForm.FormCreate(Sender: TObject); begin with TrayIconData do begin cbSize := SizeOf; //(TrayIconData); Wnd := Handle; uID := 0; uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP; uCallbackMessage := WM_ICONTRAY; hIcon := Application.Icon.Handle; StrPCopy(szTip, Application.Title); end; Shell_NotifyIcon(NIM_ADD, @TrayIconData); FTimeTrackerLog := TTimeTrackerLog.Create; FTimeTrackerLog.ReadLogEntries(edActivityDescription.Items,5); if edActivityDescription.Items.Count > 0 then edActivityDescription.ItemIndex := 0; {$ifdef DEBUG} Timer1.Interval := 5 * MSecsPerSec; //when debugging prompt every 5 secs {$else} Timer1.Interval := 15 * SecsPerMin * MSecsPerSec; //default prompt every 15 minutes {$endif} Timer1.Enabled := True; end; procedure TMainForm.FormDestroy(Sender: TObject); begin Shell_NotifyIcon(NIM_DELETE, @TrayIconData); end; procedure TMainForm.mnuOpenClick(Sender: TObject); begin if MainForm.Visible then MainForm.Activate else MainForm.ShowModal; end; procedure TMainForm.mnuOpenLogClick(Sender: TObject); var FileLogger :IFileLogger; begin if Supports(FTimeTrackerLog,IFileLogger,FileLogger) and FileExists(FileLogger.FileName) then ShellExecute(0, 'open', PChar(FileLogger.FileName), nil, nil, SW_SHOWNORMAL); end; procedure TMainForm.mnuShowFolderinExplorerClick(Sender: TObject); begin ShellExecute(0, 'explore', PChar(ExtractFilePath(Application.ExeName)),nil, nil, SW_SHOWNORMAL); end; end.
unit uFrmAddItems; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodos, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, LblEffct, ADODB, Provider, DBClient, mrBarCodeEdit, Mask, SuperComboADO, SubListPanel, PaideTodosGeral; type TDisplayColumns = set of (dcQty, dcSalePrice, dcCostPrice); TValidateValues = set of (vvQty, vvCostPrice, vvSellingPrice); TAddItem = class IDModel: Integer; VendorCost: Currency; SellingPrice: Currency; Tax: Double; Qty: Double; end; TFrmAddItems = class(TFrmParent) btSave: TButton; dsModelAdd: TDataSource; cdsModelAdd: TClientDataSet; cdsModelAddIDModel: TIntegerField; cdsModelAddQty: TFloatField; cdsModelAddSalePrice: TCurrencyField; cdsModelAddCostPrice: TCurrencyField; pnlFilter: TPanel; cdsModelAddModel: TStringField; cdsModelAddDescription: TStringField; spSalePrice: TADOStoredProc; pnlClient: TPanel; lblCategory: TLabel; scCategory: TSuperComboADO; btnCategClear: TButton; lblGroup: TLabel; scGroup: TSuperComboADO; btnGroupClear: TButton; lblSubGroup: TLabel; scSubGroup: TSuperComboADO; btnSubGroupClear: TButton; quModelResult: TADODataSet; dsModelResult: TDataSource; quModelResultIDModel: TIntegerField; quModelResultModel: TStringField; quModelResultDescription: TStringField; quModelResultSellingPrice: TBCDField; quModelResultVendorCost: TBCDField; quModelResultIDGroup: TIntegerField; quModelResultName: TStringField; quModelResultIDModelGroup: TIntegerField; quModelResultModelGroup: TStringField; quModelResultIDModelSubGroup: TIntegerField; quModelResultModelSubGroup: TStringField; cbxMethod: TComboBox; cbxType: TComboBox; edBarcode: TEdit; quModelResultIDBarcode: TStringField; pnlModelAdd: TPanel; pnlModelResult: TPanel; grdModelResult: TcxGrid; grdModelResultTableView: TcxGridDBTableView; grdModelResultTableViewIDBarcode: TcxGridDBColumn; grdModelResultTableViewIDModel: TcxGridDBColumn; grdModelResultTableViewModel: TcxGridDBColumn; grdModelResultTableViewDescription: TcxGridDBColumn; grdModelResultTableViewSellingPrice: TcxGridDBColumn; grdModelResultTableViewVendorCost: TcxGridDBColumn; grdModelResultTableViewIDGroup: TcxGridDBColumn; grdModelResultTableViewName: TcxGridDBColumn; grdModelResultTableViewIDModelGroup: TcxGridDBColumn; grdModelResultTableViewModelGroup: TcxGridDBColumn; grdModelResultTableViewIDModelSubGroup: TcxGridDBColumn; grdModelResultTableViewModelSubGroup: TcxGridDBColumn; grdModelResultLevel: TcxGridLevel; pnlBtnModelAdd: TPanel; grdModelAdd: TcxGrid; grdModelAddTableView: TcxGridDBTableView; grdModelAddLevel: TcxGridLevel; pnlBtnModelResult: TPanel; lblModelResultTitle: TLabel; lblModelAddTitle: TLabel; btnAdd: TSpeedButton; btnAddAll: TSpeedButton; btnRemoveAll: TSpeedButton; btnRemove: TSpeedButton; btnSearch: TBitBtn; slModelDetail: TSubListPanel; btnShowDetails: TSpeedButton; Splitter: TSplitter; grdModelAddTableViewIDModel: TcxGridDBColumn; grdModelAddTableViewModel: TcxGridDBColumn; grdModelAddTableViewDescription: TcxGridDBColumn; grdModelAddTableViewQty: TcxGridDBColumn; grdModelAddTableViewCostPrice: TcxGridDBColumn; grdModelAddTableViewSalePrice: TcxGridDBColumn; pnlDivisoria2: TPanel; btnGroup: TSpeedButton; btnColumn: TSpeedButton; Panel4: TPanel; cdsModelAddTax: TFloatField; quModelResultCaseQty: TBCDField; quModelResultQty: TIntegerField; grdModelResultTableViewQty: TcxGridDBColumn; dspModelResult: TDataSetProvider; cdsModelResult: TClientDataSet; cdsModelResultIDModel: TIntegerField; cdsModelResultModel: TStringField; cdsModelResultDescription: TStringField; cdsModelResultSellingPrice: TBCDField; cdsModelResultVendorCost: TBCDField; cdsModelResultIDGroup: TIntegerField; cdsModelResultName: TStringField; cdsModelResultIDModelGroup: TIntegerField; cdsModelResultModelGroup: TStringField; cdsModelResultIDModelSubGroup: TIntegerField; cdsModelResultModelSubGroup: TStringField; cdsModelResultIDBarcode: TStringField; cdsModelResultCaseQty: TBCDField; cdsModelResultQty: TIntegerField; quModelResultManufacturer: TStringField; cdsModelResultManufacturer: TStringField; grdModelResultTableViewManufacturer: TcxGridDBColumn; cdsModelAddManufacturer: TStringField; grdModelAddTableViewManufacturer: TcxGridDBColumn; procedure btSaveClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure grdModelResultTableViewDblClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure btnRemoveAllClick(Sender: TObject); procedure cdsModelAddAfterScroll(DataSet: TDataSet); procedure btnShowDetailsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure dsModelResultDataChange(Sender: TObject; Field: TField); procedure btnAddAllClick(Sender: TObject); procedure btnGroupClick(Sender: TObject); procedure btnColumnClick(Sender: TObject); procedure cdsModelResultAfterScroll(DataSet: TDataSet); procedure btnCategClearClick(Sender: TObject); procedure btnGroupClearClick(Sender: TObject); procedure btnSubGroupClearClick(Sender: TObject); procedure grdModelResultTableViewCustomization(Sender: TObject); private FID: Integer; FItemList: TList; FDisplayColumns: TDisplayColumns; FValidateValues: TValidateValues; FIDCliente: Integer; FIDModelActual: Integer; procedure PrepareDataSets; procedure DisplayColumns; procedure RefreshModelControls(AIDModel: Integer); procedure ConfigGrouping(AGroup: Boolean; AView: TcxCustomGridTableView); procedure ConfigColumns(AView: TcxCustomGridTableView); procedure AddModel; procedure GetPrices(AIDModel: Integer; var ACostPrice: Currency; var ASalePrice: Currency); function WasModelAdd(AIDModel: Integer): Boolean; function ValidateCaseQty: Boolean; function ValidateValues: Boolean; public function Start(AIDCliente: Integer; ADisplayColumns: TDisplayColumns; AValidateValues: TValidateValues): TList; end; implementation uses uDM, uMsgBox, uMsgConstant, uSystemConst, StrUtils, uPassword; {$R *.dfm} { TFrmAddItems } procedure TFrmAddItems.PrepareDataSets; begin cdsModelAdd.CreateDataSet; cdsModelAdd.Open; DM.quLookUpModelPack.Open; end; function TFrmAddItems.Start(AIDCliente: Integer; ADisplayColumns: TDisplayColumns; AValidateValues: TValidateValues): TList; begin FItemList := TList.Create; FID := 1; FIDCliente := AIDCliente; FDisplayColumns := ADisplayColumns; FValidateValues := AValidateValues; PrepareDataSets; DisplayColumns; ShowModal; cdsModelAdd.Close; DM.quLookUpModelPack.Close; Result := FItemList; end; procedure TFrmAddItems.btSaveClick(Sender: TObject); var Item: TAddItem; begin inherited; if cdsModelAdd.IsEmpty then MsgBox(MSG_CRT_NO_MODEL_SELECTED, vbInformation + vbOkOnly) else if ValidateValues then begin with cdsModelAdd do try DisableControls; First; while not Eof do begin Item := TAddItem.Create; Item.IDModel := FieldByName('IDModel').AsInteger; Item.Qty := FieldByName('Qty').AsFloat; Item.VendorCost := FieldByName('CostPrice').AsFloat; Item.SellingPrice := FieldByName('SalePrice').AsFloat; Item.Tax := FieldByName('Tax').AsFloat; FItemList.Add(Item); Next; end; finally First; EnableControls; end; Close; end; end; procedure TFrmAddItems.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(FItemList); end; procedure TFrmAddItems.DisplayColumns; var bCanSeeCost: Boolean; begin bCanSeeCost := Password.HasFuncRight(70); btnColumn.Enabled := bCanSeeCost; grdModelResultTableViewVendorCost.Hidden := (not (dcCostPrice in FDisplayColumns)) and (not bCanSeeCost); grdModelResultTableViewVendorCost.Visible := not grdModelResultTableViewVendorCost.Hidden; grdModelResultTableViewSellingPrice.Visible := (dcSalePrice in FDisplayColumns); grdModelAddTableViewCostPrice.Hidden := (not (dcCostPrice in FDisplayColumns)) and (not bCanSeeCost); grdModelAddTableViewCostPrice.Visible := not grdModelAddTableViewCostPrice.Hidden; grdModelAddTableViewSalePrice.Visible := (dcSalePrice in FDisplayColumns); end; procedure TFrmAddItems.GetPrices(AIDModel: Integer; var ACostPrice, ASalePrice: Currency); var cStoreCost, cStoreSell, cStoreAvg, cCustomerDiscount, cPromoPrice: Currency; begin cCustomerDiscount := 0; with spSalePrice do begin Parameters.ParambyName('@ModelID').Value := AIDModel; Parameters.ParambyName('@IDStore').Value := DM.fStore.ID; Parameters.ParambyName('@IDCustomer').Value := FIDCliente; Parameters.ParambyName('@Discount').Value := cCustomerDiscount; Parameters.ParambyName('@SpecialPriceID').Value := null; ExecProc; cStoreCost := Parameters.ParambyName('@StoreCostPrice').Value; cStoreSell := Parameters.ParambyName('@StoreSalePrice').Value; cStoreAvg := Parameters.ParambyName('@StoreAvgCost').Value; cPromoPrice := Parameters.ParambyName('@PromotionPrice').Value; cCustomerDiscount := Parameters.ParambyName('@Discount').Value; if DM.fStore.Franchase then ASalePrice := cStoreSell else begin if (cStoreSell <> 0) then ASalePrice := cStoreSell else ASalePrice := Parameters.ParambyName('@SalePrice').Value; end; ACostPrice := Parameters.ParambyName('@CostPrice').Value; end; end; procedure TFrmAddItems.btCloseClick(Sender: TObject); begin inherited; FItemList.Clear; Close; end; procedure TFrmAddItems.btnAddClick(Sender: TObject); begin inherited; if WasModelAdd(cdsModelResultIDModel.AsInteger) then MsgBox(MSG_CRT_NO_DUPLICATE_MODEL, vbInformation + vbOKOnly) else if not ValidateCaseQty then MsgBox(MSG_INF_QTY_NOT_DIF_MULT_CASE, vbCritical + vbOKOnly) else AddModel; end; function TFrmAddItems.WasModelAdd(AIDModel: Integer): Boolean; begin with cdsModelAdd do begin Filtered := False; Filter := 'IDModel = ' + IntToStr(AIDModel); Filtered := True; Result := not IsEmpty; Filtered := False; end; end; procedure TFrmAddItems.btnSearchClick(Sender: TObject); var sSQL, sWhere, sCampo : String; begin inherited; sWhere := ' WHERE M.Desativado = 0 AND M.System = 0 AND M.Hidden = 0 '; sSQL := ''; sCampo := ''; case cbxType.ItemIndex of 0 : sCampo := 'B.IDBarcode %S '; 1 : sCampo := 'M.Model %S '; 2 : sCampo := 'M.Description %S '; end; case cbxMethod.ItemIndex of 0 : sWhere := sWhere + ' AND ' + Format(sCampo, [' like ' + QuotedStr(edBarcode.Text+'%')]); 1 : sWhere := sWhere + ' AND ' + Format(sCampo, [' like ' + QuotedStr('%'+edBarcode.Text)]); 2 : sWhere := sWhere + ' AND ' + Format(sCampo, [' like ' + QuotedStr('%'+edBarcode.Text+'%')]); end; if scCategory.LookUpValue <> '' then sWhere := sWhere + ' AND TG.IDGroup = ' + scCategory.LookUpValue; if scGroup.LookUpValue <> '' then sWhere := sWhere + ' AND MG.IDModelGroup = ' + scCategory.LookUpValue; if scSubGroup.LookUpValue <> '' then sWhere := sWhere + ' AND MG.IDModelSubGroup = ' + scCategory.LookUpValue; sSQL := 'SELECT ' + 'M.IDModel, ' + 'M.Model, ' + 'M.Description, ' + 'M.SellingPrice, ' + 'M.VendorCost, ' + 'IsNull(M.CaseQty,0) as CaseQty, ' + 'TG.IDGroup, ' + 'TG.Name, ' + 'B.IDBarcode, ' + 'IsNull(MG.IDModelGroup, 0) as IDModelGroup, ' + 'MG.ModelGroup, ' + 'IsNull(MSG.IDModelSubGroup, 0) as IDModelSubGroup, ' + 'MSG.ModelSubGroup, ' + '1 as Qty, ' + 'F.Pessoa as Manufacturer ' + 'FROM ' + 'Model M (NOLOCK) ' + 'JOIN TabGroup TG (NOLOCK) ON (M.GroupID = TG.IDgroup) ' + 'LEFT JOIN ModelGroup MG (NOLOCK) ON (M.IDModelGroup = MG.IDModelGroup) ' + 'LEFT JOIN ModelSubGroup MSG (NOLOCK) ON (M.IDModelSubGroup = MSG.IDModelSubGroup) ' + 'LEFT JOIN Barcode B (NOLOCK) ON (M.IDModel = B.IDModel AND B.BarcodeOrder = 1)' + 'LEFT JOIN Pessoa F (NOLOCK) ON (M.IDFabricante = F.IDPessoa)' + sWhere; quModelResult.CommandText := sSQL; with cdsModelResult do begin if Active then Close; Open; end; end; procedure TFrmAddItems.AddModel; var cCostPrice, cSalePrice: Currency; begin with cdsModelAdd do begin GetPrices(cdsModelResultIDModel.AsInteger, cCostPrice, cSalePrice); Append; FieldByName('IDModel').AsInteger := cdsModelResultIDModel.AsInteger; FieldByName('CostPrice').AsCurrency := cCostPrice; FieldByName('SalePrice').AsCurrency := cSalePrice; FieldByName('Description').AsString := cdsModelResultDescription.AsString; FieldByName('Manufacturer').AsString := cdsModelResultManufacturer.AsString; FieldByName('Model').AsString := cdsModelResultModel.AsString; FieldByName('Qty').AsFloat := cdsModelResultQty.AsFloat; Post; end; end; procedure TFrmAddItems.grdModelResultTableViewDblClick(Sender: TObject); begin inherited; btnAddClick(Sender); end; procedure TFrmAddItems.btnRemoveClick(Sender: TObject); begin inherited; cdsModelAdd.Delete; end; procedure TFrmAddItems.btnRemoveAllClick(Sender: TObject); begin inherited; with cdsModelAdd do while not Eof do Delete; end; procedure TFrmAddItems.cdsModelAddAfterScroll(DataSet: TDataSet); begin inherited; btnRemove.Enabled := not dsModelAdd.DataSet.IsEmpty; btnRemoveAll.Enabled := btnRemove.Enabled; end; procedure TFrmAddItems.btnShowDetailsClick(Sender: TObject); begin inherited; slModelDetail.Visible := not slModelDetail.Visible; btnShowDetails.Down := slModelDetail.Visible; if slModelDetail.Visible then with cdsModelResult do RefreshModelControls(FieldByName('IDModel').AsInteger); end; procedure TFrmAddItems.RefreshModelControls(AIDModel: Integer); begin slModelDetail.Param := 'IDModel=' + IntToStr(AIDModel) + ';'; end; procedure TFrmAddItems.FormCreate(Sender: TObject); begin inherited; DM.imgBTN.GetBitmap(BTN_ADD, btnAdd.Glyph); DM.imgBTN.GetBitmap(BTN_ADDALL, btnAddAll.Glyph); DM.imgBTN.GetBitmap(BTN_GROUPING, btnGroup.Glyph); DM.imgBTN.GetBitmap(BTN_COLUMN, btnColumn.Glyph); DM.imgBTN.GetBitmap(BTN_INVENTORY, btnShowDetails.Glyph); DM.imgBTN.GetBitmap(BTN_DELETE, btnRemove.Glyph); DM.imgBTN.GetBitmap(BTN_DELETEALL, btnRemoveAll.Glyph); slModelDetail.CreateSubList; end; procedure TFrmAddItems.dsModelResultDataChange(Sender: TObject; Field: TField); begin inherited; if slModelDetail.Visible then with cdsModelResult do begin if FIDModelActual <> FieldByName('IDModel').AsInteger then RefreshModelControls(FieldByName('IDModel').AsInteger); FIDModelActual := FieldByName('IDModel').AsInteger; end; end; procedure TFrmAddItems.btnAddAllClick(Sender: TObject); begin inherited; with cdsModelResult do try cdsModelAdd.DisableControls; DisableControls; First; while not Eof do begin if (not WasModelAdd(cdsModelResultIDModel.AsInteger)) and ValidateCaseQty then AddModel; Next; end; First; finally EnableControls; cdsModelAdd.EnableControls; end; end; procedure TFrmAddItems.ConfigGrouping(AGroup: Boolean; AView: TcxCustomGridTableView); begin if AGroup then begin TcxGridDBTableView(AView).OptionsView.GroupByBox := True; end else begin // Retiro todos os grupos while TcxGridDBTableView(AView).GroupedItemCount > 0 do TcxGridDBTableView(AView).GroupedColumns[TcxGridDBTableView(AView).GroupedItemCount-1].GroupIndex := -1; TcxGridDBTableView(AView).OptionsView.GroupByBox := False; end; end; procedure TFrmAddItems.ConfigColumns(AView: TcxCustomGridTableView); begin if not TcxGridDBTableView(AView).Controller.Customization then TcxGridDBTableView(AView).Controller.Customization := True else TcxGridDBTableView(AView).Controller.Customization := False; end; procedure TFrmAddItems.btnGroupClick(Sender: TObject); begin inherited; ConfigGrouping(btnGroup.Down, grdModelResultTableView); end; procedure TFrmAddItems.btnColumnClick(Sender: TObject); begin inherited; ConfigColumns(grdModelResultTableView); end; function TFrmAddItems.ValidateValues: Boolean; begin Result := True; with cdsModelAdd do begin First; while not Eof do begin if vvQty in FValidateValues then if not (cdsModelAddQty.AsFloat >= 1) then begin MsgBox(MSG_INF_WRONG_QTY, vbCritical + vbOKOnly); Result := False; Exit; end; { if vvCostPrice in FValidateValues then if not (cdsModelAddCostPrice.AsCurrency > 0) then begin MsgBox(MSG_CRT_COST_POSITIVE, vbCritical + vbOKOnly); Result := False; Exit; end; } if vvSellingPrice in FValidateValues then if not (cdsModelAddSalePrice.AsCurrency > 0) then begin MsgBox(MSG_INF_PRICE_INVALID, vbCritical + vbOKOnly); Result := False; Exit; end; Next; end; end; end; function TFrmAddItems.ValidateCaseQty: Boolean; begin Result := True; if cdsModelResultCaseQty.AsFloat > 0 then if DM.fSystem.SrvParam[PARAM_VALIDATE_CASE_QTY_ON_HOLD] then Result := Frac(cdsModelResultQty.AsFloat / cdsModelResultCaseQty.AsFloat) = 0; end; procedure TFrmAddItems.cdsModelResultAfterScroll(DataSet: TDataSet); begin inherited; btnAdd.Enabled := not dsModelResult.DataSet.IsEmpty; btnAddAll.Enabled := btnAdd.Enabled; btnShowDetails.Enabled := btnAdd.Enabled; end; procedure TFrmAddItems.btnCategClearClick(Sender: TObject); begin inherited; scCategory.LookUpValue := ''; scCategory.Text := ''; end; procedure TFrmAddItems.btnGroupClearClick(Sender: TObject); begin inherited; scGroup.LookUpValue := ''; scGroup.Text := ''; end; procedure TFrmAddItems.btnSubGroupClearClick(Sender: TObject); begin inherited; scSubGroup.LookUpValue := ''; scSubGroup.Text := ''; end; procedure TFrmAddItems.grdModelResultTableViewCustomization( Sender: TObject); begin inherited; btnColumn.Down := TcxGridDBTableView(grdModelResult.FocusedView).Controller.Customization; end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uMacros; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, ComCtrls, Buttons, StdCtrls, SynEditKeyCmds, fEditor, uCommon, uMultiLanguage; const MAX_MACRO_SIZE = 4096; type TMacroDataTyp = (mdtNone, mdtFindReplace, mdtFill); TMacroCmdTyp = record DataTyp :TMacroDataTyp; end; TMacroCmdFind = record DataTyp :TMacroDataTyp; StrFind :string[255]; StrReplace :string[255]; Cfg :TFindDlgCfg; end; TMacroCmdFill = record DataTyp :TMacroDataTyp; Str :string[255]; end; pTMacroCmdTyp = ^TMacroCmdTyp; pTMacroCmdFind = ^TMacroCmdFind; pTMacroCmdFill = ^TMacroCmdFill; TMacroCmd = record Cmd :TSynEditorCommand; AChar :char; Data :pointer; DataSize :integer; end; TMacro = record Key :word; Shift :TShiftState; Commands :array[0..MAX_MACRO_SIZE-1] of TMacroCmd; CmdCount :integer; Disabled :boolean; end; pTMacro = ^TMacro; pTMacroCmd = ^TMacroCmd; //////////////////////////////////////////////////////////////////////////////////////////// TMacros = class private FStopPlayingMacro :boolean; CurrEditor :TObject; CurrMacro :pTMacro; CurrMacroName :string; Changed :boolean; function MacroCommandToStr(var CmdStr:string; Command:pTMacroCmd):boolean; public strMacros :TStringList; Recording :boolean; Playing :boolean; constructor Create; destructor Destroy; override; function StartRecording(Sender: TObject; Name:string; AKey: word; AShift: TShiftState):pTMacro; procedure AbortRecording(Sender: TObject); function StopRecording(Sender: TObject):boolean; procedure AddMacroCommand(Sender: TObject; Command: TSynEditorCommand; AChar: char; Data: pointer); function Play(ed:TfmEditor; var AKey: word; var AShift: TShiftState):boolean; function PlaybyName(ed:TfmEditor; MacroName:string):boolean; procedure StopPlayMacro; procedure Clear; procedure AddMacro(Name:string; mac:pTMacro); procedure DeleteMacro(mac:pTMacro); function Count:integer; function FindMacroWithShortcut(SC:TShortcut):pTMacro; function Load(fname:string):boolean; function Save(fname:string):boolean; published end; function GetMacroDataSize(DataTyp:TMacroDataTyp):integer; procedure FreeMacro(Macro:pTMacro); function DuplicateMacro(Macro:pTMacro):pTMacro; function AllocMacroCmdData(DataTyp:TMacroDataTyp):pointer; //////////////////////////////////////////////////////////////////////////////////////////// implementation uses fMain; const DEF_FNAME = 'default.mac'; const ERR_SYNTAX_ERR = 1; ERR_MACROBEGIN_EXPECTED = 2; ERR_LBRACE_EXPECTED = 3; ERR_RBRACE_EXPECTED = 4; ERR_STRING_EXPECTED = 5; ERR_NUMBER_EXPECTED = 6; ERR_COMMA_EXPECTED = 7; ERR_NUM = 7; ERR_STR :array[1..ERR_NUM] of string = ('Syntax error.', '''MacroBegin'' keyword expected.', '''('' expected.', '")" expected.', 'String expected.', 'Number expected.', 'Comma expected.' ); //////////////////////////////////////////////////////////////////////////////////////////// // Static functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function GetMacroDataSize(DataTyp:TMacroDataTyp):integer; begin case DataTyp of mdtFindReplace :result:=SizeOf(TMacroCmdFind); mdtFill :result:=SizeOf(TMacroCmdFill); else result:=0; end; end; //------------------------------------------------------------------------------------------ procedure FreeMacro(Macro:pTMacro); var i :integer; begin if not Assigned(Macro) then EXIT; with Macro^ do begin for i:=0 to CmdCount-1 do if Assigned(Commands[i].Data) then FreeMem(Commands[i].Data,Commands[i].DataSize); end; FreeMem(Macro); end; //------------------------------------------------------------------------------------------ function DuplicateMacro(Macro:pTMacro):pTMacro; var mac :pTMacro; i :integer; begin result:=nil; if not Assigned(Macro) then EXIT; mac:=AllocMem(SizeOf(TMacro)); Move(Macro^,mac^,SizeOf(TMacro)); // iskopiraj i stringove ako postoje for i:=0 to Macro^.CmdCount-1 do begin if Assigned(Macro^.Commands[i].Data) then begin mac^.Commands[i].Data:=AllocMem(Macro^.Commands[i].DataSize); Move(Macro^.Commands[i].Data^, mac^.Commands[i].Data^, Macro^.Commands[i].DataSize); end; end; result:=mac; end; //------------------------------------------------------------------------------------------ function AllocMacroCmdData(DataTyp:TMacroDataTyp):pointer; var size :integer; rec :pointer; begin size:=GetMacroDataSize(DataTyp); if (size>0) then begin rec:=AllocMem(size); pTMacroCmdTyp(rec)^.DataTyp:=DataTyp; end else rec:=nil; result:=rec; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Constructor, destructor //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TMacros.Create; var i :integer; begin for i:=1 to ERR_NUM do ERR_STR[i]:=mlStr(05000+i, ERR_STR[i]); Recording:=FALSE; Playing:=FALSE; CurrEditor:=nil; strMacros:=TStringList.Create; Changed:=FALSE; Load(ApplicationDir+DEF_FNAME); end; //------------------------------------------------------------------------------------------ destructor TMacros.Destroy; begin Save(ApplicationDir+DEF_FNAME); Clear; strMacros.Free; inherited; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Macro functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TMacros.Clear; var i :integer; begin for i:=0 to strMacros.Count-1 do FreeMacro(pTMacro(strMacros.Objects[i])); Changed:=TRUE; strMacros.Clear; end; //------------------------------------------------------------------------------------------ procedure TMacros.AddMacro(Name:string; mac:pTMacro); begin strMacros.AddObject(Name, pointer(mac)); end; //------------------------------------------------------------------------------------------ procedure TMacros.DeleteMacro(mac:pTMacro); var n :integer; begin n:=strMacros.IndexOfObject(pointer(mac)); if (n<>-1) then begin FreeMem(pTMacro(strMacros.Objects[n])); strMacros.Delete(n); end; end; //------------------------------------------------------------------------------------------ function TMacros.StartRecording(Sender: TObject; Name:string; AKey: word; AShift: TShiftState):pTMacro; begin result:=nil; if Recording then EXIT; Recording:=TRUE; CurrEditor:=Sender; CurrMacro:=AllocMem(SizeOf(TMacro)); CurrMacro^.Key:=AKey; CurrMacro^.Shift:=AShift; CurrMacroName:=Name; if Assigned(Sender) then TfmEditor(Sender).RefreshMacroRecording(Recording); result:=CurrMacro; end; //------------------------------------------------------------------------------------------ procedure TMacros.AbortRecording(Sender: TObject); begin if (not Recording) or Playing or (Sender<>CurrEditor) then EXIT; if Assigned(CurrMacro) then FreeMem(CurrMacro); CurrMacro:=nil; Recording:=FALSE; if Assigned(Sender) then TfmEditor(Sender).RefreshMacroRecording(Recording); end; //------------------------------------------------------------------------------------------ procedure TMacros.AddMacroCommand(Sender: TObject; Command: TSynEditorCommand; AChar: char; Data: pointer); var DataSize :integer; begin if (not Recording) or Playing or (Sender<>CurrEditor) then EXIT; case Command of ecFillBlock :DataSize:=GetMacroDataSize(mdtFill); ecFind :DataSize:=GetMacroDataSize(mdtFindReplace); else DataSize:=0; end; CurrMacro^.Commands[CurrMacro^.CmdCount].Cmd:=Command; CurrMacro^.Commands[CurrMacro^.CmdCount].AChar:=AChar; CurrMacro^.Commands[CurrMacro^.CmdCount].Data:=Data; CurrMacro^.Commands[CurrMacro^.CmdCount].DataSize:=DataSize; inc(CurrMacro^.CmdCount); end; //------------------------------------------------------------------------------------------ function TMacros.StopRecording(Sender: TObject):boolean; begin result:=FALSE; if not Recording or (Sender<>CurrEditor) then EXIT; strMacros.AddObject(CurrMacroName,pointer(CurrMacro)); CurrMacro:=nil; CurrEditor:=nil; Recording:=FALSE; Changed:=TRUE; if Assigned(Sender) then TfmEditor(Sender).RefreshMacroRecording(Recording); result:=TRUE; end; //------------------------------------------------------------------------------------------ function TMacros.Play(ed:TfmEditor; var AKey: word; var AShift: TShiftState):boolean; var i,ii :integer; Macro :pTMacro; begin result:=FALSE; if Recording or Playing then EXIT; i:=0; while (i<strMacros.Count) do begin Macro:=pTMacro(strMacros.Objects[i]); if (Macro^.Shift=AShift) and (Macro^.Key=AKey) then begin if not (Macro^.Disabled) then begin Playing:=TRUE; FStopPlayingMacro:=FALSE; SetLengthyOperation(TRUE); // play macro ii:=0; while (ii<Macro^.CmdCount) and not FStopPlayingMacro do begin ed.memo.CommandProcessor(Macro^.Commands[ii].Cmd, Macro^.Commands[ii].AChar, Macro^.Commands[ii].Data); inc(ii); end; SetLengthyOperation(FALSE); Playing:=FALSE; result:=TRUE; end; BREAK; end; inc(i); end; end; //------------------------------------------------------------------------------------------ function TMacros.PlaybyName(ed:TfmEditor; MacroName:string):boolean; var i :integer; M :pTMacro; old_D :boolean; begin result:=FALSE; MacroName:=Trim(UpperCase(MacroName)); if (Length(MacroName)=0) then EXIT; i:=0; while (i<strMacros.Count) do begin if (UpperCase(strMacros[i])=MacroName) then begin M:=pTMacro(strMacros.Objects[i]); old_D:=M^.Disabled; M^.Disabled:=FALSE; Play(ed, M^.Key, M^.Shift); M^.Disabled:=old_D; result:=TRUE; BREAK; end; inc(i); end; end; //------------------------------------------------------------------------------------------ procedure TMacros.StopPlayMacro; begin FStopPlayingMacro:=TRUE; end; //------------------------------------------------------------------------------------------ function TMacros.Count:integer; begin result:=strMacros.Count; end; //------------------------------------------------------------------------------------------ function TMacros.FindMacroWithShortcut(SC:TShortcut):pTMacro; var i :integer; begin result:=nil; i:=0; while (i<Count) do begin if (Shortcut((pTMacro(strMacros.Objects[i]).Key),(pTMacro(strMacros.Objects[i]).Shift))=SC) then begin result:=pTMacro(strMacros.Objects[i]); BREAK; end; inc(i); end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // File functions //////////////////////////////////////////////////////////////////////////////////////////// type TToken = ( tkEOF, tkERROR, tkASSIGN, tkColon, tkComma, tkLBRACE, tkRBRACE, tkNUMBER, tkIDENT, tkSemiColon, tkNOT, tkNEG, tkMUL, tkDIV, tkMOD, tkADD, tkSUB, tkLT, tkLE, tkEQ, tkNE, tkGE, tkGT, tkOR, tkXOR, tkAND, tkQuote, tkString ); var token :TToken; svalue :string; numvalue :integer; ptr :PChar; //------------------------------------------------------------------------------------------ procedure lex; label Error; var c :char; s_pos :PChar; function NextNonBlankChar:char; var ptr_ :PChar; begin ptr_:=ptr; repeat inc(ptr_) until ((ptr_^>' ') or (ptr_^=#0)); result:=ptr_^; end; function ConvertNumber(first, last: PChar; base: Word): boolean; var c: Byte; begin numvalue := 0; while first < last do begin c := Ord(first^) - Ord('0'); if (c > 9) then begin Dec(c, Ord('A') - Ord('9') - 1); if (c > 15) then Dec(c, Ord('a') - Ord('A')); end; if (c >= base) then break; numvalue := numvalue * base + c; Inc(first); end; Result := (first = last); end; begin { skip blanks } while (ptr^<>#0) do begin if (ptr^>' ') then break; inc(ptr); end; { check EOF } if (ptr^=#0) then begin token:=tkEOF; EXIT; end; token:=tkNUMBER; { match numbers } if (ptr^ in ['0'..'9']) then begin s_pos:=ptr; while (s_pos^ in ['0'..'9']) do inc(s_pos); { match simple decimal number } if not ConvertNumber(ptr, s_pos, 10) then goto Error; ptr:=s_pos; EXIT; end; { match identifiers } if (ptr^ in ['A'..'Z','a'..'z','_']) then begin svalue := ptr^; inc(ptr); while (ptr^ in ['A'..'Z','a'..'z','0'..'9','_']) do begin svalue := svalue + ptr^; inc(ptr); end; token := tkIDENT; EXIT; end; // match strings if (ptr^='"') then begin inc(ptr); svalue:=''; while not (ptr^ in ['"', #00, #13, #13]) do begin if (ptr^='\') and ((ptr+1)^ in ['"','\']) then inc(ptr); svalue:=svalue+ptr^; inc(ptr); end; if (ptr^='"') then begin inc(ptr); token:=tkString; end else token:=tkError; EXIT; end; { match operators } c:=ptr^; inc(ptr); case c of '(': begin token := tkLBRACE; end; ')': begin token := tkRBRACE; end; ',': token := tkComma; ':': token := tkColon; ';': token := tkSemiColon; '=': begin token := tkEQ; if (ptr^ = '=') then begin inc(ptr); token := tkEQ; end; end; '+': begin token := tkADD; end; '-': begin token := tkSUB; end; '*': begin token := tkMUL; end; '/': begin token := tkDIV; end; '%': begin token := tkMOD; end; '^': begin token := tkXOR; end; '&': begin token := tkAND; end; '|': begin token := tkOR; end; '<': begin token := tkLT; if (ptr^ = '=') then begin inc(ptr); token := tkLE; end else if (ptr^ = '>') then begin inc(ptr); token := tkNE; end; end; '>': begin token := tkGT; if (ptr^ = '=') then begin inc(ptr); token := tkGE; end else if (ptr^ = '<') then begin inc(ptr); token := tkNE; end; end; '!': begin token := tkNOT; if (ptr^ = '=') then begin inc(ptr); token := tkNE; end; end; else begin token := tkERROR; dec(ptr); end; end; EXIT; Error: token := tkERROR; end; //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ function TMacros.Load(fname:string):boolean; var str :TStringList; error :boolean; MacroName :string; MacroShortCut :string; MacroDisabled :string; MacroKey :word; MacroShift :TShiftState; Cmd :integer; finished :boolean; buff :PChar; mac :pTMacro; procedure SetError(err:integer); var ed :TfmEditor; begin AbortRecording(nil); fmMain.OpenFile(fname); ed:=fmMain.ActiveEditor; if Assigned(ed) then ed.memo.BlockEnd:=ed.memo.BlockBegin; MessageDlg(mlStr(ML_MACRO_SYNTAX_ERROR,'Macros syntax error')+': '+ERR_STR[err],mtError,[mbOK],0); error:=TRUE; end; function CheckSyntax(Condition:boolean; Error:integer):boolean; begin result:=Condition; if not result then SetError(Error); end; function ParseMacroDefinition:boolean; function GetParam(name:string; var value:string; IsLast, Optional:boolean):boolean; var old_ptr :PChar; begin old_ptr:=ptr; result:=FALSE; lex; if (UpperCase(svalue)=name) then begin lex; if CheckSyntax(token=tkColon, ERR_SYNTAX_ERR) then begin lex; if CheckSyntax(token=tkString, ERR_STRING_EXPECTED) then begin value:=svalue; if not IsLast then begin lex; if CheckSyntax(token=tkSemiColon, ERR_SYNTAX_ERR) then result:=TRUE; end else result:=TRUE; end; end; end else begin if Optional then begin result:=TRUE; ptr:=old_ptr; end else SetError(ERR_SYNTAX_ERR); end; end; begin lex; if (token=tkEOF) then begin result:=FALSE; EXIT; end; if CheckSyntax(UpperCase(svalue)='MACROBEGIN', ERR_MACROBEGIN_EXPECTED) then begin lex; if CheckSyntax(token=tkLBrace, ERR_LBRACE_EXPECTED) then begin if GetParam('NAME',MacroName,FALSE,FALSE) then begin MacroDisabled:='0'; GetParam('DISABLED',MacroDisabled,FALSE,TRUE); if GetParam('SHORTCUT',MacroShortCut,TRUE,FALSE) then begin ShortCutToKey(TextToShortcut(MacroShortcut),MacroKey,MacroShift); lex; CheckSyntax(token=tkRBrace, ERR_RBRACE_EXPECTED); end; end; end; end; result:=not error; end; function CheckLBrace:boolean; begin lex; result:=CheckSyntax(token=tkLBrace, ERR_LBRACE_EXPECTED); end; function CheckRBrace:boolean; begin lex; result:=CheckSyntax(token=tkRBrace, ERR_RBRACE_EXPECTED); end; function CheckComma:boolean; begin lex; result:=CheckSyntax(token=tkComma, ERR_COMMA_EXPECTED); end; function GetStringParam(var s:string; const FirstParam:boolean=FALSE; const LastParam:boolean=FALSE):boolean; begin result:=TRUE; if FirstParam then result:=CheckLBrace; if result then begin lex; result:=CheckSyntax(token=tkString, ERR_STRING_EXPECTED); if result then begin s:=svalue; if LastParam then result:=CheckRBrace else result:=CheckComma; end; end; end; function GetNumberParam(var i:integer; const FirstParam:boolean=FALSE; const LastParam:boolean=FALSE):boolean; begin result:=TRUE; if FirstParam then result:=CheckLBrace; if result then begin lex; result:=CheckSyntax(token=tkNUMBER, ERR_NUMBER_EXPECTED); if result then begin i:=numvalue; if LastParam then result:=CheckRBrace else result:=CheckComma; end; end; end; procedure ParseCommand(Cmd:TSynEditorCommand); var s :string; Data :pointer; Chr :char; num_values :array[1..10] of integer; i :integer; begin Chr:=#0; Data:=nil; case Cmd of ecChar: begin if GetStringParam(s,TRUE,TRUE) and CheckSyntax(Length(s)=1, ERR_SYNTAX_ERR) then Chr:=s[1]; end; ecFillBlock: begin if GetStringParam(s,TRUE,TRUE) then begin Data:=AllocMacroCmdData(mdtFill); pTMacroCmdFill(Data)^.Str:=s; end; end; (* ecFind: with pTMacroCmdFind(Command^.Data)^ do begin result:=Format('%s("%s",%d,%d,%d,%d,%d)', [Name, StrFind, ord(Cfg.Origin), ord(Cfg.Scope), integer(Cfg.CaseSensitive), integer(Cfg.WholeWords), ord(Cfg.Direction) ]); end; *) ecFind: begin if GetStringParam(s,TRUE,FALSE) and GetNumberParam(num_values[1]) and GetNumberParam(num_values[2]) and GetNumberParam(num_values[3]) and GetNumberParam(num_values[4]) and GetNumberParam(num_values[5],FALSE,TRUE) then begin Data:=AllocMacroCmdData(mdtFindReplace); with pTMacroCmdFind(Data)^ do begin StrFind:=s; Cfg.Origin:=TFindOrigin(num_values[1]); Cfg.Scope:=TFindScope(num_values[2]); Cfg.CaseSensitive:=boolean(num_values[3]); Cfg.WholeWords:=boolean(num_values[4]); Cfg.Direction:=TFindDirection(num_values[5]); end; end; end; ecString: if GetStringParam(s,TRUE,TRUE) then begin for i:=1 to Length(s) do AddMacroCommand(nil,ecChar,s[i],nil); end; end; if (not error) and not (Cmd=ecString) then AddMacroCommand(nil,Cmd,Chr,Data); end; begin result:=FALSE; if FileExists(fname) then begin str:=TStringList.Create; try str.LoadFromFile(fname); except str.Free; EXIT; result:=TRUE; end; end else EXIT; buff:=AllocMem(Length(str.Text)+1); try StrPCopy(buff, str.Text); ptr:=buff; repeat if ParseMacroDefinition then begin mac:=StartRecording(nil,MacroName,MacroKey,MacroShift); mac^.Disabled:=(MacroDisabled='1'); finished:=FALSE; repeat lex; if (token=tkIdent) then begin if IdentToEditorCommand(svalue,Cmd) or (CustomIdentToEditorCommand(svalue,Cmd)) then begin ParseCommand(Cmd); end else if CheckSyntax(UpperCase(svalue)='MACROEND', ERR_SYNTAX_ERR) then begin finished:=TRUE; end; end else CheckSyntax(token=tkEOF, ERR_SYNTAX_ERR); until (finished or error or (token in [tkEOF,tkError])); if not error then StopRecording(nil); end; until (error or (token in [tkEOF,tkError])); finally FreeMem(buff); str.Free; Changed:=FALSE; end; end; //------------------------------------------------------------------------------------------ function TMacros.MacroCommandToStr(var CmdStr:string; Command:pTMacroCmd):boolean; begin result:=TRUE; case Command^.Cmd of ecFillBlock: with pTMacroCmdFill(Command^.Data)^ do begin CmdStr:=Format('%s("%s")', [CmdStr, Str ]); end; ecFind: with pTMacroCmdFind(Command^.Data)^ do begin CmdStr:=Format('%s("%s",%d,%d,%d,%d,%d)', [CmdStr, StrFind, ord(Cfg.Origin), ord(Cfg.Scope), integer(Cfg.CaseSensitive), integer(Cfg.WholeWords), ord(Cfg.Direction) ]); end; else result:=FALSE; end; end; //------------------------------------------------------------------------------------------ function TMacros.Save(fname:string):boolean; var i, ii :integer; str :TStringList; s :string; ss :string; mac :pTMacro; retry :boolean; function FlushString:boolean; begin result:=FALSE; if (Length(ss)>0) then begin if (Length(ss)=1) then str.Add(' ecChar("'+ss+'")') else str.Add(' ecString("'+ss+'")'); ss:=''; result:=TRUE; end; end; begin if Changed then begin if (MessageDlg(mlStr(ML_MACRO_SAVE_PROMPT,'Macros changed, but not saved. Save macro file now?'), mtWarning,[mbYes,mbNo],0)=mrNo) then begin result:=TRUE; EXIT; end; str:=TStringList.Create; try for i:=0 to Count-1 do begin mac:=pTMacro(strMacros.Objects[i]); if Assigned(mac) then begin // prvo header str.Add(''); str.Add(Format('MacroBegin(Name:"%s"; Disabled:"%d"; Shortcut:"%s")', [strMacros[i], integer(mac^.Disabled), ShortcutToText(Shortcut(mac^.Key,mac^.Shift)) ])); ss:=''; for ii:=0 to mac^.CmdCount-1 do begin if EditorCommandToIdent(mac^.Commands[ii].Cmd,s) or CustomEditorCommandToIdent(mac^.Commands[ii].Cmd,s) then if (mac^.Commands[ii].Cmd=ecChar) then begin if (mac^.Commands[ii].AChar in ['"','\']) then ss:=ss+'\'; ss:=ss+mac^.Commands[ii].AChar end else begin FlushString; MacroCommandToStr(s,@mac^.Commands[ii]); str.Add(' '+s); end; end; FlushString; // kraj macroa str.Add('MacroEnd'); str.Add(''); end; end; retry:=TRUE; while retry do begin try str.SaveToFile(fname); retry:=FALSE; except retry:=MessageDlg(Format(mlStr(ML_MACRO_ERR_SAVING,'Error saving macro file ''%s''.'),[fname]), mtError,[mbOK, mbRetry],0)=mrRetry; end; end; finally str.Free; end; Changed:=FALSE; end; end; //------------------------------------------------------------------------------------------ end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.TargetPlatform; interface uses DPM.Core.Types; type TTargetPlatform = record private FCompiler : TCompilerVersion; FPlatform : TDPMPlatform; function GetIsValid : boolean; public class operator Equal(a : TTargetPlatform; b : TTargetPlatform) : boolean; class operator NotEqual(a : TTargetPlatform; b : TTargetPlatform) : boolean; class function Parse(const value : string) : TTargetPlatform; static; class function TryParse(const value : string; out targetPlatform : TTargetPlatform) : boolean; static; class function Empty : TTargetPlatform; static; constructor Create(const compiler : TCompilerVersion; const platform : TDPMPlatform); function Clone : TTargetPlatform; function ToString : string; function IsCompatibleWith(const value : TTargetPlatform) : boolean; property Compiler : TCompilerVersion read FCompiler; property Platform : TDPMPlatform read FPlatform; property IsValid : boolean read GetIsValid; end; //make sure the compiler supports the platform function ValidatePlatform(const target : TCompilerVersion; const platform : TDPMPlatform) : boolean; implementation uses System.SysUtils, System.StrUtils, System.TypInfo, System.Types; function ValidatePlatform(const target : TCompilerVersion; const platform : TDPMPlatform) : boolean; begin result := platform in AllPlatforms(target); end; { TTargetPlatform } function TTargetPlatform.IsCompatibleWith(const value : TTargetPlatform) : boolean; begin result := (Self.Compiler = value.Compiler) and (Self.Platform = value.Platform); exit; end; function TTargetPlatform.Clone : TTargetPlatform; begin result := TTargetPlatform.Create(FCompiler, FPlatform); end; constructor TTargetPlatform.Create(const compiler : TCompilerVersion; const platform : TDPMPlatform); begin FCompiler := compiler; FPlatform := platform; end; class function TTargetPlatform.Empty : TTargetPlatform; begin result := TTargetPlatform.Create(TCompilerVersion.UnknownVersion, TDPMPlatform.UnknownPlatform); end; class operator TTargetPlatform.Equal(a, b : TTargetPlatform) : boolean; begin result := (a.Compiler = b.Compiler) and (a.Platform = b.Platform); end; function TTargetPlatform.GetIsValid : boolean; begin result := ValidatePlatform(FCompiler, FPlatform); end; class operator TTargetPlatform.NotEqual(a, b : TTargetPlatform) : boolean; begin result := not (a = b); end; class function TTargetPlatform.Parse(const value : string) : TTargetPlatform; var parts : array[0..1] of string; target : TCompilerVersion; platform : TDPMPlatform; i : integer; begin i := LastDelimiter('.', value); if i = 0 then raise EArgumentException.Create(value + ' is not a valid target platform, format is [Target].[Platform], e.g: RSXE7.Win32'); parts[0] := Copy(value, 1, i - 1); parts[1] := Copy(value, i + 1, length(value)); if (parts[0] = '') or (parts[1] = '') then raise EArgumentException.Create(value + ' is not a valid target platform, format is [Target].[Platform], e.g: RSXE7.Win32'); target := StringToCompilerVersion(parts[0]); if target = TCompilerVersion.UnknownVersion then raise EArgumentOutOfRangeException.Create('Invalid Compiler version : ' + parts[0]); platform := StringToDPMPlatform(parts[1]); if platform = TDPMPlatform.UnknownPlatform then raise EArgumentOutOfRangeException.Create('Invalid Platform : ' + parts[1]); result := TTargetPlatform.Create(target, platform); end; function TTargetPlatform.ToString : string; var sCompiler : string; sPlatform : string; begin sCompiler := GetEnumName(typeinfo(TCompilerVersion), ord(Compiler)); sPlatform := GetEnumName(typeinfo(TDPMPlatform), ord(FPlatform)); result := Format('%s.%s', [sCompiler, sPlatform]); end; class function TTargetPlatform.TryParse(const value : string; out targetPlatform : TTargetPlatform) : boolean; begin result := true; try targetPlatform := TTargetPlatform.Parse(value); except result := false; end; end; end.
unit Ils.Redis.Conf; interface uses IniFiles; type TRedisConf = record Host: string; Port: Integer; Password: string; SSL: Boolean; Enabled: Boolean; constructor Create(const AHost: string; const APort: Integer; const APassword: string; const ASSL: Boolean; const AEnabled: Boolean); overload; constructor Create(const AIni: TIniFile; const ASectionSuffix: string = ''); overload; end; implementation { TRedisConf } constructor TRedisConf.Create(const AHost: string; const APort: Integer; const APassword: string; const ASSL: Boolean; const AEnabled: Boolean); begin Host := AHost; Port := APort; Password := APassword; SSL := ASSL; Enabled := AEnabled; end; constructor TRedisConf.Create(const AIni: TIniFile; const ASectionSuffix: string = ''); var SectionName: string; begin SectionName := 'redis'; if ASectionSuffix <> '' then SectionName := SectionName + '.' + ASectionSuffix; Host := AIni.ReadString(SectionName, 'host', '127.0.0.1'); Port := AIni.ReadInteger(SectionName, 'port', 6378); Password := AIni.ReadString(SectionName, 'password', ''); SSL := AIni.ReadBool(SectionName, 'ssl', False); Enabled := AIni.ReadBool(SectionName, 'enabled', True); end; end.
namespace archimedianspiralapplet; // Sample applet project by Brian Long (http://blong.com) // Translated from Michael McGuffin's ArchimedianSpiral applet // from http://profs.etsmtl.ca/mmcguffin/learn/java/12-miscellaneous interface uses java.util, java.applet.*, java.awt; type ArchimedianSpiralApplet = public class(Applet) private var width, height: Integer; const N = 30; // number of points per full rotation const W = 5; // winding number, or number of full rotations public method init(); override; method paint(g: Graphics); override; end; implementation method ArchimedianSpiralApplet.init(); begin width := Size.width; height := Size.height; Background := Color.BLACK; Foreground := Color.GREEN; end; method ArchimedianSpiralApplet.paint(g: Graphics); begin var x1: Integer := 0; var y1: Integer := 0; var x2, y2: Integer; for i: Integer := 1 to W * N - 1 do begin var angle: Double := 2 * Math.PI * i / Double(N); var radius: Double := i / Double(N) * width / 2 / (W + 1); x2 := Integer(radius * Math.cos(angle)); y2 := -Integer(radius * Math.sin(angle)); g.drawLine(width / 2 + x1, height / 2 + y1, width / 2 + x2, height / 2 + y2); x1 := x2; y1 := y2 end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XMLDoc, XMLIntf, ShellAPI, XPMan, ActiveX, IdBaseComponent, IdComponent, IdTCPServer, IdCustomHTTPServer, IdHTTPServer, ShlObj, Menus, ExtCtrls, ComCtrls, IniFiles; type TMain = class(TForm) PathSearchLbl: TLabel; ExtFilesLbl: TLabel; TypeFilesLbl: TLabel; IgnorePathLbl: TLabel; CreateCatBtn: TButton; ExtsEdit: TEdit; AllCB: TCheckBox; TextCB: TCheckBox; PicsCB: TCheckBox; ArchCB: TCheckBox; ClearExtsBtn: TButton; IgnorePaths: TMemo; AddIgnorePathBtn: TButton; XPManifest: TXPManifest; IdHTTPServer: TIdHTTPServer; SaveDialog: TSaveDialog; PopupMenu: TPopupMenu; GoToSearchBtn: TMenuItem; Line: TMenuItem; DataBaseBtn: TMenuItem; DBCreateBtn: TMenuItem; Line2: TMenuItem; AboutBtn: TMenuItem; ExitBtn: TMenuItem; Paths: TMemo; AddPathBtn: TButton; CancelBtn: TButton; StatusBar: TStatusBar; OpenPathsBtn: TButton; SavePathsBtn: TButton; OpenDialog: TOpenDialog; OpenIgnorePathsBtn: TButton; SaveIgnorePathsBtn: TButton; VideoCB: TCheckBox; AudioCB: TCheckBox; DBsOpen: TMenuItem; Line3: TMenuItem; TagsCB: TCheckBox; TagsBtn: TMenuItem; TagsCreateBtn: TMenuItem; procedure FormCreate(Sender: TObject); procedure CreateCatBtnClick(Sender: TObject); procedure IdHTTPServerCommandGet(AThread: TIdPeerThread; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure AddPathBtnClick(Sender: TObject); procedure ClearExtsBtnClick(Sender: TObject); procedure AddIgnorePathBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure DBCreateBtnClick(Sender: TObject); procedure GoToSearchBtnClick(Sender: TObject); procedure AboutBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure OpenPathsBtnClick(Sender: TObject); procedure SavePathsBtnClick(Sender: TObject); procedure OpenIgnorePathsBtnClick(Sender: TObject); procedure SaveIgnorePathsBtnClick(Sender: TObject); procedure DBsOpenClick(Sender: TObject); procedure TagsCreateBtnClick(Sender: TObject); procedure FormActivate(Sender: TObject); private procedure ScanDir(Dir: string); procedure DefaultHandler(var Message); override; function GetResults(RequestText, RequestType, RequestExt, RequestCategory: string): string; procedure ControlWindow(var Msg: TMessage); message WM_SYSCOMMAND; { Private declarations } public { Public declarations } protected { Protected declarations } procedure IconMouse(var Msg : TMessage); message wm_user+1; end; const DataBasesPath = 'dbs'; PathsExt = 'hsp'; //Расширение для файла со списком папок - Home Search Paths (HSP) TagsExt = 'hst'; //Расширение для файла с тегами - Home Search Tags (HST) var Main: TMain; WM_TASKBARCREATED: Cardinal; doc: IXMLDocument; XMLFile: TStringList; AllowIPs, TemplateMain, TemplateResults, TemplateOpen, Template404: TStringList; RunOnce: boolean; TemplateName: string; TextExts, PicExts, VideoExts, AudioExts, ArchExts: string; MaxPageResults, MaxPages: integer; FileTagsList: TStringList; implementation uses Unit2; {$R *.dfm} const cuthalf = 100; var buf: array [0..((cuthalf * 2) - 1)] of integer; function min3(a, b, c: integer): integer; begin Result:=a; if b < Result then Result:=b; if c < Result then Result:=c; end; procedure Tray(n:integer); //1 - добавить, 2 - удалить, 3 - заменить var nim: TNotifyIconData; begin with nim do begin cbSize:=SizeOf(nim); wnd:=Main.Handle; uId:=1; uFlags:=NIF_ICON or NIF_MESSAGE or NIF_TIP; //hIcon:=Application.Icon.Handle; hIcon:=Main.Icon.Handle; uCallBackMessage:=WM_User + 1; StrCopy(szTip, PChar(Application.Title)); end; case n of 1: Shell_NotifyIcon(NIM_ADD, @nim); 2: Shell_NotifyIcon(NIM_DELETE, @nim); 3: Shell_NotifyIcon(NIM_MODIFY, @nim); end; end; procedure TMain.IconMouse(var Msg: TMessage); begin case Msg.lParam of WM_LBUTTONDOWN: begin //Скрываем PopupMenu PostMessage(Handle, WM_LBUTTONDOWN, MK_LBUTTON, 0); PostMessage(Handle, WM_LBUTTONUP, MK_LBUTTON, 0); end; WM_LBUTTONDBLCLK: GoToSearchBtn.Click; WM_RBUTTONDOWN: PopupMenu.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; //Расстояние Левенштейна function LevDist(s, t: string): integer; var i, j, m, n: integer; cost: integer; flip: boolean; begin s:=Copy(s, 1, cuthalf - 1); t:=Copy(t, 1, cuthalf - 1); m:=Length(s); n:=Length(t); if m = 0 then Result:=n else if n = 0 then Result:=m else begin flip := false; for i:=0 to n do buf[i] := i; for i:=1 to m do begin if flip then buf[0]:=i else buf[cuthalf]:=i; for j:=1 to n do begin if s[i] = t[j] then cost:=0 else cost:=1; if flip then buf[j]:=min3((buf[cuthalf + j] + 1), (buf[j - 1] + 1), (buf[cuthalf + j - 1] + cost)) else buf[cuthalf + j]:=min3((buf[j] + 1), (buf[cuthalf + j - 1] + 1), (buf[j - 1] + cost)); end; flip:=not flip; end; if flip then Result:=buf[cuthalf + n] else Result:=buf[n]; end; end; procedure TMain.FormCreate(Sender: TObject); var Ini: TIniFile; begin //Main.BorderStyle:=bsNone; Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Setup.ini'); IdHTTPServer.DefaultPort:=Ini.ReadInteger('Main', 'Port', 757); IdHTTPServer.TerminateWaitTime:=Ini.ReadInteger('Main', 'TerminateWaitTime', 5000); TemplateName:=Ini.ReadString('Main', 'Template', 'default'); //Результаты MaxPageResults:=Ini.ReadInteger('Results', 'MaxPageResults', 12); MaxPages:=Ini.ReadInteger('Results', 'MaxPages', 10); //Типы данных TextExts:=Ini.ReadString('Types', 'TextExts', 'txt html htm pdf rtf chm'); PicExts:=Ini.ReadString('Types', 'PicExts', 'jpg jpeg bmp png apng gif'); VideoExts:=Ini.ReadString('Types', 'VideoExts', 'mp4 3gp flv mpeg avi mkv mov'); AudioExts:=Ini.ReadString('Types', 'AudioExts', 'mp3 wav aac flac ogg'); ArchExts:=Ini.ReadString('Types', 'ArchExts', '7z zip rar'); Ini.Free; //Шаблоны TemplateMain:=TStringList.Create; TemplateMain.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'templates\' + TemplateName + '\index.htm'); TemplateResults:=TStringList.Create; TemplateResults.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'templates\' + TemplateName + '\results.htm'); TemplateOpen:=TStringList.Create; TemplateOpen.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'templates\' + TemplateName + '\open.htm'); Template404:=TStringList.Create; Template404.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'templates\' + TemplateName + '\404.htm'); //IP для доступа AllowIPs:=TStringList.Create; AllowIPs.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Allow.txt'); Application.Title:='Home Search'; IdHTTPServer.Active:=true; WM_TASKBARCREATED:=RegisterWindowMessage('TaskbarCreated'); Tray(1); //Main.AlphaBlend:=true; //Main.AlphaBlendValue:=0; SetWindowLong(Application.Handle, GWL_EXSTYLE,GetWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW); //Скрываем программу с панели задач ExtsEdit.Text:=TextExts; end; //Возможное количество ошибок для слова function GetWordErrorCount(Str: string): integer; begin Result:=(Length(Str) div 4) + 1; end; function DigitToHex(Digit: Integer): Char; begin case Digit of 0..9: Result := Chr(Digit + Ord('0')); 10..15: Result := Chr(Digit - 10 + Ord('A')); else Result:='0'; end; end; function URLDecode(const S: string): string; var i, idx, len, n_coded: Integer; function WebHexToInt(HexChar: Char): Integer; begin if HexChar < '0' then Result:=Ord(HexChar) + 256 - Ord('0') else if HexChar <= Chr(Ord('A') - 1) then Result:=Ord(HexChar) - Ord('0') else if HexChar <= Chr(Ord('a') - 1) then Result:=Ord(HexChar) - Ord('A') + 10 else Result:=Ord(HexChar) - Ord('a') + 10; end; begin len:=0; n_coded:=0; for i:=1 to Length(S) do if n_coded >= 1 then begin n_coded:=n_coded + 1; if n_coded >= 3 then n_coded:=0; end else begin len:=len + 1; if S[i] = '%' then n_coded:=1; end; SetLength(Result, len); idx:=0; n_coded:=0; for i:=1 to Length(S) do if n_coded >= 1 then begin n_coded:=n_coded + 1; if n_coded >= 3 then begin Result[idx]:=Chr((WebHexToInt(S[i - 1]) * 16 + WebHexToInt(S[i])) mod 256); n_coded:=0; end; end else begin idx:=idx + 1; if S[i] = '%' then n_coded:=1; if S[i] = '+' then Result[idx]:=' ' else Result[idx]:=S[i]; end; end; function FixName(Str: string): string; begin Str:=StringReplace(Str, '&', '&amp;', [rfReplaceAll]); //Str:=StringReplace(Str, '<', '&lt;', [rfReplaceAll]); //Str:=StringReplace(Str, '>', '&gt;', [rfReplaceAll]); //Str:=StringReplace(Str, '"', '&quot;', [rfReplaceAll]); //Str:=StringReplace(Str, '«', '&laquo;', [rfReplaceAll]); //Str:=StringReplace(Str, '»', '&raquo;', [rfReplaceAll]); Result:=Str; end; function RevertFixName(Str: string): string; begin Str:=StringReplace(Str, '&amp;', '&', [rfReplaceAll]); //Str:=StringReplace(Str, '&lt;', '<', [rfReplaceAll]); //Str:=StringReplace(Str, '&gt;', '>', [rfReplaceAll]); //Str:=StringReplace(Str, '&quot;', '"', [rfReplaceAll]); //Str:=StringReplace(Str, '&laquo;', '«', [rfReplaceAll]); //Str:=StringReplace(Str, '&raquo;', '»', [rfReplaceAll]); Result:=Str; end; function FixNameURI(Str: string): string; begin Str:=StringReplace(Str, '\', '\\', [rfReplaceAll]); Str:=StringReplace(Str, '&', '*AMP', [rfReplaceAll]); Str:=StringReplace(Str, '''', '*APOS', [rfReplaceAll]); //апостроф заменяется на спец. слово *APOS Result:=Str; end; //Проверка на UTF8 function IsUTF8Encoded(Str: string): boolean; begin Result:=(Str <> '') and (UTF8Decode(Str) <> '') end; function RevertFixNameURI(Str: string): string; begin Str:=URLDecode(Str); Str:=StringReplace(Str, '*APOS', '''', [rfReplaceAll]); //апостроф заменяется на спец. слово *APOS Str:=StringReplace(Str, '\\', '\',[rfReplaceAll]); Str:=StringReplace(Str, '*AMP', '&',[rfReplaceAll]); if UTF8Decode(Str) <> '' then Str:=UTF8ToAnsi(Str); Result:=Str; end; function TMain.GetResults(RequestText, RequestType, RequestExt, RequestCategory: string): string; var ResponseNode: IXMLNode; i, j, n, ResultRank, TickTime, PagesCount: integer; Doc: IXMLDocument; Filters: string; SearchList, CheckList, TagsList, Results: TStringList; ResultsA: array of Packed Record Name: string; Path: string; Rank: integer; end; ResultsC: integer; TempRank: integer; TempName, TempPath: string; const MinCountChars = 2; begin SearchList:=TStringList.Create; CheckList:=TStringList.Create; TagsList:=TStringList.Create; Results:=TStringList.Create; RequestText:=AnsiLowerCase(RequestText); SearchList.Text:=StringReplace(RequestText, ' ', #13#10, [rfReplaceAll]); //Категория if (RequestCategory <> '') and (FileExists(ExtractFilePath(ParamStr(0)) + DataBasesPath + '\' + RequestCategory + '.xml')) then RequestCategory:=RequestCategory + '.xml' else RequestCategory:='default.xml'; Doc:=LoadXMLDocument(ExtractFilePath(ParamStr(0)) + DataBasesPath + '\' + RequestCategory); TickTime:=GetTickCount; //Затраченное время ResponseNode:=Doc.DocumentElement.childnodes.Findnode('files'); //Фильтры по умолчанию Filters:=TextExts; //Если заданы типы расширений if RequestExt <> '' then begin Filters:=StringReplace(RequestExt, ';', ' ', [rfReplaceAll]); Filters:=StringReplace(Filters, '+', ' ', [rfReplaceAll]); Filters:=StringReplace(Filters, ',', ' ', [rfReplaceAll]); end; if RequestType = 'all' then Filters:=''; if RequestType = 'text' then Filters:=TextExts; if RequestType = 'pics' then Filters:=PicExts; if RequestType = 'video' then Filters:=VideoExts; if RequestType = 'audio' then Filters:=AudioExts; if RequestType = 'arch' then Filters:=ArchExts; ResultsC:=0; for i:=0 to Responsenode.ChildNodes.Count - 1 do begin ResultRank:=0; //Пропускаем если расширение не совпадает, кроме поиска по всем файлам if ((RequestType <> 'all') and (Pos(ResponseNode.ChildNodes[i].Attributes['ext'], Filters) = 0)) then Continue; //Преобразование названия в список (разбор поискового текста на строки) CheckList.Text:=AnsiLowerCase(ResponseNode.ChildNodes[i].NodeValue); CheckList.Text:=StringReplace(CheckList.Text, '&amp;', ' ', [rfReplaceAll]); //CheckList.Text:=StringReplace(CheckList.Text, '&lt;', '', [rfReplaceAll]); //CheckList.Text:=StringReplace(CheckList.Text, '&gt;', '', [rfReplaceAll]); //CheckList.Text:=StringReplace(CheckList.Text, '&quot;', '', [rfReplaceAll]); CheckList.Text:=StringReplace(CheckList.Text, '-', '', [rfReplaceAll]); CheckList.Text:=StringReplace(CheckList.Text, ' ', #13#10, [rfReplaceAll]); //Преобразование тегов в список TagsList.Text:=ResponseNode.ChildNodes[i].Attributes['tags']; //Теги в базе уже LowerCase TagsList.Text:=StringReplace(TagsList.Text, ',', #13#10, [rfReplaceAll]); //Проверка на полное совпадение включая расширение if RequestText = AnsiLowerCase(ResponseNode.ChildNodes[i].NodeValue + '.' + ResponseNode.ChildNodes[i].Attributes['ext']) then ResultRank:=ResultRank + 12; //Проверка на полное совпадение без расширения if RequestText = AnsiLowerCase(ResponseNode.ChildNodes[i].NodeValue) then ResultRank:=ResultRank + 9; //Проверка на частичное вхождение if Pos(RequestText, CheckList.Text) > 0 then ResultRank:=ResultRank + 3; if Pos(CheckList.Text, RequestText) > 0 then ResultRank:=ResultRank + 3; //Проверка на совпадение c ошибками if LevDist(RequestText, AnsiLowerCase(ResponseNode.ChildNodes[i].NodeValue)) < GetWordErrorCount(RequestText) then ResultRank:=ResultRank + 7; //Проверка на отдельных слова for j:=0 to CheckList.Count - 1 do for n:=0 to SearchList.Count - 1 do begin if (Length(SearchList.Strings[n]) > MinCountChars) and (Length(CheckList.Strings[j]) > MinCountChars) then begin //Проверка на прямое вхождение if SearchList.Strings[n] = CheckList.Strings[j] then ResultRank:=ResultRank + 7 //Проверка на вхождение с ошибками (расстояние Левинштейна) else if LevDist(SearchList.Strings[n], CheckList.Strings[j]) < GetWordErrorCount(SearchList.Strings[n]) then ResultRank:=ResultRank + 5 //Проверка на частичное вхождение else if Pos(SearchList.Strings[n], CheckList.Strings[j]) > 0 then ResultRank:=ResultRank + 3; end; //Проверка на прямое совпадение расширения с запросом (Запрос + " " + расширение) if SearchList.Strings[n] = ResponseNode.ChildNodes[i].Attributes['ext'] then //Расширения в базе уже LowerCase ResultRank:=ResultRank + 1; end; //Проверки на теги if TagsList.Text <> '' then for j:=0 to TagsList.Count - 1 do begin for n:=0 to SearchList.Count - 1 do if (Length(SearchList.Strings[n]) > MinCountChars) and (Length(TagsList.Strings[j]) > MinCountChars) then begin //Проверка на прямое вхождение if SearchList.Strings[n] = TagsList.Strings[j] then ResultRank:=ResultRank + 7 //Проверка на вхождение с ошибками (расстояние Левинштейна) else if LevDist(SearchList.Strings[n], TagsList.Strings[j]) < GetWordErrorCount(SearchList.Strings[n]) then ResultRank:=ResultRank + 4; end; //Проверка на прямое совпадение тега и запроса if RequestText = TagsList.Strings[j] then ResultRank:=ResultRank + 8 //Проверка на совпадение с ошибками else if LevDist(RequestText, TagsList.Strings[j]) < GetWordErrorCount(RequestText) then ResultRank:=ResultRank + 5; end; //Проверка на вхождение рядом стоящих склеенных слов запроса for j:=0 to SearchList.Count - 2 do for n:=0 to CheckList.Count - 1 do begin //Проверка на прямое вхождение склеенных слов запроса if Pos(SearchList.Strings[j] + SearchList.Strings[j + 1], CheckList.Strings[n]) > 0 then ResultRank:=ResultRank + 3 //Проверка на вхождение рядом стоящих склеенных слов запроса с ошибками (расстояние Левинштейна) else if LevDist(SearchList.Strings[j] + SearchList.Strings[j + 1], CheckList.Strings[n]) < GetWordErrorCount(SearchList.Strings[j] + SearchList.Strings[j + 1]) then ResultRank:=ResultRank + 2; end; //Преобразование пути в список папок CheckList.Text:=Copy(Copy(ResponseNode.ChildNodes[i].Attributes['path'], Length(ExtractFileDrive(ResponseNode.ChildNodes[i].Attributes['path'])) + 1, Length(ResponseNode.ChildNodes[i].Attributes['path'])), 2, Length(ResponseNode.ChildNodes[i].Attributes['path']) - Length(ResponseNode.ChildNodes[i].NodeValue + '.' + ResponseNode.ChildNodes[i].Attributes['ext']) - 3); //Проверка на частичное вхождение запроса в название всего пути if Pos(RequestText, CheckList.Text) > 0 then ResultRank:=ResultRank + 3; //Разделение папок на строки CheckList.Text:=StringReplace(CheckList.Text, '\', #13#10, [rfReplaceAll]); for j:=0 to CheckList.Count - 1 do for n:=0 to SearchList.Count - 1 do if (Length(SearchList.Strings[n]) > MinCountChars) and (Length(CheckList.Strings[j]) > MinCountChars) then begin //Проверка на название папок без ошибок if SearchList.Strings[n] = CheckList.Strings[j] then ResultRank:=ResultRank + 2 //Проверка на название папок с ошибками (расстояние Левинштейна) else if (LevDist(SearchList.Strings[n], CheckList.Strings[j]) < GetWordErrorCount(SearchList.Strings[n])) then ResultRank:=ResultRank + 1; end; //Конец проверки на совпадения папок //Если найдены совпадения if ResultRank > 0 then begin //Заполнение массива для сортировки по ResultRank Inc(ResultsC); SetLength(ResultsA, ResultsC); ResultsA[ResultsC - 1].Name:=Responsenode.ChildNodes[i].NodeValue; ResultsA[ResultsC - 1].Path:=ResponseNode.ChildNodes[i].Attributes['path']; ResultsA[ResultsC - 1].Rank:=ResultRank; end; end; //Конец проверки XML //Сортировка результатов по ResultRank for i:=0 to Length(ResultsA) - 1 do for j:=0 to Length(ResultsA) - 1 do if ResultsA[i].Rank > ResultsA[j].Rank then begin TempName:=ResultsA[i].Name; TempPath:=ResultsA[i].Path; TempRank:=ResultsA[i].Rank; ResultsA[i].Name:=ResultsA[j].Name; ResultsA[i].Path:=ResultsA[j].Path; ResultsA[i].Rank:=ResultsA[j].Rank; ResultsA[j].Name:=TempName; ResultsA[j].Path:=TempPath; ResultsA[j].Rank:=TempRank; end; if ResultsC > 0 then Results.Add(#9 + '<span style="display:block; color:gray; padding-bottom:12px;">Результатов: '+ IntToStr(ResultsC) + ' ('+ FloatToStr((GetTickCount - TickTime) / 1000) + ' сек.)</span>' + #13#10) else Results.Add(#9 + '<p>По Вашему запросу <b>' + RequestText + '</b> не найдено соответствующих файлов.</p>' + #13#10); //Вывод результатов PagesCount:=1; Results.Add(#9 + '<div id="page1" style="display:block;">' + #13#10); for i:=0 to Length(ResultsA) - 1 do begin if (i <> 0) and (i mod MaxPageResults = 0) then begin //Ограничить кол-во страниц if PagesCount = MaxPages then break; Inc(PagesCount); Results.Add('</div>' + #13#10#13#10 + '<div id="page' + IntToStr(PagesCount) + '" style="display:none;">'); end; Results.Add(#9#9 + '<div id="item">' + #13#10 + #9#9#9 + '<span id="title" onclick="Request(''' + '/?file=' + FixNameURI(ResultsA[i].path) + ''', this);">' + ResultsA[i].Name + ExtractFileExt(ResultsA[i].Path) + '</span>' + #13#10 + #9#9#9 + '<!--ResultRank ' + IntToStr(ResultsA[i].Rank) + '-->' + #13#10 + #9#9#9 + '<div id="link">' + ResultsA[i].Path + '</div>' + #13#10 + //'<div id="description">Пусто</div>' + #13#10 + #9#9#9 + '<span id="folder" onclick="Request(''' + '/?folder=' + FixNameURI(ResultsA[i].Path) + ''', this);">Открыть папку</span>' + #13#10 + #9#9 + '</div>' + #13#10); end; Results.Add(#9 + '</div>' + #13#10); //Вывод страничной навигации if PagesCount > 1 then begin Results.Add(#13#10 + '<div id="pages">Страницы: '); Results.Text:=Results.Text + #9 + '<span id="nav1" class="active" onclick="ShowResults(1);">1</span>'; for i:=2 to PagesCount do Results.Text:=Results.Text + #9 + '<span id="nav' + IntToStr(i) + '" onclick="ShowResults(' + IntToStr(i) + ');">' + IntToStr(i) + '</span>'; Results.Add('</div>'); end; ResultsA:=nil; Result:=Results.Text; Results.Free; SearchList.Free; CheckList.Free; TagsList.Free; end; function CutStr(Str: string; CharCount: integer): string; begin if Length(Str) > CharCount then Result:=Copy(Str, 1, CharCount - 3) + '...' else Result:=Str; end; procedure TMain.ScanDir(Dir: string); var SR: TSearchRec; i: integer; FileTags: string; begin StatusBar.SimpleText:=CutStr(' Идет сканирование папки: ' + Dir, 70); if Dir[Length(Dir)] <> '\' then Dir:=Dir + '\'; //Игнорируемые папки if (Trim(IgnorePaths.Text) <> '') then for i:=0 to IgnorePaths.Lines.Count - 1 do if Trim(IgnorePaths.Lines.Strings[i]) <> '' then if IgnorePaths.Lines.Strings[i] + '\' = Dir then Exit; //Теги if (TagsCB.Checked) and (FileExists(Dir + 'tags.' + TagsExt)) then try FileTagsList.LoadFromFile(Dir + 'tags.' + TagsExt); except FileTagsList.Text:=''; end; //Поиск файлов if FindFirst(Dir + '*.*', faAnyFile, SR) = 0 then begin repeat Application.ProcessMessages; if (SR.Name <> '.') and (SR.Name <> '..') then if (SR.Attr and faDirectory) <> faDirectory then begin if (Pos(AnsiLowerCase(Copy(ExtractFileExt(SR.Name), 2, Length(ExtractFileExt(SR.Name)))), AnsiLowerCase(ExtsEdit.Text)) > 0) or (ExtsEdit.Text = '') and (ExtractFileExt(SR.Name) <> '.' + TagsExt) then begin FileTags:=''; //Теги if (TagsCB.Checked) and (FileTagsList.Text <> '') then for i:=0 to FileTagsList.Count - 1 do if (Trim(FileTagsList.Strings[i]) <> '') and (AnsiLowerCase( Copy(FileTagsList.Strings[i], 1, Pos(#9, FileTagsList.Strings[i]) - 1)) = AnsiLowerCase(SR.Name)) then begin FileTags:=Copy(FileTagsList.Strings[i], Pos(#9, FileTagsList.Strings[i]) + 1, Length(FileTagsList.Strings[i])); FileTags:=StringReplace(FileTags, ' ', ' ', [rfReplaceAll]); FileTags:=StringReplace(FileTags, ', ', ',', [rfReplaceAll]); break; end; XMLFile.Add(' <file ext="' + AnsiLowerCase(Copy(ExtractFileExt(SR.Name), 2, Length(ExtractFileExt(SR.Name)))) + '" tags="' + AnsiLowerCase(FileTags) + '" path="'+ FixName(Dir + SR.name) + '">'+ FixName(Copy(SR.Name, 1, Length(SR.Name) - Length(ExtractFileExt(SR.Name)))) + '</file>'); end; end else ScanDir(Dir + SR.Name + '\'); until FindNext(SR)<>0; FindClose(SR); end; end; procedure TMain.CreateCatBtnClick(Sender: TObject); var i: integer; DBSaveName: string; begin DBSaveName:=''; if InputQuery(Caption, 'Введите название базы данных:', DBSaveName) then begin if Pos(' ', DBSaveName) > 0 then begin Application.MessageBox('Название базы данных не должно содержать пробелов.', PChar(Application.Title), MB_ICONWARNING); Exit; end; //NTFS if (Pos('\', DBSaveName) > 0) or (Pos('/', DBSaveName) > 0) or (Pos(':', DBSaveName) > 0) or (Pos('*', DBSaveName) > 0) or (Pos('?', DBSaveName) > 0) or (Pos('"', DBSaveName) > 0) or (Pos('<', DBSaveName) > 0) or (Pos('>', DBSaveName) > 0) or (Pos('|', DBSaveName) > 0)// or //FAT //(Pos('+', DBSaveName) > 0) or (Pos('.', DBSaveName) > 0) or (Pos(';', DBSaveName) > 0) or //(Pos('=', DBSaveName) > 0) or (Pos('[', DBSaveName) > 0) or (Pos(']', DBSaveName) > 0) then begin Application.MessageBox('Имя файла не должно содержать запрещенных файловой системой знаков.', PChar(Application.Title), MB_ICONWARNING); Exit; end; //Отключение кнопок Paths.Enabled:=false; AddPathBtn.Enabled:=false; OpenPathsBtn.Enabled:=false; SavePathsBtn.Enabled:=false; ExtsEdit.Enabled:=false; ClearExtsBtn.Enabled:=false; AllCB.Enabled:=false; TextCB.Enabled:=false; PicsCB.Enabled:=false; ArchCB.Enabled:=false; IgnorePaths.Enabled:=false; AddIgnorePathBtn.Enabled:=false; OpenIgnorePathsBtn.Enabled:=false; SaveIgnorePathsBtn.Enabled:=false; CreateCatBtn.Enabled:=false; CancelBtn.Enabled:=false; if TextCB.Checked then if Pos(TextExts, ExtsEdit.Text) = 0 then ExtsEdit.Text:=ExtsEdit.Text + ' ' + TextExts; if PicsCB.Checked then if Pos(PicExts, ExtsEdit.Text) = 0 then ExtsEdit.Text:=ExtsEdit.Text + ' ' + PicExts; if VideoCB.Checked then if Pos(VideoExts, ExtsEdit.Text) = 0 then ExtsEdit.Text:=ExtsEdit.Text + ' ' + VideoExts; if AudioCB.Checked then if Pos(AudioExts, ExtsEdit.Text) = 0 then ExtsEdit.Text:=ExtsEdit.Text + ' ' + AudioExts; if ArchCB.Checked then if Pos(ArchExts, ExtsEdit.Text) = 0 then ExtsEdit.Text:=ExtsEdit.Text + ' ' + ArchExts; if (ExtsEdit.Text <> '') and (ExtsEdit.Text[1] = ' ') then ExtsEdit.Text:=Copy(ExtsEdit.Text, 2, Length(ExtsEdit.Text)); if AllCB.Checked then ExtsEdit.Text:=''; FileTagsList:=TStringList.Create; XMLFile:=TStringList.Create; XMLFile.Add('<?xml version="1.0" encoding="windows-1251" ?>'+#13#10+'<tree>'+#13#10+' <files>'); for i:=0 to Paths.Lines.Count - 1 do if Trim(Paths.Lines.Strings[i]) <> '' then ScanDir(Paths.Lines.Strings[i]); XMLFile.Add(' </files>'+#13#10+'</tree>'); if FileExists(ExtractFilePath(ParamStr(0)) + DataBasesPath + '\' + DBSaveName + '.xml') then DeleteFile(ExtractFilePath(ParamStr(0)) + 'dbs\' + DBSaveName + '.xml'); XMLFile.SaveToFile(ExtractFilePath(ParamStr(0)) + DataBasesPath + '\' + DBSaveName + '.xml'); XMLFile.Free; FileTagsList.Free; StatusBar.SimpleText:=''; Application.MessageBox('Готово', PChar(Application.Title), MB_ICONINFORMATION); //Включение кнопок Paths.Enabled:=true; AddPathBtn.Enabled:=true; OpenPathsBtn.Enabled:=true; SavePathsBtn.Enabled:=true; ExtsEdit.Enabled:=true; ClearExtsBtn.Enabled:=true; AllCB.Enabled:=true; TextCB.Enabled:=true; PicsCB.Enabled:=true; ArchCB.Enabled:=true; IgnorePaths.Enabled:=true; AddIgnorePathBtn.Enabled:=true; OpenIgnorePathsBtn.Enabled:=true; SaveIgnorePathsBtn.Enabled:=true; CreateCatBtn.Enabled:=true; CancelBtn.Enabled:=true; end; end; procedure TMain.IdHTTPServerCommandGet(AThread: TIdPeerThread; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var RequestText, RequestType, RequestExt, RequestCategory, TempRequestDocument, TempFilePath, TempDirPath: string; i: integer; WND: HWND; begin if (AllowIPs.Count > 0) and (Trim(AnsiUpperCase(AllowIPs.Strings[0])) <> 'ALL') then if Pos(AThread.Connection.Socket.Binding.PeerIP, AllowIPs.Text) = 0 then Exit; CoInitialize(nil); if (ARequestInfo.Document = '') or (ARequestInfo.Document = '/') and (ARequestInfo.Params.Text = '') then AResponseInfo.ContentText:=TemplateMain.Text else begin TempRequestDocument:=StringReplace(ARequestInfo.Document, '/', '\', [rfReplaceAll]); TempRequestDocument:=StringReplace(TempRequestDocument, '\\', '\', [rfReplaceAll]); if TempRequestDocument[1] = '\' then Delete(TempRequestDocument, 1, 1); if FileExists(ExtractFilePath(ParamStr(0)) + TempRequestDocument) then begin AResponseInfo.ContentType:=IdHTTPServer.MIMETable.GetDefaultFileExt(ExtractFilePath(ParamStr(0)) + TempRequestDocument); IdHTTPServer.ServeFile(AThread, AResponseinfo, ExtractFilePath(ParamStr(0)) + TempRequestDocument); end; end; if ARequestInfo.Params.Count > 0 then begin //Открытие файлов по запросу if Copy(ARequestInfo.Params.Text, 1, 5) = 'file=' then begin WND:=GetForegroundWindow(); AResponseInfo.ContentText:=TemplateOpen.Text; TempFilePath:=RevertFixNameURI(Copy(ARequestInfo.Params.Strings[0], 6, Length(ARequestInfo.Params.Strings[0]))); if FileExists(TempFilePath) then begin ShellExecute(0, 'open', PChar(TempFilePath), nil, nil, SW_SHOW); AResponseInfo.ContentText:=TemplateOpen.Text; SetForegroundWindow(WND); end else AResponseInfo.ContentText:=StringReplace(Template404.Text, '[%FILE%]', AnsiToUTF8(TempFilePath), [rfIgnoreCase]); end; //Открытие папок по запросу if Copy(ARequestInfo.Params.Text, 1, 7) = 'folder=' then begin TempFilePath:=RevertFixNameURI(Copy(ARequestInfo.Params.Strings[0], 8, Length(ARequestInfo.Params.Strings[0]))); if FileExists(TempFilePath) then begin ShellExecute(0, 'open', 'explorer', PChar('/select, ' + TempFilePath), nil, SW_SHOW); AResponseInfo.ContentText:=TemplateOpen.Text; end else begin TempDirPath:=Copy(TempFilePath, 1, Pos(ExtractFileName(TempFilePath), TempFilePath) - 1); if DirectoryExists(TempDirPath) then ShellExecute(0, 'open', PChar(TempDirPath), nil, nil, SW_SHOW) else AResponseInfo.ContentText:=StringReplace(Template404.Text, '[%FILE%]', UTF8ToAnsi(TempDirPath), [rfIgnoreCase]); end; end; if Copy(ARequestInfo.Params.Text, 1, 2) = 'q=' then begin RequestText:=Copy(ARequestInfo.Params.Strings[0], 3, Length(ARequestInfo.Params.Strings[0])); RequestText:=StringReplace(RequestText, ' ', ' ', [rfReplaceAll]); RequestText:=StringReplace(RequestText, ' type: ', ' type:', [rfIgnoreCase]); RequestText:=StringReplace(RequestText, ' ext: ', ' ext:', [rfIgnoreCase]); RequestText:=StringReplace(RequestText, ' cat: ', ' cat:', [rfIgnoreCase]); //Поиск команды type (тип данных) if Pos(' type:', AnsiLowerCase(RequestText)) > 0 then for i:=Pos(' type:', AnsiLowerCase(RequestText)) + 6 to Length(RequestText) do begin if RequestText[i]=' ' then break; RequestType:=RequestType+AnsiLowerCase(RequestText[i]); end; //Поиск команды ext (расширение) if Pos(AnsiLowerCase(' ext:'), AnsiLowerCase(RequestText)) > 0 then for i:=Pos(' ext:', AnsiLowerCase(RequestText)) + 5 to Length(RequestText) do begin if RequestText[i]=' ' then break; RequestExt:=RequestExt + AnsiLowerCase(RequestText[i]); end; //Поиск команды cat (категория) if Pos(AnsiLowerCase(' cat:'), AnsiLowerCase(RequestText)) > 0 then for i:=Pos(' cat:', AnsiLowerCase(RequestText)) + 5 to Length(RequestText) do begin if RequestText[i]=' ' then break; RequestCategory:=RequestCategory + AnsiLowerCase(RequestText[i]); end; //Удаление из запроса команд if Pos(' type:', AnsiLowerCase(RequestText)) > 0 then RequestText:=Copy(RequestText, 1, Pos(' type:', AnsiLowerCase(RequestText)) - 1); if Pos(' ext:', AnsiLowerCase(RequestText)) > 0 then RequestText:=Copy(RequestText, 1, Pos(' ext:', AnsiLowerCase(RequestText)) - 1); if Pos(' cat:', AnsiLowerCase(RequestText)) > 0 then RequestText:=Copy(RequestText, 1, Pos(' cat:', AnsiLowerCase(RequestText)) - 1); AResponseInfo.ContentText:=StringReplace( StringReplace(TemplateResults.Text, '[%NAME%]', Copy(ARequestInfo.Params.Strings[0], 3, Length(ARequestInfo.Params.Strings[0])), [rfReplaceAll]), '[%RESULTS%]', GetResults(RequestText, RequestType, RequestExt, RequestCategory), [rfIgnoreCase]); end; end; RequestType:=''; RequestExt:=''; RequestCategory:=''; CoUninitialize; end; function BrowseFolderDialog(Title: PChar): string; var TitleName: string; lpItemid: pItemIdList; BrowseInfo: TBrowseInfo; DisplayName: array[0..MAX_PATH] of Char; TempPath: array[0..MAX_PATH] of Char; begin FillChar(BrowseInfo, SizeOf(TBrowseInfo), #0); BrowseInfo.hwndOwner:=GetDesktopWindow; BrowseInfo.pSzDisplayName:=@DisplayName; TitleName:=Title; BrowseInfo.lpSzTitle:=PChar(TitleName); BrowseInfo.ulFlags:=bIf_ReturnOnlyFSDirs; lpItemId:=shBrowseForFolder(BrowseInfo); if lpItemId <> nil then begin shGetPathFromIdList(lpItemId, TempPath); Result:=TempPath; GlobalFreePtr(lpItemId); end; end; procedure TMain.AddPathBtnClick(Sender: TObject); begin Paths.Lines.Add(BrowseFolderDialog('Выберите папку')); if Paths.Lines.Strings[Paths.Lines.Count - 1] = '' then Paths.Lines.Delete(Paths.Lines.Count - 1); end; procedure TMain.ClearExtsBtnClick(Sender: TObject); begin ExtsEdit.Clear; end; procedure TMain.AddIgnorePathBtnClick(Sender: TObject); begin IgnorePaths.Lines.Add(BrowseFolderDialog('Выберите папку')); if IgnorePaths.Lines.Strings[IgnorePaths.Lines.Count - 1] = '' then IgnorePaths.Lines.Delete(IgnorePaths.Lines.Count - 1); end; procedure TMain.ExitBtnClick(Sender: TObject); begin Close; end; procedure TMain.FormDestroy(Sender: TObject); begin Tray(2); IdHTTPServer.Active:=false; TemplateMain.Free; TemplateResults.Free; TemplateOpen.Free; Template404.Free; AllowIPs.Free; end; procedure TMain.DefaultHandler(var Message); begin if TMessage(Message).Msg = WM_TASKBARCREATED then Tray(1); inherited; end; procedure TMain.DBCreateBtnClick(Sender: TObject); begin ShowWindow(Handle, SW_NORMAL); SetForegroundWindow(Main.Handle); end; procedure TMain.GoToSearchBtnClick(Sender: TObject); begin ShellExecute(Handle, nil, PChar('http://127.0.0.1:' + IntToStr(IdHTTPServer.DefaultPort)), nil, nil, SW_SHOW); end; procedure TMain.ControlWindow(var Msg: TMessage); begin case Msg.WParam of SC_MINIMIZE: ShowWindow(Handle, SW_HIDE); SC_CLOSE: ShowWindow(Handle, SW_HIDE); else inherited; end; end; procedure TMain.AboutBtnClick(Sender: TObject); begin Application.MessageBox('Home Search 0.6.3' + #13#10 + 'Последнее обновление: 17.11.2018' + #13#10 + 'http://r57zone.github.io' + #13#10 + 'r57zone@gmail.com', 'О программе...', MB_ICONINFORMATION); end; procedure TMain.CancelBtnClick(Sender: TObject); begin ShowWindow(Handle, SW_HIDE); end; procedure TMain.OpenPathsBtnClick(Sender: TObject); begin OpenDialog.FileName:=''; OpenDialog.Filter:='Папки Home Search|*.' + PathsExt; if OpenDialog.Execute then Paths.Lines.LoadFromFile(OpenDialog.FileName); end; procedure TMain.SavePathsBtnClick(Sender: TObject); begin SaveDialog.FileName:=''; SaveDialog.Filter:='Папки Home Search|*.' + PathsExt; SaveDialog.DefaultExt:=SaveDialog.Filter; if SaveDialog.Execute then Paths.Lines.SaveToFile(SaveDialog.FileName); end; procedure TMain.OpenIgnorePathsBtnClick(Sender: TObject); begin OpenDialog.FileName:=''; OpenDialog.Filter:='Папки Home Search|*.' + PathsExt; if OpenDialog.Execute then IgnorePaths.Lines.LoadFromFile(OpenDialog.FileName); end; procedure TMain.SaveIgnorePathsBtnClick(Sender: TObject); begin SaveDialog.FileName:=''; SaveDialog.Filter:='Папки Home Search|*.' + PathsExt; SaveDialog.DefaultExt:=SaveDialog.Filter; if SaveDialog.Execute then IgnorePaths.Lines.SaveToFile(SaveDialog.FileName); end; procedure TMain.DBsOpenClick(Sender: TObject); begin ShellExecute(Handle, 'open', PChar(ExtractFilePath(ParamStr(0)) + DataBasesPath), nil, nil, SW_SHOW); end; procedure TMain.TagsCreateBtnClick(Sender: TObject); begin TagsForm.Show; end; procedure TMain.FormActivate(Sender: TObject); begin if RunOnce = false then begin RunOnce:=true; Main.AlphaBlendValue:=255; ShowWindow(Handle, SW_HIDE); //Скрываем программу ShowWindow(Application.Handle, SW_HIDE); //Скрываем программу с панели задач end; end; end.
unit uAutoTablesClientDM; interface uses System.SysUtils, System.Classes, IPPeerClient, REST.Backend.ServiceTypes, System.JSON, REST.Backend.EMSServices, REST.Backend.MetaTypes, REST.Backend.BindSource, REST.Backend.ServiceComponents, Data.Bind.Components, Data.Bind.ObjectScope, REST.Client, REST.Backend.EndPoint, REST.Types, REST.Backend.EMSProvider, FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Stan.StorageJSON, REST.Backend.Providers; type TGetFuncType = procedure of object; TPostFuncType = procedure of object; TDeleteFuncType = procedure(const ID: String) of object; TAutoTablesClientDM = class(TDataModule) {#CompHeaderList#} private { Private declarations } public { Public declarations } procedure CallGet(MethodName: string); procedure CallPost(MethodName: string); procedure CallDelete(MethodName: string; const ID: String); function Login(const UserName, Password: String): Boolean; procedure Logout; published {#HeaderList#} end; var AutoTablesClientDM: TAutoTablesClientDM; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} // https://stackoverflow.com/questions/4186458/delphi-call-a-function-whose-name-is-stored-in-a-string procedure TAutoTablesClientDM.CallGet(MethodName: string); var M: System.TMethod; begin M.Code := Self.MethodAddress(MethodName); //find method code M.Data := Pointer(Self); //store pointer to object instance TGetFuncType(m)(); end; procedure TAutoTablesClientDM.CallPost(MethodName: string); var M: System.TMethod; begin M.Code := Self.MethodAddress(MethodName); //find method code M.Data := Pointer(Self); //store pointer to object instance TPostFuncType(m)(); end; procedure TAutoTablesClientDM.CallDelete(MethodName: string; const ID: String); var M: System.TMethod; begin M.Code := Self.MethodAddress(MethodName); //find method code M.Data := Pointer(Self); //store pointer to object instance TDeleteFuncType(m)(ID); end; function TAutoTablesClientDM.Login(const UserName, Password: String): Boolean; begin if not BackendAuth1.LoggedIn then begin BackendAuth1.UserName := UserName; BackendAuth1.Password := Password; BackendAuth1.Login; if BackendAuth1.LoggedIn then begin if BackendAuth1.LoggedInToken = '' then begin BackendAuth1.Authentication := TBackendAuthentication.Default; Result := False; end else begin BackendAuth1.Authentication := TBackendAuthentication.Session; Result := True; end; end; end else Result := True; end; procedure TAutoTablesClientDM.Logout; begin BackendAuth1.Logout; BackendAuth1.Authentication := TBackendAuthentication.Default; end; {#FunctionList#} end.
//============================================================================= // sgArduino.pas //============================================================================= /// SwinGame's Arduino unit is capable of connecting and communicating /// with an Arduino device using a Serial port. /// /// @module Arduino /// @static /// /// @doc_types ArduinoDevice unit sgArduino; interface uses sgTypes; /// Creates an Arduino device at the specified port, with /// the indicated baud. The name of the device matches its port. /// /// @lib /// @sn createArduinoOnPort:%s atBaud:%s /// /// @class ArduinoDevice /// @constructor /// @csn initOnPort:%s atBaud:%s function CreateArduinoDevice(const port: String; baud: LongInt) : ArduinoDevice; /// Creates an Arduino device with the given name, /// at the specified port, with the indicated baud. /// /// @lib CreateArduinoNamed /// @sn createArduinoNamed:%s onPort:%s atBaud:%s /// /// @class ArduinoDevice /// @constructor /// @csn initWithName:%s OnPort:%s atBaud:%s function CreateArduinoDevice(const name, port: String; baud: LongInt) : ArduinoDevice; /// Returns the ArduinoDevice with the indicated name. /// /// @lib function ArduinoDeviceNamed(const name: String): ArduinoDevice; /// Does an ArduinoDevice exist with the indicated name? /// /// @lib function HasArduinoDevice(const name: String): Boolean; /// Release the ArduinoDevice with the indicated name. /// /// @lib procedure ReleaseArduinoDevice(const name: String); /// Close the connection to the Arduino Device and dispose /// of the resources associated with the Device. /// /// @lib /// @sn ArduinoCloseConnection:%s /// /// @class ArduinoDevice /// @dispose procedure FreeArduinoDevice(var dev: ArduinoDevice); /// Reads a line of text from the ArduinoDevice. This /// returns an empty string if nothing is read within a /// few milliseconds. /// /// @lib /// /// @class ArduinoDevice /// @method ReadLine function ArduinoReadLine(dev: ArduinoDevice): String; /// Reads a line of text from the ArduinoDevice, within a /// specified amount of time. /// /// @lib ArduinoReadLineTimeout /// @sn arduinoReadLine:%s timeout:%s /// /// @class ArduinoDevice /// @overload ReadLine ReadLineTimeout /// @csn readLineWithTimeout:%s function ArduinoReadLine(dev: ArduinoDevice; timeout: LongInt): String; /// Read a Byte from the ArduinoDevice. Has a short /// timeout and returns 0 if no byte is read within the given time. /// /// @lib /// /// @class ArduinoDevice /// @method ReadByte function ArduinoReadByte(dev: ArduinoDevice): Byte; overload; /// Reads a byte from the ArduinoDevice, with the given timeout in milliseconds. /// Returns 0 if no byte is read within the given time. /// /// @lib ArduinoReadByteTimeout /// @sn arduinoReadByte:%s timeout:%s /// /// @class ArduinoDevice /// @overload ReadByte ReadByteTimeout /// @csn readByteWithTimeout:%s function ArduinoReadByte(dev: ArduinoDevice; timeout: LongInt): Byte; overload; /// Send a byte value to the arduino device. /// /// @lib /// @sn arduinoSendByte:%s value:%s /// /// @class ArduinoDevice /// @method SendByte procedure ArduinoSendByte(dev: ArduinoDevice; value: Byte); overload; /// Send a string value to the arduino device. /// /// @lib /// @sn arduinoSendString:%s value:%s /// /// @class ArduinoDevice /// @method SendString procedure ArduinoSendString(dev: ArduinoDevice; const value: String); /// Send a string value to the arduino device, along with a newline /// so the arduino can identify the end of the sent data. /// /// @lib /// @sn arduinoSendStringLine:%s value:%s /// /// @class ArduinoDevice /// @method SendStringLine procedure ArduinoSendStringLine(dev: ArduinoDevice; const value: String); /// Returns true if there is data waiting to be read from the device. /// /// @lib /// /// @class ArduinoDevice /// @getter HasData function ArduinoHasData(dev: ArduinoDevice): Boolean; /// Release all of the ArduinoDevices /// /// @lib procedure ReleaseAllArduinoDevices(); implementation uses SysUtils, Classes, Synaser, sgShared, sgUtils, stringhash, sgBackendTypes; var _ArduinoDevices: TStringHash; function CreateArduinoDevice(const port: String; baud: LongInt) : ArduinoDevice; begin result := CreateArduinoDevice(port, port, baud); end; function CreateArduinoDevice(const name, port: String; baud: LongInt) : ArduinoDevice; var obj: tResourceContainer; ser: TBlockSerial; ap: ArduinoPtr; begin if HasArduinoDevice(name) then begin result := ArduinoDeviceNamed(name); exit; end; New(ap); result := ap; ap^.id := ARDUINO_PTR; ap^.name := name; ap^.ptr := Pointer(TBlockSerial.Create()); ap^.port := port; ap^.baud := baud; ap^.open := false; ap^.hasError := false; ap^.errorMessage := 'Working'; obj := tResourceContainer.Create(ap); if not _ArduinoDevices.setValue(name, obj) then begin RaiseWarning('** Leaking: Caused by ArduinoDevice resource loading twice, ' + name); result := nil; exit; end; if assigned(ap) then begin ser := TBlockSerial(ap^.ptr); // WriteLn('Connecting...'); ser.Connect(port); // WriteLn('Configure...'); ser.Config(baud, 8, 'N', SB1, False, False); if ser.LastError <> sOK then begin RaiseWarning('Error configuring connection to Arduino: ' + IntToStr(ser.LastError) + ' ' + ser.LastErrorDesc); ap^.hasError := true; ap^.errorMessage := ser.LastErrorDesc; exit; end; end; end; function _Serial(dev: ArduinoDevice): TBlockSerial; var ap: ArduinoPtr; begin ap := ToArduinoPtr(dev); if Assigned(ap) then result := TBlockSerial(ap^.ptr) else result := nil; end; function ArduinoHasData(dev: ArduinoDevice): Boolean; var ser: TBlockSerial; begin result := false; if assigned(dev) then begin ser := _Serial(dev); // result := ser.CanRead(0); result := ser.WaitingData() > 0; end; end; function ArduinoReadLine(dev: ArduinoDevice): String; begin result := ArduinoReadLine(dev, 10); end; function ArduinoReadLine(dev: ArduinoDevice; timeout: LongInt): String; var ser: TBlockSerial; begin result := ''; if assigned(dev) then begin ser := _Serial(dev); result := ser.RecvString(timeout) end; end; function ArduinoReadByte(dev: ArduinoDevice): Byte; overload; begin result := ArduinoReadByte(dev, 10); end; function ArduinoReadByte(dev: ArduinoDevice; timeout: LongInt): Byte; overload; var ser: TBlockSerial; begin result := 0; if assigned(dev) then begin ser := _Serial(dev); result := ser.RecvByte(timeout); end; end; procedure ArduinoSendByte(dev: ArduinoDevice; value: Byte); overload; var ser: TBlockSerial; begin if assigned(dev) then begin ser := _Serial(dev); ser.SendByte(value); end; end; procedure ArduinoSendStringLine(dev: ArduinoDevice; const value: String); var ser: TBlockSerial; begin if assigned(dev) then begin ser := _Serial(dev); ser.SendString(value); ser.SendString(#13#10); end; end; procedure ArduinoSendString(dev: ArduinoDevice; const value: String); var ser: TBlockSerial; begin if assigned(dev) then begin ser := _Serial(dev); ser.SendString(value); end; end; // ======================== // = Resource Management Routines // ======================== // private: // Called to actually free the resource procedure DoFreeArduinoDevice(var dev: ArduinoPtr); var ser: TBlockSerial; begin if assigned(dev) then begin CallFreeNotifier(dev); ser := _Serial(dev); ser.Free(); dev^.ptr := nil; Dispose(dev); end; dev := nil; end; procedure FreeArduinoDevice(var dev: ArduinoDevice); var ap: ArduinoPtr; begin ap := ToArduinoPtr(dev); if assigned(ap) then begin ReleaseArduinoDevice(ap^.name); end; dev := nil; end; procedure ReleaseArduinoDevice(const name: String); var dev: ArduinoDevice; ap: ArduinoPtr; begin dev := ArduinoDeviceNamed(name); if assigned(dev) then begin _ArduinoDevices.remove(name).Free(); DoFreeArduinoDevice(ap); end; end; procedure ReleaseAllArduinoDevices(); begin ReleaseAll(_ArduinoDevices, @ReleaseArduinoDevice); end; function HasArduinoDevice(const name: String): Boolean; begin result := _ArduinoDevices.containsKey(name); end; function ArduinoDeviceNamed(const name: String): ArduinoDevice; var tmp : TObject; begin tmp := _ArduinoDevices.values[name]; if assigned(tmp) then result := ArduinoDevice(tResourceContainer(tmp).Resource) else result := nil; end; initialization begin InitialiseSwinGame(); _ArduinoDevices := TStringHash.Create(False, 1024); end; finalization begin ReleaseAllArduinoDevices(); FreeAndNil(_ArduinoDevices); end; end.
unit uSubCustomerInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentSub, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DB, ADODB, cxLookAndFeelPainters, cxButtons, Menus, uFrmSearchCustomer, uSystemTypes; type TSubCustomerInfo = class(TParentSub) pnlPessoa: TPanel; lbCPhone: TLabel; lbCEmail: TLabel; lbCEmployID: TLabel; EditCustomer: TEdit; edtAddress: TEdit; edtComplement: TEdit; edtPhone: TEdit; edtEmpID: TEdit; edtEmail: TEdit; quCustomer: TADOQuery; quCustomerPessoaFirstName: TStringField; quCustomerPessoaLastName: TStringField; quCustomerEndereco: TStringField; quCustomerCidade: TStringField; quCustomerBairro: TStringField; quCustomerCEP: TStringField; quCustomerTelefone: TStringField; quCustomerCellular: TStringField; quCustomerEmail: TStringField; quCustomerNascimento: TDateTimeField; quCustomerCPF: TStringField; quCustomerCartTrabalho: TStringField; quCustomerInscEstadual: TStringField; quCustomerInscMunicipal: TStringField; quCustomerNomeJuridico: TStringField; quCustomerCodPais: TStringField; quCustomerPais: TStringField; quCustomerIDEstado: TStringField; quCustomerEstado: TStringField; quCustomerJuridico: TBooleanField; quCustomerPessoa: TStringField; quCustomerPhoneAreaCode: TStringField; quCustomerCellAreaCode: TStringField; pnlCustomerResumed: TPanel; memCustomer: TMemo; quCustomerIDPessoa: TIntegerField; btDetCliente: TcxButton; popupDetails: TPopupMenu; btnChangeCustomer: TMenuItem; quCustomerIDUser: TIntegerField; quCustomerComissionID: TIntegerField; quCustomerHasAddress: TIntegerField; procedure btDetClienteClick(Sender: TObject); procedure btnChangeCustomerClick(Sender: TObject); private FAllowCommand : TSetCommandType; fInfoType : Integer; fSelectCustomer : Boolean; fIDCustomer: Integer; FNumOfAddress : Integer; fFirstName, fLastName, fAddress, fTel, fCel, fEmail, fZip: String; procedure ClearFields; protected procedure AfterSetParam; override; procedure SetCustomer; public procedure DataSetRefresh; procedure DataSetOpen; override; procedure DataSetClose; override; function GiveInfo(InfoString: String): String; override; function getIdCustomer(): Integer; end; implementation {$R *.dfm} uses uDM, uParamFunctions, uFchPessoa, uPassword, uMsgBox, uMsgConstant, uSystemConst; { TSubCustomerInfo } procedure TSubCustomerInfo.AfterSetParam; var fColor: String; begin inherited; fIDCustomer := -1; fInfoType := -1; if fParam = '' then Exit; fIDCustomer := StrToIntDef(ParseParam(FParam, 'IDCustomer'), -1); fColor := ParseParam(FParam, 'BackColor'); fSelectCustomer := (ParseParam(FParam, 'SelectCustomer') = 'Y'); if (ParseParam(FParam, 'DisplayType') = 'R') then fInfoType := 0 else if (ParseParam(FParam, 'DisplayType') = 'T') then fInfoType := 1; pnlCustomerResumed.Visible := (fInfoType <> -1); pnlPessoa.Visible := not pnlCustomerResumed.Visible; btnChangeCustomer.Visible := ParseParam(FParam, 'ChangeCustomer') = '1'; if fColor <> '' then begin Self.Color := StringToColor(fColor); memCustomer.Color := Color; pnlPessoa.Color := Color; end; DataSetRefresh; end; procedure TSubCustomerInfo.DataSetClose; begin inherited; with quCustomer do if Active then Close; end; procedure TSubCustomerInfo.DataSetOpen; begin inherited; if fIDCustomer = -1 then Exit; with quCustomer do if not Active then begin Parameters.ParamByName('IDPessoa').Value := fIDCustomer; Open; end; end; procedure TSubCustomerInfo.DataSetRefresh; begin DataSetClose; DataSetOpen; SetCustomer; end; procedure TSubCustomerInfo.btDetClienteClick(Sender: TObject); var ID1, ID2: String; begin inherited; if fIDCustomer in [0,1] then begin btnChangeCustomerClick(Self); Exit; end; with TFchPessoa.Create(Self) do begin ID1 := IntToStr(fIDCustomer); ID2 := ''; try FAllowCommand := Password.GetAllowCommand(2, 6, DM.fUser.Password); if (TBtnCommandType(btAlt) in FAllowCommand) then begin if Start(btAlt, Nil, False, ID1, ID2, nil) then begin DataSetRefresh; NotifyChanges('CHANGED=TRUE;'); end; end else MsgBox(MSG_INF_CANNOT_ACCESS_MODULE, vbOKOnly + vbInformation); finally Free; end; end; end; function TSubCustomerInfo.GiveInfo(InfoString: String): String; begin Result := Format('ZIP=%S;IDCUSTOMER=%D;FIRSTNAME=%S;LASTNAME=%S;ADDRESS=%S;NUMOFADDRESS=%D', [fZip, fIDCustomer, fFirstName, fLastName, fAddress, fNumOfAddress]); end; procedure TSubCustomerInfo.ClearFields; begin EditCustomer.Text := ''; fFirstName := ''; fLastName := ''; edtAddress.Text := ''; edtComplement.Text := ''; edtPhone.Text := ''; edtEmpID.Text := ''; edtEmail.Text := ''; fTel := ''; fCel := ''; memCustomer.Clear; end; procedure TSubCustomerInfo.btnChangeCustomerClick(Sender: TObject); begin inherited; // amfsouza 02.07.2012 // if Password.HasFuncRight(72) then // begin with TFrmSearchCustomer.Create(Self) do try fIDCustomer := Start; finally Free; end; DataSetRefresh; NotifyChanges('CHANGED=TRUE;'); // end; end; procedure TSubCustomerInfo.SetCustomer; begin if not quCustomer.IsEmpty then begin ClearFields; if not quCustomerJuridico.AsBoolean then EditCustomer.Text := Trim(quCustomerPessoaFirstName.AsString) + ' ' + Trim(quCustomerPessoaLastName.AsString) else EditCustomer.Text := Trim(quCustomerPessoa.AsString); fIDCustomer := quCustomerIDPessoa.AsInteger; fFirstName := quCustomerPessoaFirstName.AsString; fLastName := quCustomerPessoaLastName.AsString; fAddress := quCustomerEndereco.AsString; fZip := quCustomerCEP.AsString; FNumOfAddress := quCustomerHasAddress.AsInteger; if quCustomerTelefone.AsString <> '' then fTel := '('+quCustomerPhoneAreaCode.AsString+') '+ Trim(quCustomerTelefone.AsString); if quCustomerCellular.AsString <> '' then fCel := '('+quCustomerCellAreaCode.AsString+') '+ Trim(quCustomerCellular.AsString); fEmail := Trim(quCustomerEmail.AsString); edtAddress.Text := fAddress; edtComplement.Text := ''; if quCustomerBairro.AsString <> '' then edtComplement.Text := quCustomerBairro.AsString; if (quCustomerCidade.AsString <> '') then if(edtComplement.Text = '') then edtComplement.Text := quCustomerCidade.AsString else edtComplement.Text := edtComplement.Text + ' - ' +quCustomerCidade.AsString; if (quCustomerIDEstado.AsString <> '') then if (edtComplement.Text = '') then edtComplement.Text := quCustomerIDEstado.AsString else edtComplement.Text := edtComplement.Text + ' - ' +quCustomerIDEstado.AsString; if (quCustomerCEP.AsString <> '') then if (edtComplement.Text = '') then edtComplement.Text := quCustomerCEP.AsString else edtComplement.Text := edtComplement.Text + ', ' +quCustomerCEP.AsString; edtPhone.Text := fTel; edtEmail.Text := fEmail; if quCustomerJuridico.AsBoolean then edtEmpID.Text := quCustomerInscEstadual.AsString else edtEmpID.Text := quCustomerCPF.AsString; if pnlCustomerResumed.Visible then begin memCustomer.Clear; if fInfoType = 0 then begin memCustomer.Lines.Add(EditCustomer.Text); memCustomer.Lines.Add(fAddress); memCustomer.Lines.Add(edtComplement.Text); if fEmail <> '' then memCustomer.Lines.Add(fEmail); end else begin memCustomer.Lines.Add(EditCustomer.Text); if fCel <> '' then memCustomer.Lines.Add(fTel + ' / ' + fCel) else memCustomer.Lines.Add(fTel); if fEmail <> '' then memCustomer.Lines.Add(fEmail); memCustomer.Lines.Add(fAddress); memCustomer.Lines.Add(edtComplement.Text); end; memCustomer.SelStart := 0; memCustomer.SelLength := 0; end; if DM.fSystem.SrvParam[PARAM_SALE_REPEAT_CUSTOMER_SALESPERSON] then begin DM.fUser.IDUserCliente := quCustomerIDUser.AsInteger; DM.fUser.IDCommissionCliente := quCustomerComissionID.AsInteger; end; end; if (Trim(EditCustomer.Text) = '') and fSelectCustomer then btnChangeCustomerClick(Self); end; function TSubCustomerInfo.getIdCustomer: Integer; begin result := fIDCustomer; end; initialization RegisterClass(TSubCustomerInfo); end.
unit AdjustQtyReasonView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Grids, ExtCtrls, contnrs; type TvwAdjustReason = class(TForm) pnTop: TPanel; pnBottom: TPanel; stgReason: TStringGrid; bbtnAdd: TBitBtn; procedure stgReasonDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure stgReasonSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure bbtnAddClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } reasons: TObjectList; procedure LoadHeader(); procedure LoadReasons(); procedure RefreshInfo(); procedure CallReasonUpsert(argIsDelete: Boolean; argId: Integer); public { Public declarations } function Start(): Boolean; end; var vwAdjustReason: TvwAdjustReason; implementation uses uDM, AdjustReasonCls, AdjustQtyReasonUpsertView; {$R *.dfm} { TvwAdjustReason } procedure TvwAdjustReason.LoadHeader; var i: Integer; begin stgReason.FixedRows := 1; stgReason.Cells[1, 0] := 'Reason'; stgReason.ColWidths[1] := 200; stgReason.Cells[2, 0] := 'Hidden'; stgReason.Cells[3, 0] := 'System'; stgReason.Cells[4, 0] := 'Activated'; stgReason.Cells[5, 0] := ' '; stgReason.Cells[6, 0] := ' '; end; procedure TvwAdjustReason.LoadReasons(); var i: Integer; begin reasons := dm.ReadAllReason(); stgReason.RowCount := 1; for i:= 0 to reasons.Count - 1 do begin stgReason.RowCount := stgReason.RowCount + 1; stgReason.Cells[0, i+1] := IntToStr(TAdjustReason(reasons.Items[i]).Id); stgReason.Cells[1, i+1] := TAdjustReason(reasons.Items[i]).Reason; stgReason.Cells[2, i+1] := InttoStr(TAdjustReason(reasons.Items[i]).Hidden); stgReason.Cells[3, i+1] := IntToStr(TAdjustReason(reasons.Items[i]).System); stgReason.Cells[4, i+1] := IntToStr(TAdjustReason(reasons.Items[i]).Activated); stgReason.Cells[5, i+1] := 'Update'; stgReason.Cells[6, i+1] := 'Delete'; end; pnBottom.Caption := format('records: %d',[(reasons.Count)]); end; function TvwAdjustReason.Start: Boolean; begin LoadHeader(); LoadReasons(); result := ShowModal = mrOK; end; procedure TvwAdjustReason.stgReasonDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var canvas: TCanvas; begin canvas := stgReason.Canvas; if ( ARow = 0 ) then begin canvas.Brush.Color := clBtnFace; canvas.Font.Color := clBlack; canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, stgReason.Cells[Acol, Arow]); end; if ( (ARow > 0) and (ACol > 0) ) then begin if ( Acol = 5 ) then begin canvas.Font.Color := clGreen; canvas.Font.Style := [fsBold]; canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, stgReason.Cells[Acol, Arow]); end; if ( Acol = 6 ) then begin canvas.Font.Color := clRed; canvas.Font.Style := [fsBold]; canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, stgReason.Cells[Acol, Arow]); end; end; end; procedure TvwAdjustReason.stgReasonSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var view: TvwAdjustQtyReasonUpsert; begin if ( ARow > 0 ) then begin if ( ACol = 5 ) then begin CallReasonUpsert(FALSE, StrToInt(stgReason.Cells[0, ARow])); RefreshInfo(); end else if ( ACol = 6 ) then begin dm.DeleteReason(StrToInt(stgReason.Cells[0, Arow])); RefreshInfo(); end; end; end; procedure TvwAdjustReason.bbtnAddClick(Sender: TObject); begin CallReasonUpsert(False, 0); RefreshInfo(); end; procedure TvwAdjustReason.RefreshInfo; begin FreeAndNil(reasons); LoadReasons(); end; procedure TvwAdjustReason.FormClose(Sender: TObject; var Action: TCloseAction); begin if ( reasons <> nil ) then begin FreeAndNil(reasons); end; end; procedure TvwAdjustReason.CallReasonUpsert(argIsDelete: Boolean; argId: Integer); var view: TvwAdjustQtyReasonUpsert; begin try if ( not argIsDelete ) then begin view := TvwAdjustQtyReasonUpsert.Create(nil); view.Start(argId); end; finally FreeAndNil(view); end; end; end.
unit bufferedwrites; {$mode objfpc}{$H+} interface uses Classes, SysUtils, threads, globaltypes; type TBufferedWriter = class private FBufferSize : integer; FBufferP : PChar; FBufferPosP : PChar; FMutex : TMutexHandle; FBatchSize : integer; FBytesUsed : integer; FLogFile : file of byte; FOpen : Boolean; FRootFolder : string; public constructor Create(BufferSize : integer; BatchSize : integer; CreateSuspended: Boolean; ARootFolder : string); destructor Destroy; override; procedure AddRow(arow : string); procedure StartNewFile(afilename : string); procedure CloseLogFile; end; implementation uses logoutput; constructor TBufferedWriter.Create(BufferSize : integer; BatchSize : integer; CreateSuspended : Boolean; ARootFolder : string); begin FBufferSize := BufferSize; FBufferP := GetMem(FBufferSize); FBatchSize := BatchSize; FRootFolder := aRootFolder; // start off with an empty buffer. FBytesUsed := 0; FBufferPosP := FBufferP; FMutex := MutexCreate; FOpen := False; end; destructor TBufferedWriter.Destroy; begin try FreeMem(FBufferP); MutexDestroy(FMutex); if (FOpen) then CloseFile(FLogFile); except log('exception 5'); // threadhalt(0); end; inherited Destroy; end; procedure TBufferedWriter.AddRow(arow : string); var l : integer; begin // we grab mutex here as we don't want the thread execute to alter the // bytes used while we are looking at it. MutexLock(FMutex); try l := Length(ARow); if ((l + FBytesUsed) < FBufferSize) then begin move(arow[1], FBufferPosP^, l); FBufferPosP := FBufferPosP + l; FBytesUsed := FBytesUsed + l; // note we don't release the lock until we have finished checking shared // resources and ths if statement is part of that. if (FBytesUsed > FBatchSize) then begin // release the semphore to signal a write is required. if (FOpen) then BlockWrite(FLogFile, FBufferP^, FBytesUsed); FBytesUsed := 0; FBufferPosP := FBufferP; end; end else begin // here there isn't enough room so we need to write the buffer now. if (FOpen) then BlockWrite(FLogFile, FBufferP^, FBytesUsed); FBytesUsed := 0; FBufferPosP := FBufferP; // now we should be able to write our data to the buffer. move(arow[1], FBufferPosP, l); FBufferPosP := FBufferPosP + l; FBytesUsed := FBytesUsed + l; end; finally MutexUnlock(FMutex); end; end; procedure TBufferedWriter.StartNewFile(afilename : string); begin MutexLock(FMutex); try if (FOpen) then CloseFile(FLogFile); Assignfile (FLogFile, FRootFolder + afilename); Rewrite(FLogFile); FOpen := True; finally MutexUnlock(FMutex); end; end; procedure TBufferedWriter.CloseLogFile; begin MutexLock(FMutex); try if (FOpen) then begin CloseFile(FLogFile); FOpen := False; //reset buffer. FBytesUsed := 0; FBufferPosP := FBufferP; end; finally MutexUnLock(FMutex); end; end; end.
/// <summary> /// Unit generated using the Delphi Wmi class generator tool, Copyright Rodrigo Ruz V. 2010-2012 /// Application version 1.0.4674.62299 /// WMI version 7601.17514 /// Creation Date 17-10-2012 18:18:32 /// Namespace root\CIMV2 Class Win32_OperatingSystem /// MSDN info about this class http://msdn2.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/Win32_OperatingSystem.asp /// </summary> unit uWin32_OperatingSystem; interface uses Classes, Activex, Variants, ComObj, uWmiDelphiClass; type {$REGION 'Documentation'} /// <summary> /// The Win32_OperatingSystem class represents an operating system installed on a Win32 computer system. Any operating system that can be installed on a Win32 system is a descendent (or member) of this class. /// Example: Microsoft Windows 95. /// </summary> {$ENDREGION} TWin32_OperatingSystem=class(TWmiClass) private FCaption : String; FOSArchitecture : String; FVersion : String; public constructor Create(LoadWmiData : boolean=True); overload; destructor Destroy;Override; {$REGION 'Documentation'} /// <summary> /// The Caption property is a short textual description (one-line string) of the /// object. /// </summary> {$ENDREGION} property Caption : String read FCaption; {$REGION 'Documentation'} /// <summary> /// The OSArchitecture property indicates the Architecture of the operating /// system.Example: 32-bit, 64-bit Intel, 64-bit AMD /// </summary> {$ENDREGION} property OSArchitecture : String read FOSArchitecture; {$REGION 'Documentation'} /// <summary> /// The Version property indicates the version number of the operating system. /// Example: 4.0 /// </summary> {$ENDREGION} property Version : String read FVersion; procedure SetCollectionIndex(Index : Integer); override; end; implementation {TWin32_OperatingSystem} constructor TWin32_OperatingSystem.Create(LoadWmiData : boolean=True); begin inherited Create(LoadWmiData,'root\CIMV2','Win32_OperatingSystem'); end; destructor TWin32_OperatingSystem.Destroy; begin inherited; end; procedure TWin32_OperatingSystem.SetCollectionIndex(Index : Integer); begin if (Index>=0) and (Index<=FWmiCollection.Count-1) and (FWmiCollectionIndex<>Index) then begin FWmiCollectionIndex:=Index; FCaption := VarStrNull(inherited Value['Caption']); FOSArchitecture := VarStrNull(inherited Value['OSArchitecture']); FVersion := VarStrNull(inherited Value['Version']); end; end; end.
unit ibSHPSQLDebuggerActions; interface uses SysUtils, Classes, Menus, SHDesignIntf, ibSHDesignIntf, ibSHConsts; type TibSHPSQLDebuggerPaletteAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHPSQLDebuggerFormAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHPSQLDebuggerToolbarAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHSendToPSQLDebuggerToolbarAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHPSQLDebuggerEditorAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; //Toolbar Actions TibSHPSQLDebuggerToolbarAction_TraceInto = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_StepOver = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_ToggleBreakpoint = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_Reset = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_SetParameters = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_Run = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_Pause = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_SkipStatement = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_RunToCursor = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_AddWatch = class(TibSHPSQLDebuggerToolbarAction) end; TibSHPSQLDebuggerToolbarAction_ModifyVarValues = class(TibSHPSQLDebuggerToolbarAction) end; //Editor Actions implementation uses ibSHPSQLDebuggerFrm, ActnList; { TibSHPSQLDebuggerPaletteAction } constructor TibSHPSQLDebuggerPaletteAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallPalette; Category := Format('%s', ['Tools']); Caption := Format('%s', ['PSQL Debugger']); // ShortCut := TextToShortCut(''); end; function TibSHPSQLDebuggerPaletteAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID); end; procedure TibSHPSQLDebuggerPaletteAction.EventExecute(Sender: TObject); begin Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHPSQLDebugger, EmptyStr); end; procedure TibSHPSQLDebuggerPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHPSQLDebuggerPaletteAction.EventUpdate(Sender: TObject); begin Enabled := Assigned(Designer.CurrentDatabase) and (Designer.CurrentDatabase as ISHRegistration).Connected and SupportComponent(Designer.CurrentDatabase.BranchIID); end; { TibSHPSQLDebuggerFormAction } constructor TibSHPSQLDebuggerFormAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallForm; Caption := SCallTracing; SHRegisterComponentForm(IibSHPSQLDebugger, Caption, TibSHPSQLDebuggerForm); end; function TibSHPSQLDebuggerFormAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHPSQLDebugger, AClassIID); end; procedure TibSHPSQLDebuggerFormAction.EventExecute(Sender: TObject); begin Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert); end; procedure TibSHPSQLDebuggerFormAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHPSQLDebuggerFormAction.EventUpdate(Sender: TObject); begin FDefault := Assigned(Designer.CurrentComponentForm) and AnsiSameText(Designer.CurrentComponentForm.CallString, Caption); end; { TibSHPSQLDebuggerToolbarAction } constructor TibSHPSQLDebuggerToolbarAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; Caption := '-'; if Self is TibSHPSQLDebuggerToolbarAction_TraceInto then Tag := 1; if Self is TibSHPSQLDebuggerToolbarAction_StepOver then Tag := 2; if Self is TibSHPSQLDebuggerToolbarAction_ToggleBreakpoint then Tag := 3; if Self is TibSHPSQLDebuggerToolbarAction_Reset then Tag := 4; if Self is TibSHPSQLDebuggerToolbarAction_SetParameters then Tag := 5; if Self is TibSHPSQLDebuggerToolbarAction_Run then begin Tag := 6; end; if Self is TibSHPSQLDebuggerToolbarAction_Pause then begin Tag := 7; end; if Self is TibSHPSQLDebuggerToolbarAction_SkipStatement then Tag := 8; if Self is TibSHPSQLDebuggerToolbarAction_RunToCursor then Tag := 9; if Self is TibSHPSQLDebuggerToolbarAction_AddWatch then Tag := 10; if Self is TibSHPSQLDebuggerToolbarAction_ModifyVarValues then Tag := 11; case Tag of 1: begin Caption := Format('%s', ['Trace Into']); ShortCut := TextToShortCut('F7'); end; 2: begin Caption := Format('%s', ['Step Over']); ShortCut := TextToShortCut('F8'); end; 3: begin Caption := Format('%s', ['Toggle Breakpoint']); ShortCut := TextToShortCut('F5'); end; 4: begin Caption := Format('%s', ['Reset Tracing']); ShortCut := TextToShortCut('Ctrl+F2'); end; 5: begin Caption := Format('%s', ['Set Input Parameters']); ShortCut := TextToShortCut('Ctrl+F4'); end; 6: begin Caption := Format('%s', ['Run from Current Position']); ShortCut := TextToShortCut('Ctrl+Enter'); SecondaryShortCuts.Add('F9'); end; 7: begin Caption := Format('%s', ['Stop']); ShortCut := TextToShortCut('Ctrl+Bksp'); end; 8: begin Caption := Format('%s', ['Skip Statement']); ShortCut := TextToShortCut('Shift+F8'); end; 9: begin Caption := Format('%s', ['Run To Cursor']); ShortCut := TextToShortCut('F4'); end; 10: begin Caption := Format('%s', ['Add Watch at Cursor']); ShortCut := TextToShortCut('Ctrl+F5'); end; 11: begin Caption := Format('%s', ['Evaluate/Modify']); ShortCut := TextToShortCut('Ctrl+F7'); end; end; if Tag <> 0 then Hint := Caption; end; function TibSHPSQLDebuggerToolbarAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHPSQLDebugger, AClassIID); end; procedure TibSHPSQLDebuggerToolbarAction.EventExecute(Sender: TObject); begin with (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm) do case Tag of // Trace Into 1: TraceInto; // Step Over 2: StepOver; // Toggle Breakpoint 3: ToggleBreakpoint; // Reset Tracing 4: Reset; // Set Input Parameters 5: SetParameters; // Run from Current Position 6: (Designer.CurrentComponentForm as ISHRunCommands).Run; // Pause 7: (Designer.CurrentComponentForm as ISHRunCommands).Pause; // Skip Statement 8: SkipStatement; // Run To Cursor 9: RunToCursor; // Add Watch at Cursor 10:AddWatch; 11:ModifyVarValues end; end; procedure TibSHPSQLDebuggerToolbarAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHPSQLDebuggerToolbarAction.EventUpdate(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) and AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTracing) then begin case Tag of // Separator 0: ; // Trace Into 1: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanTraceInto; Visible := Enabled; end; // Step Over 2: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanStepOver; Visible := True end; // Toggle Breakpoint 3: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanToggleBreakpoint; Visible := True end; // Reset Tracing 4: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanReset; Visible := True end; // Set Input Parameters 5: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanSetParameters; Visible := True end; // Run from Current Position 6: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun; Visible := True; end; // Pause 7: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause; Visible := True; end; // Skip Statement 8: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanSkipStatement; Visible := Enabled; end; // Run To Cursor 9: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanRunToCursor; Visible := True end; // Add Watch at Cursor 10: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).CanAddWatch; Visible := True end; 11: begin Enabled := (Designer.CurrentComponentForm as IibSHPSQLDebuggerForm).GetCanModifyVarValues; Visible := True end; end; end else begin Enabled := False; Visible := Enabled; //DisableShortCut end; end; { TibSHSendToPSQLDebuggerToolbarAction } constructor TibSHSendToPSQLDebuggerToolbarAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; Caption := '-'; Caption := Format('%s', ['Debug Object']); ShortCut := TextToShortCut('F7'); Hint := Caption; end; function TibSHSendToPSQLDebuggerToolbarAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHProcedure, AClassIID) or IsEqualGUID(IibSHTrigger, AClassIID){ or IsEqualGUID(IibSHSQLEditor, AClassIID)}; end; procedure TibSHSendToPSQLDebuggerToolbarAction.EventExecute( Sender: TObject); var vCurrentComponent: TSHComponent; vPSQLDebugger: IibSHPSQLDebugger; begin vCurrentComponent := Designer.CurrentComponent; if Assigned(vCurrentComponent) then begin if Supports(Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHPSQLDebugger, EmptyStr), IibSHPSQLDebugger, vPSQLDebugger) then vPSQLDebugger.Debug(nil, vCurrentComponent.ClassIID, vCurrentComponent.Caption); end; end; procedure TibSHSendToPSQLDebuggerToolbarAction.EventHint( var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHSendToPSQLDebuggerToolbarAction.EventUpdate(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) and (AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSourceDDL) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallAlterDDL)) then begin Enabled := True; Visible := Enabled; end else begin Enabled := False; Visible := Enabled; //DisableShortCut end; end; { TibSHPSQLDebuggerEditorAction } constructor TibSHPSQLDebuggerEditorAction.Create(AOwner: TComponent); begin inherited; end; function TibSHPSQLDebuggerEditorAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHProcedure, AClassIID) or IsEqualGUID(IibSHTrigger, AClassIID){ or IsEqualGUID(IibSHSQLEditor, AClassIID)}; end; procedure TibSHPSQLDebuggerEditorAction.EventExecute(Sender: TObject); begin inherited; end; procedure TibSHPSQLDebuggerEditorAction.EventHint(var HintStr: String; var CanShow: Boolean); begin inherited; end; procedure TibSHPSQLDebuggerEditorAction.EventUpdate(Sender: TObject); begin inherited; end; end.
unit uContinente; interface uses System.Generics.Collections, uPais, uEnumContinente, System.SysUtils, uExceptions; type TContinente = class private FNomeContinente : tContinentes; FoListaDePaises : TList<TPais>; function GetNome: tContinentes; procedure SetNome(const Value: tContinentes); function GetListaDePaises: TList<TPais>; procedure SetListaDePaises(const Value: TList<TPais>); public property Nome : tContinentes read GetNome write SetNome; property ListaDePaises : TList<TPais> read GetListaDePaises write SetListaDePaises; procedure Adicionar(AoPais: TPais); function ToString : String; override; function MaiorArea : Extended; function NomeContinente : String; function AreaTotal : Extended; function MaiorPopulacao : Integer; function MenorArea : Extended; function MenorPopulacao : Integer; function PopulacaoTotal : Integer; function Densidade : Extended; function MaiorMenor : Extended; constructor Create; destructor Destroy; override; end; implementation { TContinente } procedure TContinente.Adicionar(AoPais: TPais); begin FoListaDePaises.Add(AoPais); end; function TContinente.AreaTotal: Extended; var oPais: TPais; begin Result := 0; for oPais in FoListaDePaises do Result:= Result + oPais.Dimensao; end; constructor TContinente.Create; begin FoListaDePaises := TList<TPais>.Create; end; function TContinente.Densidade: Extended; begin Result:= PopulacaoTotal / AreaTotal; end; destructor TContinente.Destroy; begin if Assigned(FoListaDePaises) then FoListaDePaises.Free; end; function TContinente.GetListaDePaises: TList<TPais>; begin Result := FoListaDePaises; end; function TContinente.GetNome: tContinentes; begin Result := FNomeContinente; end; function TContinente.MaiorArea: Extended; var oPais: TPais; begin Result := 0; for oPais in FoListaDePaises do if oPais.Dimensao>Result then Result:= oPais.Dimensao; end; function TContinente.MaiorMenor: Extended; begin Result:= MaiorArea / MenorArea; end; function TContinente.MaiorPopulacao: Integer; var oPais: TPais; begin Result:= 0; for oPais in FoListaDePaises do if oPais.Populacao>Result then Result:= oPais.Populacao; end; function TContinente.MenorArea: Extended; var oPais: TPais; begin Result := 9999999999; for oPais in FoListaDePaises do if oPais.Dimensao<Result then Result:= oPais.Dimensao; end; function TContinente.MenorPopulacao: Integer; var oPais: TPais; begin Result := 999999999; for oPais in FoListaDePaises do if oPais.Populacao<Result then Result:= oPais.Populacao; end; function TContinente.NomeContinente: String; begin case FNomeContinente of tcAmerica : Result := 'América'; tcEuropa : Result := 'Europa'; tcAsia : Result := 'Ásia'; tcAfrica : Result := 'África'; tcOceania : Result := 'Oceania'; tcAntartida : Result := 'Antártida'; end; end; function TContinente.PopulacaoTotal: Integer; var oPais: TPais; begin Result := 0; for oPais in FoListaDePaises do Result:= Result + oPais.Populacao; end; procedure TContinente.SetListaDePaises(const Value: TList<TPais>); begin FoListaDePaises := Value; end; procedure TContinente.SetNome(const Value: tContinentes); begin if Value = tcVazio then raise EContinenteObrigatorio.Create; FNomeContinente := Value; end; function TContinente.ToString: String; var oPais : TPais; begin Result := 'Continente: ' + NomeContinente + sLineBreak + 'Países: ' + sLineBreak; for oPais in FoListaDePaises do begin Result:= Result + oPais.ToString; end; end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, LuaWrapper, StdCtrls; type { TfrmMain } TfrmMain = class(TForm) btn: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { private declarations } public { public declarations } Lua : TLua; end; var frmMain: TfrmMain; implementation uses lua, plua, LuaButton, pLuaObject; function lua_ShowMessage(l : PLua_State) : integer; cdecl; var n, i : Integer; msg : AnsiString; begin result := 0; n := lua_gettop(l); if n > 0 then begin msg := ''; for i := 1 to n do msg := msg + plua_tostring(L, i); ShowMessage(msg); end; end; { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); begin Lua := TLua.Create(self); Lua.RegisterLuaMethod('ShowMessage', @lua_ShowMessage); RegisterLuaButton(Lua.LuaState); end; procedure TfrmMain.FormShow(Sender: TObject); begin RegisterExistingButton(Lua.LuaState, 'btn', btn); if FileExists('script.lua') then begin Lua.LoadFile('script.lua'); Lua.Execute; end; end; initialization {$I MainForm.lrs} end.
unit HandlebarsScanner; {$mode objfpc}{$H+} interface uses Classes; type THandlebarsToken = ( tkEOF, tkContent, tkOpenPartial, tkOpenPartialBlock, tkOpenBlock, tkOpenEndBlock, tkEndBlock, tkOpenRawBlock, tkCloseRawBlock, tkEndRawBlock, tkOpenBlockParams, tkCloseBlockParams, tkOpenSExpr, tkCloseSExpr, tkInverse, tkOpenInverse, tkOpenInverseChain, tkOpenUnescaped, tkCloseUnescaped, tkOpen, tkClose, tkComment, tkEquals, tkId, tkSep, tkData, tkUndefined, tkNull, tkBoolean, tkNumber, tkString, tkInvalid ); THandlebarsTokens = set of THandlebarsToken; //inspired by fpc jsonscanner { THandlebarsScanner } THandlebarsScanner = class private FSource : TStringList; FCurToken: THandlebarsToken; FCurTokenString: string; FCurLine: string; TokenStr: PChar; FCurRow: Integer; FMustacheLevel: Integer; function FetchLine: Boolean; function GetCurColumn: Integer; procedure ScanComment; procedure ScanContent(TokenOffset: Integer = 0); protected procedure Error(const Msg: string);overload; procedure Error(const Msg: string; const Args: array of Const);overload; public constructor Create(Source : TStream); overload; constructor Create(const Source : String); overload; destructor Destroy; override; function FetchToken: THandlebarsToken; property CurLine: string read FCurLine; property CurRow: Integer read FCurRow; property CurColumn: Integer read GetCurColumn; property CurToken: THandlebarsToken read FCurToken; property CurTokenString: string read FCurTokenString; end; const LiteralTokens = [tkUndefined..tkString]; implementation uses strings; { THandlebarsScanner } function THandlebarsScanner.FetchLine: Boolean; begin Result := FCurRow < FSource.Count; if Result then begin FCurLine := FSource[FCurRow]; TokenStr := PChar(FCurLine); Inc(FCurRow); end else begin FCurLine := ''; TokenStr := nil; end; end; function THandlebarsScanner.GetCurColumn: Integer; begin Result := TokenStr - PChar(CurLine); end; procedure THandlebarsScanner.ScanComment; var TokenStart: PChar; SectionLength, StrOffset: Integer; IsDoubleDash, EndOfComment: Boolean; begin //todo: handlebars.js returns the token content with the mustaches and later removes them at parsing. //seems a limitation of tokenizer. We don't have this issue and the code could be cleaned a bit TokenStart := TokenStr; IsDoubleDash := (TokenStr[3] = '-') and (TokenStr[4] = '-'); StrOffset := 0; while True do begin Inc(TokenStr); if TokenStr[0] = #0 then begin SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, StrOffset + SectionLength + Length(LineEnding)); Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); Move(LineEnding[1], FCurTokenString[StrOffset + SectionLength + 1], Length(LineEnding)); if not FetchLine then begin //todo: mark as invalid Break; end; TokenStart := TokenStr; Inc(StrOffset, SectionLength + Length(LineEnding)); end; if IsDoubleDash then EndOfComment := (TokenStr[0] = '-') and (TokenStr[1] = '-') and (TokenStr[2] = '}') and (TokenStr[3] = '}') else EndOfComment := (TokenStr[0] = '}') and (TokenStr[1] = '}'); if EndOfComment then begin if IsDoubleDash then Inc(TokenStr, 4) else Inc(TokenStr, 2); SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, StrOffset + SectionLength); Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); Break; end; end; end; procedure THandlebarsScanner.ScanContent(TokenOffset: Integer); var TokenStart: PChar; SectionLength, StrOffset: Integer; begin TokenStart := TokenStr; StrOffset := 0; Inc(TokenStr, TokenOffset); while True do begin if TokenStr[0] = #0 then begin SectionLength := TokenStr - TokenStart; if FetchLine then begin SetLength(FCurTokenString, StrOffset + SectionLength + Length(LineEnding)); Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); Move(LineEnding[1], FCurTokenString[StrOffset + SectionLength + 1], Length(LineEnding)); end else begin SetLength(FCurTokenString, StrOffset + SectionLength); Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); Break; end; TokenStart := TokenStr; Inc(StrOffset, SectionLength + Length(LineEnding)); continue; end; if ((TokenStr[0] = '{') and (TokenStr[1] = '{')) or (((TokenStr[0] = '\') and not (TokenStr[-1] = '\')) and (TokenStr[1] = '{') and (TokenStr[2] = '{')) then begin SectionLength := TokenStr - TokenStart; //escaped escape if (TokenStr[0] = '{') and (TokenStr[-1] = '\') then Dec(SectionLength); SetLength(FCurTokenString, StrOffset + SectionLength); Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); Break; end; Inc(TokenStr); end; end; procedure THandlebarsScanner.Error(const Msg: string); begin end; procedure THandlebarsScanner.Error(const Msg: string; const Args: array of const); begin end; constructor THandlebarsScanner.Create(Source: TStream); begin FSource := TStringList.Create; FSource.LoadFromStream(Source); end; constructor THandlebarsScanner.Create(const Source: String); var L: Integer; begin FSource := TStringList.Create; FSource.Text := Source; //TStringList eats a lineending at string tail //add a workaround until develop a proper solution L := Length(Source); if (L >= Length(LineEnding)) and (CompareByte(Source[L - Length(LineEnding) + 1], LineEnding[1], Length(LineEnding)) = 0) then FSource.Add(''); end; destructor THandlebarsScanner.Destroy; begin FSource.Destroy; inherited Destroy; end; function GetNextToken(Start: PChar): PChar; begin Result := Start; while Result[0] = ' ' do Inc(Result); end; function GetNextChar(Start: PChar; out Next: PChar; const C: Char): Boolean; begin Next := Start; while Next[0] = ' ' do Inc(Next); Result := Next[0] = C; end; function GetNextStr(Start: PChar; out Next: PChar; const Str: PChar; Size: SizeInt): Boolean; begin Next := Start; while Next[0] = ' ' do Inc(Next); Result := strlcomp(Next, Str, Size) = 0; end; function THandlebarsScanner.FetchToken: THandlebarsToken; var TokenStart, NextToken: PChar; SectionLength, StrOffset: Integer; C, Escaped: Char; begin FCurTokenString := ''; if (TokenStr = nil) and not FetchLine then begin Result := tkEOF; FCurToken := tkEOF; Exit; end; Result := tkInvalid; case TokenStr[0] of '{': begin //{{ TokenStart := TokenStr; if TokenStr[1] = '{' then begin Result := tkOpen; Inc(TokenStr, 2); case TokenStr[0] of '>': Result := tkOpenPartial; '#': begin Result := tkOpenBlock; case TokenStr[1] of '>': begin Result := tkOpenPartialBlock; Inc(TokenStr); end; '*': Inc(TokenStr); // directive end; end; '/': Result := tkOpenEndBlock; '&', '*': Inc(TokenStr); '{': Result := tkOpenUnescaped; '^': begin NextToken := GetNextToken(TokenStr + 1); if (NextToken[0] = '}') and (NextToken[1] = '}') then begin Result := tkInverse; TokenStr := NextToken + 2; end else Result := tkOpenInverse; end; '!': begin Result := tkComment; Dec(TokenStr, 2); ScanComment; end; else if GetNextStr(TokenStr, NextToken, 'else', 4) then begin NextToken := GetNextToken(NextToken + 4); if (NextToken[0] = '}') and (NextToken[1] = '}') then begin Result := tkInverse; TokenStr := NextToken + 2; end else begin Result := tkOpenInverseChain; TokenStr := NextToken; end; end; end; if not (Result in [tkInverse, tkComment]) then begin if not (Result in [tkOpen, tkOpenInverseChain]) then Inc(TokenStr); Inc(FMustacheLevel); end; if Result <> tkComment then begin SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, SectionLength); Move(TokenStart^, FCurTokenString[1], SectionLength); end; end else begin Result := tkContent; ScanContent; end; end; '}': begin TokenStart := TokenStr; if (TokenStr[1] = '}') and (FMustacheLevel > 0) then begin if TokenStr[2] = '}' then begin Result := tkCloseUnescaped; Inc(TokenStr, 3); end else begin Result := tkClose; Inc(TokenStr, 2); end; SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, SectionLength); Move(TokenStart^, FCurTokenString[1], SectionLength); Dec(FMustacheLevel); end else begin Result := tkContent; ScanContent; end; end; else if FMustacheLevel = 0 then begin Result := tkContent; if (TokenStr[0] = #0) then begin if FCurRow >= FSource.Count then Result := tkEOF else ScanContent; end else if strlcomp(TokenStr, '\{{', 3) = 0 then begin Inc(TokenStr); ScanContent(2); end else ScanContent; end else begin while TokenStr[0] = ' ' do Inc(TokenStr); StrOffset := 0; TokenStart := TokenStr; case TokenStr[0] of '/': begin Result := tkSep; Inc(TokenStr); end; '.': begin Result := tkSep; if TokenStr[1] = '.' then begin Result := tkId; Inc(TokenStr); end else if FCurToken <> tkId then Result := tkId; Inc(TokenStr); end; '"', '''': begin Result := tkString; C := TokenStr[0]; Inc(TokenStr); TokenStart := TokenStr; while not (TokenStr[0] in [#0, C]) do begin if (TokenStr[0] = '\') then begin // Save length SectionLength := TokenStr - TokenStart; Inc(TokenStr); // Read escaped token case TokenStr[0] of '"' : Escaped:='"'; '''': Escaped:=''''; 't' : Escaped:=#9; 'b' : Escaped:=#8; 'n' : Escaped:=#10; 'r' : Escaped:=#13; 'f' : Escaped:=#12; '\' : Escaped:='\'; '/' : Escaped:='/'; #0 : Error('SErrOpenString'); else Error('SErrInvalidCharacter', [CurRow,CurColumn,TokenStr[0]]); end; SetLength(FCurTokenString, StrOffset + SectionLength + 2); if SectionLength > 0 then Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); FCurTokenString[StrOffset + SectionLength + 1] := Escaped; Inc(StrOffset, SectionLength + 1); // Next char // Inc(TokenStr); TokenStart := TokenStr + 1; end; if TokenStr[0] = #0 then Error('SErrOpenString'); Inc(TokenStr); end; if TokenStr[0] = #0 then Error('SErrOpenString'); end; '0'..'9','-': begin Result := tkNumber; TokenStart := TokenStr; while True do begin Inc(TokenStr); case TokenStr[0] of '.': begin if TokenStr[1] in ['0'..'9', 'e', 'E'] then begin Inc(TokenStr); repeat Inc(TokenStr); until not (TokenStr[0] in ['0'..'9', 'e', 'E','-','+']); end; break; end; '0'..'9': ; 'e', 'E': begin Inc(TokenStr); if TokenStr[0] in ['-','+'] then Inc(TokenStr); while TokenStr[0] in ['0'..'9'] do Inc(TokenStr); break; end; else break; end; end; SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, SectionLength); if SectionLength > 0 then Move(TokenStart^, FCurTokenString[1], SectionLength); end; '=': begin Result := tkEquals; Inc(TokenStr); end; '@': begin Result := tkData; Inc(TokenStr); end; '(': begin Result := tkOpenSExpr; Inc(TokenStr); end; ')': begin Result := tkCloseSExpr; Inc(TokenStr); end; '|': begin Result := tkCloseBlockParams; Inc(TokenStr); end; '&': begin //todo: see what are the other invalid chars //Result := tkInvalid; Inc(TokenStr); end; else if (strlcomp(TokenStr, 'true', 4) = 0) or (strlcomp(TokenStr, 'false', 5) = 0) then Result := tkBoolean else if strlcomp(TokenStr, 'null', 4) = 0 then Result := tkNull else if strlcomp(TokenStr, 'undefined', 9) = 0 then Result := tkUndefined else if (strlcomp(TokenStr, 'as', 2) = 0) and GetNextChar(TokenStr + 2, NextToken, '|') then begin Result := tkOpenBlockParams; TokenStr := NextToken; end else Result := tkId; while True do begin if ((TokenStr[0] = '}') and (TokenStr[1] = '}')) or (TokenStr[0] in [' ', '.', '/']) or (TokenStr[0] = '=') or (TokenStr[0] = ')') or (TokenStr[0] = '|') or (TokenStr[0] = #0) then break; Inc(TokenStr); end; end; if TokenStr <> nil then begin SectionLength := TokenStr - TokenStart; SetLength(FCurTokenString, SectionLength + StrOffset); if SectionLength > 0 then Move(TokenStart^, FCurTokenString[StrOffset + 1], SectionLength); if Result in [tkString, tkOpenBlockParams] then Inc(TokenStr); //rigth trim space and line break while TokenStr[0] = ' ' do Inc(TokenStr); while TokenStr[0] = #0 do begin if not FetchLine then Break; end; end; end; end; FCurToken := Result; end; end.
//////////////////////////////////////////////////////////////////////////////// // // **************************************************************************** // * Project : Fangorn Wizards Lab Extension Library v2.00 // * Unit Name : Unit1 // * Purpose : Тестовый пример использования FWCobweb // * Author : Александр (Rouse_) Багель // * Copyright : © Fangorn Wizards Lab 1998 - 2008. // * Version : 1.00 // * Home Page : http://rouse.drkb.ru // **************************************************************************** // unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, StdCtrls, ComCtrls, FWCobWeb, FWHelpers; type TSimplePoint = class(TAbstractCobwebKnot) strict private FPosition: TPoint; FMouseOnItem: Boolean; FSelected: Boolean; private function GetPoint(const Index: Integer): Integer; procedure SetPoint(const Index, Value: Integer); protected procedure StoreToStream(Stream: TStream); override; procedure ExtractFromStream(Stream: TStream); override; public procedure Assign(const Value: TAbstractCobwebKnot); override; property X: Integer index 0 read GetPoint write SetPoint; property Y: Integer index 1 read GetPoint write SetPoint; property MouseOnItem: Boolean read FMouseOnItem write FMouseOnItem; property Selected: Boolean read FSelected write FSelected; end; TSpider = class(TAbstractCobweb) protected function GetKnotClass: TAbstractCobwebKnotClass; override; public function AddKnot(const ID: Integer): TSimplePoint; reintroduce; function GetKnot(const Index: Integer): TSimplePoint; reintroduce; end; TfrmCobwebDemo = class(TForm) PopupMenu1: TPopupMenu; Addpoint1: TMenuItem; MakeRoute1: TMenuItem; lvPoints: TListView; gbPoints: TGroupBox; Panel1: TPanel; gbRoutes: TGroupBox; lvRoutes: TListView; MainMenu1: TMainMenu; File1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; N1: TMenuItem; Close1: TMenuItem; Edit1: TMenuItem; Addpoint2: TMenuItem; MakeRoute2: TMenuItem; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; N2: TMenuItem; Clear1: TMenuItem; N3: TMenuItem; Clear2: TMenuItem; PopupMenu2: TPopupMenu; Delete1: TMenuItem; Saveasdefault1: TMenuItem; StatusBar1: TStatusBar; procedure Addpoint1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PopupMenu1Popup(Sender: TObject); procedure MakeRoute1Click(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Save1Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Close1Click(Sender: TObject); procedure Clear1Click(Sender: TObject); procedure Delete1Click(Sender: TObject); procedure Saveasdefault1Click(Sender: TObject); private Spider: TSpider; isMakeRoute: Boolean; SelectedPoint: TSimplePoint; procedure UpdateListViews; end; var frmCobwebDemo: TfrmCobwebDemo; implementation {$R *.dfm} { TSimplePoint } procedure TSimplePoint.Assign(const Value: TAbstractCobwebKnot); begin inherited; if Value is TSimplePoint then begin X := TSimplePoint(Value).X; Y := TSimplePoint(Value).Y; end; end; procedure TSimplePoint.ExtractFromStream(Stream: TStream); begin inherited; X := Stream.ReadInt32; Y := Stream.ReadInt32; end; function TSimplePoint.GetPoint(const Index: Integer): Integer; begin case Index of 0: Result := FPosition.X; 1: Result := FPosition.Y; else Result := 0; end; end; procedure TSimplePoint.SetPoint(const Index, Value: Integer); begin case Index of 0: FPosition.X := Value; 1: FPosition.Y := Value; end; end; procedure TSimplePoint.StoreToStream(Stream: TStream); begin inherited; Stream.WriteInt32(X); Stream.WriteInt32(Y); end; { TSpider } function TSpider.AddKnot(const ID: Integer): TSimplePoint; begin Result := TSimplePoint(inherited AddKnot(ID)); end; function TSpider.GetKnot(const Index: Integer): TSimplePoint; begin Result := TSimplePoint(inherited GetKnot(Index)); end; function TSpider.GetKnotClass: TAbstractCobwebKnotClass; begin Result := TSimplePoint; end; { Form38 } procedure TfrmCobwebDemo.Addpoint1Click(Sender: TObject); var P: TPoint; begin GetCursorPos(P); P := ScreenToClient(P); with Spider.AddKnot(Spider.KnotsCount) do begin X := P.X; Y := P.Y; end; Invalidate; UpdateListViews; end; procedure TfrmCobwebDemo.Clear1Click(Sender: TObject); begin Spider.Clear; UpdateListViews; Invalidate; end; procedure TfrmCobwebDemo.Close1Click(Sender: TObject); begin Close; end; procedure TfrmCobwebDemo.Delete1Click(Sender: TObject); begin if TListView(PopupMenu2.PopupComponent).Selected <> nil then begin TObject(TListView(PopupMenu2.PopupComponent).Selected.Data).Free; UpdateListViews; Invalidate; end; end; procedure TfrmCobwebDemo.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; Spider := TSpider.Create; DoubleBuffered := True; isMakeRoute := False; if FileExists(ExtractFilePath(ParamStr(0)) + 'default.cbw') then Spider.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'default.cbw'); UpdateListViews; end; procedure TfrmCobwebDemo.FormDestroy(Sender: TObject); begin Spider.Free; end; procedure TfrmCobwebDemo.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; Knot: TSimplePoint; HRegion: THandle; Primary, Slave: TSimplePoint; begin if not isMakeRoute then begin for I := 0 to Spider.KnotsCount - 1 do begin Knot := Spider.GetKnot(I); HRegion := CreateEllipticRgn( Knot.X - 9, Knot.Y - 9, Knot.X + 9, Knot.Y + 9); try if PtInRegion(HRegion, X, Y) then begin SelectedPoint := Knot; Break; end; finally DeleteObject(HRegion); end; end; Exit; end; Primary := nil; for I := 0 to Spider.KnotsCount - 1 do begin Knot := Spider.GetKnot(I); HRegion := CreateEllipticRgn( Knot.X - 9, Knot.Y - 9, Knot.X + 9, Knot.Y + 9); try if PtInRegion(HRegion, X, Y) then Knot.Selected := not Knot.Selected; finally DeleteObject(HRegion); end; if Knot.Selected then begin if Primary = nil then Primary := Knot else begin Slave := Knot; Primary.Selected := False; Slave.Selected := False; Spider.AddRoute(Primary, Slave); UpdateListViews; isMakeRoute := False; end; end; end; Invalidate; end; procedure TfrmCobwebDemo.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var I: Integer; Knot: TSimplePoint; HRegion: THandle; NeedInvalidate, MouseOnItem: Boolean; begin if SelectedPoint <> nil then begin SelectedPoint.X := X; SelectedPoint.Y := Y; Invalidate; Exit; end; NeedInvalidate := False; for I := 0 to Spider.KnotsCount - 1 do begin Knot := Spider.GetKnot(I); HRegion := CreateEllipticRgn( Knot.X - 9, Knot.Y - 9, Knot.X + 9, Knot.Y + 9); try MouseOnItem := PtInRegion(HRegion, X, Y); if not NeedInvalidate then NeedInvalidate := MouseOnItem xor Knot.MouseOnItem; Knot.MouseOnItem := MouseOnItem; finally DeleteObject(HRegion); end; end; if NeedInvalidate then Invalidate; end; procedure TfrmCobwebDemo.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SelectedPoint := nil; UpdateListViews; end; procedure TfrmCobwebDemo.FormPaint(Sender: TObject); procedure DrawPoint(const Highligt, Selected: Boolean; const X, Y: Integer); begin if Highligt then Canvas.Pen.Color := clRed else Canvas.Pen.Color := clBlue; if isMakeRoute then if Selected then Canvas.Pen.Color := clGreen; Canvas.Pen.Width := 4; Canvas.Ellipse(X - 6, Y - 6, X + 6, Y + 6); end; procedure DrawRoute(Route: TAbstractCobwebRoute); var Primary, Slave: TSimplePoint; begin Primary := TSimplePoint(Route.PrimaryKnot); Slave := TSimplePoint(Route.SlaveKnot); Canvas.Pen.Color := clOlive; Canvas.Pen.Width := 4; Canvas.MoveTo(Primary.X, Primary.Y); Canvas.LineTo(Slave.X, Slave.Y); end; var I: Integer; Knot: TSimplePoint; begin for I := 0 to Spider.KnotsCount - 1 do begin Knot := Spider.GetKnot(I); DrawPoint(Knot.MouseOnItem, Knot.Selected, Knot.X, Knot.Y); end; for I := 0 to Spider.RoutesCount - 1 do DrawRoute(Spider.GetRoute(I)); end; procedure TfrmCobwebDemo.MakeRoute1Click(Sender: TObject); begin isMakeRoute := True; end; procedure TfrmCobwebDemo.Open1Click(Sender: TObject); begin if OpenDialog1.Execute then begin Spider.LoadFromFile(OpenDialog1.FileName); Invalidate; end; end; procedure TfrmCobwebDemo.PopupMenu1Popup(Sender: TObject); begin MakeRoute1.Enabled := (Spider.KnotsCount > 1) and not isMakeRoute; Addpoint1.Enabled := not isMakeRoute; end; procedure TfrmCobwebDemo.Save1Click(Sender: TObject); begin if SaveDialog1.Execute then Spider.SaveToFile(SaveDialog1.FileName); end; procedure TfrmCobwebDemo.Saveasdefault1Click(Sender: TObject); begin Spider.SaveToFile(ExtractFilePath(ParamStr(0)) + 'default.cbw'); end; procedure TfrmCobwebDemo.UpdateListViews; var I: Integer; Knot: TSimplePoint; Route: TAbstractCobwebRoute; begin lvPoints.Items.BeginUpdate; try lvPoints.Items.Clear; for I := 0 to Spider.KnotsCount - 1 do with lvPoints.Items.Add do begin Knot := Spider.GetKnot(I); Caption := IntToStr(Knot.ID); SubItems.Add(IntToStr(Knot.X)); SubItems.Add(IntToStr(Knot.Y)); SubItems.Add(IntToStr(Knot.RouteCount)); Data := Knot; end; finally lvPoints.Items.EndUpdate; end; lvRoutes.Items.BeginUpdate; try lvRoutes.Items.Clear; for I := 0 to Spider.RoutesCount - 1 do with lvRoutes.Items.Add do begin Route := Spider.GetRoute(I); Caption := IntToStr(Route.PrimaryKnot.ID); SubItems.Add(IntToStr(Route.SlaveKnot.ID)); Data := Route; end; finally lvRoutes.Items.EndUpdate; end; StatusBar1.Panels.Items[0].Text := 'Total points count: ' + IntToStr(Spider.KnotsCount); StatusBar1.Panels.Items[1].Text := 'Total routes count: ' + IntToStr(Spider.RoutesCount); end; end.
unit CrudExampleHorseServer.Model.Conexao.DB; interface uses Data.DB , TBGConnection.View.Principal , System.Classes , TBGFiredacDriver.View.Driver , FireDAC.UI.Intf , FireDAC.VCLUI.Wait , FireDAC.Stan.Intf , FireDAC.Stan.Option , FireDAC.Stan.Error , FireDAC.Phys.Intf , FireDAC.Stan.Def , FireDAC.Stan.Pool , FireDAC.Stan.Async , FireDAC.Phys , FireDAC.Stan.Param , FireDAC.DatS , FireDAC.DApt.Intf , FireDAC.DApt , FireDAC.Phys.FBDef , FireDAC.Phys.IBBase , FireDAC.Phys.FB , FireDAC.Comp.DataSet , FireDAC.Comp.Client , FireDAC.Comp.UI , CrudExampleHorseServer.Controller.Constants , TBGQuery.View.Principal , SimpleInterface ; type IModelQuery = interface ['{5485B3BC-E154-4689-82C6-0412B5A5DABE}'] function DataSet : TDataSet; function SetSQL( aSQL: string ): IModelQuery; overload; function SetSQL( aSQL: string; const aArgs: array of const ): IModelQuery; overload; function SetParameter(const aParamName: string; const aTypeParam: TFieldType): IModelQuery; overload; function SetParameter(const aParamName: string; const aTypeParam: TFieldType; const aValueParam: string): IModelQuery; overload; function SetDataSource( DataSource: TDataSource ): IModelQuery; function Open: IModelQuery; overload; function Open( aSQL: string ): IModelQuery; overload; function Open( aSQL: string; const Args: array of const ): IModelQuery; overload; function OpenDataSetCheckIsEmpty: boolean; function ExecSQL(aSQLText: string): IModelQuery; overload; function ExecSQL(aSQLText: string; const aArgs: array of const): IModelQuery; overload; function BooleanSQL(aSQLText: string): boolean; overload; function BooleanSQL(aSQLText: string; const aArgs: array of const): boolean; overload; function IntegerSQL(aSQLText: string): integer; overload; function IntegerSQL(aSQLText: string; const aArgs: array of const): integer; overload; function NumberSQL(aSQLText: string): double; overload; function NumberSQL(aSQLText: string; const Args: array of const): double; overload; function StringSQL(aSQLText: string): string; overload; function StringSQL(aSQLText: string; const Args: array of const): string; overload; end; IModelConexaoDB = interface ['{ACCB041A-9A2E-4E57-B36C-2B2AA063B487}'] function Connection : TTBGConnection; function Query: IModelQuery; function FDConnection: TFDConnection; function GetNextID(const aField: string): integer; end; IMySimpleQuery = interface ['{C533B898-F63E-4B16-AD0A-D79312D5AF48}'] function SimpleQueryFireDac: ISimpleQuery; end; TModelConexaoDB = class(TInterfacedObject, IModelConexaoDB) private FConexaoDB : TTBGConnection; FFDConnection: TFDConnection; FBGFiredacDriverConexao: TBGFiredacDriverConexao; public constructor CreateNew( aParamConnectionDB: TParamConnectionDB ); destructor Destroy; override; class function New( aParamConnectionDB: TParamConnectionDB ) : IModelConexaoDB; function Connection : TTBGConnection; function Query: IModelQuery; function FDConnection: TFDConnection; function GetNextID(const aField: string): integer; //function Owner: TComponent; end; TModelConexaoDBQuery = class(TInterfacedObject,IModelQuery) private FQuery : TTBGQuery; //FInternalDataSource: TDataSource; public constructor CreateNew( aConnection : IModelConexaoDB ); destructor Destroy; override; class function New( aConnection : IModelConexaoDB ): IModelQuery; overload; function DataSet : TDataSet; function SetSQL( aSQL: string ): IModelQuery; overload; function SetSQL( aSQL: string; const aArgs: array of const ): IModelQuery; overload; function SetParameter(const aParamName: string; const aTypeParam: TFieldType): IModelQuery; overload; function SetParameter(const aParamName: string; const aTypeParam: TFieldType; const aValueParam: string): IModelQuery; overload; function SetDataSource( aDataSource: TDataSource ): IModelQuery; function Open: IModelQuery; overload; function Open( aSQL: string ): IModelQuery; overload; function Open( aSQL: string; const aArgs: array of const ): IModelQuery; overload; function OpenDataSetCheckIsEmpty: boolean; function ExecSQL(aSQLText: string): IModelQuery; overload; function ExecSQL(aSQLText: string; const aArgs: array of const): IModelQuery; overload; function BooleanSQL(aSQLText: string): boolean; overload; function BooleanSQL(aSQLText: string; const aArgs: array of const): boolean; overload; function IntegerSQL(aSQLText: string): integer; overload; function IntegerSQL(aSQLText: string; const aArgs: array of const): integer; overload; function NumberSQL(aSQLText: string): double; overload; function NumberSQL(aSQLText: string; const aArgs: array of const): double; overload; function StringSQL(aSQLText: string): string; overload; function StringSQL(aSQLText: string; const aArgs: array of const): string; overload; end; TMySimpleQuery = class(TInterfacedObject, IMySimpleQuery) private FConexaoDB: IModelConexaoDB; { private declarations } public { public declarations } class function New( aConexaoDB: IModelConexaoDB ) : IMySimpleQuery; constructor Create( aConexaoDB: IModelConexaoDB ); destructor Destroy; override; function SimpleQueryFireDac: ISimpleQuery; end; implementation uses System.SysUtils, System.TypInfo, SimpleQueryFiredac; { TModelConexaoDB } function TModelConexaoDB.Connection: TTBGConnection; begin Result := FConexaoDB; end; constructor TModelConexaoDB.CreateNew( aParamConnectionDB: TParamConnectionDB ); begin FConexaoDB := TTBGConnection.Create; FBGFiredacDriverConexao := TBGFiredacDriverConexao.Create; FFDConnection := TFDConnection.Create(Nil); with FFDConnection do begin Params.Database := aParamConnectionDB.Database; Params.UserName := aParamConnectionDB.UserName; Params.Password := aParamConnectionDB.Password; Params.DriverID := aParamConnectionDB.DriverID; end; FBGFiredacDriverConexao.FConnection := FFDConnection; FConexaoDB.Driver := FBGFiredacDriverConexao; end; destructor TModelConexaoDB.Destroy; begin inherited; end; function TModelConexaoDB.FDConnection: TFDConnection; begin Result:=FFDConnection; end; function TModelConexaoDB.GetNextID(const aField: string): integer; begin if FDConnection.Params.DriverID='FB' then Result:=Query.IntegerSQL(Format('SELECT GEN_ID(GEN_%s,1) FROM RDB$DATABASE',[aField])) else raise Exception.Create(Format('Erro ao recuperar NextID: %s',[aField])); end; class function TModelConexaoDB.New( aParamConnectionDB: TParamConnectionDB ): IModelConexaoDB; begin Result := Self.CreateNew( aParamConnectionDB ); end; function TModelConexaoDB.Query: IModelQuery; begin Result:=TModelConexaoDBQuery.New( Self ) end; { TModelConexaoDBQuery } function TModelConexaoDBQuery.BooleanSQL(aSQLText: string): boolean; begin FQuery.Query.Open(aSQLText); Result:=Not (FQuery.Query.DataSet.IsEmpty); FQuery.Query.Close; end; function TModelConexaoDBQuery.BooleanSQL(aSQLText: string; const aArgs: array of const): boolean; begin Result:=BooleanSQL(Format(aSQLText, aArgs)); end; constructor TModelConexaoDBQuery.CreateNew(aConnection: IModelConexaoDB); begin FQuery :=TTBGQuery.Create; FQuery.Connection :=aConnection.Connection; FQuery.DataSource :=TDataSource.Create( Nil ); end; destructor TModelConexaoDBQuery.Destroy; begin FQuery.Query.Close; if Assigned( FQuery ) then FreeAndNil(FQuery); inherited; end; function TModelConexaoDBQuery.IntegerSQL(aSQLText: string): integer; begin FQuery.Query.Open(aSQLText); if ( not (FQuery.Query.DataSet.IsEmpty) ) and ( not FQuery.Query.DataSet.Fields[0].IsNull ) then Result:=FQuery.Query.DataSet.Fields[0].AsInteger else Result:=-999999999; FQuery.Query.Close; end; function TModelConexaoDBQuery.IntegerSQL(aSQLText: string; const aArgs: array of const): integer; begin Result:=IntegerSQL(Format(aSQLText,aArgs)); end; class function TModelConexaoDBQuery.New( aConnection: IModelConexaoDB): IModelQuery; begin Result := Self.CreateNew(aConnection); end; function TModelConexaoDBQuery.NumberSQL(aSQLText: string): double; begin FQuery.Query.Open(aSQLText); if ( not (FQuery.Query.DataSet.IsEmpty) ) and ( not FQuery.Query.DataSet.Fields[0].IsNull ) then Result:=FQuery.Query.DataSet.Fields[0].AsFloat else Result:=-999999999999999999; FQuery.Query.Close; end; function TModelConexaoDBQuery.NumberSQL(aSQLText: string; const aArgs: array of const): double; begin Result:=NumberSQL(Format(aSQLText,aArgs)); end; function TModelConexaoDBQuery.Open: IModelQuery; begin Result := Self; FQuery.Query.DataSet.Open; end; function TModelConexaoDBQuery.Open(aSQL: string): IModelQuery; begin Result := Self; FQuery.Query.Open(aSQL); end; function TModelConexaoDBQuery.Open(aSQL: string; const aArgs: array of const): IModelQuery; begin FQuery.Query.Open(Format(aSQL, aArgs)); Result := Self; end; function TModelConexaoDBQuery.OpenDataSetCheckIsEmpty: boolean; begin Open; Result := FQuery.Query.DataSet.IsEmpty; end; function TModelConexaoDBQuery.DataSet : TDataSet; begin Result := FQuery.Query.DataSet; end; function TModelConexaoDBQuery.SetDataSource( aDataSource: TDataSource): IModelQuery; begin Result := Self; aDataSource.DataSet:=FQuery.Query.DataSet; end; function TModelConexaoDBQuery.SetSQL(aSQL: String): IModelQuery; begin Result := Self; FQuery.Query.SQL.Text:=aSQL; end; function TModelConexaoDBQuery.SetSQL(aSQL: String; const aArgs: array of const): IModelQuery; begin Result := Self; SetSQL(Format(aSQL,aArgs)); end; function TModelConexaoDBQuery.StringSQL(aSQLText: string): string; begin FQuery.Query.Open(aSQLText); if ( not (FQuery.Query.DataSet.IsEmpty) ) and ( not FQuery.Query.DataSet.Fields[0].IsNull ) then Result:=FQuery.Query.DataSet.Fields[0].AsString; FQuery.Query.Close; end; function TModelConexaoDBQuery.StringSQL(aSQLText: string; const aArgs: array of const): string; begin Result:=StringSQL(Format(aSQLText,aArgs)); end; function TModelConexaoDBQuery.ExecSQL(aSQLText: string): IModelQuery; begin Result:=Self; FQuery.Query.ExecSQL(aSQLText); end; function TModelConexaoDBQuery.ExecSQL(aSQLText: String; const aArgs: array of const): IModelQuery; begin Result:=Self; ExecSQL(Format(aSQLText,aArgs)); end; function TModelConexaoDBQuery.SetParameter(const aParamName: string; const aTypeParam: TFieldType): IModelQuery; begin Result:=Self; if GetPropInfo(DataSet,'Params') = nil then raise Exception.CreateFmt('Erro Dataset %s não tem propriedade Params',[DataSet.Name]) else if TFDQuery(DataSet).Params.FindParam(aParamName) = nil then TFDQuery(DataSet).Params.CreateParam(aTypePAram,aParamName,ptInput); end; function TModelConexaoDBQuery.SetParameter(const aParamName: string; const aTypeParam: TFieldType; const aValueParam: string): IModelQuery; begin Result:=Self; SetParameter(aParamName,aTypeParam); TFDQuery(DataSet).ParamByName(aParamName).AsString:=aValueParam; end; { TMySimpleQuery } constructor TMySimpleQuery.Create( aConexaoDB: IModelConexaoDB ); begin FConexaoDB:=aConexaoDB; end; destructor TMySimpleQuery.Destroy; begin inherited; end; class function TMySimpleQuery.New( aConexaoDB: IModelConexaoDB ) : IMySimpleQuery; begin Result := Self.Create( aConexaoDB ); end; function TMySimpleQuery.SimpleQueryFireDac: ISimpleQuery; begin if FConexaoDB.FDConnection.Params.DriverID='FB' then Result:=TSimpleQueryFiredac.New( FConexaoDB.FDConnection ); end; end.
{ "name": "Five teams 2vs2 shared or FFA", "description":"Hemispheric map inspired by WPMarshall's pack, you can play with 5 teams shared or 5 players FFA", "version":"1.0", "creator":"TheRealF", "players":[10, 10], "planets": [ { "name": "Burning star", "mass": 35000, "position_x": 12600, "position_y": 400, "velocity_x": -6.3191938400268555, "velocity_y": 199.05433654785156, "required_thrust_to_move": 0, "starting_planet": true, "respawn": false, "start_destroyed": false, "min_spawn_delay": 0, "max_spawn_delay": 0, "planet": { "seed": 962992704, "radius": 800, "heightRange": 0, "waterHeight": 70, "waterDepth": 100, "temperature": 50, "metalDensity": 0, "metalClusters": 0, "metalSpotLimit": -1, "biomeScale": 50, "biome": "lava", "symmetryType": "none", "symmetricalMetal": false, "symmetricalStarts": false, "numArmies": 2, "landingZonesPerArmy": 0, "landingZoneSize": 50 } } ] }
namespace TicTacToe; interface uses UIKit, GameKit; type [IBObject] RootViewController = public class(UIViewController, IUIActionSheetDelegate, IGKTurnBasedMatchmakerViewControllerDelegate, IGKTurnBasedEventHandlerDelegate, IBoardDelegate) private method dictionaryFromData(aData: NSData): NSDictionary; method dataFromDictionary(aDictioanry: NSDictionary): NSData; method getMatchDataFromBoard: NSData; method nextLocalTurn(aCompletion: block ): Boolean; method nextParticipantForMatch(aMatch: GKTurnBasedMatch): GKTurnBasedParticipant; method remoteParticipantForMatch(aMatch: GKTurnBasedMatch): GKTurnBasedParticipant; method yourTurn; method remoteTurn; method computerTurn; method loadCurrentMatch(aResumePlay: Boolean := true); method setGameOverStatus(aMatch: GKTurnBasedMatch); method setParticipantsTurnStatus(aParticipant: GKTurnBasedParticipant); method updateGameCenterButton; method alertError(aMessage: NSString); [IBAction] method newGame(aSender: id); [IBAction] method newComputerGame(aSender: id); var fInitialLaunchComplete: Boolean; var fBoard: Board; var fCurrentMatch: GKTurnBasedMatch; const KEY_CURRENT_MATCH_ID = 'CurrentMatchID'; const KEY_COMPUTER_STARTS_NEXT = 'ComputerStartsNext'; public method init: id; override; method viewDidLoad; override; method didReceiveMemoryWarning; override; {$REGION IUIActionSheetDelegate} method actionSheet(aActionSheet: UIKit.UIActionSheet) clickedButtonAtIndex(aButtonIndex: Foundation.NSInteger); {$ENDREGION} {$REGION IGKTurnBasedMatchmakerViewControllerDelegate} method turnBasedMatchmakerViewControllerWasCancelled(aViewController: not nullable GKTurnBasedMatchmakerViewController); method turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) didFailWithError(aError: not nullable NSError); method turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) didFindMatch(aMatch: not nullable GKTurnBasedMatch); method turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) playerQuitForMatch(aMatch: not nullable GKTurnBasedMatch); {$ENDREGION} {$REGION IGKTurnBasedEventHandlerDelegate} method handleInviteFromGameCenter(playersToInvite: not nullable NSArray); method handleTurnEventForMatch(aMatch: not nullable GKTurnBasedMatch) didBecomeActive(didBecomeActive: RemObjects.Oxygene.System.Boolean); method handleTurnEventForMatch(aMatch: GKTurnBasedMatch); method handleMatchEnded(aMatch: GKTurnBasedMatch); {$ENDREGION} {$REGION IBoardDelegate} method board(aBoard: Board) playerWillSelectGridIndex(aGridIndex: GridIndex): Boolean; method board(aBoard: Board) playerDidSelectGridIndex(aGridIndex: GridIndex); {$ENDREGION} end; implementation method RootViewController.init: id; begin self := inherited initWithNibName('RootViewController') bundle(nil); if assigned(self) then begin //title := 'Tic Tac Toe'; end; result := self; end; method RootViewController.didReceiveMemoryWarning; begin inherited didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; method RootViewController.viewDidLoad; begin inherited viewDidLoad; GKLocalPlayer.localPlayer.authenticateHandler := method (aViewController: UIViewController; aError: NSError) begin if assigned(aViewController) then begin NSLog('authentication viewcontroller'); presentViewController(aViewController) animated(true) completion(nil); end else begin updateGameCenterButton(); end; end; GKTurnBasedEventHandler.sharedTurnBasedEventHandler.delegate := self; navigationController.navigationBar.topItem.leftBarButtonItem := new UIBarButtonItem withTitle('New Computer Match') style(UIBarButtonItemStyle.UIBarButtonItemStyleBordered) target(self) action(selector(newComputerGame:)); fBoard := new Board withFrame(view.frame); fBoard.delegate := self; view.addSubview(fBoard); end; method RootViewController.updateGameCenterButton; begin if GKLocalPlayer.localPlayer.isAuthenticated then begin NSLog('player is authenticated with Game Center'); if not assigned(navigationController.navigationBar.topItem.rightBarButtonItem) then navigationController.navigationBar.topItem.rightBarButtonItem := new UIBarButtonItem withTitle('...') style(UIBarButtonItemStyle.UIBarButtonItemStyleBordered) target(self) action(selector(newGame:)); GKTurnBasedMatch.loadMatchesWithCompletionHandler(method (aMatches: NSArray; aError: NSError) begin if assigned(aMatches) and (aMatches.count > 0) then begin navigationController.navigationBar.topItem.rightBarButtonItem.title := 'Matches'; var lLastMatchID := NSUserDefaults.standardUserDefaults.objectForKey(KEY_CURRENT_MATCH_ID); if assigned(lLastMatchID) and not assigned(fCurrentMatch) then begin for each m in aMatches do begin if m.matchID = lLastMatchID then begin fCurrentMatch := m; loadCurrentMatch(true); break; end; end; end; end else begin navigationController.navigationBar.topItem.rightBarButtonItem.title := 'Start'; end; if not assigned(fCurrentMatch) and not fInitialLaunchComplete then begin newComputerGame(nil); fInitialLaunchComplete := true; end; end); end else begin NSLog('player is NOT authenticated with Game Center'); if assigned(navigationController.navigationBar.topItem.rightBarButtonItem) then navigationController.navigationBar.topItem.rightBarButtonItem := nil; if not assigned(fCurrentMatch) and not fInitialLaunchComplete then begin newComputerGame(nil); fInitialLaunchComplete := true; end; end; end; {$REGION IUIActionSheetDelegate} method RootViewController.actionSheet(aActionSheet: UIKit.UIActionSheet) clickedButtonAtIndex(aButtonIndex: Foundation.NSInteger); begin if aButtonIndex = 0 then newComputerGame(nil); end; {$ENDREGION} method RootViewController.newComputerGame(aSender: id); begin if assigned(aSender) and // not called from UI? always start right away not assigned(fCurrentMatch) and // in a Game Center match? always start right away, since we can go back via Games button not fBoard.isEmpty and // no move made yet? no need to ask whether to cancel not fBoard.isGameOver then begin // Game over? also no sense in askling for confirmation var lAction := new UIActionSheet withTitle('Cancel current game?') &delegate(self) cancelButtonTitle('No, keep playing') destructiveButtonTitle('Yes, start new game') otherButtonTitles(nil); lAction.showFromBarButtonItem(navigationController.navigationBar.topItem.leftBarButtonItem) animated(true); exit; end; fBoard.clear(method begin fCurrentMatch := nil; var lComputerStartsNext := NSUserDefaults.standardUserDefaults.boolForKey(KEY_COMPUTER_STARTS_NEXT); if lComputerStartsNext then computerTurn() else yourTurn(); NSUserDefaults.standardUserDefaults.setBool(not lComputerStartsNext) forKey(KEY_COMPUTER_STARTS_NEXT); NSUserDefaults.standardUserDefaults.setObject(nil) forKey(KEY_CURRENT_MATCH_ID); end, true); end; method RootViewController.newGame(aSender: id); begin if not GKLocalPlayer.localPlayer.isAuthenticated then begin GKLocalPlayer.localPlayer.authenticateWithCompletionHandler(method (aError: NSError) begin NSLog('authenticateWithCompletionHandler completion - Error:%@', aError); if not assigned(aError) then newGame(nil); end); exit; end; var request := new GKMatchRequest; request.minPlayers := 2; request.maxPlayers := 2; var mmvc := new GKTurnBasedMatchmakerViewController withMatchRequest(request); mmvc.turnBasedMatchmakerDelegate := self; mmvc.showExistingMatches := true; presentViewController(mmvc) animated(true) completion(nil); end; {$REGION IGKTurnBasedMatchmakerViewControllerDelegate} method RootViewController.turnBasedMatchmakerViewControllerWasCancelled(aViewController: not nullable GKTurnBasedMatchmakerViewController); begin NSLog('turnBasedMatchmakerViewControllerWasCancelled:'); updateGameCenterButton(); aViewController.dismissViewControllerAnimated(true) completion(nil); end; method RootViewController.turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) didFailWithError(aError: not nullable NSError); begin NSLog('turnBasedMatchmakerViewController:didFailWithError: %@', aError); updateGameCenterButton(); aViewController.dismissViewControllerAnimated(true) completion(nil); end; method RootViewController.turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) didFindMatch(aMatch: not nullable GKTurnBasedMatch); begin NSLog('turnBasedMatchmakerViewController:didFindMatch:'); updateGameCenterButton(); aViewController.dismissViewControllerAnimated(true) completion(nil); //fBoard.clear(); // Internal NRE fBoard.clear(method begin fCurrentMatch := aMatch; NSUserDefaults.standardUserDefaults.setObject(fCurrentMatch.matchID) forKey(KEY_CURRENT_MATCH_ID); loadCurrentMatch(); end, true); end; method RootViewController.turnBasedMatchmakerViewController(aViewController: not nullable GKTurnBasedMatchmakerViewController) playerQuitForMatch(aMatch: not nullable GKTurnBasedMatch); begin NSLog('turnBasedMatchmakerViewController:playerQuitForMatch:'); if (fCurrentMatch:matchID = aMatch:matchID) then fBoard.setStatus('game over'); if aMatch.currentParticipant.playerID = GKLocalPlayer.localPlayer.playerID then begin aMatch.participantQuitInTurnWithOutcome(GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeQuit) nextParticipant(nextParticipantForMatch(aMatch)) //turnTimeout(0) matchData(aMatch.matchData) completionHandler(method (aError: NSError) begin NSLog('participantQuitInTurnWithOutcome completion - Error:%@', aError); alertError(aError.localizedDescription); end); end else begin aMatch.participantQuitOutOfTurnWithOutcome(GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeQuit) withCompletionHandler(method begin NSLog('participantQuitOutOfTurnWithOutcome completion'); end) end; end; {$ENDREGION} {$REGION IGKTurnBasedEventHandlerDelegate} method RootViewController.handleInviteFromGameCenter(playersToInvite: not nullable NSArray); begin NSLog('handleInviteFromGameCenter:'); end; method RootViewController.handleTurnEventForMatch(aMatch: not nullable GKTurnBasedMatch) didBecomeActive(didBecomeActive: Boolean); begin NSLog('handleTurnEventForMatch:%@ didBecomeActive:%d (current match is %@)', aMatch, didBecomeActive, fCurrentMatch); // do not switch to a different game, if app was already active if (not didBecomeActive) and (fCurrentMatch:matchID ≠ aMatch:matchID) then exit; fBoard.clear(method begin fCurrentMatch := aMatch; loadCurrentMatch(); end, fCurrentMatch:matchID ≠ aMatch:matchID); end; method RootViewController.handleTurnEventForMatch(aMatch: GKTurnBasedMatch); begin NSLog('handleTurnEventForMatch:'); end; method RootViewController.handleMatchEnded(aMatch: GKTurnBasedMatch); begin NSLog('handleMatchEnded:%@ (current match is %@)', aMatch, fCurrentMatch); fBoard.clear(method begin fCurrentMatch := aMatch; loadCurrentMatch(false); setGameOverStatus(fCurrentMatch); end, fCurrentMatch:matchID ≠ aMatch:matchID); end; {$ENDREGION} {$REGION IBoardDelegate} method RootViewController.board(aBoard: Board) playerWillSelectGridIndex(aGridIndex: GridIndex): Boolean; begin result := true; end; method RootViewController.board(aBoard: Board) playerDidSelectGridIndex(aGridIndex: GridIndex); begin nextLocalTurn(method begin fBoard.acceptingTurn := false; if assigned(fCurrentMatch) then remoteTurn() else computerTurn(); end); end; {$ENDREGION} method RootViewController.dictionaryFromData(aData: NSData): NSDictionary; begin if not assigned(aData) or (aData.length = 0) then exit new NSDictionary; var unarchiver := new NSKeyedUnarchiver forReadingWithData(aData); result := unarchiver.decodeObjectForKey('board'); unarchiver.finishDecoding(); end; method RootViewController.dataFromDictionary(aDictioanry: NSDictionary): NSData; begin result := new NSMutableData; var archiver := new NSKeyedArchiver forWritingWithMutableData(result as NSMutableData); archiver.encodeObject(aDictioanry) forKey('board'); archiver.finishEncoding(); end; method RootViewController.loadCurrentMatch(aResumePlay: Boolean := true); begin var lDictionary := dictionaryFromData(fCurrentMatch.matchData); fBoard.loadFromNSDictionary(lDictionary, GKLocalPlayer.localPlayer.playerID, remoteParticipantForMatch(fCurrentMatch):playerID); fBoard.acceptingTurn := false; if assigned(fCurrentMatch.currentParticipant) then begin if fCurrentMatch.currentParticipant.playerID = GKLocalPlayer.localPlayer.playerID then begin if aResumePlay then yourTurn(); end else begin if aResumePlay then begin NSLog('current player (remote): %@', fCurrentMatch.currentParticipant); setParticipantsTurnStatus(fCurrentMatch.currentParticipant); end else begin setParticipantsTurnStatus(fCurrentMatch.currentParticipant); end; end; end else begin if aResumePlay then setGameOverStatus(fCurrentMatch); end; end; method RootViewController.setGameOverStatus(aMatch: GKTurnBasedMatch); begin var lStatus := 'game over'; for each p: GKTurnBasedParticipant in aMatch.participants do begin if p.playerID = GKLocalPlayer.localPlayer.playerID then begin if p.matchOutcome = GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeWon then lStatus := "you've won" else if p.matchOutcome = GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeLost then lStatus := "you've lost" else lStatus := 'game tied'; break; end; end; fBoard.setStatus(lStatus); end; method RootViewController.setParticipantsTurnStatus(aParticipant: GKTurnBasedParticipant); begin if length(aParticipant.playerID) > 0 then begin GKPlayer.loadPlayersForIdentifiers(NSArray.arrayWithObject(aParticipant.playerID)) withCompletionHandler(method(aPlayers: NSArray; aError: NSError) begin NSLog('loadPlayersForIdentifiers:completion: completion(%@, %@)', aPlayers, aError); if aPlayers.count > 0 then //dispatch_async(dispatch_get_main_queue(), -> fBoard.setStatus(aPlayers[0].alias+"'s turn")) fBoard.setStatus(aPlayers[0].alias+"'s turn") else //dispatch_async(dispatch_get_main_queue(), -> fBoard.setStatus(aParticipant.playerID+"'s turn")) fBoard.setStatus(aParticipant.playerID+"'s turn") end); end else begin fBoard.setStatus('waiting for player'); end; end; method RootViewController.yourTurn; begin fBoard.acceptingTurn := true; fBoard.setStatus('your turn.'); end; method RootViewController.remoteParticipantForMatch(aMatch: GKTurnBasedMatch): GKTurnBasedParticipant; begin if aMatch.participants[0]:playerID.isEqualToString(GKLocalPlayer.localPlayer.playerID) then result := aMatch.participants[1] else result := aMatch.participants[0]; end; method RootViewController.nextParticipantForMatch(aMatch: GKTurnBasedMatch): GKTurnBasedParticipant; begin var i := aMatch.participants.indexOfObject(aMatch.currentParticipant); i := i+1; if i ≥ aMatch.participants.count then i := 0; result := aMatch.participants[i] end; method RootViewController.getMatchDataFromBoard: NSData; begin var lDictionary := new NSMutableDictionary(); fBoard.saveToNSDictionary(lDictionary, GKLocalPlayer.localPlayer.playerID, remoteParticipantForMatch(fCurrentMatch):playerID); result := dataFromDictionary(lDictionary) ; end; method RootViewController.remoteTurn; begin fBoard.acceptingTurn := false; setParticipantsTurnStatus(remoteParticipantForMatch(fCurrentMatch)); fCurrentMatch.endTurnWithNextParticipant(remoteParticipantForMatch(fCurrentMatch)) //turnTimeout(0) matchData(getMatchDataFromBoard) completionHandler(method (aError: NSError) begin NSLog('endTurnWithNextParticipant completion'); if assigned(aError) then NSLog('error: %@', aError); end); end; method RootViewController.computerTurn; begin fBoard.acceptingTurn := false; fBoard.setStatus('thinking...'); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), method begin NSThread.sleepForTimeInterval(0.75); dispatch_async(dispatch_get_main_queue(), method begin fBoard.makeComputerMove('O'); nextLocalTurn(method begin yourTurn(); end); end); end); end; method RootViewController.nextLocalTurn(aCompletion: block): Boolean; begin var lWinner := fBoard.markWinner; if assigned(lWinner) then begin fBoard.acceptingTurn := false; if lWinner = "X" then fBoard.setStatus("you've won") else fBoard.setStatus("you've lost"); // we can only get here in single player mode if assigned(fCurrentMatch) then begin // only the player making the turn can win for each p: GKTurnBasedParticipant in fCurrentMatch.participants do if p.playerID = GKLocalPlayer.localPlayer.playerID then p.matchOutcome := GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeWon else p.matchOutcome := GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeLost; fCurrentMatch.endMatchInTurnWithMatchData(getMatchDataFromBoard) completionHandler(method (aError: NSError) begin NSLog('endMatchInTurnWithMatchData:completionHandler: completion(%@)', aError); end); end; end else if fBoard.isFull then begin fBoard.acceptingTurn := false; fBoard.setStatus('game over'); if assigned(fCurrentMatch) then begin for each p: GKTurnBasedParticipant in fCurrentMatch.participants do p.matchOutcome := GKTurnBasedMatchOutcome.GKTurnBasedMatchOutcomeTied; fCurrentMatch.endMatchInTurnWithMatchData(getMatchDataFromBoard) completionHandler(method (aError: NSError) begin NSLog('endMatchInTurnWithMatchData:completionHandler: completion(%@)', aError); end); end; end else begin aCompletion(); end; end; method RootViewController.alertError(aMessage: NSString); begin var lAlert := new UIAlertView withTitle('Error') message(aMessage) &delegate(nil) cancelButtonTitle('OK') otherButtonTitles(nil); lAlert.show(); end; end.
unit CFLable; interface uses Winapi.Windows, System.Classes, Vcl.Controls, Vcl.Graphics; type TCFLable = class(TGraphicControl) private FAutoSize: Boolean; protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property Text; property Align; end; implementation { TCFLable } constructor TCFLable.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoSize := True; end; procedure TCFLable.Paint; var vRect: TRect; vText: string; begin Canvas.Brush.Style := bsClear; vRect := ClientRect; vText := Self.Text; Canvas.TextRect(vRect, vText, [tfSingleLine, tfVerticalCenter]); end; procedure TCFLable.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var vWidth: Integer; begin if Self.HasParent and FAutoSize then vWidth := Canvas.TextWidth(Text) else vWidth := AWidth; inherited SetBounds(ALeft, ATop, vWidth, AHeight); end; end.
unit ideSHEnvironmentOptionsFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ideSHBaseDialogFrm, StdCtrls, ExtCtrls, AppEvnts, VirtualTrees, TypInfo, SHDesignIntf, SHOptionsIntf, SHEvents, Menus; type TEnvironmentOptionsForm = class(TBaseDialogForm) Panel1: TPanel; Tree: TVirtualStringTree; Splitter1: TSplitter; pnlComponentForm: TPanel; PopupMenu1: TPopupMenu; RestoreDefaults1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); procedure RestoreDefaults1Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FComponentForm: TSHComponentForm; procedure OnChangeNode; procedure Expand; procedure FindNodeProc(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean); function FindNode(Node: PVirtualNode; AName: string): PVirtualNode; public { Public declarations } procedure RecreateOptionList(const IID: TGUID); property ComponentForm: TSHComponentForm read FComponentForm write FComponentForm; end; var EnvironmentOptionsForm: TEnvironmentOptionsForm; implementation uses ideSHSystem, ideSHConsts; {$R *.dfm} type PTreeRec = ^TTreeRec; TTreeRec = record NormalText: string; StaticText: string; Component: TSHComponent; ImageIndex: Integer; end; var OldNode: PVirtualNode; { TEnvironmentOptionsForm } procedure TEnvironmentOptionsForm.FormCreate(Sender: TObject); begin SetFormSize(540, 640); Position := poScreenCenter; inherited; Caption := Format('%s', [SCaptionDialogOptions]); CaptionOK := Format('%s', [SCaptionButtonSave]); pnlComponentForm.Caption := Format('%s', [SSubentryFrom]); if Assigned(MainIntf) then Tree.Images := MainIntf.ImageList; RegistryIntf.SaveOptionsToList; end; procedure TEnvironmentOptionsForm.FormShow(Sender: TObject); begin inherited; OnChangeNode; end; procedure TEnvironmentOptionsForm.FormClose(Sender: TObject; var Action: TCloseAction); var Event: TSHEvent; begin inherited; if Assigned(RegistryIntf) then begin try Screen.Cursor := crHourGlass; if (ModalResult = mrOK) and Assigned(DesignerIntf) then begin RegistryIntf.SaveOptionsToFile; Event.Event := SHE_OPTIONS_CHANGED; DesignerIntf.SendEvent(Event); end else RegistryIntf.LoadOptionsFromList; finally Screen.Cursor := crDefault; end; end; end; procedure TEnvironmentOptionsForm.FormDestroy(Sender: TObject); begin inherited; if Assigned(FComponentForm) then FComponentForm.Free; end; procedure TEnvironmentOptionsForm.RecreateOptionList(const IID: TGUID); var I: Integer; Data: PTreeRec; ParentNode, ChildNode: PVirtualNode; ComponentOptionsIntf: ISHComponentOptions; ParentCategory: string; procedure Test(S: string); var I: Integer; begin for I := 0 to Pred(RegistryIntf.RegDemonCount) do if Supports(RegistryIntf.GetRegDemon(I), ISHComponentOptions, ComponentOptionsIntf) and ComponentOptionsIntf.Visible and (ComponentOptionsIntf.ParentCategory = S) then begin ParentNode := FindNode(nil, ComponentOptionsIntf.ParentCategory); if not Assigned(ParentNode) then begin ParentNode := Tree.AddChild(nil); Data := Tree.GetNodeData(ParentNode); end else begin ChildNode := Tree.AddChild(ParentNode); Data := Tree.GetNodeData(ChildNode); end; Data.NormalText := ComponentOptionsIntf.Category; Data.Component := RegistryIntf.GetRegDemon(I); Data.ImageIndex := DesignerIntf.GetImageIndex(RegistryIntf.GetRegDemon(I).ClassIID); Test(Data.NormalText); end; end; begin try Tree.BeginUpdate; if not IsEqualGUID(IUnknown, IID) then for I := 0 to Pred(RegistryIntf.RegDemonCount) do if Supports(RegistryIntf.GetRegDemon(I), ISHComponentOptions, ComponentOptionsIntf) and ComponentOptionsIntf.Visible and Supports(RegistryIntf.GetRegDemon(I), IID) then begin ParentCategory := ComponentOptionsIntf.Category; ParentNode := Tree.AddChild(nil); Data := Tree.GetNodeData(ParentNode); Data.NormalText := ComponentOptionsIntf.Category; Data.Component := RegistryIntf.GetRegDemon(I); Data.ImageIndex := DesignerIntf.GetImageIndex(RegistryIntf.GetRegDemon(I).ClassIID); end; Test(ParentCategory); Expand; Tree.FocusedNode := Tree.GetFirst; Tree.Selected[Tree.FocusedNode] := True; finally Tree.EndUpdate; end; end; procedure TEnvironmentOptionsForm.OnChangeNode; var Data: PTreeRec; ComponentOptionsIntf: ISHComponentOptions; ComponentFormClass: TSHComponentFormClass; begin if Assigned(Tree.FocusedNode) and Assigned(RegistryIntf) then begin Data := Tree.GetNodeData(Tree.FocusedNode); if Assigned(ComponentForm) then begin ComponentForm.Free; ComponentForm := nil; end; Supports(Data.Component, ISHComponentOptions, ComponentOptionsIntf); if ComponentOptionsIntf.UseDefaultEditor then ComponentFormClass := RegistryIntf.GetRegComponentForm(ISHSystemOptions, SSystem) else ComponentFormClass := RegistryIntf.GetRegComponentForm(Data.Component.ClassIID, Data.NormalText); if Assigned(ComponentFormClass) then begin ComponentForm := ComponentFormClass.Create(Application, pnlComponentForm, Data.Component, Data.NormalText); ComponentForm.Show; end; end; end; procedure TEnvironmentOptionsForm.Expand; var Node: PVirtualNode; begin Node := Tree.GetFirst; while Assigned(Node) do begin if Node.ChildCount > 0 then Tree.Expanded[Node] := True; Node := Tree.GetNext(Node); end; end; procedure TEnvironmentOptionsForm.FindNodeProc(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean); var NodeData: PTreeRec; begin NodeData := nil; if Assigned(Node) then NodeData := Sender.GetNodeData(Node); Abort := (not Assigned(NodeData)) or (NodeData.NormalText = String(Data)); end; function TEnvironmentOptionsForm.FindNode(Node: PVirtualNode; AName: string): PVirtualNode; begin Result := Tree.IterateSubtree(Node, FindNodeProc, Pointer(AName), []); end; procedure TEnvironmentOptionsForm.RestoreDefaults1Click(Sender: TObject); var Data: PTreeRec; ComponentOptionsIntf: ISHComponentOptions; Event: TSHEvent; begin Event.Event := SHE_OPTIONS_DEFAULTS_RESTORED; if Assigned(Tree.FocusedNode) then begin Data := Tree.GetNodeData(Tree.FocusedNode); if Supports(Data.Component, ISHComponentOptions, ComponentOptionsIntf) then begin ComponentOptionsIntf.RestoreDefaults; DesignerIntf.SendEvent(Event); end; end; end; { Tree } procedure TEnvironmentOptionsForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TEnvironmentOptionsForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then Finalize(Data^); end; procedure TEnvironmentOptionsForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PTreeRec; begin Data := Tree.GetNodeData(Node); if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := Data.ImageIndex; end; procedure TEnvironmentOptionsForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Tree.GetNodeData(Node); case TextType of ttNormal: CellText := Data.NormalText; ttStatic: ; end; end; procedure TEnvironmentOptionsForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); begin // end; procedure TEnvironmentOptionsForm.TreeFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin if OldNode <> Tree.FocusedNode then OnChangeNode; OldNode := Tree.FocusedNode; end; procedure TEnvironmentOptionsForm.TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); var HT: THitInfo; begin PopupMenu := nil; Tree.GetHitTestInfoAt(P.X, P.Y, True, HT); if (HT.HitNode = Tree.FocusedNode) and not (hiOnItemButton in HT.HitPositions) then if Assigned(FComponentForm) then PopupMenu := PopupMenu1; end; end.
unit uThreadConnectMRPDS; interface uses Classes, uInvoicePollDisplay, IdTCPClient; type TAfterSynchAdvertising = procedure of object; TAfterSynchCrossSaleItem = procedure of object; TThreadConnectMRPDS = class(TThread) private TCPClient: TIdTCPClient; FLocalPath: String; FIP : String; FPort : Integer; FTerminated: Boolean; FAfterSynchAdvertising: TAfterSynchAdvertising; FAfterSynchCrossSaleItem: TAfterSynchCrossSaleItem; function SimpleStreamRequest( ARequestType: TMRPDSHeaderType): TMemoryStream; procedure SynchAdvertising; procedure SynchCrossSaleItem; { Private declarations } public property LocalPath: String read FLocalPath write FLocalPath; property IP: String read FIP write FIP; property Port: Integer read FPort write FPort; property Terminated: Boolean read FTerminated write FTerminated; property AfterSynchAdvertising: TAfterSynchAdvertising read FAfterSynchAdvertising write FAfterSynchAdvertising; property AfterSynchCrossSaleItem: TAfterSynchCrossSaleItem read FAfterSynchCrossSaleItem write FAfterSynchCrossSaleItem; constructor Create(CreateSuspended: Boolean); protected procedure Execute; override; end; implementation { ThreadConnectMRPDS } constructor TThreadConnectMRPDS.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FTerminated := False; end; procedure TThreadConnectMRPDS.Execute; begin FTerminated := False; try if FIP = '' then Exit; TCPClient := TIdTCPClient.Create(nil); try TCPClient.Host := FIP; TCPClient.Port := FPort; try TCPClient.Connect(5000); except end; if TCPClient.Connected then begin SynchAdvertising; SynchCrossSaleItem; end; finally TCPClient.Free; end; finally FTerminated := True; end; end; function TThreadConnectMRPDS.SimpleStreamRequest(ARequestType: TMRPDSHeaderType): TMemoryStream; var SendingHeader, ReceivingHeader: TMRPDSHeader; SendingStream, SendingHeaderStream, ReceivingStream: TMemoryStream; begin ReceivingStream := TMemoryStream.Create; SendingHeaderStream := TMemoryStream.Create; try SendingStream := TMemoryStream.Create; try SendingStream.Write(SendingHeader, SizeOf(TMRPDSHeader)); SendingHeader.BodyType := ARequestType; SendingHeader.ByteCount := SendingStream.Size; SendingHeaderStream.Write(SendingHeader, SizeOf(TMRPDSHeader)); SendingStream.Seek(0, soFromBeginning); SendingHeaderStream.Seek(0, soFromBeginning); TCPClient.WriteStream(SendingHeaderStream); TCPClient.WriteStream(SendingStream); finally SendingStream.Free; end; finally SendingHeaderStream.Free; end; TCPClient.ReadStream(ReceivingStream, SizeOf(TMRPDSHeader)); ReceivingStream.Seek(0, soFromBeginning); ReceivingHeader := TMRPDSHeader(ReceivingStream.Memory^); ReceivingStream.Clear; ReceivingStream.Seek(0, soFromBeginning); TCPClient.ReadStream(ReceivingStream, ReceivingHeader.ByteCount); ReceivingStream.Seek(0, soFromBeginning); Result := ReceivingStream; end; procedure TThreadConnectMRPDS.SynchAdvertising; var ReceivedStream : TMemoryStream; begin ReceivedStream := SimpleStreamRequest(pdsAdvertising); if ReceivedStream.Size > 0 then begin ReceivedStream.SaveToFile(FLocalPath + 'Advertising.xml'); ReceivedStream.Clear; ReceivedStream.Free; end; if Assigned(FAfterSynchAdvertising) then FAfterSynchAdvertising; end; procedure TThreadConnectMRPDS.SynchCrossSaleItem; var ReceivedStream : TMemoryStream; begin ReceivedStream := SimpleStreamRequest(pdsCrossSaleItem); if ReceivedStream.Size > 0 then begin ReceivedStream.SaveToFile(FLocalPath + 'CrossSaleItem.xml'); ReceivedStream.Clear; ReceivedStream.Free; end; if Assigned(FAfterSynchCrossSaleItem) then FAfterSynchCrossSaleItem; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0051.PAS Description: Compute POWER of Number Author: SWAG SUPPORT GROUP Date: 11-26-93 17:37 *) Procedure Power1(Var Num,Togo,Sofar:LongInt); Begin If Togo = 0 then Exit; If Sofar = 0 then Sofar := num Else Sofar := Sofar*Num; Togo := Togo-1; Power1(Num,Togo,Sofar) End; { While this is programatically elegant, an iterative routine would be more efficient: } function power2(base,exponent:longint):longint; var absexp,temp,loop:longint; begin power2 := 0; { error } if exponent < 0 then exit; temp := 1; for loop := 1 to exponent do temp := temp * base; power2 := temp; end; { Well it all looks nice, but this is problably the easiest way } function Power3(base,p : real): real; { compute base^p, with base>0 } begin power3 := exp(p*ln(base)) end; { Test program} var n1, n2, n3: longint; begin n1 := 2; n2 := 3; n3 := 2; power1(n1,n2,n3); WriteLn( n3 ); WriteLn( power2(2,4) ); WriteLn( power3(2,4) ); end.
{*******************************************************} { } { FileInfoDataModule.pas { Copyright @2014/5/12 14:17:45 by 姜梁 { } { 功能描述:fileinfo 文件信息构造类 { 函数说明: {*******************************************************} unit dDataModelFileInfo; interface uses Generics.Collections, Windows, Messages; type TFileInfoDataModule= class public MDString:string; MDFString:string; //文件名 FileName: string; //文件大小 FileSize: Int64; //文件路径 FilePath: string; //是否已经排序 IsSort:Boolean; //是否已经计算添加了完整的MD5 ISMD5:Boolean; //组号 GroupIndex:Integer; FileTime:Integer; end; PFileInfoDataModule = ^TFileInfoDataModule; type /// <summary> /// 文件信息列表 /// </summary> TListFileInfo = TList<TFileInfoDataModule> ; type SameFileData = class FileList: TListFileInfo; SameNum:Integer; end; type TListSameFileData = TList<SameFileData>; implementation end.
unit Render3Test; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, pngimage, Node, Box {Layout}; type TRender3TestForm = class(TForm) BoxMemo: TMemo; Panel: TPanel; PaintBox: TPaintBox; Splitter1: TSplitter; DOMMemo: TMemo; Splitter3: TSplitter; Image1: TImage; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); private { Private declarations } procedure DoDumpNodes(inNodes: TNodeList; inDent: string); procedure DumpBoxes(inBoxes: TBoxList; inDent: string); procedure DumpBoxStructure; procedure DumpDOMStructure; public { Public declarations } end; var Render3TestForm: TRender3TestForm; implementation uses {Render3, Nodes, LayoutTest} FlowTest; var N: TNodeList; B: TBoxList; {$R *.dfm} procedure TRender3TestForm.FormCreate(Sender: TObject); begin N := BuildNodeList; DumpDOMStructure; Show; end; procedure TRender3TestForm.FormResize(Sender: TObject); begin //R.Width := ClientWidth - 32; B.Free; B := BuildBoxList(PaintBox.Canvas, N); DumpBoxStructure; PaintBox.Invalidate; end; procedure TRender3TestForm.PaintBoxPaint(Sender: TObject); begin //RenderBoxList(B, PaintBox.Canvas, PaintBox.ClientRect); end; procedure TRender3TestForm.DoDumpNodes(inNodes: TNodeList; inDent: string); var i: Integer; node: TNode; s: string; begin for i := 0 to Pred(inNodes.Count) do begin node := inNodes[i]; if (node <> nil) then begin s := Format('%s| (%d) [%s: %s] => [%s] ', [ inDent, i, {node.Element}'', node.ClassName, node.Text ]); DOMMemo.Lines.Add(s); if node.Nodes <> nil then DoDumpNodes(node.Nodes, inDent + '--'); end; end; end; procedure TRender3TestForm.DumpDOMStructure; begin DOMMemo.Lines.BeginUpdate; try DOMMemo.Lines.Clear; DOMMemo.Lines.Add('DOM Structure:'); DoDumpNodes(N, ''); finally DOMMemo.Lines.EndUpdate; end; end; procedure TRender3TestForm.DumpBoxes(inBoxes: TBoxList; inDent: string); var i: Integer; box: TBox; s, t: string; begin if inBoxes <> nil then for i := 0 to Pred(inBoxes.Count) do begin box := inBoxes[i]; if (box <> nil) then begin t := ''; if box.Node <> nil then t := box.Node.Text; s := Format('%s| (%d) [%s] [%d, %d => %d, %d] [%d, %d] => [%s] ', [ inDent, i, {box.Name}'', box.Left, box.Top, box.Width, box.Height, box.Offset.X, box.Offset.Y, t ]); //if (box.Node <> nil) then // s := s + '(' + box.className + ')'; BoxMemo.Lines.Add(s); DumpBoxes(box.Boxes, inDent + '--'); end; end; end; procedure TRender3TestForm.DumpBoxStructure; begin try BoxMemo.Lines.BeginUpdate; BoxMemo.Lines.Clear; BoxMemo.Lines.Add('Box Structure:'); DumpBoxes(B, ''); finally BoxMemo.Lines.EndUpdate; end; end; end.
{ This Unit shall contain default values for strings, constant values etc. This is the place for the translation strings } unit CoyoteDefaults; interface uses INIFiles, workdays; procedure LoadFromLanguageFile(AFilePath: string); resourcestring // Programme-Information ProgrammeName = 'CoYOT(e)'; // Official Name shown to the user VersionNr = '0.1.1.0'; // Programme-Version VersionDate = '29.08.2014'; // Date of the latest changes LazarusVersion = '1.2.2'; // Version of the Lazarus IDE the programme was created with defLanguage = 'English'; // not sure what we will need in future defLanguageID = 'en'; // The following values are either default strings that can be translated using a lang-file or are default values which // will be changed if there is an entry in the INI-file. var // Messages / Errors txtDeleteAllMsg: string = 'Do you really wish to delete every entry? All data will be lost if you do not make a copy!'; txtDeleteMsg: string = 'Are you sure you want to delete this period including all days related to it? This cannot be made undone afterwards!'; txtRemoveMsg: string = 'Do you really want to delete the selected day? This will delete all data related to it!'; txtClearMsg: string = 'This will clear the current week and make it empty but will NOT delete the week! Do you wish to Continue?'; txtQuitMsg: string = 'Do you want to save your changes? Otherwise they will get lost!'; txtCaptionDelete: string = 'Really delete?'; txtQuitProgramme: string = 'Quit Programme'; txtFileSaved: string = 'File saved...'; txtNewFile: string = 'Created new file...'; emDateOrder: string = 'Error: The dates are in the wrong order!'; emHoursPerDay: string = 'Error: Enter a valid amount of time per day!'; emInvalidFileFormat: string = 'The file could not be loaded, because it is not a valid CoYOT(e) file!'; emFileNotFound: string = 'Error: The selected file could not be found!'; emMergeNoWeekSelected: string = 'Cannot merge, because no week to merge with has been selected! Please select one using the combobox!'; emMergeSameWeek: string = 'Cannot merge a week with itself! Please select a different week via the combobox!'; emInvalidNumber: string = 'Not a valid number input! Try switching "." and "," as the comma separator!'; txtRemoveUserMsg: string = 'Do you really want to delete the selected user? This will delete all related data permanently!'; dbDefaultFirebirdUser: string = 'SYSDBA'; dbDefaultFirebirdPort: string = ''; // 3050 // Captions in menus mcFile: string = 'File'; mcEdit: string = 'Edit'; mcShow: string = 'Show'; mcDataBase: string = 'Database'; mcOptions: string = 'Options'; mcHelp: string = 'Help'; mcNew: string = 'New'; mcSaveAs: string = 'Save as'; mcSave: string = 'Save'; mcOpen: string = 'Open'; mcOpenRecent: string = 'Open Recent'; mcExit: string = 'Exit'; mcPeople: string = 'People'; mcStatistics: string = 'Statistics'; mcDatabaseSettings: string = 'database settings'; mcDatabaseUpload: string = 'push to database'; mcDatabaseDownload: string = 'load from database'; mcProgrammeSettings: string = 'Programme Settings'; mcColorTheme: string = 'Color Theme'; mcLanguage: string = 'Language'; mcManual: string = 'Manual (PDF)'; mcAbout: string = 'About'; bcApply: string = 'Apply'; bcBack: string = 'Back'; bcReset: string = 'Reset'; // default short day names txtMon: string = 'Mon'; txtTue: string = 'Tue'; txtWed: string = 'Wed'; txtThu: string = 'Thu'; txtFri: string = 'Fri'; txtSat: string = 'Sat'; txtSun: string = 'Sun'; txtSum: string = 'Sum'; txtGoal: string = 'Goal'; txtDiff: string = 'Diff'; txtDays: string = 'Days'; txtPeriod: string = 'Period'; txtVacation: string = 'Vacation'; txtSummary: String = 'Summary'; // default long day names txtMonday: string = 'Monday'; txtTuesday: string = 'Tuesday'; txtWednesday: string = 'Wednesday'; txtThursday: string = 'Thursday'; txtFriday: string = 'Friday'; txtSaturday: string = 'Saturday'; txtSunday: string = 'Sunday'; txtEarliestBegin: String = 'earliest begin'; txtLatestLeave: String = 'latest leave'; txtLongestDay: String = 'longest day'; // Standard Values - will be used, if nothing was found in the ini-file defHoursUntilPause: double = 6; // Amount of time before the obligatory pause is needed / added defPausePerDay: double = 0.75; defHoursPerDay: double = 8; // Standard Value defToolbarColor: integer = $00FFE4CA; //$00E0E0E0; // $00FFDBB7; option_openLatestFile: Boolean = False; colorMarkedDays: Integer = $000080FF; colorVacationDays: Integer = $00FF0080; implementation procedure LoadFromLanguageFile(AFilePath: string); var INI: TInifile; begin INI := TINIFile.Create(AFilePath); txtMon := INI.ReadString('CoyoteDefaults', 'txtMon', ''); txtTue := INI.ReadString('CoyoteDefaults', 'txtTue', ''); txtWed := INI.ReadString('CoyoteDefaults', 'txtWed', ''); txtThu := INI.ReadString('CoyoteDefaults', 'txtThu', ''); txtFri := INI.ReadString('CoyoteDefaults', 'txtFri', ''); txtSat := INI.ReadString('CoyoteDefaults', 'txtSat', ''); txtSun := INI.ReadString('CoyoteDefaults', 'txtSun', ''); txtWeekDays[1] := txtMon; txtWeekDays[2] := txtTue; txtWeekDays[3] := txtWed; txtWeekDays[4] := txtThu; txtWeekDays[5] := txtFri; txtWeekDays[6] := txtSat; txtWeekDays[7] := txtSun; txtQuitMsg := INI.ReadString('CoyoteDefaults', 'txtQuitMsg', txtQuitMsg); txtQuitProgramme := INI.ReadString('CoyoteDefaults', 'txtQuitProgramme', txtQuitProgramme); txtSum := INI.ReadString('CoyoteDefaults', 'txtSum', txtSum); txtGoal := INI.ReadString('CoyoteDefaults', 'txtGoal', txtGoal); txtDiff := INI.ReadString('CoyoteDefaults', 'txtDiff', txtDiff); txtDays := INI.ReadString('CoyoteDefaults', 'txtDays', txtDays); txtPeriod := INI.ReadString('CoyoteDefaults', 'txtPeriod', txtPeriod); txtVacation := INI.ReadString('CoyoteDefaults', 'txtVacation', txtVacation); txtSummary := INI.ReadString('CoyoteDefaults', 'txtSummary', txtSummary); txtLatestLeave := INI.ReadString('CoyoteDefaults', 'txtLatestLeave', txtLatestLeave); txtEarliestBegin := INI.ReadString('CoyoteDefaults', 'txtEarliestBegin', txtEarliestBegin); txtLongestDay := INI.ReadString('CoyoteDefaults', 'txtLongestDay', txtLongestDay); mcFile := INI.ReadString('MenuCaption', 'mcFile', mcFile); mcEdit := INI.ReadString('MenuCaption', 'mcEdit', mcEdit); mcShow := INI.ReadString('MenuCaption', 'mcShow', mcShow); mcDataBase := INI.ReadString('MenuCaption', 'mcDataBase', mcDataBase); mcOptions := INI.ReadString('MenuCaption', 'mcOptions', mcOptions); mcHelp := INI.ReadString('MenuCaption', 'mcHelp', mcHelp); mcNew := INI.ReadString('MenuCaption', 'mcNew', mcNew); mcOpen := INI.ReadString('MenuCaption', 'mcOpen', mcOpen); mcOpenRecent := INI.ReadString('MenuCaption', 'mcOpenRecent', mcOpenRecent); mcSaveAs := INI.ReadString('MenuCaption', 'mcSaveAs', mcSaveAs); mcSave := INI.ReadString('MenuCaption', 'mcSave', mcSave); mcExit := INI.ReadString('MenuCaption', 'mcExit', mcExit); mcPeople := INI.ReadString('MenuCaption', 'mcPeople', mcPeople); mcStatistics := INI.ReadString('MenuCaption', 'mcStatistics', mcStatistics); mcDatabaseSettings := INI.ReadString('MenuCaption', 'mcDatabaseSettings', mcDatabaseSettings); mcDatabaseUpload := INI.ReadString('MenuCaption', 'mcDatabaseUpload', mcDatabaseUpload); mcDatabaseDownload := INI.ReadString('MenuCaption', 'mcDatabaseDownload', mcDatabaseDownload); mcProgrammeSettings := INI.ReadString('MenuCaption', 'mcProgrammeSettings', mcProgrammeSettings); mcColorTheme := INI.ReadString('MenuCaption', 'mcColorTheme', mcColorTheme); mcLanguage := INI.ReadString('MenuCaption', 'mcLanguage', mcLanguage); mcManual := INI.ReadString('MenuCaption', 'mcManual', mcManual); mcAbout := INI.ReadString('MenuCaption', 'mcAbout', mcAbout); bcApply := INI.ReadString('Buttons', 'bcApply', bcApply); bcBack := INI.ReadString('Buttons', 'bcBack', bcBack); bcReset := INI.ReadString('Buttons', 'bcReset', bcReset); end; end.
unit weather_utils; interface uses fillables, Data.DB; type TCityCountry = record City: string; Country: string; end; TCityCountryDynArray = array of TCityCountry; TWeatherRec = record Location: string; Time: string; Wind: string; Visibility: string; SkyConditions: string; Temperature: string; DewPoint: string; RelativeHumidity: string; Pressure: string; Status: string; end; TWeatherInfo = record LocName: string; LocCode: string; LocLatitude: TFillableSingle; LocLongitude: TFillableSingle; LocAltitude: TFillableSingle; Time: string; DateTimeUTC: TFillableDateTime; Wind: string; WindDir: TFillableSingle; WindSpeed: TFillableSingle; Visibility: string; SkyConditions: string; TempF: TFillableSingle; TempC: TFillableSingle; DewPoint: string; RelativeHumidity: TFillableSingle; PressureHg: TFillableSingle; PressurehPa: TFillableSingle; Status: string; end; function WeatherRecToInfo(wr: TWeatherRec): TWeatherInfo; procedure SetSingleField(f: TSingleField; v: TFillableSingle); procedure SetDateTimeField(f: TDateTimeField; v: TFillableDateTime); implementation uses System.Types, System.SysUtils, StrUtils, DateUtils; procedure SetSingleField(f: TSingleField; v: TFillableSingle); begin if f <> nil then begin if v.IsFilled then f.AsFloat := v.Value else f.Clear; end; end; procedure SetDateTimeField(f: TDateTimeField; v: TFillableDateTime); begin if f <> nil then begin if v.IsFilled then f.AsDateTime := v.Value else f.Clear; end; end; function ConvGeoPos(s: string; NegChar: string): TFillableSingle; var p: integer; begin Result.IsFilled := s <> ''; if Result.IsFilled then begin p := Pos('-',s); Result.Value := StrToInt(copy(s,1,p-1)); s := copy(s,p+1,Length(s)); Result.Value := Result.Value + StrToInt(copy(s,1,Length(s)-1)) / 100; if copy(s,Length(s)-1,1) = NegChar then Result.Value := -Result.Value; end; end; function ConvDateTimeUTC(s: string): TFillableDateTime; var y,m,d,h,min: word; begin //2013.07.12 1630 UTC Result.IsFilled := s <> ''; if Result.IsFilled then begin y := StrToInt(copy(s,1,4)); m := StrToInt(copy(s,6,2)); d := StrToInt(copy(s,9,2)); h := StrToInt(copy(s,12,2)); min := StrToInt(copy(s,14,2)); Result.Value := EncodeDateTime(y,m,d,h,min,0,0); end; end; function SaveStrToFloat(s: string): single; begin try Result := StrToFloat(s); except on EConvertError do begin s := StringReplace(s,'.',',',[]); Result := StrToFloat(s); end; end; end; function WeatherRecToInfo(wr: TWeatherRec): TWeatherInfo; var s,s1: string; pos1: integer; begin s := wr.Location; pos1 := Pos('(',s); Result.LocName := trim(copy(s,1,pos1-1)); s := copy(s, pos1+1, Length(s)); pos1 := Pos(')',s); Result.LocCode := copy(s,1,pos1-1); s := trim(copy(s,pos1+1,Length(s))); Pos1 := Pos(' ',s); Result.LocLatitude := ConvGeoPos(copy(s,1,Pos1-1),'S'); s := trim(copy(s,pos1+1,Length(s))); Pos1 := Pos(' ',s); Result.LocLongitude := ConvGeoPos(copy(s,1,Pos1-1),'W'); s := trim(copy(s,pos1+1,Length(s))); if Length(s) > 0 then begin Result.LocAltitude.IsFilled := True; Result.LocAltitude.Value := StrToFloat(copy(s,1,Length(s)-1)); end else Result.LocAltitude.IsFilled := False; Result.Time := wr.Time; s := wr.Time; if s <> '' then begin Pos1 := Pos('/',s); if Pos1 > 0 then begin s := trim(copy(s,pos1+1,Length(s))); Result.DateTimeUTC := ConvDateTimeUTC(s); end else Result.DateTimeUTC.IsFilled := False; end else Result.DateTimeUTC.IsFilled := False; Result.Wind := wr.Wind; if wr.Wind <> '' then begin s := wr.Wind; if Pos('degrees',s) > 0 then begin pos1 := Pos('(',s); if pos1 > 0 then begin s := copy(s,pos1+1,Length(s)); pos1 := Pos(' ',s); Result.WindDir.Value := StrToFloat(copy(s,1,Pos1-1)); Result.WindDir.IsFilled := true; end else Result.WindDir.IsFilled := false; end else Result.WindDir.IsFilled := false; pos1 := Pos('at',s); if pos1 > 0 then begin s := trim(copy(s,pos1+3,Length(s))); pos1 := Pos(' ',s); Result.WindSpeed.Value := StrToFloat(copy(s,1,Pos1-1)); Result.WindSpeed.IsFilled := True; end else Result.WindSpeed.IsFilled := False; end else begin Result.WindDir.IsFilled := false; Result.WindSpeed.IsFilled := false; end; Result.Visibility := wr.Visibility; Result.SkyConditions := wr.SkyConditions; s := trim(wr.Temperature); if s <> '' then begin Pos1 := Pos('F',s); if Pos1 > 0 then begin Result.TempF.Value := StrToFloat(copy(s,1,Pos1-1)); Result.TempF.IsFilled := True; end else Result.TempF.IsFilled := False; Pos1 := Pos('(',s); if Pos1 > 0 then begin s := trim(copy(s,pos1+1,Length(s))); Pos1 := Pos(' ',s); s := copy(s,1,Pos1-1); // s := StringReplace(s,'.',',',[]); // Result.TempC.Value := StrToFloat(s); Result.TempC.Value := SaveStrToFloat(s); Result.TempC.IsFilled := True; end else Result.TempC.IsFilled := False; end else begin Result.TempF.IsFilled := False; Result.TempC.IsFilled := False; end; Result.DewPoint := wr.DewPoint; s := trim(wr.RelativeHumidity); if s <> '' then begin Pos1 := Pos('%',s); if Pos1 > 0 then begin s := copy(s,1,Pos1-1); // s := StringReplace(s,'.',',',[]); // Result.RelativeHumidity.Value := StrToFloat(s); Result.RelativeHumidity.Value := SaveStrToFloat(s); Result.RelativeHumidity.IsFilled := True; end else Result.RelativeHumidity.IsFilled := False; end else Result.RelativeHumidity.IsFilled := False; s := trim(wr.Pressure); if s <> '' then begin Pos1 := Pos(' ',s); if Pos1 > 0 then begin s1 := copy(s,1,Pos1-1); // s1 := StringReplace(s1,'.',',',[]); // Result.PressureHg.Value := StrToFloat(s1); Result.PressureHg.Value := SaveStrToFloat(s1); Result.PressureHg.IsFilled := True; end else Result.PressureHg.IsFilled := False; Pos1 := Pos('(',s); if Pos1 > 0 then begin s := trim(copy(s,pos1+1,Length(s))); Pos1 := Pos(' ',s); s := copy(s,1,Pos1-1); // s := StringReplace(s,'.',',',[]); // Result.PressurehPa.Value := StrToFloat(s); Result.PressurehPa.Value := SaveStrToFloat(s); Result.PressurehPa.IsFilled := True; end else Result.PressurehPa.IsFilled := False; end else begin Result.PressureHg.IsFilled := False; Result.PressurehPa.IsFilled := False; end; Result.Status := wr.Status end; end.
{ $OmniXML: OmniXML/GpMemStr.pas,v 1.1.1.1 2004/04/17 11:16:33 mr Exp $ } (*:Different memory stream, designed to work with a preallocated, fixed-size buffer. @author Primoz Gabrijelcic @desc <pre> (c) 2001 Primoz Gabrijelcic Free for personal and commercial use. No rights reserved. Author : Primoz Gabrijelcic Creation date : unknown Last modification : 2002-11-23 Version : 2.02a </pre>*)(* History: 2.02a: 2002-11-23 - Fixed read/write bug that allowed caller to read/write one byte over the buffer boundary. 2.02: 2002-11-20 - Adedd overloaded parameterless constructor to preserve existing code that calls SetBuffer explicitely. 2.01: 2002-11-17 - Added constructor. 2.0: 2001-12-07 - Class TMyMemoryStream renamed to TGpFixedMemoryStream and made descendant of TStream. *) unit GpMemStr; interface uses Classes; type TGpFixedMemoryStream = class(TStream) private fmsBuffer : pointer; fmsPosition: integer; fmsSize : integer; public constructor Create; overload; constructor Create(const data; size: integer); overload; function Read(var data; size: integer): integer; override; function Seek(offset: longint; origin: word): longint; override; procedure SetBuffer(const data; size: integer); function Write(const data; size: integer): integer; override; property Position: integer read fmsPosition write fmsPosition; property Memory: pointer read fmsBuffer; end; { TGpFixedMemoryStream } implementation constructor TGpFixedMemoryStream.Create; begin inherited Create; end; { TGpFixedMemoryStream.Create } constructor TGpFixedMemoryStream.Create(const data; size: integer); begin inherited Create; SetBuffer(data, size); end; { TGpFixedMemoryStream.Create } procedure TGpFixedMemoryStream.SetBuffer(const data; size: integer); begin fmsBuffer := @data; fmsSize := size; fmsPosition:= 0; end; { TGpFixedMemoryStream.SetBuffer } function TGpFixedMemoryStream.Read(var data; size: integer): integer; begin if (fmsPosition+size) > fmsSize then size := fmsSize-fmsPosition; Move(pointer(integer(fmsBuffer)+fmsPosition)^,data,size); fmsPosition := fmsPosition + size; Read := size; end; { TGpFixedMemoryStream.Read } function TGpFixedMemoryStream.Write(const data; size: integer): integer; begin if (fmsPosition+size) > fmsSize then size := fmsSize-fmsPosition; Move(data,pointer(integer(fmsBuffer)+fmsPosition)^,size); fmsPosition := fmsPosition + size; Write := size; end; { TGpFixedMemoryStream.Write } function TGpFixedMemoryStream.Seek(offset: longint; origin: word): longint; begin if origin = soFromBeginning then fmsPosition := offset else if origin = soFromCurrent then fmsPosition := fmsPosition + offset else fmsPosition := fmsSize - offset; Result := fmsPosition; end; { TGpFixedMemoryStream.Seek } end.
unit Pospolite.View.HTML.Scrolling; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, math, Pospolite.View.Basics, Pospolite.View.Drawing.Basics, Pospolite.View.Drawing.Renderer; type { TPLHTMLScrollingRealSize } TPLHTMLScrollingRealSize = packed record public Width, Height: TPLFloat; procedure Apply(const AWidth, AHeight: TPLFloat); end; { TPLHTMLScrollingInfo } TPLHTMLScrollingInfo = packed record public RealSize: TPLHTMLScrollingRealSize; Position: TPLPointF; class operator = (a, b: TPLHTMLScrollingInfo) r: TPLBool; end; { TPLHTMLScrolling } TPLHTMLScrolling = class(TObject) private FInfo: TPLHTMLScrollingInfo; FObject: TPLHTMLObject; FRenderer: TObject; procedure SetInfo(AValue: TPLHTMLScrollingInfo); public constructor Create(AObject: TPLHTMLObject); procedure UpdateScrolling; procedure Draw(ARenderer: TPLDrawingRenderer); property Info: TPLHTMLScrollingInfo read FInfo write SetInfo; end; implementation { TPLHTMLScrollingRealSize } procedure TPLHTMLScrollingRealSize.Apply(const AWidth, AHeight: TPLFloat); begin Width := AWidth; Height := AHeight; end; { TPLHTMLScrollingInfo } class operator TPLHTMLScrollingInfo.=(a, b: TPLHTMLScrollingInfo) r: TPLBool; begin r := (a.Position = b.Position) and (a.RealSize.Height = b.RealSize.Height) and (a.RealSize.Width = b.RealSize.Width); end; { TPLHTMLScrolling } procedure TPLHTMLScrolling.SetInfo(AValue: TPLHTMLScrollingInfo); begin if FInfo = AValue then exit; FInfo := AValue; UpdateScrolling; end; constructor TPLHTMLScrolling.Create(AObject: TPLHTMLObject); begin inherited Create; FObject := AObject; end; procedure TPLHTMLScrolling.UpdateScrolling; var obj: TPLHTMLObject; begin if not Assigned(FObject) then exit; Info.RealSize.Apply(FObject.GetWidth, FObject.GetHeight); for obj in FObject.Children do begin if (obj.PositionType = 'fixed') or ((FObject.PositionType = 'static') and (obj.PositionType = 'absolute')) then continue; // child obj is not in parent FObject Info.RealSize.Apply( max(Info.RealSize.Width, obj.GetLeft + obj.GetWidth), max(Info.RealSize.Height, obj.GetTop + obj.GetHeight) ); end; end; procedure TPLHTMLScrolling.Draw(ARenderer: TPLDrawingRenderer); var r: TPLDrawingRenderer absolute ARenderer; begin end; end.
unit UDPictures; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32; type TCrpePicturesDlg = class(TForm) pnlPictures: TPanel; lblNumber: TLabel; lbNumbers: TListBox; editCount: TEdit; lblCount: TLabel; btnOk: TButton; btnClear: TButton; gbCropFrom: TGroupBox; lblCropLeft: TLabel; lblCropRight: TLabel; lblCropTop: TLabel; lblCropBottom: TLabel; editCropLeft: TEdit; editCropRight: TEdit; editCropTop: TEdit; editCropBottom: TEdit; gbScaling: TGroupBox; lblScalingWidth: TLabel; lblScalingHeight: TLabel; editScalingWidth: TEdit; editScalingHeight: TEdit; lblPercent1: TLabel; lblPercent2: TLabel; rgUnits: TRadioGroup; btnBorder: TButton; btnFormat: TButton; gbFormat: TGroupBox; lblTop: TLabel; lblLeft: TLabel; lblSection: TLabel; lblWidth: TLabel; lblHeight: TLabel; editTop: TEdit; editLeft: TEdit; editWidth: TEdit; editHeight: TEdit; cbSection: TComboBox; procedure btnClearClick(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdatePictures; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure editSizeEnter(Sender: TObject); procedure editSizeExit(Sender: TObject); procedure cbSectionChange(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure rgUnitsClick(Sender: TObject); procedure btnFormatClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; PIndex : smallint; PrevSize : string; end; var CrpePicturesDlg: TCrpePicturesDlg; bPictures : boolean; implementation {$R *.DFM} uses UCrpeUtl, UDBorder, UDFormat; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.FormCreate(Sender: TObject); begin bPictures := True; LoadFormPos(Self); btnOk.Tag := 1; PIndex := -1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.FormShow(Sender: TObject); begin UpdatePictures; end; {------------------------------------------------------------------------------} { UpdatePictures } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.UpdatePictures; var i : smallint; OnOff : boolean; begin PIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin OnOff := (Cr.Pictures.Count > 0); {Get Pictures Index} if OnOff then begin if Cr.Pictures.ItemIndex > -1 then PIndex := Cr.Pictures.ItemIndex else PIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff = True then begin {Fill Section ComboBox} cbSection.Items.AddStrings(Cr.SectionFormat.Names); for i := 0 to Cr.Pictures.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.Pictures.Count); lbNumbers.ItemIndex := PIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.lbNumbersClick(Sender: TObject); var OnOff : Boolean; begin PIndex := lbNumbers.ItemIndex; OnOff := (Cr.Pictures[PIndex].Handle <> 0); btnBorder.Enabled := OnOff; btnFormat.Enabled := OnOff; editScalingWidth.Text := CrFloatingToStr(Cr.Pictures.Item.ScalingWidth); editScalingHeight.Text := CrFloatingToStr(Cr.Pictures.Item.ScalingHeight); cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Pictures.Item.Section); rgUnitsClick(Self); end; {------------------------------------------------------------------------------} { editSizeEnter } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.editSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { editSizeExit } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.editSizeExit(Sender: TObject); begin if TEdit(Sender).Name = 'editScalingWidth' then begin Cr.Pictures.Item.ScalingWidth := CrStrToFloating(TEdit(Sender).Text); Exit; end; if TEdit(Sender).Name = 'editScalingHeight' then begin Cr.Pictures.Item.ScalingHeight := CrStrToFloating(TEdit(Sender).Text); Exit; end; if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editCropTop' then Cr.Pictures.Item.CropTop := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editCropLeft' then Cr.Pictures.Item.CropLeft := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editCropBottom' then Cr.Pictures.Item.CropBottom := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editCropRight' then Cr.Pictures.Item.CropRight := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editTop' then Cr.Pictures.Item.Top := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Pictures.Item.Left := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Pictures.Item.Width := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Pictures.Item.Height := InchesStrToTwips(TEdit(Sender).Text); UpdatePictures; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.Pictures.Item.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Pictures.Item.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Pictures.Item.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Pictures.Item.Height := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editCropLeft.Text := TwipsToInchesStr(Cr.Pictures.Item.CropLeft); editCropRight.Text := TwipsToInchesStr(Cr.Pictures.Item.CropRight); editCropTop.Text := TwipsToInchesStr(Cr.Pictures.Item.CropTop); editCropBottom.Text := TwipsToInchesStr(Cr.Pictures.Item.CropBottom); editTop.Text := TwipsToInchesStr(Cr.Pictures.Item.Top); editLeft.Text := TwipsToInchesStr(Cr.Pictures.Item.Left); editWidth.Text := TwipsToInchesStr(Cr.Pictures.Item.Width); editHeight.Text := TwipsToInchesStr(Cr.Pictures.Item.Height); end else {twips} begin editCropLeft.Text := IntToStr(Cr.Pictures.Item.CropLeft); editCropRight.Text := IntToStr(Cr.Pictures.Item.CropRight); editCropTop.Text := IntToStr(Cr.Pictures.Item.CropTop); editCropBottom.Text := IntToStr(Cr.Pictures.Item.CropBottom); editTop.Text := IntToStr(Cr.Pictures.Item.Top); editLeft.Text := IntToStr(Cr.Pictures.Item.Left); editWidth.Text := IntToStr(Cr.Pictures.Item.Width); editHeight.Text := IntToStr(Cr.Pictures.Item.Height); end; end; {------------------------------------------------------------------------------} { cbSectionChange } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.cbSectionChange(Sender: TObject); begin Cr.Pictures.Item.Section := cbSection.Items[cbSection.ItemIndex]; end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.Pictures.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.Pictures.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.btnClearClick(Sender: TObject); begin Cr.Pictures.Clear; UpdatePictures; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the UpdatePictures call} if (not IsStrEmpty(Cr.ReportName)) and (PIndex > -1) then begin editSizeExit(editCropLeft); editSizeExit(editCropRight); editSizeExit(editCropTop); editSizeExit(editCropBottom); editSizeExit(editScalingWidth); editSizeExit(editScalingHeight); editSizeExit(editTop); editSizeExit(editWidth); editSizeExit(editLeft); editSizeExit(editHeight); end; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpePicturesDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bPictures := False; Release; end; end.
unit Subtitles; interface uses Classes, Sysutils, Dialogs; const HEADER_UNICODE = $FEFF; MAX_SRT_FILESIZE = 1024 * 1024 * 2; // 2 Mb type TSubtitle = class private FIndex: Integer; FBeginTime: Integer; FEndTime: Integer; FText: String; public function isInTime(pos1, pos2: Integer): Boolean; overload; function isInTime(time_pos: Integer): Boolean; overload; property IntervalStart: Integer read FBeginTime write FBeginTime; property IntervalEnd: Integer read FEndTime write FEndTime; property Text: String read FText write FText; property id: Integer read FIndex write FIndex; end; PSubtitle = ^TSubtitle; TSrtSubtitles = class private FSubList: TList; function ParseTimings(const time: String; out ABegin, AEnd: Integer): Boolean; function GetSubtitle(Index: Integer): TSubtitle; procedure SetSubtitle(Index: Integer; const Value: TSubtitle); public constructor Create; destructor Destroy; override; function LoadFromFile(const filename: String): Boolean; function LoadUnicodeSubs(const filename: String): Boolean; function LoadFromStream(Stream: TStream): Boolean; function LoadFromStrings(Strings: TStrings): Boolean; function GetTextForTime(milisecs: Integer; out Text: String): Integer; procedure Clear; function GetTimeForIndex(Index: Integer; bStartTime: Boolean = True): Integer; function GetLastIndexForTime(millisecs: Integer): Integer; function Count: Integer; property Items[Index: Integer]: TSubtitle read GetSubtitle write SetSubtitle; default; end; implementation uses Misc; { TSubtitle } function TSubtitle.isInTime(pos1, pos2: Integer): Boolean; begin Result := (pos1 >= FBeginTime) AND (pos2 <= FEndTime); end; function TSubtitle.isInTime(time_pos: Integer): Boolean; begin Result := (time_pos >= FBeginTime) AND (time_pos <= FEndTime); end; { TSrtSubtitles } procedure TSrtSubtitles.Clear; var i: Integer; begin for i := 0 to FSubList.Count - 1 do begin TSubtitle(FSubList[i]).Free; FSubList[i] := nil; end; FSubList.Clear; end; function TSrtSubtitles.Count: Integer; begin Result := FSubList.Count; end; constructor TSrtSubtitles.Create; begin FSubList := TList.Create; end; destructor TSrtSubtitles.Destroy; begin try Clear; finally FSubList.Free; inherited; end; end; function TSrtSubtitles.GetLastIndexForTime(millisecs: Integer): Integer; var i: Integer; begin Result := -1; for i := 0 to FSubList.Count - 1 do begin if (TSubtitle(FSubList[i]).IntervalStart > millisecs) then begin Result := i - 1; Exit; end; end; Result := FSubList.Count - 1; end; function TSrtSubtitles.GetSubtitle(Index: Integer): TSubtitle; begin Result := FSubList[Index]; end; function TSrtSubtitles.GetTextForTime(milisecs: Integer; out Text: String): Integer; var i: Integer; begin Result := -1; Text := ''; for i := 0 to FSubList.Count - 1 do begin if TSubtitle(FSubList[i]).isInTime(milisecs) then begin Text := TSubtitle(FSubList[i]).Text; Result := i; Exit; end; end; end; function TSrtSubtitles.GetTimeForIndex(Index: Integer; bStartTime: Boolean): Integer; begin Result := -1; if (Index >= FSubList.Count) OR (Index < 0) then Exit; if bStartTime then Result := TSubtitle(FSubList[Index]).IntervalStart else Result := TSubtitle(FSubList[Index]).IntervalEnd; end; function TSrtSubtitles.LoadFromFile(const filename: String): Boolean; var ss: TStringList; begin Result := False; if NOT LoadUnicodeSubs(filename) then begin ss := TStringList.Create; try ss.LoadFromFile(filename); Result := LoadFromStrings(ss); finally ss.Free; end; end; end; function TSrtSubtitles.LoadFromStream(Stream: TStream): Boolean; var ss: TStringList; begin Result := False; ss := TStringList.Create; try ss.LoadFromStream(Stream); Result := LoadFromStrings(ss); finally ss.Free; end; end; function TSrtSubtitles.LoadFromStrings(Strings: TStrings): Boolean; const DELIMITER_SUB = ''; var i, u, v: Integer; sub: TSubtitle; ABegin, AEnd: Integer; begin (* SRT Subtitles SRT is perhaps the most basic of all subtitle formats. It consists of four parts, all in text.. 1. A number indicating the which subtitle it is in the sequence. 2. The time that the subtitle should appear on the screen, and then disappear. 3. The subtitle itself. 4. A blank line indicating the start of a new subtitle. When placing SRT in Matroska, part 3 is converted to UTF-8 and placed in the data portion of the Block. Part 2 is used to set the timecode of the Block, and BlockDuration element. Nothing else is used. Here is an example SRT file: --------------------------------------------------- 1 00:02:17,440 --> 00:02:20,375 Senator, we're making our final approach into Coruscant. 2 00:02:20,476 --> 00:02:22,501 Very good, Lieutenant. --------------------------------------------------- *) Result := False; Clear; i := 0; while i < Strings.Count do begin u := i; //locate position of next subs while (i < Strings.Count) do begin if (Strings[i] = DELIMITER_SUB) then if (i < Strings.Count - 1) AND (Strings[i + 1] <> DELIMITER_SUB) then Break; Inc(i); end; //if i >= Strings.Count then //i := Strings.Count - 1; sub := TSubtitle.Create; try sub.id := StrToInt(Strings[u]); except ShowMessage(Format('Error in subtitles: %d line', [u])); Inc(i); Continue; end; Inc(u); try if NOT ParseTimings(Strings[u], ABegin, AEnd) then raise Exception.Create('cannot parse subtitle timings: ' + Strings[u]); except ShowMessage(Format('Error in subtitles: %d line', [u])); end; if (ABegin >= AEnd) then begin //invalid subtitles - skip ShowMessage(Format('Invalid subtitles timing: %d line', [u])); Inc(i); Continue; end; sub.IntervalStart := ABegin; sub.IntervalEnd := AEnd; sub.Text := ''; Inc(u); for v := u to i - 1 do begin sub.Text := sub.Text + Strings[v] + ' '; end; FSubList.Add(sub); Inc(i); end; Result := True; end; function TSrtSubtitles.LoadUnicodeSubs(const filename: String): Boolean; var Stream: TFileStream; MemStream: TMemoryStream; wHeader: Word; Buffer: Word; wstr: WideString; len: Integer; ss: TStringList; begin //check size and header Stream := TFileStream.Create(filename, fmOpenRead); Result := False; try Stream.Position := 0; Stream.Read(wHeader, SizeOf(wHeader)); if (wHeader <> HEADER_UNICODE) OR (Stream.Size > MAX_SRT_FILESIZE) then begin Stream.Free; Stream := nil; Exit; end; //prepare len := Stream.Size - SizeOf(wHeader); SetLength(wstr, len div SizeOf(Word)); //parse file if Stream.Read(wstr[1], len) = len then begin ss := TStringList.Create; try ss.SetText(PAnsiChar(String(wstr))); Result := Self.LoadFromStrings(ss); finally ss.Free; end; end; finally Stream.Free; SetLength(wstr, 0); end; end; function TSrtSubtitles.ParseTimings(const time: String; out ABegin, AEnd: Integer): Boolean; const DELIMITER_TIME = ' --> '; var po: Integer; s: String; begin Result := False; po := Pos(DELIMITER_TIME, time); if po < 0 then Exit; ABegin := ConvertStrTimeToMilliseconds(Trim(Copy(time, 1, po)), '::,'); s := Trim(Copy(time, po + Length(DELIMITER_TIME), Length(time))); try AEnd := ConvertStrTimeToMilliseconds(s, '::,'); except //there also can be subs coordinates after space character //cut it s := Copy(s, 1, Pos(' ', s) - 1); AEnd := ConvertStrTimeToMilliseconds(s, '::,'); end; Result := True; end; procedure TSrtSubtitles.SetSubtitle(Index: Integer; const Value: TSubtitle); begin if Index < Count then begin TSubtitle(FSubList[Index]).Free; FSubList[Index] := Value; end else begin raise Exception.Create('SetSubtitle: Index >= Count'); end; end; end.
{ ****************************************************************************** } { * ObjectDB Stream by qq600585 * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } (* update history *) unit ItemStream; {$INCLUDE zDefine.inc} interface uses SysUtils, CoreClasses, Classes, UnicodeMixedLib, ObjectData, ObjectDataManager, PascalStrings; type TItemStream = class(TCoreClassStream) private DB_Engine: TObjectDataManager; ItemHnd_Ptr: PItemHandle; AutoFreeHnd: Boolean; protected function GetSize: Int64; override; public constructor Create(eng_: TObjectDataManager; DBPath, DBItem: SystemString); overload; constructor Create(eng_: TObjectDataManager; var ItemHnd: TItemHandle); overload; constructor Create(eng_: TObjectDataManager; const ItemHeaderPos: Int64); overload; destructor Destroy; override; procedure SaveToFile(fn: SystemString); procedure LoadFromFile(fn: SystemString); function read(var buffer; Count: longint): longint; override; function write(const buffer; Count: longint): longint; override; function Seek(Offset: longint; origin: Word): longint; overload; override; function Seek(const Offset: Int64; origin: TSeekOrigin): Int64; overload; override; function CopyFrom64(const Source: TCoreClassStream; Count: Int64): Int64; procedure SeekStart; procedure SeekLast; function UpdateHandle: Boolean; function CloseHandle: Boolean; property Hnd: PItemHandle read ItemHnd_Ptr; end; implementation function TItemStream.GetSize: Int64; begin Result := DB_Engine.ItemGetSize(ItemHnd_Ptr^); end; constructor TItemStream.Create(eng_: TObjectDataManager; DBPath, DBItem: SystemString); begin inherited Create; DB_Engine := eng_; New(ItemHnd_Ptr); eng_.ItemAutoOpenOrCreate(DBPath, DBItem, DBItem, ItemHnd_Ptr^); AutoFreeHnd := True; end; constructor TItemStream.Create(eng_: TObjectDataManager; var ItemHnd: TItemHandle); begin inherited Create; DB_Engine := eng_; ItemHnd_Ptr := @ItemHnd; AutoFreeHnd := False; end; constructor TItemStream.Create(eng_: TObjectDataManager; const ItemHeaderPos: Int64); begin inherited Create; DB_Engine := eng_; New(ItemHnd_Ptr); eng_.ItemFastOpen(ItemHeaderPos, ItemHnd_Ptr^); AutoFreeHnd := True; end; destructor TItemStream.Destroy; begin UpdateHandle(); if AutoFreeHnd then begin Dispose(ItemHnd_Ptr); ItemHnd_Ptr := nil; end; inherited Destroy; end; procedure TItemStream.SaveToFile(fn: SystemString); var stream: TCoreClassStream; begin stream := TCoreClassFileStream.Create(fn, fmCreate); try stream.CopyFrom(Self, Size); finally DisposeObject(stream); end; end; procedure TItemStream.LoadFromFile(fn: SystemString); var stream: TCoreClassStream; begin stream := TCoreClassFileStream.Create(fn, fmOpenRead or fmShareDenyNone); try CopyFrom(stream, stream.Size); finally DisposeObject(stream); end; end; function TItemStream.read(var buffer; Count: longint): longint; var _P: Int64; _Size: Int64; begin Result := 0; if (Count > 0) then begin _P := DB_Engine.ItemGetPos(ItemHnd_Ptr^); _Size := DB_Engine.ItemGetSize(ItemHnd_Ptr^); if _P + Count <= _Size then begin if DB_Engine.ItemRead(ItemHnd_Ptr^, Count, PByte(@buffer)^) then Result := Count; end else if DB_Engine.ItemRead(ItemHnd_Ptr^, _Size - _P, PByte(@buffer)^) then Result := _Size - _P; end; end; function TItemStream.write(const buffer; Count: longint): longint; begin Result := Count; if (Count > 0) then if not DB_Engine.ItemWrite(ItemHnd_Ptr^, Count, PByte(@buffer)^) then begin Result := 0; end; end; function TItemStream.Seek(Offset: longint; origin: Word): longint; begin case origin of soFromBeginning: begin DB_Engine.ItemSeek(ItemHnd_Ptr^, Offset); end; soFromCurrent: begin if Offset <> 0 then DB_Engine.ItemSeek(ItemHnd_Ptr^, DB_Engine.ItemGetPos(ItemHnd_Ptr^) + Offset); end; soFromEnd: begin DB_Engine.ItemSeek(ItemHnd_Ptr^, DB_Engine.ItemGetSize(ItemHnd_Ptr^) + Offset); end; end; Result := DB_Engine.ItemGetPos(ItemHnd_Ptr^); end; function TItemStream.Seek(const Offset: Int64; origin: TSeekOrigin): Int64; begin case origin of TSeekOrigin.soBeginning: begin DB_Engine.ItemSeek(ItemHnd_Ptr^, Offset); end; TSeekOrigin.soCurrent: begin if Offset <> 0 then DB_Engine.ItemSeek(ItemHnd_Ptr^, DB_Engine.ItemGetPos(ItemHnd_Ptr^) + Offset); end; TSeekOrigin.soEnd: begin DB_Engine.ItemSeek(ItemHnd_Ptr^, DB_Engine.ItemGetSize(ItemHnd_Ptr^) + Offset); end; end; Result := DB_Engine.ItemGetPos(ItemHnd_Ptr^); end; function TItemStream.CopyFrom64(const Source: TCoreClassStream; Count: Int64): Int64; const MaxBufSize = $F000; var BufSize, N: Int64; buffer: PByte; begin if Count <= 0 then begin Source.Position := 0; Count := Source.Size; end; Result := Count; if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count; buffer := System.GetMemory(BufSize); try while Count <> 0 do begin if Count > BufSize then N := BufSize else N := Count; Source.ReadBuffer(buffer^, N); WriteBuffer(buffer^, N); Dec(Count, N); end; finally System.FreeMem(buffer); end; end; procedure TItemStream.SeekStart; begin DB_Engine.ItemSeekStart(ItemHnd_Ptr^); end; procedure TItemStream.SeekLast; begin DB_Engine.ItemSeekLast(ItemHnd_Ptr^); end; function TItemStream.UpdateHandle: Boolean; begin if DB_Engine.IsOnlyRead then Result := False else Result := DB_Engine.ItemUpdate(ItemHnd_Ptr^); end; function TItemStream.CloseHandle: Boolean; begin Result := DB_Engine.ItemClose(ItemHnd_Ptr^); end; end.
{..............................................................................} { Summary Demo the use of Schematic Font Manager interface. } { Copyright (c) 2003 by Altium Limited } {..............................................................................} {..............................................................................} Interface Type TForm_FontsEditor = class(TForm) tvObjects : TTreeView; ImageList1 : TImageList; btnSelectAll : TButton; btnClearAll : TButton; txtFont : TEdit; Label1 : TLabel; btnSelectFont : TButton; Label2 : TLabel; txtRotation : TEdit; btnSet : TButton; FontDialog : TFontDialog; Button3 : TButton; procedure tvObjectsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure btnSetClick(Sender: TObject); procedure btnSelectAllClick(Sender: TObject); procedure btnSelectFontClick(Sender: TObject); procedure btnClearAllClick(Sender: TObject); End; {..............................................................................} var Form_FontsEditor: TForm_FontsEditor; {..............................................................................} Implementation {$R *.DFM} Const iiChecked = 1; Var SchFont : TFont; {..............................................................................} {..............................................................................} Function IsObjectOk(Obj : ISch_BasicContainer) : Boolean; Var ObjectID : TObjectID; Begin ObjectID := Obj.ObjectId; Case ObjectID Of eLabel, eTextFrame, eNetLabel, ePowerObject, eCrossSheetConnector, eParameter, eSheetFileName, eSheetName, eDesignator : Result := True Else Result := False; End; End; {..............................................................................} {..............................................................................} Function BuildFontStyleString(Bold, Italic, Underline, StrikeOut : Boolean) : String; Begin Result := ''; If Bold Then Result := Result + ' Bold'; If Italic Then Result := Result + ' Italic'; If Underline Then Result := Result + ' Underline'; If StrikeOut Then Result := Result + ' StrikeOut'; End; {..............................................................................} {..............................................................................} Function GetFontString(FontManager : ISch_FontManager; FontID : TFontID) : String; Var Size : Integer; Rotation : Integer; Underline : Boolean; Italic : Boolean; Bold : Boolean; StrikeOut : Boolean; FontName : String; Begin FontManager.GetFontSpec(FontID, Size, Rotation, Underline, Italic, Bold, StrikeOut, FontName); Result := Format('%s %d %d deg%s', [FontName, Size, Rotation, BuildFontStyleString(Bold, Italic, Underline, StrikeOut)]); End; {..............................................................................} {..............................................................................} Function FindNode(ObjectID : TObjectID) : TTreeNode; Var List : TList; Begin Result := tvObjects.Items.GetFirstNode; While Result <> Nil Do Begin List := Result.Data; If List[0].ObjectID = ObjectID Then Exit; Result := Result.GetNextSibling; End; Result := Nil; End; {..............................................................................} {..............................................................................} Function GetObjectText(Obj : ISchBasicContainer; FontManager : ISch_FontManager) : String; Begin Result := Format('%s (%s)', [Obj.GetState_Text, GetFontString(FontManager, Obj.FontID)]); End; {..............................................................................} {..............................................................................} Procedure AddObject(Obj : ISch_BasicContainer; FontManager : ISch_FontManager); Var Node : TTreeNode; ObjectID : TObjectID; List : TList; Begin ObjectID := Obj.ObjectID; Node := FindNode(ObjectID); If Node = Nil Then Begin List := TList.Create; Node := tvObjects.Items.Add(Nil, GetStateString_ObjectId(ObjectID)); Node.Data := List; End Else List := Node.Data; List.Add(Obj); Node := tvObjects.Items.AddChild(Node, GetObjectText(Obj, FontManager)); Node.Data := Obj; End; {..............................................................................} {..............................................................................} Procedure CollectInfo(Dummy : Integer = 0);; Var Server : ISchServer; Document : ISch_Document; Iterator : ISch_Iterator; Obj : ISch_BasicContainer; FontManager : ISch_FontManager; Begin Server := SchServer; If Server = Nil Then Begin ShowError('No SchServer started'); Exit; End; Document := SchServer.GetCurrentSchDocument; If Document = Nil Then Begin ShowError('Current document is not SCH document'); Exit; End; FontManager := SchServer.FontManager; Iterator := Document.SchIterator_Create; Obj := Iterator.FirstSchObject; While Obj <> Nil Do Begin If IsObjectOk(Obj) Then AddObject(Obj, FontManager); Obj := Iterator.NextSchObject; End; End; {..............................................................................} {..............................................................................} Function BuildFontStylesText(Font : TFont) : String; Var FontStyle : TFontStyles; Begin FontStyle := Font.Style; Result := BuildFontStyleString(InSet(fsBold, FontStyle), InSet(fsItalic, FontStyle), InSet(fsUnderline, FontStyle), InSet(fsStrikeOut, FontStyle)); End; {..............................................................................} {..............................................................................} Procedure UpdateFont(Dummy : Integer = 0);; Begin Form_FontsEditor.txtFont.Text := Format('%s %d%s',[SchFont.Name, SchFont.Size, BuildFontStylesText(SchFont)]); End; {..............................................................................} {..............................................................................} Procedure InitFont(Dummy : Integer = 0); Begin SchFont := TFont.Create; SchFont.Assign(Form_FontsEditor.Font); UpdateFont; End; {..............................................................................} {..............................................................................} Procedure RunDialog; Begin CollectInfo; InitFont; Form_FontsEditor.ShowModal; End; {..............................................................................} {..............................................................................} Procedure TForm_FontsEditor.tvObjectsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Var Pt : TPoint; HitTests : THitTests; Node : TTreeNode; ARect : TRect; Begin Pt := Mouse.CursorPos; Pt := tvObjects.ScreenToClient(Pt); HitTests := tvObjects.GetHitTestInfoAt(Pt.X, Pt.Y); If InSet(htOnIcon, HitTests) Then Begin Node := tvObjects.GetNodeAt(Pt.X, Pt.Y); If Node.SelectedIndex = 0 Then Node.SelectedIndex := 1 Else Node.SelectedIndex := 0; Node.ImageIndex := Node.SelectedIndex; ARect := Node.DisplayRect(False); tvObjects.Invalidate; End; End; {..............................................................................} {..............................................................................} Procedure AddChildItems(Node : TTreeNode; ForceAdd : Boolean; List : TList); Begin Node := Node.GetFirstChild; While Node <> Nil Do Begin If ForceAdd Or (Node.ImageIndex = iiChecked) Then List.Add(Node); Node := Node.GetNextSibling; End; End; {..............................................................................} {..............................................................................} Procedure BuildObjectList(List : TList); Var Node : TTreeNode; Begin Node := tvObjects.Items.GetFirstNode; While Node <> Nil Do Begin AddChildItems(Node, Node.ImageIndex = iiChecked, List); Node := Node.GetNextSibling; End; End; {..............................................................................} {..............................................................................} Procedure UpdateObjects(List : TList; FontID : TFontID; FontManager : ISch_FontManager); Var I : Integer; Node : TTreeNode; Obj : ISch_BasicContainer; Begin For I := 0 To List.Count - 1 Do Begin Node := List[I]; Obj := Node.Data; Obj.FontID := FontID; Node.Text := GetObjectText(Obj, FontManager); Obj.GraphicallyInvalidate; End; End; {..............................................................................} {..............................................................................} Procedure TForm_FontsEditor.btnSetClick(Sender: TObject); Var Rotation : Integer; Server : ISchServer; FontManager : ISch_FontManager; FontID : Integer; List : TList; Begin Rotation := StrToIntDef(txtRotation.Text, -1); If Rotation < 0 Then Begin ShowError('Rotation have to be valid positive value.'); Exit; End; List := TList.Create; Try BuildObjectList(List); Server := SchServer; FontManager := SchServer.FontManager; FontID := FontManager.GetFontID(SchFont.Size, Rotation, InSet(fsUnderline, SchFont.Style), InSet(fsItalic, SchFont.Style), InSet(fsBold, SchFont.Style), InSet(fsStrikeOut, SchFont.Style), SchFont.Name); UpdateObjects(List, FontID, FontManager); Finally List.Free; End; End; {..............................................................................} {..............................................................................} Procedure SelectClear(Index : Integer); Var Node : TTreeNode; begin Node := tvObjects.Items.GetFirstNode; While Node <> Nil Do Begin Node.ImageIndex := Index; Node.SelectedIndex := Node.ImageIndex; Node := Node.GetNext; End; tvObjects.Invalidate; End; {..............................................................................} {..............................................................................} Procedure TForm_FontsEditor.btnSelectAllClick(Sender: TObject); Begin SelectClear(iiChecked); End; {..............................................................................} {..............................................................................} Procedure TForm_FontsEditor.btnSelectFontClick(Sender: TObject); Begin FontDialog.Font.Assign(SchFont); If FontDialog.Execute Then Begin SchFont.Assign(FontDialog.Font); UpdateFont; End; End; {..............................................................................} {..............................................................................} Procedure TForm_FontsEditor.btnClearAllClick(Sender: TObject); Begin SelectClear(0); End; {..............................................................................} {..............................................................................} End.
unit uMain; {$mode delphi}{$H+} interface uses uFont, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, EditBtn, Spin; type { TForm1 } TForm1 = class(TForm) bChooseFont: TButton; bLoadFont: TButton; bChooseFilePath: TButton; bGenerate: TButton; bSave: TButton; cbBold: TCheckBox; cbItalic: TCheckBox; editFontName: TEdit; editFilePath: TEdit; editSize: TSpinEdit; FontDialog: TFontDialog; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Label1: TLabel; Label2: TLabel; labelSize: TLabel; mSymbols: TMemo; OpenDialog: TOpenDialog; Panel1: TPanel; procedure bChooseFontClick(Sender: TObject); procedure bGenerateClick(Sender: TObject); procedure bLoadFontClick(Sender: TObject); procedure bSaveClick(Sender: TObject); procedure editFontNameChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FontGen: TFontGenerator; end; var Form1: TForm1; implementation {$R *.lfm} uses Windows; { TForm1 } procedure TForm1.bChooseFontClick(Sender: TObject); begin if FontDialog.Execute() then begin editFontName.Text := FontDialog.Font.Name; cbBold.Checked := FontDialog.Font.Bold; cbItalic.Checked := FontDialog.Font.Italic; editSize.Value := FontDialog.Font.Size; end; end; procedure TForm1.bGenerateClick(Sender: TObject); var g: Graphics.TBitmap; s: TStream; (* p_in, p_out: Pointer; size: LongInt; f: File; *) begin if (Trim(editFontName.Text) = '') then begin ShowMessage('Font name is empty'); Exit; end; FontGen.GenFree(); FontGen.ClearChars(); FontGen.GenInit(editFontName.Text, editSize.Value, cbBold.Checked, cbItalic.Checked); FontGen.AddChars(UTF8Decode(mSymbols.Lines.Text)); FontGen.PackChars(); labelSize.Caption := 'Size: ' + IntToStr(FontGen.TexWidth) + 'x' + IntToStr(FontGen.TexHeight); g := Graphics.TBitmap.Create(); s := FontGen.SaveBmpToStream(); s.Position := 0; g.LoadFromStream(s, s.Size); Panel1.Canvas.Brush.Color := clDefault; Panel1.Canvas.Clear(); Panel1.Canvas.Brush.Color := clBlack; Panel1.Canvas.FillRect(0, 0, FontGen.TexWidth, FontGen.TexHeight); Panel1.Canvas.Draw(0, 0, g); (* //compress GetMem(p_in, s.Size); s.Position := 0; s.Read(p_in^, s.Size); CompressData(p_in, s.Size, p_out, size); AssignFile(f, editFilePath.Text + '.fnt'); Rewrite(f, 1); BlockWrite(f, p_out^, size); CloseFile(f); FreeMem(p_in); FreeMem(p_out); *) g.Free(); s.Free(); end; function AddFontResourceEx(name: LPCSTR; fl: LongWord; pdv: Pointer): longint; stdcall; external 'gdi32' name 'AddFontResourceExA'; procedure TForm1.bLoadFontClick(Sender: TObject); var p: PChar; begin if (OpenDialog.Execute) then begin p := PChar(AnsiString(OpenDialog.FileName)); if (AddFontResourceEx(p, 16, nil) = 0) then ShowMessage('Font loading failed!') else begin editFontName.Text := ExtractFileNameOnly(OpenDialog.FileName); ShowMessage('Font loading successful. Do not forget to edit font name. Generator specify file name as font name'); end; end; end; procedure TForm1.bSaveClick(Sender: TObject); (* var f: File; p_in, p_out: Pointer; size: LongInt; *) begin FontGen.SaveBmpToFile(editFilePath.Text); (* //decompress and save AssignFile(f, editFilePath.Text + '.fnt'); Reset(f, 1); size := FileSize(editFilePath.Text + '.fnt'); GetMem(p_in, size); GetMem(p_out, size * 100); BlockRead(f, p_in^, size); CloseFile(f); DecompressData(p_in, size, p_out, size); AssignFile(f, editFilePath.Text + '1.bmp'); Rewrite(f, 1); BlockWrite(f, p_out^, size); CloseFile(f); FreeMem(p_in); FreeMem(p_out); *) end; procedure TForm1.editFontNameChange(Sender: TObject); var name, path: String; begin name := ExtractFileName(editFilePath.Text); path := ExtractFilePath(editFilePath.Text); name := editFontName.Text + IntToStr(editSize.Value); if (cbBold.Checked) then name += 'b'; if (cbItalic.Checked) then name += 'i'; editFilePath.Text := path + name; end; procedure TForm1.FormCreate(Sender: TObject); begin FontGen := TFontGenerator.Create(); editFilePath.Text := ExtractFileDir(ParamStr(0)) + '\'; editFontName.Text := 'Arial'; cbBold.Checked := True; cbItalic.Checked := False; editSize.Value := 12; OpenDialog.InitialDir := ExtractFileDir(ParamStr(0)) + '\'; end; procedure TForm1.FormDestroy(Sender: TObject); begin FontGen.Free(); end; end.
unit antrikanU; interface uses System.Classes, Winapi.MMSystem, System.SysUtils, System.StrUtils, Vcl.Dialogs; type Antrian = class private fAntri : Integer; fLoket : Integer; suaraFile : TStringList; dbFile : TStringList; procedure masukkan_bawah12(angka : Integer); procedure masukkan_belasan(angka : Integer); procedure masukkan_bawah100(angka : Integer); procedure masukkan_bawah200(angka : Integer); procedure masukkan_bawah1000(angka : Integer); procedure susunFileAntri(i : integer); public procedure mainkan; constructor create(antri : Integer; loket : Integer); destructor destroy; end; implementation { Antrian } procedure Antrian.masukkan_bawah200(angka: Integer); var sisa : Integer; begin sisa := angka - 100; if angka = 100 then suaraFile.Add('seratus.wav') else begin suaraFile.Add('seratus.wav'); if sisa < 12 then masukkan_bawah12(sisa) else if sisa < 20 then masukkan_belasan(sisa) else masukkan_bawah100(sisa); end; end; procedure Antrian.masukkan_bawah12(angka: Integer); begin suaraFile.Add(dbFile[angka-1]); end; procedure Antrian.masukkan_bawah100(angka: Integer); var satuan : Integer; puluhan : Integer; strAngka : string; begin puluhan := angka div 10; masukkan_bawah12(puluhan); suaraFile.Add('puluh.wav'); satuan := angka mod 10; if (satuan > 0) then masukkan_bawah12(satuan); end; procedure Antrian.masukkan_bawah1000(angka: Integer); var ratusan, sisa : Integer; begin ratusan := angka div 100; masukkan_bawah12(ratusan); suaraFile.Add('ratus.wav'); sisa := angka mod 100; if sisa > 0 then begin if sisa < 12 then masukkan_bawah12(sisa) else if sisa < 20 then masukkan_belasan(sisa) else if sisa < 100 then masukkan_bawah100(sisa) else if sisa < 200 then masukkan_bawah200(sisa); end; end; procedure Antrian.masukkan_belasan(angka: Integer); begin masukkan_bawah12(angka - 10); suaraFile.Add('belas.wav'); end; constructor Antrian.create(antri, loket: Integer); begin inherited create(); fAntri := antri; fLoket := loket; suaraFile := TStringList.Create; suaraFile.Add('nomor-urut.wav'); dbFile := TStringList.Create; dbFile.Add('satu.wav'); dbFile.Add('dua.wav'); dbFile.Add('tiga.wav'); dbFile.Add('empat.wav'); dbFile.Add('lima.wav'); dbFile.Add('enam.wav'); dbFile.Add('tujuh.wav'); dbFile.Add('delapan.wav'); dbFile.Add('sembilan.wav'); dbFile.Add('sepuluh.wav'); dbFile.Add('sebelas.wav'); dbFile.Add('belas.wav'); dbFile.Add('puluh.wav'); dbFile.Add('ratus.wav'); susunFileAntri(fAntri); suaraFile.Add('loket.wav'); susunFileAntri(fLoket); end; destructor Antrian.destroy; begin suaraFile.Free; inherited destroy; end; procedure Antrian.mainkan; var i : Integer; begin //ShowMessage(IntToStr(suaraFile.Count)); for I := 0 to suaraFile.Count-1 do begin //ShowMessage(suaraFile[i]); sndPlaySound(PWideChar('Sounds\'+suaraFile[i]), SND_NOSTOP); //Sleep(1000); end; end; procedure Antrian.susunFileAntri(i: integer); begin if i < 12 then masukkan_bawah12(i) else if i < 20 then masukkan_belasan(i) else if i < 100 then masukkan_bawah100(i) else if i < 200 then masukkan_bawah200(i) else masukkan_bawah1000(i); end; end.
unit uBobbyClasses; interface uses Classes, SysUtils, ODEImport, math; const cLIQUID_DENSITY = 3; cGRAVITY = -9.91; type TBobby = class; TBobbyHandler = class; // TBobby is a particle that handles buoyancy. It bobs in the water, hence // the name TOnGetDepthAndNormal = procedure (Bobby: TBobby) of object; TBobby = class // The position of the Bobby, relative to the body. This will be modified // by the bobbys location and rotation Position : TdVector3; // TotalVolume is stored to speed up calculations. It's updated whenever // radius is altered TotalVolume : single; // Keeps track of how much of the bobbys volume is in submerged SubmergedVolume : single; // A Bobby must be connected to a body that it can act upon Body : PdxBody; // The current depth of the bobby CenterDepth : single; // WaterNormal is a vector that describes the normal of the water at the // location of the bobby WaterNormal : TdVector3; // This is the force as it has been calculated by the bobby, depending on // the displacement BuoyancyForce : TdVector3; // This is the position that the force acts upon BuoyancyForceCenter : TdVector3; // BobbyHandler is responsible for handling this bobby BobbyHandler : TBobbyHandler; // WorldPosition holds the world position of the bobby WorldPosition : TdVector3; // OldWorldPosition is used to calculate where the Bobby was before, for // calculating drag OldWorldPosition : TdVector3; // DragForce is the drag that the bobby feels due to it's speed in the // liquid. If the bobby isn't submerged, the drag is zero DragForce : TdVector3; BobbySpeed : TdVector3; // DragCoefficient is used to calculate drag forces DragCoefficient : single; // SurfaceArea is the area of the surface SurfaceArea : single; // SubmergedSurfaceArea is the area that's submerged SubmergedSurfaceArea : single; // Update procedure Update(DeltaTime : single); // UpdateWorldPosition updates the world position procedure UpdateWorldPosition; procedure UpdateSpeed(DeltaTime : single); // Calculate the drag force procedure CalcDragForce; // Calculate the magnitude and direction of the buoyancy force procedure CalcBuoyancyForce; // Apply the buoyancy force to the body procedure ApplyForces; constructor Create(BobbyHandler : TBobbyHandler); destructor Destroy; override; private FRadius: single; procedure SetRadius(const Value: single); public // The Radius of the bobby determines it's buoyancy. The amount of liquid // it displaces is the same as the volume property Radius : single read FRadius write SetRadius; end; TBobbyList = class(TList) private function GetItems(i: integer): TBobby; procedure SetItems(i: integer; const Value: TBobby); public property Items[i : integer] : TBobby read GetItems write SetItems; default; end; TBobbyHandler = class private FOnGetDepthAndNormal: TOnGetDepthAndNormal; procedure SetOnGetDepthAndNormal(const Value: TOnGetDepthAndNormal); public // Bobbies is a list of all handled bobbies (duh!) Bobbies : TBobbyList; // LiquidDensity determines the density of the liquid that the bobby is // suspended in LiquidDensity : single; // Gravity determines how much the mass of the water weights. This should // be the same gravity as ODE uses. Gravity : TdVector3; // AddBobby adds a new bobby to the bobbies list procedure AddBobby(Bobby : TBobby); // AddBobby removes a bobby to the bobbies list procedure RemoveBobby(Bobby : TBobby); // Free all bobbies and clear the list procedure ClearBobbies; // UpdateBobbies will // * Update each bobby world position // * Call GetDepthAndNormal with each bobby // * Calculate the buoyancy forces // * Calculate the drag forces // * Add the forces to the bodies procedure UpdateBobbies(DeltaTime : single); property OnGetDepthAndNormal : TOnGetDepthAndNormal read FOnGetDepthAndNormal write SetOnGetDepthAndNormal; function GetSubmergedAmount : single; constructor Create; destructor Destroy; override; end; function SphereCapVolume(const SphereRadius, CapHeight : single) : single; function SphereCapCentroidHeight(SphereRadius, CapHeight : single) : single; function SubmergedSphereCapVolume(const SphereRadius, CenterDepth : single) : single; function SubmergedSphereCapCentroidHeight(SphereRadius, CenterDepth : single) : single; implementation const c4PiDiv3 = 4 * pi / 3; cPiDiv3 = pi / 3; function SphereCapVolume(const SphereRadius, CapHeight : single) : single; begin // Calculates the volume of a sphere cap, as clipped by a plane // SphereRadius is the radius of the sphere // CapHeight is the height from the _TOP_ of the sphere to the clipping plane { See http://mathworld.wolfram.com/SphericalCap.html and http://mathforum.org/dr.math/faq/formulas/faq.sphere.html and http://mathforum.org/library/drmath/view/55253.html V_cap = 2/3 pi r^2 h - 1/3 pi (2rh - h^2)(r - h) = 2/3 pi r^2 h - 1/3 pi (2r^2h - 3rh^2 +h^3) = 1/3 pi h [2r^2 - 2r^2 + 3rh - h^2] = 1/3 pi h (3rh - h^2) *** Both sources seem to agree ;) } Assert(Abs(CapHeight)<=2 * SphereRadius, Format('Cap must be smaller than sphere diameter, Abs(%f) > 2 * %f!',[CapHeight, SphereRadius]));//} // Calculate the volume result := cPiDiv3 * CapHeight * (3 * SphereRadius * CapHeight - CapHeight * CapHeight) end; function SphereCapCentroidHeight(SphereRadius, CapHeight : single) : single; begin // This function from http://mathworld.wolfram.com/SphericalCap.html, // (Harris and Stocker 1998, p. 107). Assert(Abs(CapHeight)<=2 * SphereRadius, Format('Cap must be smaller than sphere diameter, Abs(%f) > 2 * %f!',[CapHeight, SphereRadius]));//} result := 3*sqr(2 * SphereRadius - CapHeight)/(4 * (3 * SphereRadius - CapHeight)); end; function SubmergedSphereCapVolume(const SphereRadius, CenterDepth : single) : single; begin // Is it not submerged at all? if CenterDepth >= SphereRadius then result := 0 // Is it fully submerged? else if CenterDepth <= -SphereRadius then result := c4PiDiv3 * SphereRadius * SphereRadius * SphereRadius else // Partially submerged, the amount submerged is calculated by the cap volume result := SphereCapVolume(SphereRadius, SphereRadius - CenterDepth ); end; function SubmergedSphereCapCentroidHeight(SphereRadius, CenterDepth : single) : single; begin // Is it not submerged at all? If it's not submerged, it has no centroid! if CenterDepth >= SphereRadius then result := 0 // Is it fully submerged? else if CenterDepth <= -SphereRadius then result := 0 else // Partially submerged, the amount submerged is calculated by the cap volume result := -SphereCapCentroidHeight(SphereRadius, (SphereRadius - CenterDepth)); end; { TBobby } procedure TBobby.ApplyForces; begin Assert(Assigned(Body),'Bobby has no body!'); dBodyAddForceAtPos(Body, BuoyancyForce[0] + DragForce[0], BuoyancyForce[1] + DragForce[1], BuoyancyForce[2] + DragForce[2], BuoyancyForceCenter[0], BuoyancyForceCenter[1], BuoyancyForceCenter[2]); end; procedure TBobby.CalcBuoyancyForce; var DisplacementMass : single; Depth : single; g : single; begin // PLEASE NOTE: This function currently only handles gravity that lies along // z! // Make sure there's a body to apply the force to Assert(Assigned(Body),'Bobby has no body!'); // The force center will go through the center of the Bobby, but it will be // moved ackording to the normal of the water and the depth of the water // around the bobby Depth := SubmergedSphereCapCentroidHeight(Radius, CenterDepth); BuoyancyForceCenter[0] := WorldPosition[0] + Depth * WaterNormal[0]; BuoyancyForceCenter[1] := WorldPosition[1] + Depth * WaterNormal[1]; BuoyancyForceCenter[2] := WorldPosition[2] + Depth * WaterNormal[2];//} // Calculate displaced volume SubmergedVolume := SubmergedSphereCapVolume(Radius, CenterDepth); if SubmergedVolume = 0 then SubmergedSurfaceArea := 0 else if CenterDepth<-Radius then SubmergedSurfaceArea := SurfaceArea else SubmergedSurfaceArea := SurfaceArea * (Radius * 2 - CenterDepth); // Calculate displacement mass DisplacementMass := SubmergedVolume * BobbyHandler.LiquidDensity; // The lifting force is always opposing gravity BuoyancyForce[0] := - BobbyHandler.Gravity[0] * DisplacementMass; BuoyancyForce[1] := - BobbyHandler.Gravity[1] * DisplacementMass; BuoyancyForce[2] := - BobbyHandler.Gravity[2] * DisplacementMass;//} g := BobbyHandler.Gravity[0]; if abs(BobbyHandler.Gravity[1]) > abs(g) then g := BobbyHandler.Gravity[1]; if abs(BobbyHandler.Gravity[2]) > abs(g) then g := BobbyHandler.Gravity[2]; // The sideways moving force is proportional to the slope of the water normal if (BobbyHandler.Gravity[0]=0) then BuoyancyForce[0] := BuoyancyForce[0] - WaterNormal[0] * DisplacementMass * g; if (BobbyHandler.Gravity[1]=0) then BuoyancyForce[1] := BuoyancyForce[1] - WaterNormal[1] * DisplacementMass * g; if (BobbyHandler.Gravity[2]=0) then BuoyancyForce[2] := BuoyancyForce[2] - WaterNormal[2] * DisplacementMass * g;//} end; procedure TBobby.CalcDragForce; var ForceMagnitude : single; Speed, Speed2 : single; begin // If this is the first time, ignore drag! if OldWorldPosition[0] = -10e5 then exit; // If the bobby isn't submerged, the force is zero if SubmergedVolume=0 then begin DragForce[0] := 0; DragForce[1] := 0; DragForce[2] := 0; exit; end; Speed2 := (sqr(BobbySpeed[0]) + sqr(BobbySpeed[1]) + sqr(BobbySpeed[2])); Speed := sqrt(Speed2); // Fd = Cd / 2 * p * V^2 * A // Cd = Drag coefficient // p = density of medium // v = flow speed // A = cross sectional area ForceMagnitude := - DragCoefficient / 2 * BobbyHandler.LiquidDensity * Speed2 * SubmergedSurfaceArea; // Preset drag force to a normalized version of bobby speed DragForce[0] := BobbySpeed[0] / Speed * ForceMagnitude; DragForce[1] := BobbySpeed[1] / Speed * ForceMagnitude; DragForce[2] := BobbySpeed[2] / Speed * ForceMagnitude; end; constructor TBobby.Create(BobbyHandler: TBobbyHandler); begin self.BobbyHandler := BobbyHandler; BobbyHandler.AddBobby(self); // Note that the bobby hasn't ever had a position before, so that the speed // calculation doesn't come out bonkers WorldPosition[0] := -10e5; OldWorldPosition[0] := -10e5; DragCoefficient := 1.5; end; destructor TBobby.Destroy; begin BobbyHandler.RemoveBobby(self); inherited; end; procedure TBobby.SetRadius(const Value: single); begin FRadius := Value; TotalVolume := 4 / 3 * pi * Value * Value * Value; SurfaceArea := pi * sqr(Value); end; procedure TBobby.Update(DeltaTime : single); begin // If the body that the bobby is connected to is disabled, then we can jump out // here if (dBodyIsEnabled(Body)=0) then exit; // * Update bobby world position UpdateWorldPosition; // * Update bobby speed UpdateSpeed(DeltaTime); // * Call GetDepthAndNormal with each bobby BobbyHandler.OnGetDepthAndNormal(self); // * Calculate the buoyancy forces CalcBuoyancyForce; // * Calculate the drag forces CalcDragForce; // * Add the forces to the bodies ApplyForces; end; procedure TBobby.UpdateSpeed(DeltaTime: single); begin // Also update the speed of the bobby BobbySpeed[0] := (WorldPosition[0] - OldWorldPosition[0]) / DeltaTime; BobbySpeed[1] := (WorldPosition[1] - OldWorldPosition[1]) / DeltaTime; BobbySpeed[2] := (WorldPosition[2] - OldWorldPosition[2]) / DeltaTime; end; procedure TBobby.UpdateWorldPosition; var pos : PdVector3; begin OldWorldPosition := WorldPosition; // First, calculate the actual center of the bobby dBodyVectorToWorld(Body, Position[0], Position[1], Position[2], WorldPosition); pos := dBodyGetPosition(Body); Assert(abs(pos[2])>-10e10 , Format('Bad body position : %f, %f, %f',[pos[0], pos[1], pos[2]])); WorldPosition[0] := WorldPosition[0] + Pos[0]; WorldPosition[1] := WorldPosition[1] + Pos[1]; WorldPosition[2] := WorldPosition[2] + Pos[2]; end; { TBobbyHandler } procedure TBobbyHandler.AddBobby(Bobby: TBobby); begin Bobbies.Add(Bobby); end; procedure TBobbyHandler.ClearBobbies; begin try while Bobbies.Count>0 do Bobbies[Bobbies.Count-1].Free; finally Bobbies.Clear; end; end; constructor TBobbyHandler.Create; begin Bobbies := TBobbyList.Create; LiquidDensity := cLIQUID_DENSITY; Gravity[0] := 0; Gravity[1] := 0; Gravity[2] := cGRAVITY; end; destructor TBobbyHandler.Destroy; begin ClearBobbies; FreeAndNil(Bobbies); inherited; end; function TBobbyHandler.GetSubmergedAmount: single; var i : integer; TotVolume, TotSubmergedVolume : single; begin TotVolume := 0; TotSubmergedVolume := 0; for i := 0 to Bobbies.Count-1 do with Bobbies[i] do begin TotVolume := TotVolume + TotalVolume; TotSubmergedVolume := TotSubmergedVolume + SubmergedVolume; end; if TotVolume = 0 then result := 0 else result := TotSubmergedVolume / TotVolume; end; procedure TBobbyHandler.RemoveBobby(Bobby: TBobby); begin Bobbies.Remove(Bobby); end; procedure TBobbyHandler.SetOnGetDepthAndNormal( const Value: TOnGetDepthAndNormal); begin FOnGetDepthAndNormal := Value; end; procedure TBobbyHandler.UpdateBobbies(DeltaTime : single); var i : integer; Bobby : TBobby; begin Assert(Assigned(OnGetDepthAndNormal),'OnGetDepthAndNormal must be assigned!'); for i := 0 to Bobbies.Count-1 do begin // Retrieve the bobby for easy access Bobby := Bobbies[i]; // Update the bobby Bobby.Update(DeltaTime); end; end; { TBobbyList } function TBobbyList.GetItems(i: integer): TBobby; begin result := Get(i); end; procedure TBobbyList.SetItems(i: integer; const Value: TBobby); begin Put(i, Value); end; end.
unit NewFrontiers.GUI.BindingTarget; interface uses NewFrontiers.GUI.Binding, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, System.Rtti, System.Classes, SysUtils; type TBindingTargetProperty = class(TBindingTarget) protected procedure setTarget(const Value: TObject); override; public function getValue: TValue; override; procedure setValue(aValue: TValue); override; end; TBindingTargetField = class(TBindingTarget) protected procedure setTarget(const Value: TObject); override; public function getValue: TValue; override; procedure setValue(aValue: TValue); override; end; TBindingTargetControl = class(TBindingTargetProperty) protected _oldOnExit: TNotifyEvent; procedure setTarget(const Value: TObject); override; procedure targetExit(Sender: TObject); end; TBindingTargetEdit = class(TBindingTargetControl) protected procedure setTarget(const Value: TObject); override; end; TBindingTargetButton = class(TBindingTargetControl) protected procedure setTarget(const Value: TObject); override; end; TBindingTargetLabel = class(TBindingTargetProperty) protected procedure setTarget(const Value: TObject); override; end; TBindingTargetDateTimePicker = class(TBindingTargetControl) protected procedure setTarget(const Value: TObject); override; end; implementation uses NewFrontiers.Reflection, NewFrontiers.Utility.StringUtil; { TBindingTargetProperty } function TBindingTargetProperty.getValue: TValue; begin if (_target = nil) then result := TValue.Empty else result := TReflectionManager.getPropertyValue(_target, _bindingPath); end; procedure TBindingTargetProperty.setTarget(const Value: TObject); begin inherited; _target := Value; end; procedure TBindingTargetProperty.setValue(aValue: TValue); begin inherited; if (_target <> nil) then TReflectionManager.setPropertyValue(_target, _bindingPath, aValue); end; { TBindingTargetEdit } procedure TBindingTargetEdit.setTarget(const Value: TObject); begin inherited; _target := Value; _bindingPath := 'Text'; end; { TBindingTargetLabel } procedure TBindingTargetLabel.setTarget(const Value: TObject); begin inherited; _target := Value; _bindingPath := 'Caption'; end; { TBindingTargetDateTimePicker } procedure TBindingTargetDateTimePicker.setTarget(const Value: TObject); begin inherited; _target := Value; _bindingPath := 'DateTime'; end; { TBindingTargetControl } procedure TBindingTargetControl.setTarget(const Value: TObject); begin inherited; _oldOnExit := TEdit(Value).OnExit; TEdit(Value).OnExit := targetExit; end; procedure TBindingTargetControl.targetExit(Sender: TObject); begin TBindingDictionary.getInstance.propertyChanged(_target, _bindingPath); if (assigned(_oldOnExit)) then _oldOnExit(_target); end; { TBindingTargetField } function TBindingTargetField.getValue: TValue; begin if (_target = nil) then result := TValue.Empty else result := TReflectionManager.getFieldValue(_target, _bindingPath); end; procedure TBindingTargetField.setTarget(const Value: TObject); begin inherited; _target := Value; end; procedure TBindingTargetField.setValue(aValue: TValue); begin inherited; if (_target <> nil) then TReflectionManager.setFieldValue(_target, _bindingPath, aValue); end; { TBindingTargetButton } procedure TBindingTargetButton.setTarget(const Value: TObject); begin inherited; _target := Value; _bindingPath := 'Enabled'; end; initialization TBindingTargetFactory.registerTargetClass(TEdit, TBindingTargetEdit); TBindingTargetFactory.registerTargetClass(TLabeledEdit, TBindingTargetEdit); TBindingTargetFactory.registerTargetClass(TLabel, TBindingTargetLabel); TBindingTargetFactory.registerTargetClass(TDateTimePicker, TBindingTargetDateTimePicker); TBindingTargetFactory.registerTargetClass(TButton, TBindingTargetButton); finalization if TBindingTargetFactory.getInstance <> nil then TBindingTargetFactory.getInstance.Free; end.
unit QuarterRangeSearch_u; { Delphi Implementaion of a 2D quadrant search static DS -> TQuarterRangeSearch. Based on the ideas given of day 4 in the course 6.851 MIT OpenWare https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-851-advanced-data-structures-spring-2012/lecture-videos/session-4-geometric-structures-ii/ The DS is prepared for 3D applications so keys are 3D points and quarter search is done on (z,y) components. The DS is Build with a List of TKey3D, (x,y,z) points. Four different search modes are implemented for different 2D queries given an input key (see TQuadrant). (*) The problem is solved for a Third quadrant problem and the rest of search modes are converted to a Third quadrant search by changing the sign of y and/or z component of Input Points. Once the DS is build For a fixed Quadrant search the function queries are solved by getSortedListOfMembersDominatedBykey, that outputs a List of keys, a subset of the Initial list of keys being dominated by a new input key. Note that this List should be freed by TQuarterRangeSearch.Free, and it is cleared every new query. Addictionally we can ask if a key is dominated by another one using getSortedListOfMembersDominatedBykey. (*) See RangeTree2DForm_u.pas for an example of how to use DS on standard 2D points (x,y). } interface uses Math, System.SysUtils,DIalogs, System.Variants, System.Classes, System.Generics.collections, Generics.Defaults; // query is : find (x,y,z) dominated by input key (x0,y0,z0) // type TQuadrant = (First, // y > y0, z > z0 // Second, // y > y0, z < z0 // Third, // y < y0, z < z0 // Fourth); // y < y0, z > z0 // type TKey3D = class x, y, z : Single; entityNo : Integer; constructor create(const x_, y_, z_ : Single; const entityNo_ : Integer); end; type TzNode = class pointerToKey3D : TKey3D; pointerToLeft, pointerToRight, pointerToBaseNode : TzNode; posInsortedListOfZNodes : Integer; constructor create(const key : TKey3D); end; type TQRSNode = class pointerToKey3D : TKey3D; constructor create(const key : TKey3D); procedure free; private sortedListOfZNodes : TList<TzNode>; pointerToBaseNode : TzNode; posInYList : Integer; end; type TQuarterRangeSearch = class private FCount, NextYPosition, YPosition : Integer; compareY : TComparison<TKey3D>; comparerY : IComparer<TKey3D>; compareZ : TComparison<TKey3D>; compareZNode : TComparison<TZNode>; comparerZNode : IComparer<TZNode>; OutputSortedListOfKeys, WorkingListOfKeys, ListOfKeysSortedByY : TList<TKey3D>; DictOfKeyToInputKey : TDictionary<TKey3D,TKey3D>; DictOfkeyToTQRSNode : TDictionary<TKey3D,TQRSNode>; EnteringZList : TList<TzNode>; procedure LeftToRightPass; procedure RightToLeftPass; procedure cascade; procedure updatePosInsortedListOfZNodes; procedure trackListUpwards(const List : TList<TzNode>; const probeZNode : TzNode; var position : Integer); procedure trackListDownwards(const List : TList<TzNode>; const probeZNode : TzNode; var position : Integer); procedure updatePredecessor(const probeZNode : TzNode; var pred : TzNode); function updateSuccessorIfSuccIsNIL(const probeZNode : TzNode) : TzNode; procedure updateSuccessor(const probeZNode : TzNode; var succ : TzNode); procedure updatePredSucc(const probeZNode : TzNode; var pred, succ : TZNode); public quadrant : Tquadrant; constructor create; procedure Clear; procedure free; procedure Build(const ListOfKeys : TList<TKey3D>; const quadrant_ : TQuadrant); overload; procedure Build(const InitIdx, LastIdx : Integer; const ListOfKeys : TList<TKey3D>; const quadrant_ : TQuadrant); overload; property Count : integer read FCount; function isKey1DominatedByKey2(const k1, k2 : TKey3D) : Boolean; function getSortedListOfMembersDominatedBykey(const key_ : TKey3D) : TList<TKey3D>; end; implementation const CascadeConstant = 2; //Begin define Methods of TKey3D constructor TKey3D.create(const x_, y_, z_ : Single; const entityNo_ : Integer); begin inherited create; x := x_; y := y_; z := z_; entityNo := entityNo_; end; // end define methods of TKey3D // begin define methods of TzNode<TKey3D> constructor TzNode.create(const key : TKey3D); begin pointerToKey3D := key; pointerToLeft := nil; pointerToRight := nil; pointerToBaseNode := nil; end; // end define methods of TzNode<TKey3D> // begin define methods of TQRSNode<TKey3D> ç constructor TQRSNode.create(const key : TKey3D); begin pointerToKey3D := key; pointerToBaseNode := nil; sortedListOfZNodes := TList<TzNode>.create; end; procedure TQRSNode.free; var i : Integer; begin for i := 0 to sortedListOfZNodes.Count-1 do sortedListOfZNodes[i].Free; sortedListOfZNodes.Free; inherited free; end; // end define methods of TQRSNode<TKey3D> // begin define methods of TQuarterRangeSearch<TKey3D> constructor TQuarterRangeSearch.create; begin inherited create; WorkingListOfKeys := TList<TKey3D>.create; ListOfKeysSortedByY := TList<TKey3D>.create; OutputSortedListOfKeys := TList<TKey3D>.create; DictOfkeyToTQRSNode := TDictionary<TKey3D,TQRSNode>.create; DictOfKeyToInputKey := TDictionary<TKey3D,TKey3D>.create; EnteringZList := TList<TzNode>.Create; FCount := 0; // define compare functions compareY := function(const left, right: TKey3D): Integer begin RESULT := TComparer<Single>.Default.Compare(left.y,right.y); if RESULT = 0 then begin RESULT := TComparer<Single>.Default.Compare(left.z,right.z); if RESULT =0 then RESULT := TComparer<Integer>.Default.Compare(left.entityNo,right.entityNo); end; end; compareZ := function(const left, right: TKey3D): Integer begin RESULT := TComparer<Single>.Default.Compare(left.z,right.z); if RESULT = 0 then begin RESULT := TComparer<Single>.Default.Compare(left.y,right.y); if RESULT =0 then RESULT := TComparer<Integer>.Default.Compare(left.entityNo,right.entityNo); end; end; compareZNode := function(const left, right: TZNode): Integer begin RESULT := compareZ(left.pointerToKey3D,right.pointerToKey3D); end; comparerZNode := TComparer<TzNode>.Construct(compareZNode); comparerY := TComparer<TKey3D>.Construct(compareY); end; procedure TQuarterRangeSearch.Clear; var key : TKey3D; i : Integer; begin if FCount>0 then begin for key in DictOfkeyToTQRSNode.Keys do DictOfkeyToTQRSNode[key].free; DictOfkeyToTQRSNode.Clear; for i := 0 to WorkingListOfKeys.Count-1 do WorkingListOfKeys[i].free; WorkingListOfKeys.Clear; DictOfKeyToInputKey.Clear; for i := 0 to EnteringZList.Count-1 do EnteringZList[i].Free; EnteringZList.Clear; ListOfKeysSortedByY.Clear; FCount := 0; end; OutputSortedListOfKeys.Clear; end; procedure TQuarterRangeSearch.free; var i : integer; begin Clear; WorkingListOfKeys.Free; DictOfKeyToInputKey.Free; OutputSortedListOfKeys.Free; DictOfkeyToTQRSNode.Free; ListOfKeysSortedByY.Free; EnteringZList.Free; inherited free; end; procedure TQuarterRangeSearch.LeftToRightPass; var i, j, aInteger, position : Integer; key : TKey3D; node : TQRSNode; BaseZNode, zNode, RightExtension_zNode : TzNode; zNodesbeingRightExtended : TList<TzNode>; begin zNodesbeingRightExtended := TList<TzNode>.create; for i := 0 to ListOfKeysSortedByY.Count-1 do begin key := ListOfKeysSortedByY[i]; node := DictOfkeyToTQRSNode[key]; // newZNode first on the node.sortedListOfZNodes / but there will be inserted copies that make it being not the first BaseZNode := TzNode.create(key); BaseZNode.pointerToBaseNode := BaseZNode; node.sortedListOfZNodes.Add(BaseZNode); node.pointerToBaseNode := BaseZNode; zNodesbeingRightExtended.BinarySearch(BaseZNode,position,comparerZNode); for j := position to zNodesbeingRightExtended.Count-1 do begin zNode := zNodesbeingRightExtended[j]; // Create new zNode to be attatched in node.sortedListOfNodes RightExtension_zNode := TzNode.create(znode.pointerToKey3D); zNode.pointerToRight := RightExtension_zNode; RightExtension_zNode.pointerToLeft := zNode; RightExtension_zNode.pointerToBaseNode := BaseZNode; node.sortedListOfZNodes.Add(RightExtension_zNode); end; for j := zNodesbeingRightExtended.Count-1 downto position do zNodesbeingRightExtended.Delete(j); zNodesbeingRightExtended.Add(BaseZNode); end; zNodesbeingRightExtended.Free; end; procedure TQuarterRangeSearch.RightToLeftPass; var i, j, aInteger, position, position2 : Integer; key : TKey3D; node : TQRSNode; BaseZNode, zNode, LeftExtension_zNode : TzNode; zNodesbeingLeftExtended : TList<TzNode>; begin zNodesbeingLeftExtended := TList<TzNode>.create; for i := ListOfKeysSortedByY.Count-1 downto 0 do begin key := ListOfKeysSortedByY[i]; node := DictOfkeyToTQRSNode[key]; BaseZNode := node.pointerToBaseNode; zNodesbeingLeftExtended.BinarySearch(BaseZNode,position,comparerZNode); for j := position to zNodesbeingLeftExtended.Count-1 do begin zNode := zNodesbeingLeftExtended[j]; // Create new zNode to be attatched in node.sortedListOfNodes LeftExtension_zNode := TzNode.create(znode.pointerToKey3D); zNode.pointerToLeft := LeftExtension_zNode; // take CONSERVATIVE leftExtension LeftExtension_zNode.pointerToRight := zNode; LeftExtension_zNode.pointerToBaseNode := BaseZNode; node.sortedListOfZNodes.binarySearch(LeftExtension_zNode,position2,comparerZnode); node.sortedListOfZNodes.insert(position2,LeftExtension_zNode); end; for j := zNodesbeingLeftExtended.Count-1 downto position do zNodesbeingLeftExtended.Delete(j); zNodesbeingLeftExtended.Add(BaseZNode); end; // remaining Nodes in zNodesbeingLeftExtended are in -infinity // we get them because pointerToBaseNode = nil EnteringZList.Clear; for i := 0 to zNodesbeingLeftExtended.Count-1 do begin zNode := zNodesbeingLeftExtended[i]; // Create new zNode to be attatched in node.sortedListOfNodes LeftExtension_zNode := TzNode.create(znode.pointerToKey3D); zNode.pointerToLeft := LeftExtension_zNode; LeftExtension_zNode.pointerToRight := zNode; EnteringZList.Add(LeftExtension_zNode); end; zNodesbeingLeftExtended.Free; end; procedure TQuarterRangeSearch.cascade; var cascadeNodes : TList<TzNode>; node : TQRSNode; promZNode, BaseNode, zNode : TzNode; i, j, position, position2 : Integer; key : TKey3D; begin cascadeNodes := TList<TzNode>.create; for i := ListOfKeysSortedByY.Count-1 downto 0 do begin key := ListOfKeysSortedByY[i]; node := DictOfkeyToTQRSNode[key]; BaseNode := node.pointerToBaseNode; // introduce cascadeNodes in nodes.SortedListOfNodes cascadeNodes.BinarySearch(BaseNode,position,comparerZNode); // ensure repetitions of BaseNode dont go farther left while (position > 0) AND (compareZNode(cascadeNodes[position-1], BaseNode) <> -1) do dec(position); for j := position to cascadeNodes.Count-1 do begin zNode := cascadeNodes[j]; zNode.pointerToBaseNode := BaseNode; node.sortedListOfZNodes.binarySearch(znode,position2,comparerZNode); node.sortedListOfZNodes.insert(position2, zNode); end; for j := cascadeNodes.Count-1 downto position do cascadeNodes.Delete(j); // update cascadeNodes for j := 0 to node.sortedListOfZNodes.Count-1 do begin if (j mod cascadeConstant) = 0 then begin znode := node.sortedListOfZNodes[j]; promZNode := TzNode.create(znode.pointerToKey3D); promZNode.pointerToRight := zNode; promZNode.pointerToBaseNode := BaseNode; cascadeNodes.Add(promZNode); end; end; end; // remaining Nodes in cascadeNodes goesto EnteringZList for i := 0 to cascadeNodes.Count-1 do begin zNode := cascadeNodes[i]; EnteringZList.binarySearch(zNode,position,comparerZNode); EnteringZList.insert(position,zNode); end; cascadeNodes.Free; end; procedure TQuarterRangeSearch.updateposInsortedListOfZNodes; var i, j : Integer; key : TKey3D; node : TQRSNode; begin for i := 0 to ListOfKeysSortedByY.Count-1 do begin key := ListOfKeysSortedByY[i]; node := DictOfkeyToTQRSNode[key]; node.posInYList := i; for j := 0 to node.sortedListOfZNodes.Count-1 do node.sortedListOfZNodes[j].posInsortedListOfZNodes := j; end; end; procedure TQuarterRangeSearch.Build(const ListOfKeys : TList<TKey3D>; const quadrant_ : TQuadrant); begin Build(0,ListOfKeys.Count-1,ListOfKeys,quadrant_); end; procedure TQuarterRangeSearch.Build(const InitIdx, LastIdx : Integer; const ListOfKeys : TList<TKey3D>; const quadrant_ : TQuadrant); var node : TQRSNode; i : Integer; key, WorkingKey : TKey3D; znode : TZNode; begin Clear; // Build Working list according to quadrant quadrant := quadrant_; case quadrant of First: begin for i := InitIdx to LastIdx do begin key := ListOfKeys[i]; with key do begin WorkingKey := TKey3D.create(x,-y,-z,entityNo); end; DictOfKeyToInputKey.Add(WorkingKey,Key); WorkingListOfKeys.Add(workingKey); end; end; Second:begin for i := InitIdx to LastIdx do begin key := ListOfKeys[i]; with key do begin WorkingKey := TKey3D.create(x,y,-z,entityNo); end; DictOfKeyToInputKey.Add(WorkingKey,Key); WorkingListOfKeys.Add(workingKey); end; end; Third: begin for i := InitIdx to LastIdx do begin key := ListOfKeys[i]; with key do begin WorkingKey := TKey3D.create(x,y,z,entityNo); end; DictOfKeyToInputKey.Add(WorkingKey,Key); WorkingListOfKeys.Add(workingKey); end; end; Fourth:begin for i := InitIdx to LastIdx do begin key := ListOfKeys[i]; with key do begin WorkingKey := TKey3D.create(x,-y,z,entityNo); end; DictOfKeyToInputKey.Add(WorkingKey,Key); WorkingListOfKeys.Add(workingKey); end; end; end; // Build QRSNodes and Store ListOfKeys and DicTKey3DToNode for i := 0 to WorkingListOfKeys.Count-1 do begin key := WorkingListOfKeys[i]; node := TQRSNode.create(key); ListOfKeysSortedByY.Add(key); DictOfkeyToTQRSNode.Add(key,node); end; ListOfKeysSortedByY.sort(comparerY); // //Inspect sorted LIst // for i := 0 to ListOfKeysSortedByY.count-1 do // key := ListOfKeysSortedByY[i]; // Build Nodes LeftToRightPass; RightToLeftPass; cascade; updateposInsortedListOfZNodes; FCount := WorkingListOfKeys.Count; // // inspect // for i := 0 to EnteringZList.Count-1 do // znode := EnteringZList[i]; end; procedure TQuarterRangeSearch.trackListUpwards(const List : TList<TZNode>; const probeZNode : TzNode; var position : Integer); var StartPosition, LastPosWithPointerToRight : Integer; begin StartPosition := position; LastPosWithPointerToRight := -1; while (position < List.Count-1) AND (compareZNode(probeZNode,List[position+1]) = 1) do begin Inc(position); if Assigned(List[position].pointerToRight) then LastPosWithPointerToRight := position; end; if LastPosWithPointerToRight = -1 then position := StartPosition else position := LastPosWithPointerToRight; end; procedure TQuarterRangeSearch.trackListDownwards(const List : TList<TZNode>; const probeZNode : TzNode; var position : Integer); var StartPosition, LastPosWithPointerToRight : Integer; begin StartPosition := position; LastPosWithPointerToRight := -1; while (position > 0) AND (compareZNode(probeZNode,List[position-1]) = -1) do begin Dec(position); if Assigned(List[position].pointerToRight) then LastPosWithPointerToRight := position; end; if LastPosWithPointerToRight = -1 then position := StartPosition else position := LastPosWithPointerToRight; end; procedure TQuarterRangeSearch.updatePredecessor(const probeZNode : TzNode; var pred : TzNode); var NextPred : TzNode; QRSNode, NextQRSNode : TQRSNode; position : Integer; begin if Assigned(pred.pointerToRight) then Nextpred := pred.pointerToRight else begin // Look for a pred with rightPointer in YPosition Node QRSNode := DictOfkeyToTQRSNode[pred.pointerToBaseNode.pointerToKey3D]; position := pred.posInsortedListOfZNodes; // BaseNodePoints To right so we are save while (position>0) AND NOT Assigned(QRSNode.sortedListOfZNodes[position].pointerToRight) do dec(position); if position = 0 then // use BaseNode always have a pointerTORight NextPred := pred.pointerToBaseNode.pointerToRight else NextPred := QRSNode.sortedListOfZNodes[position].pointerToRight; end; // at NextYposition track upward ZList for a tighter predecesor if Assigned(NextPred) then begin NextQRSNode := DictOfkeyToTQRSNode[Nextpred.pointerToBaseNode.pointerToKey3D]; position := Nextpred.posInsortedListOfZNodes; trackListUpwards(NextQRSNode.sortedListOfZNodes,probeZNode,position); Nextpred := NextQRSNode.sortedListOfZNodes[position]; NextYPosition := NextQRSNode.posInYList; end; // output pred := NextPred; end; function TQuarterRangeSearch.updateSuccessorIfSuccIsNIL(const probeZNode : TzNode) : TzNode; var NextQRSNode, QRSNode : TQRSNode; position, i, FinalPosition, StartPosition : Integer; key : TKey3D; begin NextQRSNode := DictOfkeyToTQRSNode[ListOfKeysSortedByY[NextYPosition]]; // We need to account here every Edge crossed from posInYListOfOldQRSNode To Next Pred StartPosition := YPosition + 1; FinalPosition := NextYPosition-1; for i := StartPosition to FinalPosition do begin YPosition := i; key := ListOfKeysSortedByY[i]; QRSNode := DictOfkeyToTQRSNode[key]; // At every QRSNodelook for a valid successor position := QRSNode.sortedListOfZNodes.Count; trackListDownwards(QRSNode.sortedListOfZNodes,probeZNode,position); if position <> QRSNode.sortedListOfZNodes.Count then begin RESULT := QRSNode.sortedListOfZNodes[position]; Exit; end else begin if compareY(key,probeZNode.pointerToKey3D) = -1 then OutputSortedListOfKeys.Add(DictOfKeyToInputKey[ListOfKeysSortedByY[i]]); end; end; // if no valid successor is found in all those nodes inspect NextQRSNode position := NextQRSNode.sortedListOfZNodes.Count; while comparezNode(probeZNode,NextQRSNode.sortedListOfZNodes[position-1]) = -1 do dec(position); if position < NextQRSNode.sortedListOfZNodes.Count then RESULT := NextQRSNode.sortedListOfZNodes[position] else RESULT := nil; end; procedure TQuarterRangeSearch.updateSuccessor(const probeZNode : TzNode; var succ : TzNode); var NextSucc : TzNode; QRSNode, NextQRSNode : TQRSNode; position : Integer; begin if Assigned(succ) then begin if Assigned(succ.pointerToRight) then begin NextSucc := succ.pointerToRight; NextQRSNode := DictOfkeyToTQRSNode[NextSucc.pointerToBaseNode.pointerToKey3D]; position := NextSucc.posInsortedListOfZNodes; trackListDownwards(NextQRSNode.sortedListOfZNodes,probeZNode,position); NextSucc := NextQRSNode.sortedListOfZNodes[position]; end else begin QRSNode := DictOfkeyToTQRSNode[succ.pointerToBaseNode.pointerToKey3D]; position := succ.posInsortedListOfZNodes; while (position < QRSNode.sortedListOfZNodes.Count) AND (NOT Assigned(QRSNode.sortedListOfZNodes[position].pointerToRight)) do Inc(position); if position < QRSNode.sortedListOfZNodes.Count then Nextsucc := QRSNode.sortedListOfZNodes[position].pointerToRight else NextSucc := updateSuccessorIfSuccIsNIL(probeZNode); end; end else NextSucc := updateSuccessorIfSuccIsNIL(probeZNode); // output succ := NextSucc; end; procedure TQuarterRangeSearch.updatePredSucc(const probeZNode : TzNode; var pred, succ : TZNode); {Assumed inputs belong to the same QRSNode, outputs must satisfy this condition to} var position, anInteger : Integer; begin updatePredecessor(probeZNode,pred); if Assigned(pred) then begin updateSuccessor(probeZNode,succ); // update succesor until pred and Succ live in the same QRSNode or Succ is nil if Assigned(Succ) then begin anInteger := compareY(pred.pointerToBaseNode.pointerToKey3D,succ.pointerToBaseNode.pointerToKey3D); while anInteger <> 0 do begin if anInteger = 1 then begin // Stop if succ beyond y mark -> no more keys to OutputSortedListOfKeys anInteger := compareY(succ.pointerToBaseNode.pointerToKey3D,probeZNode.pointerToKey3D); if anInteger = 1 then Exit; if compareZNode(probeZNode,succ.pointerToBaseNode) = 1 then OutputSortedListOfKeys.Add(DictOfKeyToInputKey[succ.pointerToBaseNode.pointerToKey3D]); YPosition := DictOfkeyToTQRSNode[succ.pointerToBaseNode.pointerToKey3D].posInYList; updateSuccessor(probeZNode,succ); if NOT Assigned(succ) then break; end else showmessage('This should not happen'); //update anInteger := compareY(pred.pointerToBaseNode.pointerToKey3D,succ.pointerToBaseNode.pointerToKey3D); end; // update YPosition := NextYPosition; end end end; function TQuarterRangeSearch.isKey1DominatedByKey2(const k1, k2 : TKey3D) : Boolean; var key : TKey3D; begin // transform k1 into key case quadrant of First : key := TKey3D.create(100000,-k1.y,-k1.z,k1.entityNo); Second : key := TKey3D.create(100000,k1.y,-k1.z,k1.entityNo); Third : key := TKey3D.create(100000,k1.y,k1.z,k1.entityNo); Fourth : key := TKey3D.create(100000,-k1.y,k1.z,k1.entityNo); end; RESULT := (compareY(key,k2) <> 1) AND (compareZ(key,k2) <> 1); key.Free; end; function TQuarterRangeSearch.getSortedListOfMembersDominatedBykey(const key_ : TKey3D) : TList<TKey3D>; var probeZNode, pred, succ : TzNode; position, i : Integer; label FreeAndExit; begin OutputSortedListOfKeys.Clear; RESULT := OutputSortedListOfKeys; probeZNode := TzNode.create(key_); // BinarySearch in EnteringZList Just once EnteringZList.BinarySearch(probeZnode,position,comparerZNode); if position = 0 then goto FreeAndExit else begin pred := EnteringZList[position-1]; if position = EnteringZList.Count then succ := nil else succ := EnteringZList[position]; end; // Walk right storing output every edgeCrossed YPosition := -1; updatePredSucc(probeZNode,pred,succ); while Assigned(pred) AND (compareY(key_,pred.pointerToBaseNode.pointerToKey3D) = 1) do begin OutputSortedListOfKeys.Add(DictOfKeyToInputKey[pred.pointerToBaseNode.pointerToKey3D]); YPosition := DictOfkeyToTQRSNode[pred.pointerToBaseNode.pointerToKey3D].posInYList; updatePredSucc(probeZNode,pred,succ); end; FreeAndExit: probeZNode.Free; end; // end define methods of TQuarterRangeSearch<TKey3D> end.
unit form_conf; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, appconfig, Vcl.Grids, Vcl.ValEdit, strtools, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList; type Tfrm_conf = class(TForm) ValueListEditor1: TValueListEditor; ActionList1: TActionList; ImageList1: TImageList; act_result_ok: TAction; act_result_cancel: TAction; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ValueListEditor1GetPickList(Sender: TObject; const KeyName: string; Values: TStrings); procedure FormDestroy(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure act_result_okExecute(Sender: TObject); procedure act_result_cancelExecute(Sender: TObject); private FOnParamsApply: TNotifyEvent; FGetPickListEvent: TGetPickListEvent; FConfig: TAppConfig; procedure SetConfig(AConfig: TAppConfig); function GetValue(ValueName: string): string; procedure SetValue(ValueName: string; const Source: string); public property OnParamsApply: TNotifyEvent read FOnParamsApply write FOnParamsApply; property GetPickListEvent: TGetPickListEvent read FGetPickListEvent write FGetPickListEvent; property Config: TAppConfig read FConfig write SetConfig; property Value[ValueName: string]: string read GetValue write SetValue; procedure ReadConfig(Section: string); procedure WriteConfig(Section: string); public class function AsBool(const Source: string): boolean; class function ToStr(const Source: boolean): string; end; implementation {$R *.dfm} procedure Tfrm_conf.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure Tfrm_conf.SetConfig(AConfig: TAppConfig); begin FConfig := AConfig; ReadConfig(''); end; procedure Tfrm_conf.FormDestroy(Sender: TObject); begin WriteConfig(''); end; procedure Tfrm_conf.FormKeyPress(Sender: TObject; var Key: Char); begin case Key of #13: begin act_result_okExecute(Sender); Key := #0; end; #27: begin act_result_cancelExecute(Sender); Key := #0; end; end; end; function Tfrm_conf.GetValue(ValueName: string): string; begin if ValueName='' then Result := '' else Result := ValueListEditor1.Values[ValueName]; end; procedure Tfrm_conf.SetValue(ValueName: string; const Source: string); begin if ValueName<>'' then begin ValueListEditor1.Values[ValueName] := Trim(Source); end; end; procedure Tfrm_conf.ValueListEditor1GetPickList(Sender: TObject; const KeyName: string; Values: TStrings); begin if Assigned(FGetPickListEvent) then begin FGetPickListEvent(Self, KeyName, Values); end; end; procedure Tfrm_conf.ReadConfig(Section: string); begin if Assigned(FConfig) then begin if Section='' then Section := ClassName; FConfig.Read(Section, 'position', Self); ValueListEditor1.ColWidths[0] := FConfig.Read(Section, 'cname', ValueListEditor1.ColWidths[0]); FConfig.Close; end; end; procedure Tfrm_conf.WriteConfig(Section: string); begin if Assigned(FConfig) then begin if Section='' then Section := ClassName; FConfig.Write(Section, 'position', Self); FConfig.Write(Section, 'cname', ValueListEditor1.ColWidths[0]); FConfig.Close; end; end; procedure Tfrm_conf.act_result_cancelExecute(Sender: TObject); begin ModalResult := mrCancel; if not (fsModal in FormState) then begin Close; end; end; procedure Tfrm_conf.act_result_okExecute(Sender: TObject); begin ModalResult := mrOk; if not (fsModal in FormState) then begin Close; end; end; class function Tfrm_conf.AsBool(const Source: string): boolean; begin Result := str2bool(Source, false); end; class function Tfrm_conf.ToStr(const Source: boolean): string; begin Result := cname_bool[Source]; end; end.
unit Invoice.Model.Customer; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes; type [Entity] [Table('Customer', '')] TCustomer = class private { Private declarations } FidCustomer: Integer; FnameCustomer: String; FphoneCustomer: String; public { Public declarations } [Restrictions([NotNull])] [Column('idCustomer', ftInteger)] [Dictionary('idCustomer', 'Mensagem de validação', '', '', '', taCenter)] property idCustomer: Integer Index 0 read FidCustomer write FidCustomer; [Restrictions([NotNull])] [Column('nameCustomer', ftString, 100)] [Dictionary('nameCustomer', 'Mensagem de validação', '', '', '', taLeftJustify)] property nameCustomer: String Index 1 read FnameCustomer write FnameCustomer; [Restrictions([NotNull])] [Column('phoneCustomer', ftString, 11)] [Dictionary('phoneCustomer', 'Mensagem de validação', '', '', '', taLeftJustify)] property phoneCustomer: String Index 2 read FphoneCustomer write FphoneCustomer; end; implementation initialization TRegisterClass.RegisterEntity(TCustomer) end.
unit uStageJSON; interface uses System.Generics.Collections, Rest.JSON; {$M+} type TPlayerDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TGoalsDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TBoxesDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TBoxesGoalDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TFloorsDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TWallsDTO = class private FX: Integer; FY: Integer; published property X: Integer read FX write FX; property Y: Integer read FY write FY; end; TStageDTO = class private FBoxes: TArray<TBoxesDTO>; FBoxesGoal: TArray<TBoxesGoalDTO>; FFloors: TArray<TFloorsDTO>; FGoals: TArray<TGoalsDTO>; FNumber: Integer; FPlayer: TPlayerDTO; FWalls: TArray<TWallsDTO>; FX: Integer; FY: Integer; FPerfectMoves: Integer; published property Boxes: TArray<TBoxesDTO> read FBoxes write FBoxes; property BoxesGoal: TArray<TBoxesGoalDTO> read FBoxesGoal write FBoxesGoal; property Floors: TArray<TFloorsDTO> read FFloors write FFloors; property Goals: TArray<TGoalsDTO> read FGoals write FGoals; property Number: Integer read FNumber write FNumber; property Player: TPlayerDTO read FPlayer write FPlayer; property PerfectMoves: Integer read FPerfectMoves write FPerfectMoves; property Walls: TArray<TWallsDTO> read FWalls write FWalls; property X: Integer read FX write FX; property Y: Integer read FY write FY; public constructor Create; destructor Destroy; override; procedure AddWall(const X, Y: Integer); procedure AddFloor(const X, Y: Integer); procedure AddBox(const X, Y: Integer); procedure AddBoxGoal(const X, Y: Integer); procedure AddGoal(const X, Y: Integer); procedure AddPlayer(const X, Y: Integer); end; TStage = class private FStage: TStageDTO; published property Stage: TStageDTO read FStage write FStage; public constructor Create; destructor Destroy; override; function ToJSONString: string; class function FromJSONString(const JSON: string): TStage; end; implementation { TStageDTO } procedure TStageDTO.AddBox(const X, Y: Integer); begin SetLength(FBoxes, Length(FBoxes) + 1); FBoxes[Length(FBoxes) - 1] := TBoxesDTO.Create; FBoxes[Length(FBoxes) - 1].FX := X; FBoxes[Length(FBoxes) - 1].FY := Y; end; procedure TStageDTO.AddBoxGoal(const X, Y: Integer); begin SetLength(FBoxesGoal, Length(FBoxesGoal) + 1); FBoxesGoal[Length(FBoxesGoal) - 1] := TBoxesGoalDTO.Create; FBoxesGoal[Length(FBoxesGoal) - 1].FX := X; FBoxesGoal[Length(FBoxesGoal) - 1].FY := Y; end; procedure TStageDTO.AddFloor(const X, Y: Integer); begin SetLength(FFloors, Length(FFloors) + 1); FFloors[Length(FFloors) - 1] := TFloorsDTO.Create; FFloors[Length(FFloors) - 1].FX := X; FFloors[Length(FFloors) - 1].FY := Y; end; procedure TStageDTO.AddGoal(const X, Y: Integer); begin SetLength(FGoals, Length(FGoals) + 1); FGoals[Length(FGoals) - 1] := TGoalsDTO.Create; FGoals[Length(FGoals) - 1].FX := X; FGoals[Length(FGoals) - 1].FY := Y; end; procedure TStageDTO.AddPlayer(const X, Y: Integer); begin FPlayer.FX := X; FPlayer.FY := Y; end; procedure TStageDTO.AddWall(const X, Y: Integer); begin SetLength(FWalls, Length(FWalls) + 1); FWalls[Length(FWalls) - 1] := TWallsDTO.Create; FWalls[Length(FWalls) - 1].FX := X; FWalls[Length(FWalls) - 1].FY := Y; end; constructor TStageDTO.Create; begin inherited; FPlayer := TPlayerDTO.Create; end; destructor TStageDTO.Destroy; var Element: TObject; begin FPlayer.Free; for Element in FWalls do Element.Free; for Element in FFloors do Element.Free; for Element in FBoxes do Element.Free; for Element in FGoals do Element.Free; for Element in FBoxesGoal do Element.Free; inherited; end; { TStage } constructor TStage.Create; begin inherited; FStage := TStageDTO.Create; end; destructor TStage.Destroy; begin FStage.Free; inherited; end; class function TStage.FromJSONString(const JSON: string): TStage; begin Result := TJson.JsonToObject<TStage>(JSON); end; function TStage.ToJSONString: string; begin Result := TJson.ObjectToJsonString(Self); end; end.
{Newton copied from Mandel / Julia Explorer Copyright 2000 Hugh Allen Hugh.Allen@oz.quest.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. } unit fNewton; interface uses Controls, Classes, Messages, FastDIB ; type TNewton = class(TCustomControl) private dib: TFastDIB; FIsEgg: Boolean; FCx, FCy: Real; FChanged: Boolean; FOnPaint: TNotifyEvent; FMaxIters:Integer; procedure SetCx(const Value: Real); procedure SetCy(const Value: Real); procedure SetIsEgg(const Value: Boolean); procedure SetMaxIters(const Value: Integer); function GetDIBPalette: PFColorTable; procedure Render(); procedure WMEraseBackGround(var message: TMessage); message WM_ERASEBKGND; protected procedure Paint(); override; procedure Resize(); override; public ViewLeft: real; ViewTop: real; ViewWidth: real; ViewHeight: real; constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure SetChanged(); function PixelToViewX(const x: integer): Real; function PixelToViewY(const y: integer): Real; function ViewToPixelX(const x: Real): integer; function ViewToPixelY(const y: Real): integer; property Canvas; property Palette: PFColorTable read GetDIBPalette; procedure MakePalette(Seed: Longint); published property IsEgg: Boolean read FIsEgg write SetIsEgg; property Cx: Real read FCx write SetCx; property Cy: Real read FCy write SetCy; property OnPaint: TNotifyEvent read FOnPaint write FOnPaint; property MaxIterations:Integer read FMaxIters write SetMaxIters default 200; property Align; property Anchors; property AutoSize; property BiDiMode; property BorderWidth; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; procedure Register(); implementation procedure Register(); begin RegisterComponents('Newton', [TNewton]); end; { TNewton } constructor TNewton.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; dib := TFastDIB.Create; ViewLeft := -3.0; ViewTop := -3.0; ViewWidth := 6.0; ViewHeight := 6.0; dib.SetSize(2, 2, 8, 0); MakePalette(2); MaxIterations := 200; FChanged := True; FOnPaint := nil; end; destructor TNewton.Destroy; begin dib.Free; inherited; end; Procedure TNewton.MakePalette(Seed: Longint); var i : integer; r0, g0, b0: integer; r1, g1, b1: integer; s: real; begin RandSeed := Seed; r0 := 64; g0 := 64; b0 := 64; //r1 := 255; //g1 := 200; //b1 := 64; r1 := random(256); g1 := random(256); b1 := random(256); s := 0; for i := 0 to 255 do begin s := s + 0.02 + 0.03 * (255-i)/255; if s >= 1.0 then begin r0 := r1; g0 := g1; b0 := b1; repeat r1 := random(256); g1 := random(256); b1 := random(256); until abs(r1-r0) + abs(g1-g0) + abs(b1-b0) > 200; // fixme s := 0; end; dib.colors[i].r := trunc((1-s) * r0 + s * r1); dib.colors[i].g := trunc((1-s) * g0 + s * g1); dib.colors[i].b := trunc((1-s) * b0 + s * b1); end; dib.colors[255].r := 0;//255; dib.colors[255].g := 0;//255; dib.colors[255].b := 0;//255; end; procedure TNewton.Paint; begin if FChanged then Render; FChanged := False; dib.Draw(integer(Canvas.Handle), 0, 0); if Assigned(FOnPaint) then FOnPaint(Self); end; procedure TNewton.Render(); var Code, i, SetSelection, Pixelx, maxcolx, maxrowy, FMcolor, rowy, colx: integer; cos_theta, sin_theta, theta, Xi, Yi, Xisquare, Xitemp, deltaXi, Xtemp, YTemp, Temp, X, Y, Xsquare, Ysquare, deltaX, deltaY, max_size, deltaP, deltaQ, Q, P: Extended; { S: string;} { Bitmap: TBitmap;} { PixelLine: PByteArray;} var x, y, i: integer; vx, vy: real; vx2: real; tx1, ty1: real; //tx2, ty2: real; lake: boolean; dx, dy: real; d, ld: real; { label done;} begin dib.SetSize(Width, Height, 8, 0); maxcolx := (Width - 1); maxrowy := (Height - 1); if IsEgg then {LobsterSets} begin deltaX:=(ViewWidth- ViewLeft)/ maxcolx ; deltaY := (ViewHeight-ViewTop)/ maxrowy; { deltaX := (FXMax - FXMin) / maxcolx; deltaY := (FYMax - FYMin) / maxrowy;} for colx := 0 to maxcolx do begin for rowy := 0 to maxrowy do begin Y := ViewWidth - rowy * deltaY; X := ViewLeft + colx * deltaX; { X := FXMin + colx * deltaX; Y := FYMax - rowy * deltaY;} Xold := 42; Yold := 42; FMcolor := 0; flag := 0; while (FMcolor < FMaxIters) and (flag = 0) do begin Xsquare := X * X; Ysquare := Y * Y; denom := 3 * ((Xsquare - Ysquare) * (Xsquare - Ysquare) + 4 * Xsquare * Ysquare); if denom = 0 then denom := 0.00000001; X := 0.6666667 * X + (Xsquare - Ysquare) / denom; Y := 0.6666667 * Y - 2 * X * Y / denom; if (Xold = X) and (Yold = Y) then flag := 1; Xold := X; Yold := Y; inc(FMcolor); end; dib.Pixels8[y, x] := FMcolor; end;end; end else // Mandelbrot begin deltaX:=(ViewWidth- ViewLeft)/ maxcolx ; deltaY := (ViewHeight-ViewTop)/ maxrowy; { deltaX := (FXMax - FXMin) / maxcolx; deltaY := (FYMax - FYMin) / maxrowy;} for colx := 0 to maxcolx do begin for rowy := 0 to maxrowy do begin Y := ViewWidth - rowy * deltaY; X := ViewLeft + colx * deltaX; { X := FXMin + colx * deltaX; Y := FYMax - rowy * deltaY;} Xold := 42; Yold := 42; FMcolor := 0; flag := 0; while (FMcolor < FMaxIters) and (flag = 0) do begin Xsquare := X * X; Ysquare := Y * Y; denom := (3 * Xsquare - 3 * Ysquare - 2); denom := denom * denom + 36 * Xsquare * Ysquare; if denom = 0 then denom := 0.00000001; temp1 := X * Xsquare - 3 * X * Ysquare - 2 * X - 5; temp2 := 3 * Xsquare - 3 * Ysquare - 2; temp3 := 3 * Xsquare * Y - Ysquare * Y - 2 * Y; X := X - (temp1 * temp2 - 6 * X * Y * temp3) / denom; Y := Y - (temp1 * (-6 * X * Y) + temp3 * temp2) / denom; Xnew := X; Ynew := Y; if (Xold = Xnew) and (Yold = Ynew) then flag := 1; Xold := X; Yold := Y; inc(FMcolor); end; begin {Actual 16 color selection} if x > 0 then begin dib.Pixels8[y, x] := FMcolor mod 8; { Pixelx := (colx * PixelScanSize); PixelLine[Pixelx] := Colors[0, FMcolor mod 8]; PixelLine[(Pixelx + 1)] := Colors[1, FMcolor mod 8]; PixelLine[(Pixelx + 2)] := Colors[2, FMcolor mod 8]; } end else begin if ((x < -0.3) and (y > 0)) then begin Pixelx := (colx * PixelScanSize); PixelLine[Pixelx] := Colors[0, ((FMcolor mod 8) + 15)]; PixelLine[(Pixelx + 1)] := Colors[1, ((FMcolor mod 8) +15)]; PixelLine[(Pixelx + 2)] := Colors[2, ((FMcolor mod 8) +15)]; end else begin Pixelx := (colx * PixelScanSize); PixelLine[Pixelx] := Colors[0, ((FMcolor mod 8) + 32)]; PixelLine[(Pixelx + 1)] := Colors[1, ((FMcolor mod 8) + 32)]; PixelLine[(Pixelx + 2)] := Colors[2, ((FMcolor mod 8) + 32)]; end end; end end;end; end; end; procedure TNewton.SetCx(const Value: real); begin FCx := Value; SetChanged(); end; procedure TNewton.SetCy(const Value: real); begin FCy := Value; SetChanged(); end; procedure TNewton.SetIsEgg(const Value: Boolean); begin FIsEgg := Value; FCx := -1.209169;{0.28; FHQ := -1.209169;} FCy := 0.356338;{0.00; FVP := 0.356338;} SetChanged(); end; function TNewton.GetDIBPalette: PFColorTable; begin Result := dib.Colors; end; procedure TNewton.SetChanged(); begin FChanged := True; Invalidate; end; procedure TNewton.WMEraseBackGround(var message: TMessage); begin // don't do it. It makes them flicker! end; procedure TNewton.Resize; begin inherited; FChanged := True; end; function TNewton.PixelToViewX(const x: integer): Real; begin Result := ViewLeft + x * ViewWidth / Width; end; function TNewton.PixelToViewY(const y: integer): Real; begin Result := ViewTop + y * ViewHeight / Height; end; function TNewton.ViewToPixelX(const x: Real): integer; begin Result := round((x - ViewLeft) * Width / ViewWidth); end; function TNewton.ViewToPixelY(const y: Real): integer; begin Result := round((y - ViewTop) * Height / ViewHeight); end; procedure TNewton.SetMaxIters(const Value: Integer); begin FMaxIters := Value; SetChanged; end; end.
unit Chapter03._05_Solution2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils; // 75. Sort Colors // https://leetcode.com/problems/sort-colors/description/ // 三路快速排序的思想 // 对整个数组只遍历了一遍 // 时间复杂度: O(n) // 空间复杂度: O(1) type TSolution = class(TObject) public procedure SortColors(nums: TArr_int); end; procedure Main; implementation procedure Main; var arr: TArr_int; begin arr := [2, 2, 2, 1, 1, 0]; with TSolution.Create do begin SortColors(arr); Free; end; TArrayUtils_int.Print(arr); end; { TSolution } procedure TSolution.SortColors(nums: TArr_int); var zero, two, i: integer; begin zero := -1; // [0...zero] = 0 two := Length(nums); // [two...n-1] = 2 i := 0; while i < two do begin if nums[i] = 1 then begin i += 1; end else if nums[i] = 2 then begin two -= 1; TUtils_int.Swap(nums[i], nums[two]); end else // nums[i] == 0 begin Assert(nums[i] = 0); zero += 1; TUtils_int.Swap(nums[zero], nums[i]); i += 1; end; end; end; end.
unit AssociationList; interface uses AssociationListConst, AssociationListUtils; type TStringAssociationList = class(TObject) private FCapacity: Integer; FKeys: PStringItemList; FValues: PPointerItemList; FCount: Integer; FCaseSensitive: Boolean; FOwnValues: Boolean; procedure SetCapacity(NewCapacity: Integer); function GetItem(const Key: string): Pointer; function SearchFirstGE(const Key: string): Integer; procedure SetItem(const Key: string; Value: Pointer); public constructor Create(CaseSensitive: Boolean; InitialCapacity: Integer = 0); destructor Destroy; override; property Count: Integer read FCount write FCount; property Items[const Key: string]: Pointer read GetItem write SetItem; default; property Capacity: Integer read FCapacity write SetCapacity; property CaseSensitive: Boolean read FCaseSensitive; property OwnValues: Boolean read FOwnValues write FOwnValues; property KeyList: PStringItemList read FKeys; property ValueList: PPointerItemList read FValues; procedure EnsureCapacity(Capacity: Integer); function IndexOf(const Key: string): Integer; procedure Add(const Key: string; Value: Pointer); procedure Remove(const Key: string); procedure RemoveAt(Index: Integer); overload; procedure RemoveAt(Index, Count: Integer); overload; procedure Clear(SuppressDisposingValues: Boolean = False); procedure TrimToSize; end; implementation { TStringAssociationList } constructor TStringAssociationList.Create(CaseSensitive: Boolean; InitialCapacity: Integer); begin FCapacity := InitialCapacity; FCaseSensitive := CaseSensitive; if (InitialCapacity > 0) then begin GetMem(FKeys, InitialCapacity * SizeOf(Pointer)); GetMem(FValues, InitialCapacity * SizeOf(Pointer)); end; end; destructor TStringAssociationList.Destroy; begin if FCapacity > 0 then begin Clear(False); FreeMem(FKeys); FreeMem(FValues); end; end; procedure TStringAssociationList.SetCapacity(NewCapacity: Integer); var NewKeys: PStringItemList; NewValues: PPointerItemList; begin if (NewCapacity <> FCapacity) and (NewCapacity >= FCount) then begin if NewCapacity > 0 then begin GetMem(NewKeys, NewCapacity * SizeOf(Pointer)); GetMem(NewValues, NewCapacity * SizeOf(Pointer)); if FCount > 0 then begin G_CopyLongs(FKeys, NewKeys, FCount); G_CopyLongs(FValues, NewValues, FCount); end; end else begin NewKeys := nil; NewValues := nil; end; if FCapacity > 0 then begin FreeMem(FKeys); FreeMem(FValues); end; FCapacity := NewCapacity; FKeys := NewKeys; FValues := NewValues; end; end; function TStringAssociationList.GetItem(const Key: string): Pointer; var L: Integer; begin L := IndexOf(Key); if L >= 0 then Result := FValues^[L] else Result := nil; end; function TStringAssociationList.SearchFirstGE(const Key: string): Integer; var L, H, I: Integer; begin L := 0; H := FCount - 1; if not FCaseSensitive then while L <= H do begin I := (L + H) shr 1; if G_CompareText(FKeys^[I], Key) < 0 then L := I + 1 else H := I - 1; end else while L <= H do begin I := (L + H) shr 1; if G_CompareStr(FKeys^[I], Key) < 0 then L := I + 1 else H := I - 1; end; Result := L; end; procedure TStringAssociationList.SetItem(const Key: string; Value: Pointer); var L: Integer; O: Pointer; begin L := SearchFirstGE(Key); if (L < FCount) and (FKeys^[L] = Key) then begin if not FOwnValues then FValues^[L] := Value else begin O := FValues^[L]; if O <> Value then begin FValues^[L] := Value; TObject(O).Free; end; end; end else begin if FCount >= FCapacity then SetCapacity(G_EnlargeCapacity(FCapacity)); if L < FCount then begin G_MoveLongs(@FKeys^[L], @FKeys^[L + 1], FCount - L); G_MoveLongs(@FValues^[L], @FValues^[L + 1], FCount - L); end; Pointer(FKeys^[L]) := nil; FKeys^[L] := Key; FValues^[L] := Value; Inc(FCount); end; end; procedure TStringAssociationList.EnsureCapacity(Capacity: Integer); begin if FCapacity < Capacity then SetCapacity(G_NormalizeCapacity(Capacity)); end; function TStringAssociationList.IndexOf(const Key: string): Integer; var L, H, I, C: Integer; begin L := 0; H := FCount - 1; if not FCaseSensitive then while L <= H do begin I := (L + H) shr 1; C := G_CompareText(FKeys^[I], Key); if C < 0 then L := I + 1 else begin if C = 0 then begin Result := I; Exit; end; H := I - 1; end; end else while L <= H do begin I := (L + H) shr 1; C := G_CompareStr(FKeys^[I], Key); if C < 0 then L := I + 1 else begin if C = 0 then begin Result := I; Exit; end; H := I - 1; end; end; Result := -1; end; procedure TStringAssociationList.Add(const Key: string; Value: Pointer); var L: Integer; begin L := SearchFirstGE(Key); if (L < FCount) and (FKeys^[L] = Key) then RaiseErrorFmt(SErrKeyDuplicatesInAssociationList, 'TStringAssociationList'); if FCount >= FCapacity then SetCapacity(G_EnlargeCapacity(FCapacity)); if L < FCount then begin G_MoveLongs(@FKeys^[L], @FKeys^[L + 1], FCount - L); G_MoveLongs(@FValues^[L], @FValues^[L + 1], FCount - L); end; Pointer(FKeys^[L]) := nil; FKeys^[L] := Key; FValues^[L] := Value; Inc(FCount); end; procedure TStringAssociationList.Remove(const Key: string); var L: Integer; begin L := IndexOf(Key); if L >= 0 then RemoveAt(L); end; procedure TStringAssociationList.RemoveAt(Index: Integer); begin if LongWord(Index) >= LongWord(FCount) then RaiseError(SErrIndexOutOfRange); if FOwnValues then TObject(FValues^[Index]).Free; FKeys^[Index] := ''; Dec(FCount); if Index < FCount then begin G_MoveLongs(@FKeys^[Index + 1], @FKeys^[Index], FCount - Index); G_MoveLongs(@FValues^[Index + 1], @FValues^[Index], FCount - Index); end; end; procedure TStringAssociationList.RemoveAt(Index, Count: Integer); var I: Integer; begin if LongWord(Index) > LongWord(FCount) then RaiseError(SErrIndexOutOfRange); if LongWord(Index + Count) >= LongWord(FCount) then begin for I := FCount - 1 downto Index do begin if FOwnValues then TObject(FValues^[I]).Free; FKeys^[I] := ''; end; FCount := Index; end else if Count > 0 then begin for I := Index + Count - 1 downto Index do begin if FOwnValues then TObject(FValues^[I]).Free; FKeys^[I] := ''; end; Dec(FCount, Count); G_MoveLongs(@FKeys^[Index + Count], @FKeys^[Index], FCount - Index); G_MoveLongs(@FValues^[Index + Count], @FValues^[Index], FCount - Index); end; end; procedure TStringAssociationList.Clear(SuppressDisposingValues: Boolean); var I: Integer; begin for I := FCount - 1 downto 0 do begin if FOwnValues and not SuppressDisposingValues then TObject(FValues^[I]).Free; FKeys^[I] := ''; end; FCount := 0; end; procedure TStringAssociationList.TrimToSize; begin if FCount < FCapacity then SetCapacity(FCount); end; end.
unit Inventores_Model; interface uses {$IFDEF PRUEBAS} {$IFDEF VER130} Forms, {$ENDIF} {$ENDIF} Classes; type TInventor = class ID: integer; Nombre: string; Invento: string; Anyo: Integer; constructor Create(const aNombre,aInvento:string;const aAnyo: integer); end; type TmvvmNotifyEvent = procedure (aSender:TObject) of object; type TdmInventores_Model_Class = class of TdmInventores_Model; TdmInventores_Model = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private fTick: TmvvmNotifyEvent; fListaInventores: TList; function BuscaInventorID(const aID: integer): integer; procedure AddInventor(const aNombre,aInvento:string;const aAnyo: integer); protected procedure Tick; procedure ProducirResultado; virtual; {$IFNDEF PRUEBAS} abstract; {$ENDIF} public class function CreateModel:TdmInventores_Model; procedure RealizarProceso(const aTick:TmvvmNotifyEvent); procedure AppendInventor(const aInventor:TInventor); procedure ActualizarInventor(aInventor:TInventor); function LeerInventor(const aID:integer):TInventor; function LeerInventorIDX(const IDX:integer):TInventor; procedure DestruirInventor(const ID:integer); function InventoresCuenta:integer; end; implementation {$R *.DFM} uses {$IFDEF PRUEBAS} {$IFNDEF VER130} Forms, {$ENDIF} Dialogs; {$ELSE} x FormMax; {$ENDIF} procedure TdmInventores_Model.RealizarProceso(const aTick:TmvvmNotifyEvent); begin fTick:=aTick; ProducirResultado; end; class function TdmInventores_Model.CreateModel:TdmInventores_Model; begin {$IFDEF PRUEBAS} Application.CreateForm(Self,result); {$ELSE} AppCreateDatamodule(Self,result); {$ENDIF} end; {$IFDEF PRUEBAS} procedure TdmInventores_Model.ProducirResultado; begin ShowMessage('RESULTADO'); end; {$ENDIF} procedure TdmInventores_Model.Tick; begin if Assigned(fTick) then fTick(Self); end; procedure TdmInventores_Model.DataModuleCreate(Sender: TObject); begin fListaInventores:=TList.Create; AddInventor('JACQUES E. BRANDENBERGER','CELOFÁN',1911); AddInventor('JUAN DE LA CIERVA','AUTOGIRO',1923); AddInventor('JOHN LOGIE BAIRD','TELEVISIÓN',1924); AddInventor('ERIK ROTHEIM','AEROSOL',1927); AddInventor('ALEXANDER FLEMING','PENICILINA',1928); AddInventor('MAX KNOLL - ERNST RUSKA','MICROSCOPIO ELECTRÓNICO',1931); AddInventor('ROBERT WATSON-WATT','RADAR',1935); AddInventor('WALLACE CAROTHERS','NAILON',1935); AddInventor('GEORGE Y LADISLAO BIRO','BOLÍGRAFO',1938); AddInventor('JOHN PRESPER ECKERT, JOHN W. MAUCHLY','ORDENADOR ELECTRÓNICO DIGITAL',1946); AddInventor('NARINDER SINGH KAPANY','FIBRA ÓPTICA',1955); AddInventor('MANUEL JALÓN COROMINAS','FREGONA',1956); AddInventor('CIENTÍFICOS SOVIÉTICOS','SATÉLITE ARTIFICIAL',1957); AddInventor('THEODORE MAIMAN, CHARLES H. TOWNES, ARTHUR L. SCHAWLOW','LÁSER',1960); AddInventor('MARCIAN EDWARD HOFF','MICROPROCESADOR',1971); AddInventor('ROBERT K. JARVIK','CORAZÓN ARTIFICIAL',1982); end; procedure TdmInventores_Model.DataModuleDestroy(Sender: TObject); begin while FListaInventores.Count<>0 do DestruirInventor(0); end; procedure TdmInventores_Model.ActualizarInventor(aInventor: TInventor); var InventorActual: TInventor; begin InventorActual:=LeerInventor(aInventor.ID); InventorActual.Nombre:=aInventor.Nombre; InventorActual.Invento:=aInventor.Invento; InventorActual.Anyo:=aInventor.Anyo; end; procedure TdmInventores_Model.AppendInventor(const aInventor: TInventor); var aID: integer; i: integer; begin aID:=0; for i:=0 to FListaInventores.Count-1 do begin if TInventor(FListaInventores[i]).ID>aID then aID:=TInventor(FListaInventores[i]).ID; end; Inc(aID); aInventor.ID:=aID; FListaInventores.Add(aInventor); end; function TdmInventores_Model.BuscaInventorID(const aID:integer):integer; var i: integer; begin for i:=0 to FListaInventores.Count-1 do begin if TInventor(FListaInventores[i]).ID=aID then begin result:=i; EXIT; end; end; result:=-1; end; procedure TdmInventores_Model.DestruirInventor(const ID: integer); var idx: integer; begin idx:=BuscaInventorID(ID); TInventor(FListaInventores[idx]).Free; FListaInventores.Delete(idx); end; function TdmInventores_Model.LeerInventor(const aID: integer): TInventor; var idx: integer; begin idx:=BuscaInventorID(aID); if idx=-1 then result:=nil else result:=TInventor(FListaInventores[idx]); end; procedure TdmInventores_Model.AddInventor(const aNombre,aInvento:string;const aAnyo: integer); begin AppendInventor(TInventor.Create(aNombre,aInvento,aAnyo)); end; { TInventor } constructor TInventor.Create(const aNombre,aInvento:string;const aAnyo: integer); begin inherited Create; Nombre:=aNombre; Invento:=aInvento; Anyo:=aAnyo; end; function TdmInventores_Model.InventoresCuenta: integer; begin result:=fListaInventores.Count; end; function TdmInventores_Model.LeerInventorIDX(const IDX: integer): TInventor; begin if idx=-1 then result:=nil else result:=TInventor(FListaInventores[idx]); end; end.
unit ToStringTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, SysUtils, uIntX, uConstants; type { TTestToString } TTestToString = class(TTestCase) published procedure VerySimple(); procedure Simple(); procedure Zero(); procedure Neg(); procedure Big(); procedure Binary(); procedure Octal(); procedure Octal2(); procedure Octal3(); procedure Hex(); procedure HexLower(); procedure OtherBase(); end; implementation procedure TTestToString.VerySimple(); var IntX: TIntX; begin IntX := TIntX.Create(11); AssertEquals('11', IntX.ToString()); end; procedure TTestToString.Simple(); var IntX: TIntX; begin IntX := TIntX.Create(12345670); AssertEquals('12345670', IntX.ToString()); end; procedure TTestToString.Zero(); var IntX: TIntX; begin IntX := TIntX.Create(0); AssertEquals('0', IntX.ToString()); end; procedure TTestToString.Neg(); var IntX: TIntX; begin IntX := TIntX.Create(TConstants.MinIntValue); AssertEquals(InttoStr(TConstants.MinIntValue), IntX.ToString()); end; procedure TTestToString.Big(); var IntX: TIntX; Int64X: Int64; begin IntX := TIntX.Create(TConstants.MaxIntValue); IntX := IntX + IntX + IntX + IntX + IntX + IntX + IntX + IntX; Int64X := TConstants.MaxIntValue; Int64X := Int64X + Int64X + Int64X + Int64X + Int64X + Int64X + Int64X + Int64X; AssertEquals(IntX.ToString(), InttoStr(Int64X)); end; procedure TTestToString.Binary(); var IntX: TIntX; begin IntX := TIntX.Create(19); AssertEquals('10011', IntX.ToString(2)); end; procedure TTestToString.Octal(); var IntX: TIntX; begin IntX := TIntX.Create(100); AssertEquals('144', IntX.ToString(8)); end; procedure TTestToString.Octal2(); var IntX: TIntX; begin IntX := TIntX.Create(901); AssertEquals('1605', IntX.ToString(8)); end; procedure TTestToString.Octal3(); var IntX: TIntX; begin IntX := $80000000; AssertEquals('20000000000', IntX.ToString(8)); IntX := $100000000; AssertEquals('40000000000', IntX.ToString(8)); end; procedure TTestToString.Hex(); var IntX: TIntX; begin IntX := TIntX.Create($ABCDEF); AssertEquals('ABCDEF', IntX.ToString(16)); end; procedure TTestToString.HexLower(); var IntX: TIntX; begin IntX := TIntX.Create($FF00FF00FF00FF); AssertEquals('ff00ff00ff00ff', IntX.ToString(16, False)); end; procedure TTestToString.OtherBase(); var IntX: TIntX; begin IntX := TIntX.Create(-144); AssertEquals('-{1}{4}', IntX.ToString(140)); end; initialization RegisterTest(TTestToString); end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_PAUSE.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_PAUSE; interface uses {$I uses.def} SysUtils, PAXCOMP_CONSTANTS, PAXCOMP_SYS; type TPauseRec = class public _EBP: IntPax; _ESP: IntPax; ESP0: IntPax; ProgOffset: Integer; StackFrame: Pointer; StackFrameSize: Integer; PaxExcFrame1: PPaxExcFrame; constructor Create; destructor Destroy; override; procedure Clear; procedure SaveStackFrame; function GetPtr(EBP_Value, Shift: Integer): Pointer; end; implementation //-- TPauseRec ----------------------------------------------------------------- constructor TPauseRec.Create; begin inherited; StackFrame := nil; Clear; end; destructor TPauseRec.Destroy; begin Clear; inherited; end; procedure TPauseRec.Clear; begin if StackFrame <> nil then FreeMem(StackFrame, StackFrameSize); _ESP := 0; ESP0 := 0; ProgOffset := 0; StackFrame := nil; StackFrameSize := 0; PaxExcFrame1 := nil; end; {$IFDEF PAX64} procedure _Save(I: Int64; P: Pointer; K: Int64); assembler; asm mov rax, I mov rbx, P mov rcx, K @@loop: mov rdx, [rax] mov [rbx], rdx sub rax, 8 sub rbx, 8 sub rcx, 1 cmp rcx, 0 jnz @@loop end; procedure TPauseRec.SaveStackFrame; var P: Pointer; I, K: Integer; begin if ESP0 = _ESP then Exit; if StackFrame <> nil then FreeMem(StackFrame, StackFrameSize); StackFrameSize := ESP0 - _ESP; if StackFrameSize < 0 then Exit; StackFrame := AllocMem(StackFrameSize); I := ESP0 - SizeOf(Pointer); P := ShiftPointer(StackFrame, StackFrameSize - SizeOf(Pointer)); K := StackFrameSize div SizeOf(Pointer); _Save(I, P, K); end; {$ELSE} procedure TPauseRec.SaveStackFrame; var P: Pointer; I, K: Integer; begin if ESP0 = _ESP then Exit; if StackFrame <> nil then FreeMem(StackFrame, StackFrameSize); StackFrameSize := ESP0 - _ESP; if StackFrameSize < 0 then Exit; StackFrame := AllocMem(StackFrameSize); I := ESP0 - 4; P := ShiftPointer(StackFrame, StackFrameSize - 4); K := StackFrameSize div 4; asm mov eax, I mov ebx, P mov ecx, K @@loop: mov edx, [eax] mov [ebx], edx sub eax, 4 sub ebx, 4 sub ecx, 1 cmp ecx, 0 jnz @@loop end; end; {$ENDIF} function TPauseRec.GetPtr(EBP_Value, Shift: Integer): Pointer; var K: Integer; begin K := EBP_Value + Shift - _ESP; result := ShiftPointer(StackFrame, K); end; end.
unit uEditorTypes; interface uses System.Classes, System.Math, Winapi.Windows, Vcl.Graphics, CCR.Exif, Dmitry.Graphics.Types, uDBForm; type TSetPointerToNewImage = procedure(Image: TBitmap) of object; TCancelTemporaryImage = procedure(Destroy: Boolean) of object; TBaseEffectProc = procedure(S, D: TBitmap; CallBack: TProgressCallBackProc = nil); TBaseEffectProcThreadExit = procedure(Image: TBitmap; SID: string) of object; TBaseEffectProcW = record Proc: TBaseEffectProc; name: string; ID: string; end; TBaseEffectProcedures = array of TBaseEffectProcW; TResizeProcedure = procedure(Width, Height: Integer; S, D: TBitmap; CallBack: TProgressCallBackProc = nil); TEffectOneIntParam = procedure(S, D: TBitmap; Int: Integer; CallBack: TProgressCallBackProc = nil); type TTool = (ToolNone, ToolPen, ToolCrop, ToolRotate, ToolResize, ToolEffects, ToolColor, ToolRedEye, ToolText, ToolBrush, ToolInsertImage); type TVBrushType = array of TPoint; type TImageEditorForm = class(TDBForm) protected function GetZoom: Extended; virtual; abstract; function GetFileName: string; virtual; abstract; function GetExifData: TExifData; virtual; abstract; public Transparency: Extended; VirtualBrushCursor: Boolean; VBrush: TVBrushType; function EditImage(Image: TBitmap): Boolean; virtual; abstract; function EditFile(Image: string; BitmapOut: TBitmap): Boolean; virtual; abstract; property Zoom: Extended read GetZoom; procedure MakeImage(ResizedWindow: Boolean = False); virtual; abstract; procedure DoPaint; virtual; abstract; property CurrentFileName: string read GetFileName; property ExifData: TExifData read GetExifData; end; function NormalizeRect(R : TRect) : TRect; procedure ClearBrush(var Brush : TVBrushType); procedure MakeRadialBrush(var Brush : TVBrushType; Size : Integer); implementation procedure ClearBrush(var Brush : TVBrushType); begin SetLength(Brush, 0); end; procedure MakeRadialBrush(var Brush : TVBrushType; Size : Integer); var I: Integer; Count: Integer; X: Extended; begin Count := Round(Size * 4 / Sqrt(2)); SetLength(Brush, Count); for I := 0 to Length(Brush) - 1 do begin X := 2 * I * Pi / Count; Brush[I].X := Round(Size * Cos(X)); Brush[I].Y := Round(Size * Sin(X)); end; end; function NormalizeRect(R: TRect): TRect; begin Result.Left := Min(R.Left, R.Right); Result.Right := Max(R.Left, R.Right); Result.Top := Min(R.Top, R.Bottom); Result.Bottom := Max(R.Top, R.Bottom); end; end.
unit Counters; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, StdCtrls, cxLookAndFeelPainters, cxButtons, ActnList; type TCountersAdd = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; CountEdit: TcxCurrencyEdit; Shape1: TShape; SumEdit: TcxCurrencyEdit; Label6: TLabel; Bevel1: TBevel; ApplyButton: TcxButton; CancelButton: TcxButton; PeriodStr: TLabel; Label5: TLabel; FavLabel: TLabel; OldEdit: TcxTextEdit; CurEdit: TcxTextEdit; ActionList1: TActionList; Action1: TAction; procedure OldEditKeyPress(Sender: TObject; var Key: Char); procedure CurEditKeyPress(Sender: TObject; var Key: Char); procedure SumEditKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure ApplyButtonClick(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public Sum_One:Double; ZeroF : Integer; { Public declarations } function GetZeroValls(Counter:string):Integer; end; var CountersAdd: TCountersAdd; implementation {$R *.dfm} // Определение количества нулей в начальных показателях, для приведения к нужному типу function TCountersAdd.GetZeroValls(Counter:string):Integer; var i : Integer; k : char; begin for i:=1 to SizeOf(Counter) do begin if Counter[i] <> '0' then begin Break; end; end; ZeroF:=i; Result:=i; end; procedure TCountersAdd.OldEditKeyPress(Sender: TObject; var Key: Char); var x:integer; begin if OldEdit.Text <> '' then begin if Key = #13 then begin Key := #0; GetZeroValls(OldEdit.Text); CurEdit.SetFocus; end; end; end; procedure TCountersAdd.CurEditKeyPress(Sender: TObject; var Key: Char); var x:integer; // y,z:integer; begin if CurEdit.Text <> '' then begin if Key = #13 then begin Key := #0; x:=StrToInt(CurEdit.Text); GetZeroValls(OldEdit.Text); CurEdit.Text:=Format('%.'+IntToStr(ZeroF+1)+'d',[x]); CountEdit.Text:=IntToStr(StrToInt(CurEdit.Text) - StrToInt(OldEdit.Text)); ApplyButton.SetFocus; end; end; SumEdit.Value:=Sum_One*CountEdit.Value; end; procedure TCountersAdd.SumEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; CurEdit.SetFocus; end; end; procedure TCountersAdd.FormShow(Sender: TObject); begin if OldEdit.Text <> '' then begin GetZeroValls(OldEdit.Text); CurEdit.SetFocus; end; end; procedure TCountersAdd.ApplyButtonClick(Sender: TObject); begin if (StrToInt(OldEdit.Text) < 0) or (StrToInt(CurEdit.Text) < 0) then begin ShowMessage('Показники не можуть бути меньше за нуль!'); OldEdit.SetFocus; Exit; end; if StrToInt(CurEdit.Text) = 0 then begin ShowMessage('Ви не ввели поточні показники лічильників!'); CurEdit.SetFocus; Exit; end; if StrToInt(OldEdit.Text) = 0 then begin ShowMessage('Ви не ввели минулі показники лічильників!'); OldEdit.SetFocus; Exit; end; if StrToInt(CurEdit.Text) < StrToInt(OldEdit.Text) then begin ShowMessage('Поточні показники не можуть бути меньшими за старі!'); CurEdit.SetFocus; Exit; end; if StrToInt(CurEdit.Text) < StrToInt(OldEdit.Text) then begin ShowMessage('Поточні показники не можуть бути меньшими за старі!'); CurEdit.SetFocus; Exit; end; ModalResult:=mrOk; end; procedure TCountersAdd.Action1Execute(Sender: TObject); begin ModalResult:=mrNone; Close; end; procedure TCountersAdd.FormCreate(Sender: TObject); begin // end; end.
namespace Anonymous_Methods; interface uses System.Threading, System.Windows.Forms; type Program = assembly static class public class method Main; end; implementation /// <summary> /// The main entry point for the application. /// </summary> //[STAThread] class method Program.Main; begin Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Default exception handler - using an anonymous method. Application.ThreadException += method (sender: Object; e: ThreadExceptionEventArgs); begin MessageBox.Show(e.Exception.Message); end; using lMainForm := new MainForm do Application.Run(lMainForm); end; end.
{/*! Provides Dll entry point and exported functions. \modified 2019-07-19 13:04 \author Wuping Xin */} namespace TsmPluginFx.Core; uses rtl; {/*! Invokes a user-supplied editor for editing plugin parameters. */} [SymbolName('OpenParameterEditor'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method OpenParameterEditor; begin TsmPlugin.Singleton.OpenParameterEditor; end; {/*! Activates the plugin. An associated user interface may be generated and inserted into the main user interface of the hosting microsimulator. */} [SymbolName('EnablePlugin'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method EnablePlugin; begin SetEnabled(true); end; {/*! Deactivates the plugin. An associated user interface, if any, will be removed from the main user interface of the hosting microsimulator. */} [SymbolName('DisablePlugin'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method DisablePlugin; begin SetEnabled(false); end; {/*! Returns a descriptive string about the plugin. \param aPluginInfo A 0-indexed char pointer referencing a null-terminated string. If nil, then aSize will be ingored, and return value is the actual size of the plugin info string plus 1. The caller should allocate enough memory based on the returned size, and call this function again, with a non-null pointer. \param aSize Size of the memory space allocated for aPluginInfo, including the null character. \remark The caller is responsible for allocating and releasing memory for aPluginInfo. \returns Actual number of characters copied to aPluginInfo, including the null character. */} [SymbolName('GetPluginInfo'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method GetPluginInfo(aPluginInfo: LPWSTR; aSize: DWORD): DWORD; begin exit StringToLPWSTR(TsmPlugin.Singleton.PluginInfo, aPluginInfo, aSize); end; [SymbolName('GetPluginName'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method GetPluginName(aPluginName: LPWSTR; aSize: DWORD): DWORD; begin exit StringToLPWSTR(TsmPlugin.Singleton.PluginName, aPluginName, aSize); end; [SymbolName('GetPluginVersion'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method GetPluginVersion(aPluginVersion: LPWSTR; aSize: DWORD): DWORD; begin exit StringToLPWSTR(TsmPlugin.Singleton.PluginVersion, aPluginVersion, aSize); end; [SymbolName('GetEnabled'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method GetEnabled: Boolean; begin exit TsmPlugin.Singleton.Enabled; end; [SymbolName('SetEnabled'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method SetEnabled(aValue: Boolean); begin TsmPlugin.Singleton.Enabled := aValue; end; {/*! Returns a newly created user vehicle pointer. \param aID Vehicle ID. \param aProperty Vehicle property. \param aFlags Vehicle monitor option. */} [SymbolName('CreateUserVehicle'), DLLExport, CallingConvention(CallingConvention.Stdcall)] method CreateUserVehicle(aID: LongInt; aProperty: ^VehicleProperty; aFlags: ^VehicleMonitorOption): ^UserVehicle; begin if assigned(TsmPlugin.Singleton.VehicleFactory) then result := TsmPlugin.Singleton.VehicleFactory.CreateUserVehicle(aID, aProperty, aFlags); end; {/*! Dll entry point. */} [SymbolName('__elements_dll_main', ReferenceFromMain := true)] method DllMain(aModule: HMODULE; aReason: DWORD; aReserved: ^Void): Boolean; begin method GetPluginDllPath: String; begin var lBuffer: array of Char := new Char[MAX_PATH]; GetModuleFileName(aModule, lBuffer, MAX_PATH); exit String.FromCharArray(lBuffer); end; case aReason of DLL_PROCESS_ATTACH: begin var lPluginDir: String := Path.GetParentDirectory(GetPluginDllPath); exit TsmPlugin.CreateSingleton(lPluginDir); end; DLL_PROCESS_DETACH: exit true; DLL_THREAD_ATTACH: exit true; DLL_THREAD_DETACH: exit true; end; end; end.
unit NewFrontiers.Validation.Base; interface uses NewFrontiers.Validation; type /// <summary> /// Nur Buchstaben /// </summary> TValidatorLetter = class(TValidator) public function validate(aString: string): boolean; override; end; /// <summary> /// Feld muss ausgefüllt werden /// </summary> TValidatorRequired = class(TValidator) public function validate(aString: string): boolean; override; end; /// <summary> /// Nur Zahlen /// </summary> TValidatorDigit = class(TValidator) public function validate(aString: string): boolean; override; end; /// <summary> /// Prüft auf eine gültige E-Mail-Adresse /// </summary> TValidatorEmail = class(TValidator) public function validate(aString: string): boolean; override; end; implementation uses NewFrontiers.Utility.StringUtil, NewFrontiers.Utility.Exceptions, System.Character, RegularExpressions; { TValidatorLetter } function TValidatorLetter.validate(aString: string): boolean; var i: Integer; begin result := true; for i := 1 to length(aString) do result := result and TCharacter.isLetter(aString[i]); if (not result) then _lastError := 'Bitte geben Sie in diesem Feld nur Buchstaben ein'; end; { TValidatorRequired } function TValidatorRequired.validate(aString: string): boolean; begin result := not TStringUtil.isEmpty(aString); if (not result) then _lastError := 'Dieses Feld muss ausgefüllt werden'; end; { TValidatorDigit } function TValidatorDigit.validate(aString: string): boolean; var i: Integer; begin result := true; for i := 1 to length(aString) do result := result and TCharacter.IsDigit(aString[i]); if (not result) then _lastError := 'Bitte geben Sie in diesem Feld nur Zahlen ein'; end; { TValidatorEmail } function TValidatorEmail.validate(aString: string): boolean; var mailPattern: TRegEx; begin if (TStringUtil.isEmpty(aString)) then begin result := true; exit; end; mailPattern := TRegEx.Create('[A-Za-z0-9._-]+@[A-Za-z0-9]+.[A-Za-z.]+'); result := mailPattern.Match(aString).Success; if (not result) then _lastError := 'Bitte geben Sie eine gültige EMail-Adresse ein'; end; end.
unit tvl_udatabinder; interface uses Classes, SysUtils, trl_irttibroker, Controls, StdCtrls, ExtCtrls, fgl, Graphics, tvl_udatabinders, Grids, SynEdit, trl_ipersist, tvl_ibindings, EditBtn, trl_urttibroker, ComCtrls; type { TCustomDataSlotsItem } TCustomDataSlotsItem = class private fDataItem: IRBDataItem; protected procedure DoBind(const AControl: TWinControl); virtual; abstract; procedure DoDataChange; virtual; abstract; procedure DoFlush(AControl: TControl = nil); virtual; abstract; public constructor Create(const ADataItem: IRBDataItem); virtual; procedure Bind(const AControl: TWinControl); procedure DataChange; procedure Flush(AControl: TControl = nil); procedure RegisterChangeEvent(AEvent: TBinderChangeEvent); virtual; abstract; procedure UnregisterChangeEvent(AEvent: TBinderChangeEvent); virtual; abstract; property DataItem: IRBDataItem read fDataItem; end; { TDataSlotsItem } TDataSlotsItem = class(TCustomDataSlotsItem) protected type TBinderItems = specialize TFPGObjectList<TEditBinder>; private fBinders: TBinderItems; fRecallDataChangeEvents: TBinderChangeEvents; function CreateBinder(const AControl: TWinControl): TEditBinder; function FindBinder(const AControl: TWinControl): TEditBinder; protected procedure PushDataChange(const ADataItem: IRBDataItem; AControl: TWinControl); procedure RecallDataChange(const ADataItem: IRBDataItem; AControl: TWinControl); protected procedure DoBind(const AControl: TWinControl); override; procedure DoDataChange; override; procedure DoFlush(AControl: TControl = nil); override; public constructor Create(const ADataItem: IRBDataItem); override; destructor Destroy; override; procedure RegisterChangeEvent(AEvent: TBinderChangeEvent); override; procedure UnregisterChangeEvent(AEvent: TBinderChangeEvent); override; end; { TObjectSlotsItem } TObjectSlotsItem = class(TCustomDataSlotsItem) protected type TBinderItems = specialize TFPGMapInterfacedObjectData<Pointer, IRBDataBinder>; private fBinders: TBinderItems; protected procedure DoBind(const AControl: TWinControl); override; procedure DoDataChange; override; procedure DoFlush(AControl: TControl = nil); override; public constructor Create(const ADataItem: IRBDataItem); override; destructor Destroy; override; procedure RegisterChangeEvent(AEvent: TBinderChangeEvent); override; procedure UnregisterChangeEvent(AEvent: TBinderChangeEvent); override; end; { TDataSlots } TDataSlots = class private type TDataEditItems = specialize TFPGMapObject<string, TCustomDataSlotsItem>; private fItems: TDataEditItems; fData: IRBData; fContainer: TWinControl; function FindControl(const AName: string; AContainer: TWinControl): TWinControl; procedure ActualizeItems; function GetData: IRBData; procedure SetData(AValue: IRBData); private function GetItems(AIndex: Integer): TCustomDataSlotsItem; procedure SetItems(AIndex: Integer; AValue: TCustomDataSlotsItem); function GetItemsCount: integer; procedure SetItemsCount(AValue: integer); function GetItemByName(const AName: string): TCustomDataSlotsItem; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure BindArea(const AContainer: TWinControl; const AData: IRBData); procedure BindControl(AControl: TWinControl; const AName: string); procedure BindControl(AControl: TWinControl; const AItem: IRBDataItem); procedure DataChange; procedure Flush(AControl: TControl = nil); property Data: IRBData read GetData write SetData; public property Items[AIndex: integer]: TCustomDataSlotsItem read GetItems write SetItems; default; property ItemsCount: integer read GetItemsCount write SetItemsCount; property ItemByName[const AName: string]: TCustomDataSlotsItem read GetItemByName; end; { TRBDataBinder } TRBDataBinder = class(TInterfacedObject, IRBDataBinder) protected fDataSlots: TDataSlots; function GetDataSlots: TDataSlots; property DataSlots: TDataSlots read GetDataSlots; protected // IRBDataBinder procedure BindArea(AContainer: TWinControl; const AData: IRBData); procedure BindControl(AControl: TWinControl; const AName: string); procedure Unbind; procedure DataChange; procedure Flush(AControl: TControl = nil); function GetData: IRBData; procedure SetData(AValue: IRBData); property AData: IRBData read GetData write SetData; procedure RegisterChangeEvent(const AItemName: string; AEvent: TBinderChangeEvent); procedure UnregisterChangeEvent(const AItemName: string; AEvent: TBinderChangeEvent); public destructor Destroy; override; end; EDataBinder = class(Exception); implementation { TObjectSlotsItem } procedure TObjectSlotsItem.DoBind(const AControl: TWinControl); var mInd: integer; mBinder: IRBDataBinder; mData: IRBData; begin mInd := fBinders.IndexOf(AControl); if mInd = -1 then begin mBinder := TRBDataBinder.Create; mInd := fBinders.Add(AControl, mBinder); end; fBinders.Data[mInd].Unbind; mData := TRBData.Create(fDataItem.AsObject); fBinders.Data[mInd].BindArea(AControl, mData); DataChange; end; procedure TObjectSlotsItem.DoDataChange; var i: integer; begin for i := 0 to fBinders.Count - 1 do fBinders.Data[i].DataChange; end; procedure TObjectSlotsItem.DoFlush(AControl: TControl); var i: integer; begin for i := 0 to fBinders.Count - 1 do fBinders.Data[i].Flush(AControl); end; constructor TObjectSlotsItem.Create(const ADataItem: IRBDataItem); begin inherited; fBinders := TBinderItems.Create; end; destructor TObjectSlotsItem.Destroy; begin FreeAndNil(fBinders); inherited Destroy; end; procedure TObjectSlotsItem.RegisterChangeEvent(AEvent: TBinderChangeEvent); var i, j: integer; begin for i := 0 to fBinders.Count - 1 do for j := 0 to fBinders.Data[i].Data.Count - 1 do fBinders.Data[i].RegisterChangeEvent(fBinders.Data[i].Data[j].Name, AEvent); end; procedure TObjectSlotsItem.UnregisterChangeEvent(AEvent: TBinderChangeEvent); var i, j: integer; begin for i := 0 to fBinders.Count - 1 do for j := 0 to fBinders.Data[i].Data.Count - 1 do fBinders.Data[i].UnregisterChangeEvent(fBinders.Data[i].Data[j].Name, AEvent); end; { TDataSlotsItem } function TDataSlotsItem.CreateBinder(const AControl: TWinControl): TEditBinder; begin if AControl is TCustomEdit then Result := TTextBinder.Create else if AControl is TCustomEditButton then Result := TTextBtnBinder.Create else if AControl is TCustomComboBox then begin if (fDataItem.IsInterface) and Supports(fDataItem.AsInterface, IPersistRef) then begin Result := TOfferRefBinder.Create; end else if fDataItem.EnumNameCount > 0 then begin Result := TOfferEnumBinder.Create; end; end else if AControl is TCustomStringGrid then Result := TListBinder.Create else if AControl is TCustomCheckBox then Result := TBoolBinder.Create else if AControl is TCustomSynEdit then Result := TMemoBinder.Create else if AControl is TCustomPage then Result := TTabSheetBinder.Create end; function TDataSlotsItem.FindBinder(const AControl: TWinControl): TEditBinder; var i: integer; begin Result := nil; for i := 0 to fBinders.Count - 1 do if fBinders[i].Control = AControl then begin Result := fBinders[i]; Break; end; end; procedure TDataSlotsItem.PushDataChange(const ADataItem: IRBDataItem; AControl: TWinControl); var mBinder: TEditBinder; begin // when one control change, this will tell others control on this same DataItem // to refresh for mBinder in fBinders do if mBinder.Control <> AControl then mBinder.DataToControl; end; procedure TDataSlotsItem.RecallDataChange(const ADataItem: IRBDataItem; AControl: TWinControl); var mEvent: TBinderChangeEvent; begin for mEvent in fRecallDataChangeEvents do mEvent(ADataItem, AControl); end; procedure TDataSlotsItem.DoBind(const AControl: TWinControl); var mBinder: TEditBinder; begin mBinder := FindBinder(AControl); if mBinder = nil then begin mBinder := CreateBinder(AControl); mBinder.RegisterChangeEvent(@PushDataChange); mBinder.RegisterChangeEvent(@RecallDataChange); fBinders.Add(mBinder); end; mBinder.Unbind; mBinder.Bind(AControl, fDataItem); DataChange; end; procedure TDataSlotsItem.DoDataChange; var mBinder: TEditBinder; begin for mBinder in fBinders do mBinder.DataToControl; end; procedure TDataSlotsItem.DoFlush(AControl: TControl); var mBinder: TEditBinder; begin for mBinder in fBinders do if (AControl = nil) or (AControl = mBinder.Control) then mBinder.ControlToData; end; constructor TDataSlotsItem.Create(const ADataItem: IRBDataItem); begin inherited; fBinders := TBinderItems.Create; fRecallDataChangeEvents := TBinderChangeEvents.Create; end; destructor TDataSlotsItem.Destroy; begin FreeAndNil(fRecallDataChangeEvents); FreeAndNil(fBinders); inherited Destroy; end; procedure TDataSlotsItem.RegisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fRecallDataChangeEvents.IndexOf(AEvent); if mIndex = -1 then fRecallDataChangeEvents.Add(AEvent); end; procedure TDataSlotsItem.UnregisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fRecallDataChangeEvents.IndexOf(AEvent); if mIndex <> -1 then fRecallDataChangeEvents.Delete(mIndex); end; { TCustomDataSlotsItem } constructor TCustomDataSlotsItem.Create(const ADataItem: IRBDataItem); begin fDataItem := ADataItem; end; procedure TCustomDataSlotsItem.DataChange; begin DoDataChange; end; procedure TCustomDataSlotsItem.Flush(AControl: TControl = nil); begin DoFlush(AControl); end; procedure TCustomDataSlotsItem.Bind(const AControl: TWinControl); begin DoBind(AControl); end; { TDataSlots } function TDataSlots.GetItems(AIndex: Integer): TCustomDataSlotsItem; begin Result := fItems.Data[AIndex]; end; procedure TDataSlots.SetData(AValue: IRBData); begin fData := AValue; ActualizeItems; end; function TDataSlots.GetItemByName(const AName: string): TCustomDataSlotsItem; var mInd: Integer; begin mInd := fItems.IndexOf(AName); if mInd = -1 then raise EDataBinder.CreateFmt('GetItemByName - data slot item %s not exists', [AName]); Result := fItems.Data[mInd]; if Result = nil then raise EDataBinder.CreateFmt('GetItemByName - data slot item %s point to nil', [AName]); end; function TDataSlots.GetItemsCount: integer; begin Result := fItems.Count; end; function TDataSlots.FindControl(const AName: string; AContainer: TWinControl): TWinControl; var i: integer; begin Result := nil; for i := 0 to AContainer.ControlCount - 1 do begin if not (AContainer.Controls[i] is TWinControl) then Continue; Result := FindControl(AName, AContainer.Controls[i] as TWinControl); if Assigned(Result) then Exit; if SameText(AName + '_bind', AContainer.Controls[i].Name) then begin Result := AContainer.Controls[i] as TWinControl; Exit; end; end; end; procedure TDataSlots.ActualizeItems; var i: integer; mControl: TWinControl; begin fItems.Clear; for i := 0 to fData.Count - 1 do begin // for now create only items with control mControl := FindControl(fData[i].Name, fContainer); if mControl = nil then Continue; BindControl(mControl, fData[i]); end; end; procedure TDataSlots.BindControl(AControl: TWinControl; const AName: string); var mItem: IRBDataItem; begin if fData = nil then raise EDataBinder.Create('Data not set'); mItem := fData.FindItem(AName); if mItem = nil then raise EDataBinder.CreateFmt('Data item %s not found', [AName]); BindControl(AControl, mItem); end; procedure TDataSlots.BindControl(AControl: TWinControl; const AItem: IRBDataItem); var mInd: integer; begin if AItem = nil then raise EDataBinder.Create('Cannot add empty item'); mInd := fItems.IndexOf(AItem.Name); if mInd = -1 then begin if AItem.IsObject then mInd := fItems.Add(AItem.Name, TObjectSlotsItem.Create(AItem)) else mInd := fItems.Add(AItem.Name, TDataSlotsItem.Create(AItem)); end; Items[mInd].Bind(AControl); end; function TDataSlots.GetData: IRBData; begin Result := fData; end; procedure TDataSlots.SetItems(AIndex: Integer; AValue: TCustomDataSlotsItem); begin fItems.Data[AIndex] := AValue; end; procedure TDataSlots.SetItemsCount(AValue: integer); begin fItems.Count := AValue; end; procedure TDataSlots.AfterConstruction; begin inherited AfterConstruction; fItems := TDataEditItems.Create; end; procedure TDataSlots.BeforeDestruction; begin FreeAndNil(fItems); inherited BeforeDestruction; end; procedure TDataSlots.BindArea(const AContainer: TWinControl; const AData: IRBData); begin fContainer := AContainer; Data := AData; end; procedure TDataSlots.DataChange; var i: Integer; begin for i := 0 to ItemsCount - 1 do Items[i].DataChange; end; procedure TDataSlots.Flush(AControl: TControl = nil); var i: Integer; begin for i := 0 to ItemsCount - 1 do Items[i].Flush(AControl); end; { TRBDataBinder } destructor TRBDataBinder.Destroy; begin FreeAndNil(fDataSlots); inherited Destroy; end; function TRBDataBinder.GetDataSlots: TDataSlots; begin if fDataSlots = nil then fDataSlots := TDataSlots.Create; Result := fDataSlots; end; procedure TRBDataBinder.BindArea(AContainer: TWinControl; const AData: IRBData); begin DataSlots.BindArea(AContainer, AData); end; procedure TRBDataBinder.BindControl(AControl: TWinControl; const AName: string); begin DataSlots.BindControl(AControl, AName); end; procedure TRBDataBinder.Unbind; begin FreeAndNil(fDataSlots); end; procedure TRBDataBinder.DataChange; begin fDataSlots.DataChange; end; procedure TRBDataBinder.Flush(AControl: TControl = nil); begin fDataSlots.Flush(AControl); end; function TRBDataBinder.GetData: IRBData; begin Result := fDataSlots.Data; end; procedure TRBDataBinder.SetData(AValue: IRBData); begin fDataSlots.Data := AValue; end; procedure TRBDataBinder.RegisterChangeEvent(const AItemName: string; AEvent: TBinderChangeEvent); var mSlotItem: TCustomDataSlotsItem; begin mSlotItem := fDataSlots.ItemByName[AItemName]; mSlotItem.RegisterChangeEvent(AEvent) end; procedure TRBDataBinder.UnregisterChangeEvent(const AItemName: string; AEvent: TBinderChangeEvent); var mSlotItem: TCustomDataSlotsItem; begin mSlotItem := fDataSlots.ItemByName[AItemName]; mSlotItem.UnregisterChangeEvent(AEvent) end; end.
//********************************************************************************************************************** // $Id: udTranProps.pas,v 1.10 2006-08-23 15:19:11 dale Exp $ //---------------------------------------------------------------------------------------------------------------------- // DKLang Translation Editor // Copyright ęDK Software, http://www.dk-soft.org/ //********************************************************************************************************************** unit udTranProps; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TntForms, DKLang, StdCtrls, ExtCtrls, TB2MRU, TntStdCtrls, TntExtCtrls, DKLTranEdFrm; type TdTranProps = class(TDKLTranEdForm) bCancel: TTntButton; bHelp: TTntButton; bOK: TTntButton; cbSrcLang: TTntComboBox; cbTargetApp: TTntComboBox; cbTranLang: TTntComboBox; dklcMain: TDKLanguageController; eAuthor: TTntEdit; lAdditionalParams: TTntLabel; lAuthor: TTntLabel; lSrcLang: TTntLabel; lTargetApp: TTntLabel; lTranLang: TTntLabel; mAdditionalParams: TTntMemo; MRUTargetApp: TTBMRUList; pMain: TTntPanel; procedure AdjustOKCancel(Sender: TObject); procedure bOKClick(Sender: TObject); private // The translations which properties are to edit FTranslations: TDKLang_CompTranslations; // Source and target LangIDs FSrcLangID: LANGID; FTranLangID: LANGID; // Loads the language list into cbLang procedure LoadLanguages; protected procedure DoCreate; override; procedure ExecuteFinalize; override; procedure ExecuteInitialize; override; end; function EditTranslationProps(ATranslations: TDKLang_CompTranslations; var wSrcLangID, wTranLangID: LANGID): Boolean; implementation {$R *.dfm} uses Registry, ConsVars; const // Params considered to be known (they do not appear in 'Additional parameters' list) asKnownParams: Array[0..5] of String = ( SDKLang_TranParam_LangID, SDKLang_TranParam_SourceLangID, SDKLang_TranParam_Author, SDKLang_TranParam_Generator, SDKLang_TranParam_LastModified, SDKLang_TranParam_TargetApplication); function EditTranslationProps(ATranslations: TDKLang_CompTranslations; var wSrcLangID, wTranLangID: LANGID): Boolean; begin with TdTranProps.Create(Application) do try FTranslations := ATranslations; FSrcLangID := wSrcLangID; FTranLangID := wTranLangID; Result := ExecuteModal; if Result then begin wSrcLangID := FSrcLangID; wTranLangID := FTranLangID; end; finally Free; end; end; // Returns True if parameter is in asKnownParams[] function IsParamKnown(const sParam: String): Boolean; var i: Integer; begin for i := 0 to High(asKnownParams) do if SameText(sParam, asKnownParams[i]) then begin Result := True; Exit; end; Result := False; end; //=================================================================================================================== // TdTranProps //=================================================================================================================== procedure TdTranProps.AdjustOKCancel(Sender: TObject); begin if Visible then bOK.Enabled := (cbSrcLang.ItemIndex>=0) and (cbTranLang.ItemIndex>=0); end; procedure TdTranProps.bOKClick(Sender: TObject); var i: Integer; begin // Get LangIDs FSrcLangID := GetCBObject(cbSrcLang); FTranLangID := GetCBObject(cbTranLang); if FSrcLangID=FTranLangID then TranEdError(DKLangConstW('SErrMsg_SrcAndTranLangsAreSame')); // Update translation params FTranslations.Params.Clear; with FTranslations.Params do begin Values[SDKLang_TranParam_TargetApplication] := cbTargetApp.Text; Values[SDKLang_TranParam_Author] := eAuthor.Text; end; // Fill additional parameters for i := 0 to mAdditionalParams.Lines.Count-1 do if not IsParamKnown(mAdditionalParams.Lines.Names[i]) then FTranslations.Params.Add(mAdditionalParams.Lines[i]); // Update MRU MRUTargetApp.Add(cbTargetApp.Text); ModalResult := mrOK; end; procedure TdTranProps.DoCreate; begin inherited DoCreate; // Initialize help context ID HelpContext := IDH_iface_dlg_tran_props; end; procedure TdTranProps.ExecuteFinalize; var rif: TRegIniFile; begin // Save settings rif := TRegIniFile.Create(SRegKey_Root); try MRUTargetApp.SaveToRegIni(rif, SRegSection_MRUTargetApp); finally rif.Free; end; inherited ExecuteFinalize; end; procedure TdTranProps.ExecuteInitialize; var i: Integer; rif: TRegIniFile; begin inherited ExecuteInitialize; // Load settings rif := TRegIniFile.Create(SRegKey_Root); try MRUTargetApp.LoadFromRegIni(rif, SRegSection_MRUTargetApp); finally rif.Free; end; // Load languages LoadLanguages; cbTargetApp.Items.Assign(MRUTargetApp.Items); with FTranslations.Params do begin SetCBObject(cbSrcLang, FSrcLangID); SetCBObject(cbTranLang, FTranLangID); cbTargetApp.Text := Values[SDKLang_TranParam_TargetApplication]; eAuthor.Text := Values[SDKLang_TranParam_Author]; end; // Fill additional parameters for i := 0 to FTranslations.Params.Count-1 do if not IsParamKnown(FTranslations.Params.Names[i]) then mAdditionalParams.Lines.Add(FTranslations.Params[i]); AdjustOKCancel(nil); end; procedure TdTranProps.LoadLanguages; var i: Integer; L: LCID; begin for i := 0 to Languages.Count-1 do begin L := Languages.LocaleID[i]; if L and $ffff0000=0 then cbSrcLang.AddItem(WideFormat('%.5d - 0x%0:.4x - %s', [L, Languages.Name[i]]), Pointer(L)); end; // Copy the language list into cbTranLang cbTranLang.Items.Assign(cbSrcLang.Items); end; end.
unit uServers; interface uses {$ifdef MSWINDOWS} Winapi.Windows, {$else .POSIX} {$endif} System.SysUtils, System.Classes, System.Generics.Collections, System.JSON; var WORK_MODE: Boolean = False; const SERVER_PORT = 1234; TEXT_CONTENT = 'text/plain'; JSON_CONTENT = 'application/json'; BLANK_RESPONSE = 'OK'; BLANK_RESPONSE_UTF8: UTF8String = UTF8String(BLANK_RESPONSE); BLANK_RESPONSE_BYTES: TBytes = [Ord('O'), Ord('K')]; procedure LogServerListening(const AServer: TObject); procedure SleepLoop; procedure ProcessJson(const ATargetJson, ASourceJson: TJSONObject); overload; function ProcessJson(const AJson: TJSONObject): string; overload; function ProcessJson(const AStream: TStream): string; overload; function ProcessJson(const AJson: string): string; overload; function ProcessJson(const AJson: TBytes): TBytes; overload; implementation var Terminated: Boolean = False; {$ifdef MSWINDOWS} function CtrlHandler(Ctrl: Longint): LongBool; stdcall; begin case (Ctrl) of CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT: begin Terminated := True; end; end; Result := True; end; procedure InitKeyHandler; begin SetConsoleCtrlHandler(@CtrlHandler, True); end; {$else .POSIX} // ToDo procedure InitKeyHandler; begin end; {$endif} procedure LogServerListening(const AServer: TObject); const MODES: array[Boolean] of string = ('blank', 'work'); begin Write(AServer.UnitName, ' (', MODES[WORK_MODE], ' mode) port ', SERVER_PORT, ' listening...'); end; procedure SleepLoop; begin while (not Terminated) do begin Sleep(1000); end; end; (* Request: { "product": "test", "requestId": "{BC6B8989-DAB7-484E-9AD3-F7C34A800A1A}", "group": { "kind": "clients", "default": true, "balance": 109240.59, "dates": [ "2020-01-12T10:53:17.773Z", "2020-11-10T06:47:04.462Z", "2020-01-01T00:00:00.007Z", "2020-03-14T22:36:33.316Z", "2020-04-09T14:47:25.082Z", "2020-09-02T03:41:33.744Z", "2020-04-26T07:44:07.926Z", "2020-02-29T01:19:41.793Z", "2020-05-15T20:48:28.880Z", "2020-06-04T08:54:07.931Z" ] } }*) (* Response: { "product": "test", "requestId": "{BC6B8989-DAB7-484E-9AD3-F7C34A800A1A}", "client": { "balance": 109240.59, "minDate": "2020-01-01T00:00:00.007Z", "maxDate": "2020-11-10T06:47:04.462Z" } }*) procedure ProcessJson(const ATargetJson, ASourceJson: TJSONObject); var i: Integer; LClient, LGroup: TJSONObject; LDates: TJSONArray; LDate: TDateTime; LMinDate, LMaxDate: TDateTime; function InternalStrToDateTime(const AValue: string): TDateTime; var LYear, LMonth, LDay, LHour, LMinute, LSecond, LMillisecond: Word; begin LYear := StrToInt(Copy(AValue, 1, 4)); LMonth := StrToInt(Copy(AValue, 6, 2)); LDay := StrToInt(Copy(AValue, 9, 2)); LHour := StrToInt(Copy(AValue, 12, 2)); LMinute := StrToInt(Copy(AValue, 15, 2)); LSecond := StrToInt(Copy(AValue, 18, 2)); LMillisecond := StrToInt(Copy(AValue, 21, 3)); Result := EncodeDate(LYear, LMonth, LDay) + EncodeTime(LHour, LMinute, LSecond, LMillisecond); end; function InternalDateTimeToStr(const AValue: TDateTime): string; begin Result := FormatDateTime('yyyy-mm-dd', AValue) + 'T' + FormatDateTime('hh:mm:ss.zzz', AValue) + 'Z'; end; begin LGroup := ASourceJson.GetValue('group') as TJSONObject; ATargetJson.AddPair('product', ASourceJson.GetValue('product').Clone as TJsonValue); ATargetJson.AddPair('requestId', ASourceJson.GetValue('requestId').Clone as TJsonValue); LDates := LGroup.GetValue('dates') as TJSONArray; LMinDate := MaxDateTime; LMaxDate := MinDateTime; for i := 0 to LDates.Count - 1 do begin LDate := InternalStrToDateTime((LDates.Items[i] as TJSONString).Value); if (LDate < LMinDate) then LMinDate := LDate; if (LDate > LMaxDate) then LMaxDate := LDate; end; LClient := TJSONObject.Create; ATargetJson.AddPair('client', LClient); LClient.AddPair('balance', LGroup.GetValue('balance').Clone as TJsonValue); LClient.AddPair('minDate', InternalDateTimeToStr(LMinDate)); LClient.AddPair('maxDate', InternalDateTimeToStr(LMaxDate)); end; function ProcessJson(const AJson: TJSONObject): string; var LTargetJson: TJSONObject; begin LTargetJson := TJSONObject.Create; try ProcessJson(LTargetJson, AJson); Result := LTargetJson.ToString; finally LTargetJson.Free; end; end; function ProcessJson(const AStream: TStream): string; var LBuffer: TBytes; LCount: NativeUInt; LValue: TJSONValue; begin LCount := AStream.Size; SetLength(LBuffer, LCount); AStream.ReadBuffer(Pointer(LBuffer)^, LCount); LValue := TJSONObject.ParseJSONValue(LBuffer, 0); try Result := ProcessJson(LValue as TJSONObject); finally LValue.Free; end; end; function ProcessJson(const AJson: string): string; var LValue: TJSONValue; begin LValue := TJSONObject.ParseJSONValue(AJson); try Result := ProcessJson(LValue as TJSONObject); finally LValue.Free; end; end; function ProcessJson(const AJson: TBytes): TBytes; var LTargetJson: TJSONObject; LSourceJson: TJSONValue; begin LTargetJson := TJSONObject.Create; try LSourceJson := TJSONObject.ParseJSONValue(AJson, 0); try ProcessJson(LTargetJson, LSourceJson as TJSONObject); finally LSourceJson.Free; end; SetLength(Result, LTargetJson.EstimatedByteSize); SetLength(Result, LTargetJson.ToBytes(Result, 0)); finally LTargetJson.Free; end; end; initialization InitKeyHandler; if (ParamStr(1) = '1') then begin WORK_MODE := True; end; end.
unit Validade; interface type TValidade = class private FData: TDateTime; public property Data: TDateTime read FData write FData; constructor Create; overload; constructor Create(Data: TDateTime); overload; end; implementation { TValidade } constructor TValidade.Create; begin end; constructor TValidade.Create(Data: TDateTime); begin Self.Data := Data; end; end.
unit Contour; {Demonstrates contour drawing features of MathImage, as well as the use of the TSurface/TLevelSurface object. The routines marked by *********** use MathImage methods. The filled level lines routine is very memory intensive. I found Robert Lee's memory manager replacement (available from Code Central) to a) speed up things a lot, b) allow me to use more grid points.} interface uses Winapi.Windows, Winapi.Messages, System.Classes, System.SysUtils, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.Clipbrd, // MathImage, OverlayImage; const gxmin = -3; gxmax = 6.5; gymin = -4; gymax = 4; {graph domain} xMesh = 100; yMesh = 100; {graph mesh} c = 4; colorarray: array[0..13] of TColor = ($00CB9F74, $00D8AD49, $00E6C986, $00F2E3C1, $00DAF0C4, $00A6E089, $0086D560, $0065CFB5, $008DC5FC, $0075D5FD, $0078E1ED, $00ACEDF4, $00D0F2F7, $00F2FBFD); levelsarray: array[0..13] of MathFloat = (-1, -0.7, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.1, 1.4, 1.6, 2.2, 4); type TContourform = class(TForm) Panel1: TPanel; ContourlinesButton: TButton; ColorDialog1: TColorDialog; Panel2: TPanel; FilledContoursButton: TButton; GraphImage: TMathImage; Label1: TLabel; procedure ContourlinesButtonClick(Sender: TObject); procedure GraphImageResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FilledContoursButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); private CurrentType: Integer; GraphSurface: TLevelSurface; LevelsMade: Boolean; procedure Graph(x, y: MathFloat; var z: MathFloat); procedure MakeGraphSurface; protected procedure CreateParams(var Params: TCreateParams); override; public values: array[0..13] of TLabel; Colors: array[0..13] of TLabel; end; var ContourForm: TContourform; implementation uses MDemo1; {$R *.DFM} procedure TContourform.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin WndParent := Demoform.Handle; Parent := Demoform; Style := WS_CHILD or WS_CLIPSIBLINGS or WS_CLIPCHILDREN; Align := alClient; end; end; {*************************************} procedure TContourform.FormCreate(Sender: TObject); var i: Integer; begin makegraphsurface; ControlStyle := ControlStyle + [csOpaque]; currenttype := 1; for i := 0 to 13 do begin values[i] := TLabel.Create(self); with values[i] do begin Top := Label1.Top + Label1.Height + 5 + i * Label1.Height; Left := Label1.Left; Parent := Panel1; Caption := FloatToStrf(levelsarray[i], ffgeneral, 4, 4); end; Colors[i] := TLabel.Create(self); with Colors[i] do begin autosize := False; Caption := ''; Left := Label1.Left + Label1.Width; Top := values[i].Top; Width := values[i].Height; Height := Width; Color := colorarray[i]; Parent := Panel1; end; end; end; procedure TContourform.Graph(x, y: MathFloat; var z: MathFloat); {graph formula} begin //this first one is a real test, it looks crummy unless you //give it a mesh of about 200x200, in which case the filled level //curve drawing runs out of mem under Win2K on my machine... //****Cure: Use Robert Lee's memory manager replacement, //available from CodeCentral, it's awesome.**************** //There isn't anything I can do about level //curves near intersection points looking bad, //other than increasing the mesh. // z := 2 * (cos(1.5 * (x - y)) + sin(1.6 * (x + 0.6 * y))) + 0.8; if (x <> c) or (y <> 0) then z := sin(sqrt(sqr(x) + sqr(y))) + 1 / sqrt(sqr(x - c) + sqr(y)) else z := 1.0E10 end; {**************************} procedure TContourform.ContourlinesButtonClick(Sender: TObject); var SavePen: TPen; i: Integer; begin Screen.Cursor := CrHourGlass; currenttype := 1; with GraphImage do begin SetWorld(gxmin, gymin, gxmax, gymax); Clear; DrawAxes('x ', 'y', False, clSilver, clSilver, False); SavePen := TPen.Create; SavePen.assign(Pen); for i := 0 to High(levelsarray) do begin Pen.Color := colorarray[i]; DrawLevelCurves(graphsurface, levelsarray[i]); end; Pen.assign(SavePen); SavePen.Free; end; Screen.Cursor := crDefault; end; {******************************} procedure TContourform.FilledContoursButtonClick(Sender: TObject); begin Screen.Cursor := CrHourGlass; currenttype := 2; with GraphImage do begin if not LevelsMade then begin //The following is what takes long graphsurface.SetLevels(levelsarray, colorarray); LevelsMade := True; end; SetWorld(gxmin, gymin, gxmax, gymax); Clear; DrawAxes('x ', 'y', False, clSilver, clSilver, False); DrawFilledLevelCurves(graphsurface); end; Screen.Cursor := crDefault; end; {*****************************************} procedure TContourform.MakeGraphSurface; var i, j: Integer; x, y, z: MathFloat; begin graphsurface := TLevelSurface.Create(xMesh, yMesh); for i := 0 to xMesh do begin x := gxmin + i * (gxmax - gxmin) / xMesh; for j := 0 to yMesh do begin y := gymin + j * (gymax - gymin) / yMesh; Graph(x, y, z); graphsurface.Make(i, j, x, y, z); end; end; LevelsMade := False; end; {****************************} procedure TContourform.GraphImageResize(Sender: TObject); begin if currenttype = 1 then ContourlinesButtonClick(self) else FilledContoursButtonClick(self); end; procedure TContourform.FormDestroy(Sender: TObject); begin graphsurface.Free; end; procedure TContourform.FormShow(Sender: TObject); begin /// SaveasMetafile1.enabled := False; ContourlinesButtonClick(self); //Already done in GraphimageResize end; initialization end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.Banner; interface uses DPM.Console.Writer; procedure ShowBanner(const consoleWriter : IConsoleWriter); implementation uses System.SysUtils, DPM.Core.Utils.System; procedure ShowBanner(const consoleWriter : IConsoleWriter); begin Assert(consoleWriter <> nil, 'No console writer available'); consoleWriter.WriteLine(''); consoleWriter.SetColour(ccBrightAqua, ccDefault); consoleWriter.WriteLine('DPM - Delphi Package Manager - Version : ' + TSystemUtils.GetVersionString); consoleWriter.SetColour(ccBrightWhite); consoleWriter.WriteLine('© 2019-2021 Vincent Parrett and Contributors'); //consoleWriter.WriteLine('License - http://www.apache.org/licenses/LICENSE-2.0'); consoleWriter.WriteLine(''); end; end.
unit SpPeople_ModForm; { Здесь есть переменная pManModified, указывающая на то, что данные лица изменены, если ИСТИНА. Потому при добавлении новых полей, относящихся к таблице People нужно в событии их редактирования присваивать этой переменной значение ИСТИНЫ, иначе ничего не сохранится.} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxButtons, ComCtrls, cxDropDownEdit, cxCalendar, cxMaskEdit, IBase, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, ExtCtrls, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxDBEdit, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ToolWin, Buttons, cxCheckBox, GlobalSPR, cxButtonEdit, uCommonSp, DBCtrls, SpPeople_Types, SpPeople_z_dmCommonStyles, PassEditUnit, cxLabel, cxDBLabel, UManFamilyEdit, ActnList, AccMgmt, cxImage, SpPeople_CardFrame; const InsMan_Message = 'Для прийняття нових даних треба додати фізичну особу.' + #13 + 'Додати нову особу?'; type TfModifyMan = class(TForm) PeoplePageControl: TPageControl; MainPage: TTabSheet; OkButton: TcxButton; CancelButton: TcxButton; ManModProc: TpFIBStoredProc; GetIdManQuery: TpFIBDataSet; DSDetails: TpFIBDataSet; MainPanel: TPanel; PassPage: TTabSheet; ToolBar1: TToolBar; PasportGridDBTableView1: TcxGridDBTableView; PasportGridLevel1: TcxGridLevel; PasportGrid: TcxGrid; AddButton: TSpeedButton; ModifyButton: TSpeedButton; ViewButton: TSpeedButton; DeleteButton: TSpeedButton; RefreshButton: TSpeedButton; DSPassData: TpFIBDataSet; PassDataSourse: TDataSource; cmnFIO: TcxGridDBColumn; cmnSERIA: TcxGridDBColumn; cmnNUMBER: TcxGridDBColumn; cmnDATE_BEG: TcxGridDBColumn; cmnDATE_END: TcxGridDBColumn; ProcPassData: TpFIBStoredProc; Panel2: TPanel; ActualPaspCB: TcxCheckBox; GenearlInfoGroupBox: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; FamiliaEdit: TcxMaskEdit; ImyaEdit: TcxMaskEdit; OtchestvoEdit: TcxMaskEdit; Label4: TLabel; Label5: TLabel; Label6: TLabel; RusFamEdit: TcxMaskEdit; RusImyaEdit: TcxMaskEdit; RusOtchEdit: TcxMaskEdit; SexBox: TcxComboBox; Label7: TLabel; Label8: TLabel; BirthDateEdit: TcxDateEdit; AdditionalBox: TGroupBox; CardNumItemLabel: TLabel; Label9: TLabel; TinEdit: TcxMaskEdit; SocCardNumEdit: TcxMaskEdit; AdressGroupBox: TGroupBox; Label10: TLabel; AdressEdit: TcxButtonEdit; BirthPlaceLabel: TLabel; BirthPlaceEdit: TcxButtonEdit; AdditionalPage: TTabSheet; PhonePage: TGroupBox; WorkPhoneNum: TLabel; WorkPhoneEdit: TcxTextEdit; HomePhoneLabel: TLabel; HomePhoneEdit: TcxTextEdit; DSFamily: TpFIBDataSet; FamilyDataSource: TDataSource; NationalityBox: TGroupBox; Label11: TLabel; DSNationality: TpFIBDataSet; NationalityDataSource: TDataSource; NationalityComboBox: TcxLookupComboBox; DSGetAdress: TpFIBDataSet; ClearCurAdrBtn: TcxButton; ClearBirthAdrBtn: TcxButton; Label12: TLabel; CopyFIOBtn: TSpeedButton; DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; VidanDBText: TcxTextEdit; FamilyToolBar: TToolBar; FamilyAddBtn: TSpeedButton; FamilyModifyBtn: TSpeedButton; FamilyDelBtn: TSpeedButton; FamilyGrid: TcxGrid; FamilyTV: TcxGridDBTableView; FamilyTVFIO: TcxGridDBColumn; FamilyTVNAME_RELATION: TcxGridDBColumn; FamilyTVBIRTH_DATE: TcxGridDBColumn; FamilyGridLevel1: TcxGridLevel; PanelGroup: TPanel; FamilyRefreshBtn: TSpeedButton; StProcFamily: TpFIBStoredProc; HistWriteTransaction: TpFIBTransaction; StProcHist: TpFIBStoredProc; ActionList1: TActionList; OkAction: TAction; CancelAction: TAction; FotoImage: TcxDBImage; DBFoto: TpFIBDatabase; ReadTrFoto: TpFIBTransaction; DSetFoto: TpFIBDataSet; DSourceFoto: TDataSource; AddFotoBtn: TcxButton; SaveAsBtn: TcxButton; FotoPanel: TPanel; StProcFoto: TpFIBStoredProc; WriteTrFoto: TpFIBTransaction; DelFotoBtn: TcxButton; BankCardPage: TTabSheet; WithOutOtchestvoCB: TcxCheckBox; SaveDialog: TSaveDialog; FotoGrid: TcxGrid; FotoGridDBTableView1: TcxGridDBTableView; cmnID_FOTO: TcxGridDBColumn; cmnDATE_FOTO: TcxGridDBColumn; cmnACTUALWIDTH: TcxGridDBColumn; cmnACTUALHEIGHT: TcxGridDBColumn; FotoGridLevel1: TcxGridLevel; Label13: TLabel; Gromod: TcxButtonEdit; DSGetCountry: TpFIBDataSet; DSContryDef: TpFIBDataSet; DelFotoProc: TpFIBStoredProc; Label14: TLabel; LiveAdressEdit: TcxButtonEdit; ClearLiveAdrBtn: TcxButton; CopyBirthPlace: TSpeedButton; CopyAdressBtn: TSpeedButton; STProcPerevodFioRus: TpFIBStoredProc; procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure ActualPaspCBClick(Sender: TObject); procedure ModifyButtonClick(Sender: TObject); procedure ViewButtonClick(Sender: TObject); procedure DSPassDataDATE_ENDGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure cxMaskEdit1PropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure AdressEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FamilyAddBtnClick(Sender: TObject); procedure FamilyDelBtnClick(Sender: TObject); procedure FamilyModifyBtnClick(Sender: TObject); procedure ClearCurAdrBtnClick(Sender: TObject); procedure ClearBirthAdrBtnClick(Sender: TObject); procedure CopyFIOBtnClick(Sender: TObject); procedure PasportGridDBTableView1CellClick( Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure FamilyRefreshBtnClick(Sender: TObject); procedure HistWriteTransactionAfterStart(Sender: TObject); procedure ManEditEditing(Sender: TObject; var CanEdit: Boolean); procedure NationalityComboBoxPropertiesChange(Sender: TObject); procedure PasportGridDBTableView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FamilyTVKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FamiliaEditKeyPress(Sender: TObject; var Key: Char); procedure ImyaEditKeyPress(Sender: TObject; var Key: Char); procedure OtchestvoEditKeyPress(Sender: TObject; var Key: Char); procedure RusFamEditKeyPress(Sender: TObject; var Key: Char); procedure RusImyaEditKeyPress(Sender: TObject; var Key: Char); procedure RusOtchEditKeyPress(Sender: TObject; var Key: Char); procedure SexBoxKeyPress(Sender: TObject; var Key: Char); procedure BirthDateEditKeyPress(Sender: TObject; var Key: Char); procedure TinEditKeyPress(Sender: TObject; var Key: Char); procedure SocCardNumEditKeyPress(Sender: TObject; var Key: Char); procedure AdressEditKeyPress(Sender: TObject; var Key: Char); procedure BirthPlaceEditKeyPress(Sender: TObject; var Key: Char); procedure WorkPhoneEditKeyPress(Sender: TObject; var Key: Char); procedure HomePhoneEditKeyPress(Sender: TObject; var Key: Char); procedure NationalityComboBoxKeyPress(Sender: TObject; var Key: Char); procedure SaveAsBtnClick(Sender: TObject); procedure AddFotoBtnClick(Sender: TObject); procedure DelFotoBtnClick(Sender: TObject); procedure cmnDATE_FOTOGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); procedure PeoplePageControlChange(Sender: TObject); procedure ManEditPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure GromodPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure GromodEditing(Sender: TObject; var CanEdit: Boolean); procedure FormShow(Sender: TObject); procedure RusFamEditEnter(Sender: TObject); procedure RusImyaEditEnter(Sender: TObject); procedure RusOtchEditEnter(Sender: TObject); procedure RusFamEditExit(Sender: TObject); procedure RusOtchEditExit(Sender: TObject); procedure RusImyaEditExit(Sender: TObject); procedure LiveAdressEditKeyPress(Sender: TObject; var Key: Char); procedure ClearLiveAdrBtnClick(Sender: TObject); procedure CopyBirthPlaceClick(Sender: TObject); procedure CopyAdressBtnClick(Sender: TObject); private FMode: TEditMode; Familia: string; Imya: string; Otchestvo: string; RusFamilia: string; RusImya: string; RusOtchestvo: string; IdSex: Integer; BirthDate: Variant; TIN: string; SocCardNum: string; FIdBirthAdress: Integer; FIdLiveAdress: Integer; FIdCurrentAdress: Integer; FWork_Phone: string; FHome_Phone: string; FIdNationality: Variant; FidGrom: Integer; IdSexCheck: Integer; pStylesDM: TStylesDM; pManModified: Boolean; pBankCardFrame: TframeCard; function ApplyData: Boolean; function AskToInsMan(MessageInfo: string): Boolean; function CheckData: Boolean; function CheckString(aText: string): Boolean; procedure PrepareData; procedure FormPrepare; function GetAdress(IdAdress: Integer): string; function GetBirthPlace(IdPlace: Integer): string; procedure SetDefaultBirthPlace(IdAdress: Integer); procedure InitFoto(AImageDB_Handle: TISC_DB_HANDLE); procedure RefreshFoto; function ValidateTIN: Boolean; function GetCorrectTIN: Variant; function GetCountry(IdCountry: Integer): string; procedure UpdateFIOOnForm; public IdMan: Integer; constructor Create(AOwner: TComponent; ADB_Handle: TISC_DB_HANDLE; {*} AImageDB_Handle: TISC_DB_HANDLE; {*} AEditMode: TEditMode; AIdMan: Integer = -1); reintroduce; end; implementation {$R *.dfm} uses SpPeople_ZMessages, IniFiles, StrUtils, AllPeopleDataModule; procedure TfModifyMan.SetDefaultBirthPlace(IdAdress: Integer); begin if DSGetAdress.Active then DSGetAdress.Close; DSGetAdress.SQLs.SelectSQL.Text := 'SELECT * FROM ADR_ADRESS_SEL(' + IntToStr(IdAdress) + ')'; DSGetAdress.Open; FIdBirthAdress := DSGetAdress['ID_PLACE']; DSGetAdress.Close; BirthPlaceEdit.Text := GetBirthPlace(FIdBirthAdress); end; function TfModifyMan.ApplyData: Boolean; begin Result := False; if CheckData then begin if FMode = emNew then begin try GetIdManQuery.Open; IdMan := GetIdManQuery['IDMAN']; GetIdManQuery.Close; PrepareData; ManModProc.Transaction.StartTransaction; ManModProc.ExecProcedure('PUB_ALL_PEOPLE_INSERT', [Familia, Imya, Otchestvo, RusFamilia, RusImya, RusOtchestvo, IdSex, BirthDate, {Tin} GetCorrectTIN, FIdBirthAdress, FIdCurrentAdress, IDMAN, SocCardNum, FWork_Phone, FHome_Phone, FIdNationality, FidGrom, FIdLiveAdress]); ManModProc.Transaction.Commit; Result := True; except on E: Exception do begin MessageDlg('Не вдалося створити фізичну особу. Причина:' + #10#13 + E.Message, mtError, [mbOk], 0); ManModProc.Transaction.Rollback; Result := False; end; end; end; if FMode = emModify then begin if pManModified then begin try PrepareData; ManModProc.Transaction.StartTransaction; ManModProc.ExecProcedure('PUB_ALL_PEOPLE_UPDATE', [Familia, Imya, Otchestvo, RusFamilia, RusImya, RusOtchestvo, IdSex, BirthDate, {Tin} GetCorrectTIN, FIdBirthAdress, FIdCurrentAdress, IDMAN, SocCardNum, FWork_Phone, FHome_Phone, FIdNationality, FidGrom, FIdLiveAdress]); ManModProc.Transaction.Commit; Result := True; except on E: Exception do begin MessageDlg('Не вдалося змінити фізичну особу. Причина:' + #10#13 + E.Message, mtError, [mbOk], 0); ManModProc.Transaction.Rollback; Result := False; end; end; end; end; end; end; function TfModifyMan.AskToInsMan(MessageInfo: string): Boolean; begin Result := False; if ZShowMessage(Self.Caption, MessageInfo, mtCustom, [mbYes, mbNo]) = mrYes then begin Refresh; if ApplyData then begin Result := True; FMode := emModify; end; end; end; function TfModifyMan.GetAdress(IdAdress: Integer): string; {var CountryName:String; PlaceName:String; StreetName:String; House:String; Flat:String; AdrFull:String; } begin if DSGetAdress.Active then DSGetAdress.Close; DSGetAdress.SQLs.SelectSQL.Text := 'SELECT * FROM ADR_ADRESS_SEL(' + IntToStr(IdAdress) + ')'; DSGetAdress.Open; Result := VarToStr(DSGetAdress['FULL_NAME']); DSGetAdress.Close; { DSGetAdress.ParamByName('ACTDATE').Value:=Date(); DSGetAdress.ParamByName('ID_ADRESS').Value:=IdAdress; DSGetAdress.Open; if (not VarIsNull(DSGetAdress['COUNTRY_NAME'])) then CountryName:=DSGetAdress['COUNTRY_NAME']+', ' else CountryName:=''; if (not VarIsNull(DSGetAdress['PLACE_NAME'])) then PlaceName:=DSGetAdress['PLACE_NAME']+', ' else PlaceName:=''; if (not VarIsNull(DSGetAdress['STREET_NAME'])) then StreetName:=DSGetAdress['STREET_NAME']+', ' else StreetName:=''; if (not VarIsNull(DSGetAdress['HOUSE'])) then House:=', буд '+DSGetAdress['HOUSE'] else House:=''; if (not VarIsNull(DSGetAdress['FLAT'])) then Flat:=', кв '+DSGetAdress['FLAT'] else Flat:=''; DSGetAdress.Close; AdrFull:=CountryName+PlaceName+StreetName+House+Flat; Result:=AdrFull; } end; function TfModifyMan.GetCountry(IdCountry: Integer): string; begin if DSGetCountry.Active then DSGetCountry.Close; DSGetCountry.SQLs.SelectSQL.Text := 'SELECT * FROM ADR_COUNTRY_S(' + IntToStr(IdCountry) + ')'; DSGetCountry.Open; Result := VarToStr(DSGetCountry['NAME_COUNTRY']); DSGetCountry.Close; end; function TfModifyMan.GetBirthPlace(IdPlace: Integer): string; begin if DSGetAdress.Active then DSGetAdress.Close; DSGetAdress.SQLs.SelectSQL.Text := 'SELECT * FROM ADR_GET_BY_ID_PLACE(' + IntToStr(IdPlace) + ')'; DSGetAdress.Open; Result := VarToStr(DSGetAdress['FULL_NAME']); DSGetAdress.Close; end; constructor TfModifyMan.Create(AOwner: TComponent; ADB_Handle: TISC_DB_HANDLE; AImageDB_Handle: TISC_DB_HANDLE; AEditMode: TEditMode; AIdMan: Integer = -1); begin try inherited Create(AOwner); //****************************************************************************** DB.Handle := ADB_Handle; ReadTransaction.Active := True; //****************************************************************************** pStylesDM := TStylesDM.Create(Self); PasportGridDBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; FamilyTV.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; FotoGridDBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; //****************************************************************************** FIdBirthAdress := -1; FIdCurrentAdress := -1; FIdLiveAdress := -1; //****************************************************************************** pManModified := False; FMode := AEditMode; IdMan := AIdMan; if (FMode = emNew) then begin Caption := 'Довідник фізичних осіб: Додати'; if DSContryDef.Active then DSContryDef.Close; DSContryDef.SQLs.SelectSQL.Text := 'SELECT DEF_ID_COUNTRY, CN_DEF_ID_NATIONAL FROM PUB_SYS_DATA'; DSContryDef.Open; if not (DSContryDef['DEF_ID_COUNTRY'] = null) then begin FidGrom := DSContryDef['DEF_ID_COUNTRY']; if DSGetCountry.Active then DSGetCountry.Close; DSGetCountry.SQLs.SelectSQL.Text := 'SELECT * FROM ADR_COUNTRY_S(' + IntToStr(FidGrom) + ')'; DSGetCountry.Open; Gromod.Text := VarToStr(DSGetCountry['NAME_COUNTRY']); DSGetCountry.Close; end; if not (DSContryDef['CN_DEF_ID_NATIONAL'] = null) then NationalityComboBox.EditValue := DSContryDef['CN_DEF_ID_NATIONAL']; DSContryDef.Close; end else DSContryDef.Close; if (FMode = emModify) then Caption := 'Довідник фізичних осіб: Редагувати'; if (FMode = emView) then begin Caption := 'Довідник фізичних осіб: Перегляд'; OkButton.Visible := False; end; PeoplePageControl.ActivePageIndex := 0; DSNationality.Open; if Fmode <> emNew then FormPrepare; //****************************************************************************** InitFoto(AImageDB_Handle); // Width:=Width-155; //****************************************************************************** if not IsAccessGranted(SAP_MainInfo, cEdit) then begin MainPanel.Enabled := False; if not IsAccessGranted(SAP_MainInfo, cView) then MainPage.TabVisible := False; end; if not IsAccessGranted(SAP_Otchestvo, cEdit) then begin WithOutOtchestvoCB.Visible := False; end; if not IsAccessGranted(SAP_PassData, cEdit) then begin AddButton.Enabled := False; ModifyButton.Enabled := False; DeleteButton.Enabled := False; if not IsAccessGranted(SAP_PassData, cView) then PassPage.TabVisible := False; end; if not IsAccessGranted(SAP_Info, cEdit) then begin FamilyAddBtn.Enabled := False; FamilyModifyBtn.Enabled := False; FamilyDelBtn.Enabled := False; PhonePage.Enabled := False; NationalityBox.Enabled := False; if not IsAccessGranted(SAP_Info, cView) then AdditionalPage.TabVisible := False; end; if not IsAccessGranted(SAP_BankCards, cEdit) then if not IsAccessGranted(SAP_BankCards, cView) then BankCardPage.TabVisible := False; except on E: Exception do begin ShowMessage(E.Message); end; end; end; function TfModifyMan.CheckString(aText: string): Boolean; var i, n: Integer; s: Char; Txt: string; begin CheckString := True; Txt := aText; n := Length(aText); if n >= 1 then for i := 1 to n do begin s := Txt[i]; if not (s in ['А'..'Я', 'а'..'я', '-', '''', ' ', 'І', 'і', 'Є', 'є', 'Ґ', 'ґ', 'Ї', 'ї', #27, #8]) then begin CheckString := False; Exit; end; end; end; function TfModifyMan.CheckData: Boolean; begin CheckData := True; if FamiliaEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Прізвище''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; FamiliaEdit.SetFocus; Exit; end; if CheckString(FamiliaEdit.Text) = False then begin MessageDlg('Поле ' + '''Прізвище''' + ' містить недопустимі символи!', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; FamiliaEdit.SetFocus; Exit; end; if ImyaEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Ім''я''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; ImyaEdit.SetFocus; Exit; end; if CheckString(ImyaEdit.Text) = False then begin MessageDlg('Поле ' + '''Ім''я''' + ' містить недопустимі символи!', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; ImyaEdit.SetFocus; Exit; end; // У иностранцев отчеств нет if not WithOutOtchestvoCB.Checked then begin if OtchestvoEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''По батькові''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; OtchestvoEdit.SetFocus; Exit; end; if CheckString(OtchestvoEdit.Text) = False then begin MessageDlg('Поле ' + '''По батькові''' + ' містить недопустимі символи!', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; OtchestvoEdit.SetFocus; Exit; end; end; if RusFamEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Фамилия''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; RusFamEdit.SetFocus; Exit; end; if RusImyaEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Имя''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; RusImyaEdit.SetFocus; Exit; end; if not WithOutOtchestvoCB.Checked then if RusOtchEdit.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Отчество''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; RusOtchEdit.SetFocus; Exit; end; if Gromod.Text = '' then begin MessageDlg('Не задано необхіднe поле ' + '''Громадянство''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; Gromod.SetFocus; Exit; end; if SexBox.ItemIndex = -1 then begin MessageDlg('Не задано необхіднe поле ' + '''Стать''', mtError, [mbOk], 0); CheckData := False; PeoplePageControl.ActivePage := MainPage; SexBox.SetFocus; Exit; end; if not ValidateTIN then begin CheckData := False; Exit; end; end; procedure TfModifyMan.FormPrepare; begin if DSDetails.Active then DSDetails.Close; DSDetails.ParamByName('ID_MAN').Value := IDMAN; DSDetails.Open; FamiliaEdit.Text := DSDetails['Familia']; ImyaEdit.Text := DSDetails['Imya']; OtchestvoEdit.Text := DSDetails['Otchestvo']; if (not VarIsNull(DSDetails['Rus_Familia'])) then RusFamEdit.Text := DSDetails['Rus_Familia'] else RusFamEdit.Text := ''; if (not VarIsNull(DSDetails['Rus_Imya'])) then RusImyaEdit.Text := DSDetails['Rus_Imya'] else RusImyaEdit.Text := ''; if (not VarIsNull(DSDetails['Rus_Otchestvo'])) then RusOtchEdit.Text := DSDetails['Rus_Otchestvo'] else RusOtchEdit.Text := ''; // Сначала задаем значение, а потом навешиваем процедуру на событие OnEditing, // иначе она срабатывает при инициализации данных и проверка на вненсение изменений // не работает. SexBox.ItemIndex := DSDetails['Id_Sex'] - 1; IdSexCheck := DSDetails['Id_Sex']; SexBox.OnEditing := ManEditEditing; if (VarIsNull(DSDetails['SOC_CARD_NUMBER'])) then SocCardNumEdit.Text := '' else SocCardNumEdit.Text := DSDetails['SOC_CARD_NUMBER']; if (not VarIsNull(DSDetails['BIRTH_DATE'])) then BirthDateEdit.Date := StrToDate(DSDetails['BIRTH_DATE']); if (VarIsNull(DSDetails['WORK_PHONE'])) then WorkPhoneEdit.Text := '' else WorkPhoneEdit.Text := DSDetails['WORK_PHONE']; if (VarIsNull(DSDetails['HOME_PHONE'])) then HomePhoneEdit.Text := '' else HomePhoneEdit.Text := DSDetails['HOME_PHONE']; if DSDetails['TIN'] <= 0 then TINEdit.Text := '' else TINEdit.Text := DSDetails['TIN']; RefreshButtonClick(Self); FamilyRefreshBtnClick(Self); if FMode = emView then begin MainPanel.Enabled := False; AddButton.Enabled := False; ModifyButton.Enabled := False; DeleteButton.Enabled := False; FamilyAddBtn.Enabled := False; FamilyModifyBtn.Enabled := False; FamilyDelBtn.Enabled := False; PhonePage.Enabled := False; NationalityBox.Enabled := False; AddFotoBtn.Enabled := False; DelFotoBtn.Enabled := False; end; NationalityComboBox.EditValue := DSDetails['ID_NATIONALITY']; if DSDetails['ID_COUNTRY'] <> null then Gromod.Text := GetCountry(DSDetails['ID_COUNTRY']); FidGrom := DSDetails['ID_COUNTRY']; AdressEdit.Text := GetAdress(DSDetails['ID_ADRESS']); FIdCurrentAdress := DSDetails['ID_ADRESS']; BirthPlaceEdit.Text := GetBirthPlace(DSDetails['ID_BIRTH_PLACE']); FIdBirthAdress := DSDetails['ID_BIRTH_PLACE']; LiveAdressEdit.Text := GetAdress(DSDetails['ID_LIVE_ADRESS']); FIdLiveAdress := DSDetails['ID_LIVE_ADRESS']; // Если не указаны отчества, то, вероятнее всего, в прошлый раз была выбрана опция "Без отчества". Повторяем if (Trim(OtchestvoEdit.Text) = '') or (Trim(RusOtchEdit.Text) = '') then WithOutOtchestvoCB.Checked := True; //****************************************************************************** pBankCardFrame := TframeCard.Create(BankCardPage, DB.Handle, FMode, IdMan, DSDetails['TIN']); end; procedure TfModifyMan.PrepareData; begin Familia := FamiliaEdit.Text; Imya := ImyaEdit.Text; Otchestvo := OtchestvoEdit.Text; RusFamilia := RusFamEdit.Text; RusImya := RusImyaEdit.Text; RusOtchestvo := RusOtchEdit.Text; IdSex := SexBox.ItemIndex + 1; BirthDate := DateToStr(BirthDateEdit.Date); if (BirthDate = '00.00.0000') then BirthDate := null; TIN := TinEdit.Text; {******* if (FMode<>emNew) then begin if TinEdit.Text<>'' then TIN:=TinEdit.Text else TIN:=DSDetails['TIN'] end else TIN:=TinEdit.Text; *******} // Поскольку лицам без ИНН в базе в качестве ИНН присвоены отрицательные значения, // а отображаются и СОХРАНЯЮТСЯ они БЕЗ минуса, проверяем настоящий ИНН или нет. { if (FMode<>emNew) and (TinEdit.Text<>'') then begin if ((Length(TinEdit.Text)<10) {т.е. ИНН ненастоящий}{and (DSDetails['TIN']<0)) and (TinEdit.Text=IntToStr(-DSDetails['TIN'])) then TIN:='-'+TinEdit.Text else TIN:=TinEdit.Text; end else TIN:=TinEdit.Text; } SocCardNum := SocCardNumEdit.Text; FWork_Phone := WorkPhoneEdit.Text; FHome_Phone := HomePhoneEdit.Text; FIdNationality := NationalityComboBox.EditValue; end; procedure TfModifyMan.OkButtonClick(Sender: TObject); begin if ApplyData then ModalResult := mrOk; end; procedure TfModifyMan.CancelButtonClick(Sender: TObject); begin ModalResult := mrCancel; if FMode = emNew then IdMan := -1; end; procedure TfModifyMan.AddButtonClick(Sender: TObject); var PassInfo: TPassRec; pIdPasData: Int64; begin if IdMan = -1 then if not AskToInsMan(InsMan_Message) then Exit; PassInfo.Familia := FamiliaEdit.Text; PassInfo.Imya := ImyaEdit.Text; PassInfo.Otchestvo := OtchestvoEdit.Text; PassInfo.RusFamilia := RusFamEdit.Text; PassInfo.RusImya := RusImyaEdit.Text; PassInfo.RusOtchestvo := RusOtchEdit.Text; PassInfo.ID_MAN := IdMan; PassInfo.ID_PAS_DATA := -1; PassInfo.WithOutOtchestvo := WithOutOtchestvoCB.Checked; if GetPassInfo(Self, DB.Handle, emNew, PassInfo) then begin ProcPassData.Transaction.StartTransaction; try ProcPassData.ExecProcedure('PUB_PASS_DATA_INSERT', [PassInfo.Familia, PassInfo.Imya, PassInfo.Otchestvo, PassInfo.RusFamilia, PassInfo.RusImya, PassInfo.RusOtchestvo, PassInfo.Seria, PassInfo.Number, DateToStr(PassInfo.GrantDate), PassInfo.GrantedBy, IdMan, PassInfo.IdPassType]); pIdPasData := ProcPassData.FN('ID_OUT').AsInt64; ProcPassData.Transaction.Commit; RefreshButtonClick(Self); DSPassData.Locate('ID_PAS_DATA', pIdPasData, []); if PassInfo.UpdateFIO then begin UpdateFIOOnForm; end; except on E: Exception do begin MessageDlg('Не вдалося додати інформацію про паспортні дані. Причина: ' + #10#13 + E.Message, mtError, [mbOk], 0); ProcPassData.Transaction.Rollback; end; end; end; end; procedure TfModifyMan.ActualPaspCBClick(Sender: TObject); begin RefreshButtonClick(Self); end; procedure TfModifyMan.ModifyButtonClick(Sender: TObject); var PassInfo: TPassRec; pIdPassData: Int64; begin if DSPassData.IsEmpty then Exit; PassInfo.Familia := DSPassData['FAMILIA']; PassInfo.Imya := DSPassData['IMYA']; PassInfo.Otchestvo := DSPassData['OTCHESTVO']; PassInfo.RusFamilia := DSPassData['RUS_FAMILIA']; PassInfo.RusImya := DSPassData['RUS_IMYA']; PassInfo.RusOtchestvo := DSPassData['RUS_OTCHESTVO']; PassInfo.Seria := DSPassData['SERIA']; PassInfo.Number := DSPassData['NUMBER']; PassInfo.GrantDate := {StrToDate}(DSPassData['DATE_BEG']); PassInfo.GrantedBy := DSPassData['VIDAN']; PassInfo.WithOutOtchestvo := WithOutOtchestvoCB.Checked; if (VarIsNull(DSPassData['ID_PASS_TYPE'])) then PassInfo.IdPassType := 1 else PassInfo.IdPassType := DSPassData['ID_PASS_TYPE']; PassInfo.ID_MAN := IdMan; PassInfo.ID_PAS_DATA := DSPassData['ID_PAS_DATA']; if GetPassInfo(Self, DB.Handle, emModify, PassInfo) then begin ProcPassData.Transaction.StartTransaction; try ProcPassData.ExecProcedure('PUB_PASS_DATA_UPDATE', [PassInfo.Familia, PassInfo.Imya, PassInfo.Otchestvo, PassInfo.RusFamilia, PassInfo.RusImya, PassInfo.RusOtchestvo, PassInfo.Seria, PassInfo.Number, DateToStr(PassInfo.GrantDate), PassInfo.GrantedBy, IdMan, PassInfo.IdPassType, DSPassData['ID_PAS_DATA']]); ProcPassData.Transaction.Commit; pIdPassData := DSPassData['ID_PAS_DATA']; RefreshButtonClick(Self); DSPassData.Locate('ID_PAS_DATA', pIdPassData, []); if PassInfo.UpdateFIO then begin UpdateFIOOnForm; end; except on E: Exception do begin MessageDlg('Не вдалося змінити інформацію про паспортні дані. Причина: ' + #10#13 + E.Message, mtError, [mbOk], 0); ProcPassData.Transaction.Rollback; end; end; end; end; procedure TfModifyMan.ViewButtonClick(Sender: TObject); var PassInfo: TPassRec; begin if DSPassData.IsEmpty then Exit; PassInfo.Familia := DSPassData['FAMILIA']; PassInfo.Imya := DSPassData['IMYA']; PassInfo.Otchestvo := DSPassData['OTCHESTVO']; PassInfo.RusFamilia := DSPassData['RUS_FAMILIA']; PassInfo.RusImya := DSPassData['RUS_IMYA']; PassInfo.RusOtchestvo := DSPassData['RUS_OTCHESTVO']; PassInfo.Seria := DSPassData['SERIA']; PassInfo.Number := DSPassData['NUMBER']; PassInfo.GrantDate := {StrToDate}(DSPassData['DATE_BEG']); PassInfo.GrantedBy := DSPassData['VIDAN']; PassInfo.WithOutOtchestvo := WithOutOtchestvoCB.Checked; if (VarIsNull(DSPassData['ID_PASS_TYPE'])) then PassInfo.IdPassType := 1 else PassInfo.IdPassType := DSPassData['ID_PASS_TYPE']; PassInfo.ID_MAN := IdMan; PassInfo.ID_PAS_DATA := DSPassData['ID_PAS_DATA']; GetPassInfo(Self, DB.Handle, emView, PassInfo); end; procedure TfModifyMan.DSPassDataDATE_ENDGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin { if DSPassDataDATE_END.Value=Module.ConstsQuery['INFINITY_DATE'] then Text:='безстроково' else Text:=DateToStr(DSPassDataDATE_END.Value); } end; procedure TfModifyMan.DeleteButtonClick(Sender: TObject); var ViewMessageForm: TForm; i: integer; pUpdateFIO, pPassed: Boolean; sOldImya, sOldFamilia: string; sOldOtchestvo: string; begin if DSPassData.IsEmpty then Exit; repeat if ZShowMessage('Вилучення', 'Запис буде вилучено! Продовжити?', mtconfirmation, [mbYes, MbNo]) = mrYes then begin pPassed := True; pUpdateFIO := False; ProcPassData.Transaction.StartTransaction; ProcPassData.StoredProcName := 'PEOPLE_PASS_FIO_EQUAL'; ProcPassData.Prepare; ProcPassData.ParamByName('ID_MAN').AsInteger := IdMan; ProcPassData.ParamByName('ID_PAS_DATA').AsInt64 := DSPassData['ID_PAS_DATA']; ProcPassData.ParamByName('EDIT_MODE').AsInteger := 2; ProcPassData.ExecProc; if ProcPassData.FN('IS_EQUAL').AsInteger = 0 then begin pPassed := False; sOldImya := ProcPassData.FN('OLD_IMYA').AsString; if VarIsNull(ProcPassData.FN('OLD_OTCHESTVO').AsString) then sOldOtchestvo := '' else sOldOtchestvo := ProcPassData.FN('OLD_OTCHESTVO').AsString; sOldFamilia := ProcPassData.FN('OLD_FAMILIA').AsString; ViewMessageForm := CreateMessageDialog('Змінити ПІБ у даних фізичної особи?' + #13 + 'Увага!!! Якщо Ви відповісте "ТАК", то у всіх вихідних документах,' + #13 + 'де вона зустрічається, її ПІБ буде записане як:' + #13 + sOldFamilia + ' ' + sOldImya + ' ' + sOldOtchestvo, mtWarning, [mbYes, mbNo, mbCancel]); with ViewMessageForm do begin for i := 0 to ComponentCount - 1 do if (Components[i].ClassType = TButton) then begin if UpperCase((Components[i] as TButton).Caption) = '&YES' then begin (Components[i] as TButton).Left := 70; (Components[i] as TButton).Caption := 'Так'; (Components[i] as TButton).Width := 45; end; if UpperCase((Components[i] as TButton).Caption) = '&NO' then begin (Components[i] as TButton).Left := 120; (Components[i] as TButton).Caption := 'Ні'; (Components[i] as TButton).Width := 45; end; if UpperCase((Components[i] as TButton).Caption) = 'CANCEL' then begin (Components[i] as TButton).Left := 170; (Components[i] as TButton).Caption := 'Повернутися до редагування'; (Components[i] as TButton).Width := 170; end; end; Caption := 'Увага'; i := ShowModal; Free; end; case i of mrYes: begin pPassed := True; pUpdateFIO := True; end; mrNo: begin pPassed := True; end; mrCancel: begin pPassed := False; end; end; end; ProcPassData.Transaction.Rollback; if pPassed then begin ProcPassData.StoredProcName := 'PASS_DATA_DELETE'; try ProcPassData.Transaction.StartTransaction; ProcPassData.ParamByName('ID_MAN').Value := IdMan; ProcPassData.ParamByName('DATE_BEG').Value := DSPassData['DATE_BEG']; ProcPassData.ParamByName('ID_PAS_DATA').Value := DSPassData['ID_PAS_DATA']; ProcPassData.ExecProc; ProcPassData.Transaction.Commit; except on E: Exception do begin MessageDlg('Не вдалося додати інформацію про паспортні дані. Причина: ' + #10#13 + E.Message, mtError, [mbOk], 0); ProcPassData.Transaction.Rollback; end; end; DSPassData.CloseOpen(True); if pUpdateFIO then begin UpdateFIOOnForm; end; end; end else pPassed := False; until pPassed; RefreshButtonClick(Self); end; procedure TfModifyMan.RefreshButtonClick(Sender: TObject); var pIdPasData: Int64; begin pIdPasData := -1; if DSPassData.Active then begin if not DSPassData.IsEmpty then pIdPasData := DSPassData['ID_PAS_DATA']; DSPassData.Close; end; if ActualPaspCB.Checked then DSPassData.SQLs.SelectSQL.Text := 'SELECT * FROM PASS_DATA_GET_BY_ID_MAN(' + IntToStr(IdMan) + ',''T'')' else DSPassData.SQLs.SelectSQL.Text := 'SELECT * FROM PASS_DATA_GET_BY_ID_MAN(' + IntToStr(IdMan) + ',''F'')'; try DSPassData.Open; except on E: Exception do MessageDlg('Не вдалося отримати інформацію про паспортні дані. Причина: ' + #10#13 + E.Message, mtError, [mbOk], 0); end; if pIdPasData <> -1 then DSPassData.Locate('ID_PAS_DATA', pIdPasData, []); if VarIsNull(DSPassData['VIDAN']) then VidanDBText.Text := '' else VidanDBText.Text := DSPassData['VIDAN']; end; procedure TfModifyMan.cxMaskEdit1PropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin ErrorText := 'Довжина поля "Податковий номер" повинна дорівнювати 10!'; end; procedure TfModifyMan.AdressEditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var AdressesSp: TSprav; ShowStyle, Select: Integer; IdAdr: Variant; begin if (Sender = AdressEdit) then begin if (FIdCurrentAdress <= 0) then IdAdr := null else IdAdr := FIdCurrentAdress; end else if (Sender = BirthPlaceEdit) then begin if (FIdBirthAdress <= 0) then IdAdr := null else IdAdr := FIdBirthAdress; end else if (Sender = LiveAdressEdit) then begin if (FIdLiveAdress <= 0) then IdAdr := null else IdAdr := FIdLiveAdress; end; if (Sender = BirthPlaceEdit) then ShowStyle := 3 else ShowStyle := 4; if (FMode = emView) then Select := 0 else Select := 1; AdressesSp := GetSprav('Adresses'); if (AdressesSp <> nil) then begin with AdressesSp.Input do begin Edit; FieldValues['Id_Adress'] := IdAdr; FieldValues['DbHandle'] := Integer(DB.Handle); FieldValues['Select'] := 1; FieldValues['ShowStyle'] := ShowStyle; Post; end; AdressesSp.Show; if (not VarIsNull(AdressesSp.Output['Name_Adr'])) then begin if (Sender = AdressEdit) then begin AdressEdit.Text := AdressesSp.Output['Name_Adr']; FIdCurrentAdress := AdressesSp.Output['Id_Adress']; end else if (Sender = BirthPlaceEdit) then begin BirthPlaceEdit.Text := AdressesSp.Output['Name_Adr']; FIdBirthAdress := AdressesSp.Output['Id_Adress']; end else if (Sender = LiveAdressEdit) then begin LiveAdressEdit.Text := AdressesSp.Output['Name_Adr']; FIdLiveAdress := AdressesSp.Output['Id_Adress']; end; pManModified := True; end; AdressesSp.Destroy; end; end; procedure TfModifyMan.FamilyAddBtnClick(Sender: TObject); var ViewForm: TfFamilyEdit; begin if IdMan = -1 then begin if not AskToInsMan(InsMan_Message) then Exit; end else begin if IdSexCheck <> SexBox.ItemIndex + 1 then AskToInsMan('Була внесені зміни по фізичній особі! Бажаєте зберегти інформацію?'); end; ViewForm := TfFamilyEdit.Create(Self, DB.Handle); if ViewForm.ShowModal = mrOk then begin try StProcFamily.Transaction.StartTransaction; StProcFamily.StoredProcName := 'MAN_FAMILY_INSERT'; StProcFamily.Prepare; StProcFamily.ParamByName('ID_MAN_INT').AsInteger := IdMan; StProcFamily.ParamByName('FIO').AsString := ViewForm.FIO; StProcFamily.ParamByName('ID_RELATION').AsInteger := ViewForm.IdRelation; if ViewForm.UseDate then StProcFamily.ParamByName('BIRTH_DATE').AsDate := ViewForm.BirthDate else StProcFamily.ParamByName('BIRTH_DATE').Clear; StProcFamily.ExecProc; StProcFamily.Transaction.Commit; FamilyRefreshBtnClick(Self); DSFamily.Locate('FIO', ViewForm.FIO, []); except on e: Exception do begin StProcFamily.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; ViewForm.Free; end; procedure TfModifyMan.FamilyDelBtnClick(Sender: TObject); begin if DSFamily.IsEmpty then Exit; if ZShowMessage('Вилучення', 'Ви справді бажаєте вилучити запис?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin try StProcFamily.Transaction.StartTransaction; StProcFamily.StoredProcName := 'MAN_FAMILY_DELETE'; StProcFamily.Prepare; StProcFamily.ParamByName('ID_WA').AsInteger := IdMan; StProcFamily.ParamByName('FIO').AsString := DSFamily['FIO']; StProcFamily.ExecProc; StProcFamily.Transaction.Commit; FamilyRefreshBtnClick(Self); except on e: Exception do begin StProcFamily.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; end; procedure TfModifyMan.FamilyModifyBtnClick(Sender: TObject); var ViewForm: TfFamilyEdit; begin if DSFamily.IsEmpty then Exit; if VarIsNull(DSFamily['BIRTH_DATE']) then ViewForm := TfFamilyEdit.Create(Self, DB.Handle, DSFamily['ID_RELATION'], DSFamily['FIO']) else ViewForm := TfFamilyEdit.Create(Self, DB.Handle, DSFamily['ID_RELATION'], DSFamily['FIO'], DSFamily['BIRTH_DATE']); if ViewForm.ShowModal = mrOk then begin try StProcFamily.Transaction.StartTransaction; StProcFamily.StoredProcName := 'Z_MAN_FAMILY_U'; StProcFamily.Prepare; StProcFamily.ParamByName('ID_MAN_INT').AsInteger := IdMan; StProcFamily.ParamByName('FIO_OLD').AsString := DSFamily['FIO']; StProcFamily.ParamByName('FIO').AsString := ViewForm.FIO; StProcFamily.ParamByName('ID_RELATION').AsInteger := ViewForm.IdRelation; if ViewForm.UseDate then StProcFamily.ParamByName('BIRTH_DATE').AsDate := ViewForm.BirthDate else StProcFamily.ParamByName('BIRTH_DATE').Clear; StProcFamily.ExecProc; StProcFamily.Transaction.Commit; FamilyRefreshBtnClick(Self); DSFamily.Locate('FIO', ViewForm.FIO, []); except on e: Exception do begin StProcFamily.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; ViewForm.Free; end; procedure TfModifyMan.ClearCurAdrBtnClick(Sender: TObject); begin AdressEdit.Text := ''; FIdCurrentAdress := -1; pManModified := True; end; procedure TfModifyMan.ClearBirthAdrBtnClick(Sender: TObject); begin BirthPlaceEdit.Text := ''; FIdBirthAdress := -1; pManModified := True; end; procedure TfModifyMan.CopyFIOBtnClick(Sender: TObject); var IdSex: integer; cLastSymbol :Char; sName: String; bHasLowerCase: Boolean; begin if (SexBox.ItemIndex = 1) then IdSex := 2 else IdSex := 1; //mug po umolch sName:= ImyaEdit.Text; cLastSymbol := sName[Length(sName)]; bHasLowerCase := ((Ord(cLastSymbol) >= Ord('а')) and (Ord(cLastSymbol) <= Ord('я'))); STProcPerevodFioRus.Transaction.StartTransaction; STProcPerevodFioRus.StoredProcName := 'SYS_PEOPLE_FIO_CONVERT_RUS'; try STProcPerevodFioRus.Prepare; STProcPerevodFioRus.ParamByName('ID_SEX').AsInteger := IdSex; STProcPerevodFioRus.ParamByName('FAMILIYA').AsString := FamiliaEdit.Text; STProcPerevodFioRus.ParamByName('IMYA').AsString := ImyaEdit.Text; STProcPerevodFioRus.ParamByName('OTCHESTVO').AsString := OtchestvoEdit.Text; STProcPerevodFioRus.ParamByName('PRIZNAK').AsInteger := Integer(bHasLowerCase); STProcPerevodFioRus.ExecProc; RusFamEdit.Text := STProcPerevodFioRus.ParamByName('FAMILIYA_RU').AsString; RusImyaEdit.Text := STProcPerevodFioRus.ParamByName('IMYA_RU').AsString; RusOtchEdit.Text := STProcPerevodFioRus.ParamByName('OTCHESTVO_RU').AsString; except on E:Exception do begin MessageDlg('Не вдалося автоматично перекласти ФІО. Причина: ' + #10#13 + E.Message, mtError, [mbOk], 0); RusFamEdit.Text := FamiliaEdit.Text; RusImyaEdit.Text := ImyaEdit.Text; RusOtchEdit.Text := OtchestvoEdit.Text; end end; STProcPerevodFioRus.Transaction.Rollback; end; procedure TfModifyMan.PasportGridDBTableView1CellClick( Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin if VarIsNull(DSPassData['VIDAN']) then VidanDBText.Text := '' else VidanDBText.Text := DSPassData['VIDAN']; end; procedure TfModifyMan.FamilyRefreshBtnClick(Sender: TObject); begin if DSFamily.Active then DSFamily.Close; DSFamily.SQLs.SelectSQL.Text := 'SELECT * FROM Z_FAMILY_BY_ID_MAN(' + IntToStr(IdMan) + ')'; DSFamily.Open; end; procedure TfModifyMan.HistWriteTransactionAfterStart(Sender: TObject); begin // записываем данные о грядущем изменении в таблицу PUB_DT_HISTORY_INFO // уже не записываем, по словам КЯВа данные должна писать аццмжмт-бплина {StProcHist.StoredProcName := 'PUB_SET_HISTORY_INS'; StProcHist.Prepare; StProcHist.ParamByName('IN_ID_USER').AsInt64 := accMgmt.GetUserId; StProcHist.ParamByName('IN_IP_ADRESS').AsString := GetIPAddress; StProcHist.ParamByName('IN_HOST_NAME').AsString := GetCompName; StProcHist.ParamByName('APP_NAME').AsString := ExtractFileName(Application.ExeName); StProcHist.ExecProc; } end; procedure TfModifyMan.ManEditEditing(Sender: TObject; var CanEdit: Boolean); begin // ShowMessage(TComponent(Sender).Name); pManModified := True; end; procedure TfModifyMan.NationalityComboBoxPropertiesChange(Sender: TObject); begin pManModified := True; end; procedure TfModifyMan.PasportGridDBTableView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT: begin if FMode <> emView then AddButtonClick(Self); end; VK_F2: begin if FMode <> emView then ModifyButtonClick(Self); end; VK_SPACE: begin ViewButtonClick(Self); end; VK_DELETE: begin if FMode <> emView then DeleteButtonClick(Self); end; VK_F5: begin RefreshButtonClick(Self); end; end; end; procedure TfModifyMan.FamilyTVKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT: begin if FMode <> emView then FamilyAddBtnClick(Self); end; VK_F2: begin if FMode <> emView then FamilyModifyBtnClick(Self); end; VK_DELETE: begin if FMode <> emView then FamilyDelBtnClick(Self); end; VK_F5: begin FamilyRefreshBtnClick(Self); end; end; end; procedure TfModifyMan.FamiliaEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then ImyaEdit.SetFocus else if not (Key in ['А'..'Я', 'а'..'я', '-', '''', ' ', 'І', 'і', 'Є', 'є', 'Ґ', 'ґ', 'Ї', 'ї', #27, #8]) then Key := #0; end; procedure TfModifyMan.ImyaEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then OtchestvoEdit.SetFocus else if not (Key in ['А'..'Я', 'а'..'я', '-', '''', ' ', 'І', 'і', 'Є', 'є', 'Ґ', 'ґ', 'Ї', 'ї', #27, #8]) then Key := #0; end; procedure TfModifyMan.OtchestvoEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then RusFamEdit.SetFocus else if not (Key in ['А'..'Я', 'а'..'я', '-', '''', ' ', 'І', 'і', 'Є', 'є', 'Ґ', 'ґ', 'Ї', 'ї', #27, #8]) then Key := #0; end; procedure TfModifyMan.RusFamEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then RusImyaEdit.SetFocus; end; procedure TfModifyMan.RusImyaEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then RusOtchEdit.SetFocus; end; procedure TfModifyMan.RusOtchEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then SexBox.SetFocus; end; procedure TfModifyMan.SexBoxKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then BirthDateEdit.SetFocus; end; procedure TfModifyMan.BirthDateEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then TinEdit.SetFocus; end; procedure TfModifyMan.TinEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then SocCardNumEdit.SetFocus; end; procedure TfModifyMan.SocCardNumEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then AdressEdit.SetFocus; end; procedure TfModifyMan.AdressEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then LiveAdressEdit.SetFocus; end; procedure TfModifyMan.BirthPlaceEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then FamiliaEdit.SetFocus; end; procedure TfModifyMan.WorkPhoneEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then HomePhoneEdit.SetFocus; end; procedure TfModifyMan.HomePhoneEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then NationalityComboBox.SetFocus; end; procedure TfModifyMan.NationalityComboBoxKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then WorkPhoneEdit.SetFocus; end; procedure TfModifyMan.InitFoto(AImageDB_Handle: TISC_DB_HANDLE); begin if AImageDB_Handle = nil then // не показываем панели с фотографиями, но и не выводим никакого сообщения begin FotoPanel.Hide; Width := Width - 155; end else // в случае, если все пучком, - подключаемся к базе begin DBFoto.Handle := AImageDB_Handle; ReadTrFoto.Active := True; if IdMan <> -1 then RefreshFoto; //проверяем наличие прав на правку/просмотр фотографий if not IsAccessGranted(SAP_Foto, cEdit) then begin AddFotoBtn.Enabled := False; DelFotoBtn.Enabled := False; if not IsAccessGranted(SAP_Foto, cView) then begin FotoPanel.Hide; Width := Width - 155; end; end; end; end; procedure TfModifyMan.RefreshFoto; begin if DSetFoto.Active then DSetFoto.Close; DSetFoto.SQLs.SelectSQL.Text := 'SELECT * FROM FOTO_ICON_GET_BY_ID_MAN(' + IntToStr(IdMan) + ') ORDER BY DATE_FOTO DESCENDING, ID_FOTO DESCENDING'; // Т.к. ID_FOTO присваивается по мере добавления в БД, следовательно, более поздние фото имеют больший ID DSetFoto.Open; DSetFoto.First; end; procedure TfModifyMan.SaveAsBtnClick(Sender: TObject); begin StProcFoto.StoredProcName := 'FOTO_GET_BY_ID'; // Процедура вставки записи в таблицу StProcFoto.Transaction.StartTransaction; StProcFoto.Prepare; StProcFoto.ParamByName('IN_ID_FOTO').AsInteger := DSetFoto.fbn('ID_FOTO').AsInteger; StProcFoto.ExecProc; // выполняем try if not SaveDialog.Execute then Exit; StProcFoto.FieldByName('FOTO').SaveToFile(SaveDialog.FileName); StProcFoto.Transaction.Commit; except on E: Exception do begin StProcFoto.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; procedure TfModifyMan.AddFotoBtnClick(Sender: TObject); var HandlePack: HModule; MDIFUNC: function(AOwner: TComponent; DBM, DB: TISC_DB_HANDLE; AIdMan: Integer): Variant; stdcall; Res: Variant; begin if IdMan = -1 then if not AskToInsMan(InsMan_Message) then Exit; HandlePack := GetModuleHandle('SpAllPeople_Foto.bpl'); if HandlePack < 32 then try Screen.Cursor := crHourGlass; HandlePack := LoadPackage(ExtractFilePath(Application.ExeName) + 'SpAllPeople_Foto.bpl'); finally Screen.Cursor := crDefault; end; if HandlePack > 0 then begin @MDIFUNC := GetProcAddress(HandlePack, PChar('AddFoto')); if @MDIFUNC <> nil then Res := MDIFUNC(Self, DB.Handle, DBFoto.Handle, IdMan); end else begin MessageBox(TForm(Self).Handle, PChar('Неможливо завантажити' + #13 + 'SpAllPeople_Foto.bpl'), PChar('Помилка'), MB_OK and MB_ICONWARNING); Res := NULL; end; RefreshFoto; end; function TfModifyMan.ValidateTIN: Boolean; var Str: string; BDate: TDate; ViewMessageForm: TForm; i: integer; begin Result := True; if not ((TinEdit.Text = '') or (BirthDateEdit.Text = '')) then begin // Если ИНН ненастоящий, то делать нам тут нечего if Length(TinEdit.Text) < 10 then Exit; {Проверяем первые пять цифр ИД номера. Они образуют число, которое равно количеству дней от 01.01.1900 до даты рождения, т.е. : 31.12.1899 + N = Дата_рождения (N - количество дней - первые пять цифр). Если ИД номер не проходит проверку, то выдается сообщение и дается возможность вернуться в редактирование и продолжить сохранение. Сообщение должно содержать вариант начала ИД номера (по введенной дате рождения), и вариант даты рождения(по введенному ИД номеру). } Str := Copy(TinEdit.Text, 1, 5); BDate := StrToInt(Str) + 1; if BDate <> BirthDateEdit.EditValue then begin //****************************************************************************** ViewMessageForm := CreateMessageDialog('Введений податковий номер не відповідає даті народження.' + #13 + 'Можливі варіанти податкового коду та дати народження, відповідно:' + #13 + TinEdit.Text + ' - ' + DateToStr(BDate) + #13 + IntToStr(Integer(BirthDateEdit.EditValue) - 1) + Copy(TinEdit.Text, 6, 5) + ' - ' + BirthDateEdit.Text, mtWarning, [mbYes, mbNo]); with ViewMessageForm do begin for i := 0 to ComponentCount - 1 do if (Components[i].ClassType = TButton) then begin if UpperCase((Components[i] as TButton).Caption) = '&YES' then begin (Components[i] as TButton).Left := 15; (Components[i] as TButton).Caption := 'Повернутися до редагування'; (Components[i] as TButton).Width := 240; end; if UpperCase((Components[i] as TButton).Caption) = '&NO' then begin (Components[i] as TButton).Left := 260; (Components[i] as TButton).Caption := 'Продовжити збереження'; (Components[i] as TButton).Width := 150; end; end; Caption := 'Увага'; i := ShowModal; Free; end; case i of mrYes: begin Result := False; PeoplePageControl.ActivePage := MainPage; TinEdit.SetFocus; end; mrNo: begin Result := True; end; end; //****************************************************************************** end; end else begin //****************************************************************************** ViewMessageForm := CreateMessageDialog('Не вказано ' + IfThen(TinEdit.Text = '', 'податковий номер', '') + IfThen((TinEdit.Text = '') and (BirthDateEdit.Text = ''), ' та ', '') + IfThen(BirthDateEdit.Text = '', 'дату народження', '') + '!', mtWarning, [mbYes, mbNo]); with ViewMessageForm do begin Width := 425; Position := poScreenCenter; for i := 0 to ComponentCount - 1 do if (Components[i].ClassType = TButton) then begin if UpperCase((Components[i] as TButton).Caption) = '&YES' then begin (Components[i] as TButton).Left := 15; (Components[i] as TButton).Caption := 'Повернутися до редагування'; (Components[i] as TButton).Width := 240; end; if UpperCase((Components[i] as TButton).Caption) = '&NO' then begin (Components[i] as TButton).Left := 260; (Components[i] as TButton).Caption := 'Продовжити збереження'; (Components[i] as TButton).Width := 150; end; end; Caption := 'Увага'; i := ShowModal; Free; end; case i of mrYes: begin Result := False; PeoplePageControl.ActivePage := MainPage; if BirthDateEdit.Text = '' then BirthDateEdit.SetFocus else TinEdit.SetFocus; end; mrNo: begin //********* TIN := ''; //********* Result := True; //*** //PeoplePageControl.ActivePage:=MainPage; //*** end; end; //****************************************************************************** end; end; procedure TfModifyMan.DelFotoBtnClick(Sender: TObject); begin if DSetFoto.IsEmpty then Exit; if ZShowMessage('Вилучення', 'Ви справді бажаєте вилучити фото?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin try StProcFoto.Transaction.StartTransaction; StProcFoto.StoredProcName := 'FOTO_MAIN_D'; StProcFoto.Prepare; StProcFoto.ParamByName('IN_ID_FOTO').AsInteger := DSetFoto['ID_FOTO']; StProcFoto.ExecProc; StProcFoto.Transaction.Commit; DelFotoProc.Transaction.StartTransaction; DelFotoProc.StoredProcName := 'UP_DT_CERT_MAN_FOTO_I_D'; DelFotoProc.Prepare; DelFotoProc.ParamByName('ID_FOTO').AsInteger := DSetFoto['ID_FOTO']; //DSetFoto.FieldByName('ID_FOTO').AsInteger; DelFotoProc.ParamByName('IS_INSERT').AsInteger := 0; DelFotoProc.ExecProc; DelFotoProc.Transaction.Commit; RefreshFoto; except on e: Exception do begin StProcFoto.Transaction.Rollback; DelFotoProc.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; end; procedure TfModifyMan.cmnDATE_FOTOGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); begin AText := 'Від ' + AText; end; function TfModifyMan.GetCorrectTIN: Variant; begin if Trim(TIN) = '' then Result := Null else Result := TIN; end; procedure TfModifyMan.UpdateFIOOnForm; begin ProcPassData.Transaction.StartTransaction; try ProcPassData.ExecProcedure('PEOPLE_UPDATE_FIO_BY_PASS', [IdMan]); FamiliaEdit.Text := ProcPassData.FN('Familia').AsString; ImyaEdit.Text := ProcPassData.FN('Imya').AsString; OtchestvoEdit.Text := ProcPassData.FN('Otchestvo').AsString; CopyFIOBtnClick(Self); ProcPassData.Transaction.Commit; except on e: Exception do begin ProcPassData.Transaction.Rollback; ZShowMessage('Помилка', E.Message, mtError, [mbOK]); end; end; end; procedure TfModifyMan.PeoplePageControlChange(Sender: TObject); begin if (IdMan = -1) and (PeoplePageControl.ActivePage = BankCardPage) then if not AskToInsMan(InsMan_Message) then Exit else pBankCardFrame := TframeCard.Create(BankCardPage, DB.Handle, FMode, IdMan, TinEdit.Text); end; procedure TfModifyMan.ManEditPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var s: string; begin // удаляем пробелы в начале и в конце фамилии, имени и т.д. s := VarToStr(DisplayValue); if Length(s)<1 then Exit; while s[1] = ' ' do Delete(s, 1, 1); while s[Length(s)] = ' ' do Delete(s, Length(s), 1); DisplayValue := s; end; procedure TfModifyMan.GromodPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var AdressesSp: TSprav; IdAdr: Variant; begin AdressesSp := GetSprav('Adresses'); if (AdressesSp <> nil) then begin with AdressesSp.Input do begin Edit; FieldValues['Id_Adress'] := IdAdr; FieldValues['DbHandle'] := Integer(DB.Handle); FieldValues['Select'] := 1; FieldValues['ShowStyle'] := 6; Post; end; AdressesSp.Show; // ShowMessage(AdressesSp.Output['Name_Adr']); if (not VarIsNull(AdressesSp.Output['Name_Adr'])) then begin Gromod.Text := AdressesSp.Output['Name_Adr']; FidGrom := AdressesSp.Output['id_adress']; pManModified := True; end; end; end; procedure TfModifyMan.GromodEditing(Sender: TObject; var CanEdit: Boolean); begin pManModified := True; end; procedure TfModifyMan.FormShow(Sender: TObject); begin {if (RusFamEdit.IsFocused or RusImyaEdit.IsFocused or RusOtchEdit.IsFocused) then begin Showmessage('Aaaa!'); LoadKeyboardLayout('00000419', 1); // ActivateKeyboardLayout(00000419, KLF_SETFORPROCESS); end; } end; procedure TfModifyMan.RusFamEditEnter(Sender: TObject); begin LoadKeyboardLayout('00000419', 1); end; procedure TfModifyMan.RusImyaEditEnter(Sender: TObject); begin LoadKeyboardLayout('00000419', 1); end; procedure TfModifyMan.RusOtchEditEnter(Sender: TObject); begin LoadKeyboardLayout('00000419', 1); end; procedure TfModifyMan.RusFamEditExit(Sender: TObject); begin LoadKeyboardLayout('00000422', 1); end; procedure TfModifyMan.RusOtchEditExit(Sender: TObject); begin LoadKeyboardLayout('00000422', 1); end; procedure TfModifyMan.RusImyaEditExit(Sender: TObject); begin LoadKeyboardLayout('00000422', 1); end; procedure TfModifyMan.LiveAdressEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then BirthPlaceEdit.SetFocus; end; procedure TfModifyMan.ClearLiveAdrBtnClick(Sender: TObject); begin LiveAdressEdit.Text := ''; FIdLiveAdress := -1; pManModified := True; end; procedure TfModifyMan.CopyBirthPlaceClick(Sender: TObject); begin if not (FIdBirthAdress > 0) then // т.е. место рождения не указано => мы предполагаем его сами SetDefaultBirthPlace(FIdCurrentAdress); end; procedure TfModifyMan.CopyAdressBtnClick(Sender: TObject); begin if not (FIdCurrentAdress > 0) then begin AdressEdit.Text := LiveAdressEdit.Text; FIdCurrentAdress := FIdLiveAdress; end; end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0047.PAS Description: One Month Calendar Author: KEITH MERCATILI Date: 11-26-94 04:59 *) { A couple of weeks ago, my computer science had to write a computer program to generate a calendar. Now my assignment is to incorporate the use of appropriate enumeration and subrange data types, and corresponding procedures to support these, into the program as a way of improving it. Here is the program that I would like some suggestions on.. Thanks in advance: } program OneMonthCalendar ( INPUT, OUTPUT ) ; var Month : INTEGER ; (* The month number; a value in the range 1 - 12 *) PrevMonthDays : INTEGER ; (* The number of days in the previous month *) CurrMonthDays : INTEGER ; (* The number of days in the desired month *) StartDay : INTEGER ; (* A value indicating the day of the week on *) (* which the month begins; 0 = Sunday, 1 = *) (* Monday, etc *) Date : INTEGER ; (* The data currently being generated *) (*----------------------------------------------------------*) (*----------------------------------------------------------*) procedure ReadData ( var MonthNumber : INTEGER (* out - The month number *) ; var PreviousMonthDays : INTEGER (* out - Number of days in the previous month *) ; var CurrentMonthDays : INTEGER (* out - Number of days in the desired month *) ; var StartingDay : INTEGER (* out - The day of the week on which the desired month begins *) ) ; begin (* procedure *) Write ('Enter the month number: '); ReadLn ( MonthNumber ) ; Write ('Enter the days in the previous month: '); ReadLn ( PreviousMonthDays ) ; Write ('Enter the days in the current month: '); ReadLn ( CurrentMonthDays ) ; Write ('Enter the starting day: '); ReadLn ( StartingDay ) ; end (* ReadData *) ; (*----------------------------------------------------------*) procedure WriteHeading ( Month : INTEGER (* in - The month number *) ) ; begin (* procedure *) WriteLn; WriteLn ( 'Month ', Month:2); WriteLn ( '+----------------------+'); WriteLn ( '| S M T W T F S |'); WriteLn ( '+----------------------+'); end (* WriteHeading *) ; (*----------------------------------------------------------*) procedure WriteTrailing; begin (* procedure *) WriteLn ('+----------------------+'); end (* WriteTrailing *) ; (*----------------------------------------------------------*) procedure IncrementDate ( var Date : INTEGER (* in out - The date value to be incremented *) ; DateLimit : INTEGER (* in - The number of days in the month corresponding to the given date value *) ); begin (* procedure *) if Date < DateLimit then begin Date := Date + 1 ; end else begin Date := 1 end (* if *) ; end (* IncrementDate *) ; (*----------------------------------------------------------*) procedure OneDayCalendar ( Date : INTEGER (* in - The date value for the day *) ) ; begin (* procedure *) Write ( Date:3 ) ; end (* OneDayCalendar *) ; (*----------------------------------------------------------*) procedure OneWeekCalendar ( var Date : INTEGER (* in out - The date value *) ; MonthsLastDate : INTEGER (* in - The date value of the last day *) (* in the month corresponding to the *) (* given date value *) ) ; var Day : INTEGER ;(* Counting variable *) begin (* procedure *) Write ('|'); for Day := 1 to 7 do begin OneDayCalendar ( Date ) ; IncrementDate ( Date, MonthsLastDate ) ; (* Day's value represents the number of dates outputed *) end (* for *) ; WriteLn (' |'); end (* OneWeekCalendar *) ; (*----------------------------------------------------------*) procedure DetermineSundayDate ( PreviousMonthDays : INTEGER (* in - The number of days in the *) (* previous month *) ; StartingDay : INTEGER (* in - A value representing the day of the *) (* week on which the desired month begins *) ; var SundayDate : INTEGER (* out - The date of the Sunday for the *) (* first week in the calendar *) ) ; begin (* procedure *) SundayDate := PreviousMonthDays - StartingDay; IncrementDate (SundayDate, PreviousMonthDays); end (* DetermineSundayDate *) ; (*----------------------------------------------------------*) procedure GenerateCalendar ( Date : INTEGER (* in - The starting date *) ; PreviousMonth : INTEGER (* in - The number of days in the previous month *) ; CurrentMonth : INTEGER (* in - The number of days in the current month *) ) ; var PreviousSunday : INTEGER ; (* The date of the previous sunday *) begin (* procedure *) OneWeekCalendar ( Date, PreviousMonth ) ; PreviousSunday := Date; while Date >= PreviousSunday do begin PreviousSunday := Date; OneWeekCalendar ( Date, CurrentMonth ) ; end (* while *) ; end (* GenerateCalendar *) ; (*=======================================================================*) begin (* main program *) WriteLn ('One Month Calendar - Version 4'); WriteLn; while NOT EOF do begin ReadData ( Month, PrevMonthDays, CurrMonthDays, StartDay ) ; WriteHeading (Month); DetermineSundayDate (PrevMonthDays, StartDay, Date); GenerateCalendar (Date, PrevMonthDays, CurrMonthDays); WriteTrailing; (* EOLN is true *) end (* while *) ; end (* OneMonthCalendar *).
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_Base64; interface uses Classes, uTPLb_StreamCipher; type TBase64Converter = class( TInterfacedObject, IStreamCipher, ICryptoGraphicAlgorithm, IisBase64Converter) private function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DefinitionURL: string; function WikipediaReference: string; function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; function SeedByteSize: integer; function Parameterize( const Params: IInterface): IStreamCipher; function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor; end; implementation uses SysUtils, uTPLb_CipherUtils, uTPLb_StreamUtils, uTPLb_PointerArithmetic, uTPLb_Constants, uTPLb_I18n; { TBase64Converter } function TBase64Converter.DefinitionURL: string; begin result := 'http://tools.ietf.org/html/rfc4648' end; function TBase64Converter.DisplayName: string; begin result := Base64_DisplayName end; function TBase64Converter.Features: TAlgorithmicFeatureSet; begin result := [afOpenSourceSoftware, afConverter] end; function TBase64Converter.GenerateKey( Seed: TStream): TSymetricKey; begin result := TDummyKey.Create end; function TBase64Converter.LoadKeyFromStream( Store: TStream): TSymetricKey; begin result := TDummyKey.Create end; function TBase64Converter.Parameterize( const Params: IInterface): IStreamCipher; begin result := nil end; function TBase64Converter.ProgId: string; begin result := Base64_ProgId end; function TBase64Converter.SeedByteSize: integer; begin result := -1 end; type TBase64Conv = class( TInterfacedObject, IStreamEncryptor, IStreamDecryptor, IisBase64Converter) private FInBuffer: TMemoryStream; FInBufferLen: integer; FOutStream: TStream; procedure Encrypt( const Plaintext: TStream); procedure End_Encrypt; procedure Decrypt( const Ciphertext: TStream); procedure End_Decrypt; procedure Reset; public constructor Create( OutStream1: TStream); destructor Destroy; override; end; function TBase64Converter.Start_Decrypt( Key: TSymetricKey; PlainText: TStream): IStreamDecryptor; begin result := TBase64Conv.Create( Plaintext) end; function TBase64Converter.Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; begin result := TBase64Conv.Create( Ciphertext) end; function TBase64Converter.WikipediaReference: string; begin result := {'http://en.wikipedia.org/wiki/' +} 'Base64' end; { TBase64Conv } constructor TBase64Conv.Create( OutStream1: TStream); begin FInBuffer := TMemoryStream.Create; FInBufferLen := 0; FOutStream := OutStream1 end; destructor TBase64Conv.Destroy; begin BurnMemoryStream( FInBuffer); FInBuffer.Free; inherited end; const BufferBlocks = 100; ToBase64_BufferSize = BufferBlocks * 3; FromBase64_BufferSize = BufferBlocks * 4; procedure TBase64Conv.Encrypt( const Plaintext: TStream); var Space: integer; Amnt: integer; isLast: boolean; base64_Fragment: TBytes; begin if FInBufferLen = 0 then FInBuffer.Size := ToBase64_BufferSize; // It can be any size, as long as it is a multiple of 3. repeat Space := ToBase64_BufferSize - FInBufferLen; Amnt := ReadMem( Plaintext, FInBuffer, FInBufferLen, Space); // Amnt := Plaintext.Read( pointer( integer(FInBuffer.Memory) + FInBufferLen)^, Space); isLast := Amnt < Space; Inc( FInBufferLen, Amnt); Dec( Space, Amnt); if Space <= 0 then begin // We have full buffer, aligned to 3-byte. base64_Fragment := Stream_to_Base64( FInBuffer); AnsiString_to_stream( base64_Fragment, FOutStream); FInBufferLen := 0 end until isLast end; procedure TBase64Conv.End_Encrypt; var base64_Fragment: TBytes; begin if FInBufferLen > 0 then begin FInBuffer.Size := FInBufferLen; base64_Fragment := Stream_to_Base64( FInBuffer); AnsiString_to_stream( base64_Fragment, FOutStream); FInBufferLen := 0 end end; procedure TBase64Conv.Decrypt( const Ciphertext: TStream); var Space: integer; Amnt: integer; isLast: boolean; base64_Fragment: TBytes; begin if FInBufferLen = 0 then FInBuffer.Size := FromBase64_BufferSize; // It can be any size, as long as it is a multiple of 4. repeat Space := FromBase64_BufferSize - FInBufferLen; // Amnt := Ciphertext.Read( pointer( integer(FInBuffer.Memory) + FInBufferLen)^, Space); Amnt := ReadMem( Ciphertext, FInBuffer, FInBufferLen, Space); isLast := Amnt < Space; Inc( FInBufferLen, Amnt); Dec( Space, Amnt); if Space <= 0 then begin // We have full buffer, aligned to 4-ansichar. SetLength( base64_Fragment, FromBase64_BufferSize); FInBuffer.Position := 0; FInBuffer.Read( base64_Fragment[1], FromBase64_BufferSize); Base64_to_stream( base64_Fragment, FOutStream); FInBufferLen := 0 end until isLast end; procedure TBase64Conv.End_Decrypt; var base64_Fragment: TBytes; begin if FInBufferLen > 0 then begin SetLength( base64_Fragment, FInBufferLen); FInBuffer.Position := 0; FInBuffer.Read( base64_Fragment[0], FInBufferLen); Base64_to_stream( base64_Fragment, FOutStream); FInBufferLen := 0 end end; procedure TBase64Conv.Reset; begin BurnMemoryStream( FInBuffer); FInBufferLen := 0 end; end.
unit Odontologia.Modelo.Entidades.Pais; interface uses SimpleAttributes; type [Tabela('DPAIS')] TDPAIS = Class private FID: Integer; FNOMBRE: String; procedure SetID(const Value: Integer); procedure SetNOMBRE(const Value: String); published [Campo('PAI_CODIGO'), Pk, AutoInc] property ID : Integer read FID write SetID; [Campo('PAI_NOMBRE')] property NOMBRE : String read FNOMBRE write SetNOMBRE; End; implementation { TPAIS } procedure TDPAIS.SetID(const Value: Integer); begin FID := Value; end; procedure TDPAIS.SetNOMBRE(const Value: String); begin FNOMBRE := Value; end; end.
unit pkcs11_mechanism; interface uses pkcs11_api, pkcs11t; type TPKCS11KeysizeUnits = (ksmBits, ksmBytes, ksmNA); TPKCS11Mechanism = class (TPKCS11API) private protected FSlotID: Integer; FMechanismType: CK_MECHANISM_TYPE; function GetFlags(): CK_FLAGS; function GetMinKeySize(): Cardinal; function GetMaxKeySize(): Cardinal; function GetMinKeySizeInBits(): Cardinal; function GetMaxKeySizeInBits(): Cardinal; function GetMechanismTypeStr(): String; // Determine whether the ulMinKeySize/ulMaxKeySize fields returned by // CK_MECHANISM_INFO are measured in bits or bytes function KeysizeUnits(mechanism: CK_MECHANISM_TYPE): TPKCS11KeysizeUnits; public property SlotID: Integer Read FSlotID Write FSlotID; property MechanismType: CK_MECHANISM_TYPE Read FMechanismType Write FMechanismType; property MechanismTypeStr: String Read GetMechanismTypeStr; // Warning! // The values returned by these properties are those returned by // the mechanism's CK_MECHANISM_INFO; can be measured bits or bytes - it's // mechanism dependant! property MinKeySize: Cardinal Read GetMinKeySize; property MaxKeySize: Cardinal Read GetMaxKeySize; // Return the above, but always return the sizes as a number of *bits* property MinKeySizeInBits: Cardinal Read GetMinKeySizeInBits; property MaxKeySizeInBits: Cardinal Read GetMaxKeySizeInBits; property Flags: CK_FLAGS Read GetFlags; function GetMechanismInfo(var info: CK_MECHANISM_INFO): Boolean; function MechanismToString(mechanism: CK_MECHANISM_TYPE): String; end; TPKCS11MechanismArray = array of TPKCS11Mechanism; implementation uses pkcs11f, SDUGeneral, SDUi18n, SysUtils; function TPKCS11Mechanism.GetMechanismInfo(var info: CK_MECHANISM_INFO): Boolean; begin CheckFnAvailable(@LibraryFunctionList.CK_C_GetMechanismInfo, FN_NAME_C_GetMechanismInfo); LastRV := LibraryFunctionList.CK_C_GetMechanismInfo(FSlotID, FMechanismType, @info); Result := RVSuccess(LastRV); end; function TPKCS11Mechanism.GetFlags(): CK_FLAGS; var info: CK_MECHANISM_INFO; begin Result := 0; if (GetMechanismInfo(info)) then Result := info.Flags; Result := Result; end; function TPKCS11Mechanism.GetMinKeySize(): Cardinal; var info: CK_MECHANISM_INFO; begin Result := 0; if (GetMechanismInfo(info)) then Result := info.ulMinKeySize; Result := Result; end; function TPKCS11Mechanism.GetMaxKeySize(): Cardinal; var info: CK_MECHANISM_INFO; begin Result := 0; if (GetMechanismInfo(info)) then Result := info.ulMaxKeySize; Result := Result; end; function TPKCS11Mechanism.GetMinKeySizeInBits(): Cardinal; begin Result := GetMinKeySize(); if (KeysizeUnits(MechanismType) = ksmBytes) then begin Result := Result * 8; end; Result := Result; end; function TPKCS11Mechanism.GetMaxKeySizeInBits(): Cardinal; begin Result := GetMaxKeySize(); if (KeysizeUnits(MechanismType) = ksmBytes) then begin Result := Result * 8; end; Result := Result; end; function TPKCS11Mechanism.GetMechanismTypeStr(): String; begin Result := MechanismToString(FMechanismType); end; function TPKCS11Mechanism.MechanismToString(mechanism: CK_MECHANISM_TYPE): String; begin Result := RS_UNKNOWN + ' (0x' + inttohex(Ord(mechanism), 8) + ')'; case mechanism of CKM_RSA_PKCS_KEY_PAIR_GEN: Result := 'CKM_RSA_PKCS_KEY_PAIR_GEN'; CKM_RSA_PKCS: Result := 'CKM_RSA_PKCS'; CKM_RSA_9796: Result := 'CKM_RSA_9796'; CKM_RSA_X_509: Result := 'CKM_RSA_X_509'; CKM_MD2_RSA_PKCS: Result := 'CKM_MD2_RSA_PKCS'; CKM_MD5_RSA_PKCS: Result := 'CKM_MD5_RSA_PKCS'; CKM_SHA1_RSA_PKCS: Result := 'CKM_SHA1_RSA_PKCS'; CKM_RIPEMD128_RSA_PKCS: Result := 'CKM_RIPEMD128_RSA_PKCS'; CKM_RIPEMD160_RSA_PKCS: Result := 'CKM_RIPEMD160_RSA_PKCS'; CKM_RSA_PKCS_OAEP: Result := 'CKM_RSA_PKCS_OAEP'; CKM_RSA_X9_31_KEY_PAIR_GEN: Result := 'CKM_RSA_X9_31_KEY_PAIR_GEN'; CKM_RSA_X9_31: Result := 'CKM_RSA_X9_31'; CKM_SHA1_RSA_X9_31: Result := 'CKM_SHA1_RSA_X9_31'; CKM_RSA_PKCS_PSS: Result := 'CKM_RSA_PKCS_PSS'; CKM_SHA1_RSA_PKCS_PSS: Result := 'CKM_SHA1_RSA_PKCS_PSS'; CKM_DSA_KEY_PAIR_GEN: Result := 'CKM_DSA_KEY_PAIR_GEN'; CKM_DSA: Result := 'CKM_DSA'; CKM_DSA_SHA1: Result := 'CKM_DSA_SHA1'; CKM_DH_PKCS_KEY_PAIR_GEN: Result := 'CKM_DH_PKCS_KEY_PAIR_GEN'; CKM_DH_PKCS_DERIVE: Result := 'CKM_DH_PKCS_DERIVE'; CKM_X9_42_DH_KEY_PAIR_GEN: Result := 'CKM_X9_42_DH_KEY_PAIR_GEN'; CKM_X9_42_DH_DERIVE: Result := 'CKM_X9_42_DH_DERIVE'; CKM_X9_42_DH_HYBRID_DERIVE: Result := 'CKM_X9_42_DH_HYBRID_DERIVE'; CKM_X9_42_MQV_DERIVE: Result := 'CKM_X9_42_MQV_DERIVE'; CKM_SHA256_RSA_PKCS: Result := 'CKM_SHA256_RSA_PKCS'; CKM_SHA384_RSA_PKCS: Result := 'CKM_SHA384_RSA_PKCS'; CKM_SHA512_RSA_PKCS: Result := 'CKM_SHA512_RSA_PKCS'; CKM_SHA256_RSA_PKCS_PSS: Result := 'CKM_SHA256_RSA_PKCS_PSS'; CKM_SHA384_RSA_PKCS_PSS: Result := 'CKM_SHA384_RSA_PKCS_PSS'; CKM_SHA512_RSA_PKCS_PSS: Result := 'CKM_SHA512_RSA_PKCS_PSS'; CKM_SHA224_RSA_PKCS: Result := 'CKM_SHA224_RSA_PKCS'; CKM_SHA224_RSA_PKCS_PSS: Result := 'CKM_SHA224_RSA_PKCS_PSS'; CKM_RC2_KEY_GEN: Result := 'CKM_RC2_KEY_GEN'; CKM_RC2_ECB: Result := 'CKM_RC2_ECB'; CKM_RC2_CBC: Result := 'CKM_RC2_CBC'; CKM_RC2_MAC: Result := 'CKM_RC2_MAC'; CKM_RC2_MAC_GENERAL: Result := 'CKM_RC2_MAC_GENERAL'; CKM_RC2_CBC_PAD: Result := 'CKM_RC2_CBC_PAD'; CKM_RC4_KEY_GEN: Result := 'CKM_RC4_KEY_GEN'; CKM_RC4: Result := 'CKM_RC4'; CKM_DES_KEY_GEN: Result := 'CKM_DES_KEY_GEN'; CKM_DES_ECB: Result := 'CKM_DES_ECB'; CKM_DES_CBC: Result := 'CKM_DES_CBC'; CKM_DES_MAC: Result := 'CKM_DES_MAC'; CKM_DES_MAC_GENERAL: Result := 'CKM_DES_MAC_GENERAL'; CKM_DES_CBC_PAD: Result := 'CKM_DES_CBC_PAD'; CKM_DES2_KEY_GEN: Result := 'CKM_DES2_KEY_GEN'; CKM_DES3_KEY_GEN: Result := 'CKM_DES3_KEY_GEN'; CKM_DES3_ECB: Result := 'CKM_DES3_ECB'; CKM_DES3_CBC: Result := 'CKM_DES3_CBC'; CKM_DES3_MAC: Result := 'CKM_DES3_MAC'; CKM_DES3_MAC_GENERAL: Result := 'CKM_DES3_MAC_GENERAL'; CKM_DES3_CBC_PAD: Result := 'CKM_DES3_CBC_PAD'; CKM_CDMF_KEY_GEN: Result := 'CKM_CDMF_KEY_GEN'; CKM_CDMF_ECB: Result := 'CKM_CDMF_ECB'; CKM_CDMF_CBC: Result := 'CKM_CDMF_CBC'; CKM_CDMF_MAC: Result := 'CKM_CDMF_MAC'; CKM_CDMF_MAC_GENERAL: Result := 'CKM_CDMF_MAC_GENERAL'; CKM_CDMF_CBC_PAD: Result := 'CKM_CDMF_CBC_PAD'; CKM_DES_OFB64: Result := 'CKM_DES_OFB64'; CKM_DES_OFB8: Result := 'CKM_DES_OFB8'; CKM_DES_CFB64: Result := 'CKM_DES_CFB64'; CKM_DES_CFB8: Result := 'CKM_DES_CFB8'; CKM_MD2: Result := 'CKM_MD2'; CKM_MD2_HMAC: Result := 'CKM_MD2_HMAC'; CKM_MD2_HMAC_GENERAL: Result := 'CKM_MD2_HMAC_GENERAL'; CKM_MD5: Result := 'CKM_MD5'; CKM_MD5_HMAC: Result := 'CKM_MD5_HMAC'; CKM_MD5_HMAC_GENERAL: Result := 'CKM_MD5_HMAC_GENERAL'; CKM_SHA_1: Result := 'CKM_SHA_1'; CKM_SHA_1_HMAC: Result := 'CKM_SHA_1_HMAC'; CKM_SHA_1_HMAC_GENERAL: Result := 'CKM_SHA_1_HMAC_GENERAL'; CKM_RIPEMD128: Result := 'CKM_RIPEMD128'; CKM_RIPEMD128_HMAC: Result := 'CKM_RIPEMD128_HMAC'; CKM_RIPEMD128_HMAC_GENERAL: Result := 'CKM_RIPEMD128_HMAC_GENERAL'; CKM_RIPEMD160: Result := 'CKM_RIPEMD160'; CKM_RIPEMD160_HMAC: Result := 'CKM_RIPEMD160_HMAC'; CKM_RIPEMD160_HMAC_GENERAL: Result := 'CKM_RIPEMD160_HMAC_GENERAL'; CKM_SHA256: Result := 'CKM_SHA256'; CKM_SHA256_HMAC: Result := 'CKM_SHA256_HMAC'; CKM_SHA256_HMAC_GENERAL: Result := 'CKM_SHA256_HMAC_GENERAL'; CKM_SHA224: Result := 'CKM_SHA224'; CKM_SHA224_HMAC: Result := 'CKM_SHA224_HMAC'; CKM_SHA224_HMAC_GENERAL: Result := 'CKM_SHA224_HMAC_GENERAL'; CKM_SHA384: Result := 'CKM_SHA384'; CKM_SHA384_HMAC: Result := 'CKM_SHA384_HMAC'; CKM_SHA384_HMAC_GENERAL: Result := 'CKM_SHA384_HMAC_GENERAL'; CKM_SHA512: Result := 'CKM_SHA512'; CKM_SHA512_HMAC: Result := 'CKM_SHA512_HMAC'; CKM_SHA512_HMAC_GENERAL: Result := 'CKM_SHA512_HMAC_GENERAL'; CKM_SECURID_KEY_GEN: Result := 'CKM_SECURID_KEY_GEN'; CKM_SECURID: Result := 'CKM_SECURID'; CKM_HOTP_KEY_GEN: Result := 'CKM_HOTP_KEY_GEN'; CKM_HOTP: Result := 'CKM_HOTP'; CKM_ACTI: Result := 'CKM_ACTI'; CKM_ACTI_KEY_GEN: Result := 'CKM_ACTI_KEY_GEN'; CKM_CAST_KEY_GEN: Result := 'CKM_CAST_KEY_GEN'; CKM_CAST_ECB: Result := 'CKM_CAST_ECB'; CKM_CAST_CBC: Result := 'CKM_CAST_CBC'; CKM_CAST_MAC: Result := 'CKM_CAST_MAC'; CKM_CAST_MAC_GENERAL: Result := 'CKM_CAST_MAC_GENERAL'; CKM_CAST_CBC_PAD: Result := 'CKM_CAST_CBC_PAD'; CKM_CAST3_KEY_GEN: Result := 'CKM_CAST3_KEY_GEN'; CKM_CAST3_ECB: Result := 'CKM_CAST3_ECB'; CKM_CAST3_CBC: Result := 'CKM_CAST3_CBC'; CKM_CAST3_MAC: Result := 'CKM_CAST3_MAC'; CKM_CAST3_MAC_GENERAL: Result := 'CKM_CAST3_MAC_GENERAL'; CKM_CAST3_CBC_PAD: Result := 'CKM_CAST3_CBC_PAD'; CKM_CAST5_KEY_GEN: Result := 'CKM_CAST5_KEY_GEN'; //CKM_CAST128_KEY_GEN: Result := 'CKM_CAST128_KEY_GEN'; CKM_CAST5_ECB: Result := 'CKM_CAST5_ECB'; //CKM_CAST128_ECB: Result := 'CKM_CAST128_ECB'; CKM_CAST5_CBC: Result := 'CKM_CAST5_CBC'; //CKM_CAST128_CBC: Result := 'CKM_CAST128_CBC'; CKM_CAST5_MAC: Result := 'CKM_CAST5_MAC'; //CKM_CAST128_MAC: Result := 'CKM_CAST128_MAC'; CKM_CAST5_MAC_GENERAL: Result := 'CKM_CAST5_MAC_GENERAL'; //CKM_CAST128_MAC_GENERAL: Result := 'CKM_CAST128_MAC_GENERAL'; CKM_CAST5_CBC_PAD: Result := 'CKM_CAST5_CBC_PAD'; //CKM_CAST128_CBC_PAD: Result := 'CKM_CAST128_CBC_PAD'; CKM_RC5_KEY_GEN: Result := 'CKM_RC5_KEY_GEN'; CKM_RC5_ECB: Result := 'CKM_RC5_ECB'; CKM_RC5_CBC: Result := 'CKM_RC5_CBC'; CKM_RC5_MAC: Result := 'CKM_RC5_MAC'; CKM_RC5_MAC_GENERAL: Result := 'CKM_RC5_MAC_GENERAL'; CKM_RC5_CBC_PAD: Result := 'CKM_RC5_CBC_PAD'; CKM_IDEA_KEY_GEN: Result := 'CKM_IDEA_KEY_GEN'; CKM_IDEA_ECB: Result := 'CKM_IDEA_ECB'; CKM_IDEA_CBC: Result := 'CKM_IDEA_CBC'; CKM_IDEA_MAC: Result := 'CKM_IDEA_MAC'; CKM_IDEA_MAC_GENERAL: Result := 'CKM_IDEA_MAC_GENERAL'; CKM_IDEA_CBC_PAD: Result := 'CKM_IDEA_CBC_PAD'; CKM_GENERIC_SECRET_KEY_GEN: Result := 'CKM_GENERIC_SECRET_KEY_GEN'; CKM_CONCATENATE_BASE_AND_KEY: Result := 'CKM_CONCATENATE_BASE_AND_KEY'; CKM_CONCATENATE_BASE_AND_DATA: Result := 'CKM_CONCATENATE_BASE_AND_DATA'; CKM_CONCATENATE_DATA_AND_BASE: Result := 'CKM_CONCATENATE_DATA_AND_BASE'; CKM_XOR_BASE_AND_DATA: Result := 'CKM_XOR_BASE_AND_DATA'; CKM_EXTRACT_KEY_FROM_KEY: Result := 'CKM_EXTRACT_KEY_FROM_KEY'; CKM_SSL3_PRE_MASTER_KEY_GEN: Result := 'CKM_SSL3_PRE_MASTER_KEY_GEN'; CKM_SSL3_MASTER_KEY_DERIVE: Result := 'CKM_SSL3_MASTER_KEY_DERIVE'; CKM_SSL3_KEY_AND_MAC_DERIVE: Result := 'CKM_SSL3_KEY_AND_MAC_DERIVE'; CKM_SSL3_MASTER_KEY_DERIVE_DH: Result := 'CKM_SSL3_MASTER_KEY_DERIVE_DH'; CKM_TLS_PRE_MASTER_KEY_GEN: Result := 'CKM_TLS_PRE_MASTER_KEY_GEN'; CKM_TLS_MASTER_KEY_DERIVE: Result := 'CKM_TLS_MASTER_KEY_DERIVE'; CKM_TLS_KEY_AND_MAC_DERIVE: Result := 'CKM_TLS_KEY_AND_MAC_DERIVE'; CKM_TLS_MASTER_KEY_DERIVE_DH: Result := 'CKM_TLS_MASTER_KEY_DERIVE_DH'; CKM_TLS_PRF: Result := 'CKM_TLS_PRF'; CKM_SSL3_MD5_MAC: Result := 'CKM_SSL3_MD5_MAC'; CKM_SSL3_SHA1_MAC: Result := 'CKM_SSL3_SHA1_MAC'; CKM_MD5_KEY_DERIVATION: Result := 'CKM_MD5_KEY_DERIVATION'; CKM_MD2_KEY_DERIVATION: Result := 'CKM_MD2_KEY_DERIVATION'; CKM_SHA1_KEY_DERIVATION: Result := 'CKM_SHA1_KEY_DERIVATION'; CKM_SHA256_KEY_DERIVATION: Result := 'CKM_SHA256_KEY_DERIVATION'; CKM_SHA384_KEY_DERIVATION: Result := 'CKM_SHA384_KEY_DERIVATION'; CKM_SHA512_KEY_DERIVATION: Result := 'CKM_SHA512_KEY_DERIVATION'; CKM_SHA224_KEY_DERIVATION: Result := 'CKM_SHA224_KEY_DERIVATION'; CKM_PBE_MD2_DES_CBC: Result := 'CKM_PBE_MD2_DES_CBC'; CKM_PBE_MD5_DES_CBC: Result := 'CKM_PBE_MD5_DES_CBC'; CKM_PBE_MD5_CAST_CBC: Result := 'CKM_PBE_MD5_CAST_CBC'; CKM_PBE_MD5_CAST3_CBC: Result := 'CKM_PBE_MD5_CAST3_CBC'; CKM_PBE_MD5_CAST5_CBC: Result := 'CKM_PBE_MD5_CAST5_CBC'; //CKM_PBE_MD5_CAST128_CBC: Result := 'CKM_PBE_MD5_CAST128_CBC'; CKM_PBE_SHA1_CAST5_CBC: Result := 'CKM_PBE_SHA1_CAST5_CBC'; //CKM_PBE_SHA1_CAST128_CBC: Result := 'CKM_PBE_SHA1_CAST128_CBC'; CKM_PBE_SHA1_RC4_128: Result := 'CKM_PBE_SHA1_RC4_128'; CKM_PBE_SHA1_RC4_40: Result := 'CKM_PBE_SHA1_RC4_40'; CKM_PBE_SHA1_DES3_EDE_CBC: Result := 'CKM_PBE_SHA1_DES3_EDE_CBC'; CKM_PBE_SHA1_DES2_EDE_CBC: Result := 'CKM_PBE_SHA1_DES2_EDE_CBC'; CKM_PBE_SHA1_RC2_128_CBC: Result := 'CKM_PBE_SHA1_RC2_128_CBC'; CKM_PBE_SHA1_RC2_40_CBC: Result := 'CKM_PBE_SHA1_RC2_40_CBC'; CKM_PKCS5_PBKD2: Result := 'CKM_PKCS5_PBKD2'; CKM_PBA_SHA1_WITH_SHA1_HMAC: Result := 'CKM_PBA_SHA1_WITH_SHA1_HMAC'; CKM_WTLS_PRE_MASTER_KEY_GEN: Result := 'CKM_WTLS_PRE_MASTER_KEY_GEN'; CKM_WTLS_MASTER_KEY_DERIVE: Result := 'CKM_WTLS_MASTER_KEY_DERIVE'; CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: Result := 'CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC'; CKM_WTLS_PRF: Result := 'CKM_WTLS_PRF'; CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: Result := 'CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE'; CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: Result := 'CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE'; CKM_KEY_WRAP_LYNKS: Result := 'CKM_KEY_WRAP_LYNKS'; CKM_KEY_WRAP_SET_OAEP: Result := 'CKM_KEY_WRAP_SET_OAEP'; CKM_CMS_SIG: Result := 'CKM_CMS_SIG'; CKM_KIP_DERIVE: Result := 'CKM_KIP_DERIVE'; CKM_KIP_WRAP: Result := 'CKM_KIP_WRAP'; CKM_KIP_MAC: Result := 'CKM_KIP_MAC'; CKM_CAMELLIA_KEY_GEN: Result := 'CKM_CAMELLIA_KEY_GEN'; CKM_CAMELLIA_ECB: Result := 'CKM_CAMELLIA_ECB'; CKM_CAMELLIA_CBC: Result := 'CKM_CAMELLIA_CBC'; CKM_CAMELLIA_MAC: Result := 'CKM_CAMELLIA_MAC'; CKM_CAMELLIA_MAC_GENERAL: Result := 'CKM_CAMELLIA_MAC_GENERAL'; CKM_CAMELLIA_CBC_PAD: Result := 'CKM_CAMELLIA_CBC_PAD'; CKM_CAMELLIA_ECB_ENCRYPT_DATA: Result := 'CKM_CAMELLIA_ECB_ENCRYPT_DATA'; CKM_CAMELLIA_CBC_ENCRYPT_DATA: Result := 'CKM_CAMELLIA_CBC_ENCRYPT_DATA'; CKM_CAMELLIA_CTR: Result := 'CKM_CAMELLIA_CTR'; CKM_ARIA_KEY_GEN: Result := 'CKM_ARIA_KEY_GEN'; CKM_ARIA_ECB: Result := 'CKM_ARIA_ECB'; CKM_ARIA_CBC: Result := 'CKM_ARIA_CBC'; CKM_ARIA_MAC: Result := 'CKM_ARIA_MAC'; CKM_ARIA_MAC_GENERAL: Result := 'CKM_ARIA_MAC_GENERAL'; CKM_ARIA_CBC_PAD: Result := 'CKM_ARIA_CBC_PAD'; CKM_ARIA_ECB_ENCRYPT_DATA: Result := 'CKM_ARIA_ECB_ENCRYPT_DATA'; CKM_ARIA_CBC_ENCRYPT_DATA: Result := 'CKM_ARIA_CBC_ENCRYPT_DATA'; CKM_SKIPJACK_KEY_GEN: Result := 'CKM_SKIPJACK_KEY_GEN'; CKM_SKIPJACK_ECB64: Result := 'CKM_SKIPJACK_ECB64'; CKM_SKIPJACK_CBC64: Result := 'CKM_SKIPJACK_CBC64'; CKM_SKIPJACK_OFB64: Result := 'CKM_SKIPJACK_OFB64'; CKM_SKIPJACK_CFB64: Result := 'CKM_SKIPJACK_CFB64'; CKM_SKIPJACK_CFB32: Result := 'CKM_SKIPJACK_CFB32'; CKM_SKIPJACK_CFB16: Result := 'CKM_SKIPJACK_CFB16'; CKM_SKIPJACK_CFB8: Result := 'CKM_SKIPJACK_CFB8'; CKM_SKIPJACK_WRAP: Result := 'CKM_SKIPJACK_WRAP'; CKM_SKIPJACK_PRIVATE_WRAP: Result := 'CKM_SKIPJACK_PRIVATE_WRAP'; CKM_SKIPJACK_RELAYX: Result := 'CKM_SKIPJACK_RELAYX'; CKM_KEA_KEY_PAIR_GEN: Result := 'CKM_KEA_KEY_PAIR_GEN'; CKM_KEA_KEY_DERIVE: Result := 'CKM_KEA_KEY_DERIVE'; CKM_FORTEZZA_TIMESTAMP: Result := 'CKM_FORTEZZA_TIMESTAMP'; CKM_BATON_KEY_GEN: Result := 'CKM_BATON_KEY_GEN'; CKM_BATON_ECB128: Result := 'CKM_BATON_ECB128'; CKM_BATON_ECB96: Result := 'CKM_BATON_ECB96'; CKM_BATON_CBC128: Result := 'CKM_BATON_CBC128'; CKM_BATON_COUNTER: Result := 'CKM_BATON_COUNTER'; CKM_BATON_SHUFFLE: Result := 'CKM_BATON_SHUFFLE'; CKM_BATON_WRAP: Result := 'CKM_BATON_WRAP'; CKM_ECDSA_KEY_PAIR_GEN: Result := 'CKM_ECDSA_KEY_PAIR_GEN'; //CKM_EC_KEY_PAIR_GEN: Result := 'CKM_EC_KEY_PAIR_GEN'; CKM_ECDSA: Result := 'CKM_ECDSA'; CKM_ECDSA_SHA1: Result := 'CKM_ECDSA_SHA1'; CKM_ECDH1_DERIVE: Result := 'CKM_ECDH1_DERIVE'; CKM_ECDH1_COFACTOR_DERIVE: Result := 'CKM_ECDH1_COFACTOR_DERIVE'; CKM_ECMQV_DERIVE: Result := 'CKM_ECMQV_DERIVE'; CKM_JUNIPER_KEY_GEN: Result := 'CKM_JUNIPER_KEY_GEN'; CKM_JUNIPER_ECB128: Result := 'CKM_JUNIPER_ECB128'; CKM_JUNIPER_CBC128: Result := 'CKM_JUNIPER_CBC128'; CKM_JUNIPER_COUNTER: Result := 'CKM_JUNIPER_COUNTER'; CKM_JUNIPER_SHUFFLE: Result := 'CKM_JUNIPER_SHUFFLE'; CKM_JUNIPER_WRAP: Result := 'CKM_JUNIPER_WRAP'; CKM_FASTHASH: Result := 'CKM_FASTHASH'; CKM_AES_KEY_GEN: Result := 'CKM_AES_KEY_GEN'; CKM_AES_ECB: Result := 'CKM_AES_ECB'; CKM_AES_CBC: Result := 'CKM_AES_CBC'; CKM_AES_MAC: Result := 'CKM_AES_MAC'; CKM_AES_MAC_GENERAL: Result := 'CKM_AES_MAC_GENERAL'; CKM_AES_CBC_PAD: Result := 'CKM_AES_CBC_PAD'; CKM_AES_CTR: Result := 'CKM_AES_CTR'; CKM_BLOWFISH_KEY_GEN: Result := 'CKM_BLOWFISH_KEY_GEN'; CKM_BLOWFISH_CBC: Result := 'CKM_BLOWFISH_CBC'; CKM_TWOFISH_KEY_GEN: Result := 'CKM_TWOFISH_KEY_GEN'; CKM_TWOFISH_CBC: Result := 'CKM_TWOFISH_CBC'; CKM_DES_ECB_ENCRYPT_DATA: Result := 'CKM_DES_ECB_ENCRYPT_DATA'; CKM_DES_CBC_ENCRYPT_DATA: Result := 'CKM_DES_CBC_ENCRYPT_DATA'; CKM_DES3_ECB_ENCRYPT_DATA: Result := 'CKM_DES3_ECB_ENCRYPT_DATA'; CKM_DES3_CBC_ENCRYPT_DATA: Result := 'CKM_DES3_CBC_ENCRYPT_DATA'; CKM_AES_ECB_ENCRYPT_DATA: Result := 'CKM_AES_ECB_ENCRYPT_DATA'; CKM_AES_CBC_ENCRYPT_DATA: Result := 'CKM_AES_CBC_ENCRYPT_DATA'; CKM_DSA_PARAMETER_GEN: Result := 'CKM_DSA_PARAMETER_GEN'; CKM_DH_PKCS_PARAMETER_GEN: Result := 'CKM_DH_PKCS_PARAMETER_GEN'; CKM_X9_42_DH_PARAMETER_GEN: Result := 'CKM_X9_42_DH_PARAMETER_GEN'; CKM_VENDOR_DEFINED: Result := 'CKM_VENDOR_DEFINED'; end; end; function TPKCS11Mechanism.KeysizeUnits(mechanism: CK_MECHANISM_TYPE): TPKCS11KeysizeUnits; begin Result := ksmNA; case mechanism of CKM_RSA_PKCS_KEY_PAIR_GEN: Result := ksmBits; CKM_RSA_PKCS: Result := ksmBits; CKM_RSA_9796: Result := ksmBits; CKM_RSA_X_509: Result := ksmBits; CKM_MD2_RSA_PKCS: Result := ksmBits; CKM_MD5_RSA_PKCS: Result := ksmBits; CKM_SHA1_RSA_PKCS: Result := ksmBits; CKM_RIPEMD128_RSA_PKCS: Result := ksmBits; CKM_RIPEMD160_RSA_PKCS: Result := ksmBits; CKM_RSA_PKCS_OAEP: Result := ksmBits; CKM_RSA_X9_31_KEY_PAIR_GEN: Result := ksmBits; CKM_RSA_X9_31: Result := ksmBits; CKM_SHA1_RSA_X9_31: Result := ksmBits; CKM_RSA_PKCS_PSS: Result := ksmBits; CKM_SHA1_RSA_PKCS_PSS: Result := ksmBits; CKM_DSA_KEY_PAIR_GEN: Result := ksmBits; CKM_DSA: Result := ksmBits; CKM_DSA_SHA1: Result := ksmBits; CKM_DH_PKCS_KEY_PAIR_GEN: Result := ksmBits; CKM_DH_PKCS_DERIVE: Result := ksmBits; CKM_X9_42_DH_KEY_PAIR_GEN: Result := ksmBits; CKM_X9_42_DH_DERIVE: Result := ksmBits; CKM_X9_42_DH_HYBRID_DERIVE: Result := ksmBits; CKM_X9_42_MQV_DERIVE: Result := ksmBits; CKM_SHA256_RSA_PKCS: Result := ksmBits; CKM_SHA384_RSA_PKCS: Result := ksmBits; CKM_SHA512_RSA_PKCS: Result := ksmBits; CKM_SHA256_RSA_PKCS_PSS: Result := ksmBits; CKM_SHA384_RSA_PKCS_PSS: Result := ksmBits; CKM_SHA512_RSA_PKCS_PSS: Result := ksmBits; CKM_SHA224_RSA_PKCS: Result := ksmBits; CKM_SHA224_RSA_PKCS_PSS: Result := ksmBits; CKM_RC2_KEY_GEN: Result := ksmBits; CKM_RC2_ECB: Result := ksmBits; CKM_RC2_CBC: Result := ksmBits; CKM_RC2_MAC: Result := ksmBits; CKM_RC2_MAC_GENERAL: Result := ksmBits; CKM_RC2_CBC_PAD: Result := ksmBits; CKM_RC4_KEY_GEN: Result := ksmBits; CKM_RC4: Result := ksmBits; CKM_DES_KEY_GEN: Result := ksmNA; CKM_DES_ECB: Result := ksmNA; CKM_DES_CBC: Result := ksmNA; CKM_DES_MAC: Result := ksmNA; CKM_DES_MAC_GENERAL: Result := ksmNA; CKM_DES_CBC_PAD: Result := ksmNA; CKM_DES2_KEY_GEN: Result := ksmNA; CKM_DES3_KEY_GEN: Result := ksmNA; CKM_DES3_ECB: Result := ksmNA; CKM_DES3_CBC: Result := ksmNA; CKM_DES3_MAC: Result := ksmNA; CKM_DES3_MAC_GENERAL: Result := ksmNA; CKM_DES3_CBC_PAD: Result := ksmNA; CKM_CDMF_KEY_GEN: Result := ksmNA; CKM_CDMF_ECB: Result := ksmNA; CKM_CDMF_CBC: Result := ksmNA; CKM_CDMF_MAC: Result := ksmNA; CKM_CDMF_MAC_GENERAL: Result := ksmNA; CKM_CDMF_CBC_PAD: Result := ksmNA; CKM_DES_OFB64: Result := ksmNA; CKM_DES_OFB8: Result := ksmNA; CKM_DES_CFB64: Result := ksmNA; CKM_DES_CFB8: Result := ksmNA; CKM_MD2: Result := ksmNA; // Not documented in spec CKM_MD2_HMAC: Result := ksmNA; // Not documented in spec CKM_MD2_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_MD5: Result := ksmNA; // Not documented in spec CKM_MD5_HMAC: Result := ksmNA; // Not documented in spec CKM_MD5_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SHA_1: Result := ksmNA; // Not documented in spec CKM_SHA_1_HMAC: Result := ksmNA; // Not documented in spec CKM_SHA_1_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_RIPEMD128: Result := ksmNA; // Not documented in spec CKM_RIPEMD128_HMAC: Result := ksmNA; // Not documented in spec CKM_RIPEMD128_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_RIPEMD160: Result := ksmNA; // Not documented in spec CKM_RIPEMD160_HMAC: Result := ksmNA; // Not documented in spec CKM_RIPEMD160_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SHA256: Result := ksmNA; // Not documented in spec CKM_SHA256_HMAC: Result := ksmNA; // Not documented in spec CKM_SHA256_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SHA224: Result := ksmNA; // Not documented in spec CKM_SHA224_HMAC: Result := ksmNA; // Not documented in spec CKM_SHA224_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SHA384: Result := ksmNA; // Not documented in spec CKM_SHA384_HMAC: Result := ksmNA; // Not documented in spec CKM_SHA384_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SHA512: Result := ksmNA; // Not documented in spec CKM_SHA512_HMAC: Result := ksmNA; // Not documented in spec CKM_SHA512_HMAC_GENERAL: Result := ksmNA; // Not documented in spec CKM_SECURID_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_SECURID: Result := ksmNA; // Not documented in spec CKM_HOTP_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_HOTP: Result := ksmNA; // Not documented in spec CKM_ACTI: Result := ksmNA; // Not documented in spec CKM_ACTI_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_CAST_KEY_GEN: Result := ksmBytes; CKM_CAST_ECB: Result := ksmBytes; CKM_CAST_CBC: Result := ksmBytes; CKM_CAST_MAC: Result := ksmBytes; CKM_CAST_MAC_GENERAL: Result := ksmBytes; CKM_CAST_CBC_PAD: Result := ksmBytes; CKM_CAST3_KEY_GEN: Result := ksmBytes; CKM_CAST3_ECB: Result := ksmBytes; CKM_CAST3_CBC: Result := ksmBytes; CKM_CAST3_MAC: Result := ksmBytes; CKM_CAST3_MAC_GENERAL: Result := ksmBytes; CKM_CAST3_CBC_PAD: Result := ksmBytes; CKM_CAST5_KEY_GEN: Result := ksmBytes; //CKM_CAST128_KEY_GEN: Result := ksmBytes; CKM_CAST5_ECB: Result := ksmBytes; //CKM_CAST128_ECB: Result := ksmBytes; CKM_CAST5_CBC: Result := ksmBytes; //CKM_CAST128_CBC: Result := ksmBytes; CKM_CAST5_MAC: Result := ksmBytes; //CKM_CAST128_MAC: Result := ksmBytes; CKM_CAST5_MAC_GENERAL: Result := ksmBytes; //CKM_CAST128_MAC_GENERAL: Result := ksmBytes; CKM_CAST5_CBC_PAD: Result := ksmBytes; //CKM_CAST128_CBC_PAD: Result := ksmBytes; CKM_RC5_KEY_GEN: Result := ksmBits; CKM_RC5_ECB: Result := ksmBits; CKM_RC5_CBC: Result := ksmBits; CKM_RC5_MAC: Result := ksmBits; CKM_RC5_MAC_GENERAL: Result := ksmBits; CKM_RC5_CBC_PAD: Result := ksmBits; CKM_IDEA_KEY_GEN: Result := ksmNA; CKM_IDEA_ECB: Result := ksmNA; CKM_IDEA_CBC: Result := ksmNA; CKM_IDEA_MAC: Result := ksmNA; CKM_IDEA_MAC_GENERAL: Result := ksmNA; CKM_IDEA_CBC_PAD: Result := ksmNA; CKM_GENERIC_SECRET_KEY_GEN: Result := ksmBits; CKM_CONCATENATE_BASE_AND_KEY: Result := ksmNA; // Not documented in spec CKM_CONCATENATE_BASE_AND_DATA: Result := ksmNA; // Not documented in spec CKM_CONCATENATE_DATA_AND_BASE: Result := ksmNA; // Not documented in spec CKM_XOR_BASE_AND_DATA: Result := ksmNA; // Not documented in spec CKM_EXTRACT_KEY_FROM_KEY: Result := ksmNA; // Not documented in spec CKM_SSL3_PRE_MASTER_KEY_GEN: Result := ksmBytes; CKM_SSL3_MASTER_KEY_DERIVE: Result := ksmBytes; CKM_SSL3_KEY_AND_MAC_DERIVE: Result := ksmNA; // Not documented in spec CKM_SSL3_MASTER_KEY_DERIVE_DH: Result := ksmBytes; CKM_TLS_PRE_MASTER_KEY_GEN: Result := ksmBytes; CKM_TLS_MASTER_KEY_DERIVE: Result := ksmBytes; CKM_TLS_KEY_AND_MAC_DERIVE: Result := ksmNA; // Not documented in spec CKM_TLS_MASTER_KEY_DERIVE_DH: Result := ksmBytes; CKM_TLS_PRF: Result := ksmNA; // Not documented in spec CKM_SSL3_MD5_MAC: Result := ksmBits; CKM_SSL3_SHA1_MAC: Result := ksmBits; CKM_MD5_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_MD2_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_SHA1_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_SHA256_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_SHA384_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_SHA512_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_SHA224_KEY_DERIVATION: Result := ksmNA; // Not documented in spec CKM_PBE_MD2_DES_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_MD5_DES_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_MD5_CAST_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_MD5_CAST3_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_MD5_CAST5_CBC: Result := ksmNA; // Not documented in spec //CKM_PBE_MD5_CAST128_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_CAST5_CBC: Result := ksmNA; // Not documented in spec //CKM_PBE_SHA1_CAST128_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_RC4_128: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_RC4_40: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_DES3_EDE_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_DES2_EDE_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_RC2_128_CBC: Result := ksmNA; // Not documented in spec CKM_PBE_SHA1_RC2_40_CBC: Result := ksmNA; // Not documented in spec CKM_PKCS5_PBKD2: Result := ksmNA; // Not documented in spec CKM_PBA_SHA1_WITH_SHA1_HMAC: Result := ksmNA; // Not documented in spec CKM_WTLS_PRE_MASTER_KEY_GEN: Result := ksmBytes; CKM_WTLS_MASTER_KEY_DERIVE: Result := ksmBytes; CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: Result := ksmBytes; CKM_WTLS_PRF: Result := ksmNA; // Not documented in spec CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: Result := ksmNA; // Not documented in spec CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: Result := ksmNA; // Not documented in spec CKM_KEY_WRAP_LYNKS: Result := ksmNA; // Not documented in spec CKM_KEY_WRAP_SET_OAEP: Result := ksmNA; // Not documented in spec CKM_CMS_SIG: Result := ksmNA; // Not documented in spec CKM_KIP_DERIVE: Result := ksmNA; // Not documented in spec CKM_KIP_WRAP: Result := ksmNA; // Not documented in spec CKM_KIP_MAC: Result := ksmNA; // Not documented in spec CKM_CAMELLIA_KEY_GEN: Result := ksmBytes; CKM_CAMELLIA_ECB: Result := ksmBytes; CKM_CAMELLIA_CBC: Result := ksmBytes; CKM_CAMELLIA_MAC: Result := ksmBytes; CKM_CAMELLIA_MAC_GENERAL: Result := ksmBytes; CKM_CAMELLIA_CBC_PAD: Result := ksmBytes; CKM_CAMELLIA_ECB_ENCRYPT_DATA: Result := ksmBytes; CKM_CAMELLIA_CBC_ENCRYPT_DATA: Result := ksmBytes; CKM_CAMELLIA_CTR: Result := ksmBytes; CKM_ARIA_KEY_GEN: Result := ksmBytes; CKM_ARIA_ECB: Result := ksmBytes; CKM_ARIA_CBC: Result := ksmBytes; CKM_ARIA_MAC: Result := ksmBytes; CKM_ARIA_MAC_GENERAL: Result := ksmBytes; CKM_ARIA_CBC_PAD: Result := ksmBytes; CKM_ARIA_ECB_ENCRYPT_DATA: Result := ksmBytes; CKM_ARIA_CBC_ENCRYPT_DATA: Result := ksmBytes; CKM_SKIPJACK_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_ECB64: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_CBC64: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_OFB64: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_CFB64: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_CFB32: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_CFB16: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_CFB8: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_WRAP: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_PRIVATE_WRAP: Result := ksmNA; // Not documented in spec CKM_SKIPJACK_RELAYX: Result := ksmNA; // Not documented in spec CKM_KEA_KEY_PAIR_GEN: Result := ksmBits; CKM_KEA_KEY_DERIVE: Result := ksmBits; CKM_FORTEZZA_TIMESTAMP: Result := ksmBits; CKM_BATON_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_BATON_ECB128: Result := ksmNA; // Not documented in spec CKM_BATON_ECB96: Result := ksmNA; // Not documented in spec CKM_BATON_CBC128: Result := ksmNA; // Not documented in spec CKM_BATON_COUNTER: Result := ksmNA; // Not documented in spec CKM_BATON_SHUFFLE: Result := ksmNA; // Not documented in spec CKM_BATON_WRAP: Result := ksmNA; // Not documented in spec CKM_ECDSA_KEY_PAIR_GEN: Result := ksmBits; //CKM_EC_KEY_PAIR_GEN: Result := ksmBits; CKM_ECDSA: Result := ksmBits; CKM_ECDSA_SHA1: Result := ksmBits; CKM_ECDH1_DERIVE: Result := ksmBits; CKM_ECDH1_COFACTOR_DERIVE: Result := ksmBits; CKM_ECMQV_DERIVE: Result := ksmBits; CKM_JUNIPER_KEY_GEN: Result := ksmNA; // Not documented in spec CKM_JUNIPER_ECB128: Result := ksmNA; // Not documented in spec CKM_JUNIPER_CBC128: Result := ksmNA; // Not documented in spec CKM_JUNIPER_COUNTER: Result := ksmNA; // Not documented in spec CKM_JUNIPER_SHUFFLE: Result := ksmNA; // Not documented in spec CKM_JUNIPER_WRAP: Result := ksmNA; // Not documented in spec CKM_FASTHASH: Result := ksmNA; // Not documented in spec CKM_AES_KEY_GEN: Result := ksmBytes; CKM_AES_ECB: Result := ksmBytes; CKM_AES_CBC: Result := ksmBytes; CKM_AES_MAC: Result := ksmBytes; CKM_AES_MAC_GENERAL: Result := ksmBytes; CKM_AES_CBC_PAD: Result := ksmBytes; CKM_AES_CTR: Result := ksmBytes; CKM_BLOWFISH_KEY_GEN: Result := ksmBytes; CKM_BLOWFISH_CBC: Result := ksmBytes; CKM_TWOFISH_KEY_GEN: Result := ksmBytes; // Not documented in spec; assumption based on what Blowfish does CKM_TWOFISH_CBC: Result := ksmBytes; // Not documented in spec; assumption based on what Blowfish does CKM_DES_ECB_ENCRYPT_DATA: Result := ksmNA; // Not documented in spec CKM_DES_CBC_ENCRYPT_DATA: Result := ksmNA; // Not documented in spec CKM_DES3_ECB_ENCRYPT_DATA: Result := ksmNA; // Not documented in spec CKM_DES3_CBC_ENCRYPT_DATA: Result := ksmNA; // Not documented in spec CKM_AES_ECB_ENCRYPT_DATA: Result := ksmBytes; CKM_AES_CBC_ENCRYPT_DATA: Result := ksmBytes; CKM_DSA_PARAMETER_GEN: Result := ksmBits; CKM_DH_PKCS_PARAMETER_GEN: Result := ksmBits; CKM_X9_42_DH_PARAMETER_GEN: Result := ksmBits; CKM_VENDOR_DEFINED: Result := ksmNA; // Vendor specific end; end; end.
{ * zExpression * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit zExpression; {$INCLUDE zDefine.inc} interface uses SysUtils, Variants, CoreClasses, TypInfo, TextParsing, PascalStrings, UnicodeMixedLib, DoStatusIO, ListEngine, OpCode; type {$REGION 'internal define'} TSymbolOperation = (soAdd, soSub, soMul, soDiv, soMod, soIntDiv, soPow, soOr, soAnd, soXor, // math soEqual, soLessThan, soEqualOrLessThan, soGreaterThan, soEqualOrGreaterThan, soNotEqual, // logic soShl, soShr, // bit soBlockIndentBegin, soBlockIndentEnd, // block indent soPropIndentBegin, soPropIndentEnd, // property indent soDotSymbol, soCommaSymbol, // dot and comma soEolSymbol, // eol soProc, soParameter, // proc soUnknow); TSymbolOperations = set of TSymbolOperation; TExpressionDeclType = ( edtSymbol, // symbol edtBool, edtInt, edtInt64, edtUInt64, edtWord, edtByte, edtSmallInt, edtShortInt, edtUInt, // inbuild byte type edtSingle, edtDouble, edtCurrency, // inbuild float type edtString, // string edtProcExp, // proc edtExpressionAsValue, // expression edtUnknow); TExpressionDeclTypes = set of TExpressionDeclType; TSymbolExpression = class; TExpressionListData = record DeclType: TExpressionDeclType; // declaration charPos: Integer; // char pos Symbol: TSymbolOperation; // symbol Value: Variant; // value Expression: TSymbolExpression; // expression ExpressionAutoFree: Boolean; // autofree end; PExpressionListData = ^TExpressionListData; TNumTextType = (nttBool, nttInt, nttInt64, nttUInt64, nttWord, nttByte, nttSmallInt, nttShortInt, nttUInt, nttSingle, nttDouble, nttCurrency, nttUnknow); TSymbolExpression = class sealed(TCoreClassObject) protected FList: TCoreClassList; FTextStyle: TTextStyle; public constructor Create(const TextStyle_: TTextStyle); destructor Destroy; override; property TextStyle: TTextStyle read FTextStyle; procedure Clear; procedure PrintDebug(const detail: Boolean; const prefix: SystemString); overload; procedure PrintDebug(const detail: Boolean); overload; function Decl(): SystemString; function GetCount(t: TExpressionDeclTypes): Integer; function GetSymbolCount(Operations: TSymbolOperations): Integer; function AvailValueCount: Integer; function Count: Integer; function InsertSymbol(const idx: Integer; v: TSymbolOperation; charPos: Integer): PExpressionListData; function Insert(const idx: Integer; v: TExpressionListData): PExpressionListData; procedure InsertExpression(const idx: Integer; E: TSymbolExpression); procedure AddExpression(const E: TSymbolExpression); function AddSymbol(const v: TSymbolOperation; charPos: Integer): PExpressionListData; function AddBool(const v: Boolean; charPos: Integer): PExpressionListData; function AddInt(const v: Integer; charPos: Integer): PExpressionListData; function AddUInt(const v: Cardinal; charPos: Integer): PExpressionListData; function AddInt64(const v: Int64; charPos: Integer): PExpressionListData; function AddUInt64(const v: UInt64; charPos: Integer): PExpressionListData; function AddWord(const v: Word; charPos: Integer): PExpressionListData; function AddByte(const v: Byte; charPos: Integer): PExpressionListData; function AddSmallInt(const v: SmallInt; charPos: Integer): PExpressionListData; function AddShortInt(const v: ShortInt; charPos: Integer): PExpressionListData; function AddSingle(const v: Single; charPos: Integer): PExpressionListData; function AddDouble(const v: Double; charPos: Integer): PExpressionListData; function AddCurrency(const v: Currency; charPos: Integer): PExpressionListData; function AddString(const v: SystemString; charPos: Integer): PExpressionListData; function AddFunc(const v: SystemString; charPos: Integer): PExpressionListData; function AddExpressionAsValue(AutoFree: Boolean; Expression: TSymbolExpression; Symbol: TSymbolOperation; Value: Variant; charPos: Integer): PExpressionListData; function Add(const v: TExpressionListData): PExpressionListData; function AddCopy(const v: TExpressionListData): PExpressionListData; procedure Delete(const idx: Integer); procedure DeleteLast; function Last: PExpressionListData; function First: PExpressionListData; function IndexOf(p: PExpressionListData): Integer; function GetItems(index: Integer): PExpressionListData; property Items[index: Integer]: PExpressionListData read GetItems; default; end; TOnDeclValueCall = procedure(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant); TOnDeclValueMethod = procedure(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant) of object; {$IFDEF FPC} TOnDeclValueProc = procedure(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant) is nested; {$ELSE FPC} TOnDeclValueProc = reference to procedure(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant); {$ENDIF FPC} // { text parse support } TExpressionParsingState = set of (esFirst, esWaitOp, esWaitIndentEnd, esWaitPropParamIndentEnd, esWaitValue); PExpressionParsingState = ^TExpressionParsingState; { variant array vector } TExpressionValueVector = array of Variant; PExpressionValueVector = ^TExpressionValueVector; { aligned variant matrix } TExpressionValueMatrix = array of TExpressionValueVector; PExpressionValueMatrix = ^TExpressionValueMatrix; // other function NumTextType(s: TPascalString): TNumTextType; procedure InitExp(var v: TExpressionListData); function dt2op(const v: TExpressionDeclType): TOpValueType; function VariantToExpressionDeclType(var v: Variant): TExpressionDeclType; function ParseOperationState(ParsingEng: TTextParsing; var cPos, bPos, ePos, BlockIndent, PropIndent: Integer; var pStates: TExpressionParsingState): TSymbolOperation; function ParseSymbol(ParsingEng: TTextParsing; WorkSym: TSymbolExpression; var cPos, bPos, ePos, BlockIndent, PropIndent: Integer; pStates: PExpressionParsingState): Boolean; function __ParseTextExpressionAsSymbol(ParsingEng: TTextParsing; const uName: SystemString; const OnDeclValueCall: TOnDeclValueCall; const OnDeclValueMethod: TOnDeclValueMethod; const OnDeclValueProc: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; // parsing text as expression structor, backcall is TOnDeclValueCall function ParseTextExpressionAsSymbol_C(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor, backcall is TOnDeclValueMethod function ParseTextExpressionAsSymbol_M(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor, backcall is TOnDeclValueProc function ParseTextExpressionAsSymbol_P(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol(TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; function ParseTextExpressionAsSymbol(ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): TSymbolExpression; overload; function ParseTextExpressionAsSymbol(ExpressionText: SystemString): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_M(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_M(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_C(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_C(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_P(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // parsing text as expression structor function ParseTextExpressionAsSymbol_P(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; overload; // symbol priority function RebuildLogicalPrioritySymbol(Exps: TSymbolExpression): TSymbolExpression; // format symbol function RebuildAllSymbol(Exps: TSymbolExpression): TSymbolExpression; // build opCode function BuildAsOpCode(DebugMode: Boolean; SymbExps: TSymbolExpression; const uName: SystemString; LineNo: Integer): TOpCode; overload; function BuildAsOpCode(SymbExps: TSymbolExpression): TOpCode; overload; function BuildAsOpCode(DebugMode: Boolean; SymbExps: TSymbolExpression): TOpCode; overload; function BuildAsOpCode(DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString): TOpCode; overload; function BuildAsOpCode(TextStyle: TTextStyle; ExpressionText: SystemString): TOpCode; overload; function BuildAsOpCode(ExpressionText: SystemString): TOpCode; overload; function BuildAsOpCode(DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; overload; function BuildAsOpCode(TextStyle: TTextStyle; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; overload; function BuildAsOpCode(ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; overload; // Evaluate Expression function EvaluateExpressionValue_M(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod): Variant; function EvaluateExpressionValue_C(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall): Variant; function EvaluateExpressionValue_P(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc): Variant; {$ENDREGION 'internal define'} function OpCache: THashObjectList; procedure CleanOpCache(); { prototype: EvaluateExpressionValue } function IsSymbolVectorExpression(ExpressionText: SystemString; TextStyle: TTextStyle; SpecialAsciiToken: TListPascalString): Boolean; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; // select used Cache function EvaluateExpressionValue(UsedCache: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; // used Cache function EvaluateExpressionValue(ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(TextStyle: TTextStyle; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): Variant; overload; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; overload; // Evaluate multi Expression as variant Vector function EvaluateExpressionVector(DebugMode, UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; overload; function EvaluateExpressionVector(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; overload; function EvaluateExpressionVector(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; overload; function EvaluateExpressionVector(ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; overload; function EvaluateExpressionVector(ExpressionText: SystemString; const_vl: THashVariantList): TExpressionValueVector; overload; function EvaluateExpressionVector(ExpressionText: SystemString; TextStyle: TTextStyle): TExpressionValueVector; overload; function EvaluateExpressionVector(ExpressionText: SystemString): TExpressionValueVector; overload; // Evaluate multi Expression as variant matrix function EvaluateExpressionMatrix(W, H: Integer; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueMatrix; overload; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueMatrix; overload; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; const_vl: THashVariantList): TExpressionValueMatrix; overload; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; TextStyle: TTextStyle): TExpressionValueMatrix; overload; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString): TExpressionValueMatrix; overload; // easy API function EStr(s: U_String): U_String; function EStrToInt(s: U_String; default: Integer): Integer; function EStrToInt64(s: U_String; default: Int64): Int64; function EStrToFloat(s: U_String; default: Double): Double; function EStrToSingle(s: U_String; default: Single): Single; function EStrToDouble(s: U_String; default: Double): Double; // print function ExpressionValueVectorToStr(v: TExpressionValueVector): TPascalString; procedure DoStatusE(v: TExpressionValueVector); overload; procedure DoStatusE(v: TExpressionValueMatrix); overload; // test procedure EvaluateExpressionVectorAndMatrix_test_; implementation var OpCache___: THashObjectList = nil; {$REGION 'internal imp'} type TSymbolOperationType = record State: TSymbolOperation; Decl: SystemString; end; const MethodToken: TExpressionDeclTypes = ([edtProcExp]); AllExpressionValueType: TExpressionDeclTypes = ([ edtBool, edtInt, edtInt64, edtUInt64, edtWord, edtByte, edtSmallInt, edtShortInt, edtUInt, edtSingle, edtDouble, edtCurrency, edtString, edtProcExp, edtExpressionAsValue]); SymbolOperationPriority: array [0 .. 4] of TSymbolOperations = ( ([soAnd]), ([soOr, soXor]), ([soEqual, soLessThan, soEqualOrLessThan, soGreaterThan, soEqualOrGreaterThan, soNotEqual]), ([soAdd, soSub]), ([soMul, soDiv, soMod, soIntDiv, soShl, soShr, soPow]) ); AllowPrioritySymbol: TSymbolOperations = ([ soAdd, soSub, soMul, soDiv, soMod, soIntDiv, soPow, soOr, soAnd, soXor, soEqual, soLessThan, soEqualOrLessThan, soGreaterThan, soEqualOrGreaterThan, soNotEqual, soShl, soShr, soDotSymbol, soCommaSymbol]); OpLogicalSymbol: TSymbolOperations = ([ soAdd, soSub, soMul, soDiv, soMod, soIntDiv, soPow, soOr, soAnd, soXor, soEqual, soLessThan, soEqualOrLessThan, soGreaterThan, soEqualOrGreaterThan, soNotEqual, soShl, soShr]); SymbolOperationTextDecl: array [TSymbolOperation] of TSymbolOperationType = ( (State: soAdd; Decl: '+'), (State: soSub; Decl: '-'), (State: soMul; Decl: '*'), (State: soDiv; Decl: '/'), (State: soMod; Decl: ' mod '), (State: soIntDiv; Decl: ' div '), (State: soPow; Decl: '^'), (State: soOr; Decl: ' or '), (State: soAnd; Decl: ' and '), (State: soXor; Decl: ' xor '), (State: soEqual; Decl: ' = '), (State: soLessThan; Decl: ' < '), (State: soEqualOrLessThan; Decl: ' <= '), (State: soGreaterThan; Decl: ' > '), (State: soEqualOrGreaterThan; Decl: ' => '), (State: soNotEqual; Decl: ' <> '), (State: soShl; Decl: ' shl '), (State: soShr; Decl: ' shr '), (State: soBlockIndentBegin; Decl: '('), (State: soBlockIndentEnd; Decl: ')'), (State: soPropIndentBegin; Decl: '['), (State: soPropIndentEnd; Decl: ']'), (State: soDotSymbol; Decl: '.'), (State: soCommaSymbol; Decl: ','), (State: soEolSymbol; Decl: ';'), (State: soProc; Decl: '|Proc|'), (State: soParameter; Decl: ','), (State: soUnknow; Decl: '?') ); function NumTextType(s: TPascalString): TNumTextType; type TValSym = (vsSymSub, vsSymAdd, vsSymAddSub, vsSymDollar, vsDot, vsDotBeforNum, vsDotAfterNum, vsNum, vsAtoF, vsE, vsUnknow); var cnt: array [TValSym] of Integer; v: TValSym; c: SystemChar; i: Integer; begin if s.Same('true') or s.Same('false') then Exit(nttBool); for v := low(TValSym) to high(TValSym) do cnt[v] := 0; for i := 1 to s.Len do begin c := s[i]; if CharIn(c, [c0to9]) then begin inc(cnt[vsNum]); if cnt[vsDot] > 0 then inc(cnt[vsDotAfterNum]); end else if CharIn(c, [cLoAtoF, cHiAtoF]) then begin inc(cnt[vsAtoF]); if CharIn(c, 'eE') then inc(cnt[vsE]); end else if c = '.' then begin inc(cnt[vsDot]); cnt[vsDotBeforNum] := cnt[vsNum]; end else if CharIn(c, '-') then begin inc(cnt[vsSymSub]); inc(cnt[vsSymAddSub]); end else if CharIn(c, '+') then begin inc(cnt[vsSymAdd]); inc(cnt[vsSymAddSub]); end else if CharIn(c, '$') and (i = 1) then begin inc(cnt[vsSymDollar]); if i <> 1 then Exit(nttUnknow); end else Exit(nttUnknow); end; if cnt[vsDot] > 1 then Exit(nttUnknow); if cnt[vsSymDollar] > 1 then Exit(nttUnknow); if (cnt[vsSymDollar] = 0) and (cnt[vsNum] = 0) then Exit(nttUnknow); if (cnt[vsSymAdd] > 1) and (cnt[vsE] = 0) and (cnt[vsSymDollar] = 0) then Exit(nttUnknow); if (cnt[vsSymDollar] = 0) and ((cnt[vsDot] = 1) or ((cnt[vsE] = 1) and ((cnt[vsSymAddSub] >= 1) and (cnt[vsSymDollar] = 0)))) then begin if cnt[vsSymDollar] > 0 then Exit(nttUnknow); if (cnt[vsAtoF] <> cnt[vsE]) then Exit(nttUnknow); if cnt[vsE] = 1 then begin Result := nttDouble end else if ((cnt[vsDotBeforNum] > 0)) and (cnt[vsDotAfterNum] > 0) then begin if cnt[vsDotAfterNum] < 5 then Result := nttCurrency else if cnt[vsNum] > 7 then Result := nttDouble else Result := nttSingle; end else Exit(nttUnknow); end else begin if cnt[vsSymDollar] = 1 then begin if cnt[vsSymSub] > 0 then begin if cnt[vsNum] + cnt[vsAtoF] = 0 then Result := nttUnknow else if cnt[vsNum] + cnt[vsAtoF] < 2 then Result := nttShortInt else if cnt[vsNum] + cnt[vsAtoF] < 4 then Result := nttSmallInt else if cnt[vsNum] + cnt[vsAtoF] < 7 then Result := nttInt else if cnt[vsNum] + cnt[vsAtoF] < 13 then Result := nttInt64 else Result := nttUnknow; end else begin if cnt[vsNum] + cnt[vsAtoF] = 0 then Result := nttUnknow else if cnt[vsNum] + cnt[vsAtoF] < 3 then Result := nttByte else if cnt[vsNum] + cnt[vsAtoF] < 5 then Result := nttWord else if cnt[vsNum] + cnt[vsAtoF] < 8 then Result := nttUInt else if cnt[vsNum] + cnt[vsAtoF] < 14 then Result := nttUInt64 else Result := nttUnknow; end; end else if cnt[vsAtoF] > 0 then Exit(nttUnknow) else if cnt[vsSymSub] > 0 then begin if cnt[vsNum] = 0 then Result := nttUnknow else if cnt[vsNum] < 3 then Result := nttShortInt else if cnt[vsNum] < 5 then Result := nttSmallInt else if cnt[vsNum] < 8 then Result := nttInt else if cnt[vsNum] < 15 then Result := nttInt64 else Result := nttUnknow; end else begin if cnt[vsNum] = 0 then Result := nttUnknow else if cnt[vsNum] < 3 then Result := nttByte else if cnt[vsNum] < 5 then Result := nttWord else if cnt[vsNum] < 8 then Result := nttUInt else if cnt[vsNum] < 16 then Result := nttUInt64 else Result := nttUnknow; end; end; end; procedure InitExp(var v: TExpressionListData); begin v.DeclType := edtUnknow; v.charPos := -1; v.Symbol := soUnknow; v.Value := NULL; v.Expression := nil; v.ExpressionAutoFree := False; end; function dt2op(const v: TExpressionDeclType): TOpValueType; begin case v of edtBool: Result := ovtBool; edtInt: Result := ovtInt; edtInt64: Result := ovtInt64; edtUInt64: Result := ovtUInt64; edtWord: Result := ovtWord; edtByte: Result := ovtByte; edtSmallInt: Result := ovtSmallInt; edtShortInt: Result := ovtShortInt; edtUInt: Result := ovtUInt; edtSingle: Result := ovtSingle; edtDouble: Result := ovtDouble; edtCurrency: Result := ovtCurrency; edtString: Result := ovtString; edtProcExp: Result := ovtProc; else Result := ovtUnknow; end; end; function VariantToExpressionDeclType(var v: Variant): TExpressionDeclType; begin case VarType(v) of varSmallInt: Result := edtSmallInt; varInteger: Result := edtInt; varSingle: Result := edtSingle; varDouble: Result := edtDouble; varCurrency: Result := edtCurrency; varBoolean: Result := edtBool; varShortInt: Result := edtShortInt; varByte: Result := edtByte; varWord: Result := edtWord; varLongWord: Result := edtUInt; varInt64: Result := edtInt64; varUInt64: Result := edtUInt64; else begin if VarIsStr(v) then Result := edtString else Result := edtUnknow; end; end; end; constructor TSymbolExpression.Create(const TextStyle_: TTextStyle); begin inherited Create; FList := TCoreClassList.Create; FTextStyle := TextStyle_; end; destructor TSymbolExpression.Destroy; begin Clear; DisposeObject(FList); inherited Destroy; end; procedure TSymbolExpression.Clear; var i: Integer; begin for i := 0 to FList.Count - 1 do begin if (PExpressionListData(FList[i])^.ExpressionAutoFree) and (PExpressionListData(FList[i])^.Expression <> nil) then DisposeObject(PExpressionListData(FList[i])^.Expression); Dispose(PExpressionListData(FList[i])); end; FList.Clear; end; procedure TSymbolExpression.PrintDebug(const detail: Boolean; const prefix: SystemString); var i: Integer; p: PExpressionListData; begin DoStatus(prefix + ' decl: ' + Decl()); if detail then begin for i := 0 to Count - 1 do begin p := GetItems(i); DoStatus(prefix + ' id:%d exp:%s symbol:%s val:%s', [i, GetEnumName(TypeInfo(TExpressionDeclType), Ord(p^.DeclType)), GetEnumName(TypeInfo(TSymbolOperation), Ord(p^.Symbol)), VarToStr(p^.Value)]); end; DoStatus(''); for i := 0 to Count - 1 do begin p := GetItems(i); if p^.Expression <> nil then if p^.Expression.Count > 0 then p^.Expression.PrintDebug(detail, prefix + ' -> ' + VarToStr(p^.Value)); end; end; end; procedure TSymbolExpression.PrintDebug(const detail: Boolean); begin PrintDebug(detail, ''); end; function TSymbolExpression.Decl(): SystemString; var i, j: Integer; p: PExpressionListData; begin Result := ''; for i := 0 to FList.Count - 1 do begin p := FList[i]; case p^.DeclType of edtSymbol: Result := Result + SymbolOperationTextDecl[p^.Symbol].Decl; edtSingle, edtDouble, edtCurrency: Result := Result + FloatToStr(p^.Value); edtProcExp: begin Result := Result + VarToStr(p^.Value) + '('; for j := 0 to p^.Expression.Count - 1 do begin if j = 0 then Result := Result + p^.Expression[j]^.Expression.Decl else Result := Result + ',' + p^.Expression[j]^.Expression.Decl; end; Result := Result + ')'; end; edtString: begin case FTextStyle of tsPascal: Result := Result + TTextParsing.TranslateTextToPascalDecl(VarToStr(p^.Value)); tsC: Result := Result + TTextParsing.TranslateTextToC_Decl(VarToStr(p^.Value)); else Result := Result + VarToStr(p^.Value); end; end; edtExpressionAsValue: begin case p^.Symbol of soBlockIndentBegin: Result := Format('%s%s%s%s', [Result, SymbolOperationTextDecl[soBlockIndentBegin].Decl, p^.Expression.Decl, SymbolOperationTextDecl[soBlockIndentEnd].Decl ]); soPropIndentBegin: Result := Format('%s%s%s%s', [Result, SymbolOperationTextDecl[soPropIndentBegin].Decl, p^.Expression.Decl, SymbolOperationTextDecl[soPropIndentEnd].Decl ]); soParameter: begin Result := Format('%s%s%s%s', [Result, SymbolOperationTextDecl[soBlockIndentBegin].Decl, p^.Expression.Decl, SymbolOperationTextDecl[soBlockIndentEnd].Decl ]); end; else Result := Result + ' !error! '; end; end; edtUnknow: Result := Result + ' !error! '; else Result := Result + VarToStr(p^.Value); end; end; end; function TSymbolExpression.GetCount(t: TExpressionDeclTypes): Integer; var i: Integer; p: PExpressionListData; begin Result := 0; for i := 0 to FList.Count - 1 do begin p := FList[i]; if p^.DeclType in t then inc(Result); end; end; function TSymbolExpression.GetSymbolCount(Operations: TSymbolOperations): Integer; var i: Integer; p: PExpressionListData; begin Result := 0; for i := 0 to FList.Count - 1 do begin p := FList[i]; if p^.DeclType = edtSymbol then begin if p^.Symbol in Operations then inc(Result); end; end; end; function TSymbolExpression.AvailValueCount: Integer; begin Result := GetCount(AllExpressionValueType); end; function TSymbolExpression.Count: Integer; begin Result := FList.Count; end; function TSymbolExpression.InsertSymbol(const idx: Integer; v: TSymbolOperation; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtSymbol; p^.charPos := charPos; p^.Symbol := v; p^.Value := v; FList.Insert(idx, p); Result := p; end; function TSymbolExpression.Insert(const idx: Integer; v: TExpressionListData): PExpressionListData; var p: PExpressionListData; begin new(p); p^ := v; FList.Insert(idx, p); Result := p; end; procedure TSymbolExpression.InsertExpression(const idx: Integer; E: TSymbolExpression); var NewList: TCoreClassList; i: Integer; p: PExpressionListData; begin NewList := TCoreClassList.Create; NewList.Capacity := E.FList.Count + FList.Count; for i := 0 to idx do NewList.Add(FList[i]); for i := 0 to E.FList.Count - 1 do begin new(p); p^ := PExpressionListData(E.FList[i])^; NewList.Add(p); end; for i := idx to FList.Count - 1 do NewList.Add(FList[i]); DisposeObject(FList); FList := NewList; end; procedure TSymbolExpression.AddExpression(const E: TSymbolExpression); var i: Integer; begin for i := 0 to E.Count - 1 do AddCopy(E[i]^); end; function TSymbolExpression.AddSymbol(const v: TSymbolOperation; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtSymbol; p^.charPos := charPos; p^.Symbol := v; p^.Value := SymbolOperationTextDecl[v].Decl; FList.Add(p); Result := p; end; function TSymbolExpression.AddBool(const v: Boolean; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtBool; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddInt(const v: Integer; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtInt; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddUInt(const v: Cardinal; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtUInt; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddInt64(const v: Int64; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtInt64; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddUInt64(const v: UInt64; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtUInt64; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddWord(const v: Word; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtWord; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddByte(const v: Byte; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtByte; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddSmallInt(const v: SmallInt; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtSmallInt; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddShortInt(const v: ShortInt; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtShortInt; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddSingle(const v: Single; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtSingle; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddDouble(const v: Double; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtDouble; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddCurrency(const v: Currency; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtCurrency; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddString(const v: SystemString; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtString; p^.charPos := charPos; p^.Value := v; FList.Add(p); Result := p; end; function TSymbolExpression.AddFunc(const v: SystemString; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtProcExp; p^.charPos := charPos; p^.Symbol := soProc; p^.Value := v; p^.Expression := TSymbolExpression.Create(FTextStyle); p^.ExpressionAutoFree := True; FList.Add(p); Result := p; end; function TSymbolExpression.AddExpressionAsValue(AutoFree: Boolean; Expression: TSymbolExpression; Symbol: TSymbolOperation; Value: Variant; charPos: Integer): PExpressionListData; var p: PExpressionListData; begin new(p); InitExp(p^); p^.DeclType := edtExpressionAsValue; p^.charPos := charPos; p^.Symbol := Symbol; p^.Value := Value; p^.Expression := Expression; p^.ExpressionAutoFree := AutoFree; FList.Add(p); Result := p; end; function TSymbolExpression.Add(const v: TExpressionListData): PExpressionListData; var p: PExpressionListData; begin new(p); p^ := v; p^.ExpressionAutoFree := False; FList.Add(p); Result := p; end; function TSymbolExpression.AddCopy(const v: TExpressionListData): PExpressionListData; var p: PExpressionListData; i: Integer; begin new(p); p^ := v; p^.ExpressionAutoFree := False; if v.Expression <> nil then begin p^.Expression := TSymbolExpression.Create(FTextStyle); p^.ExpressionAutoFree := True; for i := 0 to v.Expression.Count - 1 do p^.Expression.AddCopy(v.Expression[i]^) end; FList.Add(p); Result := p; end; procedure TSymbolExpression.Delete(const idx: Integer); var p: PExpressionListData; begin p := FList[idx]; if (p^.ExpressionAutoFree) and (p^.Expression <> nil) then DisposeObject(p^.Expression); Dispose(p); FList.Delete(idx); end; procedure TSymbolExpression.DeleteLast; begin Delete(Count - 1); end; function TSymbolExpression.Last: PExpressionListData; begin Result := FList.Last; end; function TSymbolExpression.First: PExpressionListData; begin Result := FList.First; end; function TSymbolExpression.IndexOf(p: PExpressionListData): Integer; var i: Integer; begin for i := FList.Count - 1 downto 0 do if FList[i] = p then Exit(i); Exit(-1); end; function TSymbolExpression.GetItems(index: Integer): PExpressionListData; begin Result := FList[index]; end; function ParseOperationState(ParsingEng: TTextParsing; var cPos, bPos, ePos, BlockIndent, PropIndent: Integer; var pStates: TExpressionParsingState): TSymbolOperation; var c: SystemChar; Decl: TPascalString; p: PExpressionListData; begin Result := soUnknow; if not(esWaitOp in pStates) then Exit; while cPos <= ParsingEng.Len do begin if ParsingEng.isComment(cPos) then begin cPos := ParsingEng.GetCommentEndPos(cPos); Continue; end; c := ParsingEng.ParsingData.Text[cPos]; bPos := cPos; if (CharIn(c, ';')) then begin inc(cPos); Result := soEolSymbol; Exit; end; if (CharIn(c, ',')) then begin inc(cPos); pStates := pStates - [esWaitOp] + [esWaitValue]; Result := soCommaSymbol; Exit; end; if CharIn(c, ')') then begin inc(cPos); if (esWaitIndentEnd in pStates) then begin dec(BlockIndent); if BlockIndent < 0 then begin pStates := pStates - [esWaitOp, esWaitIndentEnd]; Result := soBlockIndentEnd; Exit; end else if BlockIndent = 0 then pStates := pStates - [esWaitIndentEnd]; pStates := pStates + [esWaitOp]; Result := soBlockIndentEnd; Exit; end else begin pStates := pStates - [esWaitOp, esWaitIndentEnd]; Result := soBlockIndentEnd; Exit; end; end; if CharIn(c, ']') then begin inc(cPos); if (esWaitPropParamIndentEnd in pStates) then begin dec(PropIndent); if PropIndent < 0 then begin pStates := pStates - [esWaitOp, esWaitPropParamIndentEnd]; Result := soPropIndentEnd; Exit; end else if PropIndent = 0 then pStates := pStates - [esWaitPropParamIndentEnd]; pStates := pStates + [esWaitOp]; Result := soPropIndentEnd; Exit; end else begin pStates := pStates - [esWaitOp, esWaitPropParamIndentEnd]; Result := soPropIndentEnd; Exit; end; end; if CharIn(c, '(') then begin inc(cPos); inc(BlockIndent); pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue, esWaitIndentEnd]; Result := soBlockIndentBegin; Exit; end; if CharIn(c, '[') then begin inc(cPos); inc(PropIndent); Result := soPropIndentBegin; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue, esWaitPropParamIndentEnd]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '>=')) or (ParsingEng.ComparePosStr(cPos, '=>')) then begin inc(cPos, 2); Result := soEqualOrGreaterThan; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '<=')) or (ParsingEng.ComparePosStr(cPos, '=<')) then begin inc(cPos, 2); Result := soEqualOrLessThan; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '<>')) or (ParsingEng.ComparePosStr(cPos, '><')) or (ParsingEng.ComparePosStr(cPos, '!=')) then begin inc(cPos, 2); Result := soNotEqual; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '==')) then begin inc(cPos, 2); Result := soEqual; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '&&')) then begin inc(cPos, 2); Result := soAnd; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '||')) then begin inc(cPos, 2); Result := soOr; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '<<')) then begin inc(cPos, 2); Result := soShl; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.ComparePosStr(cPos, '>>')) then begin inc(cPos, 2); Result := soShr; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if CharIn(c, '+-*/^=><.,&|%') then begin if c = '+' then Result := soAdd else if c = '-' then Result := soSub else if c = '*' then Result := soMul else if c = '/' then Result := soDiv else if c = '^' then Result := soPow else if c = '=' then Result := soEqual else if c = '>' then Result := soGreaterThan else if c = '<' then Result := soLessThan else if c = '.' then Result := soDotSymbol else if c = ',' then Result := soCommaSymbol else if c = '&' then Result := soAnd else if c = '|' then Result := soOr else if c = '%' then Result := soMod; inc(cPos); pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if (ParsingEng.isAscii(cPos)) then begin bPos := cPos; ePos := ParsingEng.GetAsciiEndPos(cPos); Decl := ParsingEng.GetStr(bPos, ePos); if Decl.Same('or') then Result := soOr else if Decl.Same('and') then Result := soAnd else if Decl.Same('xor') then Result := soXor else if Decl.Same('div', 'idiv', 'intdiv') then Result := soIntDiv else if Decl.Same('fdiv', 'floatdiv') then Result := soDiv else if Decl.Same('mod') then Result := soMod else if Decl.Same('shl') then Result := soShl else if Decl.Same('shr') then Result := soShr else begin Result := soUnknow; Exit; end; cPos := ePos; pStates := pStates - [esWaitOp]; pStates := pStates + [esWaitValue]; Exit; end; if ParsingEng.isNumber(cPos) then begin Result := soUnknow; Exit; end; inc(cPos); end; pStates := []; Result := soEolSymbol; end; function ParseSymbol(ParsingEng: TTextParsing; WorkSym: TSymbolExpression; var cPos, bPos, ePos, BlockIndent, PropIndent: Integer; pStates: PExpressionParsingState): Boolean; var bak_cPos: Integer; Decl: SystemString; OpState: TSymbolOperation; RV: Variant; robj: TCoreClassObject; p: PExpressionListData; begin while cPos <= ParsingEng.Len do begin pStates^ := pStates^ - [esWaitValue, esFirst]; pStates^ := pStates^ + [esWaitOp]; bak_cPos := cPos; OpState := ParseOperationState(ParsingEng, cPos, bPos, ePos, BlockIndent, PropIndent, pStates^); case OpState of soUnknow, soEolSymbol: begin Result := False; Exit; end; soDotSymbol: begin Result := False; Exit; end; soCommaSymbol: begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; soPropIndentBegin: begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; soPropIndentEnd: begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; soBlockIndentEnd: begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; soBlockIndentBegin: begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; else begin WorkSym.AddSymbol(OpState, bak_cPos); Result := True; Exit; end; end; end; Result := False; end; function __ParseTextExpressionAsSymbol(ParsingEng: TTextParsing; const uName: SystemString; const OnDeclValueCall: TOnDeclValueCall; const OnDeclValueMethod: TOnDeclValueMethod; const OnDeclValueProc: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; procedure PrintError(const s: SystemString); begin if s = '' then DoStatus('declaration error "%s"', [ParsingEng.Text.Text]) else DoStatus('declaration error "%s" -> [%s]', [ParsingEng.Text.Text, s]); DoStatus(''); end; function GetDeclValue(const Decl: SystemString; var v: Variant): TExpressionDeclType; begin v := Decl; Result := edtProcExp; if Assigned(OnDeclValueCall) then OnDeclValueCall(Decl, Result, v); if Assigned(OnDeclValueMethod) then OnDeclValueMethod(Decl, Result, v); if Assigned(OnDeclValueProc) then OnDeclValueProc(Decl, Result, v); end; function FillProc(var ExpIndex: Integer; const Exps, procExp: TSymbolExpression): TSymbolExpression; var WasProc: Boolean; LocalExp, ResExp: TSymbolExpression; p1, p2, p: PExpressionListData; begin if ExpIndex >= Exps.Count then begin Result := nil; Exit; end; WasProc := procExp <> nil; if WasProc then LocalExp := procExp.AddExpressionAsValue( True, TSymbolExpression.Create(ParsingEng.TextStyle), soParameter, 'param_1', Exps[ExpIndex]^.charPos)^.Expression else LocalExp := TSymbolExpression.Create(ParsingEng.TextStyle); Result := LocalExp; while ExpIndex < Exps.Count do begin p1 := Exps[ExpIndex]; if ExpIndex + 1 < Exps.Count then p2 := Exps[ExpIndex + 1] else p2 := nil; if (p1^.DeclType = edtProcExp) then begin if p2 <> nil then begin if (p2^.DeclType = edtSymbol) and (p2^.Symbol in [soBlockIndentBegin, soPropIndentBegin]) then begin inc(ExpIndex, 2); p := LocalExp.AddFunc(p1^.Value, p1^.charPos); FillProc(ExpIndex, Exps, p^.Expression); Continue; end; end else begin Result.AddFunc(p1^.Value, p1^.charPos); inc(ExpIndex); Continue; end; end; if (p1^.DeclType = edtSymbol) then begin if p1^.Symbol in [soBlockIndentBegin, soPropIndentBegin] then begin inc(ExpIndex); ResExp := FillProc(ExpIndex, Exps, nil); if ResExp <> nil then LocalExp.AddExpressionAsValue(True, ResExp, soBlockIndentBegin, p1^.Symbol, p1^.charPos); Continue; end; if p1^.Symbol in [soBlockIndentEnd, soPropIndentEnd] then begin inc(ExpIndex); Exit; end; if (p1^.Symbol in [soCommaSymbol]) then begin if not WasProc then begin PrintError('comma Illegal'); Exit; end; LocalExp := procExp.AddExpressionAsValue(True, TSymbolExpression.Create(ParsingEng.TextStyle), soParameter, 'param_' + IntToStr(procExp.Count + 1), Exps[ExpIndex]^.charPos)^.Expression; inc(ExpIndex); Continue; end; end; LocalExp.AddCopy(p1^); inc(ExpIndex); end; end; var cPos, bPos, ePos, i: Integer; td: PTokenData; State: TExpressionParsingState; BlockIndent, PropIndent: Integer; Container: TSymbolExpression; te: TTextParsing; Decl: TPascalString; OpState: TSymbolOperation; isNumber, isSpecialSymbol, isAscii, isTextDecl, isSymbol: Boolean; RV: Variant; p: PExpressionListData; begin Result := nil; if ParsingEng.ParsingData.Len < 1 then Exit; if ParsingEng.TokenCountT([ttTextDecl, ttNumber, ttAscii]) = 0 then Exit; cPos := 1; BlockIndent := 0; PropIndent := 0; State := [esFirst]; Container := TSymbolExpression.Create(ParsingEng.TextStyle); while cPos <= ParsingEng.Len do begin if ParsingEng.isComment(cPos) then begin cPos := ParsingEng.GetCommentEndPos(cPos) + 1; Continue; end; // check esWaitOp state if (esWaitOp in State) and (CharIn(ParsingEng.GetChar(cPos), ParsingEng.SymbolTable)) then begin isNumber := False; isTextDecl := False; isAscii := False; isSymbol := True; bPos := cPos; ePos := bPos + 1; end else begin td := ParsingEng.TokenPos[cPos]; isSpecialSymbol := td^.tokenType = ttSpecialSymbol; if isSpecialSymbol then begin isNumber := False; isTextDecl := False; isAscii := False; isSymbol := False; end else if (td^.tokenType = ttAscii) and ( td^.Text.Same('and', 'or', 'xor', 'shl', 'shr') or td^.Text.Same('div', 'idiv', 'intdiv', 'fdiv', 'floatdiv') or td^.Text.Same('mod') ) then begin isSymbol := True; isNumber := False; isTextDecl := False; isAscii := False; end else begin isNumber := td^.tokenType = ttNumber; isTextDecl := td^.tokenType = ttTextDecl; isAscii := td^.tokenType = ttAscii; isSymbol := td^.tokenType = ttSymbol; end; end; if (not(esWaitOp in State)) and (isSpecialSymbol or isNumber or isTextDecl or isAscii) then begin if not((esWaitValue in State) or (esFirst in State)) then begin PrintError(''); Break; end; bPos := cPos; ePos := td^.ePos; if (isSpecialSymbol) and (ParsingEng.GetAsciiBeginPos(ePos) <= ePos) then ePos := ParsingEng.GetSpecialSymbolEndPos(ParsingEng.GetAsciiEndPos(ePos)); cPos := ePos; Decl := ParsingEng.GetStr(bPos, ePos); if isNumber then begin if Decl.ComparePos(1, '0x') then begin Decl.DeleteFirst; Decl[1] := '$'; end; case NumTextType(Decl) of nttBool: Container.AddBool(StrToBool(Decl), bPos); nttInt: Container.AddInt(StrToInt(Decl), bPos); nttInt64: Container.AddInt64(StrToInt64(Decl), bPos); {$IFDEF FPC} nttUInt64: Container.AddUInt64(StrToQWord(Decl), bPos); {$ELSE} nttUInt64: Container.AddUInt64(StrToUInt64(Decl), bPos); {$ENDIF} nttWord: Container.AddWord(StrToInt(Decl), bPos); nttByte: Container.AddByte(StrToInt(Decl), bPos); nttSmallInt: Container.AddSmallInt(StrToInt(Decl), bPos); nttShortInt: Container.AddShortInt(StrToInt(Decl), bPos); nttUInt: Container.AddUInt(StrToInt(Decl), bPos); nttSingle: Container.AddSingle(StrToFloat(Decl), bPos); nttDouble: Container.AddDouble(StrToFloat(Decl), bPos); nttCurrency: Container.AddCurrency(StrToFloat(Decl), bPos); else begin PrintError(Format('number expression "%s" Illegal', [Decl.Text])); Break; end; end; end else if isTextDecl then begin Container.AddString(ParsingEng.GetTextBody(Decl), bPos); end else case NumTextType(Decl) of nttBool: Container.AddBool(StrToBool(Decl), bPos); nttInt: Container.AddInt(StrToInt(Decl), bPos); nttInt64: Container.AddInt64(StrToInt64(Decl), bPos); {$IFDEF FPC} nttUInt64: Container.AddUInt64(StrToQWord(Decl), bPos); {$ELSE} nttUInt64: Container.AddUInt64(StrToUInt64(Decl), bPos); {$ENDIF} nttWord: Container.AddWord(StrToInt(Decl), bPos); nttByte: Container.AddByte(StrToInt(Decl), bPos); nttSmallInt: Container.AddSmallInt(StrToInt(Decl), bPos); nttShortInt: Container.AddShortInt(StrToInt(Decl), bPos); nttUInt: Container.AddUInt(StrToInt(Decl), bPos); nttSingle: Container.AddSingle(StrToFloat(Decl), bPos); nttDouble: Container.AddDouble(StrToFloat(Decl), bPos); nttCurrency: Container.AddCurrency(StrToFloat(Decl), bPos); else begin case GetDeclValue(Decl, RV) of edtBool: Container.AddBool(RV, bPos); edtInt: Container.AddInt(RV, bPos); edtInt64: Container.AddInt64(RV, bPos); edtUInt64: Container.AddUInt64(RV, bPos); edtWord: Container.AddWord(RV, bPos); edtByte: Container.AddByte(RV, bPos); edtSmallInt: Container.AddSmallInt(RV, bPos); edtShortInt: Container.AddShortInt(RV, bPos); edtUInt: Container.AddUInt(RV, bPos); edtSingle: Container.AddSingle(RV, bPos); edtDouble: Container.AddDouble(RV, bPos); edtCurrency: Container.AddCurrency(RV, bPos); edtString: Container.AddString(RV, bPos); edtProcExp: begin if (RefrenceOpRT <> nil) and (not RefrenceOpRT.ProcList.Exists(RV)) then if (DefaultOpRT <> RefrenceOpRT) and (not DefaultOpRT.ProcList.Exists(RV)) then begin PrintError(Format('function "%s" Illegal', [RV])); Break; end; Container.AddFunc(RV, bPos); end; else begin PrintError(Format('define "%s" Illegal', [Decl.Text])); Break; end; end; end; end; if not ParseSymbol(ParsingEng, Container, cPos, bPos, ePos, BlockIndent, PropIndent, @State) then Break else Continue; end; if (isSymbol) then begin if not ParseSymbol(ParsingEng, Container, cPos, bPos, ePos, BlockIndent, PropIndent, @State) then Break else Continue; end; inc(cPos); end; if (BlockIndent + PropIndent = 0) then begin i := 0; Result := FillProc(i, Container, nil); if Result = nil then PrintError('indent error'); end else PrintError('indent error'); DisposeObject(Container); end; function ParseTextExpressionAsSymbol_C(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := __ParseTextExpressionAsSymbol(ParsingEng, uName, OnGetValue, nil, nil, RefrenceOpRT); end; function ParseTextExpressionAsSymbol_M(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := __ParseTextExpressionAsSymbol(ParsingEng, uName, nil, OnGetValue, nil, RefrenceOpRT); end; function ParseTextExpressionAsSymbol_P(ParsingEng: TTextParsing; const uName: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := __ParseTextExpressionAsSymbol(ParsingEng, uName, nil, nil, OnGetValue, RefrenceOpRT); end; function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TTextParsing.Create(ExpressionText, TextStyle, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_M(ParsingEng, uName, OnGetValue, RefrenceOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol(TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol(nil, TextStyle, uName, ExpressionText, OnGetValue, RefrenceOpRT); end; function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TTextParsing.Create(ExpressionText, tsPascal, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_M(ParsingEng, '', nil, RefrenceOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol(ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol(nil, ExpressionText, RefrenceOpRT); end; function ParseTextExpressionAsSymbol(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TTextParsing.Create(ExpressionText, tsPascal, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_M(ParsingEng, '', nil, DefaultOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol(ExpressionText: SystemString): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol(nil, ExpressionText); end; function ParseTextExpressionAsSymbol_M(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TextEngClass.Create(ExpressionText, TextStyle, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_M(ParsingEng, '', OnGetValue, RefrenceOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol_M(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol_M(nil, TextEngClass, TextStyle, uName, ExpressionText, OnGetValue, RefrenceOpRT); end; function ParseTextExpressionAsSymbol_C(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TextEngClass.Create(ExpressionText, TextStyle, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_C(ParsingEng, '', OnGetValue, RefrenceOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol_C(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol_C(nil, TextEngClass, TextStyle, uName, ExpressionText, OnGetValue, RefrenceOpRT); end; function ParseTextExpressionAsSymbol_P(SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; var ParsingEng: TTextParsing; begin ParsingEng := TextEngClass.Create(ExpressionText, TextStyle, SpecialAsciiToken); Result := ParseTextExpressionAsSymbol_P(ParsingEng, '', OnGetValue, RefrenceOpRT); DisposeObject(ParsingEng); end; function ParseTextExpressionAsSymbol_P(TextEngClass: TTextParsingClass; TextStyle: TTextStyle; const uName, ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc; RefrenceOpRT: TOpCustomRunTime): TSymbolExpression; begin Result := ParseTextExpressionAsSymbol_P(nil, TextEngClass, TextStyle, uName, ExpressionText, OnGetValue, RefrenceOpRT); end; function RebuildLogicalPrioritySymbol(Exps: TSymbolExpression): TSymbolExpression; function SymbolPriority(s1, s2: TSymbolOperation): Integer; function FindSymbol(s: TSymbolOperation): Integer; var i: Integer; begin for i := low(SymbolOperationPriority) to high(SymbolOperationPriority) do if s in SymbolOperationPriority[i] then Exit(i); raise Exception.Create('no define symbol'); end; begin if (s1 in [soUnknow, soCommaSymbol]) or (s2 in [soUnknow, soCommaSymbol]) then Exit(0); Result := FindSymbol(s2) - FindSymbol(s1); end; var SymbolIndex: Integer; newExpression: TSymbolExpression; ParseAborted: Boolean; procedure PrintError(const s: SystemString); begin ParseAborted := True; if s <> '' then DoStatus(Format('Priority symbol failed : %s', [s])) else DoStatus('Priority symbol failed'); end; procedure ProcessSymbol(OwnerSym: TSymbolOperation); var p1, p2, startIndent, lastIndent: PExpressionListData; LastSym, lastIndentSym: TSymbolOperation; LastSymbolPriority, LastOwnerSymbolPriority: Integer; begin if ParseAborted then Exit; if SymbolIndex >= Exps.Count then Exit; if newExpression.Count > 0 then startIndent := newExpression.Last else startIndent := nil; LastSym := OwnerSym; lastIndent := nil; lastIndentSym := OwnerSym; while True do begin if ParseAborted then Break; if SymbolIndex >= Exps.Count then Break; p1 := Exps[SymbolIndex]; if (p1^.DeclType in AllExpressionValueType) then begin inc(SymbolIndex); if SymbolIndex >= Exps.Count then begin newExpression.Add(p1^); Break; end; p2 := Exps[SymbolIndex]; if (p1^.DeclType in MethodToken) and (p2^.DeclType = edtExpressionAsValue) then begin newExpression.Add(p1^); newExpression.Add(p2^); end else if p2^.DeclType = edtSymbol then begin if p2^.Symbol in AllowPrioritySymbol then begin LastOwnerSymbolPriority := SymbolPriority(p2^.Symbol, OwnerSym); LastSymbolPriority := SymbolPriority(p2^.Symbol, LastSym); if LastOwnerSymbolPriority > 0 then begin newExpression.Add(p1^); Break; end; if LastSymbolPriority < 0 then begin lastIndent := newExpression.AddSymbol(soBlockIndentBegin, p1^.charPos); lastIndentSym := LastSym; newExpression.Add(p1^); newExpression.Add(p2^); inc(SymbolIndex); ProcessSymbol(p2^.Symbol); newExpression.AddSymbol(soBlockIndentEnd, p2^.charPos); Continue; end else if LastSymbolPriority > 0 then begin if startIndent = nil then startIndent := newExpression.First; newExpression.InsertSymbol(newExpression.IndexOf(startIndent), soBlockIndentBegin, startIndent^.charPos); newExpression.Add(p1^); newExpression.AddSymbol(soBlockIndentEnd, p2^.charPos); newExpression.Add(p2^); end else begin newExpression.Add(p1^); newExpression.Add(p2^); end; LastSym := p2^.Symbol; end else begin PrintError(SymbolOperationTextDecl[p2^.Symbol].Decl); Exit; end; end; end else if (p1^.DeclType = edtSymbol) then begin inc(SymbolIndex); if SymbolIndex >= Exps.Count then begin newExpression.Add(p1^); Break; end; p2 := Exps[SymbolIndex]; if (p2^.DeclType in AllExpressionValueType) then begin if p1^.Symbol in AllowPrioritySymbol then begin LastSymbolPriority := SymbolPriority(p1^.Symbol, lastIndentSym); if LastSymbolPriority < 0 then begin newExpression.InsertSymbol(newExpression.IndexOf(lastIndent), soBlockIndentBegin, lastIndent^.charPos); newExpression.Add(p1^); LastSym := p1^.Symbol; ProcessSymbol(p1^.Symbol); newExpression.AddSymbol(soBlockIndentEnd, p2^.charPos); Continue; end else begin newExpression.Add(p1^); Continue; end; end else begin PrintError(SymbolOperationTextDecl[p1^.Symbol].Decl); Exit; end; end else begin PrintError('expression structor Illegal'); Exit; end; end; inc(SymbolIndex); end; end; begin Result := nil; if Exps.AvailValueCount = 0 then Exit; if Exps.GetSymbolCount([ soBlockIndentBegin, soBlockIndentEnd, soPropIndentBegin, soPropIndentEnd, soEolSymbol, soUnknow]) > 0 then begin PrintError('Illegal symbol'); Exit; end; SymbolIndex := 0; newExpression := TSymbolExpression.Create(Exps.FTextStyle); ParseAborted := False; ProcessSymbol(soUnknow); if ParseAborted then begin newExpression.Free; PrintError('Illegal'); end else Result := newExpression; end; function RebuildAllSymbol(Exps: TSymbolExpression): TSymbolExpression; var SymbolIndex: Integer; ParseAborted: Boolean; procedure PrintError(const s: SystemString); begin ParseAborted := True; if s <> '' then DoStatus(Format('indent symbol failed : %s', [s])) else DoStatus('indent symbol failed'); end; function ProcessIndent(OwnerIndentSym: TSymbolOperation): TSymbolExpression; var p1, p2: PExpressionListData; LocalExp, ResExp: TSymbolExpression; begin LocalExp := TSymbolExpression.Create(Exps.FTextStyle); Result := LocalExp; while True do begin if SymbolIndex >= Exps.Count then Break; p1 := Exps[SymbolIndex]; if (p1^.DeclType in [edtSymbol]) then begin if p1^.Symbol in [soBlockIndentBegin, soPropIndentBegin] then begin inc(SymbolIndex); ResExp := ProcessIndent(p1^.Symbol); LocalExp.AddExpressionAsValue(True, ResExp, p1^.Symbol, SymbolOperationTextDecl[p1^.Symbol].Decl, p1^.charPos); if SymbolIndex >= Exps.Count then begin PrintError('indent Illegal'); Exit; end; end else if ((OwnerIndentSym = soBlockIndentBegin) and (p1^.Symbol = soBlockIndentEnd)) or ((OwnerIndentSym = soPropIndentBegin) and (p1^.Symbol = soPropIndentEnd)) then begin Exit; end else if p1^.Symbol in [soCommaSymbol] then begin LocalExp.Add(p1^); end else begin LocalExp.Add(p1^); end; end else if (p1^.DeclType in AllExpressionValueType) then begin if p1^.DeclType = edtProcExp then begin LocalExp.Add(p1^); inc(SymbolIndex); Continue; end; inc(SymbolIndex); if SymbolIndex >= Exps.Count then begin LocalExp.Add(p1^); Break; end; p2 := Exps[SymbolIndex]; if p2^.DeclType = edtSymbol then begin if (p2^.Symbol in [soBlockIndentBegin, soPropIndentBegin]) then begin if (p1^.DeclType in MethodToken) then begin PrintError('method Illegal'); Exit; end; LocalExp.Add(p1^); inc(SymbolIndex); ResExp := ProcessIndent(p2^.Symbol); LocalExp.AddExpressionAsValue(True, ResExp, p2^.Symbol, SymbolOperationTextDecl[p2^.Symbol].Decl, p2^.charPos); if SymbolIndex >= Exps.Count then begin PrintError('indent Illegal'); Exit; end; end else if ((OwnerIndentSym = soBlockIndentBegin) and (p2^.Symbol = soBlockIndentEnd)) or ((OwnerIndentSym = soPropIndentBegin) and (p2^.Symbol = soPropIndentEnd)) then begin LocalExp.Add(p1^); Exit; end else if p2^.Symbol = soCommaSymbol then begin PrintError('Comma Illegal'); Exit; end else begin LocalExp.Add(p1^); LocalExp.Add(p2^); end; end else begin PrintError('expression structor Illegal'); Exit; end; end; inc(SymbolIndex); end; end; function ProcessPriority(_e: TSymbolExpression): TSymbolExpression; var i, j: Integer; E, ResExp: TSymbolExpression; p, funcP: PExpressionListData; begin E := RebuildLogicalPrioritySymbol(_e); if E = nil then begin Result := nil; PrintError('parse priority failed'); Exit; end; Result := TSymbolExpression.Create(E.FTextStyle); for i := 0 to E.Count - 1 do begin p := E[i]; if p^.DeclType = edtExpressionAsValue then begin case p^.Symbol of soBlockIndentBegin: begin Result.AddSymbol(soBlockIndentBegin, p^.charPos); ResExp := ProcessPriority(p^.Expression); if ResExp <> nil then begin Result.AddExpression(ResExp); DisposeObject(ResExp); end; Result.AddSymbol(soBlockIndentEnd, p^.charPos); end; soPropIndentBegin: begin Result.AddSymbol(soPropIndentBegin, p^.charPos); ResExp := ProcessPriority(p^.Expression); if ResExp <> nil then begin Result.AddExpression(ResExp); DisposeObject(ResExp); end; Result.AddSymbol(soPropIndentEnd, p^.charPos); end; else begin Break; end; end; end else if p^.DeclType = edtProcExp then begin funcP := Result.AddFunc(VarToStr(p^.Value), p^.charPos); if (p^.Expression.Count > 0) and (p^.Expression.First^.Expression.Count > 0) then for j := 0 to p^.Expression.Count - 1 do begin ResExp := RebuildAllSymbol(p^.Expression[j]^.Expression); if ResExp <> nil then funcP^.Expression.AddExpressionAsValue(True, ResExp, soParameter, VarToStr(p^.Expression[j]^.Value), p^.Expression[j]^.charPos); end; end else begin Result.Add(p^); end; end; DisposeObject([E]); end; var rse: TSymbolExpression; begin Result := nil; SymbolIndex := 0; ParseAborted := False; rse := ProcessIndent(soUnknow); Result := ProcessPriority(rse); DisposeObject(rse); end; function BuildAsOpCode(DebugMode: Boolean; SymbExps: TSymbolExpression; const uName: SystemString; LineNo: Integer): TOpCode; var NewSymbExps: TSymbolExpression; SymbolIndex: Integer; BuildAborted: Boolean; OpContainer: TCoreClassListForObj; procedure PrintError(const s: SystemString); begin BuildAborted := True; if s <> '' then DoStatus(Format('build op failed : %s', [s])) else DoStatus('build op failed'); end; function NewOpValue(uName: SystemString): TOpCode; begin Result := op_Value.Create(False); Result.ParsedInfo := uName; Result.ParsedLineNo := LineNo; OpContainer.Add(Result); end; function NewOpProc(uName: SystemString): TOpCode; begin Result := op_Proc.Create(False); Result.ParsedInfo := uName; Result.ParsedLineNo := LineNo; OpContainer.Add(Result); end; function NewOpPrefixFromSym(sym: TSymbolOperation; const uName: SystemString): TOpCode; begin case sym of soAdd: Result := op_Add_Prefix.Create(False); soSub: Result := op_Sub_Prefix.Create(False); else Result := nil; end; if Result <> nil then begin Result.ParsedInfo := uName; Result.ParsedLineNo := LineNo; OpContainer.Add(Result); end; end; function NewOpFromSym(sym: TSymbolOperation; const uName: SystemString): TOpCode; begin case sym of soAdd: Result := op_Add.Create(False); soSub: Result := op_Sub.Create(False); soMul: Result := op_Mul.Create(False); soDiv: Result := op_Div.Create(False); soMod: Result := op_Mod.Create(False); soIntDiv: Result := op_IntDiv.Create(False); soPow: Result := op_Pow.Create(False); soOr: Result := op_Or.Create(False); soAnd: Result := op_And.Create(False); soXor: Result := op_Xor.Create(False); soEqual: Result := op_Equal.Create(False); soLessThan: Result := op_LessThan.Create(False); soEqualOrLessThan: Result := op_EqualOrLessThan.Create(False); soGreaterThan: Result := op_GreaterThan.Create(False); soEqualOrGreaterThan: Result := op_EqualOrGreaterThan.Create(False); soNotEqual: Result := op_NotEqual.Create(False); soShl: Result := op_Shl.Create(False); soShr: Result := op_Shr.Create(False); else Result := nil; end; if Result <> nil then begin Result.ParsedInfo := uName; Result.ParsedLineNo := LineNo; OpContainer.Add(Result); end; end; function ProcessIndent(OwnerIndentSym: TSymbolOperation): TOpCode; var i: Integer; p1, p2: PExpressionListData; LocalOp, OldOp, ResOp, ProcOp: TOpCode; begin LocalOp := nil; OldOp := nil; ResOp := nil; Result := nil; while True do begin if SymbolIndex >= NewSymbExps.Count then begin if LocalOp <> nil then Result := LocalOp; Break; end; p1 := NewSymbExps[SymbolIndex]; if (p1^.DeclType in [edtSymbol]) then begin if p1^.Symbol in [soBlockIndentBegin, soPropIndentBegin] then begin inc(SymbolIndex); ResOp := ProcessIndent(p1^.Symbol); if ResOp <> nil then begin if LocalOp <> nil then begin LocalOp.AddLink(ResOp); end else begin LocalOp := NewOpValue(uName); LocalOp.AddLink(ResOp); end; end else begin PrintError('logical operotion Illegal'); Break; end; end else if ((OwnerIndentSym = soBlockIndentBegin) and (p1^.Symbol = soBlockIndentEnd)) or ((OwnerIndentSym = soPropIndentBegin) and (p1^.Symbol = soPropIndentEnd)) then begin Result := LocalOp; Break; end else if p1^.Symbol in OpLogicalSymbol then begin if LocalOp <> nil then begin OldOp := LocalOp; LocalOp := NewOpFromSym(p1^.Symbol, uName); if LocalOp = nil then begin PrintError('prefix symbol Illegal'); Break; end; LocalOp.AddLink(OldOp); end else begin // fixed symbol prefix, -(operation), -proc(xx)... if (SymbolIndex + 1 < NewSymbExps.Count) then begin p2 := NewSymbExps[SymbolIndex + 1]; if (p1^.Symbol in [soAdd, soSub]) then begin if (p2^.DeclType = edtSymbol) and (p2^.Symbol in [soBlockIndentBegin, soPropIndentBegin]) then begin inc(SymbolIndex); ResOp := ProcessIndent(p2^.Symbol); if ResOp <> nil then begin LocalOp := NewOpPrefixFromSym(p1^.Symbol, uName); if LocalOp = nil then begin PrintError('prefix symbol Illegal'); Break; end; LocalOp.AddLink(ResOp); end else begin PrintError('logical operotion Illegal'); Break; end; Continue; end else if (p2^.DeclType = edtProcExp) and (p2^.Symbol = soProc) then begin ProcOp := NewOpProc(uName); ProcOp.AddValue(p2^.Value); for i := 0 to p2^.Expression.Count - 1 do begin ResOp := BuildAsOpCode(False, p2^.Expression[i]^.Expression, uName, LineNo); if ResOp <> nil then ProcOp.AddLink(ResOp) else begin PrintError('method Illegal'); Break; end; end; LocalOp := NewOpPrefixFromSym(p1^.Symbol, uName); LocalOp.AddLink(ProcOp); inc(SymbolIndex, 2); Continue; end; end; end; PrintError('logical operotion Illegal'); Break; end; end else begin PrintError('logical operotion Illegal'); Break; end; end else if (p1^.DeclType in AllExpressionValueType) then begin if p1^.DeclType = edtProcExp then begin ProcOp := NewOpProc(uName); ProcOp.AddValue(p1^.Value); for i := 0 to p1^.Expression.Count - 1 do begin ResOp := BuildAsOpCode(False, p1^.Expression[i]^.Expression, uName, LineNo); if ResOp <> nil then ProcOp.AddLink(ResOp) else begin PrintError('method Illegal'); Break; end; end; if LocalOp <> nil then begin LocalOp.AddLink(ProcOp); end else begin LocalOp := NewOpValue(uName); LocalOp.AddLink(ProcOp); end; inc(SymbolIndex); Continue; end; inc(SymbolIndex); if SymbolIndex >= NewSymbExps.Count then begin if LocalOp <> nil then begin LocalOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); end else begin LocalOp := NewOpValue(uName); LocalOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); end; Result := LocalOp; Break; end; p2 := NewSymbExps[SymbolIndex]; if p2^.DeclType = edtSymbol then begin if (p2^.Symbol in [soBlockIndentBegin, soPropIndentBegin]) then begin // function call if not(p1^.DeclType in MethodToken) then begin PrintError('method Illegal'); Break; end else begin end; inc(SymbolIndex); ResOp := ProcessIndent(p2^.Symbol); end else if ((OwnerIndentSym = soBlockIndentBegin) and (p2^.Symbol = soBlockIndentEnd)) or ((OwnerIndentSym = soPropIndentBegin) and (p2^.Symbol = soPropIndentEnd)) then begin if LocalOp <> nil then begin LocalOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); end else begin LocalOp := NewOpValue(uName); LocalOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); end; Result := LocalOp; Break; end else if p2^.Symbol in OpLogicalSymbol then begin if LocalOp <> nil then begin OldOp := LocalOp; OldOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); LocalOp := NewOpFromSym(p2^.Symbol, uName); LocalOp.AddLink(OldOp); end else begin LocalOp := NewOpFromSym(p2^.Symbol, uName); LocalOp.AddValueT(p1^.Value, dt2op(p1^.DeclType)); end; end else begin PrintError('Illegal'); Break; end; end else begin PrintError('Illegal'); Break; end; end; inc(SymbolIndex); end; end; procedure ProcessOpContainer(Successed: Boolean); var i: Integer; begin for i := 0 to OpContainer.Count - 1 do if Successed then TOpCode(OpContainer[i]).AutoFreeLink := True else DisposeObject(TOpCode(OpContainer[i])); OpContainer.Clear; end; begin Result := nil; if SymbExps <> nil then begin NewSymbExps := RebuildAllSymbol(SymbExps); if NewSymbExps <> nil then begin if DebugMode then NewSymbExps.PrintDebug(True); if NewSymbExps.GetSymbolCount([soBlockIndentBegin, soPropIndentBegin]) = NewSymbExps.GetSymbolCount([soBlockIndentEnd, soPropIndentEnd]) then begin OpContainer := TCoreClassListForObj.Create; SymbolIndex := 0; BuildAborted := False; Result := ProcessIndent(soUnknow); ProcessOpContainer(Result <> nil); DisposeObject(OpContainer); end; DisposeObject(NewSymbExps); end; end; end; function BuildAsOpCode(SymbExps: TSymbolExpression): TOpCode; begin Result := BuildAsOpCode(False, SymbExps, '', 0); end; function BuildAsOpCode(DebugMode: Boolean; SymbExps: TSymbolExpression): TOpCode; begin Result := BuildAsOpCode(DebugMode, SymbExps, '', 0); end; function BuildAsOpCode(DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(TextStyle, '', ExpressionText, nil, DefaultOpRT); Result := BuildAsOpCode(DebugMode, sym, '', 0); DisposeObject(sym); end; function BuildAsOpCode(TextStyle: TTextStyle; ExpressionText: SystemString): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(TextStyle, '', ExpressionText, nil, DefaultOpRT); Result := BuildAsOpCode(False, sym, '', 0); DisposeObject(sym); end; function BuildAsOpCode(ExpressionText: SystemString): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(ExpressionText); Result := BuildAsOpCode(False, sym, '', 0); DisposeObject(sym); end; function BuildAsOpCode(DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(TextStyle, '', ExpressionText, nil, RefrenceOpRT); Result := BuildAsOpCode(DebugMode, sym, '', 0); DisposeObject(sym); end; function BuildAsOpCode(TextStyle: TTextStyle; ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(TextStyle, '', ExpressionText, nil, RefrenceOpRT); Result := BuildAsOpCode(False, sym, '', 0); DisposeObject(sym); end; function BuildAsOpCode(ExpressionText: SystemString; RefrenceOpRT: TOpCustomRunTime): TOpCode; var sym: TSymbolExpression; begin sym := ParseTextExpressionAsSymbol(ExpressionText, RefrenceOpRT); Result := BuildAsOpCode(False, sym, '', 0); DisposeObject(sym); end; function EvaluateExpressionValue_M(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueMethod): Variant; var sym: TSymbolExpression; Op: TOpCode; i: Integer; begin Op := nil; if UsedCache then begin LockObject(OpCache); Op := TOpCode(OpCache[ExpressionText]); UnLockObject(OpCache); end; if (Op <> nil) and (UsedCache) then begin try Result := Op.Execute(DefaultOpRT); except Result := NULL; end; end else begin Result := NULL; sym := ParseTextExpressionAsSymbol_M(SpecialAsciiToken, TextEngClass, TextStyle, '', ExpressionText, OnGetValue, DefaultOpRT); if sym <> nil then begin Op := BuildAsOpCode(False, sym, 'Main', -1); if Op <> nil then begin try Result := Op.Execute(DefaultOpRT); if UsedCache then begin LockObject(OpCache); OpCache.Add(ExpressionText, Op); UnLockObject(OpCache); end else DisposeObject(Op); except Result := NULL; end; end; DisposeObject(sym); end; end; end; function EvaluateExpressionValue_C(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueCall): Variant; var sym: TSymbolExpression; Op: TOpCode; i: Integer; begin Op := nil; if UsedCache then begin LockObject(OpCache); Op := TOpCode(OpCache[ExpressionText]); UnLockObject(OpCache); end; if (Op <> nil) and (UsedCache) then begin try Result := Op.Execute(DefaultOpRT); except Result := NULL; end; end else begin Result := NULL; sym := ParseTextExpressionAsSymbol_C(SpecialAsciiToken, TextEngClass, TextStyle, '', ExpressionText, OnGetValue, DefaultOpRT); if sym <> nil then begin Op := BuildAsOpCode(False, sym, 'Main', -1); if Op <> nil then begin try Result := Op.Execute(DefaultOpRT); if UsedCache then begin LockObject(OpCache); OpCache.Add(ExpressionText, Op); UnLockObject(OpCache); end else DisposeObject(Op); except Result := NULL; end; end; DisposeObject(sym); end; end; end; function EvaluateExpressionValue_P(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextEngClass: TTextParsingClass; TextStyle: TTextStyle; ExpressionText: SystemString; const OnGetValue: TOnDeclValueProc): Variant; var sym: TSymbolExpression; Op: TOpCode; i: Integer; begin Op := nil; if UsedCache then begin LockObject(OpCache); Op := TOpCode(OpCache[ExpressionText]); UnLockObject(OpCache); end; if (Op <> nil) and (UsedCache) then begin try Result := Op.Execute(DefaultOpRT); except Result := NULL; end; end else begin Result := NULL; sym := ParseTextExpressionAsSymbol_P(SpecialAsciiToken, TextEngClass, TextStyle, '', ExpressionText, OnGetValue, DefaultOpRT); if sym <> nil then begin Op := BuildAsOpCode(False, sym, 'Main', -1); if Op <> nil then begin try Result := Op.Execute(DefaultOpRT); if UsedCache then begin LockObject(OpCache); OpCache.Add(ExpressionText, Op); UnLockObject(OpCache); end else DisposeObject(Op); except Result := NULL; end; end; DisposeObject(sym); end; end; end; {$ENDREGION 'internal imp'} function OpCache: THashObjectList; begin if OpCache___ = nil then OpCache___ := THashObjectList.CustomCreate(True, 1024 * 1024); Result := OpCache___; end; procedure CleanOpCache(); begin LockObject(OpCache); OpCache.Clear; UnLockObject(OpCache); end; type TExpression_ConstVL = class VL: THashVariantList; procedure GetValue(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant); end; procedure TExpression_ConstVL.GetValue(const Decl: SystemString; var ValType: TExpressionDeclType; var Value: Variant); begin if (VL <> nil) and (VL.Exists(Decl)) then begin Value := VL[Decl]; ValType := VariantToExpressionDeclType(Value); end end; function IsSymbolVectorExpression(ExpressionText: SystemString; TextStyle: TTextStyle; SpecialAsciiToken: TListPascalString): Boolean; var t: TTextParsing; L: TPascalStringList; begin Result := False; t := TTextParsing.Create(umlDeleteChar(ExpressionText, #13#10#32#9), TextStyle, SpecialAsciiToken, SpacerSymbol.v); L := TPascalStringList.Create; if t.FillSymbolVector(L) then begin if (L.Count = 2) and (L[1].L = 0) then Result := False else Result := L.Count > 1; end; DisposeObject(t); DisposeObject(L); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): Variant; var v: TExpressionValueVector; sym: TSymbolExpression; Op: TOpCode; i: Integer; exp_const_vl: TExpression_ConstVL; begin if IsSymbolVectorExpression(ExpressionText, TextStyle, SpecialAsciiToken) then begin v := EvaluateExpressionVector(DebugMode, UsedCache, SpecialAsciiToken, TextStyle, ExpressionText, opRT, const_vl); Result := ExpressionValueVectorToStr(v).Text; SetLength(v, 0); Exit; end; Op := nil; if (UsedCache) and (const_vl = nil) then begin LockObject(OpCache); Op := TOpCode(OpCache[ExpressionText]); UnLockObject(OpCache); end; if (Op <> nil) and (UsedCache) and (const_vl = nil) then begin try Result := Op.Execute(opRT); except Result := NULL; end; end else begin exp_const_vl := TExpression_ConstVL.Create; exp_const_vl.VL := const_vl; Result := NULL; sym := ParseTextExpressionAsSymbol(SpecialAsciiToken, TextStyle, '', ExpressionText, {$IFDEF FPC}@{$ENDIF FPC}exp_const_vl.GetValue, opRT); if sym <> nil then begin Op := BuildAsOpCode(DebugMode, sym, 'Main', -1); if Op <> nil then begin try Result := Op.Execute(opRT); if (UsedCache) and (const_vl = nil) then begin LockObject(OpCache); OpCache.Add(ExpressionText, Op); UnLockObject(OpCache); end else DisposeObject(Op); except Result := NULL; end; end; DisposeObject(sym); end else begin end; DisposeObject(exp_const_vl); end; end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, DebugMode, TextStyle, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, nil, False, tsPascal, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(UsedCache, nil, False, tsPascal, ExpressionText, DefaultOpRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(UsedCache, nil, False, TextStyle, ExpressionText, DefaultOpRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, nil, False, TextStyle, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, DebugMode, tsPascal, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, False, tsPascal, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, DebugMode, tsPascal, ExpressionText, DefaultOpRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, False, tsPascal, ExpressionText, DefaultOpRT, nil); end; function EvaluateExpressionValue(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, False, TextStyle, ExpressionText, opRT, nil); end; function EvaluateExpressionValue(ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(True, ExpressionText, opRT); end; function EvaluateExpressionValue(ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(True, ExpressionText); end; function EvaluateExpressionValue(TextStyle: TTextStyle; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(True, nil, False, TextStyle, ExpressionText, DefaultOpRT); end; function EvaluateExpressionValue(TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(True, nil, False, TextStyle, ExpressionText, opRT); end; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(True, SpecialAsciiToken, DebugMode, tsPascal, ExpressionText, opRT); end; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(True, SpecialAsciiToken, False, tsPascal, ExpressionText, opRT); end; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; DebugMode: Boolean; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(True, SpecialAsciiToken, DebugMode, tsPascal, ExpressionText, DefaultOpRT); end; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; ExpressionText: SystemString): Variant; begin Result := EvaluateExpressionValue(True, SpecialAsciiToken, False, tsPascal, ExpressionText, DefaultOpRT); end; function EvaluateExpressionValue(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime): Variant; begin Result := EvaluateExpressionValue(True, SpecialAsciiToken, False, TextStyle, ExpressionText, opRT); end; function EvaluateExpressionVector(DebugMode, UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; var t: TTextParsing; L: TPascalStringList; i: Integer; begin SetLength(Result, 0); if ExpressionText = '' then Exit; t := TTextParsing.Create(ExpressionText, TextStyle, SpecialAsciiToken, SpacerSymbol.v); L := TPascalStringList.Create; if t.FillSymbolVector(L) then begin SetLength(Result, L.Count); for i := 0 to L.Count - 1 do begin try Result[i] := EvaluateExpressionValue(UsedCache, SpecialAsciiToken, DebugMode, TextStyle, L[i], opRT, const_vl); except Result[i] := NULL; end; end; end; DisposeObject(L); DisposeObject(t); end; function EvaluateExpressionVector(UsedCache: Boolean; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; begin Result := EvaluateExpressionVector(False, UsedCache, SpecialAsciiToken, TextStyle, ExpressionText, opRT, const_vl); end; function EvaluateExpressionVector(SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; begin Result := EvaluateExpressionVector(False, False, SpecialAsciiToken, TextStyle, ExpressionText, opRT, const_vl); end; function EvaluateExpressionVector(ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueVector; begin Result := EvaluateExpressionVector(nil, tsPascal, ExpressionText, opRT, const_vl); end; function EvaluateExpressionVector(ExpressionText: SystemString; const_vl: THashVariantList): TExpressionValueVector; begin Result := EvaluateExpressionVector(ExpressionText, DefaultOpRT, const_vl); end; function EvaluateExpressionVector(ExpressionText: SystemString; TextStyle: TTextStyle): TExpressionValueVector; begin Result := EvaluateExpressionVector(nil, TextStyle, ExpressionText, nil, nil); end; function EvaluateExpressionVector(ExpressionText: SystemString): TExpressionValueVector; begin Result := EvaluateExpressionVector(ExpressionText, nil); end; function EvaluateExpressionMatrix(W, H: Integer; SpecialAsciiToken: TListPascalString; TextStyle: TTextStyle; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueMatrix; overload; var buff: TExpressionValueVector; i, j, k: Integer; begin SetLength(Result, 0, 0); buff := EvaluateExpressionVector(SpecialAsciiToken, TextStyle, ExpressionText, opRT, const_vl); if length(buff) >= W * H then begin SetLength(Result, H, W); k := 0; for j := 0 to H - 1 do for i := 0 to W - 1 do begin Result[j, i] := buff[k]; inc(k); end; end; end; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; opRT: TOpCustomRunTime; const_vl: THashVariantList): TExpressionValueMatrix; begin Result := EvaluateExpressionMatrix(W, H, nil, tsPascal, ExpressionText, opRT, const_vl); end; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; const_vl: THashVariantList): TExpressionValueMatrix; begin Result := EvaluateExpressionMatrix(W, H, ExpressionText, DefaultOpRT, const_vl); end; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString; TextStyle: TTextStyle): TExpressionValueMatrix; begin Result := EvaluateExpressionMatrix(W, H, nil, TextStyle, ExpressionText, nil, nil); end; function EvaluateExpressionMatrix(W, H: Integer; ExpressionText: SystemString): TExpressionValueMatrix; begin Result := EvaluateExpressionMatrix(W, H, ExpressionText, DefaultOpRT, nil); end; function EStr(s: U_String): U_String; begin Result := umlVarToStr(EvaluateExpressionValue(s), False); end; function EStrToInt(s: U_String; default: Integer): Integer; var v: Variant; begin v := EvaluateExpressionValue(s); if VarIsNumeric(v) then Result := v else Result := default; end; function EStrToInt64(s: U_String; default: Int64): Int64; var v: Variant; begin v := EvaluateExpressionValue(s); if VarIsNumeric(v) then Result := v else Result := default; end; function EStrToFloat(s: U_String; default: Double): Double; begin Result := EStrToDouble(s, default); end; function EStrToSingle(s: U_String; default: Single): Single; var v: Variant; begin v := EvaluateExpressionValue(s); if VarIsNumeric(v) then Result := v else Result := default; end; function EStrToDouble(s: U_String; default: Double): Double; var v: Variant; begin v := EvaluateExpressionValue(s); if VarIsNumeric(v) then Result := v else Result := default; end; function ExpressionValueVectorToStr(v: TExpressionValueVector): TPascalString; var i: Integer; begin Result := ''; for i := 0 to length(v) - 1 do begin if VarIsNull(v[i]) then Result.Append('error, ') else if VarIsStr(v[i]) then Result.Append(VarToStr(v[i]) + ', ') else Result.Append(VarToStr(v[i]) + ', '); end; Result := Result.TrimChar(', '); end; procedure DoStatusE(v: TExpressionValueVector); var i: Integer; begin for i := 0 to length(v) - 1 do DoStatusNoLn(umlVarToStr(v[i]) + ' '); DoStatusNoLn; end; procedure DoStatusE(v: TExpressionValueMatrix); var i: Integer; begin for i := 0 to high(v) do DoStatusE(v[i]); end; procedure EvaluateExpressionVectorAndMatrix_test_; var VL: THashVariantList; buff: TExpressionValueVector; EM: TExpressionValueMatrix; begin VL := THashVariantList.Create; VL['a1'] := 10; VL['a2'] := 20; VL['a3'] := 30; buff := EvaluateExpressionVector('a1,a2,a3,a1*a2,a1+a2+a3,min(a1,a2,a3)*a3', VL); EM := EvaluateExpressionMatrix(3, 2, 'a1,a2,a3,a1*a2,a1+a2+a3,min(a1,a2,a3)*a3', VL); DisposeObject(VL); SetLength(buff, 0); SetLength(EM, 0, 0); end; initialization OpCache___ := nil; finalization DisposeObject(OpCache___); end.
program MCAmiga; {$mode objfpc}{$H+} uses {$ifdef HASAMIGA} Exec, workbench, icon, AppWindowUnit, {$endif} {$ifdef RELEASE} Versioncheck, {$endif} Types, SysUtils, Video, mouse, keyboard, FileListUnit, dialogunit, EventUnit, archiveunit, {$if defined(Amiga68k) or defined(MorphOS) or defined(AROS)} xad, xadarchive, {$endif} toolsunit; var Src: TFileList; Dest: TFileList; Left, Right: TFileList; ViewerLink: string = ''; AltViewerLink: string = ''; EditLink: string = ''; AltEditLink: string = ''; LeftDefaultPath: string = ''; RightDefaultPath: string = ''; procedure SwapSrcDest; var Temp: TFileList; begin Temp := Dest; Dest := Src; Src := Temp; Src.IsActive := True; Dest.IsActive := False; end; procedure MouseEvent(Me: TMouseEvent); var P: TPoint; begin if me.Action = MouseActionDown then begin P := Point(Me.x, Me.y); if Left.PanelRect.Contains(P) then begin if Right.IsActive then SwapSrcDest; Left.MouseEvent(Me); end else if Right.PanelRect.Contains(P) then begin if Left.IsActive then SwapSrcDest; Right.MouseEvent(Me); end; end else Src.MouseEvent(Me); end; procedure KeyEvent(Ev: TKeyEvent); var st: Byte; begin st := GetKeyEventShiftState(Ev); case TranslateKeyEvent(Ev) and $ffff of $0F09: SwapSrcDest; // TAB -> change Focus to other window $0008: Src.GoToParent; // Backspace -> Parent $1C0D, $000D: Src.EnterPressed(st and kbShift <> 0); // return -> Enter Dir/Assign/Drive kbdUp, $38: begin if (st and kbShift) <> 0 then Src.SelectActiveEntry(False); Src.ActiveElement := Src.ActiveElement - 1; end; // cursor up -> Move around kbdDown, $32: if (st and kbShift) <> 0 then Src.SelectActiveEntry else Src.ActiveElement := Src.ActiveElement + 1; // cursor down -> Move around kbdPgUp, $39, $8D00: Src.ActiveElement := Src.ActiveElement - 10; // pg up -> Move around kbdPgDn, $33, $9100: Src.ActiveElement := Src.ActiveElement + 10; // pg down -> Move around kbdHome, $37, $7300: Src.ActiveElement := 0; // Home -> Move around kbdEnd, $31, $7400: Src.ActiveElement := MaxInt; // end -> Move around $1312, $1300: Src.Update(True); // Ctrl + R Alt + R -> Reload $180F, $1800: Dest.CurrentPath := Src.CurrentPath; // Ctrl + O Alt + O -> copy path to dest $2004, $2000: Src.CurrentPath := ''; // Ctrl + D Alt + D -> back to drives/Assign $1F13: Src.SearchList; // Crtl + s -> jump mode kbdInsert, $23, $30, $20: begin if ((st and kbShift) <> 0) and (TranslateKeyEvent(Ev) and $ffff = $20) then begin Src.ScanSize; Left.Update(False); Right.Update(False); end else Src.SelectActiveEntry; // Insert, #, 0, Space -> Select file end; $002B: Src.SelectByPattern(True); // + -> Select files by pattern $002D: Src.SelectByPattern(False); // - -> Deselect files by pattern kbdF10, $011B: begin // F10, ESC -> Quit if AskQuestion('Quit Program') then begin Terminate; Exit; end; Left.Update(False); Right.Update(False); end; kbdF3: begin // F3 -> View if st and kbShift <> 0 then Src.ViewFile(AltViewerLink) else Src.ViewFile(ViewerLink); end; kbdF4: begin // F4 -> Edit if st and kbShift <> 0 then Src.EditFile(AltEditLink) else Src.EditFile(EditLink); end; kbdF5: Src.CopyFiles; // F5 -> Copy/CopyAs kbdF6: begin // F6 -> Move/Rename if st and kbShift <> 0 then Src.Rename() else Src.MoveFiles; end; kbdF7: Src.MakeDir(); // F7 -> MakeDir kbdF8, kbdDelete: Src.DeleteSelected(); // F8 -> Delete kbdF2: begin // F2 if ((st and kbAlt) <> 0) or ((st and kbCtrl) <> 0) then begin Right.CurrentPath := ''; end else begin ShowTools(Src, Dest); Left.Update(False); Right.Update(False); end; end; kbdF1: begin // F1 -> Help if ((st and kbAlt) <> 0) or ((st and kbCtrl) <> 0) then begin Left.CurrentPath := ''; end else begin ShowHelp; Left.Update(False); Right.Update(False); end; end {$ifndef RELEASE} else if (ev and $FFFF) <> 0 then writeln('Key: $' + HexStr(TranslateKeyEvent(Ev), 4)); {$endif} end; end; var MySize: TSize; procedure ResizeEvent(NewWidth, NewHeight: Integer); var Mode: TVideoMode; begin if (NewWidth > 0) and (NewHeight > 0) and ((NewWidth <> MySize.cx) or (NewHeight <> MySize.cy)) then begin Mode.Col := 0; Video.GetVideoMode(Mode); Mode.Col := NewWidth; Mode.Row := NewHeight; Video.SetVideoMode(Mode); MySize.cx := NewWidth; MySize.cy := NewHeight; ClearScreen; Left.Resize(Rect(0, 0, (ScreenWidth div 2) - 1, ScreenHeight - 1)); Right.Resize(Rect((ScreenWidth div 2), 0, ScreenWidth - 1, ScreenHeight - 1)); end; end; procedure IdleEvent; begin Src.IdleEvent; end; procedure DropEvent(Path, Name: string; MousePos: TPoint); begin if Path = '' then Exit; if PtInRect(Left.PanelRect, MousePos) then begin Left.CurrentPath := Path; if Name <> '' then Left.ActivateFile(Name); end else if PtInRect(Right.PanelRect, MousePos) then begin Right.CurrentPath := Path; if Name <> '' then Right.ActivateFile(Name); end; end; {$ifdef HASAMIGA} function GetStrToolType(DObj: PDiskObject; Entry: string; Default: string): string; var Res: PChar; {$ifdef AROS} TT: PPchar; s: string; {$endif} begin Result := Default; if not assigned(Dobj) then Exit; if not Assigned(Dobj^.do_Tooltypes) then Exit; {$ifdef AROS} TT := Dobj^.do_Tooltypes; while Assigned(TT^) do begin s := TT^; if (Pos('=', s) > 0) and (Trim(Copy(s, 1, Pos('=', s) - 1)) = Entry) then begin Result := copy(s, Pos('=', s) + 1, Length(s)); Break; end; Inc(TT); end; {$else} Res := FindToolType(Dobj^.do_Tooltypes, PChar(Entry)); if Assigned(Res) then Result := Res; {$endif} end; {$endif} procedure GetSettings; {$ifdef HASAMIGA} var DObj: PDiskObject; {$endif} begin {$ifdef HASAMIGA} DObj := GetDiskObject(PChar(ParamStr(0))); if Assigned(DObj) then begin // Viewer ViewerLink := GetStrToolType(DObj, 'VIEWER', ViewerLink); AltViewerLink := GetStrToolType(DObj, 'VIEWER2', AltViewerLink); // Editor EditLink := GetStrToolType(DObj, 'EDITOR', EditLink); AltEditLink := GetStrToolType(DObj, 'EDITOR2', AltEditLink); // Defaults but with th LeftDefaultPath := GetStrToolType(DObj, 'LEFT', LeftDefaultPath); RightDefaultPath := GetStrToolType(DObj, 'RIGHT', RightDefaultPath); // WithDevices WithDevices := GetStrToolType(DObj, 'WITHDEVICES', '0') <> '0'; FreeDiskObject(DObj); end; {$endif} end; procedure StartMe; var Mode: TVideoMode; begin LockScreenUpdate; {$ifdef HASAMIGA} LeftDefaultPath := 'sys:'; RightDefaultPath := 'ram:'; {$endif} {$ifdef LINUX} LeftDefaultPath := '/'; RightDefaultPath := '/usr/bin'; {$endif} GetSettings; OnKeyPress := @KeyEvent; OnMouseEvent := @MouseEvent; OnResize := @ResizeEvent; OnIdle := @IdleEvent; {$ifdef HASAMIGA} OnDropItem := @DropEvent; {$endif} Left := TFileList.Create(Rect(0, 0, (ScreenWidth div 2) - 1, ScreenHeight - 1)); Right := TFileList.Create(Rect((ScreenWidth div 2), 0, ScreenWidth - 1, ScreenHeight - 1)); Left.OtherSide := Right; Right.OtherSide := Left; Src := Left; Dest := Right; Mode.Col := 0; Video.GetVideoMode(Mode); Video.SetVideoMode(Mode); Left.CurrentPath := LeftDefaultPath; Right.CurrentPath := RightDefaultPath; UnlockScreenUpdate; UpdateScreen(True); Right.ActiveElement := 0; Left.IsActive := True; {$ifdef RELEASE} CreateVersion; {$endif} {$ifdef HASAMIGA} MakeAppWindow; {$endif} RunApp; {$ifdef HASAMIGA} DestroyAppWindow; {$endif} Left.Free; Right.Free; end; begin {$ifdef RELEASE} DoVersionInformation; {$endif} InitVideo; InitMouse; InitKeyboard; {$ifdef HASAMIGA} Video.SetWindowTitle('MyCommander Amiga ' + NumVERSION, Copy(VERSION, 6, 12)); {$endif} StartMe; DoneKeyboard; DoneMouse; DoneVideo; end.
unit uSkeletonColliders; interface uses System.Classes, System.SysUtils, GLVectorGeometry, GLApplicationFileIO, GLVectorFileObjects; const cSkeletonColliderID = 'SMCF'; cSkeletonColliderVersion = 1; type TSCDParamRange = 0..2; TSkeletonColliderType = (sctSphere, sctCapsule, sctBox); TSkeletonColliderHeader = record ID : array[0..3] of char; Version, ColliderCount : Integer; end; TSkeletonColliderData = record Collider : TSkeletonColliderType; Bone1, Bone2 : Integer; Params : array[TSCDParamRange] of Single; Matrix : TMatrix; end; TSkeletonColliders = class; TSkeletonCollider = class private FData : TSkeletonColliderData; function GetMatrix : TMatrix; function GetBone1 : Integer; function GetBone2 : Integer; procedure SetMatrix(const Value : TMatrix); procedure SetBone1(const Value : Integer); procedure SetBone2(const Value : Integer); protected function GetParam(Index : TSCDParamRange) : Single; function GetCollider : TSkeletonColliderType; procedure SetParam(Index : TSCDParamRange; const Value : Single); procedure SetCollider(const Value : TSkeletonColliderType); public constructor Create; virtual; constructor CreateOwned(Owner : TSkeletonColliders); procedure LoadFromStream(aStream : TStream); procedure SaveToStream(aStream : TStream); property Bone1 : Integer read GetBone1 write SetBone1; property Bone2 : Integer read GetBone2 write SetBone2; property Matrix : TMatrix read GetMatrix write SetMatrix; end; TSkeletonColliderSphere = class(TSkeletonCollider) private function GetRadius : Single; procedure SetRadius(const Value : Single); public constructor Create; override; property Radius : Single read GetRadius write SetRadius; end; TSkeletonColliderCapsule = class(TSkeletonCollider) private function GetRadius : Single; function GetHeight : Single; procedure SetRadius(const Value : Single); procedure SetHeight(const Value : Single); public constructor Create; override; property Radius : Single read GetRadius write SetRadius; property Height : Single read GetHeight write SetHeight; end; TSkeletonColliderBox = class(TSkeletonCollider) private function GetWidth : Single; function GetHeight : Single; function GetDepth : Single; procedure SetWidth(const Value : Single); procedure SetHeight(const Value : Single); procedure SetDepth(const Value : Single); public constructor Create; override; property Width : Single read GetWidth write SetWidth; property Height : Single read GetHeight write SetHeight; property Depth : Single read GetDepth write SetDepth; end; TSkeletonColliders = class (TList) private FHeader : TSkeletonColliderHeader; FSkeleton : TGLSkeleton; function GetItem(Index : Integer) : TSkeletonCollider; public constructor Create; function Remove(item: TSkeletonCollider) : Integer; procedure Delete(index : Integer); procedure SaveToStream(aStream : TStream); procedure LoadFromStream(aStream : TStream); procedure SaveToFile(FileName : String); procedure LoadFromFile(FileName : String); property Skeleton : TGLSkeleton read FSkeleton write FSkeleton; property Items[Index : Integer] : TSkeletonCollider read GetItem; default; end; //========================================================================= implementation //========================================================================= // //----- TSkeletonCollider // constructor TSkeletonCollider.Create; begin FData.Bone1:=-1; FData.Bone2:=-1; FData.Params[0]:=0; FData.Params[1]:=0; FData.Params[2]:=0; FData.Matrix:=IdentityHMGMatrix; end; constructor TSkeletonCollider.CreateOwned(Owner: TSkeletonColliders); begin Create; Owner.Add(Self); end; procedure TSkeletonCollider.LoadFromStream(aStream: TStream); begin aStream.Read(FData, SizeOf(TSkeletonColliderData)); end; procedure TSkeletonCollider.SaveToStream(aStream: TStream); begin aStream.Write(FData, SizeOf(TSkeletonColliderData)); end; function TSkeletonCollider.GetBone1: Integer; begin Result:=FData.Bone1; end; function TSkeletonCollider.GetBone2: Integer; begin Result:=FData.Bone2; end; function TSkeletonCollider.GetCollider: TSkeletonColliderType; begin Result:=FData.Collider; end; function TSkeletonCollider.GetMatrix: TMatrix; begin Result:=FData.Matrix; end; function TSkeletonCollider.GetParam(Index: TSCDParamRange): Single; begin Result:=FData.Params[Index]; end; procedure TSkeletonCollider.SetBone1(const Value: Integer); begin FData.Bone1:=Value; end; procedure TSkeletonCollider.SetBone2(const Value: Integer); begin FData.Bone2:=Value; end; procedure TSkeletonCollider.SetCollider(const Value: TSkeletonColliderType); begin FData.Collider:=Value; end; procedure TSkeletonCollider.SetMatrix(const Value: TMatrix); begin FData.Matrix:=Value; end; procedure TSkeletonCollider.SetParam(Index: TSCDParamRange; const Value: Single); begin FData.Params[Index]:=Value; end; { TSkeletonColliderSphere } constructor TSkeletonColliderSphere.Create; begin inherited; FData.Collider:=sctSphere; end; function TSkeletonColliderSphere.GetRadius: Single; begin Result:=GetParam(0); end; procedure TSkeletonColliderSphere.SetRadius(const Value: Single); begin SetParam(0,Value); end; { TSkeletonColliderCapsule } function TSkeletonColliderCapsule.GetRadius: Single; begin Result:=GetParam(0); end; function TSkeletonColliderCapsule.GetHeight: Single; begin Result:=GetParam(1); end; procedure TSkeletonColliderCapsule.SetRadius(const Value: Single); begin SetParam(0,Value); end; procedure TSkeletonColliderCapsule.SetHeight(const Value: Single); begin SetParam(1,Value); end; constructor TSkeletonColliderCapsule.Create; begin inherited; FData.Collider:=sctCapsule; end; { TSkeletonColliderBox } function TSkeletonColliderBox.GetWidth: Single; begin Result:=GetParam(0); end; function TSkeletonColliderBox.GetHeight: Single; begin Result:=GetParam(1); end; function TSkeletonColliderBox.GetDepth: Single; begin Result:=GetParam(2); end; procedure TSkeletonColliderBox.SetWidth(const Value: Single); begin SetParam(0,Value); end; procedure TSkeletonColliderBox.SetHeight(const Value: Single); begin SetParam(1,Value); end; procedure TSkeletonColliderBox.SetDepth(const Value: Single); begin SetParam(2,Value); end; constructor TSkeletonColliderBox.Create; begin inherited; FData.Collider:=sctBox; end; { TSkeletonColliders } constructor TSkeletonColliders.Create; begin inherited; FHeader.ID:=cSkeletonColliderID; FHeader.Version:=cSkeletonColliderVersion; end; procedure TSkeletonColliders.Delete(index: Integer); begin GetItem(index).Free; inherited Delete(index); end; function TSkeletonColliders.Remove(item: TSkeletonCollider) : Integer; begin Result:=(inherited Remove(item)); item.Free; end; function TSkeletonColliders.GetItem(Index: Integer): TSkeletonCollider; begin Result:=TSkeletonCollider(Get(Index)); end; procedure TSkeletonColliders.LoadFromFile(FileName: String); var Stream : TStream; begin Stream:=CreateFileStream(FileName); LoadFromStream(Stream); Stream.Free; end; procedure TSkeletonColliders.LoadFromStream(aStream: TStream); var i : Integer; p : Int64; sct : TSkeletonColliderType; begin Clear; aStream.Read(FHeader,SizeOf(TSkeletonColliderHeader)); if FHeader.ID<>cSkeletonColliderID then Exception.Create('File ID mismatch ['+FHeader.ID+'].'); // This version check will need to be updated if the versions // change to support older formats. if FHeader.Version<>cSkeletonColliderVersion then Exception.Create('File version mismatch ['+IntToStr(FHeader.Version)+']. Supported version is '+IntToStr(cSkeletonColliderVersion)+'.'); for i:=0 to FHeader.ColliderCount-1 do begin p:=aStream.Position; aStream.Read(sct,SizeOf(TSkeletonColliderType)); aStream.Position:=p; case sct of sctSphere : TSkeletonColliderSphere.CreateOwned(self); sctCapsule : TSkeletonColliderCapsule.CreateOwned(self); sctBox : TSkeletonColliderBox.CreateOwned(self); end; Items[i].LoadFromStream(aStream); end; end; procedure TSkeletonColliders.SaveToFile(FileName: String); var Stream : TStream; begin Stream:=CreateFileStream(FileName,fmCreate); SaveToStream(Stream); Stream.Free; end; procedure TSkeletonColliders.SaveToStream(aStream: TStream); var i : integer; begin FHeader.ColliderCount:=Count; aStream.Write(FHeader,SizeOf(TSkeletonColliderHeader)); for i:=0 to Count-1 do Items[i].SaveToStream(aStream); end; end.
unit EmpresaEnderecoController; interface uses System.Generics.Collections, // Aurelius.Engine.ObjectManager, Aurelius.Criteria.Base, Aurelius.Criteria.Expression, Aurelius.Criteria.Linq, Aurelius.Criteria.Projections, // EmpresaEndereco; type TEmpresaEnderecoController = class private class var FManager: TObjectManager; public class procedure Save(AEmpresaEndereco: TEmpresaEndereco); class function Update(AEmpresaEndereco: TEmpresaEndereco): Boolean; class function Delete(AEmpresaEndereco: TEmpresaEndereco): Boolean; class function FindObject(AFilter: TCustomCriterion): TEmpresaEndereco; class function FindObjectList(AFilter: TCustomCriterion): TObjectList<TEmpresaEndereco>; class function FindCriteria(AFilter: TCustomCriterion): TCriteria; end; implementation uses ConnectionModule; class procedure TEmpresaEnderecoController.Save(AEmpresaEndereco: TEmpresaEndereco); begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.Save(AEmpresaEndereco); finally FManager.Free; end; end; class function TEmpresaEnderecoController.Update(AEmpresaEndereco: TEmpresaEndereco): Boolean; begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.Update(AEmpresaEndereco); Result := True; finally FManager.Free; end; end; class function TEmpresaEnderecoController.Delete(AEmpresaEndereco: TEmpresaEndereco): Boolean; begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.Remove(AEmpresaEndereco); Result := True; finally FManager.Free; end; end; class function TEmpresaEnderecoController.FindObject(AFilter: TCustomCriterion): TEmpresaEndereco; begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.OwnsObjects := False; Result := FManager.CreateCriteria<TEmpresaEndereco>.Add(AFilter).UniqueResult; finally FManager.Free; end; end; class function TEmpresaEnderecoController.FindObjectList(AFilter: TCustomCriterion): TObjectList<TEmpresaEndereco>; begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.OwnsObjects := False; Result := FManager.CreateCriteria<TEmpresaEndereco>.Add(AFilter).List; finally FManager.Free; end; end; class function TEmpresaEnderecoController.FindCriteria(AFilter: TCustomCriterion): TCriteria; begin FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection); try FManager.OwnsObjects := False; Result := FManager.CreateCriteria<TEmpresaEndereco>.Add(AFilter); finally FManager.Free; end; end; end.
unit uFrmImportInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Grids, siComp; type TFrmImportInfo = class(TForm) Panel1: TPanel; Bevel1: TBevel; btnClose: TBitBtn; sgridInfo: TStringGrid; siLang: TsiLang; Splitter1: TSplitter; pnlHistory: TPanel; lbCashRegister: TLabel; lboxCashOpen: TListBox; Panel2: TPanel; shpOK: TShape; Label1: TLabel; Shape1: TShape; Label2: TLabel; Shape2: TShape; Label3: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCloseClick(Sender: TObject); procedure sgridInfoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure sgridInfoSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); private sItems, sDate, sFile, sCashOpen : String; function GetStatus(fDate : TDateTime):String; procedure LoadSystemInfo; procedure LoadOpenLog(fCashRegister, fFileName : String); public procedure Start; end; implementation uses uMainConf, uDMGlobal, uPOSServerConsts; {$R *.dfm} procedure TFrmImportInfo.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmImportInfo.btnCloseClick(Sender: TObject); begin Close; end; procedure TFrmImportInfo.Start; begin case DMGlobal.IDLanguage of LANG_ENGLISH : begin sItems := 'Items'; sDate := 'Last import date'; sFile := 'Last import file'; sCashOpen := 'Open CashRegister (%S)'; end; LANG_PORTUGUESE : begin sItems := 'Arquivos'; sDate := 'Última importação'; sFile := 'Último arquivo'; sCashOpen := 'Arquivo(s) de caixa aberto (%S)'; end; LANG_SPANISH : begin sItems := 'Items'; sDate := 'Last import date'; sFile := 'Last import file'; sCashOpen := 'Open CashRegister (%S)'; end; end; LoadSystemInfo; pnlHistory.Visible := (FrmMain.fServerConnection.ConnectType = CON_TYPE_SERVER); ShowModal; end; procedure TFrmImportInfo.LoadSystemInfo; var sPDVList : TStringList; sPDV : TStringList; i, iIDCashReg : integer; begin sPDVList := TStringList.Create; try sPDV := TStringList.Create; try FrmMain.fIniConfig.ReadSection(POS_PDV_KEY, sPDVList); sgridInfo.CellRect(0,1); sgridInfo.RowCount := sPDVList.Count + 2; sgridInfo.Cells[0,0] := ''; sgridInfo.Cells[1,0] := sItems; sgridInfo.Cells[2,0] := sDate; sgridInfo.Cells[3,0] := sFile; sgridInfo.Cells[0,1] := GetStatus(FrmMain.fIniConfig.ReadDateTime('ServerSchedule','SuccedDate', Now-7)); sgridInfo.Cells[1,1] := 'Global Files'; sgridInfo.Cells[2,1] := FrmMain.fIniConfig.ReadString('ServerSchedule','SuccedDate', ''); sgridInfo.Cells[3,1] := ' --- no file ---'; for i:=0 to sPDVList.Count-1 do begin iIDCashReg := LongInt(FrmMain.fIniConfig.ReadInteger(POS_PDV_KEY, sPDVList[i], 0)); sgridInfo.Cells[0,i+2] := GetStatus(FrmMain.fIniConfig.ReadDateTime(IntToStr(iIDCashReg), POS_LAST_IMPORT_DATE, Now-7)); sgridInfo.Cells[1,i+2] := sPDVList[i]; sgridInfo.Cells[2,i+2] := FrmMain.fIniConfig.ReadString(IntToStr(iIDCashReg), POS_LAST_IMPORT_DATE, ''); sgridInfo.Cells[3,i+2] := FrmMain.fIniConfig.ReadString(IntToStr(iIDCashReg), POS_PDV_KEY_LAST_FILE, ''); end; finally FreeAndNil(sPDV); end; finally FreeAndNil(sPDVList); end; end; procedure TFrmImportInfo.sgridInfoDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var Text : String; begin if ACol = 0 then begin Text := sgridInfo.Cells[ACol, ARow]; if Text = '1' then begin sgridInfo.Canvas.Brush.Color := clGreen; sgridInfo.Canvas.FillRect(Rect); end else if Text = '2' then begin sgridInfo.Canvas.Brush.Color := $004080FF; sgridInfo.Canvas.FillRect(Rect); end else if Text = '3' then begin sgridInfo.Canvas.Brush.Color := clRed; sgridInfo.Canvas.FillRect(Rect); end; end; end; function TFrmImportInfo.GetStatus(fDate: TDateTime): String; begin if (Trunc(Now) - Trunc(fDate)) <= 3 then Result := '1' else if (Trunc(Now) - Trunc(fDate)) <= 5 then Result := '2' else Result := '3'; end; procedure TFrmImportInfo.LoadOpenLog(fCashRegister, fFileName : String); var sFile : String; i : Integer; begin lboxCashOpen.Items.Clear; lbCashRegister.Caption := ''; if fFileName <> '' then begin sFile := Copy(fFileName, 0, 4); lbCashRegister.Caption := Format(sCashOpen, [fCashRegister]); if FrmMain.fPOSConfig.SectionExists(sFile) then begin FrmMain.fPOSConfig.ReadSection(sFile, lboxCashOpen.Items); for i := 0 to (lboxCashOpen.Count-1) do lboxCashOpen.Items.Strings[i] := sFile+'-'+lboxCashOpen.Items.Strings[i]+'.ven'; end; end; end; procedure TFrmImportInfo.sgridInfoSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if ARow <> 1 then LoadOpenLog(sgridInfo.Cells[1, ARow], sgridInfo.Cells[3, ARow]); end; end.
unit UntLibrary; interface function IsEmpty(value: string): boolean; function IIf(condition: boolean; trueValue, falseValue: string): string; overload; function IIf(condition: boolean; trueValue, falseValue: integer): integer; overload; implementation uses SysUtils; function IsEmpty(value: string): boolean; begin result := Trim(value) = ''; end; function IsPopulated(value: string): boolean; begin result := not IsEmpty(value); end; function IIf(condition: boolean; trueValue, falseValue: string): string; begin if condition then result := trueValue else result := falseValue; end; function IIf(condition: boolean; trueValue, falseValue: integer): integer; begin if condition then result := trueValue else result := falseValue; end; end.
unit OTFEStrongDiskPasswordEntry_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask; type TOTFEStrongDiskPasswordEntry_F = class(TForm) Label1: TLabel; mePassword: TMaskEdit; Label2: TLabel; cbDrives: TComboBox; pbOK: TButton; pbCancel: TButton; ckElectronicKey: TCheckBox; edKeyfile: TEdit; pbBrowse: TButton; Label3: TLabel; ckAutostart: TCheckBox; OpenDialog1: TOpenDialog; procedure pbBrowseClick(Sender: TObject); procedure FormCreate(Sender: TObject); private FDefaultDrive: char; procedure SetDrivesAllowed(drvs: string); procedure SetDrive(dfltDrv: char); function GetDrive(): char; public procedure ClearEnteredPassword(); published property Drive: char read GetDrive write SetDrive; property DrivesAllowed: string write SetDrivesAllowed; end; implementation {$R *.DFM} uses SDUGeneral; // Presumably this should be enough to overwrite the relevant strings in memory? procedure TOTFEStrongDiskPasswordEntry_F.ClearEnteredPassword(); var junkString : string; i : integer; begin // Create a string 1024 chars long... (assumes that user won't try to enter // a password more than this length; anything more than 40 is probably // overkill anyway) junkString := ''; randomize; for i:=0 to 1024 do begin junkString := junkString + chr(random(255)); end; // ...overwrite any passwords entered... edKeyfile.text := junkString; mePassword.text := junkString; // ...and then reset to a zero length string, just to be tidy. edKeyfile.text := ''; mePassword.text := ''; end; procedure TOTFEStrongDiskPasswordEntry_F.SetDrive(dfltDrv: char); begin FDefaultDrive:= dfltDrv; dfltDrv := (uppercase(dfltDrv))[1]; // This will ensure that we either have the default drive selected, or the // first drive if cbDrives.items.IndexOf(dfltDrv+':')>-1 then begin cbDrives.itemindex := cbDrives.items.IndexOf(dfltDrv+':'); end else begin cbDrives.itemindex := 0; end; end; function TOTFEStrongDiskPasswordEntry_F.GetDrive(): char; begin if cbDrives.items.count<1 then begin Result := #0 end else begin Result := cbDrives.text[1]; end; end; procedure TOTFEStrongDiskPasswordEntry_F.SetDrivesAllowed(drvs: string); var i: integer; begin // Setup the drives the user is allowed to select for i:=1 to length(drvs) do begin cbDrives.items.Add(drvs[i]+':'); end; cbDrives.sorted := TRUE; SetDrive(FDefaultDrive); end; procedure TOTFEStrongDiskPasswordEntry_F.pbBrowseClick(Sender: TObject); begin SDUOpenSaveDialogSetup(OpenDialog1, edKeyfile.text); if OpenDialog1.execute then begin edKeyfile.text := OpenDialog1.Filename; end; end; procedure TOTFEStrongDiskPasswordEntry_F.FormCreate(Sender: TObject); begin edKeyfile.text := ''; mePassword.text := ''; end; END.
{Ingresar los elementos de un vector A y a continuación ingresar los de un vector B, si la cantidad de componentes ingresadas para cada uno de los vectores no es la misma indicar con un cartel y finalizar, de lo contrario calcular: a. La suma y la diferencia de los vectores. b. El vector que posee mas elementos} Program eje6; Type TV = array[1..100] of integer; Procedure LeerVectores(Var VA:TV; Var VB:TV; Var N,M:byte); Var i:byte; begin write('Ingrese la cantidad de numeros del vector A: ');readln(N); For i:= 1 to N do begin write('Ingrese un numero para el vector A: ');readln(VA[i]); end; writeln; write('Ingrese la canitdad de numeros del vector B: ');readln(M); For i:= 1 to M do begin write('Ingrese un numero para el vector B: ');readln(VB[i]); end; end; Procedure Compara(VA,VB:TV; N,M:byte); Var i:byte; SumA,SumB,Dif:integer; begin SumA:= 0; SumB:= 0; For i:= 1 to N do begin SumA:= SumA + VA[i]; end; For i:= 1 to M do begin SumB:= SumB + VB[i]; end; writeln; Dif:= SumA - SumB; writeln('La suma del vector A es: ',SumA); writeln('La suma del vector B es: ',SumB); writeln; writeln('La diferencia entre los vectores (A - B) es: ',Dif); writeln; If (N > M) then writeln('El vector A es el que posee mas cantidad de elementos ') Else writeln('El vector B es el que posee mas cantidad de elementos '); end; Var VA,VB:TV; N,M:byte; Begin LeerVectores(VA,VB,N,M); Compara(VA,VB,N,M); end.
unit ConvertDBaseToSQLUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ComCtrls, StdCtrls, ExtCtrls, xpButton, xpEdit, xpCheckBox, xpCombo, xpGroupBox, FileCtrl, DBTables, DB, ADODB, Menus, HotLog, SQLRemoteLogging, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdBaseComponent, IdComponent, IdServerIOHandler, IdSSL, IdSSLOpenSSL, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdMessage, IDText; type TfmConvertDBaseToSQL = class(TForm) gbx_DatabaseSettings: TxpGroupBox; Label1: TLabel; Label2: TLabel; cbxSQLDatabase: TxpComboBox; gbx_LoginParameters: TxpGroupBox; lb_SQLUser: TLabel; lb_SQLPassword: TLabel; cbUseSQLLogin: TxpCheckBox; edSQLUser: TxpEdit; edSQLPassword: TxpEdit; edSQLServer: TxpEdit; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; lbxTables: TListBox; Panel5: TPanel; ProgressBar: TProgressBar; pnlStatus: TPanel; cbxSelectTableFilter: TxpComboBox; cbxDBaseDatabase: TxpComboBox; Label3: TLabel; cbCreateTableStructure: TxpCheckBox; Panel6: TPanel; btnLoad: TSpeedButton; btnSave: TSpeedButton; btnRun: TSpeedButton; Label4: TLabel; edUDLFileName: TxpEdit; btnLocateUDL: TxpButton; lbResults: TListBox; dlgUDLFileLocate: TOpenDialog; cbCombineToNY: TxpCheckBox; Label5: TLabel; edExtractFolder: TxpEdit; btnLocateExtractFolder: TxpButton; Label6: TLabel; edServerFolder: TxpEdit; dlgSaveIniFile: TSaveDialog; dlgLoadIniFile: TOpenDialog; btnLocateServerFolder: TxpButton; cbUseRemoteLogging: TxpCheckBox; edClientId: TxpEdit; Label7: TLabel; cbAutoInc: TxpCheckBox; IdSMTP: TIdSMTP; IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; procedure FormCreate(Sender: TObject); procedure btnRunClick(Sender: TObject); procedure cbxDBaseDatabaseCloseUp(Sender: TObject); procedure btnLocateUDLClick(Sender: TObject); procedure btnLocateExtractFolderClick(Sender: TObject); procedure btnLocateServerFolderClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnLoadClick(Sender: TObject); private { Private declarations } public { Public declarations } bAutoRun, bCreateTables, bCombineToNY, bUseSQLLogin, bDeleteExtracts, bCancelled, bLoadDefaultsOnStartUp, bAutoInc : Boolean; sDefaultSet, sDBaseDatabaseName, sUDLFileName, sSQLPassword, sSQLUser, sServerName, sSQLDatabaseName, sLogFileLocation, sNotificationSettings : String; Procedure UpdateStatus(sStatus : String); Procedure LoadParameters; Procedure LoadDefaults(sDefaultSet : String); Procedure SaveDefaults(sDefaultSet : String); Procedure ExtractOneTable( tbExtract : TTable; sDBaseDatabaseName : String; sTableName : String; sExtractFileName : String; bExtractMemosAsFiles : Boolean; bFirstLineIsHeaders : Boolean; bIncludeFieldTypes : Boolean; bCreateNewFile : Boolean; var iMemoNumber : Integer); Procedure CreateOneTable(adoQuery : TADOQuery; tbExtract : TTable; sDBaseDatabaseName : String; sTableName : String; sSQLDatabaseName : String; sExtractName : String); Procedure LoadOneTable(adoQuery : TADOQuery; sTableName : String; sSQLDatabaseName : String; sExtractName : String); Procedure CopyOneTable(adoQuery : TADOQuery; sSQLDatabaseName : String; sSourceTable : String; sDestTable : String; bDropSourceTable : Boolean); Procedure AutoRun; Procedure SendNotification(NotificationLevel : Integer); Procedure ReindexTables; end; var GlblCurrentCommaDelimitedField : Integer; fmConvertDBaseToSQL: TfmConvertDBaseToSQL; sStartLogString, sFinishLogString : String; rlRemoteLog, rlEndRemoteLog : TRemoteLog; const sSeparator = '|'; sDefaultIniFileName = '\default.ini'; implementation {$R *.dfm} uses Utilities, Definitions; {==========================================================} Procedure TfmConvertDBaseToSQL.LoadParameters; begin LoadIniFile(Self, sDefaultIniFileName, True, False); end; {==========================================================} Procedure TfmConvertDBaseToSQL.LoadDefaults(sDefaultSet : String); begin end; {LoadDefaults} {==========================================================} Procedure TfmConvertDBaseToSQL.SaveDefaults(sDefaultSet : String); begin end; {SaveDefaults} {===============================================================} Procedure TfmConvertDBaseToSQL.btnLocateUDLClick(Sender: TObject); begin If dlgUDLFileLocate.Execute then edUDLFileName.Text := dlgUDLFileLocate.FileName; end; {btnLocateUDLClick} {==============================================================================} Function GetADOConnectionString(bUseSQLLogin : Boolean; sSQLPassword : String; sSQLUser : String; sServerName : String; sDatabaseName : String) : String; begin If bUseSQLLogin then Result := 'Provider=SQLNCLI.1;Password=' + sSQLPassword + ';Persist Security Info=True;User ID=' + sSQLUser else Result := 'Provider=SQLNCLI.1;Integrated Security=SSPI;Persist Security Info=False;User ID=' + sSQLUser; Result := Result + ';Initial Catalog=' + sDatabaseName + ';Data Source=' + sServerName; end; {GetADOConnectionString} {==========================================================} Function GetExtractName(sTableName : String; sExtractFolder : String) : String; begin Result := sExtractFolder + sTableName + '.txt'; end; {==========================================================} Procedure TfmConvertDBaseToSQL.cbxDBaseDatabaseCloseUp(Sender: TObject); begin Session.GetTableNames(cbxDBaseDatabase.Items[cbxDBaseDatabase.ItemIndex], '*.*', False, False, lbxTables.Items); end; {==========================================================} Procedure GetSelectedFromListBox(lbTemp : TListBox; slSelected : TStringList); var I : Integer; begin slSelected.Clear; with lbTemp do For I := 0 to (Items.Count - 1) do If Selected[I] then slSelected.Add(Items[I]); end; {GetSelectedFromListBox} {==========================================================} Procedure TfmConvertDBaseToSQL.FormCreate(Sender: TObject); var sParameterString, sIniFilePath, sTempStr : String; i : integer; {CHG12112013(MPT):Add support for logging} begin {Local Logging} hLog.StartLogging; hLog.hlWriter.hlFileDef.append := True; sStartLogString := FormatDateTime(DateFormat, Date) + #9 + FormatDateTime(TimeFormat, Now) + #9 + 'STARTUP' + #9; {Remote Logging} rlRemoteLog := TRemoteLog.Create; rlRemoteLog.SetTable('log_entry'); GlblCurrentCommaDelimitedField := 0; Session.GetDatabaseNames(cbxDBaseDatabase.Items); bAutoRun := False; bLoadDefaultsOnStartUp := True; {CHG11302013(MPT):Add parameter functions} For i := 1 to ParamCount do begin sParameterString := ParamStr(i); if Uppercase(sParameterString) = 'AUTORUN' then begin bAutoRun := True; end; if (Pos('SETTINGS',Uppercase(sParameterString)) > 0) then begin sIniFilePath := sParameterString; Delete(sIniFilePath,1,9); bLoadDefaultsOnStartUp := False; LoadIniFile(Self, sIniFilepath, True, True); end; if (Pos('LOGGING',Uppercase(sParameterString)) > 0) then begin sLogFileLocation := sParameterString; Delete(sLogFileLocation,1,8); hLog.hlWriter.hlFileDef.fileName := sLogFileLocation ; end; end; rlRemoteLog.AddColumn('configuration'); sTempStr := sIniFilePath + ' ' + sLogFileLocation + ' ' + sNotificationSettings; rlRemoteLog.AddValue(sTempStr); if bLoadDefaultsOnStartUp then LoadParameters; SendNotification(3); AutoRun; end; {FormCreate} {======================================================} Procedure TfmConvertDBaseToSQL.UpdateStatus(sStatus : String); begin pnlStatus.Caption := sStatus; Application.ProcessMessages; end; {======================================================} Procedure TfmConvertDBaseToSQL.ExtractOneTable( tbExtract : TTable; sDBaseDatabaseName : String; sTableName : String; sExtractFileName : String; bExtractMemosAsFiles : Boolean; bFirstLineIsHeaders : Boolean; bIncludeFieldTypes : Boolean; bCreateNewFile : Boolean; var iMemoNumber : Integer); var sTempFileName : String; I, iNumRecordsExported : Integer; slFields : TStringList; flExtract : TextFile; begin slFields := TStringList.Create; AssignFile(flExtract, sExtractFileName); Rewrite(flExtract); with tbExtract do try TableName := sTableName; DatabaseName := sDBaseDatabaseName; Open; First; For I := 0 to (FieldList.Count - 1) do slFields.Add(FieldList[I].FieldName); except SendNotification(5); end; If (bCreateNewFile and bFirstLineIsHeaders) then begin For I := 0 to (slFields.Count - 1) do WriteCommaDelimitedLine(flExtract, [slFields[I]]); WritelnCommaDelimitedLine(flExtract, []); end; {If FirstLineIsHeadersCheckBox.Checked} iNumRecordsExported := 0; ProgressBar.Max := tbExtract.RecordCount; ProgressBar.Position := 0; with tbExtract do while not EOF do begin iNumRecordsExported := iNumRecordsExported + 1; ProgressBar.StepIt; Self.UpdateStatus(sDBaseDatabaseName + ':' + sTableName + ' ' + IntToStr(iNumRecordsExported) + ' exported.'); For I := 0 to (slFields.Count - 1) do If ((FindField(slFields[I]).DataType = ftMemo) and bExtractMemosAsFiles and (not FindField(slFields[I]).IsNull)) then begin iMemoNumber := iMemoNumber + 1; sTempFileName := 'MEMO' + IntToStr(iMemoNumber) + '.MEM'; TMemoField(FindField(slFields[I])).SaveToFile(sTempFileName); WriteCommaDelimitedLine(flExtract, [sTempFileName]); end else WriteCommaDelimitedLine(flExtract, [FindField(slFields[I]).AsString]); WritelnCommaDelimitedLine(flExtract, ['|']); Next; end; {while not EOF do} CloseFile(flExtract); tbExtract.Close; end; {ExtractOneTable} {==========================================================} Procedure TfmConvertDBaseToSQL.CreateOneTable(adoQuery : TADOQuery; tbExtract : TTable; sDBaseDatabaseName : String; sTableName : String; sSQLDatabaseName : String; sExtractName : String); var slSQL : TStringList; I : Integer; sFieldName, sTemp : String; begin slSQL := TStringList.Create; UpdateStatus('Dropping Table ' + sTableName); _QueryExec(adoQuery, ['Drop Table [' + sSQLDatabaseName + '].[dbo].[' + sTableName + ']']); UpdateStatus('Creating Table ' + sTableName); slSQL.Add('CREATE TABLE [' + sSQLDatabaseName + '].[dbo].[' + sTableName + '] ('); with tbExtract do try TableName := sTableName; DatabaseName := sDBaseDatabaseName; Open; First; except SendNotification(5); end; with tbExtract do begin For I := 0 to (FieldCount - 1) do begin //sFieldName := '[' + StringReplace(FieldDefs.Items[I].Name, '2', 'Second', [rfReplaceAll]) + ']'; sFieldName := '[' + FieldDefs.Items[I].Name + ']'; If (Fields[I].DataType = ftMemo) then sTemp := sFieldName + ' text NULL' else sTemp := sFieldName + ' varchar(250) NULL'; If _Compare(I, (FieldCount - 1), coLessThan) then sTemp := sTemp + ','; slSQL.Add(sTemp); end; {For I := 0 to (FieldCount - 1) do} end; {with tbExtract do} slSQL.Add(')'); try adoQuery.Close; adoQuery.SQL.Assign(slSQL); adoQuery.ExecSQL; except SendNotification(5); end; tbExtract.Close; end; {CreateOneTable} {==========================================================} Procedure TfmConvertDBaseToSQL.LoadOneTable(adoQuery : TADOQuery; sTableName : String; sSQLDatabaseName : String; sExtractName : String); begin _QueryExec(adoQuery, ['BULK INSERT [' + sSQLDatabaseName + '].[dbo].[' + sTableName + ']', 'FROM ' + FormatSQLString(sExtractName), 'WITH (DATAFILETYPE = ' + FormatSQLString('char') + ',', 'FIELDTERMINATOR = ' + FormatSQLString('|') + ',', 'ROWTERMINATOR = ' + FormatSQLString('\n') + ')']); UpdateStatus(sSQLDatabaseName + ':' + sTableName + ' imported data from ' + sExtractName); end; {LoadOneTable} {==========================================================} Procedure DeleteOneExtract(sExtractName : String); begin try DeleteFile(sExtractName); except end; end; {DeleteOneExtract} {==========================================================} Procedure TfmConvertDBaseToSQL.CopyOneTable(adoQuery : TADOQuery; sSQLDatabaseName : String; sSourceTable : String; sDestTable : String; bDropSourceTable : Boolean); begin _QueryExec(adoQuery, ['INSERT INTO [' + sSQLDatabaseName + '].[dbo].[' + sDestTable + ']', 'SELECT * FROM [' + sSQLDatabaseName + '].[dbo].[' + sSourceTable + ']']); If bDropSourceTable then _QueryExec(adoQuery, ['DROP TABLE [' + sSQLDatabaseName + '].[dbo].[' + sSourceTable + ']']); UpdateStatus(sSQLDatabaseName + ':' + sSourceTable + ' copied to ' + sDestTable); end; {CopyOneTable} {============================================================} Procedure TfmConvertDBaseToSQL.btnLocateExtractFolderClick(Sender: TObject); var sChosenDirectory : String; begin if SelectDirectory('Select a directory', 'C:\', sChosenDirectory) then edExtractFolder.Text := sChosenDirectory; end; {============================================================} procedure TfmConvertDBaseToSQL.btnLocateServerFolderClick(Sender: TObject); var sChosenDirectory : String; begin if SelectDirectory('Select a directory', 'C:\', sChosenDirectory) then edServerFolder.Text := sChosenDirectory; end; {CHG12062013(MPT): Add automatic shutdown if autorun parameter is specified} {==========================================================} Procedure TfmConvertDBaseToSQL.btnRunClick(Sender: TObject); var slSelectedTables, slSaveTables : TStringList; I, iMemoNumber : Integer; sConnectionString, sAutoInc, sExtractName, sExtractFolder, sServerFolder, sTempStr : String; adoQuery, adoAutoInc : TADOQuery; tbExtract : TTable; adoConnectAutoInc : TADOConnection; begin {CHG12202013(MPT):Implementation of both client and server side logging} {Local Logging} sStartLogString := sStartLogString + 'START' + #9; If bAutoRun then sStartLogString := sStartLogString + 'AUTO' + #9 else sStartLogString := sStartLogString + 'MANUAL' + #9; slSaveTables := TStringList.Create; slSaveTables := SaveSelectedListBoxItems(lbxTables); sStartLogString := sStartLogString + edUDLFileName.Text + #9 + cbxDBaseDatabase.Text + #9 + StringListToCommaDelimitedString(slSaveTables) + #9; hLog.Add(sStartLogString); {Remote Logging} if cbUseRemoteLogging.Checked then begin rlRemoteLog.AddColumnValuePair(rlDateTime, rlRemoteLog.CurrentDatetime); rlRemoteLog.AddColumnValuePair(rlAction, 'START'); rlRemoteLog.AddColumn(rlRunType); if bAutoRun then rlRemoteLog.AddValue('AUTO') else rlRemoteLog.AddValue('MANUAL'); rlRemoteLog.AddColumnValuePair(rlSource, cbxDBaseDatabase.Text); rlRemoteLog.AddColumnValuePair(rlDestination, edExtractFolder.Text); sTempStr := StringListToCommaDelimitedString(SaveSelectedListBoxItems(lbxTables)); rlRemoteLog.AddColumnValuePair(rlTables, sTempStr); rlRemoteLog.AddColumnValuePair(rlClientId, edClientId.Text); rlRemoteLog.SaveLog; end; bCancelled := False; slSelectedTables := TStringList.Create; sExtractFolder := IncludeTrailingPathDelimiter(edExtractFolder.Text); sServerFolder := IncludeTrailingPathDelimiter(edServerFolder.Text); bDeleteExtracts := False; GetSelectedFromListBox(lbxTables, slSelectedTables); (*If not bAutoRun then GetOptions(edServer.Text, cbxSQLDatabase.Text, cbxDBaseDatabase.Text, cbUseSQLLogin.Checked, edSQLUser.Text, edSQLPassword.Text, cbCreateTableStructure.Checked); *) sServerName := edSQLServer.Text; sDBaseDatabaseName := cbxDBaseDatabase.Text; sSQLDatabaseName := cbxSQLDatabase.Text; bUseSQLLogin := cbUseSQLLogin.Checked; sSQLUser := edSQLUser.Text; sSQLPassword := edSQLPassword.Text; bCreateTables := cbCreateTableStructure.Checked; bCombineToNY := cbCombineToNY.Checked; sUDLFileName := edUDLFileName.Text; If _Compare(sUDLFileName, coBlank) then sConnectionString := GetADOConnectionString(bUseSQLLogin, sSQLPassword, sSQLUser, sServerName, sSQLDatabaseName) else sConnectionString := 'FILE NAME=' + sUDLFileName; bCancelled := False; I := 0; tbExtract := TTable.Create(nil); adoQuery := TADOQuery.Create(nil); tbExtract.TableType := ttDBase; adoQuery.ConnectionString := sConnectionString; adoQuery.CommandTimeout := 10000; while ((not bCancelled) and (I <= (slSelectedTables.Count - 1))) do begin sExtractName := GetExtractName(slSelectedTables[I], sExtractFolder); ExtractOneTable(tbExtract, sDBaseDatabaseName, slSelectedTables[I], sExtractName, True, False, False, bCreateTables, iMemoNumber); If bCreateTables then CreateOneTable(adoQuery, tbExtract, sDBaseDatabaseName, slSelectedTables[I], sSQLDatabaseName, sExtractName); sExtractName := sServerFolder + slSelectedTables[I] + '.txt'; LoadOneTable(adoQuery, slSelectedTables[I], sSQLDatabaseName, sExtractName); If bDeleteExtracts then DeleteOneExtract(sExtractName); I := I + 1; end; {while ((not bCancelled) and...} I := 0; If bCombineToNY then while ((not bCancelled) and (I <= (slSelectedTables.Count - 1))) do begin If (_Compare(slSelectedTables[I], 'h', coStartsWith) or _Compare(slSelectedTables[I], 't', coStartsWith)) then CopyOneTable(adoQuery, sSQLDatabaseName, slSelectedTables[I], 'N' + Copy(slSelectedTables[I], 2, 255), True); I := I + 1; end; {while ((not bCancelled) and...} {CHG010520114(MPT):Allow Sales_ID in PSalesRec to autoincrement if checked} bAutoInc := cbAutoInc.Checked; sAutoInc := 'ALTER TABLE PSalesRec DROP COLUMN Sale_ID;'; if bAutoInc then begin adoAutoInc := TADOQuery.Create(nil); adoConnectAutoInc := TADOConnection.Create(nil); adoConnectAutoInc.ConnectionString := 'FILE NAME=' + edUDLFileName.Text; adoConnectAutoInc.LoginPrompt := False; adoConnectAutoInc.Connected := True; try adoAutoInc.Connection := adoConnectAutoInc; adoAutoInc.SQL.Add(sAutoInc); adoAutoInc.ExecSQL; adoAutoInc.Free; except SendNotification(5); end; try adoAutoInc := TADOQuery.Create(nil); adoAutoInc.Connection := adoConnectAutoInc; adoAutoInc.SQL.Add('ALTER TABLE PSalesRec ADD Sale_ID int IDENTITY(1,1);'); adoAutoInc.ExecSQL; adoAutoInc.Free; except SendNotification(5); end; end; ReindexTables; UpdateStatus('Done.'); ProgressBar.Position := 0; {End of run logging} {Local} sFinishLogString := FormatDateTime(DateFormat, Date) + #9 + FormatDateTime(TimeFormat, Now) + #9 + 'CLOSE' + #9 + 'FINISHED' ; hLog.AddStr(sFinishLogString); {Remote} if cbUseRemoteLogging.checked then begin rlEndRemoteLog := TRemoteLog.Create; rlEndRemoteLog.SetTable('log_entry'); rlEndRemoteLog.AddColumnValuePair(rlAction, 'FINISH'); rlEndRemoteLog.AddColumn(rlRunType); if bAutoRun then rlEndRemoteLog.AddValue('AUTO') else rlEndRemoteLog.AddValue('MANUAL'); rlEndRemoteLog.AddColumnValuePair(rlDatetime, rlEndRemoteLog.CurrentDatetime); rlEndRemoteLog.SaveLog; end; SendNotification(1); slSelectedTables.Free; slSaveTables.Free; tbExtract.Close; tbExtract.Free; adoQuery.Close; adoQuery.Free; adoAutoInc.Close; adoAutoInc.Free; adoConnectAutoInc.Close; adoConnectAutoInc.Free; if bAutoRun then fmConvertDBaseToSQL.Release; end; {btnRunClick} {==========================================================} {CHG11272013(MPT): Add Saving and Loading from INI file} procedure TfmConvertDBaseToSQL.btnSaveClick(Sender: TObject); var sIniFileName : String; begin if dlgSaveIniFile.Execute then begin sIniFileName := dlgSaveIniFile.FileName; SaveIniFile(Self, sIniFileName, True, True); end; {Check for cancel} end; {Save custom INI files} {==========================================================} procedure TfmConvertDBaseToSQL.btnLoadClick(Sender: TObject); var sIniFileName : string; begin if dlgLoadIniFile.Execute then begin sIniFileName := dlgLoadIniFile.FileName; LoadIniFile(Self, sIniFileName, True, True); end; {Check for cancel} end; {Load custom INI files} {==========================================================} procedure TfmConvertDBaseToSQL.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveIniFile(Self, sDefaultIniFileName, True, False); SendNotification(4); end; {Save current setup as default on close} {CHG12082103(MPT):Adding autorun functionaity} {==========================================================} procedure TfmConvertDBaseToSQL.AutoRun; begin If bAutoRun then fmConvertDBaseToSQL.btnRunClick(Self); end; {CHG282014(MPT):Add support for notifications to be sent via e-mail.} {==========================================================} procedure TfmConvertDBaseToSQL.SendNotification(NotificationLevel : Integer); var X, I : Integer; sQuery, sNotification : String; slEmail, slTableList : TStringList; IdmEmail : TIdMessage; adoCon : TADOConnection; adoQuery : TADOQuery; begin IdmEmail := TIdMessage.Create; adoCon := TADOConnection.Create(nil); adoQuery := TADOQuery.Create(nil); slEmail := TStringList.Create; slTableList := TStringList.Create; slTableList := SaveSelectedListBoxItems(lbxTables); with adoCon do begin ConnectionString := 'FILE NAME=' + GetCurrentDir + '\RemoteLog.udl'; ConnectionTimeout := 20000; LoginPrompt := False; Connected := True; end; //Establish a connection to SCAWebDB. for X:=NotificationLevel to 5 do begin sQuery := 'SELECT email FROM recipient WHERE alert_level = ' + IntToStr(X) + ' AND client_id = ' + edClientId.Text; with adoQuery do begin SQL.Clear; Connection := adoCon; SQL.Add(sQuery); Prepared := True; Open; end; //Get Email for all recipient with appropriate alert levels. adoQuery.First; for I:=1 to (adoQuery.RecordCount) do begin slEmail.Add(adoQuery.FieldByName('email').AsString); Next; end; //Move emails to stringlist. adoQuery.Close; end; //Gets all recipients where alert_level <= NotificationLevel. case NotificationLevel of 1 : sNotification := 'The following tables have been successfully converted: ' + StringListToCommaDelimitedString(slTableList); 2 : sNotification := ''; 3 : sNotification := 'ConvertDBaseToSQL has been opened.'; 4 : sNotification := 'ConvertDBaseToSQL has been shutdown.'; 5 : sNotification := 'ConvertDBaseToSQL has crashed with the following error: '; end; //Generate the body of the email based on the notification level. for X:=0 to (slEmail.Count - 1) do begin with IdSMTP do begin Host := 'smtp.gmail.com'; Username := 'convertdbasetosql@gmail.com'; Password := 'SCAcdbtsql71'; Connect; ConnectTimeout := 20000; end; //Connect to google SMTP server. with IdmEmail do begin ContentType := 'text/plain'; From.Text := 'convertdbasetosql@gmail.com'; From.Address := 'convertdbasetosql@gmail.com'; From.Name := 'ConvertDBaseToSQL'; Recipients.Add.Address := slEmail[X]; Subject := 'ConvertDBaseToSQL'; Body.Text := sNotification; end; //Assemble the E-mail. try IdSMTP.Send(IdmEmail); except on E: Exception do ShowMessage('Error: ' + E.Message); end; //Try to send the email. end; //Generate and send notifcation emails. IdSMTP.Disconnect; slEmail.Free; slTableList.Free; adoCon.Close; adoCon.Free; adoQuery.Close; adoQuery.Free; IdmEmail.Free; end; {CHG2102014(MPT):Added reindexing tables on job completion} {==========================================================} procedure TfmConvertDBaseToSQL.ReindexTables; var sQuery : String; adoCon : TADOConnection; adoQuery : TADOQuery; begin adoCon := TADOConnection.Create(nil); adoQuery := TADOQuery.Create(nil); sQuery := 'USE ' + cbxSQLDatabase.Text + 'GO EXEC sp_MSforeachtable @command1="print ''?'' DBCC DBREINDEX (''?'', '' '',80)" GO EXEC sp_updatestats GO'; with adoCon do begin ConnectionString := 'FILE NAME=' + edUDLFileName.Text; ConnectionTimeout := 5000; LoginPrompt := False; Connected := True; end; with adoQuery do begin Connection := adoCon; SQL.Add(sQuery); ExecSQL; end; adoCon.Close; adoCon.Free; adoQuery.Close; adoQuery.Free; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmCornerGrip Purpose : Allow for a working "Size Grip" to be placed on the components owner form. Date : 10-26-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================ } unit rmCornerGrip; interface {$I CompilerDefines.INC} uses Windows, Messages, Classes, forms, Controls; type TrmCornerGrip = class(TComponent) private { Private declarations } OldWndProc: TFarProc; NewWndProc: Pointer; fHeight : integer; fWidth : integer; fCanPaint : boolean; procedure HookWndProc(var AMsg: TMessage); procedure HookWin; procedure UnhookWin; procedure setHeight(const Value: integer); procedure setwidth(const Value: integer); protected { Protected declarations } procedure Paint; function GripRect:TRect; function GripTestRect:TRect; public { Public declarations } constructor create(AOwner : TComponent); override; destructor destroy; override; published { Published declarations } property Height:integer read fheight write setHeight default 15; property Width :integer read fWidth write setwidth default 20; end; implementation Uses rmglobalComponentHook, Graphics; type TWinControlInvasion = class(TWinControl) end; { TrmCornerGrip } constructor TrmCornerGrip.create(AOwner: TComponent); begin inherited; fHeight := 15; fwidth := 20; fCanPaint := true; HookWin; end; destructor TrmCornerGrip.destroy; begin UnhookWin; inherited; end; procedure TrmCornerGrip.HookWin; begin if csdesigning in componentstate then exit; if not assigned(NewWndProc) then begin OldWndProc := TFarProc(GetWindowLong(TForm(Owner).handle, GWL_WNDPROC)); {$ifdef D6_or_higher} NewWndProc := Classes.MakeObjectInstance(HookWndProc); {$else} NewWndProc := MakeObjectInstance(HookWndProc); {$endif} SetWindowLong(TForm(Owner).handle, GWL_WNDPROC, LongInt(NewWndProc)); PushOldProc(TForm(Owner), OldWndProc); end; end; procedure TrmCornerGrip.UnhookWin; begin if csdesigning in componentstate then exit; if assigned(NewWndProc) then begin SetWindowLong(TForm(Owner).handle, GWL_WNDPROC, LongInt(PopOldProc(TForm(Owner)))); if assigned(NewWndProc) then {$ifdef D6_or_higher} Classes.FreeObjectInstance(NewWndProc); {$else} FreeObjectInstance(NewWndProc); {$endif} NewWndProc := nil; OldWndProc := nil; end; end; procedure TrmCornerGrip.HookWndProc(var AMsg: TMessage); var wPt : TPoint; wRect : TRect; begin case AMsg.msg of wm_destroy: begin AMsg.Result := CallWindowProc(OldWndProc, Tform(Owner).handle, AMsg.Msg, AMsg.wParam, AMsg.lParam); UnHookWin; exit; end; wm_NCHitTest: begin wPt.x := aMsg.lParam and $0000FFFF; wPT.y := (amsg.lparam and $FFFF0000) shr 16; wRect := GripTestRect; if ptInRect(wRect,wPT) then begin AMsg.Result := HTBOTTOMRIGHT; Paint; exit; end end; WM_ENTERSIZEMOVE: begin fCanPaint := False; Tform(Owner).Repaint; end; end; AMsg.Result := CallWindowProc(OldWndProc, Tform(Owner).handle, AMsg.Msg, AMsg.wParam, AMsg.lParam); case AMsg.msg of WM_EXITSIZEMOVE: begin fCanPaint := true; Paint; end; WM_ERASEBKGND: begin paint; end; end; end; procedure TrmCornerGrip.Paint; var wRect : TRect; begin if csdesigning in componentstate then exit; if not fCanPaint then exit; wrect := GripRect; wRect.Left := wRect.Left; wRect.Top := wRect.top; Tform(Owner).Update; DrawFrameControl(Tform(Owner).Canvas.handle, wRect, DFC_SCROLL, DFCS_SCROLLSIZEGRIP) end; procedure TrmCornerGrip.setHeight(const Value: integer); begin fheight := Value; Paint; end; procedure TrmCornerGrip.setwidth(const Value: integer); begin fWidth := Value; Paint; end; function TrmCornerGrip.GripRect: TRect; begin result := TForm(Owner).ClientRect; result.top := result.bottom - fHeight; result.Left := result.right - fWidth; end; function TrmCornerGrip.GripTestRect: TRect; begin result := TForm(Owner).BoundsRect; result.top := result.bottom - fHeight; result.Left := result.right - fWidth; end; end.