text
stringlengths
14
6.51M
unit TextOutScripts; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>TextOutScripts <What>产生文本输出的脚本描述语言 <Written By> Huang YanLai (黄燕来) <History> **********************************************} interface uses SysUtils,Classes, TextUtils, Contnrs, RPDB, RPDBVCL; type {ITextOut = Interface procedure Print(const AText:string); end;} TScriptContext = class; TTOScriptNode = class(TObject) public procedure Prepare(Context : TScriptContext); virtual; procedure DoIt(Context : TScriptContext); virtual; abstract; end; TTOText = class(TTOScriptNode) private FText: string; public property Text : string read FText write FText; procedure DoIt(Context : TScriptContext); override; end; TTOTextAlign = (taLeft, taCenter, taRight); TTOFieldValue = class(TTOScriptNode) private FWidth: Integer; FFieldName: string; FAlign: TTOTextAlign; public procedure DoIt(Context : TScriptContext); override; property Align : TTOTextAlign read FAlign write FAlign; property Width : Integer read FWidth write FWidth; property FieldName : string read FFieldName write FFieldName; end; TTOForLoop = class(TTOScriptNode) private FExitNodeIndex: Integer; FBrowser : TRPDatasetBrowser; FIsFirst : Boolean; function GetControllerName: string; function GetGroupIndex: Integer; procedure SetControllerName(const Value: string); procedure SetGroupIndex(const Value: Integer); public constructor Create; destructor Destroy;override; procedure Prepare(Context : TScriptContext); override; procedure DoIt(Context : TScriptContext); override; property ControllerName : string read GetControllerName write SetControllerName; property GroupIndex : Integer read GetGroupIndex write SetGroupIndex; property ExitNodeIndex : Integer read FExitNodeIndex write FExitNodeIndex; end; TTOEndLoop = class(TTOScriptNode) private FForNodeIndex: Integer; public procedure DoIt(Context : TScriptContext); override; property ForNodeIndex : Integer read FForNodeIndex write FForNodeIndex; end; TScriptContext = class(TComponent) private //FTextOut: ITextOut; FCurrentNode: TTOScriptNode; FWriter : TTextWriter; FEnvironment: TRPDataEnvironment; FNodes: TObjectList; FDataEntries: TRPDBDataEntries; FCurrentNodeIndex: Integer; FNextNodeIndex: Integer; FDefaultFileName: string; procedure DoOutput; procedure Prepare; procedure Parse(TANodes : TList); procedure MakeRelations; procedure SetEnvironment(const Value: TRPDataEnvironment); protected procedure TextOut(const AText:string); procedure Notification(AComponent: TComponent; Operation: TOperation); override; property NextNodeIndex : Integer read FNextNodeIndex write FNextNodeIndex; property CurrentNode : TTOScriptNode read FCurrentNode; property CurrentNodeIndex : Integer read FCurrentNodeIndex; public constructor Create(AOwner : TComponent); override; destructor Destroy;override; procedure Clear; //property TextOut : ITextOut read FTextOut; procedure LoadScripts(Stream : TStream); overload; procedure LoadScripts(const FileName:string); overload; procedure Output(Stream : TStream); overload; procedure Output(const FileName:string); overload; property Nodes : TObjectList read FNodes; property DataEntries : TRPDBDataEntries read FDataEntries; property DefaultFileName : string read FDefaultFileName write FDefaultFileName; published property Environment : TRPDataEnvironment read FEnvironment write SetEnvironment; end; resourcestring ScriptError = 'Script Error.'; const // function names RDataEntry = 'DataEntry'; RForLoop = 'ForLoop'; REndLoop = 'EndLoop'; RFieldValue = 'FieldValue'; RFileName = 'FileName'; // params PAlignCenter = 'Center'; PAlignRight = 'Right'; PAlignLeft = 'Left'; implementation uses SafeCode, TextTags, FuncScripts, KSStrUtils; { TTOScriptNode } procedure TTOScriptNode.Prepare(Context : TScriptContext); begin end; { TTOText } procedure TTOText.DoIt(Context: TScriptContext); begin Context.TextOut(Text); end; { TTOFieldValue } procedure TTOFieldValue.DoIt(Context: TScriptContext); var Value : string; Len : Integer; begin Value := Context.Environment.GetFieldText(FieldName); Len := Length(Value); if Width>0 then begin case Align of taLeft: Value := Value + StringOfChar(' ',Width); taCenter: if Len<Width then Value := StringOfChar(' ',(Width-Len) div 2) + Value + StringOfChar(' ',Width); taRight: Value := StringOfChar(' ',Width-Len) + Value; end; Value := Copy(Value,1,Width); end; Context.TextOut(Value); end; { TTOForLoop } constructor TTOForLoop.Create; begin inherited; FBrowser := TRPDatasetBrowser.Create; end; destructor TTOForLoop.Destroy; begin FBrowser.Free; inherited; end; procedure TTOForLoop.Prepare(Context : TScriptContext); begin inherited; FBrowser.Environment := Context.Environment; FBrowser.CheckController; if FBrowser.Controller<>nil then FBrowser.Controller.Init; FIsFirst := True; end; procedure TTOForLoop.DoIt(Context: TScriptContext); begin if FIsFirst then begin if FBrowser.Available then FBrowser.Init; FIsFirst := False; end; if FBrowser.Available then begin FBrowser.GotoNextData; if FBrowser.Eof then begin Context.NextNodeIndex := ExitNodeIndex; FIsFirst := True; end; end else Context.NextNodeIndex := ExitNodeIndex; end; function TTOForLoop.GetControllerName: string; begin Result := FBrowser.ControllerName; end; function TTOForLoop.GetGroupIndex: Integer; begin Result := FBrowser.GroupingIndex; end; procedure TTOForLoop.SetControllerName(const Value: string); begin FBrowser.ControllerName := Value; end; procedure TTOForLoop.SetGroupIndex(const Value: Integer); begin FBrowser.GroupingIndex:= Value; end; { TTOEndLoop } procedure TTOEndLoop.DoIt(Context: TScriptContext); begin Context.NextNodeIndex := ForNodeIndex; end; { TScriptContext } constructor TScriptContext.Create(AOwner : TComponent); begin inherited; FNodes := TObjectList.Create; FDataEntries:= TRPDBDataEntries.Create(Self); end; destructor TScriptContext.Destroy; begin FDataEntries.Free; FNodes.Free; inherited; end; procedure TScriptContext.Output(Stream: TStream); begin try FWriter := TTextWriter.Create(Stream); DoOutput; finally FreeAndNil(FWriter); end; end; procedure TScriptContext.Output(const FileName: string); begin try FWriter := TTextWriter.Create(FileName); DoOutput; finally FreeAndNil(FWriter); end; end; procedure TScriptContext.TextOut(const AText: string); begin Assert(FWriter<>nil); FWriter.Print(AText); end; procedure TScriptContext.DoOutput; begin Prepare; FCurrentNodeIndex := 0; while FCurrentNodeIndex<Nodes.Count do begin FNextNodeIndex := FCurrentNodeIndex+1; FCurrentNode := TTOScriptNode(Nodes[FCurrentNodeIndex]); FCurrentNode.DoIt(Self); FCurrentNodeIndex := FNextNodeIndex; end; end; procedure TScriptContext.LoadScripts(Stream: TStream); var Parser : TTextTagParser; begin Parser := TTextTagParser.Create; try Parser.Parse(Stream); Parse(Parser.Nodes); finally Parser.Free; end; end; procedure TScriptContext.LoadScripts(const FileName: string); var Parser : TTextTagParser; begin Parser := TTextTagParser.Create; try Parser.ParseFile(FileName); Parse(Parser.Nodes); finally Parser.Free; end; end; procedure TScriptContext.Parse(TANodes: TList); var i,j : integer; Funcs : TObjectList; TANode : TTATextNode; Node : TTOScriptNode; Func : TScriptFunc; AlignStr : string; DataEntry : TRPDataEntry; Groups : string; begin Clear; // get all nodes Funcs := TObjectList.Create; try for i:=0 to TANodes.Count-1 do begin TANode := TTATextNode(TANodes[i]); if TANode.NodeType=stText then begin // just a plaintext node Node := TTOText.Create; Nodes.Add(Node); TTOText(Node).Text := TANode.Text; end else begin // there is a script tag need to parse Funcs.Clear; ParseFunctions(TANode.Text,Funcs); for j:=0 to Funcs.Count-1 do begin Func := TScriptFunc(Funcs[j]); if SameText(Func.FunctionName,RDataEntry) then begin // create data entry DataEntry := TRPDataEntry(DataEntries.Add); DataEntry.DatasetName:=GetParam(Func.Params,0,''); DataEntry.ControllerName:=GetParam(Func.Params,1,''); Groups := GetParam(Func.Params,2,''); SeperateStr(Groups,['|'],DataEntry.Groups,True); end else if SameText(Func.FunctionName,RForLoop) then begin Node := TTOForLoop.Create; Nodes.Add(Node); with TTOForLoop(Node) do begin ControllerName := GetParam(Func.Params,0,''); GroupIndex := StrToIntDef(GetParam(Func.Params,1,''),-1); end; end else if SameText(Func.FunctionName,REndLoop) then begin Node := TTOEndLoop.Create; Nodes.Add(Node); end else if SameText(Func.FunctionName,RFieldValue) then begin Node := TTOFieldValue.Create; Nodes.Add(Node); with TTOFieldValue(Node) do begin FieldName := GetParam(Func.Params,0,''); Width := StrToIntDef(GetParam(Func.Params,1,''),0); AlignStr := GetParam(Func.Params,2,''); if SameText(AlignStr,PAlignRight) then Align := taRight else if SameText(AlignStr,PAlignCenter) then Align := taCenter else Align := taLeft; end; end else if SameText(Func.FunctionName,RFileName) then begin FDefaultFileName := GetParam(Func.Params,0,''); end; end; end; end; finally Funcs.Free; end; // create controllers DataEntries.CreateControllers(Environment); // make relations between nodes MakeRelations; end; procedure TScriptContext.MakeRelations; var i : integer; Stack : TStack; Node : TTOScriptNode; ForNode : TTOForLoop; begin Stack := TStack.Create; try for i:=0 to Nodes.Count-1 do begin Node := TTOScriptNode(Nodes[i]); if Node is TTOForLoop then Stack.Push(Pointer(I)) else if Node is TTOEndLoop then begin TTOEndLoop(Node).ForNodeIndex := Integer(Stack.Pop); ForNode := TTOForLoop(Nodes[TTOEndLoop(Node).ForNodeIndex]); ForNode.ExitNodeIndex:=I+1; end; end; CheckTrue(Stack.Count=0,ScriptError); finally Stack.Free; end; end; procedure TScriptContext.SetEnvironment(const Value: TRPDataEnvironment); begin if FEnvironment <> Value then begin FEnvironment := Value; if FEnvironment<>nil then begin FEnvironment.FreeNotification(Self); end; end; end; procedure TScriptContext.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent=FEnvironment) and (Operation=opRemove) then begin Environment := nil; end; end; procedure TScriptContext.Clear; begin DataEntries.Clear; Nodes.Clear; FDefaultFileName := ''; end; procedure TScriptContext.Prepare; var i : integer; begin for i:=0 to Nodes.Count-1 do begin TTOScriptNode(Nodes[i]).Prepare(Self); end; end; end.
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Cmp_CSS; {$mode objfpc}{$H+} interface uses ATSynEdit, ATSynEdit_Cmp_CSS_Provider; procedure DoEditorCompletionCss(AEdit: TATSynEdit); type TATCompletionOptionsCss = record Provider: TATCssProvider; FilenameCssList: string; //from CudaText: data/autocompletespec/css_list.ini FilenameCssColors: string; //from CudaText: data/autocompletespec/css_colors.ini FilenameCssSelectors: string; //from CudaText: data/autocompletespec/css_sel.ini PrefixProp: string; PrefixAtRule: string; PrefixPseudo: string; LinesToLookup: integer; NonWordChars: UnicodeString; end; var CompletionOpsCss: TATCompletionOptionsCss; implementation uses SysUtils, Classes, Graphics, StrUtils, Math, ATSynEdit_Carets, ATSynEdit_RegExpr, ATSynEdit_Cmp_Form; type { TAcp } TAcp = class private ListSel: TStringList; //CSS at-rules (@) and pseudo elements (:) procedure DoOnGetCompleteProp(Sender: TObject; out AText: string; out ACharsLeft, ACharsRight: integer); public Ed: TATSynEdit; constructor Create; virtual; destructor Destroy; override; end; var Acp: TAcp = nil; type TCompletionCssContext = ( CtxNone, CtxPropertyName, CtxPropertyValue, CtxSelectors ); function SFindRegex(const SText, SRegex: UnicodeString; NGroup: integer): string; var R: TRegExpr; begin Result:= ''; R:= TRegExpr.Create; try R.ModifierS:= false; R.ModifierM:= true; R.ModifierI:= true; R.Expression:= SRegex; R.InputString:= SText; if R.ExecPos(1) then Result:= Copy(SText, R.MatchPos[NGroup], R.MatchLen[NGroup]); finally R.Free; end; end; function EditorGetCaretInCurlyBrackets(Ed: TATSynEdit; APosX, APosY: integer): boolean; var S: UnicodeString; X, Y: integer; begin Result:= false; for Y:= APosY downto Max(0, APosY-CompletionOpsCss.LinesToLookup) do begin S:= Ed.Strings.Lines[Y]; if Y=APosY then Delete(S, APosX+1, MaxInt); for X:= Length(S) downto 1 do begin if S[X]='{' then exit(true); if S[X]='}' then exit(false); end; end; end; procedure EditorGetCssContext(Ed: TATSynEdit; APosX, APosY: integer; out AContext: TCompletionCssContext; out ATag: string); const //char class for all chars in css values cRegexChars = '[''"\w\s\.,:/~&%@!=\#\$\^\-\+\(\)\?]'; //regex to catch css property name, before css attribs and before ":", at line end cRegexProp = '([\w\-]+):\s*' + cRegexChars + '*$'; cRegexAtRule = '(@[a-z\-]*)$'; cRegexSelectors = '\w+(:+[a-z\-]*)$'; cRegexGroup = 1; //group 1 in (..) var S: UnicodeString; begin AContext:= CtxNone; ATag:= ''; S:= Ed.Strings.LineSub(APosY, 1, APosX); ATag:= SFindRegex(S, cRegexAtRule, cRegexGroup); if ATag<>'' then begin AContext:= CtxSelectors; exit; end; if EditorGetCaretInCurlyBrackets(Ed, APosX, APosY) then begin AContext:= CtxPropertyName; if S='' then exit; ATag:= SFindRegex(S, cRegexProp, cRegexGroup); if ATag<>'' then AContext:= CtxPropertyValue; end else begin ATag:= SFindRegex(S, cRegexSelectors, cRegexGroup); if ATag<>'' then AContext:= CtxSelectors; end; end; { TAcp } procedure TAcp.DoOnGetCompleteProp(Sender: TObject; out AText: string; out ACharsLeft, ACharsRight: integer); var Caret: TATCaretItem; L: TStringList; s_word: UnicodeString; s_tag, s_item, s_val, s_valsuffix: string; context: TCompletionCssContext; ok: boolean; begin AText:= ''; ACharsLeft:= 0; ACharsRight:= 0; Caret:= Ed.Carets[0]; EditorGetCssContext(Ed, Caret.PosX, Caret.PosY, context, s_tag); EditorGetCurrentWord(Ed, Caret.PosX, Caret.PosY, CompletionOpsCss.NonWordChars, s_word, ACharsLeft, ACharsRight); case context of CtxPropertyValue: begin L:= TStringList.Create; try CompletionOpsCss.Provider.GetValues(s_tag, L); for s_item in L do begin s_val:= s_item; //filter values by cur word (not case sens) if s_word<>'' then begin ok:= StartsText(s_word, s_val); if not ok then Continue; end; //handle values like 'rgb()', 'val()' if EndsStr('()', s_val) then begin SetLength(s_val, Length(s_val)-2); s_valsuffix:= '|()'; end else s_valsuffix:= ''; //CompletionOps.SuffixSep+' '; AText:= AText+CompletionOpsCss.PrefixProp+' "'+s_tag+'"|'+s_val+s_valsuffix+#10; end; finally FreeAndNil(L); end; end; CtxPropertyName: begin //if caret is inside property // back|ground: left; //then we must replace "background: ", ie replace extra 2 chars s_item:= Ed.Strings.LineSub(Caret.PosY, Caret.PosX+ACharsRight+1, 2); if s_item=': ' then Inc(ACharsRight, 2); L:= TStringList.Create; try CompletionOpsCss.Provider.GetProps(L); for s_item in L do begin //filter by cur word (not case sens) if s_word<>'' then begin ok:= StartsText(s_word, s_item); if not ok then Continue; end; AText:= AText+CompletionOpsCss.PrefixProp+'|'+s_item+#1': '#10; end; finally FreeAndNil(L); end; end; CtxSelectors: begin ACharsLeft:= Length(s_tag); if s_tag[1]='@' then s_val:= CompletionOpsCss.PrefixAtRule else if s_tag[1]=':' then s_val:= CompletionOpsCss.PrefixPseudo else exit; for s_item in ListSel do begin if (s_tag='') or StartsText(s_tag, s_item) then AText+= s_val+'|'+s_item+#10; end; end; end; end; constructor TAcp.Create; begin inherited; ListSel:= TStringlist.create; end; destructor TAcp.Destroy; begin FreeAndNil(ListSel); inherited; end; procedure DoEditorCompletionCss(AEdit: TATSynEdit); begin Acp.Ed:= AEdit; if CompletionOpsCss.Provider=nil then begin CompletionOpsCss.Provider:= TATCssBasicProvider.Create( CompletionOpsCss.FilenameCssList, CompletionOpsCss.FilenameCssColors); end; //optional list, load only once if Acp.ListSel.Count=0 then begin if FileExists(CompletionOpsCss.FilenameCssSelectors) then Acp.ListSel.LoadFromFile(CompletionOpsCss.FilenameCssSelectors); end; DoEditorCompletionListbox(AEdit, @Acp.DoOnGetCompleteProp); end; initialization Acp:= TAcp.Create; with CompletionOpsCss do begin Provider:= nil; FilenameCssList:= ''; FilenameCssColors:= ''; FilenameCssSelectors:= ''; PrefixProp:= 'css'; PrefixAtRule:= 'at-rule'; PrefixPseudo:= 'pseudo'; LinesToLookup:= 50; NonWordChars:= '#!@.{};''"<>'; //don't include ':' end; finalization with CompletionOpsCss do if Assigned(Provider) then FreeAndNil(Provider); FreeAndNil(Acp); end.
unit SubtitleSettings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.UITypes, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, VideoConverterInt, SubTitleInt, Vcl.ExtCtrls, Vcl.StdCtrls, ColorToolBar; type TfrmSubtitleSettings = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; lblHorizontal: TLabel; cmbHorizontal: TComboBox; lblVertical: TLabel; cmbVertical: TComboBox; lblFont: TLabel; btnFont: TButton; lblFontColor: TLabel; lblBorderColor: TLabel; lblEffectEnter: TLabel; cmbEffectEnter: TComboBox; cmbDirectEnter: TComboBox; cmbSpeedEnter: TComboBox; lblSpeedEnter: TLabel; lblEffectExit: TLabel; lblSpeedExit: TLabel; cmbEffectExit: TComboBox; cmbSpeedExit: TComboBox; cmbDirectExit: TComboBox; lblAlignment: TLabel; cmbAlignment: TComboBox; tbFont: TTrackBar; Label1: TLabel; Label2: TLabel; tbBorder: TTrackBar; ctbFont: TColorToolBar; ctbBorder: TColorToolBar; FontDialog1: TFontDialog; ckbExitOnce: TCheckBox; ckbEnterOnce: TCheckBox; Button1: TButton; ctbShadow: TColorToolBar; Label3: TLabel; Label4: TLabel; tbShadow: TTrackBar; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure cmbEffectEnterChange(Sender: TObject); procedure cmbDirectEnterChange(Sender: TObject); procedure cmbSpeedEnterChange(Sender: TObject); procedure cmbEffectExitChange(Sender: TObject); procedure cmbDirectExitChange(Sender: TObject); procedure cmbSpeedExitChange(Sender: TObject); procedure btnFontClick(Sender: TObject); procedure ctbFontColorChanged(Sender: TColorToolBar; Color: Cardinal); procedure ctbFontDropdown(Sender: TColorToolBar); procedure ctbBorderColorChanged(Sender: TColorToolBar; Color: Cardinal); procedure ctbBorderDropdown(Sender: TColorToolBar); procedure tbFontChange(Sender: TObject); procedure tbBorderChange(Sender: TObject); procedure cmbAlignmentChange(Sender: TObject); procedure ckbEnterOnceClick(Sender: TObject); procedure ckbExitOnceClick(Sender: TObject); procedure ctbShadowColorChanged(Sender: TColorToolBar; Color: Cardinal); procedure tbShadowChange(Sender: TObject); procedure ctbShadowDropdown(Sender: TColorToolBar); private { Private declarations } FSettings: PSubtitleDefault; FItem : PVCItem; FSubtitle: PSubtitle; FChanging: Boolean; public { Public declarations } procedure InitForm(Item: PVCItem); end; implementation {$R *.dfm} uses Functions; procedure TfrmSubtitleSettings.btnFontClick(Sender: TObject); var font: TFont; begin font := FontDialog1.font; font.Name := FSettings.m_FontName; font.Size := FSettings.m_FontSize; font.Style := FontStyleFromMask(FSettings.m_FontStyle); font.Color := BGRToTColor(FSettings.m_FontColor); if FontDialog1.Execute(self.Handle) = FALSE then Exit; lstrcpy(FSettings.m_FontName, PWideChar(WideString(font.Name))); FSettings.m_FontSize := font.Size; FSettings.m_FontStyle := FontStyleToMask(font.Style); TColorToBGR(FSettings.m_FontColor, font.Color); lblFont.Caption := GetFontString(FSettings.m_FontName, FSettings.m_FontSize, FSettings.m_FontStyle); end; procedure TfrmSubtitleSettings.Button1Click(Sender: TObject); begin // end; procedure TfrmSubtitleSettings.Button2Click(Sender: TObject); begin // end; procedure TfrmSubtitleSettings.Button3Click(Sender: TObject); begin // end; procedure TfrmSubtitleSettings.Button4Click(Sender: TObject); begin // end; procedure TfrmSubtitleSettings.ckbEnterOnceClick(Sender: TObject); begin if FChanging then Exit; FSettings.m_EntranceOnce := ckbEnterOnce.Checked; end; procedure TfrmSubtitleSettings.ckbExitOnceClick(Sender: TObject); begin if FChanging then Exit; FSettings.m_ExitOnce := ckbExitOnce.Checked; end; procedure TfrmSubtitleSettings.cmbAlignmentChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_Alignment := cmbAlignment.ItemIndex; end; procedure TfrmSubtitleSettings.cmbDirectEnterChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_EntranceParam := cmbDirectEnter.ItemIndex; end; procedure TfrmSubtitleSettings.cmbDirectExitChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_ExitParam := cmbDirectExit.ItemIndex; end; procedure TfrmSubtitleSettings.cmbEffectEnterChange(Sender: TObject); begin if FChanging then Exit; case cmbEffectEnter.ItemIndex of 0: begin FSettings.m_Entrance := IID_Subtitle_None; cmbDirectEnter.Enabled := FALSE; cmbSpeedEnter.Enabled := FALSE; end; 1: begin FSettings.m_Entrance := IID_Subtitle_Fade; cmbDirectEnter.Enabled := FALSE; cmbSpeedEnter.Enabled := TRUE; end; 2: begin FSettings.m_Entrance := IID_Subtitle_Slide; cmbDirectEnter.Enabled := TRUE; cmbSpeedEnter.Enabled := TRUE; end; end; end; procedure TfrmSubtitleSettings.cmbEffectExitChange(Sender: TObject); begin if FChanging then Exit; case cmbEffectExit.ItemIndex of 0: begin FSettings.m_Exit := IID_Subtitle_None; cmbDirectExit.Enabled := FALSE; cmbSpeedExit.Enabled := FALSE; end; 1: begin FSettings.m_Exit := IID_Subtitle_Fade; cmbDirectExit.Enabled := FALSE; cmbSpeedExit.Enabled := TRUE; end; 2: begin FSettings.m_Exit := IID_Subtitle_Slide; cmbDirectExit.Enabled := TRUE; cmbSpeedExit.Enabled := TRUE; end; end; end; procedure TfrmSubtitleSettings.cmbSpeedEnterChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_EntranceTime := SubtitleSpeeds[cmbSpeedEnter.ItemIndex]; end; procedure TfrmSubtitleSettings.cmbSpeedExitChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_ExitTime := SubtitleSpeeds[cmbSpeedExit.ItemIndex]; end; procedure TfrmSubtitleSettings.ctbBorderColorChanged(Sender: TColorToolBar; Color: Cardinal); begin FSettings.m_BorderColor.Color := (FSettings.m_BorderColor.Color and $FF000000) or Color; end; procedure TfrmSubtitleSettings.ctbBorderDropdown(Sender: TColorToolBar); begin CreateHSBControl(self.Handle, ctbBorder.Handle, CM_COLOR_TOOLBAR_SETCOLOR, FSettings.m_BorderColor.Color); end; procedure TfrmSubtitleSettings.ctbFontColorChanged(Sender: TColorToolBar; Color: Cardinal); begin FSettings.m_FontColor.Color := (FSettings.m_FontColor.Color and $FF000000) or Color; end; procedure TfrmSubtitleSettings.ctbFontDropdown(Sender: TColorToolBar); begin CreateHSBControl(self.Handle, ctbFont.Handle, CM_COLOR_TOOLBAR_SETCOLOR, FSettings.m_FontColor.Color); end; procedure TfrmSubtitleSettings.ctbShadowColorChanged(Sender: TColorToolBar; Color: Cardinal); begin FSettings.m_ShadowColor.Color := (FSettings.m_ShadowColor.Color and $FF000000) or Color; end; procedure TfrmSubtitleSettings.ctbShadowDropdown(Sender: TColorToolBar); begin CreateHSBControl(self.Handle, ctbShadow.Handle, CM_COLOR_TOOLBAR_SETCOLOR, FSettings.m_ShadowColor.Color); end; procedure TfrmSubtitleSettings.FormCreate(Sender: TObject); begin FSettings := SubtitleGetDefault(); PageControl1.ActivePageIndex := 0; end; procedure TfrmSubtitleSettings.InitForm(Item: PVCItem); begin FItem := Item; FSubtitle := SubtitleGet(FItem); FSettings := SubtitleGetDefault(); FChanging := TRUE; cmbHorizontal.ItemIndex := FSettings.m_HPosition; cmbVertical.ItemIndex := FSettings.m_VPosition; lblFont.Caption := GetFontString(FSettings.m_FontName, FSettings.m_FontSize, FSettings.m_FontStyle); ctbFont.SelectedColor := FSettings.m_FontColor.Color; ctbBorder.SelectedColor := FSettings.m_BorderColor.Color; ctbShadow.SelectedColor := FSettings.m_ShadowColor.Color; tbFont.Position := $FF - FSettings.m_FontColor.A; tbBorder.Position := $FF - FSettings.m_BorderColor.A; tbShadow.Position := $FF - FSettings.m_ShadowColor.A; cmbAlignment.ItemIndex := FSettings.m_Alignment; cmbEffectEnter.ItemIndex := GetSubtitleEffectIndex(FSettings.m_Entrance); cmbDirectEnter.ItemIndex := FSettings.m_EntranceParam; cmbSpeedEnter.ItemIndex := GetSubtitleSpeedIndex(FSettings.m_EntranceTime); ckbEnterOnce.Checked := FSettings.m_EntranceOnce; cmbEffectExit.ItemIndex := GetSubtitleEffectIndex(FSettings.m_Exit); cmbDirectExit.ItemIndex := FSettings.m_ExitParam; cmbSpeedExit.ItemIndex := GetSubtitleSpeedIndex(FSettings.m_ExitTime); ckbExitOnce.Checked := FSettings.m_ExitOnce; FChanging := FALSE; end; procedure TfrmSubtitleSettings.tbBorderChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_BorderColor.A := $FF - tbBorder.Position; end; procedure TfrmSubtitleSettings.tbFontChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_FontColor.A := $FF - tbFont.Position; end; procedure TfrmSubtitleSettings.tbShadowChange(Sender: TObject); begin if FChanging then Exit; FSettings.m_ShadowColor.A := $FF - tbShadow.Position; end; end.
{$mode objfpc} // directive to be used for defining classes {$m+} // directive to be used for using constructor unit containers; interface type link = ^longInt; iterator = class public constructor create(l: link); procedure next(); procedure prev(); procedure set_data(data: longInt); function get_data(): longInt; function equal(other: iterator): boolean; function get_link(): link; private m_link: link; end; container = class public constructor create(); destructor destroy(); override; function get_begin(): iterator; function get_end(): iterator; procedure push_back(data: longInt); function pop_back(): longInt; procedure insert(p: iterator; data: longInt); procedure erase(p: iterator); function at(index: longInt): longInt; function empty(): boolean; function size(): longInt; private m_length: longInt; m_capacity: longInt; m_data: array of longInt; end; implementation constructor iterator.create(l: link); begin m_link := l; end; procedure iterator.next(); begin m_link := m_link + 1; end; procedure iterator.prev(); begin m_link := m_link - 1; end; procedure iterator.set_data(data: longInt); begin m_link^ := data; end; function iterator.get_data(): longInt; begin get_data := m_link^; end; function iterator.equal(other: iterator): boolean; begin equal := (m_link = other.m_link); end; function iterator.get_link(): link; begin get_link := m_link; end; constructor container.create(); begin m_length := 0; m_capacity := 1; setLength(m_data, m_capacity); end; destructor container.destroy(); begin m_length := 0; m_capacity := 0; setLength(m_data, m_capacity); end; procedure container.push_back(data: longInt); var it: iterator; begin it := get_end(); insert(it, data); it.destroy(); end; function container.pop_back(): longInt; begin m_length := m_length - 1; pop_back := m_data[m_length]; end; procedure container.insert(p: iterator; data: longInt); var index, i: longInt; it: iterator; begin it := get_begin(); index := p.get_link() - it.get_link(); it.destroy(); if m_length = m_capacity then begin m_capacity := 3 * m_capacity div 2 + 1; setLength(m_data, m_capacity); end; m_length := m_length + 1; for i := m_length - 1 downto index + 1 do m_data[i] := m_data[i-1]; m_data[index] := data; p.destroy(); p := iterator.create(@m_data[index]); end; procedure container.erase(p: iterator); var index, i: longInt; it: iterator; begin it := get_begin(); index := p.get_link() - it.get_link(); it.destroy(); m_length := m_length - 1; for i := index to m_length - 1 do m_data[i] := m_data[i+1]; end; function container.get_begin(): iterator; begin get_begin := iterator.create(@m_data[0]); end; function container.get_end(): iterator; begin get_end := iterator.create(@m_data[m_length]); end; function container.at(index: longInt): longInt; begin at := m_data[index]; end; function container.empty(): boolean; begin empty := (m_length = 0); end; function container.size(): longInt; begin size := m_length; end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Jpeg, ExtCtrls, StdCtrls, Menus, CustomizeDlg; type TMainForm = class(TForm) ImageBackground: TImage; ButtonStart: TButton; MainMenu: TMainMenu; N1: TMenuItem; N2: TMenuItem; LabelTetris: TLabel; EditName: TEdit; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; LabelStartText: TLabel; LabelScores: TLabel; LabelSpeed: TLabel; LabelPause: TLabel; PanelGame: TPanel; PanelNextFigure: TPanel; ImageGame: TImage; ImageNextFigure: TImage; TimerGame: TTimer; procedure FormCreate(Sender: TObject); procedure TimerGameTimer(Sender:TObject); procedure FormKeyDown(Sender:TObject;var Key:Word;Shift:TShiftState); procedure ButtonStartClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure N2Click(Sender: TObject); procedure N1Click(Sender: TObject); procedure N4Click(Sender: TObject); procedure N5Click(Sender: TObject); private { Private declarations } public { Public declarations } end; type TTetr = array[1..4, 1..4] of Byte; const tetramino: array [1..7, 1..4] of TTetr = //7 фигурок, у каждой 4 положения ( (((1,1,0,0),(0,1,1,0),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(1,1,0,0),(1,0,0,0),(0,0,0,0)), ((1,1,0,0),(0,1,1,0),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(1,1,0,0),(1,0,0,0),(0,0,0,0))), (((0,1,1,0),(1,1,0,0),(0,0,0,0),(0,0,0,0)), ((1,0,0,0),(1,1,0,0),(0,1,0,0),(0,0,0,0)), ((0,1,1,0),(1,1,0,0),(0,0,0,0),(0,0,0,0)), ((1,0,0,0),(1,1,0,0),(0,1,0,0),(0,0,0,0))), (((0,1,0,0),(1,1,1,0),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(0,1,1,0),(0,1,0,0),(0,0,0,0)), ((0,0,0,0),(1,1,1,0),(0,1,0,0),(0,0,0,0)), ((0,1,0,0),(1,1,0,0),(0,1,0,0),(0,0,0,0))), (((0,0,0,0),(1,1,1,1),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(0,1,0,0),(0,1,0,0),(0,1,0,0)), ((0,0,0,0),(1,1,1,1),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(0,1,0,0),(0,1,0,0),(0,1,0,0))), (((1,1,0,0),(1,1,0,0),(0,0,0,0),(0,0,0,0)), ((1,1,0,0),(1,1,0,0),(0,0,0,0),(0,0,0,0)), ((1,1,0,0),(1,1,0,0),(0,0,0,0),(0,0,0,0)), ((1,1,0,0),(1,1,0,0),(0,0,0,0),(0,0,0,0))), (((1,1,0,0),(0,1,0,0),(0,1,0,0),(0,0,0,0)), ((0,0,1,0),(1,1,1,0),(0,0,0,0),(0,0,0,0)), ((1,0,0,0),(1,0,0,0),(1,1,0,0),(0,0,0,0)), ((1,1,1,0),(1,0,0,0),(0,0,0,0),(0,0,0,0))), (((1,1,0,0),(1,0,0,0),(1,0,0,0),(0,0,0,0)), ((1,1,1,0),(0,0,1,0),(0,0,0,0),(0,0,0,0)), ((0,1,0,0),(0,1,0,0),(1,1,0,0),(0,0,0,0)), ((1,0,0,0),(1,1,1,0),(0,0,0,0),(0,0,0,0))) ); stakanWidth = 10; //ширина стакана stakanHeight = 20; //высота стакана sqrs = 30; //размер 1 кубика colors: Array[1..12] of Integer = (clAqua, clBlue, clFuchsia, clGreen, clLime, clMaroon, clNavy, clOlive, clPurple, clRed, clTeal, clYellow); type TStakan = array[-3..stakanHeight, 1..stakanWidth] of Integer; var MainForm: TMainForm; namePlayer: String; recordPlayer: Integer; tetr, nextTetr: TTetr; numFigure, nextNumFigure, gen, nextGen, figureColor, nextFigureColor, x, y: Integer; stakan: TStakan; implementation uses UnitRecords, UnitControl, UnitInfo; {$R *.dfm} //установка скорости procedure setSpeed (s: Byte); begin MainForm.LabelSpeed.Caption := 'Скорость ' + IntToStr(s); MainForm.TimerGame.Interval := 500 - (s - 1) * 100; end; //прорисовка квадрата procedure drawSquare(i, j, clr: Integer; cnv: TCanvas); var x, y: Integer; begin x := (j - 1) * sqrs; y := (i - 1) * sqrs; with cnv do begin Brush.Color := clr; FillRect(Bounds(x + 2, y + 2, sqrs - 4, sqrs - 4)); Pen.Color := clLtGray; MoveTo(x, y); LineTo(x + sqrs, y); MoveTo(x, y); LineTo(x, y + sqrs); Pen.Color := clWhite; MoveTo(x + 1, y + 1); LineTo(x + sqrs - 2, y + 1); MoveTo(x + 1, y + 1); LineTo(x + 1, y + sqrs - 2); Pen.Color := clBlack; MoveTo(x + sqrs - 1, y + sqrs - 1); LineTo(x, y + sqrs - 1); MoveTo(x + sqrs - 1, y + sqrs - 1); LineTo(x + sqrs - 1, y); MoveTo(x + sqrs - 2, y + sqrs - 2); LineTo(x + 1, y + sqrs - 2); MoveTo(x + sqrs - 2, y + sqrs - 2); LineTo(x + sqrs - 2, y + 1); end; end; //прорисовка фигуры с помощью квадратов procedure showFigure(var x, y, figureColor: Integer; var tetr: TTetr); var i, j: Integer; begin for i := 1 to 4 do for j := 1 to 4 do if (tetr[i, j] = 1) then drawSquare(i + y - 1, j + x - 1, figureColor, MainForm.ImageGame.Canvas); end; //удаление квадрата procedure eraseSquare(i, j: Integer); var x, y: Integer; begin MainForm.ImageGame.Canvas.Brush.Color := clGray; x := (j - 1) * sqrs; y := (i - 1) * sqrs; MainForm.ImageGame.Canvas.FillRect(Bounds(x, y, sqrs, sqrs)); end; //удаление фигуры с помощью удаления квадратов procedure hideFigure(var x, y: Integer; var tetr: TTetr); var i, j: Integer; begin for i := 1 to 4 do for j := 1 to 4 do if (tetr[i, j] = 1) then eraseSquare(i + y - 1, j + x - 1); end; //можно ли сделать поворот фигуры function canRotate(var x, y, gen, numFigure: Integer; var stakan: TStakan): Boolean; var i, j, k: Integer; t: TTetr; begin result := true; k := numFigure; if (k < 4) then inc(k) else k := 1; t := tetramino[gen, k]; for i := 1 to 4 do for j := 1 to 4 do if (t[i, j] = 1) and ((stakan[i + y - 1, j + x - 1] > 0) or (j - 1 + x - 1 < 0) or (j + x > stakanWidth + 1) or (i + y > stakanHeight + 1)) then begin result := false; exit; end; end; //повернуть фигуру procedure rotateFigure(var x, y, gen, numFigure, figureColor: Integer; var tetr: TTetr); begin hideFigure(x, y, tetr); if (numFigure < 4) then inc(numFigure) else numFigure := 1; tetr := tetramino[gen, numFigure]; showFigure(x, y, figureColor, tetr); end; //генерация следующей фигуры procedure genNextFigure(var nextFigureColor, nextNumFigure, nextGen: Integer; var nextTetr: TTetr); begin nextGen := random(7) + 1; nextFigureColor := colors[random(12) + 1]; nextNumFigure := random(4) + 1; nextTetr := tetramino[nextGen, nextNumFigure]; end; //вылет следующей фигуры procedure nextFigure(var x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor: integer); var i, j: Integer; o: Boolean; begin o := true; gen := nextGen; numFigure := nextNumFigure; tetr := nextTetr; figureColor := nextFigureColor; for i := 4 downto 1 do begin for j := 1 to 4 do begin if (tetr[i, j] = 1)then begin y := -3 + (4 - i); o := false; end; if o = false then break; end; if o = false then break; end; x := Round(stakanWidth / 2); //фигура падает примерно с середины genNextFigure(nextFigureColor, nextNumFigure, nextGen, nextTetr); MainForm.ImageNextFigure.Canvas.Brush.Color := clGray; MainForm.ImageNextFigure.Canvas.FillRect(Bounds(0, 0, sqrs * 4, sqrs * 4)); for i := 1 to 4 do for j := 1 to 4 do if nextTetr[i, j] = 1 then drawSquare(i, j, nextFigureColor, MainForm.ImageNextFigure.Canvas); end; //начинаем новую игру procedure newGame(var x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor: Integer; var tetr: TTetr; var stakan: TStakan); var i, j: Integer; begin for i := -3 to stakanHeight do for j := 1 to stakanWidth do stakan[i, j] := 0; MainForm.ImageGame.Canvas.Brush.Color := clGray; MainForm.ImageGame.Canvas.FillRect(Bounds(0, 0, sqrs * stakanWidth, sqrs * stakanHeight)); RecordPlayer := 0; MainForm.LabelScores.Caption := 'Счет ' + IntToStr(RecordPlayer); setSpeed(1); randomize; genNextFigure(nextFigureColor, nextNumFigure, nextGen, nextTetr); nextFigure(x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor); showFigure(x, y, figureColor, tetr); MainForm.LabelPause.Caption := ''; MainForm.TimerGame.Enabled := true; end; //можно ли сдвинуть фигуру влево function canMoveLeft(var tetr: TTetr; var stakan: TStakan): Boolean; var i, j: Integer; begin result := true; for i := 1 to 4 do for j := 1 to 4 do if (tetr[i, j] = 1) and ((stakan[i + y - 1, j - 1 + x - 1] > 0) or (j - 1 + x - 1 = 0)) then begin result := false; exit; end; end; //можно ли сдвинуть фигуру вправо function canMoveRight(var tetr: TTetr; var stakan: TStakan): Boolean; var i, j: Integer; begin result := true; for i := 1 to 4 do for j := 1 to 4 do if (tetr[i, j] = 1) and ((stakan[i + y - 1, j + x] > 0) or (j + x = stakanWidth + 1)) then begin result := false; exit; end; end; //можно ли фигуре двигаться вниз function canMoveDown(var tetr: TTetr; var stakan: TStakan): Boolean; var i, j: Integer; begin result := true; for i := 4 downto 1 do for j := 1 to 4 do if (tetr[i, j] = 1) and ((stakan[i + y, j + x - 1] > 0) or (i + y = stakanHeight + 1)) then begin result := false; exit; end; end; //проверка конца игры function gameOver(var stakan: TStakan): Boolean; var i: Integer; begin Result := false; for i := 1 to stakanWidth do if (stakan[0, i] > 0) then begin Result := true; Exit; end; end; //проверяем стакан на заполенность, удаляем строки и начисляем очки, при надобности procedure checkStakan(var recordPlayer: integer; var stakan: TStakan); var i, j, k, lines, c: Integer; begin with MainForm.ImageGame.Canvas do begin lines := 0; for i := 1 to stakanHeight do begin c := 0; for j := 1 to stakanWidth do if (stakan[i, j] > 0) then inc(c); if (c = stakanWidth) then begin inc(lines); for k := 1 to stakanWidth do eraseSquare(i, k); for k := 1 to i - 1 do for j := 1 to stakanWidth do begin stakan[i - k + 1, j] := stakan[i - k, j]; if stakan[i - k + 1, j] > 0 then drawSquare(i - k + 1, j, stakan[i - k + 1, j], MainForm.ImageGame.Canvas); stakan[i - k, j] := 0; eraseSquare(i - k, j); end; end; end; if (lines = 1) then recordPlayer := recordPlayer + lines * 100; if (lines = 2) then recordPlayer := recordPlayer + lines * 200; if (lines = 3) then recordPlayer := recordPlayer + lines * 300; if (lines = 4) then recordPlayer := recordPlayer + lines * 400; if (recordPlayer >= 1000) and (recordPlayer < 3000) then setSpeed(2); if (recordPlayer >= 3000) and (recordPlayer < 6000) then setSpeed(3); if (recordPlayer >= 6000) and (recordPlayer < 10000) then setSpeed(4); if (recordPlayer >= 10000) then setSpeed(5); MainForm.LabelScores.Caption := 'Счет ' + IntToStr(recordPlayer); end; end; //фиксируем фигуру procedure fixFigure(var figureColor: Integer; var tetr: TTetr; var stakan: TStakan); var i, j: Integer; begin for i := 1 to 4 do for j := 1 to 4 do if (tetr[i, j] = 1) then stakan[y + i - 1, x + j - 1] := figureColor; end; //если фигура не может идти вниз, фиксируем ее, проверяем стакан, заканчиваем игру, при надобности procedure stopMove(var x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor, recordPlayer: integer; var tetr: TTetr; var namePlayer: String; var stakan: TStakan); var outFile1: TextFile; begin fixFigure(figureColor, tetr, stakan); checkStakan(recordPlayer, stakan); if not gameOver(stakan) then begin nextFigure(x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor); showFigure(x, y, figureColor, tetr); end else begin MainForm.TimerGame.Enabled := False; AssignFile(outFile1, 'names.txt'); Append(outFile1); writeln(outFile1, NamePlayer); CloseFile(outFile1); AssignFile(outFile1, 'records.txt'); Append(outFile1); writeln(outFile1, RecordPlayer); CloseFile(outFile1); Application.MessageBox(PChar('Конец игры!'), PChar('Тетрис'), MB_ICONINFORMATION + MB_OK); end; end; procedure moveLeft(var x, y, figureColor: Integer; var tetr: TTetr); begin hideFigure(x, y, tetr); dec(x); showFigure(x, y, figureColor, tetr); end; procedure moveRight(var x, y, figureColor: Integer; var tetr: TTetr); begin hideFigure(x, y, tetr); inc(x); showFigure(x, y, figureColor, tetr); end; procedure moveDown(var x, y, figureColor: Integer; var tetr: TTetr); begin hideFigure(x, y, tetr); inc(y); showFigure(x, y, figureColor, tetr); end; //убрать поле игры procedure HideField; begin with MainForm do begin PanelGame.Visible := false; PanelNextFigure.Visible := false; ImageGame.Visible := false; ImageGame.Visible := false; LabelScores.Visible := false; LabelSpeed.Visible := false; LabelPause.Visible := false; TimerGame.Enabled := false; end; end; //показать начальное меню procedure ShowMenu; begin with MainForm do begin //убрать фокус с кнопки ButtonStart.ControlState := [csFocusing]; //загрузка фона with ImageBackground do begin Picture.LoadFromFile('BackGround.jpg'); //$004204C1 Left := -88; Top := -64; Height := 781; Width := 805; end; //начальная кнопка with ButtonStart do begin Visible := true; Font.Name := 'ObelixPro'; Font.Size := 30; Left := 200; Top := 560; Height := 105; Width := 321; end; //текст "ТЕТРИС" with LabelTetris do begin Visible := true; Font.Name := 'ObelixPro'; Font.Size := 120; Left := 20; Top := 32; Height := 197; Width := 800; end; //текст над полем ввода никнейма with LabelStartText do begin Visible := true; Font.Name := 'ObelixPro'; Font.Size := 17; Left := 200; Top := 360; Height := 29; Width := 400; end; //поле ввода никнейма with EditName do begin Visible := true; Font.Size := 18; Left := 200; Top := 400; Height := 37; Width := 321; end; end; end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not gameOver(stakan) then case key of 27: if ButtonStart.Visible = false then begin TimerGame.Enabled := False; if (Application.MessageBox(PChar('Выйти в главное меню?'), PChar('Тетрис'), MB_ICONQUESTION + MB_YESNO) = IDYES) then begin with MainForm do begin ClientHeight := 695; ClientWidth := 717; Top := Top - 50; Left := Left - 100; HideField; ShowMenu; end; end else TimerGame.Enabled := True; LabelPause.Caption := ''; end else Close; 37: if TimerGame.Enabled and canMoveLeft(tetr, stakan) then moveleft(x, y, figureColor, tetr); 38: if TimerGame.Enabled and canRotate(x, y, gen, numFigure, stakan) then rotateFigure(x, y, gen, numFigure, figureColor, tetr); 39: if TimerGame.Enabled and canMoveRight(tetr, stakan) then moveRight(x, y, figureColor, tetr); 40: begin if TimerGame.Enabled and canMoveDown(tetr, stakan) then moveDown(x, y, figureColor, tetr) else if TimerGame.Enabled then stopMove(x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor, recordPlayer, tetr, namePlayer, stakan); end; 32: begin if TimerGame.Enabled then begin LabelPause.Caption := 'Пауза!'; TimerGame.Enabled := False; end else begin LabelPause.Caption := ''; TimerGame.Enabled := True; end; end; end else if gameOver(stakan) then begin case key of 27: if ButtonStart.Visible = false then begin TimerGame.Enabled := False; if (Application.MessageBox(PChar('Выйти в главное меню?'), PChar('Тетрис'), MB_ICONQUESTION + MB_YESNO) = IDYES) then begin with MainForm do begin ClientHeight := 695; ClientWidth := 717; Top := Top - 50; Left := Left - 100; HideField; ShowMenu; end; end; end else Close; end; end; end; //каждый интервал времени что-то делаем procedure TMainForm.TimerGameTimer(Sender: TObject); begin if canMoveDown(tetr, stakan) then moveDown(x, y, figureColor, tetr) else stopMove(x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor, recordPlayer, tetr, namePlayer, stakan); end; procedure TMainForm.FormCreate(Sender: TObject); begin MainForm.ClientHeight := 695; MainForm.ClientWidth := 717; //добавление шрифта AddFontResource('ObelixPro.ttf'); ShowMenu; end; procedure TMainForm.ButtonStartClick(Sender: TObject); begin //запись никнейма NamePlayer := trim(EditName.Text); if NamePlayer = '' then begin MessageBox(0,'Никнейм не может быть пустым','Тетрис',MB_ICONINFORMATION + MB_OK); end else begin //подготовка поля к игре LabelStartText.Visible := false; LabelTetris.Visible := false; ButtonStart.Visible := false; EditName.Visible := false; //подготовка поля игры with imageGame do begin Visible := true; Top := 2; Left := 2; Width := stakanWidth * sqrs; Height := stakanHeight * sqrs; end; with PanelGame do begin Visible := true; Top := 5; Left := 5; Width := ImageGame.Width + 4; Height := ImageGame.Height + 4; end; with ImageNextFigure do begin Visible := true; Top := 2; Left := 2; Width := sqrs * 4; Height := ImageNextFigure.Width; end; with PanelNextFigure do begin Visible := true; Top := 5; Left := PanelGame.Left + PanelGame.Width + 10; Width := ImageNextFigure.Width + 4; Height := PanelNextFigure.Width; end; with LabelScores do begin Font.Name := 'ObelixPro'; Visible := true; Top := PanelNextFigure.Top + PanelNextFigure.Height + 10; Left := PanelNextFigure.Left; Font.Color := clWindow; end; with LabelSpeed do begin Font.Name := 'ObelixPro'; Visible := true; Top := LabelScores.Top + LabelScores.Height + 10; Left := PanelNextFigure.Left; Font.Color := clWindow; end; with LabelPause do begin Font.Name := 'ObelixPro'; Visible := true; Top := LabelSpeed.Top * 2; Left := PanelNextFigure.Left; Font.Size := 20; Font.Color := clWindow; end; MainForm.Height := PanelGame.Height + PanelGame.Top + 54; //665; MainForm.Width := PanelNextFigure.Left + PanelNextFigure.Width + 38; //481; MainForm.Top := MainForm.Top + 50; MainForm.Left := MainForm.Left + 100; //ImageGame.Parent.DoubleBuffered := True; newGame(x, y, gen, nextGen, numFigure, nextNumFigure, figureColor, nextFigureColor, tetr, stakan); end; end; procedure TMainForm.FormShow(Sender: TObject); begin //фокус на edit EditName.SetFocus; end; procedure TMainForm.N2Click(Sender: TObject); begin //вызов 2 формы if (not Assigned(FormRecords)) then begin FormRecords := TFormRecords.Create(Self); with FormRecords do begin Top := MainForm.Top; Left := MainForm.Left - FormRecords.Width - 50; ClientHeight := 516; ClientWidth := 318; end; end; FormRecords.Show; end; procedure TMainForm.N1Click(Sender: TObject); begin if not gameOver(stakan) then begin if ButtonStart.Visible = false then begin TimerGame.Enabled := False; if (Application.MessageBox(PChar('Выйти в главное меню?'), PChar('Тетрис'), MB_ICONQUESTION + MB_YESNO) = IDYES) then begin with MainForm do begin ClientHeight := 695; ClientWidth := 717; Top := Top - 50; Left := Left - 100; HideField; ShowMenu; end; end else TimerGame.Enabled := True; LabelPause.Caption := ''; end; end else if gameOver(stakan) then begin if ButtonStart.Visible = false then begin TimerGame.Enabled := False; if (Application.MessageBox(PChar('Выйти в главное меню?'), PChar('Тетрис'), MB_ICONQUESTION + MB_YESNO) = IDYES) then begin with MainForm do begin ClientHeight := 695; ClientWidth := 717; Top := Top - 50; Left := Left - 100; HideField; ShowMenu; end; end; end; end; end; procedure TMainForm.N4Click(Sender: TObject); begin //вызов 3 формы if (not Assigned(FormControl)) then begin FormControl := TFormControl.Create(Self); with FormControl do begin Top := MainForm.Top; Left := MainForm.Left + MainForm.Width + 50; ClientHeight := 400; ClientWidth := 400; end; end; FormControl.Show; end; procedure TMainForm.N5Click(Sender: TObject); begin //вызов 4 формы if (not Assigned(FormInfo)) then begin FormInfo := TFormInfo.Create(Self); with FormInfo do begin Top := MainForm.Top + 450; Left := MainForm.Left + MainForm.Width + 50; ClientHeight := 200; ClientWidth := 400; end; end; FormInfo.Show; end; end.
unit uCalculadoraTests; interface uses DUnitX.TestFramework, uCalculadora; type [TestFixture] TCalculadoraTests = class(TObject) private FCalculadora: TCalculadora; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestSomar; [Test] procedure TestSubtrair; [Test] procedure TestMultiplicar; [Test] [TestCase('TestDividir','1,2,0.5')] // [TestCase('TestDividirPorZero','12,0,0')] procedure TestDividir(const AValue1, AValue2 : Integer; const AValue3 : Extended); end; implementation procedure TCalculadoraTests.Setup; begin FCalculadora := TCalculadora.Create; end; procedure TCalculadoraTests.TearDown; begin FCalculadora.Free; end; procedure TCalculadoraTests.TestDividir(const AValue1, AValue2 : Integer; const AValue3 : Extended); begin Assert.AreEqual(AValue3, FCalculadora.Dividir(AValue1, AValue2)); end; procedure TCalculadoraTests.TestMultiplicar; begin Assert.AreEqual(12, FCalculadora.Multiplicar(3, 4)); end; procedure TCalculadoraTests.TestSomar; begin Assert.AreEqual(2, FCalculadora.Somar(1, 1)); end; procedure TCalculadoraTests.TestSubtrair; begin Assert.AreEqual(10, FCalculadora.Subtrair(15, 5)); end; initialization TDUnitX.RegisterTestFixture(TCalculadoraTests); end.
unit ParametrosEmpresa; interface uses TipoRegimeTributario, EnderecoNFCe; type TParametrosEmpresa = class private FCNPJ: String; FIE: String; FRazao: String; FFantasia: String; FEndereco: TEndereco; FRegime: TTipoRegimeTributario; private procedure SetCNPJ(const Value: String); procedure SetIE(const Value: String); procedure SetRazao(const Value: String); procedure SetFantasia(const Value: String); procedure SetEndereco(const Value: TEndereco); procedure SetRegime(const Value: TTipoRegimeTributario); public property CNPJ :String read FCNPJ write SetCNPJ; property IE :String read FIE write SetIE; property Razao :String read FRazao write SetRazao; property Fantasia :String read FFantasia write SetFantasia; property Endereco :TEndereco read FEndereco; property Regime :TTipoRegimeTributario read FRegime write SetRegime; public constructor Create; destructor Destroy; override; end; implementation uses SysUtils, ExcecaoCampoNaoInformado; { TParametrosEmpresa } constructor TParametrosEmpresa.Create(); begin FCNPJ := ''; FIE := ''; FRazao := ''; FFantasia := ''; FEndereco := TEndereco.Create; FRegime := trtSimplesNacional; end; destructor TParametrosEmpresa.Destroy; begin FreeAndNil(FEndereco); inherited; end; procedure TParametrosEmpresa.SetCNPJ(const Value: String); begin if (Trim(Value) = '') then raise TExcecaoCampoNaoInformado.Create('CNPJ'); FCNPJ := Value; end; procedure TParametrosEmpresa.SetEndereco(const Value: TEndereco); begin FEndereco := Value; end; procedure TParametrosEmpresa.SetFantasia(const Value: String); begin if ('' = Trim(Value)) then raise TExcecaoCampoNaoInformado.Create('Fantasia'); FFantasia := Value; end; procedure TParametrosEmpresa.SetIE(const Value: String); begin if (Trim(Value) = '') then raise TExcecaoCampoNaoInformado.Create('IE'); FIE := Value; end; procedure TParametrosEmpresa.SetRazao(const Value: String); begin if ('' = Trim(Value)) then raise TExcecaoCampoNaoInformado.Create('Razao'); FRazao := Value; end; procedure TParametrosEmpresa.SetRegime(const Value: TTipoRegimeTributario); begin if (Integer(Value) <= 0) then raise TExcecaoCampoNaoInformado.Create('Regime'); FRegime := Value; end; end.
UNIT BeRoZLIB; {$IFDEF FPC} {$MODE DELPHI} {$WARNINGS OFF} {$HINTS OFF} {$OVERFLOWCHECKS OFF} {$RANGECHECKS OFF} {$IFDEF CPUI386} {$DEFINE CPU386} {$ASMMODE INTEL} {$ENDIF} {$IFDEF FPC_LITTLE_ENDIAN} {$DEFINE LITTLE_ENDIAN} {$ELSE} {$IFDEF FPC_BIG_ENDIAN} {$DEFINE BIG_ENDIAN} {$ENDIF} {$ENDIF} {$ELSE} {$DEFINE LITTLE_ENDIAN} {$IFNDEF CPU64} {$DEFINE CPU32} {$ENDIF} {$OPTIMIZATION ON} {$ENDIF} INTERFACE USES BeRoStream,BeRoUtils; FUNCTION ZCompressStream(InStream,OutStream:TBeRoStream;Level:INTEGER=6):BOOLEAN; IMPLEMENTATION USES BeRoZLIBCore; FUNCTION ZCompressStream(InStream,OutStream:TBeRoStream;Level:INTEGER=6):BOOLEAN; CONST BufferSize=32768; TYPE PBuffer=^TBuffer; TBuffer=ARRAY[0..BufferSize-1] OF CHAR; VAR zstream:z_stream; zresult:INTEGER; InBuffer:PBuffer; OutBuffer:PBuffer; InSize:INTEGER; OutSize:INTEGER; BEGIN RESULT:=FALSE; TRY NEW(InBuffer); NEW(OutBuffer); FastFillChar(zstream,SIZEOF(z_stream),#0); IF DeflateInit(zstream,Level)<0 THEN EXIT; InStream.Seek(0); InSize:=InStream.Read(InBuffer^,BufferSize); WHILE InSize>0 DO BEGIN zstream.next_in:=POINTER(InBuffer); zstream.avail_in:=InSize; REPEAT zstream.next_out:=POINTER(OutBuffer); zstream.avail_out:=BufferSize; IF deflate(zstream,Z_NO_FLUSH)<0 THEN EXIT; OutSize:=BufferSize-zstream.avail_out; OutStream.Write(OutBuffer^,OutSize); UNTIL (zstream.avail_in=0) AND (zstream.avail_out>0); InSize:=InStream.Read(InBuffer^,BufferSize); END; REPEAT zstream.next_out:=POINTER(OutBuffer); zstream.avail_out:=BufferSize; zresult:=deflate(zstream,Z_FINISH); IF zresult<0 THEN EXIT; OutSize:=BufferSize-zstream.avail_out; OutStream.Write(OutBuffer^,OutSize); UNTIL (zresult=Z_STREAM_END) AND (zstream.avail_out>0); RESULT:=deflateEnd(zstream)>=0; DISPOSE(InBuffer); DISPOSE(OutBuffer); EXCEPT END; END; END.
unit QEngine.Core; interface uses QuadEngine, QCore.Types, QEngine.Types, QEngine.Device, QEngine.Render, QEngine.Camera, QEngine.Texture, QEngine.Font, Strope.Math; type TQuadEngine = class sealed (TBaseObject, IQuadEngine) strict private FDefaultResolution: TVectorI; FCurrentResolution: TVectorI; FQuadDevice: TQuadDevice; FQuadRender: TQuadRender; FCamera: IQuadCamera; function GetDevice(): IQuadDevice; function GetRender(): IQuadRender; function GetCamera(): IQuadCamera; procedure SetCamera(const ACamera: IQuadCamera); function GetDefaultResolution(): TVectorI; function GetCurrentResolution(): TVectorI; private constructor Create(const ADefaultResolution, ACurrentResolution: TVector2I); public destructor Destroy; override; function CreateCamera(): IQuadCamera; function CreateTexture(): TQuadTexture; function CreateFont(): TQuadFont; property QuadDevice: IQuadDevice read GetDevice; property QuadDeviceEx: TQuadDevice read FQuadDevice; property QuadRender: IQuadRender read GetRender; property QyadRenderEx: TQuadRender read FQuadRender; ///<summary>Камера, которую учитывает движок при отрисовке.</summary> property Camera: IQuadCamera read GetCamera write SetCamera; ///<summary>Размер экрана по-умолчанию, к которому корректирует /// размеры и позиции текущая камера.</summary> property DefaultResolution: TVectorI read GetDefaultResolution; ///<summary>Текущий размер экрана.</summary> property CurrentResolution: TVectorI read GetCurrentResolution; end; var TheEngine: TQuadEngine = nil; TheDevice: IQuadDevice = nil; TheRender: IQuadRender = nil; procedure CreateEngine(const ADefaultResolution, ACurrentResolution: TVector2I); implementation uses SysUtils, Math; type TQuadCamera = class sealed (TBaseObject, IQuadCamera) strict private FCurrentResolution: TVectorF; FDefaultResolution: TVectorF; FHalfDScreen: TVectorF; FHalfCScreen: TVectorF; FUseCorrection: Boolean; FCorrectionShift: TVectorF; FCorrectionScale: TVectorF; FPosition: TVectorF; FScale: TVectorF; function DSP2CSP(const APos: TVectorF): TVectorF; function CSP2DSP(const APos: TVectorF): TVectorF; function WP2DSP(const APos: TVectorF): TVectorF; function DSP2WP(const APos: TVectorF): TVectorF; function WP2CSP(const APos: TVectorF): TVectorF; function CSP2WP(const APos: TVectorF): TVectorF; function DSS2CSS(const ASize: TVectorF): TVectorF; function CSS2DSS(const ASize: TVectorF): TVectorF; function WS2CSS(const ASize: TVectorF): TVectorF; function CSS2WS(const ASize: TVectorF): TVectorF; function WS2DSS(const ASize: TVectorF): TVectorF; function DSS2WS(const ASize: TVectorF): TVectorF; function GetPosition(): TVectorF; procedure SetPosition(const APosition: TVectorF); function GetScale(): TVectorF; procedure SetScale(const AScale: TVectorF); function GetUseCorrection(): Boolean; procedure SetUseCorrection(AUseCorrection: Boolean); function GetResolution(): TVectorF; function GetDefaultResolution(): TVectorF; function GetScreenPos(const APosition: TVectorF; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetScreenPos(X, Y: Single; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetScreenSize(const ASize: TVectorF; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetScreenSize(Width, Height: Single; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetWorldPos(const APosition: TVectorF; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetWorldPos(X, Y: Single; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetWorldSize(const ASize: TVectorF; AIsUseCorrection: Boolean = True): TVectorF; overload; function GetWorldSize(Width, Height: Single; AIsUseCorrection: Boolean = True): TVectorF; overload; public constructor Create(const ADefaultResolution, ACurrentResolution: TVectorI); property Position: TVectorF read GetPosition write SetPosition; property Scale: TVectorF read GetScale write SetScale; property UseCorrection: Boolean read GetUseCorrection write SetUseCorrection; property Resolution: TVectorF read GetResolution; property DefaultResolution: TVectorF read GetDefaultResolution; end; procedure CreateEngine(const ADefaultResolution, ACurrentResolution: TVector2I); begin if not Assigned(TheEngine) then TheEngine := TQuadEngine.Create(ADefaultResolution, ACurrentResolution); end; {$REGION ' TQuadCamera '} constructor TQuadCamera.Create(const ADefaultResolution, ACurrentResolution: TVector2I); var AValue: Single; begin FCurrentResolution := ACurrentResolution; FDefaultResolution := ADefaultResolution; FHalfDScreen := FDefaultResolution * 0.5; FHalfCScreen := FCurrentResolution * 0.5; FCorrectionScale := FCurrentResolution.ComponentwiseDivide(FDefaultResolution); if FCorrectionScale.X > FCorrectionScale.Y then begin FCorrectionScale.Create(FCorrectionScale.Y, FCorrectionScale.Y); AValue := (FCurrentResolution.X - FDefaultResolution.X * FCorrectionScale.X) * 0.5; FCorrectionShift.Create(AValue, 0); end else begin FCorrectionScale.Create(FCorrectionScale.X, FCorrectionScale.X); AValue := (FCurrentResolution.Y - FDefaultResolution.Y * FCorrectionScale.Y) * 0.5; FCorrectionShift.Create(0, AValue); end; FUseCorrection := True; FScale.Create(1, 1); FPosition := ZeroVectorF; end; function TQuadCamera.DSP2CSP(const APos: TVectorF): TVectorF; begin Result := FCorrectionShift + APos.ComponentwiseMultiply(FCorrectionScale); end; function TQuadCamera.CSP2DSP(const APos: TVectorF): TVectorF; begin Result := (APos - FCorrectionShift).ComponentwiseDivide(FCorrectionScale); end; function TQuadCamera.WP2CSP(const APos: TVectorF): TVectorF; begin Result := (APos - FPosition).ComponentwiseMultiply(FScale) + FHalfCScreen; end; function TQuadCamera.CSP2WP(const APos: TVectorF): TVectorF; begin Result := (APos - FHalfCScreen).ComponentwiseDivide(FScale) + FPosition; end; function TQuadCamera.WP2DSP(const APos: TVectorF): TVectorF; begin Result := (APos - FPosition).ComponentwiseMultiply(FScale) + FHalfDScreen; end; function TQuadCamera.DSP2WP(const APos: TVectorF): TVectorF; begin Result := (APos - FHalfDScreen).ComponentwiseDivide(FScale) + FPosition; end; function TQuadCamera.DSS2CSS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseMultiply(FCorrectionScale); end; function TQuadCamera.CSS2DSS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseDivide(FCorrectionScale); end; function TQuadCamera.WS2CSS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseDivide(FScale); end; function TQuadCamera.CSS2WS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseMultiply(FScale); end; function TQuadCamera.WS2DSS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseDivide(FScale); end; function TQuadCamera.DSS2WS(const ASize: TVectorF): TVectorF; begin Result := ASize.ComponentwiseMultiply(FScale); end; function TQuadCamera.GetDefaultResolution: TVectorF; begin Result := FDefaultResolution; end; function TQuadCamera.GetPosition: TVectorF; begin Result := FPosition; end; function TQuadCamera.GetResolution: TVectorF; begin Result := FCurrentResolution; end; function TQuadCamera.GetScale: TVectorF; begin Result := FScale; end; function TQuadCamera.GetScreenPos(const APosition: TVectorF; AIsUseCorrection: Boolean): TVectorF; begin if FUseCorrection and AIsUseCorrection then begin Result := WP2DSP(APosition); Result := DSP2CSP(Result); end else Result := WP2CSP(APosition); end; function TQuadCamera.GetScreenSize(const ASize: TVectorF; AIsUseCorrection: Boolean): TVectorF; begin if FUseCorrection and AIsUseCorrection then begin Result := WS2DSS(ASize); Result := DSS2CSS(Result); end else Result := WS2CSS(ASize); end; function TQuadCamera.GetUseCorrection: Boolean; begin Result := FUseCorrection; end; function TQuadCamera.GetWorldPos(const APosition: TVectorF; AIsUseCorrection: Boolean): TVectorF; begin if FUseCorrection and AIsUseCorrection then begin Result := CSP2DSP(APosition); Result := DSP2WP(Result); end else Result := CSP2WP(APosition); end; function TQuadCamera.GetWorldSize(const ASize: TVectorF; AIsUseCorrection: Boolean): TVectorF; begin if FUseCorrection and AIsUseCorrection then begin Result := CSS2DSS(ASize); Result := DSS2WS(Result); end else Result := CSS2WS(ASize); end; procedure TQuadCamera.SetPosition(const APosition: TVectorF); begin FPosition := APosition; end; procedure TQuadCamera.SetScale(const AScale: TVectorF); begin FScale := AScale; end; procedure TQuadCamera.SetUseCorrection(AUseCorrection: Boolean); begin FUseCorrection := AUseCorrection; end; function TQuadCamera.GetScreenPos(X, Y: Single; AIsUseCorrection: Boolean): TVectorF; begin GetScreenPos(Vec2F(X, Y), AIsUseCorrection); end; function TQuadCamera.GetScreenSize(Width, Height: Single; AIsUseCorrection: Boolean): TVectorF; begin GetScreenSize(Vec2F(Width, Height), AIsUseCorrection); end; function TQuadCamera.GetWorldPos(X, Y: Single; AIsUseCorrection: Boolean): TVectorF; begin GetWorldPos(Vec2F(X, Y), AIsUseCorrection); end; function TQuadCamera.GetWorldSize(Width, Height: Single; AIsUseCorrection: Boolean): TVectorF; begin GetWorldSize(Vec2F(Width, Height), AIsUseCorrection); end; {$ENDREGION} {$REGION ' TQuadEngine '} constructor TQuadEngine.Create; var ARender: IQuadRender; begin Inc(FRefCount); FDefaultResolution := ADefaultResolution; FCurrentResolution := ACurrentResolution; FQuadDevice := TQuadDevice.Create(Self); FQuadDevice.Device.CreateRender(ARender); FQuadRender := TQuadRender.Create(Self, ARender); TheDevice := QuadDevice; TheRender := QuadRender; end; destructor TQuadEngine.Destroy; begin TheRender.Finalize; FreeAndNil(FQuadDevice); FreeAndNil(FQuadRender); TheDevice := nil; TheRender := nil; inherited; end; function TQuadEngine.GetDevice; begin Result := FQuadDevice; end; function TQuadEngine.GetRender; begin Result := FQuadRender; end; function TQuadEngine.GetCamera; begin Result := FCamera; end; procedure TQuadEngine.SetCamera(const ACamera: IQuadCamera); begin FCamera := ACamera; end; function TQuadEngine.GetDefaultResolution: TVectorI; begin Result := FDefaultResolution; end; function TQuadEngine.GetCurrentResolution: TVectorI; begin Result := FCurrentResolution; end; function TQuadEngine.CreateCamera; begin Result := TQuadCamera.Create(DefaultResolution, CurrentResolution); end; function TQuadEngine.CreateTexture: TQuadTexture; var ATexture: IQuadTexture; begin FQuadDevice.Device.CreateTexture(ATexture); Result := TQuadTexture.Create(Self, ATexture); ATexture := nil; end; function TQuadEngine.CreateFont: TQuadFont; var AFont: IQuadFont; begin FQuadDevice.Device.CreateFont(AFont); Result := TQuadFont.Create(Self, AFont); end; {$ENDREGION} end.
unit View.PermissionListForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.TemplateForm, Data.DB, Vcl.Menus, GrdPMenu, JvComponentBase, JvFormPlacement, Vcl.Grids, Vcl.DBGrids, JvExDBGrids, JvDBGrid, Vcl.ExtCtrls, Model.Interfaces, Model.ProSu.Interfaces, Model.FormDeclarations, Model.Declarations, Model.ProSu.InterfaceActions, Vcl.ComCtrls, JvExComCtrls, JvDBTreeView; type TPermissionListForm = class(TTemplateForm) JvDBTreeView1: TJvDBTreeView; Splitter1: TSplitter; procedure FormCreate(Sender: TObject); procedure JvDBTreeView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure JvDBTreeView1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private fViewModel : IPermissionListViewModelInterface; fPossibleParentPermissionId : Integer; lastHintNode : TTreeNode; procedure NotificationFromProvider(const notifyClass : INotificationClass); procedure SetViewModel(const newViewModel: IPermissionListViewModelInterface); function GetViewModel : IPermissionListViewModelInterface; procedure NewPermission(aDS: TDataset); protected procedure OpenDataset; override; function GetProvider : IProviderInterface; override; public procedure AddNew; override; //procedure DeleteCurrent; override; procedure EditCurrent; override; procedure Print; override; property ViewModel : IPermissionListViewModelInterface read GetViewModel write SetViewModel; end; var PermissionListForm: TPermissionListForm; implementation uses //View.PermissionEdit, ViewModel.PermissionList, Model.LanguageDictionary, Spring.DesignPatterns, Model.Fabrication, MainDM, View.PermissionEdit; {$R *.dfm} procedure TPermissionListForm.EditCurrent; begin try TPermissionEditForm.Execute(efcmdEdit, ViewModel.SubscriberToEdit, fObjectDataset); finally fObjectDataset.Cancel; end; end; procedure TPermissionListForm.FormCreate(Sender: TObject); begin inherited; ViewModel.SubscriberToEdit.SetUpdateSubscriberMethod(NotificationFromProvider); end; function TPermissionListForm.GetProvider: IProviderInterface; begin Result := ViewModel.Provider; end; function TPermissionListForm.GetViewModel: IPermissionListViewModelInterface; begin if not Assigned(fViewModel) then fViewModel := CreatePermissionListViewModelClass; Result := fViewModel; end; procedure TPermissionListForm.JvDBTreeView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=vk_Return then begin EditCurrent; end; end; procedure TPermissionListForm.JvDBTreeView1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var tree: TJvDBTreeView; hoverNode: TTreeNode; hitTest : THitTests; begin {if (Sender is TJvDBTreeView) then tree := TJvDBTreeView(Sender) else Exit; hoverNode := tree.GetNodeAt(X, Y) ; hitTest := tree.GetHitTestInfoAt(X, Y) ; if (lastHintNode <> hoverNode) then begin Application.CancelHint; if (hitTest <= [htOnItem, htOnIcon, htOnLabel, htOnStateIcon]) then begin lastHintNode := hoverNode; tree.Hint := IntToStr(Integer(hoverNode.Index))+' '+hoverNode.Text; end; end; } end; procedure TPermissionListForm.AddNew; begin try if fObjectDataset.RecordCount>0 then fPossibleParentPermissionId := fObjectDataset.FieldByName('PermissionId').AsInteger else fPossibleParentPermissionId := 0; TPermissionEditForm.Execute(efcmdAdd, ViewModel.SubscriberToEdit, fObjectDataset); finally fObjectDataset.Cancel; end; end; procedure TPermissionListForm.NewPermission(aDS: TDataset); begin //fObjectDataset.FieldByName('CompanyId').AsInteger := DMMain.Company.CompanyId; if fPossibleParentPermissionId>=0 then fObjectDataset.FieldByName('ParentId').AsInteger := fPossibleParentPermissionId; end; procedure TPermissionListForm.NotificationFromProvider( const notifyClass: INotificationClass); var tmpNotifClass : TNotificationClass; tmpErrorNotifClass : TErrorNotificationClass; begin if notifyClass is TNotificationClass then begin tmpNotifClass := notifyClass as TNotificationClass; end; if notifyClass is TErrorNotificationClass then begin tmpErrorNotifClass := notifyClass as TErrorNotificationClass; end; end; procedure TPermissionListForm.OpenDataset; begin fObjectDataset.DataList := ViewModel.Model.GetAllPermissions(''); fObjectDataset.Open; DataSource1.DataSet := fObjectDataset; fObjectDataset.OnNewRecord := NewPermission; if fObjectDataset.RecordCount>0 then JvDBTreeView1.Items[0].Expand(True); end; procedure TPermissionListForm.Print; begin end; procedure TPermissionListForm.SetViewModel(const newViewModel: IPermissionListViewModelInterface); begin fViewModel := newViewModel; if not Assigned(fViewModel) then raise Exception.Create('Permission List View Model is required!'); fViewModel.Provider.Subscribe(ViewModel.SubscriberToEdit); end; var CreateForm : TFactoryMethod<TTemplateForm>; initialization CreateForm := function : TTemplateForm begin if not DMMain.Authorize('131,132,133,134,135') then raise Exception.Create(Model.LanguageDictionary.MessageDictionary().GetMessage('SNotAuthorized')+#13#10+'TEmployeeListForm'); Result := TPermissionListForm.Create(Application); end; MyFactory.RegisterForm<TPermissionListForm>('TPermissionListForm', CreateForm); end.
unit uClasseBoletim; { ** ATENÇÃO ** - As Querys utilizadas por essa unit estão em DMBoletim, Composicao um datamodule exclusivo para essa classe. Quase todas as Querys estão com a propriedade Cursortype definida como ctOpenForwardOnly, o que significa que a query é aberta como somente leitura, e só é possível avançar nos registros, não pode voltar ou ir para o primeiro. Qualquer tentativa de usar o comando .first ou .prior não irá gerar erro, mas o registro será avançado de qualquer forma. Devido a isso, não uso locate em nenhum ponto do código, toda busca de registros é feita varrendo as tabelas sincronizadamente, comparando seus registros, ou seja, A ORDEM DOS REGISTROS É FUNDAMENTAL, pois espera-se que as tabelas estarão na mesma ordem. Logo, se for necessário alterar a ordem em que os registros aparecem, a ordenação deve ser feita manualmente, nos objetos já gerados(verificar a função Ordenar() para maiores informações). Todo esse trabalho é para otimizar o código. Como não haverá alteração dos dados e será sempre pego o próximo registro, a leitura fica mais rápida.} interface uses Windows, Classes, uDMPrincipal, uFuncoesGeral, sysutils, uDMBoletim, uClasseCalculaNotas, consttipos, uClasseCriterio, contnrs; type TBoletim = class; TGerarBoletim = class; TSetMaiorProgProc = procedure (Sender : TGerarBoletim; MaxProg : Integer); TProgressProc = procedure (Sender : TGerarBoletim; Msg : String; Posicao : Integer); TLinhaBoletim = class(TComponent) private Boletim : TBoletim; public CodDisciplina : String; NomeDisciplina : String; OrdemDisciplina: Integer; Exibir : Boolean; MediaBim, MediaFinal, MediaAntSem1, MediaAntSem2, MediaSem1, // Médias para o 1° e 2° semestre. Somente MediaSem2 : Double; // para sistema de 4 períodos. RecupSem1, // Recuperação para o 1 e 2 semestre RecupSem2: Double; MediaBimTexto, MediaFinalTexto : String; ValorMedia : Double; PercFaltas : Double; ConselhoMedia, // Aprov.por Conselho - alterar média. ConselhoSituacao : Boolean; // Aprov.Cons. - Alterar Situação Situacao : Char; DescricaoSituacao : String; { Os arrays abaixo são criados com dois espaços a mais que o número de períodos (Bimestre) pois O primeiro item (0) não é utilizado e o último é a recuperação. Antes eram Notas[1..5] of .. Ou seja, o primeiro elemento era 1, depois 2 e assim por diante. Depois da alteração para deixar flexível o número de períodos, tive que transformar em array de tamanho variável. Com isso, o array passa a ser de base zero. Para não causar problemas em lugares que já acessavam deixei a primeira posição sem utilizar} NotasNormal : array of Double; NotasRec : array of Double; NotasRecMedia: array of Double; Notas : array of Double; Faltas : array of Integer; Dispensa : array of string; Atrasos : array of Integer; AulasDadas : Array of integer; Dependencia : array of string; function NumPeriodos : Integer; function TotalAtrasos : Integer; function TotalFaltas : Integer; function TotalAulasDadas : Integer; function PecFaltas : String; function FormataNota(Valor: Currency; Campo: TCampoNotaBoletim; Periodo: Integer = 0): String; constructor Create(Owner : TComponent); override; end; TBoletim = class(TComponent) private fLinhas : TList; Gerador : TGerarBoletim; function GetLinha(Index: Integer): TLinhaBoletim; procedure SetLinha(Index: Integer; const Value: TLinhaBoletim); public Matricula : string; NomeAluno : String; Numero : String; // Frequente, Transferido, Remanejado etc. SituacaoTurma : char; // Situação quanto à aprovação (Aprovado, Recuperação etc). SituacaoAprov : char; DescricaoSitAprov : string; DtNascimento : TDateTime; Endereco, Cidade, bairro, Uf, CEP, RG,cidade_Nasc,Uf_Nasc : String; SexoAluno : Integer; //1 - Masculino, 0 - Feminino FrequenciaGlobal: Double; Observacoes : TStringList; function NumLinhas : Integer; property Linhas[Index : Integer] : TLinhaBoletim read GetLinha write SetLinha; default; function NovaLinha : TLinhaBoletim; procedure RemoveLinha(Indice: Integer); constructor Create(Owner : TComponent); override; destructor Destroy; override; end; TDisciplina = record Codigo : String; Nome : String; Ordem : Integer; Sigla : String; Tipo : String; Reprova : Boolean; Historico : Boolean; Cargahoraria : Integer; // Habilitacao : String; // Número de aulas dadas em cada um dos bimestres AulasDadas : array of Integer; end; TGerarBoletim = class(TComponent) private fBoletins : TList; Cron, CronGeral : TCronometro; fDisciplinas : array of TDisciplina; NumInicial, NumFinal : String; Tipo : String; // 'classe' se está imprimindo boletim por classe // 'aluno' se está imprimindo boletim por aluno Codigo : String; // Cód.da classe ou matrícula do aluno, de // acordo com a opção anterior FProgressao: TProgressProc; FMaiorProgressao: TSetMaiorProgProc; function GetBoletim(Indice: Integer): TBoletim; procedure SetBoletim(Indice: Integer; const Value: TBoletim); procedure CarregarDisciplinas; procedure AbrirTabelas; procedure Calcular(Linha : TLinhaBoletim; disciplina: TDisciplina); procedure Carregar(pTipo, pCodigo: String;nbim:integer); procedure ObterInformacoesClasse; function GetDisciplina(Indice: Integer): TDisciplina; procedure SetDisciplina(Indice: Integer; const Value: TDisciplina); protected FPosicao : Integer; Mensagem : String; procedure DoMaiorProg(Value : Integer); procedure Step(Msg : String = ''; Inc : Integer = 1); public Curso : String; Serie : String; Turma : String; Calculo : TCalculaNotas; CodClasse : String; SomenteFrequentes : Boolean; ExibirRemanejados : Boolean; mostrarDiversificadas : Boolean; CapitularDisciplinas: Boolean; AnoLetivo : String; TipoImpressora : Integer; // 0 - Colorida, 1 - Matricial procedure CarregarClasse(sCodClasse : String; pNumInicial : String = '000'; pNumFinal : String = '000';nbim:integer = 0); procedure CarregarAluno(Mat : String;nbim:integer); constructor Create(Owner: TComponent); override; destructor Destroy; override; function NumDisciplina : Integer; property Disciplina[Indice : Integer] : TDisciplina read GetDisciplina write SetDisciplina; property Boletim[Indice : Integer] : TBoletim read GetBoletim write SetBoletim; default; function NovoBoletim : TBoletim; procedure RemoveBoletim(Indice : Integer); function NumBoletins : Integer; procedure LimpaBoletins; procedure Ordenar; class procedure RecalcularDiscComposta(CodDisciplina, CodClasse: String; Periodo : Integer); property OnMaiorProgressao : TSetMaiorProgProc read FMaiorProgressao write FMaiorProgressao; property OnProgressao : TProgressProc read FProgressao write FProgressao; end; implementation function TLinhaBoletim.FormataNota(Valor: Currency; Campo: TCampoNotaBoletim; Periodo: Integer = 0): String; var Mascara : String; sValor : String; posEspaco : Integer; Crit : TCriterio; Conceito : String; Erro : Boolean; begin Crit := Boletim.Gerador.Calculo.Criterio; Mascara := Crit.MascaraNota(campo = cnbMediaFinal); Mascara := Crit.MascaraNota(campo = cnbMediaSem1); Mascara := Crit.MascaraNota(campo = cnbMediaSem2); // Se está dispensado mostra o texto da dispensa if (periodo > 0) and (Dispensa[periodo] <> '') then Result := Dispensa[periodo] // Se está sem nota fica em branco else if (Valor = ntSemNota) then Result := '' else begin Conceito := Crit.ConceitoNota(valor, erro); if Erro then Result := '' else if Conceito <> '' then begin Result := Conceito; if (Boletim.Gerador.TipoImpressora = 1) and (valor < Crit.NotaCorte(Campo, periodo)) then Result := '*' + Result; end else // Se for a nota máxima mostra em extenso se assim configurado if Crit.UsarExtensoMax and (Valor = Crit.NotaMaxima(Campo, Periodo)) then begin sValor := Extenso(Valor); posEspaco := Pos(' ', sValor); if posEspaco < 1 then posEspaco := Length(sValor) + 2; Result := UpperCase(Copy(sValor, 1, 1)) + Copy(sValor, 2, posEspaco - 2); end else // Se for zero mostra em extenso se assim configurado if (Valor = 0) and Crit.UsarExtensoMin then Result := 'Zero' // Se for impressora preto e branco coloca um '*' caso a nota esteja abaixo // abaixo da nota de corte. else if (Boletim.Gerador.TipoImpressora = 1) and (valor < Crit.NotaCorte(Campo, periodo)) then Result := '*' + FormatFloat(Mascara, Valor) // Exibição normal da nota else Result := FormatFloat(Mascara, Valor); if (FloatToStr(StrToFloat(FormatFloat('0.00', Valor))-StrToFloat(FormatFloat('0', Valor)))='0,45') and (Mascara='0.0') then Result := FormatCurr('0', Valor)+',5'; end; end; procedure TGerarBoletim.AbrirTabelas; var sSQL, sSQLTurmas : String; begin with DMBoletim do begin // Abre a tabela de turmas sSQLTurmas := ' FROM Turmas WHERE AnoLetivo = ' + QuotedStr(AnoLetivo); if Tipo = 'classe' then begin sSQLTurmas := sSQLTurmas + ' AND idClasse1 = ' + QuotedStr(CodClasse); if SomenteFrequentes then sSQLTurmas := sSQLTurmas + ' AND Situacao = "F" ' else begin if not ExibirRemanejados then sSQLTurmas := sSQLTurmas + ' AND Situacao <> "R" '; end; if NumInicial <> '000' then sSQLTurmas := sSQLTurmas + ' AND Numero >= ' + QuotedStr(NumInicial); if NumFinal <> '000' then sSQLTurmas := sSQLTurmas + ' AND Numero <= ' + QuotedStr(NumFinal); end else sSQLTurmas := sSQLTurmas + ' AND Mat = ' + QuotedStr(Codigo) + ' AND Situacao <> "R" '; Cron.Start('sqlBolTurmas'); Step('Carregando turmas...', 0); DMPrincipal.OpenSQL(sqlTurmas,'SELECT Mat, Numero, Situacao ' + sSQLTurmas + ' ORDER BY Mat'); Cron.Stop; // Abrindo tabela de alunos Cron.Start('sqlAlunos'); sSQL := ' SELECT Mat, Nome, DtNascimento, Endereco, Bairro, Cidade, CEP, UF, RGAluno, Sexo,cidadeNasc, ufnasc '+ ' FROM Alunos WHERE '; if Tipo = 'classe' then sSQL := sSQL + ' Mat IN (Select Mat ' + sSQLTurmas + ') ORDER BY Mat ' else sSQL := sSQL + ' Mat = ' + QuotedStr(Codigo); Step('Carregando alunos...', 0); DMPrincipal.OpenSQL(sqlAlunos,sSQL); Cron.Stop; // Abrindo tabela de Notas Cron.Start('sqlNotasFaltas'); sSQL := ' SELECT Mat, Disc, Bim, Nota, Falta, Atrasos, NotaRecPeriodo, AulasDadas '+ ' FROM NotasFaltas '+ ' WHERE AnoLetivo = ' + QuotedStr(AnoLetivo) ; if Tipo = 'classe' then sSQL := sSQL + ' AND Mat IN (SELECT Mat ' + sSQLturmas + ')' else sSQL := sSQL + ' AND Mat = ' + QuotedStr(Codigo); sSQL := sSQL + ' ORDER BY Mat, Disc, Bim '; Step('Carregando notas...', 0); DMPrincipal.OpenSQL(sqlNotasFaltas,sSQL); Cron.Stop; Step('Carregando outras informações', 0); // Abrindo tabela de abono de faltas Cron.Start('sqlAbono'); sSQL := 'SELECT Mat, Disc, Bim, Faltas FROM AbonoFaltas WHERE AnoLetivo = ' + QuotedStr(AnoLetivo); if Tipo = 'classe' then sSQL := sSQL + ' AND Mat IN (SELECT Mat ' + sSQLTurmas + ')' else sSQL := sSQL + ' AND Mat = ' + QuotedStr(Codigo); sSQL := sSQL + ' ORDER BY Mat, Disc, Bim '; DMPrincipal.OpenSQL(sqlAbono,sSQL); Cron.Stop; // abrindo tabela de dispensa por Disciplina Cron.Start('sqlDispensa'); sSQL := 'SELECT Mat, Disc, Bim, Tipo FROM Dispensa WHERE AnoLetivo = ' + QuotedStr(AnoLetivo); if Tipo = 'classe' then sSQL := sSQL + ' AND Mat IN (SELECT Mat ' + sSQLTurmas + ')' else sSQL := sSQL + ' AND Mat = ' + QuotedStr(Codigo); sSQL := sSQL + ' ORDER BY Mat, Disc, Bim '; DMPrincipal.OpenSQL(sqlDispensa,sSQL); Cron.Stop; // Abrindo a tabela de Conselho de classe Cron.Start('sqlConselho'); sSQL := 'SELECT Matricula, Disc, AlterarMedia, AlterarSituacao, Media, Mostrarsit_Conselho ' + 'FROM Conselho WHERE AnoLetivo = ' + QuotedStr(AnoLetivo); if Tipo = 'classe' then sSQL := sSQL + ' AND Matricula IN (SELECT Mat ' + sSQLTurmas + ')' else sSQL := sSQL + ' AND Matricula = ' + QuotedStr(Codigo); sSQL := sSQL + ' ORDER BY Matricula,Disc '; DMPrincipal.OpenSQL(sqlConselho,sSQL); Cron.Stop; Cron.Start('sqlDiscDependencias'); sSQL := ' SELECT DISTINCT Dep.Mat, Dep.Disciplina, Dep.LetivoDisciplina, d1.Nome, d1.Sigla, d1.Tipo '+ ' FROM Dependencia Dep '+ ' INNER JOIN Disciplina1 d1 '+ ' ON Dep.Disciplina = d1.Codigo '+ ' AND Dep.LetivoDisciplina = d1.AnoLetivo '+ ' INNER JOIN Turmas t '+ ' ON Dep.Mat = t.Mat '+ ' AND Dep.AnoLetivo = t.AnoLetivo '+ ' AND t.Situacao = "F" '+ ' WHERE Dep.AnoLetivo = ' + QuotedStr(AnoLetivo) ; if Tipo = 'classe' then sSQL := sSQL + ' AND Dep.Mat in (SELECT Mat ' + sSQLTurmas + ')' else sSQL := sSQL + ' AND Dep.Mat = ' + QuotedStr(Codigo) ; sSQL := sSQL + ' ORDER BY Dep.Mat, Dep.Disciplina'; DMPrincipal.OpenSQL(sqlDiscDependencias,sSQL); Cron.Stop; end; end; procedure TGerarBoletim.Calcular(linha : TLinhaboletim; disciplina : TDisciplina); var iBim : Integer; begin Calculo.MediaFinalTexto := ''; Calculo.MediaBimTexto := ''; for iBim := 1 to Calculo.Criterio.NumPeriodos + 1 do begin Calculo.Notas[iBim] := linha.Notas[iBim]; Calculo.NotasRecBim[iBim] := linha.NotasRec[iBim]; Calculo.Faltas[iBim] := linha.faltas[iBim]; Calculo.AulasDadas[iBim] := linha.AulasDadas[iBim]; Calculo.Dispensa[iBim] := linha.Dispensa[iBim]; if linha.Dispensa[iBim] = 'NF' then Calculo.Notas[iBim] := 0 else if linha.Dispensa[iBim] <> '' then Calculo.Notas[iBim] := ntSemNota; end; Calculo.RecupSem1 := linha.RecupSem1; Calculo.RecupSem2 := Linha.RecupSem2; Calculo.valorMedia := Linha.ValorMedia; Calculo.conselhoMedia := Linha.ConselhoMedia; Calculo.conselhoSituacao := Linha.ConselhoSituacao; Calculo.Execute; Linha.MediaBim := Calculo.MediaBim; Linha.MediaFinal := Calculo.MediaFinal; Linha.MediaSem1 := Calculo.MediaSem1; Linha.MediaSem2 := Calculo.MediaSem2; Linha.MediaAntSem1 := Calculo.MediaAntSem1; Linha.MediaAntSem2 := Calculo.MediaAntSem2; if Calculo.MediaBimTexto = '' then Linha.MediaBimTexto := Linha.FormataNota(Calculo.MediaBim, cnbMediaBim) else Linha.MediaBimTexto := Calculo.MediaBimTexto; if Calculo.MediaFinalTexto = '' then Linha.MediaFinalTexto := Linha.FormataNota(Calculo.MediaFinal, cnbMediaFinal) else Linha.MediaFinalTexto := Calculo.MediaFinalTexto; if disciplina.Reprova then begin Linha.Situacao := Calculo.Situacao; linha.DescricaoSituacao := Calculo.DescricaoSituacao; end else begin linha.Situacao := SIT_APROVADO; linha.DescricaoSituacao := 'Aprovado'; end end; procedure TGerarBoletim.CarregarAluno(Mat: String;nbim:integer); begin Carregar('aluno', Mat,nbim); end; procedure TGerarBoletim.CarregarClasse(sCodClasse: String; pNumInicial: String = '000'; pNumFinal: String = '000'; nbim: integer = 0) ; begin if Trim(pNumInicial) = '' then NumInicial := '000' else NumInicial := pNumInicial; if Trim(pNumFinal) = '' then NumFinal := '000' else NumFinal := pNumFinal; Carregar('classe', sCodClasse,nbim); end; procedure TGerarBoletim.ObterInformacoesClasse; begin with DMBoletim do begin Cron.Start('ObterInformacoesClasse'); if Tipo = 'classe' then begin CodClasse := Codigo; DMPrincipal.OpenSQL(sqlClasses, ' SELECT idClasse1, idCursos, Serie, Turma '+ ' FROM Classe1 '+ ' WHERE AnoLetivo = ' + QuotedStr(AnoLetivo) + ' AND idClasse1 = ' + QuotedStr(CodClasse) ); try Curso := sqlClassesidCursos.Value; Serie := sqlClassesSerie.Value; Turma := sqlClassesTurma.Value; finally sqlClasses.Close; end; end else begin DMPrincipal.OpenSQL(sqlClasses, ' SELECT idClasse1, idCursos, Serie, Turma '+ ' FROM Classe1 '+ ' WHERE AnoLetivo = ' + QuotedStr(AnoLetivo) + ' AND idClasse1 IN ( '+ ' SELECT idClasse1 '+ ' FROM Turmas '+ ' WHERE AnoLetivo = ' + QuotedStr(AnoLetivo) + ' AND Mat = ' + QuotedStr(Codigo) + ' AND Situacao <> "R" '+ ' ) '); try CodClasse := sqlClassesidClasse1.Value; Curso := sqlClassesidCursos.Value; Serie := sqlClassesSerie.Value; Turma := sqlClassesTurma.value; finally sqlClasses.Close; end; end; Cron.Stop; end; end; procedure TGerarBoletim.Carregar(pTipo : string; pCodigo : String;nbim:integer); var boletim : TBoletim; Numdisc, iDisc : Integer; linha : TLinhaBoletim; MateriasRep, MateriasRec,MateriasDep : TGerenciaLista; Conselho : Boolean; // Procurar por ***Início*** para achar o começo dessa função procedure CriaBoletim; begin with DMBoletim do begin boletim := NovoBoletim; boletim.Matricula := sqlTurmasMat.Value; boletim.Numero := sqlTurmasNumero.Value; boletim.SituacaoTurma := StrToChar(sqlTurmasSituacao.value); MateriasRep.Items.Clear; MateriasRec.Items.Clear; MateriasDep.Items.Clear; while not sqlAlunos.Eof and (sqlAlunosMat.Value < sqlTurmasMat.Value) do sqlAlunos.next; boletim.NomeAluno := Capitular(sqlAlunosNome.Value); boletim.DtNascimento := sqlAlunosDtNascimento.Value; boletim.Endereco := sqlAlunosEndereco.Value; boletim.bairro := sqlAlunosBairro.Value; boletim.Cidade := sqlAlunosCidade.Value; boletim.Uf := sqlAlunosUF.Value; boletim.CEP := sqlAlunosCEP.Value; boletim.RG := sqlAlunosRGAluno.Value; boletim.cidade_Nasc := sqlAlunoscidadeNasc.value; boletim.Uf_Nasc := sqlAlunosufnasc.value; boletim.SexoAluno := sqlAlunossexo.Value; end; end; procedure PosicionaTabelas; begin with DMBoletim do begin while not sqlNotasFaltas.Eof and (sqlNotasFaltasMat.Value < sqlTurmasMat.Value) do sqlNotasFaltas.Next; while not sqlAbono.Eof and (sqlAbonoMat.Value < sqlTurmasMat.Value) do sqlAbono.Next; while not sqlConselho.Eof and (sqlConselhoMatricula.Value < sqlTurmasMat.Value) do sqlConselho.Next; while not sqlDispensa.Eof and (sqlDispensaMat.Value < sqlTurmasMat.Value) do sqlDispensa.Next; while not sqlDiscDependencias.Eof and (sqlDiscDependenciasMat.Value < sqlTurmasMat.Value) do sqlDiscDependencias.Next; end; end; procedure CarregaValores; var Periodo : Integer; Semestral: Boolean; begin with DMBoletim do begin // Carrega Notas, Faltas e atrasos while not sqlNotasFaltas.Eof and (sqlNotasFaltasMat.Value = sqlTurmasMat.Value) and (sqlNotasFaltasDisc.AsInteger < StrToInt(fDisciplinas[iDisc].Codigo)) do sqlNotasFaltas.Next; while not sqlNotasFaltas.Eof and (sqlNotasFaltasMat.Value = sqlTurmasMat.Value) and (sqlNotasFaltasDisc.Value = fDisciplinas[iDisc].Codigo) do begin Periodo := sqlNotasFaltasBim.AsInteger; Semestral := (Calculo.Criterio.TipoBoletim = BOL_REC_SEMESTRAL) or (Calculo.Criterio.TipoBoletim = BOL_REC_SEMESTRAL2); if Semestral and (Periodo = Calculo.Criterio.NumPeriodos + 2) then begin if not sqlNotasFaltasNota.IsNull then linha.RecupSem1 := sqlNotasFaltasNota.Value end else if Semestral and (Periodo = Calculo.Criterio.NumPeriodos + 3) then begin if not sqlNotasFaltasNota.IsNull then linha.RecupSem2 := sqlNotasFaltasNota.Value end else if Periodo <= (Calculo.Criterio.NumPeriodos + 1) then begin if (Periodo = Calculo.Criterio.NumPeriodos + 1) // Se for recuperação and (sqlNotasFaltasNota.IsNull) then // e não tiver nota de recuperação não considera as aulas dadas linha.AulasDadas[Periodo] := 0 else if sqlNotasFaltasAulasDadas.Value = 0 then linha.AulasDadas[Periodo] := fDisciplinas[iDisc].AulasDadas[Periodo] else linha.AulasDadas[Periodo] := sqlNotasFaltasAulasDadas.Value; if DMPrincipal.ExSQLi(' SELECT COUNT(*) '+ ' FROM Dispensa '+ ' WHERE Mat = ' + QuotedStr(sqlNotasFaltasMat.Value) + ' AND AnoLetivo = ' + QuotedStr(AnoLetivo) + ' AND Bim = ' + QuotedStr(inttostr(periodo)) + ' AND Disc = ' + QuotedStr(sqlNotasFaltasDisc.Value) ) > 0 then begin linha.AulasDadas[Periodo] := 0; end; if not sqlNotasFaltasNota.IsNull then linha.NotasNormal[Periodo] := sqlNotasFaltasNota.Value; if not sqlNotasFaltasNotaRecPeriodo.IsNull then linha.NotasRec[Periodo] := sqlNotasFaltasNotaRecPeriodo.Value; linha.Notas[Periodo] := Calculo.CalcularNotaPeriodo(linha.NotasNormal[Periodo], linha.notasrec[periodo]); linha.Faltas[Periodo] := sqlNotasFaltasFalta.Value; linha.Atrasos[Periodo] := linha.Atrasos[Periodo] + sqlNotasFaltasatrasos.Value; linha.NotasRecMedia[Periodo] := Calculo.CalcularNotaPeriodo(linha.NotasNormal[Periodo], linha.notasrec[periodo]); end; sqlNotasFaltas.Next; end; // Carrega Abono de faltas while not sqlAbono.Eof and (sqlAbonoMat.Value = sqlTurmasMat.Value) and (sqlAbonoDisc.Value < fDisciplinas[iDisc].Codigo) do sqlAbono.Next; // Carrega Abono de faltas while not sqlAbono.Eof and (sqlAbonoMat.Value = sqlTurmasMat.Value) and (sqlAbonoDisc.Value = fDisciplinas[iDisc].Codigo) do begin if sqlAbonoBim.Asinteger <= (Calculo.Criterio.NumPeriodos + 1) then linha.Faltas[sqlAbonoBim.AsInteger] := linha.Faltas[sqlAbonoBim.AsInteger] - sqlAbonoFaltas.Value; sqlAbono.Next; end; // Carrega Aprovação por conselho. while not sqlConselho.Eof and (sqlConselhoMatricula.Value = sqlTurmasMat.Value) and (sqlConselhoDisc.Value < fDisciplinas[iDisc].Codigo) do sqlConselho.Next; if not sqlconselho.Eof and (sqlConselhoMatricula.Value = sqlTurmasMat.Value) and (sqlConselhoDisc.Value = fDisciplinas[iDisc].Codigo) then begin linha.ConselhoMedia := IntToBol(sqlConselhoAlterarMedia.AsInteger); linha.ConselhoSituacao := IntToBol(sqlConselhoAlterarSituacao.AsInteger); if sqlConselhoMedia.IsNull then linha.ValorMedia := ntSemNota else linha.ValorMedia := sqlConselhoMedia.Value; end; while not sqlDispensa.Eof and (sqlDispensaMat.Value = sqlTurmasMat.Value) and (sqlDispensaDisc.Value < fDisciplinas[iDisc].Codigo) do sqlDispensa.Next; // Carrega Dispensa por disciplina. while not sqlDispensa.Eof and (sqlDispensaMat.Value = sqlTurmasMat.Value) and (sqlDispensaDisc.Value = fDisciplinas[iDisc].Codigo) do begin if sqlDispensaBim.AsInteger <= (Calculo.Criterio.NumPeriodos + 1) then linha.Dispensa[sqlDispensaBim.AsInteger] := sqlDispensaTipo.Value; sqlDispensa.Next; end; end; end; procedure MontaObservacoes; var sAluno, sAprov, sReprov,sdependencia,Texto : String; begin sdependencia := 'Dependência'; if boletim.SexoAluno = 1 then begin sAluno := 'O aluno '; sAprov := copy(GetAprov,1,Length(GetAprov)-1)+'o'; sReprov := copy(GetReprov,1,Length(GetReprov)-1)+'o'; end else begin sAluno := 'A aluna '; sAprov := copy(GetAprov,1,Length(GetAprov)-1)+'a'; sReprov := copy(GetReprov,1,Length(GetReprov)-1)+'a'; end; // Verifica se reprovou pela frequência Global if (boletim.FrequenciaGlobal >= 0) and (boletim.FrequenciaGlobal < Calculo.Criterio.FreqGlobalMinima) then begin boletim.Observacoes.Text := sAluno + 'foi reprovado por faltas. A frequência global foi de ' + FormatFloat('0.0 %', boletim.FrequenciaGlobal); boletim.SituacaoAprov := SIT_REPROVADO; boletim.DescricaoSitAprov := 'Reprov.Faltas'; end else begin if (MateriasRep.Items.Count > 0) or ( (Calculo.Criterio.LimiteRecuperacao > 0) and (MateriasRec.Items.Count > Calculo.Criterio.LimiteRecuperacao) ) then begin // Reprovado Texto := sAluno + 'foi ' + sReprov; if MateriasRep.Items.Count > 0 then boletim.Observacoes.Text := Texto + ' em ' + MateriasRep.MontaLista else boletim.Observacoes.Text := Texto; boletim.SituacaoAprov := SIT_REPROVADO end else ////////////////////////////////Novo Calculo para Dependencia if (MateriasDep.Items.Count > 0) and (IntToBol(DMPrincipal.qry_ParametrosUtilizarDependencia.AsInteger)) then begin if MateriasDep.Items.Count <= Calculo.Criterio.LimiteDependencia then begin boletim.SituacaoAprov := SIT_DEPENDENCIA; boletim.Observacoes.Text := sAluno + 'ficou em '+GetDepend+' em '+ MateriasDep.MontaLista; end else begin boletim.SituacaoAprov := SIT_REPROVADO; boletim.Observacoes.Text := sAluno + 'ficou reprovado por exceder o limite de dependência ('+MateriasDep.MontaLista+')'; end; end else if MateriasRec.Items.Count > 0 then //Deve se verificar se existem dependencias e se ela for maior que x entao exibir reprovado por dependencia. begin // Recuperação if DMPrincipal.qry_ParametrosNivelSuperior.AsInteger = 1 then boletim.Observacoes.Text := sAluno + 'ficou em '+GetDepend+' em '+ MateriasRec.MontaLista else boletim.Observacoes.Text := sAluno + 'ficou em '+GetRecup+' em '+ MateriasRec.MontaLista; boletim.SituacaoAprov := SIT_RECUPERACAO; end else begin boletim.Observacoes.Text := sAluno + 'foi ' + sAprov; if Conselho then boletim.SituacaoAprov := SIT_CONSELHO else boletim.SituacaoAprov := SIT_APROVADO; end; case boletim.SituacaoAprov of SIT_APROVADO : boletim.DescricaoSitAprov := 'Aprovado'; SIT_CONSELHO : begin if dmBoletim.sqlconselhoMostrarsit_Conselho.AsInteger = 1 then boletim.DescricaoSitAprov := 'Aprovado' else boletim.DescricaoSitAprov := 'Aprov.Consel.'; end; SIT_REPROVADO : boletim.DescricaoSitAprov := 'Reprovado'; SIT_RECUPERACAO : boletim.DescricaoSitAprov := 'Recuperação'; end; end; end; // ***Início*** var iBim : Integer; AulasAcumuladas : Integer; FaltasAcumuladas: Integer; begin with DMBoletim do begin CronGeral.Start('Carregar Boletim de ' + pTipo + ' : ' + pCodigo); Tipo := pTipo; Codigo := pCodigo; LimpaBoletins; ObterInformacoesClasse; Cron.Start('Carregar Critério'); Calculo.CarregarCriterioClasse(CodClasse, AnoLetivo); Cron.Stop; AbrirTabelas; CarregarDisciplinas; Numdisc := Length(fDisciplinas); DoMaiorProg(sqlTurmas.RecordCount * Numdisc); fPosicao := 0; MateriasRep := TGerenciaLista.Create; MateriasRep.Separador := ', '; MateriasRep.UltSeparador := ' e '; MateriasRec := TGerenciaLista.Create; MateriasRec.Separador := ', '; MateriasRec.UltSeparador := ' e '; MateriasDep := TGerenciaLista.Create; MateriasDep.Separador := ', '; MateriasDep.UltSeparador := ' e '; try Step('Montando boletins...', 0); while not sqlTurmas.Eof do begin Conselho := False; CriaBoletim; PosicionaTabelas; AulasAcumuladas := 0; FaltasAcumuladas := 0; for iDisc := 0 to NumDisc - 1 do begin linha := boletim.NovaLinha; linha.CodDisciplina := fDisciplinas[iDisc].Codigo; if linha.Exibir then begin if CapitularDisciplinas then linha.NomeDisciplina := Capitular(fDisciplinas[iDisc].Nome) else linha.NomeDisciplina := fDisciplinas[iDisc].Nome; if boletim.SituacaoTurma <> 'R' then CarregaValores; // Verifica se existe alguma dispensa que inibe a exibição da linha iBim := 1; while ((iBim <= Calculo.Criterio.NumPeriodos + 1) and linha.Exibir) do begin if (linha.Dispensa[iBim] = DMPrincipal.qry_ParametrosTipoDispensaNaoExibir.Value) then linha.Exibir := False; Inc(iBim); end; if (linha.Exibir) then begin if nbim = 0 then nbim := Calculo.Criterio.NumPeriodos; for iBim := 1 to nbim do begin if linha.Faltas[iBim] < 0 then linha.Faltas[iBim] := 0; AulasAcumuladas := AulasAcumuladas + linha.AulasDadas[iBim]; FaltasAcumuladas := FaltasAcumuladas + linha.Faltas[iBim]; end; Calcular(linha, fDisciplinas[iDisc]); case linha.Situacao of SIT_RECUPERACAO : MateriasRec.Add(linha.NomeDisciplina); SIT_REPROVADO : MateriasRep.Add(linha.NomeDisciplina); SIT_DEPENDENCIA : MateriasDep.Add(linha.NomeDisciplina); SIT_CONSELHO : Conselho := true; end; end; end; Step; end; if AulasAcumuladas = 0 then boletim.FrequenciaGlobal := -1 else boletim.FrequenciaGlobal := Arredonda( ( (AulasAcumuladas - FaltasAcumuladas) / AulasAcumuladas) * 100, 2 ); MontaObservacoes; sqlTurmas.Next; end; finally DMBoletim.FecharTabelas; MateriasRep.Free; MateriasRec.Free; MateriasDep.Free; end; Ordenar; CronGeral.Stop; end; end; procedure TGerarBoletim.CarregarDisciplinas; var i : Integer; begin with DMBoletim do begin // Abre tabela de Disciplinas Cron.Start('sqlDisciplinas'); sqlDisciplina.Close; with sqlDisciplina.SQl do begin Clear; Add(' SELECT d2.Disciplina, d1.Nome, d1.Reprova, d1.Sigla, d1.Tipo, '); Add(' d1.Historico, d1.TipoComposicao, d2.Ordem, d2.carga '); Add(' FROM Disciplina2 d2 '); Add(' INNER JOIN Disciplina1 d1 '); Add(' ON d2.AnoLetivo = d1.AnoLetivo AND d2.Disciplina = d1.Codigo '); Add(' WHERE d2.AnoLetivo = ' + QuotedStr(AnoLetivo) ); Add(' AND d1.TipoComposicao <> "D" '); Add(' AND d2.Curso = ' + QuotedStr(Curso) ); Add(' AND d2.Serie = ' + QuotedStr(Serie) ); if not mostrarDiversificadas then Add(' AND d1.Tipo = "C" '); Add('ORDER BY CAST(d2.Disciplina AS UNSIGNED)'); end; sqlDisciplina.Open; Cron.Stop; // abre tabela de Aulas Dadas Cron.Start('sqlAulasDadas'); sqlAulasDadas.Close; with sqlAulasDadas.Params do begin ParamByName('pLetivo').Value := AnoLetivo; ParamByName('pClasse').Value := CodClasse; end; sqlAulasDadas.Open; Cron.Stop; Cron.Start('carregar disciplinas'); for i := 0 to Length(fDisciplinas) - 1 do SetLength(fDisciplinas[i].AulasDadas, 0); SetLength(fDisciplinas, sqlDisciplina.RecordCount); i := 0; while not sqlDisciplina.Eof do begin fDisciplinas[i].Codigo := sqlDisciplinaDisciplina.Value; fDisciplinas[i].Nome := sqlDisciplinaNome.Value; fDisciplinas[i].Reprova := IntToBol(sqlDisciplinaReprova.asInteger); fDisciplinas[i].Sigla := sqlDisciplinaSigla.Value; fDisciplinas[i].Tipo := sqlDisciplinaTipo.Value; fDisciplinas[i].Historico := IntToBol(sqlDisciplinaHistorico.asInteger); fDisciplinas[i].Ordem := sqlDisciplinaOrdem.Value; fdisciplinas[i].cargahoraria := sqlDisciplinaCarga.Value; SetLength(fDisciplinas[i].AulasDadas, Calculo.Criterio.NumPeriodos + 2); while not sqlAulasDadas.Eof and (sqlAulasDadasDisciplina.AsInteger < StrToInt(fDisciplinas[i].Codigo)) do sqlAulasDadas.Next; while not sqlAulasDadas.Eof and (sqlAulasDadasDisciplina.Value = fDisciplinas[i].Codigo) do begin if sqlAulasDadasBimestre.AsInteger <= (Calculo.Criterio.NumPeriodos + 1) then fDisciplinas[i].AulasDadas[sqlAulasDadasBimestre.AsInteger] := sqlAulasDadasAulasDadas.Value; sqlAulasDadas.Next; end; sqlDisciplina.Next; Inc(i); end; sqlDisciplina.Close; sqlAulasDadas.Close; Cron.Stop; end; end; constructor TGerarBoletim.Create(Owner: TComponent); begin inherited; DMBoletim := TDMBoletim.Create(self); fBoletins := TList.Create; AnoLetivo := vUser.AnoLetivo; mostrarDiversificadas := True; CapitularDisciplinas := true; Cron := TCronometro.Create; Cron.NomeArquivo := ChangeFileExt(ParamStr(0), '.timer.txt'); Cron.Enabled := True; CronGeral := TCronometro.Create; CronGeral.NomeArquivo := ChangeFileExt(ParamStr(0), '.timer.txt'); CronGeral.Enabled := True; Calculo := TCalculaNotas.Create; SetLength(fDisciplinas, 0); Curso := ''; Serie := ''; end; destructor TGerarBoletim.Destroy; begin fBoletins.Free; Cron.Free; CronGeral.Free; DMBoletim.free; inherited; end; function TGerarBoletim.GetBoletim(Indice: Integer): TBoletim; begin result := TBoletim(fBoletins.Items[indice]); end; procedure TGerarBoletim.LimpaBoletins; var i : Integer; begin for i := 0 to fBoletins.Count - 1 do RemoveBoletim(0); end; function TGerarBoletim.NovoBoletim: TBoletim; begin Result := TBoletim.Create(Self); fBoletins.Add(result); end; procedure TGerarBoletim.RemoveBoletim(Indice: Integer); begin Boletim[indice].free; fBoletins.Delete(indice); end; procedure TGerarBoletim.SetBoletim(Indice: Integer; const Value: TBoletim); begin fBoletins.Items[Indice] := Value; end; { TLinhaBoletim } constructor TLinhaBoletim.Create(Owner: TComponent); var i : Integer; begin inherited; if Owner is TBoletim then Boletim := TBoletim(Owner); NomeDisciplina := ''; Exibir := true; SetLength(NotasNormal, NumPeriodos + 2); SetLength(NotasRec, NumPeriodos + 2); SetLength(NotasRecMedia, NumPeriodos + 2); SetLength(Notas, NumPeriodos + 2); SetLength(Faltas, NumPeriodos + 2); SetLength(Atrasos, NumPeriodos + 2); SetLength(Dispensa, NumPeriodos + 2); SetLength(AulasDadas, NumPeriodos + 2); for i := 1 to NumPeriodos + 1 do begin NotasNormal[i] := ntSemNota; NotasRec[i] := ntSemNota; NotasRecMedia[i]:= ntSemNota; Notas[i] := ntSemNota; Faltas[i] := 0; Atrasos[i] := 0; Dispensa[i] := ''; AulasDadas[i] := 0; end; RecupSem1 := ntSemNota; RecupSem2 := ntSemNota; MediaSem1 := ntSemNota; MediaSem2 := ntSemNota; MediaAntSem1 := ntSemNota; MediaAntSem2 := ntSemNota; MediaBim := ntSemNota; MediaFinal := ntSemNota; Situacao := #0; end; function TLinhaBoletim.TotalFaltas: Integer; var i : Integer; begin Result := 0; for i := 1 to NumPeriodos + 1 do Result := Result + Faltas[i]; end; function TLinhaBoletim.TotalAtrasos: Integer; var i : Integer; begin Result := 0; for i := 1 to NumPeriodos + 1 do Result := Result + Atrasos[i]; end; function TLinhaBoletim.NumPeriodos: Integer; begin Result := Boletim.Gerador.Calculo.Criterio.NumPeriodos; end; function TLinhaBoletim.PecFaltas: String; var valor : Double; begin Try valor := 0; valor := 100 - ( (TotalFaltas/TotalAulasDadas) * 100 ); Result := FormatFloat(',0.00', valor); except Result := FormatFloat(',0.00', 0); end; end; function TLinhaBoletim.TotalAulasDadas: Integer; var i : Integer; begin Result := 0; for i := 1 to NumPeriodos + 1 do Result := Result + aulasdadas[i]; end; { TBoletim } constructor TBoletim.Create(Owner: TComponent); begin inherited; if Owner is TGerarBoletim then Gerador := TGerarBoletim(Owner); Observacoes := TStringList.Create; fLinhas := TList.Create; end; destructor TBoletim.Destroy; begin Observacoes.Free; fLinhas.Free; inherited; end; function TBoletim.GetLinha(Index: Integer): TLinhaBoletim; begin Result := TLinhaBoletim(fLinhas[index]); end; function TBoletim.NovaLinha: TLinhaBoletim; begin Result := TLinhaBoletim.Create(Self); fLinhas.Add(Result); end; function TBoletim.NumLinhas: Integer; begin Result := fLinhas.Count; end; procedure TBoletim.RemoveLinha(Indice: Integer); begin Linhas[Indice].free; fLinhas.Delete(Indice); end; procedure TBoletim.SetLinha(Index: Integer; const Value: TLinhaBoletim); begin fLinhas[Index] := Value; end; function TGerarBoletim.NumBoletins: Integer; begin Result := fBoletins.Count; end; procedure TGerarBoletim.Ordenar; var iFixo, iVarre : Integer; Temp : TBoletim; tempDisciplina : TDisciplina; templinha : TLinhaBoletim; Ordenar : Boolean; iDisc : Integer; iBoletim : Integer; begin Cron.Start('Ordenar'); for iFixo := 0 to NumBoletins - 2 do for iVarre := iFixo + 1 to NumBoletins - 1 do begin if Boletim[iFixo].Numero > Boletim[iVarre].Numero then begin Temp := Boletim[iFixo]; Boletim[iFixo] := Boletim[iVarre]; Boletim[iVarre] := Temp; end; end; Ordenar := false; for iDisc := 0 to NumDisciplina - 1 do if Disciplina[iDisc].Ordem > 0 then begin Ordenar := true; break; end; if Ordenar then begin for iFixo := 0 to NumDisciplina - 2 do for iVarre := iFixo + 1 to NumDisciplina - 1 do begin if Disciplina[iFixo].Ordem > Disciplina[iVarre].Ordem then begin tempDisciplina := Disciplina[iFixo]; Disciplina[iFixo] := disciplina[iVarre]; Disciplina[iVarre] := tempDisciplina; for iBoletim := 0 to NumBoletins - 1 do begin templinha := Boletim[iBoletim][iFixo]; Boletim[iBoletim][iFixo] := Boletim[iBoletim][iVarre]; Boletim[iBoletim][iVarre] := templinha; end; end; end; end; Cron.Stop; end; function TGerarBoletim.GetDisciplina(Indice: Integer): TDisciplina; begin Result := fDisciplinas[Indice]; end; function TGerarBoletim.NumDisciplina: Integer; begin Result := Length(fDisciplinas); end; procedure TGerarBoletim.DoMaiorProg(Value: Integer); begin if Assigned(fMaiorProgressao) then FMaiorProgressao(self, Value); end; procedure TGerarBoletim.Step(msg: String = ''; Inc : Integer = 1); begin FPosicao := FPosicao + Inc; if Msg <> '' then Mensagem := Msg; if assigned(fProgressao) then FProgressao(Self, Mensagem, FPosicao); end; class procedure TGerarBoletim.RecalcularDiscComposta(CodDisciplina, CodClasse: String; Periodo : Integer); var slFilhas : TStringlist; sSQL, sMat : String; MaiorNumero: Integer; i, Num : Integer; AulasDadas: Integer; Notas: array of Double; Aulas : array of integer; Criterio : TCriterio; Faltas, Atrasos : Array of Integer; begin DMBoletim := TDMBoletim.Create(nil); slFilhas := nil; Criterio := nil; try sSQL := ' SELECT TipoComposicao, CalculoComp '+ ' FROM Disciplina1 '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND Codigo = ' + QuotedStr(CodDisciplina) ; DMPrincipal.OpenSQL(DMBoletim.sqlDisciplina1,sSQL); if DMBoletim.sqlDisciplina1TipoComposicao.AsString = 'C' then begin slFilhas := TStringList.Create; Criterio := TCriterio.Create; Criterio.CarregarCriterioClasse(CodClasse); DMPrincipal.Zconn.ExecuteDirect(' DELETE '+ ' FROM NotasFaltas '+ ' WHERE Bim = ' + QuotedStr(inttostr(periodo)) + ' AND AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND Disc = ' + QuotedStr(CodDisciplina) + ' AND Mat IN ( '+ ' SELECT Mat '+ ' FROM Turmas '+ ' WHERE idClasse1 = ' + QuotedStr(CodClasse) + ' AND AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' ) '); sSQL := ' SELECT MAX( CAST(Numero AS UNSIGNED)) '+ ' FROM Turmas '+ ' WHERE idClasse1 = ' + QuotedStr(CodClasse) + ' AND AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) ; MaiorNumero := DMPrincipal.ExSQLi(sSQL); SetLength(Notas, MaiorNumero); SetLength(Faltas, MaiorNumero); SetLength(Atrasos, MaiorNumero); SetLength(Aulas, MaiorNumero); for i := 0 to MaiorNumero - 1 do begin Notas[i] := 0; Faltas[i] := 0; Atrasos[i] := 0; Aulas[i] := 0; end; AulasDadas := 0; sSQL := ' SELECT Codigo '+ ' FROM Disciplina1 '+ ' WHERE DisciplinaPai = ' + QuotedStr(CodDisciplina) + ' AND AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) ; slFilhas.Text := DMPrincipal.ExSQLLst(sSQL); // Carrega as notas das disciplinas filhas for i := 0 to slFilhas.Count - 1 do begin // Aulas dadas sSQL := ' SELECT AulasDadas '+ ' FROM AulasDadas '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND Classe = ' + QuotedStr(CodClasse) + ' AND Bimestre = ' + IntToStr(Periodo) + ' AND Disciplina = ' + slFilhas[i] ; AulasDadas := AulasDadas + DMPrincipal.ExSQLi(sSQL); // Notas, faltas e atrasos if Criterio.CalcRecBim = 1 then sSQL := ' SELECT nt.ID, nt.Mat, t.Numero ,nt.Falta,nt.Atrasos, nt.AulasDadas, '+ ' IF (nt.NotaRecPeriodo IS NULL, nt.Nota, ( IFNULL(nt.Nota,0) + IFNULL(nt.NotaRecPeriodo,0) )/2 ) AS Nota '+ ' FROM NotasFaltas nt '+ ' INNER JOIN Turmas t '+ ' ON nt.AnoLetivo = t.AnoLetivo '+ ' AND nt.Mat = t.Mat '+ ' AND t.Situacao = "F" '+ ' WHERE nt.AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND nt.Bim = ' + QuotedStr(IntToStr(Periodo)) + ' AND nt.Disc = ' + QuotedStr(slFilhas[i]) + ' AND t.idClasse1 = ' + QuotedStr(CodClasse) + ' ORDER BY CAST(t.Numero AS UNSIGNED) ' else if Criterio.CalcRecBim = 0 then sSQL := 'SELECT nt.ID, nt.Mat, t.Numero, nt.Falta,nt.Atrasos, nt.AulasDadas, '+ ' IF(nt.NotaRecPeriodo>nt.Nota, nt.NotaRecPeriodo, nt.Nota) AS Nota '+ ' FROM NotasFaltas nt '+ ' INNER JOIN Turmas t '+ ' ON nt.AnoLetivo = t.AnoLetivo '+ ' AND nt.Mat = t.Mat '+ ' AND t.Situacao = "F" '+ ' WHERE nt.AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND nt.Bim = ' + QuotedStr(IntToStr(Periodo)) + ' AND nt.Disc = ' + QuotedStr(slFilhas[i]) + ' AND t.idClasse1 = ' + QuotedStr(CodClasse) + ' ORDER BY CAST(t.Numero AS UNSIGNED) ' else if Criterio.CalcRecBim = 2 then sSQL := ' SELECT nt.ID, nt.Mat, t.Numero, nt.Nota, nt.Falta,nt.Atrasos, nt.AulasDadas '+ ' FROM NotasFaltas nt '+ ' INNER JOIN Turmas t '+ ' ON nt.AnoLetivo = t.AnoLetivo '+ ' AND nt.Mat = t.Mat '+ ' AND t.Situacao = "F" '+ ' WHERE nt.AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND nt.Bim = ' + QuotedStr(IntToStr(Periodo)) + ' AND nt.Disc = ' + QuotedStr(slFilhas[i]) + ' AND t.idClasse1 = ' + QuotedStr(CodClasse) + ' ORDER BY CAST(t.Numero AS UNSIGNED) '; DMPrincipal.OpenSQL(DMBoletim.sqlnotasFilhas,sSQL); while not DMBoletim.sqlNotasFilhas.Eof do begin Num := DMBoletim.sqlNotasFilhasNumero.AsInteger; if DMBoletim.sqlNotasFilhasNota.isnull then Notas[Num - 1] := Notas[Num - 1] + -1 //-1 para definir que é branco. else Notas[Num - 1] := Notas[Num - 1] + DMBoletim.sqlNotasFilhasNota.Value; Faltas[Num - 1] := Faltas[Num - 1] + DMBoletim.sqlNotasFilhasFalta.Value; Atrasos[Num - 1] := Atrasos[Num - 1] + DMBoletim.sqlNotasFilhasAtrasos.Value; if DMBoletim.sqlNotasFilhasAulasDadas.Value > 0 then Aulas[Num - 1] := Aulas[Num - 1] + DMBoletim.sqlNotasFilhasAulasDadas.Value; DMBoletim.sqlnotasFilhas.Next; end; end; // Aulas dadas DMPrincipal.OpenSQL(DMPrincipal.sqlAulasDadas,' SELECT * '+ ' FROM AulasDadas '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND Classe = ' + QuotedStr(CodClasse) + ' AND Bimestre = ' + QuotedStr(IntToStr(Periodo)) + ' AND Disciplina = ' + QuotedStr(CodDisciplina) ); if DMPrincipal.sqlAulasDadas.RecordCount = 0 then begin DMPrincipal.sqlAulasDadas.Append; DMPrincipal.sqlAulasDadas.FieldByName('AnoLetivo').Value := vUser.AnoLetivo; DMPrincipal.sqlAulasDadas.FieldByName('Classe').Value := CodClasse; DMPrincipal.sqlAulasDadas.FieldByName('Bimestre').AsInteger := Periodo; DMPrincipal.sqlAulasDadas.FieldByName('Disciplina').Value := CodDisciplina; end else DMPrincipal.sqlAulasDadas.Edit; DMPrincipal.sqlAulasDadas.FieldByName('AulasDadas').Value := AulasDadas; DMPrincipal.sqlAulasDadas.Post; DMPrincipal.OpenSQL(DMPrincipal.sqlNotasFaltas, ' SELECT * '+ ' FROM NotasFaltas '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND Mat in ( '+ ' SELECT Mat '+ ' FROM Turmas '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND idClasse1 = ' + QuotedStr(CodClasse) + ' ) '+ ' AND Bim = ' + QuotedStr(IntToStr(Periodo)) + ' AND Disc = ' + QuotedStr(CodDisciplina) ); for i := 0 to MaiorNumero - 1 do begin if DMBoletim.sqlDisciplina1CalculoComp.Value = 'M' then begin Notas[i] := Arredonda(Notas[i] / slFilhas.Count, Criterio.Decimais,true); notas[i] := criterio.ArredondMediaBim.arredonda(notas[i]) end; sSQL := ' SELECT Mat '+ ' FROM Turmas '+ ' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) + ' AND idClasse1 = ' + QuotedStr(CodClasse) + ' AND Numero = ' + FormatFloat('000', i + 1) + ' AND Situacao = "F" '; sMat := DMPrincipal.ExSQLs(sSQL); if (Trim(sMat) <> '') and (notas[i] >= 0) then //alterei aqui Nilton begin if not DMPrincipal.sqlNotasFaltas.Locate('Mat', sMat, []) then begin DMPrincipal.sqlNotasFaltas.Append; DMPrincipal.sqlNotasFaltas.FieldByName('AnoLetivo').Value := vUser.AnoLetivo; DMPrincipal.sqlNotasFaltas.FieldByName('Mat').Value := sMat; DMPrincipal.sqlNotasFaltas.FieldByName('Bim').AsInteger := Periodo; DMPrincipal.sqlNotasFaltas.FieldByName('Disc').Value := CodDisciplina; end else DMPrincipal.sqlNotasFaltas.Edit; // 17/09/2013 -> correção Nilton if Notas[i] > Criterio.NotaMaxima(cnbNotaPeriodo, Periodo) then Notas[i] := Criterio.NotaMaxima(cnbNotaPeriodo, Periodo); DMPrincipal.sqlNotasFaltas.FieldByName('Nota').Value := Notas[i]; DMPrincipal.sqlNotasFaltas.FieldByName('Falta').Value := Faltas[i]; DMPrincipal.sqlNotasFaltas.FieldByName('Atrasos').Value := atrasos[i]; DMPrincipal.sqlNotasFaltas.FieldByName('AulasDadas').Value := Aulas[i]; DMPrincipal.sqlNotasFaltas.Post; end; end; end; finally if slFilhas <> nil then slFilhas.Free; if Criterio <> nil then Criterio.Free; DMPrincipal.sqlAulasDadas.Close; DMPrincipal.sqlNotasFaltas.Close; DMBoletim.Free; end; end; procedure TGerarBoletim.SetDisciplina(Indice: Integer; const Value: TDisciplina); begin fDisciplinas[Indice] := Value; end; end.
unit IdOpenSSLConsts; interface {$i IdCompilerDefines.inc} {$IFDEF FPC} uses ctypes {$IFDEF HAS_UNIT_UnixType} , UnixType {$ENDIF} ; {$ELSE} // Delphi defines (P)SIZE_T and (P)SSIZE_T in the Winapi.Windows unit in // XE2+, but we don't want to pull in that whole unit here just to define // a few aliases... {$IFDEF WINDOWS} {$IFDEF VCL_XE2_OR_ABOVE} uses Winapi.Windows; {$ENDIF} {$ENDIF} {$ENDIF} const CLibCryptoRaw = 'libcrypto'; CLibSSLRaw = 'libssl'; SSLDLLVers: array [0..1] of string = ('', '.1.1'); CLibCrypto = CLibCryptoRaw + '-1_1.dll'; CLibSSL = CLibSSLRaw + '-1_1.dll'; {$IFDEF FPC} IdNilHandle = {$IFDEF WINDOWS}PtrUInt(0){$ELSE}PtrInt(0){$ENDIF}; {$ELSE} IdNilHandle = THandle(0); {$ENDIF} type PPByte = ^PByte; PPPByte = ^PPByte; // this is necessary because Borland still doesn't support QWord // (unsigned 64bit type). {$IFNDEF HAS_QWord} qword = {$IFDEF HAS_UInt64}UInt64{$ELSE}Int64{$ENDIF}; {$ENDIF} {$IFDEF FPC} TIdC_INT64 = cint64; PIdC_INT64 = pcint64; TIdC_UINT64 = cuint64; PIdC_UINT64 = pcuint64; {$ELSE} TIdC_INT64 = Int64; PIdC_INT64 = ^TIdC_INT64{PInt64}; TIdC_UINT64 = QWord; PIdC_UINT64 = ^TIdC_UINT64{PQWord}; {$ENDIF} {$IFDEF FPC} TIdC_INT32 = cint; PIdC_INT32 = pcint; TIdC_UINT32 = cuint; PIdC_UINT32 = pcuint; {$ELSE} TIdC_INT32 = Integer; PIdC_INT32 = ^TIdC_INT64{PInt64}; TIdC_UINT32 = Cardinal; PIdC_UINT32 = ^TIdC_UINT64{PQWord}; {$ENDIF} {$IFDEF FPC} TIdC_INT = cInt; PIdC_INT = pcInt; PPIdC_INT = ^PIdC_INT; {$ELSE} TIdC_INT = Integer; PIdC_INT = ^TIdC_INT; PPIdC_INT = ^PIdC_INT; {$ENDIF} {$IFDEF HAS_SIZE_T} TIdC_SIZET = size_t; {$ELSE} {$IFDEF HAS_PtrUInt} TIdC_SIZET = PtrUInt; {$ELSE} {$IFDEF CPU32} TIdC_SIZET = TIdC_UINT32; {$ENDIF} {$IFDEF CPU64} TIdC_SIZET = TIdC_UINT64; {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF HAS_PSIZE_T} PIdC_SIZET = psize_t; {$ELSE} PIdC_SIZET = ^TIdC_SIZET; {$ENDIF} {$IFDEF FPC} TIdLibHandle = {$IFDEF WINDOWS}PtrUInt{$ELSE}PtrInt{$ENDIF}; {$ELSE} TIdLibHandle = THandle; {$ENDIF} TIdLibFuncName = String; PIdLibFuncNameChar = PChar; {$IFDEF HAS_TIME_T} TIdC_TIMET = time_t; {$ELSE} {$IFDEF HAS_PtrInt} TIdC_TIMET = PtrInt; {$ELSE} {$IFDEF CPU32} TIdC_TIMET = TIdC_INT32; {$ENDIF} {$IFDEF CPU64} TIdC_TIMET = TIdC_INT64; {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF HAS_PTIME_T} PIdC_TIMET = ptime_t; {$ELSE} PIdC_TIMET = ^TIdC_TIMET; {$ENDIF} function LoadLibFunction(const ALibHandle: TIdLibHandle; const AProcName: TIdLibFuncName): Pointer; implementation function LoadLibFunction(const ALibHandle: TIdLibHandle; const AProcName: TIdLibFuncName): Pointer; begin {$I IdRangeCheckingOff.inc} Result := {$IFDEF WINDOWS}{$IFNDEF FPC}Winapi.Windows.{$ENDIF}{$ENDIF}GetProcAddress(ALibHandle, PIdLibFuncNameChar(AProcName)); {$I IdRangeCheckingOn.inc} end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 2005-2007, Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> 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 (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit sdet; interface uses Math, Sysutils, Ap, ldlt; function SMatrixLDLTDet(const A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger; IsUpper : Boolean):Double; function SMatrixDet(A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Double; function DeterminantLDLT(const A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger; IsUpper : Boolean):Double; function DeterminantSymmetric(A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Double; implementation (************************************************************************* Determinant calculation of the matrix given by LDLT decomposition. Input parameters: A - LDLT-decomposition of the matrix, output of subroutine SMatrixLDLT. Pivots - table of permutations which were made during LDLT decomposition, output of subroutine SMatrixLDLT. N - size of matrix A. IsUpper - matrix storage format. The value is equal to the input parameter of subroutine SMatrixLDLT. Result: matrix determinant. -- ALGLIB -- Copyright 2005-2008 by Bochkanov Sergey *************************************************************************) function SMatrixLDLTDet(const A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger; IsUpper : Boolean):Double; var K : AlglibInteger; begin Result := 1; if IsUpper then begin K := 0; while K<N do begin if Pivots[K]>=0 then begin Result := Result*A[K,K]; K := K+1; end else begin Result := Result*(A[K,K]*A[K+1,K+1]-A[K,K+1]*A[K,K+1]); K := K+2; end; end; end else begin K := N-1; while K>=0 do begin if Pivots[K]>=0 then begin Result := Result*A[K,K]; K := K-1; end else begin Result := Result*(A[K-1,K-1]*A[K,K]-A[K,K-1]*A[K,K-1]); K := K-2; end; end; end; end; (************************************************************************* Determinant calculation of the symmetric matrix Input parameters: A - matrix. Array with elements [0..N-1, 0..N-1]. N - size of matrix A. IsUpper - if IsUpper = True, then symmetric matrix A is given by its upper triangle, and the lower triangle isnít used by subroutine. Similarly, if IsUpper = False, then A is given by its lower triangle. Result: determinant of matrix A. -- ALGLIB -- Copyright 2005-2008 by Bochkanov Sergey *************************************************************************) function SMatrixDet(A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Double; var Pivots : TInteger1DArray; begin A := DynamicArrayCopy(A); SMatrixLDLT(A, N, IsUpper, Pivots); Result := SMatrixLDLTDet(A, Pivots, N, IsUpper); end; function DeterminantLDLT(const A : TReal2DArray; const Pivots : TInteger1DArray; N : AlglibInteger; IsUpper : Boolean):Double; var K : AlglibInteger; begin Result := 1; if IsUpper then begin K := 1; while K<=N do begin if Pivots[K]>0 then begin Result := Result*A[K,K]; K := K+1; end else begin Result := Result*(A[K,K]*A[K+1,K+1]-A[K,K+1]*A[K,K+1]); K := K+2; end; end; end else begin K := N; while K>=1 do begin if Pivots[K]>0 then begin Result := Result*A[K,K]; K := K-1; end else begin Result := Result*(A[K-1,K-1]*A[K,K]-A[K,K-1]*A[K,K-1]); K := K-2; end; end; end; end; function DeterminantSymmetric(A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Double; var Pivots : TInteger1DArray; begin A := DynamicArrayCopy(A); LDLTDecomposition(A, N, IsUpper, Pivots); Result := DeterminantLDLT(A, Pivots, N, IsUpper); end; end.
unit frFS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, ImgList, ActnList, dmFS, SpTBXItem, TB2Item; type TBasicNodeData = class; EFSNoFocusedNodeException = class(Exception); TfFS = class(TFrame) TreeFS: TVirtualStringTree; ImageListTree: TImageList; procedure TreeFSGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFSFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeFSGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreeFSGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeFSExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean); procedure TreeFSCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure TreeFSInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure TreeFSPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); private FFS: TFS; procedure AnadirRama(const ParentNode: PVirtualNode); function GetOIDNodeFocused: integer; protected procedure SetFS(const Value: TFS); function AnadirFileTreeFS(const ParentNode: PVirtualNode; const nombre: string; const OID: integer): PVirtualNode; function AnadirCarpetaTreeFS(const ParentNode: PVirtualNode; const nombre: string; const OID: integer): PVirtualNode; public procedure MarkAsLoaded(const Node: PVirtualNode); function GetNodeData(const Node: PVirtualNode): TBasicNodeData; function GetNodeDataFocused: TBasicNodeData; function IsFocusedRoot: boolean; function IsFocusedDirectory: boolean; function IsFocusedFile: boolean; function IsDirectory(const Node: PVirtualNode): boolean; property OIDNodeFocused: integer read GetOIDNodeFocused; property FS: TFS read FFS write SetFS; end; TBasicNodeData = class protected FCaption: string; FOID: integer; FImageIndex: integer; public constructor Create( const Caption : string; const OID, ImageIndex: integer); property Caption: string read FCaption write FCaption; property OID: integer read FOID write FOID; property ImageIndex: integer read FImageIndex write FImageIndex; end; TDirectoryNode = class(TBasicNodeData) public constructor Create(const Caption : string; const OID: integer); reintroduce; end; TFileNode = class(TBasicNodeData) public constructor Create(const Caption : string; const OID: integer); reintroduce; end; implementation {$R *.dfm} type PBasicNodeRec= ^TBasicNodeRec; TBasicNodeRec = record node : TBasicNodeData; loaded: boolean; end; const DIRECTORY_NODE_IMAGE_INDEX = 0; FILE_NODE_IMAGE_INDEX = 1; function TfFS.AnadirCarpetaTreeFS(const ParentNode: PVirtualNode; const nombre: string; const OID: integer): PVirtualNode; var Data: PBasicNodeRec; begin result := TreeFS.AddChild(ParentNode); Data := TreeFS.GetNodeData(result); Data^.node := TDirectoryNode.Create(nombre, OID); Data^.loaded := false; end; function TfFS.AnadirFileTreeFS(const ParentNode: PVirtualNode; const nombre: string; const OID: integer): PVirtualNode; var Data: PBasicNodeRec; begin result := TreeFS.AddChild(ParentNode); Data := TreeFS.GetNodeData(result); Data^.node := TFileNode.Create(nombre, OID); Data^.loaded := true; end; procedure TfFS.AnadirRama(const ParentNode: PVirtualNode); begin TreeFS.BeginUpdate; try FFS.First; while not FFS.Eof do begin if FFS.Tipo = fstDirectory then AnadirCarpetaTreeFS(ParentNode, FS.Nombre, FS.OID) else AnadirFileTreeFS(ParentNode, FS.Nombre, FS.OID); FFS.Next; end; FFS.Close; finally TreeFS.EndUpdate; end; end; function TfFS.GetNodeData(const Node: PVirtualNode): TBasicNodeData; var Data: PBasicNodeRec; begin Data := TreeFS.GetNodeData(Node); result := Data^.node; end; function TfFS.GetNodeDataFocused: TBasicNodeData; var FocusedNode: PVirtualNode; begin FocusedNode := TreeFS.FocusedNode; if FocusedNode = nil then result := nil else result := GetNodeData(FocusedNode); end; function TfFS.GetOIDNodeFocused: integer; var FocusedNode: PVirtualNode; begin FocusedNode := TreeFS.FocusedNode; if FocusedNode = nil then raise EFSNoFocusedNodeException.Create('') else result := GetNodeData(FocusedNode).OID;; end; function TfFS.IsDirectory(const Node: PVirtualNode): boolean; begin result := GetNodeData(Node) is TDirectoryNode; end; function TfFS.IsFocusedDirectory: boolean; var FocusedNode: PVirtualNode; begin FocusedNode := TreeFS.FocusedNode; if FocusedNode = nil then result := false else result := GetNodeData(FocusedNode) is TDirectoryNode; end; function TfFS.IsFocusedFile: boolean; var FocusedNode: PVirtualNode; begin FocusedNode := TreeFS.FocusedNode; if FocusedNode = nil then result := false else result := GetNodeData(FocusedNode) is TFileNode; end; function TfFS.IsFocusedRoot: boolean; var FocusedNode: PVirtualNode; begin FocusedNode := TreeFS.FocusedNode; result := (FocusedNode = nil) or (FocusedNode.Parent = TreeFS.RootNode); end; procedure TfFS.MarkAsLoaded(const Node: PVirtualNode); begin PBasicNodeRec(TreeFS.GetNodeData(Node))^.loaded := true; end; procedure TfFS.SetFS(const Value: TFS); begin FFS := Value; FS.LoadRoot; AnadirRama(nil); end; procedure TfFS.TreeFSCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2 : TBasicNodeData; Data1Dir, Data2Dir: boolean; begin Data1 := GetNodeData(Node1); Data2 := GetNodeData(Node2); Data1Dir := Data1 is TDirectoryNode; Data2Dir := Data2 is TDirectoryNode; // Los 2 son directorios o ficheros if Data1Dir = Data2Dir then result := WideCompareText(Data1.Caption, Data2.Caption) else begin if (Data1Dir) and (not Data2Dir) then result := 1; end; end; procedure TfFS.TreeFSExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean); var Data: PBasicNodeRec; begin Data := TreeFS.GetNodeData(Node); Allowed := Data^.node is TDirectoryNode; if (Allowed) and (not Data^.loaded) then begin if Node.Parent = nil then FS.LoadRoot else FS.Load(Data^.node.OID); AnadirRama(Node); Data^.loaded := true; end; end; procedure TfFS.TreeFSFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PBasicNodeRec; begin Data := Sender.GetNodeData(Node); Data^.node.Free; Data^.node := nil; end; procedure TfFS.TreeFSGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); begin ImageIndex := GetNodeData(Node).ImageIndex; end; procedure TfFS.TreeFSGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TBasicNodeRec); end; procedure TfFS.TreeFSGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); begin CellText := GetNodeData(Node).Caption; end; procedure TfFS.TreeFSInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var Data: PBasicNodeRec; begin Data := Sender.GetNodeData(Node); if (Data^.node is TDirectoryNode) and (FS.ChildCount(Data^.node.OID) > 0) then Include(InitialStates, ivsHasChildren); end; procedure TfFS.TreeFSPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); begin end; { TBasicNodeData } constructor TBasicNodeData.Create(const Caption: string; const OID, ImageIndex: Integer); begin FCaption := Caption; FOID := OID; FImageIndex := ImageIndex; end; { TDirectoryNode } constructor TDirectoryNode.Create(const Caption: string; const OID: integer); begin inherited Create(Caption, OID, DIRECTORY_NODE_IMAGE_INDEX); end; { TFileNode } constructor TFileNode.Create(const Caption: string; const OID: integer); begin inherited Create(Caption, OID, FILE_NODE_IMAGE_INDEX); end; end.
unit ViewModel.Invoice; interface uses Model.Interfaces; function CreateInvoiceViewModelClass: IInvoiceViewModelInterface; implementation uses Model.Declarations, System.SysUtils, System.Generics.Collections, Model.ProSu.Interfaces, Model.ProSu.Provider, Model.ProSu.InterfaceActions; type TInvoiceViewModel = class(TInterfacedObject, IInvoiceViewModelInterface) private fModel: IInvoiceModelInterface; fLabelsText: TInvoiceFormLabelsText; fTitle: string; fInvoiceItemsEnabled, fBalanceEnabled, fPrintButtonEnabled, fAniIndicatorVisible, fPrintingLabelVisible, fDiscountChecked: boolean; fProvider: IProviderInterface; fInvoiceItemsText: TInvoiceItemsText; function GetModel: IInvoiceModelInterface; procedure SetModel(const newModel: IInvoiceModelInterface); function GetLabelsText: TInvoiceFormLabelsText; function GetTitleText: string; function GetGroupBoxInvoiceItemsEnabled: Boolean; function GetGroupBoxBalanceEnabled: Boolean; function GetButtonPrintInvoiceEnabled: Boolean; function GetAniIndicatorProgressVisible: Boolean; function GetLabelPrintingVisible: Boolean; procedure GetCustomerList(var customers: TObjectList<TCustomer>); procedure GetItems(var items: TObjectList<TItem>); function GetProvider: IProviderInterface; procedure GetCustomerDetails (const customerName: string; var customerDetails: TCustomerDetailsText); function GetInvoiceItemsText: TInvoiceItemsText; procedure SendNotification (const actions: TInterfaceActions); procedure SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string); procedure SetDiscountApplied (const discount: boolean); function GetDiscountApplied: boolean; public constructor Create; procedure AddInvoiceItem(const itemDescription: string; const quantity: integer); procedure DeleteAllInvoiceItems; procedure ValidateItem (const newItem: string); procedure ValidateQuantity (const newQuantityText: string); procedure DeleteInvoiceItem (const delItemIDAsText: string); procedure PrintInvoice; property Model: IInvoiceModelInterface read GetModel write SetModel; property LabelsText: TInvoiceFormLabelsText read GetLabelsText; property TitleText: string read GetTitleText; property GroupBoxInvoiceItemsEnabled: boolean read GetGroupBoxInvoiceItemsEnabled; property GroupBoxBalanceEnabled: boolean read GetGroupBoxBalanceEnabled; property ButtonPrintInvoiceEnabled: Boolean read GetButtonPrintInvoiceEnabled; property AniIndicatorProgressVisible: Boolean read GetAniIndicatorProgressVisible; property LabelPrintingVisible: Boolean read GetLabelPrintingVisible; property Provider: IProviderInterface read GetProvider; property InvoiceItemsText: TInvoiceItemsText read GetInvoiceItemsText; property DiscountApplied: boolean read GetDiscountApplied write SetDiscountApplied; end; function CreateInvoiceViewModelClass: IInvoiceViewModelInterface; begin result:=TInvoiceViewModel.Create; end; { TInvoiceViewModel } procedure TInvoiceViewModel.AddInvoiceItem(const itemDescription: string; const quantity: integer); begin fModel.AddInvoiceItem(itemDescription, quantity); SendNotification([actInvoiceItemsChanges]); end; constructor TInvoiceViewModel.Create; begin fInvoiceItemsEnabled:=false; fBalanceEnabled:=false; fPrintButtonEnabled:=false; fAniIndicatorVisible:=false; fPrintingLabelVisible:=false; fDiscountChecked:=false; fProvider:=CreateProSuProviderClass; end; procedure TInvoiceViewModel.DeleteAllInvoiceItems; begin fModel.DeleteAllInvoiceItems; SendNotification([actInvoiceItemsChanges]); end; procedure TInvoiceViewModel.DeleteInvoiceItem(const delItemIDAsText: string); begin if (trim(delItemIDAsText)='') then Exit; fModel.DeleteInvoiceItem(delItemIDAsText.ToInteger); SendNotification([actInvoiceItemsChanges]); end; function TInvoiceViewModel.GetAniIndicatorProgressVisible: Boolean; begin result:=fAniIndicatorVisible; end; function TInvoiceViewModel.GetButtonPrintInvoiceEnabled: Boolean; begin result:=fPrintButtonEnabled; end; procedure TInvoiceViewModel.GetCustomerDetails(const customerName: string; var customerDetails: TCustomerDetailsText); var tmpCustomer: TCustomer; begin if trim(customerName)='' then begin customerDetails.DiscountRate:='Please Choose a Customer'; customerDetails.OutstandingBalance:='Please Choose a Customer'; end else begin tmpCustomer:=TCustomer.Create; fModel.GetCustomer(trim(customerName), tmpCustomer); customerDetails.DiscountRate:=Format('%5.2f', [tmpCustomer.DiscountRate])+'%'; customerDetails.OutstandingBalance:=Format('%-n',[tmpCustomer.Balance]); tmpCustomer.Free; fInvoiceItemsEnabled:=true; fBalanceEnabled:=true; fDiscountChecked:=false; end; end; procedure TInvoiceViewModel.GetCustomerList( var customers: TObjectList<TCustomer>); begin fModel.GetCustomerList(customers); end; function TInvoiceViewModel.GetDiscountApplied: boolean; begin result:=fDiscountChecked; end; function TInvoiceViewModel.GetGroupBoxBalanceEnabled: Boolean; begin result:=fBalanceEnabled; end; function TInvoiceViewModel.GetGroupBoxInvoiceItemsEnabled: Boolean; begin Result:=fInvoiceItemsEnabled; end; function TInvoiceViewModel.GetInvoiceItemsText: TInvoiceItemsText; var tmpRunning, tmpDiscount: Currency; tmpInvoiceItems: TObjectList<TInvoiceItem>; i, tmpLen: integer; tmpItem: TItem; begin tmpLen:=0; SetLength(fInvoiceItemsText.DescriptionText,tmpLen); SetLength(fInvoiceItemsText.QuantityText,tmpLen); SetLength(fInvoiceItemsText.UnitPriceText,tmpLen); SetLength(fInvoiceItemsText.PriceText,tmpLen); SetLength(fInvoiceItemsText.IDText, tmpLen); tmpRunning:=0.00; tmpDiscount:=0.00; tmpInvoiceItems:=TObjectList<TInvoiceItem>.Create; fModel.GetInvoiceItems(tmpInvoiceItems); for i := 0 to tmpInvoiceItems.Count-1 do begin tmpLen:=Length(fInvoiceItemsText.DescriptionText)+1; SetLength(fInvoiceItemsText.DescriptionText,tmpLen); SetLength(fInvoiceItemsText.QuantityText,tmpLen); SetLength(fInvoiceItemsText.UnitPriceText,tmpLen); SetLength(fInvoiceItemsText.PriceText,tmpLen); SetLength(fInvoiceItemsText.IDText, tmpLen); tmpItem:=TItem.Create; fModel.GetInvoiceItemFromID(tmpInvoiceItems.Items[i].ID, tmpItem); fInvoiceItemsText.DescriptionText[tmpLen-1]:=tmpItem.Description; tmpItem.Free; fInvoiceItemsText.QuantityText[tmpLen-1]:=tmpInvoiceItems.Items[i].Quantity.ToString; fInvoiceItemsText.UnitPriceText[tmpLen-1]:=format('%10.2f',[tmpInvoiceItems.Items[i].UnitPrice]); fInvoiceItemsText.PriceText[tmpLen-1]:= format('%10.2f',[tmpInvoiceItems.Items[i].UnitPrice*tmpInvoiceItems.items[i].Quantity]); fInvoiceItemsText.IDText[tmpLen-1]:=tmpInvoiceItems.Items[i].ID.ToString; end; tmpInvoiceItems.Free; tmpRunning:=fModel.InvoiceRunningBalance; if fDiscountChecked then tmpDiscount:=fModel.InvoiceDiscount; fInvoiceItemsText.InvoiceRunningBalance:=Format('%10.2f', [tmpRunning]); fInvoiceItemsText.InvoiceDiscountFigure:=Format('%10.2f', [tmpDiscount]); fInvoiceItemsText.InvoiceTotalBalance:=Format('%10.2f', [tmpRunning-tmpDiscount]); fPrintButtonEnabled:=fModel.NumberOfInvoiceItems > 0; Result:=fInvoiceItemsText; end; procedure TInvoiceViewModel.GetItems(var items: TObjectList<TItem>); begin fModel.GetItems(items); end; function TInvoiceViewModel.GetLabelPrintingVisible: Boolean; begin result:=fPrintingLabelVisible; end; function TInvoiceViewModel.GetLabelsText: TInvoiceFormLabelsText; begin result:=fModel.GetInvoiceFormLabelsText; end; function TInvoiceViewModel.GetModel: IInvoiceModelInterface; begin result:=fModel; end; function TInvoiceViewModel.GetProvider: IProviderInterface; begin result:=fProvider; end; function TInvoiceViewModel.GetTitleText: string; var tmpInvoice: TInvoice; begin fModel.GetInvoice(tmpInvoice); if Assigned(tmpInvoice) then result:=fModel.GetInvoiceFormLabelsText.Title+' #'+IntToStr(tmpInvoice.Number) end; procedure TInvoiceViewModel.PrintInvoice; var tmpNotifClass: TNotificationClass; begin fAniIndicatorVisible:=true; fPrintingLabelVisible:=true; SendNotification([actPrintingStart]); fModel.PrintInvoice; fAniIndicatorVisible:=false; fPrintingLabelVisible:=false; SendNotification([actPrintingFinish]); end; procedure TInvoiceViewModel.SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string); var tmpErrorNotificationClass: TErrorNotificationClass; begin tmpErrorNotificationClass:=TErrorNotificationClass.Create; try tmpErrorNotificationClass.Actions:=errorType; tmpErrorNotificationClass.ActionMessage:=errorMessage; fProvider.NotifySubscribers(tmpErrorNotificationClass); finally tmpErrorNotificationClass.Free; end; end; procedure TInvoiceViewModel.SendNotification(const actions: TInterfaceActions); var tmpNotificationClass: TNotificationClass; begin tmpNotificationClass:=TNotificationClass.Create; tmpNotificationClass.Actions:=actions; if Assigned(fProvider) then fProvider.NotifySubscribers(tmpNotificationClass); tmpNotificationClass.Free; end; procedure TInvoiceViewModel.SetDiscountApplied(const discount: boolean); begin fDiscountChecked:=discount; end; procedure TInvoiceViewModel.SetModel(const newModel: IInvoiceModelInterface); begin fModel:=newModel; end; procedure TInvoiceViewModel.ValidateItem(const newItem: string); begin if trim(newItem)='' then SendErrorNotification([errInvoiceItemEmpty], 'Please choose an item'); end; procedure TInvoiceViewModel.ValidateQuantity(const newQuantityText: string); var value, code: integer; begin if trim(newQuantityText)='' then begin SendErrorNotification([errInvoiceItemQuantityEmpty], 'Please enter quantity'); Exit; end; Val(trim(newQuantityText), value, code); if code<>0 then begin SendErrorNotification([errInvoiceItemQuantityNotNumber], 'Quantity must be a number'); Exit; end; if trim(newQuantityText).ToInteger<=0 then begin SendErrorNotification([errInvoiceItemQuantityNonPositive], 'The quantity must be positive number'); Exit; end; SendErrorNotification([errNoError], ''); end; end.
unit OAuth2.Contract.Repository.Scope; interface uses OAuth2.Contract.Entity.Client, OAuth2.Contract.Entity.Scope; type IOAuth2ScopeRepository = interface ['{318F5A92-4B9B-4E40-874F-90EDA87615DA}'] function GetScopeEntityByIdentifier(AIdentifier: string): IOAuth2ScopeEntity; function FinalizeScopes(AScopes: TArray<IOAuth2ScopeEntity>; AGrantType: string; AClientEntity: IOAuth2ClientEntity; const AUserIdentifier: string = ''): TArray<IOAuth2ScopeEntity>; end; implementation end.
unit AqDrop.Core.REST; interface uses System.SysUtils, REST.Client, AqDrop.Core.InterfacedObject, AqDrop.Core.HTTP.Types, AqDrop.Core.HTTP.Intf, AqDrop.Core.REST.Intf; type TAqRESTRequest = class(TAqARCObject, IAqRESTRequest) strict private FRESTClient: TRESTClient; FRESTResponse: TRESTResponse; FRESTRequest: TRESTRequest; procedure ExecuteRequest; public constructor Create; destructor Destroy; override; function SetURL(const pURL: string): IAqRESTRequest; function SetBasicAuth(const pUsername, pPassword: string): IAqRESTRequest; function SetResource(const pResource: string): IAqRESTRequest; function AddHeader(const pType: TAqHTTPHeaderType; const pValue: string; const pEncode: Boolean = True): IAqRESTRequest; function AddBody(const pValue: string): IAqRESTRequest; function AddURLSegment(const pName: string; const pValue: string): IAqRESTRequest; function SetTimeOut(const pTimeOut: Int32): IAqRESTRequest; function Customize(const pCustomizationMethod: TProc<IAqRESTRequest>): IAqRESTRequest; function ExecuteGet: IAqRESTRequest; function ExecutePost: IAqRESTRequest; function ExecutePut: IAqRESTRequest; function ExecuteDelete: IAqRESTRequest; function ExecutePatch: IAqRESTRequest; function GetResult: IAqHTTPResult; function GetResultContent: string; end; TAqRESTBuilder = class public class function CreateRequest: IAqRESTRequest; end; implementation uses REST.Types, REST.Authenticator.Basic, AqDrop.Core.HTTP; { TAqRESTBuilder } class function TAqRESTBuilder.CreateRequest: IAqRESTRequest; begin Result := TAqRESTRequest.Create; end; { TAqRESTRequest } function TAqRESTRequest.AddBody(const pValue: string): IAqRESTRequest; var lParam: TRESTRequestParameter; begin lParam := FRESTRequest.Params.AddItem; lParam.Kind := TRESTRequestParameterKind.pkREQUESTBODY; lParam.Value := pValue; lParam.ContentType := ctAPPLICATION_JSON; Result := Self; end; function TAqRESTRequest.AddHeader(const pType: TAqHTTPHeaderType; const pValue: string; const pEncode: Boolean): IAqRESTRequest; var lParam: TRESTRequestParameter; begin lParam := FRESTRequest.Params.AddHeader(pType.ToString, pValue); if not pEncode then begin lParam.Options := lParam.Options + [TRESTRequestParameterOption.poDoNotEncode]; end; Result := Self; end; function TAqRESTRequest.AddURLSegment(const pName, pValue: string): IAqRESTRequest; begin FRESTRequest.Params.AddUrlSegment(pName, pValue); Result := Self; end; constructor TAqRESTRequest.Create; begin FRESTClient := TRESTClient.Create(nil); FRESTResponse := TRESTResponse.Create(nil); FRESTRequest := TRESTRequest.Create(nil); FRESTRequest.Client := FRESTClient; FRESTRequest.Response := FRESTResponse; end; function TAqRESTRequest.Customize(const pCustomizationMethod: TProc<IAqRESTRequest>): IAqRESTRequest; begin if Assigned(pCustomizationMethod) then begin pCustomizationMethod(Self); end; Result := Self; end; function TAqRESTRequest.ExecuteDelete: IAqRESTRequest; begin FRESTRequest.Method := TRESTRequestMethod.rmDELETE; ExecuteRequest; Result := Self; end; destructor TAqRESTRequest.Destroy; begin FRESTRequest.Free; FRESTResponse.Free; FRESTClient.Free; inherited; end; procedure TAqRESTRequest.ExecuteRequest; begin FRESTRequest.Execute; end; function TAqRESTRequest.ExecuteGet: IAqRESTRequest; begin FRESTRequest.Method := TRESTRequestMethod.rmGET; ExecuteRequest; Result := Self; end; function TAqRESTRequest.GetResult: IAqHTTPResult; begin Result := TAqHTTPResult.Create(FRESTResponse.StatusCode, FRESTResponse.Content); end; function TAqRESTRequest.GetResultContent: string; begin Result := FRESTResponse.Content; end; function TAqRESTRequest.ExecutePatch: IAqRESTRequest; begin FRESTRequest.Method := TRESTRequestMethod.rmDELETE; ExecuteRequest; Result := Self; end; function TAqRESTRequest.ExecutePost: IAqRESTRequest; begin FRESTRequest.Method := TRESTRequestMethod.rmPOST; ExecuteRequest; Result := Self; end; function TAqRESTRequest.ExecutePut: IAqRESTRequest; begin FRESTRequest.Method := TRESTRequestMethod.rmPUT; ExecuteRequest; Result := Self; end; function TAqRESTRequest.SetBasicAuth(const pUsername, pPassword: string): IAqRESTRequest; var lAuthenticator: THTTPBasicAuthenticator; begin if Assigned(FRESTClient.Authenticator) then begin FRESTClient.Authenticator.Free; FRESTClient.Authenticator := nil; end; lAuthenticator := THTTPBasicAuthenticator.Create(FRESTClient); FRESTClient.Authenticator := lAuthenticator; lAuthenticator.Username := pUsername; lAuthenticator.Password := pPassword; Result := Self; end; function TAqRESTRequest.SetResource(const pResource: string): IAqRESTRequest; begin FRESTRequest.Resource := pResource; Result := Self; end; function TAqRESTRequest.SetTimeOut(const pTimeOut: Int32): IAqRESTRequest; begin FRESTRequest.Timeout := pTimeOut; Result := Self; end; function TAqRESTRequest.SetURL(const pURL: string): IAqRESTRequest; begin FRESTClient.BaseURL := pURL; Result := Self; end; end.
{**********************************************************************************} { } { Project vkDBF - dbf ntx clipper compatibility delphi component } { } { This Source Code Form is subject to the terms of the Mozilla Public } { License, v. 2.0. If a copy of the MPL was not distributed with this } { file, You can obtain one at http://mozilla.org/MPL/2.0/. } { } { The Initial Developer of the Original Code is Vlad Karpov (KarpovVV@protek.ru). } { } { Contributors: } { Sergey Klochkov (HSerg@sklabs.ru) } { } { You may retrieve the latest version of this file at the Project vkDBF home page, } { located at http://sourceforge.net/projects/vkdbf/ } { } {**********************************************************************************} unit VKDBFNTX; {$I VKDBF.DEF} interface uses Windows, Messages, SysUtils, Classes, contnrs, db, Math, {$IFDEF DELPHI6} Variants, {$ENDIF} VKDBFPrx, VKDBFParser, VKDBFIndex, VKDBFUtil, VKDBFMemMgr, VKDBFSorters, VKDBFSortedList, VKDBFCrypt, syncobjs; const NTX_MAX_KEY = 256; // Maximum of length of key expression NTX_PAGE = 1024; // Dimension of NTX page MAX_LEV_BTREE = 30; // Maximum depth of BTREE MAX_NTX_STOCK = 100000; // Stock ntx pages for count size of ntx pages buffer NTX_STOCK_INSURANCE = 3; // MAX_ITEMS_IN_PAGE = 510; // DEFPAGESPERBUFFER = 4; type TDeleteKeyStyle = (dksClipper, dksApolloHalcyon); //NTX Structute NTX_HEADER = packed record sign: WORD; //2 0 version: WORD; //2 2 root: DWORD; //4 4 next_page: DWORD; //4 8 item_size: WORD; //2 12 key_size: WORD; //2 14 key_dec: WORD; //2 16 max_item: WORD; //2 18 half_page: WORD; //2 20 key_expr: array [0..NTX_MAX_KEY-1] of AnsiChar; //256 22 unique: AnsiChar; //1 278 reserv1: AnsiChar; //1 279 desc: AnsiChar; //1 280 reserv3: AnsiChar; //1 281 for_expr: array [0..NTX_MAX_KEY-1] of AnsiChar; //256 282 order: array [0..7] of AnsiChar; //8 538 Rest: array [0..477] of AnsiChar; //478 546 end; //1024 // // Describer one ITEM // NTX_ITEM = packed record page: DWORD; rec_no: DWORD; key: array[0..NTX_PAGE-1] of AnsiChar; end; pNTX_ITEM = ^NTX_ITEM; // // Beginign of Index page // NTX_BUFFER = packed record count: WORD; ref: array[0..MAX_ITEMS_IN_PAGE] of WORD; end; pNTX_BUFFER = ^NTX_BUFFER; // // Block item for compact indexing // BLOCK_ITEM = packed record rec_no: DWORD; key: array[WORD] of AnsiChar; end; pBLOCK_ITEM = ^BLOCK_ITEM; // // Block for compact indexing // BLOCK_BUFFER = packed record count: WORD; ref: array[WORD] of WORD; end; pBLOCK_BUFFER = ^BLOCK_BUFFER; TBTreeLevels = array [0..MAX_LEV_BTREE] of NTX_BUFFER; pBTreeLevels = ^TBTreeLevels; // // Abstract class Iterator // TVKNTXIndexIterator = class(TObject) public item: NTX_ITEM; Eof: boolean; procedure Open; virtual; abstract; procedure Close; virtual; abstract; procedure Next; virtual; abstract; constructor Create; destructor Destroy; override; end; // // Block class Iterator // TVKNTXBlockIterator = class(TVKNTXIndexIterator) protected i: Integer; FBufSize: Integer; Fkey_size: Integer; FFileName: AnsiString; FHndl: Integer; p: pBLOCK_BUFFER; public procedure Open; override; procedure Close; override; procedure Next; override; constructor Create(FileName: AnsiString; key_size, BufSize: Integer); overload; destructor Destroy; override; end; // // NTX class Iterator // TVKNTXIterator = class(TVKNTXIndexIterator) protected FFileName: AnsiString; FHndl: Integer; SHead: NTX_HEADER; levels: pBTreeLevels; indexes: array [0..MAX_LEV_BTREE] of WORD; cur_lev: Integer; public procedure Open; override; procedure Close; override; procedure Next; override; constructor Create(FileName: AnsiString); overload; destructor Destroy; override; end; // // Compact index class for CreateCompact method TVKNTXIndex // TVKNTXCompactIndex = class(TObject) private FHndl: Integer; SHead: NTX_HEADER; levels: TBTreeLevels; cur_lev: Integer; max_lev: Integer; SubOffSet: DWORD; CryptPage: NTX_BUFFER; pWriteBuff: pAnsiChar; wbCount: Integer; wbAmount: Integer; public FileName: AnsiString; OwnerTable: TDataSet; Crypt: boolean; Handler: TProxyStream; CreateTmpFilesInTmpFilesDir: boolean; TmpFilesDir: AnsiString; constructor Create(pBuffCount: Integer = 0); destructor Destroy; override; procedure NewPage(lev: Integer); procedure CreateEmptyIndex(var FHead: NTX_HEADER); procedure AddItem(item: pNTX_ITEM); procedure Flush; procedure LinkRest; procedure NormalizeRest; procedure Close; end; //Forword declarations TVKNTXIndex = class; TVKNTXBuffer = class; {TVKNTXNodeDirect} TVKNTXNodeDirect = class private FNodeOffset: DWORD; FNode: NTX_BUFFER; function GetNode: NTX_BUFFER; function GetPNode: pNTX_BUFFER; public constructor Create(Offset: DWORD); property PNode: pNTX_BUFFER read GetPNode; property Node: NTX_BUFFER read GetNode; property NodeOffset: DWORD read FNodeOffset; end; {TVKNTXNode} TVKNTXNode = class private FNTXBuffer: TVKNTXBuffer; FNodeOffset: DWORD; FIndexInBuffer: Integer; FChanged: boolean; function GetPNode: pNTX_BUFFER; function GetNode: NTX_BUFFER; public constructor Create(Owner: TVKNTXBuffer; Offset: DWORD; Index: Integer); property PNode: pNTX_BUFFER read GetPNode; property Node: NTX_BUFFER read GetNode; property NodeOffset: DWORD read FNodeOffset; property Changed: boolean read FChanged write FChanged; property NTXBuffer: TVKNTXBuffer read FNTXBuffer; end; //{$DEFINE NTXBUFFERASTREE} //{//$UNDEF NTXBUFFERASTREE} //{$IFNDEF NTXBUFFERASTREE} {TVKNTXBuffer} TVKNTXBuffer = class private FOffset: DWORD; FBusyCount: Integer; FUseCount: DWORD; FNodeCount: Word; FPages: pNTX_BUFFER; FNTXNode: array[0..Pred(MAX_ITEMS_IN_PAGE)] of TVKNTXNode; function GetBusy: boolean; procedure SetBusy(const Value: boolean); function GetChanged: boolean; function GetPPages(ndx: DWord): pNTX_BUFFER; function GetNTXNode(ndx: DWord): TVKNTXNode; procedure SetChanged(const Value: boolean); procedure SetOffset(const Value: DWORD); public constructor Create(pOffset: DWORD; pNodeCount: Word); destructor Destroy; override; property Changed: boolean read GetChanged write SetChanged; property NodeCount: Word read FNodeCount; property Pages: pNTX_BUFFER read FPages; property PPage[ndx: DWord]: pNTX_BUFFER read GetPPages; property NTXNode[ndx: DWord]: TVKNTXNode read GetNTXNode; property Busy: boolean read GetBusy write SetBusy; property UseCount: DWORD read FUseCount write FUseCount; property Offset: DWORD read FOffset write SetOffset; end; {TVKNTXBuffers} TVKNTXBuffers = class(TObjectList) private NXTObject: TVKNTXIndex; Flt: TVKLimitBuffersType; FMaxBuffers: Integer; FPagesPerBuffer: Integer; FUseCount: DWORD; function FindIndex(block_offset: DWORD; out Ind: Integer): boolean; function FindLeastUsed(out Ind: Integer): boolean; public constructor Create; destructor Destroy; override; function IncUseCount(b: TVKNTXBuffer): DWORD; function GetNTXBuffer(Handle: TProxyStream; page_offset: DWORD; out page: pNTX_BUFFER; fRead: boolean = true): TVKNTXNode; procedure FreeNTXBuffer(ntxb: TVKNTXBuffer); procedure SetPageChanged(Handle: TProxyStream; page_offset: DWORD); procedure Flush(Handle: TProxyStream); procedure Flash(ntxb: TVKNTXBuffer); property lt: TVKLimitBuffersType read Flt write Flt; property MaxBuffers: Integer read FMaxBuffers write FMaxBuffers; property PagesPerBuffer: Integer read FPagesPerBuffer write FPagesPerBuffer; end; //{$ELSE} (* {TVKNTXBuffer} TVKNTXBuffer = class(TVKSortedObject) private FOffset: DWORD; FBusyCount: Integer; FUseCount: DWORD; FNodeCount: Word; FPages: pNTX_BUFFER; FNTXNode: array[0..Pred(MAX_ITEMS_IN_PAGE)] of TVKNTXNode; function GetBusy: boolean; procedure SetBusy(const Value: boolean); function GetChanged: boolean; function GetPPages(ndx: DWord): pNTX_BUFFER; function GetNTXNode(ndx: DWord): TVKNTXNode; procedure SetChanged(const Value: boolean); procedure SetOffset(const Value: DWORD); public constructor Create(pOffset: DWORD; pNodeCount: Word); destructor Destroy; override; function cpm(sObj: TVKSortedObject): Integer; override; function IncUseCount: DWORD; property Changed: boolean read GetChanged write SetChanged; property NodeCount: Word read FNodeCount; property Pages: pNTX_BUFFER read FPages; property PPage[ndx: DWord]: pNTX_BUFFER read GetPPages; property NTXNode[ndx: DWord]: TVKNTXNode read GetNTXNode; property Busy: boolean read GetBusy write SetBusy; property UseCount: DWORD read FUseCount write FUseCount; property Offset: DWORD read FOffset write SetOffset; end; {TVKNTXBuffers} TVKNTXBuffers = class(TVKSortedList) private NXTObject: TVKNTXIndex; Flt: TVKLimitBuffersType; FMaxBuffers: Integer; FPagesPerBuffer: Integer; FTMPHandle: TProxyStream; function FindLeastUsed(out Ind: Integer): boolean; public constructor Create; destructor Destroy; override; function FindKey(dwKey: DWORD): TVKSortedObject; function GetNTXBuffer(Handle: TProxyStream; page_offset: DWORD; out page: pNTX_BUFFER; fRead: boolean = true): TVKNTXNode; procedure FreeNTXBuffer(ntxb: TVKNTXBuffer); procedure SetPageChanged(Handle: TProxyStream; page_offset: DWORD); procedure Flush(Handle: TProxyStream); procedure Flash(ntxb: TVKNTXBuffer); procedure OnFlush(Sender: TVKSortedListAbstract; SortedObject: TVKSortedObject); property lt: TVKLimitBuffersType read Flt write Flt; property MaxBuffers: Integer read FMaxBuffers write FMaxBuffers; property PagesPerBuffer: Integer read FPagesPerBuffer write FPagesPerBuffer; end; //{$ENDIF} *) {TVKNTXRange} TVKNTXRange = class(TPersistent) private FActive: boolean; FLoKey: AnsiString; FHiKey: AnsiString; FNTX: TVKNTXIndex; function GetActive: boolean; procedure SetActive(const Value: boolean); protected public function InRange(S: AnsiString): boolean; procedure ReOpen; property NTX: TVKNTXIndex read FNTX write FNTX; published property Active: boolean read GetActive write SetActive; property HiKey: AnsiString read FHiKey write FHiKey; property LoKey: AnsiString read FLoKey write FLoKey; end; {TVKNTXOrder} TVKNTXOrder = class(TVKDBFOrder) public FHead: NTX_HEADER; constructor Create(Collection: TCollection); override; destructor Destroy; override; function CreateOrder: boolean; override; published property OnCreateIndex; property OnEvaluteKey; property OnEvaluteFor; property OnCompareKeys; end; {TVKNTXBag} TVKNTXBag = class(TVKDBFIndexBag) private //FLstOffset: DWORD; public constructor Create(Collection: TCollection); override; destructor Destroy; override; function CreateBag: boolean; override; function Open: boolean; override; function IsOpen: boolean; override; procedure Close; override; procedure FillHandler; //property FLastOffset: DWORD read FLstOffset write FLstOffset; property NTXHandler: TProxyStream read Handler write Handler; end; {TVKNTXIndex} TVKNTXIndex = class(TIndex) private FNTXBag: TVKNTXBag; FNTXOrder: TVKNTXOrder; FLastOffset: DWORD; FReindex: boolean; FCreateIndexProc: boolean; FNTXBuffers: TVKNTXBuffers; FNTXFileName: AnsiString; //NTXHandler: Integer; //FHead: NTX_HEADER; FKeyExpresion: AnsiString; FForExpresion: AnsiString; FKeyParser: TVKDBFExprParser; FForParser: TVKDBFExprParser; FForExists: boolean; FKeyTranslate: boolean; //FCl501Rus: boolean; FFileLock: boolean; FSeekRecord: Integer; FSeekKey: AnsiString; FSeekOk: boolean; FTemp: boolean; FNTXRange: TVKNTXRange; FOnSubNtx: TOnSubNtx; FDestructor: boolean; FClipperVer: TCLIPPER_VERSION; FUpdated: boolean; FFLastFUpdated: boolean; FDeleteKeyStyle: TDeleteKeyStyle; FUnique: boolean; FDesc: boolean; FOrder: AnsiString; FGetHashFromSortItem: boolean; FFLockObject: TCriticalSection; FFUnLockObject: TCriticalSection; //procedure ForwardPass; //procedure BackwardPass; procedure SetNTXFileName(const Value: AnsiString); procedure SetKeyExpresion(Value: AnsiString); procedure SetForExpresion(Value: AnsiString); function CompareKeys(S1, S2: PAnsiChar; MaxLen: Cardinal): Integer; function GetFreePage: DWORD; procedure SetUnique(const Value: boolean); function GetUnique: boolean; procedure SetDesc(const Value: boolean); function GetDesc: boolean; function SeekFirstInternal(Key: AnsiString; SoftSeek: boolean = false): boolean; function SeekLastInternal(Key: AnsiString; SoftSeek: boolean = false): boolean; procedure ChekExpression(var Value: AnsiString); function GetOwnerTable: TDataSet; procedure ClearIfChange; function GetCreateNow: Boolean; procedure SetCreateNow(const Value: Boolean); procedure SetNTXRange(const Value: TVKNTXRange); //procedure SortNtxNode(NtxNode: TVKNTXNode); procedure IndexSortProc(Sender: TObject; CurrentItem, Item: PSORT_ITEM; MaxLen: Cardinal; out c: Integer); procedure IndexSortCharsProc(Sender: TObject; Char1, Char2: Byte; out c: Integer); protected FCurrentKey: AnsiString; FCurrentRec: DWORD; function GetIsRanged: boolean; override; procedure AssignIndex(oInd: TVKNTXIndex); function InternalFirst: TGetResult; override; function InternalNext: TGetResult; override; function InternalPrior: TGetResult; override; function InternalLast: TGetResult; override; function GetCurrentKey: AnsiString; override; function GetCurrentRec: DWORD; override; //function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer; //function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer; function AddItem(ntxItem: pNTX_ITEM; AddItemAtEnd: boolean = False): boolean; function GetOrder: AnsiString; override; procedure SetOrder(Value: AnsiString); override; procedure DefineBag; override; procedure DefineBagAndOrder; override; function GetIndexBag: TVKDBFIndexBag; override; function GetIndexOrder: TVKDBFOrder; override; procedure GetVKHashCode(Sender: TObject; Item: PSORT_ITEM; out HashCode: DWord); override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function IsEqual(Value: TIndex): Boolean; override; function CmpKeys(ItemKey, CurrKey: pAnsiChar; KSize: Integer = 0): Integer; function CmpKeys1(ItemKey, CurrKey: pAnsiChar; KSize: Integer = 0): Integer; function CmpKeys2(ItemKey, CurrKey: pAnsiChar; KSize: Integer = 0): Integer; function CmpKeys3(ItemKey, CurrKey: pAnsiChar; KSize: Integer = 0): Integer; procedure TransKey(Key: pAnsiChar; KSize: Integer = 0; ToOem: Boolean = true); overload; function TransKey(Key: AnsiString): AnsiString; overload; procedure TransKey(var SItem: SORT_ITEM); overload; function Open: boolean; override; procedure Close; override; function IsOpen: boolean; override; function SetToRecord: boolean; overload; override; function SetToRecord(Rec: Longint): boolean; overload; override; function SetToRecord(Key: AnsiString; Rec: Longint): boolean; overload; override; // function Seek(Key: AnsiString; SoftSeek: boolean = false): boolean; override; function SeekFirst( Key: AnsiString; SoftSeek: boolean = false; PartialKey: boolean = false): boolean; override; function SeekFirstRecord( Key: AnsiString; SoftSeek: boolean = false; PartialKey: boolean = false): Integer; override; function SeekFields(const KeyFields: AnsiString; const KeyValues: Variant; SoftSeek: boolean = false; PartialKey: boolean = false): Integer; override; // It is a new find mashine subject to SetDeleted, Filter and Range function FindKey(Key: AnsiString; PartialKey: boolean = false; SoftSeek: boolean = false; Rec: DWORD = 0): Integer; override; function FindKeyFields( const KeyFields: AnsiString; const KeyValues: Variant; PartialKey: boolean = false; SoftSeek: boolean = false): Integer; overload; override; function FindKeyFields( const KeyFields: AnsiString; const KeyValues: array of const; PartialKey: boolean = false; SoftSeek: boolean = false): Integer; overload; override; function FindKeyFields( PartialKey: boolean = false; SoftSeek: boolean = false): Integer; overload; override; // function SubIndex(LoKey, HiKey: AnsiString): boolean; override; function SubNtx(var SubNtxFile: AnsiString; LoKey, HiKey: AnsiString): boolean; function FillFirstBufRecords(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): longint; override; function FillLastBufRecords(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): longint; override; function EvaluteKeyExpr: AnsiString; override; function SuiteFieldList(fl: AnsiString; out m: Integer): Integer; override; function EvaluteForExpr: boolean; override; function GetRecordByIndex(GetMode: TGetMode; var cRec: Longint): TGetResult; override; function GetFirstByIndex(var cRec: Longint): TGetResult; override; function GetLastByIndex(var cRec: Longint): TGetResult; override; procedure First; override; procedure Next; override; procedure Prior; override; procedure Last; override; function LastKey(out LastKey: AnsiString; out LastRec: LongInt): boolean; override; function NextBuffer(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): Longint; override; function PriorBuffer(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): Longint; override; procedure SetRangeFields(FieldList: AnsiString; FieldValues: array of const); overload; override; procedure SetRangeFields(FieldList: AnsiString; FieldValues: variant); overload; override; procedure SetRangeFields(FieldList: AnsiString; FieldValuesLow: array of const; FieldValuesHigh: array of const); overload; override; procedure SetRangeFields(FieldList: AnsiString; FieldValuesLow: variant; FieldValuesHigh: variant); overload; override; function InRange(Key: AnsiString): boolean; overload; override; function InRange: boolean; overload; override; function FLock: boolean; override; function FUnLock: boolean; override; procedure StartUpdate(UnLock: boolean = true); override; procedure Flush; override; procedure DeleteKey(sKey: AnsiString; nRec: Longint); override; procedure AddKey(sKey: AnsiString; nRec: Longint); override; // Create index file adding keys one by one using classic algorithm // division B-tree pages. B-tree pages stores im memory according // LimitPages property procedure CreateIndex(Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); override; // Save on disk sorted blocks, then merge blocks into BTrees. Slowly CreateIndex, but no need memory procedure CreateCompactIndex( BlockBufferSize: LongWord = 65536; Activate: boolean = true; CreateTmpFilesInCurrentDir: boolean = false); override; // Create index using RAM SORTER algorithm. // SorterClass must be one of the descendant of TVKSorterAbstract. procedure CreateIndexUsingSorter(SorterClass: TVKSorterClass; Activate: boolean = true); override; //procedure CreateIndexUsingSorter1(SorterClass: TVKSorterClass; Activate: boolean = true); override; // All keys has copied to RAM buffer and sorted using "Quick Sort" algorithm, // then carried to the index file. ATTANTION: All keys stores in memory! //procedure CreateIndexUsingQuickSort(Activate: boolean = true); override; // //Experiments with external sort of B-Tree // (* procedure CreateIndexUsingMergeBinaryTreeAndBTree( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = True; PreSorterBlockSize: LongWord = 65536); override; procedure CreateIndexUsingBTreeHeapSort(Activate: boolean = true); override; procedure CreateIndexUsingFindMinsAndJoinItToBTree( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); override; procedure CreateIndexUsingAbsorption( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); override; *) // // // procedure Reindex(Activate: boolean = true); override; procedure VerifyIndex; override; procedure Truncate; override; procedure BeginCreateIndexProcess; override; procedure EvaluteAndAddKey(nRec: DWORD); override; procedure EndCreateIndexProcess; override; function IsUniqueIndex: boolean; override; function IsForIndex: boolean; override; function ReCrypt(pNewCrypt: TVKDBFCrypt): boolean; override; property OwnerTable: TDataSet read GetOwnerTable; published property NTXFileName: AnsiString read FNTXFileName write SetNTXFileName; property KeyExpresion: AnsiString read FKeyExpresion write SetKeyExpresion stored false; property ForExpresion: AnsiString read FForExpresion write SetForExpresion stored false; property KeyTranslate: boolean read FKeyTranslate write FKeyTranslate default true; //property Clipper501RusOrder: boolean read FCl501Rus write FCl501Rus; property Unique: boolean read GetUnique write SetUnique; property Desc: boolean read GetDesc write SetDesc; property Order; property Temp: boolean read FTemp write FTemp; property NTXRange: TVKNTXRange read FNTXRange write SetNTXRange; property ClipperVer: TCLIPPER_VERSION read FClipperVer write FClipperVer default v500; property CreateNow: Boolean read GetCreateNow write SetCreateNow; property DeleteKeyStyle: TDeleteKeyStyle read FDeleteKeyStyle write FDeleteKeyStyle; property LimitPages; property OuterSorterProperties; property HashTypeForTreeSorters; property MaxBitsInHashCode; property OnCreateIndex; property OnSubIndex; property OnEvaluteKey; property OnEvaluteFor; property OnCompareKeys; property OnSubNtx: TOnSubNtx read FOnSubNtx write FOnSubNtx; end; implementation uses DBCommon, Dialogs, AnsiStrings, VKDBFDataSet; { TVKNTXIndex } procedure TVKNTXIndex.Assign(Source: TPersistent); begin if Source is TVKNTXIndex then AssignIndex(TVKNTXIndex(Source)) else inherited Assign(Source); end; procedure TVKNTXIndex.AssignIndex(oInd: TVKNTXIndex); begin if oInd <> nil then begin Name := oInd.Name; NTXFileName := oInd.NTXFileName; end; end; procedure TVKNTXIndex.Close; begin // FNTXOrder.LimitPages.LimitPagesType := LimitPages.LimitPagesType; FNTXOrder.LimitPages.LimitBuffers := LimitPages.LimitBuffers; FNTXOrder.LimitPages.PagesPerBuffer := LimitPages.PagesPerBuffer; FNTXOrder.Collation.CollationType := Collation.CollationType; FNTXOrder.Collation.CustomCollatingSequence := Collation.CustomCollatingSequence; // FNTXOrder.OuterSorterProperties := OuterSorterProperties; // if not IsOpen then Exit; Flush; FNTXBuffers.Clear; FNTXBag.Close; FForExists := false; if FTemp then begin DeleteFile(FNTXFileName); if not FDestructor then Collection.Delete(Index); end; end; constructor TVKNTXIndex.Create(Collection: TCollection); var FieldMap: TFieldMap; begin inherited Create(Collection); FFLockObject := TCriticalSection.Create; FFUnLockObject := TCriticalSection.Create; FUpdated := False; FClipperVer := v500; FDeleteKeyStyle := dksClipper; FUnique := False; FDesc := False ; FOrder := ''; (* FNTXOrder.FHead.sign := 6; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := 0; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.item_size := 0; FNTXOrder.FHead.key_size := 0; FNTXOrder.FHead.key_dec := 0; FNTXOrder.FHead.max_item := 0; FNTXOrder.FHead.half_page := 0; for i := 0 to NTX_MAX_KEY-1 do FNTXOrder.FHead.key_expr[i] := #0; FNTXOrder.FHead.unique := #0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.desc := #0; FNTXOrder.FHead.reserv3 := #0; for i := 0 to NTX_MAX_KEY-1 do FNTXOrder.FHead.for_expr[i] := #0; for i := 0 to 7 do FNTXOrder.FHead.order[i] := #0; for i := 0 to 477 do FNTXOrder.FHead.Rest[i] := #0; *) FKeyParser := TVKDBFExprParser.Create(TVKDBFNTX(FIndexes.Owner), '', [], [poExtSyntax], '', nil, FieldMap); FKeyParser.IndexKeyValue := true; FForParser := TVKDBFExprParser.Create(TVKDBFNTX(FIndexes.Owner), '', [], [poExtSyntax], '', nil, FieldMap); FForParser.IndexKeyValue := true; FKeyTranslate := true; //FCl501Rus := false; FFileLock := false; FTemp := false; FForExists := false; FNTXRange := TVKNTXRange.Create; FNTXRange.NTX := self; FNTXBuffers := TVKNTXBuffers.Create; FNTXBuffers.NXTObject := self; FCreateIndexProc:= false; FReindex := false; FOnSubNtx := nil; FDestructor := false; FGetHashFromSortItem := False; end; destructor TVKNTXIndex.Destroy; begin FDestructor := true; if IsOpen then Close; FKeyParser.Free; FForParser.Free; FNTXRange.Free; FNTXBuffers.Free; FreeAndNil(FFLockObject); FreeAndNil(FFUnLockObject); if TIndexes(Collection).ActiveObject = self then TIndexes(Collection).ActiveObject := nil; inherited Destroy; end; function TVKNTXIndex.EvaluteForExpr: boolean; begin if Assigned(FOnEvaluteFor) then FOnEvaluteFor(self, Result) else Result := FForParser.Execute; end; function TVKNTXIndex.EvaluteKeyExpr: AnsiString; begin if Assigned(FOnEvaluteKey) then FOnEvaluteKey(self, Result) else Result := FKeyParser.EvaluteKey; end; function TVKNTXIndex.InternalFirst: TGetResult; var level: Integer; v: WORD; function Pass(page_off: DWORD): TGetResult; var page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; ntxb: TVKNTXNode; begin Inc(level); try ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[0]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result = grOK then Exit; end; if page.count <> 0 then begin // if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(FCurrentKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(FCurrentKey, item.key, FNTXOrder.FHead.key_size); FCurrentRec := item.rec_no; // Result := grOK; end else if level = 1 then Result := grEOF else Result := grError; Exit; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; finally Dec(level); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; level := 0; Result := Pass(FNTXOrder.FHead.root); end; procedure TVKNTXIndex.First; begin if InternalFirst = grOk then TVKDBFNTX(FIndexes.Owner).RecNo := FCurrentRec; end; function TVKNTXIndex.IsEqual(Value: TIndex): Boolean; var oNTX: TVKNTXIndex; begin oNTX := Value as TVKNTXIndex; Result := ( (FName = oNTX.Name) and (FNTXFileName = oNTX.NTXFileName) ); end; function TVKNTXIndex.IsOpen: boolean; begin Result := ((FNTXBag <> nil) and (FNTXBag.IsOpen)); end; function TVKNTXIndex.InternalLast: TGetResult; var level: Integer; v: WORD; function Pass(page_off: DWORD): TGetResult; var page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; ntxb: TVKNTXNode; begin Inc(level); try ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result = grOK then Exit; end; if page.count <> 0 then begin // item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(FCurrentKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(FCurrentKey, item.key, FNTXOrder.FHead.key_size); FCurrentRec := item.rec_no; // Result := grOK; end else if level = 1 then Result := grBOF else Result := grError; Exit; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; finally Dec(level); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; level := 0; Result := Pass(FNTXOrder.FHead.root); end; function TVKNTXIndex.InternalPrior: TGetResult; var Found: boolean; gr: TGetResult; v: WORD; procedure Pass(page_off: DWORD); var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; c: Integer; ntxb1, ntxb2: TVKNTXNode; procedure SetCurrentKey; begin if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(FCurrentKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(FCurrentKey, item.key, FNTXOrder.FHead.key_size); FCurrentRec := item.rec_no; end; begin ntxb1 := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(FCurrentKey)); if c <= 0 then begin if ( FCurrentRec = item.rec_no ) and ( c = 0 ) then begin Found := true; if ( item.page = 0 ) then begin if ( i <> 0 ) then begin gr := grOK; item := pNTX_ITEM(pAnsiChar(page) + page.ref[i - 1]); SetCurrentKey; end; end else begin ntxb2 := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, item.page, page); try if page.count > 0 then begin gr := grOK; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); SetCurrentKey; end else gr := grError; finally FNTXBuffers.FreeNTXBuffer(ntxb2.FNTXBuffer); end; end; Exit; end; if ( item.page <> 0 ) then Pass(item.page); if Found and (gr = grBOF) then begin if ( i <> 0 ) then begin gr := grOK; item := pNTX_ITEM(pAnsiChar(page) + page.ref[i - 1]); SetCurrentKey; end; Exit; end; if gr = grError then Exit; if gr = grOK then Exit; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); if Found and (gr = grBOF ) then begin if ( page.count <> 0 ) then begin gr := grOK; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); SetCurrentKey; end else gr := grError; end; finally FNTXBuffers.FreeNTXBuffer(ntxb1.FNTXBuffer); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; gr := grBOF; Found := false; Pass(FNTXOrder.FHead.root); Result := gr; end; function TVKNTXIndex.Open: boolean; var oW: TVKDBFNTX; begin FFileLock := False; oW := TVKDBFNTX(FIndexes.Owner); DefineBagAndOrder; FNTXBuffers.Clear; if not ((FNTXOrder.FHead.sign = 6) or (FNTXOrder.FHead.sign = 7)) then begin FNTXBag.Close; raise Exception.Create('TVKNTXIndex.Open: File "' + FNTXFileName + '" is not NTX file'); end; Result := IsOpen; if Result then begin //FKeyParser.SetExprParams1(FKeyExpresion, [], [poExtSyntax], ''); //FForParser.SetExprParams1(FForExpresion, [], [poExtSyntax], ''); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oW.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := FNTXBag.NTXHandler.Seek(0, 2); if ( ( ( oW.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oW.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; end; end; function TVKNTXIndex.InternalNext: TGetResult; var Found: Boolean; gr: TGetResult; v: WORD; procedure Pass(page_off: DWORD); var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; c: Integer; level: Integer; ntxb: TVKNTXNode; procedure SetCurrentKey; begin if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(FCurrentKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(FCurrentKey, item.key, FNTXOrder.FHead.key_size); FCurrentRec := item.rec_no; end; procedure GetFirstFromSubTree(page_off: DWORD); var ntxb: TVKNTXNode; begin Inc(level); try ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[0]); if ( item.page <> 0 ) then begin GetFirstFromSubTree(item.page); if gr = grOK then Exit; end; if page.count <> 0 then begin SetCurrentKey; gr := grOK; end else if level = 1 then gr := grEOF else gr := grError; Exit; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; finally Dec(level); end; end; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(FCurrentKey)); if c <= 0 then begin if ( FCurrentRec = item.rec_no ) and ( c = 0 ) then begin Found := true; // SetCurrentKey; item := pNTX_ITEM(pAnsiChar(page) + page.ref[i + 1]); if item.page <> 0 then begin level := 0; GetFirstFromSubTree(item.page); end else begin if ( ( i + 1 ) = page.count ) then begin gr := grEOF; end else begin gr := grOK; SetCurrentKey; end; end; // Exit; end; if ( item.page <> 0 ) then Pass(item.page); if (gr = grOK) then Exit; if Found and (gr = grEOF) then begin gr := grOK; SetCurrentKey; Exit; end; if gr = grError then Exit; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; Found := false; gr := grEOF; Pass(FNTXOrder.FHead.root); Result := gr; end; function TVKNTXIndex.Seek(Key: AnsiString; SoftSeek: boolean = false): boolean; var R: Integer; begin R := FindKey(Key, false, SoftSeek); if R <> 0 then begin (TVKDBFNTX(FIndexes.Owner)).RecNo := R; Result := True; end else Result := False; end; function TVKNTXIndex.SeekFirstInternal( Key: AnsiString; SoftSeek: boolean = false): boolean; var lResult, SoftSeekSet: boolean; procedure Pass(page_off: DWORD); var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; c: Integer; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin item := nil; for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(Key)); if c < 0 then begin //Key < item.key if ( item.page <> 0 ) then Pass(item.page); if (SoftSeek) and (not lResult) and (not SoftSeekSet) then begin FSeekRecord := item.rec_no; SetString(FSeekKey, item.key, FNTXOrder.FHead.key_size); SoftSeekSet := true; FSeekOk := true; end; Exit; end; if c = 0 then begin //Key = item.key if ( item.page <> 0 ) then Pass(item.page); if not lResult then begin FSeekRecord := item.rec_no; SetString(FSeekKey, item.key, FNTXOrder.FHead.key_size); FSeekOk := true; lResult := true; end; Exit; end; end; FSeekRecord := item.rec_no; SetString(FSeekKey, item.key, FNTXOrder.FHead.key_size); FSeekOk := true; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin FSeekOk := false; if FLock then try ClearIfChange; SoftSeekSet := false; lResult := false; Pass(FNTXOrder.FHead.root); Result := lResult; finally FUnLock; end else Result := false; end; function TVKNTXIndex.SeekFirst( Key: AnsiString; SoftSeek: boolean = false; PartialKey: boolean = false): boolean; var R: Integer; begin R := FindKey(Key, PartialKey, SoftSeek); if R <> 0 then begin (TVKDBFNTX(FIndexes.Owner)).RecNo := R; Result := True; end else Result := False; end; procedure TVKNTXIndex.SetKeyExpresion(Value: AnsiString); var oW: TVKDBFNTX; begin ChekExpression(Value); FKeyExpresion := Value; oW := TVKDBFNTX(FIndexes.Owner); if oW.IsCursorOpen then FKeyParser.SetExprParams1(FKeyExpresion, [], [poExtSyntax], ''); end; procedure TVKNTXIndex.SetForExpresion(Value: AnsiString); var oW: TVKDBFNTX; begin ChekExpression(Value); FForExpresion := Value; oW := TVKDBFNTX(FIndexes.Owner); if oW.IsCursorOpen then FForParser.SetExprParams1(FForExpresion, [], [poExtSyntax], ''); end; procedure TVKNTXIndex.SetNTXFileName(const Value: AnsiString); var PointPos: Integer; begin FNTXFileName := Value; FName := ExtractFileName(FNTXFileName); PointPos := Pos('.', FName); if PointPos <> 0 then FName := Copy(FName, 1, PointPos - 1); end; function TVKNTXIndex.SubIndex(LoKey, HiKey: AnsiString): boolean; var l, m: Integer; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; c: Integer; S: AnsiString; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(LoKey), m); if c <= 0 then begin //LoKey <= item.key if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; c := CmpKeys(item.key, pAnsiChar(HiKey), l); if c < 0 then begin // HiKey < item.key Result := true; Exit; end; if Assigned(OnSubIndex) then begin SetString(S, item.key, FNTXOrder.FHead.key_size); ExitCode := 0; OnSubIndex(self, S, item.rec_no, ExitCode); if ExitCode = 1 then begin Result := true; Exit; end; end; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if FLock then try ClearIfChange; m := Length(LoKey); if FNTXOrder.FHead.key_size < m then m := FNTXOrder.FHead.key_size; l := Length(HiKey); if FNTXOrder.FHead.key_size < l then l := FNTXOrder.FHead.key_size; Pass(FNTXOrder.FHead.root); Result := true; finally FUnLock; end else Result := false; end; function TVKNTXIndex.SubNtx(var SubNtxFile: AnsiString; LoKey, HiKey: AnsiString): boolean; var l, m: Integer; Accept: boolean; oSubIndex: TVKNTXCompactIndex; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; itm: NTX_ITEM; c: Integer; S: AnsiString; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(LoKey), m); if c <= 0 then begin //LoKey <= item.key if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; c := CmpKeys(item.key, pAnsiChar(HiKey), l); if c < 0 then begin // HiKey < item.key Result := true; Exit; end; Accept := true; if Assigned(OnSubNtx) then begin SetString(S, item.key, FNTXOrder.FHead.key_size); OnSubNtx(self, S, item.rec_no, Accept); end; if Accept then begin Move(item^, itm, FNTXOrder.FHead.item_size); oSubIndex.AddItem(@itm); end; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin oSubIndex := TVKNTXCompactIndex.Create(LimitPages.PagesPerBuffer); try oSubIndex.FileName := SubNtxFile; oSubIndex.OwnerTable := OwnerTable; oSubIndex.Crypt := TVKDBFNTX(OwnerTable).Crypt.Active; oSubIndex.CreateEmptyIndex(FNTXOrder.FHead); if oSubIndex.FHndl > 0 then try if FLock then try ClearIfChange; m := Length(LoKey); if FNTXOrder.FHead.key_size < m then m := FNTXOrder.FHead.key_size; l := Length(HiKey); if FNTXOrder.FHead.key_size < l then l := FNTXOrder.FHead.key_size; Pass(FNTXOrder.FHead.root); Result := true; finally FUnLock; end else Result := false; finally oSubIndex.Close; with FIndexes.Add as TVKNTXIndex do begin Temp := True; NTXFileName := SubNtxFile; Open; Active := true; TVKDBFNTX(FIndexes.Owner).First; end; end else Result := false; finally oSubIndex.Free; end; end; procedure TVKNTXIndex.Last; begin if InternalLast = grOk then TVKDBFNTX(FIndexes.Owner).RecNo := FCurrentRec; end; procedure TVKNTXIndex.Next; begin if InternalNext = grOk then TVKDBFNTX(FIndexes.Owner).RecNo := FCurrentRec; end; procedure TVKNTXIndex.Prior; begin if InternalPrior = grOk then TVKDBFNTX(FIndexes.Owner).RecNo := FCurrentRec; end; function TVKNTXIndex.GetRecordByIndex(GetMode: TGetMode; var cRec: Integer): TGetResult; begin Result := grOk; case GetMode of gmNext: begin if cRec <> - 1 then Result := InternalNext else Result := InternalFirst; end; gmPrior: begin if cRec <> TVKDBFNTX(FIndexes.Owner).RecordCount then Result := InternalPrior else Result := InternalLast; end; end; if Result = grOk then cRec := FCurrentRec; if Result = grBOF then cRec := -1; if Result = grEOF then cRec := TVKDBFNTX(FIndexes.Owner).RecordCount; if Result = grError then cRec := TVKDBFNTX(FIndexes.Owner).RecordCount; end; function TVKNTXIndex.GetFirstByIndex(var cRec: Integer): TGetResult; begin Result := InternalFirst; cRec := FCurrentRec; end; function TVKNTXIndex.GetLastByIndex(var cRec: Integer): TGetResult; begin Result := InternalLast; cRec := FCurrentRec; end; function TVKNTXIndex.SetToRecord: boolean; var TmpKey: AnsiString; begin Result := true; FCurrentKey := EvaluteKeyExpr; FCurrentRec := TVKDBFNTX(FIndexes.Owner).RecNo; if Unique or FForExists then begin SeekFirstInternal(FCurrentKey, true); if FSeekOk then begin TmpKey := TransKey(FSeekKey); if (FCurrentKey <> TmpKey) then begin FCurrentKey := TmpKey; FCurrentRec := FSeekRecord; end; end else Result := false; end; end; function TVKNTXIndex.NextBuffer(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): Longint; var lResult: Longint; Found: boolean; v: WORD; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; c: Integer; l: Integer; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(FCurrentKey)); if c <= 0 then begin //FCurrentKey <= item.key if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; // if Found then begin if NTXRange.Active then begin l := Length(NTXRange.HiKey); if l > 0 then begin c := CmpKeys(item.key, pAnsiChar(NTXRange.HiKey), l); if c < 0 then begin //NTXRange.HiKey < item.key Result := true; Exit; end; end; end; pLongint(pAnsiChar(FBufInd) + lResult * SizeOf(Longint))^ := item.rec_no; DBFHandler.Seek(data_offset + (item.rec_no - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read((FBuffer + lResult * FRecordSize)^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(item.rec_no, Pointer(FBuffer + lResult * FRecordSize), FRecordSize); Inc(lResult); end; // if lResult = FRecordsPerBuf then begin Result := true; Exit; end; if ( FCurrentRec = item.rec_no ) and ( c = 0 ) then Found := true; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; lResult := 0; Found := false; Pass(FNTXOrder.FHead.root); // if not Found then // beep; Result := lResult; end; function TVKNTXIndex.PriorBuffer(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf: Integer; FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): Longint; var lResult: Longint; bResult: boolean; Found: boolean; v: WORD; procedure Pass(page_off: DWORD); var k, i: Integer; page: pNTX_BUFFER; item: pNTX_ITEM; c: Integer; ntxb: TVKNTXNode; label a1; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try k := page.count; if not Found then begin if page.count > 0 then begin for i := 0 to page.count - 1 do begin k := i - 1; item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(FCurrentKey)); if c <= 0 then begin //FCurrentKey <= item.key if ( FCurrentRec = item.rec_no ) and ( c = 0 ) then Found := true; if ( item.page <> 0 ) then begin Pass(item.page); if bResult then Exit; end; if Found then goto a1; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Pass(item.page); if bResult then Exit; k := page.count - 1; if Found then goto a1; end; end; // a1: if Found then begin while k >= 0 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[k]); if k < page.count then begin if NTXRange.Active then begin c := CmpKeys(item.key, pAnsiChar(NTXRange.LoKey)); if c > 0 then begin //NTXRange.LoKey > item.key bResult := true; Exit; end; end; pLongint(pAnsiChar(FBufInd) + (FRecordsPerBuf - lResult - 1) * SizeOf(Longint))^ := item.rec_no; DBFHandler.Seek(data_offset + (item.rec_no - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read((FBuffer + (FRecordsPerBuf - lResult - 1) * FRecordSize)^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(item.rec_no, Pointer(FBuffer + (FRecordsPerBuf - lResult - 1) * FRecordSize), FRecordSize); Inc(lResult); if lResult = FRecordsPerBuf then begin bResult := true; Exit; end; end; if ( item.page <> 0 ) then begin Pass(item.page); if bResult then Exit; end; Dec(k); end; end; // finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; lResult := 0; bResult := false; Found := false; Pass(FNTXOrder.FHead.root); // if not Found then // beep; Result := lResult; end; function TVKNTXIndex.SetToRecord(Key: AnsiString; Rec: Integer): boolean; var TmpKey: AnsiString; begin Result := true; FCurrentKey := Key; FCurrentRec := Rec; if Unique or FForExists then begin SeekFirstInternal(FCurrentKey, true); if FSeekOk then begin TmpKey := TransKey(FSeekKey); if (FCurrentKey <> TmpKey) then begin FCurrentKey := TmpKey; FCurrentRec := FSeekRecord; end; end else Result := false; end; end; function TVKNTXIndex.GetCurrentKey: AnsiString; begin Result := FCurrentKey; end; function TVKNTXIndex.GetCurrentRec: DWORD; begin Result := FCurrentRec; end; function TVKNTXIndex.FillFirstBufRecords(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf, FRecordSize: Integer; FBufInd: pLongInt; data_offset: Word): longint; var lResult: longint; c, l: Integer; v: WORD; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; // pLongint(pAnsiChar(FBufInd) + lResult * SizeOf(Longint))^ := item.rec_no; DBFHandler.Seek(data_offset + (item.rec_no - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read((FBuffer + lResult * FRecordSize)^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(item.rec_no, Pointer(FBuffer + lResult * FRecordSize), FRecordSize); Inc(lResult); // if lResult = FRecordsPerBuf then begin Result := true; Exit; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Result := Pass(item.page) else Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if not NTXRange.Active then begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; lResult := 0; Pass(FNTXOrder.FHead.root); Result := lResult; end else begin SeekFirstInternal(NTXRange.LoKey, true); if FSeekOk then begin l := Length(NTXRange.LoKey); c := CmpKeys2(pAnsiChar(NTXRange.LoKey), pAnsiChar(FSeekKey), l); if c >= 0 then begin l := Length(NTXRange.HiKey); c := CmpKeys2(pAnsiChar(NTXRange.HiKey), pAnsiChar(FSeekKey), l); if (l > 0) and (c <= 0) then begin FCurrentKey := TransKey(FSeekKey); FCurrentRec := FSeekRecord; pLongint(FBufInd)^ := FSeekRecord; DBFHandler.Seek(data_offset + (DWORD(FSeekRecord) - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read(FBuffer^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(FSeekRecord, Pointer(FBuffer), FRecordSize); Result := 1 + NextBuffer(DBFHandler, FBuffer + FRecordSize, FRecordsPerBuf - 1, FRecordSize, pLongint(pAnsiChar(FBufInd) + SizeOf(Longint)), data_offset); end else Result := 0; end else Result := 0; end else Result := 0; end; end; function TVKNTXIndex.FillLastBufRecords(DBFHandler: TProxyStream; FBuffer: pAnsiChar; FRecordsPerBuf, FRecordSize: Integer; FBufInd: pLongint; data_offset: Word): longint; var lResult: longint; c, l: Integer; v: WORD; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; if page.count > 0 then begin for i := page.count - 1 downto 0 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); // pLongint(pAnsiChar(FBufInd) + (FRecordsPerBuf - lResult - 1) * SizeOf(Longint))^ := item.rec_no; DBFHandler.Seek(data_offset + (item.rec_no - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read((FBuffer + (FRecordsPerBuf - lResult - 1) * FRecordSize)^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(item.rec_no, Pointer(FBuffer + (FRecordsPerBuf - lResult - 1) * FRecordSize), FRecordSize); Inc(lResult); // if lResult = FRecordsPerBuf then begin Result := true; Exit; end; if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; end; end; Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin if (not NTXRange.Active) or (NTXRange.LoKey = '') then begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; lResult := 0; Pass(FNTXOrder.FHead.root); Result := lResult; end else begin SeekLastInternal(NTXRange.HiKey, true); if FSeekOk then begin l := Length(NTXRange.LoKey); c := CmpKeys2(pAnsiChar(NTXRange.LoKey), pAnsiChar(FSeekKey), l); if c >= 0 then begin l := Length(NTXRange.HiKey); c := CmpKeys2(pAnsiChar(NTXRange.HiKey), pAnsiChar(FSeekKey), l); if (l > 0) and (c <= 0) then begin FCurrentKey := TransKey(FSeekKey); FCurrentRec := FSeekRecord; pLongint(pAnsiChar(FBufInd) + (FRecordsPerBuf - 1) * SizeOf(Longint))^ := FCurrentRec; DBFHandler.Seek(data_offset + (FCurrentRec - 1) * DWORD(FRecordSize), soFromBeginning); DBFHandler.Read((FBuffer + (FRecordsPerBuf - 1) * FRecordSize)^, FRecordSize); if TVKDBFNTX(OwnerTable).Crypt.Active then TVKDBFNTX(OwnerTable).Crypt.Decrypt(FCurrentRec, Pointer(FBuffer + (FRecordsPerBuf - 1) * FRecordSize), FRecordSize); Result := 1 + PriorBuffer(DBFHandler, FBuffer, FRecordsPerBuf - 1, FRecordSize, FBufInd, data_offset); end else Result := 0; end else Result := 0; end else Result := 0; end; end; function TVKNTXIndex.SetToRecord(Rec: Integer): boolean; var TmpKey: AnsiString; begin Result := true; FCurrentKey := EvaluteKeyExpr; FCurrentRec := Rec; if Unique or FForExists then begin SeekFirstInternal(FCurrentKey, true); if FSeekOk then begin TmpKey := TransKey(FSeekKey); if (FCurrentKey <> FSeekKey) then begin FCurrentKey := TmpKey; FCurrentRec := FSeekRecord; end; end else Result := false; end; end; (* function TVKNTXIndex.FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer; var i: Integer; l: boolean; Ok: boolean; oW: TVKDBFNTX; begin i := 0; oW := TVKDBFNTX(FIndexes.Owner); l := (( (oW.AccessMode.FLast and fmShareExclusive) = fmShareExclusive ) or ( (oW.AccessMode.FLast and fmShareDenyWrite) = fmShareDenyWrite )); repeat Result := SysUtils.FileWrite(Handle, Buffer, Count); Ok := (Result <> -1); if not Ok then begin if l then Ok := true else begin Wait(0.001, false); Inc(i); if i = oW.WaitBusyRes then Ok := true; end; end; until Ok; end; *) (* function TVKNTXIndex.FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer; var i: Integer; l: boolean; Ok: boolean; oW: TVKDBFNTX; begin i := 0; oW := TVKDBFNTX(FIndexes.Owner); l := (( (oW.AccessMode.FLast and fmShareExclusive) = fmShareExclusive ) or ( (oW.AccessMode.FLast and fmShareDenyWrite) = fmShareDenyWrite )); repeat Result := SysUtils.FileRead(Handle, Buffer, Count); Ok := (Result <> -1); if not Ok then begin if l then Ok := true else begin Wait(0.001, false); Inc(i); if i = oW.WaitBusyRes then Ok := true; end; end; until Ok; end; *) function TVKNTXIndex.CompareKeys(S1, S2: PAnsiChar; MaxLen: Cardinal): Integer; var i: Integer; T1: array [0..NTX_PAGE] of AnsiChar; T2: array [0..NTX_PAGE] of AnsiChar; begin //S1 - CurrentKey //S2 - Item Key if Assigned(OnCompareKeys) then begin OnCompareKeys(self, S1, S2, MaxLen, Result); end else begin if CollationType <> cltNone then begin Result := 0; //DONE: make it throws TVKNTXIndex.TransKey //CharToOem(pChar(S1), T1); //CharToOem(pAnsiChar(S2), T2); TVKDBFNTX(FIndexes.Owner).Translate(S1, pAnsiChar(@T1[0]), True); TVKDBFNTX(FIndexes.Owner).Translate(S2, pAnsiChar(@T2[0]), True); //end TODO for i := 0 to MaxLen - 1 do begin Result := CollatingTable[Ord(T1[i])] - CollatingTable[Ord(T2[i])]; if Result <> 0 then Exit; end; end else begin //Result := AnsiStrLComp(S1, S2, MaxLen); - in Win95-98 not currect Result := {$IFDEF DELPHIXE4}AnsiStrings.{$ENDIF}StrLComp(S1, S2, MaxLen); end; end; end; function TVKNTXIndex.GetFreePage: DWORD; var page: pNTX_BUFFER; i: Integer; Ind: TVKNTXNode; item_off: WORD; begin if FNTXOrder.FHead.next_page <> 0 then begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, FNTXOrder.FHead.next_page, page); page.count := 0; Result := FNTXOrder.FHead.next_page; FNTXOrder.FHead.next_page := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).page; pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).page := 0; Ind.Changed := true; FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end else begin Result := FLastOffset; Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, Result, page, false); page.count := 0; item_off := ( FNTXOrder.FHead.max_item * 2 ) + 4; for i := 0 to FNTXOrder.FHead.max_item do begin page.ref[i] := item_off; item_off := item_off + FNTXOrder.FHead.item_size; end; pNTX_ITEM(pAnsiChar(page) + page.ref[0]).page := 0; Inc(FLastOffset, SizeOf(NTX_BUFFER)); Ind.Changed := true; FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; function TVKNTXIndex.AddItem(ntxItem: pNTX_ITEM; AddItemAtEnd: boolean = False): boolean; var NewPage: pNTX_BUFFER; _NewPageOff, NewPageOff: DWORD; ItemHasBeenAdded: boolean; rf: WORD; Ind: TVKNTXNode; procedure AddItemInternal(page_off: DWORD; ParentNode: TVKNTXNode = nil; ParentItem: pNTX_ITEM = nil; ParentItemNo: Word = Word(-1)); var i, j, beg, Mid, k, l: Integer; page, SiblingNodePage: pNTX_BUFFER; item, SiblingItem, i1, i2: pNTX_ITEM; c: Integer; Ind, Ind1, SiblingNode: TVKNTXNode; BreakItem: Word; procedure InsItem(page: pNTX_BUFFER); begin j := page.count; while j >= i do begin rf := page.ref[j + 1]; page.ref[j + 1] := page.ref[j]; page.ref[j] := rf; Dec(j); end; page.count := page.count + 1; Move(ntxItem.key, pNTX_ITEM(pAnsiChar(page) + page.ref[i]).key, FNTXOrder.FHead.key_size); pNTX_ITEM(pAnsiChar(page) + page.ref[i]).rec_no := ntxItem.rec_no; pNTX_ITEM(pAnsiChar(page) + page.ref[i]).page := ntxItem.page; if ( ntxItem.page <> 0 ) then begin pNTX_ITEM(pAnsiChar(page) + page.ref[i + 1]).page := NewPageOff; NewPageOff := 0; end; end; procedure CmpRec; begin if c = 0 then begin if item.rec_no < ntxItem.rec_no then c := 1 else c := -1; end; end; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try i := page.count; if not AddItemAtEnd then begin if ( i > 0 ) then begin beg := 0; item := pNTX_ITEM(pAnsiChar(page) + page.ref[beg]); c := CmpKeys1(item.key, pAnsiChar(@ntxItem^.key[0])); CmpRec; if ( c > 0 ) then begin repeat Mid := ( i + beg ) shr 1; item := pNTX_ITEM(pAnsiChar(page) + page.ref[Mid]); c := CmpKeys1(item.key, pAnsiChar(@ntxItem^.key[0])); CmpRec; if ( c > 0 ) then beg := Mid else i := Mid; until ( ((i-beg) div 2) = 0 ); end else i := beg; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); if ( item.page <> 0 ) then AddItemInternal(item.page, Ind, item, i); if not ItemHasBeenAdded then begin // If Item add at end and node is full then try carry half node to left sibling node if AddItemAtEnd and ( page.count = FNTXOrder.FHead.max_item ) then begin if ( ParentNode <> nil ) and ( ParentItem <> nil ) and ( ParentItemNo <> Word(-1) ) and ( ParentItemNo > 0 ) then begin SiblingItem := pNTX_ITEM(pAnsiChar(ParentNode.pNode) + ParentNode.PNode.ref[Pred(ParentItemNo)]); SiblingNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, SiblingItem.page, SiblingNodePage); try l := 0; for k := SiblingNodePage.count to Pred(FNTXOrder.FHead.max_item) do begin i1 := pNTX_ITEM(pAnsiChar(SiblingNode.pNode) + SiblingNode.PNode.ref[k]); i2 := pNTX_ITEM(pAnsiChar(Ind.pNode) + Ind.PNode.ref[l]); i1.rec_no := SiblingItem.rec_no; Move(SiblingItem.key, i1.key, FNTXOrder.FHead.key_size); i1 := pNTX_ITEM(pAnsiChar(SiblingNode.pNode) + SiblingNode.PNode.ref[Succ(k)]); i1.page := i2.page; i2.page := 0; SiblingItem.rec_no := i2.rec_no; Move(i2.key, SiblingItem.key, FNTXOrder.FHead.key_size); Inc(l); end; if l > 0 then begin Inc(SiblingNodePage.count, l); //Shift cuttent page for k := l to page.count do begin rf := page.ref[k - l]; page.ref[k - l] := page.ref[k]; page.ref[k] := rf; end; Dec(page.count, l); Ind.Changed := true; SiblingNode.Changed := true; ParentNode.Changed := true; Dec(i, l); end; finally FNTXBuffers.FreeNTXBuffer(SiblingNode.FNTXBuffer); end; end; end; if (page.count = FNTXOrder.FHead.max_item) then begin _NewPageOff := GetFreePage; Ind1 := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, _NewPageOff, NewPage); try BreakItem := FNTXOrder.FHead.half_page; Move(page^, NewPage^, SizeOf(NTX_BUFFER)); page.count := BreakItem; for j := BreakItem to NewPage.count do begin rf := NewPage.ref[j - BreakItem]; NewPage.ref[j - BreakItem] := NewPage.ref[j]; NewPage.ref[j] := rf; end; NewPage.count := NewPage.count - BreakItem; if i < BreakItem then begin InsItem(page); end else begin i := i - BreakItem; InsItem(NewPage); end; NewPageOff := _NewPageOff; if page.count >= NewPage.count then begin page.count := page.count - 1; Move(pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).key, ntxItem.key, FNTXOrder.FHead.key_size); ntxItem.rec_no := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).rec_no; end else begin Move(pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[0]).key, ntxItem.key, FNTXOrder.FHead.key_size); ntxItem.rec_no := pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[0]).rec_no; for j := 0 to NewPage.count - 1 do begin rf := NewPage.ref[j]; NewPage.ref[j] := NewPage.ref[j + 1]; NewPage.ref[j + 1] := rf; end; NewPage.count := NewPage.count - 1; end; ntxItem.page := page_off; Ind.Changed := true; Ind1.Changed := true; finally FNTXBuffers.FreeNTXBuffer(Ind1.FNTXBuffer); end; ItemHasBeenAdded := false; end else begin InsItem(page); Ind.Changed := true; ItemHasBeenAdded := true; end; end; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; begin NewPageOff := 0; ItemHasBeenAdded := false; AddItemInternal(FNTXOrder.FHead.root, nil, nil, Word(-1)); if not ItemHasBeenAdded then begin _NewPageOff := GetFreePage; Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, _NewPageOff, NewPage); try NewPage.count := 1; Move(ntxItem.key, pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[0]).key, FNTXOrder.FHead.key_size); pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[0]).rec_no := ntxItem.rec_no; pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[0]).page := ntxItem.page; pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[1]).page := NewPageOff; FNTXOrder.FHead.root := _NewPageOff; Ind.Changed := True; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; ItemHasBeenAdded := true; end; Result := ItemHasBeenAdded; end; procedure TVKNTXIndex.AddKey(sKey: AnsiString; nRec: Integer); var item: NTX_ITEM; AddOk: boolean; begin AddOk := true; if Unique then AddOk := AddOk and (not SeekFirstInternal(sKey)); if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin item.page := 0; item.rec_no := nRec; Move(pAnsiChar(sKey)^, item.key, FNTXOrder.FHead.key_size); TransKey(item.key); AddItem(@item); end; end; procedure TVKNTXIndex.DeleteKey(sKey: AnsiString; nRec: Integer); var TempItem: NTX_ITEM; LastItem: NTX_ITEM; FLastKey: AnsiString; FLastRec: DWORD; rf: WORD; procedure AddInEndItem(page_off: DWORD; itemKey: pAnsiChar; itemRec: DWORD); var page: pNTX_BUFFER; NewPage: pNTX_BUFFER; item: pNTX_ITEM; NewPageOff: DWORD; i: DWORD; Ind, Ind1: TVKNTXNode; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then AddInEndItem(item.page, itemKey, itemRec) else begin if page.count < FNTXOrder.FHead.max_item then begin Move(itemKey^, pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).key, FNTXOrder.FHead.key_size); pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).rec_no := itemRec; pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).page := 0; page.count := page.count + 1; pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]).page := 0; Ind.Changed := true; end else begin NewPageOff := GetFreePage; Ind1 := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, NewPageOff, NewPage); try Move(page^, NewPage^, SizeOf(NTX_BUFFER)); page.count := FNTXOrder.FHead.half_page; pNTX_ITEM(pAnsiChar(page) + page.ref[FNTXOrder.FHead.half_page]).page := NewPageOff; Ind.Changed := true; for i := FNTXOrder.FHead.half_page to NewPage.count do begin rf := NewPage.ref[i - FNTXOrder.FHead.half_page]; NewPage.ref[i - FNTXOrder.FHead.half_page] := NewPage.ref[i]; NewPage.ref[i] := rf; end; NewPage.count := NewPage.count - FNTXOrder.FHead.half_page; Move(itemKey^, pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[NewPage.count]).key, FNTXOrder.FHead.key_size); pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[NewPage.count]).rec_no := itemRec; pNTX_ITEM(pAnsiChar(NewPage) + NewPage.ref[NewPage.count]).page := 0; NewPage.count := NewPage.count + 1; Ind1.Changed := true; finally FNTXBuffers.FreeNTXBuffer(Ind1.FNTXBuffer); end; end; end; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; procedure DeletePage(page_off: DWORD); var page: pNTX_BUFFER; Ind: TVKNTXNode; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); page.count := 0; pNTX_ITEM(pAnsiChar(page) + page.ref[0]).page := FNTXOrder.FHead.next_page; Ind.Changed := true; FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); FNTXOrder.FHead.next_page := page_off; end; procedure GetLastItemOld(page_off: DWORD; PrePage: pNTX_BUFFER; PrePageOffset: DWORD; PreItemRef: WORD); var page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; Ind: TVKNTXNode; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then GetLastItemOld(item.page, page, page_off, page.count) else begin // item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(FLastKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(FLastKey, item.key, FNTXOrder.FHead.key_size); FLastRec := item.rec_no; // page.count := page.count - 1; Ind.Changed := true; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( page.count = 0 ) and ( item.page = 0 ) then begin DeletePage(page_off); pNTX_ITEM(pAnsiChar(PrePage) + NTX_BUFFER(PrePage^).ref[PreItemRef])^.page := 0; FNTXBuffers.SetPageChanged(FNTXBag.NTXHandler, PrePageOffset); end; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; function Pass(page_off: DWORD; LastItemRef: WORD; LastPage: pNTX_BUFFER; LastPageOffset: DWORD): boolean; var i, j: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; item1: pNTX_ITEM; c: Integer; Ind: TVKNTXNode; function DelPage: boolean; begin Result := false; if page.count = 0 then begin item1 := pNTX_ITEM(pAnsiChar(page) + page.ref[0]); if ( item1.page = 0 ) then begin if LastPage <> nil then begin pNTX_ITEM(pAnsiChar(LastPage) + NTX_BUFFER(LastPage^).ref[LastItemRef])^.page := 0; DeletePage(page_off); FNTXBuffers.SetPageChanged(FNTXBag.NTXHandler, LastPageOffset); Result := true; end; end; end; end; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(sKey)); if c <= 0 then begin //sKey <= item.key if ( item.page <> 0 ) then begin Result := Pass(item.page, i, page, page_off); DelPage; if Result then Exit; end; if ( DWORD(nRec) = item.rec_no ) and ( c = 0 ) then begin if ( item.page = 0 ) then begin j := i; while j < page.count do begin rf := page.ref[j]; page.ref[j] := page.ref[j + 1]; page.ref[j + 1] := rf; Inc(j); end; if page.count > 0 then begin page.count := page.count - 1; Ind.Changed := true; end; DelPage; Result := true; end else begin GetLastItemOld(item.page, page, page_off, i); Move(pAnsiChar(FLastKey)^, pNTX_ITEM(pAnsiChar(page) + page.ref[i]).key, FNTXOrder.FHead.key_size); pNTX_ITEM(pAnsiChar(page) + page.ref[i]).rec_no := FLastRec; Ind.Changed := true; Result := true; end; Exit; end; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page, page.count, page, page_off); DelPage; if Result then Exit; end; Result := false; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; procedure GetLastItem(page_off: DWORD); var page: pNTX_BUFFER; item: pNTX_ITEM; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then GetLastItem(item.page) else begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); Move(item^, LastItem, FNTXOrder.FHead.item_size); end; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; function PassForDel(page_off: DWORD; ItemForDelete: pNTX_ITEM; Parent: TVKNTXNode; ParentItemRef: WORD): boolean; var i, j: DWORD; item: pNTX_ITEM; page: pNTX_BUFFER; Ind: TVKNTXNode; c: Integer; procedure DelItemi; var rf: WORD; begin j := i; while j < page.count do begin rf := page.ref[j]; page.ref[j] := page.ref[j + 1]; page.ref[j + 1] := rf; Inc(j); end; page.count := page.count - 1; end; procedure NormalizePage(CurrPage, Parent: TVKNTXNode; ParentItemRef: WORD); var LeftSibling, RightSibling: TVKNTXNode; LeftPage, RightPage: pNTX_BUFFER; TryRight: boolean; SLItem, LItem, CItem, RItem, Item, SRItem: pNTX_ITEM; Shift, j: Integer; rf: WORD; LstPage: DWORD; begin if Parent <> nil then begin if CurrPage.PNode.count < FNTXOrder.FHead.half_page then begin TryRight := false; if ParentItemRef > 0 then begin LItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[ParentItemRef - 1]); if LItem.page <> 0 then begin LeftSibling := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, LItem.page, LeftPage); if LeftPage.count > FNTXOrder.FHead.half_page then begin SLItem := pNTX_ITEM( pAnsiChar(LeftPage) + LeftPage.ref[LeftPage.count]); rf := LeftPage.count - FNTXOrder.FHead.half_page; Shift := (rf div 2) + (rf mod 2); LeftPage.count := LeftPage.count - Shift; j := CurrPage.PNode.count; while j >= 0 do begin rf := CurrPage.PNode.ref[j + Shift]; CurrPage.PNode.ref[j + Shift] := CurrPage.PNode.ref[j]; CurrPage.PNode.ref[j] := rf; Dec(j); end; Inc(CurrPage.PNode.count, Shift); CItem := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[Shift - 1]); Move(LItem.key, CItem.key, FNTXOrder.FHead.key_size); CItem.rec_no := LItem.rec_no; CItem.page := SLItem.page; Dec(Shift); while Shift > 0 do begin SLItem := pNTX_ITEM( pAnsiChar(LeftPage) + LeftPage.ref[LeftPage.count + Shift]); CItem := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[Shift - 1]); Move(SLItem.key, CItem.key, FNTXOrder.FHead.key_size); CItem.rec_no := SLItem.rec_no; CItem.page := SLItem.page; Dec(Shift); end; SLItem := pNTX_ITEM( pAnsiChar(LeftPage) + LeftPage.ref[LeftPage.count]); Move(SLItem.key, LItem.key, FNTXOrder.FHead.key_size); LItem.rec_no := SLItem.rec_no; end else begin CItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[ParentItemRef]); Item := pNTX_ITEM( pAnsiChar(LeftPage) + LeftPage.ref[LeftPage.count]); Move(LItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := LItem.rec_no; Inc(LeftPage.count); CItem.page := LItem.page; for j := ParentItemRef - 1 to Parent.PNode.count - 1 do begin rf := Parent.PNode.ref[j]; Parent.PNode.ref[j] := Parent.PNode.ref[j + 1]; Parent.PNode.ref[j + 1] := rf; end; Dec(Parent.PNode.count); for j := 0 to CurrPage.PNode.count do begin CItem := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[j]); Item := pNTX_ITEM( pAnsiChar(LeftPage) + LeftPage.ref[LeftPage.count]); Move(CItem^, Item^, FNTXOrder.FHead.item_size); Inc(LeftPage.count); end; Dec(LeftPage.count); //Delete page CurrPage.PNode.count := 0; CItem := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[0]); CItem.page := FNTXOrder.FHead.next_page; FNTXOrder.FHead.next_page := CurrPage.NodeOffset; if Parent.PNode.count = 0 then begin //Delete Parent CItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[0]); FNTXOrder.FHead.root := CItem.page; CItem.page := FNTXOrder.FHead.next_page; FNTXOrder.FHead.next_page := Parent.NodeOffset; end; end; LeftSibling.Changed := true; FNTXBuffers.FreeNTXBuffer(LeftSibling.FNTXBuffer); CurrPage.Changed := true; Parent.Changed := true; end else TryRight := true; end else TryRight := true; if TryRight then begin if ParentItemRef < Parent.PNode.count then begin RItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[ParentItemRef + 1]); if RItem.page <> 0 then begin RightSibling := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, RItem.page, RightPage); if RightPage.count > FNTXOrder.FHead.half_page then begin rf := RightPage.count - FNTXOrder.FHead.half_page; Shift := (rf div 2) + (rf mod 2); CItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[ParentItemRef]); Item := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[CurrPage.PNode.count]); Move(CItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := CItem.rec_no; Inc(CurrPage.PNode.count); Item := pNTX_ITEM( pAnsiChar(RightSibling.PNode) + RightSibling.PNode.ref[Shift - 1]); Move(Item.key, CItem.key, FNTXOrder.FHead.key_size); CItem.rec_no := Item.rec_no; LstPage := Item.page; for j := 0 to Shift - 2 do begin SRItem := pNTX_ITEM( pAnsiChar(RightSibling.PNode) + RightSibling.PNode.ref[j]); Item := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[CurrPage.PNode.count]); Move(SRItem^, Item^, FNTXOrder.FHead.item_size); Inc(CurrPage.PNode.count); end; Item := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[CurrPage.PNode.count]); Item.page := LstPage; Dec(RightSibling.PNode.count, Shift); for j := 0 to RightSibling.PNode.count do begin rf := RightSibling.PNode.ref[j]; RightSibling.PNode.ref[j] := RightSibling.PNode.ref[j + Shift]; RightSibling.PNode.ref[j + Shift] := rf; end; end else begin CItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[ParentItemRef]); Item := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[CurrPage.PNode.count]); Move(CItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := CItem.rec_no; Inc(CurrPage.PNode.count); RItem.page := CItem.page; for j := ParentItemRef to Parent.PNode.count - 1 do begin rf := Parent.PNode.ref[j]; Parent.PNode.ref[j] := Parent.PNode.ref[j + 1]; Parent.PNode.ref[j + 1] := rf; end; Dec(Parent.PNode.count); for j := 0 to RightSibling.PNode.count do begin SRItem := pNTX_ITEM( pAnsiChar(RightSibling.PNode) + RightSibling.PNode.ref[j]); Item := pNTX_ITEM( pAnsiChar(CurrPage.PNode) + CurrPage.PNode.ref[CurrPage.PNode.count]); Move(SRItem^, Item^, FNTXOrder.FHead.item_size); Inc(CurrPage.PNode.count); end; Dec(CurrPage.PNode.count); //Delete page RightSibling.PNode.count := 0; CItem := pNTX_ITEM( pAnsiChar(RightSibling.PNode) + RightSibling.PNode.ref[0]); CItem.page := FNTXOrder.FHead.next_page; FNTXOrder.FHead.next_page := RightSibling.NodeOffset; if Parent.PNode.count = 0 then begin //Delete Parent CItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[0]); FNTXOrder.FHead.root := CItem.page; CItem.page := FNTXOrder.FHead.next_page; FNTXOrder.FHead.next_page := Parent.NodeOffset; end; end; RightSibling.Changed := true; FNTXBuffers.FreeNTXBuffer(RightSibling.FNTXBuffer); CurrPage.Changed := true; Parent.Changed := true; end; end; end; end; end; end; begin Ind := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys1(item.key, ItemForDelete.key); if c <= 0 then begin //ItemForDelete.key <= item.key if ( item.page <> 0 ) then begin Result := PassForDel(item.page, ItemForDelete, Ind, i); NormalizePage(Ind, Parent, ParentItemRef); if Result then Exit; end; if ( ItemForDelete.rec_no = item.rec_no ) and ( c = 0 ) then begin if ( item.page = 0 ) then begin DelItemi; Ind.Changed := true; end else begin GetLastItem(item.page); Move(LastItem.key, item.key, FNTXOrder.FHead.key_size); item.rec_no := LastItem.rec_no; Ind.Changed := true; PassForDel(item.page, @LastItem, Ind, i); end; NormalizePage(Ind, Parent, ParentItemRef); Result := true; Exit; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := PassForDel(item.page, ItemForDelete, Ind, page.count); NormalizePage(Ind, Parent, ParentItemRef); if Result then Exit; end; Result := false; finally FNTXBuffers.FreeNTXBuffer(Ind.FNTXBuffer); end; end; begin if FDeleteKeyStyle = dksClipper then begin TempItem.page := 0; TempItem.rec_no := nRec; Move(pAnsiChar(sKey)^, TempItem.key, FNTXOrder.FHead.key_size); TransKey(TempItem.key); PassForDel(FNTXOrder.FHead.root, @TempItem, nil, 0); end else Pass(FNTXOrder.FHead.root, 0, nil, 0); end; function TVKNTXIndex.LastKey(out LastKey: AnsiString; out LastRec: Integer): boolean; var level: Integer; function Pass(page_off: DWORD): TGetResult; var page: pNTX_BUFFER; item: pNTX_ITEM; Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; ntxb: TVKNTXNode; begin Inc(level); try ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result = grOK then Exit; end; if page.count <> 0 then begin // item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count - 1]); if FKeyTranslate then begin Move(item.key, Srckey, FNTXOrder.FHead.key_size); Srckey[FNTXOrder.FHead.key_size] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); SetString(LastKey, Destkey, FNTXOrder.FHead.key_size); end else SetString(LastKey, item.key, FNTXOrder.FHead.key_size); LastRec := item.rec_no; // Result := grOK; end else if level = 1 then Result := grBOF else Result := grError; Exit; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; finally Dec(level); end; end; begin if FLock then try ClearIfChange; level := 0; Result := (Pass(FNTXOrder.FHead.root) = grOK); finally FUnLock; end else Result := false; end; function TVKNTXIndex.FLock: boolean; var i: Integer; l: boolean; oW: TVKDBFNTX; begin FFLockObject.Enter; try if not FFileLock then begin i := 0; oW := TVKDBFNTX(FIndexes.Owner); l := ( ( (oW.AccessMode.FLast and fmShareExclusive) = fmShareExclusive ) or ( (oW.AccessMode.FLast and fmShareDenyWrite) = fmShareDenyWrite ) or FFileLock ); repeat if not l then begin Result := False; case oW.LockProtocol of lpNone : Result := True; lpDB4Lock : Result := FNTXBag.NTXHandler.Lock(DB4_LockMax, 1); lpClipperLock : Result := FNTXBag.NTXHandler.Lock(CLIPPER_LockMax, 1); lpFoxLock : Result := FNTXBag.NTXHandler.Lock(FOX_LockMax, 1); lpClipperForFoxLob: Result := FNTXBag.NTXHandler.Lock(CLIPPER_FOR_FOX_LOB_LockMax, 1); end; if not Result then begin Wait(0.001, false); Inc(i); if i >= oW.WaitBusyRes then begin FFileLock := Result; Exit; end; end; end else Result := true; until Result; FFileLock := Result; end else Result := true; finally FFLockObject.Release; end; end; function TVKNTXIndex.FUnLock: boolean; var l: boolean; oW: TVKDBFNTX; begin FFUnLockObject.Enter; try oW := TVKDBFNTX(FIndexes.Owner); l := ( ( (oW.AccessMode.FLast and fmShareExclusive) = fmShareExclusive ) or ( (oW.AccessMode.FLast and fmShareDenyWrite) = fmShareDenyWrite ) ); if not l then begin Result := False; case oW.LockProtocol of lpNone : Result := True; lpDB4Lock : Result := FNTXBag.NTXHandler.UnLock(DB4_LockMax, 1); lpClipperLock : Result := FNTXBag.NTXHandler.UnLock(CLIPPER_LockMax, 1); lpFoxLock : Result := FNTXBag.NTXHandler.UnLock(FOX_LockMax, 1); lpClipperForFoxLob: Result := FNTXBag.NTXHandler.UnLock(CLIPPER_FOR_FOX_LOB_LockMax, 1); end; end else Result := true; FFileLock := not Result; finally FFUnLockObject.Release; end; end; procedure TVKNTXIndex.SetUnique(const Value: boolean); begin if IsOpen then begin if Value then FNTXOrder.FHead.unique := #1 else FNTXOrder.FHead.unique := #0; end else FUnique := Value; end; function TVKNTXIndex.GetUnique: boolean; begin if IsOpen then Result := (FNTXOrder.FHead.unique <> #0) else Result := FUnique; end; procedure TVKNTXIndex.SetDesc(const Value: boolean); begin if IsOpen then begin if Value then FNTXOrder.FHead.Desc := #1 else FNTXOrder.FHead.Desc := #0; end else FDesc := Value; end; function TVKNTXIndex.GetDesc: boolean; begin if IsOpen then Result := (FNTXOrder.FHead.Desc <> #0) else Result := FDesc; end; function TVKNTXIndex.GetOrder: AnsiString; var i: Integer; p: pAnsiChar; begin if IsOpen then begin for i := 0 to 7 do if FNTXOrder.FHead.order[i] = #0 then break; p := pAnsiChar(@FNTXOrder.FHead.order[0]); SetString(Result, p, i); ChekExpression(Result); if Result = '' then Result := Name; end else Result := FOrder; end; procedure TVKNTXIndex.SetOrder(Value: AnsiString); var i, j: Integer; begin if IsOpen then begin ChekExpression(Value); j := Length(Value); if j > 8 then j := 8; for i := 0 to j - 1 do FNTXOrder.FHead.order[i] := Value[i + 1]; FNTXOrder.FHead.order[j] := #0; Name := FNTXOrder.FHead.order; end else FOrder := Value; end; procedure TVKNTXIndex.ChekExpression(var Value: AnsiString); var i, j: Integer; begin j := Length(Value); for i := 1 to j do if Value[i] < #32 then begin Value := ''; Exit; end; end; function TVKNTXIndex.CmpKeys1(ItemKey, CurrKey: pAnsiChar; KSize: Integer): Integer; var Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey1, Destkey2: array[0..NTX_PAGE-1] of AnsiChar; begin if KSize = 0 then KSize := FNTXOrder.FHead.key_size; if FKeyTranslate then begin Move(ItemKey^, Srckey, KSize); Srckey[KSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey1, false); Move(CurrKey^, Srckey, KSize); Srckey[KSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey2, false); Result := CompareKeys(Destkey2, Destkey1, KSize); end else Result := CompareKeys(CurrKey, ItemKey, KSize); if Desc then Result := - Result; end; function TVKNTXIndex.CmpKeys2(ItemKey, CurrKey: pAnsiChar; KSize: Integer): Integer; var Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey1, Destkey2: array[0..NTX_PAGE-1] of AnsiChar; begin if KSize = 0 then KSize := FNTXOrder.FHead.key_size; if FKeyTranslate then begin Move(ItemKey^, Destkey1, KSize); //Move(ItemKey^, Srckey, KSize); //Srckey[KSize] := #0; //TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey1, false); Move(CurrKey^, Srckey, KSize); Srckey[KSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey2, false); Result := CompareKeys(Destkey2, Destkey1, KSize); end else Result := CompareKeys(CurrKey, ItemKey, KSize); if Desc then Result := - Result; end; function TVKNTXIndex.CmpKeys(ItemKey, CurrKey: pAnsiChar; KSize: Integer = 0): Integer; var Srckey: array[0..NTX_PAGE-1] of AnsiChar; Destkey: array[0..NTX_PAGE-1] of AnsiChar; begin if KSize = 0 then KSize := FNTXOrder.FHead.key_size; if FKeyTranslate then begin Move(ItemKey^, Srckey, KSize); Srckey[KSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Destkey, false); Result := CompareKeys(CurrKey, Destkey, KSize); end else Result := CompareKeys(CurrKey, ItemKey, KSize); if Desc then Result := - Result; end; function TVKNTXIndex.CmpKeys3(ItemKey, CurrKey: pAnsiChar; KSize: Integer): Integer; begin if KSize = 0 then KSize := FNTXOrder.FHead.key_size; Result := CompareKeys(CurrKey, ItemKey, KSize); if Desc then Result := - Result; end; procedure TVKNTXIndex.TransKey(Key: pAnsiChar; KSize: Integer = 0; ToOem: Boolean = true); var Srckey: array[0..NTX_PAGE-1] of AnsiChar; begin if KSize = 0 then KSize := FNTXOrder.FHead.key_size; if FKeyTranslate then begin Move(Key^, Srckey, KSize); Srckey[KSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(Srckey, Key, ToOem); end; end; procedure TVKNTXIndex.TransKey(var SItem: SORT_ITEM); begin if TVKDBFNTX(FIndexes.Owner).OEM and ( CollationType <> cltNone ) then begin TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(@SItem.key[0]), pAnsiChar(@SItem.key[0]), True, FNTXOrder.FHead.key_size); end; end; procedure TVKNTXIndex.CreateIndex(Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; Sorter: TVKSorterAbstract; SorterRecCount: DWord; sitem: SORT_ITEM; ntxitem: NTX_ITEM; AddOk: boolean; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; SortItem: PSORT_ITEM; procedure AddKeyInSorter(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; if TVKDBFNTX(FIndexes.Owner).OEM and ( CollationType <> cltNone ) then TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(Key), pAnsiChar(@sitem.key[0]), True, FNTXOrder.FHead.key_size) else Move(pAnsiChar(Key)^, sitem.key, FNTXOrder.FHead.key_size); Sorter.AddItem(sitem); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndex: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FGetHashFromSortItem := True; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; SorterRecCount :=( PreSorterBlockSize ) div ( FNTXOrder.FHead.key_size + ( 2 * SizeOf(DWord) ) ); Sorter := TVKRedBlackTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, IndexSortCharsProc, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode)); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInSorter(Key, Rec); // if Sorter.CountAddedItems = Sorter.CountRecords then begin Sorter.Sort; /////////// if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; if oB.OEM and ( CollationType <> cltNone ) then Move(SortItem.key, ntxitem.key, FNTXOrder.FHead.key_size) else TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(@SortItem.key[0]), pAnsiChar(@ntxitem.key[0]), True, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; SetString(Key, pAnsiChar(@ntxitem.key[0]), FNTXOrder.FHead.key_size); TransKey(pAnsiChar(Key), FNTXOrder.FHead.key_size, False); AddOk := true; if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem); until Sorter.NextSortItem; end; /////////// Sorter.Clear; end; // end; until ( BufCnt <= 0 ); // if Sorter.CountAddedItems > 0 then begin Sorter.Sort; /////////// if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; if oB.OEM and ( CollationType <> cltNone ) then Move(SortItem.key, ntxitem.key, FNTXOrder.FHead.key_size) else TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(@SortItem.key[0]), pAnsiChar(@ntxitem.key[0]), True, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; SetString(Key, pAnsiChar(@ntxitem.key[0]), FNTXOrder.FHead.key_size); TransKey(pAnsiChar(Key), FNTXOrder.FHead.key_size, False); AddOk := true; if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem); until Sorter.NextSortItem; end; /////////// Sorter.Clear; end; // end else Exception.Create('TVKNTXIndex.CreateIndex: Record size too lage'); finally FreeAndNil(Sorter); end; finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndex: Create index only on active DataSet'); end; procedure TVKNTXIndex.CreateCompactIndex( BlockBufferSize: LongWord = 65536; Activate: boolean = true; CreateTmpFilesInCurrentDir: boolean = false); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; BlockBuffer: pAnsiChar; FNtxHead: NTX_HEADER; max_item: WORD; Objects: TObjectList; Iter1, Iter2: TVKNTXIndexIterator; cIndex: TVKNTXCompactIndex; procedure LoadBlock(BlockFile: AnsiString; pBlock: pAnsiChar); var h: Integer; begin h := FileOpen(BlockFile, fmOpenRead or fmShareExclusive); if h > 0 then begin SysUtils.FileRead(h, pBlock^, BlockBufferSize); SysUtils.FileClose(h); end; end; procedure SaveBlock; var TmpFileName: AnsiString; h: Integer; begin if pBLOCK_BUFFER(BlockBuffer).count > 0 then begin if CreateTmpFilesInCurrentDir then //if CreateTmpFilesInCurrentDir = True then create TmpFileName in current path TmpFileName := GetTmpFileName(ExtractFilePath(NTXFileName)) else // else in system temporary directory TmpFileName := GetTmpFileName; h := FileOpen(TmpFileName, fmOpenWrite or fmShareExclusive); if h > 0 then begin SysUtils.FileWrite(h, BlockBuffer^, BlockBufferSize); SysUtils.FileClose(h); Objects.Add(TVKNTXBlockIterator.Create(TmpFileName, FNtxHead.key_size, BlockBufferSize)); end; end; end; procedure FillNtxHeader; var i: Integer; IndAttr: TIndexAttributes; begin DefineBag; if FClipperVer in [v500, v501] then FNtxHead.sign := 6 else FNtxHead.sign := 7; FNtxHead.version := 0; FNtxHead.root := NTX_PAGE; FNtxHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNtxHead.key_size := IndAttr.key_size; FNtxHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNtxHead.key_expr, Length(IndAttr.key_expr)); FNtxHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNtxHead.for_expr, Length(IndAttr.for_expr)); FNtxHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNtxHead.key_size := Length(FKeyParser.Key); FNtxHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNtxHead.key_expr, Length(FKeyExpresion)); FNtxHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNtxHead.for_expr, Length(FForExpresion)); FNtxHead.for_expr[Length(FForExpresion)] := #0; end; FNtxHead.item_size := FNtxHead.key_size + 8; FNtxHead.max_item := (NTX_PAGE - FNtxHead.item_size - 4) div (FNtxHead.item_size + 2); FNtxHead.half_page := FNtxHead.max_item div 2; FNtxHead.max_item := FNtxHead.half_page * 2; if Unique then FNtxHead.unique := #1 else FNtxHead.unique := #0; FNtxHead.reserv1 := #0; if Desc then FNtxHead.desc := #1 else FNtxHead.desc := #0; FNtxHead.reserv3 := #0; for i := 0 to 7 do FNtxHead.order[i] := FNTXOrder.FHead.Order[i]; // FNTXOrder.FHead := FNtxHead; // // FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; // end; procedure InitBlock(Block: pAnsiChar); var page: pBLOCK_BUFFER; half_page, item_size, item_off: WORD; i: Integer; q: LongWord; begin item_size := FNtxHead.key_size + 4; q := (BlockBufferSize - item_size - 4) div (item_size + 2); if q > MAXWORD then raise Exception.Create('TVKNTXIndex.CreateCompactIndex: BlockBufferSize too large!'); max_item := WORD(q); half_page := max_item div 2; max_item := half_page * 2; page := pBLOCK_BUFFER(Block); page.count := 0; item_off := ( max_item * 2 ) + 4; for i := 0 to max_item do begin page.ref[i] := item_off; item_off := item_off + item_size; end; end; procedure AddKeyInBlock(Key: AnsiString; Rec: DWORD); var AddOk: boolean; i, j, beg, Mid: Integer; page: pBLOCK_BUFFER; item: pBLOCK_ITEM; c: Integer; rf: WORD; procedure InsItem; begin j := page.count; while j >= i do begin rf := page.ref[j + 1]; page.ref[j + 1] := page.ref[j]; page.ref[j] := rf; Dec(j); end; page.count := page.count + 1; Move(pAnsiChar(Key)^, pBLOCK_ITEM(pAnsiChar(page) + page.ref[i]).key, FNTXOrder.FHead.key_size); pBLOCK_ITEM(pAnsiChar(page) + page.ref[i]).rec_no := Rec; end; procedure CmpRec; begin if c = 0 then begin if item.rec_no < Rec then c := 1 else c := -1; end; end; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin page := pBLOCK_BUFFER(BlockBuffer); if page.count = max_item then begin //Save block on disc SaveBlock; //Truncate block page.count := 0; end; TransKey(pAnsiChar(Key)); i := page.count; if ( i > 0 ) then begin beg := 0; item := pBLOCK_ITEM(pAnsiChar(page) + page.ref[beg]); c := CmpKeys1(item.key, pAnsiChar(Key)); if ( c = 0 ) and Unique then Exit; CmpRec; if ( c > 0 ) then begin repeat Mid := (i+beg) div 2; item := pBLOCK_ITEM(pAnsiChar(page) + page.ref[Mid]); c := CmpKeys1(item.key, pAnsiChar(Key)); if ( c = 0 ) and Unique then Exit; CmpRec; if ( c > 0 ) then beg := Mid else i := Mid; until ( ((i-beg) div 2) = 0 ); end else i := beg; end; if AddOk then InsItem; end; end; procedure MergeList(Iter1, Iter2: TVKNTXIndexIterator; cIndex: TVKNTXCompactIndex); var c: Integer; procedure CmpRec; begin if c = 0 then begin if Iter1.item.rec_no < Iter2.item.rec_no then c := 1 else c := -1; end; end; begin if Iter2 = nil then begin Iter1.Open; try while not Iter1.Eof do begin cIndex.AddItem(@Iter1.item); Iter1.Next; end; finally Iter1.Close; end; end else begin Iter1.Open; Iter2.Open; try repeat if not ( Iter1.Eof or Iter2.Eof ) then begin c := CmpKeys1(Iter1.Item.key, Iter2.Item.key); if ( c = 0 ) and Unique then begin cIndex.AddItem(@Iter1.Item); Iter1.Next; Iter2.Next; Continue; end; CmpRec; if c > 0 then begin if not Iter1.Eof then begin cIndex.AddItem(@Iter1.Item); Iter1.Next; end; end else if not Iter2.Eof then begin cIndex.AddItem(@Iter2.Item); Iter2.Next; end; end else begin if not Iter1.Eof then begin cIndex.AddItem(@Iter1.Item); Iter1.Next; end; if not Iter2.Eof then begin cIndex.AddItem(@Iter2.Item); Iter2.Next; end; end; until ( Iter1.Eof and Iter2.Eof ); finally Iter1.Close; Iter2.Close; end; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; Objects := TObjectList.Create; cIndex := TVKNTXCompactIndex.Create(LimitPages.PagesPerBuffer); cIndex.CreateTmpFilesInTmpFilesDir := CreateTmpFilesInCurrentDir; cIndex.TmpFilesDir := ExtractFilePath(NTXFileName); DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); BlockBuffer := VKDBFMemMgr.oMem.GetMem(self, BlockBufferSize); try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; FillNtxHeader; InitBlock(BlockBuffer); RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInBlock(Key, Rec); // end; until ( BufCnt <= 0 ); //Save the rest block SaveBlock; if Objects.Count > 0 then begin // Merge lists i := 0; while i < Objects.Count do begin Iter1 := TVKNTXIndexIterator(Objects[i]); if ( i + 1 ) < Objects.Count then Iter2 := TVKNTXIndexIterator(Objects[i + 1]) else Iter2 := nil; if ( Objects.Count - i ) > 2 then cIndex.FileName := '' else begin cIndex.FileName := FNTXFileName; cIndex.Crypt := oB.Crypt.Active; cIndex.OwnerTable := oB; if FNTXBag.NTXHandler.ProxyStreamType <> pstFile then cIndex.Handler := FNTXBag.NTXHandler; end; cIndex.CreateEmptyIndex(FNtxHead); try MergeList(Iter1, Iter2, cIndex); finally cIndex.Close; if ( Objects.Count - i ) > 2 then Objects.Add(TVKNTXIterator.Create(cIndex.FileName)); end; Inc(i, 2); end; end else begin cIndex.FileName := FNTXFileName; cIndex.Crypt := oB.Crypt.Active; cIndex.OwnerTable := oB; if FNTXBag.NTXHandler.ProxyStreamType <> pstFile then cIndex.Handler := FNTXBag.NTXHandler; cIndex.CreateEmptyIndex(FNtxHead); cIndex.Close; end; // end else Exception.Create('TVKNTXIndex.CreateCompactIndex: Record size too lage'); finally oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); VKDBFMemMgr.oMem.FreeMem(BlockBuffer); Objects.Free; cIndex.Free; end; Open; if IsOpen and Activate then Active := true; end else raise Exception.Create('TVKNTXIndex.CreateCompactIndex: Create index only on active DataSet'); end; function TVKNTXIndex.SuiteFieldList(fl: AnsiString; out m: Integer): Integer; begin if Temp then begin m := 0; Result := 0 end else Result := FKeyParser.SuiteFieldList(fl, m); end; function TVKNTXIndex.SeekFields(const KeyFields: AnsiString; const KeyValues: Variant; SoftSeek: boolean = false; PartialKey: boolean = false): Integer; var m, n: Integer; Key: AnsiString; begin Result := 0; m := FKeyParser.SuiteFieldList(KeyFields, n); if m > 0 then begin if PartialKey then FKeyParser.PartualKeyValue := True; try Key := FKeyParser.EvaluteKey(KeyFields, KeyValues); finally FKeyParser.PartualKeyValue := False; end; Result := SeekFirstRecord(Key, SoftSeek, PartialKey); end; end; function TVKNTXIndex.GetOwnerTable: TDataSet; begin Result := TDataSet(FIndexes.Owner); end; function TVKNTXIndex.SeekLastInternal(Key: AnsiString; SoftSeek: boolean): boolean; var lResult, SoftSeekSet: boolean; procedure Pass(page_off: DWORD); var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; c: Integer; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(Key), Length(Key)); if c < 0 then begin //Key < item.key if ( item.page <> 0 ) then Pass(item.page); if (SoftSeek) and (not lResult) and ( not SoftSeekSet ) then begin FSeekRecord := item.rec_no; SoftSeekSet := true; SetString(FSeekKey, item.key, FNTXOrder.FHead.key_size); FSeekOk := true; end; Exit; end; if c = 0 then begin //Key = item.key FSeekRecord := item.rec_no; SetString(FSeekKey, item.key, FNTXOrder.FHead.key_size); FSeekOk := true; lResult := true; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin FSeekOk := false; SoftSeekSet := false; if FLock then try ClearIfChange; lResult := false; Pass(FNTXOrder.FHead.root); Result := lResult; finally FUnLock; end else Result := false; end; procedure TVKNTXIndex.SetRangeFields(FieldList: AnsiString; FieldValues: array of const); var FieldVal: Variant; begin ArrayOfConstant2Variant(FieldValues, FieldVal); SetRangeFields(FieldList, FieldVal); end; procedure TVKNTXIndex.SetRangeFields(FieldList: AnsiString; FieldValues: Variant); var Key: AnsiString; begin FKeyParser.PartualKeyValue := True; try Key := FKeyParser.EvaluteKey(FieldList, FieldValues); finally FKeyParser.PartualKeyValue := False; end; NTXRange.LoKey := Key; NTXRange.HiKey := Key; NTXRange.ReOpen; end; function TVKNTXIndex.GetIsRanged: boolean; begin Result := NTXRange.Active; end; function TVKNTXIndex.InRange(Key: AnsiString): boolean; begin Result := NTXRange.InRange(Key); end; procedure TVKNTXIndex.ClearIfChange; var v: WORD; begin if not FCreateIndexProc then begin if not FUpdated then begin v := FNTXOrder.FHead.version; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Read(FNTXOrder.FHead, 12); if v <> FNTXOrder.FHead.version then FNTXBuffers.Clear; end; end; end; procedure TVKNTXIndex.StartUpdate(UnLock: boolean = true); begin if not FUpdated then if FLock then try FLastOffset := FNTXBag.NTXHandler.Seek(0, 2); ClearIfChange; FUpdated := true; finally if UnLock then FUnLock; end; end; procedure TVKNTXIndex.Flush; begin if FUpdated then begin FNTXBuffers.Flush(FNTXBag.NTXHandler); if not FCreateIndexProc then begin if FNTXOrder.FHead.version > 65530 then FNTXOrder.FHead.version := 0 else FNTXOrder.FHead.version := FNTXOrder.FHead.version + 1; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, 12); end; FUpdated := false; end; end; procedure TVKNTXIndex.Reindex(Activate: boolean = true); begin FReindex := true; try CreateIndex(Activate); finally FReindex := false; end; end; function TVKNTXIndex.GetCreateNow: Boolean; begin Result := false; end; procedure TVKNTXIndex.SetCreateNow(const Value: Boolean); begin if Value then begin CreateIndex; if csDesigning in OwnerTable.ComponentState then ShowMessage(Format('Index %s create successfully!', [NTXFileName])); end; end; function TVKNTXIndex.SeekFirstRecord(Key: AnsiString; SoftSeek: boolean = false; PartialKey: boolean = false): Integer; begin Result := FindKey(Key, PartialKey, SoftSeek); end; procedure TVKNTXIndex.Truncate; begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; //Create new header FNTXBuffers.Clear; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; procedure TVKNTXIndex.BeginCreateIndexProcess; begin Truncate; FCreateIndexProc:= true; FFLastFUpdated := FUpdated; FUpdated := true; end; procedure TVKNTXIndex.EndCreateIndexProcess; begin Flush; FUpdated := FFLastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; end; procedure TVKNTXIndex.EvaluteAndAddKey(nRec: DWORD); var Key: AnsiString; begin Key := EvaluteKeyExpr; AddKey(Key, nRec); end; function TVKNTXIndex.InRange: boolean; var Key: AnsiString; begin FKeyParser.PartualKeyValue := True; try Key := EvaluteKeyExpr; finally FKeyParser.PartualKeyValue := False; end; Result := NTXRange.InRange(Key); end; function TVKNTXIndex.FindKey( Key: AnsiString; PartialKey: boolean = false; SoftSeek: boolean = false; Rec: DWORD = 0): Integer; var oB: TVKDBFNTX; m: Integer; iResult: Integer; function Pass(page_off: DWORD): boolean; var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; c, c1: Integer; ntxb: TVKNTXNode; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); c := CmpKeys(item.key, pAnsiChar(Key), m); c1 := c; if Rec > 0 then if c = 0 then begin if item.rec_no < Rec then c1 := 1 else if item.rec_no = Rec then c1 := 0 else c1 := -1; end; if c1 <= 0 then begin //Key + RecNo <= item.key + RecNo if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; if c = 0 then begin // Key = item.key if oB.AcceptTmpRecord(item.rec_no) then begin iResult := item.rec_no; Result := true; Exit; end; end else begin if SoftSeek then begin if oB.AcceptTmpRecord(item.rec_no) then begin iResult := item.rec_no; Result := true; Exit; end; end else begin Result := false; Exit; end; end; end; end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Result := Pass(item.page); if Result then Exit; end; Result := false; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; end; begin Result := 0; oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then if FLock then try ClearIfChange; m := Length(Key); if m > FNTXOrder.FHead.key_size then m := FNTXOrder.FHead.key_size; if ( not ( PartialKey or SoftSeek ) ) and (m < FNTXOrder.FHead.key_size) then Exit; iResult := 0; Pass(FNTXOrder.FHead.root); Result := iResult; finally FUnLock; end; end; function TVKNTXIndex.FindKeyFields(const KeyFields: AnsiString; const KeyValues: Variant; PartialKey: boolean = false; SoftSeek: boolean = false): Integer; var m, l: Integer; Key: AnsiString; KeyFields_: AnsiString; PartialKeyInternal: boolean; begin Result := 0; KeyFields_ := KeyFields; if KeyFields_ = '' then KeyFields_ := FKeyParser.GetFieldList; m := FKeyParser.SuiteFieldList(KeyFields_, l); if m > 0 then begin PartialKeyInternal := PartialKey; if not PartialKeyInternal then begin if m > VarArrayDimCount(KeyValues) then PartialKeyInternal := True; end; if PartialKeyInternal then FKeyParser.PartualKeyValue := True; try Key := FKeyParser.EvaluteKey(KeyFields_, KeyValues); finally FKeyParser.PartualKeyValue := False; end; Result := FindKey(Key, PartialKeyInternal, SoftSeek); end; end; function TVKNTXIndex.FindKeyFields(const KeyFields: AnsiString; const KeyValues: array of const; PartialKey: boolean = false; SoftSeek: boolean = false): Integer; var FieldVal: Variant; begin ArrayOfConstant2Variant(KeyValues, FieldVal); Result := FindKeyFields(KeyFields, FieldVal, PartialKey, SoftSeek); end; function TVKNTXIndex.FindKeyFields(PartialKey: boolean = false; SoftSeek: boolean = false): Integer; var Key: AnsiString; begin if PartialKey then FKeyParser.PartualKeyValue := True; try Key := FKeyParser.EvaluteKey; finally FKeyParser.PartualKeyValue := False; end; Result := FindKey(Key, PartialKey, SoftSeek); end; function TVKNTXIndex.TransKey(Key: AnsiString): AnsiString; begin Result := Key; TransKey(pAnsiChar(Result), Length(Result), false); end; function TVKNTXIndex.IsForIndex: boolean; begin Result := FForExists; end; function TVKNTXIndex.IsUniqueIndex: boolean; begin Result := Unique; end; procedure TVKNTXIndex.DefineBagAndOrder; var oO: TVKNTXOrder; i: Integer; IndexName: AnsiString; begin IndexName := ChangeFileExt(ExtractFileName(NTXFileName), ''); if IndexName = '' then IndexName := Order; if IndexName = '' then IndexName := Name; DefineBag; if not FNTXBag.IsOpen then FNTXBag.Open; for i := 0 to FNTXBag.Orders.Count - 1 do begin oO := TVKNTXOrder(FNTXBag.Orders.Items[i]); if AnsiUpperCase(oO.Name) = AnsiUpperCase(IndexName) then begin FNTXOrder := oO; LimitPages.LimitPagesType := oO.LimitPages.LimitPagesType; LimitPages.LimitBuffers := oO.LimitPages.LimitBuffers; LimitPages.PagesPerBuffer := oO.LimitPages.PagesPerBuffer; Collation.CollationType := oO.Collation.CollationType; Collation.CustomCollatingSequence := oO.Collation.CustomCollatingSequence; OuterSorterProperties := oO.OuterSorterProperties; end; end; if FNTXOrder = nil then raise Exception.Create('TVKNTXIndex.DefineBagAndOrder: FNTXOrder not defined!'); end; procedure TVKNTXIndex.DefineBag; var oW: TVKDBFNTX; oB: TVKNTXBag; oO: TVKNTXOrder; i: Integer; BgNm, IndexName: AnsiString; NewOrder: boolean; begin oW := TVKDBFNTX(FIndexes.Owner); IndexName := ChangeFileExt(ExtractFileName(NTXFileName), ''); if IndexName = '' then IndexName := Order; if IndexName = '' then IndexName := Name; FNTXOrder := nil; FNTXBag := nil; for i := 0 to oW.DBFIndexDefs.Count - 1 do begin oB := TVKNTXBag(oW.DBFIndexDefs.Items[i]); BgNm := oB.Name; if BgNm = '' then BgNm := ChangeFileExt(ExtractFileName(oB.IndexFileName), ''); if BagName <> '' then begin if AnsiUpperCase(BgNm) = AnsiUpperCase(BagName) then begin FNTXBag := oB; break; end; end else begin if AnsiUpperCase(BgNm) = AnsiUpperCase(IndexName) then begin FNTXBag := oB; break; end; end; end; if FNTXBag = nil then begin oB := TVKNTXBag(oW.DBFIndexDefs.Add); oB.Name := ChangeFileExt(ExtractFileName(NTXFileName), ''); oB.IndexFileName := NTXFileName; oB.StorageType := oW.StorageType; FNTXBag := oB; end; FNTXBag.FillHandler; NewOrder := False; if FNTXBag.Orders.Count = 0 then begin FNTXBag.Orders.Add; NewOrder := True; end; oO := TVKNTXOrder(FNTXBag.Orders.Items[0]); FillChar(oO.FHead, SizeOf(NTX_HEADER), #0); oO.Name := ChangeFileExt(ExtractFileName(FNTXBag.IndexFileName), ''); if oO.Name = '' then oO.Name := FNTXBag.Name; FNTXOrder := oO; if NewOrder then begin oO.LimitPages.LimitPagesType := LimitPages.LimitPagesType; oO.LimitPages.LimitBuffers := LimitPages.LimitBuffers; oO.LimitPages.PagesPerBuffer := LimitPages.PagesPerBuffer; oO.Collation.CollationType := Collation.CollationType; oO.Collation.CustomCollatingSequence := Collation.CustomCollatingSequence; oO.OuterSorterProperties := OuterSorterProperties; end else begin LimitPages.LimitPagesType := oO.LimitPages.LimitPagesType; LimitPages.LimitBuffers := oO.LimitPages.LimitBuffers; LimitPages.PagesPerBuffer := oO.LimitPages.PagesPerBuffer; Collation.CollationType := oO.Collation.CollationType; Collation.CustomCollatingSequence := oO.Collation.CustomCollatingSequence; OuterSorterProperties := oO.OuterSorterProperties; end; end; (* procedure TVKNTXIndex.BackwardPass; begin end; procedure TVKNTXIndex.ForwardPass; procedure Pass(page_off: DWORD); var i: DWORD; page: pNTX_BUFFER; item: pNTX_ITEM; ntxb: TVKNTXBuffer; begin ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count > 0 then begin for i := 0 to page.count - 1 do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); if ( item.page <> 0 ) then Pass(item.page); // end; end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then Pass(item.page); finally FNTXBuffers.FreeNTXBuffer(ntxb); end; end; begin Pass(FNTXOrder.FHead.root); end; *) procedure TVKNTXIndex.SetNTXRange(const Value: TVKNTXRange); begin FNTXRange.HiKey := Value.HiKey; FNTXRange.LoKey := Value.LoKey; FNTXRange.Active := Value.Active; end; function TVKNTXIndex.GetIndexBag: TVKDBFIndexBag; begin Result := FNTXBag; end; function TVKNTXIndex.GetIndexOrder: TVKDBFOrder; begin Result := FNTXOrder; end; procedure TVKNTXIndex.IndexSortProc(Sender: TObject; CurrentItem, Item: PSORT_ITEM; MaxLen: Cardinal; out c: Integer); var i: integer; c1, c2: pAnsiChar; begin c1 := @CurrentItem.key[0]; c2 := @Item.key[0]; if CollationType <> cltNone then begin for i := 0 to MaxLen - 1 do begin c := CollatingTable[Ord(c1[i])] - CollatingTable[Ord(c2[i])]; if c <> 0 then Break; end; end else begin c := {$IFDEF DELPHIXE4}AnsiStrings.{$ENDIF}StrLComp(c1, c2, MaxLen); end; if Desc then c := - c; end; procedure TVKNTXIndex.IndexSortCharsProc(Sender: TObject; Char1, Char2: Byte; out c: Integer); begin (* if TVKDBFNTX(FIndexes.Owner).OEM and ( CollationType <> cltNone ) then begin c1 := AnsiChar3; c2 := AnsiChar4; end else begin c1 := AnsiChar1; c2 := AnsiChar2; end; *) if CollationType <> cltNone then begin c := CollatingTable[Char1] - CollatingTable[Char2]; end else begin c := Char1 - Char2; end; if Desc then c := - c; end; (* procedure TVKNTXIndex.CreateIndexUsingSorter1( SorterClass: TVKSorterClass; Activate: boolean); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i {, j}: Integer; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; Sorter: TVKSorterAbstract; sitem: SORT_ITEM; ntxitem: NTX_ITEM; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; SortItem: PSORT_ITEM; procedure AddKeyInSorter(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; if TVKDBFNTX(FIndexes.Owner).OEM and ( CollationType <> cltNone ) then TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(Key), pAnsiChar(@sitem.key[0]), True, FNTXOrder.FHead.key_size) else Move(pAnsiChar(Key)^, sitem.key, FNTXOrder.FHead.key_size); Sorter.AddItem(sitem); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndexUsingSorter1: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin Sorter := nil; oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FGetHashFromSortItem := True; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; Sorter := SorterClass.Create( oB.Header.last_rec, FNTXOrder.FHead.key_size, IndexSortProc, IndexSortAnsiCharsProc, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), False); if Sorter = nil then Exception.Create('TVKNTXIndex.CreateIndexUsingSorter1: Sorter object is null!'); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInSorter(Key, Rec); // end; until ( BufCnt <= 0 ); // Sorter.Sort; // /////////// if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; if oB.OEM and ( CollationType <> cltNone ) then Move(SortItem.key, ntxitem.key, FNTXOrder.FHead.key_size) else TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(@SortItem.key[0]), pAnsiChar(@ntxitem.key[0]), True, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; AddItem(@ntxitem, True); until Sorter.NextSortItem; end; /////////// // Sorter.Clear; // end else Exception.Create('TVKNTXIndex.CreateIndexUsingSorter1: Record size too lage'); finally FreeAndNil(Sorter); end; finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingSorter1: Create index only on active DataSet'); end; *) procedure TVKNTXIndex.CreateIndexUsingSorter( SorterClass: TVKSorterClass; Activate: boolean); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; FNtxHead: NTX_HEADER; cIndex: TVKNTXCompactIndex; Sorter: TVKSorterAbstract; TmpHandler: TProxyStream; sitem: SORT_ITEM; ntxitem: NTX_ITEM; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; SortItem: PSORT_ITEM; procedure AddKeyInSorter(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; if TVKDBFNTX(FIndexes.Owner).OEM and ( CollationType <> cltNone ) then TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(Key), pAnsiChar(@sitem.key[0]), True, FNtxHead.key_size) else Move(pAnsiChar(Key)^, sitem.key, FNtxHead.key_size); Sorter.AddItem(sitem); end; end; procedure FillNtxHeader; var i: Integer; IndAttr: TIndexAttributes; begin DefineBag; if FClipperVer in [v500, v501] then FNtxHead.sign := 6 else FNtxHead.sign := 7; FNtxHead.version := 0; FNtxHead.root := NTX_PAGE; FNtxHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNtxHead.key_size := IndAttr.key_size; FNtxHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNtxHead.key_expr, Length(IndAttr.key_expr)); FNtxHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNtxHead.for_expr, Length(IndAttr.for_expr)); FNtxHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNtxHead.key_size := Length(FKeyParser.Key); FNtxHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNtxHead.key_expr, Length(FKeyExpresion)); FNtxHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNtxHead.for_expr, Length(FForExpresion)); FNtxHead.for_expr[Length(FForExpresion)] := #0; end; FNtxHead.item_size := FNtxHead.key_size + 8; FNtxHead.max_item := (NTX_PAGE - FNtxHead.item_size - 4) div (FNtxHead.item_size + 2); FNtxHead.half_page := FNtxHead.max_item div 2; FNtxHead.max_item := FNtxHead.half_page * 2; if Unique then FNtxHead.unique := #1 else FNtxHead.unique := #0; FNtxHead.reserv1 := #0; if Desc then FNtxHead.desc := #1 else FNtxHead.desc := #0; FNtxHead.reserv3 := #0; for i := 0 to 7 do FNtxHead.order[i] := FNTXOrder.FHead.Order[i]; // FNTXOrder.FHead := FNtxHead; // FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; // end; begin Sorter := nil; TmpHandler := nil; oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FGetHashFromSortItem := True; cIndex := TVKNTXCompactIndex.Create(LimitPages.PagesPerBuffer); DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; FillNtxHeader; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; if SorterClass.InheritsFrom(TVKOuterSorter) then begin TmpHandler := TProxyStream.Create; if OuterSorterProperties.TmpPath = '' then TmpHandler.FileName := GetTmpFileName else TmpHandler.FileName := GetTmpFileName(OuterSorterProperties.TmpPath); TmpHandler.AccessMode.AccessMode := 66; TmpHandler.ProxyStreamType := pstFile; TmpHandler.CreateProxyStream; end; Sorter := SorterClass.Create( oB.Header.last_rec, FNtxHead.key_size, IndexSortProc, IndexSortCharsProc, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), False, TmpHandler, OuterSorterProperties.InnerSorterClass, OuterSorterProperties.BufferSize, OuterSorterProperties.SortItemPerInnerSorter); if Sorter = nil then Exception.Create('TVKNTXIndex.CreateIndexUsingSorter: Sorter object is null!'); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to pred(BufCnt) do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInSorter(Key, Rec); // end; until ( BufCnt <= 0 ); // Sort sorter object Sorter.Sort; // // cIndex.FileName := FNTXFileName; cIndex.Crypt := oB.Crypt.Active; cIndex.OwnerTable := oB; if FNTXBag.NTXHandler.ProxyStreamType <> pstFile then cIndex.Handler := FNTXBag.NTXHandler; cIndex.CreateEmptyIndex(FNtxHead); /////////// if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; if oB.OEM and ( CollationType <> cltNone ) then Move(SortItem.key, ntxitem.key, FNTXOrder.FHead.key_size) else TVKDBFNTX(FIndexes.Owner).TranslateBuff(pAnsiChar(@SortItem.key[0]), pAnsiChar(@ntxitem.key[0]), True, FNtxHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; cIndex.AddItem(@ntxitem); until Sorter.NextSortItem; end; /////////// // cIndex.Close; // // end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingSorter: Record size too lage'); if TmpHandler <> nil then begin TmpHandler.Close; DeleteFile(TmpHandler.FileName); end; finally FreeAndNil(Sorter); FreeAndNil(TmpHandler); end; finally FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); cIndex.Free; end; Open; if IsOpen and Activate then Active := true; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingSorter: Create index only on active DataSet'); end; (* procedure TVKNTXIndex.CreateIndexUsingMergeBinaryTreeAndBTree( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = True; PreSorterBlockSize: LongWord = 65536); type TJoinTreesResult = (jtrUndefined, jtrMergeCompleted, jtrAddItemNeeded, jtrReturnToPreviosLevel); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; pKey: pAnsiChar; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; Sorter: TVKBinaryTreeSorterAbstract; SorterRecCount: DWord; sitem: SORT_ITEM; ntxitem: NTX_ITEM; AddOk: boolean; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; NextSortItemPoint{, SortItemPoint}: DWord; SortItem: PSORT_ITEM; function MergeTreesInternal(CurrentPageOffset: DWord; ParentNode: TVKNTXNode; PreviousItem: pNTX_ITEM = nil; PreviousItemNo: Word = Word(-1)): TJoinTreesResult; var CurrentNodePage: pNTX_BUFFER; CurrentNode: TVKNTXNode; SiblingNodePage: pNTX_BUFFER; SiblingNode: TVKNTXNode; c, i, j: Integer; Item, Item1, SiblingItem: pNTX_ITEM; Item2: NTX_ITEM; IsLeaf , IsRoot, IsAddInSibling: boolean; swap_value: Word; function TrySiblings: TJoinTreesResult; var j: Integer; begin Result := jtrUndefined; //Check right and left sibling node for ability to add items into them //The right node is the first IsAddInSibling := False; if ( ParentNode <> nil ) and ( PreviousItem <> nil ) and ( PreviousItemNo <> Word(-1) ) and ( PreviousItemNo < ParentNode.PNode.count { note: item parent.ref[count] always exist } ) then begin SiblingItem := pNTX_ITEM(pAnsiChar(ParentNode.PNode) + ParentNode.PNode.ref[Succ(PreviousItemNo)]); SiblingNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, SiblingItem.page, SiblingNodePage); try // if SiblingNodePage.count < FNTXOrder.FHead.max_item then begin Item1 := pNTX_ITEM(pAnsiChar(CurrentNode.PNode) + CurrentNode.PNode.ref[Pred(CurrentNode.PNode.count)]); //Save infomation from Previouse (parent) Item in Item2 Move(PreviousItem.key, Item2.key, FNTXOrder.FHead.key_size); Item2.rec_no := PreviousItem.rec_no; //Copy Item1 to Previouse (parent) Item Move(Item1.key, PreviousItem.key, FNTXOrder.FHead.key_size); PreviousItem.rec_no := Item1.rec_no; ParentNode.Changed := True; //Add Item2 in SiblingNode in first position // shift ref array for j := SiblingNodePage.count downto 0 do begin swap_value := SiblingNodePage.ref[succ(j)]; SiblingNodePage.ref[succ(j)] := SiblingNodePage.ref[j]; SiblingNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(SiblingNodePage) + SiblingNodePage.ref[0]); // Save Item2 to Item Move(Item2.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := Item2.rec_no; Item.page := 0; Inc(SiblingNodePage.count); SiblingNode.Changed := True; Dec(CurrentNodePage.count); CurrentNode.Changed := True; //Insert SortItem to the current page // shift ref array for j := CurrentNodePage.count downto i do begin swap_value := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; Item.page := 0; Inc(CurrentNodePage.count); CurrentNode.Changed := True; //Get next SORT_ITEM //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; // SortItemPoint; if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; IsAddInSibling := True; end; // finally FNTXBuffers.FreeNTXBuffer(SiblingNode.FNTXBuffer); end; end; //The left node is the second if ( not IsAddInSibling ) and ( ParentNode <> nil ) and ( PreviousItem <> nil ) and ( PreviousItemNo <> Word(-1) ) and ( PreviousItemNo > 0 ) then begin SiblingItem := pNTX_ITEM(pAnsiChar(ParentNode.pNode) + ParentNode.PNode.ref[Pred(PreviousItemNo)]); SiblingNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, SiblingItem.page, SiblingNodePage); try // if SiblingNodePage.count < FNTXOrder.FHead.max_item then begin if i > 0 then begin Item1 := pNTX_ITEM(pAnsiChar(CurrentNode.PNode) + CurrentNode.PNode.ref[0]); //Save infomation from SiblingItem (parent) Item in Item2 Move(SiblingItem.key, Item2.key, FNTXOrder.FHead.key_size); Item2.rec_no := SiblingItem.rec_no; //Copy Item1 to Previouse (parent) Item Move(Item1.key, SiblingItem.key, FNTXOrder.FHead.key_size); SiblingItem.rec_no := Item1.rec_no; ParentNode.Changed := True; //Add Item2 in SiblingNode in end position // shift ref array for Sibling for j := SiblingNodePage.count downto SiblingNodePage.count do begin swap_value := SiblingNodePage.ref[succ(j)]; SiblingNodePage.ref[succ(j)] := SiblingNodePage.ref[j]; SiblingNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(SiblingNodePage) + SiblingNodePage.ref[SiblingNodePage.count]); // Save Item2 to Item Move(Item2.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := Item2.rec_no; Item.page := 0; Inc(SiblingNodePage.count); SiblingNode.Changed := True; // shift ref array for Current for j := 0 to Pred(CurrentNodePage.count) do begin swap_value := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := swap_value; end; Dec(CurrentNodePage.count); CurrentNode.Changed := True; Dec(i); //Insert SortItem to the current page // shift ref array for j := CurrentNodePage.count downto i do begin swap_value := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; Item.page := 0; Inc(CurrentNodePage.count); CurrentNode.Changed := True; //Get next SORT_ITEM //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; IsAddInSibling := True; end else begin IsAddInSibling := False; end; end; // finally FNTXBuffers.FreeNTXBuffer(SiblingNode.FNTXBuffer); end; end; if ( not IsAddInSibling ) then begin Result := jtrAddItemNeeded; Exit; end; end; function TrySiblingsForEnd: TJoinTreesResult; var j: Integer; begin Result := jtrUndefined; //Check right and left sibling node for ability to add items into them //The right node is the first IsAddInSibling := False; if ( ParentNode <> nil ) and ( PreviousItem <> nil ) and ( PreviousItemNo <> Word(-1) ) and ( PreviousItemNo < ParentNode.PNode.count { note: item parent.ref[count] always exist } ) then begin SiblingItem := pNTX_ITEM(pAnsiChar(ParentNode.PNode) + ParentNode.PNode.ref[Succ(PreviousItemNo)]); SiblingNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, SiblingItem.page, SiblingNodePage); try // if SiblingNodePage.count < FNTXOrder.FHead.max_item then begin //Save infomation from Previouse (parent) Item in Item2 Move(PreviousItem.key, Item2.key, FNTXOrder.FHead.key_size); Item2.rec_no := PreviousItem.rec_no; //Copy SortItem to Previouse (parent) Item Move(SortItem.key, PreviousItem.key, FNTXOrder.FHead.key_size); PreviousItem.rec_no := SortItem.RID; ParentNode.Changed := True; //Add Item2 in SiblingNode in first position // shift ref array for j := SiblingNodePage.count downto 0 do begin swap_value := SiblingNodePage.ref[succ(j)]; SiblingNodePage.ref[succ(j)] := SiblingNodePage.ref[j]; SiblingNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(SiblingNodePage) + SiblingNodePage.ref[0]); // Save Item2 to Item Move(Item2.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := Item2.rec_no; Item.page := 0; Inc(SiblingNodePage.count); SiblingNode.Changed := True; //Get next SORT_ITEM //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; IsAddInSibling := True; end; // finally FNTXBuffers.FreeNTXBuffer(SiblingNode.FNTXBuffer); end; end; //The left node is the second if ( not IsAddInSibling ) and ( ParentNode <> nil ) and ( PreviousItem <> nil ) and ( PreviousItemNo <> Word(-1) ) and ( PreviousItemNo > 0 ) then begin SiblingItem := pNTX_ITEM(pAnsiChar(ParentNode.pNode) + ParentNode.PNode.ref[Pred(PreviousItemNo)]); SiblingNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, SiblingItem.page, SiblingNodePage); try // if SiblingNodePage.count < FNTXOrder.FHead.max_item then begin Item1 := pNTX_ITEM(pAnsiChar(CurrentNode.PNode) + CurrentNode.PNode.ref[0]); //Save infomation from SiblingItem (parent) Item in Item2 Move(SiblingItem.key, Item2.key, FNTXOrder.FHead.key_size); Item2.rec_no := SiblingItem.rec_no; //Copy Item1 to Previouse (parent) Item Move(Item1.key, SiblingItem.key, FNTXOrder.FHead.key_size); SiblingItem.rec_no := Item1.rec_no; ParentNode.Changed := True; //Add Item2 in SiblingNode in end position // shift ref array for Sibling for j := SiblingNodePage.count downto SiblingNodePage.count do begin swap_value := SiblingNodePage.ref[succ(j)]; SiblingNodePage.ref[succ(j)] := SiblingNodePage.ref[j]; SiblingNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(SiblingNodePage) + SiblingNodePage.ref[SiblingNodePage.count]); // Save Item2 to Item Move(Item2.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := Item2.rec_no; Item.page := 0; Inc(SiblingNodePage.count); SiblingNode.Changed := True; // shift ref array for Current for j := 0 to Pred(CurrentNodePage.count) do begin swap_value := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := swap_value; end; Dec(CurrentNodePage.count); CurrentNode.Changed := True; Dec(i); //Insert SortItem to the current page at end position // shift ref array for j := CurrentNodePage.count downto CurrentNodePage.count do begin swap_value := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; Item.page := 0; Inc(CurrentNodePage.count); CurrentNode.Changed := True; //Get next SORT_ITEM //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; IsAddInSibling := True; end; // finally FNTXBuffers.FreeNTXBuffer(SiblingNode.FNTXBuffer); end; end; if ( not IsAddInSibling ) then begin Result := jtrAddItemNeeded; Exit; end; end; begin Result := jtrUndefined; IsRoot := ( ParentNode = nil ); IsLeaf := False; CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try // if CurrentNodePage.count > 0 then begin i := 0; while i < CurrentNodePage.count do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); c := CmpKeys1(pAnsiChar(@SortItem.key[0]), Item.key, FNTXOrder.FHead.key_size); if c > 0 then begin //Item.key > SortItem if ( Item.page <> 0 ) then begin Result := MergeTreesInternal(Item.page, CurrentNode, Item, i); if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; c := CmpKeys1(pAnsiChar(@SortItem.key[0]), Item.key, FNTXOrder.FHead.key_size); IsLeaf := False; end else IsLeaf := True; if c > 0 then begin if IsLeaf then begin if ( CurrentNodePage.count < FNTXOrder.FHead.max_item ) then begin // shift ref array for j := CurrentNodePage.count downto i do begin swap_value := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; Item.page := 0; Inc(CurrentNodePage.count); CurrentNode.Changed := True; //Get next SORT_ITEM //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; end else begin Result := TrySiblings; if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; end; end else begin Result := jtrAddItemNeeded; Exit; // This is code is real work, but not efficient. { // //Prepare sitem for add to binary tree (culculate hash) sitem.RID := Item.rec_no; Move(Item.key, sitem.key, FNTXOrder.FHead.key_size); TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, false); try FGetHashFromSortItem := False; GetVKHashCode(self, @sitem, sitem.Hash); finally FGetHashFromSortItem := True; end; TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, true); sitem.key[FNTXOrder.FHead.key_size] := 0; // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; CurrentNode.Changed := True; //Add in binary tree new item (sitem) Sorter.SortItem[NextSortItemPoint] := sitem; Sorter.AddItemInTreeByEntry(NextSortItemPoint); //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; //Get next SORT_ITEM (it may be recently added item) if Sorter.NextSortItem then // is there eof Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; Inc(i); } end; end else Inc(i); end else Inc(i); end; // c := 0; if IsLeaf then begin while True do begin if IsRoot then c := 1 else begin if PreviousItem <> nil then c := CmpKeys1(pAnsiChar(@SortItem.key[0]), PreviousItem.key, FNTXOrder.FHead.key_size) else Break; end; if ( CurrentNodePage.count < FNTXOrder.FHead.max_item ) then begin if c > 0 then begin //PreviousItem.key > SortItem // shift ref array i := CurrentNodePage.count; for j := CurrentNodePage.count downto i do begin swap_value := CurrentNodePage.ref[succ(j)]; CurrentNodePage.ref[succ(j)] := CurrentNodePage.ref[j]; CurrentNodePage.ref[j] := swap_value; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; Item.page := 0; Inc(CurrentNodePage.count); CurrentNode.Changed := True; //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; //Get next SORT_ITEM (it may be recently added item) if Sorter.NextSortItem then // is there more SortItems? Result := jtrMergeCompleted; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; //SortItem := Sorter.PSortItem[Sorter.SortArray[SortItemPoint]]; SortItem := Sorter.CurrentSortItem; //Sorter.PSortItem[SortItemPoint]; end else Break; end else begin if c > 0 then begin //PreviousItem.key > SortItem Result := TrySiblingsForEnd; if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; end else Break; end; end; end; // end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then Result := MergeTreesInternal(Item.page, CurrentNode, nil, CurrentNodePage.count); if Result in [jtrMergeCompleted, jtrAddItemNeeded] then Exit; Result := jtrReturnToPreviosLevel; // finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; function JoinTreesInternal: boolean; var jtr: TJoinTreesResult; begin repeat jtr := MergeTreesInternal(FNTXOrder.FHead.root, nil, nil, Word(-1)); case jtr of jtrMergeCompleted, jtrReturnToPreviosLevel: begin Result := True; Exit; end; jtrAddItemNeeded: begin ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; pKey := pAnsiChar(@SortItem.key[0]); Move(pKey^, ntxitem.key, FNTXOrder.FHead.key_size); AddItem(@ntxitem); //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; //Get next SORT_ITEM (it may be recently added item) if not Sorter.NextSortItem then // is there eof begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); end else begin Result := True; //In anyway delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); Exit; end; // end; end; until False; end; procedure AddKeyInSorter(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; Move(pAnsiChar(Key)^, sitem.key, FNTXOrder.FHead.key_size); sitem.key[FNTXOrder.FHead.key_size] := 0; TransKey(pAnsiChar(@sitem.key[0])); Sorter.AddItem(sitem); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndexUsingMergeBinaryTreeAndBTree: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FGetHashFromSortItem := True; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; // SorterRecCount := ( PreSorterBlockSize ) div ( FNTXOrder.FHead.key_size + ( 2 * SizeOf(DWord) ) ); // if TreeSorterClass = TVKBinaryTreeSorter then Sorter := TVKBinaryTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKRedBlackTreeSorter then Sorter := TVKRedBlackTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKAVLTreeSorter then Sorter := TVKAVLTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if Sorter = nil then raise Exception.Create('TVKNTXIndex.CreateIndexUsingMergeBinaryTreeAndBTree: Sorter object is null!'); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInSorter(Key, Rec); // if Sorter.CountAddedItems = Pred(Sorter.CountRecords) then begin // //DONE: Join trees! // // NextSortItemPoint := Sorter.CountAddedItems; if not Sorter.FirstSortItem then begin SortItem := Sorter.CurrentSortItem; // PSortItem[SortItemPoint]; JoinTreesInternal; end; if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; // ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; pKey := pAnsiChar(@SortItem.key[0]); Move(pKey^, ntxitem.key, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; SetString(Key, pAnsiChar(@ntxitem.key[0]), FNTXOrder.FHead.key_size); TransKey(pAnsiChar(Key), FNTXOrder.FHead.key_size, False); AddOk := true; if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem, True); // until Sorter.NextSortItem; end; // Sorter.Clear; end; // end; until ( BufCnt <= 0 ); // if Sorter.CountAddedItems > 0 then begin // //DONE: Join trees! // // NextSortItemPoint := Sorter.CountAddedItems; if not Sorter.FirstSortItem then begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; JoinTreesInternal; end; // if not Sorter.FirstSortItem then begin repeat SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; // ntxitem.page := 0; ntxitem.rec_no := SortItem.RID; pKey := pAnsiChar(@SortItem.key[0]); Move(pKey^, ntxitem.key, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; SetString(Key, pAnsiChar(@ntxitem.key[0]), FNTXOrder.FHead.key_size); TransKey(pAnsiChar(Key), FNTXOrder.FHead.key_size, False); AddOk := true; if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem, True); // until Sorter.NextSortItem; end; // Sorter.Clear; end; // end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingMergeBinaryTreeAndBTree: Record size too lage'); finally FreeAndNil(Sorter); end; finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingMergeBinaryTreeAndBTree: Create index only on active DataSet'); end; *) (* procedure TVKNTXIndex.CreateIndexUsingabsorption( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); type TMergeTreesResult = (mtrUndefined, mtrMergeCompleted, mtrAddItemNeeded, mtrReturnToPreviosLevel); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; ntxitem: NTX_ITEM; Sorter: TVKBinaryTreeSorterAbstract; SorterRecCount: DWord; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; NextSortItemPoint {, SortItemPoint}: DWord; SortItem: PSORT_ITEM; sitem: SORT_ITEM; fb: boolean; c: Integer; procedure AddKeyInSorter(Key: pAnsiChar; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; Move(Key^, sitem.key, FNTXOrder.FHead.key_size); sitem.key[FNTXOrder.FHead.key_size] := 0; Sorter.AddItem(sitem); end; end; function WorkTraversal(CurrentPageOffset: DWord): boolean; var i, j: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item, LItem: pNTX_ITEM; begin Result := False; CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try LItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if LItem.rec_no = DWord(-1) then j := 0 else j := Succ(LItem.rec_no); for i := 0 to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if i < j then begin c := CmpKeys1(pAnsiChar(@SortItem.key[0]), Item.key, FNTXOrder.FHead.key_size); if c >= 0 then begin //Item.key >= SortItem if ( Item.page <> 0 ) then begin Result := WorkTraversal(Item.page); if Result then exit; c := CmpKeys1(pAnsiChar(@SortItem.key[0]), Item.key, FNTXOrder.FHead.key_size); end; if ( c = 0 ) and ( not Unique ) then c := 1; if c > 0 then begin // sitem.RID := Item.rec_no; Move(Item.key, sitem.key, FNTXOrder.FHead.key_size); TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, false); try FGetHashFromSortItem := False; GetVKHashCode(self, @sitem, sitem.Hash); finally FGetHashFromSortItem := True; end; TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, true); sitem.key[FNTXOrder.FHead.key_size] := 0; // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; CurrentNode.Changed := True; //Add in binary tree new item (sitem) Sorter.SortItem[NextSortItemPoint] := sitem; Sorter.AddItemInTreeByEntry(NextSortItemPoint); //Save SortItemPoint as NextSortItemPoint NextSortItemPoint := Sorter.CurrentItem; //SortItemPoint; //Get next SORT_ITEM (it may be recently added item) Sorter.NextSortItem; //Delete previous item from binary tree Sorter.DeleteFromTreeByEntry(NextSortItemPoint); // SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; // end; end; end else begin if ( Item.page <> 0 ) then begin Result := WorkTraversal(Item.page); if Result then exit; end; if not fb then begin // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; CurrentNode.Changed := True; //Get next SORT_ITEM if not Sorter.NextSortItem then begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; end else begin Sorter.Clear; fb := True; end; // LItem.rec_no := i; CurrentNode.Changed := true; // end else begin if Sorter.CountAddedItems < Pred(Sorter.CountRecords) then AddKeyInSorter(Item.Key, Item.rec_no) else begin Result := True; Exit; end; end; // end; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then begin Result := WorkTraversal(Item.page); if Result then exit; end; finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure MarkAllPagesAsNotHandled(CurrentPageOffset: DWord); var i: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item: pNTX_ITEM; begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try for i := 0 to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if ( Item.page <> 0 ) then MarkAllPagesAsNotHandled(Item.page); if Sorter.CountAddedItems < Pred(Sorter.CountRecords) then AddKeyInSorter(Item.Key, Item.rec_no); end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then MarkAllPagesAsNotHandled(Item.page); //Save in last item (page.ref[count]) in rec_no field node def value ( -1 ) for use it field to store current position Item.rec_no := DWord(-1); CurrentNode.Changed := true; // finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure AddKeyInBTreeAtEnd(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin ntxitem.page := 0; ntxitem.rec_no := Rec; Move(pAnsiChar(Key)^, ntxitem.key, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; TransKey(pAnsiChar(@ntxitem.key[0])); if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem, True); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndexUsingMerge: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; // SorterRecCount := ( PreSorterBlockSize ) div ( FNTXOrder.FHead.key_size + ( 2 * SizeOf(DWord) ) ); // if TreeSorterClass = TVKBinaryTreeSorter then Sorter := TVKBinaryTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKRedBlackTreeSorter then Sorter := TVKRedBlackTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKAVLTreeSorter then Sorter := TVKAVLTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if Sorter = nil then raise Exception.Create('TVKNTXIndex.CreateIndexUsingMerge: Sorter object is null!'); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin // First of all create a not sorted B-Tree structure ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInBTreeAtEnd(Key, Rec); // end; until ( BufCnt <= 0 ); // //Than mark all pages as not handled MarkAllPagesAsNotHandled(FNTXOrder.FHead.root); // // while True do begin NextSortItemPoint := Sorter.CountAddedItems; if not Sorter.FirstSortItem then begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; fb := False; WorkTraversal(FNTXOrder.FHead.root); end else Break; end; // end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingMerge: Record size too lage'); finally FreeAndNil(Sorter); end; finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingMerge: Create index only on active DataSet'); end; *) (* procedure TVKNTXIndex.SortNtxNode(NtxNode: TVKNTXNode); const TNILL = MAX_ITEMS_IN_PAGE; var lson: array[0..TNILL] of WORD; rson: array[0..TNILL + 1] of WORD; ref: array[0..MAX_ITEMS_IN_PAGE] of WORD; root: Word; NtxPage: pNTX_BUFFER; i, j: Integer; function CompareItems(point, p: Word): Integer; var Ipoint, Ip: pNTX_ITEM; begin Ipoint := pNTX_ITEM(pAnsiChar(NtxPage) + NtxPage.ref[point]); Ip := pNTX_ITEM(pAnsiChar(NtxPage) + NtxPage.ref[p]); Result := CmpKeys1(Ipoint.key, Ip.key, FNTXOrder.FHead.key_size); if Result = 0 then begin if Ip.rec_no < Ipoint.rec_no then Result := -1 else Result := 1; end; end; procedure InitTree; begin rson[Succ(TNILL)] := TNILL; lson[TNILL] := TNILL; rson[TNILL] := TNILL; end; procedure AddItemInTree(point: Word); var p: DWord; c: Integer; begin p := Succ(TNILL); c := 1; rson[point] := TNILL; lson[point] := TNILL; while true do begin if (c >= 0) then begin if (rson[p] <> TNILL) then begin p := rson[p]; end else begin rson[p] := point; break; end; end else begin if (lson[p] <> TNILL) then begin p := lson[p]; end else begin lson[p] := point; break; end; end; c := CompareItems(point, p); end; end; procedure TreeTraversal(root: Word); begin if lson[Root] <> TNILL then TreeTraversal(lson[Root]); ref[j] := NtxPage.ref[Root]; Inc(j); if rson[Root] <> TNILL then TreeTraversal(rson[Root]); end; begin NtxPage := NtxNode.PNode; InitTree; for i := 0 to Pred(NtxPage.count) do AddItemInTree(i); j := 0; root := rson[Succ(TNILL)]; if root <> TNILL then TreeTraversal(root); if j <> 0 then begin for i := 0 to Pred(NtxPage.count) do NtxPage.ref[i] := ref[i]; NtxNode.Changed := True; end; end; *) (* procedure TVKNTXIndex.CreateIndexUsingBTreeHeapSort(Activate: boolean = true); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; ntxitem, change_item: NTX_ITEM; HeapRootNode: TVKNTXNode; HeapRootNodePage: pNTX_BUFFER; LastItemInHeap: pNTX_ITEM; { function RestoreOrder(CurrentNode: TVKNTXBuffer): integer; var CurrentNodePage: pNTX_BUFFER; b, e, m, c, i, l: Integer; Item, MoveItem, LastItem: pNTX_ITEM; swap: Word; begin CurrentNodePage := CurrentNode.GetPage; LastItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); //Result := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Pred(CurrentNodePage.count)]); Result := -1; if ( LastItem.rec_no = DWord(-1) ) then b := 0 else b := Succ(LastItem.rec_no); l := b; e := CurrentNodePage.count - 2; MoveItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Pred(CurrentNodePage.count)]); repeat m := ( b + e ) shr 1; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[m]); c := CmpKeys1(MoveItem.key, Item.key, FNTXOrder.FHead.key_size); if c = 0 then begin if Item.rec_no < MoveItem.rec_no then c := -1 else c := 1; end; if c < 0 then begin //Item < MoveItem if e = m then break else e := m; end else begin if b = m then Inc(b) else b := m; end; until b > e; if c < 0 then e := e + 1 else e := e + 2; for i := Pred(CurrentNodePage.count) downto e do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); MoveItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Pred(i)]); //Result := MoveItem; if i <> l then begin swap := CurrentNodePage.ref[Pred(i)]; CurrentNodePage.ref[Pred(i)] := CurrentNodePage.ref[i]; CurrentNodePage.ref[i] := swap; end else begin change_item.rec_no := Item.rec_no; Move(Item.key, change_item.key, FNTXOrder.FHead.key_size); Item.rec_no := MoveItem.rec_no; Move(MoveItem.key, Item.key, FNTXOrder.FHead.key_size); MoveItem.rec_no := change_item.rec_no; Move(change_item.key, MoveItem.key, FNTXOrder.FHead.key_size); Result := l; end; CurrentNode.Changed := True; end; end; } procedure GetMinItem(CurrentNode: TVKNTXNode; var MinItem: pNTX_ITEM; var MinItemNo: Word; b: Integer); var CurrentNodePage: pNTX_BUFFER; e, c, i, j: Integer; Item1, Item2 {, LastItem } : pNTX_ITEM; q: array[0..MAX_ITEMS_IN_PAGE] of Word; q_Count: Integer; begin CurrentNodePage := CurrentNode.PNode; //LastItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); //if ( LastItem.rec_no = DWord(-1) ) then // b := 0 //else // b := Succ(LastItem.rec_no); e := Pred(CurrentNodePage.count); i := b; j := 0; while True do begin if i <= e then begin if (i + 1) <= e then begin Item1 := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); Item2 := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Succ(i)]); c := CmpKeys1(Item1.key, Item2.key, FNTXOrder.FHead.key_size); if c = 0 then begin if Item2.rec_no < Item1.rec_no then c := -1 else c := 1; end; if c < 0 then begin //Item2 > Item1 q[j] := Succ(i); Inc(j); end else begin q[j] := i; Inc(j); end; end else begin q[j] := i; Inc(j); end; end else break; Inc(i, 2); end; q_Count := j; while q_Count > 1 do begin i := 0; j := 0; while True do begin if i < q_Count then begin if (i + 1) < q_Count then begin Item1 := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[q[i]]); Item2 := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[q[Succ(i)]]); c := CmpKeys1(Item1.key, Item2.key, FNTXOrder.FHead.key_size); if c = 0 then begin if Item2.rec_no < Item1.rec_no then c := -1 else c := 1; end; if c < 0 then begin //Item2 > Item1 q[j] := q[Succ(i)]; Inc(j); end else begin q[j] := q[i]; Inc(j); end; end else begin q[j] := q[i]; Inc(j); end; end else break; Inc(i, 2); end; q_Count := j; end; MinItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[q[0]]); MinItemNo := q[0]; end; procedure siftItem( pageOffset: DWord; itemForSift: pNTX_ITEM; ParentNode: TVKNTXNode); var i: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; {Item,} LastItem, MinItem: pNTX_ITEM; c: Integer; MinItemNo: Word; begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, pageOffset, CurrentNodePage); try if CurrentNodePage.count > 0 then begin LastItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( LastItem.rec_no = DWord(-1) ) or ( LastItem.rec_no < CurrentNodePage.count ) then begin // if LastItem.rec_no = DWord(-1) then i := 0 else begin if LastItem.rec_no < DWord(Pred(CurrentNodePage.count)) then i := Succ(LastItem.rec_no) else i := -1; end; if i >= 0 then begin GetMinItem(CurrentNode, MinItem, MinItemNo, i); //MinItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Pred(CurrentNodePage.count)]); c := CmpKeys1(MinItem.key, itemForSift.key, FNTXOrder.FHead.key_size); if c = 0 then begin if itemForSift.rec_no < MinItem.rec_no then c := -1 else c := 1; end; if c > 0 then begin //itemForSift > MinItem change_item.rec_no := itemForSift.rec_no; Move(itemForSift.key, change_item.key, FNTXOrder.FHead.key_size); itemForSift.rec_no := MinItem.rec_no; Move(MinItem.key, itemForSift.key, FNTXOrder.FHead.key_size); MinItem.rec_no := change_item.rec_no; Move(change_item.key, MinItem.key, FNTXOrder.FHead.key_size); CurrentNode.Changed := true; ParentNode.Changed := true; // and make a sift if ( MinItem.page <> 0 ) then siftItem(MinItem.page, MinItem, CurrentNode); if ( LastItem.page <> 0 ) then siftItem(LastItem.page, MinItem, CurrentNode); // end; end; end; end; finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure CreateHeapInternal(CurrentPageOffset: DWord; ParentNode: TVKNTXNode = nil; PreviousItem: pNTX_ITEM = nil); var i: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item, MinItem: pNTX_ITEM; c: Integer; begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try if CurrentNodePage.count > 0 then begin for i := 0 to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if ( Item.page <> 0 ) then CreateHeapInternal(Item.page, CurrentNode, Item); end; end; SortNtxNode(CurrentNode); MinItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[Pred(CurrentNodePage.count)]); Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then CreateHeapInternal(Item.page, CurrentNode, MinItem); //Save in last item (page.ref[count]) in rec_no field node def value ( -1 ) for use it field to store current position Item.rec_no := DWord(-1); CurrentNode.Changed := true; //Change MinItem and PreviousItem (if need it) if PreviousItem <> nil then begin c := CmpKeys1(MinItem.key, PreviousItem.key, FNTXOrder.FHead.key_size); if c = 0 then begin if PreviousItem.rec_no < MinItem.rec_no then c := -1 else c := 1; end; if c > 0 then begin //if PreviousItem > MinItem then make change change_item.rec_no := PreviousItem.rec_no; Move(PreviousItem.key, change_item.key, FNTXOrder.FHead.key_size); PreviousItem.rec_no := MinItem.rec_no; Move(MinItem.key, PreviousItem.key, FNTXOrder.FHead.key_size); MinItem.rec_no := change_item.rec_no; Move(change_item.key, MinItem.key, FNTXOrder.FHead.key_size); CurrentNode.Changed := true; ParentNode.Changed := true; // and make a sift if ( MinItem.page <> 0 ) then siftItem(MinItem.page, MinItem, CurrentNode); if ( Item.page <> 0 ) then siftItem(Item.page, MinItem, CurrentNode); // end; end; // finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure SiftTraversalInternal(pageOffset: DWord); var i, j: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item, LastItem, MinItem {, ItemInHeap}: pNTX_ITEM; MinItemNo: Word; {c: Integer;} begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, pageOffset, CurrentNodePage); try LastItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); for i := 0 to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if ( Item.page <> 0 ) then SiftTraversalInternal(Item.page); // //Write at last item curent position LastItem.rec_no := i; CurrentNode.Changed := true; // // Find minimum item in root of heap // First of all define j (j is begin of loop minimum finding) if ( HeapRootNode.NodeOffset = CurrentNode.NodeOffset ) then begin if LastItemInHeap.rec_no <> DWord(-1) then begin if LastItemInHeap.rec_no < HeapRootNodePage.count then begin j := LastItemInHeap.rec_no; end else begin j := -1; end; end else begin j := 0; end; end else begin if LastItemInHeap.rec_no <> DWord(-1) then begin if LastItemInHeap.rec_no < DWord(Pred(HeapRootNodePage.count)) then begin j := Succ(LastItemInHeap.rec_no); end else begin j := -1; end; end else begin j := 0; end; end; // if j >= 0 then begin //MinItem := pNTX_ITEM(pAnsiChar(HeapRootNodePage) + HeapRootNodePage.ref[Pred(HeapRootNodePage.count)]); //MinItemNo := Pred(HeapRootNodePage.count); GetMinItem(HeapRootNode, MinItem, MinItemNo, j ); // //Change MinItem and current Item if ( HeapRootNode.NodeOffset <> CurrentNode.NodeOffset ) or ( ( HeapRootNode.NodeOffset = CurrentNode.NodeOffset ) and ( MinItemNo > i ) ) then begin change_item.rec_no := Item.rec_no; Move(Item.key, change_item.key, FNTXOrder.FHead.key_size); Item.rec_no := MinItem.rec_no; Move(MinItem.key, Item.key, FNTXOrder.FHead.key_size); MinItem.rec_no := change_item.rec_no; Move(change_item.key, MinItem.key, FNTXOrder.FHead.key_size); CurrentNode.Changed := true; HeapRootNode.Changed := true; // and make a sift if ( MinItem.page <> 0 ) then siftItem(MinItem.page, MinItem, HeapRootNode); if ( LastItemInHeap.page <> 0 ) then siftItem(LastItemInHeap.page, MinItem, HeapRootNode); // end; end; // end; // // Redefine HeapRootNode if ( HeapRootNode.NodeOffset = CurrentNode.NodeOffset ) then begin FNTXBuffers.FreeNTXBuffer(HeapRootNode.FNTXBuffer); HeapRootNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, LastItemInHeap.page, HeapRootNodePage); LastItemInHeap := pNTX_ITEM(pAnsiChar(HeapRootNodePage) + HeapRootNodePage.ref[HeapRootNodePage.count]); end; // LastItem.rec_no := CurrentNodePage.count; CurrentNode.Changed := true; // if ( LastItem.page <> 0 ) then SiftTraversalInternal(LastItem.page); finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure AddKeyInBTreeAtEnd(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin ntxitem.page := 0; ntxitem.rec_no := Rec; Move(pAnsiChar(Key)^, ntxitem.key, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; TransKey(pAnsiChar(@ntxitem.key[0])); if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem, True); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndexUsingBTreeHeapSort: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin // First of all create a not sorted B-Tree structure ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInBTreeAtEnd(Key, Rec); // end; until ( BufCnt <= 0 ); // //Than create a heap CreateHeapInternal(FNTXOrder.FHead.root, nil, nil); // //And at the end sift all items throw heap and create sorted B-Tree HeapRootNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, FNTXOrder.FHead.root, HeapRootNodePage); try LastItemInHeap := pNTX_ITEM(pAnsiChar(HeapRootNodePage) + HeapRootNodePage.ref[HeapRootNodePage.count]); SiftTraversalInternal(FNTXOrder.FHead.root); finally FNTXBuffers.FreeNTXBuffer(HeapRootNode.FNTXBuffer); end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingBTreeHeapSort: Record size too lage'); finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingBTreeHeapSort: Create index only on active DataSet'); end; *) (* procedure TVKNTXIndex.CreateIndexUsingFindMinsAndJoinItToBTree( TreeSorterClass: TVKBinaryTreeSorterClass; Activate: boolean = true; PreSorterBlockSize: LongWord = 65536); var oB: TVKDBFNTX; DBFBuffer: pAnsiChar; RecPareBuf: Integer; ReadSize, RealRead, BufCnt: Integer; i: Integer; Key: AnsiString; Rec: DWORD; LastFUpdated: boolean; ntxitem: NTX_ITEM; Sorter: TVKBinaryTreeSorterAbstract; SorterRecCount: DWord; HashTableSize: THashTableSizeType; GetHashCodeMethod: TOnGetHashCode; //SortItemPoint: DWord; SortItem: PSORT_ITEM; sitem: SORT_ITEM; r: boolean; fb: boolean; LastItemP: DWord; LastItem: PSORT_ITEM; c: Integer; procedure AddKeyInSorter(Key: pAnsiChar; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin sitem.RID := Rec; sitem.Hash := FKeyParser.Hash; Move(Key^, sitem.key, FNTXOrder.FHead.key_size); sitem.key[FNTXOrder.FHead.key_size] := 0; Sorter.AddItem(sitem); end; end; procedure AddOrReplaceSortItemInSorter(CurrentNode: TVKNTXNode; Item: pNTX_ITEM); begin if Sorter.CountAddedItems < Sorter.CountRecords then begin AddKeyInSorter(Item.Key, Item.rec_no); end else begin if Sorter.GetLastSortItem(LastItemP) then begin //if eof AddKeyInSorter(Item.Key, Item.rec_no); end else begin LastItem := Sorter.PSortItem[LastItemP]; //Prepare sitem for add to binary tree (culculate hash) sitem.RID := Item.rec_no; Move(Item.key, sitem.key, FNTXOrder.FHead.key_size); TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, false); try FGetHashFromSortItem := False; GetVKHashCode(self, @sitem, sitem.Hash); finally FGetHashFromSortItem := True; end; TransKey(pAnsiChar(@sitem.key[0]), FNTXOrder.FHead.key_size, true); sitem.key[FNTXOrder.FHead.key_size] := 0; // Sorter.CompareItems(LastItem, @sitem, c); if c > 0 then begin //LastItem > sitem // Save LastItem to Item Move(LastItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := LastItem.RID; CurrentNode.Changed := True; // Sorter.DeleteFromTreeByEntry(LastItemP); Sorter.SortItem[LastItemP] := sitem; Sorter.AddItemInTreeByEntry(LastItemP); end; end; end; end; procedure WorkTraversal(CurrentPageOffset: DWord); var i, j: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item, LItem: pNTX_ITEM; begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try LItem := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if LItem.rec_no = DWord(-1) then j := 0 else j := Succ(LItem.rec_no); for i := j to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if ( Item.page <> 0 ) then WorkTraversal(Item.page); // if not fb then begin // // Save SortItem to Item Move(SortItem.key, Item.key, FNTXOrder.FHead.key_size); Item.rec_no := SortItem.RID; LItem.rec_no := i; CurrentNode.Changed := True; // if not Sorter.NextSortItem then begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; end else begin fb := True; Sorter.Clear; end; end else begin AddOrReplaceSortItemInSorter(CurrentNode, Item); r := False; end; end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then WorkTraversal(Item.page); finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure MarkAllPagesAsNotHandled(CurrentPageOffset: DWord); var i: Integer; CurrentNode: TVKNTXNode; CurrentNodePage: pNTX_BUFFER; Item: pNTX_ITEM; begin CurrentNode := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, CurrentPageOffset, CurrentNodePage); try for i := 0 to Pred(CurrentNodePage.count) do begin Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[i]); if ( Item.page <> 0 ) then MarkAllPagesAsNotHandled(Item.page); // AddOrReplaceSortItemInSorter(CurrentNode, Item); // end; Item := pNTX_ITEM(pAnsiChar(CurrentNodePage) + CurrentNodePage.ref[CurrentNodePage.count]); if ( Item.page <> 0 ) then MarkAllPagesAsNotHandled(Item.page); //Save in last item (page.ref[count]) in rec_no field node def value ( -1 ) for use it field to store current position Item.rec_no := DWord(-1); CurrentNode.Changed := true; // finally FNTXBuffers.FreeNTXBuffer(CurrentNode.FNTXBuffer); end; end; procedure AddKeyInBTreeAtEnd(Key: AnsiString; Rec: DWORD); var AddOk: boolean; begin AddOk := true; if FForExists then AddOk := AddOk and (FForParser.Execute); if AddOk then begin ntxitem.page := 0; ntxitem.rec_no := Rec; Move(pAnsiChar(Key)^, ntxitem.key, FNTXOrder.FHead.key_size); ntxitem.key[FNTXOrder.FHead.key_size] := #0; TransKey(pAnsiChar(@ntxitem.key[0])); if Unique then AddOk := AddOk and (not SeekFirstInternal(Key)); if AddOk then AddItem(@ntxitem, True); end; end; procedure CreateEmptyIndex; var IndAttr: TIndexAttributes; begin if not FReindex then begin DefineBag; FNTXBag.NTXHandler.CreateProxyStream; if not FNTXBag.NTXHandler.IsOpen then begin raise Exception.Create('TVKNTXIndex.CreateIndexUsingFindMinsAndJoinItToBTree: Create error "' + Name + '"'); end else begin FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FNTXOrder.FHead.key_size := IndAttr.key_size; FNTXOrder.FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FNTXOrder.FHead.key_expr, Length(IndAttr.key_expr)); FNTXOrder.FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FNTXOrder.FHead.for_expr, Length(IndAttr.for_expr)); FNTXOrder.FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FNTXOrder.FHead.key_size := Length(FKeyParser.Key); FNTXOrder.FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(FKeyExpresion)^, FNTXOrder.FHead.key_expr, Length(FKeyExpresion)); FNTXOrder.FHead.key_expr[Length(FKeyExpresion)] := #0; System.Move(pAnsiChar(FForExpresion)^, FNTXOrder.FHead.for_expr, Length(FForExpresion)); FNTXOrder.FHead.for_expr[Length(FForExpresion)] := #0; end; FNTXOrder.FHead.item_size := FNTXOrder.FHead.key_size + 8; FNTXOrder.FHead.max_item := (NTX_PAGE - FNTXOrder.FHead.item_size - 4) div (FNTXOrder.FHead.item_size + 2); FNTXOrder.FHead.half_page := FNTXOrder.FHead.max_item div 2; FNTXOrder.FHead.max_item := FNTXOrder.FHead.half_page * 2; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; Order := FOrder; Desc := FDesc; Unique := FUnique; FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end else begin //Truncate ntx file FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.SetEndOfFile; FNTXBuffers.Clear; if FClipperVer in [v500, v501] then FNTXOrder.FHead.sign := 6 else FNTXOrder.FHead.sign := 7; FNTXOrder.FHead.version := 1; FNTXOrder.FHead.root := NTX_PAGE; FNTXOrder.FHead.next_page := 0; FNTXOrder.FHead.reserv1 := #0; FNTXOrder.FHead.reserv3 := #0; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Flt := LimitPages.LimitPagesType; case FNTXBuffers.Flt of lbtAuto: begin FNTXBuffers.MaxBuffers := Round( LogN(FNTXOrder.FHead.half_page + 1, oB.RecordCount + MAX_NTX_STOCK) ) * NTX_STOCK_INSURANCE; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; LimitPages.LimitBuffers := FNTXBuffers.MaxBuffers; LimitPages.PagesPerBuffer := FNTXBuffers.PagesPerBuffer; end; lbtLimited: begin FNTXBuffers.MaxBuffers := LimitPages.LimitBuffers; FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; lbtUnlimited: begin FNTXBuffers.PagesPerBuffer := LimitPages.PagesPerBuffer; end; end; FAllowSetCollationType := True; try CollationType := Collation.CollationType; finally FAllowSetCollationType := False; end; CustomCollatingSequence := Collation.CustomCollatingSequence; FLastOffset := SizeOf(NTX_HEADER); GetFreePage; end; end; begin oB := TVKDBFNTX(FIndexes.Owner); if oB.Active then begin oB.IndState := true; FCreateIndexProc:= true; DBFBuffer := VKDBFMemMgr.oMem.GetMem(self, oB.BufferSize); LastFUpdated := FUpdated; FUpdated := true; try FillChar(DBFBuffer^, oB.BufferSize, ' '); oB.IndRecBuf := DBFBuffer; if FForExpresion <> '' then FForExists := true; EvaluteKeyExpr; CreateEmptyIndex; if FHashTypeForTreeSorters = httsDefault then begin HashTableSize := htst256; GetHashCodeMethod := nil; end else begin HashTableSize := THashTableSizeType(Integer(FHashTypeForTreeSorters) - 1); GetHashCodeMethod := GetVKHashCode; end; // SorterRecCount := ( PreSorterBlockSize ) div ( FNTXOrder.FHead.key_size + ( 2 * SizeOf(DWord) ) ); // if TreeSorterClass = TVKBinaryTreeSorter then Sorter := TVKBinaryTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKRedBlackTreeSorter then Sorter := TVKRedBlackTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if TreeSorterClass = TVKAVLTreeSorter then Sorter := TVKAVLTreeSorter.Create( SorterRecCount, FNTXOrder.FHead.key_size, IndexSortProc, nil, nil, Unique, HashTableSize, GetHashCodeMethod, TMaxBitsInHashCode(MaxBitsInHashCode), True); if Sorter = nil then Exception.Create('TVKNTXIndex.CreateIndexUsingFindMinsAndJoinItToBTree: Sorter object is null!'); try RecPareBuf := oB.BufferSize div oB.Header.rec_size; if RecPareBuf >= 1 then begin // First of all create a not sorted B-Tree structure ReadSize := RecPareBuf * oB.Header.rec_size; oB.Handle.Seek(oB.Header.data_offset, 0); Rec := 0; repeat RealRead := oB.Handle.Read(DBFBuffer^, ReadSize); BufCnt := RealRead div oB.Header.rec_size; for i := 0 to BufCnt - 1 do begin oB.IndRecBuf := DBFBuffer + oB.Header.rec_size * i; if oB.Crypt.Active then oB.Crypt.Decrypt(Rec + 1, Pointer(oB.IndRecBuf), oB.Header.rec_size); Inc(Rec); Key := EvaluteKeyExpr; // AddKeyInBTreeAtEnd(Key, Rec); // end; until ( BufCnt <= 0 ); // //Than mark all pages as not handled and in the same time accumulate in //Sorter all smallest items MarkAllPagesAsNotHandled(FNTXOrder.FHead.root); // // repeat if not Sorter.FirstSortItem then begin SortItem := Sorter.CurrentSortItem; //PSortItem[SortItemPoint]; r := True; fb := False; WorkTraversal(FNTXOrder.FHead.root); end else r := False; until r; // end else Exception.Create('TVKNTXIndex.CreateIndexUsingFindMinsAndJoinItToBTree: Record size too lage'); finally FreeAndNil(Sorter); end; finally Flush; FUpdated := LastFUpdated; FNTXBag.NTXHandler.Seek(0, 0); FNTXBag.NTXHandler.Write(FNTXOrder.FHead, SizeOf(NTX_HEADER)); FNTXBuffers.Clear; FCreateIndexProc:= false; FGetHashFromSortItem := False; oB.IndState := false; oB.IndRecBuf := nil; VKDBFMemMgr.oMem.FreeMem(DBFBuffer); end; if IsOpen then begin if ( ( ( oB.AccessMode.FLast and fmShareExclusive ) = fmShareExclusive ) or ( ( oB.AccessMode.FLast and fmShareDenyWrite ) = fmShareDenyWrite ) ) then StartUpdate; InternalFirst; KeyExpresion := FNTXOrder.FHead.key_expr; ForExpresion := FNTXOrder.FHead.for_expr; if ForExpresion <> '' then FForExists := true; if Activate then Active := true; end; end else raise Exception.Create('TVKNTXIndex.CreateIndexUsingFindMinsAndJoinItToBTree: Create index only on active DataSet'); end; *) procedure TVKNTXIndex.GetVKHashCode(Sender: TObject; Item: PSORT_ITEM; out HashCode: DWord); var HashCodeArr: array[0..3] of Byte absolute HashCode; S: AnsiString; i64: Int64; key: array[0..pred(MAX_SORTER_KEY_SIZE)] of Byte; sign: boolean; Curr: Currency absolute i64; y, m, d: Word; q: DWord; procedure convert; var i: Integer; begin sign := False; if AnsiChar(Item.key[0]) in [',', '#', '$', '%', '&', '''', '(', ')', '*', '+'] then begin sign := True; for i := 0 to Pred(FNTXOrder.FHead.key_size) do key[i] := Byte(Ord(#92) - Ord(Item.key[i])); end else begin Move(Item.key, key, FNTXOrder.FHead.key_size); end; if FKeyParser.Prec <> 0 then key[FKeyParser.Len - FKeyParser.Prec] := Byte({$IFDEF DELPHIXE}FormatSettings.{$ENDIF}DecimalSeparator); SetString(S, pAnsiChar(@key[0]), FNTXOrder.FHead.key_size); end; procedure HashFromInt64(j64: Int64); var j64Rec: Int64Rec absolute j64; begin if j64 < 0 then begin j64 := - j64; if j64Rec.Hi <> 0 then begin j64Rec.Hi := 0; j64Rec.Lo := $80000000; end else begin j64 := - j64; end; end else begin if j64Rec.Hi <> 0 then begin j64Rec.Hi := 0; j64Rec.Lo := $7FFFFFFF; end; end; HashCode := j64Rec.Lo; end; begin if FGetHashFromSortItem then HashCode := Item.Hash else begin case FKeyParser.ValueType of varCurrency: begin convert; Curr := StrToCurr(S); if sign then Curr := - Curr; HashFromInt64(i64); end; varDouble, varSingle: begin convert; i64 := Trunc(StrToFloat(S)); if sign then i64 := - i64; HashFromInt64(i64); end; {$IFDEF DELPHI6} varShortInt, varByte, {$ENDIF} -1: begin convert; i64 := Word(StrToInt(S)); if sign then i64 := - i64; HashFromInt64(i64); end; {$IFDEF DELPHI6} varWord, {$ENDIF} varSmallint: begin convert; i64 := Word(StrToInt(S)); if sign then i64 := - i64; HashFromInt64(i64); end; {$IFDEF DELPHI6} varLongWord, {$ENDIF} varInteger: begin convert; i64 := DWord(StrToInt(S)); if sign then i64 := - i64; HashFromInt64(i64); end; varBoolean: begin if AnsiChar(Item.key[0]) = 'T' then HashCode := $FFFFFFFF else HashCode := 0; end; varDate: begin SetString(S, pAnsiChar(@key[0]), 4); y := StrToInt(S); SetString(S, pAnsiChar(@key[4]), 2); m := StrToInt(S); SetString(S, pAnsiChar(@key[6]), 2); d := StrToInt(S); i64 := Trunc(EncodeDate(y, m, d)); HashFromInt64(i64); end; else {$IFDEF DELPHI6} if (FKeyParser.ValueType = varInt64) then begin {$ELSE} if (FKeyParser.ValueType = 14) then begin {$ENDIF} convert; i64 := StrToInt64(S); if sign then i64 := -i64; HashFromInt64(i64); end else begin q := Pred(FNTXOrder.FHead.key_size); if q > 3 then q := 3; //HashCode := ( Item.key[( q ) and 3] shl 24 ) or // ( Item.key[( q + 1 ) and 3] shl 16 ) or // ( Item.key[( q + 2 ) and 3] shl 8 ) or // ( Item.key[( q + 3 ) and 3] ); HashCodeArr[0] := Item.key[q and 3]; Dec(q); HashCodeArr[1] := Item.key[q and 3]; Dec(q); HashCodeArr[2] := Item.key[q and 3]; Dec(q); HashCodeArr[3] := Item.key[q and 3]; end; end; end; end; procedure TVKNTXIndex.SetRangeFields(FieldList: AnsiString; FieldValuesLow, FieldValuesHigh: variant); var KeyLow, KeyHigh: AnsiString; begin FKeyParser.PartualKeyValue := True; try KeyLow := FKeyParser.EvaluteKey(FieldList, FieldValuesLow); KeyHigh := FKeyParser.EvaluteKey(FieldList, FieldValuesHigh); finally FKeyParser.PartualKeyValue := False; end; NTXRange.LoKey := KeyLow; NTXRange.HiKey := KeyHigh; NTXRange.ReOpen; end; procedure TVKNTXIndex.SetRangeFields(FieldList: AnsiString; FieldValuesLow, FieldValuesHigh: array of const); var FieldValLow, FieldValHigh: Variant; begin ArrayOfConstant2Variant(FieldValuesLow, FieldValLow); ArrayOfConstant2Variant(FieldValuesHigh, FieldValHigh); SetRangeFields(FieldList, FieldValLow, FieldValHigh); end; function TVKNTXIndex.ReCrypt(pNewCrypt: TVKDBFCrypt): boolean; var oW: TVKDBFNTX; buff: array [0..pred(NTX_PAGE)] of AnsiChar; r: Integer; offset: LongWord; begin oW := TVKDBFNTX(FIndexes.Owner); if FLock then try Flush; FNTXBuffers.Clear; offset := NTX_PAGE; repeat FNTXBag.NTXHandler.Seek(offset, 0); r := FNTXBag.NTXHandler.Read(buff, NTX_PAGE); if r <> NTX_PAGE then begin Result := True; break; end; if oW.Crypt.Active then begin oW.Crypt.Decrypt(offset, @buff[0], NTX_PAGE); pNewCrypt.Encrypt(offset, @buff[0], NTX_PAGE); end; FNTXBag.NTXHandler.Seek(offset, 0); FNTXBag.NTXHandler.Write(buff, NTX_PAGE); Inc(offset, NTX_PAGE); until False; Result := True; finally FUnLock; end else Result := false; end; procedure TVKNTXIndex.VerifyIndex; var level: Integer; predItem: pNTX_ITEM; ItemCount: DWORD; PageCount: DWORD; PageCountBySize: DWORD; key: AnsiString; function cmp(item1, item2: pNTX_ITEM): Integer; begin Result := CmpKeys1(item1.key, item2.key); if Result = 0 then begin if item1.rec_no < item2.rec_no then Result := 1 else Result := -1; end; end; function keyToStr(item: pNTX_ITEM): AnsiString; var keyArr: array[0..NTX_PAGE-1] of AnsiChar; destKeyArr: array[0..NTX_PAGE-1] of AnsiChar; kSize: WORD; begin kSize := FNTXOrder.FHead.key_size; if FKeyTranslate then begin Move(item.key, keyArr, kSize); keyArr[kSize] := #0; TVKDBFNTX(FIndexes.Owner).Translate(keyArr, destKeyArr, false); Result := AnsiString(destKeyArr); end else begin Move(item.key, keyArr, kSize); keyArr[kSize] := #0; Result := AnsiString(keyArr); end; end; procedure VerifyPageRef(item: pNTX_ITEM; isLeaf: Boolean); begin if isLeaf then begin if item.page <> 0 then raise Exception.Create('TVKNTXIndex.VerifyIndex: item.page must be null on the leaf node item!'); end else begin if item.page = 0 then raise Exception.Create('TVKNTXIndex.VerifyIndex: item.page must be not null on the not leaf node item!'); end; end; procedure PassFreeList(page_off: DWORD); var ntxb: TVKNTXNode; page: pNTX_BUFFER; nextFree: DWORD; begin if page_off <> 0 then begin nextFree := 0; ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); try if page.count <> 0 then raise Exception.Create('TVKNTXIndex.VerifyIndex: page count for free page must be 0!'); Inc(PageCount); nextFree := pNTX_ITEM(pAnsiChar(page) + page.ref[0]).page; finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; PassFreeList(nextFree); end; end; procedure Pass(page_off: DWORD); var page: pNTX_BUFFER; item: pNTX_ITEM; ntxb: TVKNTXNode; i: Integer; isLeaf: Boolean; begin Inc(level); try ntxb := FNTXBuffers.GetNTXBuffer(FNTXBag.NTXHandler, page_off, page); Inc(PageCount); try item := pNTX_ITEM(pAnsiChar(page) + page.ref[0]); isLeaf := (item.page = 0); for i := 0 to Pred(page.count) do begin item := pNTX_ITEM(pAnsiChar(page) + page.ref[i]); if ( item.page <> 0 ) then begin Pass(item.page); end; //check page ref VerifyPageRef(item, isLeaf); //check item order if predItem <> nil then begin if cmp(predItem, item) <= 0 then raise Exception.Create('TVKNTXIndex.VerifyIndex: Key ' + keyToStr(item) + ' must be lager then ' + keyToStr(predItem)); end; Inc(ItemCount); predItem := item; //check item key TVKDBFNTX(FIndexes.Owner).SetTmpRecord(item.rec_no); try key := EvaluteKeyExpr; finally TVKDBFNTX(FIndexes.Owner).CloseTmpRecord; end; if CmpKeys2(pAnsiChar(key), item.key, FNTXOrder.FHead.key_size) <> 0 then raise Exception.Create('TVKNTXIndex.VerifyIndex: For recNo = ' + IntToStr(item.rec_no) + ' key must be ' + key + ' , but was ' + keyToStr(item)); // end; item := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if ( item.page <> 0 ) then begin Pass(item.page); end; //check page ref VerifyPageRef(item, isLeaf); //check item count per page if ((level > 1) and (page.count < FNTXOrder.FHead.half_page)) then raise Exception.Create('TVKNTXIndex.VerifyIndex: For page = ' + IntToStr(page_off) + ' item count (' + IntToStr(page.count) + ') less then half_page count (' + IntToStr(FNTXOrder.FHead.half_page) + ')'); finally FNTXBuffers.FreeNTXBuffer(ntxb.FNTXBuffer); end; finally Dec(level); end; end; begin if FLock then begin try Flush; FNTXBuffers.Clear; level := 0; ItemCount := 0; PageCount := 0; predItem := nil; Pass(FNTXOrder.FHead.root); if not FForExists and not Unique then begin if DWORD(TVKDBFNTX(FIndexes.Owner).RecordCount) <> ItemCount then raise Exception.Create('TVKNTXIndex.VerifyIndex: ItemCount in index ' + IntToStr(ItemCount) + ', but record count in dbf ' + IntToStr(TVKDBFNTX(FIndexes.Owner).RecordCount)); end; PassFreeList(FNTXOrder.FHead.next_page); Inc(PageCount); //plus header PageCountBySize := FNTXBag.NTXHandler.size() div NTX_PAGE; if PageCountBySize <> PageCount then begin raise Exception.Create('TVKNTXIndex.VerifyIndex: Page count in index ' + IntToStr(PageCount) + ', but need ' + IntToStr(PageCountBySize)); end; finally FUnLock; end; end; end; { TVKNTXRange } function TVKNTXRange.GetActive: boolean; begin Result := FActive; end; function TVKNTXRange.InRange(S: AnsiString): boolean; var l, c: Integer; function min(a, b: Integer): Integer; begin if a < b then result := a else result := b; end; begin l := min(Length(HiKey), NTX.FNTXOrder.FHead.key_size); if l > 0 then begin c := NTX.CompareKeys(pAnsiChar(HiKey), pAnsiChar(S), l); Result := (c >= 0); //HiKey >= S if Result then begin l := min(Length(LoKey), NTX.FNTXOrder.FHead.key_size); if l > 0 then begin c := NTX.CompareKeys(pAnsiChar(LoKey), pAnsiChar(S), l); Result := (c <= 0); //LoKey <= S end; end; end else Result := false; end; procedure TVKNTXRange.ReOpen; var oDB: TVKDBFNTX; begin if not Active then begin Active := true; end else begin NTX.Active := true; oDB := TVKDBFNTX(NTX.OwnerTable); if oDB.Active then oDB.First; end; end; procedure TVKNTXRange.SetActive(const Value: boolean); var oDB: TVKDBFNTX; l: boolean; begin l := FActive; FActive := Value; oDB := TVKDBFNTX(NTX.OwnerTable); NTX.Active := true; if (l <> Value) and oDB.Active then begin oDB.First; end; end; //{$IFNDEF NTXBUFFERASTREE} { TVKNTXBuffer } constructor TVKNTXBuffer.Create(pOffset: DWORD; pNodeCount: Word); var i: Integer; begin inherited Create; FOffset := pOffset; FNodeCount := pNodeCount; FBusyCount := 0; FUseCount := 0; FPages := VKDBFMemMgr.oMem.GetMem(self, NTX_PAGE * FNodeCount); for i := 0 to Pred(MAX_ITEMS_IN_PAGE) do FNTXNode[i] := nil; for i := 0 to Pred(FNodeCount) do begin FNTXNode[i] := TVKNTXNode.Create(self, FOffset + DWord(i) * NTX_PAGE, i); end; end; destructor TVKNTXBuffer.Destroy; var i: Integer; begin VKDBFMemMgr.oMem.FreeMem(FPages); for i := 0 to Pred(FNodeCount) do FreeAndNil(FNTXNode[i]); inherited Destroy; end; function TVKNTXBuffer.GetBusy: boolean; begin Result := ( FBusyCount > 0 ); end; function TVKNTXBuffer.GetChanged: boolean; var i: Integer; begin Result := False; for i := 0 to Pred(NodeCount) do begin Result := Result or FNTXNode[i].Changed; if Result then Break; end; end; function TVKNTXBuffer.GetNTXNode(ndx: DWord): TVKNTXNode; begin Result := FNTXNode[ndx]; end; function TVKNTXBuffer.GetPPages(ndx: DWord): pNTX_BUFFER; begin result := pNTX_BUFFER( pAnsiChar( FPages ) + ( NTX_PAGE * ndx) ); end; procedure TVKNTXBuffer.SetBusy(const Value: boolean); begin if Value then Inc( FBusyCount ) else begin if ( FBusyCount > 0 ) then Dec(FBusyCount); end; end; procedure TVKNTXBuffer.SetChanged(const Value: boolean); var i: Integer; begin for i := 0 to Pred(NodeCount) do FNTXNode[i].Changed := Value; end; procedure TVKNTXBuffer.SetOffset(const Value: DWORD); var i: Integer; ntxNode: TVKNTXNode; begin FOffset := Value; for i := 0 to Pred(NodeCount) do begin ntxNode := FNTXNode[i]; ntxNode.FNodeOffset := FOffset + DWord(i) * NTX_PAGE; ntxNode.FIndexInBuffer := i; end; end; { TVKNTXBuffers } function TVKNTXBuffers.FindIndex(block_offset: DWORD; out Ind: Integer): boolean; var B: TVKNTXBuffer; beg, Mid: Integer; begin Ind := Count; if ( Ind > 0 ) then begin beg := 0; B := TVKNTXBuffer(Items[beg]); if ( block_offset > B.Offset ) then begin repeat Mid := (Ind + beg) div 2; B := TVKNTXBuffer(Items[Mid]); if ( block_offset > B.Offset ) then beg := Mid else Ind := Mid; until ( ((Ind - beg) div 2) = 0 ); end else Ind := beg; if Ind < Count then begin B := TVKNTXBuffer(Items[Ind]); Result := (block_offset = B.Offset); end else Result := false; end else Result := false; end; procedure TVKNTXBuffers.Flush(Handle: TProxyStream); var i, j, k: Integer; ntxb: TVKNTXBuffer; WriteOffsetStart: DWord; WriteBufferStart: pNTX_BUFFER; WriteLength: LongWord; begin for i := 0 to Pred(Count) do begin ntxb := TVKNTXBuffer(Items[i]); if ntxb.Changed then begin WriteOffsetStart := ntxb.Offset; WriteBufferStart := ntxb.Pages; WriteLength := NTX_PAGE * PagesPerBuffer; k := 0; for j := 0 to Pred(PagesPerBuffer) do begin if ntxb.NTXNode[j].Changed then begin WriteOffsetStart := ntxb.NTXNode[j].NodeOffset; WriteBufferStart := pNTX_BUFFER(pAnsiChar(ntxb.Pages) + (NTX_PAGE * j)); //ntxb.NTXNode[j].PNode; k := j; Break; end; end; for j := Pred(PagesPerBuffer) downto 0 do begin if ntxb.NTXNode[j].Changed then begin WriteLength := NTX_PAGE * (j - k + 1); Break; end; end; Handle.Seek(WriteOffsetStart, 0); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then begin for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Encrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); Handle.Write( WriteBufferStart^, WriteLength ); for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); end else Handle.Write( WriteBufferStart^, WriteLength ); ntxb.Changed := False; end; end; end; function TVKNTXBuffers.GetNTXBuffer(Handle: TProxyStream; page_offset: DWORD; out page: pNTX_BUFFER; fRead: boolean): TVKNTXNode; var NTXBuffer: TVKNTXBuffer; i, j, k, PageIndex: Integer; block_offset, block_size: DWORD; procedure FillBuffer; var i, lng: Integer; begin NTXBuffer.Busy := True; IncUseCount(NTXBuffer); NTXBuffer.Offset := block_offset; if fRead then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, NTX_PAGE * PagesPerBuffer ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for i := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(i), Pointer(NTXBuffer.PPage[i]), NTX_PAGE ); end else begin lng := NTX_PAGE * Pred(PagesPerBuffer); if lng > 0 then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, lng ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for i := 0 to Pred(Pred(PagesPerBuffer)) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(i), Pointer(NTXBuffer.PPage[i]), NTX_PAGE ); end; end; Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end; procedure CreateNewBuffer(i: Integer); var j, lng: Integer; begin NTXBuffer := TVKNTXBuffer.Create(block_offset, PagesPerBuffer); NTXBuffer.Busy := True; IncUseCount(NTXBuffer); Insert(i, NTXBuffer); if fRead then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, NTX_PAGE * PagesPerBuffer ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(j), Pointer(NTXBuffer.PPage[j]), NTX_PAGE ); end else begin lng := NTX_PAGE * Pred(PagesPerBuffer); if lng > 0 then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, lng ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for j := 0 to Pred(Pred(PagesPerBuffer)) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(j), Pointer(NTXBuffer.PPage[j]), NTX_PAGE ); end; end; Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end; begin block_size := PagesPerBuffer * NTX_PAGE ; block_offset := ( page_offset div block_size ) * block_size; PageIndex := ( page_offset - block_offset ) div NTX_PAGE; if FindIndex(block_offset, i) then begin NTXBuffer := TVKNTXBuffer(Items[i]); NTXBuffer.Busy := True; IncUseCount(NTXBuffer); Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end else case Flt of lbtUnlimited: CreateNewBuffer(i); lbtAuto, lbtLimited: begin if Count < FMaxBuffers then CreateNewBuffer(i) else begin if FindLeastUsed(j) then begin NTXBuffer := TVKNTXBuffer(Items[j]); Flash(NTXBuffer); FillBuffer; k := j; while k < Pred(Count) do begin if TVKNTXBuffer(Items[k]).Offset > TVKNTXBuffer(Items[k + 1]).Offset then begin Exchange(k, k + 1); Inc(k); end else Break; end; k := j; while k > 0 do begin if TVKNTXBuffer(Items[k]).Offset < TVKNTXBuffer(Items[k - 1]).Offset then begin Exchange(k, k - 1); Dec(k); end else Break; end; end else raise Exception.Create('TVKNTXBuffers.GetNTXBuffer: There is no enough free NTX page buffers! Increase LimitPages property.'); end; end; end; end; procedure TVKNTXBuffers.SetPageChanged(Handle: TProxyStream; page_offset: DWORD); var NTXBuffer: TVKNTXBuffer; i, PageIndex: Integer; block_offset, block_size: DWORD; begin block_size := PagesPerBuffer * NTX_PAGE ; block_offset := ( page_offset div block_size ) * block_size; PageIndex := ( page_offset - block_offset ) div NTX_PAGE; if FindIndex(block_offset, i) then begin NTXBuffer := TVKNTXBuffer(Items[i]); NTXBuffer.NTXNode[PageIndex].Changed := true; end; end; procedure TVKNTXBuffers.FreeNTXBuffer(ntxb: TVKNTXBuffer); begin ntxb.Busy := False; end; procedure TVKNTXBuffers.Flash(ntxb: TVKNTXBuffer); var j, k: Integer; WriteOffsetStart: DWord; WriteBufferStart: pNTX_BUFFER; WriteLength: LongWord; begin if ntxb.Changed then begin WriteOffsetStart := ntxb.Offset; WriteBufferStart := ntxb.Pages; WriteLength := 0; k := 0; for j := 0 to Pred(PagesPerBuffer) do begin if ntxb.NTXNode[j].Changed then begin WriteOffsetStart := ntxb.NTXNode[j].NodeOffset; WriteBufferStart := pNTX_BUFFER(pAnsiChar(ntxb.Pages) + (NTX_PAGE * j)); k := j; Break; end; end; for j := Pred(PagesPerBuffer) downto 0 do begin if ntxb.NTXNode[j].Changed then begin WriteLength := NTX_PAGE * (j - k + 1); Break; end; end; if WriteLength <> 0 then begin NXTObject.FNTXBag.Handler.Seek(WriteOffsetStart, 0); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then begin for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Encrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); NXTObject.FNTXBag.Handler.Write( WriteBufferStart^, WriteLength ); for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); end else NXTObject.FNTXBag.Handler.Write( WriteBufferStart^, WriteLength ); end else raise Exception.Create('TVKNTXBuffers.Flash: Internal Error!'); ntxb.Changed := False; end; end; constructor TVKNTXBuffers.Create; begin inherited Create; Flt := lbtUnlimited; FMaxBuffers := 0; FPagesPerBuffer := DEFPAGESPERBUFFER; FUseCount := 0; end; destructor TVKNTXBuffers.Destroy; begin inherited Destroy; end; function TVKNTXBuffers.FindLeastUsed(out Ind: Integer): boolean; var i: Integer; mn: DWORD; B: TVKNTXBuffer; begin mn := MAXDWORD; Ind := -1; for i := 0 to Pred(Count) do begin B := TVKNTXBuffer(Items[i]); if not B.Busy then begin if B.UseCount <= mn then begin mn := B.UseCount; Ind := i; end; end; end; Result := (Ind <> -1); end; function TVKNTXBuffers.IncUseCount(b: TVKNTXBuffer): DWORD; var i: Integer; uc: DWORD; buf: TVKNTXBuffer; begin Inc(FUseCount); if FUseCount = MAXDWORD then begin FUseCount := 6; for i := 0 to Pred(Count) do begin buf := TVKNTXBuffer(Items[i]); uc := buf.UseCount; buf.UseCount := 0; if uc = MAXDWORD - 1 then buf.UseCount := 5; if uc = MAXDWORD - 2 then buf.UseCount := 4; if uc = MAXDWORD - 3 then buf.UseCount := 3; if uc = MAXDWORD - 4 then buf.UseCount := 2; if uc = MAXDWORD - 5 then buf.UseCount := 1; end; end; b.UseCount := FUseCount; Result := FUseCount; end; //{$ELSE} (* {TVKNTXBuffer} constructor TVKNTXBuffer.Create(pOffset: DWORD; pNodeCount: Word); var i: Integer; begin inherited Create; FOffset := pOffset; FNodeCount := pNodeCount; FBusyCount := 0; FUseCount := 0; FPages := VKDBFMemMgr.oMem.GetMem(self, NTX_PAGE * FNodeCount); for i := 0 to Pred(MAX_ITEMS_IN_PAGE) do FNTXNode[i] := nil; for i := 0 to Pred(FNodeCount) do begin FNTXNode[i] := TVKNTXNode.Create(self, FOffset + DWord(i) * NTX_PAGE, i); end; end; destructor TVKNTXBuffer.Destroy; var i: Integer; begin VKDBFMemMgr.oMem.FreeMem(FPages); for i := 0 to Pred(FNodeCount) do FreeAndNil(FNTXNode[i]); inherited Destroy; end; function TVKNTXBuffer.GetBusy: boolean; begin Result := ( FBusyCount > 0 ); end; function TVKNTXBuffer.GetChanged: boolean; var i: Integer; begin Result := False; for i := 0 to Pred(NodeCount) do begin Result := Result or FNTXNode[i].Changed; if Result then Break; end; end; function TVKNTXBuffer.GetNTXNode(ndx: DWord): TVKNTXNode; begin Result := FNTXNode[ndx]; end; function TVKNTXBuffer.GetPPages(ndx: DWord): pNTX_BUFFER; begin result := pNTX_BUFFER( pAnsiChar( FPages ) + ( NTX_PAGE * ndx) ); end; function TVKNTXBuffer.IncUseCount: DWORD; begin Inc(FUseCount); Result := FUseCount; end; procedure TVKNTXBuffer.SetBusy(const Value: boolean); begin if Value then Inc( FBusyCount ) else begin if ( FBusyCount > 0 ) then Dec(FBusyCount); end; end; procedure TVKNTXBuffer.SetChanged(const Value: boolean); var i: Integer; begin for i := 0 to Pred(NodeCount) do FNTXNode[i].Changed := Value; end; procedure TVKNTXBuffer.SetOffset(const Value: DWORD); var i: Integer; ntxNode: TVKNTXNode; begin FOffset := Value; for i := 0 to Pred(NodeCount) do begin ntxNode := FNTXNode[i]; ntxNode.FNodeOffset := FOffset + DWord(i) * NTX_PAGE; ntxNode.FIndexInBuffer := i; end; end; { TVKNTXBuffers } procedure TVKNTXBuffers.Flush(Handle: TProxyStream); begin OnTraversal := OnFlush; FTMPHandle := Handle; Traversal; end; function TVKNTXBuffers.GetNTXBuffer(Handle: TProxyStream; page_offset: DWORD; out page: pNTX_BUFFER; fRead: boolean): TVKNTXNode; var NTXBuffer: TVKNTXBuffer; j, PageIndex: Integer; block_offset, block_size: DWORD; procedure FillBuffer; var i, lng: Integer; begin NTXBuffer.Busy := True; NTXBuffer.IncUseCount; NTXBuffer.Offset := block_offset; if fRead then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, NTX_PAGE * PagesPerBuffer ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for i := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(i), Pointer(NTXBuffer.PPage[i]), NTX_PAGE ); end else begin lng := NTX_PAGE * Pred(PagesPerBuffer); if lng > 0 then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, lng ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for i := 0 to Pred(Pred(PagesPerBuffer)) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(i), Pointer(NTXBuffer.PPage[i]), NTX_PAGE ); end; end; Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end; procedure CreateNewBuffer; var j, lng: Integer; begin NTXBuffer := TVKNTXBuffer.Create(block_offset, PagesPerBuffer); NTXBuffer.Busy := True; NTXBuffer.IncUseCount; Add(NTXBuffer); if fRead then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, NTX_PAGE * PagesPerBuffer ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(j), Pointer(NTXBuffer.PPage[j]), NTX_PAGE ); end else begin lng := NTX_PAGE * Pred(PagesPerBuffer); if lng > 0 then begin Handle.Seek( NTXBuffer.Offset, 0 ); Handle.Read( NTXBuffer.FPages^, lng ); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then for j := 0 to Pred(Pred(PagesPerBuffer)) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( NTXBuffer.Offset + NTX_PAGE * DWord(j), Pointer(NTXBuffer.PPage[j]), NTX_PAGE ); end; end; Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end; begin block_size := PagesPerBuffer * NTX_PAGE ; block_offset := ( page_offset div block_size ) * block_size; PageIndex := ( page_offset - block_offset ) div NTX_PAGE; NTXBuffer := TVKNTXBuffer(FindKey(block_offset)); if NTXBuffer <> nil then begin NTXBuffer.Busy := True; NTXBuffer.IncUseCount; Result := NTXBuffer.NTXNode[PageIndex]; page := Result.PNode; end else case Flt of lbtUnlimited: CreateNewBuffer; lbtAuto, lbtLimited: begin if Count < FMaxBuffers then CreateNewBuffer else begin if FindLeastUsed(j) then begin NTXBuffer := TVKNTXBuffer(Items[j]); Flash(NTXBuffer); FillBuffer; UpdateObjectInTree(NTXBuffer); end else raise Exception.Create('TVKNTXBuffers.GetNTXBuffer: There is no enough free NTX page buffers! Increase LimitPages property.'); end; end; end; end; procedure TVKNTXBuffers.SetPageChanged(Handle: TProxyStream; page_offset: DWORD); var NTXBuffer: TVKNTXBuffer; PageIndex: Integer; block_offset, block_size: DWORD; begin block_size := PagesPerBuffer * NTX_PAGE ; block_offset := ( page_offset div block_size ) * block_size; PageIndex := ( page_offset - block_offset ) div NTX_PAGE; NTXBuffer := TVKNTXBuffer(FindKey(block_offset)); if NTXBuffer <> nil then NTXBuffer.NTXNode[PageIndex].Changed := true; end; procedure TVKNTXBuffers.FreeNTXBuffer(ntxb: TVKNTXBuffer); begin ntxb.Busy := False; end; procedure TVKNTXBuffers.Flash(ntxb: TVKNTXBuffer); var j, k: Integer; WriteOffsetStart: DWord; WriteBufferStart: pNTX_BUFFER; WriteLength: LongWord; begin if ntxb.Changed then begin WriteOffsetStart := ntxb.Offset; WriteBufferStart := ntxb.Pages; WriteLength := 0; k := 0; for j := 0 to Pred(PagesPerBuffer) do begin if ntxb.NTXNode[j].Changed then begin WriteOffsetStart := ntxb.NTXNode[j].NodeOffset; WriteBufferStart := pNTX_BUFFER(pAnsiChar(ntxb.Pages) + (NTX_PAGE * j)); k := j; Break; end; end; for j := Pred(PagesPerBuffer) downto 0 do begin if ntxb.NTXNode[j].Changed then begin WriteLength := NTX_PAGE * (j - k + 1); Break; end; end; if WriteLength <> 0 then begin NXTObject.FNTXBag.Handler.Seek(WriteOffsetStart, 0); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then begin for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Encrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); NXTObject.FNTXBag.Handler.Write( WriteBufferStart^, WriteLength ); for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); end else NXTObject.FNTXBag.Handler.Write( WriteBufferStart^, WriteLength ); end else raise Exception.Create('TVKNTXBuffers.Flash: Internal Error!'); ntxb.Changed := False; end; end; constructor TVKNTXBuffers.Create; begin inherited Create; Flt := lbtUnlimited; FMaxBuffers := 0; FPagesPerBuffer := DEFPAGESPERBUFFER; end; destructor TVKNTXBuffers.Destroy; begin inherited Destroy; end; function TVKNTXBuffers.FindLeastUsed(out Ind: Integer): boolean; var i: Integer; mn: DWORD; B: TVKNTXBuffer; begin mn := MAXDWORD; Ind := -1; for i := 0 to Pred(Count) do begin B := TVKNTXBuffer(Items[i]); if not B.Busy then begin if B.UseCount < mn then begin mn := B.UseCount; Ind := i; end; end; end; Result := (Ind <> -1); end; function TVKNTXBuffer.cpm(sObj: TVKSortedObject): Integer; begin Result := TVKNTXBuffer(sObj).Offset - Offset; end; procedure TVKNTXBuffers.OnFlush(Sender: TVKSortedListAbstract; SortedObject: TVKSortedObject); var j, k: Integer; ntxb: TVKNTXBuffer; WriteOffsetStart: DWord; WriteBufferStart: pNTX_BUFFER; WriteLength: LongWord; begin ntxb := TVKNTXBuffer(SortedObject); if ntxb.Changed then begin WriteOffsetStart := ntxb.Offset; WriteBufferStart := ntxb.Pages; WriteLength := NTX_PAGE * PagesPerBuffer; k := 0; for j := 0 to Pred(PagesPerBuffer) do begin if ntxb.NTXNode[j].Changed then begin WriteOffsetStart := ntxb.NTXNode[j].NodeOffset; WriteBufferStart := pNTX_BUFFER(pAnsiChar(ntxb.Pages) + (NTX_PAGE * j)); //ntxb.NTXNode[j].PNode; k := j; Break; end; end; for j := Pred(PagesPerBuffer) downto 0 do begin if ntxb.NTXNode[j].Changed then begin WriteLength := NTX_PAGE * (j - k + 1); Break; end; end; FTMPHandle.Seek(WriteOffsetStart, 0); if TVKDBFNTX(NXTObject.OwnerTable).Crypt.Active then begin for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Encrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); FTMPHandle.Write( WriteBufferStart^, WriteLength ); for j := 0 to Pred(PagesPerBuffer) do TVKDBFNTX(NXTObject.OwnerTable).Crypt.Decrypt( ntxb.Offset + NTX_PAGE * DWord(j), Pointer(ntxb.PPage[j]), NTX_PAGE ); end else FTMPHandle.Write( WriteBufferStart^, WriteLength ); ntxb.Changed := False; end; end; function TVKNTXBuffers.FindKey(dwKey: DWORD): TVKSortedObject; function FindKeyInternal(RootNodeObject: TVKSortedObject): TVKSortedObject; var c: Integer; CurrentObject: TVKSortedObject; begin if RootNodeObject.dad <> nil then c := dwKey - TVKNTXBuffer(RootNodeObject).FOffset else c := 1; //for root object alwase get 1 if c > 0 then begin //dwKey > RootNodeObject CurrentObject := RootNodeObject.rson; if CurrentObject <> nil then Result := FindKeyInternal(CurrentObject) else begin Result := nil; end; end else if c = 0 then begin Result := RootNodeObject; end else begin CurrentObject := RootNodeObject.lson; if CurrentObject <> nil then Result := FindKeyInternal(CurrentObject) else begin Result := nil; end; end; end; begin Result := FindKeyInternal(Root); end; {$ENDIF} *) { TVKNTXCompactIndex } procedure TVKNTXCompactIndex.Close; begin Flush; SubOffSet := 0; LinkRest; SHead.root := SubOffSet; SHead.next_page := 0; if Handler = nil then begin SysUtils.FileSeek(FHndl, 0, 0); SysUtils.FileWrite(FHndl, SHead, SizeOf(NTX_HEADER)); end else begin Handler.Seek(0, 0); Handler.Write(SHead, SizeOf(NTX_HEADER)); end; NormalizeRest; if Handler = nil then FileClose(FHndl) else Handler.Close; end; procedure TVKNTXCompactIndex.CreateEmptyIndex(var FHead: NTX_HEADER); begin if Handler = nil then begin if FileName = '' then begin if CreateTmpFilesInTmpFilesDir then FileName := GetTmpFileName(TmpFilesDir) else FileName := GetTmpFileName; end; FHndl := FileCreate(FileName); if FHndl <= 0 then raise Exception.Create('TVKNTXCompactIndex.CreateEmptyIndex: Index create error'); end else Handler.CreateProxyStream; SHead := FHead; SHead.version := 0; SHead.root := NTX_PAGE; SHead.next_page := 0; if Handler = nil then begin SysUtils.FileSeek(FHndl, 0, 0); SysUtils.FileWrite(FHndl, SHead, SizeOf(NTX_HEADER)); end else begin Handler.Seek(0, 0); Handler.Write(SHead, SizeOf(NTX_HEADER)); end; NewPage(0); cur_lev := -1; SubOffSet := NTX_PAGE; end; procedure TVKNTXCompactIndex.NewPage(lev: Integer); var item_off: WORD; i: Integer; begin levels[lev].count := 0; item_off := ( SHead.max_item * 2 ) + 4; for i := 0 to SHead.max_item do begin levels[lev].ref[i] := item_off; item_off := item_off + SHead.item_size; end; pNTX_ITEM(pAnsiChar(@levels[lev]) + levels[lev].ref[0]).page := 0; max_lev := lev; end; procedure TVKNTXCompactIndex.NormalizeRest; var LeftPage: TVKNTXNodeDirect; procedure SavePage(page: TVKNTXNodeDirect); begin if Handler = nil then FileSeek(FHndl, page.NodeOffset, 0) else Handler.Seek(page.NodeOffset, 0); if Crypt then begin CryptPage := page.Node; TVKDBFNTX(OwnerTable).Crypt.Encrypt(SubOffSet, @CryptPage, SizeOf(NTX_BUFFER)); if Handler = nil then SysUtils.FileWrite(FHndl, CryptPage, SizeOf(NTX_BUFFER)) else Handler.Write(CryptPage, SizeOf(NTX_BUFFER)); end else begin if Handler = nil then SysUtils.FileWrite(FHndl, page.PNode^, SizeOf(NTX_BUFFER)) else Handler.Write(page.PNode^, SizeOf(NTX_BUFFER)); end; end; procedure GetPage(root: DWORD; page: TVKNTXNodeDirect); begin if Handler = nil then begin SysUtils.FileSeek(FHndl, root, 0); SysUtils.FileRead(FHndl, page.PNode^, SizeOf(NTX_BUFFER)); end else begin Handler.Seek(root, 0); Handler.Read(page.PNode^, SizeOf(NTX_BUFFER)); end; if Crypt then TVKDBFNTX(OwnerTable).Crypt.Decrypt(root, page.PNode, SizeOf(NTX_BUFFER)); page.FNodeOffset := root; end; procedure Normalize(root: DWORD; Parent: TVKNTXNodeDirect); var item, LItem, SLItem, CItem: pNTX_ITEM; rf: DWORD; Shift, j: Integer; CurrentPage: TVKNTXNodeDirect; begin CurrentPage := TVKNTXNodeDirect.Create(root); GetPage(root, CurrentPage); if Parent <> nil then begin if CurrentPage.PNode.count < SHead.half_page then begin LItem := pNTX_ITEM( pAnsiChar(Parent.PNode) + Parent.PNode.ref[Parent.PNode.count - 1]); GetPage(LItem.page, LeftPage); SLItem := pNTX_ITEM( pAnsiChar(LeftPage.PNode) + LeftPage.PNode.ref[LeftPage.PNode.count]); Shift := SHead.half_page; LeftPage.PNode.count := LeftPage.PNode.count - Shift; j := CurrentPage.PNode.count; while j >= 0 do begin rf := CurrentPage.PNode.ref[j + Shift]; CurrentPage.PNode.ref[j + Shift] := CurrentPage.PNode.ref[j]; CurrentPage.PNode.ref[j] := rf; Dec(j); end; Inc(CurrentPage.PNode.count, Shift); CItem := pNTX_ITEM( pAnsiChar(CurrentPage.PNode) + CurrentPage.PNode.ref[Shift - 1]); Move(LItem.key, CItem.key, SHead.key_size); CItem.rec_no := LItem.rec_no; CItem.page := SLItem.page; Dec(Shift); while Shift > 0 do begin SLItem := pNTX_ITEM( pAnsiChar(LeftPage.PNode) + LeftPage.PNode.ref[LeftPage.PNode.count + Shift]); CItem := pNTX_ITEM( pAnsiChar(CurrentPage.PNode) + CurrentPage.PNode.ref[Shift - 1]); Move(SLItem.key, CItem.key, SHead.key_size); CItem.rec_no := SLItem.rec_no; CItem.page := SLItem.page; Dec(Shift); end; SLItem := pNTX_ITEM( pAnsiChar(LeftPage.PNode) + LeftPage.PNode.ref[LeftPage.PNode.count]); Move(SLItem.key, LItem.key, SHead.key_size); LItem.rec_no := SLItem.rec_no; SavePage(Parent); SavePage(CurrentPage); SavePage(LeftPage); end; end; Item := pNTX_ITEM( pAnsiChar(CurrentPage.PNode) + CurrentPage.PNode.ref[CurrentPage.PNode.count]); if Item.page <> 0 then Normalize(Item.page, CurrentPage); CurrentPage.Free; end; begin LeftPage := TVKNTXNodeDirect.Create(0); try Normalize(SHead.root, nil); finally FreeAndNil(LeftPage); end; end; procedure TVKNTXCompactIndex.LinkRest; var page: pNTX_BUFFER; i: pNTX_ITEM; begin Inc(cur_lev); if (cur_lev <= max_lev) then begin page := pNTX_BUFFER(@levels[cur_lev]); i := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); i.page := SubOffSet; if Handler = nil then SubOffSet := FileSeek(FHndl, 0, 2) else SubOffSet := Handler.Seek(0, 2); if Crypt then begin CryptPage := page^; TVKDBFNTX(OwnerTable).Crypt.Encrypt(SubOffSet, @CryptPage, SizeOf(NTX_BUFFER)); if Handler = nil then SysUtils.FileWrite(FHndl, CryptPage, SizeOf(NTX_BUFFER)) else Handler.Write(CryptPage, SizeOf(NTX_BUFFER)); end else begin if Handler = nil then SysUtils.FileWrite(FHndl, page^, SizeOf(NTX_BUFFER)) else Handler.Write(page^, SizeOf(NTX_BUFFER)); end; LinkRest; end; Dec(cur_lev); end; procedure TVKNTXCompactIndex.AddItem(item: pNTX_ITEM); var page: pNTX_BUFFER; i: pNTX_ITEM; begin Inc(cur_lev); if (cur_lev > max_lev) then NewPage(cur_lev); page := pNTX_BUFFER(@levels[cur_lev]); if page.count = SHead.max_item then begin i := pNTX_ITEM(pAnsiChar(page) + page.ref[page.count]); if cur_lev <> 0 then i.page := item.page else i.page := 0; if Crypt then begin CryptPage := page^; TVKDBFNTX(OwnerTable).Crypt.Encrypt(SubOffSet, @CryptPage, SizeOf(NTX_BUFFER)); if wbAmount > 1 then begin if wbCount = wbAmount then begin if Handler = nil then SysUtils.FileWrite(FHndl, pWriteBuff^, NTX_PAGE * wbCount) else Handler.Write(pWriteBuff^, NTX_PAGE * wbCount); wbCount := 0; end; Move(CryptPage, pAnsiChar(pWriteBuff + NTX_PAGE * wbCount)^, NTX_PAGE); Inc(wbCount); end else begin if Handler = nil then SysUtils.FileWrite(FHndl, CryptPage, SizeOf(NTX_BUFFER)) else Handler.Write(CryptPage, SizeOf(NTX_BUFFER)); end; end else begin if wbAmount > 1 then begin if wbCount = wbAmount then begin if Handler = nil then SysUtils.FileWrite(FHndl, pWriteBuff^, NTX_PAGE * wbCount) else Handler.Write(pWriteBuff^, NTX_PAGE * wbCount); wbCount := 0; end; Move(page^, pAnsiChar(pWriteBuff + NTX_PAGE * wbCount)^, NTX_PAGE); Inc(wbCount); end else begin if Handler = nil then SysUtils.FileWrite(FHndl, page^, SizeOf(NTX_BUFFER)) else Handler.Write(page^, SizeOf(NTX_BUFFER)); end; end; item.page := SubOffSet; Inc(SubOffSet, NTX_PAGE); AddItem(item); page.count := 0; end else begin if ( cur_lev = 0 ) then item.page := 0; Move(item^, (pAnsiChar(page) + page.ref[page.count])^, SHead.item_size); page.count := page.count + 1; end; Dec(cur_lev); end; constructor TVKNTXCompactIndex.Create(pBuffCount: Integer = 0); begin Handler := nil; FHndl := -1; cur_lev := -1; max_lev := -1; SubOffSet := 0; FileName := ''; OwnerTable := nil; Crypt := false; CreateTmpFilesInTmpFilesDir := false; TmpFilesDir := ''; wbAmount := pBuffCount; if wbAmount > 1 then begin pWriteBuff := VKDBFMemMgr.oMem.GetMem(self, NTX_PAGE * wbAmount); end; wbCount := 0; end; destructor TVKNTXCompactIndex.Destroy; begin if wbAmount > 1 then VKDBFMemMgr.oMem.FreeMem(pWriteBuff); inherited Destroy; end; procedure TVKNTXCompactIndex.Flush; begin if wbAmount > 1 then begin if wbCount > 0 then begin if Handler = nil then SysUtils.FileWrite(FHndl, pWriteBuff^, NTX_PAGE * wbCount) else Handler.Write(pWriteBuff^, NTX_PAGE * wbCount); wbCount := 0; end; end; end; { TVKNTXIndexIterator } constructor TVKNTXIndexIterator.Create; begin Eof := false; end; destructor TVKNTXIndexIterator.Destroy; begin inherited Destroy; end; { TVKNTXBlockIterator } procedure TVKNTXBlockIterator.Close; begin VKDBFMemMgr.oMem.FreeMem(p); DeleteFile(FFileName); end; constructor TVKNTXBlockIterator.Create(FileName: AnsiString; key_size, BufSize: Integer); begin inherited Create; FFileName := FileName; Fkey_size := key_size; FBufSize := BufSize; end; destructor TVKNTXBlockIterator.Destroy; begin DeleteFile(FFileName); inherited Destroy; end; procedure TVKNTXBlockIterator.Next; var BlockItem: pBLOCK_ITEM; begin Inc(i); if i >= p.count then Eof := true else begin item.page := 0; BlockItem := pBLOCK_ITEM(pAnsiChar(p) + p.ref[i]); item.rec_no := BlockItem.rec_no; Move(BlockItem.key, item.key, Fkey_size); end; end; procedure TVKNTXBlockIterator.Open; var BlockItem: pBLOCK_ITEM; begin p := VKDBFMemMgr.oMem.GetMem(self, FBufSize); FHndl := FileOpen(FFileName, fmOpenRead or fmShareExclusive); if FHndl > 0 then begin SysUtils.FileRead(FHndl, p^, FBufSize); SysUtils.FileClose(FHndl); i := 0; if p.count = 0 then Eof := true; item.page := 0; BlockItem := pBLOCK_ITEM(pAnsiChar(p) + p.ref[i]); item.rec_no := BlockItem.rec_no; Move(BlockItem.key, item.key, Fkey_size); end else raise Exception.Create('TVKNTXBlockIterator.Open: Open Error "' + FFileName + '"'); end; { TVKNTXIterator } procedure TVKNTXIterator.Close; begin FileClose(FHndl); VKDBFMemMgr.oMem.FreeMem(levels); DeleteFile(FFileName); end; constructor TVKNTXIterator.Create(FileName: AnsiString); begin inherited Create; FFileName := FileName; end; destructor TVKNTXIterator.Destroy; begin DeleteFile(FFileName); inherited Destroy; end; procedure TVKNTXIterator.Next; var page: pNTX_BUFFER; i: pNTX_ITEM; begin Inc(indexes[cur_lev]); repeat page := pNTX_BUFFER(@levels^[cur_lev]); i := pNTX_ITEM(pAnsiChar(page) + page.ref[indexes[cur_lev]]); if i.page <> 0 then begin Inc(cur_lev); indexes[cur_lev] := 0; SysUtils.FileSeek(FHndl, i.page, 0); SysUtils.FileRead(FHndl, levels^[cur_lev], SizeOf(NTX_BUFFER)); end; until i.page = 0; repeat if indexes[cur_lev] = page.count then begin Dec(cur_lev); if cur_lev = -1 then begin Eof := true; Break; end else begin page := pNTX_BUFFER(@levels^[cur_lev]); i := pNTX_ITEM(pAnsiChar(page) + page.ref[indexes[cur_lev]]); item.page := 0; item.rec_no := i.rec_no; Move(i.key, item.key, SHead.key_size); end; end else begin item.page := 0; item.rec_no := i.rec_no; Move(i.key, item.key, SHead.key_size); end; until indexes[cur_lev] < page.count; end; procedure TVKNTXIterator.Open; var page: pNTX_BUFFER; i: pNTX_ITEM; begin levels := VKDBFMemMgr.oMem.GetMem(self, MAX_LEV_BTREE * SizeOf(NTX_BUFFER)); FHndl := FileOpen(FFileName, fmOpenRead or fmShareExclusive); if FHndl > 0 then begin SysUtils.FileRead(FHndl, SHead, SizeOf(NTX_HEADER)); cur_lev := 0; SysUtils.FileSeek(FHndl, SHead.root, 0); SysUtils.FileRead(FHndl, levels^[cur_lev], SizeOf(NTX_BUFFER)); Eof := false; indexes[cur_lev] := 0; if levels^[cur_lev].count = 0 then Eof := true; if not Eof then begin repeat page := pNTX_BUFFER(@levels^[cur_lev]); i := pNTX_ITEM(pAnsiChar(page) + page.ref[indexes[cur_lev]]); if i.page <> 0 then begin Inc(cur_lev); indexes[cur_lev] := 0; SysUtils.FileSeek(FHndl, i.page, 0); SysUtils.FileRead(FHndl, levels^[cur_lev], SizeOf(NTX_BUFFER)); end; until i.page = 0; item.page := 0; item.rec_no := i.rec_no; Move(i.key, item.key, SHead.key_size); end; end else raise Exception.Create('TVKNTXIterator.Open: Open Error "' + FFileName + '"'); end; { TVKNTXBag } procedure TVKNTXBag.Close; begin Handler.Close; end; constructor TVKNTXBag.Create(Collection: TCollection); begin inherited Create(Collection); end; function TVKNTXBag.CreateBag: boolean; begin if ( StorageType = pstOuterStream ) and ( OuterStream = nil ) then raise Exception.Create('TVKNTXBag.CreateBag: StorageType = pstOuterStream but OuterStream = nil!'); Handler.FileName := IndexFileName; Handler.AccessMode.AccessMode := TVKDBFNTX(OwnerTable).AccessMode.AccessMode; Handler.ProxyStreamType := StorageType; Handler.OuterStream := OuterStream; Handler.OnLockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamLock; Handler.OnUnlockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamUnlock; Handler.CreateProxyStream; Result := Handler.IsOpen; end; destructor TVKNTXBag.Destroy; begin inherited Destroy; end; procedure TVKNTXBag.FillHandler; begin Handler.FileName := IndexFileName; Handler.AccessMode.AccessMode := TVKDBFNTX(OwnerTable).AccessMode.AccessMode; Handler.ProxyStreamType := StorageType; Handler.OuterStream := OuterStream; Handler.OnLockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamLock; Handler.OnUnlockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamUnlock; end; function TVKNTXBag.IsOpen: boolean; begin Result := Handler.IsOpen; end; function TVKNTXBag.Open: boolean; begin if ( StorageType = pstOuterStream ) and ( OuterStream = nil ) then raise Exception.Create('TVKNTXBag.Open: StorageType = pstOuterStream but OuterStream = nil!'); Handler.FileName := IndexFileName; Handler.AccessMode.AccessMode := TVKDBFNTX(OwnerTable).AccessMode.AccessMode; Handler.ProxyStreamType := StorageType; Handler.OuterStream := OuterStream; Handler.OnLockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamLock; Handler.OnUnlockEvent := TVKDBFNTX(OwnerTable).OnOuterStreamUnlock; Handler.Open; if not Handler.IsOpen then raise Exception.Create('TVKNTXBag.Open: Open error "' + IndexFileName + '"') else begin if Orders.Count = 0 then Orders.Add; with Orders.Items[0] as TVKNTXOrder do begin Handler.Seek(0, 0); Handler.Read(FHead, SizeOf(NTX_HEADER)); //FLastOffset := Handler.Seek(0, 2); if FHead.order <> '' then TVKNTXOrder(Orders.Items[0]).Name := FHead.Order else TVKNTXOrder(Orders.Items[0]).Name := ChangeFileExt(ExtractFileName(IndexFileName), ''); KeyExpresion := FHead.key_expr; ForExpresion := FHead.for_expr; Unique := (FHead.unique <> #0); Desc := (FHead.Desc <> #0); end; end; Result := Handler.IsOpen; end; { TVKNTXOrder } constructor TVKNTXOrder.Create(Collection: TCollection); begin inherited Create(Collection); if Index > 0 then raise Exception.Create('TVKNTXOrder.Create: NTX bag can not content more then one order!'); end; function TVKNTXOrder.CreateOrder: boolean; var oBag: TVKNTXBag; FKeyParser: TVKDBFExprParser; FieldMap: TFieldMap; IndAttr: TIndexAttributes; CryptPage, page: NTX_BUFFER; item_off: WORD; i: Integer; function EvaluteKeyExpr: AnsiString; begin if Assigned(OnEvaluteKey) then OnEvaluteKey(self, Result) else Result := FKeyParser.EvaluteKey; end; begin oBag := TVKNTXBag(TVKDBFOrders(Collection).Owner); FKeyParser := TVKDBFExprParser.Create(TVKDBFNTX(oBag.OwnerTable), '', [], [poExtSyntax], '', nil, FieldMap); FKeyParser.IndexKeyValue := true; if ClipperVer in [v500, v501] then FHead.sign := 6 else FHead.sign := 7; FHead.version := 1; FHead.root := NTX_PAGE; FHead.next_page := 0; if Assigned(OnCreateIndex) then begin OnCreateIndex(self, IndAttr); FHead.key_size := IndAttr.key_size; FHead.key_dec := IndAttr.key_dec; System.Move(pAnsiChar(IndAttr.key_expr)^, FHead.key_expr, Length(IndAttr.key_expr)); FHead.key_expr[Length(IndAttr.key_expr)] := #0; System.Move(pAnsiChar(IndAttr.for_expr)^, FHead.for_expr, Length(IndAttr.for_expr)); FHead.for_expr[Length(IndAttr.for_expr)] := #0; end else begin FKeyParser.SetExprParams1(KeyExpresion, [], [poExtSyntax], ''); EvaluteKeyExpr; FHead.key_size := Length(FKeyParser.Key); FHead.key_dec := FKeyParser.Prec; System.Move(pAnsiChar(KeyExpresion)^, FHead.key_expr, Length(KeyExpresion)); FHead.key_expr[Length(KeyExpresion)] := #0; System.Move(pAnsiChar(ForExpresion)^, FHead.for_expr, Length(ForExpresion)); FHead.for_expr[Length(ForExpresion)] := #0; end; FHead.item_size := FHead.key_size + 8; FHead.max_item := (NTX_PAGE - FHead.item_size - 4) div (FHead.item_size + 2); FHead.half_page := FHead.max_item div 2; FHead.max_item := FHead.half_page * 2; FHead.reserv1 := #0; FHead.reserv3 := #0; System.Move(pAnsiChar(Name)^, FHead.order, Length(Name)); if Desc then FHead.Desc := #1; if Unique then FHead.Unique := #1; oBag.NTXHandler.Seek(0, 0); oBag.NTXHandler.Write(FHead, SizeOf(NTX_HEADER)); page.count := 0; item_off := ( FHead.max_item * 2 ) + 4; for i := 0 to FHead.max_item do begin page.ref[i] := item_off; item_off := item_off + FHead.item_size; end; pNTX_ITEM(pAnsiChar(@page) + page.ref[0]).page := 0; if TVKDBFNTX(oBag.OwnerTable).Crypt.Active then begin CryptPage := page; TVKDBFNTX(oBag.OwnerTable).Crypt.Encrypt(SizeOf(NTX_BUFFER), @CryptPage, SizeOf(NTX_BUFFER)); oBag.NTXHandler.Write(CryptPage, SizeOf(NTX_BUFFER)); end else oBag.NTXHandler.Write(page, SizeOf(NTX_BUFFER)); oBag.NTXHandler.SetEndOfFile; FKeyParser.Free; Result := True; end; destructor TVKNTXOrder.Destroy; begin inherited Destroy; end; { TVKNTXNode } constructor TVKNTXNode.Create(Owner: TVKNTXBuffer; Offset: DWORD; Index: Integer); begin inherited Create; FChanged := false; FNTXBuffer := Owner; FNodeOffset := Offset; FIndexInBuffer := Index; end; function TVKNTXNode.GetNode: NTX_BUFFER; begin Result := FNTXBuffer.PPage[FIndexInBuffer]^; end; function TVKNTXNode.GetPNode: pNTX_BUFFER; begin Result := FNTXBuffer.PPage[FIndexInBuffer]; end; { TVKNTXNodeDirect } constructor TVKNTXNodeDirect.Create(Offset: DWORD); begin inherited Create; FNodeOffset := Offset; end; function TVKNTXNodeDirect.GetNode: NTX_BUFFER; begin Result := FNode; end; function TVKNTXNodeDirect.GetPNode: pNTX_BUFFER; begin Result := @FNode; end; end.
namespace RemObjects.Elements.Profiler; uses RemObjects.Elements.Cirrus.*; type [AttributeUsage(AttributeTargets.Class or AttributeTargets.Method)] ProfileAspect = public class(IMethodImplementationDecorator) private var fOptionalDefine: String; public constructor; empty; constructor (aOptionalDefine: not nullable String); begin fOptionalDefine := aOptionalDefine; end; method HandleImplementation(aServices: IServices; aMethod: IMethodDefinition); begin if aMethod.Virtual = VirtualMode.Abstract then exit; if aMethod.Empty then exit; if aMethod.Owner.TypeKind = TypeDefKind.Interface then exit; if aMethod.Name.StartsWith("get_") then exit; if aMethod.Name.StartsWith("set_") then exit; if aMethod.Name.StartsWith("add_") then exit; if aMethod.Name.StartsWith("remove_") then exit; if not aServices.IsDefined('PROFILE') then exit; if (length(fOptionalDefine) > 0) and not aServices.IsDefined(fOptionalDefine) then exit; var lType := aServices.GetType('RemObjects.Elements.Profiler.Profiler'); var lName := aMethod.Owner.Name+'.'+aMethod.Name+'('; for i: Integer := 0 to aMethod.ParameterCount -1 do begin if i <> 0 then lName := lName+','; lName := lName+ aMethod.GetParameter(i).Type.Fullname; end; lName := lName+')'; aMethod.SurroundMethodBody( new StandaloneStatement(new ProcValue(new TypeValue(lType), 'Enter', new DataValue(lName))), new StandaloneStatement(new ProcValue(new TypeValue(lType), 'Exit', new DataValue(lName))), SurroundMethod.Always); end; end; end.
unit jclass_types; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TLocalVariableTableRecord = record StartPC: UInt16; Length: UInt16; NameIndex: UInt16; TargetIndex: UInt16; Index: UInt16; end; TJClassCodeException = record StartPC: UInt16; EndPC: UInt16; HandlerPC: UInt16; CatchType: UInt16; end; TJClassInnerClass = record InnerClassInfoIndex: UInt16; OuterClassInfoIndex: UInt16; InnerNameIndex: UInt16; InnerClassAccessFlags: UInt16; end; TJClassTypePath = record TypePathKind: UInt8; TypeArgumentIndex: UInt8; end; TJClassTypeParameterTarget = UInt8; TJClassSupertypeTarget = UInt16; TJClassTypeParameterBoundTarget = record TypeParameterIndex: UInt8; BoundIndex: UInt8; end; TJClassMethodFormalParameterTarget = UInt8; TJClassThrowsTarget = UInt16; TJClassLocalVar = record StartPC: UInt16; Length: UInt16; Index: UInt16; end; TJClassLocalvarTarget = array of TJClassLocalVar; TJClassCatchTarget = UInt16; TJClassOffsetTarget = UInt16; TJClassTypeArgumentTarget = record Offset: UInt16; TypeArguementIndex: UInt8; end; TJClassBootstrapMethods = record BootstrapMethodRef: UInt16; BootstrapArguments: array of UInt16; end; TJClassMethodParameter = record NameIndex: UInt16; AccessFlags: UInt16; end; TJClassLineNumberEntry = record StartPC: UInt16; LineNumber: UInt16; end; TVerificationTypeInfo = record Tag: UInt8; case boolean of True: ( CPoolIndex: UInt16; ); False: ( Offset: UInt16; ); end; TJClassModuleRequirement = record RequirementIndex: UInt16; RequirementFlags: UInt16; RequirementVersionIndex: UInt16; end; TJClassModuleExports = record ExportsIndex: UInt16; ExportsFlags: UInt16; ExportsToIndices: array of UInt16; end; TJClassModuleOpens = record OpensIndex: UInt16; OpensFlags: UInt16; OpensToIndices: array of UInt16; end; TJClassModuleProvides = record ProvidesIndex: UInt16; ProvidesWithIndices: array of UInt16; end; TVerificationTypeInfoArray = array of TVerificationTypeInfo; implementation end.
{*****************************************************************************} { BindAPI } { Copyright (C) 2020 Paolo Morandotti } { Unit fBindApiSimpleDemo } {*****************************************************************************} { } {Permission is hereby granted, free of charge, to any person obtaining } {a copy of this software and associated documentation files (the "Software"), } {to deal in the Software without restriction, including without limitation } {the rights to use, copy, modify, merge, publish, distribute, sublicense, } {and/or sell copies of the Software, and to permit persons to whom the } {Software is furnished to do so, subject to the following conditions: } { } {The above copyright notice and this permission notice shall be included in } {all copies or substantial portions of the Software. } { } {THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS } {OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, } {FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE } {AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER } {LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING } {FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS } {IN THE SOFTWARE. } {*****************************************************************************} unit fBindApiSimpleDemo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, plBindAPI.Attributes, plBindAPI.CoreBinder, plBindAPI.AutoBinder, plBindAPI.ClassFactory, Vcl.ExtCtrls; type [ClassBind(True, 'TTestController', True)] [ClassBind(True, 'TTestSecond')] [BindFieldFrom(False, 'edtTarget2.Text', 'LowerText')] [BindFieldFrom(False, 'edtTarget2a.Text', 'UpperText')] [BindFieldTo(False, 'edtSource2.Text', 'CurrentText')] [BindFieldFrom('edtSame.Text', 'TestObject.IntProp')] [BindFieldFrom(True, 'edtDouble.Text', 'DoubleValue')] [BindFieldTo(False, 'speValue.Value', 'TestObject.IntProp')] [BindFieldTo(False, 'speValue.Value', 'NewValue')] [BindFieldTo(False, 'speValue.Value', 'DoubleValue', 'DoubleOf')] [EventBind(True, 'btnTest.OnClick', 'TestEventBind')] TfrmBindApiSimpleDemo = class(TForm) lblCounter2: TLabel; edtSource2: TEdit; edtTarget2: TEdit; edtTarget2a: TEdit; btnTest: TButton; edtSame: TEdit; [BindFieldTo('Value', 'TestObject.IntProp')] speValue: TSpinEdit; edtDouble: TEdit; [BindField('Text', 'StrBidirectional', '', 'TTestSecond')] edtBidirectional: TEdit; [BindField('Text', 'StrBidirectional', '', 'TTestSecond')] edtBidirectional2: TEdit; bvlInput: TBevel; bvlOutput: TBevel; [BindFieldFrom(True, 'Caption', 'NewValue')] lblInt: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } function GetSourceText: string; procedure SetSourceText(const Value: string); function GetLowerText: string; function GetUpperText: string; procedure SetLowerText(const Value: string); procedure SetUpperText(const Value: string); function GetValue: Integer; procedure SetValue(const Value: Integer); published { Public declarations } [BindPropertyTo('CurrentText')] property SourceText: string read GetSourceText write SetSourceText; [BindPropertyFrom('LowerText')] property LowerText: string read GetLowerText write SetLowerText; [BindPropertyFrom('UpperText')] property UpperText: string read GetUpperText write SetUpperText; [BindPropertyTo(True, 'NewValue')] [BindPropertyTo('DoubleValue', 'DoubleOf')] property Value: Integer read GetValue write SetValue; end; var frmBindApiSimpleDemo: TfrmBindApiSimpleDemo; implementation uses plBindAPI.BindManagement; {$R *.dfm} procedure TfrmBindApiSimpleDemo.FormCreate(Sender: TObject); begin {Remember: if the bound class is not a singleton, the binder is responsible of its destruction} TplBindManager.Bind(Self); end; procedure TfrmBindApiSimpleDemo.FormDestroy(Sender: TObject); begin TplBindManager.Unbind(Self); end; function TfrmBindApiSimpleDemo.GetLowerText: string; begin Result := edtTarget2.Text; end; function TfrmBindApiSimpleDemo.GetSourceText: string; begin Result := edtSource2.Text; end; function TfrmBindApiSimpleDemo.GetUpperText: string; begin Result := edtTarget2a.Text; end; function TfrmBindApiSimpleDemo.GetValue: Integer; begin Result := speValue.Value; end; procedure TfrmBindApiSimpleDemo.SetLowerText(const Value: string); begin edtTarget2.Text := Value; end; procedure TfrmBindApiSimpleDemo.SetSourceText(const Value: string); begin edtSource2.Text := Value; end; procedure TfrmBindApiSimpleDemo.SetUpperText(const Value: string); begin edtTarget2a.Text := Value; end; procedure TfrmBindApiSimpleDemo.SetValue(const Value: Integer); begin speValue.Value := Value; end; end.
unit PrintPageSizer; interface uses Types, Printers; // Given Margins in Millimeters, Calculate the rectangle describing the // printable area of the page in printer device pixels. function CalculatePrintRectangle( MarginLeftMM, MarginTopMM, MarginRightMM : integer ) : TRect; implementation uses Windows; function CalculatePrintRectangle( MarginLeftMM, MarginTopMM, MarginRightMM : integer ) : TRect; var PixelsPerInchX : integer; PixelsPerInchY : integer; Margin : integer; MinMargin : integer; begin PixelsPerInchX := GetDeviceCaps(Printer.Handle, LOGPIXELSX); PixelsPerInchY := GetDeviceCaps(Printer.Handle, LOGPIXELSY); // left margin //.. convert left margin to device pixels Margin := (MarginLeftMM * PixelsPerInchX * 10) div 254; //.. minimum margin allowed by printer MinMargin := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETX); if Margin < MinMargin then begin Margin := MinMargin; end; //.. convert margin to offset from left printable point result.Left := Margin - MinMargin; // top margin //.. convert right margin to device pixels Margin := (MarginTopMM * PixelsPerInchY * 10) div 254; //.. minimum margin allowed by printer MinMargin := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETY); if Margin < MinMargin then begin Margin := MinMargin; end; //.. convert margin to offset from left printable point result.Top := Margin - MinMargin; // right margin //.. convert right margin to device pixels Margin := (MarginRightMM * PixelsPerInchX * 10) div 254; MinMargin := GetDeviceCaps(Printer.Handle, PHYSICALWIDTH) - GetDeviceCaps(Printer.Handle, HORZRES) - GetDeviceCaps(Printer.Handle, PHYSICALOFFSETX); if Margin < MinMargin then begin Margin := MinMargin; end; //.. convert margin to device pixels result.Right := GetDeviceCaps(Printer.Handle, PHYSICALWIDTH) - Margin; // bottom has no margin - as far as is possible down the page result.Bottom := GetDeviceCaps(Printer.Handle, VERTRES); end; end.
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsUtils; {$I dws.inc} {$WARN DUPLICATE_CTOR_DTOR OFF} interface uses Classes, SysUtils, Variants, Types, StrUtils, Masks, dwsStrings, dwsXPlatform, Math; type TStringDynArray = array of UnicodeString; // TRefCountedObject // // Uses Monitor hidden field to store refcount, so not compatible with monitor use // (but Monitor is buggy, so no great loss) TRefCountedObject = class private {$ifdef FPC} FRefCount : Integer; {$endif} function GetRefCount : Integer; inline; procedure SetRefCount(n : Integer); inline; public function IncRefCount : Integer; inline; function DecRefCount : Integer; property RefCount : Integer read GetRefCount write SetRefCount; procedure Free; end; // IGetSelf // IGetSelf = interface ['{77D8EA0B-311C-422B-B8DE-AA5BDE726E41}'] function GetSelf : TObject; function ToString : String; end; // TInterfacedSelfObject // TInterfacedSelfObject = class (TRefCountedObject, IUnknown, IGetSelf) protected function GetSelf : TObject; function QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID; out Obj): HResult; stdcall; function _AddRef : Integer; stdcall; function _Release : Integer; stdcall; public class function NewInstance: TObject; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; // IAutoStrings // IAutoStrings = interface function GetValue : TStringList; property Value : TStringList read GetValue; function Clone : IAutoStrings; end; // TAutoStrings // TAutoStrings = class(TInterfacedSelfObject, IAutoStrings) private FValue : TStringList; protected function GetValue : TStringList; function Clone : IAutoStrings; public constructor Create; constructor CreateCapture(value : TStringList); constructor CreateClone(value : TStringList); destructor Destroy; override; end; // TVarRecArrayContainer // TVarRecArrayContainer = class private FIntegers : array of Int64; FFloats : array of Extended; FStrings : array of UnicodeString; function AddVarRec : PVarRec; public VarRecArray : array of TVarRec; constructor Create; overload; constructor Create(const variantArray : array of Variant); overload; procedure Add(const v : Variant); procedure AddBoolean(const b : Boolean); procedure AddInteger(const i : Int64); procedure AddFloat(const f : Double); procedure AddString(const s : UnicodeString); procedure Initialize; end; // TTightList // {: Compact list embedded in a record.<p> If the list holds only 1 item, no dynamic memory is allocated (the list pointer is used). Make sure to Clear or Clean in the destructor of the Owner. } TTightListArray = array [0..MaxInt shr 4] of TRefCountedObject; PObjectTightList = ^TTightListArray; TTightList = record private FList : PObjectTightList; procedure RaiseIndexOutOfBounds; function GetList : PObjectTightList; inline; public FCount : Integer; // exposed so it can be used for direct property access property List : PObjectTightList read GetList; property Count : Integer read FCount; procedure Free; // to posture as a regular TList procedure Clean; // clear the list and free the item objects procedure Clear; // clear the list without freeing the items function Add(item : TRefCountedObject) : Integer; procedure Assign(const aList : TTightList); function IndexOf(item : TRefCountedObject) : Integer; function Remove(item : TRefCountedObject) : Integer; procedure Delete(index : Integer); procedure Insert(index : Integer; item : TRefCountedObject); procedure MoveItem(curIndex, newIndex : Integer); // Note: D2009 fails if this method is called Move (!) - HV procedure Exchange(index1, index2 : Integer); function ItemsAllOfClass(aClass : TClass) : Boolean; end; // TTightStack // {: Embeddable stack functionality } TTightStack = record private FList : PObjectTightList; FCount : Integer; FCapacity : Integer; procedure Grow; public procedure Push(item : TRefCountedObject); inline; function Peek : TRefCountedObject; inline; procedure Pop; inline; procedure Clear; inline; procedure Clean; procedure Free; property List : PObjectTightList read FList; property Count : Integer read FCount; end; TSimpleCallbackStatus = (csContinue, csAbort); TSimpleCallback<T> = function (var item : T) : TSimpleCallbackStatus; // TSimpleList<T> // {: A minimalistic generic list class. } TSimpleList<T> = class private type ArrayT = array of T; var FItems : ArrayT; FCount : Integer; FCapacity : Integer; protected procedure Grow; function GetItems(const idx : Integer) : T; {$IFDEF DELPHI_2010_MINUS}{$ELSE} inline; {$ENDIF} procedure SetItems(const idx : Integer; const value : T); public procedure Add(const item : T); procedure Extract(idx : Integer); procedure Clear; procedure Enumerate(const callback : TSimpleCallback<T>); property Items[const position : Integer] : T read GetItems write SetItems; default; property Count : Integer read FCount; end; // TObjectList // {: A simple generic object list, owns objects } TObjectList<T{$IFNDEF FPC}: TRefCountedObject{$ENDIF}> = class private type ArrayT = array of T; var FItems : ArrayT; FCount : Integer; protected function GetItem(index : Integer) : T; {$IFDEF DELPHI_2010_MINUS}{$ELSE} inline; {$ENDIF} procedure SetItem(index : Integer; const item : T); public destructor Destroy; override; function Add(const anItem : T) : Integer; function IndexOf(const anItem : T) : Integer; function Extract(idx : Integer) : T; procedure ExtractAll; procedure Clear; property Items[index : Integer] : T read GetItem write SetItem; default; property Count : Integer read FCount; end; // TSortedList // {: List that maintains its elements sorted, subclasses must override Compare } TSortedList<T{$IFNDEF FPC}: TRefCountedObject{$ENDIF}> = class private type ArrayT = array of T; var FItems : ArrayT; FCount : Integer; protected function GetItem(index : Integer) : T; function Find(const item : T; var index : Integer) : Boolean; function Compare(const item1, item2 : T) : Integer; virtual; abstract; procedure InsertItem(index : Integer; const anItem : T); public function Add(const anItem : T) : Integer; function AddOrFind(const anItem : T; var added : Boolean) : Integer; function Extract(const anItem : T) : Integer; function ExtractAt(index : Integer) : T; function IndexOf(const anItem : T) : Integer; procedure Clear; procedure Clean; procedure Enumerate(const callback : TSimpleCallback<T>); property Items[index : Integer] : T read GetItem; default; property Count : Integer read FCount; end; // TSimpleStack<T> // {: A minimalistic generic stack. Note that internal array items are NOT cleared on Pop, for refcounted types, you need to clear yourself manually via Peek. } TSimpleStack<T> = class private type ArrayT = array of T; var FItems : ArrayT; FCount : Integer; FCapacity : Integer; protected procedure Grow; function GetPeek : T; inline; procedure SetPeek(const item : T); function GetItems(const position : Integer) : T; procedure SetItems(const position : Integer; const value : T); public procedure Push(const item : T); procedure Pop; inline; procedure Clear; property Peek : T read GetPeek write SetPeek; property Items[const position : Integer] : T read GetItems write SetItems; property Count : Integer read FCount; end; PSimpleIntegerStackChunk = ^TSimpleIntegerStackChunk; TSimpleIntegerStackChunk = record public const ChunkSize = 16-2; public Data : array [0..ChunkSize-1] of Integer; Prev : PSimpleIntegerStackChunk; end; // TSimpleIntegerStack // {: A minimalistic chunked integer stack. } TSimpleIntegerStack = class private FChunk : PSimpleIntegerStackChunk; FChunkIndex : Integer; FCount : Integer; FPooledChunk : PSimpleIntegerStackChunk; FBaseChunk : TSimpleIntegerStackChunk; class var vTemplate : TSimpleIntegerStack; protected procedure Grow; procedure Shrink; function GetPeek : Integer; inline; procedure SetPeek(const item : Integer); inline; public constructor Create; destructor Destroy; override; class function Allocate : TSimpleIntegerStack; static; procedure Push(const item : Integer); inline; procedure Pop; inline; procedure Clear; property Peek : Integer read GetPeek write SetPeek; property Count : Integer read FCount; end; TSimpleHashBucket<T> = record HashCode : Cardinal; Value : T; end; TSimpleHashBucketArray<T> = array of TSimpleHashBucket<T>; TSimpleHashProc<T> = procedure (const item : T) of object; {: Minimalistic open-addressing hash, subclasses must override SameItem and GetItemHashCode. HashCodes *MUST* be non zero } TSimpleHash<T> = class private {$IFDEF DELPHI_XE3} // workaround for XE3 compiler bug FBuckets : array of TSimpleHashBucket<T>; {$ELSE} FBuckets : TSimpleHashBucketArray<T>; {$ENDIF} FCount : Integer; FGrowth : Integer; FCapacity : Integer; protected procedure Grow; function LinearFind(const item : T; var index : Integer) : Boolean; function SameItem(const item1, item2 : T) : Boolean; virtual; abstract; // hashCode must be non-null function GetItemHashCode(const item1 : T) : Integer; virtual; abstract; public function Add(const anItem : T) : Boolean; // true if added function Replace(const anItem : T) : Boolean; // true if added function Contains(const anItem : T) : Boolean; function Match(var anItem : T) : Boolean; procedure Enumerate(callBack : TSimpleHashProc<T>); procedure Clear; property Count : Integer read FCount; end; TSimpleObjectHash<T{$IFNDEF FPC}: TRefCountedObject{$ENDIF}> = class(TSimpleHash<T>) protected function SameItem(const item1, item2 : T) : Boolean; override; function GetItemHashCode(const item1 : T) : Integer; override; public procedure Clean; end; TSimpleRefCountedObjectHash = class (TSimpleObjectHash<TRefCountedObject>); TSimpleNameObjectHash<T{$IFNDEF FPC}: class{$ENDIF}> = class type TNameObjectHashBucket = record HashCode : Cardinal; Name : UnicodeString; Obj : T; end; TNameObjectHashBuckets = array of TNameObjectHashBucket; private FBuckets : TNameObjectHashBuckets; FCount : Integer; FGrowth : Integer; FHighIndex : Integer; protected procedure Grow; function GetIndex(const aName : UnicodeString) : Integer; function GetObjects(const aName : UnicodeString) : T; inline; procedure SetObjects(const aName : UnicodeString; obj : T); inline; function GetBucketObject(index : Integer) : T; inline; procedure SetBucketObject(index : Integer; obj : T); inline; function GetBucketName(index : Integer) : String; inline; public constructor Create(initialCapacity : Integer = 0); function AddObject(const aName : UnicodeString; aObj : T; replace : Boolean = False) : Boolean; procedure Clean; procedure Clear; property Objects[const aName : UnicodeString] : T read GetObjects write SetObjects; default; property BucketObject[index : Integer] : T read GetBucketObject write SetBucketObject; property BucketName[index : Integer] : String read GetBucketName; property BucketIndex[const aName : UnicodeString] : Integer read GetIndex; property Count : Integer read FCount; property HighIndex : Integer read FHighIndex; end; TObjectObjectHashBucket<TKey, TValue{$IFNDEF FPC}: TRefCountedObject{$ENDIF}> = record Key : TKey; Value : TValue; end; TSimpleObjectObjectHash<TKey, TValue{$IFNDEF FPC}: TRefCountedObject{$ENDIF}> = class type TObjectObjectHashBucket = record HashCode : Cardinal; Name : UnicodeString; Key : TKey; Value : TValue; end; TObjectObjectHashBuckets = array of TObjectObjectHashBucket; private FBuckets : TObjectObjectHashBuckets; FCount : Integer; FGrowth : Integer; FCapacity : Integer; protected procedure Grow; function GetItemHashCode(const item1 : TObjectObjectHashBucket) : Integer; function LinearFind(const item : TObjectObjectHashBucket; var index : Integer) : Boolean; function Match(var anItem : TObjectObjectHashBucket) : Boolean; function Replace(const anItem : TObjectObjectHashBucket) : Boolean; // true if added public function GetValue(aKey : TKey) : TValue; procedure SetValue(aKey : TKey; aValue : TValue); procedure Clear; procedure CleanValues; end; TNameValueHashBucket<T> = record Name : String; Value : T; end; TCaseInsensitiveNameValueHash<T> = class (TSimpleHash<TNameValueHashBucket<T>>) protected function SameItem(const item1, item2 : TNameValueHashBucket<T>) : Boolean; override; function GetItemHashCode(const item1 : TNameValueHashBucket<T>) : Integer; override; end; TObjectsLookup = class (TSortedList<TRefCountedObject>) protected function Compare(const item1, item2 : TRefCountedObject) : Integer; override; end; TStringUnifierBucket = record Hash : Cardinal; Str : UnicodeString; end; PStringUnifierBucket = ^TStringUnifierBucket; TStringUnifierBuckets = array of TStringUnifierBucket; TStringUnifier = class private FLock : TMultiReadSingleWrite; FBuckets : TStringUnifierBuckets; FCount : Integer; FGrowth : Integer; FCapacity : Integer; protected procedure Grow; public constructor Create; destructor Destroy; override; // aString must NOT be empty procedure UnifyAssign(const aString : UnicodeString; h : Cardinal; var unifiedString : UnicodeString); procedure Lock; inline; procedure UnLock; inline; property Count : Integer read FCount; procedure Clear; end; TThreadCached<T> = class private FLock : TMultiReadSingleWrite; FExpiresAt : Int64; FMaxAge : Int64; FOnNeedValue : TSimpleCallback<T>; FValue : T; protected function GetValue : T; procedure SetValue(const v : T); public constructor Create(const aNeedValue : TSimpleCallback<T>; maxAgeMSec : Integer); destructor Destroy; override; procedure Invalidate; property Value : T read GetValue write SetValue; property MaxAge : Int64 read FMaxAge; end; // TSimpleQueue<T> // {: A minimalistic generic queue. Based on a linked list with an items pool, supports both FIFO & LIFO. } TSimpleQueue<T> = class private type PItemT = ^ItemT; ItemT = record Prev, Next : PItemT; Value : T; end; var FFirst, FLast : PItemT; FCount : Integer; FPool : PItemT; FPoolLeft : Integer; protected function Alloc : PItemT; procedure Release(i : PItemT); public constructor Create(poolSize : Integer = 8); destructor Destroy; override; // Adds to the end of the queue procedure Push(const v : T); // Removes from the end of the queue function Pop(var v : T) : Boolean; overload; function Pop : T; overload; // Adds to the beginning of the queue procedure Insert(const v : T); // Removes from the beginning of the queue function Pull(var v : T) : Boolean; overload; function Pull : T; overload; procedure Clear; property Count : Integer read FCount; end; const cWriteOnlyBlockStreamBlockSize = $2000 - 2*SizeOf(Pointer); type // TWriteOnlyBlockStream // {: Provides a write-only block-based stream. } TWriteOnlyBlockStream = class (TStream) private FFirstBlock : PPointerArray; FCurrentBlock : PPointerArray; FBlockRemaining : PInteger; FTotalSize : Integer; protected const cCRLF : array [0..1] of WideChar = (#13, #10); const cAsciiCRLF : array [0..1] of AnsiChar = (#13, #10); function GetSize: Int64; override; procedure AllocateCurrentBlock; procedure FreeBlocks; procedure WriteSpanning(source : PByteArray; count : Integer); procedure WriteLarge(source : PByteArray; count : Integer); procedure WriteBuf(source : PByteArray; count : Integer); public constructor Create; destructor Destroy; override; class function AllocFromPool : TWriteOnlyBlockStream; static; procedure ReturnToPool; function Seek(Offset: Longint; Origin: Word): Longint; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const buffer; count: Longint): Longint; override; procedure WriteByte(b : Byte); inline; procedure WriteBytes(const b : array of Byte); procedure WriteInt32(const i : Integer); inline; procedure WriteDWord(const dw : DWORD); inline; // must be strictly an utf16 UnicodeString procedure WriteString(const utf16String : UnicodeString); overload; inline; procedure WriteString(const i : Int32); overload; inline; procedure WriteString(const i : Int64); overload; inline; procedure WriteSubString(const utf16String : UnicodeString; startPos : Integer); overload; procedure WriteSubString(const utf16String : UnicodeString; startPos, aLength : Integer); overload; procedure WriteUTF8String(const utf8String : RawByteString); overload; inline; procedure WriteCRLF; inline; procedure WriteAsciiCRLF; inline; procedure WriteChar(utf16Char : WideChar); inline; procedure WriteDigits(value : Int64; digits : Integer); // assumes data is an utf16 UnicodeString, spits out utf8 in FPC, utf16 in Delphi function ToString : String; override; function ToUTF8String : RawByteString; function ToBytes : TBytes; function ToRawBytes : RawByteString; procedure Clear; procedure StoreData(var buffer); overload; procedure StoreData(destStream : TStream); overload; procedure StoreUTF8Data(destStream : TStream); overload; end; IWriteOnlyBlockStream = interface function Stream : TWriteOnlyBlockStream; procedure WriteString(const utf16String : UnicodeString); overload; procedure WriteChar(utf16Char : WideChar); procedure WriteCRLF; function ToString : String; end; TAutoWriteOnlyBlockStream = class (TInterfacedSelfObject, IWriteOnlyBlockStream) private FStream : TWriteOnlyBlockStream; protected function Stream : TWriteOnlyBlockStream; procedure WriteString(const utf16String : UnicodeString); overload; procedure WriteChar(utf16Char : WideChar); procedure WriteCRLF; public constructor Create; destructor Destroy; override; function ToString : String; override; end; TSimpleInt64List = class(TSimpleList<Int64>) end; TSimpleDoubleList = class(TSimpleList<Double>) protected procedure DoExchange(index1, index2 : Integer); inline; procedure QuickSort(minIndex, maxIndex : Integer); public procedure Sort; // Kahan summation function Sum : Double; end; TSimpleStringHash = class(TSimpleHash<String>) protected function SameItem(const item1, item2 : String) : Boolean; override; function GetItemHashCode(const item1 : String) : Integer; override; end; TFastCompareStringList = class (TStringList) {$ifdef FPC} function DoCompareText(const s1,s2 : string) : PtrInt; override; {$else} function CompareStrings(const S1, S2: UnicodeString): Integer; override; function IndexOfName(const name : UnicodeString): Integer; override; {$endif} end; TFastCompareTextList = class (TStringList) {$ifdef FPC} function DoCompareText(const s1,s2 : string) : PtrInt; override; {$else} function CompareStrings(const S1, S2: UnicodeString): Integer; override; function FindName(const name : UnicodeString; var index : Integer) : Boolean; function IndexOfName(const name : UnicodeString): Integer; override; {$endif} end; TClassCloneConstructor<T: TRefCountedObject> = record private FTemplate : T; FSize : Integer; public procedure Initialize(aTemplate : T); procedure Finalize; function Create : T; inline; end; ETightListOutOfBound = class(Exception) end; TQuickSort = record public CompareMethod : function (index1, index2 : Integer) : Integer of object; SwapMethod : procedure (index1, index2 : Integer) of object; procedure Sort(minIndex, maxIndex : Integer); end; TStringIterator = class private FStr : String; FPStr : PChar; FPosition : Integer; FLength : Integer; public constructor Create(const s : String); function Current : Char; inline; function EOF : Boolean; inline; procedure Next; inline; procedure SkipWhiteSpace; function CollectQuotedString : String; function CollectAlphaNumeric : String; function CollectInteger : Int64; property Str : String read FStr; property Length : Integer read FLength write FLength; end; EStringIterator = class (Exception) end; EdwsVariantTypeCastError = class(EVariantTypeCastError) public constructor Create(const v : Variant; const desiredType : UnicodeString; originalException : Exception); end; PFormatSettings = ^TFormatSettings; TPooledObject = class private FNext : TPooledObject; public constructor Create; virtual; destructor Destroy; override; end; TPooledObjectClass = class of TPooledObject; TPool = record private FRoot : TPooledObject; FPoolClass : TPooledObjectClass; FLock : TMultiReadSingleWrite; public procedure Initialize(aClass : TPooledObjectClass); procedure Finalize; function Acquire : TPooledObject; procedure Release(const obj : TPooledObject); end; const cMSecToDateTime : Double = 1/(24*3600*1000); procedure UnifyAssignString(const fromStr : UnicodeString; var toStr : UnicodeString); function UnifiedString(const fromStr : UnicodeString) : UnicodeString; inline; procedure TidyStringsUnifier; function StringUnifierHistogram : TIntegerDynArray; function UnicodeCompareLen(p1, p2 : PWideChar; n : Integer) : Integer; function UnicodeCompareText(const s1, s2 : UnicodeString) : Integer; function UnicodeSameText(const s1, s2 : UnicodeString) : Boolean; function AsciiCompareLen(p1, p2 : PAnsiChar; n : Integer) : Integer; overload; function AsciiCompareText(p : PAnsiChar; const s : RawByteString) : Integer; function AsciiSameText(p : PAnsiChar; const s : RawByteString) : Boolean; function PosA(const sub, main : RawByteString) : Integer; inline; function StrIsASCII(const s : String) : Boolean; function StrNonNilLength(const aString : UnicodeString) : Integer; inline; function StrIBeginsWith(const aStr, aBegin : UnicodeString) : Boolean; function StrBeginsWith(const aStr, aBegin : UnicodeString) : Boolean; function StrBeginsWithA(const aStr, aBegin : RawByteString) : Boolean; function StrBeginsWithBytes(const aStr : RawByteString; const bytes : array of Byte) : Boolean; function StrIEndsWith(const aStr, aEnd : UnicodeString) : Boolean; function StrIEndsWithA(const aStr, aEnd : RawByteString) : Boolean; function StrEndsWith(const aStr, aEnd : UnicodeString) : Boolean; function StrEndsWithA(const aStr, aEnd : RawByteString) : Boolean; function StrContains(const aStr, aSubStr : UnicodeString) : Boolean; overload; function StrContains(const aStr : UnicodeString; aChar : WideChar) : Boolean; overload; function LowerCaseA(const aStr : RawByteString) : RawByteString; function StrMatches(const aStr, aMask : UnicodeString) : Boolean; function StrDeleteLeft(const aStr : UnicodeString; n : Integer) : UnicodeString; function StrDeleteRight(const aStr : UnicodeString; n : Integer) : UnicodeString; function StrAfterChar(const aStr : UnicodeString; aChar : WideChar) : UnicodeString; function StrBeforeChar(const aStr : UnicodeString; aChar : WideChar) : UnicodeString; function StrReplaceChar(const aStr : UnicodeString; oldChar, newChar : WideChar) : UnicodeString; function StrCountChar(const aStr : UnicodeString; c : WideChar) : Integer; function Min(a, b : Integer) : Integer; inline; function WhichPowerOfTwo(const v : Int64) : Integer; function SimpleStringHash(const s : UnicodeString) : Cardinal; inline; function SimpleLowerCaseStringHash(const s : UnicodeString) : Cardinal; function SimpleByteHash(p : PByte; n : Integer) : Cardinal; function SimpleIntegerHash(x : Cardinal) : Cardinal; function SimpleInt64Hash(x : Int64) : Cardinal; function RawByteStringToScriptString(const s : RawByteString) : UnicodeString; overload; inline; procedure RawByteStringToScriptString(const s : RawByteString; var result : UnicodeString); inline; overload; procedure BytesToScriptString(const p : PByte; n : Integer; var result : UnicodeString); function ScriptStringToRawByteString(const s : UnicodeString) : RawByteString; overload; inline; procedure ScriptStringToRawByteString(const s : UnicodeString; var result : RawByteString); overload; function BinToHex(const data; n : Integer) : String; overload; function BinToHex(const data : RawByteString) : String; overload; inline; function HexToBin(const data : String) : RawByteString; type TInt64StringBuffer = array [0..21] of WideChar; TInt32StringBuffer = array [0..11] of WideChar; function FastInt32ToBuffer(const val : Int32; var buf : TInt32StringBuffer) : Integer; function FastInt64ToBuffer(const val : Int64; var buf : TInt64StringBuffer) : Integer; procedure FastInt64ToStr(const val : Int64; var s : UnicodeString); procedure FastInt64ToHex(val : Int64; digits : Integer; var s : UnicodeString); function Int64ToHex(val : Int64; digits : Integer) : UnicodeString; inline; function DivMod100(var dividend : Cardinal) : Cardinal; procedure FastStringReplace(var str : UnicodeString; const sub, newSub : UnicodeString); procedure VariantToString(const v : Variant; var s : UnicodeString); procedure VariantToInt64(const v : Variant; var r : Int64); procedure VarClearSafe(var v : Variant); procedure VarCopySafe(var dest : Variant; const src : Variant); overload; procedure VarCopySafe(var dest : Variant; const src : IUnknown); overload; procedure VarCopySafe(var dest : Variant; const src : IDispatch); overload; procedure VarCopySafe(var dest : Variant; const src : Int64); overload; procedure VarCopySafe(var dest : Variant; const src : UnicodeString); overload; procedure VarCopySafe(var dest : Variant; const src : Double); overload; procedure VarCopySafe(var dest : Variant; const src : Boolean); overload; type EISO8601Exception = class (Exception); function TryISO8601ToDateTime(const v : String; var aResult : TDateTime) : Boolean; function ISO8601ToDateTime(const v : String) : TDateTime; function DateTimeToISO8601(dt : TDateTime; extendedFormat : Boolean) : String; procedure SuppressH2077ValueAssignedToVariableNeverUsed(const X); inline; procedure dwsFreeAndNil(var O); // transitional function, do not use // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // SuppressH2077ValueAssignedToVariableNeverUsed // procedure SuppressH2077ValueAssignedToVariableNeverUsed(const X); inline; begin end; // dwsFreeAndNil // procedure dwsFreeAndNil(var o); var obj : TObject; begin obj:=TObject(o); Pointer(o):=nil; if obj is TRefCountedObject then TRefCountedObject(obj).Free else obj.Free; end; // SimpleStringHash // function SimpleStringHash(const s : UnicodeString) : Cardinal; inline; var i : Integer; begin // modified FNV-1a using length as seed Result:=Length(s); for i:=1 to Result do Result:=(Result xor Ord(s[i]))*16777619; end; // SimpleLowerCaseStringHash // function SimpleLowerCaseStringHash(const s : UnicodeString) : Cardinal; function Fallback(const s : UnicodeString) : Cardinal; begin Result:=SimpleStringHash(UnicodeLowerCase(s)); end; var i : Integer; c : Word; begin // modified FNV-1a using length as seed Result:=Length(s); for i:=1 to Result do begin c:=Ord(s[i]); if c>127 then Exit(Fallback(s)) else if c in [Ord('A')..Ord('Z')] then c:=c+(Ord('a')-Ord('A')); Result:=(Result xor c)*16777619; end; end; // SimpleByteHash // function SimpleByteHash(p : PByte; n : Integer) : Cardinal; begin Result:=2166136261; for n:=n downto 1 do begin Result:=(Result xor p^)*16777619; Inc(p); end; end; // SimpleIntegerHash // function SimpleIntegerHash(x : Cardinal) : Cardinal; begin // simplified MurmurHash 3 Result := x * $cc9e2d51; Result := (Result shl 15) or (Result shr 17); Result := Result * $1b873593 + $e6546b64; end; // SimpleInt64Hash // function SimpleInt64Hash(x : Int64) : Cardinal; var k : Cardinal; begin // simplified MurmurHash 3 Result := Cardinal(x) * $cc9e2d51; Result := (Result shl 15) or (Result shr 17); Result := Result * $1b873593 + $e6546b64; k := (x shr 32) * $cc9e2d51; k := (k shl 15) or (k shr 17); Result := k * $1b873593 xor Result; end; // ScriptStringToRawByteString // function ScriptStringToRawByteString(const s : UnicodeString) : RawByteString; begin ScriptStringToRawByteString(s, Result); end; // ScriptStringToRawByteString // procedure ScriptStringToRawByteString(const s : UnicodeString; var result : RawByteString); overload; type PByteArray = ^TByteArray; TByteArray = array[0..maxInt shr 1] of Byte; var i, n : Integer; pSrc : PWideChar; pDest : PByteArray; begin n:=Length(s); SetLength(Result, n); if n=0 then Exit; pSrc:=PWideChar(Pointer(s)); pDest:=PByteArray(NativeUInt(Result)); for i:=0 to n-1 do pDest[i]:=PByte(@pSrc[i])^; end; // BinToHex // function BinToHex(const data; n : Integer) : String; const cHexDigits : array [0..15] of Char = ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ); var i : Integer; pDest : PLongWord; p : PByte; begin if n=0 then Exit; SetLength(Result, n*2); pDest:=Pointer(Result); p:=@data; for i:=1 to n do begin pDest^ := Ord(cHexDigits[p^ shr 4]) + (Ord(cHexDigits[p^ and 15]) shl 16); Inc(pDest); Inc(p); end; end; // BinToHex // function BinToHex(const data : RawByteString) : String; overload; begin Result:=BinToHex(Pointer(data)^, Length(data)); end; // HexToBin // function HexToBin(const data : String) : RawByteString; var i, n, b : Integer; c : Char; pSrc : PChar; pDest : PByte; begin n:=Length(data); if (n and 1)<>0 then raise Exception.Create('Even hexadecimal character count expected'); n:=n shr 1; SetLength(Result, n); pSrc:=PChar(Pointer(data)); pDest:=PByte(Result); for i:=1 to n do begin c:=pSrc[0]; case c of '0'..'9' : b := (Ord(c) shl 4)-(Ord('0') shl 4); 'A'..'F' : b := (Ord(c) shl 4)+(160-(Ord('A') shl 4)); 'a'..'f' : b := (Ord(c) shl 4)+(160-(Ord('a') shl 4)); else raise Exception.Create('Invalid characters in hexadecimal'); end; c:=pSrc[1]; case c of '0'..'9' : b := b + Ord(c) - Ord('0'); 'A'..'F' : b := b + Ord(c) + (10-Ord('A')); 'a'..'f' : b := b + Ord(c) + (10-Ord('a')); else raise Exception.Create('Invalid characters in hexadecimal'); end; pDest^ := b; Inc(pDest); pSrc := @pSrc[2]; end; end; // DivMod100 // function DivMod100(var dividend : Cardinal) : Cardinal; const c100 : Cardinal = 100; {$ifndef WIN32_ASM} var divided : Cardinal; begin divided:=dividend div 100; Result:=dividend-divided*100; dividend:=divided; {$else} asm mov ecx, eax mov eax, [eax] xor edx, edx div c100 mov [ecx], eax mov eax, edx {$endif} end; type TTwoChars = packed array [0..1] of WideChar; PTwoChars = ^TTwoChars; const cTwoDigits : packed array [0..99] of TTwoChars = ( ('0','0'), ('0','1'), ('0','2'), ('0','3'), ('0','4'), ('0','5'), ('0','6'), ('0','7'), ('0','8'), ('0','9'), ('1','0'), ('1','1'), ('1','2'), ('1','3'), ('1','4'), ('1','5'), ('1','6'), ('1','7'), ('1','8'), ('1','9'), ('2','0'), ('2','1'), ('2','2'), ('2','3'), ('2','4'), ('2','5'), ('2','6'), ('2','7'), ('2','8'), ('2','9'), ('3','0'), ('3','1'), ('3','2'), ('3','3'), ('3','4'), ('3','5'), ('3','6'), ('3','7'), ('3','8'), ('3','9'), ('4','0'), ('4','1'), ('4','2'), ('4','3'), ('4','4'), ('4','5'), ('4','6'), ('4','7'), ('4','8'), ('4','9'), ('5','0'), ('5','1'), ('5','2'), ('5','3'), ('5','4'), ('5','5'), ('5','6'), ('5','7'), ('5','8'), ('5','9'), ('6','0'), ('6','1'), ('6','2'), ('6','3'), ('6','4'), ('6','5'), ('6','6'), ('6','7'), ('6','8'), ('6','9'), ('7','0'), ('7','1'), ('7','2'), ('7','3'), ('7','4'), ('7','5'), ('7','6'), ('7','7'), ('7','8'), ('7','9'), ('8','0'), ('8','1'), ('8','2'), ('8','3'), ('8','4'), ('8','5'), ('8','6'), ('8','7'), ('8','8'), ('8','9'), ('9','0'), ('9','1'), ('9','2'), ('9','3'), ('9','4'), ('9','5'), ('9','6'), ('9','7'), ('9','8'), ('9','9') ); function EightDigits(i : Cardinal; p : PWideChar) : Integer; var r : Integer; begin Result:=0; Dec(p); repeat if i<100 then begin r:=i; i:=0; end else begin r:=DivMod100(i); end; if r>=10 then begin PTwoChars(p)^:=cTwoDigits[r]; Dec(p, 2); Inc(Result, 2); end else begin p[1]:=WideChar(Ord('0')+r); if i>0 then begin p[0]:='0'; Dec(p, 2); Inc(Result, 2); end else begin Inc(Result); Break; end; end; until i=0; end; // FastInt32ToBuffer // {$IFOPT R+} {$DEFINE RANGEON} {$R-} {$ELSE} {$UNDEF RANGEON} {$ENDIF} function FastInt32ToBuffer(const val : Int32; var buf : TInt32StringBuffer) : Integer; var n, nd : Integer; neg : Boolean; i, next : UInt32; begin if val<0 then begin neg:=True; //range checking is off here because the code causes range check errors //code here... i:=-val; end else begin if val=0 then begin Result:=High(buf); buf[Result]:='0'; Exit; end else i:=val; neg:=False; end; nd:=High(buf); n:=nd; while True do begin if i>100000000 then begin next:=i div 100000000; n:=n-EightDigits(i-next*100000000, @buf[n]); i:=next; end else begin n:=n-EightDigits(i, @buf[n]); Break; end; Dec(nd, 8); while n>nd do begin buf[n]:='0'; Dec(n); end; end; if neg then buf[n]:='-' else Inc(n); Result:=n; end; {$IFDEF RANGEON} {$R+} {$ENDIF} // FastInt64ToBuffer // {$IFOPT R+} {$DEFINE RANGEON} {$R-} {$ELSE} {$UNDEF RANGEON} {$ENDIF} function FastInt64ToBuffer(const val : Int64; var buf : TInt64StringBuffer) : Integer; var n, nd : Integer; neg : Boolean; i, next : UInt64; begin if val<0 then begin neg:=True; //range checking is off here because the code causes range check errors //code here... i:=-val; end else begin if val=0 then begin Result:=High(buf); buf[Result]:='0'; Exit; end else i:=val; neg:=False; end; nd:=High(buf); n:=nd; while True do begin if i>100000000 then begin next:=i div 100000000; n:=n-EightDigits(i-next*100000000, @buf[n]); i:=next; end else begin n:=n-EightDigits(i, @buf[n]); Break; end; Dec(nd, 8); while n>nd do begin buf[n]:='0'; Dec(n); end; end; if neg then buf[n]:='-' else Inc(n); Result:=n; end; {$IFDEF RANGEON} {$R+} {$ENDIF} // InitializeSmallIntegers // var vSmallIntegers : array [0..39] of String; procedure InitializeSmallIntegers; var i : Integer; begin // we can't use a constant array here, as obtaining a string from a constant // array implies a memory allocations, which would defeat the whole purpose for i := 0 to High(vSmallIntegers) do vSmallIntegers[i] := IntToStr(i); end; // FastInt64ToStr // procedure FastInt64ToStr(const val : Int64; var s : UnicodeString); var buf : TInt64StringBuffer; n : Integer; begin if (Int64Rec(val).Hi=0) and (Int64Rec(val).Lo<=High(vSmallIntegers)) then s:=vSmallIntegers[Int64Rec(val).Lo] else begin n:=FastInt64ToBuffer(val, buf); SetString(s, PWideChar(@buf[n]), (High(buf)+1)-n); end; end; // FastInt64ToHex // procedure FastInt64ToHex(val : Int64; digits : Integer; var s : UnicodeString); const cIntToHex : array [0..15] of WideChar = ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ); var buf : array [0..15] of WideChar; p : PWideChar; d, i : Integer; begin if Cardinal(digits)>16 then begin if digits<=0 then digits:=1 else digits:=16; end; p:=@buf[15]; if PIntegerArray(@val)[1]=0 then begin i:=PIntegerArray(@val)[0]; repeat d:=i and 15; i:=i shr 4; p^:=cIntToHex[d]; Dec(p); Dec(digits); until i=0; end else begin repeat d:=val and 15; val:=val shr 4; p^:=cIntToHex[d]; Dec(p); Dec(digits); until val=0; end; for i:=1 to digits do begin p^:='0'; Dec(p); end; SetString(s, PWideChar(@p[1]), (NativeUInt(@buf[15])-NativeUInt(p)) div SizeOf(WideChar)); end; // Int64ToHex // function Int64ToHex(val : Int64; digits : Integer) : UnicodeString; begin FastInt64ToHex(val, digits, Result); end; // FastStringReplace // procedure FastStringReplace(var str : UnicodeString; const sub, newSub : UnicodeString); procedure FallBack; begin str:=SysUtils.StringReplace(str, sub, newSub, [rfReplaceAll]); end; procedure ReplaceChars(pStr : PWideChar; oldChar, newChar : WideChar; n : Integer); begin pStr^:=newChar; for n:=1 to n do begin if pStr[n]=oldChar then pStr[n]:=newChar; end; end; var p, dp, np : Integer; subLen, newSubLen : Integer; pStr, pNewSub : PWideChar; begin if (str='') or (sub='') then Exit; p:=Pos(sub, str); if p<=0 then Exit; subLen:=Length(sub); newSubLen:=Length(newSub); pNewSub:=PWideChar(newSub); if subLen=newSubLen then begin // same length, replace in-place UniqueString(str); pStr:=PWideChar(Pointer(str)); if subLen=1 then begin // special case of character replacement ReplaceChars(@pStr[p-1], sub[1], pNewSub^, Length(str)-p); end else begin repeat System.Move(pNewSub^, pStr[p-1], subLen*SizeOf(WideChar)); p:=PosEx(sub, str, p+subLen); until p<=0; end; end else if newSubLen<subLen then begin // shorter replacement, replace & pack in-place UniqueString(str); pStr:=PWideChar(Pointer(str)); dp:=p-1; while True do begin if newSubLen>0 then begin System.Move(pNewSub^, pStr[dp], newSubLen*SizeOf(WideChar)); dp:=dp+newSubLen; end; p:=p+subLen; np:=PosEx(sub, str, p); if np>0 then begin if np>p then begin System.Move(pStr[p-1], pStr[dp], (np-p)*SizeOf(WideChar)); dp:=dp+np-p; end; p:=np; end else begin np:=Length(str)+1-p; if np>0 then System.Move(pStr[p-1], pStr[dp], np*SizeOf(WideChar)); SetLength(str, dp+np); Break; end; end; end else begin // growth required (not optimized yet, todo) FallBack; end; end; // VariantToString // procedure VariantToString(const v : Variant; var s : UnicodeString); procedure DispatchAsString(const disp : Pointer; var Result : UnicodeString); begin Result:=UnicodeFormat('IDispatch (%p)', [disp]); end; procedure UnknownAsString(const unknown : IUnknown; var Result : UnicodeString); var intf : IGetSelf; begin if unknown=nil then Result:='nil' else if unknown.QueryInterface(IGetSelf, intf)=0 then Result:=intf.ToString else Result:='[IUnknown]'; end; procedure FloatAsString(var v : Double; var Result : UnicodeString); begin Result:=FloatToStr(v); end; var varData : PVarData; begin varData:=PVarData(@v); case varData^.VType of {$ifdef FPC} varString : s:=UnicodeString(varData^.VString); {$else} varString : s:=RawByteStringToScriptString(RawByteString(varData^.VString)); varUString : s:=UnicodeString(varData^.VUString); {$endif} varInt64 : FastInt64ToStr(varData^.VInt64, s); varDouble : FloatAsString(varData^.VDouble, s); varBoolean : if varData^.VBoolean then s:='True' else s:='False'; varNull : s:='Null'; varUnknown : UnknownAsString(IUnknown(varData^.VUnknown), s); else s:=v; end; end; // VariantToInt64 // procedure VariantToInt64(const v : Variant; var r : Int64); procedure DefaultCast; begin try r:=v; except // workaround for RTL bug that will sometimes report a failed cast to Int64 // as being a failed cast to Boolean on E : EVariantError do begin raise EdwsVariantTypeCastError.Create(v, 'Integer', E); end else raise; end; end; begin case TVarData(v).VType of varInt64 : r:=TVarData(v).VInt64; varBoolean : r:=Ord(TVarData(v).VBoolean); varUnknown : if TVarData(v).VUnknown=nil then r:=0 else DefaultCast; else DefaultCast; end; end; // VarClearSafe // procedure VarClearSafe(var v : Variant); // This procedure exists because of a bug in Variants / Windows where if you clear // a varUnknown, the _Release method will be called before the variable is niled // So if _Release's code assigns a nil to the same variable, it will result in // an invalid refcount. _IntfClear does not suffer from that issue begin case TVarData(v).VType of varEmpty : begin TVarData(v).VUInt64:=0; end; varBoolean, varInt64, varDouble : begin TVarData(v).VType:=varEmpty; TVarData(v).VUInt64:=0; end; varUnknown : begin TVarData(v).VType:=varEmpty; IUnknown(TVarData(v).VUnknown):=nil; end; varDispatch : begin TVarData(v).VType:=varEmpty; IDispatch(TVarData(v).VDispatch):=nil; end; varUString : begin TVarData(v).VType:=varEmpty; UnicodeString(TVarData(v).VString):=''; end; else VarClear(v); TVarData(v).VUInt64:=0; end; end; // VarCopySafe (variant) // procedure VarCopySafe(var dest : Variant; const src : Variant); begin if @dest=@src then Exit; VarClearSafe(dest); case TVarData(src).VType of varEmpty : ; varNull : TVarData(dest).VType:=varNull; varBoolean : begin TVarData(dest).VType:=varBoolean; TVarData(dest).VBoolean:=TVarData(src).VBoolean; end; varInt64 : begin TVarData(dest).VType:=varInt64; TVarData(dest).VInt64:=TVarData(src).VInt64; end; varDouble : begin TVarData(dest).VType:=varDouble; TVarData(dest).VDouble:=TVarData(src).VDouble; end; varUnknown : begin {$ifdef DEBUG} Assert(TVarData(dest).VUnknown=nil); {$endif} TVarData(dest).VType:=varUnknown; IUnknown(TVarData(dest).VUnknown):=IUnknown(TVarData(src).VUnknown); end; varDispatch : begin {$ifdef DEBUG} Assert(TVarData(dest).VDispatch=nil); {$endif} TVarData(dest).VType:=varDispatch; IDispatch(TVarData(dest).VDispatch):=IDispatch(TVarData(src).VDispatch); end; varUString : begin {$ifdef DEBUG} Assert(TVarData(dest).VUString=nil); {$endif} TVarData(dest).VType:=varUString; UnicodeString(TVarData(dest).VUString):=String(TVarData(src).VUString); end; varSmallint..varSingle, varCurrency..varDate, varError, varShortInt..varLongWord, varUInt64 : begin TVarData(dest).RawData[0]:=TVarData(src).RawData[0]; TVarData(dest).RawData[1]:=TVarData(src).RawData[1]; TVarData(dest).RawData[2]:=TVarData(src).RawData[2]; TVarData(dest).RawData[3]:=TVarData(src).RawData[3]; end; else dest:=src; end; end; // VarCopySafe (iunknown) // procedure VarCopySafe(var dest : Variant; const src : IUnknown); begin VarClearSafe(dest); TVarData(dest).VType:=varUnknown; IUnknown(TVarData(dest).VUnknown):=src; end; // VarCopySafe (idispatch) // procedure VarCopySafe(var dest : Variant; const src : IDispatch); begin VarClearSafe(dest); TVarData(dest).VType:=varDispatch; IDispatch(TVarData(dest).VDispatch):=src; end; // VarCopySafe (int64) // procedure VarCopySafe(var dest : Variant; const src : Int64); begin VarClearSafe(dest); TVarData(dest).VType:=varInt64; TVarData(dest).VInt64:=src; end; // VarCopySafe (string) // procedure VarCopySafe(var dest : Variant; const src : UnicodeString); begin VarClearSafe(dest); TVarData(dest).VType:=varUString; UnicodeString(TVarData(dest).VString):=src; end; // VarCopySafe (double) // procedure VarCopySafe(var dest : Variant; const src : Double); begin VarClearSafe(dest); TVarData(dest).VType:=varDouble; TVarData(dest).VDouble:=src; end; // VarCopySafe (bool) // procedure VarCopySafe(var dest : Variant; const src : Boolean); begin VarClearSafe(dest); TVarData(dest).VType:=varBoolean; TVarData(dest).VBoolean:=src; end; // DateTimeToISO8601 // function DateTimeToISO8601(dt : TDateTime; extendedFormat : Boolean) : String; var buf : array [0..31] of Char; p : PChar; procedure WriteChar(c : Char); begin p^:=c; Inc(p); end; procedure Write2Digits(v : Integer); begin PTwoChars(p)^:=cTwoDigits[v]; Inc(p, 2); end; var y, m, d, h, n, s, z : Word; begin p:=@buf; DecodeDate(dt, y, m, d); Write2Digits((y div 100) mod 100); Write2Digits(y mod 100); if extendedFormat then WriteChar('-'); Write2Digits(m); if extendedFormat then WriteChar('-'); Write2Digits(d); DecodeTime(dt, h, n, s, z); WriteChar('T'); Write2Digits(h); if extendedFormat then WriteChar(':'); Write2Digits(n); if s<>0 then begin if extendedFormat then WriteChar(':'); Write2Digits(s); end; WriteChar('Z'); p^:=#0; Result:=buf; end; // ISO8601ToDateTime // function ISO8601ToDateTime(const v : String) : TDateTime; var p : PChar; function ReadDigit : Integer; var c : Char; begin c := p^; case c of '0'..'9' : Result:=Ord(c)-Ord('0'); else raise EISO8601Exception.CreateFmt('Unexpected character (%d) instead of digit', [Ord(c)]); end; Inc(p); end; function Read2Digits : Integer; inline; begin Result:=ReadDigit*10; Result:=Result+ReadDigit; end; function Read4Digits : Integer; inline; begin Result:=Read2Digits*100; Result:=Result+Read2Digits; end; var y, m, d, h, n, s : Integer; separator : Boolean; begin if v='' then begin Result:=0; Exit; end; p:=Pointer(v); // parsing currently limited to basic Z variations with limited validation y:=Read4Digits; separator:=(p^='-'); if separator then Inc(p); m:=Read2Digits; if separator then begin if p^<>'-' then raise EISO8601Exception.Create('"-" expected after month'); Inc(p); end; d:=Read2Digits; try Result:=EncodeDate(y, m, d); except on E: Exception do raise EISO8601Exception.Create(E.Message); end; if p^=#0 then Exit; case p^ of 'T', ' ' : Inc(p); else raise EISO8601Exception.Create('"T" expected after date'); end; h:=Read2Digits; separator:=(p^=':'); if separator then Inc(p); n:=Read2Digits; case p^ of ':', '0'..'9' : begin if (p^=':')<>separator then begin if separator then raise EISO8601Exception.Create('":" expected after minutes') else raise EISO8601Exception.Create('Unexpected ":" after minutes'); end; Inc(p); s:=Read2Digits; end; else s:=0; end; Result:=Result+EncodeTime(h, n, s, 0); case p^ of #0 : exit; 'Z' : Inc(p); else raise EISO8601Exception.Create('Unsupported ISO8601 time zone'); end; if p^<>#0 then raise EISO8601Exception.Create('Unsupported or invalid ISO8601 format'); end; // TryISO8601ToDateTime // function TryISO8601ToDateTime(const v : String; var aResult : TDateTime) : Boolean; begin try aResult:=ISO8601ToDateTime(v); Result:=True; except on E : EISO8601Exception do Result:=False; else raise end; end; // FastCompareFloat // function FastCompareFloat(d1, d2 : PDouble) : Integer; {$ifdef WIN32_ASM} asm fld qword ptr [edx] fld qword ptr [eax] xor eax, eax fcomip st, st(1) setnbe cl setb al and ecx, 1 neg eax or eax, ecx fstp st(0) {$else} begin if d1^<d2^ then Result:=-1 else Result:=Ord(d1^>d2^); {$endif} end; // RawByteStringToScriptString // function RawByteStringToScriptString(const s : RawByteString) : UnicodeString; begin RawByteStringToScriptString(s, Result); end; // RawByteStringToScriptString // procedure RawByteStringToScriptString(const s : RawByteString; var result : UnicodeString); overload; begin if s='' then begin result:=''; exit; end; BytesToScriptString(Pointer(s), Length(s), result) end; // BytesToScriptString // procedure BytesToScriptString(const p : PByte; n : Integer; var result : UnicodeString); overload; var i : Integer; pSrc : PByteArray; pDest : PWordArray; begin SetLength(result, n); pSrc:=PByteArray(p); pDest:=PWordArray(Pointer(result)); for i:=0 to n-1 do pDest[i]:=Word(PByte(@pSrc[i])^); end; // ------------------ // ------------------ TStringUnifier ------------------ // ------------------ // Create // constructor TStringUnifier.Create; begin inherited; FLock:=TMultiReadSingleWrite.Create; end; // Destroy // destructor TStringUnifier.Destroy; begin inherited; FLock.Free; end; // UnifyAssign // procedure TStringUnifier.UnifyAssign(const aString : UnicodeString; h : Cardinal; var unifiedString : UnicodeString); var i : Integer; bucket : PStringUnifierBucket; begin if FGrowth=0 then Grow; i:=(h and (FCapacity-1)); repeat bucket:=@FBuckets[i]; if (bucket^.Hash=h) and (bucket^.Str=aString) then begin unifiedString:=bucket^.Str; Exit; end else if bucket^.Hash=0 then begin bucket^.Hash:=h; bucket^.Str:=aString; unifiedString:=aString; Inc(FCount); Dec(FGrowth); Exit; end; i:=(i+1) and (FCapacity-1); until False; end; // Lock // procedure TStringUnifier.Lock; begin FLock.BeginWrite; end; // UnLock // procedure TStringUnifier.UnLock; begin FLock.EndWrite; end; // Clear // procedure TStringUnifier.Clear; begin SetLength(FBuckets, 0); FCount:=0; FGrowth:=0; FCapacity:=0; end; // Grow // procedure TStringUnifier.Grow; var i, j, n : Integer; oldBuckets : TStringUnifierBuckets; begin if FCapacity=0 then FCapacity:=32 else FCapacity:=FCapacity*2; FGrowth:=(FCapacity*3) div 4-FCount; oldBuckets:=FBuckets; FBuckets:=nil; SetLength(FBuckets, FCapacity); n:=FCapacity-1; for i:=0 to High(oldBuckets) do begin if oldBuckets[i].Hash=0 then continue; j:=(oldBuckets[i].Hash and (FCapacity-1)); while FBuckets[j].Hash<>0 do j:=(j+1) and n; FBuckets[j].Hash:=oldBuckets[i].Hash; FBuckets[j].Str:=oldBuckets[i].Str; end; end; // ------------------ // ------------------ UnicodeString Unifier ------------------ // ------------------ type {$IFNDEF FPC} {$IF CompilerVersion > 22} TStringListList = TStringItemList; {$ELSE} TStringListList = PStringItemList; {$IFEND} {$ELSE} TStringListList = PStringItemList; {$ENDIF} {$ifndef FPC} TStringListCracker = class (TStrings) private FList : TStringListList; end; {$endif} var vUnifiedStrings : array [0..63] of TStringUnifier; // CompareStrings // {$ifdef FPC} function TFastCompareStringList.DoCompareText(const S1, S2: String): Integer; begin Result:=CompareStr(S1, S2); end; {$else} function TFastCompareStringList.CompareStrings(const S1, S2: UnicodeString): Integer; begin Result:=CompareStr(S1, S2); end; // IndexOfName // function TFastCompareStringList.IndexOfName(const name : UnicodeString): Integer; var n, nc : Integer; nvs : WideChar; list : TStringListList; begin nvs:=NameValueSeparator; n:=Length(name); list:=TStringListCracker(Self).FList; for Result:=0 to Count-1 do begin nc:=Length(list[Result].FString); if (nc>n) and (list[Result].FString[n+1]=nvs) and CompareMem(PWideChar(Pointer(name)), PWideChar(Pointer(list[Result].FString)), n) then Exit; end; Result:=-1; end; {$endif} // InitializeStringsUnifier // procedure InitializeStringsUnifier; var i : Integer; begin for i:=Low(vUnifiedStrings) to High(vUnifiedStrings) do vUnifiedStrings[i]:=TStringUnifier.Create; end; // FinalizeStringsUnifier // procedure FinalizeStringsUnifier; var i : Integer; begin for i:=Low(vUnifiedStrings) to High(vUnifiedStrings) do begin vUnifiedStrings[i].Free; vUnifiedStrings[i]:=nil; end; end; // UnifyAssignString // procedure UnifyAssignString(const fromStr : UnicodeString; var toStr : UnicodeString); var i : Integer; su : TStringUnifier; h : Cardinal; begin if fromStr='' then toStr:='' else begin h:=SimpleStringHash(fromStr); i:=h and High(vUnifiedStrings); su:=vUnifiedStrings[i]; su.Lock; su.UnifyAssign(fromStr, h shr 6, toStr); su.UnLock; end; end; // UnifiedString // function UnifiedString(const fromStr : UnicodeString) : UnicodeString; begin UnifyAssignString(fromStr, Result); end; // TidyStringsUnifier // procedure TidyStringsUnifier; var i : Integer; su : TStringUnifier; begin for i:=Low(vUnifiedStrings) to High(vUnifiedStrings) do begin su:=vUnifiedStrings[i]; su.Lock; su.Clear; su.UnLock; end; end; // StringUnifierHistogram // function StringUnifierHistogram : TIntegerDynArray; var i : Integer; begin SetLength(Result, Length(vUnifiedStrings)); for i:=Low(vUnifiedStrings) to High(vUnifiedStrings) do Result[i-Low(vUnifiedStrings)]:=vUnifiedStrings[i].Count; end; // UnicodeCompareLen // function UnicodeCompareLen(p1, p2 : PWideChar; n : Integer) : Integer; var c1, c2 : Integer; begin for n:=n downto 1 do begin c1:=Ord(p1^); c2:=Ord(p2^); if (c1<>c2) then begin if (c1<=127) and (c2<=127) then begin if c1 in [Ord('a')..Ord('z')] then c1:=c1+(Ord('A')-Ord('a')); if c2 in [Ord('a')..Ord('z')] then c2:=c2+(Ord('A')-Ord('a')); if c1<>c2 then begin Result:=c1-c2; Exit; end; end else begin Result:=UnicodeComparePChars(p1, p2, n); Exit; end; end; Inc(p1); Inc(p2); end; Result:=0; end; // UnicodeCompareText // {$R-} function UnicodeCompareText(const s1, s2 : UnicodeString) : Integer; var n1, n2 : Integer; ps1, ps2 : PWideChar; begin ps1:=PWideChar(NativeInt(s1)); ps2:=PWideChar(NativeInt(s2)); if ps1<>nil then begin if ps2<>nil then begin n1:=PInteger(NativeUInt(ps1)-4)^; n2:=PInteger(NativeUInt(ps2)-4)^; if n1<n2 then begin Result:=UnicodeCompareLen(ps1, ps2, n1); if Result=0 then Result:=-1; end else begin Result:=UnicodeCompareLen(ps1, ps2, n2); if (Result=0) and (n1>n2) then Result:=1; end; end else Result:=1; end else if ps2<>nil then Result:=-1 else Result:=0; end; // UnicodeSameText // function UnicodeSameText(const s1, s2 : UnicodeString) : Boolean; begin Result:=(Length(s1)=Length(s2)) and (UnicodeCompareText(s1, s2)=0) end; // AsciiCompareLen // function AsciiCompareLen(p1, p2 : PAnsiChar; n : Integer) : Integer; var c1, c2 : Integer; begin for n:=n downto 1 do begin c1:=Ord(p1^); c2:=Ord(p2^); if (c1<>c2) then begin if c1 in [Ord('a')..Ord('z')] then c1:=c1+(Ord('A')-Ord('a')); if c2 in [Ord('a')..Ord('z')] then c2:=c2+(Ord('A')-Ord('a')); if c1<>c2 then begin Result:=c1-c2; Exit; end; end; Inc(p1); Inc(p2); end; Result:=0; end; // AsciiCompareText // function AsciiCompareText(p : PAnsiChar; const s : RawByteString) : Integer; var n : Integer; begin n:=Length(s); if n>0 then Result:=AsciiCompareLen(p, Pointer(s), n) else Result:=0; if Result=0 then if p[n]<>#0 then Result:=1; end; // AsciiSameText // function AsciiSameText(p : PAnsiChar; const s : RawByteString) : Boolean; begin Result:=(AsciiCompareText(p, s)=0); end; // PosA // function PosA(const sub, main : RawByteString) : Integer; inline; begin Result:=Pos(sub, main); end; // StrIsASCII // function StrIsASCII(const s : String) : Boolean; var i : Integer; begin for i:=1 to Length(s)-1 do begin case s[i] of #0..#127 :; else Exit(False); end; end; Result:=True; end; // StrNonNilLength // function StrNonNilLength(const aString : UnicodeString) : Integer; begin Result:=PInteger(NativeUInt(Pointer(aString))-4)^; end; // StrIBeginsWith // function StrIBeginsWith(const aStr, aBegin : UnicodeString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aBegin); if (n2>n1) or (n2=0) then Result:=False else Result:=(UnicodeCompareLen(PWideChar(aStr), PWideChar(aBegin), n2)=0); end; // StrBeginsWith // function StrBeginsWith(const aStr, aBegin : UnicodeString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aBegin); if (n2>n1) or (n2=0) then Result:=False else Result:=CompareMem(Pointer(aStr), Pointer(aBegin), n2*SizeOf(WideChar)); end; // StrBeginsWithA // function StrBeginsWithA(const aStr, aBegin : RawByteString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aBegin); if (n2>n1) or (n2=0) then Result:=False else Result:=CompareMem(Pointer(aStr), Pointer(aBegin), n2); end; // StrBeginsWithBytes // function StrBeginsWithBytes(const aStr : RawByteString; const bytes : array of Byte) : Boolean; var i, n : Integer; begin n:=Length(bytes); if Length(aStr)<n then Result:=False else begin for i:=0 to n-1 do if Ord(PAnsiChar(Pointer(aStr))[i])<>bytes[i] then Exit(False); Result:=True; end; end; // StrIEndsWith // function StrIEndsWith(const aStr, aEnd : UnicodeString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aEnd); if (n2>n1) or (n2=0) then Result:=False else Result:=(UnicodeCompareLen(@aStr[n1-n2+1], Pointer(aEnd), n2)=0); end; // StrIEndsWithA // function StrIEndsWithA(const aStr, aEnd : RawByteString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aEnd); if (n2>n1) or (n2=0) then Result:=False else Result:=(AsciiCompareLen(@aStr[n1-n2+1], Pointer(aEnd), n2)=0); end; // StrEndsWith // function StrEndsWith(const aStr, aEnd : UnicodeString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aEnd); if (n2>n1) or (n2=0) then Result:=False else Result:=CompareMem(@aStr[n1-n2+1], Pointer(aEnd), n2*SizeOf(WideChar)); end; // StrEndsWithA // function StrEndsWithA(const aStr, aEnd : RawByteString) : Boolean; var n1, n2 : Integer; begin n1:=Length(aStr); n2:=Length(aEnd); if (n2>n1) or (n2=0) then Result:=False else Result:=CompareMem(@aStr[n1-n2+1], Pointer(aEnd), n2); end; // StrContains (sub string) // function StrContains(const aStr, aSubStr : UnicodeString) : Boolean; begin if aSubStr='' then Result:=True else if StrNonNilLength(aSubStr)=1 then Result:=StrContains(aStr, aSubStr[1]) else Result:=(Pos(aSubStr, aStr)>0); end; // LowerCaseA // function LowerCaseA(const aStr : RawByteString) : RawByteString; var i, n : Integer; dst, src : PByte; c : Byte; begin n:=Length(aStr); SetLength(Result, n); if n<=0 then Exit; dst:=Pointer(Result); src:=Pointer(aStr); for i:=1 to n do begin c:=src^; if c in [Ord('A')..Ord('Z')] then c:=c or $20; dst^:=c; Inc(src); Inc(dst); end; end; // StrMatches // function StrMatches(const aStr, aMask : UnicodeString) : Boolean; var mask : TMask; begin mask:=TMask.Create(aMask); try Result:=mask.Matches(aStr); finally mask.Free; end; end; // StrContains (sub char) // function StrContains(const aStr : UnicodeString; aChar : WideChar) : Boolean; var i : Integer; begin for i:=0 to Length(aStr)-1 do if aStr[i+1]=aChar then Exit(True); Result:=False; end; // StrDeleteLeft // function StrDeleteLeft(const aStr : UnicodeString; n : Integer) : UnicodeString; begin Result:=Copy(aStr, n+1); end; // StrDeleteRight // function StrDeleteRight(const aStr : UnicodeString; n : Integer) : UnicodeString; begin Result:=Copy(aStr, 1, Length(aStr)-n); end; // StrAfterChar // function StrAfterChar(const aStr : UnicodeString; aChar : WideChar) : UnicodeString; var p : Integer; begin p:=Pos(aChar, aStr); if p>0 then Result:=Copy(aStr, p+1) else Result:=''; end; // StrBeforeChar // function StrBeforeChar(const aStr : UnicodeString; aChar : WideChar) : UnicodeString; var p : Integer; begin p:=Pos(aChar, aStr); if p>0 then Result:=Copy(aStr, 1, p-1) else Result:=aStr; end; // StrReplaceChar // function StrReplaceChar(const aStr : UnicodeString; oldChar, newChar : WideChar) : UnicodeString; var i : Integer; begin Result:=aStr; for i:=1 to Length(Result) do if Result[i]=oldChar then Result[i]:=newChar; end; // StrCountChar // function StrCountChar(const aStr : UnicodeString; c : WideChar) : Integer; var i : Integer; begin Result:=0; for i:=1 to Length(aStr) do if aStr[i]=c then Inc(Result); end; // Min // function Min(a, b : Integer) : Integer; begin if a<b then Result:=a else Result:=b; end; // WhichPowerOfTwo // function WhichPowerOfTwo(const v : Int64) : Integer; var n : Int64; begin if (v>0) and ((v and (v-1))=0) then begin for Result:=0 to 63 do begin n:=Int64(1) shl Result; if n>v then Break; if n=v then Exit; end; end; Result:=-1; end; // ------------------ // ------------------ TFastCompareTextList ------------------ // ------------------ // CompareStrings // {$ifdef FPC} function TFastCompareTextList.DoCompareText(const S1, S2: String): Integer; begin Result:=UnicodeCompareText(s1, s2); end; {$else} function TFastCompareTextList.CompareStrings(const S1, S2: UnicodeString): Integer; begin Result:=UnicodeCompareText(s1, s2); end; // FindName // function TFastCompareTextList.FindName(const name : UnicodeString; var index : Integer) : Boolean; var lo, hi, mid, cmp, n, nc : Integer; initial : UnicodeString; list : TStringListList; begin Result:=False; list:=TStringListCracker(Self).FList; initial:=Name+NameValueSeparator; n:=Length(initial); lo:=0; hi:=Count-1; while lo<=hi do begin mid:=(lo+hi) shr 1; nc:=Length(list[mid].FString); if nc>=n then begin cmp:=UnicodeCompareLen(PWideChar(Pointer(list[mid].FString)), PWideChar(Pointer(initial)), n); end else begin cmp:=UnicodeCompareLen(PWideChar(Pointer(list[mid].FString)), PWideChar(Pointer(initial)), nc); if cmp=0 then cmp:=-1; end; if cmp<0 then lo:=mid+1 else begin hi:=mid-1; if cmp=0 then begin Result:=True; if Duplicates<>dupAccept then lo:=mid; end; end; end; index:=lo; end; // IndexOfName // function TFastCompareTextList.IndexOfName(const name : UnicodeString): Integer; var n, nc : Integer; nvs : WideChar; list : TStringListList; begin if not Sorted then begin nvs:=NameValueSeparator; n:=Length(name); list:=TStringListCracker(Self).FList; for Result:=0 to Count-1 do begin nc:=Length(list[Result].FString); if (nc>n) and (list[Result].FString[n+1]=nvs) and (UnicodeCompareLen(PWideChar(Pointer(name)), PWideChar(Pointer(list[Result].FString)), n)=0) then Exit; end; Result:=-1; end else begin if not FindName(name, Result) then Result:=-1; end; end; {$endif} // ------------------ // ------------------ TVarRecArrayContainer ------------------ // ------------------ // Create // constructor TVarRecArrayContainer.Create; begin end; // Create // constructor TVarRecArrayContainer.Create(const variantArray : array of Variant); var i : Integer; begin Create; for i:=Low(variantArray) to High(variantArray) do Add(variantArray[i]); Initialize; end; // AddVarRec // function TVarRecArrayContainer.AddVarRec : PVarRec; var n : Integer; begin n:=Length(VarRecArray); SetLength(VarRecArray, n+1); Result:=@VarRecArray[n]; end; // Add // procedure TVarRecArrayContainer.Add(const v : Variant); begin if VarType(v)=varBoolean then AddBoolean(v) else if VarIsOrdinal(v) then AddInteger(v) else if VarIsNumeric(v) then AddFloat(v) else if VarIsStr(v) then AddString(v) else begin // not really supported yet, use a nil placeholder with AddVarRec^ do begin VType:=vtPointer; VPointer:=nil; end; end; end; // AddBoolean // procedure TVarRecArrayContainer.AddBoolean(const b : Boolean); begin with AddVarRec^ do begin VType:=vtBoolean; VBoolean:=b; end; end; // AddInteger // procedure TVarRecArrayContainer.AddInteger(const i : Int64); var n : Integer; begin n:=Length(FIntegers); SetLength(FIntegers, n+1); FIntegers[n]:=i; with AddVarRec^ do begin VType:=vtInt64; VInteger:=n; end; end; // AddFloat // procedure TVarRecArrayContainer.AddFloat(const f : Double); var n : Integer; begin n:=Length(FFloats); SetLength(FFloats, n+1); FFloats[n]:=f; with AddVarRec^ do begin VType:=vtExtended; VInteger:=n; end; end; // AddString // procedure TVarRecArrayContainer.AddString(const s : UnicodeString); var n : Integer; begin n:=Length(FStrings); SetLength(FStrings, n+1); FStrings[n]:=s; with AddVarRec^ do begin VType:=vtUnicodeString; VInteger:=n; end; end; // Initialize // procedure TVarRecArrayContainer.Initialize; var i : Integer; rec : PVarRec; begin for i:=0 to High(VarRecArray) do begin rec:=@VarRecArray[i]; case rec.VType of vtInt64 : rec.VInt64:=@FIntegers[rec.VInteger]; vtExtended : rec.VExtended:=@FFloats[rec.VInteger]; vtUnicodeString : rec.VString:=Pointer(FStrings[rec.VInteger]); end; end; end; // ------------------ // ------------------ TVarRecArrayContainer ------------------ // ------------------ // Clean // procedure TTightList.Clean; var i : Integer; begin case Count of 0 : Exit; 1 : TRefCountedObject(FList).Free; else for i:=Count-1 downto 0 do FList[i].Free; end; Clear; end; // Clear // procedure TTightList.Clear; begin case Count of 0 : Exit; 1 : ; else FreeMem(FList); end; FList:=nil; FCount:=0; end; // Free // procedure TTightList.Free; begin Clear; end; // GetList // function TTightList.GetList : PObjectTightList; begin if Count=1 then Result:=@FList else Result:=FList; end; // Add // function TTightList.Add(item : TRefCountedObject) : Integer; var buf : Pointer; begin case Count of 0 : begin FList:=PObjectTightList(item); FCount:=1; end; 1 : begin buf:=FList; FList:=AllocMem(2*SizeOf(Pointer)); FList[0]:=buf; FList[1]:=item; FCount:=2; end; else Inc(FCount); ReallocMem(FList, Count*SizeOf(Pointer)); FList[Count-1]:=item; end; Result:=FCount-1; end; // Assign // procedure TTightList.Assign(const aList : TTightList); begin Clear; FCount:=aList.FCount; case Count of 0 : Exit; 1 : FList:=aList.FList; else ReallocMem(FList, Count*SizeOf(Pointer)); System.Move(aList.FList^, FList^, Count*SizeOf(Pointer)); end; end; // IndexOf // function TTightList.IndexOf(item : TRefCountedObject) : Integer; begin case Count of 0 : Result:=-1; 1 : begin if FList=PObjectTightList(item) then Result:=0 else Result:=-1; end; else Result:=0; while Result<FCount do begin if FList[Result]=item then Exit; Inc(Result); end; Result:=-1; end; end; // Remove // function TTightList.Remove(item : TRefCountedObject) : Integer; begin Result:=IndexOf(item); if Result>=0 then Delete(Result); end; // Delete // procedure TTightList.Delete(index : Integer); var i : Integer; buf : Pointer; begin if Cardinal(index)>=Cardinal(Count) then RaiseIndexOutOfBounds else begin case Count of 1 : begin FList:=nil; FCount:=0; end; 2 : begin buf:=FList; if index=0 then FList:=PObjectTightList(FList[1]) else FList:=PObjectTightList(FList[0]); FreeMem(buf); FCount:=1; end; else for i:=index+1 to Count-1 do FList[i-1]:=FList[i]; Dec(FCount); end; end; end; // Insert // procedure TTightList.Insert(index : Integer; item : TRefCountedObject); var i : Integer; locList : PObjectTightList; begin if Cardinal(index)>Cardinal(FCount) then RaiseIndexOutOfBounds else case Count of 0 : begin FList:=PObjectTightList(item); FCount:=1; end; 1 : begin if index=1 then Add(item) else begin Add(TRefCountedObject(FList)); FList[0]:=item; end; end; else ReallocMem(FList, (FCount+1)*SizeOf(Pointer)); locList:=FList; for i:=Count-1 downto index do locList[i+1]:=locList[i]; locList[index]:=item; Inc(FCount); end; end; // Move // procedure TTightList.MoveItem(curIndex, newIndex : Integer); var item : Pointer; begin if (Cardinal(curIndex)>=Cardinal(FCount)) or (Cardinal(newIndex)>=Cardinal(FCount)) then RaiseIndexOutOfBounds else begin case curIndex-newIndex of 0 : ; // ignore -1, 1 : Exchange(curIndex, newIndex); else item:=FList[curIndex]; Delete(curIndex); Insert(newIndex, item); end; end; end; // Exchange // procedure TTightList.Exchange(index1, index2 : Integer); var item : Pointer; begin if index1<>index2 then begin item:=FList[index1]; FList[index1]:=FList[index2]; FList[index2]:=item; end; end; // ItemsAllOfClass // function TTightList.ItemsAllOfClass(aClass : TClass) : Boolean; var i : Integer; begin for i:=0 to FCount-1 do if List[i].ClassType<>aClass then Exit(False); Result:=True; end; // RaiseIndexOutOfBounds // procedure TTightList.RaiseIndexOutOfBounds; begin raise ETightListOutOfBound.Create('List index out of bounds'); end; // ------------------ // ------------------ TObjectList<T> ------------------ // ------------------ // Destroy // destructor TObjectList<T>.Destroy; begin Clear; inherited; end; // GetItem // function TObjectList<T>.GetItem(index : Integer) : T; begin Assert(Cardinal(index)<Cardinal(FCount), 'Index out of range'); Result:=FItems[index]; end; // SetItem // procedure TObjectList<T>.SetItem(index : Integer; const item : T); begin Assert(Cardinal(index)<Cardinal(FCount), 'Index out of range'); FItems[index]:=item; end; // Add // function TObjectList<T>.Add(const anItem : T) : Integer; begin if Count=Length(FItems) then SetLength(FItems, Count+8+(Count shr 4)); FItems[FCount]:=anItem; Result:=FCount; Inc(FCount); end; // IndexOf // function TObjectList<T>.IndexOf(const anItem : T) : Integer; var i : Integer; begin for i:=0 to Count-1 do if FItems[i]=anItem then Exit(i); Result:=-1; end; // Extract // function TObjectList<T>.Extract(idx : Integer) : T; var n : Integer; begin Assert(Cardinal(idx)<Cardinal(FCount), 'Index out of range'); n:=Count-1-idx; Dec(FCount); if n>0 then System.Move(FItems[idx+1], FItems[idx], SizeOf(T)*n); Result:=FItems[idx]; end; // ExtractAll // procedure TObjectList<T>.ExtractAll; begin FCount:=0; end; // Clear // procedure TObjectList<T>.Clear; var i : Integer; begin for i:=FCount-1 downto 0 do FItems[i].Free; FCount:=0; end; // ------------------ // ------------------ TSortedList<T> ------------------ // ------------------ // GetItem // function TSortedList<T>.GetItem(index : Integer) : T; begin Result:=FItems[index]; end; // Find // function TSortedList<T>.Find(const item : T; var index : Integer) : Boolean; var lo, hi, mid, compResult : Integer; begin Result:=False; lo:=0; hi:=FCount-1; while lo<=hi do begin mid:=(lo+hi) shr 1; compResult:=Compare(FItems[mid], item); if compResult<0 then lo:=mid+1 else begin hi:=mid- 1; if compResult=0 then Result:=True; end; end; index:=lo; end; // InsertItem // procedure TSortedList<T>.InsertItem(index : Integer; const anItem : T); begin if Count=Length(FItems) then SetLength(FItems, Count+8+(Count shr 4)); if index<Count then System.Move(FItems[index], FItems[index+1], (Count-index)*SizeOf(Pointer)); Inc(FCount); FItems[index]:=anItem; end; // Add // function TSortedList<T>.Add(const anItem : T) : Integer; begin Find(anItem, Result); InsertItem(Result, anItem); end; // AddOrFind // function TSortedList<T>.AddOrFind(const anItem : T; var added : Boolean) : Integer; begin added:=not Find(anItem, Result); if added then InsertItem(Result, anItem); end; // Extract // function TSortedList<T>.Extract(const anItem : T) : Integer; begin if Find(anItem, Result) then ExtractAt(Result) else Result:=-1; end; // ExtractAt // function TSortedList<T>.ExtractAt(index : Integer) : T; var n : Integer; begin Dec(FCount); Result:=FItems[index]; n:=FCount-index; if n>0 then System.Move(FItems[index+1], FItems[index], n*SizeOf(T)); SetLength(FItems, FCount); end; // IndexOf // function TSortedList<T>.IndexOf(const anItem : T) : Integer; begin if not Find(anItem, Result) then Result:=-1; end; // Clear // procedure TSortedList<T>.Clear; begin SetLength(FItems, 0); FCount:=0; end; // Clean // procedure TSortedList<T>.Clean; var i : Integer; begin for i:=0 to FCount-1 do FItems[i].Free; Clear; end; // Enumerate // procedure TSortedList<T>.Enumerate(const callback : TSimpleCallback<T>); var i : Integer; begin for i:=0 to Count-1 do if callback(FItems[i])=csAbort then Break; end; // ------------------ // ------------------ TSimpleStack<T> ------------------ // ------------------ // Grow // procedure TSimpleStack<T>.Grow; begin FCapacity:=FCapacity+8+(FCapacity shr 2); SetLength(FItems, FCapacity); end; // Push // procedure TSimpleStack<T>.Push(const item : T); begin if FCount=FCapacity then Grow; FItems[FCount]:=item; Inc(FCount); end; // Pop // procedure TSimpleStack<T>.Pop; begin Dec(FCount); end; // GetPeek // function TSimpleStack<T>.GetPeek : T; begin Result:=FItems[FCount-1]; end; // SetPeek // procedure TSimpleStack<T>.SetPeek(const item : T); begin FItems[FCount-1]:=item; end; // GetItems // function TSimpleStack<T>.GetItems(const position : Integer) : T; begin Result:=FItems[FCount-1-position]; end; // SetItems // procedure TSimpleStack<T>.SetItems(const position : Integer; const value : T); begin FItems[FCount-1-position]:=value; end; // Clear // procedure TSimpleStack<T>.Clear; begin SetLength(FItems, 0); FCount:=0; FCapacity:=0; end; // ------------------ // ------------------ TWriteOnlyBlockStream ------------------ // ------------------ // Create // constructor TWriteOnlyBlockStream.Create; begin inherited Create; AllocateCurrentBlock; end; // Destroy // destructor TWriteOnlyBlockStream.Destroy; begin inherited; FreeBlocks; end; var vWOBSPool : Pointer; // AllocFromPool // class function TWriteOnlyBlockStream.AllocFromPool : TWriteOnlyBlockStream; begin Result:=InterlockedExchangePointer(vWOBSPool, nil); if Result=nil then Result:=TWriteOnlyBlockStream.Create; end; // ReturnToPool // procedure TWriteOnlyBlockStream.ReturnToPool; var wobs : TWriteOnlyBlockStream; begin if Self=nil then Exit; Clear; if vWOBSPool=nil then begin wobs:=InterlockedExchangePointer(vWOBSPool, Self); if wobs<>nil then wobs.Destroy; end else Destroy; end; // FreeBlocks // procedure TWriteOnlyBlockStream.FreeBlocks; var iterator, next : PPointerArray; begin iterator:=FFirstBlock; while iterator<>nil do begin next:=PPointerArray(iterator[0]); FreeMem(iterator); iterator:=next; end; FCurrentBlock:=nil; FFirstBlock:=nil; FTotalSize:=0; end; // AllocateCurrentBlock // procedure TWriteOnlyBlockStream.AllocateCurrentBlock; var newBlock : PPointerArray; begin GetMem(newBlock, cWriteOnlyBlockStreamBlockSize+2*SizeOf(Pointer)); newBlock[0]:=nil; FBlockRemaining:=@newBlock[1]; FBlockRemaining^:=0; if FCurrentBlock<>nil then FCurrentBlock[0]:=newBlock else FFirstBlock:=newBlock; FCurrentBlock:=newBlock; end; // Clear // procedure TWriteOnlyBlockStream.Clear; begin FreeBlocks; AllocateCurrentBlock; end; // StoreData // procedure TWriteOnlyBlockStream.StoreData(var buffer); var n : Integer; iterator : PPointerArray; dest : PByteArray; begin dest:=@buffer; iterator:=FFirstBlock; while iterator<>nil do begin n:=PInteger(@iterator[1])^; if n>0 then begin System.Move(iterator[2], dest^, n); dest:=@dest[n]; end; iterator:=iterator[0]; end; end; // StoreData // procedure TWriteOnlyBlockStream.StoreData(destStream : TStream); var n : Integer; iterator : PPointerArray; begin iterator:=FFirstBlock; while iterator<>nil do begin n:=PInteger(@iterator[1])^; destStream.Write(iterator[2], n); iterator:=iterator[0]; end; end; // StoreUTF8Data // procedure TWriteOnlyBlockStream.StoreUTF8Data(destStream : TStream); var buf : UTF8String; begin buf:=UTF8Encode(ToString); if buf<>'' then destStream.Write(buf[1], Length(buf)); end; // Seek // function TWriteOnlyBlockStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Origin=soFromCurrent) and (Offset=0) then Result:=FTotalSize else raise EStreamError.Create('not allowed'); end; // Read // function TWriteOnlyBlockStream.Read(var Buffer; Count: Longint): Longint; begin raise EStreamError.Create('not allowed'); end; // WriteSpanning // procedure TWriteOnlyBlockStream.WriteSpanning(source : PByteArray; count : Integer); begin // current block contains some data, write fraction, allocate new block System.Move(source^, PByteArray(@FCurrentBlock[2])[FBlockRemaining^], count); FBlockRemaining^:=cWriteOnlyBlockStreamBlockSize; AllocateCurrentBlock; end; // WriteLarge // procedure TWriteOnlyBlockStream.WriteLarge(source : PByteArray; count : Integer); var newBlock : PPointerArray; begin // large amount still to be written, insert specific block newBlock:=GetMemory(count+2*SizeOf(Pointer)); newBlock[0]:=FCurrentBlock; PInteger(@newBlock[1])^:=count; System.Move(source^, newBlock[2], count); FCurrentBlock[0]:=newBlock; FCurrentBlock:=newBlock; AllocateCurrentBlock; end; // WriteBuf // procedure TWriteOnlyBlockStream.WriteBuf(source : PByteArray; count : Integer); type TThreeBytes = packed array [1..3] of Byte; PThreeBytes = ^TThreeBytes; TFiveBytes = packed array [1..5] of Byte; PFiveBytes = ^TFiveBytes; TSixBytes = packed array [1..6] of Byte; PSixBytes = ^TSixBytes; TSevenBytes = packed array [1..7] of Byte; PSevenBytes = ^TSevenBytes; var dest : PByteArray; fraction : Integer; begin Inc(FTotalSize, count); fraction:=cWriteOnlyBlockStreamBlockSize-FBlockRemaining^; if count>fraction then begin // does not fit in current block // was current block started? if FBlockRemaining^>0 then begin WriteSpanning(source, fraction); Dec(count, fraction); source:=@source[fraction]; end; if count>cWriteOnlyBlockStreamBlockSize div 2 then begin WriteLarge(source, count); Exit; end; end; // if we reach here, everything fits in current block dest:=@PByteArray(@FCurrentBlock[2])[FBlockRemaining^]; Inc(FBlockRemaining^, count); case Cardinal(count) of 0 : ; 1 : dest[0]:=source[0]; 2 : PWord(dest)^:=PWord(source)^; 3 : PThreeBytes(dest)^:=PThreeBytes(source)^; 4 : PCardinal(dest)^:=PCardinal(source)^; 5 : PFiveBytes(dest)^:=PFiveBytes(source)^; 6 : PSixBytes(dest)^:=PSixBytes(source)^; 7 : PSevenBytes(dest)^:=PSevenBytes(source)^; 8 : PInt64(dest)^:=PInt64(source)^; else System.Move(source^, dest^, count); end; end; // Write // function TWriteOnlyBlockStream.Write(const buffer; count: Longint): Longint; begin WriteBuf(@buffer, count); Result:=count; end; // WriteByte // procedure TWriteOnlyBlockStream.WriteByte(b : Byte); begin WriteBuf(@b, 1); end; // WriteBytes // procedure TWriteOnlyBlockStream.WriteBytes(const b : array of Byte); var n : Integer; begin n:=Length(b); if n>0 then WriteBuf(@b[0], Length(b)); end; // WriteInt32 // procedure TWriteOnlyBlockStream.WriteInt32(const i : Integer); begin WriteBuf(@i, 4); end; // WriteDWord // procedure TWriteOnlyBlockStream.WriteDWord(const dw : DWORD); begin WriteBuf(@dw, 4); end; // WriteString // procedure TWriteOnlyBlockStream.WriteString(const utf16String : UnicodeString); var stringCracker : NativeUInt; begin {$ifdef FPC} if utf16String<>'' then WriteBuf(utf16String[1], Length(utf16String)*SizeOf(WideChar)); {$else} stringCracker:=NativeUInt(utf16String); if stringCracker<>0 then WriteBuf(Pointer(stringCracker), PInteger(stringCracker-SizeOf(Integer))^*SizeOf(WideChar)); {$endif} end; // WriteString (Int32) // procedure TWriteOnlyBlockStream.WriteString(const i : Int32); var buf : TInt32StringBuffer; n : Integer; begin n:=FastInt32ToBuffer(i, buf); WriteBuf(@buf[n], (High(buf)+1-n)*SizeOf(WideChar)); end; // WriteString (Int64) // procedure TWriteOnlyBlockStream.WriteString(const i : Int64); var buf : TInt64StringBuffer; n : Integer; begin n:=FastInt64ToBuffer(i, buf); WriteBuf(@buf[n], (High(buf)+1-n)*SizeOf(WideChar)); end; // WriteChar // procedure TWriteOnlyBlockStream.WriteChar(utf16Char : WideChar); begin WriteBuf(@utf16Char, SizeOf(WideChar)); end; // WriteDigits // procedure TWriteOnlyBlockStream.WriteDigits(value : Int64; digits : Integer); var buf : array [0..19] of WideChar; n : Integer; begin if digits<=0 then Exit; Assert(digits<Length(buf)); n:=Length(buf); while digits>0 do begin Dec(n); if value<>0 then begin buf[n]:=WideChar(Ord('0')+(value mod 10)); value:=value div 10; end else buf[n]:='0'; Dec(digits); end; WriteBuf(@buf[n], (Length(buf)-n)*SizeOf(WideChar)); end; // ToString // function TWriteOnlyBlockStream.ToString : String; {$ifdef FPC} var uniBuf : UnicodeString; begin if FTotalSize>0 then begin Assert((FTotalSize and 1) = 0); SetLength(uniBuf, FTotalSize div SizeOf(WideChar)); StoreData(uniBuf[1]); Result:=UTF8Encode(uniBuf); end else Result:=''; {$else} begin if FTotalSize>0 then begin Assert((FTotalSize and 1) = 0); SetLength(Result, FTotalSize div SizeOf(WideChar)); StoreData(Result[1]); end else Result:=''; {$endif} end; // ToUTF8String // function TWriteOnlyBlockStream.ToUTF8String : RawByteString; begin Result:=UTF8Encode(ToString); end; // ToBytes // function TWriteOnlyBlockStream.ToBytes : TBytes; var s : Int64; begin s:=Size; SetLength(Result, s); if s>0 then StoreData(Result[0]); end; // ToRawBytes // function TWriteOnlyBlockStream.ToRawBytes : RawByteString; var s : Int64; begin s:=Size; SetLength(Result, s); if s>0 then StoreData(Result[1]); end; // GetSize // function TWriteOnlyBlockStream.GetSize: Int64; begin Result:=FTotalSize; end; // WriteSubString // procedure TWriteOnlyBlockStream.WriteSubString(const utf16String : UnicodeString; startPos : Integer); begin WriteSubString(utf16String, startPos, Length(utf16String)-startPos+1); end; // WriteSubString // procedure TWriteOnlyBlockStream.WriteSubString(const utf16String : UnicodeString; startPos, aLength : Integer); var p, n : Integer; begin Assert(startPos>=1); if aLength<=0 then Exit; p:=startPos+aLength-1; n:=System.Length(utf16String); if startPos>n then Exit; if p>n then n:=n-startPos+1 else n:=p-startPos+1; if n>0 then WriteBuf(@utf16String[startPos], n*SizeOf(WideChar)); end; // WriteUTF8String // procedure TWriteOnlyBlockStream.WriteUTF8String(const utf8String : RawByteString); begin WriteBuf(Pointer(utf8String), Length(utf8String)); end; // WriteCRLF // procedure TWriteOnlyBlockStream.WriteCRLF; begin WriteBuf(@cCRLF[0], 2*SizeOf(WideChar)); end; // WriteAsciiCRLF // procedure TWriteOnlyBlockStream.WriteAsciiCRLF; begin WriteBuf(@cAsciiCRLF[0], 2*SizeOf(AnsiChar)); end; // ------------------ // ------------------ TTightStack ------------------ // ------------------ // Grow // procedure TTightStack.Grow; begin FCapacity:=FCapacity+8+FCapacity shr 1; ReallocMem(FList, FCapacity*SizeOf(Pointer)); end; // Push // procedure TTightStack.Push(item : TRefCountedObject); begin if FCount=FCapacity then Grow; FList[FCount]:=item; Inc(FCount); end; // Peek // function TTightStack.Peek : TRefCountedObject; begin Result:=FList[FCount-1]; end; // Pop // procedure TTightStack.Pop; begin Dec(FCount); end; // Clear // procedure TTightStack.Clear; begin FCount:=0; end; // Clean // procedure TTightStack.Clean; begin while Count>0 do begin TRefCountedObject(Peek).Free; Pop; end; end; // Free // procedure TTightStack.Free; begin FCount:=0; FCapacity:=0; FreeMem(FList); FList:=nil; end; // ------------------ // ------------------ TSimpleHash<T> ------------------ // ------------------ // Grow // procedure TSimpleHash<T>.Grow; var i, j, n : Integer; hashCode : Integer; {$IFDEF DELPHI_XE3} oldBuckets : array of TSimpleHashBucket<T>; {$ELSE} oldBuckets : TSimpleHashBucketArray<T>; {$ENDIF} begin if FCapacity=0 then FCapacity:=32 else FCapacity:=FCapacity*2; FGrowth:=(FCapacity*11) div 16; {$IFDEF DELPHI_XE3} SetLength(oldBuckets, Length(FBuckets)); for i := 0 to Length(FBuckets) - 1 do oldBuckets[i] := FBuckets[i]; {$ELSE} oldBuckets:=FBuckets; {$ENDIF} FBuckets:=nil; SetLength(FBuckets, FCapacity); n:=FCapacity-1; for i:=0 to High(oldBuckets) do begin if oldBuckets[i].HashCode=0 then continue; j:=(oldBuckets[i].HashCode and (FCapacity-1)); while FBuckets[j].HashCode<>0 do j:=(j+1) and n; FBuckets[j]:=oldBuckets[i]; end; end; // LinearFind // function TSimpleHash<T>.LinearFind(const item : T; var index : Integer) : Boolean; begin repeat if FBuckets[index].HashCode=0 then Exit(False) else if SameItem(item, FBuckets[index].Value) then Exit(True); index:=(index+1) and (FCapacity-1); until False; end; // Add // function TSimpleHash<T>.Add(const anItem : T) : Boolean; var i : Integer; hashCode : Integer; begin if FCount>=FGrowth then Grow; hashCode:=GetItemHashCode(anItem); i:=(hashCode and (FCapacity-1)); if LinearFind(anItem, i) then Exit(False); FBuckets[i].HashCode:=hashCode; FBuckets[i].Value:=anItem; Inc(FCount); Result:=True; end; // Replace // function TSimpleHash<T>.Replace(const anItem : T) : Boolean; var i : Integer; hashCode : Integer; begin if FCount>=FGrowth then Grow; hashCode:=GetItemHashCode(anItem); i:=(hashCode and (FCapacity-1)); if LinearFind(anItem, i) then begin FBuckets[i].Value:=anItem end else begin FBuckets[i].HashCode:=hashCode; FBuckets[i].Value:=anItem; Inc(FCount); Result:=True; end; end; // Contains // function TSimpleHash<T>.Contains(const anItem : T) : Boolean; var i : Integer; begin if FCount=0 then Exit(False); i:=(GetItemHashCode(anItem) and (FCapacity-1)); Result:=LinearFind(anItem, i); end; // Match // function TSimpleHash<T>.Match(var anItem : T) : Boolean; var i : Integer; begin if FCount=0 then Exit(False); i:=(GetItemHashCode(anItem) and (FCapacity-1)); Result:=LinearFind(anItem, i); if Result then anItem:=FBuckets[i].Value; end; // Enumerate // procedure TSimpleHash<T>.Enumerate(callBack : TSimpleHashProc<T>); var i : Integer; begin for i:=0 to High(FBuckets) do if FBuckets[i].HashCode<>0 then callBack(FBuckets[i].Value); end; // Clear // procedure TSimpleHash<T>.Clear; begin FCount:=0; FCapacity:=0; FGrowth:=0; SetLength(FBuckets, 0); end; // ------------------ // ------------------ TSimpleObjectHash<T> ------------------ // ------------------ // SameItem // function TSimpleObjectHash<T>.SameItem(const item1, item2 : T) : Boolean; begin Result:=(item1=item2); end; // GetItemHashCode // function TSimpleObjectHash<T>.GetItemHashCode(const item1 : T) : Integer; var p : NativeInt; begin p:=PNativeInt(@item1)^; // workaround compiler issue Result:=(p shr 4)+1; end; // Clean // procedure TSimpleObjectHash<T>.Clean; var i : Integer; begin for i:=0 to FCapacity-1 do if FBuckets[i].HashCode<>0 then FBuckets[i].Value.Free; Clear; end; // ------------------ // ------------------ TSimpleList<T> ------------------ // ------------------ // Add // procedure TSimpleList<T>.Add(const item : T); begin if FCount=FCapacity then Grow; FItems[FCount]:=item; Inc(FCount); end; // Extract // procedure TSimpleList<T>.Extract(idx : Integer); var n : Integer; begin FItems[idx]:=Default(T); n:=FCount-idx-1; if n>0 then begin Move(FItems[idx+1], FItems[idx], n*SizeOf(T)); FillChar(FItems[FCount-1], SizeOf(T), 0); end; Dec(FCount); end; // Clear // procedure TSimpleList<T>.Clear; begin SetLength(FItems, 0); FCapacity:=0; FCount:=0; end; // Enumerate // procedure TSimpleList<T>.Enumerate(const callback : TSimpleCallback<T>); var i : Integer; begin for i:=0 to Count-1 do if callBack(FItems[i])=csAbort then Break; end; // Grow // procedure TSimpleList<T>.Grow; begin FCapacity:=FCapacity+8+(FCapacity shr 2); SetLength(FItems, FCapacity); end; // GetItems // function TSimpleList<T>.GetItems(const idx : Integer) : T; begin Result:=FItems[idx]; end; // SetItems // procedure TSimpleList<T>.SetItems(const idx : Integer; const value : T); begin FItems[idx]:=value; end; // ------------------ // ------------------ TObjectsLookup ------------------ // ------------------ // Compare // function TObjectsLookup.Compare(const item1, item2 : TRefCountedObject) : Integer; begin if NativeUInt(item1)<NativeUInt(item2) then Result:=-1 else if NativeUInt(item1)=NativeUInt(item2) then Result:=0 else Result:=-1; end; // ------------------ // ------------------ TInterfacedSelfObject ------------------ // ------------------ // GetSelf // function TInterfacedSelfObject.GetSelf : TObject; begin Result:=Self; end; // QueryInterface // function TInterfacedSelfObject.QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result:=0 else Result:=E_NOINTERFACE; end; // _AddRef // function TInterfacedSelfObject._AddRef: Integer; begin Result:=IncRefCount; end; // _Release // function TInterfacedSelfObject._Release: Integer; begin Result:=DecRefCount; if Result=0 then Destroy; end; // NewInstance // class function TInterfacedSelfObject.NewInstance: TObject; begin Result:=inherited NewInstance; TRefCountedObject(Result).IncRefCount; end; // AfterConstruction // procedure TInterfacedSelfObject.AfterConstruction; begin // Release the constructor's implicit refcount DecRefCount; end; // BeforeDestruction // procedure TInterfacedSelfObject.BeforeDestruction; begin Assert(RefCount=0); end; // ------------------ // ------------------ TAutoStrings ------------------ // ------------------ // Create // constructor TAutoStrings.Create; begin FValue:=TStringList.Create; end; // Destroy // destructor TAutoStrings.Destroy; begin FValue.Free; end; // CreateCapture // constructor TAutoStrings.CreateCapture(value : TStringList); begin FValue:=value; end; // CreateClone // constructor TAutoStrings.CreateClone(value : TStringList); var sl : TStringList; begin sl:=TStringList.Create; FValue:=sl; sl.Assign(value); sl.CaseSensitive:=value.CaseSensitive; sl.Sorted:=value.Sorted; end; // GetValue // function TAutoStrings.GetValue : TStringList; begin Result:=FValue; end; // Clone // function TAutoStrings.Clone : IAutoStrings; begin Result:=TAutoStrings.CreateClone(FValue); end; // ------------------ // ------------------ TSimpleNameObjectHash<T> ------------------ // ------------------ // Create // constructor TSimpleNameObjectHash<T>.Create(initialCapacity : Integer = 0); begin if initialCapacity>0 then begin // check if initial capacity is a power of two Assert((initialCapacity and (initialCapacity-1))=0); SetLength(FBuckets, initialCapacity); end; FHighIndex:=initialCapacity-1; end; // Grow // procedure TSimpleNameObjectHash<T>.Grow; var i, j : Integer; hashCode : Integer; oldBuckets : TNameObjectHashBuckets; begin if FHighIndex<0 then FHighIndex:=31 else FHighIndex:=FHighIndex*2+1; FGrowth:=(FHighIndex*3) div 4; oldBuckets:=FBuckets; FBuckets:=nil; SetLength(FBuckets, FHighIndex+1); for i:=0 to High(oldBuckets) do begin if oldBuckets[i].HashCode=0 then continue; j:=(oldBuckets[i].HashCode and FHighIndex); while FBuckets[j].HashCode<>0 do j:=(j+1) and FHighIndex; FBuckets[j]:=oldBuckets[i]; end; end; // GetIndex // function TSimpleNameObjectHash<T>.GetIndex(const aName : UnicodeString) : Integer; var h : Cardinal; i : Integer; begin if FCount=0 then Exit(-1); if aName='' then h:=1 else h:=SimpleStringHash(aName); i:=h and FHighIndex; repeat with FBuckets[i] do begin if HashCode=0 then Exit(-1) else if (HashCode=h) and (Name=aName) then Exit(i); end; i:=(i+1) and FHighIndex; until False; end; // GetObjects // function TSimpleNameObjectHash<T>.GetObjects(const aName : UnicodeString) : T; var i : Integer; begin i:=GetIndex(aName); if i<0 then begin {$ifdef VER200} Exit(default(T)); // D2009 support {$else} Exit(T(TObject(nil))); // workaround for D2010 compiler bug {$endif} end else Result:=FBuckets[i].Obj end; //var // h : Cardinal; // i : Integer; //begin // if FCount=0 then // {$ifdef VER200} // Exit(default(T)); // D2009 support // {$else} // Exit(T(TObject(nil))); // workaround for D2010 compiler bug // {$endif} // // h:=SimpleStringHash(aName); // i:=h and FHighIndex; // // repeat // with FBuckets[i] do begin // if HashCode=0 then begin // {$ifdef VER200} // Exit(default(T)); // D2009 support // {$else} // Exit(T(TObject(nil))); // workaround for D2010 compiler bug // {$endif} // end else if (HashCode=h) and (Name=aName) then // Exit(Obj); // end; // i:=(i+1) and FHighIndex; // until False; //end; // SetObjects // procedure TSimpleNameObjectHash<T>.SetObjects(const aName : UnicodeString; obj : T); begin AddObject(aName, obj, True); end; // AddObject // function TSimpleNameObjectHash<T>.AddObject(const aName : UnicodeString; aObj : T; replace : Boolean = False) : Boolean; var i : Integer; h : Cardinal; begin if FCount>=FGrowth then Grow; if aName='' then h:=1 else h:=SimpleStringHash(aName); i:=h and FHighIndex; repeat with FBuckets[i] do begin if HashCode=0 then Break else if (HashCode=h) and (Name=aName) then begin if replace then Obj:=aObj; Exit(False); end; end; i:=(i+1) and FHighIndex; until False; with FBuckets[i] do begin HashCode:=h; Name:=aName; Obj:=aObj; end; Inc(FCount); Result:=True; end; // Clean // procedure TSimpleNameObjectHash<T>.Clean; var i : Integer; begin for i:=0 to FHighIndex do begin if FBuckets[i].HashCode<>0 then dwsFreeAndNil(FBuckets[i].Obj); end; Clear; end; // Clear // procedure TSimpleNameObjectHash<T>.Clear; begin SetLength(FBuckets, 0); FGrowth:=0; FCount:=0; FHighIndex:=-1; end; // GetBucketName // function TSimpleNameObjectHash<T>.GetBucketName(index : Integer) : String; begin Result:=FBuckets[index].Name; end; // GetBucketObject // function TSimpleNameObjectHash<T>.GetBucketObject(index : Integer) : T; begin Result:=FBuckets[index].Obj; end; // SetBucketObject // procedure TSimpleNameObjectHash<T>.SetBucketObject(index : Integer; obj : T); begin FBuckets[index].Obj:=obj; end; // ------------------ // ------------------ TRefCountedObject ------------------ // ------------------ // Free // procedure TRefCountedObject.Free; begin if Self<>nil then DecRefCount; end; // IncRefCount // function TRefCountedObject.IncRefCount : Integer; var p : PInteger; begin {$ifdef FPC} p:=@FRefCount; {$else} p:=PInteger(NativeInt(Self)+InstanceSize-hfFieldSize+hfMonitorOffset); {$endif} Result:=InterlockedIncrement(p^); end; // DecRefCount // function TRefCountedObject.DecRefCount : Integer; var p : PInteger; begin {$ifdef FPC} p:=@FRefCount; {$else} p:=PInteger(NativeInt(Self)+InstanceSize-hfFieldSize+hfMonitorOffset); {$endif} if p^=0 then begin Destroy; Result:=0; end else Result:=InterlockedDecrement(p^); end; // GetRefCount // function TRefCountedObject.GetRefCount : Integer; var p : PInteger; begin {$ifdef FPC} p:=@FRefCount; {$else} p:=PInteger(NativeInt(Self)+InstanceSize-hfFieldSize+hfMonitorOffset); {$endif} Result:=p^; end; // SetRefCount // procedure TRefCountedObject.SetRefCount(n : Integer); var p : PInteger; begin {$ifdef FPC} p:=@FRefCount; {$else} p:=PInteger(NativeInt(Self)+InstanceSize-hfFieldSize+hfMonitorOffset); {$endif} p^:=n; end; // ------------------ // ------------------ TSimpleObjectObjectHash<T1, T2> ------------------ // ------------------ // Grow // procedure TSimpleObjectObjectHash<TKey, TValue>.Grow; var i, j, n : Integer; hashCode : Integer; oldBuckets : TObjectObjectHashBuckets; begin if FCapacity=0 then FCapacity:=32 else FCapacity:=FCapacity*2; FGrowth:=(FCapacity*3) div 4; oldBuckets:=FBuckets; FBuckets:=nil; SetLength(FBuckets, FCapacity); n:=FCapacity-1; for i:=0 to High(oldBuckets) do begin if oldBuckets[i].HashCode=0 then continue; j:=(oldBuckets[i].HashCode and (FCapacity-1)); while FBuckets[j].HashCode<>0 do j:=(j+1) and n; FBuckets[j]:=oldBuckets[i]; end; end; // GetItemHashCode // function TSimpleObjectObjectHash<TKey, TValue>.GetItemHashCode(const item1 : TObjectObjectHashBucket) : Integer; begin Result:=(PNativeInt(@item1.Key)^ shr 2); end; // GetValue // function TSimpleObjectObjectHash<TKey, TValue>.GetValue(aKey : TKey) : TValue; var bucket : TObjectObjectHashBucket; begin bucket.Key:=aKey; if Match(bucket) then Result:=bucket.Value {$ifdef VER200} else Result:=default(TValue); // D2009 support {$else} else Result:=TValue(TObject(nil)); // workaround for D2010 compiler bug {$endif} end; // SetValue // procedure TSimpleObjectObjectHash<TKey, TValue>.SetValue(aKey : TKey; aValue : TValue); var bucket : TObjectObjectHashBucket; begin bucket.Key:=aKey; bucket.Value:=aValue; Replace(bucket); end; // LinearFind // function TSimpleObjectObjectHash<TKey, TValue>.LinearFind(const item : TObjectObjectHashBucket; var index : Integer) : Boolean; begin repeat if FBuckets[index].HashCode=0 then Exit(False) else if item.Key=FBuckets[index].Key then Exit(True); index:=(index+1) and (FCapacity-1); until False; end; // Match // function TSimpleObjectObjectHash<TKey, TValue>.Match(var anItem : TObjectObjectHashBucket) : Boolean; var i : Integer; begin if FCount=0 then Exit(False); i:=(GetItemHashCode(anItem) and (FCapacity-1)); Result:=LinearFind(anItem, i); if Result then anItem:=FBuckets[i]; end; // Replace // function TSimpleObjectObjectHash<TKey, TValue>.Replace(const anItem : TObjectObjectHashBucket) : Boolean; var i : Integer; hashCode : Integer; begin if FCount>=FGrowth then Grow; hashCode:=GetItemHashCode(anItem); i:=(hashCode and (FCapacity-1)); if LinearFind(anItem, i) then begin FBuckets[i]:=anItem end else begin FBuckets[i]:=anItem; FBuckets[i].HashCode:=hashCode; Inc(FCount); Result:=True; end; end; // CleanValues // procedure TSimpleObjectObjectHash<TKey, TValue>.CleanValues; var i : Integer; begin for i:=0 to FCapacity-1 do begin if FBuckets[i].HashCode<>0 then FBuckets[i].Value.Free; end; Clear; end; // Clear // procedure TSimpleObjectObjectHash<TKey, TValue>.Clear; begin FCount:=0; FCapacity:=0; FGrowth:=0; SetLength(FBuckets, 0); end; // ------------------ // ------------------ TThreadCached<T> ------------------ // ------------------ // Create // constructor TThreadCached<T>.Create(const aNeedValue : TSimpleCallback<T>; maxAgeMSec : Integer); begin FLock:=TMultiReadSingleWrite.Create; FOnNeedValue:=aNeedValue; FMaxAge:=maxAgeMSec; end; // Destroy // destructor TThreadCached<T>.Destroy; begin FLock.Free; end; // Invalidate // procedure TThreadCached<T>.Invalidate; begin FExpiresAt:=0; end; // GetValue // function TThreadCached<T>.GetValue : T; var ts : Int64; begin ts:=GetSystemMilliseconds; if ts>=FExpiresAt then begin FLock.BeginWrite; try if FOnNeedValue(FValue)=csContinue then FExpiresAt:=ts+FMaxAge; Result:=FValue; finally FLock.EndWrite; end; end else begin FLock.BeginRead; try Result:=FValue; finally FLock.EndRead; end; end; end; // SetValue // procedure TThreadCached<T>.SetValue(const v : T); begin FLock.BeginWrite; try FExpiresAt:=GetSystemMilliseconds+FMaxAge; FValue:=v; finally FLock.EndWrite; end; end; // ------------------ // ------------------ TSimpleIntegerStack ------------------ // ------------------ // Create // constructor TSimpleIntegerStack.Create; begin FChunk:=@FBaseChunk; FChunkIndex:=-1; end; // Destroy // destructor TSimpleIntegerStack.Destroy; begin Clear; end; // Allocate // class function TSimpleIntegerStack.Allocate : TSimpleIntegerStack; var p : Pointer; n : Integer; begin n:=InstanceSize; GetMem(p, n); Move(Pointer(vTemplate)^, p^, n); Result:=TSimpleIntegerStack(p); Result.FChunk:=@Result.FBaseChunk; end; // Push // procedure TSimpleIntegerStack.Push(const item : Integer); begin if FChunkIndex<TSimpleIntegerStackChunk.ChunkSize-1 then Inc(FChunkIndex) else Grow; FChunk.Data[FChunkIndex]:=item; Inc(FCount); end; // Pop // procedure TSimpleIntegerStack.Pop; begin if FChunkIndex>0 then Dec(FChunkIndex) else Shrink; Dec(FCount); end; // Clear // procedure TSimpleIntegerStack.Clear; var p : PSimpleIntegerStackChunk; begin if FPooledChunk<>nil then FreeMem(FPooledChunk); FPooledChunk:=nil; while FChunk<>@FBaseChunk do begin p:=FChunk; FChunk:=p.Prev; FreeMem(p); end; end; // Grow // procedure TSimpleIntegerStack.Grow; var p : PSimpleIntegerStackChunk; begin if FPooledChunk<>nil then begin p:=FPooledChunk; FPooledChunk:=nil; end else GetMem(p, SizeOf(TSimpleIntegerStackChunk)); p.Prev:=FChunk; FChunk:=p; FChunkIndex:=0; end; // Shrink // procedure TSimpleIntegerStack.Shrink; begin if FChunk.Prev=nil then Dec(FChunkIndex) else begin FreeMem(FPooledChunk); FPooledChunk:=FChunk; FChunk:=FChunk.Prev; FChunkIndex:=TSimpleIntegerStackChunk.ChunkSize-1; end; end; // GetPeek // function TSimpleIntegerStack.GetPeek : Integer; begin Result:=FChunk.Data[FChunkIndex]; end; // SetPeek // procedure TSimpleIntegerStack.SetPeek(const item : Integer); begin FChunk.Data[FChunkIndex]:=item; end; // ------------------ // ------------------ TClassCloneConstructor<T> ------------------ // ------------------ // Initialize // procedure TClassCloneConstructor<T>.Initialize(aTemplate : T); begin FTemplate:=aTemplate; FSize:= FTemplate.InstanceSize; end; // Finalize // procedure TClassCloneConstructor<T>.Finalize; begin FTemplate.Free; FTemplate:=nil; end; // Create // function TClassCloneConstructor<T>.Create : T; begin GetMemForT(Result, FSize); Move(TtoPointer(FTemplate)^, TtoPointer(Result)^, FSize); end; // ------------------ // ------------------ TQuickSort ------------------ // ------------------ // Sort // procedure TQuickSort.Sort(minIndex, maxIndex : Integer); var i, j, p, n : Integer; begin n:=maxIndex-minIndex; case n of 1 : begin if CompareMethod(minIndex, maxIndex)>0 then SwapMethod(minIndex, maxIndex); end; 2 : begin i:=minIndex+1; if CompareMethod(minIndex,i)>0 then SwapMethod(minIndex, i); if CompareMethod(i, maxIndex)>0 then begin SwapMethod(i, maxIndex); if CompareMethod(minIndex, i)>0 then SwapMethod(minIndex, i); end; end; else if n<=0 then Exit; repeat i:=minIndex; j:=maxIndex; p:=((i+j) shr 1); repeat while CompareMethod(i, p)<0 do Inc(i); while CompareMethod(j, p)>0 do Dec(j); if i<=j then begin SwapMethod(i, j); if p=i then p:=j else if p=j then p:=i; Inc(i); Dec(j); end; until i>j; if minIndex<j then Sort(minIndex, j); minIndex:=i; until i>=maxIndex; end; end; // ------------------ // ------------------ TSimpleQueue<T> ------------------ // ------------------ // Create // constructor TSimpleQueue<T>.Create(poolSize: Integer); begin FPoolLeft:=poolSize; end; // Destroy // destructor TSimpleQueue<T>.Destroy; var next : PItemT; begin Clear; while FPool<>nil do begin next:=FPool.Next; FreeMem(FPool); FPool:=next; end; inherited; end; // Alloc // function TSimpleQueue<T>.Alloc: PItemT; begin if FPool=nil then Result:=AllocMem(SizeOf(ItemT)) else begin Result:=FPool; FPool:=Result.Next; Result.Next:=nil; Inc(FPoolLeft); end; Inc(FCount); end; // Release // procedure TSimpleQueue<T>.Release(i: PItemT); begin i.Value:=Default(T); if FPoolLeft>0 then begin Dec(FPoolLeft); i.Prev:=nil; i.Next:=FPool; FPool:=i; end else FreeMem(i); Dec(FCount); end; // Push // procedure TSimpleQueue<T>.Push(const v: T); var p : PItemT; begin p:=Alloc; p.Value:=v; if FLast<>nil then begin p.Prev:=FLast; FLast.Next:=p; end else FFirst:=p; FLast:=p; end; // Pop // function TSimpleQueue<T>.Pop(var v: T) : Boolean; var p : PItemT; begin if FCount=0 then Exit(False); p:=FLast; FLast:=p.Prev; v:=p.Value; Release(p); if FLast<>nil then FLast.Next:=nil else FFirst:=FLast; Result:=True; end; // Pop // function TSimpleQueue<T>.Pop : T; begin Assert(Count>0); Pop(Result); end; // Insert // procedure TSimpleQueue<T>.Insert(const v: T); var p : PItemT; begin p:=Alloc; p.Value:=v; if FFirst<>nil then begin p.Next:=FFirst; FFirst.Prev:=p; end else FLast:=p; FFirst:=p; end; // Pull // function TSimpleQueue<T>.Pull(var v: T) : Boolean; var p : PItemT; begin if FCount=0 then Exit(False); p:=FFirst; FFirst:=p.Next; v:=p.Value; Release(p); if FFirst<>nil then FFirst.Prev:=nil else FLast:=FFirst; Result:=True; end; // Pull // function TSimpleQueue<T>.Pull : T; begin Assert(Count>0); Pull(Result); end; // Clear // procedure TSimpleQueue<T>.Clear; var p, pNext : PItemT; begin p:=FFirst; while p<>nil do begin pNext:=p.Next; Release(p); p:=pNext; end; FFirst:=nil; FLast:=nil; end; // ------------------ // ------------------ EdwsVariantTypeCastError ------------------ // ------------------ // Create // constructor EdwsVariantTypeCastError.Create(const v : Variant; const desiredType : UnicodeString; originalException : Exception); begin inherited CreateFmt(RTE_VariantCastFailed, [VarTypeAsText(VarType(v)), desiredType, originalException.ClassName]) end; // ------------------ // ------------------ TAutoWriteOnlyBlockStream ------------------ // ------------------ // Create // constructor TAutoWriteOnlyBlockStream.Create; begin FStream:=TWriteOnlyBlockStream.AllocFromPool; end; // Destroy // destructor TAutoWriteOnlyBlockStream.Destroy; begin FStream.ReturnToPool; end; // Stream // function TAutoWriteOnlyBlockStream.Stream : TWriteOnlyBlockStream; begin Result:=FStream; end; // WriteString // procedure TAutoWriteOnlyBlockStream.WriteString(const utf16String : UnicodeString); begin FStream.WriteString(utf16String); end; // WriteChar // procedure TAutoWriteOnlyBlockStream.WriteChar(utf16Char : WideChar); begin FStream.WriteChar(utf16Char); end; // WriteCRLF // procedure TAutoWriteOnlyBlockStream.WriteCRLF; begin FStream.WriteCRLF; end; // ToString // function TAutoWriteOnlyBlockStream.ToString : String; begin Result:=FStream.ToString; end; // ------------------ // ------------------ TStringIterator ------------------ // ------------------ // Create // constructor TStringIterator.Create(const s : String); begin FStr:=s; FPStr:=PChar(Pointer(s)); FLength:=System.Length(s); FPosition:=0; end; // Current // function TStringIterator.Current : Char; begin if Cardinal(FPosition)<Cardinal(FLength) then Result:=FPstr[FPosition] else Result:=#0; end; // EOF // function TStringIterator.EOF : Boolean; begin Result:=(FPosition>=FLength); end; // Next // procedure TStringIterator.Next; begin Inc(FPosition); end; // SkipWhiteSpace // procedure TStringIterator.SkipWhiteSpace; begin while (FPosition<FLength) and (Ord(FPStr[FPosition])<=Ord(' ')) do Inc(FPosition); end; // CollectQuotedString // function TStringIterator.CollectQuotedString : String; var quoteChar : Char; begin quoteChar:=Current; Inc(FPosition); while not EOF do begin if FPstr[FPosition]=quoteChar then begin Inc(FPosition); if EOF or (FPstr[FPosition]<>quoteChar) then Exit; Result:=Result+quoteChar; end else begin Result:=Result+FPstr[FPosition]; Inc(FPosition); end; end; raise EStringIterator.Create('Unfinished quoted string'); end; // CollectAlphaNumeric // function TStringIterator.CollectAlphaNumeric : String; var start : Integer; begin start:=FPosition; while FPosition<FLength do begin case FPstr[FPosition] of '0'..'9', 'a'..'z', 'A'..'Z' : Inc(FPosition); else break; end; end; Result:=Copy(FStr, start+1, FPosition-start); end; // CollectInteger // function TStringIterator.CollectInteger : Int64; var neg : Boolean; begin if (FPosition<FLength) and (FPStr[FPosition]='-') then begin neg:=True; Inc(FPosition); end else neg:=False; if FPosition>=FLength then EStringIterator.Create('Unfinished integer'); Result:=0; while FPosition<FLength do begin case FPstr[FPosition] of '0'..'9' : begin Result:=Result*10+Ord(FPstr[FPosition])-Ord('0'); Inc(FPosition); end; else break; end; end; if neg then Result:=-Result; end; // ------------------ // ------------------ TCaseInsensitiveNameValueHash<T> ------------------ // ------------------ // SameItem // function TCaseInsensitiveNameValueHash<T>.SameItem(const item1, item2 : TNameValueHashBucket<T>) : Boolean; begin Result:=UnicodeSameText(item1.Name, item2.Name); end; // GetItemHashCode // function TCaseInsensitiveNameValueHash<T>.GetItemHashCode(const item1 : TNameValueHashBucket<T>) : Integer; begin Result:=SimpleLowerCaseStringHash(item1.Name); end; // ------------------ // ------------------ TSimpleStringHash ------------------ // ------------------ // SameItem // function TSimpleStringHash.SameItem(const item1, item2 : String) : Boolean; begin Result:=UnicodeSameText(item1, item2); end; // GetItemHashCode // function TSimpleStringHash.GetItemHashCode(const item1 : String) : Integer; begin Result:=SimpleLowerCaseStringHash(item1); end; // ------------------ // ------------------ TSimpleDoubleList ------------------ // ------------------ // Sort // procedure TSimpleDoubleList.Sort; begin QuickSort(0, Count-1); end; // Sum // function TSimpleDoubleList.Sum : Double; var c, y, t : Double; i : Integer; begin if Count=0 then Exit(0); Result:=FItems[0]; c:=0; for i:=1 to Count-1 do begin y:=FItems[i]-c; t:=Result+y; c:=(t-Result)-y; Result:=t; end; end; // DoExchange // procedure TSimpleDoubleList.DoExchange(index1, index2 : Integer); var buf : Double; begin buf:=FItems[index1]; FItems[index1]:=FItems[index2]; FItems[index2]:=buf; end; // QuickSort // procedure TSimpleDoubleList.QuickSort(minIndex, maxIndex : Integer); var i, j, p, n : Integer; begin n:=maxIndex-minIndex; case n of 1 : begin if FItems[minIndex]>FItems[maxIndex] then DoExchange(minIndex, maxIndex); end; 2 : begin i:=minIndex+1; if FItems[minIndex]>FItems[i] then DoExchange(minIndex, i); if FItems[i]>FItems[maxIndex] then begin DoExchange(i, maxIndex); if FItems[minIndex]>FItems[i] then DoExchange(minIndex, i); end; end; else if n<=0 then Exit; repeat i:=minIndex; j:=maxIndex; p:=((i+j) shr 1); repeat while FItems[i]>FItems[p] do Inc(i); while Fitems[j]>FItems[p] do Dec(j); if i<=j then begin DoExchange(i, j); if p=i then p:=j else if p=j then p:=i; Inc(i); Dec(j); end; until i>j; if minIndex<j then QuickSort(minIndex, j); minIndex:=i; until i>=maxIndex; end; end; // ------------------ // ------------------ TPooledObject ------------------ // ------------------ // Create // constructor TPooledObject.Create; begin // nothing, just to introduce virtual construction end; // Destroy // destructor TPooledObject.Destroy; begin inherited; FNext.Free; end; // ------------------ // ------------------ TPool ------------------ // ------------------ // Initialize // procedure TPool.Initialize(aClass : TPooledObjectClass); begin FRoot:=nil; FPoolClass:=aClass; FLock:=TMultiReadSingleWrite.Create; end; // Finalize // procedure TPool.Finalize; begin FRoot.Free; FRoot:=nil; FLock.Free; FLock:=nil; FPoolClass:=nil; end; // Acquire // function TPool.Acquire : TPooledObject; begin Result:=nil; FLock.BeginWrite; try if FRoot<>nil then begin Result:=FRoot; FRoot:=Result.FNext; end; finally FLock.EndWrite; end; if Result=nil then Result:=FPoolClass.Create else Result.FNext:=nil; end; // Release // procedure TPool.Release(const obj : TPooledObject); begin FLock.BeginWrite; try obj.FNext:=FRoot; FRoot:=obj; finally FLock.EndWrite; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ InitializeSmallIntegers; InitializeStringsUnifier; TSimpleIntegerStack.vTemplate:=TSimpleIntegerStack.Create; finalization FinalizeStringsUnifier; TSimpleIntegerStack.vTemplate.Free; TObject(vWOBSPool).Free; end.
unit fmCorreo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmBase, DB, dmCorreo, ExtCtrls, JvExExtCtrls, JvNetscapeSplitter, Htmlview, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ActnList, ImgList, TB2Item, SpTBXItem, TB2Dock, TB2Toolbar; type TfCorreo = class(TfBase) gMensajes: TJvDBUltimGrid; MensajeViewer: THTMLViewer; Splitter: TJvNetscapeSplitter; dsCorreo: TDataSource; TBXToolbar1: TSpTBXToolbar; ActionList: TActionList; ImageList: TImageList; Obtener: TAction; Borrar: TAction; TBXItem1: TSpTBXItem; TBXItem2: TSpTBXItem; TBXSeparatorItem1: TSpTBXSeparatorItem; procedure FormCreate(Sender: TObject); procedure ObtenerExecute(Sender: TObject); procedure BorrarExecute(Sender: TObject); procedure BorrarUpdate(Sender: TObject); procedure MensajeViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean); private Correo: TCorreo; procedure OnCorreoAfterScroll(DataSet: TDataSet); public end; implementation uses Web; {$R *.dfm} resourcestring ERROR_CORREO = 'No se ha podido comprobar el correo. Inténtelo más tarde.'; NO_HAY_CORREO_NUEVO = 'No hay ningún correo nuevo.'; { TfCorreo } procedure TfCorreo.BorrarExecute(Sender: TObject); begin inherited; Correo.Borrar; end; procedure TfCorreo.BorrarUpdate(Sender: TObject); begin inherited; Borrar.Enabled := Correo.HayCorreo; end; procedure TfCorreo.FormCreate(Sender: TObject); begin inherited; Correo := TCorreo.Create(Self); Correo.qCorreo.AfterScroll := OnCorreoAfterScroll; OnCorreoAfterScroll(nil); end; procedure TfCorreo.MensajeViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean); begin inherited; AbrirURL(src); Handled := true; end; procedure TfCorreo.ObtenerExecute(Sender: TObject); var hayNuevosMsg: boolean; begin inherited; Obtener.Enabled := false; try if Correo.Obtener(hayNuevosMsg) then begin if not hayNuevosMsg then ShowMessage(NO_HAY_CORREO_NUEVO); end else ShowMessage(ERROR_CORREO); finally Obtener.Enabled := true; end; end; procedure TfCorreo.OnCorreoAfterScroll(DataSet: TDataSet); var s: TStringList; begin s := TStringList.Create; try s.Add(Correo.qCorreoMENSAJE.Value); MensajeViewer.LoadStrings(s, ''); finally s.Free; end; end; end.
Program intuition_refresh; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} { =========================================================================== Project : intuition_refresh Topic : Examine difference between simplerefresh and smartrefresh windows Author : The AROS Development Team. Source : http://www.aros.org/documentation/developers/samplecode/intuition_refresh.c =========================================================================== This example was originally written in c by The AROS Development Team. The original examples are available online and published at the AROS website (http://www.aros.org/documentation/developers/samples.php) Free Pascal sources were adjusted in order to support the following targets out of the box: - Amiga-m68k, AROS-i386 and MorphOS-ppc In order to accomplish that goal, some use of support units is used that aids compilation in a more or less uniform way. Conversion from c to Free Pascal was done by Magorium in 2015. =========================================================================== Unless otherwise noted, these examples must be considered copyrighted by their respective owner(s) =========================================================================== } {* Example for refresh handling of intuition windows Two windows are opened, one with simplerefresh, the other one with smartrefresh. You can watch what messages are sent when you move around or resize the windows. There is intentionally no redrawing in the event handler, so that you can clearly see the result of your window manipulation. *} Uses exec, agraphics, intuition, utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} chelpers, trinity; var window1, window2 : pWindow; cm : pColorMap; const {* ObtainBestPen() returns -1 when it fails, therefore we initialize the pen numbers with -1 to simplify cleanup. *} pen1 : LONG = -1; pen2 : LONG = -1; procedure draw_stuff(win: pWindow); forward; procedure clean_exit(const s: STRPTR); forward; function handle_events(win: pWindow; terminated: Boolean): Boolean; forward; function main: Integer; var signals : ULONG; terminated : Boolean; begin window1 := OpenWindowTags(nil, [ TAG_(WA_Left) , 50, TAG_(WA_Top) , 70, TAG_(WA_InnerWidth) , 300, TAG_(WA_InnerHeight) , 300, {* When we have a size gadget we must additionally define the limits. *} TAG_(WA_MinWidth) , 100, TAG_(WA_MinHeight) , 100, TAG_(WA_MaxWidth) , TAG_(-1), TAG_(WA_MaxHeight) , TAG_(-1), TAG_(WA_Title) , TAG_(PChar('Simplerefresh window')), TAG_(WA_Activate) , TAG_(TRUE), TAG_(WA_SimpleRefresh) , TAG_(TRUE), TAG_(WA_CloseGadget) , TAG_(TRUE), TAG_(WA_SizeGadget) , TAG_(TRUE), TAG_(WA_DragBar) , TAG_(TRUE), TAG_(WA_DepthGadget) , TAG_(TRUE), TAG_(WA_GimmeZeroZero) , TAG_(TRUE), TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_CHANGEWINDOW or IDCMP_NEWSIZE or IDCMP_REFRESHWINDOW or IDCMP_SIZEVERIFY), TAG_END ]); if not assigned(window1) then clean_exit('Can''t open window 1' + LineEnding); window2 := OpenWindowTags(nil, [ TAG_(WA_Left) , 400, TAG_(WA_Top) , 70, TAG_(WA_InnerWidth) , 300, TAG_(WA_InnerHeight) , 300, TAG_(WA_MinWidth) , 100, TAG_(WA_MinHeight) , 100, TAG_(WA_MaxWidth) , TAG_(-1), TAG_(WA_MaxHeight) , TAG_(-1), TAG_(WA_Title) , TAG_(PChar('Smartrefresh window')), TAG_(WA_Activate) , TAG_(TRUE), TAG_(WA_SmartRefresh) , TAG_(TRUE), TAG_(WA_CloseGadget) , TAG_(TRUE), TAG_(WA_SizeGadget) , TAG_(TRUE), TAG_(WA_DragBar) , TAG_(TRUE), TAG_(WA_DepthGadget) , TAG_(TRUE), TAG_(WA_GimmeZeroZero) , TAG_(TRUE), TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_CHANGEWINDOW or IDCMP_NEWSIZE or IDCMP_REFRESHWINDOW or IDCMP_SIZEVERIFY), TAG_END ]); if not assigned(window2) then clean_exit('Can''t open window 2' + LineEnding); {$IFNDEF AROS} cm := pScreen(window1^.WScreen)^.ViewPort.Colormap; {$ELSE} cm := window1^.WScreen^.ViewPort.Colormap; {$ENDIF} // Let's obtain two pens {$IFDEF AROS} pen1 := ObtainBestPenA(cm, $FFFF0000, 0, 0, nil); pen2 := ObtainBestPenA(cm, 0 ,0, $FFFF0000, nil); {$ELSE} pen1 := ObtainBestPen(cm, $FFFF0000, 0, 0, [TAG_END]); pen2 := ObtainBestPen(cm, 0 ,0, $FFFF0000, [TAG_END]); {$ENDIF} if (not (pen1 <> 0) or not (pen2 <> 0)) then clean_exit('Can''t allocate pen' + LineEnding); draw_stuff(window1); draw_stuff(window2); terminated := FALSE; while not(terminated) do begin {* If we want to wait for signals of more than one window we have to combine the signal bits. *} signals := Wait ( ( 1 shl window1^.UserPort^.mp_SigBit) or ( 1 shl window2^.UserPort^.mp_SigBit) ); {* Now we can check which window has received the signal and then we call the event handler for that window. *} if (signals and (1 shl window1^.UserPort^.mp_SigBit) <> 0) then terminated := handle_events(window1, terminated) else if (signals and (1 shl window2^.UserPort^.mp_SigBit) <> 0) then terminated := handle_events(window2, terminated); end; clean_exit(nil); result := 0; end; procedure draw_stuff(win: pWindow); var x : Integer; rp : pRastPort; begin rp := win^.RPort; x := 10; while (x <= 290) do begin SetAPen(rp, pen1); GfxMove(rp, x, 10); Draw(rp, 300-x, 290); SetAPen(rp, pen2); GfxMove(rp, 10, x); Draw(rp, 290, 300-x); inc(x, 10); end; end; function handle_events(win: pWindow; terminated: Boolean): Boolean; var imsg : pIntuiMessage; port : pMsgPort; event_nr : ULONG; begin port := win^.userPort; event_nr := 0; while (SetAndGet(imsg, GetMsg(port)) <> nil) do begin inc(event_nr); Write('Event # ', event_nr, ' '); if (win = window1) then Write('Window #1 ') else Write('Window #2 '); Case (imsg^.IClass) of IDCMP_CLOSEWINDOW : begin WriteLn('IDCMP_CLOSEWINDOW'); terminated := true; end; IDCMP_CHANGEWINDOW: begin // Window has been moved or resized WriteLn('IDCMP_CHANGEWINDOW'); end; IDCMP_NEWSIZE: begin WriteLn('IDCMP_NEWSIZE'); end; IDCMP_REFRESHWINDOW: begin WriteLn('IDCMP_REFRESHWINDOW'); BeginRefresh(win); {* Here you can add code which redraws exposed parts of the window. *} EndRefresh(win, TRUE); end; IDCMP_SIZEVERIFY: begin // SIZEVERIFY blocks a window until the message has been replied WriteLn('IDCMP_SIZEVERIFY'); end; end; // Every message must be replied. ReplyMsg(pMessage(imsg)); end; result := terminated; end; procedure clean_exit(const s: STRPTR); begin if assigned(s) then WriteLn(s); // Give back allocated resources if (pen1 <> -1) then ReleasePen(cm, pen1); if (pen2 <> -1) then ReleasePen(cm, pen2); if assigned(window1) then CloseWindow(window1); if assigned(window2) then CloseWindow(window2); Halt(0); end; { =========================================================================== Some additional code is required in order to open and close libraries in a cross-platform uniform way. Since AROS units automatically opens and closes libraries, this code is only actively used when compiling for Amiga and/or MorphOS. =========================================================================== } Function OpenLibs: boolean; begin Result := False; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} GfxBase := OpenLibrary(GRAPHICSNAME, 0); if not assigned(GfxBase) then Exit; {$ENDIF} {$IF DEFINED(MORPHOS)} IntuitionBase := OpenLibrary(INTUITIONNAME, 0); if not assigned(IntuitionBase) then Exit; {$ENDIF} Result := True; end; Procedure CloseLibs; begin {$IF DEFINED(MORPHOS)} if assigned(IntuitionBase) then CloseLibrary(pLibrary(IntuitionBase)); {$ENDIF} {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if assigned(GfxBase) then CloseLibrary(pLibrary(GfxBase)); {$ENDIF} end; begin if OpenLibs then ExitCode := Main() else ExitCode := 10; CloseLibs; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Console.Factory; interface uses System.SysUtils, WiRL.Console.Base, {$IFDEF LINUX} WiRL.Console.Daemon, {$ENDIF} WiRL.Console.Standard; type TWiRLConsoleStatic = class protected class var FConsoleClass: TWiRLConsoleClass; protected class function GetConsoleClass: TWiRLConsoleClass; static; public class property ConsoleClass: TWiRLConsoleClass read GetConsoleClass; end; TWiRLConsoleFactory = class(TWiRLConsoleStatic) public class function NewConsole(AConfigProc: TWiRLConfigProc): TWiRLConsoleBase; end; TWiRLConsoleLogger = class(TWiRLConsoleStatic) public class procedure LogInfo(const AMessage: string); class procedure LogWarning(const AMessage: string); class procedure LogError(const AMessage: string); class procedure LogRaw(const AMessage: string); end; implementation { TWiRLConsoleStatic } class function TWiRLConsoleStatic.GetConsoleClass: TWiRLConsoleClass; begin if not Assigned(FConsoleClass) then begin {$IFDEF LINUX} {$IFDEF DEBUG} FConsoleClass := TWiRLConsoleStandard; {$ELSE} {$IFDEF DAEMON} FConsoleClass := TWiRLConsoleDaemon; {$ELSE} FConsoleClass := TWiRLConsoleStandard; {$ENDIF} {$ENDIF} {$ELSE} FConsoleClass := TWiRLConsoleStandard; {$ENDIF} end; Result := FConsoleClass; end; { TWiRLConsoleFactory } class function TWiRLConsoleFactory.NewConsole(AConfigProc: TWiRLConfigProc): TWiRLConsoleBase; begin Result := ConsoleClass.Create(AConfigProc); end; { TWiRLConsoleLogger } class procedure TWiRLConsoleLogger.LogError(const AMessage: string); begin ConsoleClass.LogError(AMessage); end; class procedure TWiRLConsoleLogger.LogInfo(const AMessage: string); begin ConsoleClass.LogInfo(AMessage); end; class procedure TWiRLConsoleLogger.LogRaw(const AMessage: string); begin ConsoleClass.LogRaw(AMessage); end; class procedure TWiRLConsoleLogger.LogWarning(const AMessage: string); begin ConsoleClass.LogWarning(AMessage); end; end.
unit DialogSysOpenCompany; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DialogModule, cxContainer, cxCheckListBox, dxLayoutControl, StdCtrls, cxButtons, cxControls, cxEdit, cxTextEdit, cxMaskEdit, FileCtrl, RzFilSys, DB, ADODB, JvDriveCtrls, JvComponent, JvAppStorage, JvAppXMLStorage, ExtCtrls, cxDropDownEdit, cxImageComboBox, PymeConst, JvComponentBase, Menus, cxLookAndFeelPainters, cxGraphics, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxGrid; type TfrmDialogSysOpenCompany = class(TfrmDialogModule) lcDialogGroup3: TdxLayoutGroup; edUsuario: TcxMaskEdit; lcDialogItem2: TdxLayoutItem; edClave: TcxMaskEdit; lcDialogItem3: TdxLayoutItem; conTest: TADOConnection; qrLogin: TADOQuery; qrLoginUserId: TStringField; qrLoginClave: TStringField; qrLoginNombre: TStringField; qrLoginRolID: TSmallintField; Shape1: TShape; ProductName: TLabel; lcDialogItem4: TdxLayoutItem; Image1: TImage; lcDialogGroup5: TdxLayoutGroup; cbConfigurar: TcxButton; lcDialogItem1: TdxLayoutItem; dsAppEmpresas: TDataSource; lcEmpresas: TcxLookupComboBox; lcDialogItem6: TdxLayoutItem; ProgramIcon: TImage; lblVer: TLabel; procedure btCancelarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btAceptarClick(Sender: TObject); procedure cbConfigurarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmDialogSysOpenCompany: TfrmDialogSysOpenCompany; implementation uses DataModule, DialogDbSetup; {$R *.dfm} //Created with Castalia Extract Method Refactoring procedure TfrmDialogSysOpenCompany.FormCreate(Sender: TObject); begin inherited; ProgramIcon.Picture.Assign( Application.Icon ); ProductName.Caption := Application.Title; lblVer.Caption := 'Ver: '+Version_App; if not DM.ApplEmpresas.Active then DM.ApplEmpresas.Open; { if DM.CurCompany <> '' then lcEmpresas.EditText := DM.CurCompany else lcEmpresas.EditText := DM.ApplEmpresas.FieldByName('Descripcion').Text;} DM.DataBase.Close; DM.DataBase.DefaultDatabase := ''; DM.DataBase.ConnectionString := 'Data Source=' + DM.ApplEmpresas.FieldByName('Servidor').Text; DM.DataBase.ConnectionString := DM.DataBase.ConnectionString + ';Initial Catalog=' + DM.ApplEmpresas.FieldByName('Nombre').Text; DM.DataBase.ConnectionString := DM.DataBase.ConnectionString + ';User ID=' + DM.ApplEmpresas.FieldByName('sqlUser').Text; DM.DataBase.ConnectionString := DM.DataBase.ConnectionString + ';Password=' + DM.ApplEmpresas.FieldByName('sqlPassword').Text; DM.DataBase.Open; edUsuario.Text := DM.CurUser; if not DM.qrSucursal.Active then DM.qrSucursal.Open; if DM.CurSucursal <> '' then lcEmpresas.EditText := DM.CurSucursal else lcEmpresas.EditText := DM.qrSucursal.FieldByName('Nombre').Text; edUsuario.Text := DM.CurUser; end; procedure TfrmDialogSysOpenCompany.btAceptarClick(Sender: TObject); var prueba : string; begin inherited; if lcEmpresas.text <> '' then begin try conTest.Close; conTest.DefaultDatabase := ''; conTest.ConnectionString := 'Data Source=' + DM.ApplEmpresas.FieldByName('Servidor').Text; conTest.ConnectionString := conTest.ConnectionString + ';Initial Catalog=' + DM.ApplEmpresas.FieldByName('Nombre').Text; conTest.ConnectionString := conTest.ConnectionString + ';User ID=' + DM.ApplEmpresas.FieldByName('SqlUser').Text; conTest.ConnectionString := conTest.ConnectionString + ';Password=' + DM.ApplEmpresas.FieldByName('SqlPassword').Text; conTest.Open; // DM.qrSucursal.locate('Nombre',lcEmpresas.text,[]); dm.NombreSucursal := DM.qrSucursal.FieldByName('Nombre').Text; qrLogin.Close; qrLogin.Parameters.ParamByName('pUser').Value := trim(edUsuario.Text); qrLogin.Parameters.ParamByName('pSuc').Value := DM.qrSucursal.FieldByName('SucursalID').AsString; qrLogin.Open; prueba := DecryptKey(qrLoginClave.Text); if (not qrLogin.Eof and (DecryptKey(qrLoginClave.Text) = trim(edClave.Text)) ) then begin Close; end else DM.Error(SUsuarioClaveNoE); except raise; end; end else DM.Error('La sucursal no ha sido especificada.'); end; procedure TfrmDialogSysOpenCompany.btCancelarClick(Sender: TObject); begin inherited; conTest.Connected := False; if ModalResult = mrCancel then Begin Application.Terminate; end; end; procedure TfrmDialogSysOpenCompany.cbConfigurarClick(Sender: TObject); begin inherited; with TFrmDialogDbSetup.Create(Self) do begin try tvEmpresas.OptionsData.Deleting := False; liBtFunciones.Visible := False; ShowModal; finally Free; end; end; // with end; end.
unit PRelationEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel, MaxMin,LookupControls; type TPRelationEdit = class(TCustomControl) private { Private declarations } FCancut: boolean; FCheck: Boolean; FCheckResult: Boolean; FCurrentCNT: string; FDatabaseName: string; FDisplayLevel: integer; FEdit: TEdit; FFixedEdit: TEdit; FGradeLens: Array[1..7] of integer; FIsLeaf: boolean; FLabel: TRxLabel; FLabelStyle: TLabelStyle; FLookField: string; FLookFieldCaption: string; FLookSubField: string; FLookSubFieldCaption: string; FSubFieldControl: TPLabelPanel; FTableName: string; FQuery: TQuery; FPanel: TPanel; protected { Protected declarations } function CheckFormat:boolean; function FindCurrent(var LabelText: string):Boolean; function GetCaption:TCaption; function GetEditFont:TFont; function GetEditWidth:integer; function GetGradeLens(index:integer):integer; function GetRdOnly:Boolean; function GetText:string; procedure ControlExit(Sender: TObject); procedure ControlDblClick(Sender: TObject); procedure EditKeyPress(Sender: TObject; var Key: Char); procedure Paint;override; procedure SetCaption(Value: TCaption); procedure SetCurrentCNT(Value: string); procedure SetDisplayLevel(Value: integer); procedure SetEditFont(Value: TFont); procedure SetEditWidth(Value: integer); procedure SetLabelStyle(Value: TLabelStyle); procedure SetLookField(Value: string); procedure SetLookSubField(Value: string); procedure SetRdOnly(Value: Boolean); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy;override; property GradeLens[index:integer]:integer read GetGradeLens; property CheckResult: Boolean read FCheckResult write FCheckResult; property Text:string read GetText; published { Published declarations } property Caption:TCaption read GetCaption write SetCaption; property Check: Boolean read FCheck write FCheck; property Cancut:boolean read FCancut write FCancut; property CurrentCNT:string read FCurrentCNT write SetCurrentCNT; property DatabaseName: string read FDatabaseName write FDatabaseName; property DisplayLevel:integer read FDisplayLevel write SetDisplayLevel default 1; property EditFont:TFont read GetEditFont write SetEditFont; property EditWidth:integer read GetEditWidth write SetEditWidth; property IsLeaf:boolean read FIsLeaf write FIsLeaf; property LabelStyle: TLabelStyle read FLabelStyle write SetLabelStyle default Normal; property LookField: string read FLookField write SetLookField; property LookFieldCaption:string read FLookFieldCaption write FLookFieldCaption; property LookSubField: string read FLookSubField write SetLookSubField; property LookSubFieldCaption:string read FLookSubFieldCaption write FLookSubFieldCaption; property RdOnly: Boolean read GetRdOnly write SetRdOnly; property SubFieldControl: TPLabelPanel read FSubFieldControl write FSubFieldControl; property TableName: string read FTableName write FTableName; end; procedure Register; implementation constructor TPRelationEdit.Create (AOwner: TComponent); begin inherited Create(AOwner); FLabel := TRxLabel.Create(Self); FLabel.Parent := Self; FLabel.ShadowSize := 0; FLabel.Layout := tlCenter; FLabel.AutoSize := False; FLabel.Visible := True; FLabel.Font.Size := 11; FLabel.Font.Name := 'ËÎÌå'; FLabel.ParentFont := False; FPanel := TPanel.Create(Self); FPanel.Parent := Self; FPanel.BevelInner := bvNone; FPanel.BevelOuter := bvNone; FPanel.BevelWidth := 1; FPanel.BorderStyle := bsSingle; FPanel.BorderWidth := 0; FPanel.Visible := True; FPanel.Enabled := True; FPanel.Font.Size := 11; FPanel.Font.Name := 'ËÎÌå'; FPanel.ParentFont := False; FFixedEdit := TEdit.Create(Self); FFixedEdit.Parent := FPanel; FFixedEdit.Visible := True; FFixedEdit.BorderStyle := bsNone; FFixedEdit.Enabled := False; FEdit := TEdit.Create(Self); FEdit.Parent := FPanel; FEdit.Visible := True; FEdit.BorderStyle := bsNone; FEdit.OnExit := ControlExit; FEdit.OnDblClick := ControlDblClick; FEdit.OnKeyPress := EditKeyPress; FLabel.FocusControl := FEdit; Height := 20; FPanel.Height := Height; FLabel.Height := Height; FFixedEdit.Height := FPanel.Height-4; FEdit.Height := FPanel.Height-4; FFixedEdit.Top := 1; FEdit.Top := 1; Width := 200; FPanel.Width := 140; FLabel.Width := Width-FEdit.Width; FFixedEdit.Width := 0; FEdit.Width := FPanel.Width-4; FPanel.Left := FLabel.Width; FFixedEdit.Left := 1; FEdit.Left := 1; FQuery := TQuery.Create(Self); LabelStyle := Normal; DisplayLevel := 1; FGradeLens[1]:=4; FGradeLens[2]:=7; FGradeLens[3]:=10; FGradeLens[4]:=13; FGradeLens[5]:=13; FGradeLens[6]:=13; FGradeLens[7]:=13; end; destructor TPRelationEdit.Destroy; begin FEdit.Free; FFixedEdit.Free; FPanel.Free; FQuery.Free; FLabel.Free; inherited Destroy; end; procedure TPRelationEdit.Paint; begin FPanel.Height := Height; FLabel.Height := Height; FFixedEdit.Height := FPanel.Height-4; FEdit.Height := FPanel.Height-4; FLabel.Width := Width-FPanel.Width; FPanel.Left := FLabel.Width; SetLabelStyle(LabelStyle); inherited Paint; end; function TPRelationEdit.GetEditWidth:integer; begin Result := FPanel.Width; end; procedure TPRelationEdit.SetEditWidth(Value: integer); begin FPanel.Width := Value; FPanel.Left := Width-Value; FLabel.Width := FPanel.Left; FEdit.Width := FPanel.Width-4-FFixedEdit.Width; end; function TPRelationEdit.GetEditFont:TFont; begin Result := FEdit.Font; end; procedure TPRelationEdit.SetEditFont(Value: TFont); begin FEdit.Font.Assign(Value); FFixedEdit.Font.Assign(Value); end; function TPRelationEdit.GetCaption:TCaption; begin Result := FLabel.Caption; end; procedure TPRelationEdit.SetCaption(Value: TCaption); begin FLabel.Caption := Value; end; procedure TPRelationEdit.SetLabelStyle (Value: TLabelStyle); begin FLabelStyle := Value; case Value of Conditional: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := [fsUnderline]; end; Normal: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := []; end; NotnilAndConditional: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := [fsUnderline]; end; Notnil: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := []; end; end; end; function TPRelationEdit.GetRdOnly:Boolean; begin Result := FEdit.ReadOnly; end; procedure TPRelationEdit.SetRdOnly(Value: Boolean); begin FEdit.ReadOnly := Value; if Value then begin FFixedEdit.Color := clSilver; FEdit.Color := clSilver; end else begin FFixedEdit.Color := clWhite; FEdit.Color := clWhite; end; end; procedure TPRelationEdit.SetLookField(Value: string); begin if FLookField <> Value then FLookField := Value; end; procedure TPRelationEdit.SetLookSubField(Value: string); begin if FLookSubField <> Value then FLookSubField := Value; end; function TPRelationEdit.GetGradeLens(index:integer):integer; begin if (index<=7) and (index>=1) then Result := FGradeLens[index] else Result := 0; end; procedure TPRelationEdit.SetCurrentCNT(Value: string); var CNTLength,CNTWidth : integer; begin FCurrentCNT := Value; CNTLength := Length(Value); Canvas.Font.Assign(FFixedEdit.Font); CNTWidth := Canvas.TextWidth(Value); FFixedEdit.Text := Value; FEdit.Text := ''; FFixedEdit.Width := CNTWidth; FEdit.Width := FPanel.Width-4-FFixedEdit.Width; FEdit.Left := FFixedEdit.Width + 1; if CNTLength >= FGradeLens[DisplayLevel] then begin FEdit.Enabled := False; end else begin FEdit.Enabled := True; FEdit.MaxLength := FGradeLens[DisplayLevel]-CNTLength; end; end; procedure TPRelationEdit.SetDisplayLevel(Value: integer); var CNTLength : integer; begin FDisplayLevel := Value; FEdit.Text := ''; if CNTLength >= FGradeLens[DisplayLevel] then begin FEdit.Enabled := False; end else begin FEdit.Enabled := True; FEdit.MaxLength := FGradeLens[DisplayLevel]-CNTLength; end; end; function TPRelationEdit.GetText:string; begin Result := FCurrentCNT+FEdit.Text; end; procedure TPRelationEdit.EditKeyPress(Sender: TObject; var Key: Char); var LabelText : string; fgError : Boolean; begin if Key = #13 then begin fgError := False; LabelText := ''; if Check then begin if not CheckFormat then fgError := True else if not FindCurrent(LabelText) then fgError := True; end else begin if not CheckFormat then fgError := True; FindCurrent(LabelText); end; FCheckResult := fgError; if FSubFieldControl <> nil then (FSubFieldControl as TPLabelPanel).Caption := LabelText; end; end; procedure TPRelationEdit.ControlExit; var LabelText : string; fgError : Boolean; begin fgError := False; LabelText := ''; if Check then begin if not CheckFormat then fgError := True else if not FindCurrent(LabelText) then fgError := True; end else begin if not CheckFormat then fgError := True; FindCurrent(LabelText); end; FCheckResult := fgError; if FSubFieldControl <> nil then (FSubFieldControl as TPLabelPanel).Caption := LabelText; end; procedure TPRelationEdit.ControlDblClick(Sender: TObject); var SltDlg: TfrmSelectDlg; begin FQuery.DatabaseName := FDatabaseName; FQuery.SQL.Clear; FQuery.SQL.Add('Select * from '+FTableName); FQuery.Open; FQuery.FilterOptions := []; FQuery.Filter := FLookField+'='''+CurrentCNT+'*'''; FQuery.Filtered := True; if (not RdOnly) and (not FQuery.IsEmpty) then begin SltDlg := TfrmSelectDlg.Create(Self); with SltDlg do begin SelectDataSource.DataSet := FQuery; grdSelect.Columns.Clear; if FLookSubField <> '' then begin grdSelect.Columns.Add; grdSelect.Columns.Items[0].FieldName := FLookField; grdSelect.Columns.Items[0].Title.Caption := FLookFieldCaption; grdSelect.Columns.Items[0].Title.Font.Size := 10; grdSelect.Columns.Add; grdSelect.Columns.Items[1].FieldName := FLookSubField; grdSelect.Columns.Items[1].Title.Caption := FLookSubFieldCaption; grdSelect.Columns.Items[1].Title.Font.Size := 10; end else begin grdSelect.Columns.Add; grdSelect.Columns.Items[0].FieldName := FLookField; grdSelect.Columns.Items[0].Title.Caption := FLookFieldCaption; grdSelect.columns.Items[0].Width := grdSelect.Width-10; grdSelect.Columns.Items[0].Title.Font.Size := 10; end; end; if SltDlg.ShowModal=mrOK then begin FEdit.Text := Copy(FQuery.FieldByName(FLookField).AsString, Length(CurrentCNT)+1, Max(Length(FQuery.FieldByName(FLookField).AsString)-Length(CurrentCNT),0)); if (FSubFieldControl<>nil) and (FLookSubField<>'') then (FSubFieldControl as TPLabelPanel).Caption := FQuery.FieldByName(FLookSubField).AsString; end; SltDlg.Free; end; FQuery.Filtered := False; FQuery.Close; end; function TPRelationEdit.CheckFormat:boolean; var TextLen,i: integer; tmpText: string; flag : boolean; begin tmpText := FFixedEdit.Text + FEdit.Text; TextLen := Length(tmpText); Result := True; if (not Cancut) and (TextLen<>FGradeLens[DisplayLevel]) then Result := False; flag := False; for i := 1 to DisplayLevel do if TextLen=FGradeLens[i] then flag := True; if not flag then Result := False; end; function TPRelationEdit.FindCurrent(var LabelText: string):Boolean; var tmpText: string; begin tmpText := FFixedEdit.Text + FEdit.Text; FQuery.DatabaseName := FDatabaseName; FQuery.SQL.Clear; FQuery.SQL.Add('Select * from '+FTableName); FQuery.Open; if not FQuery.Locate(FLookField, tmpText,[]) then begin Result := False; LabelText := ''; end else begin if FIsLeaf then if not FQuery.FieldByName('tag').AsBoolean then begin Result := False; LabelText := ''; FQuery.Close; Exit; end; Result := True; if FLookSubField<>'' then LabelText := FQuery.FieldByName(FLookSubField).AsString else LabelText := ''; end; FQuery.Close; end; procedure Register; begin RegisterComponents('PosControl2', [TPRelationEdit]); end; end.
unit Unit_GLSavePlastomerParam; interface uses IniFiles, SysUtils; Procedure SaveIniSettings; Procedure LoadIniSettings; implementation uses Unit_GL; {=============================================================================== Save Plastomer Parameters} Procedure SaveIniSettings; var IniFile : TiniFile; begin IniFile := TIniFile.Create ('Plastomer.ini'); IniFile.WriteString ('GLMenu', 'VisualAll', IntToStr (Integer (frmGL.N5.Checked))); IniFile.WriteString ('GLMenu', 'VisualChast', IntToStr (Integer (frmGL.N6.Checked))); IniFile.WriteString ('GLMenu', 'Privyaz_Az_Zen', IntToStr (Integer (frmGL.N7.Checked))); IniFile.WriteString ('GLMenu', 'Depth', IntToStr (Integer (frmGL.N9.Checked))); IniFile.WriteString ('GLMenu', 'ShowHelpWin', IntToStr (Integer (frmGL.N8.Checked))); IniFile.Free; end; {=============================================================================== Load Plasomer Parametrs} Procedure LoadIniSettings; var IniFile : TiniFile; begin IniFile := TIniFile.Create ('Plastomer.ini'); frmGL.N5.Checked := Boolean (StrToInt (IniFile.ReadString ('GLMenu', 'VisualAll', '0'))); frmGL.N6.Checked := Boolean (StrToInt (IniFile.ReadString ('GLMenu', 'VisualChast', '1'))); frmGL.N7.Checked := Boolean (StrToInt (IniFile.ReadString ('GLMenu', 'Privyaz_Az_Zen', '1'))); frmGL.N9.Checked := Boolean (StrToInt (IniFile.ReadString ('GLMenu', 'Depth', '1'))); frmGL.N8.Checked := Boolean (StrToInt (IniFile.ReadString ('GLMenu', 'ShowHelpWin', '1'))); IniFile.Free; end; {=============================================================================== } end.
unit tcpbase; {$mode objfpc}{$H+} {******************************************************************************* Base classes for TCP/IP and Unix sockets communications! (c) 2006 by Alexander Todorov. e-mail: alexx.todorov@gmail.com ***************************************************************************** * * * See the file COPYING included in this distribution, * * for details about the copyright. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * * ***************************************************************************** *******************************************************************************} interface uses Classes, SysUtils, SSockets; type { TTextInetSocket } TTextInetSocket = class(TInetSocket) public constructor Create(AHandle : Longint); override; function RecvText : String; procedure SendText(const AText : String); end; {$IFDEF UNIX} { TTextUnixSocket } TTextUnixSocket = class(TUnixSocket) public function RecvText : String; procedure SendText(const AText : String); end; {$ENDIF} implementation uses Sockets; { TTextInetSocket } constructor TTextInetSocket.Create(AHandle: Longint); begin inherited Create(AHandle); SocketOptions := SocketOptions + [soKeepAlive]; end; function TTextInetSocket.RecvText : String; var len, n_len, r : LongInt; begin r := 0; len := 0; n_len := 0; SetLength(Result, 0); if (Read(n_len, SizeOf(n_len)) <> SizeOf(n_len)) and (SocketError <> 0) then raise Exception.Create(ClassName+'.RecvText - SOCKET ERROR '+IntToStr(SocketError)); len := NetToHost(n_len); if len > 0 then begin SetLength(Result, len); repeat r := r + Read(Result[1+r], len-r); if (SocketError <> 0) then raise Exception.Create(ClassName+'.RecvText - SOCKET ERROR '+IntToStr(SocketError)); until r >= len; if r > len then raise Exception.Create(ClassName+'.RecvText - more bytes read!'); end; end; procedure TTextInetSocket.SendText(const AText: String); var len, n_len, w : LongInt; begin w := 0; len := Length(AText); n_len := HostToNet(len); if (Write(n_len, SizeOf(n_len)) <> SizeOf(n_len)) and (SocketError <> 0) then raise Exception.Create(ClassName+'.SendText - SOCKET ERROR '+IntToStr(SocketError)); if len > 0 then begin repeat w := w + Write(AText[1+w], len-w); if (SocketError <> 0) then raise Exception.Create(ClassName+'.SendText - SOCKET ERROR '+IntToStr(SocketError)); until w = len; if w > len then raise Exception.Create(ClassName+'.SendText - more bytes read!'); end; end; {$IFDEF UNIX} { TTextUnixSocket } function TTextUnixSocket.RecvText : String; var len, n_len, r : LongInt; begin r := 0; len := 0; n_len := 0; SetLength(Result, 0); if (Read(n_len, SizeOf(n_len)) <> SizeOf(n_len)) and (SocketError <> 0) then raise Exception.Create(ClassName+'.RecvText - SOCKET ERROR '+IntToStr(SocketError)); len := NetToHost(n_len); if len > 0 then begin SetLength(Result, len); repeat r := r + Read(Result[1+r], len-r); if (SocketError <> 0) then raise Exception.Create(ClassName+'.RecvText - SOCKET ERROR '+IntToStr(SocketError)); until r >= len; if r > len then raise Exception.Create(ClassName+'.RecvText - more bytes read!'); end; end; procedure TTextUnixSocket.SendText(const AText: String); var len, n_len, w : LongInt; begin w := 0; len := Length(AText); n_len := HostToNet(len); if (Write(n_len, SizeOf(n_len)) <> SizeOf(n_len)) and (SocketError <> 0) then raise Exception.Create(ClassName+'.SendText - SOCKET ERROR '+IntToStr(SocketError)); if len > 0 then begin repeat w := w + Write(AText[1+w], len-w); if (SocketError <> 0) then raise Exception.Create(ClassName+'.SendText - SOCKET ERROR '+IntToStr(SocketError)); until w = len; if w > len then raise Exception.Create(ClassName+'.SendText - more bytes read!'); end; end; {$ENDIF} end.
unit URechner; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DateUtils { Eigen }, UDatenliste, UWahrscheinlichkeit, UAspekt; type TRechner = class private FWahrscheinlichkeit: TWahrscheinlichkeit; FPfadEingabe: String; FPfadAusgabe: String; Datenliste: TDatenliste; Aspekte: TAspektliste; procedure Durchlaufen; procedure Zusammenrechnen(Datum: TDate); public constructor Create; destructor Destroy; override; procedure AspektHinzufuegen (Aspekt: TAspekt); function Ermitteln (Datum: TDate; Speichern: Boolean = true): Double; published property PfadEingabe: String read FPfadEingabe write FPfadEingabe; property PfadAusgabe: String read FPfadAusgabe write FPfadAusgabe; end; implementation ////////////////////////// //Konstruktor/Destruktor// ////////////////////////// constructor TRechner.Create; begin inherited; Datenliste := TDatenliste.Create; FWahrscheinlichkeit := TWahrscheinlichkeit.Create; Aspekte := TAspektliste.Create; end; destructor TRechner.Destroy; begin Datenliste.Free; FWahrscheinlichkeit.Free; Aspekte.Free; inherited; end; /////////// //Private// /////////// procedure TRechner.Durchlaufen; var Zeitraum, Tag, Stichtag: Integer; Datum: TDate; begin Datum := Datenliste.Daten[0]; Zeitraum := DaysBetween(Date, Datum) - 1; //-1, da der heutige Tag nicht mitgerechnet werden soll. Stichtag := 0; for Tag := 0 to Zeitraum do begin Aspekte.Durchlauf(Datum); if (Stichtag < Length(Datenliste.Daten)) and (CompareDate(Datum, Datenliste.Daten[Stichtag]) = 0) then begin Aspekte.Treffer; Inc(Stichtag); end; Datum := IncDay(Datum); end; end; procedure TRechner.Zusammenrechnen(Datum: TDate); var i: Integer; Ergebnis, Gewichtung: Double; begin Ergebnis := 0; Gewichtung := 0; for i := 0 to Aspekte.Count - 1 do begin Ergebnis += Aspekte.Items[i].Wert(Datum) * Aspekte.Items[i].Gewichtung; Gewichtung += Aspekte.Items[i].Gewichtung; end; FWahrscheinlichkeit.Wert := Ergebnis / Gewichtung; end; ////////// //Public// ////////// procedure TRechner.AspektHinzufuegen (Aspekt: TAspekt); begin Aspekte.Add(Aspekt); end; function TRechner.Ermitteln (Datum: TDate; Speichern: Boolean = true): Double; begin Datenliste.Laden(FPfadEingabe); if Length(Datenliste.Daten) > 0 then begin Durchlaufen; Zusammenrechnen(Datum); end; if Speichern then FWahrscheinlichkeit.Speichern(FPfadAusgabe); Result := FWahrscheinlichkeit.Wert; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, StdCtrls, IdSocketHandle, IdUDPClient, Math, ComCtrls, XPMan, IniFiles; type TForm1 = class(TForm) IdUDPServer1: TIdUDPServer; IdUDPClient1: TIdUDPClient; Label1: TLabel; Label2: TLabel; TrackBar: TTrackBar; Label3: TLabel; XPManifest1: TXPManifest; procedure IdUDPServer1UDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TrackBarChange(Sender: TObject); private { Private declarations } public { Public declarations } end; type OpenTrackPacket = record x: double; y: double; z: double; yaw: double; pitch: double; roll: double; end; var Form1: TForm1; implementation {$R *.dfm} function FloatToJson(num: double): string; begin result:=FormatFloat('0.000',(DegToRad(num))); result:=StringReplace(result, ',', '.', [rfIgnoreCase]); end; procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle); var Packet: OpenTrackPacket; begin Adata.Read(packet, SIZEOF(packet)); Label1.Caption:=IntToStr(Round(packet.yaw)) + ' ' + IntToStr(Round(packet.pitch)) + ' ' + IntToStr(Round(packet.roll)); Label2.Caption:=FloatToJson(packet.yaw) + ' ' + FloatToJson(packet.pitch) + ' ' + FloatToJson(packet.roll); IdUDPClient1.Send('{"fov":'+IntToStr(TrackBar.Position)+',"id":"ked","pitch":'+FloatToJson(packet.pitch)+',"position":0,"roll":'+FloatToJson(packet.roll)+',"state":0,"url":"","yaw":'+FloatToJson(packet.yaw)+'}'); end; procedure TForm1.FormCreate(Sender: TObject); var Ini: TIniFile; begin Application.Title:=Caption; Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0))+'Setup.ini'); TrackBar.Position:=Ini.ReadInteger('Main', 'FOV', 90); Ini.Free; IdUDPServer1.Active:=true; IdUDPClient1.Active:=true; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin IdUDPServer1.Active:=false; IdUDPClient1.Active:=false; end; procedure TForm1.TrackBarChange(Sender: TObject); var Ini: TIniFile; begin Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0))+'Setup.ini'); Ini.WriteInteger('Main', 'FOV', TrackBar.Position); Ini.Free; Label3.Caption:='FOV: ' + IntToStr(TrackBar.Position); end; end.
unit FmSaveEncodingDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TSaveEncodingDlg = class(TForm) rgEncoding: TRadioGroup; btnOK: TButton; btnCancel: TButton; lblDesc: TLabel; procedure FormShow(Sender: TObject); private {$IFDEF UNICODE} function GetEncoding: TEncoding; {$ENDIF} public {$IFDEF UNICODE} property Encoding: TEncoding read GetEncoding; {$ENDIF} end; var SaveEncodingDlg: TSaveEncodingDlg; implementation {$R *.dfm} { TSaveEncodingDlg } procedure TSaveEncodingDlg.FormShow(Sender: TObject); begin // select default browser encoding option each time shown rgEncoding.ItemIndex := 0; end; {$IFDEF UNICODE} function TSaveEncodingDlg.GetEncoding: TEncoding; begin case rgEncoding.ItemIndex of 1: Result := TEncoding.Default; 2: Result := TEncoding.UTF8; 3: Result := TEncoding.Unicode; 4: Result := TEncoding.BigEndianUnicode; else Result := nil; // includes case 0 - default browser encoding end; end; {$ENDIF} end.
{*******************************************************} { PHP4Delphi } { PHP - Delphi interface } { } { Developers: } { Serhiy Perevoznyk } { serge_perevoznyk@hotmail.com } { Michael Maroszek } { maroszek@gmx.net } { } { http://users.chello.be/ws36637 } {*******************************************************} {$I PHP.INC} { $Id: phpcommon.pas,v 7.0 04/2007 delphi32 Exp $ } unit PHPCommon; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ZendTypes, ZendAPI, PHPTypes, PHPAPI; type EDelphiErrorEx = class(Exception); EPHPErrorEx = class(Exception); TPHPErrorType = ( etError, //0 etWarning, //1 etParse, //2 etNotice, etCoreError, etCoreWarning, etCompileError, etCompileWarning, etUserError, etUserWarning, etUserNotice, etUnknown); TPHPExecuteMethod = (emServer, emGet); TPHPAboutInfo = (abPHP4Delphi); TPHPVariable = class(TCollectionItem) private FName : string; FValue : string; function GetAsBoolean: boolean; function GetAsFloat: double; function GetAsInteger: integer; procedure SetAsBoolean(const Value: boolean); procedure SetAsFloat(const Value: double); procedure SetAsInteger(const Value: integer); protected function GetDisplayName : string; override; public property AsInteger : integer read GetAsInteger write SetAsInteger; property AsBoolean : boolean read GetAsBoolean write SetAsBoolean; property AsString : string read FValue write FValue; property AsFloat : double read GetAsFloat write SetAsFloat; published property Name : string read FName write FName; property Value : string read FValue write FValue; end; TPHPVariables = class(TCollection) private FOwner : TComponent; procedure SetItem(Index: Integer; const Value: TPHPVariable); function GetItem(Index: Integer): TPHPVariable; protected function GetOwner : TPersistent; override; public function Add: TPHPVariable; constructor Create(AOwner: TComponent); function GetVariables : string; function IndexOf(AName : string) : integer; procedure AddRawString(AString : string); property Items[Index: Integer]: TPHPVariable read GetItem write SetItem; default; function ByName(AName : string) : TPHPVariable; end; TPHPConstant = class(TCollectionItem) private FName : string; FValue : string; protected function GetDisplayName : string; override; published property Name : string read FName write FName; property Value : string read FValue write FValue; end; TPHPConstants = class(TCollection) private FOwner : TComponent; procedure SetItem(Index: Integer; const Value: TPHPConstant); function GetItem(Index: Integer): TPHPConstant; protected function GetOwner : TPersistent; override; public function Add: TPHPConstant; constructor Create(AOwner: TComponent); function IndexOf(AName : string) : integer; property Items[Index: Integer]: TPHPConstant read GetItem write SetItem; default; end; TPHPHeader = class(TCollectionItem) private FHeader : String; published property Header : string read FHeader write FHeader; end; TPHPHeaders = class(TCollection) private FOwner : TComponent; procedure SetItem(Index: Integer; const Value: TPHPHeader); function GetItem(Index: Integer): TPHPHeader; protected function GetOwner : TPersistent; override; public function Add: TPHPHeader; constructor Create(AOwner: TComponent); function GetHeaders : string; property Items[Index: Integer]: TPHPHeader read GetItem write SetItem; default; end; TPHPComponent = class(TComponent) private FAbout : TPHPAboutInfo; protected public published property About : TPHPAboutInfo read FAbout write FAbout stored False; end; implementation { TPHPVariables } function TPHPVariables.Add: TPHPVariable; begin result := TPHPVariable(inherited Add); end; constructor TPHPVariables.Create(AOwner: TComponent); begin inherited create(TPHPVariable); FOwner := AOwner; end; function TPHPVariables.GetItem(Index: Integer): TPHPVariable; begin Result := TPHPVariable(inherited GetItem(Index)); end; procedure TPHPVariables.SetItem(Index: Integer; const Value: TPHPVariable); begin inherited SetItem(Index, Value) end; function TPHPVariables.GetOwner : TPersistent; begin Result := FOwner; end; function TPHPVariables.GetVariables: string; var i : integer; begin for i := 0 to Count - 1 do begin Result := Result + Items[i].FName + '=' + Items[i].FValue; if i < Count - 1 then Result := Result + '&'; end; end; function TPHPVariables.IndexOf(AName: string): integer; var i : integer; begin Result := -1; for i := 0 to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := i; break; end; end; end; procedure TPHPVariables.AddRawString(AString : string); var SL : TStringList; i : integer; j : integer; V : TPHPVariable; begin if AString[Length(AString)] = ';' then SetLength(AString, Length(AString)-1); SL := TStringList.Create; ExtractStrings([';'], [], PChar(AString), SL); for i := 0 to SL.Count - 1 do begin j := IndexOf(SL.Names[i]); if j= -1 then begin V := Add; V.Name := SL.Names[i]; V.Value := Copy(SL[I], Length(SL.Names[i]) + 2, MaxInt); end else begin Items[j].Value := Copy(SL[I], Length(SL.Names[i]) + 2, MaxInt); end; end; SL.Free; end; function TPHPVariables.ByName(AName: string): TPHPVariable; var i : integer; begin Result := nil; for i := 0 to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := Items[i]; break; end; end; end; { TPHPVariable } function TPHPVariable.GetAsBoolean: boolean; begin if FValue = '' then begin Result := false; Exit; end; if SameText(FValue, 'True') then Result := true else Result := false; end; function TPHPVariable.GetAsFloat: double; begin if FValue = '' then begin Result := 0; Exit; end; Result := ValueToFloat(FValue); end; function TPHPVariable.GetAsInteger: integer; var c : char; begin c := DecimalSeparator; DecimalSeparator := '.'; Result := Round(ValueToFloat(FValue)); DecimalSeparator := c; end; function TPHPVariable.GetDisplayName: string; begin if FName = '' then result := inherited GetDisplayName else Result := FName; end; procedure TPHPVariable.SetAsBoolean(const Value: boolean); begin if Value then FValue := 'True' else FValue := 'False'; end; procedure TPHPVariable.SetAsFloat(const Value: double); begin FValue := FloatToValue(Value); end; procedure TPHPVariable.SetAsInteger(const Value: integer); var c : char; begin c := DecimalSeparator; DecimalSeparator := '.'; FValue := IntToStr(Value); DecimalSeparator := c; end; { TPHPConstant } function TPHPConstant.GetDisplayName: string; begin if FName = '' then result := inherited GetDisplayName else Result := FName; end; { TPHPConstants } function TPHPConstants.Add: TPHPConstant; begin result := TPHPConstant(inherited Add); end; constructor TPHPConstants.Create(AOwner: TComponent); begin inherited Create(TPHPConstant); FOwner := AOwner; end; function TPHPConstants.GetItem(Index: Integer): TPHPConstant; begin Result := TPHPConstant(inherited GetItem(Index)); end; function TPHPConstants.GetOwner: TPersistent; begin Result := FOwner; end; function TPHPConstants.IndexOf(AName: string): integer; var i : integer; begin Result := -1; for i := 0 to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := i; break; end; end; end; procedure TPHPConstants.SetItem(Index: Integer; const Value: TPHPConstant); begin inherited SetItem(Index, Value) end; { TPHPHeaders } function TPHPHeaders.Add: TPHPHeader; begin result := TPHPHeader(inherited Add); end; constructor TPHPHeaders.Create(AOwner: TComponent); begin inherited create(TPHPHeader); FOwner := AOwner; end; function TPHPHeaders.GetItem(Index: Integer): TPHPHeader; begin Result := TPHPHeader(inherited GetItem(Index)); end; procedure TPHPHeaders.SetItem(Index: Integer; const Value: TPHPHeader); begin inherited SetItem(Index, Value) end; function TPHPHeaders.GetOwner : TPersistent; begin Result := FOwner; end; function TPHPHeaders.GetHeaders: string; var i : integer; begin for i := 0 to Count - 1 do begin Result := Result + Items[i].FHeader; if i < Count - 1 then Result := Result + #13#10; end; end; end.
// zd01_1_ga.pas Гудулин А.О. 12.02.2012 // Программа тестирования функций работы со стеком type TStack = array[0..10] of integer; const errorMessage:string = ''; var stack: TStack; inputStr: string; i: integer; procedure init(var stack:TStack); {var i: integer;} begin {for i:=1 to 10 do stack[i] := 0;} stack[0] := 0; end; function errorHandler(count:integer): boolean; var error: byte; begin if (count > 10) then error := 1 else if (count < 1) then error := 2 else error := 0; case (error) of 0: errorHandler := true; 1: begin errorMessage := 'Ошибка! Переполнение стека.'; errorHandler := false; end; 2: begin errorMessage := 'Ошибка! В стеке нет элементов.'; errorHandler := false; end; end; end; function push(var stack:TStack; val:integer): boolean; var count: integer; begin count := stack[0]; if errorHandler(count+1) then begin inc(count); stack[0] := count; stack[count] := val; push := true; end else push := false; end; function pop(var stack:TStack; var val:integer): boolean; var count: integer; begin count := stack[0]; if errorHandler(count) then begin val := stack[count]; stack[0] := count-1; pop := true; end else pop := false; end; function top(var stack:TStack; var val:integer): boolean; var count: integer; begin count := stack[0]; if errorHandler(count) then begin val := stack[count]; top := true; end else top := false; end; procedure show(var stack:TStack); var i, count: integer; begin count := stack[0]; if errorHandler(count) then begin write('Состояние стека: ['); for i:=1 to count-1 do begin write(stack[i], ', '); end; writeln(stack[count], ']'); end; end; procedure showHelp; begin writeln('Список доступных команд:'); writeln('push':8); writeln('pop':7); writeln('top':7); writeln('show':8); writeln('help':8); writeln('exit':8); end; begin init(stack); writeln('*** zd01_1_ga.pas 12.02.2012 Гудулин А.О.'); writeln('*** Программа тестирования функций push, pop, top'); writeln('*** работы со стеком '); inputStr := ''; showHelp; while(true) do begin writeln('Введите команду:'); write('>>> '); readln(inputStr); writeln; if inputStr = 'push' then begin writeln('** Введите новое значение (int):'); write('>>> '); readln(i); if push(stack, i) then begin writeln('** Значение помещено в стек'); show(stack); end else writeln(errorMessage); writeln; end else if inputStr = 'pop' then begin if pop(stack, i) then begin write('** Значение, извлеченное из стека: '); writeln(i); if stack[0] > 0 then show(stack); end else writeln(errorMessage); writeln; end else if inputStr = 'top' then begin if top(stack, i) then begin write('** Значение, извлеченное из стека: '); writeln(i); end else writeln(errorMessage); writeln; end else if inputStr = 'show' then begin show(stack); writeln; end else if inputStr = 'help' then showHelp else if inputStr = 'exit' then exit else showHelp; //end; end; end.
unit Negocio; interface type TCliente = class private FNome: string; FCodigo: Integer; public property Codigo: Integer read FCodigo write FCodigo; property Nome: string read FNome write FNome; constructor Create(ACodigo: Integer; ANome: string); end; implementation { TCliente } constructor TCliente.Create(ACodigo: Integer; ANome: string); begin FCodigo := ACodigo; FNome := ANome; end; end.
unit UConfigIni; interface uses System.IniFiles, IWSystem, System.SysUtils, System.Classes; type TConfigIni = class private class function Ler(ASection, AIdent, ADefault: string): string; overload; class function Ler(ASection, AIdent: string; ADefault: Integer): Integer; overload; public class function Servidor: string; class function Usuario: string; class function Senha: string; class function Database: string; class function CharSet: string; class function CaminhoImagens: string; end; implementation { TConfigIni } class function TConfigIni.CaminhoImagens: string; begin Result := gsAppPath + TConfigIni.Ler('Parametros', 'Imagens', 'Imagens\'); end; class function TConfigIni.CharSet: string; begin Result := TConfigIni.Ler('Sistema', 'CharSet', 'ISO8859_1'); end; class function TConfigIni.Database: string; begin Result := TConfigIni.Ler('Sistema', 'Database', ''); end; class function TConfigIni.Ler(ASection, AIdent: string; ADefault: Integer): Integer; var Ini: TIniFile; begin Ini := TIniFile.Create(gsAppPath + 'Config.ini'); try Result := Ini.ReadInteger(ASection, AIdent, ADefault); finally FreeAndNil(Ini); end; end; class function TConfigIni.Ler(ASection, AIdent, ADefault: string): string; var Ini: TIniFile; begin Ini := TIniFile.Create(gsAppPath + 'Config.ini'); try Result := Ini.ReadString(ASection, AIdent, ADefault); finally FreeAndNil(Ini); end; end; class function TConfigIni.Senha: string; begin Result := TConfigIni.Ler('Sistema', 'Senha', ''); end; class function TConfigIni.Servidor: string; begin Result := TConfigIni.Ler('Sistema', 'Servidor', 'localhost'); end; class function TConfigIni.Usuario: string; begin Result := TConfigIni.Ler('Sistema', 'Usuario', ''); end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 23.07.2021 14:35:33 unit IdOpenSSLHeaders_x509v3; interface // Headers for OpenSSL 1.1.1 // x509v3.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ossl_typ, IdOpenSSLHeaders_asn1, IdOpenSSLHeaders_asn1t, IdOpenSSLHeaders_x509; const (* ext_flags values *) X509V3_EXT_DYNAMIC = $1; X509V3_EXT_CTX_DEP = $2; X509V3_EXT_MULTILINE = $4; // v3_ext_ctx CTX_TEST = $1; X509V3_CTX_REPLACE = $2; // GENERAL_NAME_st GEN_OTHERNAME = 0; GEN_EMAIL = 1; GEN_DNS = 2; GEN_X400 = 3; GEN_DIRNAME = 4; GEN_EDIPARTY = 5; GEN_URI = 6; GEN_IPADD = 7; GEN_RID = 8; (* All existing reasons *) CRLDP_ALL_REASONS = $807f; CRL_REASON_NONE = -1; CRL_REASON_UNSPECIFIED = 0; CRL_REASON_KEY_COMPROMISE = 1; CRL_REASON_CA_COMPROMISE = 2; CRL_REASON_AFFILIATION_CHANGED = 3; CRL_REASON_SUPERSEDED = 4; CRL_REASON_CESSATION_OF_OPERATION = 5; CRL_REASON_CERTIFICATE_HOLD = 6; CRL_REASON_REMOVE_FROM_CRL = 8; CRL_REASON_PRIVILEGE_WITHDRAWN = 9; CRL_REASON_AA_COMPROMISE = 10; (* Values in idp_flags field *) (* IDP present *) IDP_PRESENT = $1; (* IDP values inconsistent *) IDP_INVALID = $2; (* onlyuser true *) IDP_ONLYUSER = $4; (* onlyCA true *) IDP_ONLYCA = $8; (* onlyattr true *) IDP_ONLYATTR = $10; (* indirectCRL true *) IDP_INDIRECT = $20; (* onlysomereasons present *) IDP_REASONS = $40; EXT_END: array[0..13] of TIdC_INT = (-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); (* X509_PURPOSE stuff *) EXFLAG_BCONS = $1; EXFLAG_KUSAGE = $2; EXFLAG_XKUSAGE = $4; EXFLAG_NSCERT = $8; EXFLAG_CA = $10; (* Really self issued not necessarily self signed *) EXFLAG_SI = $20; EXFLAG_V1 = $40; EXFLAG_INVALID = $80; (* EXFLAG_SET is set to indicate that some values have been precomputed *) EXFLAG_SET = $100; EXFLAG_CRITICAL = $200; EXFLAG_PROXY = $400; EXFLAG_INVALID_POLICY = $800; EXFLAG_FRESHEST = $1000; (* Self signed *) EXFLAG_SS = $2000; KU_DIGITAL_SIGNATURE = $0080; KU_NON_REPUDIATION = $0040; KU_KEY_ENCIPHERMENT = $0020; KU_DATA_ENCIPHERMENT = $0010; KU_KEY_AGREEMENT = $0008; KU_KEY_CERT_SIGN = $0004; KU_CRL_SIGN = $0002; KU_ENCIPHER_ONLY = $0001; KU_DECIPHER_ONLY = $8000; NS_SSL_CLIENT = $80; NS_SSL_SERVER = $40; NS_SMIME = $20; NS_OBJSIGN = $10; NS_SSL_CA = $04; NS_SMIME_CA = $02; NS_OBJSIGN_CA = $01; NS_ANY_CA = NS_SSL_CA or NS_SMIME_CA or NS_OBJSIGN_CA; XKU_SSL_SERVER = $1; XKU_SSL_CLIENT = $2; XKU_SMIME = $4; XKU_CODE_SIGN = $8; XKU_SGC = $10; XKU_OCSP_SIGN = $20; XKU_TIMESTAMP = $40; XKU_DVCS = $80; XKU_ANYEKU = $100; X509_PURPOSE_DYNAMIC = $1; X509_PURPOSE_DYNAMIC_NAME = $2; X509_PURPOSE_SSL_CLIENT = 1; X509_PURPOSE_SSL_SERVER = 2; X509_PURPOSE_NS_SSL_SERVER = 3; X509_PURPOSE_SMIME_SIGN = 4; X509_PURPOSE_SMIME_ENCRYPT = 5; X509_PURPOSE_CRL_SIGN = 6; X509_PURPOSE_ANY = 7; X509_PURPOSE_OCSP_HELPER = 8; X509_PURPOSE_TIMESTAMP_SIGN = 9; X509_PURPOSE_MIN = 1; X509_PURPOSE_MAX = 9; (* Flags for X509V3_EXT_print() *) X509V3_EXT_UNKNOWN_MASK = TIdC_LONG($f) shl 16; (* Return error for unknown extensions *) X509V3_EXT_DEFAULT = 0; (* Print error for unknown extensions *) X509V3_EXT_ERROR_UNKNOWN = TIdC_LONG(1) shl 16; (* ASN1 parse unknown extensions *) X509V3_EXT_PARSE_UNKNOWN = TIdC_LONG(2) shl 16; (* BIO_dump unknown extensions *) X509V3_EXT_DUMP_UNKNOWN = TIdC_LONG(3) shl 16; (* Flags for X509V3_add1_i2d *) X509V3_ADD_OP_MASK = TIdC_LONG($f); X509V3_ADD_DEFAULT = TIdC_LONG(0); X509V3_ADD_APPEND = TIdC_LONG(1); X509V3_ADD_REPLACE = TIdC_LONG(2); X509V3_ADD_REPLACE_EXISTING = TIdC_LONG(3); X509V3_ADD_KEEP_EXISTING = TIdC_LONG(4); X509V3_ADD_DELETE = TIdC_LONG(5); X509V3_ADD_SILENT = $10; (* Flags for X509_check_* functions *) (* * Always check subject name for host match even if subject alt names present *) X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = $1; (* Disable wildcard matching for dnsName fields and common name. *) X509_CHECK_FLAG_NO_WILDCARDS = $2; (* Wildcards must not match a partial label. *) X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS = $4; (* Allow (non-partial) wildcards to match multiple labels. *) X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = $8; (* Constraint verifier subdomain patterns to match a single labels. *) X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS = $10; (* Never check the subject CN *) X509_CHECK_FLAG_NEVER_CHECK_SUBJECT = $20; (* * Match reference identifiers starting with "." to any sub-domain. * This is a non-public flag, turned on implicitly when the subject * reference identity is a DNS name. *) _X509_CHECK_FLAG_DOT_SUBDOMAINS = $8000; ASIdOrRange_id = 0; ASIdOrRange_range = 1; ASIdentifierChoice_inherit = 0; ASIdentifierChoice_asIdsOrRanges = 1; IPAddressOrRange_addressPrefix = 0; IPAddressOrRange_addressRange = 1; IPAddressChoice_inherit = 0; IPAddressChoice_addressesOrRanges = 1; (* * API tag for elements of the ASIdentifer SEQUENCE. *) V3_ASID_ASNUM = 0; V3_ASID_RDI = 1; (* * AFI values, assigned by IANA. It'd be nice to make the AFI * handling code totally generic, but there are too many little things * that would need to be defined for other address families for it to * be worth the trouble. *) IANA_AFI_IPV4 = 1; IANA_AFI_IPV6 = 2; type (* Forward reference *) //Pv3_ext_method = ^v3_ext_method; //Pv3_ext_ctx = ^v3_ext_ctx; (* Useful typedefs *) //X509V3_EXT_NEW = function: Pointer; cdecl; //X509V3_EXT_FREE = procedure(v1: Pointer); cdecl; //X509V3_EXT_D2I = function(v1: Pointer; v2: PPByte; v3: TIdC_Long): Pointer; cdecl; //X509V3_EXT_I2D = function(v1: Pointer; v2: PPByte): TIdC_INT; cdecl; // typedef STACK_OF(CONF_VALUE) * // (*X509V3_EXT_I2V) (const struct v3_ext_method *method, void *ext, // STACK_OF(CONF_VALUE) *extlist); // typedef void *(*X509V3_EXT_V2I)(const struct v3_ext_method *method, // struct v3_ext_ctx *ctx, // STACK_OF(CONF_VALUE) *values); //X509V3_EXT_I2S = function(method: Pv3_ext_method; ext: Pointer): PIdAnsiChar; cdecl; //X509V3_EXT_S2I = function(method: Pv3_ext_method; ctx: Pv3_ext_ctx; const str: PIdAnsiChar): Pointer; cdecl; //X509V3_EXT_I2R = function(const method: Pv3_ext_method; ext: Pointer; out_: PBIO; indent: TIdC_INT): TIdC_INT; cdecl; //X509V3_EXT_R2I = function(const method: Pv3_ext_method; ctx: Pv3_ext_ctx; const str: PIdAnsiChar): Pointer; cdecl; // (* V3 extension structure *) // v3_ext_method = record // ext_nid: TIdC_INT; // ext_flags: TIdC_INT; //(* If this is set the following four fields are ignored *) // it: PASN1_ITEM_EXP; //(* Old style ASN1 calls *) // ext_new: X509V3_EXT_NEW; // ext_free: X509V3_EXT_FREE; // d2i: X509V3_EXT_D2I; // i2d: X509V3_EXT_I2D; //(* The following pair is used for string extensions *) // i2s: X509V3_EXT_I2S; // s2i: X509V3_EXT_S2I; //(* The following pair is used for multi-valued extensions *) // i2v: X509V3_EXT_I2V; // v2i: X509V3_EXT_V2I; //(* The following are used for raw extensions *) // i2r: X509V3_EXT_I2R; // r2i: X509V3_EXT_R2I; // usr_data: Pointer; (* Any extension specific data *) // end; // X509V3_EXT_METHOD = v3_ext_method; // PX509V3_EXT_METHOD = ^X509V3_EXT_METHOD; // DEFINE_STACK_OF(X509V3_EXT_METHOD) // typedef struct X509V3_CONF_METHOD_st { // PIdAnsiChar *(*get_string) (void *db, const section: PIdAnsiChar, const value: PIdAnsiChar); // STACK_OF(CONF_VALUE) *(*get_section) (void *db, const section: PIdAnsiChar); // void (*free_string) (void *db, PIdAnsiChar *string); // void (*free_section) (void *db, STACK_OF(CONF_VALUE) *section); // } X509V3_CONF_METHOD; // Moved to ossl_typ // (* Context specific info *) // v3_ext_ctx = record // flags: TIdC_INT; // issuer_cert: PX509; // subject_cert: PX509; // subject_req: PX509_REQ; // crl: PX509_CRL; // db_meth: PX509V3_CONF_METHOD; // db: Pointer; // (* Maybe more here *) // end; ENUMERATED_NAMES = BIT_STRING_BITNAME; BASIC_CONSTRAINTS_st = record ca: TIdC_INT; pathlen: PASN1_INTEGER; end; BASIC_CONSTRAINTS = BASIC_CONSTRAINTS_st; PBASIC_CONSTRAINTS = ^BASIC_CONSTRAINTS; PKEY_USAGE_PERIOD_st = record notBefore: PASN1_GENERALIZEDTIME; notAfter: PASN1_GENERALIZEDTIME; end; PKEY_USAGE_PERIOD = PKEY_USAGE_PERIOD_st; PPKEY_USAGE_PERIOD = ^PKEY_USAGE_PERIOD; otherName_st = record type_id: PASN1_OBJECT; value: PASN1_TYPE; end; OTHERNAME = otherName_st; POTHERNAME = ^OTHERNAME; EDIPartyName_st = record nameAssigner: PASN1_STRING; partyName: PASN1_STRING; end; EDIPARTYNAME = EDIPartyName_st; PEDIPARTYNAME = ^EDIPARTYNAME; GENERAL_NAME_st_union = record case TIdC_INT of 0: (ptr: PIdAnsiChar); 1: (otherName: POTHERNAME); (* otherName *) 2: (rfc822Name: PASN1_IA5STRING); 3: (dNSName: PASN1_IA5STRING); 4: (x400Address: PASN1_TYPE); 5: (directoryName: PX509_NAME); 6: (ediPartyName: PEDIPARTYNAME); 7: (uniformResourceIdentifier: PASN1_IA5STRING); 8: (iPAddress: PASN1_OCTET_STRING); 9: (registeredID: PASN1_OBJECT); (* Old names *) 10: (ip: PASN1_OCTET_STRING); (* iPAddress *) 11: (dirn: PX509_NAME); (* dirn *) 12: (ia5: PASN1_IA5STRING); (* rfc822Name, dNSName, * uniformResourceIdentifier *) 13: (rid: PASN1_OBJECT); (* registeredID *) 14: (other: PASN1_TYPE); (* x400Address *) end; GENERAL_NAME_st = record type_: TIdC_INT; d: GENERAL_NAME_st_union; end; GENERAL_NAME = GENERAL_NAME_st; PGENERAL_NAME = ^GENERAL_NAME; ACCESS_DESCRIPTION_st = record method: PASN1_OBJECT; location: PGENERAL_NAME; end; ACCESS_DESCRIPTION = ACCESS_DESCRIPTION_st; PACCESS_DESCRIPTION = ^ACCESS_DESCRIPTION; // typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; // typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE; // typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE; // DEFINE_STACK_OF(GENERAL_NAME) // typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES; // DEFINE_STACK_OF(GENERAL_NAMES) // DEFINE_STACK_OF(ACCESS_DESCRIPTION) // DIST_POINT_NAME_st_union = record // case TIdC_INT of // 0: (GENERAL_NAMES *fullname); // 1: (STACK_OF(X509_NAME_ENTRY) *relativename); // end; DIST_POINT_NAME_st = record type_: TIdC_INT; (* If relativename then this contains the full distribution point name *) dpname: PX509_NAME; end; DIST_POINT_NAME = DIST_POINT_NAME_st; PDIST_POINT_NAME = ^DIST_POINT_NAME; // struct DIST_POINT_ST { // DIST_POINT_NAME *distpoint; // ASN1_BIT_STRING *reasons; // GENERAL_NAMES *CRLissuer; // TIdC_INT dp_reasons; // }; // typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS; // DEFINE_STACK_OF(DIST_POINT) // AUTHORITY_KEYID_st = record // keyid: PASN1_OCTET_STRING; // issuer: PGENERAL_NAMES; // serial: PASN1_INTEGER; // end; (* Strong extranet structures *) SXNET_ID_st = record zone: PASN1_INTEGER; user: PASN1_OCTET_STRING; end; SXNETID = SXNET_ID_st; PSXNETID = ^SXNETID; // DEFINE_STACK_OF(SXNETID) // SXNET_st = record // ASN1_INTEGER *version; // STACK_OF(SXNETID) *ids; // end; // SXNET = SXNET_st; // PSXNET = ^SXNET; // NOTICEREF_st = record // ASN1_STRING *organization; // STACK_OF(ASN1_INTEGER) *noticenos; // end; // NOTICEREF = NOTICEREF_st; // PNOTICEREF = ^NOTICEREF; // USERNOTICE_st = record // noticeref: PNOTICEREF; // exptext: PASN1_STRING; // end; // USERNOTICE = USERNOTICE_st; // PUSERNOTICE = ^USERNOTICE; // POLICYQUALINFO_st_union = record // case TIdC_INT of // 0: (cpsuri: PASN1_IA5STRING); // 1: (usernotice: PUSERNOTICE); // 2: (other: PASN1_TYPE); // end; // POLICYQUALINFO_st = record // pqualid: PASN1_OBJECT; // d: POLICYQUALINFO_st_union; // end; // POLICYQUALINFO = POLICYQUALINFO_st; // PPOLICYQUALINFO = ^POLICYQUALINFO; // DEFINE_STACK_OF(POLICYQUALINFO) // POLICYINFO_st = record // ASN1_OBJECT *policyid; // STACK_OF(POLICYQUALINFO) *qualifiers; // end; // POLICYINFO = POLICYINFO_st; // PPOLICYINFO = ^POLICYINFO; // typedef STACK_OF(POLICYINFO) CERTIFICATEPOLICIES; // DEFINE_STACK_OF(POLICYINFO) POLICY_MAPPING_st = record issuerDomainPolicy: PASN1_OBJECT; subjectDomainPolicy: PASN1_OBJECT; end; POLICY_MAPPING = POLICY_MAPPING_st; PPOLICY_MAPPING = ^POLICY_MAPPING; // DEFINE_STACK_OF(POLICY_MAPPING) // typedef STACK_OF(POLICY_MAPPING) POLICY_MAPPINGS; GENERAL_SUBTREE_st = record base: PGENERAL_NAME; minimum: PASN1_INTEGER; maximum: PASN1_INTEGER; end; GENERAL_SUBTREE = GENERAL_SUBTREE_st; PGENERAL_SUBTREE = ^GENERAL_SUBTREE; // DEFINE_STACK_OF(GENERAL_SUBTREE) // NAME_CONSTRAINTS_st = record // STACK_OF(GENERAL_SUBTREE) *permittedSubtrees; // STACK_OF(GENERAL_SUBTREE) *excludedSubtrees; // end; POLICY_CONSTRAINTS_st = record requireExplicitPolicy: PASN1_INTEGER; inhibitPolicyMapping: PASN1_INTEGER; end; POLICY_CONSTRAINTS = POLICY_CONSTRAINTS_st; PPOLICY_CONSTRAINTS = ^POLICY_CONSTRAINTS; (* Proxy certificate structures, see RFC 3820 *) PROXY_POLICY_st = record policyLanguage: PASN1_OBJECT; policy: PASN1_OCTET_STRING; end; PROXY_POLICY = PROXY_POLICY_st; PPROXY_POLICY = ^PROXY_POLICY; // DECLARE_ASN1_FUNCTIONS(PROXY_POLICY) PROXY_CERT_INFO_EXTENSION_st = record pcPathLengthConstraint: PASN1_INTEGER; proxyPolicy: PPROXY_POLICY; end; PROXY_CERT_INFO_EXTENSION = PROXY_CERT_INFO_EXTENSION_st; PPROXY_CERT_INFO_EXTENSION = ^PROXY_CERT_INFO_EXTENSION; // DECLARE_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION) // ISSUING_DIST_POint_st = record // distpoint: PDIST_POINT_NAME; // TIdC_INT onlyuser; // TIdC_INT onlyCA; // onlysomereasons: PASN1_BIT_STRING; // TIdC_INT indirectCRL; // TIdC_INT onlyattr; // end; // # define X509V3_conf_err(val) ERR_add_error_data(6, \ // "section:", (val)->section, \ // ",name:", (val)->name, ",value:", (val)->value) // // # define X509V3_set_ctx_test(ctx) \ // X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, CTX_TEST) // # define X509V3_set_ctx_nodb(ctx) (ctx)->db = NULL; // // # define EXT_BITSTRING(nid, table) { nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), \ // 0,0,0,0, \ // 0,0, \ // (X509V3_EXT_I2V)i2v_ASN1_BIT_STRING, \ // (X509V3_EXT_V2I)v2i_ASN1_BIT_STRING, \ // NULL, NULL, \ // table} // // # define EXT_IA5STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), \ // 0,0,0,0, \ // (X509V3_EXT_I2S)i2s_ASN1_IA5STRING, \ // (X509V3_EXT_S2I)s2i_ASN1_IA5STRING, \ // 0,0,0,0, \ // NULL} PX509_PURPOSE = ^X509_PURPOSE; x509_purpose_st = record purpose: TIdC_INT; trust: TIdC_INT; (* Default trust ID *) flags: TIdC_INT; check_purpose: function(const v1: PX509_PURPOSE; const v2: PX509; v3: TIdC_INT): TIdC_INT; cdecl; name: PIdAnsiChar; sname: PIdAnsiChar; usr_data: Pointer; end; X509_PURPOSE = x509_purpose_st; // DEFINE_STACK_OF(X509_PURPOSE) // DECLARE_ASN1_FUNCTIONS(BASIC_CONSTRAINTS_st) // DECLARE_ASN1_FUNCTIONS(SXNET) // DECLARE_ASN1_FUNCTIONS(SXNETID) ASRange_st = record min, max: PASN1_INTEGER; end; ASRange = ASRange_st; PASRange = ^ASRange; ASIdOrRange_st = record type_: TIdC_INT; case u: TIdC_INT of 0: (id: PASN1_INTEGER); 1: (range: PASRange); end; ASIdOrRange = ASIdOrRange_st; PASIdOrRange = ^ASIdOrRange; // typedef STACK_OF(ASIdOrRange) ASIdOrRanges; // DEFINE_STACK_OF(ASIdOrRange) // ASIdentifierChoice_st = record // type_: TIdC_INT; // case u: TIdC_INT of // 0: (inherit: PASN1_NULL); // 1: (asIdsOrRanges: PASIdOrRanges); // end; // ASIdentifierChoice = ASIdentifierChoice_st; // PASIdentifierChoice = ^ASIdentifierChoice; // ASIdentifiers_st = record // asnum, rdi: PASIdentifierChoice; // end; // ASIdentifiers = ASIdentifiers_st; // PASIdentifiers = ^ASIdentifiers; // DECLARE_ASN1_FUNCTIONS(ASRange) // DECLARE_ASN1_FUNCTIONS(ASIdOrRange) // DECLARE_ASN1_FUNCTIONS(ASIdentifierChoice) // DECLARE_ASN1_FUNCTIONS(ASIdentifiers) IPAddressRange_st = record min, max: PASN1_BIT_STRING; end; IPAddressRange = IPAddressRange_st; PIPAddressRange = ^IPAddressRange; IPAddressOrRange_st = record type_: TIdC_INT; case u: TIdC_INT of 0: (addressPrefix: PASN1_BIT_STRING); 1: (addressRange: PIPAddressRange); end; IPAddressOrRange = IPAddressOrRange_st; PIPAddressOrRange = ^IPAddressOrRange; // typedef STACK_OF(IPAddressOrRange) IPAddressOrRanges; // DEFINE_STACK_OF(IPAddressOrRange) // IPAddressChoice_st = record // type_: TIdC_INT; // case u: TIdC_INT of // 0: (inherit: PASN1_NULL); // 1: (addressesOrRanges: PIPAddressOrRanges); // end; // IPAddressChoice = IPAddressChoice_st; // PIPAddressChoice = ^IPAddressChoice; // IPAddressFamily_st = record // addressFamily: PASN1_OCTET_STRING; // ipAddressChoice: PIPAddressChoice; // end; // IPAddressFamily = IPAddressFamily_st; // PIPAddressFamily = ^IPAddressFamily; // typedef STACK_OF(IPAddressFamily) IPAddrBlocks; // DEFINE_STACK_OF(IPAddressFamily) // DECLARE_ASN1_FUNCTIONS(IPAddressRange) // DECLARE_ASN1_FUNCTIONS(IPAddressOrRange) // DECLARE_ASN1_FUNCTIONS(IPAddressChoice) // DECLARE_ASN1_FUNCTIONS(IPAddressFamily) NamingAuthority_st = type Pointer; NAMING_AUTHORITY = NamingAuthority_st; PNAMING_AUTHORITY = ^NAMING_AUTHORITY; ProfessionInfo_st = type Pointer; PROFESSION_INFO = ProfessionInfo_st; PPROFESSION_INFO = ^PROFESSION_INFO; Admissions_st = type Pointer; ADMISSIONS = Admissions_st; PADMISSIONS = ^ADMISSIONS; AdmissionSyntax_st = type Pointer; ADMISSION_SYNTAX = AdmissionSyntax_st; PADMISSION_SYNTAX = ^ADMISSION_SYNTAX; // DECLARE_ASN1_FUNCTIONS(NAMING_AUTHORITY) // DECLARE_ASN1_FUNCTIONS(PROFESSION_INFO) // DECLARE_ASN1_FUNCTIONS(ADMISSIONS) // DECLARE_ASN1_FUNCTIONS(ADMISSION_SYNTAX) // DEFINE_STACK_OF(ADMISSIONS) // DEFINE_STACK_OF(PROFESSION_INFO) // typedef STACK_OF(PROFESSION_INFO) PROFESSION_INFOS; // function SXNET_add_id_asc(psx: PPSXNET; const zone: PIdAnsiChar; const user: PIdAnsiChar; userlen: TIdC_INT): TIdC_INT; // function SXNET_add_id_ulong(psx: PPSXNET; lzone: TIdC_ULONG; const user: PIdAnsiChar; userlen: TIdC_INT): TIdC_INT; // function SXNET_add_id_INTEGER(psx: PPSXNET; izone: PASN1_INTEGER; const user: PIdAnsiChar; userlen: TIdC_INT): TIdC_INT; // function SXNET_get_id_asc(sx: PSXNET; const zone: PIdAnsiChar): PASN1_OCTET_STRING; // function SXNET_get_id_ulong(sx: PSXNET; lzone: TIdC_ULONG): PASN1_OCTET_STRING; // function SXNET_get_id_INTEGER(sx: PSXNET; zone: PASN1_INTEGER): PASN1_OCTET_STRING; // DECLARE_ASN1_FUNCTIONS(AUTHORITY_KEYID) // DECLARE_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD) // DECLARE_ASN1_FUNCTIONS(GENERAL_NAME) // GENERAL_NAME *GENERAL_NAME_dup(a: PGENERAL_NAME); function GENERAL_NAME_cmp(a: PGENERAL_NAME; b: PGENERAL_NAME): TIdC_INT cdecl; external CLibCrypto; // ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; STACK_OF(CONF_VALUE) *nval); // STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(method: PX509V3_EXT_METHOD; ASN1_BIT_STRING *bits; STACK_OF(CONF_VALUE) *extlist); //function i2s_ASN1_IA5STRING(method: PX509V3_EXT_METHOD; ia5: PASN1_IA5STRING): PIdAnsiChar; //function s2i_ASN1_IA5STRING(method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; const str: PIdAnsiChar): PASN1_IA5STRING; // STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(method: PX509V3_EXT_METHOD; gen: PGENERAL_NAME; STACK_OF(CONF_VALUE) *ret); function GENERAL_NAME_print(out_: PBIO; gen: PGENERAL_NAME): TIdC_INT cdecl; external CLibCrypto; // DECLARE_ASN1_FUNCTIONS(GENERAL_NAMES) // STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(method: PX509V3_EXT_METHOD, GENERAL_NAMES *gen, STACK_OF(CONF_VALUE) *extlist); // GENERAL_NAMES *v2i_GENERAL_NAMES(const method: PX509V3_EXT_METHOD, ctx: PX509V3_CTX, STACK_OF(CONF_VALUE) *nval); // DECLARE_ASN1_FUNCTIONS(OTHERNAME) // DECLARE_ASN1_FUNCTIONS(EDIPARTYNAME) function OTHERNAME_cmp(a: POTHERNAME; b: POTHERNAME): TIdC_INT cdecl; external CLibCrypto; procedure GENERAL_NAME_set0_value(a: PGENERAL_NAME; type_: TIdC_INT; value: Pointer) cdecl; external CLibCrypto; function GENERAL_NAME_get0_value(const a: PGENERAL_NAME; ptype: PIdC_INT): Pointer cdecl; external CLibCrypto; function GENERAL_NAME_set0_othername(gen: PGENERAL_NAME; oid: PASN1_OBJECT; value: PASN1_TYPE): TIdC_INT cdecl; external CLibCrypto; function GENERAL_NAME_get0_otherName(const gen: PGENERAL_NAME; poid: PPASN1_OBJECT; pvalue: PPASN1_TYPE): TIdC_INT cdecl; external CLibCrypto; //function i2s_ASN1_OCTET_STRING(method: PX509V3_EXT_METHOD; const ia5: PASN1_OCTET_STRING): PIdAnsiChar; //function s2i_ASN1_OCTET_STRING(method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; const str: PIdAnsiChar): PASN1_OCTET_STRING; // DECLARE_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE) function i2a_ACCESS_DESCRIPTION(bp: PBIO; const a: PACCESS_DESCRIPTION): TIdC_INT cdecl; external CLibCrypto; // DECLARE_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE) // DECLARE_ASN1_FUNCTIONS(CERTIFICATEPOLICIES) // DECLARE_ASN1_FUNCTIONS(POLICYINFO) // DECLARE_ASN1_FUNCTIONS(POLICYQUALINFO) // DECLARE_ASN1_FUNCTIONS(USERNOTICE) // DECLARE_ASN1_FUNCTIONS(NOTICEREF) // DECLARE_ASN1_FUNCTIONS(CRL_DIST_POINTS) // DECLARE_ASN1_FUNCTIONS(DIST_POINT) // DECLARE_ASN1_FUNCTIONS(DIST_POINT_NAME) // DECLARE_ASN1_FUNCTIONS(ISSUING_DIST_POINT) function DIST_POINT_set_dpname(dpn: PDIST_POINT_NAME; iname: PX509_NAME): TIdC_INT cdecl; external CLibCrypto; function NAME_CONSTRAINTS_check(x: PX509; nc: PNAME_CONSTRAINTS): TIdC_INT cdecl; external CLibCrypto; function NAME_CONSTRAINTS_check_CN(x: PX509; nc: PNAME_CONSTRAINTS): TIdC_INT cdecl; external CLibCrypto; // DECLARE_ASN1_FUNCTIONS(ACCESS_DESCRIPTION) // DECLARE_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS) // DECLARE_ASN1_ITEM(POLICY_MAPPING) // DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING) // DECLARE_ASN1_ITEM(POLICY_MAPPINGS) // DECLARE_ASN1_ITEM(GENERAL_SUBTREE) // DECLARE_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) // DECLARE_ASN1_ITEM(NAME_CONSTRAINTS) // DECLARE_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) // DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS) // DECLARE_ASN1_ITEM(POLICY_CONSTRAINTS) //function a2i_GENERAL_NAME(out_: PGENERAL_NAME; const method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; TIdC_INT gen_type; const value: PIdAnsiChar; is_nc: TIdC_INT): GENERAL_NAME; //function v2i_GENERAL_NAME(const method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; cnf: PCONF_VALUE): PGENERAL_NAME; //function v2i_GENERAL_NAME_ex(out_: PGENERAL_NAME; const method: PX509V3_EXT_METHOD; ctx: PX509V3_CTX; cnf: PCONF_VALUE; is_nc: TIdC_INT): PGENERAL_NAME; //procedure X509V3_conf_free(val: PCONF_VALUE); function X509V3_EXT_nconf_nid(conf: PCONF; ctx: PX509V3_CTX; ext_nid: TIdC_INT; const value: PIdAnsiChar): PX509_EXTENSION cdecl; external CLibCrypto; function X509V3_EXT_nconf(conf: PCONF; ctx: PX509V3_CTX; const name: PIdAnsiChar; const value: PIdAnsiChar): PX509_EXTENSION cdecl; external CLibCrypto; // TIdC_INT X509V3_EXT_add_nconf_sk(conf: PCONF; ctx: PX509V3_CTX; const section: PIdAnsiChar; STACK_OF(X509_EXTENSION) **sk); function X509V3_EXT_add_nconf(conf: PCONF; ctx: PX509V3_CTX; const section: PIdAnsiChar; cert: PX509): TIdC_INT cdecl; external CLibCrypto; function X509V3_EXT_REQ_add_nconf(conf: PCONF; ctx: PX509V3_CTX; const section: PIdAnsiChar; req: PX509_REQ): TIdC_INT cdecl; external CLibCrypto; function X509V3_EXT_CRL_add_nconf(conf: PCONF; ctx: PX509V3_CTX; const section: PIdAnsiChar; crl: PX509_CRL): TIdC_INT cdecl; external CLibCrypto; function X509V3_EXT_conf_nid(conf: Pointer; ctx: PX509V3_CTX; ext_nid: TIdC_INT; const value: PIdAnsiChar): PX509_EXTENSION cdecl; external CLibCrypto; // X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf; ctx: PX509V3_CTX; ext_nid: TIdC_INT; const value: PIdAnsiChar); function X509V3_EXT_conf(conf: Pointer; ctx: PX509V3_CTX; const name: PIdAnsiChar; const value: PIdAnsiChar): PX509_EXTENSION cdecl; external CLibCrypto; // X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf; ctx: PX509V3_CTX; const name: PIdAnsiChar; const value: PIdAnsiChar); function X509V3_EXT_add_conf(conf: Pointer; ctx: PX509V3_CTX; const section: PIdAnsiChar; cert: PX509): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf; ctx: PX509V3_CTX; const section: PIdAnsiChar; cert: PX509); function X509V3_EXT_REQ_add_conf(conf: Pointer; ctx: PX509V3_CTX; const section: PIdAnsiChar; req: PX509_REQ): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf; ctx: PX509V3_CTX; const section: PIdAnsiChar; req: PX509_REQ); function X509V3_EXT_CRL_add_conf(conf: Pointer; ctx: PX509V3_CTX; const section: PIdAnsiChar; crl: PX509_CRL): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf; ctx: PX509V3_CTX; const section: PIdAnsiChar; crl: PX509_CRL); // TIdC_INT X509V3_add_value_bool_nf(const name: PIdAnsiChar; TIdC_INT asn1_bool; STACK_OF(CONF_VALUE) **extlist); //function X509V3_get_value_bool(const value: PCONF_VALUE; asn1_bool: PIdC_INT): TIdC_INT; //function X509V3_get_value_int(const value: PCONF_VALUE; aint: PPASN1_INTEGER): TIdC_INT; procedure X509V3_set_nconf(ctx: PX509V3_CTX; conf: PCONF) cdecl; external CLibCrypto; // void X509V3_set_conf_lhash(ctx: PX509V3_CTX; LHASH_OF(CONF_VALUE) *lhash); function X509V3_get_string(ctx: PX509V3_CTX; const name: PIdAnsiChar; const section: PIdAnsiChar): PIdAnsiChar cdecl; external CLibCrypto; // STACK_OF(CONF_VALUE) *X509V3_get_section(ctx: PX509V3_CTX; const section: PIdAnsiChar); procedure X509V3_string_free(ctx: PX509V3_CTX; str: PIdAnsiChar) cdecl; external CLibCrypto; // void X509V3_section_free(ctx: PX509V3_CTX; STACK_OF(CONF_VALUE) *section); procedure X509V3_set_ctx(ctx: PX509V3_CTX; issuer: PX509; subject: PX509; req: PX509_REQ; crl: PX509_CRL; flags: TIdC_INT) cdecl; external CLibCrypto; // TIdC_INT X509V3_add_value(const name: PIdAnsiChar; const value: PIdAnsiChar; STACK_OF(CONF_VALUE) **extlist); // TIdC_INT X509V3_add_value_uPIdAnsiChar(const name: PIdAnsiChar; const Byte *value; STACK_OF(CONF_VALUE) **extlist); // TIdC_INT X509V3_add_value_bool(const name: PIdAnsiChar; TIdC_INT asn1_bool; STACK_OF(CONF_VALUE) **extlist); // TIdC_INT X509V3_add_value_int(const name: PIdAnsiChar; const aint: PASN1_INTEGER; STACK_OF(CONF_VALUE) **extlist); //function i2s_ASN1_INTEGER(meth: PX509V3_EXT_METHOD; const aint: PASN1_INTEGER): PIdAnsiChar; //function s2i_ASN1_INTEGER(meth: PX509V3_EXT_METHOD; const value: PIdAnsiChar): PASN1_INTEGER; //function i2s_ASN1_ENUMERATED(meth: PX509V3_EXT_METHOD; const aint: PASN1_ENUMERATED): PIdAnsiChar; //function i2s_ASN1_ENUMERATED_TABLE(meth: PX509V3_EXT_METHOD; const aint: PASN1_ENUMERATED): PIdAnsiChar; //function X509V3_EXT_add(ext: PX509V3_EXT_METHOD): TIdC_INT; //function X509V3_EXT_add_list(extlist: PX509V3_EXT_METHOD): TIdC_INT; function X509V3_EXT_add_alias(nid_to: TIdC_INT; nid_from: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; procedure X509V3_EXT_cleanup cdecl; external CLibCrypto; //function X509V3_EXT_get(ext: PX509_EXTENSION): PX509V3_EXT_METHOD; //function X509V3_EXT_get_nid(nid: TIdC_INT): PX509V3_EXT_METHOD; function X509V3_add_standard_extensions: TIdC_INT cdecl; external CLibCrypto; // STACK_OF(CONF_VALUE) *X509V3_parse_list(const line: PIdAnsiChar); function X509V3_EXT_d2i(ext: PX509_EXTENSION): Pointer cdecl; external CLibCrypto; // void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x; nid: TIdC_INT; TIdC_INT *crit; TIdC_INT *idx); function X509V3_EXT_i2d(ext_nid: TIdC_INT; crit: TIdC_INT; ext_struc: Pointer): PX509_EXTENSION cdecl; external CLibCrypto; // TIdC_INT X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x; nid: TIdC_INT; value: Pointer; crit: TIdC_INT; TIdC_ULONG flags); // void X509V3_EXT_val_prn(out_: PBIO; STACK_OF(CONF_VALUE) *val; indent: TIdC_INT; TIdC_INT ml); function X509V3_EXT_print(out_: PBIO; ext: PX509_EXTENSION; flag: TIdC_ULONG; indent: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509V3_extensions_print(out_: PBIO; const PIdAnsiChar *title; const STACK_OF(X509_EXTENSION) *exts; flag: TIdC_ULONG; indent: TIdC_INT); function X509_check_ca(x: PX509): TIdC_INT cdecl; external CLibCrypto; function X509_check_purpose(x: PX509; id: TIdC_INT; ca: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; function X509_supported_extension(ex: PX509_EXTENSION): TIdC_INT cdecl; external CLibCrypto; function X509_PURPOSE_set(p: PIdC_INT; purpose: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; function X509_check_issued(issuer: PX509; subject: PX509): TIdC_INT cdecl; external CLibCrypto; function X509_check_akid(issuer: PX509; akid: PAUTHORITY_KEYID): TIdC_INT cdecl; external CLibCrypto; procedure X509_set_proxy_flag(x: PX509) cdecl; external CLibCrypto; procedure X509_set_proxy_pathlen(x: PX509; l: TIdC_LONG) cdecl; external CLibCrypto; function X509_get_proxy_pathlen(x: PX509): TIdC_LONG cdecl; external CLibCrypto; function X509_get_extension_flags(x: PX509): TIdC_UINT32 cdecl; external CLibCrypto; function X509_get_key_usage(x: PX509): TIdC_UINT32 cdecl; external CLibCrypto; function X509_get_extended_key_usage(x: PX509): TIdC_UINT32 cdecl; external CLibCrypto; function X509_get0_subject_key_id(x: PX509): PASN1_OCTET_STRING cdecl; external CLibCrypto; function X509_get0_authority_key_id(x: PX509): PASN1_OCTET_STRING cdecl; external CLibCrypto; //function X509_get0_authority_issuer(x: PX509): PGENERAL_NAMES; function X509_get0_authority_serial(x: PX509): PASN1_INTEGER cdecl; external CLibCrypto; function X509_PURPOSE_get_count: TIdC_INT cdecl; external CLibCrypto; function X509_PURPOSE_get0(idx: TIdC_INT): PX509_PURPOSE cdecl; external CLibCrypto; function X509_PURPOSE_get_by_sname(const sname: PIdAnsiChar): TIdC_INT cdecl; external CLibCrypto; function X509_PURPOSE_get_by_id(id: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509_PURPOSE_add(id: TIdC_INT, TIdC_INT trust, flags: TIdC_INT, TIdC_INT (*ck) (const X509_PURPOSE *, const X509 *, TIdC_INT), const name: PIdAnsiChar, const sname: PIdAnsiChar, void *arg); function X509_PURPOSE_get0_name(const xp: PX509_PURPOSE): PIdAnsiChar cdecl; external CLibCrypto; function X509_PURPOSE_get0_sname(const xp: PX509_PURPOSE): PIdAnsiChar cdecl; external CLibCrypto; function X509_PURPOSE_get_trust(const xp: PX509_PURPOSE): TIdC_INT cdecl; external CLibCrypto; procedure X509_PURPOSE_cleanup cdecl; external CLibCrypto; function X509_PURPOSE_get_id(const v1: PX509_PURPOSE): TIdC_INT cdecl; external CLibCrypto; // STACK_OF(OPENSSL_STRING) *X509_get1_email(x: PX509); // STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x); // void X509_email_free(STACK_OF(OPENSSL_STRING) *sk); // STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(x: PX509); function X509_check_host(x: PX509; const chk: PIdAnsiChar; chklen: TIdC_SIZET; flags: TIdC_UINT; peername: PPIdAnsiChar): TIdC_INT cdecl; external CLibCrypto; function X509_check_email(x: PX509; const chk: PIdAnsiChar; chklen: TIdC_SIZET; flags: TIdC_UINT): TIdC_INT cdecl; external CLibCrypto; function X509_check_ip(x: PX509; const chk: PByte; chklen: TIdC_SIZET; flags: TIdC_UINT): TIdC_INT cdecl; external CLibCrypto; function X509_check_ip_asc(x: PX509; const ipasc: PIdAnsiChar; flags: TIdC_UINT): TIdC_INT cdecl; external CLibCrypto; function a2i_IPADDRESS(const ipasc: PIdAnsiChar): PASN1_OCTET_STRING cdecl; external CLibCrypto; function a2i_IPADDRESS_NC(const ipasc: PIdAnsiChar): PASN1_OCTET_STRING cdecl; external CLibCrypto; // TIdC_INT X509V3_NAME_from_section(X509_NAME *nm; STACK_OF(CONF_VALUE) *dn_sk; TIdC_ULONG chtype); procedure X509_POLICY_NODE_print(out_: PBIO; node: PX509_POLICY_NODE; indent: TIdC_INT) cdecl; external CLibCrypto; // DEFINE_STACK_OF(X509_POLICY_NODE) (* * Utilities to construct and extract values from RFC3779 extensions, * since some of the encodings (particularly for IP address prefixes * and ranges) are a bit tedious to work with directly. *) //function X509v3_asid_add_inherit(asid: PASIdentifiers; which: TIdC_INT): TIdC_INT; //function X509v3_asid_add_id_or_range(asid: PASIdentifiers; which: TIdC_INT; min: PASN1_INTEGER; max: PASN1_INTEGER): TIdC_INT; //function X509v3_addr_add_inherit(addr: PIPAddrBlocks; const afi: TIdC_UINT; const safi: PIdC_UINT): TIdC_INT; //function X509v3_addr_add_prefix(addr: PIPAddrBlocks; const afi: TIdC_UINT; const safi: PIdC_UINT; a: PByte; const prefixlen: TIdC_INT): TIdC_INT; //function X509v3_addr_add_range(addr: PIPAddrBlocks; const afi: TIdC_UINT; const safi: PIdC_UINT; min: PByte; max: PByte): TIdC_INT; //function X509v3_addr_get_afi(const f: PIPAddressFamily): TIdC_UINT; function X509v3_addr_get_range(aor: PIPAddressOrRange; const afi: TIdC_UINT; min: PByte; max: Byte; const length: TIdC_INT): TIdC_INT cdecl; external CLibCrypto; (* * Canonical forms. *) //function X509v3_asid_is_canonical(asid: PASIdentifiers): TIdC_INT; //function X509v3_addr_is_canonical(addr: PIPAddrBlocks): TIdC_INT; //function X509v3_asid_canonize(asid: PASIdentifiers): TIdC_INT; //function X509v3_addr_canonize(addr: PIPAddrBlocks): TIdC_INT; (* * Tests for inheritance and containment. *) //function X509v3_asid_inherits(asid: PASIdentifiers): TIdC_INT; //function X509v3_addr_inherits(addr: PIPAddrBlocks): TIdC_INT; //function X509v3_asid_subset(a: PASIdentifiers; b: PASIdentifiers): TIdC_INT; //function X509v3_addr_subset(a: PIPAddrBlocks; b: PIPAddrBlocks): TIdC_INT; (* * Check whether RFC 3779 extensions nest properly in chains. *) function X509v3_asid_validate_path(v1: PX509_STORE_CTX): TIdC_INT cdecl; external CLibCrypto; function X509v3_addr_validate_path(v1: PX509_STORE_CTX): TIdC_INT cdecl; external CLibCrypto; // TIdC_INT X509v3_asid_validate_resource_set(STACK_OF(X509) *chain; ASIdentifiers *ext; TIdC_INT allow_inheritance); // TIdC_INT X509v3_addr_validate_resource_set(STACK_OF(X509) *chain; IPAddrBlocks *ext; TIdC_INT allow_inheritance); // DEFINE_STACK_OF(ASN1_STRING) (* * Admission Syntax *) function NAMING_AUTHORITY_get0_authorityId(const n: PNAMING_AUTHORITY): PASN1_OBJECT cdecl; external CLibCrypto; function NAMING_AUTHORITY_get0_authorityURL(const n: PNAMING_AUTHORITY): PASN1_IA5STRING cdecl; external CLibCrypto; function NAMING_AUTHORITY_get0_authorityText(const n: PNAMING_AUTHORITY): PASN1_STRING cdecl; external CLibCrypto; procedure NAMING_AUTHORITY_set0_authorityId(n: PNAMING_AUTHORITY; namingAuthorityId: PASN1_OBJECT) cdecl; external CLibCrypto; procedure NAMING_AUTHORITY_set0_authorityURL(n: PNAMING_AUTHORITY; namingAuthorityUrl: PASN1_IA5STRING) cdecl; external CLibCrypto; procedure NAMING_AUTHORITY_set0_authorityText(n: PNAMING_AUTHORITY; namingAuthorityText: PASN1_STRING) cdecl; external CLibCrypto; function ADMISSION_SYNTAX_get0_admissionAuthority(const as_: ADMISSION_SYNTAX): PGENERAL_NAME cdecl; external CLibCrypto; procedure ADMISSION_SYNTAX_set0_admissionAuthority(as_: ADMISSION_SYNTAX; aa: PGENERAL_NAME) cdecl; external CLibCrypto; // const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions(const as_: ADMISSION_SYNTAX); // void ADMISSION_SYNTAX_set0_contentsOfAdmissions(as_: ADMISSION_SYNTAX; STACK_OF(ADMISSIONS) *a); function ADMISSIONS_get0_admissionAuthority(const a: PADMISSIONS): PGENERAL_NAME cdecl; external CLibCrypto; procedure ADMISSIONS_set0_admissionAuthority(a: PADMISSIONS; aa: PGENERAL_NAME) cdecl; external CLibCrypto; function ADMISSIONS_get0_namingAuthority(const a: PADMISSIONS): PNAMING_AUTHORITY cdecl; external CLibCrypto; procedure ADMISSIONS_set0_namingAuthority(a: PADMISSIONS; na: PNAMING_AUTHORITY) cdecl; external CLibCrypto; //function ADMISSIONS_get0_professionInfos(const a: PADMISSIONS): PPROFESSION_INFOS; //procedure ADMISSIONS_set0_professionInfos(a: PADMISSIONS; pi: PPROFESSION_INFOS); function PROFESSION_INFO_get0_addProfessionInfo(const pi: PPROFESSION_INFO): PASN1_OCTET_STRING cdecl; external CLibCrypto; procedure PROFESSION_INFO_set0_addProfessionInfo(pi: PPROFESSION_INFO; aos: PASN1_OCTET_STRING) cdecl; external CLibCrypto; function PROFESSION_INFO_get0_namingAuthority(const pi: PPROFESSION_INFO): PNAMING_AUTHORITY cdecl; external CLibCrypto; procedure PROFESSION_INFO_set0_namingAuthority(pi: PPROFESSION_INFO; na: PNAMING_AUTHORITY) cdecl; external CLibCrypto; // const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems(const pi: PPROFESSION_INFO); // void PROFESSION_INFO_set0_professionItems(pi: PPROFESSION_INFO; STACK_OF(ASN1_STRING) *as); // const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs(const pi: PPROFESSION_INFO); // void PROFESSION_INFO_set0_professionOIDs(pi: PPROFESSION_INFO; STACK_OF(ASN1_OBJECT) *po); function PROFESSION_INFO_get0_registrationNumber(const pi: PPROFESSION_INFO): PASN1_PRINTABLESTRING cdecl; external CLibCrypto; procedure PROFESSION_INFO_set0_registrationNumber(pi: PPROFESSION_INFO; rn: PASN1_PRINTABLESTRING) cdecl; external CLibCrypto; implementation end.
unit AlgoControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FrogAlgo; type TFrmControlAlgo = class(TForm) BtnBeginPauseResume: TButton; BtnQuitStop: TButton; EdtStatus: TEdit; MemFROGError: TMemo; LblAlgo: TLabel; LblFROGError: TLabel; cmdForceChange: TButton; Label1: TLabel; edtBestError: TEdit; procedure BtnBeginPauseResumeClick(Sender: TObject); procedure BtnQuitStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cmdForceChangeClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } // Events mOnBegin: TNotifyEvent; mOnPause: TNotifyEvent; mOnResume: TNotifyEvent; mOnStop: TNotifyEvent; mOnQuit: TNotifyEvent; mOnForceChange: TNotifyEvent; mClosingProperly: boolean; public { Public declarations } //procedure TheBossIs(pAlgoMgr: TFrogAlgorithmDirector); procedure StatusMessage(pMess: string); procedure Clear; procedure Add(pMessage: string); procedure SetBestError(pError: double); property OnBegin: TNotifyEvent read mOnBegin write mOnBegin; property OnPause: TNotifyEvent read mOnPause write mOnPause; property OnResume: TNotifyEvent read mOnResume write mOnResume; property OnQuit: TNotifyEvent read mOnQuit write mOnQuit; property OnStop: TNotifyEvent read mOnStop write mOnStop; property OnForceChange: TNotifyEvent read mOnForceChange write mOnForceChange; end; var FrmControlAlgo: TFrmControlAlgo; implementation uses WindowMgr; {$R *.DFM} procedure TFrmControlAlgo.BtnBeginPauseResumeClick(Sender: TObject); begin if BtnBeginPauseResume.Caption = '&Begin' then begin BtnBeginPauseResume.Caption := '&Pause'; btnQuitStop.Caption := '&Stop'; btnQuitStop.SetFocus; if Assigned(mOnBegin) then mOnBegin(Self); end else if BtnBeginPauseResume.Caption = '&Pause' then begin BtnBeginPauseResume.Caption := '&Resume'; if Assigned(mOnPause) then mOnPause(Self); end else if BtnBeginPauseResume.Caption = '&Resume' then begin BtnBeginPauseResume.Caption := '&Pause'; if Assigned(mOnResume) then mOnResume(Self); end; end; procedure TFrmControlAlgo.BtnQuitStopClick(Sender: TObject); begin if (BtnQuitStop.Caption = '&Quit') then begin if Assigned(mOnQuit) then mOnQuit(Self); mClosingProperly := True; Close; end else {if BtnQuitStop.Caption = 'Stop' then} begin btnQuitStop.Caption := '&Quit'; BtnBeginPauseResume.Caption := '&Begin'; if Assigned(mOnStop) then mOnStop(Self); end; end; procedure TFrmControlAlgo.FormCreate(Sender: TObject); var count: Integer; begin //Height := 223; //Width := 318; mClosingProperly := False; // The label controls have problems with large and small fonts // This seems to help for count := 0 to ComponentCount - 1 do if Components[count] is TLabel then begin (Components[count] as TLabel).AutoSize := False; (Components[count] as TLabel).AutoSize := True; end; end; procedure TFrmControlAlgo.StatusMessage(pMess: string); begin edtStatus.Text := pMess; end; procedure TFrmControlAlgo.Clear; begin memFrogError.Lines.Clear; end; procedure TFrmControlAlgo.Add(pMessage: string); begin memFrogError.Lines.Add(pMessage); end; procedure TFrmControlAlgo.SetBestError(pError: double); begin edtBestError.Text := FloatToStrF(pError, ffGeneral, 5, 5); end; procedure TFrmControlAlgo.cmdForceChangeClick(Sender: TObject); begin if Assigned(mOnForceChange) then mOnForceChange(Self); end; procedure TFrmControlAlgo.FormClose(Sender: TObject; var Action: TCloseAction); begin if not mClosingProperly then Action := caNone else Action := caFree; end; end.
unit SaleTest; interface uses dbTest, dbMovementTest, ObjectTest; type TSaleTest = class (TdbMovementTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TSale = class(TMovementTest) private function InsertDefault: integer; override; public function InsertUpdateSale(Id: Integer; InvNumber,InvNumberPartner,InvNumberOrder: String; OperDate: TDateTime; OperDatePartner: TDateTime; Checked, PriceWithVAT: Boolean; VATPercent, ChangePercent: double; FromId, ToId, PaidKindId, ContractId, {CarId, PersonalDriverId, RouteId, PersonalId, }RouteSortingId,PriceListId: Integer ): integer; constructor Create; override; end; implementation uses UtilConst, dbObjectMeatTest, JuridicalTest, UnitsTest, dbObjectTest, SysUtils, Db, TestFramework, PartnerTest, ContractTest; { TSale } constructor TSale.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Movement_Sale'; spSelect := 'gpSelect_Movement_Sale'; spGet := 'gpGet_Movement_Sale'; end; function TSale.InsertDefault: integer; var Id: Integer; InvNumber,InvNumberPartner: String; OperDate: TDateTime; OperDatePartner: TDateTime; Checked,PriceWithVAT: Boolean; VATPercent, ChangePercent: double; InvNumberOrder:String; FromId, ToId, PaidKindId, ContractId, {CarId, PersonalDriverId, RouteId, PersonalId,} RouteSortingId, PriceListId: Integer; begin Id:=0; InvNumber:='1'; InvNumberPartner:='123'; OperDate:= Date; OperDatePartner:= Date; Checked:=true; PriceWithVAT:=true; VATPercent:=20; ChangePercent:=-10; InvNumberOrder:=''; FromId := TPartner.Create.GetDefault; ToId := TUnit.Create.GetDefault; PaidKindId:=1; ContractId:=TContract.Create.GetDefault; //CarId:=0; //PersonalDriverId:=0; //RouteId:=0; //PersonalId:=0; RouteSortingId:=0; PriceListId:=0; // result := InsertUpdateSale(Id, InvNumber, InvNumberPartner, InvNumberOrder, OperDate, OperDatePartner, Checked, PriceWithVAT, VATPercent, ChangePercent, FromId, ToId, PaidKindId, ContractId, {CarId,PersonalDriverId, RouteId, PersonalId,} RouteSortingId,PriceListId); end; function TSale.InsertUpdateSale(Id: Integer; InvNumber,InvNumberPartner,InvNumberOrder: String; OperDate: TDateTime; OperDatePartner: TDateTime; Checked, PriceWithVAT: Boolean; VATPercent, ChangePercent: double; FromId, ToId, PaidKindId, ContractId, {CarId, PersonalDriverId, RouteId, PersonalId, }RouteSortingId,PriceListId: Integer ): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber); FParams.AddParam('inInvNumberPartner', ftString, ptInput, InvNumber); FParams.AddParam('inInvNumberOrder', ftString, ptInput, InvNumberOrder); FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate); FParams.AddParam('inOperDatePartner', ftDateTime, ptInput, OperDatePartner); FParams.AddParam('inChecked', ftBoolean, ptInput, Checked); FParams.AddParam('inPriceWithVAT', ftBoolean, ptInput, PriceWithVAT); FParams.AddParam('inVATPercent', ftFloat, ptInput, VATPercent); FParams.AddParam('inChangePercent', ftFloat, ptInput, ChangePercent); FParams.AddParam('inFromId', ftInteger, ptInput, FromId); FParams.AddParam('inToId', ftInteger, ptInput, ToId); FParams.AddParam('inPaidKindId', ftInteger, ptInput, PaidKindId); FParams.AddParam('inContractId', ftInteger, ptInput, ContractId); // FParams.AddParam('inCarId', ftInteger, ptInput, CarId); // FParams.AddParam('inPersonalDriverId', ftInteger, ptInput, PersonalDriverId); // FParams.AddParam('inRouteId', ftInteger, ptInput, RouteId); // FParams.AddParam('inPersonalId', ftInteger, ptInput, PersonalId); FParams.AddParam('inRouteSortingId', ftInteger, ptInput, RouteSortingId); FParams.AddParam('ioPriceListId', ftInteger, ptInput, PriceListId); result := InsertUpdate(FParams); end; { TSaleTest } procedure TSaleTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'Movement\Sale\'; inherited; ScriptDirectory := ProcedurePath + 'MovementItem\Sale\'; inherited; ScriptDirectory := ProcedurePath + 'MovementItemContainer\Sale\'; inherited; end; procedure TSaleTest.Test; var MovementSale: TSale; Id: Integer; begin inherited; // Создаем документ MovementSale := TSale.Create; Id := MovementSale.InsertDefault; // создание документа try // редактирование finally MovementSale.Delete(Id); end; end; initialization // TestFramework.RegisterTest('Документы', TSaleTest.Suite); end.
(* Name: UfrmSelectBCP47Language Copyright: Copyright (C) SIL International. Date: 7 Dec 2017 Authors: mcdurdin *) unit Keyman.Developer.UI.UfrmSelectBCP47Language; interface uses System.Classes, System.SysUtils, System.Variants, Winapi.Messages, Winapi.Windows, Vcl.Controls, Vcl.Dialogs, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls, UfrmTike, BCP47Tag, Vcl.ExtCtrls; type TfrmSelectBCP47Language = class(TTikeForm) cmdOK: TButton; cmdCancel: TButton; lblLanguageTag: TLabel; lblScriptTag: TLabel; lblRegionTag: TLabel; editLanguageTag: TEdit; editScriptTag: TEdit; editRegionTag: TEdit; lblBCP47Code: TLabel; editBCP47Code: TEdit; lblValidateCode: TLabel; lblLanguageName: TLabel; lblScriptName: TLabel; lblRegionName: TLabel; lblLinkToW3C: TLinkLabel; procedure editLanguageTagChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure editScriptTagChange(Sender: TObject); procedure editRegionTagChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lblLinkToW3CLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); private tag: TBCP47Tag; function GetLanguageID: string; function GetLanguageName: string; procedure RefreshPreview; { Private declarations } public { Public declarations } property LanguageID: string read GetLanguageID; property LanguageName: string read GetLanguageName; end; implementation uses Keyman.System.KMXFileLanguages, utilexecute; {$R *.dfm} { TfrmSelectBCP47Language } procedure TfrmSelectBCP47Language.FormCreate(Sender: TObject); begin inherited; tag := TBCP47Tag.Create(''); end; procedure TfrmSelectBCP47Language.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(tag); end; function TfrmSelectBCP47Language.GetLanguageID: string; begin Result := tag.Tag; end; function TfrmSelectBCP47Language.GetLanguageName: string; begin // TODO: BCP47: <DeveloperBCP47LanguageLookup> per lookup with BCP-47 feature Result := tag.Tag; end; procedure TfrmSelectBCP47Language.lblLinkToW3CLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin TUtilExecute.URL(Link); end; procedure TfrmSelectBCP47Language.editLanguageTagChange(Sender: TObject); begin inherited; // TODO: BCP47: <DeveloperBCP47LanguageLookup> search on language names instead of just taking a tag tag.Language := TKMXFileLanguages.TranslateISO6393ToBCP47(editLanguageTag.Text); RefreshPreview; end; procedure TfrmSelectBCP47Language.editRegionTagChange(Sender: TObject); begin inherited; tag.Region := editRegionTag.Text; RefreshPreview; end; procedure TfrmSelectBCP47Language.editScriptTagChange(Sender: TObject); begin inherited; tag.Script := editScriptTag.Text; RefreshPreview; end; procedure TfrmSelectBCP47Language.RefreshPreview; var msg: string; begin editBCP47Code.Text := tag.Tag; lblLanguageName.Caption := tag.Language; // TODO: BCP47: <DeveloperBCP47LanguageLookup> Lookup language name lblScriptName.Caption := tag.Script; // TODO: BCP47: <DeveloperBCP47LanguageLookup> Lookup script name lblRegionName.Caption := tag.Region; // TODO: BCP47: <DeveloperBCP47LanguageLookup> Lookup region name cmdOK.Enabled := tag.IsValid(msg); if not cmdOK.Enabled then lblValidateCode.Caption := msg else lblValidateCode.Caption := 'This is a valid BCP 47 tag'; end; end.
// ****************************************************************** // // Program Name : Single Instance Framework // Platform(s) : OSX // Framework : FMX // // Filename : AT.SingleInstance.MacOS.pas // File Version : 1.00 // Date Created : 07-Dec-2017 // Author : Matthew Vesperman // // Description: // // Defines the single instance checking class for the OSX platform. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2017 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** //Only compile for the OS X platform. {$IF ( (NOT Defined(MACOS)) OR (Defined(IOS)) )} {$MESSAGE Fatal 'AT.SingleInstance.MacOS.pas only compiles for the OS X platform.'} {$ENDIF} /// <summary> /// Defines the single instance checking class for the OSX /// platform. /// </summary> unit AT.SingleInstance.MacOS; interface uses AT.SingleInstance.Base, Macapi.CoreFoundation; type /// <summary> /// The single instance checking class for the OSX platform. /// </summary> /// <seealso cref="AT.SingleInstance.Base|TATCustomSingleInstance"> /// TATCustomSingleInstance /// </seealso> TATMacOSSingleInstance = class(TATCustomSingleInstance) strict private /// <summary> /// Holds a reference to the local CFMessagePort object. /// </summary> FLocalPort: CFMessagePortRef; /// <summary> /// Holds a reference to the local CFRunLoopSource object. /// </summary> FRunLoopSrc: CFRunLoopSourceRef; strict protected /// <seealso cref="AT.SingleInstance.Base|TATCustomSingleInstance.GetIsFirstInstance"> /// TATCustomSingleInstance.GetIsFirstInstance /// </seealso> function GetIsFirstInstance: Boolean; override; public /// <summary> /// The class' constrcutor method. /// </summary> constructor Create; override; /// <summary> /// The clas' destructor method. /// </summary> destructor Destroy; override; class function CheckSingleInstance(const AppID: String; out IsFirst: Boolean; out Err: Integer): Boolean; override; /// <seealso cref="AT.SingleInstance.Base|TATCustomSingleInstance.SendParamStrings"> /// TATCustomSingleInstance.SendParamStrings /// </seealso> procedure SendParamStrings; override; /// <seealso cref="AT.SingleInstance.Base|TATCustomSingleInstance.StartListening"> /// TATCustomSingleInstance.StartListening /// </seealso> procedure StartListening; override; end; implementation uses System.SysUtils, System.Classes, Macapi.Foundation, Macapi.Helpers, System.IOUtils, Spring.Collections, AT.SingleInstance; type /// <summary> /// Defines the buffer type to be used with the core foundation /// messaging system. /// </summary> TATDataArray = array[0..8192] of char; var /// <summary> /// Stores a reference to a NSDistributedLock (Mutex) object. /// </summary> MMutex: NSDistributedLock; /// <summary> /// Stores the AppID that was passed to CheckSingleInstance. /// </summary> MAppID: String; /// <summary> /// Stores a flag indicating if this is the first instance. /// </summary> MIsFirstInstance: Boolean; /// <summary> /// Holds the name of the port used with the core foundation /// messaging system. /// </summary> MPortName: String; /// <summary> /// The callback function that the core foundation messaging system /// calls when a new instance sends us a param strings message. /// </summary> /// <param name="APort"> /// The local message port that received the message. /// </param> /// <param name="AMessageID"> /// An arbitrary integer value assigned to the message by the /// sender. /// </param> /// <param name="AData"> /// The message data. /// </param> /// <param name="AInfo"> /// The info member of the CFMessagePortContext structure that was /// used when creating APort. /// </param> /// <returns> /// Data to send back to the sender of the message. The system /// releases the returned CFData object. Return NULL if you want an /// empty reply returned to the sender. /// </returns> /// <remarks> /// If you want the message data to persist beyond this callback, /// you must explicitly create a copy of data rather than merely /// retain it; the contents of data will be deallocated after the /// callback exits. /// </remarks> /// <seealso href="https://developer.apple.com/documentation/corefoundation/cfmessageportcallback"> /// CFMessagePortCallBack <br /> /// </seealso> function ListenCallback(APort: CFMessagePortRef; AMessageID: SInt32; AData: CFDataRef; AInfo: Pointer): CFDataRef; cdecl; var ALen: Integer; AValue: TATDataArray; AParams: TStrings; Cnt: Integer; Idx: Integer; AHandler: TATSingleInstanceHandler; begin Result := NIL; //We don't need to return anything to the caller... //Get the size of the AData object that was sent to us... ALen := CFDataGetLength(AData); //Copy the data from AData to our own data buffer variable... CFDataGetBytes(AData, CFRangeMake(0, ALen), PByte(@AValue[0])); //Create a stringlist to hold the parameters... AParams := TStringList.Create; try //Set the stringlist text to the Value variable's contents... AParams.Text := String(AValue); //Get the number of handlers in the dictionary... Cnt := SingleInstance.Handlers.Count; //For all of the handlers do the following... for Idx := 0 to (Cnt - 1) do begin //Get a reference to the handler... AHandler := SingleInstance.Handlers.Values.ElementAt(Idx); //If the reference is valid... if (Assigned(AHandler)) then AHandler(AParams); //call the handler... end; finally AParams.Free; end; end; constructor TATMacOSSingleInstance.Create; begin inherited Create; //Generate a name for the core foundatio messaging system port... MPortName := Format('%s.InstancePort', [MAppID]); end; destructor TATMacOSSingleInstance.Destroy; begin //If we have a reference to a CFRunLoopSource object... if (Assigned(FRunLoopSrc)) then CFRelease(FRunLoopSrc); //Release it... //If we have a reference to a CFMessagePort object... if (Assigned(FLocalPort)) then CFRelease(FLocalPort); //Release it... inherited; end; class function TATMacOSSingleInstance.CheckSingleInstance( const AppID: String; out IsFirst: Boolean; out Err: Integer): Boolean; var AFileName: String; begin //Save the AppID... MAppID := AppID; //Do we already have a Mutex??? if (Assigned(MMutex)) then begin //Yes, return the previous values... IsFirst := MIsFirstInstance; Err := 0; Exit(True); end; //Calculate the name for the Mutex... AFileName := TPath.GetTempPath; AFileName := IncludeTrailingPathDelimiter(AFileName); AFileName := Format('%s%s.instance.lock', [AFileName, AppID]); //Create a NSDistributedLock (Mutex) object... MMutex := TNSDistributedLock.Wrap( TNSDistributedLock.Alloc.initWithPath( StrToNSStr(AFileName))); //Get the last OS error... Err := GetLastError; //Was a Mutex created??? if (NOT Assigned(MMutex)) then begin //No, then the call failed... MIsFirstInstance := False; IsFirst := False; Exit(False); end; //This is the first instance if, and only if, we can lock the //Mutex object... MIsFirstInstance := MMutex.tryLock; //Return the first instance flag value... IsFirst := MIsFirstInstance; //Call success... Result := True; end; function TATMacOSSingleInstance.GetIsFirstInstance: Boolean; begin Result := MIsFirstInstance; end; procedure TATMacOSSingleInstance.SendParamStrings; var AMsgID: SInt32; ATimeout: CFTimeInterval; ARemotePort: CFMessagePortRef; AResult: CFDataRef; AStrings: TStrings; Idx: Integer; AValue: TATDataArray; ASize: Integer; AData: CFDataRef; begin //Set the message id to send to our MessageID property... AMsgID := MessageID; //Set the timeout for the core foundation messaging system call... ATimeout := 10.0; //Init variables... AResult := NIL; ARemotePort := NIL; //Create a stringlist to hold the params... AStrings := TStringList.Create; try //For each command line parameter... for Idx := 0 to ParamCount do AStrings.Add(ParamStr(Idx)); //Add it to the string list... //Get the size of outr data buffer... ASize := SizeOf(AValue); //Set the data buffer to all zeros (empty). FillChar(AValue, ASize, 0); //Copy the stringlist text into our data buffer... StrPLCopy(AValue, AStrings.Text, High(AValue)); //Create a data object to pass to the core foundation messaging //system... AData := CFDataCreate(NIL, PByte(@AValue[0]), ASize); //Open a core foundation system remote port object that points to //the named port... ARemotePort := CFMessagePortCreateRemote( NIL, CFSTR(MPortName)); //Send our message to the first instance using the core foundation //messaging system... CFMessagePortSendRequest(ARemotePort, AMsgID, AData, ATimeout, ATimeout, NIL, AResult); finally //Were we sent a result back??? if (Assigned(AResult)) then CFRelease(AResult); //Yes, release it... //If we have a reference to a CFMessagePort object... if (Assigned(ARemotePort)) then CFRelease(ARemotePort); //release the remote port... //free our stringlist... AStrings.Free; end; end; procedure TATMacOSSingleInstance.StartListening; begin //Create a core foundation messaging system local port that uses //our ListenCallback function to handle received messages on //our named port... FLocalPort := CFMessagePortCreateLocal( NIL, CFSTR(MPortName), ListenCallback, NIL, NIL); //Create a CFRunLoopSource object... FRunLoopSrc := CFMessagePortCreateRunLoopSource(NIL, FLocalPort, 0); //Add our runloop into the messaging system... CFRunLoopAddSource(CFRunLoopGetCurrent, FRunLoopSrc, kCFRunLoopCommonModes); end; initialization //Initialize module level variables... MMutex := NIL; MAppID := EmptyStr; MIsFirstInstance := False; finalization //If we are the first instance... if (MIsFirstInstance) then //Make sure we unlock the mutex before we terminate... MMutex.unlock; end.
unit uDocVariantTest; {$I Synopse.inc} {$I HPPas.inc} interface uses SysUtils, Math, {$ifdef MSWINDOWS} Windows, VarUtils, ComObj, {$endif} Classes, Variants, SynCommons, HPPas, HppStrs, HppTypeCast, HppSysUtils, HppJSONParser, HppVariants; procedure PrintSizeOf; procedure TestFormat; procedure PutCustomVariantToVariantArray; procedure test1; procedure test2; procedure test3; procedure test4; procedure HppVariantsTest; procedure TestRttiSerialize; procedure TestSmartString; procedure SynDynArray_Test; implementation procedure PrintSizeOf; var s1: ShortString; s2: string[20]; begin Writeln('SizeOf(TVariantDataType): ', SizeOf(TVariantDataType)); Writeln('SizeOf(TVarData): ', SizeOf(TVarData)); Writeln('SizeOf(TVariantProperty): ', SizeOf(TVariantProperty)); Writeln('SizeOf(TVariant8): ', SizeOf(TVariant8)); Writeln('SizeOf(TVariant16): ', SizeOf(TVariant16)); Writeln('SizeOf(TVariant32): ', SizeOf(TVariant32)); Writeln('SizeOf(TVariant64): ', SizeOf(TVariant64)); Writeln('SizeOf(TCompactVariant): ', SizeOf(TCompactVariant)); Writeln('SizeOf(Currency): ', SizeOf(Currency)); Writeln('SizeOf(WordBool): ', SizeOf(WordBool)); Writeln('SizeOf(ShortInt): ', SizeOf(ShortInt)); Writeln('SizeOf(SmallInt): ', SizeOf(SmallInt)); Writeln('SizeOf(ShortString): ', SizeOf(s1)); Writeln('SizeOf(string[20]): ', SizeOf(s2)); Writeln('SizeOf(ElementOfShortString): ', SizeOf(s1[1])); s1 := 's1s1s1'; s2 := 's2s2'; Writeln('s1: ', s1); Writeln('s2: ', s2); end; procedure TestFormat; begin end; function checkDocVariantData(const v: Variant; kind: TDocVariantKind; valueCount: Integer = -1): Boolean; var pData: PVarData; c: THppVariantContainer; begin pData := FindVarData(v); if pData.VType = DocVariantVType then Result := (TDocVariantData(pData^).Kind = kind) and ((valueCount = -1) or (TDocVariantData(pData^).Count = valueCount)) else if pData.VType = JsonVarTypeID then begin c := THppVariantContainer(pData.VPointer); Result := ((c.IsArray and (kind = dvArray)) or ((not c.IsArray and (kind = dvObject)))) and ((valueCount = -1) or (c.Count = valueCount)) ; end else Result := False; end; procedure printTitle(const title: string); begin Writeln; Writeln('**************************** ', title, ' ****************************'); end; procedure printPointer(ptr: Pointer); begin Writeln(Format('0x%p', [ptr])); end; procedure printVariant(const name: string; const v: Variant); var pData: PVarData; begin pData := FindVarData(v); if name <> '' then printTitle('dump ' + name); if pData.VType = DocVariantVType then Writeln(TDocVariantData(pData^).ToJSON('', '', jsonHumanReadable)) else if pData.VType and varArray = 0 then begin case pData.VType of varEmpty: Writeln('Unassigned'); varNull: Writeln('Null'); else Writeln(Variant(pData^)); end; end else begin Writeln('<OLE Array>'); end; end; procedure SynDynArray_Test; type TPerson = record name: string; age: Byte; end; TPersonDynArray = array of TPerson; TIntDynArray = array of Integer; var arrd: TIntDynArray; RecArrD: array of TPerson; arr: TDynArray; i, value, cnt: Integer; person: TPerson; begin arr.Init(TypeInfo(TIntDynArray), arrd, @cnt); for i := 0 to 100 do begin value := i * i; arr.Add(value); end; Writeln('arr.length: ', arr.Count); for i := 0 to arr.Count - 1 do Writeln('arrd[', i, ']: ', arrd[i]); arr.init(TypeInfo(TPersonDynArray), RecArrD, @cnt); person.name:='Susan'; person.age:=13; arr.Add(person); person.name := 'Bob'; person.age := 12; arr.Add(person); person.name := 'Alex'; person.age := 14; arr.Add(person); Writeln('arr.length: ', arr.Count); for i := 0 to arr.Count - 1 do Writeln('arrd[', i, ']: ', RecArrD[i].name, ' ', RecArrD[i].age); arr.Delete(1); Writeln('arr.length: ', arr.Count); for i := 0 to arr.Count - 1 do Writeln('arrd[', i, ']: ', RecArrD[i].name, ' ', RecArrD[i].age); end; const SAMPLE_JSON = '{"\"p1":"\ndfd", pp2: 1.3e50, "EmptyArray":[], "EmptyObject":{}, "students":[' + '{"age":21,"ismale":false,"name":"Susan","address":{"state":"Washington","city":"Seattle"}}' + ',{"age":22, "name":"Alex","ismale":true,"address":{"state":"California","city":"San Luis Obispo"}}' + ']}'; procedure PutCustomVariantToVariantArray; var vararr, doc: Variant; begin vararr := VarArrayCreate([0, 2], varVariant); doc := _JsonFast(SAMPLE_JSON); vararr[0] := doc; printVariant('vararr', vararr); end; procedure test1; var doc, students, student: Variant; begin printTitle('parse json text'); Writeln('doc := _JsonFast(', SAMPLE_JSON, ')'); doc := _JsonFast(SAMPLE_JSON); printVariant('doc', doc); Assert(checkDocVariantData(doc.students, dvArray, 2)); printVariant('doc.students', doc.students); Assert(doc.students[0].name = 'Susan'); Assert(doc.students[1].ismale = True); students := doc.students; printVariant('students[0]', students[0]); printVariant('students[1]', students[1]); TDocVariantData(student).Init([], dvObject); student.age := 18; student.ismale := True; student.name := 'Kobe'; student.address := _JsonFast('{"state":"Massa Chusetts","city":"Boston"}'); printVariant('student', student); students[1] := student; printVariant('students', students); printVariant('doc.students', doc.students); doc.Add('ShcoolName', 'Harvard University'); Assert(doc.ShcoolName = 'Harvard University'); printVariant('doc.ShcoolName', doc.ShcoolName); doc.Add('teachers', _JsonFast('[{"age":55,"ismale":false,"name":"Bill Gates"}]')); Assert(checkDocVariantData(doc.teachers, dvArray, 1)); Assert(doc.teachers[0].age = 55); printVariant('doc.teachers', doc.teachers); doc.students.add(_JsonFast('{"age":21,"ismale":false,"name":"James","address":{"state":"Utah","city":"Salt Lake"}}')); Assert(doc.students._count = 3); printVariant('doc.students[2]', doc.students[2]); Assert(doc.students[2].address.state = 'Utah'); Assert(doc.students[2].address['state'] = 'Utah'); printVariant('doc.students[2]', doc.students[2]); doc.students[2].address.city := doc.students[2].address['city'] + ' City'; printVariant('doc.students[2]', doc.students[2]); end; procedure test2; var doc, students: Variant; begin printTitle('parse json text'); Writeln('doc := _JsonFast(', SAMPLE_JSON, ')'); doc := _JsonFast(SAMPLE_JSON); printVariant('doc', doc); Assert(checkDocVariantData(doc.students, dvArray, 2)); printVariant('doc.students', doc.students); Assert(doc.students._(0).name = 'Susan'); Assert(doc.students._(1).ismale = True); students := doc.students; students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('students._(students._count - 1)', students._(students._count - 1)); printVariant('doc.students._(doc.students._count - 1)', doc.students._(doc.students._count - 1)); doc.Add('ShcoolName', 'Harvard University'); Assert(doc.ShcoolName = 'Harvard University'); printVariant('doc.ShcoolName', doc.ShcoolName); doc.students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('doc.students._(doc.students._count - 1)', doc.students._(doc.students._count - 1)); students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('students._(students._count - 1)', students._(students._count - 1)); end; procedure test3; var doc, students, student: Variant; begin Writeln(ParseJSON('1')); Writeln(ParseJSON('134e21')); Writeln(ParseJSON('.134e-21')); Writeln(ParseJSON('.134e-50')); printVariant('', ParseJSON('null')); Writeln(ParseJSON('false')); Writeln(ParseJSON('true')); Writeln(ParseJSON('"just a string"')); printTitle('parse json text'); Writeln('doc := ParseJSON(', SAMPLE_JSON, ')'); doc := ParseJSON(SAMPLE_JSON); printVariant('doc', doc); Assert(checkDocVariantData(doc.students, dvArray, 2)); printVariant('doc.students', doc.students); Assert(doc.students[0].name = 'Susan'); Assert(doc.students[1].ismale = True); students := doc.students; printVariant('students[0]', students[0]); printVariant('students[1]', students[1]); student := TVariantHandler.NewObject; student.age := 18; student.ismale := True; student.name := 'Kobe'; student.address := ParseJSON('{"state":"Massa Chusetts","city":"Boston"}'); printVariant('student', student); students[1] := student; printVariant('students', students); printVariant('doc.students', doc.students); doc.Add('ShcoolName', 'Harvard University'); Assert(doc.ShcoolName = 'Harvard University'); Writeln(THppVariantObject(TVarData(doc).vpointer).GetString('ShcoolName').ToUTF16String); printVariant('doc.ShcoolName', doc.ShcoolName); doc.Add('teachers', ParseJSON('[{"age":55,"ismale":false,"name":"Bill Gates"}]')); Assert(checkDocVariantData(doc.teachers, dvArray, 1)); Assert(doc.teachers[0].age = 55); printVariant('doc.teachers', doc.teachers); doc.students.add(ParseJSON('{"age":21,"ismale":false,"name":"James","address":{"state":"Utah","city":"Salt Lake"}}')); Assert(doc.students._count = 3); printVariant('doc.students[2]', doc.students[2]); Assert(doc.students[2].address.state = 'Utah'); Assert(doc.students[2].address['state'] = 'Utah'); printVariant('doc.students[2]', doc.students[2]); doc.students[2].address.city := doc.students[2].address['city'] + ' City'; printVariant('doc.students[2]', doc.students[2]); end; procedure test4; var doc, students: Variant; begin printTitle('parse json text'); Writeln('doc := ParseJSON(', SAMPLE_JSON, ')'); doc := ParseJSON(SAMPLE_JSON); printVariant('doc', doc); Assert(checkDocVariantData(doc.students, dvArray, 2)); printVariant('doc.students', doc.students); Assert(doc.students._(0).name = 'Susan'); Assert(doc.students._(1).ismale = True); students := doc.students; students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('students._(students._count - 1)', students._(students._count - 1)); printVariant('doc.students._(doc.students._count - 1)', doc.students._(doc.students._count - 1)); doc.Add('ShcoolName', 'Harvard University'); Assert(doc.ShcoolName = 'Harvard University'); printVariant('doc.ShcoolName', doc.ShcoolName); doc.students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('doc.students._(doc.students._count - 1)', doc.students._(doc.students._count - 1)); students.add('untitled'); Writeln(students._count); Writeln(doc.students._count); printVariant('students._(students._count - 1)', students._(students._count - 1)); end; procedure TestSmartString; var u8s: UTF8String; ss: TStringView; {$ifdef MSWINDOWS} oldcp: Integer; numbytes: Cardinal; {$endif} begin {$ifdef MSWINDOWS} oldcp := GetConsoleOutputCP; //SetConsoleOutputCP(CP_UTF8); try {$endif} u8s := UTF8Encode('[priˈæmbl] 美 [ˈpriˌæmbəl, priˈæm-]n.前言;序;绪言;(法令、文件等的)序文'); ss.ResetAnsiString(u8s, CP_UTF8); Writeln(ss.ToRawByteString); Writeln(ss.ToUTF16String); {$ifdef MSWINDOWS} WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), Pointer(ss.ToNullTerminatedUTF16), ss.GetUTF16Length, numbytes, nil); Writeln; {$endif} {$ifdef MSWINDOWS} finally SetConsoleOutputCP(oldcp); end; {$endif} end; type TPerson = class(TPersistent) private FName: string; FAge: Integer; procedure SetName(const Value: string); procedure SetAge(const Value: Integer); published property Name: string read FName write SetName; property Age: Integer read FAge write SetAge; end; procedure TestRttiSerialize; var person: TPerson; obj: THppVariantObject; obj2: THppVariantObject; begin obj := ParseJSONObject(UTF8Encode('{age:33,name:"李寻欢"}')); person := TPerson.Create; obj2 := THppVariantObject.Create(nil); try obj.ToSimpleObject(person); Writeln(person.Name, ' ', person.Age); obj2.FromSimpleObject(person); Writeln(obj2.ToString); finally obj.Free; obj2.Free; person.Free; end; end; procedure PrintJsonObjProp(obj: THppVariantObject; PropName: UTF8String); var v: Variant; vr: TVarData absolute v; vt: TVarType; begin try v := obj[PropName]; if vr.VType and varArray <> 0 then Writeln('obj.', PropName, ' is SafeArray'); if vr.VType and varByRef <> 0 then Writeln('obj.', PropName, ' is VariantByRef'); vt := vr.VType and varTypeMask; case vt of varEmpty: Writeln('obj.', PropName, ' is empty'); varNull: Writeln('obj.', PropName, ' is null'); varBoolean: Writeln('obj.', PropName, ' is Boolean: ', v); varShortInt: Writeln('obj.', PropName, ' is Int8: ', v); varByte: Writeln('obj.', PropName, ' is UInt8: ', v); varSmallint: Writeln('obj.', PropName, ' is Int16: ', v); varWord: Writeln('obj.', PropName, ' is UInt16: ', v); varInteger: Writeln('obj.', PropName, ' is Int32: ', v); varLongWord: Writeln('obj.', PropName, ' is UInt32: ', v); varInt64: Writeln('obj.', PropName, ' is Int64: ', v); varUInt64: Writeln('obj.', PropName, ' is UInt64: ', v); varString: Writeln('obj.', PropName, ' is AnsiString: ', v); varOleStr: Writeln('obj.', PropName, ' is WideString: ', v); {$ifdef HASVARUSTRING} varUString: Writeln('obj.', PropName, ' is UnicodeString: ', v); {$endif} varUnknown: Writeln('obj.', PropName, ' is Interface: ', PtrInt(vr.VUnknown)); varDispatch: Writeln('obj.', PropName, ' is IDispatch: ', PtrInt(vr.VDispatch)); varDouble: Writeln('obj.', PropName, ' is Double: ', v); varDate: Writeln('obj.', PropName, ' is Date: ', v); varCurrency: Writeln('obj.', PropName, ' is Currency: ', v); varSingle: Writeln('obj.', PropName, ' is Single: ', v); end; except on e: Exception do Writeln(e.ClassName, ': ', e.Message); end; end; function generatePropName: UTF8String; const CHAR_TABLE: UTF8String = '_-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; var len, i: Integer; begin len := 5 + Random(64); SetLength(Result, len); for i := 0 to len - 1 do PAnsiChar(Result)[i] := CHAR_TABLE[1 + Random(Length(CHAR_TABLE))]; end; procedure HppVariantsTest_AddEmpty(obj: THppVariantObject); var name: UTF8String; begin printTitle('test empty property'); name := generatePropName; Writeln('name: ', name); obj.Add(name); Writeln('obj.', name, '(', VarTypeAsText(VarType(obj[name])), ')'); Assert(VarIsEmpty(obj[name])); PrintJsonObjProp(obj, name); end; procedure HppVariantsTest_AddNull(obj: THppVariantObject); var name: UTF8String; value: TJSONSpecialValue; //TJsonSpecialType = (jstUndefined, jstNull, jstNotANumber, jstPositiveInfinity, jstNegativeInfinity); begin printTitle('test null property'); name := generatePropName; Writeln('name: ', name); value := TJSONSpecialValue(Random(Ord(High(TJSONSpecialValue)) + 1)); Writeln('value: ', JsonSpecialTypeNames[value]); obj.Add(name, value); Writeln('obj.', name, '(', VarTypeAsText(VarType(obj[name])), ')'); Assert(VarIsNull(obj[name])); PrintJsonObjProp(obj, name); end; procedure HppVariantsTest_AddBoolean(obj: THppVariantObject); var name: UTF8String; value: Boolean; begin printTitle('test boolean property'); name := generatePropName; Writeln('name: ', name); value := Random(2) = 1; Writeln('value: ', value); obj.Add(name, value); Writeln('obj.', name, '(', VarTypeAsText(VarType(obj[name])), '): ', obj[name]); Assert((VarType(obj[name]) = varBoolean) and (obj[name] = value)); PrintJsonObjProp(obj, name); end; procedure HppVariantsTest_AddInt8(obj: THppVariantObject); var name: UTF8String; value: Int8; begin printTitle('test int8 property'); name := generatePropName; Writeln('name: ', name); value := Random(High(Int8) * 2 + 2) - (High(Int8) + 1); Writeln('value: ', value); obj.Add(name, value); Writeln('obj.', name, '(', VarTypeAsText(VarType(obj[name])), '): ', obj[name]); Assert((VarType(obj[name]) = varShortInt) and (obj[name] = value)); PrintJsonObjProp(obj, name); end; procedure HppVariantsTest_AddUInt8(obj: THppVariantObject); var name: UTF8String; value: UInt8; begin printTitle('test uint8 property'); name := generatePropName; Writeln('name: ', name); value := Random(High(UInt8) + 1); Writeln('value: ', value); obj.Add(name, value); Writeln('obj.', name, '(', VarTypeAsText(VarType(obj[name])), '): ', obj[name]); Assert((VarType(obj[name]) = varByte) and (obj[name] = value)); PrintJsonObjProp(obj, name); end; const THppVariantObject_AddPropProcs: array [vdtEmpty..vdtUInt8] of procedure(obj: THppVariantObject) = (HppVariantsTest_AddEmpty, HppVariantsTest_AddNull, HppVariantsTest_AddBoolean, HppVariantsTest_AddInt8, HppVariantsTest_AddUInt8); procedure HppVariantsTest; const SLongPropName: RawByteString = 'LongPropName'; var obj2, obj, subobj: THppVariantObject; arr: THppVariantArray; i: Integer; v, v2, EmptyArray, EmptyObject, v3: Variant; begin v2 := ParseJSON(SAMPLE_JSON); //Clipboard.AsText := v2; EmptyArray := v2.EmptyArray; Writeln(EmptyArray); Writeln(EmptyArray._count); Writeln(EmptyArray._json); EmptyArray.Add('create and add'); printVariant('EmptyArray', EmptyArray); printVariant('v2.EmptyArray', v2.EmptyArray); v3 := EmptyArray; printVariant('v3', v3); EmptyObject := v2.EmptyObject; Writeln(EmptyObject); Writeln(EmptyObject._count); Writeln(EmptyObject._json); EmptyObject.Add('first', '007'); printVariant('EmptyObject', EmptyObject); printVariant('v2.EmptyObject', v2.EmptyObject); v3 := EmptyObject; printVariant('v3', v3); obj2 := ParseJSONObject(SAMPLE_JSON); //obj2.Clone.Free; obj2.Free; obj := THppVariantObject.Create(nil); encapsulate(obj, TVarData(v)); obj.Capacity := 2000000; for i := 1 to 1000 do THppVariantObject_AddPropProcs[TVariantDataType(Random(Ord(vdtInt16)))](obj); obj['NumberStr'] := '-52352352452355'; Writeln(obj['NumberStr']); Writeln(obj.GetNumber('NumberStr').ToString); obj.Add(PAnsiChar(SLongPropName), Length(SLongPropName), Int8(11)); Writeln(obj[SLongPropName]); obj.SetInt64(SLongPropName, High(Int64)); Writeln(obj[SLongPropName]); Assert(obj[SLongPropName]=High(Int64)); arr := obj.AddArray('persons'); subobj := arr.AddObject; subobj.Add('name', 'zzj'); subobj.Add('age', Int8(33)); subobj := arr.AddObject; subobj.Add('name', 'hyf'); subobj.Add('age', Int8(32)); Writeln(v.persons._count); Writeln(v.persons); Writeln(v.persons[1]); Writeln(obj.A['persons'].Count); Writeln(obj.A['persons'].O[1].GetString('name').ToUTF16String); obj.Remove('persons'); Writeln(obj.A['persons'].Count); //Writeln(obj.A['persons'].O[1].S['name']); for i := 1 to obj.Count div 2 do obj.Delete(Random(obj.Count)); //Clipboard.AsText := obj.ToString; Writeln(v._JSON); end; { TPerson } procedure TPerson.SetAge(const Value: Integer); begin FAge := Value; end; procedure TPerson.SetName(const Value: string); begin FName := Value; end; end.
///<summary>Queue anonymous procedure to a hidden window executing in a main thread. ///</summary> ///<author>Primoz Gabrijelcic</author> ///<remarks><para> /// (c) 2018 Primoz Gabrijelcic /// Free for personal and commercial use. No rights reserved. /// /// Author : Primoz Gabrijelcic /// Creation date : 2013-07-18 /// Last modification : 2018-01-09 /// Version : 2.02a ///</para><para> /// History: /// 2.02a: 2018-01-09 /// - If a thread wants to receive queued procedures, it has to call /// RegisterQueueTarget and UnregisterQueueTarget. /// 2.02: 2018-01-04 /// - Implemented Queue(TThread, TProc) and Queue(TThreadID, TProc) overloads which /// queue directly to a specified thread. /// 2.01: 2017-01-26 /// - After() calls with overlaping times can be nested. /// 2.0: 2016-01-29 /// - Queue can be used from a background TThread-based thread. /// In that case it will forward request to TThread.Queue. /// 1.01: 2014-08-26 /// - Implemented After function. /// 1.0: 2013-07-18 /// - Created. ///</para></remarks> unit GpQueueExec; interface uses System.SysUtils, System.Classes; procedure After(timeout_ms: integer; proc: TProc); procedure Queue(proc: TProc); overload; procedure Queue(thread: TThread; proc: TProc); overload; procedure Queue(threadID: TThreadID; proc: TProc); overload; procedure RegisterQueueTarget; procedure UnregisterQueueTarget; implementation uses Winapi.Windows, Winapi.Messages, Winapi.TLHelp32, System.Generics.Collections, DSiWin32, GpLists; type TQueueProc = class Proc: TProc; end; { TQueueProc } TQueueExec = class strict private type TTimerData = TPair<NativeUInt, TProc>; strict private FHThreads : TDictionary<TThreadID, HWND>; FTimerID : NativeUInt; FTimerData: TList<TTimerData>; strict protected procedure DeallocateDeadThreadWindows; function GetWindowForThreadID(threadID: TThreadID; autoCreate: boolean): HWND; procedure WndProc(var Message: TMessage); protected function FindTimer(timerID: NativeUInt): integer; public constructor Create; destructor Destroy; override; procedure After(timeout_ms: integer; proc: TProc); procedure Queue(proc: TProc); overload; procedure Queue(thread: TThread; proc: TProc); overload; inline; procedure Queue(threadID: TThreadID; proc: TProc); overload; procedure RegisterQueueTarget; procedure UnregisterQueueTarget; end; { TQueueExec } var GMsgExecuteProc: NativeUInt; { TQueueExec } constructor TQueueExec.Create; begin inherited Create; Assert(GetCurrentThreadID = MainThreadID); FTimerData := TList<TTimerData>.Create; FHThreads := TDictionary<TThreadID, HWND>.Create; FHThreads.Add(MainThreadID, DSiAllocateHwnd(WndProc)); end; { TQueueExec.Create } destructor TQueueExec.Destroy; var mainWindow: HWND; threadData: TPair<TThreadID, HWND>; timerData : TTimerData; begin mainWindow := GetWindowForThreadID(MainThreadID, false); for timerData in FTimerData do KillTimer(mainWindow, timerData.Key); FreeAndNil(FTimerData); for threadData in FHThreads do DSIDeallocateHwnd(threadData.Value); FreeAndNil(FHThreads); inherited; end; { TQueueExec.Destroy } procedure TQueueExec.After(timeout_ms: integer; proc: TProc); begin Assert(GetCurrentThreadID = MainThreadID, 'TQueueExec.After can only be used from the main thread'); Inc(FTimerID); FTimerData.Add(TTimerData.Create(FTimerID , proc)); SetTimer(GetWindowForThreadID(MainThreadID, false), FTimerID, timeout_ms, nil); end; { TQueueExec.After } procedure TQueueExec.DeallocateDeadThreadWindows; var hnd : THandle; procID : DWORD; removeList: TGpInt64List; te : TThreadEntry32; thHnd : THandle; threadList: TGpInt64List; begin if FHThreads.Count = 0 then Exit; thHnd := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if thHnd = INVALID_HANDLE_VALUE then Exit; procID := GetCurrentProcessId; try threadList := TGpInt64List.Create; try te.dwSize := SizeOf(te); if Thread32First(thHnd, te) then repeat if (te.dwSize >= (NativeUInt(@te.tpBasePri) - NativeUInt(@te.dwSize))) and (te.th32OwnerProcessID = procID) then threadList.Add(te.th32ThreadID); te.dwSize := SizeOf(te); until not Thread32Next(thHnd, te); threadList.Sort; removeList := TGpInt64List.Create; try for hnd in FHThreads.Keys do if not threadList.Contains(hnd) then removeList.Add(hnd); for hnd in removeList do begin DSiDeallocateHWnd(FHThreads[hnd]); FHThreads.Remove(hnd); end; finally FreeAndNil(removeList); end; finally FreeAndNil(threadList); end; finally CloseHandle(thHnd); end; end; { TQueueExec.DeallocateDeadThreadWindows } function TQueueExec.FindTimer(timerID: NativeUInt): integer; begin for Result := 0 to FTimerData.Count - 1 do if FTimerData[Result].Key = timerID then Exit; Result := -1; end; { TQueueExec.FindTimer } function TQueueExec.GetWindowForThreadID(threadID: TThreadID; autoCreate: boolean): HWND; begin TMonitor.Enter(FHThreads); try if not FHThreads.TryGetValue(threadID, Result) then begin if not autoCreate then raise Exception.CreateFmt('TQueueExec.GetWindowForThreadID: Receiver for thread %d is not created', [threadID]); DeallocateDeadThreadWindows; Result := DSiAllocateHWnd(WndProc); FHThreads.Add(threadID, Result); end; finally TMonitor.Exit(FHThreads); end; end; { TQueueExec.GetWindowForThreadID } procedure TQueueExec.Queue(proc: TProc); begin Queue(MainThreadID, proc); end; { TQueueExec.Queue } procedure TQueueExec.Queue(thread: TThread; proc: TProc); begin Queue(thread.ThreadID, proc); end; { TQueueExec.Queue } procedure TQueueExec.Queue(threadID: TThreadID; proc: TProc); var procObj: TQueueProc; begin procObj := TQueueProc.Create; procObj.Proc := proc; PostMessage(GetWindowForThreadID(threadID, false), GMsgExecuteProc, WParam(procObj), 0); end; { TQueueExec.Queue } procedure TQueueExec.RegisterQueueTarget; begin GetWindowForThreadID(GetCurrentThreadID, true); end; { TQueueExec.RegisterQueueTarget } procedure TQueueExec.UnregisterQueueTarget; var hWindow: HWND; thID : TThreadID; begin TMonitor.Enter(FHThreads); try thID := GetCurrentThreadID; if (thID <> MainThreadID) and FHThreads.TryGetValue(thID, hWindow) then begin DSiDeallocateHWnd(hWindow); FHThreads.Remove(thID); end; finally TMonitor.Exit(FHThreads); end; end; { TQueueExec.UnregisterQueueTarget } procedure TQueueExec.WndProc(var Message: TMessage); var idx : integer; procObj : TQueueProc; timerData: TTimerData; begin if Message.Msg = GMsgExecuteProc then begin procObj := TQueueProc(Message.WParam); if assigned(procObj) then begin procObj.Proc(); procObj.Free; end; end else if Message.Msg = WM_TIMER then begin idx := FindTimer(TWMTimer(Message).TimerID); if idx >= 0 then begin timerData := FTimerData[idx]; FTimerData.Delete(idx); KillTimer(GetWindowForThreadID(MainThreadID, false), timerData.Key); timerData.Value(); end; end else Message.Result := DefWindowProc(GetWindowForThreadID(GetCurrentThreadID, false), Message.Msg, Message.WParam, Message.LParam); end; { TQueueExec.WndProc } var FQueueExec: TQueueExec; procedure After(timeout_ms: integer; proc: TProc); begin FQueueExec.After(timeout_ms, proc); end; { After } procedure Queue(proc: TProc); begin FQueueExec.Queue(proc); end; { Queue } procedure Queue(thread: TThread; proc: TProc); begin FQueueExec.Queue(thread, proc); end; { Queue } procedure Queue(threadID: TThreadID; proc: TProc); begin FQueueExec.Queue(threadID, proc); end; { Queue } procedure RegisterQueueTarget; begin FQueueExec.RegisterQueueTarget; end; { RegisterQueueTarget } procedure UnregisterQueueTarget; begin FQueueExec.UnregisterQueueTarget; end; { UnregisterQueueTarget } initialization GMsgExecuteProc := RegisterWindowMessage('\Gp\QueueExec\DB2722C2-2B3E-4BED-B7BC-336FC76CE8FC\Execute'); FQueueExec := TQueueExec.Create; finalization FreeAndNil(FQueueExec); end.
program S18_A8_1; Var x : integer; Var y : integer; procedure math; Var a, b, add : integer; sub : integer; mul : integer; divi : real; begin a := 2; b := a+2; (*4*) add := a + b; write('a + b = '); writeln(add); sub := a - b; write('a - b = '); writeln(sub); mul := a * b; write('a * b = '); writeln(mul); divi := b div a; write('b / a = '); writeln(divi); end; procedure loop; Var i, c : integer; begin c := 0; for i := 1 to 5 do c := c + 5; write('c = '); writeln(c); end; function conditional(x : integer) : integer; Var d : integer; begin d := 3; if(x > d) then writeln('x is greater than d') else writeln('x is less than d'); conditional := d; end; begin x := 1; math; loop; y := conditional(x); write('conditional test value: '); writeln(y); write('x value: '); writeln(x); readln(x); writeln(x); end.
unit MailCtrls; interface uses Windows; type TMessage = packed record Msg: Cardinal; case Integer of 0: ( WParam: Longint; LParam: Longint; Result: Longint); 1: ( WParamLo: Word; WParamHi: Word; LParamLo: Word; LParamHi: Word; ResultLo: Word; ResultHi: Word); end; TWndProc = function(wnd: HWND; iMsg: UINT; wp: WPARAM; lp: LPARAM): Cardinal; stdcall; TCrbWinControl = class private FFont: HFONT; FHandle: HWND; FParent: HWND; FOldWndProc: Pointer; FCaption: string; FTop: Integer; FLeft: Integer; FWidth: Integer; FHeight: Integer; FFontHeight: Integer; FFontName: string; FEnabled: Boolean; function CreateFontHandle: HWND; procedure SetFontName(const Value: string); procedure SetFontSize(const Value: Integer); function GetFontSize: Integer; procedure WindowProc(var Message: TMessage); procedure SetEnabled(const Value: Boolean); protected function GetCaption: string; virtual; procedure SetCaption(const Value: string); virtual; procedure CreateWindow(ClassName: string; ExStyle: Cardinal; Style: Cardinal); procedure CreateWindowHandle; virtual; abstract; public constructor Create(Parent: HWND); virtual; destructor Destroy; override; property Handle: HWND read FHandle; procedure Show; property Caption: string read GetCaption write SetCaption; property Top: Integer read FTop write FTop; property Left: Integer read FLeft write FLeft; property Width: Integer read FWidth write FWidth; property Height: Integer read FHeight write FHeight; property FontSize: Integer read GetFontSize write SetFontSize; property FontName: string read FFontName write SetFontName; property Enabled: Boolean read FEnabled write SetEnabled; end; TCrbLabel = class(TCrbWinControl) public constructor Create(Parent: HWND); override; destructor Destroy; override; procedure CreateWindowHandle; override; end; TCrbEdit= class(TCrbWinControl) private FPasswordChar: Char; protected function GetCaption: string; override; public constructor Create(Parent: HWND); override; destructor Destroy; override; procedure CreateWindowHandle; override; property PasswordChar: Char read FPasswordChar write FPasswordChar; end; TCrbReadOnlyEdit = class (TCrbEdit) public procedure CreateWindowHandle; override; end; TCrbMemo = class(TCrbWinControl) public constructor Create(Parent: HWND); override; destructor Destroy; override; procedure CreateWindowHandle; override; end; TCrbButton = class(TCrbWinControl) public constructor Create(Parent: HWND); override; procedure CreateWindowHandle; override; end; TCrbCheckBox = class (TCrbWinControl) private FChecked: Boolean; function GetChecked: Boolean; procedure SetChecked(const Value: Boolean); public constructor Create(Parent: HWND); override; procedure CreateWindowHandle; override; property Checked: Boolean read GetChecked write SetChecked; end; implementation uses SysUtils, Messages; var ScreenLogPixels: Integer; // standard window procedure. Passes it to the CrbWinControl's // window proc function StdWndProc(Window: HWND; iMsg: UINT; WParam: Longint; LParam: Longint): Longint; stdcall; var CrbPointer: TCrbWinControl; Message: TMessage; begin CrbPointer := TCrbWinControl(GetWindowLong(Window, GWL_USERDATA)); Message.Msg := iMsg; Message.WParam := WParam; Message.LParam := LParam; CrbPointer.WindowProc(Message); Result := Message.Result; end; { TCrbWinControl } constructor TCrbWinControl.Create(Parent: HWND); begin inherited Create; FParent := Parent; FOldWndProc := nil; FHandle := 0; FFont := 0; FTop := 0; FLeft := 0; FWidth := 100; FHeight := 30; // Create a font FFontName := 'MS Sans Serif'; FontSize := 10; FEnabled := True; end; function TCrbWinControl.CreateFontHandle: HWND; var LogFont: TLogFont; begin FillChar(LogFont, SizeOf(LogFont), 0); with LogFont do begin lfHeight := FFontHeight; lfWidth := 0; { have font mapper choose } lfEscapement := 0; { only straight fonts } lfOrientation := 0; { no rotation } lfWeight := FW_NORMAL; lfItalic := 0; lfUnderline := 0; lfStrikeOut := 0; lfCharSet := 0; StrPCopy(lfFaceName, FFontName); lfQuality := DEFAULT_QUALITY; { Everything else as default } lfOutPrecision := OUT_DEFAULT_PRECIS; lfClipPrecision := CLIP_DEFAULT_PRECIS; lfPitchAndFamily := DEFAULT_PITCH; Result := CreateFontIndirect(LogFont); end end; procedure TCrbWinControl.CreateWindow(ClassName: string; ExStyle: Cardinal; Style: Cardinal); begin // call create window on it FHandle := CreateWindowEx(ExStyle, PChar(ClassName), PChar(FCaption), Style, FLeft, FTop, FWidth, FHeight, FParent, 0, hInstance, nil); // create the font handle, if needed if FFont = 0 then FFont := CreateFontHandle; // now apply the font to the window SendMessage(FHandle, WM_SETFONT, FFont, 0); // save a pointer to myself in my user_data section of the class SetWindowLong(FHandle, GWL_USERDATA, LongInt(Self)); // now subclass the window proc if Tab's are enabled if (Style and WS_TABSTOP) = WS_TABSTOP then FOldWndProc := Pointer(SetWindowLong(FHandle, GWL_WNDPROC, LongInt(@StdWndProc))); end; destructor TCrbWinControl.Destroy; begin if FFont <> 0 then DeleteObject(FFont); inherited Destroy; end; function TCrbWinControl.GetCaption: string; begin Result := FCaption; end; function TCrbWinControl.GetFontSize: Integer; begin Result := -MulDiv(FFontHeight, 72, ScreenLogPixels) end; procedure TCrbWinControl.SetCaption(const Value: string); begin FCaption := Value; if FHandle <> 0 then SetWindowText(FHandle, PChar(Value)); end; procedure TCrbWinControl.SetFontSize(const Value: Integer); begin FFontHeight := -MulDiv(Value, ScreenLogPixels, 72); if FFont <> 0 then DeleteObject(FFont); if FHandle <> 0 then begin FFont := CreateFontHandle; SendMessage(FHandle, WM_SETFONT, FFont, 0); end; end; procedure TCrbWinControl.SetFontName(const Value: string); begin FFontName := Value; if FFont <> 0 then DeleteObject(FFont); if FHandle <> 0 then begin FFont := CreateFontHandle; SendMessage(FHandle, WM_SETFONT, FFont, 0); end; end; procedure TCrbWinControl.Show; begin if FHandle = 0 then CreateWindowHandle; ShowWindow(FHandle, SW_SHOW); end; procedure TCrbWinControl.WindowProc(var Message: TMessage); procedure Default; begin with Message do Result := CallWindowProc(FOldWndProc, FHandle, Msg, wParam, lParam); end; begin if (Message.Msg = WM_CHAR) and (Message.WParam = VK_TAB) then SetFocus(GetNextDlgTabItem(FParent, FHandle, GetKeyState(VK_SHIFT) < 0)) else if (Message.Msg = WM_CHAR) and (Message.WParam = Vk_Escape) then // if visible, then hide if (GetWindowLong(FParent, GWL_STYLE) and WS_VISIBLE) = WS_VISIBLE then ShowWindow(FParent, SW_HIDE) else Default else if Message.Msg = WM_SETFOCUS then begin SendMessage(FHandle, EM_SETSEL, 0, -1); Default; end else Default; end; procedure TCrbWinControl.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin EnableWindow(FHandle, Value); FEnabled := Value; end; end; { TCrbLabel } constructor TCrbLabel.Create(Parent: HWND); begin inherited Create(Parent); FHeight := 16; end; procedure TCrbLabel.CreateWindowHandle; begin CreateWindow('STATIC', 0, WS_CHILD or WS_VISIBLE); end; destructor TCrbLabel.Destroy; begin inherited Destroy; end; { TCrbEdit } constructor TCrbEdit.Create(Parent: HWND); begin inherited Create(Parent); FPasswordChar := #0; FHeight := 21; end; procedure TCrbEdit.CreateWindowHandle; const Passwords: array[Boolean] of DWORD = (0, ES_PASSWORD); begin CreateWindow('EDIT', WS_EX_CLIENTEDGE , WS_CHILD or WS_VISIBLE or ES_AUTOHSCROLL or ES_AUTOVSCROLL or Passwords[FPasswordChar <> #0] or WS_TABSTOP); end; destructor TCrbEdit.Destroy; begin inherited Destroy; end; procedure InitScreenLogPixels; var DC: HDC; begin DC := GetDC(0); ScreenLogPixels := GetDeviceCaps(DC, LOGPIXELSY); ReleaseDC(0,DC); end; function TCrbEdit.GetCaption: string; const BufferSize = 1024; var Buffer: PChar; begin if Handle = 0 then Result := FCaption else begin Buffer := AllocMem(BufferSize); try GetWindowText(FHandle, Buffer, BufferSize); Result := Buffer; finally FreeMem(Buffer, BufferSize); end; end; end; { TCrbMemo } constructor TCrbMemo.Create(Parent: HWND); begin inherited Create(Parent); FHeight := 200; end; procedure TCrbMemo.CreateWindowHandle; begin CreateWindow('EDIT', WS_EX_CLIENTEDGE, WS_CHILD or WS_VISIBLE or ES_AUTOVSCROLL or ES_AUTOHSCROLL or WS_VSCROLL or ES_MULTILINE or ES_READONLY); end; destructor TCrbMemo.Destroy; begin inherited Destroy; end; { TCrbButton } constructor TCrbButton.Create(Parent: HWND); begin inherited Create(Parent); FWidth := 75; FHeight := 25; end; procedure TCrbButton.CreateWindowHandle; begin CreateWindow('BUTTON', WS_EX_CLIENTEDGE, WS_CHILD or WS_VISIBLE or BS_PUSHBUTTON or WS_TABSTOP); end; { TCrbCheckBox } constructor TCrbCheckBox.Create(Parent: HWND); begin inherited Create(Parent); FChecked := False; end; procedure TCrbCheckBox.CreateWindowHandle; begin CreateWindow('BUTTON', 0, WS_CHILD or WS_VISIBLE or BS_CHECKBOX or WS_TABSTOP or BS_AUTOCHECKBOX ); end; function TCrbCheckBox.GetChecked: Boolean; begin Result := (BST_CHECKED = SendMessage(FHandle, BM_GETCHECK, 0, 0)); end; procedure TCrbCheckBox.SetChecked(const Value: Boolean); const CheckedState: array[Boolean] of Cardinal = (BST_UNCHECKED, BST_CHECKED); begin if Value <> FChecked then begin FChecked := Value; SendMessage(FHandle, BM_SETCHECK, CheckedState[Value], 0); end; end; { TCrbReadOnlyEdit } procedure TCrbReadOnlyEdit.CreateWindowHandle; begin CreateWindow('EDIT', WS_EX_CLIENTEDGE , WS_CHILD or WS_VISIBLE or ES_AUTOHSCROLL or ES_AUTOVSCROLL or ES_READONLY ); end; initialization InitScreenLogPixels; end.
unit win.time; interface uses Windows; implementation //procedure GetSystemTime(var lpSystemTime: TSystemTime); stdcall; //procedure GetSystemTimeAsFileTime(var lpSystemTimeAsFileTime: TFileTime); stdcall; //function SetSystemTime(const lpSystemTime: TSystemTime): BOOL; stdcall; //procedure GetLocalTime(var lpSystemTime: TSystemTime); stdcall; //function SetLocalTime(const lpSystemTime: TSystemTime): BOOL; stdcall; //function SystemTimeToTzSpecificLocalTime(lpTimeZoneInformation: PTimeZoneInformation; // var lpUniversalTime, lpLocalTime: TSystemTime): BOOL; stdcall; //function GetTimeZoneInformation(var lpTimeZoneInformation: TTimeZoneInformation): DWORD; stdcall; //function SetTimeZoneInformation(const lpTimeZoneInformation: TTimeZoneInformation): BOOL; stdcall; // //function SystemTimeToFileTime(const lpSystemTime: TSystemTime; var lpFileTime: TFileTime): BOOL; stdcall; //function FileTimeToLocalFileTime(const lpFileTime: TFileTime; var lpLocalFileTime: TFileTime): BOOL; stdcall; //function LocalFileTimeToFileTime(const lpLocalFileTime: TFileTime; var lpFileTime: TFileTime): BOOL; stdcall; //function FileTimeToSystemTime(const lpFileTime: TFileTime; var lpSystemTime: TSystemTime): BOOL; stdcall; //function CompareFileTime(const lpFileTime1, lpFileTime2: TFileTime): Longint; stdcall; //function FileTimeToDosDateTime(const lpFileTime: TFileTime; // var lpFatDate, lpFatTime: Word): BOOL; stdcall; //function DosDateTimeToFileTime(wFatDate, wFatTime: Word; var lpFileTime: TFileTime): BOOL; stdcall; //function GetTickCount: DWORD; stdcall; //function SetSystemTimeAdjustment(dwTimeAdjustment: DWORD; bTimeAdjustmentDisabled: BOOL): BOOL; stdcall; //function GetSystemTimeAdjustment(var lpTimeAdjustment, lpTimeIncrement: DWORD; // var lpTimeAdjustmentDisabled: BOOL): BOOL; stdcall; end.
unit oGlobal; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TChannelIndex = (ciLeft, ciRight); TPlayRecordMode = (prmNone, prmPlay, prmRecord); TInputMode = (imRecorder, imPlayer, imWaveGenerator); TWaveForm = (wfSine, wfTri, wfRect); TChannelData = packed array[TChannelIndex] of SmallInt; TChannelDataArray = array of TChannelData; TWaveDataArray = TChannelDataArray; TFFTDataArray = TChannelDataArray; TSensitivityParams = record ChannelMax: Array[TChannelIndex] of Double; ChannelOn: Array[TChannelIndex] of Boolean; ChannelsLinked: Boolean; end; const WAVE_MAX = 32767; WAVE_MIN = -32768; NUM_SAMPLES: array[0..6] of Integer = (256, 512, 1024, 2048, 4096, 8192, 16384); SAMPLE_RATES: array[0..3] of Integer = (44100, 48000, 96000, 192000); FREQUENCIES: array[0..3] of Integer = (100, 1000, 10000, 100000); MS_PER_DIV: array[0..8] of Double = (0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0); SENSITIVITIES: array[0..6] of Double = (1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0); var SensitivityParams: TSensitivityParams = ( ChannelMax: (100.0, 100.0); ChannelOn: (true, true); ChannelsLinked: true ); NoDamageWarning_Mic: Boolean = false; NoDamageWarning_Out: Boolean = false; ShowLinesAndSymbols: Boolean = false; LogFrequencyAxis: Boolean = true; SpectrumDB: Boolean = false; implementation end.
unit aStar; {$mode objfpc}{$H+} interface uses Classes, SysUtils,math,fgl,core_listofrecords; type TQueue = specialize TFPGList<coord_t>; node = integer; pnode = ^node; astar_t = record grid:pchar; bounds:coord_t ; start:node ; goal:node ; open:TQueue; closed:pchar; gScores:pdouble; cameFrom:pnode; solutionLength:pinteger; end; { Run A* pathfinding over uniform-cost 2d grids using jump point search. grid: 0 if obstructed, non-0 if non-obstructed (the value is ignored beyond that). solLength: out-parameter, will contain the solution length boundX: width of the grid boundY: height of the grid start: index of the starting node in the grid end: index of the ending node in the grid return value: Array of node indexes making up the solution, of length solLength, in reverse order } function astar_compute(const grid:pChar;solLength:pInteger;boundX, boundY, start, eend:integer):pInteger; function astar_unopt_compute (const grid:pChar;solLength:pInteger;boundX,boundY, start,eend:integer):pInteger; { Compute cell indexes from cell coordinates and the grid width } function astar_getIndexByWidth (width, x, y:integer):integer; { Compute coordinates from a cell index and the grid width } procedure astar_getCoordByWidth ( width, node:integer;x,y:pInteger); implementation // Distance metrics, you might want to change these to match your game mechanics // Chebyshev distance metric for distance estimation by default function estimateDistance (start, eend:coord_t):double; begin result:=max (abs (start.x - eend.x), abs (start.y - eend.y)); end; // Since we only work on uniform-cost maps, this function only needs // to see the coordinates, not the map itself. // Euclidean geometry by default. // Note that since we jump over points, we actually have to compute // the entire distance - despite the uniform cost we can't just collapse // all costs to 1 function preciseDistance(start, eend:coord_t ):double; begin if (start.x - eend.x <> 0) and( start.y - eend.y <> 0) then result:= sqrt (power(start.x - eend.x, 2) + power(start.y - eend.y, 2)) else result:= abs (start.x - eend.x) + abs (start.y - eend.y); end; // Below this point, not a lot that there should be much need to change! // The order of directions is: // N, NE, E, SE, S, SW, W, NW direction:byte; const NO_DIRECTION = 8 typedef unsigned char directionset; // return and remove a direction from the set // returns NO_DIRECTION if the set was empty static direction nextDirectionInSet (directionset *dirs) { for (int i = 0; i < 8; i++) { char bit = 1 << i; if (*dirs & bit) { *dirs ^= bit; return i; } } return NO_DIRECTION; } static directionset addDirectionToSet (directionset dirs, direction dir) { return dirs | 1 << dir; } /* Coordinates are represented either as pairs of an x-coordinate and y-coordinate, or map indexes, as appropriate. getIndex and getCoord convert between the representations. */ static int getIndex (coord_t bounds, coord_t c) { return c.x + c.y * bounds.x; } int astar_getIndexByWidth (int width, int x, int y) { return x + y * width; } static coord_t getCoord (coord_t bounds, int c) { coord_t rv = { c % bounds.x, c / bounds.x }; return rv; } void astar_getCoordByWidth (int width, int node, int *x, int *y) { *x = node % width; *y = node / width; } // is this coordinate contained within the map bounds? static int contained (coord_t bounds, coord_t c) { return c.x >= 0 && c.y >= 0 && c.x < bounds.x && c.y < bounds.y; } // is this coordinate within the map bounds, and also walkable? static int isEnterable (astar_t *astar, coord_t coord) { node node = getIndex (astar->bounds, coord); return contained (astar->bounds, coord) && astar->grid[node]; } static int directionIsDiagonal (direction dir) { return (dir % 2) != 0; } // the coordinate one tile in the given direction static coord_t adjustInDirection (coord_t c, int dir) { // we want to implement "rotation" - that is, for instance, we can // subtract 2 from the direction "north" and get "east" // C's modulo operator doesn't quite behave the right way to do this, // but for our purposes this kluge should be good enough switch ((dir + 65536) % 8) { case 0: return (coord_t) {c.x, c.y - 1}; case 1: return (coord_t) {c.x + 1, c.y - 1}; case 2: return (coord_t) {c.x + 1, c.y }; case 3: return (coord_t) {c.x + 1, c.y + 1}; case 4: return (coord_t) {c.x, c.y + 1}; case 5: return (coord_t) {c.x - 1, c.y + 1}; case 6: return (coord_t) {c.x - 1, c.y}; case 7: return (coord_t) {c.x - 1, c.y - 1}; } return (coord_t) { -1, -1 }; } // logical implication operator static int implies (int a, int b) { return a ? b : 1; } /* Harabor's explanation of exactly how to determine when a cell has forced neighbours is a bit unclear IMO, but this is the best explanation I could figure out. I won't go through everything in the paper, just the extra insights above what I thought was immediately understandable that it took to actually implement this function. First, to introduce the problem, we're looking at the immedate neighbours of a cell on the grid, considering what tile we arrived from. ... This is the basic situation we're looking at. Supposing the top left -X. period is cell (0,0), we're coming in to cell (1, 1) from (0, 1). ... ... The other basic case, the diagonal case. All other cases are obviously .X. derivable from these two cases by symmetry. /.. The question is: Given that some tiles might have walls, *how many tiles are there that we can reach better by going through the center tile than any other way?* (for the horizontal case it's ok to only be able to reach them as well some other as through the center tile too) In case there are no obstructions, the answers are simple: In the horizontal or vertical case, the cell directly ahead; in the diagonal case, the three cells ahead. The paper is pretty abstract about what happens when there *are* obstructions, but fortunately the abstraction seems to collapse into some fairly simple practical cases: 123 Position 4 is a natural neighbour (according to the paper's terminology) -X4 so we don't need to count it. Positions 1, 2, 5 and 6 are accessible 567 without going through the center tile. This leaves positions 3 and 7 to be looked at. Considering position 3 (everything here also follows for 7 by symmetry): If 3 is obstructed, then it doesn't matter what's in position in 2. If 3 is free and 2 is obstructed, 3 is a forced neighbour. If 3 is free and 2 is free, 3 is pruned (not a forced neighbour) i.e. logically, 3 is not a forced neighbour iff (3 is obstructed) implies (2 is obstructed). Similar reasoning applies for the diagonal case, except with bigger angles. */ /* static int hasForcedNeighbours (astar_t *astar, coord_t coord, int dir) { #define ENTERABLE(n) isEnterable (astar, \ adjustInDirection (coord, dir + (n))) if (directionIsDiagonal (dir)) return !implies (ENTERABLE (-2), ENTERABLE (-3)) || !implies (ENTERABLE (2), ENTERABLE (3)); else return !implies (ENTERABLE (-1), ENTERABLE (-2)) || !implies (ENTERABLE (1), ENTERABLE (2)); #undef ENTERABLE } */ static directionset forcedNeighbours (astar_t *astar, coord_t coord, direction dir) { if (dir == NO_DIRECTION) return 0; directionset dirs = 0; #define ENTERABLE(n) isEnterable (astar, \ adjustInDirection (coord, (dir + (n)) % 8)) if (directionIsDiagonal (dir)) { if (!implies (ENTERABLE (6), ENTERABLE (5))) dirs = addDirectionToSet (dirs, (dir + 6) % 8); if (!implies (ENTERABLE (2), ENTERABLE (3))) dirs = addDirectionToSet (dirs, (dir + 2) % 8); } else { if (!implies (ENTERABLE (7), ENTERABLE (6))) dirs = addDirectionToSet (dirs, (dir + 7) % 8); if (!implies (ENTERABLE (1), ENTERABLE (2))) dirs = addDirectionToSet (dirs, (dir + 1) % 8); } #undef ENTERABLE return dirs; } static directionset naturalNeighbours (direction dir) { if (dir == NO_DIRECTION) return 255; directionset dirs = 0; dirs = addDirectionToSet (dirs, dir); if (directionIsDiagonal (dir)) { dirs = addDirectionToSet (dirs, (dir + 1) % 8); dirs = addDirectionToSet (dirs, (dir + 7) % 8); } return dirs; } static void addToOpenSet (astar_t *astar, int node, int nodeFrom) { coord_t nodeCoord = getCoord (astar->bounds, node); coord_t nodeFromCoord = getCoord (astar->bounds, nodeFrom); if (!exists (astar->open, node)) { astar->cameFrom[node] = nodeFrom; astar->gScores[node] = astar->gScores[nodeFrom] + preciseDistance (nodeFromCoord, nodeCoord); insert (astar->open, node, astar->gScores[node] + estimateDistance (nodeCoord, getCoord (astar->bounds, astar->goal))); } else if (astar->gScores[node] > astar->gScores[nodeFrom] + preciseDistance (nodeFromCoord, nodeCoord)) { astar->cameFrom[node] = nodeFrom; int oldGScore = astar->gScores[node]; astar->gScores[node] = astar->gScores[nodeFrom] + preciseDistance (nodeFromCoord, nodeCoord); double newPri = priorityOf (astar->open, node) - oldGScore + astar->gScores[node]; changePriority (astar->open, node, newPri); } } // directly translated from "algorithm 2" in the paper static int jump (astar_t *astar, direction dir, int start) { coord_t coord = adjustInDirection (getCoord (astar->bounds, start), dir); int node = getIndex (astar->bounds, coord); if (!isEnterable (astar, coord)) return -1; if (node == astar->goal || forcedNeighbours (astar, coord, dir)) { return node; } if (directionIsDiagonal (dir)) { int next = jump (astar, (dir + 7) % 8, node); if (next >= 0) return node; next = jump (astar, (dir + 1) % 8, node); if (next >= 0) return node; } return jump (astar, dir, node); } // path interpolation between jump points in here static int nextNodeInSolution (astar_t *astar, int *target, int node) { coord_t c = getCoord (astar->bounds, node); coord_t cTarget = getCoord (astar->bounds, *target); if (c.x < cTarget.x) c.x++; else if (c.x > cTarget.x) c.x--; if (c.y < cTarget.y) c.y++; else if (c.y > cTarget.y) c.y--; node = getIndex (astar->bounds, c); if (node == *target) *target = astar->cameFrom[*target]; return node; } // a bit more complex than the usual A* solution-recording method, // due to the need to interpolate path chunks static int *recordSolution (astar_t *astar) { int rvLen = 1; *astar->solutionLength = 0; int target = astar->goal; int *rv = malloc (rvLen * sizeof (int)); int i = astar->goal; for (;;) { i = nextNodeInSolution (astar, &target, i); rv[*astar->solutionLength] = i; (*astar->solutionLength)++; if (*astar->solutionLength >= rvLen) { rvLen *= 2; rv = realloc (rv, rvLen * sizeof (int)); if (!rv) return NULL; } if (i == astar->start) break; } (*astar->solutionLength)--; // don't include the starting tile return rv; } static direction directionOfMove (coord_t to, coord_t from) { if (from.x == to.x) { if (from.y == to.y) return -1; else if (from.y < to.y) return 4; else // from.y > to.y return 0; } else if (from.x < to.x) { if (from.y == to.y) return 2; else if (from.y < to.y) return 3; else // from.y > to.y return 1; } else { // from.x > to.x if (from.y == to.y) return 6; else if (from.y < to.y) return 5; else // from.y > to.y return 7; } } static direction directionWeCameFrom (astar_t *astar, int node, int nodeFrom) { if (nodeFrom == -1) return NO_DIRECTION; return directionOfMove (getCoord (astar->bounds, node), getCoord (astar->bounds, nodeFrom)); } int *astar_compute (const char *grid, int *solLength, int boundX, int boundY, int start, int end) { *solLength = -1; astar_t astar; coord_t bounds = {boundX, boundY}; int size = bounds.x * bounds.y; if (start >= size || start < 0 || end >= size || end < 0) return NULL; coord_t startCoord = getCoord (bounds, start); coord_t endCoord = getCoord (bounds, end); if (!contained (bounds, startCoord) || !contained (bounds, endCoord)) return NULL; queue *open = createQueue(); char closed [size]; double gScores [size]; int cameFrom [size]; astar.solutionLength = solLength; astar.bounds = bounds; astar.start = start; astar.goal = end; astar.grid = grid; astar.open = open; astar.closed = closed; astar.gScores = gScores; astar.cameFrom = cameFrom; memset (closed, 0, sizeof(closed)); gScores[start] = 0; cameFrom[start] = -1; insert (open, start, estimateDistance (startCoord, endCoord)); while (open->size) { int node = findMin (open)->value; coord_t nodeCoord = getCoord (bounds, node); if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) { freeQueue (open); return recordSolution (&astar); } deleteMin (open); closed[node] = 1; direction from = directionWeCameFrom (&astar, node, cameFrom[node]); directionset dirs = forcedNeighbours (&astar, nodeCoord, from) | naturalNeighbours (from); for (int dir = nextDirectionInSet (&dirs); dir != NO_DIRECTION; dir = nextDirectionInSet (&dirs)) { int newNode = jump (&astar, dir, node); coord_t newCoord = getCoord (bounds, newNode); // this'll also bail out if jump() returned -1 if (!contained (bounds, newCoord)) continue; if (closed[newNode]) continue; addToOpenSet (&astar, newNode, node); } } freeQueue (open); return NULL; } int *astar_unopt_compute (const char *grid, int *solLength, int boundX, int boundY, int start, int end) { astar_t astar; coord_t bounds = {boundX, boundY}; int size = bounds.x * bounds.y; if (start >= size || start < 0 || end >= size || end < 0) return NULL; coord_t startCoord = getCoord (bounds, start); coord_t endCoord = getCoord (bounds, end); if (!contained (bounds, startCoord) || !contained (bounds, endCoord)) return NULL; queue *open = createQueue(); char closed [size]; double gScores [size]; int cameFrom [size]; astar.solutionLength = solLength; *astar.solutionLength = -1; astar.bounds = bounds; astar.start = start; astar.goal = end; astar.grid = grid; astar.open = open; astar.closed = closed; astar.gScores = gScores; astar.cameFrom = cameFrom; memset (closed, 0, sizeof(closed)); gScores[start] = 0; cameFrom[start] = -1; insert (open, start, estimateDistance (startCoord, endCoord)); while (open->size) { int node = findMin (open)->value; coord_t nodeCoord = getCoord (bounds, node); if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) { freeQueue (open); return recordSolution (&astar); } deleteMin (open); closed[node] = 1; for (int dir = 0; dir < 8; dir++) { coord_t newCoord = adjustInDirection (nodeCoord, dir); int newNode = getIndex (bounds, newCoord); if (!contained (bounds, newCoord) || !grid[newNode]) continue; if (closed[newNode]) continue; addToOpenSet (&astar, newNode, node); } } freeQueue (open); return NULL; } end.
unit uSynEditExtended; { Catarinka TCatSynEditExtended - Enhanced SynEdit Copyright (c) 2013-2017 Felipe Daragon License: 3-clause BSD license See https://github.com/felipedaragon/sandcat/ for details. } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} Winapi.Messages, System.Classes, System.Types, System.SysUtils, Winapi.Windows, Vcl.Menus, Vcl.ActnList, Vcl.Dialogs, {$ELSE} Messages, Classes, Types, SysUtils, Windows, Menus, ActnList, Dialogs, {$ENDIF} CatSynEdit; type TCatSynEditExtended = class(TCatSynEdit) private fFilename: string; fSearch: TMenuItem; fSearchNewTab:TMenuItem; procedure MenuOnPopup(Sender: TObject); procedure MenuSaveAsClick(Sender: TObject); procedure MenuSearchClick(Sender: TObject); procedure MenuSearchNewTabClick(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Filename: string read fFilename write fFilename; end; implementation uses uMain, CatFiles; procedure TCatSynEditExtended.MenuSearchClick(Sender: TObject); begin if self.SelText <> emptystr then tabmanager.activetab.DoSearch(self.SelText); end; procedure TCatSynEditExtended.MenuSearchNewTabClick(Sender: TObject); begin if self.SelText <> emptystr then tabmanager.NewTab_Search(self.SelText); end; procedure TCatSynEditExtended.MenuSaveAsClick(Sender: TObject); var sd: TSaveDialog; begin sd := TSaveDialog.Create(self); sd.DefaultExt := extractfileext(fFilename); sd.Filename := fFilename; sd.Filter := 'All Files|*.*'; sd.Options := sd.Options + [ofoverwriteprompt]; if sd.execute then SL_SaveToFile(self.lines, sd.Filename); sd.free; end; procedure TCatSynEditExtended.MenuOnPopup(Sender: TObject); begin fSearch.Enabled := (SelText <> emptystr); fSearchNewTab.Enabled := fSearch.Enabled; end; constructor TCatSynEditExtended.Create(AOwner: TComponent); var mi: TMenuItem; begin inherited; PopupMenu.OnPopup := MenuOnPopup; // preview text popup menu items mi := TMenuItem.Create(PopupMenu); mi.Caption := '-'; PopupMenu.Items.Add(mi); // search fSearch := TMenuItem.Create(PopupMenu); fSearch.Caption := 'Search'; fSearch.OnClick := MenuSearchClick; PopupMenu.Items.Add(fSearch); fSearchNewTab := TMenuItem.Create(PopupMenu); fSearchNewTab.Caption := 'Search in New Tab'; fSearchNewTab.OnClick := MenuSearchNewTabClick; PopupMenu.Items.Add(fSearchNewTab); // save as mi := TMenuItem.Create(PopupMenu); mi.Caption := 'Save As...'; mi.OnClick := MenuSaveAsClick; PopupMenu.Items.Add(mi); end; destructor TCatSynEditExtended.Destroy; begin // No need to free popup items here because Destroy of TCatSynEdit's popupmenu // will do it inherited; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, Vcl.StdCtrls, IdContext, IdCustomHTTPServer, IdHTTPServer, IdUDPBase, IdUDPServer, IdTrivialFTPServer, System.Classes; type TForm1 = class(TForm) Memo1: TMemo; efPath: TEdit; IdHTTPServer1: TIdHTTPServer; procedure IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure IdHTTPServer1Connect(AContext: TIdContext); procedure IdHTTPServer1Disconnect(AContext: TIdContext); private fMemStream: TMemoryStream; public { Public declarations } end; var Form1: TForm1; implementation uses System.IOUtils; {$R *.dfm} procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var filename: string; fullPath: string; memStream: TMemoryStream; begin Memo1.Lines.Add('URL: ' + ARequestInfo.URI); filename:=ARequestInfo.URI.Replace('/', ''); Memo1.Lines.Add('Filename: ' + filename); fullPath:= TPath.Combine(efPath.Text, filename); if not FileExists(fullPath) then begin AResponseInfo.ResponseText:=fullPath + ' does not exist'; AResponseInfo.ResponseNo:=404; Exit; end; try fMemStream.LoadFromFile(fullPath); AResponseInfo.ContentStream := fMemStream; AResponseInfo.ContentType:='text'; AResponseInfo.ResponseNo:=200; except end; end; procedure TForm1.IdHTTPServer1Connect(AContext: TIdContext); begin Memo1.Lines.Add('Server Connected'); fMemStream:=TMemoryStream.Create; end; procedure TForm1.IdHTTPServer1Disconnect(AContext: TIdContext); begin Memo1.Lines.Add('Server Disconnected'); fMemStream.Free; end; end.
unit qCDKtcpClasses; interface uses Windows,SysUtils,IdTCPClient,IdTCPServer, uCalcTypes,qCDKclasses; type TTCPClientSocket=class(TCommunicationSocket) protected fsServer:AnsiString; flwPort:longword; fTCPClient:TIdTCPClient; ct:TCommTimeouts; protected function DoGetUInt(const ndx:integer):UInt64; override; // все беззнаковые целые свойства function DoCreateHandle:THandle; override; // наследники здесь должны инициализировать данные объекта procedure DoDestroyHandle; override; // наследники здесь должны освобождать созданные ресурсы public class function GetClassCaption:AString; override; // описание класса class function GetClassDescription:AString; override; // подробное описание класса constructor Create(sCommName:AnsiString; bOverlapped:boolean=false); override; class function GetObjectByName(sName:AnsiString):TCommunicationObject; override; // поиск объекта по имени - нам синглтоны не нужны procedure SetDefault; override; // отменяет все ожидающие завершения операции над коммуникационным ресурсом, запущенные вызывающим потоком программы function _CancelIo:boolean; override; // очищает все буферы и форсирует запись всех буферизированных данных в выбранный коммуникационный ресурс function _FlushFileBuffers:boolean; override; // возвращает текущую маску событий коммуникационного ресурса function _GetCommMask(var lwEventMask:longword):boolean; override; // возвращает настройки таймаутов для всех операций чтения и записи для выбранного коммуникационного ресурса function _GetCommTimeouts(var rCommTimeouts:TCommTimeouts):boolean; override; // всегда вызывается в асинхронном режиме и производит проверку выполнения асинхронной операции function _GetOverlappedResult(const prOverlapped:POverlapped; var lwNumberOfBytesTransferred:longword; const bWait:boolean):boolean; override; // может очистить буфер приёма, буфер передачи function _PurgeComm(const lwPurgeAction:longword):boolean; override; // позволяет прочитать заданное количество символов (байт) из выбранного ресурса function _ReadFile(var Buffer; const lwNumberOfBytesToRead:longword; var lwNumberOfBytesRead:longword; const prOverlapped:POverlapped=nil):boolean; override; // устанавливает маску событий, которые будут отслеживаться для определённого коммуникационного ресурса; // отслеживание событий будет вестись только после вызова функции WaitCommEvent function _SetCommMask(const lwEventMask:longword):boolean; override; // устанавливает таймауты для всех операций чтения и записи для определённого коммуникационного ресурса function _SetCommTimeouts(const rCommTimeouts:TCommTimeouts):boolean; override; // устанавливает размеры буферов приёма и передачи для коммуникационного ресурса function _SetupComm(const lwInputQueueSize,lwOutputQueueSize:longword):boolean; override; // при успешном выполнении возвращает в параметре lwEventMask набор событий, которые произошли в коммуникационном ресурсе function _WaitCommEvent(var lwEventMask:longword; const prOverlapped:POverlapped=nil):boolean; override; // позволяет записать выбранное количество байт в коммуникационный ресурс function _WriteFile(const Buffer; const lwNumberOfBytesToWrite:longword; var lwNumberOfBytesWritten:longword; prOverlapped:POverlapped=nil):boolean; override; end; TTCPClientConnection=class(TCommunicationConnection) protected function GetTCPClientSocket:TTCPClientSocket; virtual; public class function GetClassCaption:AString; override; // описание класса class function GetClassDescription:AString; override; // подробное описание класса constructor Create; override; procedure SetDefault; override; property TCPClientSocket:TTCPClientSocket read GetTCPClientSocket; end; TTCPServerSocket=class(TCommunicationSocket) protected flwPort:longword; fTCPServer:TIdTCPServer; ct:TCommTimeouts; protected function DoGetUInt(const ndx:integer):UInt64; override; // все беззнаковые целые свойства function DoCreateHandle:THandle; override; // наследники здесь должны инициализировать данные объекта procedure DoDestroyHandle; override; // наследники здесь должны освобождать созданные ресурсы public constructor Create(sCommName:AnsiString; bOverlapped:boolean=false); override; class function GetObjectByName(sName:AnsiString):TCommunicationObject; override; // поиск объекта по имени - нам синглтоны не нужны procedure SetDefault; override; // отменяет все ожидающие завершения операции над коммуникационным ресурсом, запущенные вызывающим потоком программы function _CancelIo:boolean; override; // очищает все буферы и форсирует запись всех буферизированных данных в выбранный коммуникационный ресурс function _FlushFileBuffers:boolean; override; // возвращает текущую маску событий коммуникационного ресурса function _GetCommMask(var lwEventMask:longword):boolean; override; // возвращает настройки таймаутов для всех операций чтения и записи для выбранного коммуникационного ресурса function _GetCommTimeouts(var rCommTimeouts:TCommTimeouts):boolean; override; // всегда вызывается в асинхронном режиме и производит проверку выполнения асинхронной операции function _GetOverlappedResult(const prOverlapped:POverlapped; var lwNumberOfBytesTransferred:longword; const bWait:boolean):boolean; override; // может очистить буфер приёма, буфер передачи function _PurgeComm(const lwPurgeAction:longword):boolean; override; // позволяет прочитать заданное количество символов (байт) из выбранного ресурса function _ReadFile(var Buffer; const lwNumberOfBytesToRead:longword; var lwNumberOfBytesRead:longword; const prOverlapped:POverlapped=nil):boolean; override; // устанавливает маску событий, которые будут отслеживаться для определённого коммуникационного ресурса; // отслеживание событий будет вестись только после вызова функции WaitCommEvent function _SetCommMask(const lwEventMask:longword):boolean; override; // устанавливает таймауты для всех операций чтения и записи для определённого коммуникационного ресурса function _SetCommTimeouts(const rCommTimeouts:TCommTimeouts):boolean; override; // устанавливает размеры буферов приёма и передачи для коммуникационного ресурса function _SetupComm(const lwInputQueueSize,lwOutputQueueSize:longword):boolean; override; // при успешном выполнении возвращает в параметре lwEventMask набор событий, которые произошли в коммуникационном ресурсе function _WaitCommEvent(var lwEventMask:longword; const prOverlapped:POverlapped=nil):boolean; override; // позволяет записать выбранное количество байт в коммуникационный ресурс function _WriteFile(const Buffer; const lwNumberOfBytesToWrite:longword; var lwNumberOfBytesWritten:longword; prOverlapped:POverlapped=nil):boolean; override; end; TTCPServerConnection=class(TCommunicationConnection) protected function GetTCPServerSocket:TTCPServerSocket; virtual; public constructor Create; override; property TCPClientSocket:TTCPServerSocket read GetTCPServerSocket; end; implementation uses StrUtils,IdTCPConnection,IdIOHandlerSocket; var gfs:TFormatSettings; {$BOOLEVAL OFF} {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} const excOverlappedUnavailable='асинхронный сокет невозможен'; excNoTCPPort='не задан TCP-порт'; excInvalidTCPPort='неправильный TCP-порт <%s>'; type TLIdTCPClient=class(TIdTCPClient); procedure RegisterClasses; begin CommunicationSpace.RegisterSocketClass(TTCPClientSocket); CommunicationSpace.RegisterConnectionClass(TTCPClientConnection); end; { TTCPClientSocket } constructor TTCPClientSocket.Create(sCommName:AnsiString; bOverlapped:boolean); var ndx:integer; i64:Int64; sPort:AnsiString; begin if bOverlapped then raise EqCDKexception.Create(ClassName+': '+excOverlappedUnavailable); sCommName:=AnsiUpperCase(sCommName); ndx:=Pos(':',AnsiReverseString(sCommName)); if ndx=0then raise EqCDKexception.Create(ClassName+': '+excNoTCPPort); // без TCP-порта нельзя создать клиента fsServer:=sCommName; SetLength(fsServer,Length(sCommName)-ndx); sPort:=AnsiRightStr(sCommName,ndx-1); if TryStrToInt64(sPort,i64)and(i64>=Low(flwPort))and(i64<=High(flwPort))then flwPort:=i64 else raise EqCDKexception.Create(Format(ClassName+': '+excInvalidTCPPort,[sPort],gfs)); inherited Create(sCommName); end; function TTCPClientSocket.DoCreateHandle:THandle; begin Result:=inherited DoCreateHandle; try fTCPClient:=TIdTCPClient.Create(nil); fTCPClient.Host:=fsServer; fTCPClient.Port:=flwPort; fTCPClient.Connect; fbConnected:=fTCPClient.Connected; Result:=fTCPClient.Socket.Binding.Handle; except FreeAndNil(fTCPClient); end; end; procedure TTCPClientSocket.DoDestroyHandle; begin try FreeAndNil(fTCPClient); except end; fhCommHandle:=INVALID_HANDLE_VALUE; inherited DoDestroyHandle; end; function TTCPClientSocket.DoGetUInt(const ndx:integer):UInt64; begin Result:=0; case ndx of ndxBytesForRead,ndxBytesForWrite,ndxCommInputQueueSize,ndxCommOutputQueueSize: if not Connected then begin SetLastError(ceInvalidHandle); exit; end else case ndx of ndxBytesForRead: Result:=fTCPClient.InputBuffer.Size; ndxBytesForWrite: with TLIdTCPClient(fTCPClient)do if FWriteBuffer<>nil then Result:=FWriteBuffer.Size; ndxCommInputQueueSize: Result:=fTCPClient.RecvBufferSize; ndxCommOutputQueueSize: Result:=fTCPClient.SendBufferSize; else Result:=0; end; else Result:=inherited DoGetUInt(ndx); end; end; class function TTCPClientSocket.GetClassCaption:AString; begin Result:='сетевой сокет TCP-клиент (TTCPClientSocket)'; end; class function TTCPClientSocket.GetClassDescription:AString; begin Result:='класс TTCPClientSocket реализует сокет на основе TCP-клиента'; end; class function TTCPClientSocket.GetObjectByName(sName:AnsiString):TCommunicationObject; begin Result:=nil; end; procedure TTCPClientSocket.SetDefault; begin try Lock; BeginUpdate; inherited SetDefault; fsCaption:=CommName; fsName:=fsCaption; fsDescription:=GetClassDescription; finally EndUpdate; Unlock; end; end; function TTCPClientSocket._CancelIo:boolean; begin Result:=false; SetLastError(ceInvalidFunction); end; // неверная функция function TTCPClientSocket._FlushFileBuffers:boolean; begin Result:=false; try Lock; if not Connected then begin SetLastError(ceInvalidHandle); exit; end; try fTCPClient.FlushWriteBuffer; Result:=true; except end; finally Unlock; end; end; function TTCPClientSocket._GetCommMask(var lwEventMask:longword):boolean; begin Result:=false; SetLastError(ceInvalidFunction); end; // неверная функция function TTCPClientSocket._GetCommTimeouts(var rCommTimeouts:TCommTimeouts):boolean; begin try Lock; rCommTimeouts:=ct; Result:=true; finally Unlock; end; end; function TTCPClientSocket._GetOverlappedResult(const prOverlapped:POverlapped;var lwNumberOfBytesTransferred:longword; const bWait:boolean):boolean; begin Result:=false; SetLastError(ceInvalidFunction); end; // неверная функция function TTCPClientSocket._PurgeComm(const lwPurgeAction:longword):boolean; begin Result:=false; try Lock; if not Connected then begin SetLastError(ceInvalidHandle); exit; end; if lwPurgeAction and PURGE_RXCLEAR<>0then try fTCPClient.InputBuffer.Clear; except end; if lwPurgeAction and PURGE_TXCLEAR<>0then try fTCPClient.ClearWriteBuffer; except end; Result:=true; finally Unlock; end; end; function TTCPClientSocket._ReadFile(var Buffer; const lwNumberOfBytesToRead:longword; var lwNumberOfBytesRead:longword; const prOverlapped:POverlapped):boolean; var lwTotalTicks,lwTicks,lw:longword; s,s0:AnsiString; begin Result:=false; lwNumberOfBytesRead:=0; try Lock; if not Connected then begin SetLastError(ceInvalidHandle); exit; end; if fTCPClient.Connected then try if(ct.ReadTotalTimeoutConstant=0)or(ct.ReadTotalTimeoutMultiplier=0)then lwTotalTicks:=ct.ReadIntervalTimeout else lwTotalTicks:=0; if lwNumberOfBytesToRead>0then inc(lwTotalTicks,ct.ReadTotalTimeoutMultiplier*lwNumberOfBytesToRead); inc(lwTotalTicks,ct.ReadTotalTimeoutConstant); lwTotalTicks:=GetTickCount+lwTotalTicks; repeat // выдерживаем общий таймаут чтения lw:=ct.ReadIntervalTimeout; if(lw=0)and(CommBytesForRead<>0)then lw:=1; fTCPClient.ReadTimeout:=lw; lwTicks:=GetTickCount+lw; s:=''; repeat // пытаемся читать в течение межсимвольного таймаута Result:=fTCPClient.ReadFromStack(true,lw,false)>0; if Result then begin lwNumberOfBytesRead:=fTCPClient.InputBuffer.Size; s0:=fTCPClient.ReadString(lwNumberOfBytesRead); s:=s+s0; lwTicks:=GetTickCount+lw; // восстановим межсимвольный таймаут end; until integer(longword(GetTickCount-lwTicks))>0; Result:=s<>''; if Result then begin lwNumberOfBytesRead:=Length(s); CopyMemory(@Buffer,@s[1],lwNumberOfBytesRead); break; end; until integer(longword(GetTickCount-lwTotalTicks))>0; except Connected:=fTCPClient.Connected; end; finally Unlock; end; end; function TTCPClientSocket._SetCommMask(const lwEventMask:longword):boolean; begin Result:=false; SetLastError(ceInvalidFunction); end; // неверная функция function TTCPClientSocket._SetCommTimeouts(const rCommTimeouts:TCommTimeouts):boolean; begin try Lock; ct:=rCommTimeouts; Result:=true; finally Unlock; end; end; function TTCPClientSocket._SetupComm(const lwInputQueueSize,lwOutputQueueSize:longword):boolean; begin Result:=false; try Lock; if not Connected then begin SetLastError(ceInvalidHandle); exit; end; try fTCPClient.RecvBufferSize:=lwInputQueueSize; fTCPClient.SendBufferSize:=lwOutputQueueSize; except end; finally Unlock; end; end; function TTCPClientSocket._WaitCommEvent(var lwEventMask:longword; const prOverlapped:POverlapped):boolean; begin Result:=false; SetLastError(ceInvalidFunction); end; // неверная функция function TTCPClientSocket._WriteFile(const Buffer; const lwNumberOfBytesToWrite:longword; var lwNumberOfBytesWritten:longword; prOverlapped:POverlapped):boolean; begin Result:=false; lwNumberOfBytesWritten:=0; try Lock; if not Connected then begin SetLastError(ceInvalidHandle); exit; end; if fTCPClient.Connected then try fTCPClient.WriteBuffer(Buffer,lwNumberOfBytesToWrite); lwNumberOfBytesWritten:=lwNumberOfBytesToWrite; Result:=true; except Connected:=fTCPClient.Connected; end; finally Unlock; end; end; { TTCPClientConnection } constructor TTCPClientConnection.Create; begin fCommunicationSocketClass:=TTCPClientSocket; inherited; end; class function TTCPClientConnection.GetClassCaption:AString; begin Result:='сетевое соединение TCP-клиент (TTCPClientConnection)'; end; class function TTCPClientConnection.GetClassDescription: AString; begin Result:='сетевое соединение TTCPClientConnection позволяет открыть сокет класса TTCPClientSocket со своими настройками TCommunicationMode'; end; function TTCPClientConnection.GetTCPClientSocket:TTCPClientSocket; begin Result:=TTCPClientSocket(CommunicationSocket); end; procedure TTCPClientConnection.SetDefault; begin try Lock; BeginUpdate; inherited SetDefault; // просто изменяем все свойства fsCaption:='TCPClientConnection_0x'+IntToHex(fhID,8); fsName:=fsCaption; fsDescription:=GetClassCaption; finally EndUpdate; Unlock; end; end; { TTCPServerSocket } constructor TTCPServerSocket.Create(sCommName: AnsiString; bOverlapped: boolean); begin inherited; end; function TTCPServerSocket.DoCreateHandle: THandle; begin end; procedure TTCPServerSocket.DoDestroyHandle; begin inherited; end; function TTCPServerSocket.DoGetUInt(const ndx: integer): UInt64; begin end; class function TTCPServerSocket.GetObjectByName( sName: AnsiString): TCommunicationObject; begin end; procedure TTCPServerSocket.SetDefault; begin inherited; end; function TTCPServerSocket._CancelIo: boolean; begin end; function TTCPServerSocket._FlushFileBuffers: boolean; begin end; function TTCPServerSocket._GetCommMask(var lwEventMask: longword): boolean; begin end; function TTCPServerSocket._GetCommTimeouts( var rCommTimeouts: TCommTimeouts): boolean; begin end; function TTCPServerSocket._GetOverlappedResult( const prOverlapped: POverlapped; var lwNumberOfBytesTransferred: longword; const bWait: boolean): boolean; begin end; function TTCPServerSocket._PurgeComm( const lwPurgeAction: longword): boolean; begin end; function TTCPServerSocket._ReadFile(var Buffer; const lwNumberOfBytesToRead: longword; var lwNumberOfBytesRead: longword; const prOverlapped: POverlapped): boolean; begin end; function TTCPServerSocket._SetCommMask( const lwEventMask: longword): boolean; begin end; function TTCPServerSocket._SetCommTimeouts( const rCommTimeouts: TCommTimeouts): boolean; begin end; function TTCPServerSocket._SetupComm(const lwInputQueueSize, lwOutputQueueSize: longword): boolean; begin end; function TTCPServerSocket._WaitCommEvent(var lwEventMask: longword; const prOverlapped: POverlapped): boolean; begin end; function TTCPServerSocket._WriteFile(const Buffer; const lwNumberOfBytesToWrite: longword; var lwNumberOfBytesWritten: longword; prOverlapped: POverlapped): boolean; begin end; { TTCPServerConnection } constructor TTCPServerConnection.Create; begin fCommunicationSocketClass:=TTCPServerSocket; inherited; end; function TTCPServerConnection.GetTCPServerSocket:TTCPServerSocket; begin Result:=TTCPServerSocket(CommunicationSocket); end; initialization GetLocaleFormatSettings(SysLocale.DefaultLCID,gfs); RegisterClasses; end.
{ @abstract(This file is part of the PWIG tool, Pascal Wrapper and Interface Generator.) @author(Tomas Krysl) Copyright (c) 2020 Tomas Krysl<BR><BR> <B>License:</B><BR> This code is licensed under BSD 3-Clause Clear License, see file License.txt or https://spdx.org/licenses/BSD-3-Clause-Clear.html. } unit pwig_pascal; {$mode delphi} interface uses Classes, SysUtils, PWIGGen; type TPWIGGenPascalMethodStyle = ( msIntfDeclaration, msLibCallGetLength, msLibCall, msLibExport, msClassDeclaration, msClassImplementation, msClassCall, msPropertyDeclaration, msEventDeclaration, msEventSinkCallGetLength, msEventSinkCall ); { TPWIGGenPascal } TPWIGGenPascal = class(TPWIGGenerator) private FFlags: string; FIndent: string; FFirstDashSep: Boolean; procedure IncIndent; procedure DecIndent; procedure ClearFlags; procedure AddFlag(AFlag: Boolean; const AFlagText: string); procedure InitDashSep; function ParamDirection(AMethod: TPWIGMethod; AParam: TPWIGParam; AGetter: Boolean): TPWIGParamDirection; function ParamDirectionToString(ADirection: TPWIGParamDirection): string; procedure WriteDashSep; procedure WriteSpace; procedure WritePascalBegin; procedure WritePascalEnd; procedure WritePascalEndElse; procedure WriteTry; procedure WriteExcept(const AMessage: string = ''); procedure WriteExceptLibCall; property Flags: string read FFlags; property Indent: string read FIndent; protected F: TextFile; function GetDescription: string; override; function GetName: string; override; function CallingConvToString(AMethod: TPWIGMethod): string; virtual; function TypeToString(AType: TPWIGType): string; virtual; function ReplaceNotAllowedParamName(AName: string): string; virtual; procedure WriteIntfElementProps(AElement: TPWIGElement); virtual; procedure WriteIntfAliasProps(AAlias: TPWIGAlias); virtual; procedure WriteIntfEnumProps(AEnum: TPWIGEnum); virtual; procedure WriteIntfInterfaceProps(AIntf: TPWIGInterface); virtual; procedure WriteIntfClassProps(AClass: TPWIGClass); virtual; procedure WriteMethod(const AClassName: string; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AStyle: TPWIGGenPascalMethodStyle; ADefaultInterface, AGetter: Boolean; const APrefix: string); virtual; procedure WriteCalleeConstructor(AClass: TPWIGClass; AIntf: TPWIGInterface; ABody: Boolean); virtual; procedure WriteCalleeDestructor(AClass: TPWIGClass; AIntf: TPWIGInterface; ABody: Boolean); virtual; procedure WriteCalleeMethod(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ABody, ADefaultInterface, AGetter: Boolean; const APrefix: string); virtual; procedure WriteCalleeEventSetter(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ABody, ADefaultInterface: Boolean); virtual; procedure WriteCalleeDeclarations(AClass: TPWIGClass); virtual; procedure WriteCalleeEventSinkDeclarations(AIntf: TPWIGInterface); virtual; procedure WriteCalleeEventSinkImplementations(AIntf: TPWIGInterface); virtual; procedure WriteCalleeExportedFuncs(AClass: TPWIGClass; ABody: Boolean); virtual; procedure WriteCalleeExports(AClass: TPWIGClass); virtual; function WriteCalleeUnicodeStringDeclarations(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; function WriteCalleeUnicodeStringManagement1(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; function WriteCalleeUnicodeStringManagement2(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; procedure WriteCallerConstructor(AClass: TPWIGClass; AIntf: TPWIGInterface); virtual; procedure WriteCallerDestructor(AClass: TPWIGClass; AIntf: TPWIGInterface); virtual; procedure WriteCallerMethod(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ADefaultInterface, AGetter: Boolean; const APrefix: string); virtual; procedure WriteCallerEventCallback(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ADefaultInterface: Boolean); virtual; procedure WriteCallerDeclarations(AClass: TPWIGClass); virtual; procedure WriteCallerPointers(AClass: TPWIGClass; AUseType: Boolean); virtual; procedure WriteCallerLibLoads(AClass: TPWIGClass); virtual; procedure WriteCallerImplementations(AClass: TPWIGClass); virtual; function WriteCallerUnicodeStringDeclarations(AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; function WriteCallerUnicodeStringManagement1(AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; function WriteCallerUnicodeStringManagement2(AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; function WriteCallerUnicodeStringManagement3(AMethod: TPWIGMethod; AGetter: Boolean): Boolean; virtual; procedure WriteInterfaceFile(const AFileName: string); procedure WriteCalleeFile(const AFileName: string); procedure WriteCallerFile(const AFileName: string); public constructor Create(AOwner: TPWIG); override; procedure SaveCalleeFiles(const AFileName: string); override; procedure SaveCallerFiles(const AFileName: string); override; end; implementation uses KFunctions; { TPWIGGenPascal } constructor TPWIGGenPascal.Create(AOwner: TPWIG); begin inherited Create(AOwner); FIndent := ''; end; procedure TPWIGGenPascal.IncIndent; begin FIndent := FIndent + ' '; end; procedure TPWIGGenPascal.DecIndent; begin Delete(FIndent, 1, 2); end; procedure TPWIGGenPascal.ClearFlags; begin FFlags := ''; end; procedure TPWIGGenPascal.AddFlag(AFlag: Boolean; const AFlagText: string); begin if AFlag then begin if FFlags <> '' then FFlags := FFlags + ', '; FFlags := FFlags + AFlagText; end; end; procedure TPWIGGenPascal.InitDashSep; begin FFirstDashSep := True; end; function TPWIGGenPascal.ParamDirection(AMethod: TPWIGMethod; AParam: TPWIGParam; AGetter: Boolean): TPWIGParamDirection; begin Result := AParam.ParamDirection; if AMethod is TPWIGProperty then begin // all params are [in] except last one which is [out, retval] for a getter if not AGetter or (AParam <> AMethod.Params.Last) then Result := pdIn else Result := pdOut; end; end; function TPWIGGenPascal.ParamDirectionToString(ADirection: TPWIGParamDirection ): string; begin Result := ''; case ADirection of pdIn: Result := 'const'; pdOut: Result := 'out'; pdInOut: Result := 'var'; end; end; function TPWIGGenPascal.CallingConvToString(AMethod: TPWIGMethod): string; var Conv: TPWIGCallingConv; begin if (AMethod <> nil) and (AMethod.CallingConv <> ccNone) then Conv := AMethod.CallingConv else Conv := FPWIG.GlobalCallingConv; Result := ''; case Conv of ccCDecl: Result := 'cdecl'; ccPascal: Result := 'pascal'; ccStdCall: Result := 'stdcall'; ccSafeCall: Result := 'safecall'; end; end; function TPWIGGenPascal.TypeToString(AType: TPWIGType): string; begin Result := ''; case AType.BaseType of btLongInt: Result := 'LongInt'; btLongWord: Result := 'LongWord'; btSmallInt: Result := 'SmallInt'; btWord: Result := 'Word'; btInt64: Result := 'Int64'; btUInt64: Result := 'UInt64'; btSingle: Result := 'Single'; btDouble: Result := 'Double'; btUnicodeString: Result := 'string'; // Unicode string btRawByteString: Result := 'PByteArray'; btCurrency: Result := 'Currency'; btDateTime: Result := 'TDateTime'; btEnum: Result := FPWIG.Enums.FindName(AType.CustomTypeGUID, AType.CustomTypeName); btAlias: Result := FPWIG.Aliases.FindName(AType.CustomTypeGUID, AType.CustomTypeName); btInterface: Result := FPWIG.Interfaces.FindName(AType.CustomTypeGUID, AType.CustomTypeName); end; end; function TPWIGGenPascal.ReplaceNotAllowedParamName(AName: string): string; begin Result := AName; // naive check here, should be sufficient if LowerCase(AName) = 'result' then Result := AName + 'Param'; end; procedure TPWIGGenPascal.WriteDashSep; begin if not FFirstDashSep then Writeln(F, ','); FFirstDashSep := False; end; procedure TPWIGGenPascal.WriteSpace; begin Writeln(F); end; procedure TPWIGGenPascal.WritePascalBegin; begin Writeln(F, Indent, 'begin'); IncIndent; end; procedure TPWIGGenPascal.WritePascalEnd; begin DecIndent; Writeln(F, Indent, 'end;'); end; procedure TPWIGGenPascal.WritePascalEndElse; begin DecIndent; Writeln(F, Indent, 'end else'); end; procedure TPWIGGenPascal.WriteTry; begin Writeln(F, Indent, 'try'); IncIndent; end; procedure TPWIGGenPascal.WriteExcept(const AMessage: string); begin DecIndent; Writeln(F, Indent, 'except'); if AMessage <> '' then begin IncIndent; Writeln(F, Indent, AMessage); DecIndent; end; Writeln(F, Indent, 'end;'); end; procedure TPWIGGenPascal.WriteExceptLibCall; begin WriteExcept('on E : Exception do LibCallError(E.Message);'); end; function TPWIGGenPascal.GetDescription: string; begin Result := 'Pascal (unmanaged code, callee + caller). Usable in Delphi, Lazarus/Free Pascal.'; end; function TPWIGGenPascal.GetName: string; begin Result := 'Pascal'; end; procedure TPWIGGenPascal.SaveCalleeFiles(const AFileName: string); begin WriteInterfaceFile(AFileName); WriteCalleeFile(AFileName); end; procedure TPWIGGenPascal.SaveCallerFiles(const AFileName: string); begin WriteInterfaceFile(AFileName); WriteCallerFile(AFileName); end; procedure TPWIGGenPascal.WriteIntfElementProps(AElement: TPWIGElement); begin if AElement.Name <> '' then Writeln(F, Indent, '// Name: ', AElement.Name); if AElement.Version <> '' then Writeln(F, Indent, '// Version: ', AElement.Version); if AElement.GUID <> '' then Writeln(F, Indent, '// GUID: ', AElement.GUID); if AElement.Description <> '' then Writeln(F, Indent, '// Description: ', AElement.Description); if (AElement is TPWIGInterface) and TPWIGInterface(AElement).FlagDual then Writeln(F, Indent, '// Dual interface (COM only)'); if (AElement is TPWIGInterface) and TPWIGInterface(AElement).FlagOleAutomation then Writeln(F, Indent, '// OLE automation interface (COM only)'); WriteSpace; end; procedure TPWIGGenPascal.WriteIntfAliasProps(AAlias: TPWIGAlias); begin Writeln(F, Indent, '// Alias type properties:'); WriteIntfElementProps(AAlias); Writeln(F, Indent, AAlias.Name, ' = type ', TypeToString(AAlias.AliasedType), ';'); WriteSpace; end; procedure TPWIGGenPascal.WriteIntfEnumProps(AEnum: TPWIGEnum); var I: Integer; Elem: TPWIGEnumElement; begin Writeln(F, Indent, '// Enumerated type properties:'); WriteIntfElementProps(AEnum); Writeln(F, Indent, AEnum.Name, ' = ('); IncIndent; for I := 0 to AEnum.Elements.Count - 1 do begin Elem := AEnum.Elements[I]; Write(F, Indent, Elem.Name, ' = ', Elem.Value); if I < AEnum.Elements.Count - 1 then Writeln(F, ',') else Writeln(F); end; DecIndent; Writeln(F, Indent, ');'); WriteSpace; end; procedure TPWIGGenPascal.WriteIntfInterfaceProps(AIntf: TPWIGInterface); var Method: TPWIGMethod; Prop: TPWIGProperty; begin Writeln(F, Indent, '// Interface type properties:'); WriteIntfElementProps(AIntf); Writeln(F, Indent, '// Methods:'); for Method in AIntf.Methods do begin WriteMethod('', AIntf, Method, msIntfDeclaration, False, False, ''); end; Writeln(F, Indent, '// Properties:'); for Prop in AIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteMethod('', AIntf, Prop, msIntfDeclaration, False, True, 'Get'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteMethod('', AIntf, Prop, msIntfDeclaration, False, False, 'Set'); end; end; WriteSpace; end; procedure TPWIGGenPascal.WriteIntfClassProps(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf, LIntfDef: TPWIGInterface; Method: TPWIGMethod; begin Writeln(F, Indent, '// Class properties:'); WriteIntfElementProps(AClass); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if LIntf <> nil then if LIntf.FlagDispEvents then begin // output prototypes for event handler setup functions LIntfDef := FPWIG.FindDefaultIntf(AClass, False); if LIntfDef <> nil then // we suppose default interface always exists! for Method in LIntf.Methods do Writeln(F, Indent, 'TSet', AClass.Name, LIntf.Name, Method.Name, ' = function(const ItemHandle: ', LIntfDef.Name, '; const EventSink: ', LIntf.Name, '; const EventHandler: T', LIntf.Name, Method.Name, '): Boolean; ', CallingConvToString(nil),';'); end else begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin Writeln(F, Indent, 'T', AClass.Name, 'Create = function(out ItemHandle: ', LIntf.Name, '): Boolean; ', CallingConvToString(nil),';'); Writeln(F, Indent, 'T', AClass.Name, 'Destroy = function(const ItemHandle: ', LIntf.Name, '): Boolean; ', CallingConvToString(nil),';'); end; end; end; WriteSpace; end; procedure TPWIGGenPascal.WriteMethod(const AClassName: string; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AStyle: TPWIGGenPascalMethodStyle; ADefaultInterface, AGetter: Boolean; const APrefix: string); procedure WriteLibCallUnicodeStringParam(AParamDir: TPWIGParamDirection; const AParamName: string); begin if AParamDir = pdIn then Write(F, 'PAnsiChar(String2LibUtf8String(', AParamName, '))') else if AStyle in [msLibCallGetLength, msEventSinkCallGetLength] then Write(F, 'nil, Length__', AParamName) else Write(F, 'PAnsiChar(AnsiString__', AParamName, '), Length__', AParamName); end; var Param, RetVal: TPWIGParam; ParamDir: TPWIGParamDirection; CallingConv, HandleParam, IntfName, ParamName, ParamSpecifier, FuncKeyword, RetValAssignment: string; FirstParam: Boolean; begin if AStyle in [msIntfDeclaration, msLibExport] then begin CallingConv := '; ' + CallingConvToString(AMethod); HandleParam := 'const ItemHandle: ' + AIntf.Name; RetVal := nil; FuncKeyword := ''; IntfName := AIntf.name; end else if AStyle in [msLibCall, msLibCallGetLength] then begin CallingConv := ''; HandleParam := 'FItemHandle'; if AGetter then RetVal := AMethod.Params.Last else RetVal := AMethod.Params.FindRetVal; FuncKeyword := ''; IntfName := AIntf.Name; end else if AStyle in [msEventSinkCall, msEventSinkCallGetLength] then begin CallingConv := ''; HandleParam := 'F' + AMethod.Name + 'EventSink'; RetVal := nil; FuncKeyWord := ''; RetValAssignment := ''; IntfName := ''; end else begin CallingConv := ''; HandleParam := ''; if AGetter or (AStyle = msPropertyDeclaration) then RetVal := AMethod.Params.Last else RetVal := AMethod.Params.FindRetVal; if RetVal <> nil then begin FuncKeyword := 'function'; ParamName := ReplaceNotAllowedParamName(RetVal.Name); if RetVal.ParamType.BaseType = btUnicodeString then ParamName := 'String__' + AClassName + AIntf.Name + AMethod.Name + ParamName; RetValAssignment := ParamName + ' := '; end else begin FuncKeyword := 'procedure'; RetValAssignment := ''; end; if ADefaultInterface then IntfName := '' else IntfName := AIntf.Name; end; case AStyle of msIntfDeclaration: Write(F, Indent, 'T', APrefix, IntfName, AMethod.Name, ' = function(', HandleParam); msLibCall, msLibCallGetLength: Write(F, Indent, 'Func', AClassName, APrefix, IntfName, AMethod.Name, '(', HandleParam); msLibExport: Write(F, Indent, 'function ', AClassName, APrefix, IntfName, AMethod.Name, '(', HandleParam); msClassDeclaration: Write(F, Indent, FuncKeyword, ' ', APrefix, IntfName, AMethod.Name); msClassImplementation: Write(F, Indent, FuncKeyword, ' T', AClassName, '.', APrefix, IntfName, AMethod.Name); msClassCall: Write(F, Indent, RetValAssignment, 'T', AClassName, '(ItemHandle).', APrefix, IntfName, AMethod.Name); msPropertyDeclaration: Write(F, Indent, 'property ', IntfName, AMethod.Name); msEventDeclaration: Write(F, Indent, 'T', AClassName, IntfName, AMethod.Name, APrefix, ' = ', FuncKeyword); msEventSinkCall, msEventSinkCallGetLength: Write(F, Indent, 'F', AMethod.Name, 'EventHandler(', HandleParam); end; if (AMethod.Params.Count = 0) or (AMethod.Params.Count = 1) and (RetVal <> nil) then begin if (RetVal <> nil) and (AStyle in [msLibCall, msLibCallGetLength]) then begin Write(F, ', '); if RetVal.ParamType.BaseType = btUnicodeString then begin ParamDir := ParamDirection(AMethod, RetVal, AGetter); ParamName := ReplaceNotAllowedParamName(RetVal.Name); WriteLibCallUnicodeStringParam(ParamDir, ParamName); end else Write(F, 'Result'); end; if HandleParam <> '' then Write(F, ')'); end else begin if HandleParam <> '' then begin if AStyle in [msClassCall, msLibCall, msLibCallGetLength, msEventSinkCall, msEventSinkCallGetLength] then Write(F, ', ') else Write(F, '; '); end else if AStyle = msPropertyDeclaration then Write(F, '[') else Write(F, '('); FirstParam := True; for Param in AMethod.Params do begin ParamName := ReplaceNotAllowedParamName(Param.Name); ParamDir := ParamDirection(AMethod, Param, AGetter); if Param <> RetVal then begin if not FirstParam then begin if AStyle in [msClassCall, msLibCall, msLibCallGetLength, msEventSinkCall, msEventSinkCallGetLength] then Write(F, ', ') else Write(F, '; '); end; FirstParam := False; ParamSpecifier := ParamDirectionToString(ParamDir) + ' '; if (AStyle in [msClassDeclaration, msClassImplementation]) and (AMethod is TPWIGProperty) then begin // Delphi does not support const in property getter/setter if (ParamDir = pdIn) and (Param <> AMethod.Params.Last) then ParamSpecifier := ''; end; if (Param.ParamType.BaseType = btUnicodeString) and (AStyle in [msIntfDeclaration, msLibExport]) then begin // automated string management for UnicodeString if ParamDir = pdIn then Write(F, ParamSpecifier, ParamName, ': PAnsiChar') else Write(F, 'const ', ParamName, ': PAnsiChar; var Length__', ParamName, ': LongInt'); end else if (Param.ParamType.BaseType = btUnicodeString) and (AStyle in [msClassCall]) then begin if ParamDir = pdIn then Write(F, 'LibUtf8String2String(', ParamName, ')') else Write(F, 'String__' + AClassName + AIntf.Name + AMethod.Name + ParamName); end else if (Param.ParamType.BaseType = btUnicodeString) and (AStyle in [msLibCall, msLibCallGetLength, msEventSinkCall, msEventSinkCallGetlength]) then begin WriteLibCallUnicodeStringParam(ParamDir, ParamName); end else if AStyle in [msClassCall, msLibCall, msLibCallGetLength, msEventSinkCall, msEventSinkCallGetLength] then Write(F, ParamName) else if AStyle = msPropertyDeclaration then Write(F, ParamName, ': ', TypeToString(Param.ParamType)) else Write(F, ParamSpecifier, ParamName, ': ', TypeToString(Param.ParamType)); end else if AStyle in [msLibCall, msLibCallGetLength] then begin Write(F, ', '); if Param.ParamType.BaseType = btUnicodeString then begin WriteLibCallUnicodeStringParam(ParamDir, ParamName); end else Write(F, 'Result'); end; end; if AStyle = msPropertyDeclaration then Write(F, ']') else Write(F, ')'); end; if AStyle in [msIntfDeclaration, msLibExport] then Write(F, ': Boolean', CallingConv) else if (AStyle in [msClassDeclaration, msClassImplementation]) and (RetVal <> nil) then Write(F, ': ', TypeToString(RetVal.ParamType)) else if (AStyle = msPropertyDeclaration) and (AMethod is TPWIGProperty) then begin if RetVal <> nil then Write(F, ': ', TypeToString(RetVal.ParamType)); if TPWIGProperty(AMethod).PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter Write(F, ' read Get', IntfName, AMethod.Name); end; if TPWIGProperty(AMethod).PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter Write(F, ' write Set', IntfName, AMethod.Name); end; end; if AStyle in [msLibCall, msLibCallGetLength] then Writeln(F) else if AStyle = msEventDeclaration then Writeln(F, ' of object;') else Writeln(F, ';'); end; procedure TPWIGGenPascal.WriteCalleeMethod(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ABody, ADefaultInterface, AGetter: Boolean; const APrefix: string); var UnicodeStringsExist: Boolean; begin UnicodeStringsExist := False; if ABody then UnicodeStringsExist := WriteCalleeUnicodeStringDeclarations(AClass, AIntf, AMethod, AGetter); WriteMethod(AClass.Name, AIntf, AMethod, msLibExport, False, AGetter, APrefix); if ABody then begin // begin to write function body WritePascalBegin; Writeln(F, Indent, 'Result := False;'); WriteTry; Writeln(F, Indent, 'if TObject(ItemHandle) is T', AClass.Name, ' then'); WritePascalBegin; if UnicodeStringsExist then WriteCalleeUnicodeStringManagement1(AClass, AIntf, AMethod, AGetter); WriteMethod(AClass.Name, AIntf, AMethod, msClassCall, ADefaultInterface, AGetter, APrefix); if UnicodeStringsExist then WriteCalleeUnicodeStringManagement2(AClass, AIntf, AMethod, AGetter); // end of function body Writeln(F, Indent, 'Result := True;'); WritePascalEnd; WriteExcept; WritePascalEnd; WriteSpace; end; end; procedure TPWIGGenPascal.WriteCalleeEventSetter(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ABody, ADefaultInterface: Boolean); var LIntfDef: TPWIGInterface; IntfName: string; begin LIntfDef := FPWIG.FindDefaultIntf(AClass, False); if LIntfDef = nil then Exit; // we suppose default interface always exists! if ADefaultInterface then IntfName := '' else IntfName := AIntf.Name; Writeln(F, Indent, 'function Set', AClass.Name, AIntf.Name, AMethod.Name, '(const ItemHandle:', LIntfDef.Name, '; const EventSink: ', AIntf.Name, '; const EventHandler: T', AIntf.Name, AMethod.Name, '): Boolean; ', CallingConvToString(nil),';'); if not ABody then Exit; WritePascalBegin; Writeln(F, Indent, 'Result := False;'); WriteTry; Writeln(F, Indent, 'if TObject(ItemHandle) is T', AClass.Name, ' then'); WritePascalBegin; Writeln(F, Indent, 'T', AClass.Name, '(ItemHandle).Setup', IntfName, AMethod.Name, '(EventSink, EventHandler);'); Writeln(F, Indent, 'Result := True;'); WritePascalEnd; WriteExcept; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeConstructor(AClass: TPWIGClass; AIntf: TPWIGInterface; ABody: Boolean); begin Writeln(F, Indent, 'function ', AClass.Name, 'Create(out ItemHandle:', AIntf.Name, '): Boolean; ', CallingConvToString(nil),';'); if not ABody then Exit; WritePascalBegin; WriteTry; Writeln(F, Indent, 'ItemHandle := ', AIntf.Name, '(T', AClass.Name, '.Create);'); Writeln(F, Indent, 'Result := True;'); WriteExcept('Result := False;'); WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeDestructor(AClass: TPWIGClass; AIntf: TPWIGInterface; ABody: Boolean); begin Writeln(F, Indent, 'function ', AClass.Name, 'Destroy(ItemHandle: ', AIntf.Name, '): Boolean; ', CallingConvToString(nil),';'); if not ABody then Exit; WritePascalBegin; Writeln(F, Indent, 'Result := False;'); WriteTry; Writeln(F, Indent, 'if TObject(ItemHandle) is T', AClass.Name, ' then'); WritePascalBegin; Writeln(F, Indent, 'T', AClass.Name, '(ItemHandle).Free;'); Writeln(F, Indent, 'Result := True;'); WritePascalEnd; WriteExcept; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeDeclarations(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; IntfName: string; begin WriteIntfElementProps(AClass); Writeln(F, Indent, 'T', AClass.Name, ' = class(TObject)'); Writeln(F, Indent, 'private'); IncIndent; // write event handler declarations, private section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin Writeln(F, Indent, 'FEvents: T', LIntf.Name, ';'); end; end; DecIndent; Writeln(F, Indent, 'public'); IncIndent; // write interface declarations, public section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin Writeln(F, Indent, 'constructor Create;'); Writeln(F, Indent, 'destructor Destroy; override;'); end; Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin WriteMethod(AClass.Name, LIntf, Method, msClassDeclaration, Ref.FlagDefault, False, ''); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteMethod(AClass.Name, LIntf, Prop, msClassDeclaration, Ref.FlagDefault, True, 'Get'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteMethod(AClass.Name, LIntf, Prop, msClassDeclaration, Ref.FlagDefault, False, 'Set'); end; end; end; end; // write event handler declarations, public section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Setup event handlers:'); if Ref.FlagDefault then IntfName := '' else IntfName := LIntf.Name; for Method in LIntf.Methods do begin Writeln(F, Indent, 'procedure Setup', IntfName, Method.Name, '(const EventSink: ', LIntf.Name, '; const EventHandler: T', LIntf.Name, Method.Name, ');'); end; end; end; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeEventSinkDeclarations(AIntf: TPWIGInterface); var Method: TPWIGMethod; begin WriteIntfElementProps(AIntf); Writeln(F, Indent, '// Wrapper class for ', AIntf.Name, ' interface event sinks:'); WriteSpace; Writeln(F, Indent, 'type'); IncIndent; Writeln(F, Indent, 'T', AIntf.Name, ' = class(TObject)'); Writeln(F, Indent, 'private'); IncIndent; for Method in AIntf.Methods do begin Writeln(F, Indent, 'F', Method.Name, 'EventSink: ', AIntf.Name, ';'); Writeln(F, Indent, 'F', Method.Name, 'EventHandler: T', AIntf.Name, Method.Name, ';'); end; DecIndent; Writeln(F, Indent, 'public'); IncIndent; Writeln(F, Indent, 'constructor Create;'); Writeln(F, Indent, '// Setup event handlers:'); for Method in AIntf.Methods do begin Writeln(F, Indent, 'procedure Setup', Method.Name, '(const EventSink: ', AIntf.Name, '; const EventHandler: T', AIntf.Name, Method.Name, ');'); end; Writeln(F, Indent, '// Call event handlers:'); for Method in AIntf.Methods do begin WriteMethod('', AIntf, Method, msClassDeclaration, True, False, ''); end; WritePascalEnd; DecIndent; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeEventSinkImplementations( AIntf: TPWIGInterface); var Method: TPWIGMethod; UnicodeStringsExist: Boolean; begin WriteIntfElementProps(AIntf); WriteSpace; Writeln(F, Indent, 'constructor T', AIntf.Name, '.Create;'); WritePascalBegin; for Method in AIntf.Methods do begin Writeln(F, Indent, 'F', Method.Name, 'EventSink := 0;'); Writeln(F, Indent, 'F', Method.Name, 'EventHandler := nil;'); end; WritePascalEnd; WriteSpace; Writeln(F, Indent, '// Setup event handlers:'); WriteSpace; for Method in AIntf.Methods do begin Writeln(F, Indent, 'procedure T', AIntf.Name, '.Setup', Method.Name, '(const EventSink: ', AIntf.Name, '; const EventHandler: T', AIntf.Name, Method.Name, ');'); WritePascalBegin; Writeln(F, Indent, 'F', Method.Name, 'EventSink := EventSink;'); Writeln(F, Indent, 'F', Method.Name, 'EventHandler := EventHandler;'); WritePascalEnd; WriteSpace; end; Writeln(F, Indent, '// Call event handlers:'); WriteSpace; for Method in AIntf.Methods do begin WriteMethod(AIntf.Name, AIntf, Method, msClassImplementation, True, False, ''); UnicodeStringsExist := WriteCallerUnicodeStringDeclarations(Method, False); WritePascalBegin; WriteTry; if UnicodeStringsExist then WriteCallerUnicodeStringManagement1(Method, False); Writeln(F, Indent, 'if Assigned(F', Method.Name, 'EventHandler) then'); WritePascalBegin; if UnicodeStringsExist then begin WriteMethod('', AIntf, Method, msEventSinkCallGetLength, True, False, ''); WriteCallerUnicodeStringManagement2(Method, False); end; WriteMethod('', AIntf, Method, msEventSinkCall, False, False, ''); WritePascalEnd; if UnicodeStringsExist then WriteCallerUnicodeStringManagement3(Method, False); WriteExcept; WritePascalEnd; WriteSpace; end; end; procedure TPWIGGenPascal.WriteCalleeExportedFuncs(AClass: TPWIGClass; ABody: Boolean); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; begin WriteIntfElementProps(AClass); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if LIntf <> nil then if LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Event handler setters:'); for Method in LIntf.Methods do begin WriteCalleeEventSetter(AClass, LIntf, Method, ABody, Ref.FlagDefault); end; end else begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin Writeln(F, Indent, '// Constructor:'); WriteCalleeConstructor(AClass, LIntf, ABody); Writeln(F, Indent, '// Destructor:'); WriteCalleeDestructor(AClass, LIntf, ABody); end; Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin WriteCalleeMethod(AClass, LIntf, Method, ABody, Ref.FlagDefault, False, ''); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteCalleeMethod(AClass, LIntf, Prop, ABody, Ref.FlagDefault, True, 'Get'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteCalleeMethod(AClass, LIntf, Prop, ABody, Ref.FlagDefault, False, 'Set'); end; end; end; end; WriteSpace; end; procedure TPWIGGenPascal.WriteCalleeExports(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; begin Writeln(F, Indent, '// ', AClass.Name); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if LIntf <> nil then if LIntf.FlagDispEvents then begin for Method in LIntf.Methods do begin WriteDashSep; Write(F, Indent, 'Set', AClass.Name, LIntf.Name, Method.Name); end; end else begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin WriteDashSep; Write(F, Indent, AClass.Name, 'Create'); WriteDashSep; Write(F, Indent, AClass.Name, 'Destroy'); end; for Method in LIntf.Methods do begin WriteDashSep; Write(F, Indent, AClass.Name, LIntf.Name, Method.Name); end; for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteDashSep; Write(F, Indent, AClass.Name, 'Get', LIntf.Name, Prop.Name); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteDashSep; Write(F, Indent, AClass.Name, 'Set', LIntf.Name, Prop.Name); end; end; end; end; Writeln(F); end; function TPWIGGenPascal.WriteCalleeUnicodeStringDeclarations( AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString, callee side Result := False; for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); if not Result then begin Writeln(F, Indent, 'var'); IncIndent; end; Result := True; Writeln(F, Indent, 'String__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ': string;'); Writeln(F, Indent, 'AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ': AnsiString;'); end; if Result then begin // because the function is called twice, var or out parameters are not set on the second call // we must store them in a temporary variable as well for Param in AMethod.Params do if (Param.ParamType.BaseType <> btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); Writeln(F, Indent, 'Tmp__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ': ', TypeToString(Param.ParamType), ';'); end; DecIndent; end; WriteSpace; end; function TPWIGGenPascal.WriteCalleeUnicodeStringManagement1( AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString, callee side Result := True; for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); Writeln(F, Indent, 'if ', ParamName, ' = nil then'); WritePascalBegin; Exit; end; end; function TPWIGGenPascal.WriteCalleeUnicodeStringManagement2(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString, callee side for Param in AMethod.Params do if ParamDirection(AMethod, Param, AGetter) <> pdIn then begin ParamName := ReplaceNotAllowedParamName(Param.Name); if Param.ParamType.BaseType = btUnicodeString then begin Writeln(F, Indent, 'AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ' := String2LibUtf8String(String__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ');'); Writeln(F, Indent, 'Length__', ParamName, ' := Length(AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ');') end else Writeln(F, Indent, 'Tmp__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ' := ', ParamName, ';'); end; WritePascalEndElse; WritePascalBegin; for Param in AMethod.Params do if ParamDirection(AMethod, Param, AGetter) <> pdIn then begin ParamName := ReplaceNotAllowedParamName(Param.Name); if Param.ParamType.BaseType = btUnicodeString then begin Writeln(F, Indent, 'if Length(AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ') > 0 then'); IncIndent; Writeln(F, Indent, 'System.Move(AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, '[1], ', ParamName, '^, Min(Length__', ParamName, ', Length(AnsiString__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ')));'); DecIndent; end else Writeln(F, Indent, ParamName, ' := Tmp__', AClass.Name, AIntf.Name, AMethod.Name, ParamName, ';'); end; WritePascalEnd; Result := True; end; procedure TPWIGGenPascal.WriteCallerConstructor(AClass: TPWIGClass; AIntf: TPWIGInterface); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; IntfName: string; begin Writeln(F, Indent, 'constructor T', AClass.Name, '.Create(AInterfaceHandle: ', AIntf.Name, ');'); WritePascalBegin; WriteTry; Writeln(F, Indent, 'FItemHandle := AInterfaceHandle;'); Writeln(F, Indent, 'if (FItemHandle = 0) and Assigned(Func', AClass.Name, 'Create) then'); IncIndent; Writeln(F, Indent, 'Func', AClass.Name, 'Create(FItemHandle);'); DecIndent; // call event handler setters for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin for Method in LIntf.Methods do begin if Ref.FlagDefault then IntfName := '' else IntfName := LIntf.Name; Writeln(F, Indent, 'F', IntfName, Method.Name, ' := nil;'); Writeln(F, Indent, 'if Assigned(FuncSet', AClass.name, LIntf.Name, Method.Name, ') then'); WritePascalBegin; Writeln(F, Indent, 'if not ('); IncIndent; Writeln(F, Indent, 'FuncSet', AClass.name, LIntf.Name, Method.Name, '(FItemHandle, ', LIntf.Name, '(Self), ', AClass.Name, LIntf.Name, Method.Name, ')'); DecIndent; Writeln(F, Indent, ') then LibError(''FuncSet', AClass.name, LIntf.Name, Method.Name, ''');'); WritePascalEnd; end; end; end; WriteExceptLibCall; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerDestructor(AClass: TPWIGClass; AIntf: TPWIGInterface); begin Writeln(F, Indent, 'destructor T', AClass.Name, '.Destroy;'); WritePascalBegin; WriteTry; Writeln(F, Indent, 'if Assigned(Func', AClass.Name, 'Destroy) then'); IncIndent; Writeln(F, Indent, 'Func', AClass.Name, 'Destroy(FItemHandle);'); DecIndent; Writeln(F, Indent, 'inherited;'); WriteExceptLibCall; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerMethod(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ADefaultInterface, AGetter: Boolean; const APrefix: string); var FuncName: string; UnicodeStringsExist: Boolean; begin FuncName := AClass.Name + APrefix + AIntf.Name + AMethod.Name; WriteMethod(AClass.Name, AIntf, AMethod, msClassImplementation, ADefaultInterface, AGetter, APrefix); UnicodeStringsExist := WriteCallerUnicodeStringDeclarations(AMethod, AGetter); // write method body WritePascalBegin; WriteTry; Writeln(F, Indent, 'if Assigned(Func', FuncName, ') then'); WritePascalBegin; if UnicodeStringsExist then begin WriteCallerUnicodeStringManagement1(AMethod, AGetter); Writeln(F, Indent, 'if not ('); IncIndent; WriteMethod(AClass.Name, AIntf, AMethod, msLibCallGetLength, ADefaultInterface, AGetter, APrefix); DecIndent; Writeln(F, Indent, ') then LibError(''Func', FuncName, ''');'); WriteCallerUnicodeStringManagement2(AMethod, AGetter); end; Writeln(F, Indent, 'if not ('); IncIndent; WriteMethod(AClass.Name, AIntf, AMethod, msLibCall, ADefaultInterface, AGetter, APrefix); DecIndent; Writeln(F, Indent, ') then LibError(''Func', FuncName, ''');'); WritePascalEnd; if UnicodeStringsExist then WriteCallerUnicodeStringManagement3(AMethod, AGetter); WriteExceptLibCall; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerEventCallback(AClass: TPWIGClass; AIntf: TPWIGInterface; AMethod: TPWIGMethod; ADefaultInterface: Boolean); var IntfName: string; UnicodeStringsExist: Boolean; begin if ADefaultinterface then IntfName := '' else IntfName := AIntf.Name; UnicodeStringsExist := WriteCalleeUnicodeStringDeclarations(AClass, AIntf, AMethod, False); WriteMethod(AClass.Name, AIntf, AMethod, msLibExport, ADefaultInterface, False, ''); // write method body WritePascalBegin; Writeln(F, Indent, 'Result := False;'); WriteTry; Writeln(F, Indent, 'if TObject(ItemHandle) is T', AClass.Name, ' then'); WritePascalBegin; Writeln(F, Indent, 'if Assigned(T', AClass.Name, '(ItemHandle).', IntfName, AMethod.Name, ') then'); WritePascalBegin; if UnicodeStringsExist then WriteCalleeUnicodeStringManagement1(AClass, AIntf, AMethod, False); WriteMethod(AClass.Name, AIntf, AMethod, msClassCall, ADefaultInterface, False, ''); if UnicodeStringsExist then WriteCalleeUnicodeStringManagement2(AClass, AIntf, AMethod, False); WritePascalEnd; Writeln(F, Indent, 'Result := True;'); WritePascalEnd; WriteExcept; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerDeclarations(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; IntfName: string; begin WriteIntfElementProps(AClass); // write event handler typedefs for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin for Method in LIntf.Methods do begin WriteMethod(AClass.Name, LIntf, Method, msEventDeclaration, False, False, 'Event'); end; end; end; WriteSpace; Writeln(F, Indent, 'T', AClass.Name, ' = class(TObject)'); Writeln(F, Indent, 'private'); IncIndent; // write event handler declarations, private section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin if Ref.FlagDefault then IntfName := '' else IntfName := LIntf.Name; for Method in LIntf.Methods do begin Writeln(F, Indent, 'F', IntfName, Method.Name, ': T', AClass.Name, LIntf.Name, Method.Name, 'Event;'); end; end; end; // write interface declarations, private section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin if Ref.FlagDefault then Writeln(F, Indent, 'FItemHandle: ', LIntf.Name, ';'); Writeln(F, Indent, '// Property getters and setters:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteMethod(AClass.Name, LIntf, Prop, msClassDeclaration, Ref.FlagDefault, True, 'Get'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteMethod(AClass.Name, LIntf, Prop, msClassDeclaration, Ref.FlagDefault, False, 'Set'); end; end; end; end; DecIndent; Writeln(F, Indent, 'public'); IncIndent; // write interface declarations, public section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin if Ref.FlagDefault then begin Writeln(F, Indent, 'constructor Create(AInterfaceHandle: ', LIntf.Name, ' = 0);'); Writeln(F, Indent, 'destructor Destroy; override;'); end; Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin WriteMethod(AClass.Name, LIntf, Method, msClassDeclaration, Ref.FlagDefault, False, ''); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin WriteMethod(AClass.Name, LIntf, Prop, msPropertyDeclaration, Ref.FlagDefault, False, ''); end; end; end; // write event handler declarations, public section for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin if Ref.FlagDefault then IntfName := '' else IntfName := LIntf.Name; Writeln(F, Indent, '// Events:'); for Method in LIntf.Methods do begin Writeln(F, Indent, 'property ', IntfName, Method.Name, ': T', AClass.Name, LIntf.Name, Method.Name, 'Event read F', IntfName, Method.Name, ' write F', IntfName, Method.Name, ';'); end; end; end; // write Handle property Writeln(F, Indent, '// Default interface handle:'); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents and Ref.FlagDefault then Writeln(F, Indent, 'property Handle: ', LIntf.Name, ' read FItemHandle;'); end; WritePascalEnd; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerPointers(AClass: TPWIGClass; AUseType: Boolean); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; begin WriteIntfElementProps(AClass); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin Writeln(F, Indent, '// Constructor:'); if AUseType then Writeln(F, Indent, 'Func', AClass.Name, 'Create: T', AClass.Name, 'Create = nil;') else Writeln(F, Indent, 'Func', AClass.Name, 'Create := nil;'); Writeln(F, Indent, '// Destructor:'); if AUseType then Writeln(F, Indent, 'Func', AClass.Name, 'Destroy: T', AClass.Name, 'Destroy = nil;') else Writeln(F, Indent, 'Func', AClass.Name, 'Destroy := nil;'); end; Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin if AUseType then Writeln(F, Indent, 'Func', AClass.Name, LIntf.Name, Method.Name, ': T', LIntf.Name, Method.Name, ' = nil;') else Writeln(F, Indent, 'Func', AClass.Name, LIntf.Name, Method.Name, ' := nil;'); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter if AUseType then Writeln(F, Indent, 'Func', AClass.Name, 'Get', LIntf.Name, Prop.Name, ': TGet', LIntf.Name, Prop.Name, ' = nil;') else Writeln(F, Indent, 'Func', AClass.Name, 'Get', LIntf.Name, Prop.Name, ' := nil;'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter if AUseType then Writeln(F, Indent, 'Func', AClass.Name, 'Set', LIntf.Name, Prop.Name, ': TSet', LIntf.Name, Prop.Name, ' = nil;') else Writeln(F, Indent, 'Func', AClass.Name, 'Set', LIntf.Name, Prop.Name, ' := nil;'); end; end; end; end; // write event handler setters for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Event handler setters:'); for Method in LIntf.Methods do begin if AUseType then Writeln(F, Indent, 'FuncSet', AClass.Name, LIntf.Name, Method.Name, ': TSet', AClass.Name, LIntf.Name, Method.Name, ' = nil;') else Writeln(F, Indent, 'FuncSet', AClass.Name, LIntf.Name, Method.Name, ' := nil;') end; end; end; WriteSpace; end; procedure TPWIGGenPascal.WriteCallerLibLoads(AClass: TPWIGClass); procedure WriteLibLoad(const AFuncName: string); begin Writeln(F, Indent, 'Func', AFuncName, ' := GetProcAddress(LibModule, ''', AFuncName, ''');'); Writeln(F, Indent, 'if not Assigned(Func', AFuncName, ') then LibLoadError(''', AFuncName, ''');'); end; var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; begin WriteIntfElementProps(AClass); for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin // use constructor and destructor only for default interface if Ref.FlagDefault then begin Writeln(F, Indent, '// Constructor:'); WriteLibLoad(AClass.Name + 'Create'); Writeln(F, Indent, '// Destructor:'); WriteLibLoad(AClass.Name + 'Destroy'); end; Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin WriteLibLoad(AClass.Name + LIntf.Name + Method.Name); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteLibLoad(AClass.Name + 'Get' + LIntf.Name + Prop.Name); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteLibLoad(AClass.Name + 'Set' + LIntf.Name + Prop.Name); end; end; end; end; // write event handler setters for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Event handler setters:'); for Method in LIntf.Methods do begin WriteLibLoad('Set' + AClass.Name + LIntf.Name + Method.Name); end; end; end; end; procedure TPWIGGenPascal.WriteCallerImplementations(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; Method: TPWIGMethod; Prop: TPWIGProperty; begin WriteIntfElementProps(AClass); // write event handler callbacks for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Event handler callbacks:'); for Method in LIntf.Methods do begin WriteCallerEventCallback(AClass, LIntf, Method, Ref.FlagDefault); end; end; end; for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if (LIntf <> nil) and not LIntf.FlagDispEvents then begin Writeln(F, Indent, '// Constructor:'); WriteCallerConstructor(AClass, LIntf); Writeln(F, Indent, '// Destructor:'); WriteCallerDestructor(AClass, LIntf); Writeln(F, Indent, '// Methods:'); for Method in LIntf.Methods do begin WriteCallerMethod(AClass, LIntf, Method, Ref.FlagDefault, False, ''); end; Writeln(F, Indent, '// Properties:'); for Prop in LIntf.Properties do begin if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter WriteCallerMethod(AClass, LIntf, Prop, Ref.FlagDefault, True, 'Get'); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter WriteCallerMethod(AClass, LIntf, Prop, Ref.FlagDefault, False, 'Set'); end; end; end; end; WriteSpace; end; function TPWIGGenPascal.WriteCallerUnicodeStringDeclarations( AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString, caller side Result := False; for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); if not Result then begin Writeln(F, Indent, 'var'); IncIndent; end; Result := True; Writeln(F, Indent, 'AnsiString__', ParamName, ': AnsiString; Length__', ParamName, ': LongInt;'); end; if Result then begin DecIndent; end; end; function TPWIGGenPascal.WriteCallerUnicodeStringManagement1( AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString, caller side for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); Writeln(F, Indent, 'Length__', ParamName, ' := 0;'); end; Result := True; end; function TPWIGGenPascal.WriteCallerUnicodeStringManagement2( AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param: TPWIGParam; ParamName: string; begin // automated string management for UnicodeString for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); Writeln(F, Indent, 'SetLength(AnsiString__', ParamName, ', Max(Length__', ParamName, ', 1));'); end; Result := True; end; function TPWIGGenPascal.WriteCallerUnicodeStringManagement3( AMethod: TPWIGMethod; AGetter: Boolean): Boolean; var Param, RetVal: TPWIGParam; ParamName, S: string; begin // automated string management for UnicodeString if AGetter then RetVal := AMethod.Params.Last else RetVal := AMethod.Params.FindRetVal; for Param in AMethod.Params do if (Param.ParamType.BaseType = btUnicodeString) and (ParamDirection(AMethod, Param, AGetter) <> pdIn) then begin ParamName := ReplaceNotAllowedParamName(Param.Name); if Param <> RetVal then S := ParamName else S := 'Result'; Writeln(F, Indent, 'if Length__', ParamName, ' > 0 then ', S, ' := LibUtf8String2String(AnsiString__', ParamName, ') else ', S, ' := '''';') end; Result := True; end; procedure TPWIGGenPascal.WriteInterfaceFile(const AFileName: string); var LIntf: TPWIGInterface; LCls: TPWIGClass; LAlias: TPWIGAlias; LEnum: TPWIGEnum; Name, Path, Ext, GeneratedFile, IntfName: string; begin Path := ExtractFilePath(AFileName); Name := ExtractFileRawName(AFileName); Ext := ExtractFileExt(AFileName); // write interface file (usable both for callee and for caller) IntfName := Name + '_intf'; GeneratedFile := Path + IntfName + Ext; AssignFile(F, GeneratedFile); try try Rewrite(F); // write file header (warning etc.) Writeln(F, Indent, '// ************************************************************************'); Writeln(F, Indent, '// This file contains common interface for both the caller and the callee.'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// WARNING'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// This file was generated by PWIG. Do not edit.'); Writeln(F, Indent, '// File generated on ', DateTimeToStr(Now)); WriteSpace; // begin to write library Writeln(F, Indent, 'unit ', IntfName, ';'); WriteSpace; Writeln(F, Indent, '{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}'); Writeln(F, Indent, '{$MINENUMSIZE 4} // needed for correct interop with .NET'); WriteSpace; Writeln(F, Indent, '// Library properties:'); WriteIntfElementProps(FPWIG); // interface Writeln(F, Indent, 'interface'); WriteSpace; // write uses clause // now hardcoded, later might be automated when needed Writeln(F, Indent, 'uses'); IncIndent; Writeln(F, Indent, 'SysUtils;'); DecIndent; WriteSpace; // write library ID Writeln(F, Indent, 'const'); IncIndent; Writeln(F, Indent, 'cLibGUID = ''', FPWIG.GUID, ''';'); DecIndent; WriteSpace; Writeln(F, Indent, 'type'); WriteSpace; IncIndent; // write forward declarations Writeln(F, Indent, '// Forward declarations:'); for LIntf in FPWIG.Interfaces do Writeln(F, Indent, LIntf.Name, ' = type Int64;'); WriteSpace; // write enums for LEnum in FPWIG.Enums do WriteIntfEnumProps(LEnum); // write aliases for LAlias in FPWIG.Aliases do WriteIntfAliasProps(LAlias); // write interfaces for LIntf in FPWIG.Interfaces do WriteIntfInterfaceProps(LIntf); // write classes for LCls in FPWIG.Classes do WriteIntfClassProps(LCls); Writeln(F, Indent, '// Library helper functions'); Writeln(F, Indent, 'function String2LibUtf8String(const AText: string): AnsiString;'); Writeln(F, Indent, 'function LibUtf8String2String(const AText: AnsiString): string;'); WriteSpace; // end of interface DecIndent; // implementation Writeln(F, Indent, 'implementation'); WriteSpace; Writeln(F, Indent, 'function String2LibUtf8String(const AText: string): AnsiString;'); WritePascalBegin; Writeln(F, Indent, '{$IFDEF FPC}'); Writeln(F, Indent, 'Result := AText; // FPC string is UTF8 by default'); Writeln(F, Indent, '{$ELSE}'); Writeln(F, Indent, 'Result := UTF8Encode(AText);'); Writeln(F, Indent, '{$ENDIF}'); WritePascalEnd; WriteSpace; Writeln(F, Indent, 'function LibUtf8String2String(const AText: AnsiString): string;'); WritePascalBegin; Writeln(F, Indent, '{$IFDEF FPC}'); Writeln(F, Indent, 'Result := AText; // FPC string is UTF8 by default'); Writeln(F, Indent, '{$ELSE}'); Writeln(F, Indent, 'Result := UTF8ToString(AText);'); Writeln(F, Indent, '{$ENDIF}'); WritePascalEnd; WriteSpace; // finish Writeln(F, Indent, 'end.'); Writeln('Pascal common interface file generated: ', GeneratedFile); except Writeln('Could not generate Pascal common interface file: ', GeneratedFile); end; finally CloseFile(F); end; end; procedure TPWIGGenPascal.WriteCalleeFile(const AFileName: string); var LCls: TPWIGClass; LIntf: TPWIGInterface; Name, Path, Ext, GeneratedFile, IntfName, ImplName: string; begin Path := ExtractFilePath(AFileName); Name := ExtractFileRawName(AFileName); Ext := ExtractFileExt(AFileName); // write wrapper file for the callee IntfName := Name + '_intf'; ImplName := Name + '_callee'; GeneratedFile := Path + ImplName + Ext; AssignFile(F, GeneratedFile); try try Rewrite(F); // write file header (warning etc.) Writeln(F, Indent, '// ************************************************************************'); Writeln(F, Indent, '// This file implements library exports for the callee.'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// WARNING'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// This file was generated by PWIG. Do not edit.'); Writeln(F, Indent, '// File generated on ', DateTimeToStr(Now)); WriteSpace; // begin to write library Writeln(F, Indent, 'unit ', ImplName, ';'); WriteSpace; Writeln(F, Indent, '{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}'); WriteSpace; Writeln(F, Indent, '// Library properties:'); WriteIntfElementProps(FPWIG); // interface Writeln(F, Indent, 'interface'); WriteSpace; // write uses clause // now hardcoded, later might be automated when needed Writeln(F, Indent, 'uses'); IncIndent; Writeln(F, Indent, 'Classes, ', IntfName, ';'); DecIndent; WriteSpace; ImplName := ImplName + '_impl'; // entire declaration part is commented out because the classes must be implemented in other file Writeln(F, Indent, '// Copy these class declarations into ', ImplName, '.pas and implement them there.'); Writeln(F, Indent, '// Note: ', ImplName, '.pas is not maintained by PWIG and must be implemented by library author!'); Writeln(F, Indent, '(*'); Writeln(F, Indent, 'type'); WriteSpace; IncIndent; // write forward declarations Writeln(F, Indent, '// Forward declarations:'); for LCls in FPWIG.Classes do Writeln(F, Indent, 'T', LCls.Name, ' = class;'); WriteSpace; // write class interfaces (implementation must be done by library author) for LCls in FPWIG.Classes do WriteCalleeDeclarations(LCls); // end of commented out section DecIndent; Writeln(F, Indent, '// End of declarations to be copied to ', ImplName, '.pas file.'); Writeln(F, Indent, '*)'); WriteSpace; // write event sink wrapper classes for LIntf in FPWIG.Interfaces do if LIntf.FlagDispEvents then WriteCalleeEventSinkDeclarations(LIntf); // write library identification code - interface part Writeln(F, Indent, '// Library identification code'); Writeln(F, Indent, 'function GetLibGUID: PAnsiChar; ', CallingConvToString(nil),';'); WriteSpace; // write exported function declarations for LCls in FPWIG.Classes do WriteCalleeExportedFuncs(LCls, False); WriteSpace; // implementation Writeln(F, Indent, 'implementation'); WriteSpace; // write uses clause // now hardcoded, later might be automated when needed Writeln(F, Indent, 'uses'); IncIndent; Writeln(F, Indent, 'Math, SysUtils', ', ', ImplName, ';'); DecIndent; WriteSpace; // write library identification code - implementation part Writeln(F, Indent, '// Library identification code'); Writeln(F, Indent, 'function GetLibGUID: PAnsiChar; ', CallingConvToString(nil),';'); WritePascalBegin; Writeln(F, Indent, 'Result := cLibGUID;'); WritePascalEnd; WriteSpace; // write exported function bodies for LCls in FPWIG.Classes do WriteCalleeExportedFuncs(LCls, True); // write event sink wrapper classes for LIntf in FPWIG.Interfaces do if LIntf.FlagDispEvents then WriteCalleeEventSinkImplementations(LIntf); // write library exports Writeln(F, Indent, '// Copy these exports into your main library file.'); Writeln(F, Indent, '// This is needed because of FPC bug #tbd.'); Writeln(F, Indent, '(*'); Writeln(F, Indent, 'exports'); IncIndent; InitDashSep; WriteDashSep; Writeln(F, Indent, 'GetLibGUID'); for LCls in FPWIG.Classes do WriteCalleeExports(LCls); Writeln(F, Indent, ';'); DecIndent; Writeln(F, Indent, '*)'); WriteSpace; // finish Writeln(F, Indent, 'end.'); Writeln('Pascal callee interface file generated: ', GeneratedFile); except Writeln('Could not generate Pascal callee interface file: ', GeneratedFile); end; finally CloseFile(F); end; end; procedure TPWIGGenPascal.WriteCallerFile(const AFileName: string); var LCls: TPWIGClass; Name, Path, Ext, GeneratedFile, IntfName, ImplName: string; begin Path := ExtractFilePath(AFileName); Name := ExtractFileRawName(AFileName); Ext := ExtractFileExt(AFileName); // write wrapper file for the caller IntfName := Name + '_intf'; ImplName := Name + '_caller'; GeneratedFile := Path + ImplName + Ext; AssignFile(F, GeneratedFile); try try Rewrite(F); // write file header (warning etc.) Writeln(F, Indent, '// ************************************************************************'); Writeln(F, Indent, '// This file implements library imports for the caller.'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// WARNING'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// This file was generated by PWIG. Do not edit.'); Writeln(F, Indent, '// File generated on ', DateTimeToStr(Now)); WriteSpace; // begin to write library Writeln(F, Indent, 'unit ', ImplName, ';'); WriteSpace; Writeln(F, Indent, '{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}'); WriteSpace; Writeln(F, Indent, '// Library properties:'); WriteIntfElementProps(FPWIG); // interface Writeln(F, Indent, 'interface'); WriteSpace; // write uses clause // now hardcoded, later might be automated when needed Writeln(F, Indent, 'uses'); IncIndent; Writeln(F, Indent, '{$IFDEF FPC}'); Writeln(F, Indent, 'DynLibs,'); Writeln(F, Indent, '{$ELSE}'); Writeln(F, Indent, '{$IFDEF MSWINDOWS}'); Writeln(F, Indent, 'Windows,'); Writeln(F, Indent, '{$ENDIF}'); Writeln(F, Indent, '{$ENDIF}'); Writeln(F, Indent, IntfName, ';'); DecIndent; WriteSpace; Writeln(F, Indent, 'type'); WriteSpace; IncIndent; // write forward declarations Writeln(F, Indent, '// Forward declarations:'); for LCls in FPWIG.Classes do Writeln(F, Indent, 'T', LCls.Name, ' = class;'); WriteSpace; // write class interfaces for LCls in FPWIG.Classes do WriteCallerDeclarations(LCls); // library loader Writeln(F, Indent, 'function ', FPWIG.Name, 'LibLoad(const FileName: string): Boolean;'); // library unloader Writeln(F, Indent, 'procedure ', FPWIG.Name, 'LibUnload;'); // library load error string (FPC only) Writeln(F, Indent, 'var LibLoadErrorMsg: string;'); // end of interface DecIndent; // implementation Writeln(F, Indent, 'implementation'); WriteSpace; // write uses clause // now hardcoded, later might be automated when needed Writeln(F, Indent, 'uses'); IncIndent; Writeln(F, Indent, 'Math, SysUtils;'); DecIndent; WriteSpace; // write library imports Writeln(F, Indent, 'const'); IncIndent; Writeln(F, Indent, 'LibModule: HMODULE = 0;'); for LCls in FPWIG.Classes do WriteCallerPointers(LCls, True); DecIndent; // write library generous error function Writeln(F, Indent, 'procedure LibError(const AMessage: string);'); WritePascalBegin; Writeln(F, Indent, 'raise Exception.Create(AMessage);'); WritePascalEnd; WriteSpace; // write library calling error function Writeln(F, Indent, 'procedure LibCallError(const AFuncName: string);'); WritePascalBegin; Writeln(F, Indent, 'LibError(Format(''Error while calling library function %s!'', [AFuncName]));'); WritePascalEnd; WriteSpace; // write library loading error function Writeln(F, Indent, 'procedure LibLoadError(const AFuncName: string);'); WritePascalBegin; Writeln(F, Indent, 'LibError(Format(''Requested function %s does not exist in the library!'', [AFuncName]));'); WritePascalEnd; WriteSpace; // write library loader implementation Writeln(F, Indent, 'function ', FPWIG.Name, 'LibLoad(const FileName: string): Boolean;'); Writeln(F, Indent, 'type'); IncIndent; Writeln(F, Indent, 'T_FuncLibID = function: PAnsichar; ' + CallingConvToString(nil) + ';'); DecIndent; Writeln(F, Indent, 'var'); IncIndent; Writeln(F, Indent, '_FuncLibID: T_FuncLibID;'); DecIndent; WritePascalBegin; Writeln(F, Indent, 'Result := False;'); WriteTry; Writeln(F, Indent, 'if LibModule = 0 then'); WritePascalBegin; Writeln(F, Indent, 'LibModule := LoadLibrary({$IFnDEF FPC}PChar{$ENDIF}(FileName));'); Writeln(F, Indent, '{$IFDEF FPC}'); Writeln(F, Indent, 'LibLoadErrorMsg := GetLoadErrorStr;'); Writeln(F, Indent, '{$ENDIF}'); WritePascalEnd; Writeln(F, Indent, 'if LibModule <> 0 then'); WritePascalBegin; Writeln(F, Indent, '// Call library identification code first'); Writeln(F, Indent, '_FuncLibID := GetProcAddress(LibModule, ''GetLibGUID'');'); Writeln(F, Indent, 'if not Assigned(_FuncLibID) then LibLoadError(''GetLibGUID'');'); Writeln(F, Indent, 'if _FuncLibID <> cLibGUID then LibError(''Incompatible library interface!'');'); WriteSpace; for LCls in FPWIG.Classes do WriteCallerLibLoads(LCls); Writeln(F, Indent, 'Result := True;'); WritePascalEnd; WriteExcept; WritePascalEnd; WriteSpace; // write library unloader implementation Writeln(F, Indent, 'procedure ', FPWIG.Name, 'LibUnload;'); WritePascalBegin; Writeln(F, Indent, 'if LibModule <> 0 then'); IncIndent; Writeln(F, Indent, 'FreeLibrary(LibModule);'); DecIndent; Writeln(F, Indent, 'LibModule := 0;'); for LCls in FPWIG.Classes do WriteCallerPointers(LCls, False); WritePascalEnd; WriteSpace; // write class method bodies for LCls in FPWIG.Classes do WriteCallerImplementations(LCls); // finish Writeln(F, Indent, 'end.'); Writeln('Pascal caller interface file generated: ', GeneratedFile); except Writeln('Could not generate Pascal caller interface file: ', GeneratedFile); end; finally CloseFile(F); end; end; end.
unit RenameForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, FileCtrl; const DEFAULTBASE = 'File_'; type TFormRename = class(TForm) PanelTop: TPanel; ListViewMain: TListView; StatusBarMain: TStatusBar; EditBase: TEdit; LabelBase: TLabel; RadioGroupExt: TRadioGroup; PanelBottom: TPanel; ButtonGo: TButton; GroupBoxNum: TGroupBox; ComboBoxDigits: TComboBox; EditStart: TEdit; LabelStart: TLabel; LabelDigits: TLabel; TimerBuildWait: TTimer; CheckBoxClose: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ButtonGoClick(Sender: TObject); procedure EditStartKeyPress(Sender: TObject; var Key: Char); procedure ComboBoxDigitsChange(Sender: TObject); procedure RadioGroupExtClick(Sender: TObject); procedure EditBaseKeyPress(Sender: TObject; var Key: Char); procedure TimerBuildWaitTimer(Sender: TObject); private Path: String; Start: Integer; FormatStr: String; ListChanged: Boolean; Renamed: Boolean; procedure Status(S: String); procedure SuggestBase; procedure GetFormat; function NewName(FileName: String; Cnt: Integer): String; procedure BuildList; procedure RenameAll; procedure ResetBuildWait; public procedure AssignList(FileListBox: TFileListBox); end; var FormRename: TFormRename; implementation {$R *.DFM} uses Utils; function HTTPSafe(S: String): String; var Len, Index: Integer; C: Char; begin Len := Length(S); Index := 1; Result := ''; while (Index <= Len) do begin C := S[Index]; case C of '0'..'9', 'A'..'Z', 'a'..'z', '-', '_': Result := Result + C; ' ': Result := Result + '_'; end; inc(Index); end; end; procedure TFormRename.SuggestBase; var Len, Index: Integer; Base: String; begin Len := Length(Path); Index := Len; while (Index > 1) and (Path[Index - 1] <> '\') do dec(Index); Base := HTTPSafe(Copy(Path, Index, Len - Index)); if (Length(Base) > 0) then EditBase.Text := Base + '_' else EditBase.Text := DEFAULTBASE; end; function TFormRename.NewName(FileName: String; Cnt: Integer): String; var Len, Index: Integer; Ext: String; begin Len := Length(FileName); Index := Len; while (Index > 0) and (FileName[Index] <> '.') do dec(Index); if (Index > 0) then begin Ext := Copy(FileName, Index, Len - Index + 1); case RadioGroupExt.ItemIndex of 0: Ext := Lowercase(Ext); 1: Ext := Uppercase(Ext); end; end else Ext := ''; Result := Format(FormatStr, [Start + Cnt, Ext]); end; procedure TFormRename.Status(S: String); begin StatusBarMain.SimpleText := S; end; procedure TFormRename.GetFormat; var Code: Integer; begin Val(EditStart.Text, Start, Code); if (Code <> 0) then Start := 0; FormatStr := Format('%s%%.%sd%%s', [EditBase.Text, ComboBoxDigits.Text]); end; procedure TFormRename.AssignList(FileListBox: TFileListBox); var Cnt: Integer; ListItem: TListItem; begin ListViewMain.Items.Clear; ButtonGo.Enabled := True; Path := FileListBox.Directory; if (Path[Length(Path)] <> '\') then Path := Path + '\'; SuggestBase; Caption := 'Rename - ' + Path; GetFormat; for Cnt := 0 to FileListBox.Items.Count - 1 do begin ListItem := ListViewMain.Items.Add; ListItem.Caption := FileListBox.Items.Strings[Cnt]; ListItem.SubItems.Add(NewName(ListItem.Caption, Cnt)); end; ListChanged := False; Renamed := False; Status(ItemCount(FileListBox.Items.Count, 'file')); end; procedure TFormRename.FormCreate(Sender: TObject); begin ComboBoxDigits.ItemIndex := 2; end; procedure TFormRename.FormClose(Sender: TObject; var Action: TCloseAction); begin if Renamed then ModalResult := mrOK else Action := caHide; end; procedure TFormRename.BuildList; var Cnt: Integer; ListItem: TListItem; begin TimerBuildWait.Enabled := False; GetFormat; for Cnt := 0 to ListViewMain.Items.Count - 1 do begin ListItem := ListViewMain.Items.Item[Cnt]; ListItem.SubItems.Strings[0] := NewName(ListItem.Caption, Cnt); end; ListChanged := False; end; procedure TFormRename.RenameAll; var Cnt: Integer; ListItem: TListItem; Src, Dest: String; F: File; Confs: Integer; begin ButtonGo.Enabled := False; Status('Renaming...'); Confs := 0; for Cnt := 0 to ListViewMain.Items.Count - 1 do begin ListItem := ListViewMain.Items.Item[Cnt]; Src := Path + ListItem.Caption; if FileExists(Src) then begin Dest := Path + ListItem.SubItems.Strings[0]; if FileExists(Dest) then begin Dest := Dest + '.dup'; inc(Confs); end; AssignFile(F, Src); Rename(F, Dest); end; end; // if (Confs > 0) then // RestoreConfs; Renamed := True; if CheckBoxClose.Checked then Close else begin Status('Rename operation complete with ' + ItemCount(Confs, 'conflict')); ButtonGo.Enabled := True; end; end; procedure TFormRename.ButtonGoClick(Sender: TObject); begin if ListChanged then BuildList; if (MessageDlg('Rename these files?', mtConfirmation, mbOKCancel, 0) = mrOK) then RenameAll; end; procedure TFormRename.EditStartKeyPress(Sender: TObject; var Key: Char); begin if not (Key in [#8, '0'..'9']) then Key := #0; ResetBuildWait; end; procedure TFormRename.ComboBoxDigitsChange(Sender: TObject); begin BuildList; end; procedure TFormRename.RadioGroupExtClick(Sender: TObject); begin BuildList; end; procedure TFormRename.EditBaseKeyPress(Sender: TObject; var Key: Char); begin if (Key in ['\', '/', ':', '*', '?', '"', '<', '>', '|']) then Key := #0; ResetBuildWait; end; procedure TFormRename.ResetBuildWait; begin TimerBuildWait.Enabled := False; TimerBuildWait.Enabled := True; ListChanged := True; end; procedure TFormRename.TimerBuildWaitTimer(Sender: TObject); begin BuildList; end; end.
unit dwsWebServerLibModule; interface uses SysUtils, Classes, dwsComp, dwsExprs, dwsWebServerInfo; type TdwsWebServerLib = class(TDataModule) dwsWebServer: TdwsUnit; procedure dwsWebServerClassesWebServerMethodsNameEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsWebServerClassesWebServerMethodsHttpPortEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebServerClassesWebServerMethodsHttpsPortEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsWebServerClassesWebServerMethodsAuthenticationsEval( Info: TProgramInfo; ExtObject: TObject); private { Private declarations } FServer : IWebServerInfo; public { Public declaration } property Server : IWebServerInfo read FServer write FServer; end; implementation {$R *.dfm} procedure TdwsWebServerLib.dwsWebServerClassesWebServerMethodsAuthenticationsEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=0; end; procedure TdwsWebServerLib.dwsWebServerClassesWebServerMethodsHttpPortEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=FServer.HttpPort; end; procedure TdwsWebServerLib.dwsWebServerClassesWebServerMethodsHttpsPortEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=FServer.HttpsPort; end; procedure TdwsWebServerLib.dwsWebServerClassesWebServerMethodsNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=FServer.Name; end; end.
unit ETL.FileProject.Interfaces; interface uses ETL.Form.Grid, uList; type ISourceETL = interface ['{8D0C91ED-10E1-4C14-9E35-7A01237BD8A4}'] function GetID: string; function GetGrid: TFoGrid; end; IListSources = interface(IList<ISourceETL>) ['{65B200A3-F463-43D7-9F70-3AFA7881B6FB}'] end; TListSources = class(TInterfacedList<ISourceETL>, IListSources); IComponentETL = interface(ISourceETL) ['{EF7C533C-DE01-4BD9-87E3-4A4E31A7ABB5}'] function getTitle: string; procedure setTitle(const ATitle: string); procedure setPosition(const Ax, Ay: Integer); procedure setScript(const AScript: string); function GetKind: Integer; function GetLeft: Integer; function GetTop: Integer; function getScript: string; function GetSources: IListSources; procedure AddSource(const ASource: IComponentETL); procedure Delete; property Title: string read getTitle write setTitle; property Script: string read getScript write setScript; end; TInterfacedListComponentsETL = class(TInterfacedList<IComponentETL>); IListComponentsETL = interface(IList<IComponentETL>) ['{829D88B9-7255-40AB-8486-2BCE1A6112AC}'] function Locate(const AId: string): IComponentETL; function GenerateTitle(APrefix: string): string; end; IComponentExtract = interface(IComponentETL) ['{06C636E3-93E2-420B-AD22-CD3F5B4C9F83}'] end; IComponentTransform = interface(IComponentETL) ['{FCB1B851-02E5-4768-9903-763034678F39}'] end; IComponentLoad = interface(IComponentETL) ['{AA5EB842-3CF8-4E57-81D0-520929331B4D}'] end; IProjectETL = interface ['{14B85495-D30F-45B6-BBE9-36438F0E0094}'] function getListComponents: IListComponentsETL; function getFileName: string; procedure setFileName(const AFileName: string); property FileName: string read getFileName write setFileName; end; implementation end.
unit DIOTA.Dto.Request.GetTrytesRequest; interface uses System.Classes, REST.Client, System.JSON.Builders, DIOTA.IotaAPIClasses; type TGetTrytesRequest = class(TIotaAPIRequest) private FHashes: TStrings; protected function GetCommand: String; override; function BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; override; public constructor Create(ARESTClient: TCustomRESTClient; ATimeout: Integer; AHashes: TStrings); reintroduce; virtual; end; implementation { TGetTrytesRequest } constructor TGetTrytesRequest.Create(ARESTClient: TCustomRESTClient; ATimeout: Integer; AHashes: TStrings); begin inherited Create(ARESTClient, ATimeout); FHashes := AHashes; end; function TGetTrytesRequest.GetCommand: String; begin Result := 'getTrytes'; end; function TGetTrytesRequest.BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; var AElements: TJSONCollectionBuilder.TElements; AHash: String; begin if Assigned(FHashes) then begin AElements := JsonBuilder.BeginArray('hashes'); for AHash in FHashes do AElements := AElements.Add(AHash); AElements.EndArray; end; Result := JsonBuilder; end; end.
unit UValidator; interface function IsNumber(S: string): Boolean; function IsValidCpf(CPF: String): Boolean; function IsValidCep(CEP: String): Boolean; function IsValidPhone(Phone: String): Boolean; function UnmaskNumber(Number: String): String; function ParseNumber(Number: String): Double; implementation uses System.RegularExpressions, System.SysUtils; const CPF_REGEX_MASK = '\d{3}\.\d{3}\.\d{3}\-\d{2}'; CEP_REGEX_MASK = '\d{5}\-\d{3}'; PHONE_DDD_REGEX_MASK = '\(\d{2}\) \d{8}'; PHONE_DDD_9_REGEX_MASK = '\(\d{2}\) \d{9}'; function IsNumber(S: string): Boolean; var P: PChar; begin P := PChar(S); Result := False; while P^ <> #0 do begin if not(P^ in ['0' .. '9']) then Exit; Inc(P); end; Result := True; end; function IsValidCpf(CPF: String): Boolean; begin Result := TRegEx.Match(CPF, CPF_REGEX_MASK).Success; end; function IsValidCep(CEP: String): Boolean; begin Result := TRegEx.Match(CEP, CEP_REGEX_MASK).Success; end; function IsValidPhone(Phone: String): Boolean; begin Result := (TRegEx.Match(Phone, PHONE_DDD_REGEX_MASK).Success) or (TRegEx.Match(Phone, PHONE_DDD_9_REGEX_MASK).Success); end; function UnmaskNumber(Number: String): String; begin Result := StringReplace(Number, '.', '', [rfReplaceAll]); end; function ParseNumber(Number: String): Double; var Buffer: String; begin Buffer := StringReplace(Number, '.', '', [rfReplaceAll]); Buffer := StringReplace(Buffer, 'R$ ', '', [rfReplaceAll]); Buffer := StringReplace(Buffer, '-', '', [rfReplaceAll]); // Buffer := StringReplace(Buffer, ',', '.', [rfReplaceAll]); Result := StrToFloat(Buffer); end; end.
unit ManagerOcxLib_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 52393 $ // File generated on 2014/11/11 0:08:30 from Type Library described below. // ************************************************************************ // // Type Lib: C:\Users\Ετ\Desktop\ProjectManagerGroup\ManagerOcx\ManagerOcxLib (1) // LIBID: {CE914976-E292-48F4-9DC1-1E26AACFEAB9} // LCID: 0 // Helpfile: // HelpString: // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // (2) v4.0 StdVCL, (stdvcl40.dll) // (3) v1.0 RTXCMODULEINTERFACELib, (D:\Program Files (x86)\Tencent\RTXC\RTXCModuleInterface.dll) // SYS_KIND: SYS_WIN32 // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Winapi.Windows, RTXCMODULEINTERFACELib_TLB, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleCtrls, Winapi.ActiveX; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions ManagerOcxLibMajorVersion = 1; ManagerOcxLibMinorVersion = 0; LIBID_ManagerOcxLib: TGUID = '{CE914976-E292-48F4-9DC1-1E26AACFEAB9}'; IID_IProjectManagerTab: TGUID = '{5DC0FD40-5A62-4F93-98EF-BF43AFCC4430}'; DIID_IProjectManagerTabEvents: TGUID = '{4C05950F-A4F9-4193-8189-4448AA699DBE}'; CLASS_ProjectManagerTab: TGUID = '{6FA77186-AF8D-4B6B-AC5C-6B25F29AA5E0}'; // *********************************************************************// // Declaration of Enumerations defined in Type Library // *********************************************************************// // Constants for enum TxActiveFormBorderStyle type TxActiveFormBorderStyle = TOleEnum; const afbNone = $00000000; afbSingle = $00000001; afbSunken = $00000002; afbRaised = $00000003; // Constants for enum TxPrintScale type TxPrintScale = TOleEnum; const poNone = $00000000; poProportional = $00000001; poPrintToFit = $00000002; // Constants for enum TxMouseButton type TxMouseButton = TOleEnum; const mbLeft = $00000000; mbRight = $00000001; mbMiddle = $00000002; // Constants for enum TxPopupMode type TxPopupMode = TOleEnum; const pmNone = $00000000; pmAuto = $00000001; pmExplicit = $00000002; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IProjectManagerTab = interface; IProjectManagerTabDisp = dispinterface; IProjectManagerTabEvents = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// ProjectManagerTab = IProjectManagerTab; // *********************************************************************// // Declaration of structures, unions and aliases. // *********************************************************************// PPUserType1 = ^IFontDisp; {*} // *********************************************************************// // Interface: IProjectManagerTab // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {5DC0FD40-5A62-4F93-98EF-BF43AFCC4430} // *********************************************************************// IProjectManagerTab = interface(IDispatch) ['{5DC0FD40-5A62-4F93-98EF-BF43AFCC4430}'] function Get_Visible: WordBool; safecall; procedure Set_Visible(Value: WordBool); safecall; function Get_AutoScroll: WordBool; safecall; procedure Set_AutoScroll(Value: WordBool); safecall; function Get_AutoSize: WordBool; safecall; procedure Set_AutoSize(Value: WordBool); safecall; function Get_AxBorderStyle: TxActiveFormBorderStyle; safecall; procedure Set_AxBorderStyle(Value: TxActiveFormBorderStyle); safecall; function Get_BorderWidth: Integer; safecall; procedure Set_BorderWidth(Value: Integer); safecall; function Get_Caption: WideString; safecall; procedure Set_Caption(const Value: WideString); safecall; function Get_Color: OLE_COLOR; safecall; procedure Set_Color(Value: OLE_COLOR); safecall; function Get_Font: IFontDisp; safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure _Set_Font(var Value: IFontDisp); safecall; function Get_KeyPreview: WordBool; safecall; procedure Set_KeyPreview(Value: WordBool); safecall; function Get_PixelsPerInch: Integer; safecall; procedure Set_PixelsPerInch(Value: Integer); safecall; function Get_PrintScale: TxPrintScale; safecall; procedure Set_PrintScale(Value: TxPrintScale); safecall; function Get_Scaled: WordBool; safecall; procedure Set_Scaled(Value: WordBool); safecall; function Get_Active: WordBool; safecall; function Get_DropTarget: WordBool; safecall; procedure Set_DropTarget(Value: WordBool); safecall; function Get_HelpFile: WideString; safecall; procedure Set_HelpFile(const Value: WideString); safecall; function Get_PopupMode: TxPopupMode; safecall; procedure Set_PopupMode(Value: TxPopupMode); safecall; function Get_ScreenSnap: WordBool; safecall; procedure Set_ScreenSnap(Value: WordBool); safecall; function Get_SnapBuffer: Integer; safecall; procedure Set_SnapBuffer(Value: Integer); safecall; function Get_DockSite: WordBool; safecall; procedure Set_DockSite(Value: WordBool); safecall; function Get_DoubleBuffered: WordBool; safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; function Get_AlignDisabled: WordBool; safecall; function Get_MouseInClient: WordBool; safecall; function Get_VisibleDockClientCount: Integer; safecall; function Get_ParentDoubleBuffered: WordBool; safecall; procedure Set_ParentDoubleBuffered(Value: WordBool); safecall; function Get_UseDockManager: WordBool; safecall; procedure Set_UseDockManager(Value: WordBool); safecall; function Get_Enabled: WordBool; safecall; procedure Set_Enabled(Value: WordBool); safecall; function Get_ExplicitLeft: Integer; safecall; function Get_ExplicitTop: Integer; safecall; function Get_ExplicitWidth: Integer; safecall; function Get_ExplicitHeight: Integer; safecall; function Get_AlignWithMargins: WordBool; safecall; procedure Set_AlignWithMargins(Value: WordBool); safecall; function Get_ParentCustomHint: WordBool; safecall; procedure Set_ParentCustomHint(Value: WordBool); safecall; property Visible: WordBool read Get_Visible write Set_Visible; property AutoScroll: WordBool read Get_AutoScroll write Set_AutoScroll; property AutoSize: WordBool read Get_AutoSize write Set_AutoSize; property AxBorderStyle: TxActiveFormBorderStyle read Get_AxBorderStyle write Set_AxBorderStyle; property BorderWidth: Integer read Get_BorderWidth write Set_BorderWidth; property Caption: WideString read Get_Caption write Set_Caption; property Color: OLE_COLOR read Get_Color write Set_Color; property Font: IFontDisp read Get_Font write Set_Font; property KeyPreview: WordBool read Get_KeyPreview write Set_KeyPreview; property PixelsPerInch: Integer read Get_PixelsPerInch write Set_PixelsPerInch; property PrintScale: TxPrintScale read Get_PrintScale write Set_PrintScale; property Scaled: WordBool read Get_Scaled write Set_Scaled; property Active: WordBool read Get_Active; property DropTarget: WordBool read Get_DropTarget write Set_DropTarget; property HelpFile: WideString read Get_HelpFile write Set_HelpFile; property PopupMode: TxPopupMode read Get_PopupMode write Set_PopupMode; property ScreenSnap: WordBool read Get_ScreenSnap write Set_ScreenSnap; property SnapBuffer: Integer read Get_SnapBuffer write Set_SnapBuffer; property DockSite: WordBool read Get_DockSite write Set_DockSite; property DoubleBuffered: WordBool read Get_DoubleBuffered write Set_DoubleBuffered; property AlignDisabled: WordBool read Get_AlignDisabled; property MouseInClient: WordBool read Get_MouseInClient; property VisibleDockClientCount: Integer read Get_VisibleDockClientCount; property ParentDoubleBuffered: WordBool read Get_ParentDoubleBuffered write Set_ParentDoubleBuffered; property UseDockManager: WordBool read Get_UseDockManager write Set_UseDockManager; property Enabled: WordBool read Get_Enabled write Set_Enabled; property ExplicitLeft: Integer read Get_ExplicitLeft; property ExplicitTop: Integer read Get_ExplicitTop; property ExplicitWidth: Integer read Get_ExplicitWidth; property ExplicitHeight: Integer read Get_ExplicitHeight; property AlignWithMargins: WordBool read Get_AlignWithMargins write Set_AlignWithMargins; property ParentCustomHint: WordBool read Get_ParentCustomHint write Set_ParentCustomHint; end; // *********************************************************************// // DispIntf: IProjectManagerTabDisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {5DC0FD40-5A62-4F93-98EF-BF43AFCC4430} // *********************************************************************// IProjectManagerTabDisp = dispinterface ['{5DC0FD40-5A62-4F93-98EF-BF43AFCC4430}'] property Visible: WordBool dispid 201; property AutoScroll: WordBool dispid 202; property AutoSize: WordBool dispid 203; property AxBorderStyle: TxActiveFormBorderStyle dispid 204; property BorderWidth: Integer dispid 205; property Caption: WideString dispid -518; property Color: OLE_COLOR dispid -501; property Font: IFontDisp dispid -512; property KeyPreview: WordBool dispid 206; property PixelsPerInch: Integer dispid 207; property PrintScale: TxPrintScale dispid 208; property Scaled: WordBool dispid 209; property Active: WordBool readonly dispid 210; property DropTarget: WordBool dispid 211; property HelpFile: WideString dispid 212; property PopupMode: TxPopupMode dispid 213; property ScreenSnap: WordBool dispid 214; property SnapBuffer: Integer dispid 215; property DockSite: WordBool dispid 216; property DoubleBuffered: WordBool dispid 217; property AlignDisabled: WordBool readonly dispid 218; property MouseInClient: WordBool readonly dispid 219; property VisibleDockClientCount: Integer readonly dispid 220; property ParentDoubleBuffered: WordBool dispid 221; property UseDockManager: WordBool dispid 222; property Enabled: WordBool dispid -514; property ExplicitLeft: Integer readonly dispid 223; property ExplicitTop: Integer readonly dispid 224; property ExplicitWidth: Integer readonly dispid 225; property ExplicitHeight: Integer readonly dispid 226; property AlignWithMargins: WordBool dispid 227; property ParentCustomHint: WordBool dispid 228; end; // *********************************************************************// // DispIntf: IProjectManagerTabEvents // Flags: (0) // GUID: {4C05950F-A4F9-4193-8189-4448AA699DBE} // *********************************************************************// IProjectManagerTabEvents = dispinterface ['{4C05950F-A4F9-4193-8189-4448AA699DBE}'] procedure OnActivate; dispid 201; procedure OnClick; dispid 202; procedure OnCreate; dispid 203; procedure OnDblClick; dispid 204; procedure OnDestroy; dispid 205; procedure OnDeactivate; dispid 206; procedure OnKeyPress(var Key: Smallint); dispid 207; procedure OnMouseEnter; dispid 208; procedure OnMouseLeave; dispid 209; procedure OnPaint; dispid 210; end; implementation uses System.Win.ComObj; end.
unit UFunctions; interface Uses Data.Win.ADODB, Vcl.StdCtrls, System.Contnrs; function connect_odbc(db_type, odbc_name: string; adoConnection: TADOConnection): boolean; function query_to_objectlist(sql: string): TObjectList; implementation Uses System.SysUtils,System.Classes, UDataModule, ULogger, ActiveX; function connect_odbc(db_type, odbc_name: string; adoConnection: TADOConnection): boolean; var cn_str: string; conn_str: string; begin if odbc_name = '' then begin Result := false; end else begin conn_str := 'Provider=MSDASQL.1;Persist Security Info=False;Data Source=ODBCREPLACE;'; log(conn_str); try log('Conectando WINFARMA con ODBC: ' + odbc_name); CoInitialize(nil); cn_str := StringReplace(conn_str, 'ODBCREPLACE', odbc_name, []); adoConnection.Connected := false; adoConnection.ConnectionString:= cn_str; adoConnection.Connected := true; Result := true; except on E : Exception do begin log('Error conectado ODBC: ' + e.Message); log('Cadena de conexion ' + cn_str); Result := false; end; end; end; end; function query_to_objectlist(sql: string): TObjectList; var line_sl: TStringList; I: Integer; field: string; value: string; query: TAdoQuery; count: Extended; l: TObjectList; begin query := dm.ADOQuery; l := TObjectList.create; query.SQL.Clear; query.SQL.Add(sql); try query.Open; except on E:Exception do begin log('Error ejecutando: ' + query.SQL.Text); log('Excepcion: ' + E.Message); end; end; count := query.RecordCount; while not query.eof do begin line_sl := TStringList.Create; for I := 0 to query.Fields.Count - 1 do begin field := trim(query.Fields.Fields[I].FieldName); value := trim(query.FieldByName(query.Fields.Fields[I].FieldName).AsString); if value = '' then begin value := ' '; end; line_sl.Values[lowercase(field)] := StringReplace(value, '"', '''', [rfReplaceAll]); end; query.Next; l.Add(line_sl); end; query.Close; Result := l; end; end.
unit UFrameSaleCard; {$I Link.Inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, ComCtrls, ExtCtrls, Buttons, StdCtrls, USelfHelpConst, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxDropDownEdit, dxGDIPlusClasses, jpeg, cxCheckBox, IdHttp, uSuperObject; const cHttpTimeOut = 10; type TfFrameSaleCard = class(TfFrameBase) Pnl_OrderInfo: TPanel; lvOrders: TListView; BtnSave: TSpeedButton; PrintHY: TcxCheckBox; procedure lvOrdersClick(Sender: TObject); procedure BtnSaveClick(Sender: TObject); private { Private declarations } FListA, FListB, FListC, FListD: TStrings; FSaleOrderItems : array of TOrderInfoItem; //订单数组 FSaleOrderItem : TOrderInfoItem; FLastQuery: Int64; //上次查询 private procedure LoadNcSaleList(nSTDid, nPassword: string); procedure InitListView; procedure AddListViewItem(var nSaleOrderItem: TOrderInfoItem); procedure InitUIData(nSTDid, nPassword: string); //初始化信息 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; function DealCommand(Sender: TObject; const nCmd: Integer; const nParamA: Pointer; const nParamB: Integer): Integer; override; {*处理命令*} end; var fFrameSaleCard: TfFrameSaleCard; implementation {$R *.dfm} uses ULibFun, USysLoger, UDataModule, UMgrControl, USysBusiness, UMgrTTCEDispenser, USysDB, UBase64; //------------------------------------------------------------------------------ //Desc: 记录日志 procedure WriteLog(const nEvent: string); begin gSysLoger.AddLog(TfFrameSaleCard, 'ERP 销售制卡', nEvent); end; class function TfFrameSaleCard.FrameID: Integer; begin Result := cFI_FrameSaleMakeCard; end; procedure TfFrameSaleCard.OnCreateFrame; begin FLastQuery:= 0; {$IFDEF PrintHYEach} PrintHY.Checked := False; PrintHY.Visible := True; {$ELSE} PrintHY.Checked := False; PrintHY.Visible := False; {$ENDIF} DoubleBuffered := True; FListA := TStringList.Create; FListB := TStringList.Create; FListC := TStringList.Create; FListD := TStringList.Create; end; procedure TfFrameSaleCard.OnDestroyFrame; begin FListA.Free; FListB.Free; FListC.Free; FListD.Free; end; procedure TfFrameSaleCard.LoadNcSaleList(nSTDid, nPassword: string); var nCount, i : Integer; nAutoPD: string; begin FListA.Clear; FListA.Text:= DecodeBase64(GetNcSaleList(nSTDid, nPassword)); if FListA.Text='' then begin ShowMsg('未能查询到销售订单列表', sHint); Exit; end; nAutoPD := GetPDModelFromDB; try nCount := FListA.Count; SetLength(FSaleOrderItems, nCount); for i := 0 to nCount-1 do begin FListB.Text := DecodeBase64(FListA.Strings[i]); //*********************** FSaleOrderItems[i].FOrders := FListB.Values['PK']; FSaleOrderItems[i].FZhiKaNo := FListB.Values['ZhiKa']; FSaleOrderItems[i].FCusID := FListB.Values['CusID']; FSaleOrderItems[i].FCusName := FListB.Values['CusName']; FSaleOrderItems[i].FStockID := FListB.Values['StockNo']; FSaleOrderItems[i].FStockName:= FListB.Values['StockName']; FSaleOrderItems[i].FStockBrand := FListB.Values['Brand']; FSaleOrderItems[i].FStockArea:= FListB.Values['SaleArea']; FSaleOrderItems[i].FValue := StrToFloatDef(FListB.Values['Maxnumber'],0); FSaleOrderItems[i].FTruck := FListB.Values['Truck']; FSaleOrderItems[i].FBm := FListB.Values['Bm']; if nAutoPD = sFlag_Yes then begin if Pos('散',FListB.Values['StockName']) > 0 then FSaleOrderItems[i].FPd := '' else FSaleOrderItems[i].FPd := sFlag_Yes; end else FSaleOrderItems[i].FPd := FListB.Values['ispd']; FSaleOrderItems[i].FWxZhuId := FListB.Values['wxzhuid']; FSaleOrderItems[i].FWxZiId := FListB.Values['wxziid']; FSaleOrderItems[i].FPhy := FListB.Values['isphy']; FSaleOrderItems[i].FTransType := FListB.Values['transtype']; FSaleOrderItems[i].FSelect := False; AddListViewItem(FSaleOrderItems[i]); end; finally FListB.Clear; FListA.Clear; end; end; procedure TfFrameSaleCard.InitListView; var col:TListColumn; begin lvOrders.Columns.Clear; lvOrders.Items.Clear; FillChar(FSaleOrderItem, SizeOf(TOrderInfoItem), #0); lvOrders.ViewStyle := vsReport; col := lvOrders.Columns.Add; col.Caption := '客户名称'; col.Width := 260; col := lvOrders.Columns.Add; col.Caption := '物料名称'; col.Width := 230; col := lvOrders.Columns.Add; col.Caption := '品牌'; col.Width := 100; col := lvOrders.Columns.Add; col.Caption := '车牌号码'; col.Width := 150; col := lvOrders.Columns.Add; col.Caption := '数量'; col.Width := 70; col := lvOrders.Columns.Add; col.Caption := '拼单'; col.Width := 70; col := lvOrders.Columns.Add; col.Caption := '到货地点'; col.Width := 100; col := lvOrders.Columns.Add; col.Caption := '选择'; col.Width := 70; col.Alignment := taCenter; end; procedure TfFrameSaleCard.AddListViewItem(var nSaleOrderItem: TOrderInfoItem); var nListItem:TListItem; begin nListItem := lvOrders.Items.Add; nlistitem.Caption := nSaleOrderItem.FCusName; nlistitem.SubItems.Add(nSaleOrderItem.FStockName); nlistitem.SubItems.Add(nSaleOrderItem.FStockBrand); nlistitem.SubItems.Add(nSaleOrderItem.FTruck); nlistitem.SubItems.Add(FloatToStr(nSaleOrderItem.FValue)); if nSaleOrderItem.FPd = sFlag_Yes then nlistitem.SubItems.Add('是') else nlistitem.SubItems.Add('否'); nlistitem.SubItems.Add(nSaleOrderItem.FStockArea); nlistitem.SubItems.Add(sUncheck); end; procedure TfFrameSaleCard.lvOrdersClick(Sender: TObject); var nIdx, nInt: Integer; nCanSave, nCanPd: Boolean; nTruck, nStockName: string; begin if lvOrders.Selected <> nil then begin with lvOrders.Selected do begin if SubItems[6] = sCheck then begin SubItems[6] := sUnCheck; FSaleOrderItems[lvOrders.Selected.Index].FSelect := False; nCanSave := False; for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if FSaleOrderItems[nIdx].FSelect then begin nCanSave := True; Break; end; end; btnSave.Visible := nCanSave = True; Exit; end; if not IsOrderCanLade(FSaleOrderItems[lvOrders.Selected.Index].FOrders) then begin ShowMsg('此订单已办卡,请重新选择', sHint); Exit; end; nInt := 0; nCanPd := True; nTruck := ''; nStockName := ''; for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if FSaleOrderItems[nIdx].FSelect then begin nCanPd := nCanPd and (FSaleOrderItems[nIdx].FPd = sFlag_Yes); nTruck := nTruck + FSaleOrderItems[nIdx].FTruck + ','; nStockName := nStockName + FSaleOrderItems[nIdx].FStockName + ','; Inc(nInt); end; end; if nInt > 0 then begin if Pos('散',FSaleOrderItems[lvOrders.Selected.Index].FStockName + ',' + nStockName) > 0 then begin ShowMsg('散装订单无法拼单,请重新选择', sHint); Exit; end; if FSaleOrderItems[lvOrders.Selected.Index].FPd <> sFlag_Yes then begin ShowMsg('不允许拼单的订单无法拼单,请重新选择', sHint); Exit; end; if Pos(FSaleOrderItems[lvOrders.Selected.Index].FTruck, nTruck) <= 0 then begin ShowMsg('不同车牌号无法拼单,请重新选择', sHint); Exit; end; nCanPd := nCanPd and (nInt < gSysParam.FAICMPDCount); end else nCanPd := True; if not nCanPd then begin ShowMsg('最多支持' + IntToStr(gSysParam.FAICMPDCount) +'个订单进行拼单,请重新选择', sHint); Exit; end; SubItems[6] := sCheck; FSaleOrderItems[lvOrders.Selected.Index].FSelect := True; end; nCanSave := False; for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if FSaleOrderItems[nIdx].FSelect then begin nCanSave := True; Break; end; end; {$IFDEF PrintHYEach} if nCanSave then begin for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if FSaleOrderItems[nIdx].FPhy = sFlag_Yes then begin PrintHY.Checked := True; end; end; end else PrintHY.Checked := False; {$ENDIF} btnSave.Visible := nCanSave = True; end; end; procedure TfFrameSaleCard.InitUIData(nSTDid, nPassword: string); begin InitListView; btnSave.Visible:= False; LoadNcSaleList(nSTDid, nPassword); end; procedure TfFrameSaleCard.BtnSaveClick(Sender: TObject); var nMsg, nStr, nCard, nHint: string; nIdx, nInt, nNum: Integer; nRet, nPrint, nForce, nDriverCard: Boolean; nTruck: string; nHzValue: Double; nIdHttp: TIdHTTP; wParam: TStrings; ReStream: TStringStream; ReJo, OneJo : ISuperObject; ArrsJa: TSuperArray; begin if GetTickCount - FLastQuery < 5 * 1000 then begin ShowMsg('请不要频繁操作', sHint); Exit; end; nInt := 0; BtnSave.Visible := False; nDriverCard := HasDriverCard(nTruck, nCard); for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if FSaleOrderItems[nIdx].FSelect then begin Inc(nInt); nTruck := FSaleOrderItems[nIdx].FTruck; if IFHasSaleOrder(FSaleOrderItems[nIdx].FOrders) then begin ShowMsg('订单已使用,无法开单,请联系管理员',sHint); Exit; end; {$IFDEF BusinessOnly} if not IsPurTruckReady(nTruck, nHint) then begin nStr := '车辆[%s]存在未完成的采购单据[%s],无法办卡'; nStr := Format(nStr,[nTruck, nHint]); ShowMsg(nStr, sHint); Exit; end; {$ENDIF} if Pos('散',FSaleOrderItems[nIdx].FStockName) > 0 then begin if IFHasBill(nTruck) then begin ShowMsg('车辆存在未完成的提货单,无法开单,请联系管理员',sHint); Exit; end; nHzValue := GetTruckSanMaxLadeValue(nTruck, nForce); if nForce and (nHzValue <= 0) then begin ShowMsg('核载量' + FloatToStr(nHzValue) + '未维护,无法开单,请联系管理员',sHint); Exit; end; end else begin //if gSysParam.FAICMPDCount <= 1 then begin if IFHasBill(nTruck) then begin ShowMsg('车辆存在未完成的提货单,无法开单,请联系管理员',sHint); Exit; end; end; end; end; end; if nInt = 0 then begin ShowMsg('请至少选择1个订单', sHint); Exit; end; try {$IFDEF AICMVerifyGPS} for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if not FSaleOrderItems[nIdx].FSelect then Continue; if not IsTruckGPSValid(FSaleOrderItems[nIdx].FTruck) then begin ShowMsg(FSaleOrderItems[nIdx].FTruck + '未启用GPS,请联系管理员', sHint); Exit; end; end; {$ENDIF} {$IFDEF VerifyGPSByPost} nStr := GetGPSUrl(nTruck, nHint); if nHint = sFlag_Yes then begin nidHttp := TIdHTTP.Create(nil); nidHttp.ConnectTimeout := cHttpTimeOut * 1000; nidHttp.ReadTimeout := cHttpTimeOut * 1000; nidHttp.Request.Clear; nidHttp.Request.Accept := 'application/json, text/javascript, */*; q=0.01'; nidHttp.Request.AcceptLanguage := 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3'; nidHttp.Request.ContentType := 'application/json;Charset=UTF-8'; nidHttp.Request.Connection := 'keep-alive'; wParam := TStringList.Create; ReStream := TStringstream.Create(''); try nidHttp.Post(nStr, wParam, ReStream); nStr := UTF8Decode(ReStream.DataString); WriteLog('GPS校验出参:' + nStr); ReJo := SO(nStr); if ReJo = nil then Exit; if ReJo.I['resultCode'] <> 200 then begin ArrsJa := ReJo['data'].AsArray; for nIdx := 0 to ArrsJa.Length - 1 do begin OneJo := SO(ArrsJa[nIdx].AsString); nStr := OneJo.S['info']; Break; end; ShowMsg('车辆' + nTruck + 'GPS校验失败:[ ' + nStr + ' ]', sHint); Exit; end else begin ArrsJa := ReJo['data'].AsArray; for nIdx := 0 to ArrsJa.Length - 1 do begin OneJo := SO(ArrsJa[nIdx].AsString); if not OneJo.B['inFence'] then begin nStr := OneJo.S['info']; ShowMsg('车辆' + nTruck + 'GPS校验失败:[ ' + nStr + ' ]', sHint); Exit; end; end; end; finally FreeAndNil(nidHttp); ReStream.Free; wParam.Free; end; end else begin WriteLog('GPS签到功能已关闭'); end; {$ENDIF} {$IFDEF AutoGetLineGroup} for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if not FSaleOrderItems[nIdx].FSelect then Continue; if not IfHasLine(FSaleOrderItems[nIdx].FStockID, sFlag_TypeCommon, FSaleOrderItems[nIdx].FStockBrand, nHint) then begin ShowMsg(nHint, sHint); Exit; end; end; {$ENDIF} if not nDriverCard then begin for nIdx:=0 to 3 do begin nCard := gDispenserManager.GetCardNo(gSysParam.FTTCEK720ID, nHint, False); if nCard <> '' then Break; Sleep(500); end; //连续三次读卡,成功则退出。 end; if nCard = '' then begin nMsg := '卡箱异常,请查看是否有卡.'; ShowMsg(nMsg, sWarn); Exit; end; WriteLog('读取到卡片: ' + nCard); //解析卡片 if not nDriverCard then begin if not IsCardValid(nCard) then begin gDispenserManager.RecoveryCard(gSysParam.FTTCEK720ID, nHint); nMsg := '卡号' + nCard + '非法,回收中,请稍后重新取卡'; WriteLog(nMsg); ShowMsg(nMsg, sWarn); Exit; end; end; nStr := GetCardUsed(nCard); if (nStr = sFlag_Sale) or (nStr = sFlag_SaleNew) then LogoutBillCard(nCard); //销售业务注销卡片,其它业务则无需注销 FLastQuery := GetTickCount; FListC.Clear; nInt := 0; for nIdx := Low(FSaleOrderItems) to High(FSaleOrderItems) do begin if not FSaleOrderItems[nIdx].FSelect then Continue; nInt := nInt + 1; LoadSysDictItem(sFlag_PrintBill, FListD); //需打印品种 nPrint := FListD.IndexOf(FSaleOrderItems[nIdx].FStockID) >= 0; with FListB do begin Clear; Values['Orders'] := EncodeBase64(FSaleOrderItems[nIdx].FOrders); Values['Value'] := FloatToStr(FSaleOrderItems[nIdx].FValue); //订单量 Values['Truck'] := FSaleOrderItems[nIdx].FTruck; Values['Lading'] := sFlag_TiHuo; Values['IsVIP'] := GetTransType(FSaleOrderItems[nIdx].FTransType); {$IFDEF AICMPackFromDict} Values['Pack'] := GetStockPackStyleEx(FSaleOrderItems[nIdx].FStockID, FSaleOrderItems[nIdx].FStockBrand); {$ELSE} Values['Pack'] := GetStockPackStyle(FSaleOrderItems[nIdx].FStockID); {$ENDIF} Values['BuDan'] := sFlag_No; Values['CusID'] := FSaleOrderItems[nIdx].FCusID; Values['CusName'] := FSaleOrderItems[nIdx].FCusName; Values['Brand'] := FSaleOrderItems[nIdx].FStockBrand; Values['StockArea'] := FSaleOrderItems[nIdx].FStockArea; Values['bm'] := FSaleOrderItems[nIdx].FBm; Values['wxzhuid'] := FSaleOrderItems[nIdx].FWxZhuId; Values['wxziid'] := FSaleOrderItems[nIdx].FWxZiId; if PrintHY.Checked then Values['PrintHY'] := sFlag_Yes else Values['PrintHY'] := sFlag_No; {$IFDEF RemoteSnap} Values['SnapTruck'] := sFlag_Yes; {$ELSE} Values['SnapTruck'] := sFlag_No; {$ENDIF} end; nStr := SaveBill(EncodeBase64(FListB.Text)); //call mit bus nRet := nStr <> ''; if not nRet then begin nMsg := '生成提货单信息失败,请联系管理员尝试手工制卡.'; ShowMsg(nMsg, sHint); Exit; end; nRet := False; nRet := SaveBillCard(nStr, nCard); for nNum := 0 to 2 do begin if GetBillCard(nStr) = nCard then begin nRet := True; Break; end; Sleep(200); nRet := False; nRet := SaveBillCard(nStr, nCard); end; if nRet and nPrint then FListC.Add(nStr); //SaveWebOrderMatch(nStr,FSaleOrderItems[nIdx].FOrders,sFlag_Sale); end; if not nRet then begin nMsg := '办理磁卡失败,请重试.'; ShowMsg(nMsg, sHint); Exit; end; if not nDriverCard then nRet := gDispenserManager.SendCardOut(gSysParam.FTTCEK720ID, nHint); //发卡 if nRet then begin nMsg := '提货单[ %s ]发卡成功,卡号[ %s ],请收好您的卡片'; nMsg := Format(nMsg, [nStr, nCard]); WriteLog(nMsg); ShowMsg(nMsg,sWarn); for nIdx := 0 to FListC.Count - 1 do begin PrintBillReport(FListC.Strings[nIdx], False); Sleep(200); end; {$IFDEF PrintHyOnSaveBill} for nIdx := 0 to FListC.Count - 1 do begin PrintHuaYanReportWhenSaveBill(FListC.Strings[nIdx], nMsg, gSysParam.FHYDanPrinter); if nMsg <> '' then ShowMsg(nMsg, sHint); Sleep(200); end; {$ENDIF} end else begin if not nDriverCard then gDispenserManager.RecoveryCard(gSysParam.FTTCEK720ID, nHint); nMsg := '卡号[ %s ]关联订单失败,请到开票窗口重新关联.'; nMsg := Format(nMsg, [nCard]); WriteLog(nMsg); ShowMsg(nMsg,sWarn); end; gTimeCounter := 0; finally BtnSave.Visible := True; end; end; function TfFrameSaleCard.DealCommand(Sender: TObject; const nCmd: Integer; const nParamA: Pointer; const nParamB: Integer): Integer; begin Result := 0; if nCmd = cCmd_FrameQuit then begin Close; end else if nCmd = cCmd_MakeNCSaleCard then begin if not Assigned(nParamA) then Exit; InitUIData(PFrameCommandParam(nParamA).FParamA, PFrameCommandParam(nParamA).FParamB); end; end; initialization gControlManager.RegCtrl(TfFrameSaleCard, TfFrameSaleCard.FrameID); end.
unit UConLocacao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, frxClass, frxDBSet, Vcl.Mask, Vcl.DBCtrls; type TfrmConLocacao = class(TForm) pnlPrincipal: TPanel; rbtCliente: TRadioButton; pnlPesquisa: TPanel; dbgTabela: TDBGrid; dsConLocacao: TDataSource; frxReportConsLocacao: TfrxReport; frxDBConsultaLocacao: TfrxDBDataset; rbtEndereco: TRadioButton; edtNumero: TEdit; lblEnderecoOrNome: TLabel; lblNumero: TLabel; edtEnderecoOrName: TEdit; Panel1: TPanel; Shape2: TShape; Shape1: TShape; Shape3: TShape; Pesquisar: TLabel; Relatório: TLabel; lblEditar: TLabel; btnPesquisar: TImage; btnRelatorio: TImage; btnEditar: TImage; Shape5: TShape; Shape6: TShape; procedure bitbtnRelatorioClick(Sender: TObject); procedure btnNovoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnRelatorioClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); private { Private declarations } public { Public declarations } principal,secundario:string; const selectSql ='select locacoes.locCodigo, locacoes.locPreco, locacoes.locInicio, locacoes.imoCodigo, locacoes.cliCodigo, locacoes.locFim, imoveis.imoEndereco, imoveis.imoNumero, clientes.cliNome ' +'from locacoes inner join imoveis on locacoes.imoCodigo=imoveis.imoCodigo inner' +' join clientes on locacoes.cliCodigo=clientes.cliCodigo'; end; var frmConLocacao: TfrmConLocacao; implementation {$R *.dfm} uses UDM, ULocCasa, UPrincipal; procedure TfrmConLocacao.bitbtnRelatorioClick(Sender: TObject); begin frxReportConsLocacao.ShowReport(); end; procedure TfrmConLocacao.btnEditarClick(Sender: TObject); begin frmPrincipal.edt:=True; frmLocCasa := TfrmLocCasa.Create(Self); frmLocCasa.dsLocacao.DataSet:= DM.qryConsLoc2; try frmLocCasa.ShowModal; finally frmLocCasa.Release; frmLocCasa:= Nil; end; end; procedure TfrmConLocacao.btnNovoClick(Sender: TObject); begin frmPrincipal.new:=True; frmLocCasa := TfrmLocCasa.Create(Self); try frmLocCasa.ShowModal; finally frmLocCasa.Release; frmLocCasa:= Nil; end; end; procedure TfrmConLocacao.btnPesquisarClick(Sender: TObject); begin DM.qryConsLoc2.Close; DM.qryConsLoc2.SQL.Clear; if rbtCliente.Checked=True then begin principal:=' where clientes.cliNome like '+#39+'%'+edtEnderecoOrName.Text+'%'+#39; end else if rbtEndereco.Checked=True then begin if edtNumero.Text='' then begin principal:=' where imoveis.imoEndereco like '+#39+'%'+edtEnderecoOrName.Text+'%'+#39; end else if edtEnderecoOrName.Text='' then begin principal:=' where imoveis.imoNumero ='+(edtNumero.Text); end else if (edtNumero.Text='') and (edtEnderecoOrName.Text='') then begin principal:=''; end; end; DM.qryConsLoc2.SQL.Add(selectSql + principal); DM.qryConsLoc2.Open; end; procedure TfrmConLocacao.btnRelatorioClick(Sender: TObject); begin frxReportConsLocacao.ShowReport(); end; end.
unit dmEstudioScriptError; interface uses SysUtils, Classes, DB, IBCustomDataSet, IBQuery; type TEstudioScriptError = class(TDataModule) qEstrategia: TIBQuery; qEstrategiaESTRATEGIA_APERTURA: TMemoField; qEstrategiaESTRATEGIA_APERTURA_POSICIONADO: TMemoField; qEstrategiaESTRATEGIA_CIERRE: TMemoField; qEstrategiaESTRATEGIA_CIERRE_POSICIONADO: TMemoField; private { Private declarations } public constructor Create(Owner: TComponent; const OIDEstrategia: integer); reintroduce; end; implementation uses UtilDB, dmBD; {$R *.dfm} { TEstudioScriptError } constructor TEstudioScriptError.Create(Owner: TComponent; const OIDEstrategia: integer); begin inherited Create(Owner); qEstrategia.Params[0].AsInteger := OIDEstrategia; OpenDataSet(qEstrategia); end; end.
{$MODE OBJFPC} program Lines; const InputFile = 'LINES.INP'; OutputFile = 'LINES.OUT'; max = 100000; var a, b: array[0..max + 1] of Integer; s: array[0..max + 1] of Integer; Map: array[1..max] of Integer; Trace: array[0..max] of Integer; n, m: Integer; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try Readln(f, n); for i := 1 to n do Read(f, a[i]); Readln(f); for i := 1 to n do Read(f, b[i]); finally CloseFile(f); end; end; procedure Init; var i: Integer; begin for i := 1 to n do Map[b[i]] := i; for i := 1 to n do a[i] := Map[a[i]]; a[n + 1] := n + 1; a[0] := 0; m := 1; s[m] := n + 1; end; //Find l as large as possible, so that a[s[l]] > a[i] //a[s[1]] > a[s[2]] > a[s[3]]... function Find(v: Integer): Integer; var Low, Middle, High: Integer; begin Low := 2; High := m; //Loop invariant: a[s[Low - 1]] > v >= a[High + 1] while Low <= High do begin Middle := (Low + High) div 2; if a[s[Middle]] > v then Low := Middle + 1 else High := Middle - 1; end; Result := High; end; procedure Optimize; var i, lambda: Integer; begin for i := n downto 0 do begin lambda := Find(a[i]); Trace[i] := s[lambda]; Inc(lambda); s[lambda] := i; if m < lambda then m := lambda; end; end; procedure PrintResult; var f: TextFile; i, j: Integer; begin AssignFile(f, OutputFile); Rewrite(f); try Writeln(f, m - 2); j := s[m - 1]; for i := 1 to m - 2 do begin Write(f, b[a[j]], ' '); j := Trace[j]; end; finally CloseFile(f); end; end; begin Enter; Init; Optimize; PrintResult; end. 6 2 3 1 5 6 4 3 2 5 6 1 4 7 1 2 3 4 5 6 7 1 2 6 7 3 4 5
unit FMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, tiMemoReadOnly, jpeg, ExtCtrls, ComCtrls ,tiFileSync_Mgr ; const cErrorCanNotFindOPDMSEXE = 'Can not find OPMDS application to run:'#13#13'%s'; cError = ' * * * Error * * * '; type TForm1 = class(TForm) memoLog: TtiMemoReadOnly; PB: TProgressBar; Button1: TButton; procedure tmrExecuteTimer(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure Execute ; procedure DoLog( const pMessage : string; pAppendToPrevRow: boolean); procedure DoUpdateProgress( pMax, pPos : integer ); procedure DoTerminate(Sender: TObject ) ; procedure DoTerminateWithError(Sender: TObject ) ; procedure ShowError(const pMessage: string); public end; var Form1: TForm1; implementation uses tiFileSyncReader_Abs ,tiFileSyncReader_DiskFiles ,tiFileSyncReader_Remote ,tiCompressZLib ,tiOIDGUID ,cFileSync ,tiUtils ,tiConstants , Math; // {$R *.dfm} procedure TForm1.tmrExecuteTimer(Sender: TObject); begin end; // Move this lot to a thread... procedure TForm1.Execute; var lParams: string; begin lParams := cHTTPURL + '=' + 'http://cartopddb/OPDMSLauncher.exe'; TthrdTIFileSyncOneWayCopy.Create( cgsRemote, lParams, '..\OPDMSClient\Remote', cgsDiskFiles, '', tiGetEXEPath, DoLog, DoUpdateProgress, DoTerminate, DoTerminateWithError, Self); end; procedure TForm1.DoLog(const pMessage: string; pAppendToPrevRow: boolean); begin MemoLog.Lines.Add(pMessage) end; procedure TForm1.DoUpdateProgress(pMax, pPos: integer); begin PB.Max:= pMax; PB.Position:= pPos; end; procedure TForm1.DoTerminate(Sender: TObject); begin end; procedure TForm1.DoTerminateWithError(Sender: TObject); begin end; procedure TForm1.btnCloseClick(Sender: TObject); begin Close ; end; procedure TForm1.ShowError(const pMessage: string); begin end; procedure TForm1.Button1Click(Sender: TObject); begin Execute; end; initialization end.
unit atmosphere_lib; interface uses math,table_func_lib,classes; type Yxy=record L,x,y: Real; end; TAtmosphere=class(TPersistent) private // эмпирическая модель земной атмосферы от A. J. Preetham Peter Shirley Brian Smits //University of Utah //к сожалению, подогнана конкретно к земной атмосфере под нашим Солнцем. Для других планет может выдавать полнейший бред Al,Bl,Cl,Dl,El: Real; //коэф. для распределения яркости Ax,Bx,Cx,Dx,Ex: Real; //компонент цвета x Ay,By,Cy,Dy,Ey: Real; //компонент цвета y Lz,xz,yz: Real; //яркость и цветность в зените Fl0,Fx0,Fy0 :Real; // x_matrix, y_matrix: array [1..4,1..3] of Real; function Fl(costheta,xi: Real): Real; function Fx(costheta,xi: Real): Real; function Fy(costheta,xi: Real): Real; public optical_mass_filename: string; relative_optical_mass: table_func; turbidity: Real; //затуманенность relative_density: Real; //плотность отн. Земной атм. ozone_absorb,mixed_gases_absorb,water_vapor_absorb: table_func; //поглощение разными газами ozone_amount,water_vapour_amount :Real; result_extinction: table_func; constructor Create; destructor Destroy; procedure Assign(Source: TPersistent); override; procedure Compute_extinction(angle: Real); procedure Compute_skydome_model(angle: Real; vmag: Real; x: Real; y: Real); function Skydome(costheta,xi: Real): Yxy; end; var x_matrix: array [1..3,1..4] of Real = ((0.00166, -0.00375, 0.00209, 0), (-0.02903, 0.06377, -0.03202, 0.00394), (0.11693, -0.21196, 0.06052, 0.25886)); y_matrix: array [1..3,1..4] of Real = ((0.00275, -0.00610, 0.00317, 0), (-0.04214, 0.08970, -0.04153, 0.00516), (0.15346, -0.26756, 0.06670, 0.26688)); implementation constructor TAtmosphere.Create; begin Inherited Create; optical_mass_filename:='data\relative_optical_mass\standart_relative_optical_mass.txt'; relative_optical_mass:=table_func.Create(optical_mass_filename); turbidity:=2; //ясная погода relative_density:=1; //точь в точь как на Земле ozone_amount:=0.35; water_vapour_amount:=2; ozone_absorb:=table_func.Create('data\absorption\ozone_absorption.txt'); mixed_gases_absorb:=table_func.Create('data\absorption\mixed_gases_absorption.txt'); water_vapor_absorb:=table_func.Create('data\absorption\water_vapour_absorption.txt'); result_extinction:=table_func.Create; result_extinction.order:=1; end; destructor TAtmosphere.Destroy; begin relative_optical_mass.Free; result_extinction.Free; ozone_absorb.Free; mixed_gases_absorb.Free; water_vapor_absorb.Free; Inherited Destroy; end; procedure TAtmosphere.Assign(Source: TPersistent); var t: TAtmosphere; begin if Source is TAtmosphere then begin t:=TAtmosphere(Source); optical_mass_filename:=t.optical_mass_filename; relative_optical_mass.assign(t.relative_optical_mass); turbidity:=t.turbidity; relative_density:=t.relative_density; ozone_absorb.assign(t.ozone_absorb); water_vapor_absorb.assign(t.water_vapor_absorb); mixed_gases_absorb.assign(t.mixed_gases_absorb); ozone_amount:=t.ozone_amount; water_vapour_amount:=t.water_vapour_amount; end else Inherited Assign(Source); end; procedure TAtmosphere.Compute_extinction(angle: Real); var arg: Real; //показатель экспоненты lambda: Real; //длина волны beta,m: Real; //затуманенность для закона Ангстрёма и воздушная масса w_w,vg,tmp1: Real; begin beta:=0.04608*turbidity-0.04586; m:=relative_density*relative_optical_mass[angle]; result_extinction.Clear; lambda:=0.780; while lambda>0.380 do begin //начнем с Релеевского рассеяния arg:=-0.008735*m/power(lambda,4.08); //теперь рассеяние Ангстрёма, зависящее от "затуманенности" arg:=arg-beta*m/power(lambda,1.3); //поглощение озоном arg:=arg-ozone_absorb[lambda*1000]*m*ozone_amount; //поглощение капельками воды w_w:=water_vapor_absorb[lambda*1000]*water_vapour_amount*m; tmp1:=1+20.07*w_w; w_w:=-0.2385*w_w/power(tmp1,0.45); arg:=arg+w_w; //поглощение другими газами vg:=mixed_gases_absorb[lambda*1000]*m; tmp1:=1+118.93*vg; vg:=-1.41*vg/power(tmp1,0.45); arg:=arg+vg; //уфф. result_extinction.addpoint(round(lambda*1000),exp(arg)); lambda:=lambda-0.001; end; end; procedure TAtmosphere.Compute_skydome_model(angle: Real; vmag: Real; x: Real; y: Real); var T,xi: Real; i,j: Integer; arxi: array [1..4] of Real; arT: array [1..3] of Real; begin T:=turbidity; Al:=0.1787*T-1.4630; Bl:=-0.3554*T+0.4275; Cl:=-0.0227*T+5.3251; Dl:=0.1206*T-2.5771; El:=-0.0670*T+0.3703; Ax:=-0.0193*T-0.2592; Bx:=-0.0665*T+0.0008; Cx:=-0.0004*T+0.2125; Dx:=-0.0641*T-0.8989; Ex:=-0.0033*T+0.0452; Ay:=-0.0167*T-0.2608; By:=-0.0950*T+0.0092; Cy:=-0.0079*T+0.2102; Dy:=-0.0441*T-1.6537; Ey:=-0.0109*T+0.0529; xi:=(4/9-T/120)*(pi-2*angle); Lz:=((4.0453*T-4.9710)*tan(xi)-0.2155*T+2.4192)*relative_density/power(2.51,(vmag+26.74)); //яркость в килоканделах на кв. метр //не мудрствуя лукаво, будем считать, что при более разреженной атмосфере ее яркость тупо упадет, а цвет останется тем же arxi[4]:=1; for i:=3 downto 1 do arxi[i]:=arxi[i+1]*angle; arT[3]:=1; for i:=2 downto 1 do arT[i]:=arT[i+1]*T; xz:=0; yz:=0; for i:=1 to 3 do begin for j:=1 to 4 do begin xz:=xz+arxi[j]*arT[i]*x_matrix[i,j]; yz:=yz+arxi[j]*arT[i]*y_matrix[i,j]; end; end; xz:=xz*x/0.317; //некий костыль, чтобы моделировать другие спектр. классы yz:=yz*y/0.326; //очень грубо, но иначе надо вообще всю эту модель выкидывать, считать самостоятельно //мне очень, очень стыдно :(( Fl0:=Fl(1,angle); Fx0:=Fx(1,angle); Fy0:=Fy(1,angle); //итак, вроде посчитали все коэф. end; function TAtmosphere.Fl(costheta,xi: Real): Real; begin Fl:=(1+Al*exp(Bl/costheta))*(1+Cl*exp(Dl*xi)+El*cos(xi)*cos(xi)); end; function TAtmosphere.Fx(costheta,xi: Real): Real; begin Fx:=(1+Ax*exp(Bx/costheta))*(1+Cx*exp(Dx*xi)+Ex*cos(xi)*cos(xi)); end; function TAtmosphere.Fy(costheta,xi: Real): Real; begin Fy:=(1+Ay*exp(By/costheta))*(1+Cy*exp(Dy*xi)+Ey*cos(xi)*cos(xi)); end; function TAtmosphere.Skydome(costheta,xi: Real): Yxy; begin Skydome.L:=Lz*Fl(costheta,xi)/Fl0; Skydome.x:=xz*Fx(costheta,xi)/Fx0; Skydome.y:=yz*Fy(costheta,xi)/Fy0; end; end.
//Only compile for the ANDROID platform. {$IF NOT Defined(ANDROID)} {$MESSAGE Fatal 'AT.Android.Folders.pas only compiles for the ANDROID platform.'} {$ENDIF} // ****************************************************************** // // Program Name : AT Library // Platform(s) : Android // Framework : FMX // // Filename : AT.Android.Folders.pas // Date Created : 22-Nov-2020 // Author : Matthew Vesperman // // Description: // // Android folder routines. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2020 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Contains routines that return folder paths for the Android /// platform. /// </summary> unit AT.Android.Folders; interface /// <summary> /// Returns either the shared or private documents folder on the /// Android platform. /// </summary> /// <param name="AAppPath"> /// The path to append to the documents folder path. The folder /// tree passed here will be created if it does not exist. Pass an /// empty string to get just the documents path. /// </param> /// <param name="ACommon"> /// Flag to indicate if we want the shared documents path or the /// private documents path. /// </param> /// <returns> /// The full path to either the shared or private documents folder /// for an Android device. /// </returns> /// <remarks> /// <para> /// If the AAppPath parameter is an empty string then this /// function returns just the documents folder (either shared /// or private). If AAppPath contains a value then it is /// appended to the documents path and the full path is created /// if it does not exist. /// </para> /// <para> /// If ACommon is set to TRUE then the shared documents folder /// path is returned, otherwise the private (app) documents /// folder is returned. /// </para> /// </remarks> /// <seealso cref="AT.Android.Folders|GetDocumentDirectory(string,Boolean)"> /// GetDocumentDirectory /// </seealso> function GetAppDataDirectory(AAppPath: String = ''; ACommon: Boolean = False): String; /// <summary> /// Returns either the shared or private documents folder on the /// Android platform. /// </summary> /// <param name="ADocPath"> /// The path to append to the documents folder path. The folder /// tree passed here will be created if it does not exist. Pass an /// empty string to get just the documents path. /// </param> /// <param name="ACommon"> /// Flag to indicate if we want the shared documents path or the /// private documents path. /// </param> /// <returns> /// The full path to either the shared or private documents folder /// for an Android device. /// </returns> /// <remarks> /// <para> /// If the ADocPath parameter is an empty string then this /// function returns just the documents folder (either shared /// or private). If ADocPath contains a value then it is /// appended to the documents path and the full path is created /// if it does not exist. /// </para> /// <para> /// If ACommon is set to TRUE then the shared documents folder /// path is returned, otherwise the private (app) documents /// folder is returned. /// </para> /// <para> /// On the Android platform GetDocumentDirectory is an alias to /// GetAppDataDirectory. /// </para> /// </remarks> /// <seealso cref="AT.Android.Folders|GetAppDataDirectory(string,Boolean)"> /// GetAppDataDirectory /// </seealso> function GetDocumentDirectory(const ADocPath: String = ''; ACommon: Boolean = False): String; implementation uses System.IOUtils, System.SysUtils; function GetAppDataDirectory(AAppPath: String = ''; ACommon: Boolean = False): String; begin //Are we returning the shared document folder??? if (ACommon) then begin //Yes, get the shared documents folder value... Result := TPath.GetSharedDocumentsPath; end else begin //No, get the private documents folder value... Result := TPath.GetDocumentsPath; end; //Ensure the trailing path delimeter is added to the folder value... Result := IncludeTrailingPathDelimiter(Result); if (NOT AAppPath.IsEmpty) then begin //Append the AAppPath value to the folder value... Result := Format('%s%s', [Result, AAppPath]); //Ensure the trailing path delimeter is added to the folder value... Result := IncludeTrailingPathDelimiter(Result); //Make sure the path actually exists... TDirectory.CreateDirectory(Result); end; end; function GetDocumentDirectory(const ADocPath: String = ''; ACommon: Boolean = False): String; begin //Return the value from GetAppDataDirectory... Result := GetAppDataDirectory(ADocPath, ACommon); end; end.
unit uTurmaService; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, sqldb, Forms, LCLType, DateUtils, maskutils; type TTurmaService = class private public // retorna a quantidade de alunos da turma. class function obterTotalAlunos(idTurma: integer): integer; // Aplica as regras de validação referentes à inclusão da turma. class procedure validarTurma(dataSet: TDataSet); // Aplica as regras de validação referentes à inclusão do aluno na turma. class procedure validarTurmaAluno(dataSet: TDataSet); // Verifica se aluno está dentro do horário em uma das turmas em que está matriculado class procedure validarHorarioAluno(idAluno: integer); end; implementation uses uDATMOD; //******************** MÉTODOS PÚBLICOS ********************// // retorna a quantidade de alunos da turma. class function TTurmaService.obterTotalAlunos(idTurma: integer): integer; begin result := 0; end; // Aplica as regras de validação referentes à inclusão da turma. class procedure TTurmaService.validarTurma(dataSet: TDataSet); var horaInicial: TTime; horaFinal: TTime; begin // Regra de validação 10 if dataSet.FieldByName('descricao').IsNull or (dataSet.FieldByName('descricao').AsString.Trim.Length < 10) or (dataSet.FieldByName('descricao').AsString.Trim.Length > 40) then raise Exception.Create('A descrição da turma deve conter entre 10 e 40 caracteres.'); // Regra de validação 1 if (dataSet.FieldByName('descricao').AsString.Length = 0) then raise Exception.Create('A descrição da turma tem que ser informada.'); // Regra de validação 2 if (dataSet.FieldByName('fk_perfil_professor_id').IsNull) then raise Exception.Create('O responsável pela turma tem que ser informado.'); // Regra de validação 11 if (dataSet.FieldByName('controlar_horario').AsString.Equals('S')) then begin // Regra de validação 03 if (dataSet.FieldByName('hora_inicio').AsString.Length = 0) then raise Exception.Create('O horário inicial tem que ser informado.'); // Regra de validação 12 if (dataSet.FieldByName('hora_fim').AsString.Length = 0) then raise Exception.Create('O horário final tem que ser informado.'); // Regra de validação 04 - INÍCIO // Valida hora inicial try horaInicial := StrToTime(FormatMaskText('00:00;1', dataSet.FieldByName('hora_inicio').AsString)); except raise Exception.Create('Hora inicial inválida.'); end; // Valida hora inicial try horaFinal := StrToTime(FormatMaskText('00:00;1', dataSet.FieldByName('hora_fim').AsString)); except raise Exception.Create('Hora final inválida.'); end; if (horaInicial >= horaFinal) then raise Exception.Create('O horário inicial tem que ser menor do que o horário final.'); // Regra de validação 04 - FIM end; // Regra de validação 05 if (dataSet.FieldByName('valor_sugerido').IsNull) then raise Exception.Create('O valor da mensalidade tem que ser informado.'); // Regra de validação 06 if (dataSet.FieldByName('valor_sugerido').AsFloat <= 0) then raise Exception.Create('O valor da mensalidade tem que ser maior do que zero.'); // Regra de validação 07 if (dataSet.FieldByName('limite_alunos').IsNull) then raise Exception.Create('A quantidade máxima por turma tem que ser informada.'); // Regra de validação 08 if (dataSet.FieldByName('limite_alunos').AsFloat <= 0) then raise Exception.Create('A quantidade máxima de alunos tem que ser maior do que zero.'); end; // Aplica as regras de validação referentes à inclusão do aluno na turma. class procedure TTurmaService.validarTurmaAluno(dataSet: TDataSet); begin // Regra de validação 1 if (dataSet.FieldByName('fk_turma_id').IsNull) then raise Exception.Create('A turma tem que ser informada.'); // Regra de validação 2 if (dataSet.FieldByName('fk_aluno_id').IsNull) then raise Exception.Create('O aluno tem que ser informado.'); // Regra de validação 5 if (DataModuleApp.qryLookUpTurma.FieldByName('limite_alunos').AsInteger < (DataModuleApp.qryLookUpTurma.FieldByName('qtd_alunos_turma').AsInteger) + 1) then if Application.MessageBox('Quantidade de alunos à turma selecionada está maior do que o limite registrado. Deseja continuar?', 'Validação', MB_ICONQUESTION + MB_YESNO) = IDNO then raise Exception.Create('Inclusão cancelada!'); end; // Verifica se aluno está dentro do horário em uma das turmas em que está matriculado class procedure TTurmaService.validarHorarioAluno(idAluno: integer); var sqlQueryTurmaAluno: TSQLQuery; horaInicio, horaFim: TTime; // Identifica que o aluno está vinculdao a uma turma com restrição de horário. True -> acesso dentro do horário | False -> sem acesso porque não está dentro. alunoVinculadoComRestricao, // Identifica que o aluno está vinculdao a uma turma sem restrição de horário alunoVinculadoSemRestricao: Boolean; begin alunoVinculadoSemRestricao := false; alunoVinculadoComRestricao := false; sqlQueryTurmaAluno := TSQLQuery.Create(nil); sqlQueryTurmaAluno.SQLConnection := DataModuleApp.MySQL57Connection; sqlQueryTurmaAluno.SQL.Add('select t.controlar_horario, t.hora_inicio, t.hora_fim'); sqlQueryTurmaAluno.SQL.Add('from turma t'); sqlQueryTurmaAluno.SQL.Add(' inner join turma_aluno ta on (t.id = ta.fk_turma_id and ta.fk_aluno_id = ' + idAluno.ToString + ')'); sqlQueryTurmaAluno.Open; if sqlQueryTurmaAluno.IsEmpty then raise Exception.Create('O aluno não está matriculado em nenhuma turma!'); while not sqlQueryTurmaAluno.EOF do begin // Veriica se o aluno está dentro do horário de alguma turma a que está vinvulado. if (sqlQueryTurmaAluno.FieldByName('controlar_horario').AsString = 'S') then begin horaInicio := StrToTime(FormatMaskText('00:00;1', sqlQueryTurmaAluno.FieldByName('hora_inicio').AsString)); horaFim := StrToTime(FormatMaskText('00:00;1', sqlQueryTurmaAluno.FieldByName('hora_fim').AsString)); if ((Time >= horaInicio) and (Time <= horaFim)) then begin alunoVinculadoComRestricao := true; Break; end; end // Uma vez apresnetada matrícula em um curso sem restrição de horário, esta propriedade não será mais modificada. else alunoVinculadoSemRestricao := true; sqlQueryTurmaAluno.Next; end; // Situação 1: Aluno cadastrado em uma turma sem restrição e outra(s) com restrição, mas não autorizado. if ((alunoVinculadoSemRestricao) and (sqlQueryTurmaAluno.RecordCount > 1)) and (alunoVinculadoComRestricao) then if Application.MessageBox('O aluno está registrando frequência em uma turma sem restrição de horário?', 'Validação', MB_ICONQUESTION + MB_YESNO) = IDNO then raise Exception.Create('Aluno não autorizado a frequentar a turma!'); // Situação 2: Aluno cadastrado em uma turma sem restrição apenas // Situação 3: Aluno cadastrado em uma turma com restrição apenas if (not alunoVinculadoSemRestricao) and (not alunoVinculadoComRestricao) then raise Exception.Create('Aluno não autorizado a frequentar a turma!'); end; //******************** MÉTODOS PRIVADOS ********************// end.
unit UCOMConnectorTests; interface uses Windows, Classes, SysUtils, dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsErrors, dwsComConnector, Variants, ActiveX, ComObj, dwsXPlatform, dwsUtils; type TCOMConnectorTests = class (TTestCase) private FCW : Word; FTests : TStringList; FFailures : TStringList; FCompiler : TDelphiWebScript; FConnector : TdwsComConnector; public procedure SetUp; override; procedure TearDown; override; procedure ReCreateTestMDB; procedure Execution; procedure Compilation; published procedure CompilationNormal; procedure CompilationWithMapAndSymbols; procedure ExecutionNonOptimized; procedure ExecutionOptimized; procedure CompilationFailure; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TCOMConnectorTests ------------------ // ------------------ // SetUp // procedure TCOMConnectorTests.SetUp; begin FTests:=TStringList.Create; FFailures:=TStringList.Create; CollectFiles(ExtractFilePath(ParamStr(0))+'COMConnector'+PathDelim, '*.pas', FTests); CollectFiles(ExtractFilePath(ParamStr(0))+'COMConnectorFailure'+PathDelim, '*.pas', FFailures); FCompiler:=TDelphiWebScript.Create(nil); FConnector:=TdwsComConnector.Create(nil); FConnector.Script:=FCompiler; FCW:=Get8087CW; ReCreateTestMDB; end; // TearDown // procedure TCOMConnectorTests.TearDown; begin FConnector.Free; FCompiler.Free; FFailures.Free; FTests.Free; Set8087CW(FCW); end; // ReCreateTestMDB // procedure TCOMConnectorTests.ReCreateTestMDB; var cat : OleVariant; conn : OleVariant; begin DeleteFile('Data\Db.mdb'); cat := CreateOleObject('ADOX.Catalog'); cat.Create('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\Db.mdb;'); conn := CreateOleObject('ADODB.Connection'); conn.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\Db.mdb;Persist Security Info=False'; conn.Open; conn.Execute('create table test (intCol INT, charCol VARCHAR(50), memoCol MEMO, dateCol DATE)'); conn.Execute('insert into test values (10, ''ten'', ''value ten'', cdate(''2010-10-10''))'); conn.Execute('insert into test values (20, ''twenty'', ''value twenty'', cdate(''2020-10-20''))'); conn.Close; end; // Compilation // procedure TCOMConnectorTests.Compilation; var source : TStringList; i : Integer; prog : IdwsProgram; begin source:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); end; finally source.Free; end; end; // CompilationNormal // procedure TCOMConnectorTests.CompilationNormal; begin FCompiler.Config.CompilerOptions:=[coOptimize]; Compilation; end; // CompilationWithMapAndSymbols // procedure TCOMConnectorTests.CompilationWithMapAndSymbols; begin FCompiler.Config.CompilerOptions:=[coSymbolDictionary, coContextMap, coAssertions]; Compilation; end; // ExecutionNonOptimized // procedure TCOMConnectorTests.ExecutionNonOptimized; begin FCompiler.Config.CompilerOptions:=[coAssertions]; Execution; end; // ExecutionOptimized // procedure TCOMConnectorTests.ExecutionOptimized; begin FCompiler.Config.CompilerOptions:=[coOptimize, coAssertions]; Execution; end; // CompilationFailure // procedure TCOMConnectorTests.CompilationFailure; var source : TStringList; i : Integer; prog : IdwsProgram; expectedError : TStringList; expectedErrorsFileName : String; begin FCompiler.Config.CompilerOptions:=[coOptimize, coAssertions]; source:=TStringList.Create; expectedError:=TStringList.Create; try for i:=0 to FFailures.Count-1 do begin source.LoadFromFile(FFailures[i]); prog:=FCompiler.Compile(source.Text); expectedErrorsFileName:=ChangeFileExt(FFailures[i], '.txt'); if FileExists(expectedErrorsFileName) then begin expectedError.LoadFromFile(expectedErrorsFileName); CheckEquals(expectedError.Text, prog.Msgs.AsInfo, FFailures[i]); end else Check(prog.Msgs.AsInfo<>'', FFailures[i]+': undetected error'); end; finally expectedError.Free; source.Free; end; end; // Execution // procedure TCOMConnectorTests.Execution; var source, expectedResult : TStringList; i : Integer; prog : IdwsProgram; exec : IdwsProgramExecution; resultsFileName : String; output : String; begin source:=TStringList.Create; expectedResult:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); exec:=prog.Execute; if exec.Msgs.Count=0 then output:=exec.Result.ToString else begin output:= 'Errors >>>>'#13#10 +exec.Msgs.AsInfo +'Result >>>>'#13#10 +exec.Result.ToString; end; resultsFileName:=ChangeFileExt(FTests[i], '.txt'); if FileExists(resultsFileName) then begin expectedResult.LoadFromFile(resultsFileName); CheckEquals(expectedResult.Text, output, FTests[i]); end else CheckEquals('', output, FTests[i]); end; finally expectedResult.Free; source.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('COMConnectorTests', TCOMConnectorTests); end.
unit dmImportarDatos; interface uses Windows, SysUtils, Classes, DB, IBCustomDataSet, IBQuery, IBSQL, AbUnzper, UtilFiles, auHTTP, IBUpdateSQL, kbmMemTable, Provider, dmBD, UtilDB, IBDatabase; type EImportarDatos = class(Exception); EStructureChange = class(Exception); TImportarDatos = class(TDataModule) Modificaciones: TkbmMemTable; ModificacionesOID_MODIFICACION: TSmallintField; ModificacionesCOMENTARIO: TStringField; ModificacionesSENTENCIAS: TMemoField; ModificacionesHECHO: TBooleanField; ModificacionesTIPO: TStringField; private FPerCentWindowReceiver: HWND; canceled: boolean; FCommited: boolean; FSemanal: boolean; FDiario: Boolean; IBSQLDiario, IBSQLSemanal, IBSQLComun: TIBSQL; NumImportados, Total: integer; LastOIDModificacion: integer; procedure InicializarTotal(const ZIP: TAbUnZipper); procedure import(ZIP: TAbUnZipper); procedure AsignarFieldSiguienteValor(const field: TField; const linea: string; var posicion: integer); function FechaStringToDate(const fecha: string): TDateTime; function importData(const ZIP: TAbUnZipper; const SCDatabase: TSCDatabase; const tipoBD: TBDDatos; const tabla, dataName: string): integer; procedure CargarModificaciones(ZIP: TAbUnZipper); procedure ImportarModificacion; function GetHayModificaciones: boolean; procedure NuevoValor(const iData: TIBSQL); protected procedure ImportarDatos(fileName: TFileName); function getLinea(datos: string; var posicion: integer; var ultimaLinea: boolean): string; function getSiguienteValor(linea: string; var posicion: integer): string; public constructor Create(AOwner: TComponent; IBSQLDiario, IBSQLSemanal, IBSQLComun: TIBSQL); reintroduce; procedure CancelCurrentOperation; procedure Importar(const DataFileName: TFileName; const PerCentWindowReceiver: HWND); procedure ImportarModificaciones(const transaction: TIBTransaction); property Diario: Boolean read FDiario write FDiario; property Semanal: boolean read FSemanal write FSemanal; property Commited: boolean read FCommited; property HayModificaciones: boolean read GetHayModificaciones; end; implementation uses AbUtils, strUtils, dmInternalServer, AbZipTyp, UserServerCalls, UtilString, dmConfiguracion, UserMessages, Forms, IB, dmDataComun; {$R *.dfm} type TTipoDato = record outParam: string; BD: TSCDatabase; tipoBD: TBDDatos; tabla: string; end; const DELIMITADOR_SENTENCIAS = '#'; Datos: array[0..15] of TTipoDato = ( (outParam: 'valor'; BD: scdComun; tipoBD: bddDiaria; tabla: 'valor'), (outParam: 'd_sesion'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'sesion'), (outParam: 'd_sesion_rentabilidad'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'sesion_rentabilidad'), (outParam: 'd_cotizacion'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'cotizacion'), (outParam: 'd_cotizacion_rentabilidad'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'cotizacion_rentabilidad'), (outParam: 'd_cotizacion_estado'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'cotizacion_estado'), (outParam: 'frase'; BD: scdComun; tipoBD: bddDiaria; tabla: 'FRASE'), (outParam: 'mensaje'; BD: scdComun; tipoBD: bddDiaria; tabla: 'MENSAJE'), (outParam: 'mensaje_frase'; BD: scdComun; tipoBD: bddDiaria; tabla: 'MENSAJE_FRASE'), (outParam: 'd_cotizacion_mensaje'; BD: scdDatos; tipoBD: bddDiaria; tabla: 'cotizacion_mensaje'), (outParam: 's_sesion'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'sesion'), (outParam: 's_sesion_rentabilidad'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'sesion_rentabilidad'), (outParam: 's_cotizacion'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'cotizacion'), (outParam: 's_cotizacion_rentabilidad'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'cotizacion_rentabilidad'), (outParam: 's_cotizacion_estado'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'cotizacion_estado'), (outParam: 's_cotizacion_mensaje'; BD: scdDatos; tipoBD: bddSemanal; tabla: 'cotizacion_mensaje')); resourcestring ERROR_NO_FILE = 'No se ha encontrado el fichero temporal de descarga.'; ERROR_NO_DATA = 'No se ha descargado ningún dato.'; ERROR_CORRUPT_FILE = 'El fichero temporal de descarga está corrupto, no se puede importar.'; ERROR_TOTAL = 'No se han descargado correctamente los datos.'; ABORT_MSG = 'Cancelado por el usuario'; NUEVO_VALOR = 'Se ha incorporado el valor %s - %s al mercado %s.'; procedure TImportarDatos.import(ZIP: TAbUnZipper); var tabla: string; i: integer; tipoDato: TTipoDato; function internalImport: integer; var i: integer; found, multiple: boolean; importing: string; begin importing := tipoDato.outParam; found := ZIP.FindFile(importing) <> -1; multiple := false; if not found then begin found := ZIP.FindFile(importing + '_0') <> -1; multiple := found; end; if found then begin if multiple then begin result := 0; i := 0; repeat try result := result + importData(ZIP, tipoDato.BD, tipoDato.tipoBD, tipoDato.tabla, importing + '_' + IntToStr(i)); except on e: Exception do begin e.Message := e.Message + sLineBreak + 'File=' + tabla + '_' + IntToStr(i); raise; end; end; inc(i); found := ZIP.FindFile(importing + '_' + IntToStr(i)) <> -1; until not found; end else result := importData(ZIP, tipoDato.BD, tipoDato.tipoBD, tipoDato.tabla, importing); end else result := 0; end; begin InicializarTotal(ZIP); CargarModificaciones(ZIP); NumImportados := 0; for i := Low(Datos) to High(Datos) do begin if canceled then raise EAbort.Create(ABORT_MSG); tipoDato := Datos[i]; tabla := tipoDato.tabla; internalImport; end; end; function TImportarDatos.importData(const ZIP: TAbUnZipper; const SCDatabase: TSCDatabase; const tipoBD: TBDDatos; const tabla, dataName: string): integer; var campos: TStringList; mem: TStringStream; offset, j, numCampos: integer; linea: string; position, positionValor: integer; finalDatos: boolean; datos: string; iData: TIBSQL; perCent: integer; esValor: boolean; function GetInsert: string; var i, num: integer; sql, values: string; begin num := numCampos - 1; sql := 'insert into ' + tabla + '('; values := ''; for i := 0 to num do begin sql := sql + campos[i]; values := values + ':' + campos[i]; if i < num then begin sql := sql + ','; values := values + ','; end; end; result := sql + ') values (' + values + ')'; end; procedure AmpliarColumnaMensaje(const campo: string; const largo: integer); var alterMensaje: TIBSQL; transaction: TIBTransaction; begin transaction := TIBTransaction.Create(nil); try alterMensaje := TIBSQL.Create(nil); try alterMensaje.Database := iData.Database; transaction.AddDatabase(alterMensaje.Database); alterMensaje.Transaction := transaction; alterMensaje.SQL.Text := 'alter table cotizacion_mensaje alter ' + campo + ' type varchar(' + IntToStr(largo) + ')'; ExecQuery(alterMensaje, true); finally alterMensaje.Free; end; finally transaction.Free; end; end; procedure asignarValor(const campo, valor: string); begin if valor = '<null>' then iData.ParamByName(campo).Clear else begin if Pos('FECHA', campo) > 0 then iData.ParamByName(campo).AsDate := FechaStringToDate(valor) else begin try iData.ParamByName(campo).AsString := valor; except on e: EIBClientError do begin if (e.SQLCode = integer(ibxeStringTooLarge)) and (tabla = 'cotizacion_mensaje') then begin AmpliarColumnaMensaje(campo, Length(valor)); raise EStructureChange.Create(''); end else raise; end; end; end; end; end; // procedure ClearParams; // var i: integer; // begin // for i := numCampos -1 downto 0 do // iData.Params[i].Clear; // end; procedure inicializarIData; begin if SCDatabase = scdComun then begin iData := IBSQLComun; end else begin if tipoBD = bddDiaria then iData := IBSQLDiario else iData:= IBSQLSemanal; end; iData.SQL.Text := GetInsert; end; begin mem := TStringStream.Create(''); try ZIP.ExtractToStream(dataName, mem); if mem.Size <> 0 then begin position := 1; positionValor := 1; datos := mem.DataString; if datos = '' then //Si no se consigue ningún dato, se mira si están en UTF8 datos := UTF8Decode(mem.DataString); campos := TStringList.Create; try linea := getLinea(datos, position, finalDatos); offset := Pos(SEPARADOR_COLUMNA, linea); if linea <> '' then begin while offset <> 0 do begin campos.Add(getSiguienteValor(linea, positionValor)); offset := PosEx(SEPARADOR_COLUMNA, linea, offset + 1); end; campos.Add(getSiguienteValor(linea, positionValor)); end; numCampos := campos.Count; finalDatos := numCampos = 0; result := 0; if not finalDatos then begin inicializarIData; esValor := tabla = 'valor'; repeat if canceled then raise EAbort.Create(ABORT_MSG); inc(result); linea := getLinea(datos, position, finalDatos); if linea = '' then finalDatos := true else begin positionValor := 1; for j := 0 to numCampos - 1 do asignarValor(campos[j], getSiguienteValor(linea, positionValor)); try ExecQuery(iData, false); if esValor then NuevoValor(iData); Inc(NumImportados); perCent := Trunc(NumImportados * 100 / Total); PostMessage(FPerCentWindowReceiver, WM_PERCENT, perCent, 0); Application.ProcessMessages; except on e: Exception do begin e.Message := e.Message + sLineBreak + 'Linea=' + linea; raise; end; end; end; until finalDatos; end; finally campos.Free; end; end else result := 0; finally mem.Free; end; end; procedure TImportarDatos.Importar(const DataFileName: TFileName; const PerCentWindowReceiver: HWND); begin FCommited := false; FPerCentWindowReceiver := PerCentWindowReceiver; ImportarDatos(DataFileName); end; procedure TImportarDatos.ImportarDatos(fileName: TFileName); var ZIP: TAbUnZipper; fileStream: TFileStream; begin if not FileExists(fileName) then raise EImportarDatos.Create(ERROR_NO_FILE); fileStream := TFileStream.Create(fileName, fmOpenRead); try if fileStream.Size = 0 then raise EImportarDatos.Create(ERROR_NO_DATA); if VerifyZip(fileStream) <> atZip then raise EImportarDatos.Create(ERROR_CORRUPT_FILE); finally fileStream.Free; end; ZIP := TAbUnZipper.Create(nil); try ZIP.ForceType := true; ZIP.ArchiveType := atZip; ZIP.FileName := fileName; // try import(ZIP); { finally ZIP.CloseArchive; end;} finally ZIP.Free; end; end; procedure TImportarDatos.ImportarModificacion; var iData: TIBSQL; sentencias: TStringList; tipo: string; OIDModificacion: integer; procedure Importar; var i: integer; begin for i := 0 to sentencias.Count - 1 do begin Application.ProcessMessages; if canceled then raise EAbort.Create(ABORT_MSG); iData.SQL.Clear; iData.SQL.Text := sentencias[i]; ExecQuery(iData, false); end; end; begin sentencias := TStringList.Create; try tipo := ModificacionesTIPO.Value; if tipo = 'C' then iData := IBSQLComun else begin if tipo = 'D' then iData := IBSQLDiario else begin if tipo = 'S' then iData := IBSQLSemanal else raise EImportarDatos.Create('Tipo modificación desconocido: ' + tipo); end; end; Split(DELIMITADOR_SENTENCIAS, ModificacionesSENTENCIAS.Value, sentencias); Importar; OIDModificacion := ModificacionesOID_MODIFICACION.Value; if tipo = 'C' then begin if Configuracion.Sistema.ServidorModificacionComun < OIDModificacion then Configuracion.Sistema.ServidorModificacionComun := OIDModificacion; end else begin if tipo = 'D' then begin if Configuracion.Sistema.ServidorModificacionDiaria < OIDModificacion then Configuracion.Sistema.ServidorModificacionDiaria := OIDModificacion; end else begin if Configuracion.Sistema.ServidorModificacionSemanal < OIDModificacion then Configuracion.Sistema.ServidorModificacionSemanal := OIDModificacion; end; end; Configuracion.Sistema.Commit; finally sentencias.Free; end; end; procedure TImportarDatos.ImportarModificaciones(const transaction: TIBTransaction); begin Modificaciones.First; repeat Application.ProcessMessages; if canceled then raise EAbort.Create(ABORT_MSG); transaction.StartTransaction; try // Las OID_MODIFICACION < 0 son mensajes incorporados en Modificaciones, // como NuevoValor if ModificacionesOID_MODIFICACION.Value > 0 then ImportarModificacion; Modificaciones.Edit; ModificacionesHECHO.Value := true; Modificaciones.Post; transaction.Commit; Modificaciones.Next; except on e: Exception do begin transaction.Rollback; raise; end; end; until Modificaciones.Eof; end; function TImportarDatos.getLinea(datos: string; var posicion: integer; var ultimaLinea: boolean): string; var i: integer; begin i := PosEx(SEPARADOR_LINEA, datos, posicion); if i = 0 then begin ultimaLinea := true; i := length(datos) + 1; end else ultimaLinea := false; if posicion = 0 then result := Copy(datos, posicion, i - posicion - 1) else result := Copy(datos, posicion, i - posicion); posicion := i + 1; end; function TImportarDatos.getSiguienteValor(linea: string; var posicion: integer): string; var i: integer; begin i := PosEx(SEPARADOR_COLUMNA, linea, posicion); if i = 0 then i := length(linea) + 1; if posicion = 0 then result := Copy(linea, posicion, i - posicion - 1) else result := Copy(linea, posicion, i - posicion); posicion := i + 1; end; procedure TImportarDatos.AsignarFieldSiguienteValor(const field: TField; const linea: string; var posicion: integer); var valor: string; begin valor := getSiguienteValor(linea, posicion); if valor = '<null>' then field.Clear else begin if field is TDateField then (field as TDateField).Value := FechaStringToDate(valor) else begin if field is TNumericField then begin // La parte fraccionario de un número viene con . y aquí field.AsString := StringReplace(valor, '.', DecimalSeparator, []); end else field.AsString := valor; end; end; end; procedure TImportarDatos.CancelCurrentOperation; begin inherited; canceled := true; end; procedure TImportarDatos.CargarModificaciones(ZIP: TAbUnZipper); var tabla, tipo: string; procedure cargar(const nombre: string); var datos, linea: string; i: integer; mem: TStringStream; ultimaLinea: boolean; posicionValor: integer; begin mem := TStringStream.Create(''); try ZIP.ExtractToStream(nombre, mem); if mem.Size <> 0 then begin datos := mem.DataString; if datos = '' then //Si no se consigue ningún dato, se mira si están en UTF8 datos := UTF8Decode(mem.DataString); i := 1; ultimaLinea := false; // Cabecera linea := getLinea(datos, i, ultimaLinea); if not ultimaLinea then begin repeat if canceled then raise EAbort.Create(ABORT_MSG); linea := getLinea(datos, i, ultimaLinea); posicionValor := 1; Modificaciones.Append; ModificacionesHECHO.Value := false; ModificacionesTIPO.Value := tipo; AsignarFieldSiguienteValor(ModificacionesOID_MODIFICACION, linea, posicionValor); AsignarFieldSiguienteValor(ModificacionesCOMENTARIO, linea, posicionValor); AsignarFieldSiguienteValor(ModificacionesSENTENCIAS, linea, posicionValor); Modificaciones.Post; until ultimaLinea; end; end; finally mem.Free; end; end; procedure buscar; var i: integer; found, multiple: boolean; begin found := ZIP.FindFile(tabla) <> -1; multiple := false; if not found then begin found := ZIP.FindFile(tabla + '_0') <> -1; multiple := found; end; if found then begin if multiple then begin i := 0; repeat cargar(tabla + '_' + IntToStr(i)); inc(i); found := ZIP.FindFile(tabla + '_' + IntToStr(i)) <> -1; until not found; end else cargar(tabla); end; end; begin //MUY IMPORTANTE!. Si al actualizar los datos se reinicia la actualización porque //se necesitaba ampliar el espacio de alguna de las columnas de cotizacion_mensaje, //CargaModificaciones se llamará 2 veces, con lo cual las modificaciones aparecerán //duplicadas. Para que esto no ocurra, primero cerramos Modificaciones, por //si ya se hubieran cargado los modificaciones anteriormente. Modificaciones.Close; // Modificaciones.Open; tipo := 'C'; tabla := 'modificacion_c'; buscar; tipo := 'D'; tabla := 'modificacion_d'; buscar; tipo := 'S'; tabla := 'modificacion_s'; buscar; end; procedure TImportarDatos.InicializarTotal(const ZIP: TAbUnZipper); var mem: TStringStream; begin mem := TStringStream.Create(''); try ZIP.ExtractToStream('total', mem); if mem.Size <> 0 then begin total := StrToInt(mem.DataString); end else raise EImportarDatos.Create(ERROR_TOTAL); finally mem.Free; end; end; procedure TImportarDatos.NuevoValor(const iData: TIBSQL); begin dec(LastOIDModificacion); Modificaciones.Append; ModificacionesOID_MODIFICACION.Value := LastOIDModificacion; ModificacionesCOMENTARIO.Value := Format(NUEVO_VALOR, [iData.ParamByName('SIMBOLO').AsString, iData.ParamByName('NOMBRE').AsString, DataComun.FindMercado(iData.ParamByName('OR_MERCADO').AsInteger)^.Pais]); Modificaciones.Post; end; constructor TImportarDatos.Create(AOwner: TComponent; IBSQLDiario, IBSQLSemanal, IBSQLComun: TIBSQL); begin inherited Create(AOwner); Self.IBSQLDiario := IBSQLDiario; Self.IBSQLSemanal := IBSQLSemanal; Self.IBSQLComun := IBSQLComun; LastOIDModificacion := 0; FCommited := false; end; function TImportarDatos.FechaStringToDate(const fecha: string): TDateTime; begin result := EncodeDate(StrToInt(Copy(fecha, 0, 4)), StrToInt(Copy(fecha, 6, 2)), StrToInt(Copy(fecha, 9, 2))); end; function TImportarDatos.GetHayModificaciones: boolean; begin result := not Modificaciones.IsEmpty; end; end.
{ TPrintJobInfo Component Version 1.3b - Suite GLib Copyright (©) 2009, by Germán Estévez (Neftalí) Representa un job de impresión generado por una aplicación Windows. Utilización/Usage: Basta con "soltar" el componente y activarlo. Place the component in the form and active it. MSDN Info: http://msdn.microsoft.com/en-us/library/aa394370(VS.85).aspx ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia envíame un mail a: german_ral@hotmail.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion send a mail to: german_ral@hotmail.com ========================================================================= @author Germán Estévez (Neftalí) @web http://neftali.clubDelphi.com - http://neftali-mirror.site11.com/ @cat Package GLib } unit CPrintJobInfo; { ========================================================================= TPrintJobInfo.pas Componente ======================================================================== Historia de las Versiones ------------------------------------------------------------------------ 28/01/2010 * Creación. ========================================================================= Errores detectados no corregidos ========================================================================= } //========================================================================= // // I N T E R F A C E // //========================================================================= interface uses Classes, Controls, CWMIBase; type //: Clase para definir las propiedades del componente. TPrintJobProperties = class(TPersistent) private FCaption:string; FColor:string; FDataType:string; FDescription:string; FDocument:string; FDriverName:string; FElapsedTime:TDateTime; FHostPrintQueue:string; FInstallDate:TDateTime; FJobId:Longword; FJobStatus:string; FName:string; FNotify:string; FOwner:string; FPagesPrinted:Longword; FPaperLength:Longword; FPaperSize:string; FPaperWidth:Longword; FParameters:string; FPrintProcessor:string; FPriority:Longword; FSize:Longword; FStartTime:TDateTime; FStatus:string; FStatusMask:Longword; FStatusMaskAsString:string; FTimeSubmitted:TDateTime; FTotalPages:Longword; FUntilTime:TDateTime; private public // Obtener la propiedad <StatusMask> como string function GetStatusMaskAsString():string; // {GET_ENUM} published property Caption:string read FCaption write FCaption stored False; property Color:string read FColor write FColor stored False; property DataType:string read FDataType write FDataType stored False; property Description:string read FDescription write FDescription stored False; property Document:string read FDocument write FDocument stored False; property DriverName:string read FDriverName write FDriverName stored False; property ElapsedTime:TDateTime read FElapsedTime write FElapsedTime stored False; property HostPrintQueue:string read FHostPrintQueue write FHostPrintQueue stored False; property InstallDate:TDateTime read FInstallDate write FInstallDate stored False; property JobId:Longword read FJobId write FJobId stored False; property JobStatus:string read FJobStatus write FJobStatus stored False; property Name:string read FName write FName stored False; property Notify:string read FNotify write FNotify stored False; property Owner:string read FOwner write FOwner stored False; property PagesPrinted:Longword read FPagesPrinted write FPagesPrinted stored False; property PaperLength:Longword read FPaperLength write FPaperLength stored False; property PaperSize:string read FPaperSize write FPaperSize stored False; property PaperWidth:Longword read FPaperWidth write FPaperWidth stored False; property Parameters:string read FParameters write FParameters stored False; property PrintProcessor:string read FPrintProcessor write FPrintProcessor stored False; property Priority:Longword read FPriority write FPriority stored False; property Size:Longword read FSize write FSize stored False; property StartTime:TDateTime read FStartTime write FStartTime stored False; property Status:string read FStatus write FStatus stored False; property StatusMask:Longword read FStatusMask write FStatusMask stored False; property StatusMaskAsString:string read GetStatusMaskAsString write FStatusMaskAsString stored False; property TimeSubmitted:TDateTime read FTimeSubmitted write FTimeSubmitted stored False; property TotalPages:Longword read FTotalPages write FTotalPages stored False; property UntilTime:TDateTime read FUntilTime write FUntilTime stored False; end; //: Implementación para el acceso vía WMI a la clase Win32_PrintJob TPrintJobInfo = class(TWMIBase) private FPrintJobProperties: TPrintJobProperties; protected //: Rellenar las propiedades. procedure FillProperties(AIndex:integer); override; // propiedad Active procedure SetActive(const Value: Boolean); override; //: Clase para el componente. function GetWMIClass():string; override; //: Obtener el root. function GetWMIRoot():string; override; //: Limpiar las propiedades procedure ClearProps(); override; public // redefinido el constructor constructor Create(AOwner: TComponent); override; //: destructor destructor Destroy; override; published // propiedades de la PrintJob property PrintJobProperties:TPrintJobProperties read FPrintJobProperties write FPrintJobProperties; end; // Constantes para la propiedad StatusMask const ENUM_STRING_STATUSMASK_1 = 'Paused'; ENUM_STRING_STATUSMASK_2 = 'Error'; ENUM_STRING_STATUSMASK_4 = 'Deleting'; ENUM_STRING_STATUSMASK_8 = 'Spooling'; ENUM_STRING_STATUSMASK_16 = 'Printing'; ENUM_STRING_STATUSMASK_32 = 'Offline'; ENUM_STRING_STATUSMASK_64 = 'Paperout'; ENUM_STRING_STATUSMASK_128 = 'Printed'; ENUM_STRING_STATUSMASK_256 = 'Deleted'; ENUM_STRING_STATUSMASK_512 = 'Blocked_DevQ'; ENUM_STRING_STATUSMASK_1024 = 'User_Intervention_Req'; ENUM_STRING_STATUSMASK_2048 = 'Restart'; // {CONST_ENUM} //========================================================================= // // I M P L E M E N T A T I O N // //========================================================================= implementation uses {Generales} Forms, Types, Windows, SysUtils, {GLib} UProcedures, UConstantes, Dialogs; { TPrintJob } {-------------------------------------------------------------------------------} // Limpiar las propiedades procedure TPrintJobInfo.ClearProps; begin Self.PrintJobProperties.FCaption := STR_EMPTY; Self.PrintJobProperties.FColor := STR_EMPTY; Self.PrintJobProperties.FDataType := STR_EMPTY; Self.PrintJobProperties.FDescription := STR_EMPTY; Self.PrintJobProperties.FDocument := STR_EMPTY; Self.PrintJobProperties.FDriverName := STR_EMPTY; Self.PrintJobProperties.FElapsedTime := 0; Self.PrintJobProperties.FHostPrintQueue := STR_EMPTY; Self.PrintJobProperties.FInstallDate := 0; Self.PrintJobProperties.FJobId := 0; Self.PrintJobProperties.FJobStatus := STR_EMPTY; Self.PrintJobProperties.FName := STR_EMPTY; Self.PrintJobProperties.FNotify := STR_EMPTY; Self.PrintJobProperties.FOwner := STR_EMPTY; Self.PrintJobProperties.FPagesPrinted := 0; Self.PrintJobProperties.FPaperLength := 0; Self.PrintJobProperties.FPaperSize := STR_EMPTY; Self.PrintJobProperties.FPaperWidth := 0; Self.PrintJobProperties.FParameters := STR_EMPTY; Self.PrintJobProperties.FPrintProcessor := STR_EMPTY; Self.PrintJobProperties.FPriority := 0; Self.PrintJobProperties.FSize := 0; Self.PrintJobProperties.FStartTime := 0; Self.PrintJobProperties.FStatus := STR_EMPTY; Self.PrintJobProperties.FStatusMask := 0; Self.PrintJobProperties.FTimeSubmitted := 0; Self.PrintJobProperties.FTotalPages := 0; Self.PrintJobProperties.FUntilTime := 0; end; //: Constructor del componente constructor TPrintJobInfo.Create(AOwner: TComponent); begin inherited; Self.FPrintJobProperties := TPrintJobProperties.Create(); Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library/aa394370(VS.85).aspx'; end; // destructor del componente destructor TPrintJobInfo.Destroy(); begin // liberar FreeAndNil(Self.FPrintJobProperties); inherited; end; // Obtener la clase function TPrintJobInfo.GetWMIClass(): string; begin Result := WIN32_PRINTJOB_CLASS; end; // Obtener Root function TPrintJobInfo.GetWMIRoot(): string; begin Result := STR_CIM2_ROOT; end; // Active procedure TPrintJobInfo.SetActive(const Value: Boolean); begin // método heredado inherited; end; //: Rellenar las propiedades del componente. procedure TPrintJobInfo.FillProperties(AIndex: integer); var v:variant; vNull:boolean; vp:TPrintJobProperties; begin // Llamar al heredado (importante) inherited; // Rellenar propiedades... vp := Self.PrintJobProperties; GetWMIPropertyValue(Self, 'Caption', v, vNull); vp.FCaption := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Color', v, vNull); vp.FColor := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'DataType', v, vNull); vp.FDataType := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Description', v, vNull); vp.FDescription := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Document', v, vNull); vp.FDocument := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'DriverName', v, vNull); vp.FDriverName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ElapsedTime', v, vNull); if not vNull then begin vp.FElapsedTime := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'HostPrintQueue', v, vNull); vp.FHostPrintQueue := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'InstallDate', v, vNull); if not vNull then begin vp.FInstallDate := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'JobId', v, vNull); vp.FJobId := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'JobStatus', v, vNull); vp.FJobStatus := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Name', v, vNull); vp.FName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Notify', v, vNull); vp.FNotify := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Owner', v, vNull); vp.FOwner := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PagesPrinted', v, vNull); vp.FPagesPrinted := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'PaperLength', v, vNull); vp.FPaperLength := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'PaperSize', v, vNull); vp.FPaperSize := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PaperWidth', v, vNull); vp.FPaperWidth := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Parameters', v, vNull); vp.FParameters := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PrintProcessor', v, vNull); vp.FPrintProcessor := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Priority', v, vNull); vp.FPriority := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Size', v, vNull); vp.FSize := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'StartTime', v, vNull); if not vNull then begin vp.FStartTime := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'Status', v, vNull); vp.FStatus := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'StatusMask', v, vNull); vp.FStatusMask := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'TimeSubmitted', v, vNull); if not vNull then begin vp.FTimeSubmitted := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'TotalPages', v, vNull); vp.FTotalPages := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'UntilTime', v, vNull); if not vNull then begin vp.FUntilTime := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; end; // Obtener la propiedad como string function TPrintJobProperties.GetStatusMaskAsString():string; begin case FStatusMask of 1: Result := ENUM_STRING_STATUSMASK_1; 2: Result := ENUM_STRING_STATUSMASK_2; 4: Result := ENUM_STRING_STATUSMASK_4; 8: Result := ENUM_STRING_STATUSMASK_8; 16: Result := ENUM_STRING_STATUSMASK_16; 32: Result := ENUM_STRING_STATUSMASK_32; 64: Result := ENUM_STRING_STATUSMASK_64; 128: Result := ENUM_STRING_STATUSMASK_128; 256: Result := ENUM_STRING_STATUSMASK_256; 512: Result := ENUM_STRING_STATUSMASK_512; 1024: Result := ENUM_STRING_STATUSMASK_1024; 2048: Result := ENUM_STRING_STATUSMASK_2048; else Result := STR_EMPTY; end; end; // {IMPL_ENUM} end.
unit unAbout; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, jpeg; type TAboutBox = class(TForm) Panel1: TPanel; ProgramIcon: TImage; ProductName: TLabel; Version: TLabel; Copyright: TLabel; Comments: TLabel; OKButton: TButton; procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var AboutBox: TAboutBox; implementation {$R *.dfm} //удобная функция для определения версии указанного файла function FileVersion(AFileName: string): string; var szName: array[0..255] of Char; P: Pointer; Value: Pointer; Len: UINT; GetTranslationString: string; FFileName: PChar; FValid: boolean; FSize: DWORD; FHandle: DWORD; FBuffer: PChar; begin try FFileName := StrPCopy(StrAlloc(Length(AFileName) + 1), AFileName); FValid := False; FSize := GetFileVersionInfoSize(FFileName, FHandle); if FSize > 0 then try GetMem(FBuffer, FSize); FValid := GetFileVersionInfo(FFileName, FHandle, FSize, FBuffer); except FValid := False; raise; end; Result := ''; if FValid then VerQueryValue(FBuffer, '\VarFileInfo\Translation', p, Len) else p := nil; if P <> nil then GetTranslationString := IntToHex(MakeLong(HiWord(Longint(P^)), LoWord(Longint(P^))), 8); if FValid then begin StrPCopy(szName, '\StringFileInfo\' + GetTranslationString + '\FileVersion'); if VerQueryValue(FBuffer, szName, Value, Len) then Result := StrPas(PChar(Value)); end; finally try if FBuffer <> nil then FreeMem(FBuffer, FSize); except end; try StrDispose(FFileName); except end; end; end; procedure TAboutBox.FormShow(Sender: TObject); begin Version.Caption := 'v '+copy(FileVersion(ParamStr(0)), 1, 3); end; end.
UNIT user; INTERFACE USES fct, fct2, Crt, digramme, phrases; (* Déclaration des fonctions utilisables par le programme principal *) PROCEDURE creeMotAleatoireUtilisateur(val : Integer); procedure repeterFonction(fct:String; nombre:Integer; taille : Integer; fileName: String); IMPLEMENTATION USES cmd; (* Déclaration des constantes utilisées *) CONST nombreLettreAlphabet = 43; (* ------------------------------------------------------------------------------------ -- PROCEDURE : creeMotAleatoireUtilisateur() -- Auteur : toto noName <toto.noName@eisti.eu> -- Date de creation : Tue Dec 11 14:51:33 2018 -- -- But : demander à l'utilisateur un entier et appelle la fonction creemotaleatoire() -- Remarques : Aucune -- Pré conditions : Préconditions -- Post conditions : But ------------------------------------------------------------------------------------*) PROCEDURE creeMotAleatoireUtilisateur(val :Integer); BEGIN WRITELN(creeMotAleatoire(val)); END; procedure creeMotDigrammeUtilisateur(val: Integer; tableauxDigramme :tbx); begin writeln(creeMotDigramme(val,tableauxDigramme)); end; procedure creePhraseUtilisateur; begin writeln(genererUnePhrase()); end; procedure repeterFonction(fct:String; nombre:Integer; taille : Integer; fileName: String); var i, tailleGeneree : integer; tableauxDigramme : tbx; begin clear(); if fct = 'd' then begin tableauxDigramme := creerDigrammeUtilisateur(fileName); end; for i:= 1 to nombre do begin tailleGeneree := taille; if taille = 0 then begin tailleGeneree := Random(6)+5; {Random(6) génère un nombre entre [1;5[, on y ajoute 5 pour avoir l'intervalle [5:10]} end; case fct of 'a' : creeMotAleatoireUtilisateur(tailleGeneree); 'd' : creeMotDigrammeUtilisateur(tailleGeneree, tableauxDigramme); 'p' : creePhraseUtilisateur(); ELSE afficherCommandes(); end; end; end; END.
// // Statistics Library // Earl F. Glynn, August 1997 // Parabolic fit added April 1998 // UNIT StatisticsLibrary; INTERFACE USES Math; {MaxDouble} CONST NAN = MaxDouble / 2.0; {Get "Not a Number" properly defined someday} TYPE {===================================================================} TDescriptiveStatistics = CLASS(TObject) PROTECTED FCount : INTEGER; FMaxValue : DOUBLE; FMinValue : DOUBLE; FSum : DOUBLE; FSumOfSquares: DOUBLE; PUBLIC PROPERTY Count : INTEGER READ FCount; PROPERTY MaxValue: DOUBLE READ FMaxValue; PROPERTY MinValue: DOUBLE READ FMinValue; PROPERTY Sum : DOUBLE READ FSum; CONSTRUCTOR Create; PROCEDURE NextValue(CONST x: DOUBLE); FUNCTION MeanValue : DOUBLE; FUNCTION StandardDeviation: DOUBLE; PROCEDURE ResetValues; END; {===================================================================} // Formulas from HP-45 Applications Book, pp. 72, 77, 1974 TLinearRegression = CLASS(TObject) PROTECTED FCount : INTEGER; FSumX : DOUBLE; FSumXSquared: DOUBLE; FSumY : DOUBLE; FSumYSquared: DOUBLE; FSumXY : DOUBLE; PUBLIC CONSTRUCTOR Create; FUNCTION CorrelationCoefficient: DOUBLE; PROCEDURE GetLineCoefficients(VAR A,B: DOUBLE); FUNCTION RSquared: DOUBLE; PROCEDURE NextValue(CONST x, y: DOUBLE); PROCEDURE ResetValues; END; {===================================================================} TParabolicFit = CLASS(TObject) PROTECTED FCount : INTEGER; FSumX : ARRAY[1..4] OF DOUBLE; FSumXY : ARRAY[1..3] OF DOUBLE; PUBLIC CONSTRUCTOR Create; PROCEDURE GetCoefficients(VAR A,B,C: DOUBLE); PROCEDURE NextValue(CONST x, y: DOUBLE); PROCEDURE ResetValues; END; {===================================================================} FUNCTION MedianInteger(x: ARRAY OF INTEGER): INTEGER; IMPLEMENTATION USES SysUtils; // EInvalidOp {=====================================================================} // 2-by-2 determinant FUNCTION Det2(CONST a,b, c,d: DOUBLE): DOUBLE; BEGIN RESULT := a*d - b*c END {Det2}; FUNCTION Det3(CONST a,b,c, d,e,f, g,h,i: DOUBLE): DOUBLE; BEGIN RESULT := a*Det2(e,f, h,i) - b*Det2(d,f, g,i) + c*Det2(d,e, g,h) END {Det3}; {==== TDescriptiveStatistics =========================================} CONSTRUCTOR TDescriptiveStatistics.Create; BEGIN ResetValues END {Create}; PROCEDURE TDescriptiveStatistics.NextValue (CONST x: DOUBLE); BEGIN INC(FCount); FSum := FSum + x; FSumOfSquares := FSumOfSquares + x*x; IF x > FMaxValue THEN FmaxValue := x; IF x < FMinValue THEN FMinValue := x END {NextNumber}; FUNCTION TDescriptiveStatistics.MeanValue: DOUBLE; BEGIN IF FCount = 0 THEN RESULT := NAN ELSE RESULT := FSum / FCount END {MeanValue}; FUNCTION TDescriptiveStatistics.StandardDeviation: DOUBLE; BEGIN IF FCount < 2 THEN RESULT := NAN ELSE RESULT := SQRT( (FSumOfSquares - (FSum*FSum / FCount)) / (FCount - 1) ) END {StandardDeviation}; PROCEDURE TDescriptiveStatistics.ResetValues; BEGIN FCount := 0; FMinValue := MaxDouble; FMaxValue := -MaxDouble; FSum := 0.0; FSumOfSquares := 0.0 END {ResetValues}; {==== TLinearRegression ==============================================} CONSTRUCTOR TLinearRegression.Create; BEGIN ResetValues END {Create}; {Formulas from HP-45 Applications Book, p. 77, 1974} PROCEDURE TLinearRegression.GetLineCoefficients(VAR A,B: DOUBLE); BEGIN IF FCount < 1 THEN BEGIN A := NAN; B := NAN END ELSE BEGIN A := (FSumXY - FSumX*FSumY/FCount) / (FSumXSquared - FSumX*FSumX/FCount); B := (FSumY - A*FSumX)/FCount END END {GetLineCoefficients}; {Formula from HP-45 Applications Book, p. 72, 1974} FUNCTION TLinearRegression.CorrelationCoefficient: DOUBLE; VAR numerator : DOUBLE; denominator: DOUBLE; BEGIN IF FCount < 2 THEN RESULT := NAN ELSE BEGIN numerator := FSumXY - FSumX*FSumY/FCount; denominator := SQRT( (FSumXSquared - FSumX*FSumX/FCount)* (FSumYSquared - FSumY*FSumY/FCount) ); TRY RESULT := numerator / denominator EXCEPT On EInvalidOp DO IF (numerator = 0.0) AND (denominator = 0.0) THEN RESULT := 1.0 // all zeros have "perfect" correlation ELSE RESULT := NAN; END END END {CorrelationCoefficient}; FUNCTION TLinearRegression.RSquared: DOUBLE; BEGIN RESULT := 0.0 {FIX THIS} END {RSquared}; PROCEDURE TLinearRegression.NextValue(CONST x, y: DOUBLE); BEGIN INC(FCount); FSumX := FSumX + x; FSumXSquared := FSumXSquared + x*x; FSumY := FSumY + y; FSumYSquared := FSumYSquared + y*y; FSumXY := FSumXY + x*y END {NextValue}; PROCEDURE TLinearRegression.ResetValues; BEGIN FCount := 0; FSumX := 0.0; FSumXSquared := 0.0; FSumY := 0.0; FSumYSquared := 0.0; FSumXY := 0.0 END {ResetValues}; {==== TParabolicFit ==================================================} // Use "brute force" for now CONSTRUCTOR TParabolicFit.Create; BEGIN ResetValues END {Create}; PROCEDURE TParabolicFit.GetCoefficients(VAR A,B,C: DOUBLE); VAR denominator: DOUBLE; BEGIN denominator := Det3(FCount, FSumX[1], FSumX[2], FSumX[1], FSumX[2], FSumX[3], FSumX[2], FSumX[3], FSumX[4]); IF (FCount < 3) OR (ABS(denominator - 1E-5) <= 1E-5) THEN BEGIN A := NAN; B := NAN; C := NAN; END ELSE BEGIN A := Det3(FSumXY[1], FSumX[1], FSumX[2], FSumXY[2], FSumX[2], FSumX[3], FSumXY[3], FSumX[3], FSumX[4]) / denominator; B := Det3(FCount, FSumXY[1], FSumX[2], FSumX[1], FSumXY[2], FSumX[3], FSumX[2], FSumXY[3], FSumX[4]) / denominator; C := Det3(FCount, FSumX[1], FSumXY[1], FSumX[1], FSumX[2], FSumXY[2], FSumX[2], FSumX[3], FSumXY[3]) / denominator; END END {GetCoefficients}; PROCEDURE TParabolicFit.NextValue(CONST x, y: DOUBLE); VAR Term: DOUBLE; BEGIN INC(FCount); FSumX[1] := FSumX[1] + x; Term := x*x; FSumX[2] := FSumX[2] + Term; Term := Term*x; FSumX[3] := FSumX[3] + Term; Term := Term*x; FSumX[4] := FSumX[4] + Term; FSumXY[1] := FSumXY[1] + y; Term := x*y; FSumXY[2] := FSumXY[2] + Term; Term := Term*x; FSumXY[3] := FSumXY[3] + Term END {NextValue}; PROCEDURE TParabolicFit.ResetValues; VAR i: INTEGER; BEGIN FCount := 0; FOR i := Low(FSumx) TO High(FSumX) DO FSumX[i] := 0.0; FOR i := Low(FSumXY) TO High(FSumXY) DO FSumXY[i] := 0.0 END {ResetValues}; {==== Median =========================================================} FUNCTION MedianInteger (x: ARRAY OF INTEGER): INTEGER; VAR i : INTEGER; j : INTEGER; Middle : INTEGER; Temporary: INTEGER; BEGIN {Use truncated selection sort to find median} Middle := (High(x)+1) DIV 2; FOR i := 0 TO Middle DO BEGIN FOR j := 1 TO High(x)-i DO BEGIN IF x[j] > x[j-1] THEN BEGIN Temporary := x[j]; x[j] := x[j-1]; x[j-1] := Temporary END END END; IF Odd(High(x)) THEN BEGIN {When High(x) is Odd, there are an even number of elements in array. Define median as average of two middle values.} RESULT := (x[middle] + x[middle-1]) DIV 2 END ELSE BEGIN {When High(x) is Even, there are an odd number of elements in array. Median is the middle value.} RESULT := x[middle] END END {MedianInteger}; {=====================================================================} END.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit UrlHelpersImpl; interface {$MODE OBJFPC} {$MODESWITCH TYPEHELPERS} {$H+} uses sysutils; type (*!------------------------------------------------ * Type helper for url string * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TUrlHelper = type helper(TStringHelper) for string public (*!------------------------------------------------ * url encode *------------------------------------------------- * @author Zamrony P. Juhara <zamronypj@yahoo.com> * @author BenJones * @credit http://forum.lazarus.freepascal.org/index.php?topic=15088.0 *-----------------------------------------------*) function urlEncode() : string; (*!------------------------------------------------ * url decode *------------------------------------------------- * @author Zamrony P. Juhara <zamronypj@yahoo.com> * @author BenJones * @credit http://forum.lazarus.freepascal.org/index.php?topic=15088.0 *-----------------------------------------------*) function urlDecode() : string; (*!------------------------------------------------ * remove query string part from URL *------------------------------------------------- * @return url without query string *----------------------------------------------- * Example: * url := 'http://fanoframework.github.io?id=1' * strippedUrl := url.stripQueryString(); * * strippedUrl will contains * 'http://fanoframework.github.io' *-----------------------------------------------*) function stripQueryString() : string; end; implementation (*!------------------------------------------------ * url encode *------------------------------------------------- * @author Zamrony P. Juhara <zamronypj@yahoo.com> * @author BenJones * @credit http://forum.lazarus.freepascal.org/index.php?topic=15088.0 *-----------------------------------------------*) function TUrlHelper.urlEncode() : string; const safeMask = ['A'..'Z', '0'..'9', 'a'..'z', '*', '@', '.', '_', '-']; var x, len : integer; begin //Init result := ''; len := self.length; for x := 1 to len do begin //Check if we have a safe char if (self[x] in safeMask) then begin //Append all other chars result := result + self[x]; end else if (self[x] = ' ') then begin //Append space result := result + '+'; end else begin //Convert to hex result := result + '%' + (ord(self[x])).tohexString(2); end; end; end; (*!------------------------------------------------ * url decode *------------------------------------------------- * @author Zamrony P. Juhara <zamronypj@yahoo.com> * @author BenJones * @credit http://forum.lazarus.freepascal.org/index.php?topic=15088.0 *-----------------------------------------------*) function TUrlHelper.urlDecode() : string; var x, len: integer; ch: char; sVal: string; begin //Init result := ''; x := 1; len := self.length; while x <= len do begin //Get single char ch := self[x]; if (ch = '+') then begin //Append space result := result + ' '; end else if (ch <> '%') then begin //Append other chars result := result + ch; end else begin //Get value sVal := '$' + self.substring(x, 2); //Convert sval to int then to char result := result + char(sVal.toInteger()); //Inc counter by 2 inc(x, 2); end; //Inc counter inc(x); end; end; (*!------------------------------------------------ * remove query string part from URL *------------------------------------------------- * @return url without query string *----------------------------------------------- * Example: * url := 'http://abc.io?id=1' * strippedUrl := url.stripQueryString(); * * strippedUrl will contains * 'http://abc.io' *-----------------------------------------------*) function TUrlHelper.stripQueryString() : string; var queryStrPos : integer; begin queryStrPos := pos('?', self); if (queryStrPos = 0) then begin //no query string result := self; end else begin result := system.copy(self, 1, queryStrPos - 1); end; end; end.
unit AuxVariantFunctions; interface uses Variants; function VarIsNullOrEmpty(const Value: Variant): Boolean; implementation function VarIsNullOrEmpty(const Value: Variant): Boolean; begin Result := VarIsNull(Value) or VarIsEmpty(Value); end; end.
{ Memanggil kode C dari Pascal Menggunakan Win32 API untuk memuat isi pustaka ke memory dan mendapatkan alamat fungsi yang dibutuhkan. Explicit linking. Compile: [fpc] (x64) $ fpc -Px86_64 invoker.pas (x86) $ fpc -Pi386 invoker.pas Run: $ invoker.exe } program invoker; {$mode objfpc}{$H+} uses dynlibs, SysUtils, Windows; { Setiap fungsi memiliki type signature yang memberikan beberapa informasi, seperti: - type dari return value; - jumlah argument; - type dari setiap argument. Fungsi GetProcAddress() hanya mengembalikan alamat dari suatu fungsi. Fungsi ini kemudian diperlakukan sebagai sebuah function pointer melalui typecasting. Dengan demikian, user bertanggung jawab untuk melakukan typecast ke signature yang tepat. } { Buat alias / typedef } type TLibPrint = procedure(msg: PChar); var result : integer; lib_print : TLibPrint; handle : TLibHandle; begin { Memuat modul DLL ============================================================ } { Sebelum mendapatkan alamat dari fungsi terlebih dahulu kita harus memuat pustaka ke memory dan memetakannya ke area yang masih tersedia. Kita dapat menyerahkan tanggung jawab ini ke API } handle := LoadLibrary('called.dll'); if handle = NILHandle then begin MessageBox(0,PChar('Tidak dapat memuat file DLL'), PChar('Error'), mb_ok); exit; end; { Cari fungsi berdasarkan nama ================================================ } Pointer(lib_print) := GetProcAddress(handle, 'lib_print'); { Periksa apakah ada fungsi yang tak dapat ditemukan } if (@lib_print = nil) then begin MessageBox(NULL, PChar('Tidak dapat menemukan fungsi'), PChar('Error'), mb_ok); exit; end; { Panggil fungsi ============================================================= } lib_print(PChar('Halo dunia!')); { Bebaskan area memory jika modul DLL tak terpakai lagi. } UnLoadLibrary(handle); end.
unit etalon_dlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxCntner, IBSQL, IBDatabase, DB, uZMaster, ExtCtrls, ComCtrls, kernel_h, IB, dxEditor, dxExEdtr, dxEdLib, secure_h; type Tfetalon_dlg = class(TForm) base: TIBDatabase; trR: TIBTransaction; qR: TIBSQL; qW: TIBSQL; trW: TIBTransaction; scStyle: TdxEditStyleController; master: ZMaster; p_pages: TPageControl; procedure masterMasterResult(Sender: TObject; MasterResult: ZMasterResult); virtual; procedure EditsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); virtual; procedure EditsKeyPress(Sender: TObject; var Key: Char); virtual; procedure EditsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); virtual; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); virtual; private { Private declarations } public id: ZFuncArgs; prm: ZVelesInfoRec; procedure InitInfo; virtual; procedure InitINS; virtual; procedure InitUPD; virtual; procedure InitControls; virtual; function AnalizChanges: integer; virtual; procedure ApplyChanges; virtual; procedure ApplyControls; virtual; procedure ApplyINS; virtual; procedure ApplyUPD; virtual; procedure ApplyDefault; virtual; procedure ListInit(ed_list: TdxImageEdit; sql_fill: string); procedure ListClear(ed_list: TdxImageEdit); function GetNextID(gen_name: string): integer; end; function IntToBool(ival: integer): boolean; function BoolToInt(bval: boolean): integer; var fetalon_dlg: Tfetalon_dlg; implementation {$R *.dfm} procedure Tfetalon_dlg.InitInfo; var i: integer; panel: TPanel; begin base.SetHandle(prm.db_handle); for i:=0 to p_pages.PageCount - 1 do begin panel := TPanel(p_pages.Pages[i].Controls[0]); master.PageAdd(p_pages.Pages[i].Caption, panel); end; if (id.id <= 0) then InitINS else InitUPD; InitControls; AutoSize := true; Position := poScreenCenter; end; procedure Tfetalon_dlg.InitINS; begin end; procedure Tfetalon_dlg.InitUPD; begin end; procedure Tfetalon_dlg.InitControls; begin end; function Tfetalon_dlg.AnalizChanges: integer; begin AnalizChanges := 0; end; procedure Tfetalon_dlg.ApplyChanges; begin // Підготовка даних ApplyControls; try if(trW.InTransaction)then trW.Commit; trW.StartTransaction; if id.id <= 0 then begin ApplyINS; end else if id.id > 0 then begin ApplyUPD; end; ApplyDefault; if(trW.InTransaction) then trW.Commit; except on E: EIBInterbaseError do begin if trW.InTransaction then trW.Rollback; ShowMessage(Format('Відбувся збій: %s Повідомте розробників про помилку.', [#13 + E.Message + #13])); ModalResult := mrNone; end; end; end; procedure Tfetalon_dlg.ApplyControls; begin end; procedure Tfetalon_dlg.ApplyINS; begin end; procedure Tfetalon_dlg.ApplyUPD; begin end; procedure Tfetalon_dlg.ApplyDefault; begin end; procedure Tfetalon_dlg.EditsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ((ssCtrl in Shift) and (Key = 13)) then masterMasterResult(master, MasterResultOk); if ((ssCtrl in Shift) and (Key = VK_LEFT)) then begin if master.PageIndex > 0 then master.PageIndex := master.PageIndex - 1; end; if ((ssCtrl in Shift) and (Key = VK_RIGHT)) then begin if master.PageIndex < master.PagesCount - 1 then master.PageIndex := master.PageIndex + 1; end; if (Key = VK_ESCAPE) then masterMasterResult(master, MasterResultCancel); end; procedure Tfetalon_dlg.EditsKeyPress(Sender: TObject; var Key: Char); var currWin: TWinControl; begin currWin := TWinControl(Sender); if (Key = Char(13)) then master.SetFocusAtNextEdit(TControl(currWin)); if (Sender.ClassName = 'TdxCalcEdit') then begin if ((Key = '.') or (Key = ',')) then Key := ',' else if (Key < '0') or (Key > '9') then Key := #0; end end; procedure Tfetalon_dlg.EditsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin // end; procedure Tfetalon_dlg.masterMasterResult(Sender: TObject; MasterResult: ZMasterResult); begin if MasterResult = MasterResultOk then begin if AnalizChanges = 0 then begin ModalResult := mrOk; ApplyChanges; end else ModalResult := mrNone; end else if MasterResult = MasterResultCancel then ModalResult := mrCancel; end; procedure Tfetalon_dlg.FormShow(Sender: TObject); begin master.PageIndex := 0; end; procedure Tfetalon_dlg.FormDestroy(Sender: TObject); begin // end; // Процедура заповнення випадаючого списку з запроса procedure Tfetalon_dlg.ListInit(ed_list: TdxImageEdit; sql_fill: string); begin if(trR.InTransaction)then trR.Commit; trR.StartTransaction; qR.SQL.Text := sql_fill; qR.ExecQuery; while not qR.Eof do begin ed_list.Descriptions.Add(qR.FieldByName('name').AsString); ed_list.Values.Add(qR.FieldByName('id').AsString); qR.Next; end; if(trR.InTransaction) then trR.Commit; end; procedure Tfetalon_dlg.ListClear(ed_list: TdxImageEdit); begin ed_list.Descriptions.Clear; ed_list.Values.Clear; end; // Генерація id для gen_name генератора function Tfetalon_dlg.GetNextID(gen_name: string): integer; var new_id: Integer; begin if(trR.InTransaction)then trR.Commit; trR.StartTransaction; qR.SQL.Text := 'select GEN_ID(' + gen_name + ',1) as oid from RDB$DATABASE'; qR.ExecQuery; new_id := qR.FieldByName('oid').AsInteger; if(trR.InTransaction)then trR.Commit; Result := new_id; end; function IntToBool(ival: integer): boolean; begin IntToBool := (ival <> 0); end; function BoolToInt(bval: boolean): integer; begin if bval then BoolToInt := 1 else BoolToInt := 0; end; end.
unit EspecificacaoCFOPporTipo; interface uses TipoNaturezaOperacao, Especificacao; type TEspecificacaoCFOPporTipo = class(TEspecificacao) private FTipo :TTipoNaturezaOperacao; public constructor Create(TipoNatureza :TTipoNaturezaOperacao); public function SatisfeitoPor(pCFOP :TObject) :Boolean; override; end; implementation uses CFOP, SysUtils; { TEspecificacaoCFOPporTipo } constructor TEspecificacaoCFOPporTipo.Create(TipoNatureza: TTipoNaturezaOperacao); begin self.FTipo := TipoNatureza; end; function TEspecificacaoCFOPporTipo.SatisfeitoPor(pCFOP: TObject): Boolean; var CFOP :TCFOP; begin try CFOP := (pCFOP as TCFOP); except on E: EInvalidCast do raise EInvalidCast.Create('Erro em TEspecificacaoNaturezaPorTipo.SatisfeitoPor(Natureza: TObject): Boolean; '+ 'O parâmetro passado não é do tipo TNaturezaOperacao. Entre em contato com o suporte!'); end; result := (self.FTipo = CFOP.Tipo); end; end.
unit uClasseOperacoes; interface uses uInterfaceObjeto, System.Generics.Collections, uCalculadoraEventos; type TOperacoes = class(TInterfacedObject, iOperacoes, iOperacoesDisplay) protected FLista: TList<Double>; FEventoDisplay: TEventoDisplay; procedure DisplayValue(Value: String); public function Executar: string; virtual; function Display: iOperacoesDisplay; function Resultado(Value: TEventoDisplay): iOperacoesDisplay; function EndDisplay: iOperacoes; end; implementation { TOperacoes } function TOperacoes.Display: iOperacoesDisplay; begin Result := Self; end; procedure TOperacoes.DisplayValue(Value: String); begin if Assigned(FEventoDisplay) then FEventoDisplay(Value); end; function TOperacoes.EndDisplay: iOperacoes; begin Result := Self; end; function TOperacoes.Executar: string; begin FLista.Clear; end; function TOperacoes.Resultado(Value: TEventoDisplay): iOperacoesDisplay; begin Result := Self; FEventoDisplay := Value; end; end.
unit UAdvAboneRegist; interface uses Windows, Messages, Classes, Graphics, Controls, Forms, StdCtrls, UNGWordsAssistant, JLXPSpin; type TChangeNameQueryEvent = procedure(Sender: TObject; OldName, NewName: String; var CanChange: Boolean) of object; TAdvAboneRegist = class(TForm) EditNGName: TEdit; ComboBoxNGNameType: TComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; EditNGMail: TEdit; ComboBoxNGMailType: TComboBox; Label4: TLabel; EditNGId: TEdit; ComboBoxNGIdType: TComboBox; Label5: TLabel; ComboBoxNGWordType: TComboBox; Label6: TLabel; ButtonOK: TButton; ButtonCancel: TButton; ComboBoxAboneType: TComboBox; SpinEditLifeSpan: TJLXPSpinEdit; Label7: TLabel; EditName: TEdit; EditNGWord: TEdit; ButtonRename: TButton; ComboBoxNGURLType: TComboBox; Label8: TLabel; EditNGURL: TEdit; procedure FormCreate(Sender: TObject); procedure ComboBoxNGChange(Sender: TObject); procedure EditNGChange(Sender: TObject); procedure MiscOnChange(Sender: TObject); procedure ButtonRenameClick(Sender: TObject); procedure EditNameExit(Sender: TObject); protected ComboBoxNGItems: array[TNGExItemIdent] of TComboBox; EditNGItems : array[TNGExItemIdent] of TEdit; FItemName: String; FOnChangeNameQuery: TChangeNameQueryEvent; function Validate: Boolean; function ChangeNameQuery(OldName, NewName: String): Boolean; public function ShowModal(var ItemName: string; Item: TExNgItem): Integer; reintroduce; published property OnChangeNameQuery: TChangeNameQueryEvent read FOnChangeNameQuery write FOnChangeNameQuery; end; var AdvAboneRegist: TAdvAboneRegist; implementation {$R *.dfm} //Create時にコンポーネント配列を設定 procedure TAdvAboneRegist.FormCreate(Sender: TObject); begin ComboBoxNGItems[NGEX_ITEM_NAME] := ComboBoxNGNameType; ComboBoxNGItems[NGEX_ITEM_MAIL] := ComboBoxNGMailType; ComboBoxNGItems[NGEX_ITEM_MSG] := ComboBoxNGWordType; ComboBoxNGItems[NGEX_ITEM_ID] := ComboBoxNGIdType; ComboBoxNGItems[NGEX_ITEM_URL] := ComboBoxNGURLType; EditNGItems[NGEX_ITEM_NAME] := EditNGName; EditNGItems[NGEX_ITEM_MAIL] := EditNGMail; EditNGItems[NGEX_ITEM_MSG] := EditNGWord; EditNGItems[NGEX_ITEM_ID] := EditNGId; EditNGItems[NGEX_ITEM_URL] := EditNGURL; end; //本体部分 (Itemの内容を表示、変更) function TAdvAboneRegist.ShowModal(var ItemName: string; Item: TExNgItem): Integer; var i: TNGExItemIdent; begin FItemName := ItemName; EditName.Text := FItemName; for i := Low(i) to High(i) do begin ComboBoxNGItems[i].ItemIndex := Item.SearchOpt[i] + 1; EditNGItems[i].Text := Item.SearchStr[i]; end; case Item.AboneType of 2: ComboBoxAboneType.ItemIndex := 1; 4: ComboBoxAboneType.ItemIndex := 2; else ComboBoxAboneType.ItemIndex := -1; end; SpinEditLifeSpan.Value := Item.LifeSpan; ButtonOK.Enabled := False; Result := inherited ShowModal; ItemName := FItemName; if Result = mrOK then begin for i := Low(i) to High(i) do begin Item.SearchOpt[i] := ComboBoxNGItems[i].ItemIndex - 1; Item.SearchStr[i] := EditNGItems[i].Text; end; case ComboBoxAboneType.ItemIndex of 1: Item.AboneType := 2; 2: Item.AboneType := 4; else Item.AboneType := 0; end; Item.LifeSpan := SpinEditLifeSpan.Value; end; end; //よろしボタンをEnableにしてもいいか判定 function TAdvAboneRegist.Validate; var i: TNGExItemIdent; NotNop: Boolean; begin Result := True; NotNop := False; for i := Low(i) to High(i) do case ComboBoxNGItems[i].ItemIndex of 0:; 3, 4: NotNop := True; else begin NotNop := True; Result := Result and (EditNGItems[i].Text <> ''); //念のため(要らないはず) end; end; Result := Result and NotNop; end; //「無視」にしたらキーワードをヌルに procedure TAdvAboneRegist.ComboBoxNGChange(Sender: TObject); var i: TNGExItemIdent; begin if (Sender as TComboBox).ItemIndex = 0 then for i := Low(i) to High(i) do if (Sender = ComboBoxNGItems[i]) then EditNGItems[i].Text := ''; ButtonOK.Enabled := Validate; end; //キーワードがヌルでなくなったら「無視」から「含む」に procedure TAdvAboneRegist.EditNGChange(Sender: TObject); var i: TNGExItemIdent; begin if (Sender as TEdit).Text <> '' then for i := Low(i) to High(i) do if (Sender = EditNGItems[i]) and (ComboBoxNGItems[i].ItemIndex = 0) then ComboBoxNGItems[i].ItemIndex := 1; ButtonOK.Enabled := Validate; end; //寿命、あぼーんタイプの変更でもよろしボタンをEnableに procedure TAdvAboneRegist.MiscOnChange(Sender: TObject); begin ButtonOK.Enabled := Validate; end; //名前の変更開始 procedure TAdvAboneRegist.ButtonRenameClick(Sender: TObject); begin EditName.ReadOnly := False; EditName.Color := clWindow; EditName.SetFocus; end; //名前の変更後のチェック procedure TAdvAboneRegist.EditNameExit(Sender: TObject); begin if EditName.Text = '' then EditName.Text := FItemName else if EditName.Text <> FItemName then begin if ChangeNameQuery(FItemName, EditName.Text) then FItemName := EditName.Text else EditName.Text := FItemName; end; EditName.ReadOnly := True; EditName.Color := clBtnFace; end; //名前変更イベントの生成 function TAdvAboneRegist.ChangeNameQuery(OldName, NewName: String): Boolean; begin Result := True; if Assigned(FOnChangeNameQuery) then FOnChangeNameQuery(Self, OldName, NewName, Result); end; end.
unit PG; interface uses NLO, SignalField, Func1D, Numerics, FrogTrace; type TPG = class(TNLOInteraction) public procedure MakeSignalField(pEk: TEField; pEsig: TSignalField); override; procedure MakeXSignalField(pEk, pERef: TEField; pEsig: TSignalField); override; procedure GDerivative(pEk: TEField; pEsig: TSignalField; pFrogI: TFrogTrace; Derivs: PArray); override; function Z(pEx: PArray; pEsig: TSignalField): double; override; procedure ZDerivative(pEk: TEField; pEsig: TSignalField; Derivs: PArray); override; function XFrogZ(pEx: PArray; pERef: TEField; pEsig: TSignalField): double; override; procedure XFrogZDerivative(pEk, pERef: TEField; pEsig: TSignalField; Derivs: PArray); override; procedure BasicField(pEsig: TSignalField; pEk: TEField); override; procedure GateField(pEsig: TSignalField; pEk: TEField); override; function CalculateMarginal(pSpec: TSpectrum; pAuto: TAutocorrelation; pSHGSpec: TSpectrum): TMarginal; override; function Name: string; override; function SpectrumMultiplier: double; override; function NeedSpectrum: Boolean; override; function NeedAutocorrelation: Boolean; override; function NeedSHGSpectrum: Boolean; override; function XTestLam(frogLam, refLam: double): double; override; function XFrogLam(refLam, testLam: double): double; override; constructor Create; override; end; implementation uses ReadIn; constructor TPG.Create; begin inherited; mNLOType := nlPG; end; function TPG.Name: string; begin Name := 'PG'; end; function TPG.SpectrumMultiplier: double; begin SpectrumMultiplier := 1.0; end; procedure TPG.BasicField(pEsig: TSignalField; pEk: TEField); var w, tau, N: integer; begin N := pEsig.N; for w := 0 to N - 1 do begin pEk.Re^[w] := 0.0; pEk.Im^[w] := 0.0; end; // Sum over tau for tau := 0 to N - 1 do begin for w := 0 to N - 1 do begin pEk.Re^[w] := pEk.Re^[w] + pEsig.Re^[tau*N + w]; pEk.Im^[w] := pEk.Im^[w] + pEsig.Im^[tau*N + w]; end; end; // Back to the Time domain pEk.InverseTransform; end; procedure TPG.GateField(pEsig: TSignalField; pEk: TEField); var localIntensity, corr, re, im: double; w, N, tau, minusT: integer; begin // Don't forget, for PG the gate is real so you have to mult by the complex field pEk.SetIntensityAndPhase; N := pEk.N; for tau := 0 to N - 1 do begin re := 0; im := 0; for w := 0 to N - 1 do begin re := re + pEsig.Re^[tau*N + w]; im := im + pEsig.Im^[tau*N + w]; end; localIntensity := sqrt(re*re + im*im); minusT := N - 1 - tau; if pEk.Intensity^[minusT] = 0 then Continue; corr := sqrt(Abs(localIntensity)/pEk.Intensity^[minusT]); pEk.Re^[minusT] := pEk.Re^[minusT]*corr; pEk.Im^[minusT] := pEk.Im^[minusT]*corr; end; end; procedure TPG.MakeSignalField(pEk: TEField; pEsig: TSignalField); var tau, t, t0, N, tp: integer; inten: double; begin N := pEk.N; t0 := N div 2; for tau := 0 to N - 1 do begin for t := 0 to N - 1 do begin tp := t - (tau - t0); if (tp < 0) or (tp >= N) then begin pEsig.Re^[tau*N + t] := 0.0; pEsig.Im^[tau*N + t] := 0.0; Continue; end; inten := pEk.Re^[tp]*pEk.Re^[tp] + pEk.Im^[tp]*pEk.Im^[tp]; pEsig.Re^[tau*N + t] := pEk.Re^[t]*inten; pEsig.Im^[tau*N + t] := pEk.Im^[t]*inten; end; end; // To the w domain pEsig.TransformToFreq; end; // For XFrog procedure TPG.MakeXSignalField(pEk, pERef: TEField; pEsig: TSignalField); var tau, t, t0, N, tp: integer; inten: double; begin N := pEk.N; t0 := N div 2; for tau := 0 to N - 1 do begin for t := 0 to N - 1 do begin tp := t - (tau - t0); if (tp < 0) or (tp >= N) then begin pEsig.Re^[tau*N + t] := 0.0; pEsig.Im^[tau*N + t] := 0.0; Continue; end; inten := pERef.Re^[tp]*pERef.Re^[tp] + pERef.Im^[tp]*pERef.Im^[tp]; pEsig.Re^[tau*N + t] := pEk.Re^[t]*inten; pEsig.Im^[tau*N + t] := pEk.Im^[t]*inten; end; end; // To the w domain pEsig.TransformToFreq; end; function TPG.Z(pEx: PArray; pEsig: TSignalField): double; var t, tau, tp, N, N2, tr, ti, tpr, tpi: integer; sum, sigr, sigi, re, im, inten: double; begin N := pEsig.N; N2 := N div 2; sum := 0.0; for t := 0 to N - 1 do for tau := 0 to N - 1 do begin tp := t - (tau - N2); if (tp >= 0) and (tp < N) then begin tr := 2*t; ti := tr + 1; tpr := 2*tp; tpi := tpr + 1; inten := pEx^[tpr]*pEx^[tpr] + pEx^[tpi]*pEx^[tpi]; sigr := inten*pEx^[tr]; sigi := inten*pEx^[ti]; end else begin sigr := 0.0; sigi := 0.0; end; re := pEsig.Re^[tau*N + t] - sigr; im := pEsig.Im^[tau*N + t] - sigi; sum := sum + re*re + im*im; end; Z := sum; end; procedure TPG.ZDerivative(pEk: TEField; pEsig: TSignalField; Derivs: PArray); var t, tp, tau, N, N2, vr, vi: integer; sigr, sigi, inten, brakr, braki, re, im: double; begin N := pEk.N; N2 := N div 2; pEk.SetIntensityAndPhase; for t := 0 to N - 1 do begin vr := t*2; vi := vr + 1; Derivs^[vr] := 0.0; Derivs^[vi] := 0.0; for tau := 0 to N - 1 do begin tp := t - (tau - N2); if (tp >= 0) and (tp < N) then begin inten := pEk.Intensity^[tp]; sigr := inten*pEk.Re^[t]; sigi := inten*pEk.Im^[t]; end else begin sigr := 0.0; sigi := 0.0; inten := 0.0; end; // End of check tp brakr := pEsig.Re^[tau*N + t] - sigr; braki := pEsig.Im^[tau*N + t] - sigi; Derivs^[vr] := Derivs^[vr] - 2*inten*brakr; Derivs^[vi] := Derivs^[vi] - 2*inten*braki; tp := t + tau - N2; if (tp < 0) or (tp >= N) then begin re := 0.0; im := 0.0; end else begin re := pEk.Re^[tp]; im := pEk.Im^[tp]; inten := pEk.Intensity^[t]; brakr := pEsig.Re^[tau*N + tp] - pEk.Re^[tp]*inten; braki := pEsig.Im^[tau*N + tp] - pEk.Im^[tp]*inten; end; Derivs^[vr] := Derivs^[vr] - 4*pEk.Re^[t]*(re*brakr + im*braki); Derivs^[vi] := Derivs^[vi] - 4*pEk.Im^[t]*(re*brakr + im*braki); end; // end of tau loop Derivs^[vr] := Derivs^[vr]/(1.0*N); Derivs^[vi] := Derivs^[vi]/(1.0*N); end; // end of t loop end; function TPG.XFrogZ(pEx: PArray; pERef: TEField; pEsig: TSignalField): double; var t, tau, tp, N, N2, tr, ti: integer; sum, sigr, sigi, re, im, inten: double; begin N := pEsig.N; N2 := N div 2; sum := 0.0; for t := 0 to N - 1 do for tau := 0 to N - 1 do begin tp := t - (tau - N2); if (tp >= 0) and (tp < N) then begin tr := 2*t; ti := tr + 1; inten := pERef.Intensity^[tp]; sigr := inten*pEx^[tr]; sigi := inten*pEx^[ti]; end else begin sigr := 0.0; sigi := 0.0; end; re := pEsig.Re^[tau*N + t] - sigr; im := pEsig.Im^[tau*N + t] - sigi; sum := sum + re*re + im*im; end; XFrogZ := sum; end; procedure TPG.XFrogZDerivative(pEk, pERef: TEField; pEsig: TSignalField; Derivs: PArray); var t, tp, tau, N, N2, vr, vi: integer; sigr, sigi, inten, brakr, braki: double; begin N := pEk.N; N2 := N div 2; pEk.SetIntensityAndPhase; for t := 0 to N - 1 do begin vr := t*2; vi := vr + 1; Derivs^[vr] := 0.0; Derivs^[vi] := 0.0; for tau := 0 to N - 1 do begin tp := t - (tau - N2); if (tp >= 0) and (tp < N) then begin inten := pERef.Intensity^[tp]; sigr := inten*pEk.Re^[t]; sigi := inten*pEk.Im^[t]; end else begin sigr := 0.0; sigi := 0.0; inten := 0.0; end; // End of check tp brakr := pEsig.Re^[tau*N + t] - sigr; braki := pEsig.Im^[tau*N + t] - sigi; Derivs^[vr] := Derivs^[vr] - 2*inten*brakr; Derivs^[vi] := Derivs^[vi] - 2*inten*braki; end; // end of tau loop Derivs^[vr] := Derivs^[vr]/(1.0*N); Derivs^[vi] := Derivs^[vi]/(1.0*N); end; // end of t loop end; procedure TPG.GDerivative(pEk: TEField; pEsig: TSignalField; pFrogI: TFrogTrace; Derivs: PArray); var N, t, tau, w, tp, N2, jj, tw, tauw: integer; inten, fact, derv, fmax, fkmax, cc, ss, temp: double; tFrogIk: TFrogTrace; begin N := pEk.N; SetUpMinArrays(N); N2 := N div 2; pEk.SetIntensityAndPhase; tFrogIk := TRetrievedFrogTrace.Create(N); try tFrogIk.MakeTraceFrom(pEsig); fmax := pFrogI.Max; fkmax := tFrogIk.Max; for t := 0 to N - 1 do begin Derivs^[2*t] := 0.0; Derivs^[2*t + 1] := 0.0; for w := 0 to N - 1 do for tau := 0 to N - 1 do begin fact := pFrogI.Vals^[tau*N + w]/fmax - tFrogIk.Vals^[tau*N + w]/fkmax; tw := t*N + w; tauw := tau*N + w; // The deriv wrt the real part of the field tp := t - (tau - N2); if (tp < 0) or (tp >= N) then begin derv := 0.0; inten := 0.0; end else begin inten := pEk.Intensity^[tp]; derv := mC[tw]*pEsig.Re^[tauw] + mS[tw]*pEsig.Im^[tauw]; derv := derv*inten; end; tp := t + tau - N2; if (tp < 0) or (tp >= N) then temp := 0.0 else begin jj := tp*N + w; cc := mC[jj]; ss := mS[jj]; temp := (pEk.Re^[tp]*cc - pEk.Im^[tp]*ss)*pEsig.Re^[tauw] + (pEk.Re^[tp]*ss + pEk.Im^[tp]*cc)*pEsig.Im^[tauw]; end; derv := derv + (temp*2.0*pEk.Re^[t]); Derivs^[2*t] := Derivs^[2*t] - 4*fact*derv; // Now the derivative wrt the imaginary part */ // Can use the same "inten" as before */ derv := mC[tw]*pEsig.Im^[tauw] - mS[tw]*pEsig.Re^[tauw]; derv := derv*inten; // We can also use the same temp as before! */ derv := derv + (temp*2.0*pEk.Im^[t]); Derivs^[2*t+1] := Derivs^[2*t + 1] - 4*fact*derv; end; // end of tau loop end; finally tFrogIk.Free; end; for t := 0 to N - 1 do begin Derivs^[2*t] := Derivs^[2*t]/(1.0*N*N); Derivs^[2*t+1] := Derivs^[2*t+1]/(1.0*N*N); end; end; function TPG.NeedSpectrum: Boolean; begin NeedSpectrum := True; end; function TPG.NeedAutocorrelation: Boolean; begin NeedAutocorrelation := True; end; function TPG.NeedSHGSpectrum: Boolean; begin NeedSHGSpectrum := False; end; function TPG.CalculateMarginal(pSpec: TSpectrum; pAuto: TAutocorrelation; pSHGSpec: TSpectrum): TMarginal; var Spectrum: TEField; tempSpec: TSpectrum; tempAuto: TAutocorrelation; Marginal: TMarginal; ReadIn: TReadIn; N, i, maxi: integer; DelF, Lam0, max, re, im, F, T: double; begin // Find the maximum frequency range F if (pSpec.DelF*pSpec.N) > (pAuto.DelF*pAuto.N) then F := pSpec.DelF*pSpec.N else F := pAuto.DelF*pAuto.N; // Find the maximum time range T if (pSpec.DelT*pSpec.N) > (pAuto.DelT*pAuto.N) then T := pSpec.DelT*pSpec.N else T := pAuto.DelT*pAuto.N; i := Trunc(F*T); N := 2; while N < i do N := N*2; // Get the smallest DelF if pSpec.DelF < pAuto.DelF then DelF := pSpec.DelF else DelF := pAuto.DelF; max := 0; for i := 0 to pSpec.N - 1 do if pSpec.Intensity^[i] > max then begin max := pSpec.Intensity^[i]; maxi := i; end; Lam0 := (maxi - pSpec.N div 2)*pSpec.DelLam + pSpec.Lam0; ReadIn := TReadIn.Create; tempSpec := TSpectrum.Create(N); tempAuto := TAutocorrelation.Create(N); Spectrum := TEField.Create(N); Marginal := TMarginal.Create(N); tempSpec.SetMyUnits(1.0/(N*DelF), Lam0); tempAuto.SetMyUnits(tempSpec.DelT, tempSpec.Lam0); Spectrum.SetMyUnits(tempSpec.DelT, tempSpec.Lam0); Marginal.SetMyUnits(tempSpec.DelT, tempSpec.Lam0); try ReadIn.GridSpectrum(pSpec, tempSpec); for i := 0 to N - 1 do begin Spectrum.Re^[i] := tempSpec.Intensity^[i]; Spectrum.Im^[i] := 0.0; end; tempAuto.SetMyUnits(Spectrum.DelT, Spectrum.Lam0); ReadIn.GridAutocorrelation(pAuto, tempAuto); Spectrum.InverseTransform; for i := 0 to N - 1 do begin re := Spectrum.Re^[i]*tempAuto.Intensity^[i]; im := Spectrum.Im^[i]*tempAuto.Intensity^[i]; Spectrum.Re^[i] := re; Spectrum.Im^[i] := im; end; Spectrum.Transform; for i := 0 to N - 1 do Marginal.Intensity^[i] := Spectrum.Re^[i]; finally tempAuto.Free; tempSpec.Free; Spectrum.Free; ReadIn.Free; end; CalculateMarginal := Marginal; end; function TPG.XTestLam(frogLam, refLam: double): double; begin XTestLam := frogLam; end; function TPG.XFrogLam(refLam, testLam: double): double; begin XFrogLam := testLam; end; end.
unit TNsRemotePublish.Application.WarmController; interface uses System.SysUtils, System.Net.HttpClient, System.JSON, TNsRestFramework.Infrastructure.Services.Logger, TNsRestFramework.Infrastructure.HTTPControllerFactory, TNsRestFramework.Infrastructure.HTTPRestRequest, TNsRestFramework.Infrastructure.HTTPRouting, TNsRestFramework.Infrastructure.HTTPController; type TURLJSON = class public Urls : array of string; end; THTTPWarmController = class(THTTPController) private function CallURL(const URL : string) : Cardinal; public constructor Create; function ProcessRequest(Request : THTTPRestRequest) : Cardinal; override; end; var WarmController : IController; implementation { TMVCDefaultController } function THTTPWarmController.CallURL(const URL : string) : Cardinal; var client : THTTPClient; begin client := THTTPClient.Create; try Logger.Info('Warm "%s" called',[URL]); if client.Get(URL).StatusCode <> 200 then raise Exception.Create('Server returned error code') else Result := 200; finally client.Free; end; end; constructor THTTPWarmController.Create; begin inherited; fisdefault := False; froute.Name := 'warm'; froute.IsDefault := False; froute.RelativePath := 'warm'; froute.AddMethod('POST'); froute.needStaticController := False; end; {TODO -oOwner -cGeneral : Implement from JSON method} //function THTTPWarmController.GetURLSFromJSON(const Body: string): TURLJSON; //var // vJSONScenario: TJSONValue; // vJSONValue: TJSONValue; // vval2 : TJSONValue; //begin // Result := nil; // vJSONScenario := TJSONObject.ParseJSONValue(Body, False); // if vJSONScenario <> nil then // begin // try // Result := TURLJSON.Create; // if vJSONScenario is TJSONObject then // begin // if (TJSONObject(vJSONScenario) as TJSONObject).GetValue('URLS') as TJSONArray <> nil then // begin // for vJSONValue in vJSONScenario as TJSONArray do // begin // if vJSONValue is TJSONObject then // Result.Add(GetJobFromJson(TJSONObject(vJSONValue) as TJSONObject)); // end; // for vval2 in (TJSONObject(vJSONScenario) as TJSONObject).GetValue('URLS') do // begin // Result.Urls := Result.Urls + [string(vval2)]; // end; // end; // end; // finally // vJSONScenario.Free; // end; // end; //end; function THTTPWarmController.ProcessRequest(Request: THTTPRestRequest): Cardinal; var url : string; begin if Request.Method = 'POST' then begin Logger.Info('Warm method called'); for url in Request.InContent.Split([',']) do Result := CallURL(url); end else Result := 400; end; initialization WarmController := THTTPWarmController.Create; THTTPControllerFactory.Init; THTTPControllerFactory.GetInstance.Add(WarmController); end.
unit frCalendario; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Calendar, ExtCtrls, StdCtrls, calendar2, dmCalendarioValor, Buttons, ActnList, eventos, dmCalendario; type TframeCalendario = class(TFrame) Panel1: TPanel; Panel2: TPanel; Fechas: TComboBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; ActionList: TActionList; aAnterior: TAction; aSiguiente: TAction; Cerrar: TSpeedButton; procedure FechasChange(Sender: TObject); procedure FechasDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure aAnteriorExecute(Sender: TObject); procedure aAnteriorUpdate(Sender: TObject); procedure aSiguienteUpdate(Sender: TObject); procedure aSiguienteExecute(Sender: TObject); private Calendar: TCalendar2; DataCalendar: TCalendario; FOnSelectDay: TNotificacionEvent; FMinDate: TDate; procedure Initialize; procedure OnEstadoDia(const dia: integer; var enabled: boolean); procedure CalendarSelectDay(Sender: TObject); function GetDate: TDate; procedure SetMinDate(const Value: TDate); procedure SetDate(Value: TDate); function GetMaxDate: TDate; public procedure CreateCalendar(const OIDValor: integer); overload; procedure CreateCalendar; overload; property OnSelectDay: TNotificacionEvent read FOnSelectDay write FOnSelectDay; property Date: TDate read GetDate write SetDate; property MinDate: TDate read FMinDate write SetMinDate; property MaxDate: TDate read GetMaxDate; end; implementation uses DateUtils, dmData; resourcestring ENERO = 'enero'; FEBRERO = 'febrero'; MARZO = 'marzo'; ABRIL = 'abril'; MAYO = 'mayo'; JUNIO = 'junio'; JULIO = 'julio'; AGOSTO = 'agosto'; SEPTIEMBRE = 'septiembre'; OCTUBRE = 'octubre'; NOVIEMBRE = 'noviembre'; DICIEMBRE = 'diciembre'; const meses: array [1..12] of string = (ENERO, FEBRERO, MARZO, ABRIL, MAYO, JUNIO, JULIO, AGOSTO, SEPTIEMBRE, OCTUBRE, NOVIEMBRE, DICIEMBRE); SIN_VALOR = Low(integer); {$R *.dfm} procedure TframeCalendario.CalendarSelectDay(Sender: TObject); begin if DataCalendar is TCalendarioValor then Data.IrACotizacionConFecha(Calendar.CalendarDate); if Assigned(FOnSelectDay) then FOnSelectDay; end; procedure TframeCalendario.CreateCalendar; begin CreateCalendar(SIN_VALOR); end; procedure TframeCalendario.CreateCalendar(const OIDValor: integer); var ano, mes, aux: word; begin Calendar := TCalendar2.Create(Self); Calendar.Parent := Panel1; Calendar.Align := alClient; if OIDValor = SIN_VALOR then DataCalendar := TCalendario.Create(Self) else DataCalendar := TCalendarioValor.Create(Self, OIDValor); DecodeDate(DataCalendar.CurrentDate, ano, mes, aux); DataCalendar.CambiarMes(ano, mes); Calendar.CurrentDate := DataCalendar.CurrentDate; Calendar.CalendarDate := DataCalendar.CurrentDate; Calendar.MaxDate := DataCalendar.MaxDate; MinDate := DataCalendar.MinDate; Calendar.OnSelectDay := CalendarSelectDay; Calendar.OnEstadoDia := OnEstadoDia; end; procedure TframeCalendario.Initialize; var j, ano : Word; fechaMin, fechaMax: TDate; begin Fechas.Clear; fechaMin := EncodeDate(YearOf(FMinDate), MonthOf(FMinDate), 1); fechaMax := DataCalendar.MaxDate; fechaMax := EncodeDate(YearOf(fechaMax), MonthOf(fechaMax), 1); j := MonthOf(fechaMax); ano := YearOf(fechaMax); while fechaMin <= fechaMax do begin Fechas.AddItem(IntToStr(ano) + ' - ' + meses[j], TObject(j * 10000 + ano)); if (Calendar.Year = ano) and (Calendar.Month = j) then Fechas.ItemIndex := Fechas.Items.Count - 1; dec(j); if j = 0 then begin j := 12; dec(ano); end; fechaMax := IncMonth(fechaMax, -1); end; end; procedure TframeCalendario.FechasChange(Sender: TObject); var num, i: integer; ano, mes: word; begin i := Fechas.ItemIndex; if i <> -1 then begin num := Integer(Fechas.Items.Objects[i]); ano := num mod 10000; mes := num div 10000; DataCalendar.CambiarMes(ano, mes); Calendar.CalendarDate := EncodeDate(ano, mes, 1); end; end; procedure TframeCalendario.FechasDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var num: integer; begin with Fechas.Canvas do begin if odSelected in State then Brush.Color := clBlue else begin num := Integer(Fechas.Items.Objects[Index]); if num = 0 then Brush.Color := clWhite else if num mod 2 = 0 then Brush.Color := $00E1E1FF else Brush.Color := $00E8FFFF; end; FillRect(Rect); TextOut(Rect.Left, Rect.Top, Fechas.Items[Index]); end; end; function TframeCalendario.GetDate: TDate; begin result := Calendar.CurrentDate; end; function TframeCalendario.GetMaxDate: TDate; begin result := Calendar.MaxDate; end; procedure TframeCalendario.aAnteriorExecute(Sender: TObject); begin Fechas.ItemIndex := Fechas.ItemIndex + 1; FechasChange(nil); end; procedure TframeCalendario.aAnteriorUpdate(Sender: TObject); begin aSiguiente.Enabled := Fechas.ItemIndex > 0; end; procedure TframeCalendario.aSiguienteUpdate(Sender: TObject); begin aAnterior.Enabled := Fechas.ItemIndex < Fechas.Items.Count - 1; end; procedure TframeCalendario.aSiguienteExecute(Sender: TObject); begin Fechas.ItemIndex := Fechas.ItemIndex - 1; FechasChange(nil); end; procedure TframeCalendario.OnEstadoDia(const dia: integer; var enabled: boolean); begin enabled := DataCalendar.existeDia(dia); end; procedure TframeCalendario.SetDate(Value: TDate); var ano, mes, dia, diaI: word; begin if Value < FMinDate then Value := FMinDate; if Value > DataCalendar.MaxDate then Value := DataCalendar.MaxDate; DecodeDate(Value, ano, mes, dia); DataCalendar.CambiarMes(ano, mes); diaI := dia; while (dia > 0) and (not DataCalendar.existeDia(dia)) do dec(dia); if dia = 0 then begin dia := diaI; while not DataCalendar.existeDia(dia) do inc(dia); end; Value := EncodeDate(ano, mes, dia); Calendar.CurrentDate := Value; Calendar.CalendarDate := Value; Initialize; end; procedure TframeCalendario.SetMinDate(const Value: TDate); begin FMinDate := Value; Calendar.MinDate := Value; Initialize; FechasChange(nil); end; end.
program Consumption(input, output); uses wincrt; var MilesPerWatt, DistMiles, DistKM, TimeTook, Consumed, KWPerKM, AvgSpeed : real; const KM_PER_MILE = 1.6; WATTS_PER_KW = 1000; begin {Get Input} write('Miles Per Watt: '); readln(MilesPerWatt); clrscr; write('Distance Travelled (Miles): '); readln(DistMiles); clrscr; write('Time it took (Hours): '); readln(TimeTook); {Calculate} DistKM := DistMiles * KM_PER_MILE; Consumed{KW} := (DistMiles * 1 / MilesPerWatt) / WATTS_PER_KW; KWPerKM := DistKM / Consumed; AvgSpeed := DistKM / (TimeTook * 60); {Display Results} clrscr; writeln('Distance Travelled (KM): ', DistKM:7:2); writeln('Electricity Consumed (KW): ', Consumed:7:2); writeln('KW Per KM: ', KWPerKM:7:2); writeln('Average Speed Per Minute (KM): ', AvgSpeed:7:2); {End Program} readln; donewincrt; end. {Power Consumpsion} {Kaleb Haslam}
unit uiwindow_wndproc_startend; interface uses Windows, Messages, uiwindow_clip; function UIWndProcA_StartEnd(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean; implementation function WndProcA_WMNCCREATE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_NCCREATE, wParam, lParam); end; function WndProcA_WMCREATE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_CREATE, wParam, lParam); end; function WndProcA_WMACTIVATEAPP(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_ACTIVATEAPP, wParam, lParam); end; function WndProcA_WMNCACTIVATE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_NCACTIVATE, wParam, lParam); end; function WndProcA_WMACTIVATE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_ACTIVATE, wParam, lParam); end; function WndProcA_WMCLOSE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_CLOSE, wParam, lParam); end; function WndProcA_WMDESTROY(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_DESTROY, wParam, lParam); end; function WndProcA_WMNCDESTROY(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT; begin PostQuitMessage(0); Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_NCDESTROY, wParam, lParam); end; function UIWndProcA_StartEnd(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean; begin Result := true; case AMsg of WM_NCCREATE {129 $0081}: AWndProcResult := WndProcA_WMNCCREATE(AUIWindow, wParam, lParam); //WM_NCCALCSIZE {131}: ; WM_CREATE {1}: AWndProcResult := WndProcA_WMCREATE(AUIWindow, wParam, lParam); // WM_SIZE {5}: ; // WM_MOVE {3}: ; // WM_SHOWWINDOW {24 $0018}: ; // WM_WINDOWPOSCHANGING {70 $0046}: ; WM_ACTIVATEAPP {28 $001C}: AWndProcResult := WndProcA_WMACTIVATEAPP(AUIWindow, wParam, lParam); WM_NCACTIVATE {134 $0086}: AWndProcResult := WndProcA_WMNCACTIVATE(AUIWindow, wParam, lParam); WM_ACTIVATE {6}: AWndProcResult := WndProcA_WMACTIVATE(AUIWindow, wParam, lParam); // WM_IME_SETCONTEXT{641 $0281} : ; // WM_IME_NOTIFY{642}: ; // WM_SETFOCUS{7}: ; // WM_NCPAINT{133}: ; // WM_ERASEBKGND{20 $0014}: ; // WM_WINDOWPOSCHANGED{71}: ; // WM_PAINT{15}: ; // WM_NCHITTEST{132}: ; // WM_SETCURSOR{32}: ; // WM_MOUSEMOVE{512}: ; // WM_SYSKEYDOWN{260}: begin // Alt + F4 // end; // WM_SYSCOMMAND{274}: begin // end; WM_CLOSE{16}: AWndProcResult := WndProcA_WMCLOSE(AUIWindow, wParam, lParam); // 144{144 $0090}: begin // end; // WM_KILLFOCUS{8 $8}: ; WM_DESTROY{2}: AWndProcResult := WndProcA_WMDESTROY(AUIWindow, wParam, lParam); WM_NCDESTROY{130 $0082}: AWndProcResult := WndProcA_WMNCDESTROY(AUIWindow, wParam, lParam); else Result := false; end; end; end.
{ TRegistryInfo Component Version 2.0b - Suite GLibWMI Copyright (©) 2009-2013, by Germán Estévez (Neftalí) La clase WMI Win32_Registry representa el registro del sistema en un ordenador con Windows. Utilización/Usage: Basta con "soltar" el componente y activarlo. Place the component in the form and active it. MSDN Info: http://msdn.microsoft.com/en-us/library/aa394394(v=vs.85).aspx ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia envíame un mail a: german_ral@hotmail.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion send a mail to: german_ral@hotmail.com ========================================================================= @author Germán Estévez (Neftalí) @web http://neftali.clubDelphi.com @cat Package GLibWMI } unit CRegistryInfo; { ========================================================================= TRegistryInfo.pas Componente ======================================================================== Historia de las Versiones ------------------------------------------------------------------------ 30/04/2013 * Creación. ========================================================================= Errores detectados no corregidos ========================================================================= } //========================================================================= // // I N T E R F A C E // //========================================================================= interface uses {$IF CompilerVersion >= 23.0} VCL.Controls, System.Classes, {$ELSE} Classes, Controls, {$IFEND} CWMIBase; type //: Clase para definir las propiedades del componente. TRegistryProperties = class(TPersistent) private FCaption:string; FCurrentSize:Longword; FDescription:string; FInstallDate:TDateTime; FMaximumSize:Longword; FName:string; FProposedSize:Longword; FStatus:string; private public // {GET_ENUM} published property Caption:string read FCaption write FCaption stored False; property CurrentSize:Longword read FCurrentSize write FCurrentSize stored False; property Description:string read FDescription write FDescription stored False; property InstallDate:TDateTime read FInstallDate write FInstallDate stored False; property MaximumSize:Longword read FMaximumSize write FMaximumSize stored False; property Name:string read FName write FName stored False; property ProposedSize:Longword read FProposedSize write FProposedSize stored False; property Status:string read FStatus write FStatus stored False; end; //: Implementación para el acceso vía WMI a la clase Win32_Registry TRegistryInfo = class(TWMIBase) private fConnected:boolean; FRegistryProperties: TRegistryProperties; protected //: Rellenar las propiedades. procedure FillProperties(AIndex:integer); override; // propiedad Active procedure SetActive(const Value: Boolean); override; //: Clase para el componente. function GetWMIClass():string; override; //: Obtener el root. function GetWMIRoot():string; override; //: Limpiar las propiedades procedure ClearProps(); override; public // redefinido el constructor constructor Create(AOwner: TComponent); override; //: destructor destructor Destroy; override; published // propiedades de la Registry property RegistryProperties:TRegistryProperties read FRegistryProperties write FRegistryProperties; end; // {CONST_ENUM} //========================================================================= // // I M P L E M E N T A T I O N // //========================================================================= implementation uses {$IF CompilerVersion >= 23.0} VCL.Forms, WinAPI.Windows, System.Types, VCL.Dialogs, System.SysUtils, {$ELSE} Forms, Types, Windows, SysUtils, Dialogs, {$IFEND} UProcedures, UConstantes; { TRegistry } {-------------------------------------------------------------------------------} // Limpiar las propiedades procedure TRegistryInfo.ClearProps; begin Self.RegistryProperties.FCaption := STR_EMPTY; Self.RegistryProperties.FCurrentSize := 0; Self.RegistryProperties.FDescription := STR_EMPTY; Self.RegistryProperties.FInstallDate := 0; Self.RegistryProperties.FMaximumSize := 0; Self.RegistryProperties.FName := STR_EMPTY; Self.RegistryProperties.FProposedSize := 0; Self.RegistryProperties.FStatus := STR_EMPTY; end; //: Constructor del componente constructor TRegistryInfo.Create(AOwner: TComponent); begin inherited; Self.FRegistryProperties := TRegistryProperties.Create(); Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library/aa394394(v=vs.85).aspx'; end; // destructor del componente destructor TRegistryInfo.Destroy(); begin // liberar FreeAndNil(Self.FRegistryProperties); inherited; end; // Obtener la clase function TRegistryInfo.GetWMIClass(): string; begin Result := WIN32_REGISTRY_CLASS; end; // Obtener Root function TRegistryInfo.GetWMIRoot(): string; begin Result := STR_CIM2_ROOT; end; // Active procedure TRegistryInfo.SetActive(const Value: Boolean); begin // método heredado inherited; end; //: Rellenar las propiedades del componente. procedure TRegistryInfo.FillProperties(AIndex: integer); var s:string; i:Integer; d:TDateTime; v:variant; vType:TWMIGenericPropType; vArr:TArrVariant; vNull:boolean; vp:TRegistryProperties; begin // Llamar al heredado (importante) inherited; // Rellenar propiedades... vp := Self.RegistryProperties; GetWMIPropertyValue(Self, 'Caption', v, vNull); vp.FCaption := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'CurrentSize', v, vNull); vp.FCurrentSize := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Description', v, vNull); vp.FDescription := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'InstallDate', v, vNull); if not vNull then begin vp.FInstallDate := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'MaximumSize', v, vNull); vp.FMaximumSize := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Name', v, vNull); vp.FName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ProposedSize', v, vNull); vp.FProposedSize := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'Status', v, vNull); vp.FStatus := VariantStrValue(v, vNull); end; // {IMPL_ENUM} end.
{ search-api Copyright (c) 2019 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit search.settings; {$mode delphi} interface uses Classes, SysUtils, search.types; type { TSearchSettingsImpl } (* base implementation for ISearchSettings *) TSearchSettingsImpl = class(TInterfacedObject,ISearchSettings) strict private FParent: ISearchAPI; FQuery: IQuery; strict protected function GetParent: ISearchAPI; function GetQuery: IQuery; public //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- property Query : IQuery read GetQuery; property Parent : ISearchAPI read GetParent; //-------------------------------------------------------------------------- //methods //-------------------------------------------------------------------------- constructor Create(Const AParent: ISearchAPI; Const AQuery: IQuery);virtual;overload; destructor destroy; override; end; implementation { TSearchSettingsImpl } function TSearchSettingsImpl.GetParent: ISearchAPI; begin Result:=FParent; end; function TSearchSettingsImpl.GetQuery: IQuery; begin Result:=FQuery; end; constructor TSearchSettingsImpl.Create(const AParent: ISearchAPI; Const AQuery: IQuery); begin FParent:=AParent; FQuery:=AQuery; end; destructor TSearchSettingsImpl.destroy; begin FParent:=nil; FQuery:=nil; inherited destroy; end; end.
unit ExportTabularOMOD; uses ExportCore, ExportTabularCore, ExportJson; var ExportTabularOMOD_outputLines: TStringList; function initialize(): Integer; begin ExportTabularOMOD_outputLines := TStringList.create(); ExportTabularOMOD_outputLines.add( '"File"' // Name of the originating ESM + ', "Form ID"' // Form ID + ', "Editor ID"' // Editor ID + ', "Name"' // Full name + ', "Description"' // Description + ', "Form type"' // Type of mod (`Armor` or `Weapon`) + ', "Loose mod"' // Loose mod (MISC) + ', "Attach point"' // Attach point + ', "Attach parent slots"' // Sorted JSON array of attach parent slots + ', "Includes"' // Sorted JSON object of includes + ', "Properties"' // Sorted JSON object of properties + ', "Target keywords"' // Sorted JSON array of keywords. Each keyword is represented as // `{EditorID} [KYWD:{FormID}]` ); end; function canProcess(el: IInterface): Boolean; begin result := signature(el) = 'OMOD'; end; function process(omod: IInterface): Integer; var data: IInterface; begin if not canProcess(omod) then begin addWarning(name(omod) + ' is not a OMOD. Entry was ignored.'); exit; end; data := eBySign(omod, 'DATA'); ExportTabularOMOD_outputLines.add( escapeCsvString(getFileName(getFile(omod))) + ', ' + escapeCsvString(stringFormID(omod)) + ', ' + escapeCsvString(evBySign(omod, 'EDID')) + ', ' + escapeCsvString(evBySign(omod, 'FULL')) + ', ' + escapeCsvString(evBySign(omod, 'DESC')) + ', ' + escapeCsvString(evByName(data, 'Form Type')) + ', ' + escapeCsvString(evBySign(omod, 'LNAM')) + ', ' + escapeCsvString(evByName(data, 'Attach Point')) + ', ' + escapeCsvString(getJsonChildArray(eByName(data, 'Attach Parent Slots'))) + ', ' + escapeCsvString(getJsonIncludesArray(data)) + ', ' + escapeCsvString(getJsonOMODPropertyObject(data)) + ', ' + escapeCsvString(getJsonChildArray(eBySign(omod, 'MNAM'))) ); end; function finalize(): Integer; begin createDir('dumps/'); ExportTabularOMOD_outputLines.saveToFile('dumps/OMOD.csv'); ExportTabularOMOD_outputLines.free(); end; (** * Returns a JSON array of the mods that are included by the given mod. * * @param data the mod's data * @return a JSON array of the mods that are included by the given mod *) function getJsonIncludesArray(data: IInterface): String; var i: Integer; includes: IInterface; include: IInterface; resultList: TStringList; begin resultList := TStringList.create(); includes := eByName(data, 'Includes'); for i := 0 to eCount(includes) - 1 do begin include := eByIndex(includes, i); resultList.add( '{' + '"Mod":"' + escapeJson(evByName(include, 'Mod')) + '"' + ',"Minimum Level":"' + escapeJson(evByName(include, 'Minimum Level')) + '"' + ',"Optional":"' + escapeJson(evByName(include, 'Optional')) + '"' + ',"Don''t Use All":"' + escapeJson(evByName(include, 'Don''t Use All')) + '"' + '}' ); end; resultList.sort(); result := listToJsonArray(resultList); resultList.free(); end; (** * Returns a JSON array of the properties of the given mod. * * @param data the mod's data * @return a JSON array of the properties of the given mod *) function getJsonOMODPropertyObject(data: IInterface): String; var i: Integer; props: IInterface; prop: IInterface; resultList: TStringList; begin resultList := TStringList.create(); props := eByName(data, 'Properties'); for i := 0 to eCount(props) - 1 do begin prop := eByIndex(props, i); resultList.add( '{' + '"Value Type":"' + escapeJson(evByName(prop, 'Value Type')) + '"' + ',"Function Type":"' + escapeJson(evByName(prop, 'Function Type')) + '"' + ',"Property":"' + escapeJson(evByName(prop, 'Property')) + '"' + ',"Value 1":"' + escapeJson(evByName(prop, 'Value 1')) + '"' + ',"Value 2":"' + escapeJson(evByName(prop, 'Value 2')) + '"' + ',"Curve Table":"' + escapeJson(evByName(prop, 'Curve Table')) + '"' + '}' ); end; resultList.sort(); result := listToJsonArray(resultList); resultList.free(); end; end.
unit DIOTA.Pow.SpongeFactory; interface uses DIOTA.Pow.ICurl; type TSpongeFactory = class abstract public type Mode = (CURLP81, CURLP27, KERL); class function Create(mode: Mode): ICurl; end; implementation uses DIOTA.Pow.JCurl, DIOTA.Pow.Kerl; { TSpongeFactory } class function TSpongeFactory.Create(mode: Mode): ICurl; begin case mode of CURLP81: Result := TJCurl.Create(mode); CURLP27: Result := TJCurl.Create(mode); KERL: Result := TKerl.Create else Result := nil; end; end; end.
unit HlpMurmur2; {$I ..\Include\HashLib.inc} interface uses {$IFDEF DELPHI2010} SysUtils, // to get rid of compiler hint "not inlined" on Delphi 2010. {$ENDIF DELPHI2010} HlpHashLibTypes, {$IFDEF DELPHI} HlpHash, {$ENDIF DELPHI} HlpIHash, HlpConverters, HlpIHashInfo, HlpHashResult, HlpIHashResult, HlpMultipleTransformNonBlock, HlpNullable; resourcestring SInvalidKeyLength = 'KeyLength Must Be Equal to %d'; type // The original MurmurHash2 32-bit algorithm by Austin Appleby. TMurmur2 = class sealed(TMultipleTransformNonBlock, IHash32, IHashWithKey, ITransformBlock) strict private var FKey, FWorkingKey, FH: UInt32; const CKEY = UInt32($0); M = UInt32($5BD1E995); R = Int32(24); function InternalComputeBytes(const AData: THashLibByteArray): Int32; procedure TransformUInt32Fast(ABlock: UInt32); inline; function GetKeyLength(): TNullableInteger; function GetKey: THashLibByteArray; inline; procedure SetKey(const AValue: THashLibByteArray); inline; strict protected function ComputeAggregatedBytes(const AData: THashLibByteArray) : IHashResult; override; public constructor Create(); procedure Initialize(); override; function Clone(): IHash; override; property KeyLength: TNullableInteger read GetKeyLength; property Key: THashLibByteArray read GetKey write SetKey; end; implementation { TMurmur2 } constructor TMurmur2.Create; begin Inherited Create(4, 4); FKey := CKEY; end; function TMurmur2.GetKey: THashLibByteArray; begin result := TConverters.ReadUInt32AsBytesLE(FKey); end; procedure TMurmur2.SetKey(const AValue: THashLibByteArray); begin if (AValue = Nil) then begin FKey := CKEY; end else begin if System.Length(AValue) <> KeyLength.value then begin raise EArgumentHashLibException.CreateResFmt(@SInvalidKeyLength, [KeyLength.value]); end; FKey := TConverters.ReadBytesAsUInt32LE(PByte(AValue), 0); end; end; procedure TMurmur2.TransformUInt32Fast(ABlock: UInt32); begin ABlock := ABlock * M; ABlock := ABlock xor (ABlock shr R); ABlock := ABlock * M; FH := FH * M; FH := FH xor ABlock; end; function TMurmur2.GetKeyLength: TNullableInteger; begin result := 4; end; procedure TMurmur2.Initialize; begin FWorkingKey := FKey; inherited Initialize(); end; function TMurmur2.InternalComputeBytes(const AData: THashLibByteArray): Int32; var LLength, LCurrentIndex: Int32; LBlock: UInt32; LPtrData: PByte; begin LLength := System.Length(AData); LPtrData := PByte(AData); if (LLength = 0) then begin result := 0; Exit; end; FH := FWorkingKey xor UInt32(LLength); LCurrentIndex := 0; while (LLength >= 4) do begin LBlock := TConverters.ReadBytesAsUInt32LE(LPtrData, LCurrentIndex); TransformUInt32Fast(LBlock); System.Inc(LCurrentIndex, 4); System.Dec(LLength, 4); end; case LLength of 3: begin FH := FH xor (AData[LCurrentIndex + 2] shl 16); FH := FH xor (AData[LCurrentIndex + 1] shl 8); FH := FH xor (AData[LCurrentIndex]); FH := FH * M; end; 2: begin FH := FH xor (AData[LCurrentIndex + 1] shl 8); FH := FH xor (AData[LCurrentIndex]); FH := FH * M; end; 1: begin FH := FH xor (AData[LCurrentIndex]); FH := FH * M; end; end; FH := FH xor (FH shr 13); FH := FH * M; FH := FH xor (FH shr 15); result := Int32(FH); end; function TMurmur2.Clone(): IHash; var LHashInstance: TMurmur2; begin LHashInstance := TMurmur2.Create(); LHashInstance.FKey := FKey; LHashInstance.FWorkingKey := FWorkingKey; LHashInstance.FH := FH; FBuffer.Position := 0; LHashInstance.FBuffer.CopyFrom(FBuffer, FBuffer.Size); result := LHashInstance as IHash; result.BufferSize := BufferSize; end; function TMurmur2.ComputeAggregatedBytes(const AData: THashLibByteArray) : IHashResult; begin result := THashResult.Create(InternalComputeBytes(AData)); end; end.
unit ULanguage; interface uses System.IniFiles; type TLanguageName = (langEnglish, langPortugueseBrazil); TLang = class private Section: string; Ini: TMemIniFile; public constructor Create; destructor Destroy; override; procedure SetLanguage(aLanguageName: TLanguageName); function Get(const Ident: string): string; end; var Lang: TLang; implementation uses System.Classes, System.SysUtils, Winapi.Windows; constructor TLang.Create; var R: TResourceStream; S: TStringStream; Lst: TStringList; begin inherited; Ini := TMemIniFile.Create(''); Lst := TStringList.Create; try S := TStringStream.Create('', TEncoding.UTF8); try R := TResourceStream.Create(HInstance, 'LANG', RT_RCDATA); try S.LoadFromStream(R); finally R.Free; end; Lst.Text := S.DataString; finally S.Free; end; Ini.SetStrings(Lst); finally Lst.Free; end; end; destructor TLang.Destroy; begin Ini.Free; inherited; end; procedure TLang.SetLanguage(aLanguageName: TLanguageName); begin case aLanguageName of langEnglish: Section := 'English'; langPortugueseBrazil: Section := 'Portuguese-Brazil'; end; end; function TLang.Get(const Ident: string): string; begin Result := Ini.ReadString(Section, Ident, ''); if Result='' then raise Exception.CreateFmt('Cannot retrieve language ident "%s"', [Ident]); end; initialization Lang := TLang.Create; finalization Lang.Free; end.
unit Operator; interface uses Mutex; type TOperator = class public constructor Create; destructor Destroy; override; public function Execute(Layout, Client : string; When : TDateTime) : boolean; procedure Cancel; end; var theOperator : TOperator = nil; OperatorMutex : TMutex = nil; const OperatorMutexName = 'Elbrus_Operator_Mutex'; Aire_Sequence : array[0..2] of integer = (3, 6, 5); implementation uses SysUtils, Classes, Rda_TLB, Layout, Observation, Elbrus, ElbrusTypes, Calib, Config, DateUtils, Constants, EventLog, LogTools, Users, Windows, ActiveX, ManagerDRX; var OperatorThread : TThread = nil; const AutoClient = 'Automatico'; ts_TurnOff = 'Apagado automatico'; ms_RadarOff = 'Esperando para apagar radar'; ms_TxRxOff = 'Esperando para apagar transceptores'; ts_TurnRadarStandBy = 'Poniendo en Standby el radar'; ms_RadarStandBy = 'Esperando para poner en Standby el radar'; MaxFailedObs = 5; type TObsThread = class(TThread) public constructor Create( Template : ITemplate; Client : string; When : TDateTime ); protected procedure Execute; override; private fTemplate : ITemplate; fClient : string; fTime : TDateTime; end; type TOperatorThread = class(TThread) private Index : word; Start : cardinal; FailedObs : integer; AirTime : cardinal; AirStep : integer; DRX_Update : cardinal; public constructor Create; protected procedure Execute; override; private procedure UpdateTimes( Template : ITemplate; ObsTime : TDateTime); procedure CheckTemplates; function NextAutoTime : TDateTime; function CheckTemplate( Name : string ) : TDateTime; procedure CheckAutoPowerOff; procedure TurnRadarOff; procedure TurnRadarStandBy; end; { TObsThread } constructor TObsThread.Create(Template : ITemplate; Client : string; When: TDateTime); begin inherited Create(true); fTemplate := Template; fClient := Client; fTime := When; Resume; end; procedure TObsThread.Execute; begin OperatorMutex.Acquire; try Elbrus.Acquire_Control; try with TObservation.Create(fTemplate, fClient, fTime) do try ReturnValue := Execute; finally Free; end; finally Elbrus.Release_Control; end; finally OperatorMutex.Release; end; end; { TOperatorThread } constructor TOperatorThread.Create; begin inherited Create(true); Priority := tpLowest; FailedObs := 0; Index := 0; DRX_Update := 0; Start := GetTickCount; AirStep := 0; Elbrus.Air1(Aire_Sequence[AirStep] and 1 > 0); Elbrus.Air2(Aire_Sequence[AirStep] and 2 > 0); Elbrus.Air3(Aire_Sequence[AirStep] and 4 > 0); AirTime := GetTickCount; Resume; end; procedure TOperatorThread.Execute; var Temp : ITemplate; Thread : TThread; Templates : TStrings; InitialIndex : integer; ObsResult : integer; CurrentTime : TDateTime; begin CoInitialize(nil); try while not Terminated do try if GetTickCount - Start > 60000 then begin theCalibration.Update; theConfiguration.Update; Start := GetTickCount; end; if GetTickCount - AirTime > theConfiguration.Air_Time then begin AirStep := (AirStep + 1) mod 3; Elbrus.Air1(Aire_Sequence[AirStep] and 1 > 0); Elbrus.Air2(Aire_Sequence[AirStep] and 2 > 0); Elbrus.Air3(Aire_Sequence[AirStep] and 4 > 0); AirTime := GetTickCount; end; if GetTickCount - DRX_Update > 5000 then begin if DRX1.Enabled then begin if DRX1.Ready then DRX1.Validate; if not DRX1.Ready then DRX1.Connect; end; if DRX2.Enabled then begin if DRX2.Ready then DRX2.Validate; if not DRX2.Ready then DRX2.Connect; end; DRX_Update := GetTickCount; end; if theConfiguration.AutoObs then CheckTemplates; if (not theConfiguration.AutoObs) and (theConfiguration.ContinuosRegime) then begin Templates := EnumTemplates; try if Templates.Count > 0 then begin if Index >= Templates.Count then Index := 0; InitialIndex := Index; repeat Temp := TLayout.Create( Templates[Index] ); Index := (Index+1) mod Templates.Count; if Temp.Automatica then begin CurrentTime := Now; Thread := TObsThread.Create(Temp, AutoClient, CurrentTime); ObsResult := Thread.WaitFor; if ObsResult = obs_Failed then Inc(FailedObs); Sleep( 1000 ); if FailedObs >= MaxFailedObs then UpdateTimes(Temp, CurrentTime); Break; end; until Index = InitialIndex; end; finally Templates.Free; end; end; if (not theConfiguration.ContinuosRegime) and (theConfiguration.AutoPowerOff) then CheckAutoPowerOff; Sleep(1000); except Sleep(5000); end; finally CoUninitialize; end; end; procedure TOperatorThread.CheckTemplates; var I, J : integer; Time : array of TDateTime; Min : TDateTime; Temp : ITemplate; Thread : TThread; Flag : boolean; ObsResult : integer; begin with EnumTemplates do try Flag := false; SetLength(Time, Count); for I := 0 to Count-1 do Time[I] := CheckTemplate(Strings[I]); repeat J := 0; Min := 0; for I := 0 to Count - 1 do if Time[I] > 0 then if (Min = 0) or (Time[I] < Min) then begin J := I; Min := Time[I]; end; if (Min > 0) then begin Temp := TLayout.Create(Strings[J]); Thread := TObsThread.Create(Temp, AutoClient, Temp.Proxima); ObsResult := Thread.WaitFor; if ObsResult = obs_Failed then Inc(FailedObs); Sleep( 1000 ); if FailedObs >= MaxFailedObs then UpdateTimes(Temp, Temp.Proxima); Time[J] := 0; Flag := true; end; until Min = 0; finally Free; end; Sleep(1000); if Flag and theConfiguration.AutoPowerOff and ((NextAutoTime - Now) > (theConfiguration.RadarTimeout * AMinute)) then if (NextAutoTime - Now) >= (theConfiguration.RadarRestTime * AMinute) then TurnRadarOff else TurnRadarStandBy; end; function TOperatorThread.NextAutoTime: TDateTime; var I : integer; begin Result := IncYear( Now, 1 ); try OperatorMutex.Acquire; try with EnumTemplates do try for I := 0 to Count-1 do if TemplateExists(Strings[I]) then with TLayout.Create(Strings[I]) as ITemplate do if Automatica and (Proxima < Result) then Result := Proxima; finally Free; end; finally OperatorMutex.Release; end; except end; end; function TOperatorThread.CheckTemplate(Name: string) : TDateTime; var WarmTime : TDateTime; WaitTime : TDateTime; TR1, TR2 : boolean; Template : ITemplate; I : integer; W, C, L : integer; const OneMinute = 1/24/60; begin Result := 0; if TemplateExists(Name) then begin Template := TLayout.Create(Name); if Template.Automatica then begin TR1 := false; TR2 := false; for I := 0 to Template.Formatos - 1 do begin Template.Formato(I, W, C, L); case W of wl_3cm: TR1 := true; wl_10cm: TR2 := true; end; end; if (not TR1 or Snapshot.Tx1_ON) and (not TR2 or Snapshot.Tx1_ON) then WarmTime := OneMinute/6 else WarmTime := theConfiguration.RadarWarmTime * OneMinute; WaitTime := Template.Proxima - Now; if WaitTime <= WarmTime then Result := Template.Proxima; end; end; end; procedure TOperatorThread.CheckAutoPowerOff; begin if Elbrus.Snapshot.Radar_ON and (MinutesBetween(Now, Snapshot.Last_Action_Time) >= theConfiguration.RadarTimeout) then if (MinutesBetween( NextAutoTime, Now) - theConfiguration.RadarWarmTime) >= theConfiguration.RadarRestTime then TurnRadarOff else if not(Is_Tx1Standby and Is_Tx2Standby) then TurnRadarStandBy; end; procedure TOperatorThread.TurnRadarOff; var P : integer; T : TDateTime; begin Elbrus.Report_Obs_Start( ' ' + ts_TurnOff, AutoClient ); try P := 0; T := Snapshot.Last_Action_Time; while (P < 100) and (Snapshot.Last_Action_Time = T) do begin Elbrus.Report_Obs_Progress(P, ts_TurnOff, ms_RadarOff); inc(P); Sleep(300); end; if Snapshot.Last_Action_Time = T then begin Elbrus.Apagar_Radar; LogMessages.AddLogMessage( lcInformation, Snapshot.ObsClient, 'Apagado Automatico', 'Radar apagado', 'Radar apagado' ); end else LogMessages.AddLogMessage( lcInformation, GetController, 'Apagado Automatico', 'Cancelado el apagado automatico', 'Cancelado el apagado automatico' ); finally Elbrus.Report_Obs_Finish( obs_Nothing ); end; end; procedure TOperatorThread.TurnRadarStandBy; var P : integer; T : TDateTime; begin Elbrus.Report_Obs_Start('', AutoClient); try P := 0; T := Snapshot.Last_Action_Time; while (P < 100) and (Snapshot.Last_Action_Time = T) do begin Elbrus.Report_Obs_Progress(P, ts_TurnRadarStandBy, ms_RadarStandBy); inc(P); Sleep(300); end; if Snapshot.Last_Action_Time = T then begin Elbrus.Tx1_Standby( true ); Elbrus.Tx2_Standby( true ); end; finally Elbrus.Report_Obs_Finish(obs_OK); end; end; procedure TOperatorThread.UpdateTimes(Template : ITemplate; ObsTime : TDateTime); begin FailedObs := 0; with Template as ITemplateControl do begin Anterior := ObsTime; if Template.Automatica then begin while Template.Proxima < Now do Proxima := Template.Proxima + Template.Periodo; if Template.Proxima <= ObsTime then Proxima := ObsTime + Template.Periodo; end else Proxima := 0; end; LogMessages.AddLogMessage( lcError, Snapshot.ObsClient, 'Ejecutando Observacion', 'Posponiendo Observacion', 'Se pospuso la observacion porque fallo el maximo de veces' ); end; { TOperator } constructor TOperator.Create; begin inherited Create; OperatorMutex := TMutex.Create( nil, false, OperatorMutexName ); OperatorThread := TOperatorThread.Create; end; destructor TOperator.Destroy; begin inherited; FreeAndNil( OperatorThread ); if Assigned( OperatorMutex ) then OperatorMutex.Free; end; function TOperator.Execute(Layout, Client: string; When: TDateTime): boolean; begin if not Snapshot^.ObsInProgress then if OperatorMutex.WaitFor(0) then try Result := TemplateExists(Layout); if Result then TObsThread.Create(TLayout.Create(Layout), Client, When); finally OperatorMutex.Release; end else Result := false else result := true; end; procedure TOperator.Cancel; begin WriteView^.ObsCancel := true; WriteView^.Last_Action_Time := now; end; end.
unit UColorFunctions; interface uses Windows, Classes,StrUtils, Controls, StdCtrls, SysUtils, xmldom, XMLIntf, msxmldom, XMLDoc, UTypedefs, contnrs, Dialogs, UGradientPoint, UColorPoint; type TColorTransferFunctionRecord = record numColorPoints:integer; colorPoints:array of TColorRecord; end; TTransferFunction = class private _currentWW, _currentWL:integer; _blendMode:integer; _gradEnabled:boolean; _isSistema:boolean; _isModificada:boolean; _flagColorType:integer; _shading:boolean; _clamping:boolean; _ambient:single; _diffuse:single; _specular:single; _name:string; _size:integer; _Points:TObjectList; _GradientPoints:TObjectList; _specPower:single; _scalarUnitDistance : single; function _GetGradientSize():integer; function _GetColorSize():integer; public property CurrentLevel : integer read _currentWL write _currentWL; property CurrentWindow : integer read _currentWW write _currentWW; property BlendMode:integer read _blendMode write _blendMode; property GradientSize : integer read _GetGradientSize; property GradientEnabled : boolean read _gradEnabled write _gradEnabled; property IsSistema : boolean read _isSistema write _isSistema; property IsModificada : boolean read _isModificada write _isModificada; property Name:string read _name write _name; property ColorType:integer read _flagColorType write _flagColorType; property Shading:boolean read _shading write _shading; property Clamping:boolean read _clamping write _clamping; property Ambient:single read _ambient write _ambient; property Diffuse:single read _diffuse write _diffuse; property Specular:single read _specular write _specular; property SpecularPower : single read _specPower write _specPower; property scalarOpacityUnitDistance : single read _scalarUnitDistance write _scalarUnitDistance; property Size : integer read _GetColorSize; //retorna a função como arrays. Assume que as arrays estão alocadas com o tamanho dado pela propriedade Size. Retorna //a qtd de elementos. function GetFunctionAsArray(x:PInt; c0:PFloat; c1:PFloat; c2:PFloat; c3:PFloat; midpoint:PFloat; sharpness:pFloat):integer; function GetFunctionAsArrayF(x:PSingle; c0:PSingle; c1:PSingle; c2:PSingle; c3:PSingle; midpoint:PSingle; sharpness:PSingle):integer; //function GetGradientAsArray(x:PSingle; a:PSingle; midpoint:PSingle; sharpness:PSingle):integer; function GetGradientAsArrayF(x:PSingle; a:PSingle; midpoint:PSingle; sharpness:PSingle):integer; function GetGradientPoint(i:integer):TGradientPoint; function GetPoint(i:integer):TColorPoint; //Construtor a partir do xml constructor Create(TransferFunction:IXMLNode);overload; //Construtor de cópia constructor Create(Original:TTransferFunction);overload; //construtor default constructor Create();overload; //destrutor destructor Destroy();override; procedure DeleteGradientPoint(i:integer); procedure DeletePonto(i:integer); procedure ClearPoints(); procedure PushPoint(_p:TColorPoint); procedure AddGradientPoint(_p:TGradientPoint; i:integer); procedure AddPoint(_p:TColorPoint; i:integer); procedure recalculateWL(); function GetAsRecord():TColorTransferFunctionRecord; end; implementation function TTransferFunction.GetAsRecord():TColorTransferFunctionRecord; var i:integer; begin result.numColorPoints := _Points.Count; SetLength(result.colorPoints, result.numColorPoints); for i:=0 to result.numColorPoints-1 do begin result.colorPoints[i] := TColorPoint(_Points.Items[i]).GetAsRecord(); end; end; procedure TTransferFunction.recalculateWL(); var largura:single; centro:single; begin largura := TColorPoint(_Points.Items[_Points.Count-1]).X - TColorPoint(_Points.Items[0]).X; centro := ( TColorPoint(_Points.Items[0]).X + TColorPoint(_Points.Items[_Points.Count-1]).X) / 2; _currentWW := Round(largura); _currentWL := Round(centro); end; procedure TTransferFunction.DeleteGradientPoint(i:integer); begin _GradientPoints.Delete(i); end; procedure TTransferFunction.DeletePonto(i:integer); begin _Points.Delete(i); _size := _Points.Count; end; constructor TTransferFunction.Create(); begin // Assert(False); _GradientPoints := TObjectList.Create(true); _Points := TObjectList.Create(true); // recalculateWL(); end; constructor TTransferFunction.Create(Original:TTransferFunction); var i:integer; pt:TColorPoint; gp:TGradientPoint; begin //Construtor de cópia - deixa ele vivo //ShowMessage('construtor de cópia do TTransfer'); _flagColorType := Original._flagColorType; _shading := Original._shading; _clamping := Original._clamping; _diffuse := Original._diffuse; _specular := Original._specular; _name := Original._name; _size := Original._size; _Points := TObjectList.Create(true); for i:=0 to Original._Points.Count-1 do begin pt := TColorPoint.Create( TColorPoint( Original._points.Items[i] )); _Points.Add(pt); end; _GradientPoints := TObjectList.Create(true); for i:=0 to Original._GradientPoints.Count-1 do begin gp := TGradientPoint.Create(TGradientPoint(Original._GradientPoints.Items[i])); _GradientPoints.Add(gp); end; self.recalculateWL(); end; constructor TTransferFunction.Create(TransferFunction:IXMLNode); var nRgbTransferFunction:IXMLNode; nColorTransferFunction:IXMLNode; nPiecewiseFunction:IXMLNode; nGradientFunction:IXMLNode; i,qtd:integer; nComponent : IXMLNode; _nColor : IXMLNode; _nOpacity : IXMLNode; begin // ShowMessage('construtor do TTransfer'); _GradientPoints := TObjectList.Create(true); _Points := TObjectList.Create(true); //pega o nome _name := TransferFunction.Attributes['Comment']; //pega o blend mode _blendMode := TransferFunction.Attributes['BlendMode']; //vai pro componente nComponent := TransferFunction.ChildNodes.FindNode('VolumeProperty').ChildNodes.FindNode('Component'); //guarda o shading DecimalSeparator := '.'; Shading := nComponent.Attributes['Shade']; Ambient := StrToFloat(nComponent.Attributes['Ambient']); Diffuse := StrToFloat(nComponent.Attributes['Diffuse']); Specular := StrToFloat(nComponent.Attributes['Specular']); scalarOpacityUnitDistance := StrToFloat(nComponent.Attributes['ScalarOpacityUnitDistance']); SpecularPower := StrToFloat(nComponent.Attributes['SpecularPower']); //gaurda se é pra ter clamping ou não nRgbTransferFunction := nComponent.ChildNodes.FindNode('RGBTransferFunction'); nColorTransferFunction := nRgbTransferFunction.ChildNodes.FindNode('ColorTransferFunction'); Clamping := nColorTransferFunction.Attributes['Clamping']; //pega os pontos nPiecewiseFunction := nComponent.ChildNodes.FindNode('ScalarOpacity').ChildNodes.FindNode('PiecewiseFunction'); qtd := nPiecewiseFunction.Attributes['Size']; for i:=0 to qtd-1 do begin _nColor := nRgbTransferFunction.ChildNodes.First.ChildNodes[i]; _nOpacity := nPiecewiseFunction.ChildNodes[i]; _Points.Add(TColorPoint.Create(_nColor, _nOpacity)); end; //O color type é hard-coded pra rgb ColorType := 0; //Guarda se o gradient é pra ser usado ou não if nComponent.Attributes['DisableGradientOpacity']='1' then GradientEnabled := false else GradientEnabled := true; //GradientEnabled := not nComponent.Attributes['DisableGradientOpacity']; //pega a lista de pontos de gradiente nGradientFunction := nComponent.ChildNodes.FindNode('GradientOpacity').ChildNodes.FindNode('PiecewiseFunction'); for i:=0 to nGradientFunction.Attributes['Size']-1 do begin _nOpacity := nGradientFunction.ChildNodes[i]; _GradientPoints.Add(TGradientPoint.Create(_nOpacity)); end; _size := _Points.Count; recalculateWL(); end; function TTransferFunction._GetColorSize():integer; begin result := _Points.Count; end; function TTransferFunction.GetGradientPoint(i:integer):TGradientPoint; begin result := TGradientPoint(_GradientPoints.Items[i]); end; function TTransferFunction._GetGradientSize():integer; begin result := _GradientPoints.Count; end; procedure TTransferFunction.AddGradientPoint(_p:TGradientPoint; i:integer); begin if i>=GradientSize then _GradientPoints.Add(_p) else _GradientPoints.Insert(i, _p); end; procedure TTransferFunction.AddPoint(_p:TColorPoint; i:integer); begin _Points.Insert(i, _p); _size := _Points.Count; end; function TTransferFunction.GetPoint(i:integer):TColorPoint; begin result := TColorPoint( _Points.Items[i] ); //_Points[i]; end; procedure TTransferFunction.ClearPoints(); begin _Points.Clear(); _size := _Points.Count; end; destructor TTransferFunction.Destroy(); begin // ShowMessage('destrutor do TTransfer'); _Points.Destroy(); _GradientPoints.Destroy(); end; procedure TTransferFunction.PushPoint(_p:TColorPoint); begin _Points.Add(_p); _size := _Points.Count; self.recalculateWL(); end; function TTransferFunction.GetGradientAsArrayF(x:PSingle; a:PSingle; midpoint:PSingle; sharpness:PSingle):integer; var i:integer; _cx:PSingle; _a, _cmid, _csharp:PSingle; current:TGradientPoint; begin _cx:=x; _a:=a; _cmid:=midpoint; _csharp:=sharpness; for i:=0 to GradientSize-1 do begin current := TGradientPoint( _GradientPoints.Items[i] ); _cx^ := current.X; _a^ := current.A; _cmid^ := current.Midpoint; _csharp^ := current.Sharpness; inc(_cx); inc(_a); inc(_cmid); inc(_csharp); end; result := Size; end; function TTransferFunction.GetFunctionAsArrayF(x:PSingle; c0:PSingle; c1:PSingle; c2:PSingle; c3:PSingle; midpoint:PSingle; sharpness:PSingle):integer; var i:integer; _cx,_c0, _c1, _c2, _c3, _cmid, _csharp:PSingle; current:TColorPoint; begin _cx:=x; _c0:=c0; _c1:=c1; _c2:=c2; _c3:=c3; _cmid:=midpoint; _csharp:=sharpness; for i:=0 to Size-1 do begin current := TColorPoint( _Points.Items[i] ); _cx^ := current.X; _c0^ := current.C0; _c1^ := current.C1; _c2^ := current.C2; _c3^ := current.C3; _cmid^ := current.Midpoint; _csharp^ := current.Sharpness; inc(_cx); inc(_c0); inc(_c1); inc(_c2); inc(_c3); inc(_cmid); inc(_csharp); end; result := Size; end; function TTransferFunction.GetFunctionAsArray(x:PInt; c0:PFloat; c1:PFloat; c2:PFloat; c3:PFloat; midpoint:PFloat; sharpness:pFloat):integer; var i:integer; _cx:PInt; _c0, _c1, _c2, _c3, _cmid, _csharp:PFloat; current:TColorPoint; begin _cx:=x; _c0:=c0; _c1:=c1; _c2:=c2; _c3:=c3; _cmid:=midpoint; _csharp:=sharpness; for i:=0 to Size-1 do begin current := TColorPoint( _Points.Items[i] ); with current do begin _cx^:=trunc(X); _c0^:=C0; _c1^:=C1; _c2^:=C2; _c3^:=C3; _cmid^:=Midpoint; _csharp^:=Sharpness; end; inc(_cx); inc(_c0); inc(_c1); inc(_c2); inc(_c3); inc(_cmid); inc(_csharp); end; result := Size; end; end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} /// <summary> /// A high-precision timer interface. /// </summary> unit cwTiming; {$ifdef fpc}{$mode delphiunicode}{$endif} interface const stNoHighPrecisionTimer = '{FCF855A5-694F-48D1-994E-D9D60E365930} Could not find a high precision timer on this system.'; const /// <summary> /// Constant representing the number of milliseconds per second. /// </summary> cMillisecondsPerSecond = 1000; /// <summary> /// Constant representing the number of nanoseconds per second. /// </summary> cNanosecondsPerSecond = 1000000000; type /// <summary> /// TTickInteger a large integer for conveying the nanoseconds or /// milliseconds passed in a delta period of a timer. /// </summary> TTickInteger = int64; /// <summary> /// ITimer implementations provide a high precision timer which /// begins the first time you call getDeltaTicks from it. /// Each subsequent call will return the delta time that has passed in /// ticks. You can translate the ticks back to actual time using the /// getTicksPerSecond function, which provides an indication of the /// resolution of the timer. /// </summary> ITimer = interface ['{C3A210E8-EEA8-4880-863D-8D0AB9529CE8}'] /// <summary> /// Resets delta to zero for stop-watch style timing. /// </summary> procedure Clear; /// <summary> /// Returns the time that has passed between the previous read of /// getDeltaSeconds and this one. /// </summary> function getDeltaSeconds: double; /// <summary> /// Number of ticks that have occurred since last calling getDeltaTicks. /// </summary> function getDeltaTicks: TTickInteger; /// <summary> /// The number of ticks per second by this timer (gives resolution) /// </summary> function getTicksPerSecond: TTickInteger; /// <summary> /// Returns the time that has passed between the previous read of /// DeltaSeconds and this one. /// </summary> property DeltaSeconds: double read getDeltaSeconds; /// <summary> /// Number of ticks that have occurred since last reading DeltaTicks; /// </summary> property DeltaTicks: TTickInteger read getDeltaTicks; /// <summary> /// The number of ticks per second by this timer (gives resolution) /// </summary> property TicksPerSecond: TTickInteger read getTicksPerSecond; end; implementation uses cwStatus ; initialization TStatus.Register(stNoHighPrecisionTimer); end.
unit ULicAuthorize; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 2018 by Bradford Technologies, Inc. } { This unit evaluates the user license to determine what the user is} { authorized to use. } interface function Ok2Run: Boolean; implementation uses Math,Windows, SysUtils, Controls, Forms, Messages, DateUtils, UGlobals, UStatus, ULicUser, ULicSelectOptions, ULicConfirmation, UUtil2, UUtil3, UStrings, UWebUtils,UlicUtility,USysInfo; const {flag to get user info or not} cGetUserInfo = True; cNoInfoNeeded = False; //used to be PassThru - no questions function NotifyUserOfGracePeriodUsage(DaysRemaining, LicType: Integer): Boolean; begin //days = 0 is not being used at this time if DaysRemaining = 0 then begin if LicType = ltEvaluationLic then ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expire today. Please purchase a subscription today.') else ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expire in today. Please renew your subscription today.'); end else if DaysRemaining = 1 then begin if LicType = ltEvaluationLic then ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expire tomorrow. Please purchase a subscription today.') else ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expire tomorrow. Please renew your subscription today.'); end else begin if LicType = ltEvaluationLic then ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expired in '+ IntToStr(DaysRemaining) + ' days. Please purchase ClickFORMS today.') else ShowAlert(atWarnAlert, 'Your software license has expired. Your grace period will expire in '+ IntToStr(DaysRemaining) + ' days. Please renew today.'); end; result := True; end; function NotifyUserOfApproachingExpiration(DaysRemaining: Integer): Boolean; begin if DaysRemaining = 1 then ShowAlert(atWarnAlert, 'Your software license will expire tomorrow. Please renew your subscription today to continue using ClickFORMS. Thank you.') else if DaysRemaining < 6 then ShowAlert(atWarnAlert, 'Your software license will expire in '+ IntToStr(DaysRemaining) + ' days. Please renew your subscription today to continue using ClickFORMS. Thank you.'); result := True; end; function NotifyUserOfLicenseTermination(prevUsage: Integer): Boolean; begin case prevUsage of ltSubscriptionLic: ShowAlert(atStopAlert, 'Your software subscription has expired. Please renew your software license to continuing using the software.'); ltEvaluationLic: ShowAlert(atStopAlert, 'Your software evaluation period has expired. Please purchase one of the ClickFORMS Packages to continuing using the software.'); // ltExpiredLic: ShowAlert(atStopAlert, 'Your software license has expired. Please purchase a subscription to continue using ClickFORMS. Thank you.'); ltForceUpdate: ShowAlert(atStopAlert, 'This version of the software has expired. Please update to continue using the software. We apologize for any inconvenience.'); end; result := False; //always false - cannot use software end; function NotifyUserNeedInternetConnection: Boolean; begin ShowAlert(atStopAlert, 'ClickFORMS needs to connect to the Internet before it can continue. Please enable your Internet connection and restart ClickFORMS so it can check-in for updates.'); result := false; end; function CheckInForSoftwareLicenseUpdate: Boolean; var UserInfo: TUserLicInfo; UserAWID: String; appVersion:String; HasNewVersion:Boolean; begin result := true; //result is false only if it is time to check and computer does not connect to internet if not(CurrentUser.SWLicenseType = ltUndefinedLic) then //### PAM for testing only if CurrentUser.LicenseCheckInRequired then if IsConnectedToWeb(true) then // do not display default message begin UserInfo := TUserLicInfo.Create; try CurrentUser.LoadFromUserLicenseTo(UserInfo); //load the info obj UserAWID := CurrentUser.AWUserInfo.UserAWUID; //get the AW UID FUseCRMRegistration := GetIsCRMLive; if FUseCRMRegistration then DoCheckSoftwareLicenseStatus_CRM(UserAWID ,UserInfo) //make the call else DoCheckSoftwareLicenseStatus(UserAWID ,UserInfo); //make the call if UserInfo.FForceUpdate then //server turn on Force Update begin IsClickFORMSVersionOK2(True); //check if exe version is older than the Latest version, pop up warning else return true for CF to reset force update //we don't need to reset, the above routine allow user to either download or continue to work //without downloading until the next check date then pop up warning again. //until user download the latest version. //reset the force update flag to 0 and send AW an update appVersion := getAppVersion; HasNewVersion := IsNewVersionAvailable(SysInfo.UserAppVersion,appVersion); if not HasNewVersion then begin UserInfo.FForceUpdate := False; //RESET the flag and send back to AWSI to update if FUseCRMRegistration then UpdateAWMemberSoftwareLicense_CRM(CurrentUser.AWUserInfo.UserLoginEmail, CurrentUser.AWUserInfo.UserPassWord, UserInfo) else UpdateAWMemberSoftwareLicense(CurrentUser.AWUserInfo.UserLoginEmail, CurrentUser.AWUserInfo.UserPassWord, UserInfo); end; end; //check error messages before saving the reply CurrentUser.SaveToUserLicenseFrom(UserInfo); //save the results if FUseCRMRegistration and CurrentUser.SilentlyRegister then begin CurrentUser.BackupLicenseFile(CurrentUser.UserFileName); CurrentUser.LicInfo.FLicVersion := CurrentUser.LicInfo.CurLicVersion; //after we back up, we need to update the FLicVersion to the latest, since the reregistration through help will not load from file. CurrentUser.SaveUserLicFile; //saves the User Lic file to disk end; //the results will be looked at in case statement finally UserInfo.Free; end; end else //could not connect to the internet begin //ShowAlert(atStopAlert, 'We could not connect to the internet to verify your license. Please connect to Internet.'); result := false; end end; //---------------------------------------------------- // Main Routine that authorizes sofwtare usage //---------------------------------------------------- function Ok2Run: Boolean; var Greeting: String; //name to greet user LicTyp: Integer; //license type (unDef, Eval, Subscription, Expired) UsageDaysLeft: Integer; //calc from Lic expire date - today GraceDaysLeft: Integer; EvalGraceDays: Integer; begin FUseCRMRegistration := GetIsCRMLive; //need it here to Run registration CRMToken.CRM_Authentication_Token := ''; //need to reset the token each time we bring up clickFORMS if CheckInForSoftwareLicenseUpdate then //any updates, if so get them LicTyp := CurrentUser.SWLicenseType //this is the main lic type for ClickFORM use else LicTyp := ltNoInternetConnection; //it is time for check in but no internet connection UsageDaysLeft := CurrentUser.UsageDaysRemaining; //days before license expires GraceDaysLeft := CurrentUser.GraceDaysRemaining; EvalGraceDays := CurrentUser.EvalGraceDaysRemaining; Greeting := CurrentUser.GreetingName; //For TESTING different Lic types if FALSE then //True only during testing begin LicTyp := ltSubscriptionLic; //ltUndefinedLic ltSubscriptionLic; ltEvaluationLic ltExpiredLic UsageDaysLeft := 10; GraceDaysLeft := 0; EvalGraceDays := 0; Greeting := CurrentUser.GreetingName; end; case LicTyp of ltUndefinedLic: begin result := SelectHowToWorkOption(Greeting, cMsgWelcome, UsageDaysLeft, cGetUserInfo); end; ltNoInternetConnection: result := NotifyUserNeedInternetConnection; ltSubscriptionLic: begin result := CurrentUser.IsMonthlySubscription; //Ticket #1450 if not result then begin if UsageDaysLeft > 0 then //continue using software result := NotifyUserOfApproachingExpiration(UsageDaysLeft) //notify if < 6 days to expiration else if GraceDaysLeft > 0 then //user in grace period, notify them, but continue working result := NotifyUserOfGracePeriodUsage(GraceDaysLeft, ltSubscriptionLic) else begin CurrentUser.SWLicenseType := ltExpiredLic; NotifyUserOfLicenseTermination(ltSubscriptionLic); result := SelectHowToWorkOption(Greeting, cMsgSubcrpEnded, UsageDaysLeft, cGetUserInfo); end; end; end; ltEvaluationLic: begin if UsageDaysLeft > 0 then result := SelectHowToWorkOption(Greeting, cMsgEvalLic, UsageDaysLeft, cNoInfoNeeded) else if EvalGraceDays > 0 then result := NotifyUserOfGracePeriodUsage(EvalGraceDays, ltEvaluationLic) else begin CurrentUser.SWLicenseType := ltExpiredLic; NotifyUserOfLicenseTermination(ltEvaluationLic); result := SelectHowToWorkOption(Greeting, cMsgEvalExpired, UsageDaysLeft, cGetUserInfo); //needs to register end; end; ltExpiredLic: begin result := SelectHowToWorkOption(Greeting, cMsgGeneralExpired, UsageDaysLeft, cGetUserInfo); //needs to register end; ltForceUpdate: begin result := NotifyUserOfLicenseTermination(ltForceUpdate); end; end; CurrentUser.LicInfo.HasValidSubscription := result; //NOTE: shortcut for Quick look up of status If result then //its ok to run begin AWCustomerEmail := CurrentUser.AWUserInfo.UserLoginEmail; //Store to this global var when accessing services AWCustomerPSW := CurrentUser.AWUserInfo.UserPassword; AWCustomerID := CurrentUser.AWUserInfo.UserAWUID; //any thing else needed before we run end else //canceled, expired or invalid/unknown: ForceQuit or time for checkin but no Internet connection begin result := False; AppForceQuit := True; //no questions asked PostMessage(Application.Handle, WM_CLOSE, 0, 0); end; end; end.
unit TangentClass; interface uses CommonTypes, Config; type TTangentType = ( ttForTemp, ttForDiffTemp ); TTangent = class private //fTemperature: integer; // соответствие температуре public x0, x1, x2: integer; tgA_Units: extended; //коэффициент наклона (первая производная, коэфф а в уравнении y=ax+b), тангенс угал наклона (для отсчётов АЦП) tgA_Degrees: extended; //коэффициент наклона (первая производная, коэфф а в уравнении y=ax+b), тангенс угал наклона (для градусов) tgA_Real: extended; //коэффициент наклона только для отображения уравнения кривой, в координатах градусы - секунды fTangentType: TTangentType; b_Units: extended; //коэффициент b для составления уравнения прямой вида y=kx+b; b_Degrees: extended; b_Real: extended; //коэффициент b только для отображения уравнения кривой, в координатах градусы - секунды fPointsUnits: TXYPoints; fPointsDegrees: TXYPoints; fPointsReal: TXYPoints; constructor Create( aTangentType: TTangentType ); procedure Calc( ); end; implementation uses MathUtils; procedure TTangent.Calc; var a, b: extended; i: integer; begin MinSquareLine( fPointsUnits, a, b ); tgA_Units := a; b_Units := b; MinSquareLine( fPointsDegrees, a, b ); tgA_Degrees := a; b_Degrees := b; MinSquareLine( fPointsReal, a, b ); tgA_Real := a; b_Real := b; end; constructor TTangent.Create( aTangentType: TTangentType ); begin fTangentType:= aTangentType; end; end.
unit rfContactForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BaseFrontForm_Unit, FrontData_Unit, Front_DataBase_Unit, ExtCtrls, AdvPanel, StdCtrls, AdvGroupBox, DB, kbmMemTable, Mask, DBCtrls, AdvSmoothTouchKeyBoard, AdvSmoothButton, ComCtrls, AdvDateTimePicker, AdvDBDateTimePicker, ActnList; type TrfContact = class(TBaseFrontForm) pnlMain: TAdvPanel; AdvTouchKeyBoard: TAdvSmoothTouchKeyBoard; Label1: TLabel; dbeSurName: TDBEdit; Label2: TLabel; dbeFirstName: TDBEdit; Label3: TLabel; dbeMiddleName: TDBEdit; dsMain: TDataSource; MainTable: TkbmMemTable; Label4: TLabel; dbeAddress: TDBEdit; Label5: TLabel; dbePhone: TDBEdit; Label6: TLabel; dbeHPhone: TDBEdit; avdGroupBox: TAdvGroupBox; Label7: TLabel; dbePassportNumber: TDBEdit; Label8: TLabel; Label9: TLabel; Label10: TLabel; dbePassportIssuer: TDBEdit; dbePassportIssCity: TDBEdit; Label11: TLabel; pnlRight: TAdvPanel; btnOK: TAdvSmoothButton; btnCancel: TAdvSmoothButton; dbePassportExpDate: TAdvDBDateTimePicker; dbePassportIssDate: TAdvDBDateTimePicker; alMain: TActionList; actOK: TAction; procedure FormCreate(Sender: TObject); procedure actOKUpdate(Sender: TObject); procedure actOKExecute(Sender: TObject); private FInsertMode: Boolean; FUserKey: Integer; public property InsertMode: Boolean read FInsertMode write FInsertMode; property UserKey: Integer read FUserKey write FUserKey; end; var rfContact: TrfContact; implementation {$R *.dfm} procedure TrfContact.actOKExecute(Sender: TObject); begin if FrontBase.SaveContact(MainTable, FUserKey) then ModalResult := mrOk; end; procedure TrfContact.actOKUpdate(Sender: TObject); begin actOK.Enabled := (not MainTable.FieldByName('FIRSTNAME').IsNull) and (not MainTable.FieldByName('SURNAME').IsNull) and (not MainTable.FieldByName('MIDDLENAME').IsNull); end; procedure TrfContact.FormCreate(Sender: TObject); begin FInsertMode := True; FUserKey := -1; MainTable.FieldDefs.Add('ID', ftInteger, 0); MainTable.FieldDefs.Add('FIRSTNAME', ftString, 20); MainTable.FieldDefs.Add('SURNAME', ftString, 20); MainTable.FieldDefs.Add('MIDDLENAME', ftString, 20); MainTable.FieldDefs.Add('ADDRESS', ftString, 60); MainTable.FieldDefs.Add('PHONE', ftString, 20); MainTable.FieldDefs.Add('HPHONE', ftString, 20); MainTable.FieldDefs.Add('PASSPORTNUMBER', ftString, 40); MainTable.FieldDefs.Add('PASSPORTISSDATE', ftDate, 0); MainTable.FieldDefs.Add('PASSPORTEXPDATE', ftDate, 0); MainTable.FieldDefs.Add('PASSPORTISSCITY', ftString, 20); MainTable.FieldDefs.Add('PASSPORTISSUER', ftString, 40); MainTable.CreateTable; MainTable.Open; MainTable.Edit; MainTable.FieldByName('PASSPORTISSDATE').AsDateTime := EncodeDate(2000, 1, 1); MainTable.FieldByName('PASSPORTEXPDATE').AsDateTime := EncodeDate(2000, 1, 1); MainTable.Post; end; end.
unit IPGeoLocation.Providers.DB_IP; interface uses IPGeoLocation.Interfaces, IPGeoLocation.Core, System.Net.HttpClient; type {$REGION 'TIPGeoLocationProviderDB_IP'} TIPGeoLocationProviderDB_IP = class sealed(TIPGeoLocationProviderCustom) private { private declarations } protected { protected declarations } function GetRequest: IIPGeoLocationRequest; override; public { public declarations } constructor Create(pParent: IIPGeoLocation; const pIP: string); override; end; {$ENDREGION} {$REGION 'TIPGeoLocationResponseDB_IP'} TIPGeoLocationResponseDB_IP = class sealed(TIPGeoLocationResponseCustom) private { private declarations } protected { protected declarations } procedure Parse; override; public { public declarations } end; {$ENDREGION} {$REGION 'TIPGeoLocationRequestDB_IP'} TIPGeoLocationRequestDB_IP = class sealed(TIPGeoLocationRequestCustom) private { private declarations } protected { protected declarations } function InternalExecute: IHTTPResponse; override; function GetResponse(pIHTTPResponse: IHTTPResponse): IGeoLocation; override; function GetMessageExceptionAPI(const pJSON: string): string; override; public { public declarations } constructor Create(pParent: IIPGeoLocationProvider; const pIP: string); override; end; {$ENDREGION} implementation uses System.JSON, System.SysUtils, System.Net.URLClient, IPGeoLocation.Types; {$I APIKey.inc} {$REGION 'TIPGeoLocationProviderDB_IP'} constructor TIPGeoLocationProviderDB_IP.Create(pParent: IIPGeoLocation; const pIP: string); begin inherited Create(pParent, pIP); FID := '#DB-IP'; FURL := 'http://api.db-ip.com'; FAPIKey := APIKey_DB_IP; //TOKEN FROM APIKey.inc end; function TIPGeoLocationProviderDB_IP.GetRequest: IIPGeoLocationRequest; begin Result := TIPGeoLocationRequestDB_IP.Create(Self, FIP); end; {$ENDREGION} {$REGION 'TIPGeoLocationProviderDB_IP'} procedure TIPGeoLocationResponseDB_IP.Parse; var lJSONObject: TJSONObject; begin lJSONObject := nil; try lJSONObject := TJSONObject.ParseJSONValue(FJSON) as TJSONObject; if not Assigned(lJSONObject) then Exit; lJSONObject.TryGetValue('countryCode', FCountryCode); lJSONObject.TryGetValue('countryName ', FCountryName); lJSONObject.TryGetValue('stateProv', FState); lJSONObject.TryGetValue('city', FCity); lJSONObject.TryGetValue('district', FDistrict); lJSONObject.TryGetValue('zipCode', FZipCode); lJSONObject.TryGetValue('latitude', FLatitude); lJSONObject.TryGetValue('longitude', FLongitude); lJSONObject.TryGetValue('timeZone', FTimeZoneName); lJSONObject.TryGetValue('gmtOffset', FTimeZoneOffset); lJSONObject.TryGetValue('isp', FISP); finally lJSONObject.Free; end; end; {$ENDREGION} {$REGION 'TIPGeoLocationRequestDB_IP'} constructor TIPGeoLocationRequestDB_IP.Create(pParent: IIPGeoLocationProvider; const pIP: string); begin inherited Create(pParent, pIP); FResponseLanguageCode := 'en-US'; end; function TIPGeoLocationRequestDB_IP.GetMessageExceptionAPI( const pJSON: string): string; begin Result := pJSON; end; function TIPGeoLocationRequestDB_IP.GetResponse( pIHTTPResponse: IHTTPResponse): IGeoLocation; begin Result := TIPGeoLocationResponseDB_IP.Create(pIHTTPResponse.ContentAsString, FIP, FProvider); end; function TIPGeoLocationRequestDB_IP.InternalExecute: IHTTPResponse; var lURL: TURI; lJSONObject: TJSONObject; lRequestError: string; lRequestMessage: string; begin //CONFORME A DOCUMENTAÇÃO DA API lURL := TURI.Create(Format('%s/%s/%s/%s', [ FIPGeoLocationProvider.URL, 'v2', FIPGeoLocationProvider.APIKey, FIP])); FHttpRequest.URL := lURL.ToString; FHttpRequest.CustomHeaders['Accept-Language'] := FResponseLanguageCode; //REQUISIÇÃO Result := inherited InternalExecute; lJSONObject := nil; try lJSONObject := TJSONObject.ParseJSONValue(Result.ContentAsString) as TJSONObject; lJSONObject.TryGetValue('errorCode', lRequestError); if (lRequestError <> EmptyStr) then begin lRequestMessage := Format('%s: %s', [lJSONObject.GetValue('errorCode').ToJSON, lJSONObject.GetValue('error').ToJSON]); raise EIPGeoLocationException.Create(TIPGeoLocationExceptionKind.EXCEPTION_API, FIP, FProvider, Now(), lRequestMessage); end; finally lJSONObject.Free; end; end; {$ENDREGION} end.
unit DBAppConfigArq; interface uses Winapi.Windows, System.SysUtils, System.Variants, System.Classes, IOUtils, XMLDoc, XMLIntf, DBAppBaseArq; type TDBAppConfigArq = class(TDBAppBaseArq) private ConfigArqPath : String; ConfigArqNome : String; FDiretorioDeProjetos : string; FListaProblemas : TStringList; procedure CarregarConfigArq; function GerarXml: string; procedure DefDiretorio(const Value: string); public constructor Create; function Salvar: boolean; property DiretorioDeProjetos : string read FDiretorioDeProjetos write DefDiretorio; property ListaProblemas : TStringList read FListaProblemas; end; implementation constructor TDBAppConfigArq.Create; begin inherited Create(); FListaProblemas := TStringList.Create; CarregarConfigArq; end; function TDBAppConfigArq.GerarXml: string; begin result := '<dbapp_config>'+ '<projetos>'+FDiretorioDeProjetos+'</projetos>'+ '</dbapp_config>'; end; function TDBAppConfigArq.Salvar: boolean; begin Result := false; FListaProblemas.Clear; if (FDiretorioDeProjetos = '') then begin FListaProblemas.Add('O diretório de projetos não foi informado.'); end; if (FListaProblemas.Count = 0) then begin try TFile.WriteAllText(ConfigArqPath,GerarXml()); Result := true; except FListaProblemas.Add('Não foi possível salvar o arquivo de configuração.'); end; end; end; procedure TDBAppConfigArq.CarregarConfigArq; var ConfigStr : String; ConfigDoc : IXMLDocument; NodeProjetos : IXMLNode; begin ConfigStr := GerarXml(); ConfigArqNome := 'config.dbapp'; ConfigArqPath := TPath.Combine(ExtrairDiretorio(ParamStr(0)),ConfigArqNome); if (FileExists(ConfigArqPath)) then begin try ConfigStr := TFile.ReadAllText(ConfigArqPath); except end; end; ConfigDoc := TXMLDocument.Create(nil); ConfigDoc.LoadFromXML(ConfigStr); NodeProjetos := ConfigDoc.DocumentElement.ChildNodes.FindNode('projetos'); if (NodeProjetos <> nil) then begin FDiretorioDeProjetos := NodeProjetos.Text; end; end; procedure TDBAppConfigArq.DefDiretorio(const Value: string); begin FDiretorioDeProjetos := Value; end; end.