text
stringlengths
14
6.51M
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_Random; interface uses Classes; type TRandomStream = class( TStream) private FValue: int64; FBuffer: int64; FAvail: integer; procedure Crunch; procedure SetSeed( Value: int64); protected function GetSize: Int64; override; procedure SetSize( const NewSize: Int64); override; public constructor Create; destructor Destroy; override; class function Instance: TRandomStream; function Read ( var Buffer; Count: Longint): Longint; override; function Write( const Buffer; Count: Longint): Longint; override; function Seek ( const Offset: Int64; Origin: TSeekOrigin): Int64; override; procedure Randomize; property Seed: int64 read FValue write SetSeed; end; implementation uses {$IFDEF MSWINDOWS}Windows, {$ENDIF}Math, SysUtils, uTPLb_IntegerUtils; var Inst: TRandomStream = nil; {$IFDEF MSWINDOWS} function TimeStampClock: int64; asm RDTSC end; {$ENDIF} procedure InitUnit_Random; begin end; procedure DoneUnit_Random; begin Inst.Free end; {$IFDEF MSWINDOWS} function CryptAcquireContext( var phProv: THandle; pszContainer, pszProvider: PChar; dwProvType, dwFlags: DWORD): bool; stdcall; external advapi32 name 'CryptAcquireContextW'; function CryptReleaseContext( hProv: THandle; dwFlags: DWORD): bool; stdcall; external advapi32 name 'CryptReleaseContext'; function CryptGenRandom( hProv: THandle; dwLen: DWORD; pbBuffer: pointer): bool; stdcall; external advapi32 name 'CryptGenRandom'; const PROV_RSA_FULL = 1; CRYPT_SILENT = 64; Provider = 'Microsoft Base Cryptographic Provider v1.0'; {$ENDIF} { TRandomStream } constructor TRandomStream.Create; begin if not assigned( Inst) then Inst := self; Randomize end; {$OVERFLOWCHECKS OFF} {$RANGECHECKS OFF} procedure TRandomStream.Crunch; // Refer http://www.merlyn.demon.co.uk/pas-rand.htm const Factor: int64 = 6364136223846793005; begin FValue := FValue * Factor + 1 ; FBuffer := FValue; FAvail := SizeOf( FValue) end; {$RANGECHECKS ON} {$OVERFLOWCHECKS ON} destructor TRandomStream.Destroy; begin if Inst = self then Inst := nil; inherited end; function TRandomStream.GetSize: Int64; begin result := 0 end; class function TRandomStream.Instance: TRandomStream; begin if not assigned( Inst) then TRandomStream.Create; result := Inst end; procedure TRandomStream.Randomize; {$IFDEF SMWINDOWS} var hProv: THandle; dwProvType, dwFlags: DWORD; Provider1: string; hasOpenHandle: boolean; {$ENDIF} begin {$IFDEF SMWINDOWS} Provider1 := Provider; dwProvType := PROV_RSA_FULL; dwFlags := CRYPT_SILENT; hasOpenHandle := CryptAcquireContext( hProv, nil, PChar( Provider), dwProvType, dwFlags); try if (not hasOpenHandle) or (not CryptGenRandom( hProv, SizeOf( FValue), @FValue)) then FValue := TimeStampClock finally if hasOpenHandle then CryptReleaseContext( hProv, 0) end; Crunch {$ENDIF} end; function TRandomStream.Read( var Buffer; Count: Integer): Longint; var P: PByte; Amnt, AmntBits, C: integer; Harv: int64; Carry: uint32; begin result := Max( Count, 0); if result <= 0 then exit; P := @Buffer; C := result; repeat Amnt := Min( FAvail, C); Move( FBuffer, P^, Amnt); Dec( FAvail, Amnt); Dec( C, Amnt); Inc( P, Amnt); if FAvail <= 0 then Crunch else begin Harv := FBuffer; if Amnt >= 4 then begin Int64Rec( Harv).Lo := Int64Rec( Harv).Hi; Int64Rec( Harv).Hi := 0; Dec( Amnt, 4) end; if Amnt > 0 then begin AmntBits := Amnt * 8; Carry := Int64Rec( Harv).Hi shl (32 - (AmntBits)); Int64Rec( Harv).Hi := Int64Rec( Harv).Hi shr AmntBits; Int64Rec( Harv).Lo := (Int64Rec( Harv).Lo shr AmntBits) or Carry; end; FBuffer := Harv end until C <= 0 end; function TRandomStream.Seek( const Offset: Int64; Origin: TSeekOrigin): Int64; begin result := 0 end; procedure TRandomStream.SetSeed( Value: int64); begin FValue := Value; FBuffer := FValue; FAvail := SizeOf( FBuffer) end; procedure TRandomStream.SetSize( const NewSize: Int64); begin end; function TRandomStream.Write( const Buffer; Count: Integer): Longint; begin result := Count end; initialization InitUnit_Random; finalization DoneUnit_Random; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Data.MessageBody.Default; interface uses System.Classes, System.SysUtils, System.Rtti, System.Contnrs, WiRL.Core.Classes, WiRL.Core.Attributes, WiRL.http.Core, WiRL.http.Headers, WiRL.http.Response, WiRL.Core.Declarations, WiRL.http.Accept.MediaType, WiRL.Core.MessageBody.Classes, WiRL.Core.MessageBodyReader, WiRL.Core.MessageBodyWriter, WiRL.Configuration.Neon; type [Produces(TMediaType.APPLICATION_JSON)] [Consumes(TMediaType.APPLICATION_JSON)] TArrayDataSetProvider = class(TMessageBodyProvider) private [Context] WiRLConfigurationNeon: TWiRLConfigurationNeon; public function ReadFrom(AType: TRttiType; AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream): TValue; override; procedure ReadFrom(AObject: TObject; AType: TRttitype; AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream); override; procedure WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); override; end; [Produces(TMediaType.APPLICATION_XML)] TDataSetWriterXML = class(TMessageBodyWriter) procedure WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); override; end; [Produces(TMediaType.TEXT_CSV)] TDataSetWriterCSV = class(TMessageBodyWriter) procedure WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); override; end; implementation uses Data.DB, Neon.Core.Persistence, Neon.Core.Persistence.JSON, WiRL.Core.JSON, WiRL.Data.Utils, WiRL.Rtti.Utils; { TDataSetWriterXML } procedure TDataSetWriterXML.WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); var LStreamWriter: TStreamWriter; begin LStreamWriter := TStreamWriter.Create(AContentStream); try LStreamWriter.Write(TDataUtils.DataSetToXML(Avalue.AsObject as TDataSet)); finally LStreamWriter.Free; end; end; { TArrayDataSetProvider } function TArrayDataSetProvider.ReadFrom(AType: TRttiType; AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream): TValue; begin raise Exception.Create('Not implemented'); end; procedure TArrayDataSetProvider.ReadFrom(AObject: TObject; AType: TRttitype; AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream); var LJson: TJSONValue; LBuffer: TBytes; LList: TDataSetList; LDataSet: TDataSet; begin if not (AObject is TDataSetList) then raise EWiRLException.Create('Invalid entity'); LList := TDataSetList(AObject); AContentStream.Position := 0; SetLength(LBuffer, AContentStream.Size); AContentStream.Read(LBuffer[0], AContentStream.Size); LJson := TJSONObject.ParseJSONValue(LBuffer, 0); try if not Assigned(LJson) then raise EWiRLException.Create('Invalid JSON'); for LDataSet in LList do begin if not LDataSet.Active then LDataSet.Open; TNeon.JSONToObject(LDataSet, LJson.GetValue<TJSONValue>(LDataSet.Name), WiRLConfigurationNeon.GetNeonConfig); end; finally LJson.Free; end; end; procedure TArrayDataSetProvider.WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); var LStreamWriter: TStreamWriter; LResult: TJSONObject; LData: TArray<TDataSet>; LCurrent: TDataSet; begin LStreamWriter := TStreamWriter.Create(AContentStream); try LData := AValue.AsType<TArray<TDataSet>>; LResult := TJSONObject.Create; try { TODO -opaolo -c : LCurrent.Name can be empty and producing an JSON error 30/05/2017 16:26:09 } for LCurrent in LData do LResult.AddPair(LCurrent.Name, TNeon.ObjectToJSON(LCurrent, WiRLConfigurationNeon.GetNeonConfig)); LStreamWriter.Write(TJSONHelper.ToJSON(LResult)); finally LResult.Free; end; finally LStreamWriter.Free; end; end; { TDataSetWriterCSV } procedure TDataSetWriterCSV.WriteTo(const AValue: TValue; const AAttributes: TAttributeArray; AMediaType: TMediaType; AHeaderFields: IWiRLHeaders; AContentStream: TStream); var LStreamWriter: TStreamWriter; begin LStreamWriter := TStreamWriter.Create(AContentStream); try LStreamWriter.Write(TDataUtils.DataSetToCSV(Avalue.AsObject as TDataSet)); finally LStreamWriter.Free; end; end; { RegisterMessageBodyClasses } procedure RegisterMessageBodyClasses; begin // TArrayDataSetProvider (reader and writer for TDataSet array) TMessageBodyReaderRegistry.Instance.RegisterReader( TArrayDataSetProvider, function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean begin Result := Assigned(AType) and TRttiHelper.IsObjectOfType<TDataSetList>(AType); end, function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer begin Result := TMessageBodyWriterRegistry.AFFINITY_HIGH; end ); // TArrayDataSetWriter TMessageBodyWriterRegistry.Instance.RegisterWriter( TArrayDataSetProvider, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean begin Result := Assigned(AType) and TRttiHelper.IsDynamicArrayOf<TDataSet>(AType); // and AMediaType = application/json end, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer begin Result := TMessageBodyWriterRegistry.AFFINITY_LOW end ); // TDataSetWriterXML TMessageBodyWriterRegistry.Instance.RegisterWriter( TDataSetWriterXML, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean begin Result := Assigned(AType) and TRttiHelper.IsObjectOfType<TDataSet>(AType); // and AMediaType = application/xml end, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer begin Result := TMessageBodyWriterRegistry.AFFINITY_LOW; end ); // TDataSetWriterCSV TMessageBodyWriterRegistry.Instance.RegisterWriter( TDataSetWriterCSV, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean begin Result := Assigned(AType) and TRttiHelper.IsObjectOfType<TDataSet>(AType); // and AMediaType = application/xml end, function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer begin Result := TMessageBodyWriterRegistry.AFFINITY_LOW; end ); end; initialization RegisterMessageBodyClasses; end.
unit UMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Data.Bind.Components, Data.Bind.ObjectScope, REST.Client, IPPeerClient, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Vcl.Grids, Vcl.ValEdit, REST.Types, System.NetEncoding, System.Net.URLClient, System.Net.HttpClient, Vcl.ToolWin, Vcl.Buttons, System.Actions, Vcl.ActnList; type TForm1 = class(TForm) Panel1: TPanel; edtResource: TEdit; btnSend: TButton; Panel2: TPanel; StatusBar1: TStatusBar; RadioGroup1: TRadioGroup; rbGet: TRadioButton; rbPut: TRadioButton; rbPost: TRadioButton; rbDelete: TRadioButton; RESTResponse: TRESTResponse; RESTRequest: TRESTRequest; RESTClient: TRESTClient; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Authentication: TTabSheet; MemRequestBody: TMemo; chkBasicAuth: TCheckBox; edtUsername: TLabeledEdit; edtPassword: TLabeledEdit; BindingsList1: TBindingsList; LinkControlToPropertyEnabled: TLinkControlToProperty; LinkControlToPropertyEnabled2: TLinkControlToProperty; Splitter1: TSplitter; PageControl2: TPageControl; TabSheet3: TTabSheet; MemResponse: TMemo; TabSheet4: TTabSheet; VLResponseHeaders: TValueListEditor; VLRequestHeaders: TValueListEditor; Panel3: TPanel; btnAddHeader: TBitBtn; btnRemoveHeader: TBitBtn; Splitter2: TSplitter; Panel4: TPanel; edtBaseUrl: TEdit; Panel5: TPanel; ActionList1: TActionList; actSend: TAction; function GetMethod: TRESTRequestMethod; procedure btnAddHeaderClick(Sender: TObject); procedure btnRemoveHeaderClick(Sender: TObject); procedure edtResourceKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure actSendExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.edtResourceKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then begin actSend.Execute; end; end; function TForm1.GetMethod: TRESTRequestMethod; begin if rbGet.Checked then Result := TRESTRequestMethod.rmGET else if rbPost.Checked then Result := TRESTRequestMethod.rmPOST else if rbPut.Checked then Result := TRESTRequestMethod.rmPUT else if rbDelete.Checked then Result := TRESTRequestMethod.rmDELETE; end; procedure TForm1.actSendExecute(Sender: TObject); var I: Integer; h: Array of String; key: String; basicAuthHeader: String; authHeaderIndex: Integer; bytes: TBytes; rp: TRESTRequestParameter; begin MemResponse.Lines.Clear; VLResponseHeaders.Strings.Clear; StatusBar1.Panels[0].Text := ''; StatusBar1.Panels[1].Text := 'Sending...'; StatusBar1.Panels[2].Text := ''; StatusBar1.Refresh; actSend.Enabled := false; RESTClient.BaseURL := edtBaseUrl.Text; RESTRequest.Resource := edtResource.Text; RESTRequest.Method := self.GetMethod; if chkBasicAuth.Checked then begin bytes := TEncoding.UTF8.GetBytes(edtUsername.Text + ':' + edtPassword.Text); basicAuthHeader := 'Basic ' + TNetEncoding.Base64.EncodeBytesToString(bytes); authHeaderIndex := VLRequestHeaders.Strings.IndexOfName('Authorization'); if authHeaderIndex <> -1 then begin VLRequestHeaders.DeleteRow(authHeaderIndex + 1); end; VLRequestHeaders.InsertRow('Authorization', basicAuthHeader, True); end else begin authHeaderIndex := VLRequestHeaders.Strings.IndexOfName('Authorization'); if authHeaderIndex <> -1 then begin VLRequestHeaders.DeleteRow(authHeaderIndex + 1); end; end; RESTRequest.Params.Clear; for I := 1 to VLRequestHeaders.RowCount - 1 do begin key := VLRequestHeaders.Keys[I]; if key.Length > 0 then begin rp := RESTRequest.Params.AddItem; rp.name := key; rp.Value := VLRequestHeaders.Values[key]; rp.Kind := TRESTRequestParameterKind.pkHTTPHEADER; rp.Options := [TRESTRequestParameterOption.poDoNotEncode]; //ShowMessage('Added: ' + key + '=' + VLRequestHeaders.Values[key]); end; end; if (self.GetMethod = TRESTRequestMethod.rmPOST) or (self.GetMethod = TRESTRequestMethod.rmPUT) then begin RESTRequest.AddBody(MemRequestBody.Text, TRESTContentType.ctAPPLICATION_JSON); end; { for I := 0 to RESTRequest.Params.Count - 1 do begin ShowMessage(RESTRequest.Params[I].ToString); end; } RESTRequest.Execute; StatusBar1.Panels[0].Text := RESTResponse.StatusCode.ToString; StatusBar1.Panels[1].Text := RESTResponse.StatusText; StatusBar1.Panels[2].Text := RESTResponse.ContentLength.ToString + ' Bytes'; MemResponse.Text := RESTResponse.JSONText; actSend.Enabled := true; for I := 0 to RESTResponse.Headers.Count - 1 do begin VLResponseHeaders.InsertRow(RESTResponse.Headers[I].Split(['='])[0], RESTResponse.Headers[I].Split(['='])[1], True); end; end; procedure TForm1.btnAddHeaderClick(Sender: TObject); begin VLRequestHeaders.InsertRow(' ', ' ', True); end; procedure TForm1.btnRemoveHeaderClick(Sender: TObject); begin VLRequestHeaders.DeleteRow(VLRequestHeaders.Selection.Top); end; end.
unit Mission_edit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, misc_utils, Files, FileOperations, GlobalVars; type TMissionEdit = class(TForm) GroupBox1: TGroupBox; CBSolo: TCheckBox; BNRCS: TButton; GroupBox2: TGroupBox; CBHistoric: TCheckBox; BNRCA: TButton; GroupBox3: TGroupBox; CBMulti: TCheckBox; BNRCM: TButton; BNITM: TButton; BNCHK: TButton; LBMissionIs: TLabel; procedure FormCreate(Sender: TObject); procedure CBClick(Sender: TObject); procedure BNRCSClick(Sender: TObject); procedure BNRCAClick(Sender: TObject); procedure BNRCMClick(Sender: TObject); procedure BNITMClick(Sender: TObject); procedure BNCHKClick(Sender: TObject); private { Private declarations } RCSName:String; RCAName:String; RCMName:String; Procedure SetHandlers; Procedure ClearHandlers; Function GetITMName:String; Function GetCHKName:String; Function LevelName:String; Function ProjDir:String; public { Public declarations } Procedure Reset; Procedure EditMission; end; Function GetCHKFromITM(const ITM:String):String; var MissionEdit: TMissionEdit; Const NewRCS:String= 'RCP 1.0'#13#10+ 'NAME: Outlaws Story'#13#10+ 'FLAGS: 0'#13#10#13#10+ 'STORY:'#13#10+ 'BEGIN'#13#10+ 'LEVEL: %s'#13#10+ 'END'#13#10#13#10+ 'PATHS: 0'; NewRCA:String= 'RCP 1.0'#13#10+ 'NAME: Marshal Training'#13#10+ 'FLAGS: 0'#13#10#13#10+ 'STORY:'#13#10+ 'BEGIN'#13#10+ 'LEVEL: %s'#13#10+ 'END'#13#10#13#10+ 'PATHS: 0'; NewRCM:String= 'RCP 1.0'#13#10+ 'NAME: %s'#13#10+ '# c - capture the flag'#13#10+ '# t - tag'#13#10+ '# k - kill man with ball'#13#10+ '# s - secret doc'#13#10+ '# m - team play'#13#10+ '# d - death match'#13#10+ 'MODES: CKMD'#13#10#13#10+ 'STORY:'#13#10+ 'BEGIN'#13#10+ 'LEVEL: %s'#13#10+ 'END'; NewITM:String= 'ITEM 1.0'#13#10+ 'NAME %s'#13#10+ 'FUNC NULL'#13#10+ 'ANIM NULL'#13#10+ 'PRELOAD: %s.chk'#13#10+ 'DATA 1'; implementation uses Mapper, LECScripts; {$R *.DFM} procedure TMissionEdit.FormCreate(Sender: TObject); begin ClientWidth:=2*GroupBox1.Left+GroupBox1.Width; ClientHeight:=LBMissionIs.Top+GroupBox3.Top+GroupBox3.Height; end; Procedure TMissionEdit.Reset; begin ClearHandlers; CBSolo.Checked:=false; CBHistoric.Checked:=false; CBMulti.Checked:=false; BNRCS.Enabled:=false; BNRCA.Enabled:=false; BNRCM.Enabled:=false; BNITM.Enabled:=false; BNCHK.Enabled:=false; SetHandlers; end; Procedure TMissionEdit.EditMission; var sr:TSearchRec; begin Reset; ClearHandlers; If FindFirst(ProjDir+'*.rcs',faAnyFile,sr)=0 then begin RCSName:=sr.Name; CBSolo.Checked:=true; BNRCS.Enabled:=true; end; FindClose(sr); If FindFirst(ProjDir+'*.rca',faAnyFile,sr)=0 then begin RCAName:=sr.Name; CBHistoric.Checked:=true; BNRCA.Enabled:=true; end; FindClose(sr); If FindFirst(ProjDir+'*.rcm',faAnyFile,sr)=0 then begin RCMName:=sr.Name; CBMulti.Checked:=true; BNRCM.Enabled:=true; BNITM.Enabled:=true; BNCHK.Enabled:=true; end; FindClose(sr); SetHandlers; ShowModal; end; Procedure TMissionEdit.SetHandlers; begin CBSolo.OnClick:=CBClick; CBHistoric.OnClick:=CBClick; CBMulti.OnClick:=CBClick; end; Procedure TMissionEdit.ClearHandlers; begin CBSolo.OnClick:=nil; CBHistoric.OnClick:=nil; CBMulti.OnClick:=nil; end; Function TMissionEdit.GetITMName:String; begin Result:=LevelName+'.itm'; end; Function GetCHKFromITM(const ITM:String):String; var t:TLecTextFile;s,w:String;p:integer; begin Result:=''; t:=TLecTextFile.CreateRead(OpenFileRead(ITM,0)); While not t.eof do begin T.Readln(s); p:=GetWord(s,1,w); if w='PRELOAD:' then begin GetWord(s,p,Result); break; end; end; t.FClose; end; Function TMissionEdit.GetCHKName:String; begin Result:=GetCHKFromITM(ProjDir+GetITMName); end; procedure TMissionEdit.CBClick(Sender: TObject); var CB:TCheckBox; FName:String; DefExt:String; FNew:String; sr:TSearchRec; t:TextFile; begin CB:=(Sender as TCheckBox); if CB=CBSolo then Fname:=RCSName; if CB=CBHistoric then Fname:=RCAName; if CB=CBMulti then FName:=RCMName; case CB.Checked of false: begin if MsgBox('Do you really want to delete '+Fname+'?','Confirm',mb_YesNo)=idNo then begin ClearHandlers; CB.Checked:=true; SetHandlers; exit; end; DeleteFile(ProjDir+FName); if CB=CBSolo then BNRCS.Enabled:=false; if CB=CBHistoric then BNRCA.Enabled:=false; if CB=CBMulti then begin BNRCM.Enabled:=false; BNITM.Enabled:=false; BNCHK.Enabled:=false; end; end; true: begin if CB=CBSolo then begin defExt:='.rcs'; Fnew:=Format(NewRCS,[LevelName]); end; if CB=CBHistoric then begin defExt:='.rca'; Fnew:=Format(NewRCA,[LevelName]); end; if CB=CBMulti then begin DefExt:='.rcm'; Fnew:=Format(NewRCM,[LevelName,LevelName]); end; FName:=LevelName+DefExt; AssignFile(t,ProjDir+FName); Rewrite(t); Write(t,Fnew); CloseFile(t); if CB=CBMulti then begin if not FileExists(ProjDir+LevelName+'.itm') then begin AssignFile(t,ProjDir+LevelName+'.itm');ReWrite(t); Write(t,Format(NewITM,[LevelName,LevelName])); CloseFile(t); end; Fnew:=GetCHKName; if (Fnew='') or (not FileExists(Fnew)) then begin if FileExists(BaseDir+'Lmdata\usrlevel.chk') then CopyAllFile(BaseDir+'Lmdata\usrlevel.chk',ProjDir+LevelName+'.chk') else CopyAllFile(BaseDir+'usrlevel.chk',ProjDir+LevelName+'.chk') end; end; if CB=CBSolo then begin RCSName:=Fname; BNRCS.Enabled:=true; end; if CB=CBHistoric then begin RCAName:=FName; BNRCA.Enabled:=true; end; if CB=CBMulti then begin RCMName:=FName; BNRCM.Enabled:=true; BNITM.Enabled:=true; BNCHK.Enabled:=true; end; end; end; end; Function TMissionEdit.LevelName:String; begin Result:=MapWIndow.LevelName; end; Function TMissionEdit.ProjDir:String; begin Result:=MapWIndow.ProjectDirectory; end; procedure TMissionEdit.BNRCSClick(Sender: TObject); begin ScriptEdit.OpenScript(ProjDir+RCSName); end; procedure TMissionEdit.BNRCAClick(Sender: TObject); begin ScriptEdit.OpenScript(ProjDir+RCAName); end; procedure TMissionEdit.BNRCMClick(Sender: TObject); begin ScriptEdit.OpenScript(ProjDir+RCMName); end; procedure TMissionEdit.BNITMClick(Sender: TObject); begin ScriptEdit.OpenScript(ProjDir+GetITMName); end; procedure TMissionEdit.BNCHKClick(Sender: TObject); begin ScriptEdit.OpenScript(ProjDir+GetCHKName); end; end.
unit JediInstallIntf; interface uses ComCtrls, DelphiInstall; const // Feature masks FID_Product = $7F000000; FID_IsProduct = $00FFFFFF; FID_Category = $00FF0000; FID_IsCategory = $0000FFFF; FID_Level2 = $0000FF00; FID_IsLevel2 = $000000FF; FID_Level3 = $000000FF; FID_Checked = $80000000; FID_NumberMask = $7FFFFFFF; // Icon indexes IcoProduct = 0; IcoLevel1 = 1; IcoChecked = 2; IcoUnchecked = 3; type IJediInstallTool = interface ['{30E41236-3DCD-4F84-9ADF-4489CA1E4EC7}'] function ActiveVersionNumberPage: Integer; function BPLPath(VersionNumber: Integer): string; function DCPPath(VersionNumber: Integer): string; function FeatureChecked(FeatureID: Cardinal; VersionNumber: Integer): Boolean; function GetDelphiInstallations: TJclDelphiInstallations; function MessageBox(const Text: string; Flags: Integer): Integer; procedure UpdateInfo(VersionNumber: Integer; const InfoText: string); procedure UpdateStatus(const Text: string); property DelphiInstallations: TJclDelphiInstallations read GetDelphiInstallations; end; IJediInstall = interface ['{BE0A7968-9003-40DD-99F0-250CAC8B2D85}'] function InitInformation(const ApplicationFileName: string): Boolean; function Install: Boolean; function PopulateTreeView(Nodes: TTreeNodes; VersionNumber: Integer; Page: TTabSheet): Boolean; function SelectedNodeCollapsing(Node: TTreeNode): Boolean; procedure SelectedNodeChanged(Node: TTreeNode); procedure SetTool(const Value: IJediInstallTool); end; implementation end.
unit StringsBasicsForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, FMX.Layouts, FMX.Memo; type TTabbedForm = class(TForm) HeaderToolBar: TToolBar; ToolBarLabel: TLabel; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; btnRefCount: TButton; Memo1: TMemo; procedure btnRefCountClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var TabbedForm: TTabbedForm; implementation {$R *.fmx} var str2: string; procedure TTabbedForm.btnRefCountClick(Sender: TObject); var str1: string; begin str2 := 'Hello'; Memo1.Lines.Add('Initial RefCount: ' + IntToStr (StringRefCount(str2))); str1 := str2; Memo1.Lines.Add('After assign RefCount: ' + IntToStr (StringRefCount(str2))); str2 := str2 + ' World!'; Memo1.Lines.Add('After change RefCount: ' + IntToStr (StringRefCount(str2))); end; end.
namespace proholz.xsdparser; type SimpleTypeFinalEnum = public enum (list, &union, restriction, all); //#all FinalDefaultEnum = public enum(default, extension, restriction, list, union , all); //#all FinalEnum = public enum(extension, restriction, all); //#all // * // * An {@link Enum} with all the possible values for the whiteSpace attribute. // WhiteSpaceEnum = public enum(preserve, collapse, replace); /** * An {@link Enum} with all the possible values for the blockDefault attribute of {@link XsdSchema}. */ BlockDefaultEnum = public enum(default, extension, restriction, substitution, all); //#all BlockEnum = public enum(extension, restriction, substitution, all); //#all ComplexTypeBlockEnum = public enum(extension, restriction, all); //#all FormEnum = public enum(qualified, unqualified); UsageEnum = public enum(required, prohibited, optional); {$IF TOFFEE OR ISLAND} SimpleTypeFinalEnumExtensions = public extension record(SimpleTypeFinalEnum) public class method TryParse(value : String; out res : SimpleTypeFinalEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : SimpleTypeFinalEnum := low(SimpleTypeFinalEnum) to High(SimpleTypeFinalEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; FinalDefaultEnumExtensions = public extension record(FinalDefaultEnum) public class method TryParse(value : String; out res : FinalDefaultEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : FinalDefaultEnum := low(FinalDefaultEnum) to High(FinalDefaultEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; FinalEnumExtensions = public extension record(FinalEnum) public class method TryParse(value : String; out res : FinalEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : FinalEnum := low(FinalEnum) to High(FinalEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; WhiteSpaceEnumExtensions = public extension record(WhiteSpaceEnum) public class method TryParse(value : String; out res : WhiteSpaceEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : WhiteSpaceEnum := low(WhiteSpaceEnum) to High(WhiteSpaceEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; BlockDefaultEnumExtensions = public extension record(BlockDefaultEnum) public class method TryParse(value : String; out res : BlockDefaultEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : BlockDefaultEnum := low(BlockDefaultEnum) to High(BlockDefaultEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; BlockEnumExtensions = public extension record(BlockEnum) public class method TryParse(value : String; out res : BlockEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : BlockEnum := low(BlockEnum) to High(BlockEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; FormEnumExtensions = public extension record(FormEnum) public class method TryParse(value : String; out res : FormEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : FormEnum := low(FormEnum) to High(FormEnum) do begin if temp.ToString.Equals(value) then begin res := temp; exit true; end; end; exit false; end; end; ComplexTypeBlockEnumExtensions = public extension record(ComplexTypeBlockEnum) public class method TryParse(value : String; out res : ComplexTypeBlockEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : ComplexTypeBlockEnum := low(ComplexTypeBlockEnum) to High(ComplexTypeBlockEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; UsageEnumExtensions = public extension record(UsageEnum) public class method TryParse(value : String; out res : UsageEnum) : boolean; begin If String.IsNullOrEmpty(value) then exit false; for temp : UsageEnum := low(UsageEnum) to High(UsageEnum) do if temp.ToString.Equals(value) then begin res := temp; exit true; end; exit false; end; end; {$ENDIF} end.
unit nsTemplateLib; Simple exemple interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} // nsTemplateLib.cpp : Defines the entry point for the DLL application // All exported library functions are defined here // // This is a template source file to use as an example on how to create a Neuroshare // DLL library. Library functions are provided with hints on what to create and fill in. // The following exported library functions are included here: // DllMain // ns_GetLibraryInfo // ns_OpenFile // ns_CloseFile // ns_GetFileInfo // ns_GetEntityInfo // ns_GetEventInfo; // ns_GetEventData; // ns_GetAnalogInfo; // ns_GetAnalogData; // ns_GetSegmentInfo; // ns_GetSegmentSourceInfo; // ns_GetSegmentData; // ns_GetNeuralInfo; // ns_GetNeuralData; // ns_GetIndexByTime; // ns_GetTimeByIndex; // ns_GetLastErrorMsg // // // // _stdcall calling conventions used for exported functions to make them compatible with // application using both C++ and Pascal (VBasic) calling conventions. // nsTemplateLib.def file is used to export the library functions and create the library // nsTemplateLib.dll. nsTemplateLib.def is placed in the same directory as the source file // nsTemplateLib.cpp and linked with the source file uses nsAPItypes; /////////////////////////////////////////////////////////////////////////////////////////////////// // // DLL process local storage in the form of global variables // (in Win32, each process linking a DLL gets its own copy of the DLL's global variables) // /////////////////////////////////////////////////////////////////////////////////////////////////// // Define any global handles or file catalogs. /////////////////////////////////////////////////////////////////////////////////////////////////// // // Exported Neuroshare functions // /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetLibraryInfo // // Retrieves information about the loaded API library // // Parameters: // // ns_LIBRARYINFO *pLibraryInfo pointer to ns_LIBRARYINFO structure to receive information // uint32 dwLibraryInfoSize size in bytes of ns_LIBRARYINFO structure // // Return Values: // // ns_OK ns_LIBIRARYINFO successfully retrieved // ns_LIBEERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetLibraryInfo( var LibraryInfo: ns_LIBRARYINFO; dwLibraryInfoSize: uint32):ns_Result;cdecl; // Verify validity of passed parameters // Null pointers mean that no information is returned // Fill in ns_LIBIRARYINFO structure with information for this library // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_OpenFile // // Opens the data file and assigns a file handle for internal use by the library. // Library is required to be able to handle a minimum of 64 simultaneously open data files, if // system resources allow. // // Parameters: // // char *pszFilename name of file to open // uint32 *hFile pointer to a file handle // // Return Values: // // ns_OK ns_LIBIRARYINFO successfully retrieved // ns_TYPEERROR library unable to open file type // ns_FILEERROR file access or read error // ns_LIBEERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_OpenFile(pszFilename: Pansichar; var hFile: uint32):ns_Result;cdecl; // Open data files and return file handles // Invalid file handles are NULL. // Create Neuroshare Entity types. This is may be a good place to enumerate entities // fill in general information structures, reorganize data and create pointers to // the entity data values. // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetFileInfo // // Retrieve general information about the data file // // Parameters: // // uint32 hFile handle to NEV data file // ns_FILEINFO *pFileInfo pointer to ns_FILEINFO structure that receives data // uint32 dwFileInfoSize number of bytes in ns_FILEINFO // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_FILEERROR file access or read error // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetFileInfo ( hFile: uint32; var pFileInfo: ns_FILEINFO; dwFileInfoSize: uint32 ):ns_Result;cdecl; // Check validity of passed parameters // Fill in ns_FILEINFO structure with currently open file information // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_CloseFile // // Close the opened data files. // // Parameters: // // uint32 hFile handle to NEV data file // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_CloseFile ( hFile: uint32):ns_result;cdecl; // Check validity of passed parameters // Close file, release handles and any other clean up // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetEntityInfo // // Retrieve general Entity information // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID // ns_ENTITYINFO *pEntityInfo pointer to ns_ENTITYINFO structure that receives information // uint32 dwEntityInfoSize number of bytes in ns_ENTITYINFO // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetEntityInfo ( hFile: uint32; dwEntityID: uint32; var pEntityInfo: ns_ENTITYINFO; dwEntityInfoSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Fill in ns_ENTITYINFO // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetEventInfo // // Retrieve information for Event entities. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Event entity ID // ns_EVENTINFO *pEventInfo pointer to ns_EVENTINFO structure to receive information // uint32 dwEventInfoSize number of bytes in ns_EVENTINFO // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetEventInfo ( hFile: uint32; dwEntityID: uint32; var pEventInfo: ns_EVENTINFO; dwEventInfoSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Fill in ns_EVENTINFO // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetEventData // // Retrieve the timestamp and Event entity data items. // // Parameters: // uint32 hFile handle to NEV data file // uint32 dwEntityID Event entity ID // uint32 nIndex Event entity item number // double *pdTimeStamp pointer to double timestamp (in seconds) // void *pData pointer to data buffer to receive data // uint32 dwDataBufferSize number of bytes allocated to the receiving data buffer // uint32 *pdwDataRetSize pointer to the actual number of bytes of data retrieved // // Return Values: // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_BADINDEX invalid entity index specified // ns_FILEERROR file access or read error // ns_LIBERROR library error, null pointer // // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetEventData ( hFile: uint32; dwEntityID: uint32; nIndex: uint32; var pdTimeStamp: double; pData: pointer; dwDataBufferSize: uint32; var pdwDataRetSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Fill in Event timestamp, data values and return size, if pointers are not NULL // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetAnalogInfo // // Retrieve information for Analog entities // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Analog entity ID // ns_ANALOGINFO *pAnalogInfo pointer to ns_ANALOGINFO structure to receive data // uint32 dwAnalogInfoSize number of bytes in ns_ANALOGINFO // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetAnalogInfo ( hFile: uint32; dwEntityID: uint32; var pAnalogInfo: ns_ANALOGINFO; dwAnalogInfoSize: uint32 ):ns_result;cdecl; { // Check validity of passed parameters #pragma message("ns_GetAnalogInfo - verify validity of passed parameters" ) // Fill in ns_ANALOGINFO structure. #pragma message("ns_GetAnalogInfo - fill in ns_ANALOGINFO" ) result:= ns_OK;; } /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetAnalogData // // Retrieve analog data in the buffer at pData. If possible, dwIndexCount, number of analog data // values are returned in the buffer. If there are time gaps in the sequential values, the // number of continuously sampled data items, before the first gap, is returned in pdwContCount. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Analog entity ID // uint32 dwStartIndex starting index to search for timestamp // uint32 dwIndexCount number of timestamps to retrieve // uint32 *pdwContCount pointer to count of the first non-sequential analog item // double *pData pointer to data buffer to receive data values // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetAnalogData ( hFile: uint32; dwEntityID: uint32; dwStartIndex: uint32; dwIndexCount: uint32; var pdwContCount: uint32; var pData: double):ns_result;cdecl; // Check validity of passed parameters // Fill in data buffer pData, and the number of continuous analog data values, // if pointers are not NULL. // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetSegmentInfo // // Retrieve information for Segment entities. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // ns_SEGMENTINFO *pSegmentInfo pointer to ns_SEGMENTINFO structure to receive information // uint32 dwSegmentInfoSize size in bytes of ns_SEGMENTINFO structure // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetSegmentInfo ( hFile: uint32; dwEntityID: uint32; var pSegmentInfo: ns_SEGMENTINFO; dwSegmentInfoSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Fill in ns_SEGMENTINFO structure // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetSegmentSourceInfo // // Retrieve information on the source, dwSourceID, generating segment entity dwEntityID. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // uint32 dwSourceID entity ID of source /// ns_SEGSOURCEINFO *pSourceInfo pointer to ns_SEGSOURCEINFO structure to receive information // uint32 dwSourceInfoSize size in bytes of ns_SEGSOURCEINFO structure // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetSegmentSourceInfo ( hFile: uint32; dwEntityID: uint32; dwSourceID: uint32; var pSourceInfo: ns_SEGSOURCEINFO; dwSourceInfoSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Fill in ns_SEGSOURCEINFO // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetSegmentData // // Retrieve segment data waveform and its timestamp. // The number of data points read is returned at pdwSampleCount. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Segment entity ID // int32 nIndex Segment item index to retrieve // double *pdTimeStamp pointer to timestamp to retrieve // double *pData pointer to data buffer to receive data // uint32 dwDataBufferSize number of bytes available in the data buffer // uint32 *pdwSampleCount pointer to number of data items retrieved // uint32 *pdwUnitID pointer to unit ID of Segment data // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY invalid or inappropriate entity identifier specified // ns_FILEERROR file access or read error // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetSegmentData ( hFile: uint32; dwEntityID: uint32; nIndex: int32; var pdTimeStamp: double; var pData: double; dwDataBufferSize: uint32; var pdwSampleCount: uint32; var pdwUnitID: uint32 ):ns_result;cdecl; // Check validity of passed parameters // Fill in timestamp, data values, number of data values retireved and unitID of requested // segment. If any pointers are NULL, do not fill in information for that field. // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetNeuralInfo // // Retrieve information on Neural Events. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Neural entity ID // ns_NEURALINFO *pNeuralInfo pointer to ns_NEURALINFO structure to receive information // uint32 dwNeuralInfoSize number of bytes in ns_NEURALINFO // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalid entity identifier // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetNeuralInfo( hFile: uint32; dwEntityID: uint32; var pNeuralInfo: ns_NEURALINFO; dwNeuralInfoSize: uint32 ):ns_result;cdecl; // Check validity of passed parameters // Fill in ns_NEURALINFO structure // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetNeuralData // // Retrieve requested number of Neural event timestamps (in sec) // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID Neural event entity ID // uint32 dwStartIndex index of first Neural event item time to retrieve // uint32 dwIndexCount number of Neural event items to retrieve // double *pData pointer to buffer to receive times // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_BADENTITY inappropriate or invalie entity identifier // ns_LIBERROR library error, null pointer /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetNeuralData( hFile: uint32; dwEntityID: uint32; dwStartIndex: uint32; dwIndexCount: uint32; pData: pointer ):ns_result;cdecl; // Check validity of passed parameters // Retrieve requested double timestamps (sec) in pData, if not NULL // result:= ns_OK;; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetIndexByTime // // Given the time (sec), return the closest data item index, The item's location relative to the // requested time is specified by nFlag. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID to search for // uint32 dwSearchTimeStamp timestamp of item to search for // int32 nFlag position of item relative to the requested timestamp // uint32 *pdwIndex pointer to index of item to retrieve // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetIndexByTime( hFile: uint32; dwEntityID: uint32; dTime: double; nFlag: int32; var pdwIndex: uint32 ):ns_result;cdecl; // Check validity of passed parameters // Search for entity item closest to the specified time, dTime // and return its index, pdwIndex, position. // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetTimeByIndex // // Given an index for an entity data item, return the time in seconds. // // Parameters: // // uint32 hFile handle to NEV data file // uint32 dwEntityID entity ID to search for // uint32 dwIndex index of entity item to search for // double *pdTime time of entity to retrieve // // Return Values: // // ns_OK function succeeded // ns_BADFILE invalid file handle // ns_LIBERROR library error, null pointer // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetTimeByIndex( hFile: uint32; dwEntityID: uint32; dwIndex: uint32; var pdTime: double):ns_result;cdecl; // Check validity of passed parameters // Search for time of the entity item specified by index, dwIndex // and return its timestamp in seconds, pdTime // result:= ns_OK; /////////////////////////////////////////////////////////////////////////////////////////////////// // ns_GetLastErrorMsg // // Purpose: // // Retrieve the most recent error text message // // Parameters: // // char *pszMsgBuffer pointer to text buffer to receive error message // uint32 dwMsgBufferSize size in bytes of text buffer // // Return Values: // // ns_OK function succeeded // ns_LIBERROR library error // /////////////////////////////////////////////////////////////////////////////////////////////////// function ns_GetLastErrorMsg(pszMsgBuffer: Pansichar; dwMsgBufferSize: uint32):ns_result;cdecl; // Check validity of passed parameters // Retrieve most recent error text message in pszMsgBuffer and the size in bytes // of the error message in dwMsgBufferSize. //result:= ns_OK;; implementation function ns_GetLibraryInfo( var LibraryInfo: ns_LIBRARYINFO; dwLibraryInfoSize: uint32):ns_result; begin result:=ns_OK; end; function ns_OpenFile(pszFilename: Pansichar; var hFile: uint32):ns_Result; begin end; function ns_GetFileInfo ( hFile: uint32; var pFileInfo: ns_FILEINFO; dwFileInfoSize: uint32 ):ns_Result; begin end; function ns_CloseFile ( hFile: uint32):ns_Result; begin end; function ns_GetEntityInfo ( hFile: uint32; dwEntityID: uint32; var pEntityInfo: ns_ENTITYINFO; dwEntityInfoSize: uint32):ns_Result; begin end; function ns_GetEventInfo ( hFile: uint32; dwEntityID: uint32; var pEventInfo: ns_EVENTINFO; dwEventInfoSize: uint32):ns_Result; begin end; function ns_GetEventData ( hFile: uint32; dwEntityID: uint32; nIndex: uint32; var pdTimeStamp: double; pData: pointer; dwDataBufferSize: uint32; var pdwDataRetSize: uint32):ns_Result; begin end; function ns_GetAnalogInfo ( hFile: uint32; dwEntityID: uint32; var pAnalogInfo: ns_ANALOGINFO; dwAnalogInfoSize: uint32 ):ns_Result; begin end; function ns_GetAnalogData ( hFile: uint32; dwEntityID: uint32; dwStartIndex: uint32; dwIndexCount: uint32; var pdwContCount: uint32; var pData: double):ns_Result; begin end; function ns_GetSegmentInfo ( hFile: uint32; dwEntityID: uint32; var pSegmentInfo: ns_SEGMENTINFO; dwSegmentInfoSize: uint32):ns_Result; begin end; function ns_GetSegmentSourceInfo ( hFile: uint32; dwEntityID: uint32; dwSourceID: uint32; var pSourceInfo: ns_SEGSOURCEINFO; dwSourceInfoSize: uint32):ns_Result; begin end; function ns_GetSegmentData ( hFile: uint32; dwEntityID: uint32; nIndex: int32; var pdTimeStamp: double; var pData: double; dwDataBufferSize: uint32; var pdwSampleCount: uint32; var pdwUnitID: uint32 ):ns_Result; begin end; function ns_GetNeuralInfo( hFile: uint32; dwEntityID: uint32; var pNeuralInfo: ns_NEURALINFO; dwNeuralInfoSize: uint32 ):ns_Result; begin end; function ns_GetNeuralData( hFile: uint32; dwEntityID: uint32; dwStartIndex: uint32; dwIndexCount: uint32; pData: pointer ):ns_Result; begin end; function ns_GetIndexByTime( hFile: uint32; dwEntityID: uint32; dTime: double; nFlag: int32; var pdwIndex: uint32 ):ns_Result; begin end; function ns_GetTimeByIndex( hFile: uint32; dwEntityID: uint32; dwIndex: uint32; var pdTime: double):ns_Result; begin end; function ns_GetLastErrorMsg(pszMsgBuffer: Pansichar; dwMsgBufferSize: uint32):ns_Result; begin end; end.
unit uFrmFillFreightFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Frm_BillEditBase, cxEdit, DB, DBClient, ActnList, dxBar, cxClasses, ImgList, cxGridLevel, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxDBEdit, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, ExtCtrls, StdCtrls, Menus, ADODB, cxButtons, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, StrUtils, cxCheckBox, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxLookAndFeelPainters, cxButtonEdit, dxGDIPlusClasses, jpeg, cxLabel, dxSkinsCore, dxSkinOffice2007Black, Grids, DBGrids, cxPC, cxSpinEdit; type TFrmFillFreight = class(TFM_BillEditBase) dbgListFSEQ: TcxGridDBColumn; dbgListcfMaterialNumber: TcxGridDBColumn; dbgListFQTY: TcxGridDBColumn; dbgListFPRICE: TcxGridDBColumn; dbgListcfSIZEName: TcxGridDBColumn; dbgListcfColorName: TcxGridDBColumn; dbgListFWareHouseNumber: TcxGridDBColumn; dbgListFWareHouseName: TcxGridDBColumn; dbgListFWareHouseSeNumber: TcxGridDBColumn; dbgListFWareHouseSeName: TcxGridDBColumn; cdsMasterFAPPLYSTORAGEORGUNITID: TWideStringField; cdsMasterFSCMSTORAGEORGUNITID: TWideStringField; cdsMasterFREMARK: TWideStringField; cdsMasterFDISTRIBUTIONTYPE: TWideStringField; cdsMasterFCOMANYORGID: TWideStringField; cdsMasterFAUDITTIME: TDateTimeField; cdsMasterFBASESTATUS: TFloatField; cdsMasterFBIZTYPEID: TWideStringField; cdsMasterFSOURCEBILLTYPEID: TWideStringField; cdsMasterFBILLTYPEID: TWideStringField; cdsMasterFYEAR: TFloatField; cdsMasterFPERIOD: TFloatField; cdsMasterFMODIFIERID: TWideStringField; cdsMasterFMODIFICATIONTIME: TDateTimeField; cdsMasterFNUMBER: TWideStringField; cdsMasterFBIZDATE: TDateTimeField; cdsMasterFHANDLERID: TWideStringField; cdsMasterFDESCRIPTION: TWideStringField; cdsMasterFHASEFFECTED: TFloatField; cdsMasterFAUDITORID: TWideStringField; cdsMasterFSOURCEBILLID: TWideStringField; cdsMasterFSOURCEFUNCTION: TWideStringField; cdsMasterFCREATORID: TWideStringField; cdsMasterFCREATETIME: TDateTimeField; cdsMasterFLASTUPDATEUSERID: TWideStringField; cdsMasterFLASTUPDATETIME: TDateTimeField; cdsMasterFCONTROLUNITID: TWideStringField; cdsMasterFID: TWideStringField; cdsMasterFPURCHASEORGUNIT: TWideStringField; cdsMasterCFSTORAGEORGID: TWideStringField; cdsDetailFPARENTID: TWideStringField; cdsDetailFPRICE: TFloatField; cdsDetailFAMOUNT: TFloatField; cdsDetailFLOACLAMOUNT: TFloatField; cdsDetailFCOLORID: TWideStringField; cdsDetailFSIZESID: TWideStringField; cdsDetailFCUPID: TWideStringField; cdsDetailFSIZEGROUPID: TWideStringField; cdsDetailFPACKID: TWideStringField; cdsDetailFPACKNUM: TFloatField; cdsDetailFWILLWAREHOUSEID: TWideStringField; cdsDetailFTIPWAREHOUSEID: TWideStringField; cdsDetailFQTY: TFloatField; cdsDetailFTAXPRICE: TFloatField; cdsDetailFACTUALPRICE: TFloatField; cdsDetailFMATERIALID: TWideStringField; cdsDetailFASSISTPROPERTYID: TWideStringField; cdsDetailFUNITID: TWideStringField; cdsDetailFSOURCEBILLID: TWideStringField; cdsDetailFSOURCEBILLNUMBER: TWideStringField; cdsDetailFSOURCEBILLENTRYID: TWideStringField; cdsDetailFSOURCEBILLENTRYSEQ: TFloatField; cdsDetailFASSCOEFFICIENT: TFloatField; cdsDetailFBASESTATUS: TFloatField; cdsDetailFASSOCIATEQTY: TFloatField; cdsDetailFSOURCEBILLTYPEID: TWideStringField; cdsDetailFBASEUNITID: TWideStringField; cdsDetailFASSISTUNITID: TWideStringField; cdsDetailFREMARK: TWideStringField; cdsDetailFREASONCODEID: TWideStringField; cdsDetailFSEQ: TFloatField; cdsDetailFID: TWideStringField; cdsDetailCFISCLOSE: TFloatField; cdsDetailCFTIPLOCATIONID: TWideStringField; cdsDetailCFWILLLOCATIONID: TWideStringField; cdsDetailcfMaterialNumber: TStringField; cdsDetailcfMaterialName: TStringField; cdsDetailcfColorName: TStringField; cdsDetailcfCupName: TStringField; cdsDetailcfSIZEName: TStringField; cdsDetailFWareHouseNumber: TStringField; cdsDetailFWareHouseName: TStringField; cdsDetailFWareHouseSeNumber: TStringField; cdsDetailFWareHouseSeName: TStringField; cdsDetailAmountFMATERIALID: TWideStringField; cdsDetailAmountfAmount_1: TFloatField; cdsDetailAmountfAmount_2: TFloatField; cdsDetailAmountfAmount_3: TFloatField; cdsDetailAmountfAmount_4: TFloatField; cdsDetailAmountfAmount_5: TFloatField; cdsDetailAmountfAmount_6: TFloatField; cdsDetailAmountfAmount_7: TFloatField; cdsDetailAmountfAmount_8: TFloatField; cdsDetailAmountfAmount_9: TFloatField; cdsDetailAmountfAmount_10: TFloatField; cdsDetailAmountfAmount_11: TFloatField; cdsDetailAmountfAmount_12: TFloatField; cdsDetailAmountfAmount_13: TFloatField; cdsDetailAmountfAmount_14: TFloatField; cdsDetailAmountfAmount_15: TFloatField; cdsDetailAmountfAmount_16: TFloatField; cdsDetailAmountfAmount_17: TFloatField; cdsDetailAmountfAmount_18: TFloatField; cdsDetailAmountfAmount_19: TFloatField; cdsDetailAmountfAmount_20: TFloatField; cdsDetailAmountfAmount_21: TFloatField; cdsDetailAmountfAmount_22: TFloatField; cdsDetailAmountfAmount_23: TFloatField; cdsDetailAmountfAmount_24: TFloatField; cdsDetailAmountfAmount_25: TFloatField; cdsDetailAmountfAmount_26: TFloatField; cdsDetailAmountfAmount_27: TFloatField; cdsDetailAmountfAmount_28: TFloatField; cdsDetailAmountfAmount_29: TFloatField; cdsDetailAmountfAmount_30: TFloatField; cdsDetailAmountCFCOLORID: TWideStringField; cdsDetailAmountCFCUPID: TWideStringField; cdsDetailAmountcfMaterialName: TStringField; cdsDetailAmountCFColorName: TStringField; cdsDetailAmountCFCupName: TStringField; cdsDetailAmountcfMaterialNumber: TStringField; cdsDetailAmountFWAREHOUSENumber: TStringField; cdsDetailAmountFWAREHOUSEID: TStringField; cdsDetailAmountFWAREHOUSEName: TStringField; dbgList2cfMaterialNumber: TcxGridDBColumn; dbgList2cfMaterialName: TcxGridDBColumn; dbgList2CFColorName: TcxGridDBColumn; dbgList2CFCupName: TcxGridDBColumn; dbgList2FWAREHOUSENumber: TcxGridDBColumn; dbgList2FWAREHOUSEName: TcxGridDBColumn; dbgList2fAmount_1: TcxGridDBColumn; dbgList2fAmount_2: TcxGridDBColumn; dbgList2fAmount_3: TcxGridDBColumn; dbgList2fAmount_4: TcxGridDBColumn; dbgList2fAmount_5: TcxGridDBColumn; dbgList2fAmount_6: TcxGridDBColumn; dbgList2fAmount_7: TcxGridDBColumn; dbgList2fAmount_8: TcxGridDBColumn; dbgList2fAmount_9: TcxGridDBColumn; dbgList2fAmount_10: TcxGridDBColumn; dbgList2fAmount_11: TcxGridDBColumn; dbgList2fAmount_12: TcxGridDBColumn; dbgList2fAmount_13: TcxGridDBColumn; dbgList2fAmount_14: TcxGridDBColumn; dbgList2fAmount_15: TcxGridDBColumn; dbgList2fAmount_16: TcxGridDBColumn; dbgList2fAmount_17: TcxGridDBColumn; dbgList2fAmount_18: TcxGridDBColumn; dbgList2fAmount_19: TcxGridDBColumn; dbgList2fAmount_20: TcxGridDBColumn; dbgList2fAmount_21: TcxGridDBColumn; dbgList2fAmount_22: TcxGridDBColumn; dbgList2fAmount_23: TcxGridDBColumn; dbgList2fAmount_24: TcxGridDBColumn; dbgList2fAmount_25: TcxGridDBColumn; dbgList2fAmount_26: TcxGridDBColumn; dbgList2fAmount_27: TcxGridDBColumn; dbgList2fAmount_28: TcxGridDBColumn; dbgList2fAmount_29: TcxGridDBColumn; dbgList2fAmount_30: TcxGridDBColumn; cdsMasterFCreatorName: TStringField; cdsMasterFAuditorName: TStringField; cdsDetailAmountCFPACKID: TStringField; cdsDetailAmountCFPackName: TStringField; cdsDetailAmountCFPackNum: TIntegerField; dbgList2CFPackName: TcxGridDBColumn; dbgList2CFPackNum: TcxGridDBColumn; cdsDetailAmountCFSizeGroupID: TStringField; Label7: TLabel; cxedtApplyOrg: TcxTextEdit; cxSupplyOrg: TcxDBLookupComboBox; cdsDetailAmountfPrice: TFloatField; cdsDetailAmountfAmount: TFloatField; cdsDetailAmountfTotalQty: TIntegerField; dbgList2fPrice: TcxGridDBColumn; dbgList2fAmount: TcxGridDBColumn; dbgList2fTotalQty: TcxGridDBColumn; cdsSupplyOrg: TClientDataSet; dsSupplyOrg: TDataSource; cxbtnImpPOS: TdxBarButton; cdsDetailAmountFSourceBillID: TStringField; cdsDetailAmountFSourceBillNumber: TStringField; cdsDetailAmountCFOLDPACKID: TStringField; cdsDetailCFAssistNum: TWideStringField; cdsDetailAmountFTIPWAREHOUSEID: TStringField; cdsDetailAmountFTIPWAREHOUSENumber: TStringField; cdsDetailAmountFTIPWAREHOUSEName: TStringField; dbgList2FTIPWAREHOUSENumber: TcxGridDBColumn; dbgList2FTIPWAREHOUSEName: TcxGridDBColumn; actBatchTipWareId: TAction; actImportBarCode: TAction; dxBarButton27: TdxBarButton; dxBarToExcelBH: TdxBarButton; dxBarBHIMPORT: TdxBarButton; dxBarButton28: TdxBarButton; cdsMasterCFORDERTYPEID: TWideStringField; cxbtnedtordertype: TcxDBLookupComboBox; cxLabel3: TcxLabel; cdsOrderType: TClientDataSet; dsOrderType: TDataSource; dxBarButton31qq: TdxBarButton; Label10: TLabel; cdsMasterCFINPUTWAY: TWideStringField; bt_CtrlQ: TdxBarButton; bt_Ctrl_B: TdxBarButton; bt_Ctrl_J: TdxBarButton; cdsDetailAmountCFColorCode: TStringField; dbgList2cfColorNumber: TcxGridDBColumn; cdsMastercfapplywarehouseid: TWideStringField; procedure cdsDetailNewRecord(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure cdsDetailAmountNewRecord(DataSet: TDataSet); procedure dbgList2cfMaterialNumberPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); procedure dbgList2CFColorNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure dbgList2CFCupNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cdsDetailAmountFMATERIALIDChange(Sender: TField); procedure barbtnNewClick(Sender: TObject); procedure actSaveBillExecute(Sender: TObject); procedure cdsDetailFMATERIALIDChange(Sender: TField); procedure dbgList2Editing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); procedure dbgList2Column1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cdsDetailAmountCFPackNumChange(Sender: TField); procedure cdsDetailAmountCalcFields(DataSet: TDataSet); procedure cxbtnImpPOSClick(Sender: TObject); procedure cdsDetailAmountCFPACKIDChange(Sender: TField); procedure DelAllListClick(Sender: TObject); procedure dbgList2FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure cdsMasterBeforePost(DataSet: TDataSet); procedure actDeleteExecute(Sender: TObject); procedure actAuditExecute(Sender: TObject); procedure actUnAuditExecute(Sender: TObject); procedure actReportViewExecute(Sender: TObject); procedure actReportDesignExecute(Sender: TObject); procedure cdsDetailFQTYChange(Sender: TField); procedure cdsDetailFPRICEChange(Sender: TField); procedure dbgList2FTIPWAREHOUSENumberPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); procedure actBatchTipWareIdExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actImportBarCodeExecute(Sender: TObject); procedure cdsDetailAmountAfterPost(DataSet: TDataSet); procedure actSetBillStatusExecute(Sender: TObject); procedure cdsMasterFSCMSTORAGEORGUNITIDChange(Sender: TField); procedure dxBarButton31qqClick(Sender: TObject); procedure cxdblookupInputwayEditing(Sender: TObject; var CanEdit: Boolean); procedure pmDetailPopup(Sender: TObject); procedure bbtCheckClick(Sender: TObject); procedure bt_CtrlQClick(Sender: TObject); procedure bt_Ctrl_BClick(Sender: TObject); procedure bt_Ctrl_JClick(Sender: TObject); procedure actF11Execute(Sender: TObject); procedure dxBarCodeSMClick(Sender: TObject); procedure cxdblookupInputwayPropertiesCloseUp(Sender: TObject); procedure actImportExcelExecute(Sender: TObject); procedure cdsMasterNewRecord(DataSet: TDataSet); procedure actDetailAddExecute(Sender: TObject); private IsFromPos : boolean; strWareHouseID,strOldMatID : string; fdpprice : double; { Private declarations } public { Public declarations } //打开单据编辑界面(主键字段, 字段值) procedure Open_Bill(KeyFields: String; KeyValues: String); override; //保存单据 function ST_Save : Boolean; override; function FindTIPWAREHOUS(StorageOrgID: string): string; //上级仓库(过滤掉非店铺仓库) end; var FrmFillFreight: TFrmFillFreight; function EditFillFreight_Frm(KeyValues : string):Boolean; //打开补货申请单开单界面 implementation uses FrmCliDM,Pub_Fun,frmImpDataFromPos,uSysDataSelect,uFormTxtImport, FrmCliMain; {$R *.dfm} function EditFillFreight_Frm(KeyValues : string):Boolean; //打开补货申请单开单界面 begin Result := True; if FrmFillFreight <> nil then begin Gio.AddShow('补货申请单已经存在 - 开始'); if FrmFillFreight.Showing then else FrmFillFreight.Show; FrmFillFreight.SetFocus; Exit; end else begin Gio.AddShow('补货申请单开始创建'); try Application.CreateForm(TFrmFillFreight, FrmFillFreight); FrmFillFreight.Open_Bill('FID',KeyValues); FrmFillFreight.Show; if (FrmFillFreight <> nil) and (FrmFillFreight.Visible) then FrmFillFreight.SetFocus; except Gio.AddShow('补货申请单创建出错,释放窗体'); FrmFillFreight := nil; FrmFillFreight.Free; end; end; end; { TFrmFillFreight } //新增或打开补货申请单 procedure TFrmFillFreight.Open_Bill(KeyFields: String; KeyValues: String); var OpenTables: array[0..1] of string; _cds: array[0..1] of TClientDataSet; ErrMsg,FBIZTYPEID : string; begin OpenTables[0] := 't_sd_subsidyapplybill'; OpenTables[1] := 't_sd_subsidyapplybillEntry'; _cds[0] := cdsMaster; _cds[1] := cdsDetail; try if not CliDM.Get_OpenClients(KeyValues,_cds,OpenTables,ErrMsg) then begin ShowError(Handle, ErrMsg,[]); Abort; end; except on E : Exception do begin ShowError(Handle, Self.Bill_Sign+'打开编辑数据报错:'+E.Message,[]); Abort; end; end; //新单初始化赋值 if KeyValues='' then begin with cdsMaster do begin Append; FieldByName('FID').AsString := CliDM.GetEASSID(UserInfo.t_sd_subsidyapplybill); FieldByName('FCREATETIME').AsDateTime := CliDM.Get_ServerTime; FieldByName('FNUMBER').AsString := CliDM.GetBillNo('B',UserInfo.WareHouser_Sign,UserInfo.MachineCode); FieldByName('FBIZDATE').AsDateTime := CliDM.Get_ServerTime; FieldByName('FCREATORID').AsString := UserInfo.LoginUser_FID; FieldByName('CFSTORAGEORGID').AsString := UserInfo.FStoreOrgUnit; //库存组织 FieldByName('FAPPLYSTORAGEORGUNITID').AsString := UserInfo.FStoreOrgUnit; //申请组织 //FieldByName('FSCMSTORAGEORGUNITID').AsString := UserInfo.FStoreOrgUnit; //供应组织 wushaoshu: 供应组织可以有多个,比如上级是一区,一区相同级别的物流组,一区没有仓库,需要从物流组补货 FieldByName('FSCMSTORAGEORGUNITID').AsString := cdsSupplyOrg.fieldbyName('FID').AsString; // FieldByName('FBIZTYPEID').AsString := 'd8e80652-011b-1000-e000-04c5c0a812202407435C'; //单据类型,现在默认为(跨仓库调拨成本价) FieldByName('FBASESTATUS').AsInteger := 1; //保存状态 FieldByName('FLASTUPDATEUSERID').AsString := UserInfo.LoginUser_FID; FieldByName('FLASTUPDATETIME').AsDateTime := CliDM.Get_ServerTime; FieldByName('FMODIFIERID').AsString := UserInfo.LoginUser_FID; FieldByName('FMODIFICATIONTIME').AsDateTime := CliDM.Get_ServerTime; FieldByName('FCONTROLUNITID').AsString := UserInfo.FCONTROLUNITID; //控制单元,从服务器获取 FieldByName('CFINPUTWAY').AsString := 'NOTPACK'; end; end; inherited; end; function TFrmFillFreight.ST_Save: Boolean; var ErrMsg : string; _cds: array[0..1] of TClientDataSet; AmountSum : Integer; begin Result := True; if cdsDetailAmount.State in DB.dsEditModes then cdsDetailAmount.Post; AmountSum := 0; try cdsDetailAmount.DisableControls; cdsDetailAmount.First; while not cdsDetailAmount.Eof do begin AmountSum := AmountSum + cdsDetailAmount.fieldByName('fTotalQty').AsInteger; cdsDetailAmount.Next(); end; if AmountSum =0 then begin ShowError(Handle, '单据分录数量为0,不允许保存!',[]); abort; end; finally cdsDetailAmount.EnableControls; end; //横排转竖排 try AmountToDetail_DataSet(CliDM.conClient,cdsDetailAmount,cdsDetail); except on e : Exception do begin ShowError(Handle, '【'+BillNumber+'】保存时横排转竖排出错:'+e.Message,[]); Result := False; abort; end; end; if cdsMaster.State in db.dsEditModes then cdsMaster.Post; if cdsDetail.State in db.dsEditModes then cdsDetail.Post; //定义提交的数据集数据 _cds[0] := cdsMaster; _cds[1] := cdsDetail; //提交数据 try if CliDM.Apply_Delta_Ex(_cds,['t_sd_subsidyapplybill','t_sd_subsidyapplybillentry'],ErrMsg) then begin Gio.AddShow(Self.Caption+'【'+BillNumber+'】提交成功!'); end else begin ShowMsg(Handle, Self.Caption+'提交失败'+ErrMsg,[]); Gio.AddShow(ErrMsg); Result := False; end; except on E: Exception do begin ShowMsg(Handle, Self.Caption+'提交失败:'+e.Message,[]); Result := False; Abort; end; end; CliDM.UpdateAssistProperty('t_sd_subsidyapplybillentry','FparentID',cdsDetail.fieldbyname('fparentID').AsString); //Open_Bill('FID',BillIDValue); end; procedure TFrmFillFreight.cdsDetailNewRecord(DataSet: TDataSet); begin inherited; with DataSet do begin DataSet.FieldByName('FID').AsString := CliDM.GetEASSID(UserInfo.t_sd_subsidyapplybillentry); DataSet.FieldByName('FParentID').AsString := BillIDValue; DataSet.FieldByName('FWILLWAREHOUSEID').AsString := UserInfo.Warehouse_FID; //入库仓库 //DataSet.FieldByName('FTIPWAREHOUSEID').AsString := UserInfo.Warehouse_FID; //出库仓库 end; end; procedure TFrmFillFreight.FormCreate(Sender: TObject); var i:integer; StorageFID,orderTypesql,strError : string; begin inherited; Self.ReportDir:='补货申请单'; Self.Bill_Sign := 't_sd_subsidyapplybill'; Self.BillEntryTable := 't_sd_subsidyapplybillentry'; cxedtApplyOrg.Text := UserInfo.StorageOrgName; try CliDM.GetStorageOrgOnSaleOrg(UserInfo.FsaleOrgID,cdsSupplyOrg); //获取相同销售组织下的库存组织 except on E : Exception do begin ShowMsg(Handle, '查询销售组织委托的库存组织出错:'+E.Message,[]); Abort; end; end; //过滤没有总仓的库存组织 if not cdsSupplyOrg.Active then Exit; cdsSupplyOrg.First; While not cdsSupplyOrg.Eof do begin StorageFID := cdsSupplyOrg.fieldbyName('FID').AsString; if Clidm.Client_QuerySQL('SELECT * FROM T_DB_WAREHOUSE(nolock) WHERE ISNULL(CFOFFICESTOCK,0)=0 AND FSTORAGEORGID='+QuotedStr(StorageFID)).IsEmpty then //没有总仓的库存组织 begin cdsSupplyOrg.Delete; cdsSupplyOrg.First; end; cdsSupplyOrg.Next; end; orderTypesql := 'select FID,fnumber,fname_l2 from CT_BAS_OrderType'; Clidm.Get_OpenSQL(cdsOrderType,orderTypesql,strError);//获取订单类型owen setkeyFieldList('cfMaterialNumber;CFColorCode;CFPackName;CFCupName'); end; procedure TFrmFillFreight.cdsDetailAmountNewRecord(DataSet: TDataSet); begin inherited; DataSet.FieldByName('FWILLWAREHOUSEID').AsString := UserInfo.Warehouse_FID; //入库仓库 //DataSet.FieldByName('FTIPWAREHOUSEID').AsString := strWareHouseID; //出库仓库 end; procedure TFrmFillFreight.dbgList2cfMaterialNumberPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; FindMaterial; //弹选商品 end; procedure TFrmFillFreight.dbgList2CFColorNamePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; FindColor; //弹选颜色 end; procedure TFrmFillFreight.dbgList2CFCupNamePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; FindCup; //弹选内长 end; procedure TFrmFillFreight.cdsDetailAmountFMATERIALIDChange(Sender: TField); begin inherited; //更新尺码组和基本单位 with CliDM.Client_QuerySQL('SELECT CFSIZEGROUPID,FBASEUNIT FROM T_BD_Material(nolock) WHERE FID='+QuotedStr(Sender.AsString)) do begin cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString := FieldByName('CFSIZEGROUPID').AsString; end; if Trim(strOldMatID)<>Trim(Sender.AsString) then fdpprice := CliDM.GetStylePrice_OnLine(Sender.AsString,UserInfo.FsaleOrgID,CliDM.cdsTemp,True); cdsDetailAmount.FieldByName('fprice').AsFloat := fdpprice; strOldMatID := Trim(Sender.AsString); cdsDetailAmount.FieldByName('CFCOLORID').AsString := ''; cdsDetailAmount.FieldByName('CFCUPID').AsString := ''; end; procedure TFrmFillFreight.barbtnNewClick(Sender: TObject); begin // CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_add'); //新增权限 //新增权限 if UserInfo.Is_SysOnline then if not ( FMCliMain.cdsUserRole.Locate('FOBJECTTYPE;FNUMBER', VarArrayOf([UserInfo.t_sd_subsidyapplybill, 'subsidyApplyBill_add']), []) or FMCliMain.cdsUserRole.Locate('FOBJECTTYPE;FNUMBER', VarArrayOf([UserInfo.t_sd_subsidyapplybill, 'SubsidyApplyBill_Addnew']), []) ) then begin ShowMsg(Handle, '没有补货申请单的新增权限!',[]); Abort; end; BillInfo.IsAduit := False; inherited; //Open_Bill('FID',''); //新增补货申请单 cdsDetailAmount.Close; cdsDetailAmount.CreateDataSet; cdsDetailAmount.EmptyDataSet; end; procedure TFrmFillFreight.actSaveBillExecute(Sender: TObject); begin if cdsDetailAmount.IsEmpty then begin ShowMsg(Handle, '表体记录为空不允许保存',[]); exit; end; inherited; end; procedure TFrmFillFreight.cdsDetailFMATERIALIDChange(Sender: TField); var CFSIZEGROUPID,FBASEUNITID : String; begin inherited; //更新尺码组和基本单位 owen 2011-7-19 with CliDM.Client_QuerySQL('SELECT CFSIZEGROUPID,FBASEUNIT FROM T_BD_Material(nolock) WHERE FID='+QuotedStr(Sender.AsString)) do begin CFSIZEGROUPID := FieldByName('CFSIZEGROUPID').AsString; FBASEUNITID := FieldByName('FBASEUNIT').AsString; end; with Sender.DataSet do //更新尺码组、单位 begin FieldByName('FSIZEGROUPID').AsString := CFSIZEGROUPID; FieldByName('FUNITID').AsString := FBASEUNITID; FieldByName('FBASEUNITID').AsString := FBASEUNITID; end; end; procedure TFrmFillFreight.dbgList2Editing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); var Focused_Field : string; begin inherited; Focused_Field := TcxGridDBTableView(Sender).Columns[AItem.Index].DataBinding.FieldName; if trim(cdsMaster.FieldByName('CFINPUTWAY').AsString) ='NOTPACK' then begin if uppercase(Focused_Field)='CFPACKNUM' then begin AAllow := false; end; if uppercase(Focused_Field)='CFPACKNAME' then begin AAllow := false; end; end else begin if SameText(leftstr(Focused_Field,8), 'fAmount_') then AAllow := false; end; end; procedure TFrmFillFreight.dbgList2Column1PropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin inherited; FindPack; end; procedure TFrmFillFreight.cdsDetailAmountCFPackNumChange(Sender: TField); begin inherited; PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString); end; procedure TFrmFillFreight.cdsDetailAmountCalcFields(DataSet: TDataSet); begin inherited; DataSet.FieldByName('fTotaLQty').AsInteger := DataSet.FieldByName('fAmount_1').AsInteger + DataSet.FieldByName('fAmount_2').AsInteger + DataSet.FieldByName('fAmount_3').AsInteger + DataSet.FieldByName('fAmount_4').AsInteger + DataSet.FieldByName('fAmount_5').AsInteger + DataSet.FieldByName('fAmount_6').AsInteger + DataSet.FieldByName('fAmount_7').AsInteger + DataSet.FieldByName('fAmount_8').AsInteger + DataSet.FieldByName('fAmount_9').AsInteger + DataSet.FieldByName('fAmount_10').AsInteger+ DataSet.FieldByName('fAmount_11').AsInteger+ DataSet.FieldByName('fAmount_12').AsInteger+ DataSet.FieldByName('fAmount_13').AsInteger+ DataSet.FieldByName('fAmount_14').AsInteger+ DataSet.FieldByName('fAmount_15').AsInteger+ DataSet.FieldByName('fAmount_16').AsInteger+ DataSet.FieldByName('fAmount_17').AsInteger+ DataSet.FieldByName('fAmount_18').AsInteger+ DataSet.FieldByName('fAmount_19').AsInteger+ DataSet.FieldByName('fAmount_20').AsInteger+ DataSet.FieldByName('fAmount_21').AsInteger+ DataSet.FieldByName('fAmount_22').AsInteger+ DataSet.FieldByName('fAmount_23').AsInteger+ DataSet.FieldByName('fAmount_24').AsInteger+ DataSet.FieldByName('fAmount_25').AsInteger+ DataSet.FieldByName('fAmount_26').AsInteger+ DataSet.FieldByName('fAmount_27').AsInteger+ DataSet.FieldByName('fAmount_28').AsInteger+ DataSet.FieldByName('fAmount_29').AsInteger+ DataSet.FieldByName('fAmount_30').AsInteger; DataSet.FieldByName('fAmount').AsInteger := DataSet.FieldByName('fPrice').AsInteger* DataSet.FieldByName('fTotaLQty').AsInteger; end; procedure TFrmFillFreight.cxbtnImpPOSClick(Sender: TObject); var strUnitID,strSizeGroupID : string; begin //CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_add'); //新增权限 if BillInfo.IsAduit then begin ShowMsg(Handle, '当前单据已经审核!',[]); Abort; end; inherited; with TImpDataFromPosForm.Create(self) do begin BillTypeName := '补货申请单'; Showmodal; if modalresult=mrok then begin cdsImpFromPOS.Filtered := false; cdsImpFromPOS.Filter := 'sel=1'; cdsImpFromPOS.Filtered := true; cdsImpFromPOS.first; while not cdsImpFromPOS.Eof do begin cdsDetail.Append; cdsDetail.FieldByName('FmaterialID').AsString := cdsImpFromPOS.fieldbyname('CFMaterialID').AsString; cdsDetail.FieldByName('FColorID').AsString := cdsImpFromPOS.fieldbyname('CFColorID').AsString; cdsDetail.FieldByName('FSizesID').AsString := cdsImpFromPOS.fieldbyname('CFSIzesID').AsString; cdsDetail.FieldByName('FColorID').AsString := cdsImpFromPOS.fieldbyname('CFColorID').AsString; cdsDetail.FieldByName('FCupID').AsString := cdsImpFromPOS.fieldbyname('CFCupID').AsString; cdsDetail.FieldByName('FQty').AsInteger := cdsImpFromPOS.fieldbyname('CFAmount').AsInteger; cdsDetail.FieldByName('FPACKNUM').AsFloat := 0; if Trim(cdsImpFromPOS.fieldbyname('CFMaterialID').AsString)<>Trim(strOldMatID) then fdpprice := CliDM.GetStylePrice_OnLine(cdsImpFromPOS.fieldbyname('CFMaterialID').AsString,UserInfo.FsaleOrgID,CliDM.cdsTemp,True); cdsDetail.FieldByName('FPrice').AsFloat := fdpprice; cdsDetail.FieldByName('FAmount').AsFloat := cdsDetail.FieldByName('FPrice').AsFloat* cdsImpFromPOS.fieldbyname('CFAmount').AsInteger; //cdsDetail.FieldByName('FTIPWAREHOUSEID').AsString := strWareHouseID; //出库仓库 with CliDM.Client_QuerySQL('SELECT CFSIZEGROUPID,FBASEUNIT FROM T_BD_Material(nolock) WHERE FID='+QuotedStr(cdsImpFromPOS.fieldbyname('CFMaterialID').AsString)) do begin strUnitID := FieldByName('FBASEUNIT').AsString; strSizeGroupID := FieldByName('CFSIZEGROUPID').AsString; cdsDetail.FieldByName('FBASEUNITID').AsString := strUnitID; cdsDetail.FieldByName('FUNITID').AsString := strUnitID; cdsDetail.FieldByName('FSIZEGROUPID').AsString := strSizeGroupID; end; cdsDetail.Post; strOldMatID := cdsImpFromPOS.fieldbyname('CFMaterialID').AsString; cdsImpFromPOS.Next; end; OpenDetailAmount(Self.Bill_Sign,cdsMaster.fieldbyname('FID').AsString); cdsDetailAmount.Edit; end; end; end; procedure TFrmFillFreight.cdsDetailAmountCFPACKIDChange(Sender: TField); begin inherited; if cdsDetailAmount.FieldByName('CFPackNum').AsInteger>0 then PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString); end; procedure TFrmFillFreight.DelAllListClick(Sender: TObject); begin inherited; // end; procedure TFrmFillFreight.dbgList2FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin inherited; // end; procedure TFrmFillFreight.cdsMasterBeforePost(DataSet: TDataSet); begin if trim(cxSupplyOrg.Text)='' then begin ShowMsg(Handle, '供应组织不能为空!',[]); cxSupplyOrg.SetFocus; Abort; end; inherited; end; procedure TFrmFillFreight.actDeleteExecute(Sender: TObject); begin //CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,''); //删除权限 //删除权限 if UserInfo.Is_SysOnline then if not ( FMCliMain.cdsUserRole.Locate('FOBJECTTYPE;FNUMBER', VarArrayOf([UserInfo.t_sd_subsidyapplybill, 'SubsidyApplyBill_Remove']), [loCaseInsensitive]) or FMCliMain.cdsUserRole.Locate('FOBJECTTYPE;FNUMBER', VarArrayOf([UserInfo.t_sd_subsidyapplybill, 'subsidyApplyBill_del']), [loCaseInsensitive]) ) then begin ShowMsg(Handle, '没有补货申请单的删除权限!',[]); Abort; end; inherited; end; procedure TFrmFillFreight.actAuditExecute(Sender: TObject); begin CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_audit'); //审核权限 //CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'SubsidyApplyBill_Audit'); //审核权限 inherited; end; procedure TFrmFillFreight.actUnAuditExecute(Sender: TObject); begin CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_unAudit'); //反审核权限 inherited; end; procedure TFrmFillFreight.actReportViewExecute(Sender: TObject); begin CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_printView'); //打印预览权限 inherited; end; procedure TFrmFillFreight.actReportDesignExecute(Sender: TObject); begin CliDM.Chk_UserRight(UserInfo.t_sd_subsidyapplybill,'subsidyApplyBill_printDesign'); //打印设计权限 inherited; end; procedure TFrmFillFreight.cdsDetailFQTYChange(Sender: TField); begin inherited; Sender.DataSet.FieldByName('FAMOUNT').Value := Sender.Value * Sender.DataSet.FieldByName('FPRICE').Value; //金额 Sender.DataSet.FieldByName('FASSOCIATEQTY').Value := Sender.Value; //20110815 未完成数量 如果不更新此字段,补货单生成的调拨单能提交审核 end; procedure TFrmFillFreight.cdsDetailFPRICEChange(Sender: TField); begin inherited; Sender.DataSet.FieldByName('FAMOUNT').Value := Sender.Value * Sender.DataSet.FieldByName('FQTY').Value; end; procedure TFrmFillFreight.dbgList2FTIPWAREHOUSENumberPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var FTIPWAREHOUSEID,FSCMSTORAGEORGUNITID : string; begin inherited; //FTIPWAREHOUSEID := FindTIPWAREHOUS(UserInfo.FStoreOrgUnit); //弹选库存组织下仓库 FSCMSTORAGEORGUNITID := cdsMaster.fieldbyName('FSCMSTORAGEORGUNITID').AsString; FTIPWAREHOUSEID := FindTIPWAREHOUS(FSCMSTORAGEORGUNITID); //弹选库存组织下仓库 if FTIPWAREHOUSEID <> '' then begin if not(cdsDetailAmount.State in DB.dsEditModes) then cdsDetailAmount.Edit; cdsDetailAmount.FieldByName('FTIPWAREHOUSEID').AsString := FTIPWAREHOUSEID; end; end; function TFrmFillFreight.FindTIPWAREHOUS(StorageOrgID: string): string; var sqlstr,ReturnStr: string; fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string; begin Result := ''; if Trim(StorageOrgID)='' then strORgID := UserInfo.FStoreOrgUnit else strORgID := StorageOrgID; sqlstr := 'SELECT FID,FNUMBER,FNAME_L2 FROM T_DB_WAREHOUSE(nolock) ' +' WHERE FWHState=1 and ISNULL(CFOFFICESTOCK,0)=0 AND FSTORAGEORGID='+QuotedStr(strORgID) +' ORDER BY FNUMBER'; fdEnglishList := 'Fnumber,Fname_l2'; fdChineseList := '店铺编号,店铺名称'; fdReturnAimList := 'FID'; ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200); Result := ReturnStr; end; procedure TFrmFillFreight.actBatchTipWareIdExecute(Sender: TObject); var FTIPWAREHOUSEID : string; begin inherited; if BillInfo.IsAduit then begin ShowMsg(Handle, '只有新单才能批量更新出库仓库!',[]); abort; end; if cdsDetailAmount.IsEmpty then Exit; FTIPWAREHOUSEID := FindTIPWAREHOUS(UserInfo.FStoreOrgUnit); if FTIPWAREHOUSEID='' then exit; try cdsDetailAmount.DisableControls; cdsDetailAmount.First; While not cdsDetailAmount.Eof do begin cdsDetailAmount.Edit; cdsDetailAmount.FieldByName('FTIPWAREHOUSEID').AsString := FTIPWAREHOUSEID; cdsDetailAmount.Next; end; finally cdsDetailAmount.EnableControls; end; end; procedure TFrmFillFreight.FormDestroy(Sender: TObject); begin inherited; FrmFillFreight := nil; end; procedure TFrmFillFreight.actImportBarCodeExecute(Sender: TObject); begin if cxdblookupInputway.EditValue='PACK' then begin ShowMsg(Handle, '对不起!此功能只支持散码输入方式!',[]); abort; end; inherited; try //cdsDetailAmount.BeforePost:= nil; //cdsDetailAmount.OnCalcFields:=nil; {if cdsDetailAmount.ChangeCount>0 then begin ShowMsg(Handle, '请先保存单据再导入!',[]); Abort; end; } if not BillInfo.IsNew then begin ShowMsg(Handle, '只有新单状态下才能导入条码文件!',[]); Abort; end; formTXTimport(cdsDetailAmount,''); OpenDetailAmount(Self.Bill_Sign,BillIDValue); //打开横排明细 finally //cdsDetailAmount.BeforePost:= cdsDetailBeforePost; //cdsDetailAmount.OnCalcFields:=cdsDetailCalcFields; //cdsDetailAmount.Last; //while not cdsDetailAmount.Bof do cdsDetailAmount.Prior; end; end; procedure TFrmFillFreight.cdsDetailAmountAfterPost(DataSet: TDataSet); begin inherited; //strWareHouseID := DataSet.fieldByName('FTIPWAREHOUSEID').AsString; end; procedure TFrmFillFreight.actSetBillStatusExecute(Sender: TObject); begin inherited; cxBIZDATE.Enabled := not BillInfo.IsAduit; txDescription.Enabled := not BillInfo.IsAduit; cxSupplyOrg.Enabled := not BillInfo.IsAduit; cxbtnImpPOS.Enabled := not BillInfo.IsAduit; actImportBarCode.Enabled := not BillInfo.IsAduit; if dbgList2.GetColumnByFieldName('cfMaterialNumber') <> nil then dbgList2.GetColumnByFieldName('cfMaterialNumber').Options.Editing := not BillInfo.IsAduit; if dbgList2.GetColumnByFieldName('CFColorName') <> nil then dbgList2.GetColumnByFieldName('CFColorName').Options.Editing := not BillInfo.IsAduit; if dbgList2.GetColumnByFieldName('CFCupName') <> nil then dbgList2.GetColumnByFieldName('CFCupName').Options.Editing := not BillInfo.IsAduit; //img_NewBill.Visible := True; //im_Audit.Visible := False; end; procedure TFrmFillFreight.cdsMasterFSCMSTORAGEORGUNITIDChange( Sender: TField); begin inherited; if (Sender.AsString = UserInfo.FStoreOrgUnit) or (Sender.AsString='') then //如果供应组织和当前店铺库存组织相同,供应组织为跨仓库事物类型 Sender.DataSet.FieldByName('FBIZTYPEID').AsString := 'd8e80652-011b-1000-e000-04c5c0a812202407435C' else //跨组织事物类型 if (Sender.AsString <> UserInfo.FStoreOrgUnit) then Sender.DataSet.FieldByName('FBIZTYPEID').AsString := 'd8e80652-011a-1000-e000-04c5c0a812202407435C'; end; procedure TFrmFillFreight.dxBarButton31qqClick(Sender: TObject); begin inherited; actCodeSM_F12Execute(nil); end; procedure TFrmFillFreight.cxdblookupInputwayEditing(Sender: TObject; var CanEdit: Boolean); begin inherited; if CanEdit then if cdsDetailAmount.FieldByName('FMATERIALID').AsString <>'' then begin ShowMsg(Handle, '已经有分录,不允许再修改录入方式!',[]); Abort; end; end; procedure TFrmFillFreight.pmDetailPopup(Sender: TObject); begin inherited; if trim(cdsMaster.FieldByName('CFINPUTWAY').AsString) ='PACK' then end; procedure TFrmFillFreight.bbtCheckClick(Sender: TObject); begin if trim(cdsMaster.FieldByName('CFINPUTWAY').AsString) ='PACK' then begin ShowMsg(Handle, '选择配码录入方式不允许进行扫描校验!',[]); abort; end; inherited; //// end; procedure TFrmFillFreight.bt_CtrlQClick(Sender: TObject); var fAmount:integer; begin inherited; fAmount:=strtoint(cxBaseQty.Text); if fAmount<0 then cxBaseQty.Text:=inttostr(abs(fAmount)) else cxBaseQty.Text:='-'+cxBaseQty.Text; end; procedure TFrmFillFreight.bt_Ctrl_BClick(Sender: TObject); begin inherited; if pnlCodeSM.Visible then cxCodeText.SetFocus; end; procedure TFrmFillFreight.bt_Ctrl_JClick(Sender: TObject); begin inherited; if pnlCodeSM.Visible then cxBaseQty.SetFocus; end; procedure TFrmFillFreight.actF11Execute(Sender: TObject); begin if cxdblookupInputway.EditValue='PACK' then begin ShowMsg(Handle, '对不起!此功能只支持散码输入方式!',[]); abort; end; inherited; end; procedure TFrmFillFreight.dxBarCodeSMClick(Sender: TObject); begin if cxdblookupInputway.EditValue='PACK' then begin ShowMsg(Handle, '对不起!此功能只支持散码输入方式!',[]); abort; end; inherited; end; procedure TFrmFillFreight.cxdblookupInputwayPropertiesCloseUp( Sender: TObject); begin inherited; if cxdblookupInputway.EditValue='PACK' then begin dbgList2CFPackName.Visible := True; dbgList2CFPackNum.Visible := True; end; if cxdblookupInputway.EditValue='NOTPACK' then begin dbgList2CFPackName.Visible := False; dbgList2CFPackNum.Visible := false; end; end; procedure TFrmFillFreight.actImportExcelExecute(Sender: TObject); begin if cxdblookupInputway.EditValue='PACK' then begin ShowMsg(Handle, '对不起!此功能只支持散码输入方式!',[]); abort; end; inherited; end; procedure TFrmFillFreight.cdsMasterNewRecord(DataSet: TDataSet); begin inherited; DataSet.FieldByName('cfapplywarehouseid').AsString:=UserInfo.Warehouse_FID; end; procedure TFrmFillFreight.actDetailAddExecute(Sender: TObject); begin if cxSupplyOrg.Text = '' then begin ShowMsg(Handle, '请先输入供应组织!',[]); cxSupplyOrg.SetFocus; Abort; end; inherited; end; end.
unit uDigitOpHelper; {$I ..\Include\IntXLib.inc} interface uses uConstants, uDigitHelper, uIntXLibTypes; type /// <summary> /// Contains helping methods for operations over <see cref="TIntX" /> digits as arrays. /// </summary> TDigitOpHelper = class sealed(TObject) public /// <summary> /// Adds two big integers. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function Add(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; overload; static; /// <summary> /// Adds two big integers using pointers. /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function Add(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32; overload; static; /// <summary> /// Subtracts two big integers. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function Sub(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; overload; static; /// <summary> /// Subtracts two big integers using pointers. /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function Sub(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32; overload; static; /// <summary> /// Divides one big integer represented by it's digits by another one big integer. /// Remainder is always filled (but not the result). /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="int2">Second integer.</param> /// <param name="divRes">Div result (can be null - not filled in this case).</param> /// <param name="modRes">Remainder (always filled).</param> /// <returns>Result length (0 if result is null).</returns> class function DivMod(digits1: TIntXLibUInt32Array; length1: UInt32; int2: UInt32; divRes: TIntXLibUInt32Array; out modRes: UInt32): UInt32; overload; static; /// <summary> /// Divides one big integer represented by it's digits by another one big integer. /// Remainder is always filled (but not the result). /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="int2">Second integer.</param> /// <param name="divResPtr">Div result (can be null - not filled in this case).</param> /// <param name="modRes">Remainder (always filled).</param> /// <returns>Result length (0 if result is null).</returns> class function DivMod(digitsPtr1: PCardinal; length1: UInt32; int2: UInt32; divResPtr: PCardinal; out modRes: UInt32): UInt32; overload; static; /// <summary> /// Divides one big integer represented by it's digits by another one big integer. /// Only remainder is filled. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="int2">Second integer.</param> /// <returns>Remainder.</returns> class function Modulus(digits1: TIntXLibUInt32Array; length1: UInt32; int2: UInt32): UInt32; overload; static; /// <summary> /// Divides one big integer represented by it's digits by another one big integer. /// Only remainder is filled. /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="int2">Second integer.</param> /// <returns>Remainder.</returns> class function Modulus(digitsPtr1: PCardinal; length1: UInt32; int2: UInt32) : UInt32; overload; static; /// <summary> /// Compares 2 <see cref="TIntX" /> objects represented by digits only (not taking sign into account). /// Returns "-1" if <paramref name="digits1" /> &lt; <paramref name="digits2" />, "0" if equal and "1" if &gt;. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <returns>Comparison result.</returns> class function Cmp(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32): Integer; overload; static; /// <summary> /// Compares 2 <see cref="TIntX" /> objects represented by pointers only (not taking sign into account). /// Returns "-1" if <paramref name="digitsPtr1" /> &lt; <paramref name="digitsPtr2" />, "0" if equal and "1" if &gt;. /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <returns>Comparison result.</returns> class function Cmp(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32): Integer; overload; static; /// <summary> /// Compares two integers lengths. Returns -2 if further comparing is needed. /// </summary> /// <param name="length1">First big integer length.</param> /// <param name="length2">Second big integer length.</param> /// <returns>Comparison result.</returns> class function CmpLen(length1: UInt32; length2: UInt32): Integer; static; /// <summary> /// Shifts big integer. /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="offset">Big integer digits offset.</param> /// <param name="mlength">Big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <param name="resOffset">Resulting big integer digits offset.</param> /// <param name="rightShift">Shift to the right (always between 1 an 31).</param> class procedure ShiftRight(digits: TIntXLibUInt32Array; offset: UInt32; mlength: UInt32; digitsRes: TIntXLibUInt32Array; resOffset: UInt32; rightShift: Integer); overload; static; /// <summary> /// Shifts big integer. /// </summary> /// <param name="digitsPtr">Big integer digits.</param> /// <param name="mlength">Big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <param name="rightShift">Shift to the right (always between 1 an 31).</param> /// <param name="resHasOffset">True if <paramref name="digitsResPtr" /> has offset.</param> /// <returns>Resulting big integer length.</returns> class function ShiftRight(digitsPtr: PCardinal; mlength: UInt32; digitsResPtr: PCardinal; rightShift: Integer; resHasOffset: Boolean) : UInt32; overload; static; /// <summary> /// Performs bitwise OR for two big integers. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> class procedure BitwiseOr(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array); static; /// <summary> /// Performs bitwise AND for two big integers. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="mlength">Shorter big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function BitwiseAnd(digits1: TIntXLibUInt32Array; digits2: TIntXLibUInt32Array; mlength: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; static; /// <summary> /// Performs bitwise XOR for two big integers. /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function ExclusiveOr(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; static; /// <summary> /// Performs bitwise NOT for big integer. /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength">Big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <returns>Resulting big integer length.</returns> class function OnesComplement(digits: TIntXLibUInt32Array; mlength: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; static; end; implementation class function TDigitOpHelper.Add(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; var digitsPtr1, digitsPtr2, digitsResPtr: PCardinal; begin digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; digitsResPtr := @digitsRes[0]; result := Add(digitsPtr1, length1, digitsPtr2, length2, digitsResPtr); end; class function TDigitOpHelper.Add(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32; var lengthTemp, i: UInt32; c: UInt64; ptrTemp: PCardinal; begin c := 0; if (length1 < length2) then begin // First must be bigger - swap lengthTemp := length1; length1 := length2; length2 := lengthTemp; ptrTemp := digitsPtr1; digitsPtr1 := digitsPtr2; digitsPtr2 := ptrTemp; end; // Perform digits adding i := 0; while i < (length2) do begin c := c + UInt64(digitsPtr1[i]) + digitsPtr2[i]; digitsResPtr[i] := UInt32(c); c := c shr 32; Inc(i); end; // Perform digits + carry moving i := length2; while i < (length1) do begin c := c + UInt64(digitsPtr1[i]); digitsResPtr[i] := UInt32(c); c := c shr 32; Inc(i); end; // Account last carry if (c <> 0) then begin digitsResPtr[length1] := UInt32(c); Inc(length1); end; result := length1; end; class function TDigitOpHelper.Sub(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; var digitsPtr1, digitsPtr2, digitsResPtr: PCardinal; begin digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; digitsResPtr := @digitsRes[0]; result := Sub(digitsPtr1, length1, digitsPtr2, length2, digitsResPtr); end; class function TDigitOpHelper.Sub(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32; var c: UInt64; i: UInt32; begin c := 0; // Perform digits subtraction i := 0; while i < (length2) do begin c := UInt64(digitsPtr1[i]) - digitsPtr2[i] - c; digitsResPtr[i] := UInt32(c); c := c shr 63; Inc(i); end; // Perform digits + carry moving i := length2; while i < (length1) do begin c := digitsPtr1[i] - c; digitsResPtr[i] := UInt32(c); c := c shr 63; Inc(i); end; result := TDigitHelper.GetRealDigitsLength(digitsResPtr, length1); end; class function TDigitOpHelper.DivMod(digits1: TIntXLibUInt32Array; length1: UInt32; int2: UInt32; divRes: TIntXLibUInt32Array; out modRes: UInt32): UInt32; var digits1Ptr, divResPtr: PCardinal; begin digits1Ptr := @digits1[0]; divResPtr := @divRes[0]; result := DivMod(digits1Ptr, length1, int2, divResPtr, modRes); end; class function TDigitOpHelper.DivMod(digitsPtr1: PCardinal; length1: UInt32; int2: UInt32; divResPtr: PCardinal; out modRes: UInt32): UInt32; var c: UInt64; index, res: UInt32; begin c := 0; index := length1 - 1; while index < (length1) do begin c := (c shl TConstants.DigitBitCount) + digitsPtr1[index]; res := UInt32(c div int2); c := c - UInt64(res) * int2; divResPtr[index] := res; Dec(index); end; modRes := UInt32(c); if ((divResPtr[length1 - 1]) = 0) then begin result := length1 - UInt32(1); Exit; end else result := length1 - UInt32(0); end; class function TDigitOpHelper.Modulus(digits1: TIntXLibUInt32Array; length1: UInt32; int2: UInt32): UInt32; var digitsPtr1: PCardinal; begin digitsPtr1 := @digits1[0]; result := Modulus(digitsPtr1, length1, int2); end; class function TDigitOpHelper.Modulus(digitsPtr1: PCardinal; length1: UInt32; int2: UInt32): UInt32; var c: UInt64; res: UInt32; ptr1: PCardinal; begin c := 0; ptr1 := digitsPtr1 + length1 - 1; while (ptr1) >= digitsPtr1 do begin c := (c shl TConstants.DigitBitCount) + ptr1^; res := UInt32(c div int2); c := c - UInt64(res) * int2; Dec(ptr1); end; result := UInt32(c); end; class function TDigitOpHelper.Cmp(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32): Integer; var digitsPtr1, digitsPtr2: PCardinal; begin // Always compare length if one of the integers has zero length if (length1 = 0) or (length2 = 0) then begin result := CmpLen(length1, length2); Exit; end; digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; result := Cmp(digitsPtr1, length1, digitsPtr2, length2); end; class function TDigitOpHelper.Cmp(digitsPtr1: PCardinal; length1: UInt32; digitsPtr2: PCardinal; length2: UInt32): Integer; var res: Integer; index: UInt32; begin // Maybe length comparing will be enough res := CmpLen(length1, length2); if (res <> -2) then begin result := res; Exit; end; index := length1 - 1; while index < (length1) do begin if (digitsPtr1[index] <> digitsPtr2[index]) then begin if digitsPtr1[index] < digitsPtr2[index] then begin result := -1; Exit; end else begin result := 1; Exit; end; end; Dec(index); end; result := 0; Exit; end; class function TDigitOpHelper.CmpLen(length1: UInt32; length2: UInt32): Integer; begin if (length1 < length2) then begin result := -1; Exit; end; if (length1 > length2) then begin result := 1; Exit; end; if length1 = 0 then begin result := 0; Exit; end else begin result := -2; Exit; end; end; class procedure TDigitOpHelper.ShiftRight(digits: TIntXLibUInt32Array; offset: UInt32; mlength: UInt32; digitsRes: TIntXLibUInt32Array; resOffset: UInt32; rightShift: Integer); var digitsPtr, digitsResPtr: PCardinal; begin digitsPtr := @digits[0]; digitsResPtr := @digitsRes[0]; ShiftRight(digitsPtr + offset, mlength, digitsResPtr + resOffset, rightShift, resOffset <> 0); end; class function TDigitOpHelper.ShiftRight(digitsPtr: PCardinal; mlength: UInt32; digitsResPtr: PCardinal; rightShift: Integer; resHasOffset: Boolean): UInt32; var rightShiftRev: Integer; digitsPtrEndPrev, digitsPtrNext: PCardinal; lastValue: UInt32; begin rightShiftRev := TConstants.DigitBitCount - rightShift; // Shift first digit in special way if (resHasOffset) then begin // Negative Array Indexing. (digitsResPtr - 1)^ := digitsPtr[0] shl rightShiftRev; end; if (rightShift = 0) then begin // Handle special situation here - only memcpy is needed (maybe) if (digitsPtr <> digitsResPtr) then begin TDigitHelper.DigitsBlockCopy(digitsPtr, digitsResPtr, mlength); end; end else begin // Shift all digits except last one digitsPtrEndPrev := digitsPtr + mlength - 1; digitsPtrNext := digitsPtr + 1; while digitsPtr < (digitsPtrEndPrev) do begin digitsResPtr^ := digitsPtr^ shr rightShift or digitsPtrNext^ shl rightShiftRev; Inc(digitsPtr); Inc(digitsPtrNext); Inc(digitsResPtr); end; // Shift last digit in special way lastValue := digitsPtr^ shr rightShift; if (lastValue <> 0) then begin digitsResPtr^ := lastValue; end else begin Dec(mlength); end; end; result := mlength; end; class procedure TDigitOpHelper.BitwiseOr(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array); var digitsPtr1, digitsPtr2, digitsResPtr: PCardinal; i: UInt32; begin digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; digitsResPtr := @digitsRes[0]; i := 0; while i < (length2) do begin digitsResPtr[i] := digitsPtr1[i] or digitsPtr2[i]; Inc(i); end; TDigitHelper.DigitsBlockCopy(digitsPtr1 + length2, digitsResPtr + length2, length1 - length2); end; class function TDigitOpHelper.BitwiseAnd(digits1: TIntXLibUInt32Array; digits2: TIntXLibUInt32Array; mlength: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; var digitsPtr1, digitsPtr2, digitsResPtr: PCardinal; i: UInt32; begin digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; digitsResPtr := @digitsRes[0]; i := 0; while i < (mlength) do begin digitsResPtr[i] := digitsPtr1[i] and digitsPtr2[i]; Inc(i); end; result := TDigitHelper.GetRealDigitsLength(digitsResPtr, mlength); end; class function TDigitOpHelper.ExclusiveOr(digits1: TIntXLibUInt32Array; length1: UInt32; digits2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; var digitsPtr1, digitsPtr2, digitsResPtr: PCardinal; i: UInt32; begin digitsPtr1 := @digits1[0]; digitsPtr2 := @digits2[0]; digitsResPtr := @digitsRes[0]; i := 0; while i < (length2) do begin digitsResPtr[i] := digitsPtr1[i] xor digitsPtr2[i]; Inc(i); end; TDigitHelper.DigitsBlockCopy(digitsPtr1 + length2, digitsResPtr + length2, length1 - length2); result := TDigitHelper.GetRealDigitsLength(digitsResPtr, length1); end; class function TDigitOpHelper.OnesComplement(digits: TIntXLibUInt32Array; mlength: UInt32; digitsRes: TIntXLibUInt32Array): UInt32; var digitsPtr, digitsResPtr: PCardinal; i: UInt32; begin digitsPtr := @digits[0]; digitsResPtr := @digitsRes[0]; i := 0; while i < (mlength) do begin digitsResPtr[i] := not digitsPtr[i]; Inc(i); end; result := TDigitHelper.GetRealDigitsLength(digitsResPtr, mlength); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado Ó tabela [EMPRESA] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit EmpresaVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, EmpresaEnderecoVO; type TEmpresaVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FID_SINDICATO_PATRONAL: Integer; FID_FPAS: Integer; FID_CONTADOR: Integer; FRAZAO_SOCIAL: String; FNOME_FANTASIA: String; FCNPJ: String; FINSCRICAO_ESTADUAL: String; FINSCRICAO_ESTADUAL_ST: String; FINSCRICAO_MUNICIPAL: String; FINSCRICAO_JUNTA_COMERCIAL: String; FDATA_INSC_JUNTA_COMERCIAL: TDateTime; FTIPO: String; FDATA_CADASTRO: TDateTime; FDATA_INICIO_ATIVIDADES: TDateTime; FSUFRAMA: String; FEMAIL: String; FIMAGEM_LOGOTIPO: String; FCRT: String; FTIPO_REGIME: String; FALIQUOTA_PIS: Extended; FCONTATO: String; FALIQUOTA_COFINS: Extended; FCODIGO_IBGE_CIDADE: Integer; FCODIGO_IBGE_UF: Integer; FCODIGO_TERCEIROS: Integer; FCODIGO_GPS: Integer; FALIQUOTA_SAT: Extended; FCEI: String; FCODIGO_CNAE_PRINCIPAL: String; FTIPO_CONTROLE_ESTOQUE: String; FEnderecoPrincipal: TEmpresaEnderecoVO; published property Id: Integer read FID write FID; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property IdSindicatoPatronal: Integer read FID_SINDICATO_PATRONAL write FID_SINDICATO_PATRONAL; property IdFpas: Integer read FID_FPAS write FID_FPAS; property IdContador: Integer read FID_CONTADOR write FID_CONTADOR; property RazaoSocial: String read FRAZAO_SOCIAL write FRAZAO_SOCIAL; property NomeFantasia: String read FNOME_FANTASIA write FNOME_FANTASIA; property Cnpj: String read FCNPJ write FCNPJ; property InscricaoEstadual: String read FINSCRICAO_ESTADUAL write FINSCRICAO_ESTADUAL; property InscricaoEstadualSt: String read FINSCRICAO_ESTADUAL_ST write FINSCRICAO_ESTADUAL_ST; property InscricaoMunicipal: String read FINSCRICAO_MUNICIPAL write FINSCRICAO_MUNICIPAL; property InscricaoJuntaComercial: String read FINSCRICAO_JUNTA_COMERCIAL write FINSCRICAO_JUNTA_COMERCIAL; property DataInscJuntaComercial: TDateTime read FDATA_INSC_JUNTA_COMERCIAL write FDATA_INSC_JUNTA_COMERCIAL; property Tipo: String read FTIPO write FTIPO; property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO; property DataInicioAtividades: TDateTime read FDATA_INICIO_ATIVIDADES write FDATA_INICIO_ATIVIDADES; property Suframa: String read FSUFRAMA write FSUFRAMA; property Email: String read FEMAIL write FEMAIL; property ImagemLogotipo: String read FIMAGEM_LOGOTIPO write FIMAGEM_LOGOTIPO; property Crt: String read FCRT write FCRT; property TipoRegime: String read FTIPO_REGIME write FTIPO_REGIME; property AliquotaPis: Extended read FALIQUOTA_PIS write FALIQUOTA_PIS; property Contato: String read FCONTATO write FCONTATO; property AliquotaCofins: Extended read FALIQUOTA_COFINS write FALIQUOTA_COFINS; property CodigoIbgeCidade: Integer read FCODIGO_IBGE_CIDADE write FCODIGO_IBGE_CIDADE; property CodigoIbgeUf: Integer read FCODIGO_IBGE_UF write FCODIGO_IBGE_UF; property CodigoTerceiros: Integer read FCODIGO_TERCEIROS write FCODIGO_TERCEIROS; property CodigoGps: Integer read FCODIGO_GPS write FCODIGO_GPS; property AliquotaSat: Extended read FALIQUOTA_SAT write FALIQUOTA_SAT; property Cei: String read FCEI write FCEI; property CodigoCnaePrincipal: String read FCODIGO_CNAE_PRINCIPAL write FCODIGO_CNAE_PRINCIPAL; property TipoControleEstoque: String read FTIPO_CONTROLE_ESTOQUE write FTIPO_CONTROLE_ESTOQUE; // Pega da lista de enderešos o principal e seta nessa propriedade property EnderecoPrincipal: TEmpresaEnderecoVO read FEnderecoPrincipal write FEnderecoPrincipal; end; TListaEmpresaVO = specialize TFPGObjectList<TEmpresaVO>; implementation initialization Classes.RegisterClass(TEmpresaVO); finalization Classes.UnRegisterClass(TEmpresaVO); end.
unit TpTextArea; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThTextArea, TpControls; type TTpTextArea = class(TThTextArea) private FOnGenerate: TTpEvent; protected procedure SetOnGenerate(const Value: TTpEvent); public procedure Tag(inTag: TThTag); override; published property OnGenerate: TTpEvent read FOnGenerate write SetOnGenerate; end; implementation { TTpTextArea } procedure TTpTextArea.Tag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpTextArea'); Add('tpName', Name); Add('tpOnGenerate', OnGenerate); end; end; procedure TTpTextArea.SetOnGenerate(const Value: TTpEvent); begin FOnGenerate := Value; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ReverseGeoCoder; {$IFDEF FPC} {$mode delphi} {$modeswitch objectivec1} {$ENDIF} interface uses SysUtils, Classes, FMX_Types {$IFDEF FPC} , iPhoneAll {$ENDIF} ; type TPlaceMark = record Thoroughfare, SubThoroughfare, Locality, SubLocality, AdministrativeArea, SubAdministrativeArea, PostalCode, Country, CountryCode, Street, StreetNumber, Address, City, State : String; end; type TFoundPlaceMarkEvent = procedure(PlaceMark : TPlaceMark) of object; TErrorEvent = procedure of Object; type TiOSReverseGeoCoder = class(TFmxObject) private FOnFoundPlaceMark: TFoundPlaceMarkEvent; FOnError: TErrorEvent; FLongitude: Double; FLatitude: Double; { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Execute; published { Published declarations } property OnFoundPlaceMark: TFoundPlaceMarkEvent read FOnFoundPlaceMark write FOnFoundPlaceMark; property OnError: TErrorEvent read FOnError write FOnError; property Longitude: Double read FLongitude write FLongitude; property Latitude: Double read FLatitude write FLatitude; end; var GlobalReverseGeoCoder: TiOSReverseGeoCoder; procedure Register; implementation {$IFDEF FPC} uses MapKit, CoreLocation; {$ENDIF} {$IFDEF FPC} type GeoDelegate = objcclass(NSObject) reverseGeoCoder : MKReverseGeoCoder; procedure reverseGeocoder_didFindPlacemark(geocoder: MKReverseGeocoder; placemark: MKPlacemark); message 'reverseGeocoder:didFindPlacemark:'; procedure reverseGeocoder_didFailWithError(geocoder: MKReverseGeocoder; error: NSError); message 'reverseGeocoder:didFailWithError:'; end; {$ENDIF} {$IFDEF FPC} var GeoDelegateVar : GeoDelegate; {$ENDIF} {$IFDEF FPC} procedure GeoDelegate.reverseGeocoder_didFindPlacemark(geocoder: MKReverseGeocoder; placemark: MKPlacemark); var PM : TPlaceMark; begin PM.Thoroughfare := String(PChar(placemark.thoroughfare.UTF8String)); PM.SubThoroughfare := String(PChar(placemark.subThoroughfare.UTF8String)); PM.Locality := String(PChar(placemark.locality.UTF8String)); PM.SubLocality := String(PChar(placemark.subLocality.UTF8String)); PM.AdministrativeArea := String(PChar(placemark.administrativeArea.UTF8String)); PM.SubAdministrativeArea := String(PChar(placemark.subAdministrativeArea.UTF8String)); PM.PostalCode := String(PChar(placemark.postalCode.UTF8String)); PM.Country := String(PChar(placemark.country.UTF8String)); PM.CountryCode := String(PChar(placemark.countryCode.UTF8String)); PM.Street := String(PChar(placemark.thoroughfare.UTF8String)); PM.StreetNumber := String(PChar(placemark.SubThoroughfare.UTF8String)); if PM.StreetNumber <> '' then PM.Address := PM.StreetNumber+' '+PM.Street else PM.Address := PM.Street; PM.City := String(PChar(placemark.locality.UTF8String)); PM.State := String(PChar(placemark.administrativeArea.UTF8String)); if Assigned(GlobalReverseGeoCoder) then if Assigned(GlobalReverseGeoCoder.FOnFoundPlaceMark) then GlobalReverseGeoCoder.FOnFoundPlaceMark(PM); end; {$ENDIF} {$IFDEF FPC} procedure GeoDelegate.reverseGeocoder_didFailWithError(geocoder: MKReverseGeocoder; error: NSError); begin if Assigned(GlobalReverseGeoCoder) then if Assigned(GlobalReverseGeoCoder.FOnError) then GlobalReverseGeoCoder.FOnError; end; {$ENDIF} constructor TiOSReverseGeoCoder.Create(AOwner: TComponent); begin if Assigned(GlobalReverseGeoCoder) then raise Exception.Create('I won''t let you have more than one of these things...'); inherited; // Embarcadero, 5617 Scotts Valley Dr, Scotts Valley, CA, USA FLatitude := 37.062915; FLongitude := -122.007353; GlobalReverseGeoCoder := Self; end; destructor TiOSReverseGeoCoder.Destroy; begin if GlobalReverseGeoCoder = Self then GlobalReverseGeoCoder := nil; {$IFDEF FPC} GeoDelegateVar.reverseGeoCoder.release; GeoDelegateVar.release; {$ENDIF} inherited; end; procedure TiOSReverseGeoCoder.Execute; {$IFDEF FPC} var Coordinate : CLLocationCoordinate2D; {$ENDIF} begin {$IFDEF FPC} GeoDelegateVar := GeoDelegate.alloc.init; GeoDelegateVar.reverseGeoCoder := MKReverseGeocoder.alloc; Coordinate.Latitude := FLatitude; Coordinate.Longitude := FLongitude; GeoDelegateVar.reverseGeoCoder.initWithCoordinate(Coordinate); GeoDelegateVar.reverseGeoCoder.setDelegate(GeoDelegateVar); GeoDelegateVar.reverseGeoCoder.start; {$ENDIF} end; procedure Register; begin RegisterComponents('iOS', [TiOSReverseGeoCoder]); end; end.
// XD Pascal - a 32-bit compiler for Windows // Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov {$I-} {$H-} unit Scanner; interface uses Common; var Tok: TToken; procedure InitializeScanner(const Name: TString); function SaveScanner: Boolean; function RestoreScanner: Boolean; procedure FinalizeScanner; procedure NextTok; procedure CheckTok(ExpectedTokKind: TTokenKind); procedure EatTok(ExpectedTokKind: TTokenKind); procedure AssertIdent; function ScannerFileName: TString; function ScannerLine: Integer; implementation type TBuffer = record Ptr: PCharacter; Size, Pos: Integer; end; TScannerState = record Token: TToken; FileName: TString; Line: Integer; Buffer: TBuffer; ch, ch2: TCharacter; EndOfUnit: Boolean; end; const SCANNERSTACKSIZE = 10; var ScannerState: TScannerState; ScannerStack: array [1..SCANNERSTACKSIZE] of TScannerState; ScannerStackTop: Integer = 0; const Digits: set of TCharacter = ['0'..'9']; HexDigits: set of TCharacter = ['0'..'9', 'A'..'F']; Spaces: set of TCharacter = [#1..#31, ' ']; AlphaNums: set of TCharacter = ['A'..'Z', 'a'..'z', '0'..'9', '_']; procedure InitializeScanner(const Name: TString); var F: TInFile; ActualSize: Integer; FolderIndex: Integer; begin ScannerState.Buffer.Ptr := nil; // First search the source folder, then the units folder, then the folders specified in $UNITPATH FolderIndex := 1; repeat Assign(F, TGenericString(Folders[FolderIndex] + Name)); Reset(F, 1); if IOResult = 0 then Break; Inc(FolderIndex); until FolderIndex > NumFolders; if FolderIndex > NumFolders then Error('Unable to open source file ' + Name); with ScannerState do begin FileName := Name; Line := 1; with Buffer do begin Size := FileSize(F); Pos := 0; GetMem(Ptr, Size); ActualSize := 0; BlockRead(F, Ptr^, Size, ActualSize); Close(F); if ActualSize <> Size then Error('Unable to read source file ' + Name); end; ch := ' '; ch2 := ' '; EndOfUnit := FALSE; end; end; function SaveScanner: Boolean; begin Result := FALSE; if ScannerStackTop < SCANNERSTACKSIZE then begin Inc(ScannerStackTop); ScannerStack[ScannerStackTop] := ScannerState; Result := TRUE; end; end; function RestoreScanner: Boolean; begin Result := FALSE; if ScannerStackTop > 0 then begin ScannerState := ScannerStack[ScannerStackTop]; Dec(ScannerStackTop); Tok := ScannerState.Token; Result := TRUE; end; end; procedure FinalizeScanner; begin ScannerState.EndOfUnit := TRUE; with ScannerState.Buffer do if Ptr <> nil then begin FreeMem(Ptr); Ptr := nil; end; end; procedure AppendStrSafe(var s: TString; ch: TCharacter); begin if Length(s) >= MAXSTRLENGTH - 1 then Error('String is too long'); s := s + ch; end; procedure ReadChar(var ch: TCharacter); begin if ScannerState.ch = #10 then Inc(ScannerState.Line); // End of line found ch := #0; with ScannerState.Buffer do if Pos < Size then begin ch := PCharacter(Integer(Ptr) + Pos)^; Inc(Pos); end else ScannerState.EndOfUnit := TRUE; end; procedure ReadUppercaseChar(var ch: TCharacter); begin ReadChar(ch); ch := UpCase(ch); end; procedure ReadLiteralChar(var ch: TCharacter); begin ReadChar(ch); if (ch = #0) or (ch = #10) then Error('Unterminated string'); end; procedure ReadSingleLineComment; begin with ScannerState do while (ch <> #10) and not EndOfUnit do ReadChar(ch); end; procedure ReadMultiLineComment; begin with ScannerState do while (ch <> '}') and not EndOfUnit do ReadChar(ch); end; procedure ReadDirective; var Text: TString; begin with ScannerState do begin Text := ''; repeat AppendStrSafe(Text, ch); ReadUppercaseChar(ch); until not (ch in AlphaNums); if Text = '$APPTYPE' then // Console/GUI application type directive begin Text := ''; ReadChar(ch); while (ch <> '}') and not EndOfUnit do begin if (ch = #0) or (ch > ' ') then AppendStrSafe(Text, UpCase(ch)); ReadChar(ch); end; if Text = 'CONSOLE' then IsConsoleProgram := TRUE else if Text = 'GUI' then IsConsoleProgram := FALSE else Error('Unknown application type ' + Text); end else if Text = '$UNITPATH' then // Unit path directive begin Text := ''; ReadChar(ch); while (ch <> '}') and not EndOfUnit do begin if (ch = #0) or (ch > ' ') then AppendStrSafe(Text, UpCase(ch)); ReadChar(ch); end; Inc(NumFolders); if NumFolders > MAXFOLDERS then Error('Maximum number of unit paths exceeded'); Folders[NumFolders] := Folders[1] + Text; end else // All other directives are ignored ReadMultiLineComment; end; end; procedure ReadHexadecimalNumber; var Num, Digit: Integer; NumFound: Boolean; begin with ScannerState do begin Num := 0; NumFound := FALSE; while ch in HexDigits do begin if Num and $F0000000 <> 0 then Error('Numeric constant is too large'); if ch in Digits then Digit := Ord(ch) - Ord('0') else Digit := Ord(ch) - Ord('A') + 10; Num := Num shl 4 or Digit; NumFound := TRUE; ReadUppercaseChar(ch); end; if not NumFound then Error('Hexadecimal constant is not found'); Token.Kind := INTNUMBERTOK; Token.OrdValue := Num; end; end; procedure ReadDecimalNumber; var Num, Expon, Digit: Integer; Frac, FracWeight: Double; NegExpon, RangeFound, ExponFound: Boolean; begin with ScannerState do begin Num := 0; Frac := 0; Expon := 0; NegExpon := FALSE; while ch in Digits do begin Digit := Ord(ch) - Ord('0'); if Num > (HighBound(INTEGERTYPEINDEX) - Digit) div 10 then Error('Numeric constant is too large'); Num := 10 * Num + Digit; ReadUppercaseChar(ch); end; if (ch <> '.') and (ch <> 'E') then // Integer number begin Token.Kind := INTNUMBERTOK; Token.OrdValue := Num; end else begin // Check for '..' token RangeFound := FALSE; if ch = '.' then begin ReadUppercaseChar(ch2); if ch2 = '.' then // Integer number followed by '..' token begin Token.Kind := INTNUMBERTOK; Token.OrdValue := Num; RangeFound := TRUE; end; if not EndOfUnit then Dec(Buffer.Pos); end; // if ch = '.' if not RangeFound then // Fractional number begin // Check for fractional part if ch = '.' then begin FracWeight := 0.1; ReadUppercaseChar(ch); while ch in Digits do begin Digit := Ord(ch) - Ord('0'); Frac := Frac + FracWeight * Digit; FracWeight := FracWeight / 10; ReadUppercaseChar(ch); end; end; // if ch = '.' // Check for exponent if ch = 'E' then begin ReadUppercaseChar(ch); // Check for exponent sign if ch = '+' then ReadUppercaseChar(ch) else if ch = '-' then begin NegExpon := TRUE; ReadUppercaseChar(ch); end; ExponFound := FALSE; while ch in Digits do begin Digit := Ord(ch) - Ord('0'); Expon := 10 * Expon + Digit; ReadUppercaseChar(ch); ExponFound := TRUE; end; if not ExponFound then Error('Exponent is not found'); if NegExpon then Expon := -Expon; end; // if ch = 'E' Token.Kind := REALNUMBERTOK; Token.RealValue := (Num + Frac) * exp(Expon * ln(10)); end; // if not RangeFound end; // else end; end; procedure ReadNumber; begin with ScannerState do if ch = '$' then begin ReadUppercaseChar(ch); ReadHexadecimalNumber; end else ReadDecimalNumber; end; procedure ReadCharCode; begin with ScannerState do begin ReadUppercaseChar(ch); if not (ch in Digits + ['$']) then Error('Character code is not found'); ReadNumber; if (Token.Kind = REALNUMBERTOK) or (Token.OrdValue < 0) or (Token.OrdValue > 255) then Error('Illegal character code'); Token.Kind := CHARLITERALTOK; end; end; procedure ReadKeywordOrIdentifier; var Text, NonUppercaseText: TString; CurToken: TTokenKind; begin with ScannerState do begin Text := ''; NonUppercaseText := ''; repeat AppendStrSafe(NonUppercaseText, ch); ch := UpCase(ch); AppendStrSafe(Text, ch); ReadChar(ch); until not (ch in AlphaNums); CurToken := GetKeyword(Text); if CurToken <> EMPTYTOK then // Keyword found Token.Kind := CurToken else begin // Identifier found Token.Kind := IDENTTOK; Token.Name := Text; Token.NonUppercaseName := NonUppercaseText; end; end; end; procedure ReadCharOrStringLiteral; var Text: TString; EndOfLiteral: Boolean; begin with ScannerState do begin Text := ''; EndOfLiteral := FALSE; repeat ReadLiteralChar(ch); if ch <> '''' then AppendStrSafe(Text, ch) else begin ReadChar(ch2); if ch2 = '''' then // Apostrophe character found AppendStrSafe(Text, ch) else begin if not EndOfUnit then Dec(Buffer.Pos); // Discard ch2 EndOfLiteral := TRUE; end; end; until EndOfLiteral; if Length(Text) = 1 then begin Token.Kind := CHARLITERALTOK; Token.OrdValue := Ord(Text[1]); end else begin Token.Kind := STRINGLITERALTOK; Token.Name := Text; Token.StrLength := Length(Text); DefineStaticString(Text, Token.StrAddress); end; ReadUppercaseChar(ch); end; end; procedure NextTok; begin with ScannerState do begin Token.Kind := EMPTYTOK; // Skip spaces, comments, directives while (ch in Spaces) or (ch = '{') or (ch = '/') do begin if ch = '{' then // Multi-line comment or directive begin ReadUppercaseChar(ch); if ch = '$' then ReadDirective else ReadMultiLineComment; end else if ch = '/' then begin ReadUppercaseChar(ch2); if ch2 = '/' then ReadSingleLineComment // Double-line comment else begin if not EndOfUnit then Dec(Buffer.Pos); // Discard ch2 Break; end; end; ReadChar(ch); end; // Read token case ch of '0'..'9', '$': ReadNumber; '#': ReadCharCode; 'A'..'Z', 'a'..'z', '_': ReadKeywordOrIdentifier; '''': ReadCharOrStringLiteral; ':': // Single- or double-character tokens begin Token.Kind := COLONTOK; ReadUppercaseChar(ch); if ch = '=' then begin Token.Kind := ASSIGNTOK; ReadUppercaseChar(ch); end; end; '>': begin Token.Kind := GTTOK; ReadUppercaseChar(ch); if ch = '=' then begin Token.Kind := GETOK; ReadUppercaseChar(ch); end; end; '<': begin Token.Kind := LTTOK; ReadUppercaseChar(ch); if ch = '=' then begin Token.Kind := LETOK; ReadUppercaseChar(ch); end else if ch = '>' then begin Token.Kind := NETOK; ReadUppercaseChar(ch); end; end; '.': begin Token.Kind := PERIODTOK; ReadUppercaseChar(ch); if ch = '.' then begin Token.Kind := RANGETOK; ReadUppercaseChar(ch); end; end else // Double-character tokens case ch of '=': Token.Kind := EQTOK; ',': Token.Kind := COMMATOK; ';': Token.Kind := SEMICOLONTOK; '(': Token.Kind := OPARTOK; ')': Token.Kind := CPARTOK; '*': Token.Kind := MULTOK; '/': Token.Kind := DIVTOK; '+': Token.Kind := PLUSTOK; '-': Token.Kind := MINUSTOK; '^': Token.Kind := DEREFERENCETOK; '@': Token.Kind := ADDRESSTOK; '[': Token.Kind := OBRACKETTOK; ']': Token.Kind := CBRACKETTOK else Error('Unexpected character or end of file'); end; // case ReadChar(ch); end; // case end; Tok := ScannerState.Token; end; // NextTok procedure CheckTok(ExpectedTokKind: TTokenKind); begin with ScannerState do if Token.Kind <> ExpectedTokKind then Error(GetTokSpelling(ExpectedTokKind) + ' expected but ' + GetTokSpelling(Token.Kind) + ' found'); end; procedure EatTok(ExpectedTokKind: TTokenKind); begin CheckTok(ExpectedTokKind); NextTok; end; procedure AssertIdent; begin with ScannerState do if Token.Kind <> IDENTTOK then Error('Identifier expected but ' + GetTokSpelling(Token.Kind) + ' found'); end; function ScannerFileName: TString; begin Result := ScannerState.FileName; end; function ScannerLine: Integer; begin Result := ScannerState.Line; end; end.
unit uCadVendedores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Mask, JvExStdCtrls, JvButton, JvCtrls, Data.DB, JvExMask, JvToolEdit, JvDBControls, JvCombobox, JvDBCombobox, JvDBSearchComboBox; type TTela = (Consulta, Manutencao); type TfrmCadVendedores = class(TForm) pnlManutencao: TPanel; Panel2: TPanel; Label29: TLabel; btnOk: TJvImgBtn; btnCancelar: TJvImgBtn; GroupBox3: TGroupBox; Label2: TLabel; Label5: TLabel; DBEdit1: TDBEdit; pnlConsulta: TPanel; GroupBox2: TGroupBox; dbGrid: TDBGrid; GroupBox1: TGroupBox; edtNome: TLabeledEdit; btnFiltrar: TJvImgBtn; Panel1: TPanel; btnNovo: TJvImgBtn; btnEditar: TJvImgBtn; btnExcluir: TJvImgBtn; TimerInicio: TTimer; dsTblven: TDataSource; Label1: TLabel; dbedtNome: TDBEdit; Label4: TLabel; DBEdit4: TDBEdit; dsLookup: TDataSource; DBLookupComboBox1: TDBLookupComboBox; Label3: TLabel; Label6: TLabel; dsFiltroGrupos: TDataSource; JvDBSearchComboBox1: TJvDBSearchComboBox; Label7: TLabel; procedure TimerInicioTimer(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnFiltrarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure btnNovoClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); private { Private declarations } procedure ControlarTela(ATela: TTela); public { Public declarations } end; var frmCadVendedores: TfrmCadVendedores; implementation {$R *.dfm} uses uDadosVendedores, uUsuario; { TfrmCadVendedores } procedure TfrmCadVendedores.btnCancelarClick(Sender: TObject); begin dmDadosVendedores.CalcelarManutencaoVendedor; ControlarTela(Consulta); end; procedure TfrmCadVendedores.btnEditarClick(Sender: TObject); begin dmDadosVendedores.EditarVendedor; ControlarTela(Manutencao); end; procedure TfrmCadVendedores.btnExcluirClick(Sender: TObject); begin try dmDadosVendedores.ExcluirVendedor; except on E: Exception do begin MessageDlg(e.Message, mtError,[mbOK],0); btnFiltrarClick(btnFiltrar); end; end; end; procedure TfrmCadVendedores.btnFiltrarClick(Sender: TObject); begin dmDadosVendedores.FiltrarVendedores(0, edtNome.Text, dmDadosVendedores.cdsFiltroGruposgdvcod.AsInteger); end; procedure TfrmCadVendedores.btnNovoClick(Sender: TObject); begin dmDadosVendedores.AdicionarVendedor; ControlarTela(Manutencao); end; procedure TfrmCadVendedores.btnOkClick(Sender: TObject); begin dmDadosVendedores.SalvarVendedor; ControlarTela(Consulta); btnFiltrarClick(btnFiltrar); end; procedure TfrmCadVendedores.ControlarTela(ATela: TTela); begin if ATela = Consulta then begin // Muda para a tela de Consulta pnlConsulta.Visible := true; pnlManutencao.Visible := false; edtNome.SetFocus; end else begin // Muda para a tela de Manutenção pnlConsulta.Visible := false; pnlManutencao.Visible := true; dbedtNome.SetFocus; end; end; procedure TfrmCadVendedores.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin dmDadosVendedores.CalcelarManutencaoVendedor; end; procedure TfrmCadVendedores.FormShow(Sender: TObject); begin TimerInicio.Enabled := true; end; procedure TfrmCadVendedores.TimerInicioTimer(Sender: TObject); begin TimerInicio.Enabled := false; // Verifica as permissões do usuário btnNovo.Enabled := dmUsuario.TemPermissaoAcesso(14); btnEditar.Enabled := dmUsuario.TemPermissaoAcesso(15); btnExcluir.Enabled := dmUsuario.TemPermissaoAcesso(16); dmDadosVendedores.CarregarFiltroGrupos; ControlarTela(Consulta); btnFiltrarClick(btnFiltrar); end; end.
unit ibSHDebuggerIntf; interface uses SysUtils, Classes, Graphics, Types, SHDesignIntf, ibSHDriverIntf; type TibSHDebugGroupStatementType = (dgstEmpty, dgstProcedure, dgstTrigger, dgstSimple, dgstCondition, //dgstConditionClause, dgstConditionThenClause, dgstConditionElseClause, // dgstSimpleCase, dgstSearchedCase, dgstCaseConditionClause, dgstCaseWhenClause, dgstCaseElseClause, // dgstNullIf, // dgstCoalesce, // dgstIIF, dgstIIFConditionClause, dgstIIFConditionTrueClause, dgstIIFConditionFalseClause,//!!! dgstForSelectCycle, dgstWhileCycle, dgstErrorHandler); TibSHDebugOperatorType = (dotEmpty, dotLeave, dotExit, dotSuspend, dotExpression, dotSelect, {dotSelectInto, }dotExecuteProcedure,dotExecuteStatement, dotFunction, dotInsert, dotUpdate, dotDelete, dotException,dotLastEnd,dotFirstBegin ,dotOpenCursor,dotCloseCursor, dotFetchCursor,dotErrorHandler ); IibSHPSQLProcessor = interface ['{C760EF1B-E1FA-42D0-9519-F488692647F8}'] function GetCursor(AName: string): Variant; procedure SetCursor(AName: string; const Value: Variant); function GetVariable(AName: string): Variant; procedure SetVariable(AName: string; const Value: Variant); function CreateDataSet: TComponent; property Cursor[AName: string] : Variant read GetCursor write SetCursor; property Variable[AName: string] : Variant read GetVariable write SetVariable; end; IibSHDebugStatement = interface ['{7AD838AB-8266-44FD-AF06-7BE38C0CA6FF}'] function GetGroupStatementType: TibSHDebugGroupStatementType; procedure SetGroupStatementType(Value: TibSHDebugGroupStatementType);{?} function GetOperatorType: TibSHDebugOperatorType; procedure SetOperatorType(Value: TibSHDebugOperatorType);{?} function GetParentStatement: IibSHDebugStatement; procedure SetParentStatement(Value: IibSHDebugStatement); function GetPriorStatement: IibSHDebugStatement; procedure SetPriorStatement(Value: IibSHDebugStatement); function GetNextStatement: IibSHDebugStatement; procedure SetNextStatement(Value: IibSHDebugStatement); function GetChildStatements(Index: Integer): IibSHDebugStatement; function GetChildStatementsCount: Integer; function GetBeginOfStatement: TPoint; procedure SetBeginOfStatement(Value: TPoint); function GetEndOfStatement: TPoint; procedure SetEndOfStatement(Value: TPoint); function GetDataSet: IibSHDRVDataset; function GetProcessor: IibSHPSQLProcessor; procedure SetProcessor(Value: IibSHPSQLProcessor); function GetVariableNames: TStrings; function GetVariableName: string; function GetOperatorText: string; function GetUsesCursor: Boolean; function GetCursorName: string; function AddChildStatement(Value: TComponent): Integer; function RemoveChildStatement(Value: TComponent): Integer; function GetErrorHandlerStmt: IibSHDebugStatement; procedure SetErrorHandlerStmt(Value: IibSHDebugStatement); function GetLastErrorCode:TibErrorCode; procedure SetLastErrorCode(Value:TibErrorCode); function CanExecute(Value: Variant): Boolean; procedure Execute(Values: array of Variant; out Results: array of Variant); function Parse: Boolean; function GetIsDynamicStatement:boolean; property GroupStatementType: TibSHDebugGroupStatementType read GetGroupStatementType write SetGroupStatementType; property OperatorType: TibSHDebugOperatorType read GetOperatorType write SetOperatorType; property ParentStatement: IibSHDebugStatement read GetParentStatement write SetParentStatement; property PriorStatement: IibSHDebugStatement read GetPriorStatement write SetPriorStatement; property NextStatement: IibSHDebugStatement read GetNextStatement write SetNextStatement; property ChildStatements[Index: Integer]: IibSHDebugStatement read GetChildStatements; property ChildStatementsCount: Integer read GetChildStatementsCount; property BeginOfStatement: TPoint read GetBeginOfStatement write SetBeginOfStatement; property EndOfStatement: TPoint read GetEndOfStatement write SetEndOfStatement; property DataSet: IibSHDRVDataset read GetDataSet; property Processor: IibSHPSQLProcessor read GetProcessor write SetProcessor; property VariableNames: TStrings read GetVariableNames; property VariableName: string read GetVariableName; property OperatorText: string read GetOperatorText; property UsesCursor: Boolean read GetUsesCursor; property CursorName: string read GetCursorName; property IsDynamicStatement:boolean read GetIsDynamicStatement; property ErrorHandlerStmt: IibSHDebugStatement read GetErrorHandlerStmt write SetErrorHandlerStmt; property LastErrorCode:TibErrorCode read GetLastErrorCode write SetLastErrorCode; end; IibSHPSQLDebuggerItem = interface ['{25F6FFA5-300A-4BEB-89EA-0B01CCF6C3F9}'] function GetDebugObjectName: string; function GetObjectBody: TStrings; function GetDebugObjectType: TGUID; function GetParserPosition: TPoint; procedure SetParserPosition(Value: TPoint); function GetDRVDatabase: IibSHDRVDatabase; function GetDRVTransaction: IibSHDRVTransaction; { function GetParentDebugger: IibSHPSQLDebuggerItem; function GetChildDebuggers(Index: Integer): IibSHPSQLDebuggerItem; procedure SetChildDebuggers(Index: Integer; Value: IibSHPSQLDebuggerItem); function GetChildDebuggersCount: Integer; function GetEditor: Pointer; procedure SetEditor(Value: Pointer); } function GetFirstStatement: IibSHDebugStatement; function GetCurrentStatement: IibSHDebugStatement; procedure SetCurrentStatement(Value: IibSHDebugStatement); function GetInputParameters(Index: Integer): Variant; procedure SetInputParameters(Index: Integer; Value: Variant); function GetInputParametersCount: Integer; function GetOutputParameters(Index: Integer): Variant; procedure SetOutputParameters(Index: Integer; Value: Variant); function GetOutputParametersCount: Integer; function GetLocalVariables(Index: Integer): Variant; procedure SetLocalVariables(Index: Integer; Value: Variant); function GetLocalVariablesCount: Integer; function GetTokenScaner: TComponent; function GetServerException: Boolean; procedure SetServerException(Value: Boolean); procedure StatementFound(AStatement: IibSHDebugStatement); { function AddChildDebugger(Value: IibSHPSQLDebuggerItem): Integer; } function Parse: Boolean; procedure ClearStatementTree; property DebugObjectName: string read GetDebugObjectName; property ObjectBody: TStrings read GetObjectBody; property DebugObjectType: TGUID read GetDebugObjectType; property ParserPosition: TPoint read GetParserPosition write SetParserPosition; property DRVDatabase: IibSHDRVDatabase read GetDRVDatabase; property DRVTransaction: IibSHDRVTransaction read GetDRVTransaction; { property ParentDebugger: IibSHPSQLDebuggerItem read GetParentDebugger; property ChildDebuggers[Index: Integer]: IibSHPSQLDebuggerItem read GetChildDebuggers write SetChildDebuggers; property ChildDebuggersCount: Integer read GetChildDebuggersCount; property Editor: Pointer read GetEditor write SetEditor; } property FirstStatement: IibSHDebugStatement read GetFirstStatement; property CurrentStatement: IibSHDebugStatement read GetCurrentStatement write SetCurrentStatement; property InputParameters[Index: Integer]: Variant read GetInputParameters write SetInputParameters; property InputParametersCount: Integer read GetInputParametersCount; property OutputParameters[Index: Integer]: Variant read GetOutputParameters write SetOutputParameters; property OutputParametersCount: Integer read GetOutputParametersCount; property LocalVariables[Index: Integer]: Variant read GetLocalVariables write SetLocalVariables; property LocalVariablesCount: Integer read GetLocalVariablesCount; property TokenScaner: TComponent read GetTokenScaner; property ServerException: Boolean read GetServerException write SetServerException; end; IibSHPSQLDebuggerTrigger = interface(IibSHPSQLDebuggerItem) ['{9EEE7BC6-D614-42D9-8F49-0562D3E5D358}'] procedure SetInputRow(DB_KEY: string); end; implementation end.
unit ByteDataSet; interface uses AbstractDataSet; type TByteDataSet = class (TAbstractDataSet) private // Gets function GetData(_pos: integer): byte; reintroduce; overload; // Sets procedure SetData(_pos: integer; _data: byte); reintroduce; overload; protected FData : packed array of byte; // Gets function GetDataLength: integer; override; function GetLast: integer; override; // Sets procedure SetLength(_size: integer); override; public // copies procedure Assign(const _Source: TAbstractDataSet); override; // properties property Data[_pos: integer]:byte read GetData write SetData; end; implementation // Gets function TByteDataSet.GetData(_pos: integer): byte; begin Result := FData[_pos]; end; function TByteDataSet.GetDataLength: integer; begin Result := High(FData) + 1; end; function TByteDataSet.GetLast: integer; begin Result := High(FData); end; // Sets procedure TByteDataSet.SetData(_pos: integer; _data: byte); begin FData[_pos] := _data; end; procedure TByteDataSet.SetLength(_size: Integer); begin System.SetLength(FData,_size); end; // copies procedure TByteDataSet.Assign(const _Source: TAbstractDataSet); var maxData,i: integer; begin Length := _Source.Length; maxData := GetDataLength() - 1; for i := 0 to maxData do begin Data[i] := (_Source as TByteDataSet).Data[i]; end; end; end.
{----------------------------------------------------------------------------- Unit Name: geFloatEdit Author: HochwimmerA Purpose: Edit Box for floats - incomplete... $Id: geFloatEdit.pas,v 1.7 2003/09/11 05:25:52 hochwimmera Exp $ -----------------------------------------------------------------------------} unit geFloatEdit; interface uses Classes, Controls, Forms, Messages, StdCtrls, SysUtils, Dialogs, Variants, Math, Windows; type TGEValidateOption = (vdNone,vdSilent,vdWarning); TGEFloatEdit = class(TCustomEdit) private fFormatString : string; fIsNull : boolean; fLastText : string; fMaxValue : extended; fMinValue : extended; fReturnStop : boolean; fUseMinBound : boolean; fUseMaxBound : boolean; fValidate : TGEValidateOption; fValue : extended; protected procedure Loaded;override; function ConvertText(sValue:string):extended; procedure DoEnter;override; function GetText: string; procedure KeyPress(VAR Key: Char); override; procedure Refresh; virtual; procedure SetFormatString(sFormat:string); procedure SetReturnStop(bValue:boolean); procedure SetText(sValue: String); procedure SetValidate(aGE:TGEValidateOption); procedure SetValue(aValue:extended); procedure WMKillFocus(VAR Message: TWMSetFocus); message WM_KILLFOCUS; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property IsNull : boolean read fIsNull; property Value : extended read fValue write SetValue; published property FormatString : string read fFormatString write SetFormatString; property Text : string read GetText write SetText; property MinValue : extended read fMinValue write fMinValue; property MaxValue : extended read fMaxValue write fMaxValue; property ReturnStop:Boolean read fReturnStop write SetReturnStop; property UseMinBound : boolean read fUseMinBound write fUseMinBound; property UseMaxBound : boolean read fUseMaxBound write fUseMaxBound; property Validate : TGEValidateOption read fValidate write SetValidate; // expose from TCustomEdit; property Align; property Anchors; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; procedure Register; implementation // ----- TGEFloatEdit.Loaded --------------------------------------------------- procedure TGEFloatEdit.Loaded; begin inherited Loaded; Refresh; end; // ----- TGEFloatEdit.ConvertText ---------------------------------------------- function TGEFloatEdit.ConvertText(sValue:string):extended; var s:string; begin // premultiply the number if no mantissa present s := svalue; if Pos('E',Uppercase(s)) = 1 then insert('1',s,1); if Pos('-E',UpperCase(s)) = 1 then insert('1',s,2); if (sValue = '') then begin fIsNull := true; result := 0.0 end else begin try result := StrToFloat(s); fIsNull := false; except on EConvertError do begin result := fValue; // revert back to old value // result := 0.0; fIsNull := false; end; end; end; end; // ------ TGEFloatEdit.DoEnter ------------------------------------------------- procedure TGEFloatEdit.DoEnter; begin if ISNull then inherited Text := '' else inherited Text := FloatToStr(value); // full precision inherited DoEnter; end; // ----- TGEFloatEdit.GetText -------------------------------------------------- function TGEFloatEdit.GetText: string; begin result := inherited Text; end; // ----- TGEFloatEdit.KeyPress ------------------------------------------------- procedure TGEFloatEdit.KeyPress(VAR Key: Char); var dTemp:extended; sTemp:string; // only allow numbers, 0..9, e,E function CharIsNumber(const C: AnsiChar): Boolean; begin Result := (C in ['0'..'9']) or (C in ['-','+','e','E']) or (C in ['.',',']); //Last - DecimalSeparators end; begin // control characters // if Key = #8 then // Key := #0; if (Ord(Key) = Ord(' ')) then Key := #0 else if (Ord(Key)) < Ord(' ') then begin inherited KeyPress(Key); exit; end else if (Key = Char(VK_RETURN)) then begin if ReturnStop <> true then begin stemp:=inherited Text; dtemp := ConvertText(stemp); if not IsNull then begin Value := dtemp; SelectAll; end else begin // if (InputWarning) then // AlreadyWarned:=true; // MessageDlg(strtemp + ' is invalid!', mtInformation, [mbOK], 0); Refresh; end; end else // return stop - ie a tabstop begin { do an equivalent tab out - use the screen global var ie if the key is pressed then the parent on the must be focused I think} Key := #0; Screen.ActiveForm.Perform(WM_NEXTDLGCTL, 0, 0); //method of form end; end else begin // if not a screen number return null if not CharIsNumber(AnsiChar(Key)) then Key := #0; end; inherited KeyPress(Key); end; // ----- TGEFloatEdit.Refresh -------------------------------------------------- procedure TGEFloatEdit.Refresh; begin if IsNull then inherited Text := '' else begin if (FormatString <> '') then begin try inherited Text := Format(FormatString,[value]); except inherited Text := FloatToStr(Value); end; end else inherited Text := FloatToStr(Value); end; fLastText := inherited Text; end; // ----- TGEFloatEdit.SetFormatString ------------------------------------------ procedure TGEFloatEdit.SetFormatString(sFormat:string); begin if (fFormatString <> sFormat) then begin fFormatString := sFormat; Refresh; end; end; // ----- TGEFloatEdit.SetReturnStop -------------------------------------------- procedure TGEFloatEdit.SetReturnStop(bValue:boolean); // only allow this if tabstop is true begin if bValue <> fReturnStop then fReturnStop:= (bValue and TabStop); end; // ----- TGEFloatEdit.SetText -------------------------------------------------- procedure TGEFloatEdit.SetText(sValue: String); begin if not (csLoading in ComponentState) then begin if (sValue <> '') then Value := ConvertText(sValue) else begin Value := 0.0; fIsNull := true; end; end; if IsNull then inherited Text := '' else inherited Text := FloatToStr(Value); fLastText := inherited Text; end; // ----- TGEFloatEdit.SetValidate ---------------------------------------------- procedure TGEFloatEdit.SetValidate(aGE:TGEValidateOption); begin if (aGE <> fValidate) then fValidate := aGE; end; // ----- TGEFloatEdit.SetValue ------------------------------------------------- procedure TGEFloatEdit.SetValue(aValue:extended); var bValid : boolean; begin // check for NAN if IsNan(aValue) then begin fValue := 0.0; fIsNull := true; end else begin // check for validity bValid := true; if (fValidate = vdSilent) or (fValidate = vdWarning) then begin if (AValue < fMinValue) and fUseMinBound then bValid := false; if (AValue > fMaxValue) and fUseMaxBound then bValid := false; end; if bvalid then begin fIsNull := false; fValue := AValue; end else begin end; end; Refresh; end; // ----- TGEFloatEdit.WMKillFocus ---------------------------------------------- procedure TGEFloatEdit.WMKillFocus(Var Message: TWMSetFocus); var dtemp:extended; stemp:string; begin try stemp:=inherited Text; if (stemp <> fLastText) then begin dtemp := ConvertText(sTemp); if not IsNull then Value := dtemp else begin // if (InputWarning) and not (AlreadyWarned) then // MessageDlg(strtemp+ ' is invalid!', mtInformation, [mbOK], 0); Refresh; end; end; inherited; except if inherited Text <> '' then begin Self.SelectAll; Self.SetFocus; end else begin Value := 0.0; fIsNull := true; inherited; end; end; end; // ----- TGEFloatEdit.Create --------------------------------------------------- constructor TGEFloatEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); fValidate := vdNone; fMinValue := 0.0; fMaxValue := 0.0; fUseMinBound := false; fUseMaxBound := false; fFormatString := ''; // set this to a format property - e.g. %8.2f fIsNull := false; fValue := 0.0; fLastText := inherited Text; end; // ----- TGEFloatEdit.Destroy -------------------------------------------------- destructor TGEFloatEdit.Destroy; begin inherited Destroy; end; // ======== Register ======================================================= procedure Register; begin RegisterComponents('Graphic Edge IO',[TGEFloatEdit]); end; end.
unit U_SCFEdit; {$MODE Delphi} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TSCFieldPicker = class(TForm) Panel1: TPanel; RGItems: TRadioGroup; BNOK: TButton; BNCancel: TButton; private { Private declarations } procedure SetCaptions(const name:string); Procedure ClearItems; Procedure AddItem(const name:string); public { Public declarations } Function PickGeo(geo:integer):integer; Function PickLightMode(lmode:integer):integer; Function PickTEX(tex:integer):integer; end; var SCFieldPicker: TSCFieldPicker; implementation {$R *.lfm} procedure TSCFieldPicker.SetCaptions(const name:string); begin Caption:=name; RGItems.Caption:=name; end; Procedure TSCFieldPicker.ClearItems; begin RGItems.Items.Clear; end; Procedure TSCFieldPicker.AddItem(const name:string); begin RGItems.Items.Add(name); end; Function TSCFieldPicker.PickGeo(geo:integer):integer; begin SetCaptions('GEO mode'); if geo>5 then geo:=5; ClearItems; AddItem('Not rendered'); AddItem('Draw vertices'); AddItem('Draw wireframe'); AddItem('Draw solid color'); AddItem('Draw textured'); AddItem('Draw textured'); RGItems.ItemIndex:=geo; if ShowModal=mrOk then result:=RGItems.ItemIndex else result:=geo; end; Function TSCFieldPicker.PickLightMode(lmode:integer):integer; begin SetCaptions('Lighting mode'); if lmode>5 then lmode:=5; ClearItems; AddItem('Fully lit'); AddItem('Not lit'); AddItem('Diffuse'); AddItem('Gouraud'); AddItem('Gouraud'); AddItem('Gouraud'); RGItems.ItemIndex:=lmode; if ShowModal=mrOk then result:=RGItems.ItemIndex else result:=lmode; end; {SurfaceTypes NORMAL 0x0 Normal face (one sided no overlays/masks) TWOSIDED 0x1 Face is 2 sided. TRANSLUCENT 0x2 Face is translucent"} Function TSCFieldPicker.PickTEX(tex:integer):integer; begin SetCaptions('Texturing mode'); if tex>3 then tex:=3; ClearItems; AddItem('Affine'); AddItem('Perspective'); AddItem('Perspective'); AddItem('Perspective'); RGItems.ItemIndex:=tex; if ShowModal=mrOk then result:=RGItems.ItemIndex else result:=tex; end; end.
unit eMVC.Config; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.RTTI, System.Generics.Collections, MVCBr.ObjectConfigList, eMVC.OTAUtilities, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; const mvc_maxConfig = 1; mvc_createSubFolder = 0; type TMVCConfig = class; IMVCConfig = interface ['{4CC5DC73-B326-4468-8F04-3BD5F4F0C9F5}'] function This: TMVCConfig; procedure ReadConfig; procedure WriteConfig; function IsCreateSubFolder: boolean; procedure ShowView(AProc: TProc); end; TMVCConfig = class(TForm, IMVCConfig) ScrollBox1: TScrollBox; Image1: TImage; Button1: TButton; GroupBox1: TGroupBox; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); private FConfig: IObjectConfigList; FCanceled: boolean; { Private declarations } procedure RegisterControls; function GetValues(idx: Integer): TValue; procedure SetValues(idx: Integer; const Value: TValue); public { Public declarations } procedure Init; function This: TMVCConfig; class function New: IMVCConfig; procedure ReadConfig; procedure WriteConfig; property Values[idx: Integer]: TValue read GetValues write SetValues; function IsCreateSubFolder: boolean; procedure ShowView(AProc: TProc); end; implementation {$R *.dfm} uses IniFiles, eMVC.ToolBox; var LMvcConfig: IMVCConfig; procedure TMVCConfig.Button1Click(Sender: TObject); begin WriteConfig; FCanceled := false; close; end; procedure TMVCConfig.FormCreate(Sender: TObject); begin FConfig := TObjectConfigModel.New; RegisterControls; end; procedure TMVCConfig.FormShow(Sender: TObject); begin FCanceled := true; Init; end; function TMVCConfig.GetValues(idx: Integer): TValue; begin result := FConfig.items[idx].Value; end; procedure TMVCConfig.Init; begin ReadConfig; end; function TMVCConfig.IsCreateSubFolder: boolean; begin result := GetValues(mvc_createSubFolder).AsBoolean; end; class function TMVCConfig.New: IMVCConfig; var obj: TMVCConfig; begin if LMvcConfig=nil then begin obj := TMVCConfig.create(nil); LMvcConfig := obj; obj.Init; end; result := LMvcConfig; end; procedure TMVCConfig.ReadConfig; begin try FConfig.ReadConfig; except on e:exception do DEBUG(e.message); end; end; procedure TMVCConfig.RegisterControls; begin FConfig.Add(CheckBox1); // mvc_createSubFolder end; procedure TMVCConfig.SetValues(idx: Integer; const Value: TValue); begin FConfig.items[idx].Value := Value; end; procedure TMVCConfig.ShowView(AProc: TProc); begin showmodal; if not FCanceled then if assigned(AProc) then AProc; end; function TMVCConfig.This: TMVCConfig; begin result := self; end; procedure TMVCConfig.WriteConfig; begin try FConfig.WriteConfig; except on e:exception do DEBUG(e.message); end; end; end.
{ Catarinka TStringListCache Caches multiple string lists, allowing them to be loaded or saved together to an external JSON file Copyright (c) 2003-2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } unit CatStringListCache; interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, unitObjectCache, CatJSON; {$ELSE} Classes, SysUtils, unitObjectCache, CatJSON; {$ENDIF} type TStringListCache = class protected fCache: TObjectCache; fNameList: TStringList; public function GetList(const AName: string): TStringList; procedure ClearLists; overload; procedure ClearLists(const Key: array of string); overload; procedure CopyListsFrom(var Source: TStringListCache; const Key: array of string); procedure LoadFromFile(const AFilename: string); procedure LoadFromString(const JSON: string); procedure SaveToFile(const AFilename: string); constructor Create(ACapacity: Integer = 1000; OwnsObjects: boolean = true); destructor Destroy; override; property Cache: TObjectCache read fCache; property Lists[const AName: string]: TStringList read GetList; default; end; type TCachedStringList = class(TStringList) private ID: string; end; implementation uses CatStringLoop; const cCacheKeyPrefix = 'cache.'; cIDListKey = 'idlist'; // Copies the values of specific lists from a TStringListCache procedure TStringListCache.CopyListsFrom(var Source: TStringListCache; const Key: array of string); var i: integer; begin for i := Low(Key) to High(Key) do if not(Key[i] = emptystr) then Lists[Key[i]].Text := Source[Key[i]].Text; end; procedure TStringListCache.ClearLists; var csl: TCachedStringList; m, c: Integer; begin m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; csl.Clear; end; end; procedure TStringListCache.ClearLists(const Key: array of string); var X: Integer; begin for X := Low(Key) to High(Key) do if not(Key[X] = '') then GetList(Key[X]).Clear; end; procedure TStringListCache.LoadFromFile(const AFilename: string); var sl: TStringList; begin sl := TStringList.Create; sl.LoadFromFile(AFilename); LoadFromString(sl.Text); sl.Free; end; procedure TStringListCache.LoadFromString(const JSON: string); var slp: TStringLoop; sl: TStringList; j: TCatJSON; begin fCache.Clear; fNameList.Clear; j := TCatJSON.Create(JSON); slp := TStringLoop.Create(j[cIDListKey]); while slp.Found do begin sl := GetList(slp.Current); sl.Text := j[cCacheKeyPrefix + slp.Current]; end; slp.Free; j.Free; end; procedure TStringListCache.SaveToFile(const AFilename: string); var j: TCatJSON; csl: TCachedStringList; m, c: Integer; begin j := TCatJSON.Create; j.SetValue(cIDListKey, fNameList.Text); m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; j.SetValue(cCacheKeyPrefix + csl.ID, csl.Text); end; j.SaveToFile(AFilename); j.Free; end; function TStringListCache.GetList(const AName: string): TStringList; var csl: TCachedStringList; m, c: Integer; begin result := nil; m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; if csl.ID = AName then result := csl; end; if result = nil then begin csl := TCachedStringList.Create; csl.ID := AName; fCache.Add(csl); fNameList.Add(AName); result := csl; end; end; constructor TStringListCache.Create(ACapacity: Integer = 1000; OwnsObjects: boolean = true); begin fCache := TObjectCache.Create(ACapacity, OwnsObjects); fNameList := TStringList.Create; end; destructor TStringListCache.Destroy; begin fNameList.Free; fCache.Free; inherited; end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private procedure TaskComplete(Sender: TObject); procedure HandleCheckpoint1(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} type TSpecificTaskThread = Class(TThread) private FInterimResult: string; FFinalResult: string; FOnCheckpoint1: TNotifyEvent; protected procedure DoCheckpoint1; procedure Execute; override; public property InterimResult: string read FInterimResult; property FinalResult: string read FFinalResult; property OnCheckpoint1 : TNotifyEvent read FOnCheckpoint1 write FOnCheckpoint1; End; procedure TSpecificTaskThread.DoCheckpoint1; begin if Assigned(FOnCheckpoint1) then FOnCheckpoint1(Self); end; procedure TSpecificTaskThread.Execute; var aGuid: TGuid; begin FInterimResult := ''; FFinalResult := ''; // call an external API (web, Hydra etc here) Sleep(1500); CreateGuid(aGuid); FInterimResult := GuidToString(aGuid); Synchronize(DoCheckpoint1); // call an external API (web, Hydra etc here) Sleep(1500); CreateGuid(aGuid); FFinalResult := GuidToString(aGuid); end; procedure TForm1.Button1Click(Sender: TObject); var oThread : TSpecificTaskThread; begin // True tells the thread not to start until we've configured it oThread := TSpecificTaskThread.Create(True); // OnCheckpoint1 is called on the UI thread at an intermediate progress event oThread.OnCheckpoint1 := HandleCheckpoint1; // OnTerminate is called on the UI thread after Execute completes oThread.OnTerminate := TaskComplete; // don't need this if we hang onto oThread and free it oThread.FreeOnTerminate := True; oThread.Resume; Memo1.Lines.Add(Format('%s - thread started', [DateTimeToStr(Now)])); end; procedure TForm1.HandleCheckpoint1(Sender: TObject); var value: string; begin value := TSpecificTaskThread(Sender).InterimResult; Memo1.Lines.Add(Format('%s - checkpoint, result ''%s''', [DateTimeToStr(Now), value])); end; procedure TForm1.TaskComplete(Sender: TObject); var value: string; begin value := TSpecificTaskThread(Sender).FinalResult; Memo1.Lines.Add(Format('%s - thread finished, result ''%s''', [DateTimeToStr(Now), value])); end; end.
unit OTFEBestCryptTestApp_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface {$IFDEF LINUX} This software is only intended for use under MS Windows {$ENDIF} {$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already // protecting against that! uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, OTFEBestCrypt_U, OTFEBestCryptStructures_U, OTFE_U, FileCtrl; type TBestCryptTestApp_F = class(TForm) pbClose: TButton; pbVersion: TButton; pbIsEncryptedVolFile: TButton; edTestIfMtdVolFile: TEdit; DriveComboBox1: TDriveComboBox; pbBrowse: TButton; pbDisountVolume: TButton; pbMountVolume: TButton; pbDismountDrive: TButton; pbClear: TButton; pbGetVolumeInfo2: TButton; rgActive: TRadioGroup; pbGetFileMountedForDrive: TButton; pbGetDriveMountedForFile: TButton; pbNumDrivesMounted: TButton; pbRefresh: TButton; OpenDialog1: TOpenDialog; pbGetMountedDrives: TButton; pbDismountAll: TButton; gbVolInfo: TGroupBox; lblReadOnly: TLabel; lblDriveMountedAs: TLabel; lblFilename: TLabel; Label15: TLabel; Label22: TLabel; Label23: TLabel; Label3: TLabel; lblExtent: TLabel; lblVersion: TLabel; lblAlgorithm: TLabel; lblFileSystemID: TLabel; lblKeyGen: TLabel; Label4: TLabel; Label5: TLabel; Label8: TLabel; Label10: TLabel; Label11: TLabel; reDescription: TRichEdit; pbGetKeyGenIDs: TButton; pbGetAlgIDs: TButton; pbGetVolumeInfo: TButton; Label1: TLabel; lblErrsInMounting: TLabel; pbIsDriverInstalled: TButton; OTFEBestCrypt1: TOTFEBestCrypt; RichEdit1: TRichEdit; procedure pbCloseClick(Sender: TObject); procedure rgActiveClick(Sender: TObject); procedure pbVersionClick(Sender: TObject); procedure pbNumDrivesMountedClick(Sender: TObject); procedure pbDismountDriveClick(Sender: TObject); procedure pbGetVolumeInfo2Click(Sender: TObject); procedure pbGetFileMountedForDriveClick(Sender: TObject); procedure pbIsEncryptedVolumeClick(Sender: TObject); procedure pbMountVolumeClick(Sender: TObject); procedure pbDisountVolumeClick(Sender: TObject); procedure pbGetDriveMountedForFileClick(Sender: TObject); procedure pbClearClick(Sender: TObject); procedure pbBrowseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbRefreshClick(Sender: TObject); procedure pbGetMountedDrivesClick(Sender: TObject); procedure pbDismountAllClick(Sender: TObject); procedure pbGetKeyGenIDsClick(Sender: TObject); procedure pbGetAlgIDsClick(Sender: TObject); procedure pbGetVolumeInfoClick(Sender: TObject); procedure pbIsDriverInstalledClick(Sender: TObject); private procedure ReportWhetherActive(); procedure RefreshDriveComboBox(); procedure DisplayVolumeInfo(info: TBCDiskInfo); public { Public declarations } end; var BestCryptTestApp_F: TBestCryptTestApp_F; implementation {$R *.DFM} procedure TBestCryptTestApp_F.ReportWhetherActive(); begin if OTFEBestCrypt1.Active then begin RichEdit1.lines.add('BestCrypt component ACTIVE'); rgActive.ItemIndex:=0; end else begin RichEdit1.lines.add('BestCrypt component NOT Active'); rgActive.ItemIndex:=1; end; end; procedure TBestCryptTestApp_F.pbCloseClick(Sender: TObject); begin Close; end; procedure TBestCryptTestApp_F.pbVersionClick(Sender: TObject); begin RichEdit1.lines.add('BestCrypt driver version: 0x'+inttohex(OTFEBestCrypt1.Version(), 1)); end; procedure TBestCryptTestApp_F.pbIsEncryptedVolumeClick(Sender: TObject); var filename: string; output: string; begin filename := edTestIfMtdVolFile.text; output := filename; if OTFEBestCrypt1.IsEncryptedVolFile(filename) then begin output := output + ' IS '; end else begin output := output + ' is NOT '; end; output := output + 'a BestCrypt volume file'; RichEdit1.lines.add(output); end; procedure TBestCryptTestApp_F.pbBrowseClick(Sender: TObject); begin OpenDialog1.Filename := edTestIfMtdVolFile.text; if OpenDialog1.execute() then begin edTestIfMtdVolFile.text := OpenDialog1.FileName; end; end; procedure TBestCryptTestApp_F.pbMountVolumeClick(Sender: TObject); begin try if OTFEBestCrypt1.Mount(edTestIfMtdVolFile.text)<>#0 then begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' mounted OK'); end else begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' mount failed'); end; except on E: EBestCryptVxdBadStatus do begin showmessage('CAUGHT AN EBestCryptVxdBadStatus'); end; end; RefreshDriveComboBox(); end; procedure TBestCryptTestApp_F.pbDisountVolumeClick(Sender: TObject); begin if OTFEBestCrypt1.Dismount(edTestIfMtdVolFile.text) then begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismounted OK'); end else begin RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismount failed'); end; RefreshDriveComboBox(); end; procedure TBestCryptTestApp_F.pbDismountDriveClick(Sender: TObject); var output: string; begin output := DriveComboBox1.drive + ': '; if OTFEBestCrypt1.Dismount(DriveComboBox1.drive) then begin output := output + 'dismounted OK'; end else begin output := output + 'dismount FAILED'; end; RichEdit1.lines.add(output); RefreshDriveComboBox(); end; procedure TBestCryptTestApp_F.RefreshDriveComboBox(); var origCase: TTextCase; begin origCase := DriveComboBox1.TextCase; DriveComboBox1.TextCase := tcUpperCase; DriveComboBox1.TextCase := tcLowerCase; DriveComboBox1.TextCase := origCase; end; procedure TBestCryptTestApp_F.pbClearClick(Sender: TObject); begin RichEdit1.lines.Clear(); end; procedure TBestCryptTestApp_F.pbGetVolumeInfo2Click(Sender: TObject); var info: TBCDiskInfo; begin info := TBCDiskInfo.Create(); try if OTFEBestCrypt1.GetVolumeInfo(DriveComboBox1.drive, info) then begin DisplayVolumeInfo(info); end else begin RichEdit1.lines.add('Cannot get disk info'); end; finally info.Free(); end end; procedure TBestCryptTestApp_F.rgActiveClick(Sender: TObject); begin try OTFEBestCrypt1.Active := (rgActive.ItemIndex=0); finally ReportWhetherActive(); end; end; procedure TBestCryptTestApp_F.pbGetFileMountedForDriveClick(Sender: TObject); var output: string; begin output := DriveComboBox1.drive + ': is BestCrypt volume file: "' + OTFEBestCrypt1.GetVolFileForDrive(DriveComboBox1.drive) + '"'; RichEdit1.lines.add(output); end; procedure TBestCryptTestApp_F.pbGetDriveMountedForFileClick(Sender: TObject); var output: string; begin output := '"' + edTestIfMtdVolFile.text + '" is mounted as: '+ OTFEBestCrypt1.GetDriveForVolFile(edTestIfMtdVolFile.text) + ':'; RichEdit1.lines.add(output); end; procedure TBestCryptTestApp_F.FormCreate(Sender: TObject); begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin edTestIfMtdVolFile.text := 'c:\bc_test2.jbc'; end else begin edTestIfMtdVolFile.text := 'E:\BestCrypt VolumeFile.jbc'; end; end; procedure TBestCryptTestApp_F.pbNumDrivesMountedClick(Sender: TObject); var output: string; begin output := 'Number of volumes mounted: '; output := output + inttostr(OTFEBestCrypt1.CountDrivesMounted()); RichEdit1.lines.add(output); end; procedure TBestCryptTestApp_F.pbRefreshClick(Sender: TObject); begin RefreshDriveComboBox(); end; procedure TBestCryptTestApp_F.pbGetMountedDrivesClick(Sender: TObject); begin RichEdit1.lines.Add('Drives currently mounted are: '+OTFEBestCrypt1.DrivesMounted()); end; procedure TBestCryptTestApp_F.pbDismountAllClick(Sender: TObject); var output: string; begin output := ''; if length(OTFEBestCrypt1.DismountAll())=0 then begin output := output + 'DismountAll OK'; end else begin output := output + 'DismountAll FAILED'; end; RichEdit1.lines.add(output); end; procedure TBestCryptTestApp_F.pbGetKeyGenIDsClick(Sender: TObject); var ids: TStringList; i: integer; begin ids := TStringList.Create(); try OTFEBestCrypt1.GetAllKeyGenIDs(ids); for i:=0 to (ids.count-1) do begin RichEdit1.lines.add('Key generator ID '+ids[i]+':'); RichEdit1.lines.add(' '+OTFEBestCrypt1.GetKeyGenName(strtoint(ids[i]))); RichEdit1.lines.add(' Version: 0x'+inttohex(OTFEBestCrypt1.GetKeyGenVersion(strtoint(ids[i])), 4)); RichEdit1.lines.add(' Stored in DLL: '+OTFEBestCrypt1.GetKeyGenDLLName(strtoint(ids[i]))); end; finally ids.Free(); end; end; procedure TBestCryptTestApp_F.pbGetAlgIDsClick(Sender: TObject); var ids: TStringList; i: integer; begin ids := TStringList.Create(); try OTFEBestCrypt1.GetAllAlgorithmIDs(ids); for i:=0 to (ids.count-1) do begin RichEdit1.lines.add('Algorithm ID '+ids[i]+':'); RichEdit1.lines.add(' '+OTFEBestCrypt1.GetAlgorithmName(strtoint(ids[i]))); RichEdit1.lines.add(' Version: 0x'+inttohex(OTFEBestCrypt1.GetAlgorithmVersion(strtoint(ids[i])), 4)); RichEdit1.lines.add(' Key length: '+inttostr(OTFEBestCrypt1.GetAlgorithmKeyLength(strtoint(ids[i])))); RichEdit1.lines.add(' Driver name: '+OTFEBestCrypt1.GetAlgorithmDriverName(strtoint(ids[i]))); end; finally ids.Free(); end; end; procedure TBestCryptTestApp_F.pbGetVolumeInfoClick(Sender: TObject); var info: TBCDiskInfo; begin info := TBCDiskInfo.Create(); try if OTFEBestCrypt1.GetVolumeInfo(edTestIfMtdVolFile.text, info) then begin DisplayVolumeInfo(info); end else begin RichEdit1.lines.add('Cannot get disk info'); end; finally info.Free(); end end; procedure TBestCryptTestApp_F.DisplayVolumeInfo(info: TBCDiskInfo); var algorithmProb: boolean; begin lblDriveMountedAs.caption := '<not mounted>'; lblReadOnly.caption := '<not mounted>'; lblFilename.caption := '<not mounted>'; if info.volumeFilename<>'' then begin lblFilename.caption := info.volumeFilename; end; if info.mountedAs<>#0 then begin lblDriveMountedAs.caption := info.mountedAs + ':'; if info.readOnly then begin lblReadOnly.caption := 'Readonly'; end else begin lblReadOnly.caption := 'Read/Write'; end; end; lblExtent.caption := '0x'+inttohex(info.extent, 2); lblVersion.caption := '0x'+inttohex(info.version, 2); lblFileSystemID.caption := '0x'+inttohex(info.fileSystemId, 4); algorithmProb := FALSE; if info.algorithmName='' then begin algorithmProb := TRUE; lblAlgorithm.caption := '???'; end else begin lblAlgorithm.caption := info.algorithmName; end; if info.algorithmKeyLen=-1 then begin algorithmProb := TRUE; lblAlgorithm.caption := lblAlgorithm.caption + ' (??? bit)'; end else begin lblAlgorithm.caption := lblAlgorithm.caption+' ('+inttostr(info.algorithmKeyLen)+' bit)'; end; if algorithmProb then begin lblAlgorithm.caption := lblAlgorithm.caption+' (ID=0x'+inttohex(info.algorithmId, 1)+')'; end; if info.keyGenName='' then begin lblKeyGen.caption := '??? (0x'+inttostr(info.keyGenId)+')'; end else begin lblKeyGen.caption := info.keyGenName; end; reDescription.text := info.description; lblErrsInMounting.caption := inttostr(info.errsInMounting); end; procedure TBestCryptTestApp_F.pbIsDriverInstalledClick(Sender: TObject); begin if OTFEBestCrypt1.IsDriverInstalled() then begin RichEdit1.lines.add('Driver installed'); end else begin RichEdit1.lines.add('Driver NOT installed'); end; end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- {$WARN UNIT_PLATFORM ON} // ----------------------------------------------------------------------------- END.
unit uBase64; { Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. } interface uses System.SysUtils, uBase; var tempResult: array of String; tempResultDecode: TBytes; function Encode(data: TBytes): String; function Decode(data: String): TBytes; procedure EncodeBlock(src: TBytes; beginInd, endInd: Integer); procedure DecodeBlock(src: String; beginInd, endInd: Integer); Const DefaultAlphabet: Array [0 .. 63] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'); DefaultSpecial = '='; implementation procedure EncodeBlock(src: TBytes; beginInd, endInd: Integer); var ind, srcInd, dstInd: Integer; x1, x2, x3: byte; begin for ind := beginInd to Pred(endInd) do begin srcInd := ind * 3; dstInd := ind * 4; x1 := src[srcInd]; x2 := src[srcInd + 1]; x3 := src[srcInd + 2]; tempResult[dstInd] := DefaultAlphabet[x1 shr 2]; tempResult[dstInd + 1] := DefaultAlphabet[((x1 shl 4) and $30) or (x2 shr 4)]; tempResult[dstInd + 2] := DefaultAlphabet[((x2 shl 2) and $3C) or (x3 shr 6)]; tempResult[dstInd + 3] := DefaultAlphabet[x3 and $3F]; end; end; procedure DecodeBlock(src: String; beginInd, endInd: Integer); var ind, srcInd, dstInd, x1, x2, x3, x4: Integer; begin for ind := beginInd to endInd do begin srcInd := ind * 4; dstInd := ind * 3; x1 := InvAlphabet[Ord(src[srcInd + 1])]; x2 := InvAlphabet[Ord(src[srcInd + 2])]; x3 := InvAlphabet[Ord(src[srcInd + 3])]; x4 := InvAlphabet[Ord(src[srcInd + 4])]; tempResultDecode[dstInd] := byte((x1 shl 2) or ((x2 shr 4) and $3)); tempResultDecode[dstInd + 1] := byte((x2 shl 4) or ((x3 shr 2) and $F)); tempResultDecode[dstInd + 2] := byte((x3 shl 6) or (x4 and $3F)); end; end; function Encode(data: TBytes): String; var resultLength, dataLength, tempInt, length3, ind, x1, x2, srcInd, dstInd: Integer; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; dataLength := Length(data); resultLength := (dataLength + 2) div 3 * 4; SetLength(tempResult, resultLength); length3 := Length(data) div 3; EncodeBlock(data, 0, length3); tempInt := (dataLength - length3 * 3); case tempInt of 1: begin ind := length3; srcInd := ind * 3; dstInd := ind * 4; x1 := data[srcInd]; tempResult[dstInd] := DefaultAlphabet[x1 shr 2]; tempResult[dstInd + 1] := DefaultAlphabet[(x1 shl 4) and $30]; tempResult[dstInd + 2] := DefaultSpecial; tempResult[dstInd + 3] := DefaultSpecial; end; 2: begin ind := length3; srcInd := ind * 3; dstInd := ind * 4; x1 := data[srcInd]; x2 := data[srcInd + 1]; tempResult[dstInd] := DefaultAlphabet[x1 shr 2]; tempResult[dstInd + 1] := DefaultAlphabet [((x1 shl 4) and $30) or (x2 shr 4)]; tempResult[dstInd + 2] := DefaultAlphabet[(x2 shl 2) and $3C]; tempResult[dstInd + 3] := DefaultSpecial; end; end; result := ArraytoString(tempResult); tempResult := nil; end; function Decode(data: String): TBytes; var lastSpecialInd, tailLength, resultLength, length4, ind, x1, x2, x3, srcInd, dstInd: Integer; begin if isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; lastSpecialInd := Length(data); while (data[lastSpecialInd] = DefaultSpecial) do begin dec(lastSpecialInd); end; tailLength := Length(data) - lastSpecialInd; resultLength := (Length(data) + 3) div 4 * 3 - tailLength; SetLength(tempResultDecode, resultLength); length4 := (Length(data) - tailLength) div 4; Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial); DecodeBlock(data, 0, length4); Case tailLength of 2: begin ind := length4; srcInd := ind * 4; dstInd := ind * 3; x1 := InvAlphabet[Ord(data[srcInd + 1])]; x2 := InvAlphabet[Ord(data[srcInd + 2])]; tempResultDecode[dstInd] := byte((x1 shl 2) or ((x2 shr 4) and $3)); end; 1: begin ind := length4; srcInd := ind * 4; dstInd := ind * 3; x1 := InvAlphabet[Ord(data[srcInd + 1])]; x2 := InvAlphabet[Ord(data[srcInd + 2])]; x3 := InvAlphabet[Ord(data[srcInd + 3])]; tempResultDecode[dstInd] := byte((x1 shl 2) or ((x2 shr 4) and $3)); tempResultDecode[dstInd + 1] := byte((x2 shl 4) or ((x3 shr 2) and $F)); end; end; result := tempResultDecode; tempResultDecode := nil; end; end.
unit uTextProps; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, iexColorButton, imageenview, iexLayers, ieview, hyiedefs, ExtCtrls, Buttons; type TTextProps = class(TForm) lblHeading: TLabel; btnCancel: TButton; btnOK: TButton; memText: TMemo; lblFontSize: TLabel; edtFontSize: TEdit; updFontSize: TUpDown; chkFontBold: TCheckBox; chkFontItalics: TCheckBox; btnSetFont: TButton; btnFontColor: TIEColorButton; lblFontColor: TLabel; lblText: TLabel; btnFillColor2: TIEColorButton; cmbGradient: TComboBox; edtRotate: TEdit; updRotate: TUpDown; lblRotate: TLabel; lblGradient: TLabel; btnFillColor: TIEColorButton; chkTextBox: TCheckBox; lblBorderWidth: TLabel; edtBorderWidth: TEdit; updBorderWidth: TUpDown; btnBorderColor: TIEColorButton; lblBGColor: TLabel; lblBorderColor: TLabel; GroupBox1: TGroupBox; pnlBackground: TPanel; pnlPreview: TPanel; procedure FormCreate(Sender: TObject); procedure ControlChange(Sender: TObject); procedure btnSetFontClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure InitializeValues(); public { Public declarations } procedure ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer); end; implementation {$R *.dfm} uses iexCanvasUtils, hyieutils; procedure TTextProps.FormCreate(Sender: TObject); begin InitializeValues(); end; procedure TTextProps.ControlChange(Sender: TObject); {} function _GetStyle(OldStyle: TFontStyles; Bold, Italic: Boolean): TFontStyles; begin Result := OldStyle; if Bold then Include( Result, fsBold ) else Exclude( Result, fsBold ); if Italic then Include( Result, fsItalic ) else Exclude( Result, fsItalic ); end; {} begin if not Visible then exit; btnOK.Enabled := memText.Text <> ''; // Text box btnFillColor2 .Enabled := chkTextBox.Checked and ( cmbGradient.ItemIndex > 0 );; cmbGradient .Enabled := chkTextBox.Checked; lblGradient .Enabled := chkTextBox.Checked; btnFillColor .Enabled := chkTextBox.Checked; lblBorderWidth .Enabled := chkTextBox.Checked; edtBorderWidth .Enabled := chkTextBox.Checked; updBorderWidth .Enabled := chkTextBox.Checked; btnBorderColor .Enabled := chkTextBox.Checked; lblBorderColor .Enabled := chkTextBox.Checked; lblBGColor .Enabled := chkTextBox.Checked; // Preview pnlPreview.Caption := memText.Text; pnlPreview.Font.Size := updFontSize.Position; pnlPreview.Font.Color := btnFontColor.SelectedColor; pnlPreview.Font.Style := _GetStyle( pnlPreview.Font.Style, chkFontBold.Checked, chkFontItalics.Checked ); if chkTextBox.checked = False then begin pnlBackground.BorderWidth := 0; pnlPreview.Color := clBtnFace; end else begin pnlPreview.Color := btnFillColor.SelectedColor; pnlBackground.BorderWidth := updBorderWidth.Position; pnlBackground.Color := btnBorderColor.SelectedColor; end; end; procedure TTextProps.btnSetFontClick(Sender: TObject); begin if IEPromptForFont( pnlPreview.Font ) then InitializeValues(); end; procedure TTextProps.InitializeValues(); begin if cmbGradient.ItemIndex < 0 then begin cmbGradient.ItemIndex := 0; btnFillColor2.SelectedColor := clBlue; end; updFontSize .Position := pnlPreview.Font.Size; btnFontColor.SelectedColor := pnlPreview.Font.Color; chkFontBold .Checked := fsBold in pnlPreview.Font.Style; chkFontItalics.Checked := fsItalic in pnlPreview.Font.Style; chkTextBox.checked := ( pnlBackground.BorderWidth > 0 ) and ( pnlPreview.Color <> clBtnFace ); if chkTextBox.checked then begin btnFillColor.SelectedColor := pnlPreview.Color; updBorderWidth.Position := pnlBackground.BorderWidth; btnBorderColor.SelectedColor := pnlBackground.Color; end; ControlChange(nil); end; procedure TTextProps.ApplyToLayer(ImageEnView: TImageEnView; EditingLayer: TIELayer); begin if EditingLayer.Kind <> ielkText then exit; ImageEnView.LockUpdate(); try // Text with TIETextLayer( EditingLayer ) do begin Text := memText.Text; Font.Assign( pnlPreview.Font ); Alignment := iejCenter; Layout := ielCenter; AutoSize := True; WordWrap := TRUE; end; // Rotation TIETextLayer( EditingLayer ).BorderRotate := updRotate.Position; EditingLayer.Rotate := updRotate.Position; // Text box if chkTextBox.checked = False then begin EditingLayer.FillColor := clNone; EditingLayer.FillColor2 := clNone; EditingLayer.BorderWidth := 0; end else begin EditingLayer.FillColor := btnFillColor.SelectedColor; if cmbGradient.ItemIndex = 0 then EditingLayer.FillColor2 := clNone else begin EditingLayer.FillColor2 := btnFillColor2.SelectedColor; EditingLayer.FillGradient := TIELayerGradient( cmbGradient.ItemIndex - 1 ); end; EditingLayer.BorderColor := btnBorderColor.SelectedColor; EditingLayer.BorderWidth := updBorderWidth.Position; end; finally ImageEnView.UnlockUpdate(); end; end; procedure TTextProps.FormShow(Sender: TObject); begin IEInitializeComboBox( cmbGradient ); ControlChange(nil); end; end.
namespace proholz.xsdparser; interface type XsdUnionVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdUnion} instance which owns this {@link XsdUnionVisitor} instance. This way this visitor instance // * can perform changes in the {@link XsdUnion} object. // // var owner: XsdUnion; public constructor(aowner: XsdUnion); method visit(element: XsdSimpleType); override; end; implementation constructor XsdUnionVisitor(aowner: XsdUnion); begin inherited constructor(aowner); self.owner := aowner; end; method XsdUnionVisitor.visit(element: XsdSimpleType); begin inherited visit(element); owner.add(element); end; end.
{: Archipelago GLScene demo.<p> This demo illustrates several GLScene components: - TerrainRenderer, used with a material library - TerrainRenderer's OnHeightDataPostRender, used to render sea surface - HeightTileFileHDS, used as primary elevation datasource - CustomHDS, used to attach texturing information to the elevation samples - DirectOpenGL, used to render the sailboat's wake Note that both custom OpenGL rendering sections are interrelated, the sea surface rendering code also setups the stencil buffer, which is used by the wake rendering code. Credits: - Terrain elevation map and textures : Mattias Fagerlund (http://www.cambrianlabs.com/Mattias/) - Sailboat model and textures : Daniel Polli / Daniel@dansteph.com (http://virtualsailor.dansteph.com) Eric Grange (http://glscene.org) } unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, GLTerrainRenderer, GLObjects, jpeg, GLHeightData, ExtCtrls, GLCadencer, StdCtrls, GLTexture, GLHUDObjects, VectorLists, GLSkydome, GLWin32Viewer, VectorGeometry, GLHeightTileFileHDS, GLWindowsFont, GLBitmapFont, ComCtrls, GLRoamPatch, GLVectorFileObjects, GLMaterial, GLCoordinates, GLCrossPlatform, BaseClasses, GLRenderContextInfo, GLColor; type TForm1 = class(TForm) GLSceneViewer: TGLSceneViewer; GLScene1: TGLScene; GLCamera: TGLCamera; DCCamera: TGLDummyCube; TerrainRenderer: TGLTerrainRenderer; Timer1: TTimer; GLCadencer: TGLCadencer; MaterialLibrary: TGLMaterialLibrary; HTFPS: TGLHUDText; SkyDome: TGLSkyDome; GLHeightTileFileHDS1: TGLHeightTileFileHDS; BFSmall: TGLWindowsBitmapFont; GLCustomHDS1: TGLCustomHDS; PAProgress: TPanel; ProgressBar: TProgressBar; Label1: TLabel; GLMemoryViewer1: TGLMemoryViewer; MLSailBoat: TGLMaterialLibrary; FFSailBoat: TGLFreeForm; LSSun: TGLLightSource; BFLarge: TGLWindowsBitmapFont; HTHelp: TGLHUDText; DOWake: TGLDirectOpenGL; procedure Timer1Timer(Sender: TObject); procedure GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure GLCustomHDS1MarkDirtyEvent(const area: TRect); procedure GLCustomHDS1StartPreparingData(heightData: THeightData); procedure GLSceneViewerBeforeRender(Sender: TObject); procedure TerrainRendererHeightDataPostRender( var rci: TRenderContextInfo; const heightDatas: TList); procedure DOWakeProgress(Sender: TObject; const deltaTime, newTime: Double); procedure DOWakeRender(Sender: TObject; var rci: TRenderContextInfo); private { Déclarations privées } public { Déclarations publiques } FullScreen : Boolean; CamHeight : Single; WaterPolyCount : Integer; WaterPlane : Boolean; WasAboveWater : Boolean; HelpOpacity : Single; WakeVertices : TAffineVectorList; WakeStretch : TAffineVectorList; WakeTime : TSingleList; procedure ResetMousePos; function WaterPhase(const px, py : Single) : Single; function WaterHeight(const px, py : Single) : Single; end; var Form1: TForm1; implementation {$R *.DFM} uses GLKeyboard, OpenGL1x, GLContext, GLState, GLTextureFormat; const cWaterLevel = -10000; cWaterOpaqueDepth = 2000; cWaveAmplitude = 120; procedure TForm1.FormCreate(Sender: TObject); var i, j : Integer; name : String; libMat : TGLLibMaterial; begin SetCurrentDir(ExtractFilePath(Application.ExeName)+'\Data'); GLCustomHDS1.MaxPoolSize:=8*1024*1024; GLCustomHDS1.DefaultHeight:=cWaterLevel; // load texmaps for i:=0 to 3 do for j:=0 to 3 do begin name:=Format('Tex_%d_%d.bmp', [i, j]); if not FileExists(name) then begin ShowMessage( 'Texture file '+name+' not found...'#13#10 +'Did you run "splitter.exe" as said in the readme.txt?'); Application.Terminate; Exit; end; libMat:=MaterialLibrary.AddTextureMaterial(name, name, False); with libMat.Material.Texture do begin TextureMode:=tmReplace; TextureWrap:=twNone; Compression:=tcStandard; // comment out to turn off texture compression // FilteringQuality:=tfAnisotropic; end; libMat.Texture2Name:='detail'; end; // Initial camera height offset (controled with pageUp/pageDown) CamHeight:=20; // Water plane active WaterPlane:=True; // load the sailboat FFSailBoat.LoadFromFile('sailboat.glsm'); MLSailBoat.LoadFromFile('sailboat.glml'); FFSailBoat.Position.SetPoint(-125*TerrainRenderer.Scale.X, 0, -100*TerrainRenderer.Scale.Z); FFSailBoat.TurnAngle:=-30; // boost ambient for i:=0 to MLSailBoat.Materials.Count-1 do with MLSailBoat.Materials[i].Material.FrontProperties do Ambient.Color:=Diffuse.Color; // Move camera starting point near the sailboat DCCamera.Position:=FFSailBoat.Position; DCCamera.Translate(25, 0, -15); DCCamera.Turn(200); // Help text HTHelp.Text:= 'GLScene Archipelago Demo'#13#10#13#10 +'* : Increase CLOD precision'#13#10 +'/ : decrease CLOD precision'#13#10 +'W : wireframe on/off'#13#10 +'S : sea surface on/off'#13#10 +'B : sailboat visible on/off'#13#10 +'Num4 & Num6 : steer the sailboat'#13#10 +'F1: show this help'; HTHelp.Position.SetPoint(Screen.Width div 2 - 100, Screen.Height div 2 - 150, 0); HelpOpacity:=4; GLSceneViewer.Cursor:=crNone; end; procedure TForm1.ResetMousePos; begin if GLSceneViewer.Cursor=crNone then SetCursorPos(Screen.Width div 2, Screen.Height div 2); end; procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); var speed, alpha, f : Single; terrainHeight, surfaceHeight : Single; sbp : TVector; newMousePos : TPoint; begin // handle keypresses if IsKeyDown(VK_SHIFT) then speed:=100*deltaTime else speed:=20*deltaTime; with GLCamera.Position do begin if IsKeyDown(VK_UP) then DCCamera.Position.AddScaledVector(speed, GLCamera.AbsoluteVectorToTarget); if IsKeyDown(VK_DOWN) then DCCamera.Position.AddScaledVector(-speed, GLCamera.AbsoluteVectorToTarget); if IsKeyDown(VK_LEFT) then DCCamera.Position.AddScaledVector(-speed, GLCamera.AbsoluteRightVectorToTarget); if IsKeyDown(VK_RIGHT) then DCCamera.Position.AddScaledVector(speed, GLCamera.AbsoluteRightVectorToTarget); if IsKeyDown(VK_PRIOR) then CamHeight:=CamHeight+speed; if IsKeyDown(VK_NEXT) then CamHeight:=CamHeight-speed; if IsKeyDown(VK_ESCAPE) then Close; end; if IsKeyDown(VK_F1) then HelpOpacity:=ClampValue(HelpOpacity+deltaTime*3, 0, 3); if IsKeyDown(VK_NUMPAD4) then FFSailBoat.Turn(-deltaTime*3); if IsKeyDown(VK_NUMPAD6) then FFSailBoat.Turn(deltaTime*3); // mouse movements and actions if IsKeyDown(VK_LBUTTON) then begin alpha:=DCCamera.Position.Y; DCCamera.Position.AddScaledVector(speed, GLCamera.AbsoluteVectorToTarget); CamHeight:=CamHeight+DCCamera.Position.Y-alpha; end; if IsKeyDown(VK_RBUTTON) then begin alpha:=DCCamera.Position.Y; DCCamera.Position.AddScaledVector(-speed, GLCamera.AbsoluteVectorToTarget); CamHeight:=CamHeight+DCCamera.Position.Y-alpha; end; GetCursorPos(newMousePos); GLCamera.MoveAroundTarget((Screen.Height div 2-newMousePos.Y)*0.25, (Screen.Width div 2-newMousePos.X)*0.25); ResetMousePos; // don't drop our target through terrain! with DCCamera.Position do begin terrainHeight:=TerrainRenderer.InterpolatedHeight(AsVector); surfaceHeight:=TerrainRenderer.Scale.Z*cWaterLevel/128; if terrainHeight<surfaceHeight then terrainHeight:=surfaceHeight; Y:=terrainHeight+CamHeight; end; // adjust fog distance/color for air/water if (GLCamera.AbsolutePosition[1]>surfaceHeight) or (not WaterPlane) then begin if not WasAboveWater then begin SkyDome.Visible:=True; with GLSceneViewer.Buffer.FogEnvironment do begin FogColor.Color:=clrWhite; FogEnd:=1000; FogStart:=500; end; GLSceneViewer.Buffer.BackgroundColor:=clWhite; GLCamera.DepthOfView:=1000; WasAboveWater:=True; end; end else begin if WasAboveWater then begin SkyDome.Visible:=False; with GLSceneViewer.Buffer.FogEnvironment do begin FogColor.AsWinColor:=clNavy; FogEnd:=100; FogStart:=0; end; GLSceneViewer.Buffer.BackgroundColor:=clNavy; GLCamera.DepthOfView:=100; WasAboveWater:=False; end; end; // help visibility if HelpOpacity>0 then begin HelpOpacity:=HelpOpacity-deltaTime; alpha:=ClampValue(HelpOpacity, 0, 1); if alpha>0 then begin HTHelp.Visible:=True; HTHelp.ModulateColor.Alpha:=alpha; end else HTHelp.Visible:=False; end; // rock the sailboat sbp:=TerrainRenderer.AbsoluteToLocal(FFSailBoat.AbsolutePosition); alpha:=WaterPhase(sbp[0]+TerrainRenderer.TileSize*0.5, sbp[1]+TerrainRenderer.TileSize*0.5); FFSailBoat.Position.Y:=(cWaterLevel+Sin(alpha)*cWaveAmplitude)*(TerrainRenderer.Scale.Z/128) -1.5; f:=cWaveAmplitude*0.01; FFSailBoat.Up.SetVector(Cos(alpha)*0.02*f, 1, (Sin(alpha)*0.02-0.005)*f); FFSailBoat.Move(deltaTime*2); end; procedure TForm1.Timer1Timer(Sender: TObject); begin HTFPS.Text:=Format('%.1f FPS - %d - %d', [GLSceneViewer.FramesPerSecond, TerrainRenderer.LastTriangleCount, WaterPolyCount]); GLSceneViewer.ResetPerformanceMonitor; end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); var i : Integer; pm : TPolygonMode; begin case Key of 'w', 'W' : begin with MaterialLibrary do begin if Materials[0].Material.PolygonMode=pmLines then pm:=pmFill else pm:=pmLines; for i:=0 to Materials.Count-1 do Materials[i].Material.PolygonMode:=pm; end; with MLSailBoat do for i:=0 to Materials.Count-1 do Materials[i].Material.PolygonMode:=pm; FFSailBoat.StructureChanged; end; 's', 'S' : WaterPlane:=not WaterPlane; 'b', 'B' : FFSailBoat.Visible:=not FFSailBoat.Visible; '*' : with TerrainRenderer do if CLODPrecision>1 then CLODPrecision:=Round(CLODPrecision*0.8); '/' : with TerrainRenderer do if CLODPrecision<1000 then CLODPrecision:=Round(CLODPrecision*1.2+1); end; Key:=#0; end; procedure TForm1.GLCustomHDS1MarkDirtyEvent(const area: TRect); begin GLHeightTileFileHDS1.MarkDirty(area); end; procedure TForm1.GLCustomHDS1StartPreparingData(heightData: THeightData); var htfHD : THeightData; i, j, n : Integer; offset : TTexPoint; begin with heightData do htfHD:=GLHeightTileFileHDS1.GetData(XLeft, YTop, Size, DataType); if (htfHD.DataState=hdsNone) then //or (htfHD.HeightMax<=cWaterLevel-cWaterOpaqueDepth) then heightData.DataState:=hdsNone else begin i:=(heightData.XLeft div 128); j:=(heightData.YTop div 128); if (Cardinal(i)<4) and (Cardinal(j)<4) then begin heightData.MaterialName:=format('Tex_%d_%d.bmp', [i, j]); heightData.TextureCoordinatesMode:=tcmLocal; n:=((heightData.XLeft div 32) and 3); offset.S:=n*0.25; n:=((heightData.YTop div 32) and 3); offset.T:=-n*0.25; heightData.TextureCoordinatesOffset:=offset; heightData.TextureCoordinatesScale:=TexPointMake(0.25, 0.25); heightData.DataType:=hdtSmallInt; htfHD.DataType:=hdtSmallInt; heightData.Allocate(hdtSmallInt); Move(htfHD.SmallIntData^, heightData.SmallIntData^, htfHD.DataSize); heightData.DataState:=hdsReady; heightData.HeightMin:=htfHD.HeightMin; heightData.HeightMax:=htfHD.HeightMax; end else heightData.DataState:=hdsNone end; GLHeightTileFileHDS1.Release(htfHD); end; procedure TForm1.GLSceneViewerBeforeRender(Sender: TObject); var i, n : Integer; begin PAProgress.Left:=(Width-PAProgress.Width) div 2; PAProgress.Visible:=True; n:=MaterialLibrary.Materials.Count; ProgressBar.Max:=n-1; try for i:=0 to n-1 do begin ProgressBar.Position:=i; MaterialLibrary.Materials[i].Material.Texture.Handle; PAProgress.Repaint; end; finally ResetMousePos; PAProgress.Visible:=False; GLSceneViewer.BeforeRender:=nil; end; end; function TForm1.WaterPhase(const px, py : Single) : Single; begin Result:=GLCadencer.CurrentTime*1+px*0.16+py*0.09; end; function TForm1.WaterHeight(const px, py : Single) : Single; var alpha : Single; begin alpha:=WaterPhase(px+TerrainRenderer.TileSize*0.5, py+TerrainRenderer.TileSize*0.5); Result:=(cWaterLevel+Sin(alpha)*cWaveAmplitude)*(TerrainRenderer.Scale.Z*(1/128)); end; procedure TForm1.TerrainRendererHeightDataPostRender( var rci: TRenderContextInfo; const heightDatas: TList); var i, x, y, s, s2 : Integer; t : Single; hd : THeightData; const r = 0.75; g = 0.75; b = 1; procedure IssuePoint(rx, ry : Integer); var px, py : Single; alpha, colorRatio, ca, sa : Single; begin px:=x+rx+s2; py:=y+ry+s2; if hd.DataState=hdsNone then begin alpha:=1; end else begin alpha:=(cWaterLevel-hd.SmallIntHeight(rx, ry))*(1/cWaterOpaqueDepth); alpha:=ClampValue(alpha, 0.5, 1); end; SinCos(WaterPhase(px, py), sa, ca); colorRatio:=1-alpha*0.1; GL.Color4f(r*colorRatio, g*colorRatio, b, alpha); GL.TexCoord2f(px*0.01+0.002*sa, py*0.01+0.0022*ca-t*0.002); GL.Vertex3f(px, py, cWaterLevel+cWaveAmplitude*sa); end; begin if not WaterPlane then Exit; t:=GLCadencer.CurrentTime; MaterialLibrary.ApplyMaterial('water', rci); repeat with rci.GLStates do begin if not WasAboveWater then InvertGLFrontFace; Disable(stLighting); Disable(stNormalize); SetStencilFunc(cfAlways, 1, 255); StencilWriteMask := 255; Enable(stStencilTest); SetStencilOp(soKeep, soKeep, soReplace); GL.Normal3f(0, 0, 1); for i:=0 to heightDatas.Count-1 do begin hd:=THeightData(heightDatas.List[i]); if (hd.DataState=hdsReady) and (hd.HeightMin>cWaterLevel) then continue; x:=hd.XLeft; y:=hd.YTop; s:=hd.Size-1; s2:=s div 2; GL.Begin_(GL_TRIANGLE_FAN); IssuePoint(s2, s2); IssuePoint(0, 0); IssuePoint(s2, 0); IssuePoint(s, 0); IssuePoint(s, s2); IssuePoint(s, s); IssuePoint(s2, s); IssuePoint(0, s); IssuePoint(0, s2); IssuePoint(0, 0); GL.End_; end; SetStencilOp(soKeep, soKeep, soKeep); Disable(stStencilTest); end; if not WasAboveWater then rci.GLStates.InvertGLFrontFace; WaterPolyCount:=heightDatas.Count*8; until not MaterialLibrary.UnApplyMaterial(rci); end; procedure TForm1.DOWakeProgress(Sender: TObject; const deltaTime, newTime: Double); var i : Integer; sbp, sbr : TVector; begin if WakeVertices=nil then begin WakeVertices:=TAffineVectorList.Create; WakeStretch:=TAffineVectorList.Create; WakeTime:=TSingleList.Create; end; // enlarge current vertices with WakeVertices do begin i:=0; while i<Count do begin CombineItem(i, WakeStretch.List[i shr 1], -0.45*deltaTime); CombineItem(i+1, WakeStretch.List[i shr 1], 0.45*deltaTime); Inc(i, 2); end; end; // Progress wake if newTime>DOWake.TagFloat then begin if DOWake.TagFloat=0 then begin DOWake.TagFloat:=newTime+0.2; Exit; end; DOWake.TagFloat:=newTime+1; sbp:=VectorCombine(FFSailBoat.AbsolutePosition, FFSailBoat.AbsoluteDirection, 1, 3); sbr:=FFSailBoat.AbsoluteRight; // add new WakeVertices.Add(VectorCombine(sbp, sbr, 1, -2)); WakeVertices.Add(VectorCombine(sbp, sbr, 1, 2)); WakeStretch.Add(VectorScale(sbr, (0.95+Random*0.1))); WakeTime.Add(newTime*0.1); if WakeVertices.Count>=80 then begin WakeVertices.Delete(0); WakeVertices.Delete(0); WakeStretch.Delete(0); WakeTime.Delete(0); end; end; end; procedure TForm1.DOWakeRender(Sender: TObject; var rci: TRenderContextInfo); var i, n : Integer; p : PAffineVector; sbp : TVector; c : Single; begin if not Assigned(WakeVertices) then Exit; if (not FFSailBoat.Visible) or (not WaterPlane) then Exit; MaterialLibrary.ApplyMaterial('wake', rci); repeat with rci.GLStates do begin Disable(stLighting); Disable(stFog); Enable(stBlend); SetBlendFunc(bfOne, bfOne); SetStencilFunc(cfEqual, 1, 255); StencilWriteMask := 255; Enable(stStencilTest); SetStencilOp(soKeep, soKeep, soKeep); Disable(stDepthTest); if not WasAboveWater then InvertGLFrontFace; GL.Begin_(GL_TRIANGLE_STRIP); n:=WakeVertices.Count; for i:=0 to n-1 do begin p:=@WakeVertices.List[i xor 1]; sbp:=TerrainRenderer.AbsoluteToLocal(VectorMake(p^)); if (i and 1)=0 then begin c:=(i and $FFE)*0.2/n; GL.Color3f(c, c, c); GL.TexCoord2f(0, WakeTime[i div 2]); end else GL.TexCoord2f(1, WakeTime[i div 2]); GL.Vertex3f(p[0], WaterHeight(sbp[0], sbp[1]), p[2]); end; GL.End_; if not WasAboveWater then InvertGLFrontFace; Disable(stStencilTest); end; until not MaterialLibrary.UnApplyMaterial(rci); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit CustomizedDataSnapCreatorsUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, DSServerExpertsCreators, ExpertsTemplates, ExpertsModules, ExpertsProject, DSServerFeatures, DSServerExpertsTemplateProperties, DSServerMethodsExpertsCreators; type TCustomizedDataSnapCreatorsModule = class(TDSServerExpertsCreatorsModule) private { Private declarations } FComments: string; procedure SetComments(const Value: string); function FormatComments(const AText: string): string; protected function GetServerMethodsCreatorModuleClass: TDSServerMethodsCreatorModuleClass; override; public { Public declarations } procedure UpdateProperties; override; property Comments: string read FComments write SetComments; end; var CustomizedDataSnapCreatorsModule: TCustomizedDataSnapCreatorsModule; implementation {$R *.dfm} uses CustomizedFeatures, CustomizedServerMethodsCreatorUnit; procedure TCustomizedDataSnapCreatorsModule.SetComments(const Value: string); begin FComments := Value; UpdateProperties; end; function TCustomizedDataSnapCreatorsModule.FormatComments(const AText: string): string; var LResult: TStrings; LLines: TStrings; S: string; begin LLines := TStringList.Create; try LLines.Text := AText; LResult := TStringList.Create; try for S in LLines do LResult.Add('//' + S); Result := LResult.Text; finally LResult.Free; end; finally LLines.Free; end; end; function TCustomizedDataSnapCreatorsModule.GetServerMethodsCreatorModuleClass: TDSServerMethodsCreatorModuleClass; begin Result := TCustomizedServerMethodsCreator; end; procedure TCustomizedDataSnapCreatorsModule.UpdateProperties; var LNow: TDateTime; begin inherited; // Customization: Set properties used in templates SetBoolTemplateProperty(sCustomFeatureCommentModule, IsFeatureEnabled(cCustomFeatureCommentModule)); SetBoolTemplateProperty(sCustomFeatureTimeStamp, IsFeatureEnabled(cCustomFeatureTimeStampModule)); SetBoolTemplateProperty(sCustomSampleMethods, IsFeatureEnabled(cCustomFeatureSampleMethods)); CommonTemplateProperties.Properties.Values[sCommentModuleText] := FormatComments(FComments); LNow := Now; CommonTemplateProperties.Properties.Values[sTimeStampText] := FormatDateTime(FormatSettings.ShortDateFormat, LNow) + ' ' + FormatDateTime(FormatSettings.LongTimeFormat, LNow); end; end.
unit Unit2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.Layouts, FMX.Memo, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, System.Actions, FMX.ActnList, FMX.ListBox; type TForm2 = class(TForm) TetheringManager1: TTetheringManager; TetheringAppProfile1: TTetheringAppProfile; Panel1: TPanel; Label1: TLabel; lblSomeText: TLabel; Edit1: TEdit; EditButton1: TEditButton; Label2: TLabel; GroupBox2: TGroupBox; GroupBox3: TGroupBox; ImageControl1: TImageControl; Label3: TLabel; Label4: TLabel; ImageControl2: TImageControl; OpenDialog1: TOpenDialog; Button1: TButton; GroupBox1: TGroupBox; Button2: TButton; ActionList1: TActionList; Action1: TAction; Button3: TButton; Label6: TLabel; procedure TetheringAppProfile1Resources0ResourceReceived( const Sender: TObject; const AResource: TRemoteResource); procedure EditButton1Click(Sender: TObject); procedure TetheringAppProfile1Resources1ResourceReceived( const Sender: TObject; const AResource: TRemoteResource); procedure ImageControl2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} {$R *.Macintosh.fmx _MACOS} procedure TForm2.Button3Click(Sender: TObject); begin TetheringAppProfile1.RunRemoteAction(TetheringManager1.RemoteProfiles.First, 'actToggleChecked' ); end; procedure TForm2.EditButton1Click(Sender: TObject); begin TetheringAppProfile1.SendString(TetheringManager1.RemoteProfiles.First, 'ReplyText', Edit1.Text); end; procedure TForm2.FormCreate(Sender: TObject); begin Caption := TetheringManager1.Identifier; end; procedure TForm2.ImageControl2Click(Sender: TObject); var LStream : TMemoryStream; begin if OpenDialog1.Execute then begin ImageControl2.LoadFromFile(OpenDialog1.FileName); Lstream := TMemoryStream.Create; ImageControl2.Bitmap.SaveToStream(LStream); LStream.Position := 0; TetheringAppProfile1.SendStream(TetheringManager1.RemoteProfiles.First, 'ReplyImage', LStream); end; end; procedure TForm2.TetheringAppProfile1Resources0ResourceReceived( const Sender: TObject; const AResource: TRemoteResource); begin lblSomeText.Text := AResource.Value.AsString; end; procedure TForm2.TetheringAppProfile1Resources1ResourceReceived( const Sender: TObject; const AResource: TRemoteResource); begin Aresource.Value.AsStream.Position := 0; ImageControl1.Bitmap.LoadFromStream(Aresource.Value.AsStream); end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clSmtp; interface {$I clVer.inc} uses Classes, clMC, clMailMessage, clMCUtils; type TclCustomSmtp = class(TclCustomMail) private FMailFrom: string; FMailToList: TStrings; FMailData: TStrings; FExtensions: TStrings; FAuthMechanisms: TStrings; FUseEHLO: Boolean; FMailAgent: string; procedure GetExtensions; function GetAuthExtension: string; procedure GetAuthMechanisms(const AuthExtension: string); procedure SetMailToList(AValue: TStrings); procedure SetMailData(AValue: TStrings); procedure SetMailFrom(const Value: string); procedure SetUseEHLO(const Value: Boolean); procedure SetMailAgent(const Value: string); procedure HELO(const AOkResponses: array of Integer); procedure MAIL; procedure RCPT(AMailToList: TStrings); procedure DATA(AMailData: TStrings); procedure QUIT; procedure EHLO(const AOkResponses: array of Integer); procedure AUTH; procedure DoStringsChanged(Sender: TObject); procedure RemoveBcc(AMailData: TStrings); procedure CramMD5Authenticate; procedure LoginAuthenticate; procedure NtlmAuthenticate; protected function GenMessageID: string; virtual; function GetDefaultPort: Integer; override; procedure OpenSession; override; procedure CloseSession; override; procedure DoDestroy; override; function GetResponseCode(const AResponse: string): Integer; override; procedure InternalSend(AMailData, AMailToList: TStrings); virtual; property MailFrom: string read FMailFrom write SetMailFrom; property MailToList: TStrings read FMailToList write SetMailToList; property UseEHLO: Boolean read FUseEHLO write SetUseEHLO default True; property MailAgent: string read FMailAgent write SetMailAgent; public constructor Create(AOwner: TComponent); override; procedure StartTls; override; procedure Send; overload; procedure Send(AMessage: TclMailMessage); overload; procedure Send(AMessage: TStrings); overload; procedure Reset; property AuthMechanisms: TStrings read FAuthMechanisms; property Extensions: TStrings read FExtensions; property MailData: TStrings read FMailData write SetMailData; end; TclSmtp = class(TclCustomSmtp) published property BatchSize; property UserName; property Password; property MailFrom; property MailToList; property Server; property Port default cDefaultSmtpPort; property TimeOut; property UseTLS; property CertificateFlags; property TLSFlags; property BitsPerSec; property UseSPA; property UseEHLO; property MailAgent; property MailMessage; property OnChanged; property OnOpen; property OnClose; property OnGetCertificate; property OnVerifyServer; property OnSendCommand; property OnReceiveResponse; property OnProgress; end; resourcestring cSMTPErrorDataListEmpty = 'The data list is empty'; cSMTPErrorRcptListEmpty = 'The recipient list is empty'; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsSmtpDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses Windows, SysUtils, clEncoder, clUtils, clCryptUtils, clSocket, clSspiAuth, clTcpClient{$IFDEF DEMO}, Forms, clCert{$ENDIF}; { TclCustomSmtp } constructor TclCustomSmtp.Create(AOwner: TComponent); begin inherited Create(AOwner); FMailFrom := ''; FUseEHLO := True; FMailToList := TStringList.Create(); TStringList(FMailToList).OnChange := DoStringsChanged; FMailData := TStringList.Create(); TStringList(FMailData).OnChange := DoStringsChanged; FExtensions := TStringList.Create(); FAuthMechanisms := TStringList.Create(); Port := cDefaultSmtpPort; FMailAgent := cMailAgent; end; procedure TclCustomSmtp.DoStringsChanged(Sender: TObject); begin Changed(); end; function TclCustomSmtp.GetResponseCode(const AResponse: string): Integer; begin if (Pos('-', AResponse) = 4) then begin Result := SOCKET_WAIT_RESPONSE; end else begin Result := StrToIntDef(Copy(AResponse, 1, 3), SOCKET_WAIT_RESPONSE); end; end; procedure TclCustomSmtp.GetExtensions; var i: Integer; Extension: string; begin FExtensions.Clear; for i := 1 to Response.Count - 1 do begin Extension := Response[i]; if (Pos('-', Extension) = 4) or (Pos(' ', Extension) = 4) then begin Extension := Copy(Extension, 5, MaxInt); FExtensions.Add(Extension); end; end; end; function TclCustomSmtp.GetAuthExtension: string; var I: Integer; Extension: string; begin for I := 0 to FExtensions.Count - 1 do begin Extension := FExtensions[I]; if (Pos('AUTH', Extension) = 1) then begin Result := Copy(Extension, 6, MaxInt); Exit; end; end; Result := ''; end; procedure TclCustomSmtp.GetAuthMechanisms(const AuthExtension: string); var I: Integer; AuthMechanism: string; begin FAuthMechanisms.Clear; for I := 1 to WordCount(AuthExtension, [' ']) do begin AuthMechanism := ExtractWord(I, AuthExtension, [' ']); FAuthMechanisms.Add(AuthMechanism); end; end; procedure TclCustomSmtp.SetMailToList(AValue: TStrings); begin FMailToList.Assign(AValue); end; procedure TclCustomSmtp.SetMailData(AValue: TStrings); begin FMailData.Assign(AValue); end; procedure TclCustomSmtp.HELO(const AOkResponses: array of Integer); begin FExtensions.Clear(); FAuthMechanisms.Clear(); SendCommandSync('HELO %s', AOkResponses, [GetLocalHost()]); end; procedure TclCustomSmtp.MAIL; var name, email: string; begin GetEmailAddressParts(FMailFrom, name, email); SendCommandSync('MAIL FROM: <%s>', [250], [email]); end; procedure TclCustomSmtp.RCPT(AMailToList: TStrings); var i: Integer; name, email: string; begin if (AMailToList.Count = 0) then begin RaiseSocketError(cSMTPErrorRcptListEmpty, -1); end; i := 0; while (i < AMailToList.Count) do begin GetEmailAddressParts(AMailToList[i], name, email); SendCommandSync('RCPT TO: <%s>', [250], [email]); Inc(i); end; end; procedure TclCustomSmtp.DATA(AMailData: TStrings); begin if (AMailData.Count = 0) then begin RaiseSocketError(cSMTPErrorDataListEmpty, -1); end; SendCommandSync('DATA', [354]); SendMultipleLines(AMailData); SendCommandSync('.', [250]); end; procedure TclCustomSmtp.QUIT; begin try SendCommandSync('QUIT', [221]); except on EclSocketError do ; end; end; procedure TclCustomSmtp.EHLO(const AOkResponses: array of Integer); begin SendCommandSync('EHLO %s', AOkResponses, [GetLocalHost()]); GetExtensions(); GetAuthMechanisms(GetAuthExtension()); end; procedure TclCustomSmtp.NtlmAuthenticate; var sspi: TclNtAuthClientSspi; encoder: TclEncoder; buf: TStream; authIdentity: TclAuthIdentity; challenge: string; begin SendCommandSync('AUTH NTLM', [334]); sspi := nil; encoder := nil; buf := nil; authIdentity := nil; try sspi := TclNtAuthClientSspi.Create(); encoder := TclEncoder.Create(nil); encoder.SuppressCrlf := True; buf := TMemoryStream.Create(); if (UserName <> '') then begin authIdentity := TclAuthIdentity.Create(UserName, Password); end; while not sspi.GenChallenge('NTLM', buf, Server, authIdentity) do begin buf.Position := 0; encoder.EncodeToString(buf, challenge, cmMIMEBase64); SendCommandSync(challenge, [334]); challenge := system.Copy(Response.Text, Length('334 ') + 1, MaxInt); buf.Size := 0; encoder.DecodeFromString(challenge, buf, cmMIMEBase64); buf.Position := 0; end; if (buf.Size > 0) then begin buf.Position := 0; encoder.EncodeToString(buf, challenge, cmMIMEBase64); SendCommandSync(challenge, [235]); end; finally authIdentity.Free(); buf.Free(); encoder.Free(); sspi.Free(); end; end; procedure TclCustomSmtp.CramMD5Authenticate; var respLine, DecodedResponse: string; Encoder: TclEncoder; begin Encoder := TclEncoder.Create(nil); try Encoder.SuppressCrlf := True; SendCommandSync('AUTH %s', [334], ['CRAM-MD5']); respLine := Trim(Response.Text); respLine := Copy(respLine, 5, MaxInt); Encoder.DecodeString(respLine, DecodedResponse, cmMIMEBase64); DecodedResponse := HMAC_MD5(DecodedResponse, PassWord); DecodedResponse := UserName + ' ' + DecodedResponse; Encoder.EncodeString(DecodedResponse, respLine, cmMIMEBase64); SendCommandSync(respLine, [235]); finally Encoder.Free(); end; end; procedure TclCustomSmtp.LoginAuthenticate; var EncodedUserName: string; EncodedPassWord: string; Encoder: TclEncoder; begin Encoder := TclEncoder.Create(nil); try Encoder.SuppressCrlf := True; SendCommandSync('AUTH %s', [334], ['LOGIN']); Encoder.EncodeString(UserName, EncodedUserName, cmMIMEBase64); SendCommandSync(EncodedUserName, [334]); Encoder.EncodeString(PassWord, EncodedPassWord, cmMIMEBase64); SendCommandSync(EncodedPassWord, [235]); finally Encoder.Free(); end; end; procedure TclCustomSmtp.AUTH; begin if (UserName = '') and (Password = '') then Exit; if UseSPA then begin if FindInStrings(AuthMechanisms, 'NTLM') > -1 then begin NtlmAuthenticate(); end else if FindInStrings(AuthMechanisms, 'CRAM-MD5') > -1 then begin CramMD5Authenticate(); end else begin LoginAuthenticate(); end; end else begin LoginAuthenticate(); end; end; procedure TclCustomSmtp.OpenSession; function IsExplicitTls: Boolean; begin Result := ((UseTLS = ctAutomatic) and (Port = GetDefaultPort())) or (UseTLS = ctExplicit); end; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsSmtpDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsMailMessageDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsSmtpDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsCertDemoDisplayed := True; IsMailMessageDemoDisplayed := True; {$ENDIF} end; {$ENDIF} WaitingResponse([220]); if UseEHLO then begin EHLO([250, 530]); ExplicitStartTls(); if IsExplicitTls() then begin EHLO([250]); end; AUTH(); end else begin HELO([250, 530]); ExplicitStartTls(); if IsExplicitTls() then begin HELO([250]); end; end; end; procedure TclCustomSmtp.CloseSession; begin QUIT(); end; procedure TclCustomSmtp.SetMailFrom(const Value: string); begin if (FMailFrom <> Value) then begin FMailFrom := Value; Changed(); end; end; procedure TclCustomSmtp.RemoveBcc(AMailData: TStrings); var FieldList: TStrings; begin FieldList := TStringList.Create(); try GetHeaderFieldList(0, AMailData, FieldList); RemoveHeaderField(AMailData, FieldList, 'bcc'); finally FieldList.Free(); end; end; procedure TclCustomSmtp.InternalSend(AMailData, AMailToList: TStrings); begin InsertHeaderFieldIfNeed(AMailData, 'X-Mailer', MailAgent); InsertHeaderFieldIfNeed(AMailData, 'Message-ID', GenMessageID()); RemoveBcc(AMailData); MAIL(); RCPT(AMailToList); DATA(AMailData); end; procedure TclCustomSmtp.Reset; begin SendCommandSync('RSET', [250]); end; procedure TclCustomSmtp.SetUseEHLO(const Value: Boolean); begin if (FUseEHLO <> Value) then begin FUseEHLO := Value; Changed(); end; end; procedure TclCustomSmtp.Send; begin Send(MailMessage); end; procedure TclCustomSmtp.Send(AMessage: TclMailMessage); var rcpt: TStrings; begin rcpt := TStringList.Create(); try if (AMessage <> nil) then begin if (AMessage.From <> '') then begin MailFrom := AMessage.From; end; rcpt.Assign(MailToList); rcpt.AddStrings(AMessage.ToList); rcpt.AddStrings(AMessage.CCList); rcpt.AddStrings(AMessage.BCCList); InternalSend(AMessage.MessageSource, rcpt); end else begin rcpt.Assign(MailToList); InternalSend(MailData, rcpt); end; finally rcpt.Free(); end; end; procedure TclCustomSmtp.DoDestroy; begin FMailToList.Free(); FMailData.Free(); FExtensions.Free(); FAuthMechanisms.Free(); inherited DoDestroy(); end; function TclCustomSmtp.GenMessageID: string; begin Result := GenerateMessageID(); end; procedure TclCustomSmtp.StartTls; begin SendCommandSync('STARTTLS', [220]); inherited StartTls(); end; function TclCustomSmtp.GetDefaultPort: Integer; begin Result := cDefaultSmtpPort; end; procedure TclCustomSmtp.SetMailAgent(const Value: string); begin if (FMailAgent <> Value) then begin FMailAgent := Value; Changed(); end; end; procedure TclCustomSmtp.Send(AMessage: TStrings); var rcpt: TStrings; msg: TclMailMessage; begin rcpt := nil; msg := nil; try rcpt := TStringList.Create(); msg := TclMailMessage.Create(nil); msg.HeaderSource := AMessage; if (msg.From <> '') then begin MailFrom := msg.From; end; rcpt.Assign(MailToList); rcpt.AddStrings(msg.ToList); rcpt.AddStrings(msg.CCList); rcpt.AddStrings(msg.BCCList); InternalSend(AMessage, rcpt); finally msg.Free(); rcpt.Free(); end; end; end.
unit fx1Value; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Clipbrd, uGlobal; type Tfx1ValueForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Editfx1: TEdit; ListBox1: TListBox; RecalcBtn: TBitBtn; CloseBtn: TBitBtn; procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormDestroy(Sender: TObject); procedure Editfx1KeyPress(Sender: TObject; var Key: Char); procedure Editfx1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure RecalcBtnClick(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure ListBox1Click(Sender: TObject); public DisplayOK: Boolean; fx1ValueToFind: extended; procedure ShowData; end; var fx1ValueForm: Tfx1ValueForm; //====================================================================== implementation //====================================================================== uses fMain, fFuncts; {$R *.dfm} procedure Tfx1ValueForm.FormShow(Sender: TObject); begin ShowData; end; procedure Tfx1ValueForm.FormActivate(Sender: TObject); begin DisplayOK := true; end; procedure Tfx1ValueForm.FormDeactivate(Sender: TObject); begin DisplayOK := false; end; procedure Tfx1ValueForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin with FunctionsForm.fx1Value do begin Checked := false; ImageIndex := 1; end; end; procedure Tfx1ValueForm.FormDestroy(Sender: TObject); var i: integer; begin with ListBox1 do begin for i := 0 to Count -1 do Items.Objects[i].Free; Clear; end; end; procedure Tfx1ValueForm.Editfx1KeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['-', '0'..'9', '.', 'e', 'E', #8]) then Key := #0 end; procedure Tfx1ValueForm.Editfx1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin try fx1ValueToFind := StrToFloat(Editfx1.Text); except fx1ValueToFind := 0; end; end; procedure Tfx1ValueForm.RecalcBtnClick(Sender: TObject); var i: integer; begin with ListBox1 do begin for i := 0 to Count -1 do Items.Objects[i].Free; Clear; end; MainForm.GLViewer.Invalidate; end; procedure Tfx1ValueForm.CloseBtnClick(Sender: TObject); begin Close; end; procedure Tfx1ValueForm.ListBox1Click(Sender: TObject); var w: word; i: integer; begin with ListBox1 do if Count > 0 then begin if FunctionsForm.EditEvaluate.Visible then begin FunctionsForm.EditEvaluate.Text := Trim(Copy(Items[ItemIndex], 1, 24)); for i := 0 to Count -1 do Items.Objects[i].Free; Clear; FunctionsForm.EvaluateKeyUp(Sender, w, []); end else begin Clipboard.Clear; Clipboard.AsText := Trim(Copy(Items[ItemIndex], 1, 24)); end; end; end; procedure Tfx1Valueform.ShowData; var i: integer; begin if GraphData.PlotData.TextStr = '' then Caption := '' else Caption := 'y = '+GraphData.PlotData.TextStr; Editfx1.Text := FloatToStr(fx1ValueToFind); with ListBox1 do begin for i := 0 to Count -1 do Items.Objects[i].Free; Clear; end; MainForm.GLViewer.Invalidate; end; end.
unit Types; interface uses Geometry; type Rocket = record acceleration: Vector; velocity: Vector; position: Vector; oldpos: Vector; current_drill_len, drill_len: double; drilling: boolean; removed: boolean; exp_radius: double; exp_force: double; { Used for player's equipment } name: ansistring; amount: integer; num: integer; end; pRocket = ^Rocket; Equip = array[1..9] of Rocket; ConfigPair = record key: ansistring; value: ansistring; line: integer; end; Operator = (a: ConfigPair; b: ConfigPair) eqpair : boolean; Operator = (a: Rocket; b: Rocket) eqrocket : boolean; procedure new_rocket(var r: Rocket; pos: Vector; vel: Vector; acc: Vector; rad: double; f: double; drill_len: double); implementation Operator = (a: ConfigPair; b: ConfigPair) eqpair : boolean; begin eqpair := (a.key = b.key) and (a.value = b.value); end; { Rocket operators } Operator = (a: Rocket; b: Rocket) eqrocket : boolean; begin eqrocket := a.position = b.position; end; { Rocket functions } procedure new_rocket(var r: Rocket; pos: Vector; vel: Vector; acc: Vector; rad: double; f: double; drill_len: double); begin r.oldpos := pos; r.position := pos; r.velocity := vel; r.acceleration := acc; r.removed := False; r.exp_radius := rad; r.exp_force := f; r.drilling := False; r.current_drill_len := 0; r.drill_len := drill_len; end; begin end.
unit MT5.BaseAnswer; interface type TMTAnswerParam = class private FName: string; FValue: string; procedure SetName(const Value: string); procedure SetValue(const Value: string); { private declarations } protected { protected declarations } public { public declarations } constructor Create(AName: string; AValue: string); property Name: string read FName write SetName; property Value: string read FValue write SetValue; end; implementation { TMTAnswerParam } constructor TMTAnswerParam.Create(AName, AValue: string); begin SetName(AName); SetValue(AValue); end; procedure TMTAnswerParam.SetName(const Value: string); begin FName := Value; end; procedure TMTAnswerParam.SetValue(const Value: string); begin FValue := Value; end; end.
unit ActObj; interface uses Classes, SysUtils, Dialogs, Windows, MakeRes; Type TCalculation = (tcArom,tcOctan,tcSingle); TProcess = (tpNormal,tpBenzene); TActivObj = class(TObject) private ExeFile, File_dan, File_rez, File_sk, WorkPath, DataPath: String; OktE: double; Res: ResT; CalcType: TCalculation; ProcType: TProcess; RefreshFlag, FineCalcFlag: boolean; function Prepare:boolean; public property ProcessName: String read ExeFile write ExeFile; property DanFile: String read File_dan write File_dan; property RezFile: String read File_rez write File_rez; property SkFile: String read File_sk write File_sk; property ExperimentalOctan: double read OktE write OktE; property TypeOfCalculation: TCalculation read CalcType write CalcType; property TypeOfProcess: TProcess read ProcType write ProcType; property RefreshDanFile: boolean read RefreshFlag write RefreshFlag; property CalcComplited: boolean read FineCalcFlag; property Results: ResT read Res; constructor Create; destructor Destroy; procedure Calculation; function BakupFile(Name: string): string; function UnBakupFile(Name: string): string; end; implementation Uses Unit1, Unit4, Unit5, Unit8; constructor TActivObj.Create; begin inherited Create; FineCalcFlag:=False; ExeFile:=''; File_dan:=''; File_sk:=''; File_rez:=''; CalcType:=tcArom; ProcType:=tpNormal; RefreshFlag:=True; end; destructor TActivObj.Destroy; begin inherited Destroy; end; function TActivObj.BakupFile(Name: string): string; begin BakupFile:=WorkPath+ExtractFileName(ChangeFileExt(Name,'.bak')); end; function TActivObj.Prepare:boolean; var Buf:TMemoryStream; F:TFileStream; begin Result:=false; If fileExists(ExeFile) and fileExists(File_dan) and fileExists(File_sk) then begin WorkPath:=ExtractFilePath(ExeFile); DataPath:=ExtractFilePath(File_Dan); Buf:=TMemoryStream.create; Buf.LoadFromFile(File_dan); f:=TFileStream.create(WorkPath+'dan.bak',fmCreate or fmShareDenyNone); Buf.SaveToStream(f); f.free; buf.clear; buf.LoadFromFile(File_sk); f:=TFileStream.create(WorkPath+'sirkat',fmCreate or fmShareDenyNone); Buf.SaveToStream(f); f.free; buf.free; result:=true; end; end; function TActivObj.UnBakupFile(Name: string): string; begin UnBakupFile:=DataPath+ExtractFileName(ChangeFileExt(Name,'.dan')); end; procedure TActivObj.Calculation; Var i: integer; Si: TStartupInfo; p: TProcessInformation; Buf:TMemoryStream; Fs:TFileStream; WorkStr:TStringList; Ce,Cr,CLKat1,OktR,c: double; FAkt,FCl,DoCl,SingleFlag: Boolean; Dan: TDanFile; a:double; b:double; ACl:double; BCl:double; // Res:ResT; begin FineCalcFlag:=False; If Prepare then Begin { Вызываем программу расчета риформинга с резервным файлом BAK } If FileExists(File_Rez) then SysUtils.DeleteFile(File_Rez); DoCl:=false; FillChar( Si, SizeOf( Si ) , 0 ); with Si do begin cb := SizeOf( Si); dwFlags := startf_UseShowWindow; wShowWindow := SW_hide ; end; Repeat CreateProcess(nil,StrPCopy(ComL,ExeFile+' '+ {WorkPath+}'dan.bak'),nil,nil, false,Create_default_error_mode,nil, StrPCopy(DirL,WorkPath),si,p); if WaitForSingleObject(p.hProcess,2000)=WAIT_TIMEOUT then TerminateProcess(p.hProcess,0); if ProcType=tpBenzene then begin WorkStr:=TStringList.Create; WorkStr.LoadFromFile(WorkPath+'rez'); WorkStr.Insert(22,''); WorkStr.Insert(23,''); WorkStr.Insert(62,''); WorkStr.Insert(63,''); WorkStr.SaveToFile(WorkPath+'rez'); WorkStr.Free; end; Res:=MakeRes.MakeResFile(WorkPath+'rez'); Cr:=Res.Arom[1,11]; Ce:=Res.Arom[2,11]; OktR:=Res.Ochi; ClKat1:=Res.ClKat[1]; SingleFlag:=False; ReadDan(Dan,WorkPath+'dan.bak'); DiClor1:=Dan.DiClor[1]; Akt:=Dan.Akt; Case CalcType of tcArom: Begin FAkt:=abs(Ce-Cr)<=0.051; FCl:=(abs(ClKat1-1)<=0.01); If (not Fakt) and (not DoCl)then begin If a=b then If Cr<Ce then begin a:=-50; b:=akt; end else begin a:=akt; b:=100; end else If Cr<Ce then b:=c else a:=c; c:=(A+B)/2; akt:=c; ACl:=0.1; BCl:=20; end; If (FAkt or DoCl) and (not FCl) then begin If ClKat1>1 then BCl:=DiClor1 else ACl:=DiClor1; If not DoCl then begin a:=0; b:=0; end; DoCl:=True; DiClor1:=(ACl+BCl)/2; end else DoCl:=false; end; tcOctan: Begin FAkt:=abs(OktE-OktR)<=0.051; FCl:=(abs(ClKat1-1)<=0.01); If (not Fakt) and (not DoCl)then begin If a=b then If OktR<OktE then begin a:=-50; b:=akt; end else begin a:=akt; b:=100; end else If OktR<OktE then b:=c else a:=c; c:=(A+B)/2; akt:=c; ACl:=0.1; BCl:=20; end; If (FAkt or DoCl) and (not FCl) then begin If ClKat1>1 then BCl:=DiClor1 else ACl:=DiClor1; If not DoCl then begin a:=0; b:=0; end; DoCl:=True; DiClor1:=(ACl+BCl)/2; end else DoCl:=false; end; tcSingle: SingleFlag:=True; end; Dan.Akt:=Akt; for i:=1 to 6 do Dan.DiClor[i]:=DiClor1; WriteDan(Dan,WorkPath+'dan.bak'); If Form5.ProgressBar1.Position=100 then Form5.ProgressBar1.Position:=0; Form5.ProgressBar1.Position:=Form5.ProgressBar1.Position+1; Until (FAkt and FCl) or SingleFlag; If FileExists(File_Rez) then sysutils.DeleteFile(File_Rez); Buf:=TMemoryStream.create; Buf.LoadFromFile(WorkPath+'rez'); Fs:=TFileStream.create(File_Rez,fmCreate or fmShareDenyNone); Buf.SaveToStream(Fs); Fs.free; buf.Free; {Добавление в файл с данными *.DAN изменений по добавке хлорорганики и активности} If RefreshFlag=True then WriteDan(Dan,File_Dan); FineCalcFlag:=True; end; end; end.
{------------------------------------------------------------------------------- Copyright 2012-2021 Ethea S.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------} /// <summary> /// Basic logging services. /// </summary> unit EF.Logger; {$I EF.Defines.inc} interface uses SysUtils, Types, Classes, SyncObjs, EF.ObserverIntf, EF.Tree, EF.Macros; type TEFLogger = class(TEFSubjectAndObserver) private FCriticalSection: TCriticalSection; FLogLevel: Integer; FConfig: TEFNode; FMacroExpansionEngine: TEFMacroExpansionEngine; class var FInstance: TEFLogger; protected procedure EnterCS; procedure LeaveCS; procedure Sync(AProc: TProc); public class constructor Create; class destructor Destroy; procedure AfterConstruction; override; destructor Destroy; override; public const LOG_LOW = 1; const LOG_MEDIUM = 2; const LOG_HIGH = 3; const LOG_DETAILED = 4; const LOG_DEBUG = 5; const DEFAULT_LOG_LEVEL = LOG_LOW; procedure Configure(const AConfig: TEFNode; const AMacroExpansionEngine: TEFMacroExpansionEngine); property LogLevel: Integer read FLogLevel write FLogLevel; procedure Log(const AString: string; const ALogLevel: Integer = DEFAULT_LOG_LEVEL); procedure LogStrings(const ATitle: string; const AStrings: TStrings; const ALogLevel: Integer = DEFAULT_LOG_LEVEL); procedure LogFmt(const AString: string; const AParams: array of const; const ALogLevel: Integer = DEFAULT_LOG_LEVEL); class property Instance: TEFLogger read FInstance; end; TEFLogEndpoint = class(TEFSubjectAndObserver) strict private FIsEnabled: Boolean; strict protected function GetConfigPath: string; virtual; procedure Configure(const AConfig: TEFNode; const AMacroExpansionEngine: TEFMacroExpansionEngine); virtual; procedure DoLog(const AString: string); virtual; abstract; property IsEnabled: Boolean read FIsEnabled; public procedure AfterConstruction; override; destructor Destroy; override; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); override; end; implementation { TEFLogger } procedure TEFLogger.AfterConstruction; begin inherited; FCriticalSection := TCriticalSection.Create; FLogLevel := DEFAULT_LOG_LEVEL; end; class constructor TEFLogger.Create; begin FInstance := TEFLogger.Create; end; class destructor TEFLogger.Destroy; begin FreeAndNil(FInstance); end; destructor TEFLogger.Destroy; begin FreeAndNil(FCriticalSection); inherited; end; procedure TEFLogger.EnterCS; begin FCriticalSection.Enter; end; procedure TEFLogger.LeaveCS; begin FCriticalSection.Leave; end; procedure TEFLogger.Log(const AString: string; const ALogLevel: Integer); begin Sync( procedure begin if FLogLevel >= ALogLevel then NotifyObservers(AString); end); end; procedure TEFLogger.LogFmt(const AString: string; const AParams: array of const; const ALogLevel: Integer); begin Log(Format(AString, AParams), ALogLevel); end; procedure TEFLogger.LogStrings(const ATitle: string; const AStrings: TStrings; const ALogLevel: Integer); begin Assert(Assigned(AStrings)); Log(ATitle, ALogLevel); Log(AStrings.Text, ALogLevel); end; procedure TEFLogger.Configure(const AConfig: TEFNode; const AMacroExpansionEngine: TEFMacroExpansionEngine); begin if Assigned(AConfig) then LogLevel := AConfig.GetInteger('Level', LogLevel); try FConfig := AConfig; FMacroExpansionEngine := AMacroExpansionEngine; NotifyObservers('{ConfigChanged}'); finally FConfig := nil; FMacroExpansionEngine := nil; end; end; procedure TEFLogger.Sync(AProc: TProc); begin EnterCS; try AProc; finally LeaveCS; end; end; { TEFLogEndpoint } procedure TEFLogEndpoint.AfterConstruction; begin inherited; TEFLogger.Instance.AttachObserver(Self); end; procedure TEFLogEndpoint.Configure(const AConfig: TEFNode; const AMacroExpansionEngine: TEFMacroExpansionEngine); begin FIsEnabled := False; if Assigned(AConfig) then FIsEnabled := AConfig.GetBoolean(GetConfigPath + 'IsEnabled', FIsEnabled); end; function TEFLogEndpoint.GetConfigPath: string; begin Result := ''; end; destructor TEFLogEndpoint.Destroy; begin TEFLogger.Instance.DetachObserver(Self); inherited; end; procedure TEFLogEndpoint.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin inherited; if SameText(AContext, '{ConfigChanged}') then Configure(TEFLogger(ASubject.AsObject).FConfig, TEFLogger(ASubject.AsObject).FMacroExpansionEngine) else begin //prevent logging of password if pos('PASSWORD', UpperCase(AContext)) = 0 then DoLog(AContext); end; end; end.
unit u_ast_expression; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_tokens, u_ast, u_ast_blocks, u_ast_expression_blocks; type TMashASTExpression = class(TMashBaseAST) public stk: TList; TreeNode: TMashASTBlock; constructor Create(_tokens: TList); destructor Destroy; procedure Process; private function NextPrimitive(var token_id: cardinal): TMashASTBlock; procedure NextBraces(var token_id: cardinal; list: TList); procedure NextRectBraces(var token_id: cardinal; list: TList); function MakeEnum(list: TList): TMashASTP_Enum; procedure PrepareNodes; function MakeTree(Left, Right: cardinal): TMashASTBlock; end; implementation constructor TMashASTExpression.Create(_tokens: TList); begin inherited Create(_tokens); self.stk := TList.Create; self.TreeNode := nil; end; destructor TMashASTExpression.Destroy; begin FreeAndNil(stk); inherited; end; procedure TMashASTExpression.Process; var token_id: cardinal; prim: TMashASTBlock; begin token_id := 0; while token_id < self.tokens.count do begin prim := self.NextPrimitive(token_id); if prim <> nil then self.Nodes.add(prim); Inc(token_id); end; self.PrepareNodes; self.TreeNode := self.MakeTree(0, self.nodes.count - 1); end; // Making tree function TMashASTExpression.MakeTree(Left, Right: cardinal): TMashASTBlock; var op, t: TMashASTBlock; op_index: cardinal; lvl: byte; begin Result := nil; op := nil; if Right - Left = 0 then Result := TMashASTBlock(self.nodes[Left]) else if Right > Left then begin lvl := 0; while (op = nil) and (lvl < 7) do begin op_index := Right - 1; while op_index > Left do begin t := TMashASTBlock(self.nodes[op_index]); if t.GetType = btPOperator then if TMashASTP_Operator(t).Op.short in MashOperationsPriority[lvl] then begin op := t; break; end; Dec(op_index); end; Inc(lvl); end; end; if op <> nil then Result := TMashASTE_OperationLR.Create( TMashASTP_Operator(op), self.MakeTree(Left, op_index - 1), self.MakeTree(op_index + 1, Right) ); if Result = nil then raise Exception.Create( 'Invalid expression at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); end; procedure TMashASTExpression.PrepareNodes; var i: integer; n: TMashASTBlock; founded: boolean; begin // Checking for <op> R i := self.nodes.count - 1; while (self.nodes.count > 1) and (i >= 0) do begin n := TMashASTBlock(self.nodes[i]); if n.GetType = btPOperator then if TMashASTP_Operator(n).Op.short in MashOperationLeft then begin founded := i = 0; if not founded then founded := TMashASTBlock(self.nodes[i - 1]).GetType = btPOperator; if founded then begin nodes.items[i] := TMashASTE_Operation.Create( TMashASTP_Operator(n), TMashASTBlock(TMashASTBlock(nodes[i + 1])) ); self.nodes.delete(i + 1); Inc(i); end end; Dec(i); end; // Checking for L <op> i := 1; while (self.nodes.count > 1) and (i < self.nodes.count) do begin n := TMashASTBlock(self.nodes[i]); if n.GetType = btPOperator then if TMashASTP_Operator(n).Op.short in MashOperationRight then begin founded := i + 1 = self.nodes.count; if not founded then founded := TMashASTBlock(self.nodes[i + 1]).GetType = btPOperator; if founded then begin nodes.items[i] := TMashASTE_Operation.Create( TMashASTP_Operator(n), TMashASTBlock(TMashASTBlock(nodes[i - 1])) ); self.nodes.delete(i - 1); Dec(i); end end; Inc(i); end; end; // Breaking nodes for primitives function TMashASTExpression.NextPrimitive(var token_id: cardinal): TMashASTBlock; var tk: TMashToken; lst: TList; Obj: TMashASTBlock; begin tk := self.NextToken(token_id); self.lastTk := tk; if (tk.info in [ttDigit, ttString, ttWord]) or (tk.short = tkNew) then begin Result := nil; while true do begin if (self.TkCheckID(self.Token(token_id + 1)) = tkByPtr) and (tk.info = ttWord) then begin if Result = nil then begin Result := TMashASTP_Reference.Create; TMashASTP_Reference(Result).ObjPath.add( TMashASTP_SimpleObject.Create(tk) ); end else begin Obj := TMashASTP_Reference.Create; TMashASTP_Reference(Obj).ObjPath.add(Result); Result := Obj; end; while (self.TkCheckID(self.Token(token_id + 1)) = tkByPtr) and (self.TkCheckType(self.Token(token_id + 2)) = ttWord) do begin token_id := token_id + 2; self.lastTk := tk; tk := self.NextToken(token_id); tk.value := 'vtable__' + tk.value; TMashASTP_Reference(Result).ObjPath.add( TMashASTP_SimpleObject.Create(tk) ); end; self.lastTk := tk; if self.TkCheckID(self.Token(token_id + 1)) = tkByPtr then raise Exception.Create( 'Invalid token after -> at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + '''.' ); end; if Result = nil then begin if tk.short = tkNew then begin if self.TkCheckID(self.Token(token_id + 1)) = tkORBr then Result := TMashASTP_SimpleObject.Create(tk) else Result := TMashASTP_Operator.Create(tk); end else Result := TMashASTP_SimpleObject.Create(tk); end; if self.TkCheckID(self.Token(token_id + 1)) = tkOBr then begin Inc(token_id); lst := TList.Create; self.NextBraces(token_id, lst); Obj := TMashASTP_Call.Create(Result, self.MakeEnum(lst)); Result := Obj; FreeAndNil(lst); end; if self.TkCheckID(self.Token(token_id + 1)) = tkORBr then begin Inc(token_id); Obj := TMashASTP_IndexedObject.Create(Result); Result := Obj; while true do begin Obj := TMashASTB_Expression.Create; self.NextRectBraces(token_id, TMashASTB_Expression(Obj).tokens); TMashASTExpression(TMashASTB_Expression(Obj).ast).Process; TMashASTP_IndexedObject(Result).Indexes.add(Obj); if self.TkCheckID(self.Token(token_id + 1)) = tkORBr then Inc(token_id) else break; end; end; if not (self.TkCheckID(self.Token(token_id + 1)) in [tkByPtr, tkOBr, tkORBr]) then break; end; end else if tk.info = ttToken then case tk.short of tkOBr: begin Result := TMashASTB_Expression.Create; self.NextBraces(token_id, TMashASTB_Expression(Result).tokens); TMashASTExpression(TMashASTB_Expression(Result).ast).Process; end; tkORBr: begin lst := TList.Create; self.NextRectBraces(token_id, lst); Result := self.MakeEnum(lst); FreeAndNil(lst); end; else Result := TMashASTP_Operator.Create(tk); end; end; procedure TMashASTExpression.NextBraces(var token_id: cardinal; list: TList); var brace_cnt: integer; tk: TMashToken; begin brace_cnt := 1; while brace_cnt > 0 do begin Inc(token_id); tk := self.NextToken(token_id); if tk = nil then raise Exception.Create('Unexpected end of code.'); case tk.short of tkOBr: Inc(brace_cnt); tkCBr: Dec(brace_cnt); end; if brace_cnt > 0 then list.add(tk); end; end; procedure TMashASTExpression.NextRectBraces(var token_id: cardinal; list: TList); var brace_cnt: integer; tk: TMashToken; begin brace_cnt := 1; while brace_cnt > 0 do begin Inc(token_id); tk := self.NextToken(token_id); if tk = nil then raise Exception.Create('Unexpected end of code.'); case tk.short of tkORBr: Inc(brace_cnt); tkCRBr: Dec(brace_cnt); end; if brace_cnt > 0 then list.add(tk); end; end; function TMashASTExpression.MakeEnum(list: TList): TMashASTP_Enum; var br_cnt, rbr_cnt: integer; c: cardinal; tk: TMashToken; Expr: TMashASTB_Expression; begin br_cnt := 0; rbr_cnt := 0; Result := TMashASTP_Enum.Create; Expr := TMashASTB_Expression.Create; c := 0; while c < list.count do begin tk := TMashToken(list[c]); case tk.short of tkOBr: begin Inc(br_cnt); Expr.tokens.add(tk); end; tkCBr: begin Dec(br_cnt); Expr.tokens.add(tk); end; tkORBr: begin Inc(rbr_cnt); Expr.tokens.add(tk); end; tkCRBr: begin Dec(rbr_cnt); Expr.tokens.add(tk); end; tkComma: if (br_cnt = 0) and (rbr_cnt = 0) then begin Result.objects.add(Expr); TMashASTExpression(Expr.ast).Process; Expr := TMashASTB_Expression.Create; end else Expr.tokens.add(tk); else Expr.tokens.add(tk); end; Inc(c); end; if Expr.tokens.count > 0 then begin Result.objects.add(Expr); TMashASTExpression(Expr.ast).Process; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.TreeView, FMX.ScrollBox, FMX.Memo, FMX.Objects; type TForm1 = class(TForm) TreeView1: TTreeView; Button1: TButton; Memo1: TMemo; Rectangle1: TRectangle; procedure Button1Click(Sender: TObject); procedure TreeView1Click(Sender: TObject); procedure TreeView1DragChange(SourceItem, DestItem: TTreeViewItem; var Allow: Boolean); procedure TreeView1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); procedure TreeView1DragEnd(Sender: TObject); procedure TreeView1DragEnter(Sender: TObject; const Data: TDragObject; const Point: TPointF); procedure TreeView1DragLeave(Sender: TObject); procedure TreeView1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); procedure TreeViewItemDragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); private { Déclarations privées } ItemNumber: integer; procedure generate_datas(node: TTreeViewItem = nil; profondeur: integer = 1); procedure affiche(text: string); public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.fmx} var previous: string = ''; procedure TForm1.affiche(text: string); begin if (previous <> text) then begin Memo1.lines.add(text); Memo1.GoToTextEnd; previous := text; end; end; procedure TForm1.Button1Click(Sender: TObject); begin ItemNumber := 0; generate_datas(nil, 5); end; procedure TForm1.generate_datas(node: TTreeViewItem; profondeur: integer); var item: TTreeViewItem; i, nb: integer; begin if (profondeur > 0) then begin nb := random(10); for i := 0 to nb do begin inc(ItemNumber); item := TTreeViewItem.Create(Self); item.text := 'Item : ' + ItemNumber.ToString; item.OnDragDrop := TreeViewItemDragDrop; if assigned(node) then node.AddObject(item) else TreeView1.AddObject(item); generate_datas(item, profondeur - 1); end; end; end; procedure TForm1.TreeView1Click(Sender: TObject); begin if (TreeView1.Selected.IsExpanded) then TreeView1.Selected.collapse else if TreeView1.Selected.Count > 0 then TreeView1.Selected.expand; end; procedure TForm1.TreeView1DragChange(SourceItem, DestItem: TTreeViewItem; var Allow: Boolean); begin affiche('TreeView1DragChange'); Allow := true; end; procedure TForm1.TreeView1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); begin affiche('TreeView1DragDrop'); end; procedure TForm1.TreeView1DragEnd(Sender: TObject); begin affiche('TreeView1DragEnd'); end; procedure TForm1.TreeView1DragEnter(Sender: TObject; const Data: TDragObject; const Point: TPointF); begin affiche('TreeView1DragEnter'); end; procedure TForm1.TreeView1DragLeave(Sender: TObject); begin affiche('TreeView1DragLeave'); end; procedure TForm1.TreeView1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); begin affiche('TreeView1DragOver'); Operation := TDragOperation.Move; end; procedure TForm1.TreeViewItemDragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); begin if Sender is TTreeViewItem then affiche('TreeViewItemDragDrop : ' + (Sender as TTreeViewItem).text); end; end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 1995, 2001 Borland Software Corporation } { } { Русификация: 2001-02 Polaris Software } { http://polesoft.da.ru } { *************************************************************************** } unit RTLConsts; interface resourcestring SAncestorNotFound = 'Предок для ''%s'' не найден'; SAssignError = 'Не могу значение %s присвоить %s'; SBitsIndexError = 'Индекс Bits вышел за границы'; SBucketListLocked = 'Список заблокирован при активном ForEach'; SCantWriteResourceStreamError = 'Не могу записывать в поток ресурсов "только для чтения"'; SCharExpected = 'Ожидается ''''%s'''''; SCheckSynchronizeError = 'CheckSynchronize вызван из потока (thread) $%x, который НЕ является основным потоком'; SClassNotFound = 'Класс %s не найден'; SDelimiterQuoteCharError = 'Свойства Delimiter и QuoteChar не могут иметь одно и то же значение'; SDuplicateClass = 'Класс с именем %s уже существует'; SDuplicateItem = 'Список не допускает дубликатов ($0%x)'; SDuplicateName = 'Компонент с именем %s уже существует'; SDuplicateString = 'Список строк не допускает дубликатов'; SFCreateError = 'Не могу создать файл %s'; {$IFNDEF VER140} SFCreateErrorEx = 'Не могу создать файл "%s". %s'; {$ENDIF} SFixedColTooBig = 'Число фиксированных столбцов должно быть меньше общего числа столбцов'; SFixedRowTooBig = 'Число фиксированных строк должно быть меньше общего числа строк'; SFOpenError = 'Не могу открыть файл %s'; {$IFNDEF VER140} SFOpenErrorEx = 'Не могу открыть файл "%s". %s'; {$ENDIF} SGridTooLarge = 'Таблица (Grid) слишком большая для работы'; SIdentifierExpected = 'Ожидается идентификатор'; SIndexOutOfRange = 'Индекс Grid вышел за границы'; SIniFileWriteError = 'Не могу записать в %s'; SInvalidActionCreation = 'Неверное создание действия (action)'; SInvalidActionEnumeration = 'Неверный перечень действий (action)'; SInvalidActionRegistration = 'Неверная регистрация действия (action)'; SInvalidActionUnregistration = 'Неверная отмена регистрации действия (action)'; SInvalidBinary = 'Неверное двоичное значение'; SInvalidDate = '''''%s'''' - неверная дата' {$IFNDEF VER140}deprecated{$ENDIF}; SInvalidDateTime = '''''%s'''' - неверные дата и время' {$IFNDEF VER140}deprecated{$ENDIF}; SInvalidFileName = 'Неверное имя файла - %s'; SInvalidImage = 'Неверный формат потока'; SInvalidInteger = '''''%s'''' - неверное целое число' {$IFNDEF VER140}deprecated{$ENDIF}; SInvalidMask = '''%s'' - неверная маска в позиции %d'; SInvalidName = '''''%s'''' недопустимо в качестве имени компонента'; SInvalidProperty = 'Неверное значение свойства'; SInvalidPropertyElement = 'Неверный элемент свойства: %s'; SInvalidPropertyPath = 'Неверный путь к свойству'; SInvalidPropertyType = 'Неверный тип свойства: %s'; SInvalidPropertyValue = 'Неверное значение свойства'; SInvalidRegType = 'Неверный тип данных для ''%s'''; SInvalidString = 'Неверная строковая константа'; SInvalidStringGridOp = 'Не могу вставить или удалить строки из таблицы (grid)'; SInvalidTime = '''''%s'''' - неверное время' {$IFNDEF VER140}deprecated{$ENDIF}; SItemNotFound = 'Пункт не найден ($0%x)'; SLineTooLong = 'Строка слишком длинная'; SListCapacityError = 'Размер списка вышел за границы (%d)'; SListCountError = 'Счетчик списка вышел за границы (%d)'; SListIndexError = 'Индекс списка вышел за границы (%d)'; SMaskErr = 'Введено неверное значение'; SMaskEditErr = 'Введено неверное значение. Нажмите Esc для отмены изменений'; SMemoryStreamError = 'Не хватает памяти при расширении memory stream'; SNoComSupport = '%s не зарегистрирован как COM класс'; SNotPrinting = 'Принтер не находится сейчас в состоянии печати'; SNumberExpected = 'Ожидается число'; SParseError = '%s в строке %d'; SComponentNameTooLong = 'Имя компонента ''%s'' превысило предел в 64 символов'; SPropertyException = 'Ошибка чтения %s%s%s: %s'; SPrinting = 'Идет печать...'; SReadError = 'Ошибка чтения потока'; SReadOnlyProperty = 'Свойство только для чтения'; SRegCreateFailed = 'Ошибка создания ключа %s'; SRegGetDataFailed = 'Ошибка чтения значения для ''%s'''; SRegisterError = 'Неверная регистрация компонента'; SRegSetDataFailed = 'Ошибка записи значения для ''%s'''; SResNotFound = 'Ресурс %s не найден'; SSeekNotImplemented = '%s.Seek не выполнено'; SSortedListError = 'Операция недопустима для отсортированного списка строк'; SStringExpected = 'Ожидается строка'; SSymbolExpected = 'Ожидается %s'; STimeEncodeError = 'Неверный аргумент для формирования времени' {$IFNDEF VER140}deprecated{$ENDIF}; STooManyDeleted = 'Удаляется слишком много строк или столбцов'; SUnknownGroup = '%s нет в группе регистрации класса'; SUnknownProperty = 'Свойство %s не существует'; SWriteError = 'Ошибка записи потока'; SStreamSetSize = 'Ошибка установки размера потока (stream size)'; SThreadCreateError = 'Ошибка создания потока (thread): %s'; SThreadError = 'Ошибка потока (thread): %s (%d)'; SInvalidDateDay = '(%d, %d) - неверная пара DateDay'; SInvalidDateWeek = '(%d, %d, %d) - неверное сочетание DateWeek'; SInvalidDateMonthWeek = '(%d, %d, %d, %d) - неверное сочетание DateMonthWeek'; SInvalidDayOfWeekInMonth = '(%d, %d, %d, %d) - неверное сочетание DayOfWeekInMonth'; SInvalidJulianDate = '%f Julian не может быть представлена как DateTime'; SMissingDateTimeField = '?'; SConvIncompatibleTypes2 = 'Несовместимые типы преобразования [%s, %s]'; SConvIncompatibleTypes3 = 'Несовместимые типы преобразования [%s, %s, %s]'; SConvIncompatibleTypes4 = 'Несовместимые типы преобразования [%s - %s, %s - %s]'; SConvUnknownType = 'Неизвестный тип преобразования %s'; SConvDuplicateType = 'Тип преобразования (%s) уже зарегистрирован в %s'; SConvUnknownFamily = 'Неизвестное семейство преобразования %s'; SConvDuplicateFamily = 'Семейство преобразования (%s) уже зарегистрировано'; {$IFNDEF VER140} SConvUnknownDescription = '[$%.8x]' deprecated; // no longer used SConvUnknownDescriptionWithPrefix = '[%s%.8x]'; {$ELSE} SConvUnknownDescription = '[%.8x]'; {$ENDIF} SConvIllegalType = 'Недопустимый тип'; SConvIllegalFamily = 'Недопустимое семейство'; SConvFactorZero = '%s имеет нулевой множитель'; SConvStrParseError = 'Не могу разобрать %s'; SFailedToCallConstructor = 'Потомок TStrings %s вызвал ошибку при вызове inherited constructor'; sWindowsSocketError = 'Ошибка Windows socket: %s (%d), при вызове ''%s'''; sAsyncSocketError = 'Ошибка asynchronous socket %d'; sNoAddress = 'Не определен адрес'; sCannotListenOnOpen = 'Не могу прослушивать открытый socket'; sCannotCreateSocket = 'Не могу создать новый socket'; sSocketAlreadyOpen = 'Socket уже открыт'; sCantChangeWhileActive = 'Не могу изменить значение пока socket активен'; sSocketMustBeBlocking = 'Socket должен быть в режиме блокировки'; sSocketIOError = '%s ошибка %d, %s'; sSocketRead = 'Read'; sSocketWrite = 'Write'; {$IFNDEF VER140} SCmplxCouldNotParseImaginary = 'Не могу распознать мнимую часть'; SCmplxCouldNotParseSymbol = 'Не могу распознать требуемый ''%s'' символ'; SCmplxCouldNotParsePlus = 'Не могу распознать требуемый ''+'' (или ''-'') символ'; SCmplxCouldNotParseReal = 'Не могу распознать действительную часть'; SCmplxUnexpectedEOS = 'Неожиданный конец строки [%s]'; SCmplxUnexpectedChars = 'Неожиданные символы'; SCmplxErrorSuffix = '%s [%s<?>%s]'; hNoSystem = 'Менеджер Справки не установлен.'; hNoTopics = 'Справка на основе тем (topic) не установлена.'; hNoContext = 'Контекстно-зависимая Справка не установлена.'; hNothingFound = 'Не найдено справки для "%s"'; hNoTableOfContents = 'Содержание не найдено.'; { ************************************************************************* } { Distance's family type } SDistanceDescription = 'Расстояние'; { Distance's various conversion types } SMicromicronsDescription = 'Микромикроны'; SAngstromsDescription = 'Ангстремы'; SMillimicronsDescription = 'Миллимикроны'; SMicronsDescription = 'Микроны'; SMillimetersDescription = 'Миллиметры'; SCentimetersDescription = 'Сантиметры'; SDecimetersDescription = 'Дециметры'; SMetersDescription = 'Метры'; SDecametersDescription = 'Декаметры'; SHectometersDescription = 'Гектометры'; SKilometersDescription = 'Километры'; SMegametersDescription = 'Мегаметры'; SGigametersDescription = 'Гигаметры'; SInchesDescription = 'Дюймы'; SFeetDescription = 'Футы'; SYardsDescription = 'Ярды'; SMilesDescription = 'Мили'; SNauticalMilesDescription = 'Морские мили'; SAstronomicalUnitsDescription = 'Астрономические единицы'; SLightYearsDescription = 'Световые годы'; SParsecsDescription = 'Парсеки'; SCubitsDescription = 'Локти'; SFathomsDescription = 'Морские сажени'; SFurlongsDescription = '1/8 мили'; SHandsDescription = 'Руки'; SPacesDescription = 'Шаги'; SRodsDescription = 'Пруты (rods)'; SChainsDescription = 'Мерные цепи'; SLinksDescription = 'Звенья землемерной цепи'; SPicasDescription = 'Пики (picas)'; SPointsDescription = 'Точки'; { ************************************************************************* } { Area's family type } SAreaDescription = 'Площадь'; { Area's various conversion types } SSquareMillimetersDescription = 'Кв. миллиметры'; SSquareCentimetersDescription = 'Кв. сантиметры'; SSquareDecimetersDescription = 'Кв. дециметры'; SSquareMetersDescription = 'Кв. метры'; SSquareDecametersDescription = 'Кв. декаметры'; SSquareHectometersDescription = 'Кв. гектометры'; SSquareKilometersDescription = 'Кв. километры'; SSquareInchesDescription = 'Кв. дюймы'; SSquareFeetDescription = 'Кв. футы'; SSquareYardsDescription = 'Кв. ярды'; SSquareMilesDescription = 'Кв. мили'; SAcresDescription = 'Акры'; SCentaresDescription = 'Сантиары'; SAresDescription = 'Ары'; SHectaresDescription = 'Гектары'; SSquareRodsDescription = 'Кв. пруты (rods)'; { ************************************************************************* } { Volume's family type } SVolumeDescription = 'Объем'; { Volume's various conversion types } SCubicMillimetersDescription = 'Куб. миллиметры'; SCubicCentimetersDescription = 'Куб. сантиметры'; SCubicDecimetersDescription = 'Куб. дециметры'; SCubicMetersDescription = 'Куб. метры'; SCubicDecametersDescription = 'Куб. декаметры'; SCubicHectometersDescription = 'Куб. гектометры'; SCubicKilometersDescription = 'Куб. километры'; SCubicInchesDescription = 'Куб. дюймы'; SCubicFeetDescription = 'Куб. футы'; SCubicYardsDescription = 'Куб. ярды'; SCubicMilesDescription = 'Куб. мили'; SMilliLitersDescription = 'Миллилитры'; SCentiLitersDescription = 'Сантилитры'; SDeciLitersDescription = 'Децилитры'; SLitersDescription = 'Литры'; SDecaLitersDescription = 'Декалитры'; SHectoLitersDescription = 'Гектолитры'; SKiloLitersDescription = 'Килолитры'; SAcreFeetDescription = 'Акрофуты'; SAcreInchesDescription = 'Акродюймы'; SCordsDescription = 'Корды'; SCordFeetDescription = 'Кордфуты'; SDecisteresDescription = 'Decisteres'; SSteresDescription = 'Steres'; SDecasteresDescription = 'Decasteres'; { American Fluid Units } SFluidGallonsDescription = 'Галлоны жидкие'; SFluidQuartsDescription = 'Кварты жидкие'; SFluidPintsDescription = 'Пинты жидкие'; SFluidCupsDescription = 'Кубки жидкие'; SFluidGillsDescription = '1/4 пинты жидкие'; SFluidOuncesDescription = 'Унции жидкие'; SFluidTablespoonsDescription = 'Столовые ложки'; SFluidTeaspoonsDescription = 'Чайные ложки'; { American Dry Units } SDryGallonsDescription = 'Галлоны сыпучие'; SDryQuartsDescription = 'Кварты сыпучие'; SDryPintsDescription = 'Пинты сыпучие'; SDryPecksDescription = 'DryPecks'; SDryBucketsDescription = 'Ведра'; SDryBushelsDescription = 'Бушели'; { English Imperial Fluid/Dry Units } SUKGallonsDescription = 'Англ. галлоны'; SUKPottlesDescription = 'UKPottle'; SUKQuartsDescription = 'Англ. кварты'; SUKPintsDescription = 'Англ. пинты'; SUKGillsDescription = 'Англ. 1/4 пинты'; SUKOuncesDescription = 'Англ. унции'; SUKPecksDescription = 'UKPecks'; SUKBucketsDescription = 'Англ. ведра'; SUKBushelsDescription = 'Англ. бушели'; { ************************************************************************* } { Mass's family type } SMassDescription = 'Масса'; { Mass's various conversion types } SNanogramsDescription = 'Нанограммы'; SMicrogramsDescription = 'Микрограммы'; SMilligramsDescription = 'Миллиграммы'; SCentigramsDescription = 'Сантиграммы'; SDecigramsDescription = 'Дециграммы'; SGramsDescription = 'Граммы'; SDecagramsDescription = 'Декаграммы'; SHectogramsDescription = 'Гектограммы'; SKilogramsDescription = 'Килограммы'; SMetricTonsDescription = 'Метр. тонны'; SDramsDescription = 'Драхмы'; SGrainsDescription = 'Граны'; STonsDescription = 'Тонны'; SLongTonsDescription = 'Длинные тонны'; SOuncesDescription = 'Унции'; SPoundsDescription = 'Фунты'; SStonesDescription = 'Стоуны'; { ************************************************************************* } { Temperature's family type } STemperatureDescription = 'Температура'; { Temperature's various conversion types } SCelsiusDescription = 'Цельсий'; SKelvinDescription = 'Кельвин'; SFahrenheitDescription = 'Фаренгейт'; SRankineDescription = 'Rankine'; SReaumurDescription = 'Реомюр'; { ************************************************************************* } { Time's family type } STimeDescription = 'Время'; { Time's various conversion types } SMilliSecondsDescription = 'Миллисекунды'; SSecondsDescription = 'Секунды'; SMinutesDescription = 'Минуты'; SHoursDescription = 'Часы'; SDaysDescription = 'Дни'; SWeeksDescription = 'Недели'; SFortnightsDescription = 'Две недели'; SMonthsDescription = 'Месяца'; SYearsDescription = 'Годы'; SDecadesDescription = 'Декады'; SCenturiesDescription = 'Века'; SMillenniaDescription = 'Тысячелетия'; SDateTimeDescription = 'ДатаВремя'; SJulianDateDescription = 'Юлианская дата'; SModifiedJulianDateDescription = 'Измененая Юлианская дата'; {$ENDIF} implementation end.
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Parser.LR1; interface uses System.SysUtils, System.Classes, Parse.Easy.StackPtr, Parse.Easy.Lexer.CustomLexer, Parse.Easy.Lexer.Token, Parse.Easy.Parser.CustomParser, Parse.Easy.Parser.State, Parse.Easy.Parser.Rule, Parse.Easy.Parser.Action; type TLR1 = class(TCustomParser) private FStack: TStackPtr; public constructor Create(ALexer: TCustomLexer); override; destructor Destroy; override; function Parse: Boolean; override; property Stack: TStackPtr read FStack; end; implementation { TLR1 } constructor TLR1.Create(ALexer: TCustomLexer); begin inherited; FStack := TStackPtr.Create; end; destructor TLR1.Destroy; begin FStack.Free; inherited; end; function TLR1.Parse: Boolean; var State: TState; EState: TState; Token: TToken; Actions: TList; Action: TAction; Rule: TRule; PopCount: Integer; I: Integer; J: Integer; Value: PValue; begin Result := False; EState := nil; if States.Count = 0 then Exit; FStack.Push(States[0]); Token := nil; ReturnValue := NewValue(); while (FStack.Count > 0) do begin State := FStack.Peek(); EState := State; Token := Lexer.Peek(); Actions := State.Terms[Token.TokenType]; if not Assigned(Actions) then begin Result := False; Break; end; Action := Actions[0]; case Action.ActionType of atShift: begin State := States[Action.ActionValue]; Token := Lexer.Advance(); FStack.Push(Token); FStack.Push(State); Value := NewValue(); Value^.AsToken := Token; Values.Push(Value); end; atReduce: begin Rule := Rules[Action.ActionValue]; PopCount := Rule.NumberOfItems; if (Rule.ActionIndex <> -1) then begin ReturnValue := NewValue(); UserAction(Rule.ActionIndex); end; for I := 0 to PopCount - 1 do Values.Pop(); Values.Push(ReturnValue); PopCount := PopCount * 2; for I := 0 to PopCount - 1 do FStack.Pop(); if rfAccept in Rule.Flags then begin Result := True; Break; end; State := FStack.Peek(); Actions := State.NoTerms[Rule.Id]; if not Assigned(Actions) then begin Result := False; Break; end; Action := Actions[0]; State := States[Action.ActionValue]; FStack.Push(Rule); FStack.Push(State); end; else begin Result := False; Break; end; end; end; if Result then Exit; if Assigned(EState) then begin for J := 0 to EState.Terms.Count - 1 do begin Actions := EState.Terms[J]; if Assigned(Actions) then ExceptList.Add(Pointer(J)); end; ExceptError(Token); end; end; end.
unit MyCat.BackEnd.Interfaces; interface uses System.SysUtils, MyCat.Net.CrossSocket.Base; type IResponseHandler = interface; IBackEndConnection = interface(ICrossConnection) function IsModifiedSQLExecuted: Boolean; function IsFromSlaveDB: Boolean; function GetSchema: string; procedure SetSchema(newSchema: string); function GetLastTime: Int64; function IsClosedOrQuit: Boolean; procedure SetAttachment(attachment: TObject); procedure Quit; procedure SetLastTime(currentTimeMillis: Int64); procedure Release; function SetResponseHandler(CommandHandler: IResponseHandler): Boolean; procedure Commit(); procedure Query(sql: string); function GetAttachment: TObject; // procedure execute(node: RouteResultsetNode; source: ServerConnection; // autocommit: Boolean); procedure RecordSql(host: String; schema: String; statement: String); function SyncAndExcute: Boolean; procedure Rollback; function GetBorrowed: Boolean; procedure SetBorrowed(Borrowed: Boolean); function GetTxIsolation: Integer; function IsAutocommit: Boolean; function GetId: Int64; procedure DiscardClose(reason: string); property Borrowed: Boolean read GetBorrowed write SetBorrowed; property schema: string read GetSchema write SetSchema; end; IResponseHandler = interface // * // * 无法获取连接 // * // * @param e // * @param conn // * procedure ConnectionError(E: Exception; Connection: IBackEndConnection); // * // * 已获得有效连接的响应处理 // * procedure ConnectionAcquired(Connection: IBackEndConnection); // * // * 收到错误数据包的响应处理 // * procedure ErrorResponse(Err: TBytes; Connection: IBackEndConnection); // * // * 收到OK数据包的响应处理 // * procedure OkResponse(OK: TBytes; Connection: IBackEndConnection); // * // * 收到字段数据包结束的响应处理 // * procedure FieldEofResponse(Header: TBytes; Fields: TArray<TBytes>; Eof: TBytes; Connection: IBackEndConnection); // * // * 收到行数据包的响应处理 // * procedure RowResponse(Row: TBytes; Connection: IBackEndConnection); // * // * 收到行数据包结束的响应处理 // * procedure RowEofResponse(Eof: TBytes; Connection: IBackEndConnection); // * // * 写队列为空,可以写数据了 // * procedure WriteQueueAvailable; // * // * on connetion close event // * procedure ConnectionClose(Connection: IBackEndConnection; reason: string); end; implementation end.
unit uDatabaseInfoControl; interface uses Generics.Collections, Winapi.Windows, Winapi.Messages, Winapi.ActiveX, System.Math, System.Classes, System.SysUtils, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.Imaging.PngImage, Vcl.ExtCtrls, Vcl.Forms, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.Menus, Dmitry.Utils.System, Dmitry.Graphics.LayeredBitmap, Dmitry.Controls.LoadingSign, Dmitry.Controls.Base, Dmitry.Controls.WebLink, UnitDBDeclare, uConstants, uRuntime, uMemory, uLogger, uResources, uTranslateUtils, uJpegUtils, uBitmapUtils, uGraphicUtils, uIconUtils, uSettings, uFormInterfaces, uDBManager, uDBContext, uTranslate, uDatabaseDirectoriesUpdater, uDBForm, uThreadForm, uThreadTask, uDBIcons, uAssociations, uShellIntegration, uCollectionEvents, uLinkListEditorDatabases, uManagerExplorer; type TDatabaseInfoControl = class(TPanel) private FImage: TImage; FDatabaseName: TWebLink; FLsMain: TLoadingSign; FInfoLabel: TLabel; FSeparator: TBevel; FSelectImage: TImage; FCheckTimer: TTimer; FOptionsPopupMenu: TPopupActionBar; MiRescan: TMenuItem; FMinimized: Boolean; FOnSelectClick: TNotifyEvent; FInfo: TDatabaseInfo; FMediaCountReady: Boolean; FMediaCount: Integer; FCollectionPicture: TGraphic; FIsUpdatingCollection: Boolean; FCurrentFileName: string; FIsCustomImage: Boolean; procedure DoAlignInfo; procedure LoadImagesCount; procedure LoadColectionImage; procedure ShowDatabaseProperties; procedure SelectDatabaseClick(Sender: TObject); procedure CheckTimerOnTimer(Sender: TObject); procedure ImageClick(Sender: TObject); procedure DatabaseNameOnClick(Sender: TObject); procedure MiShowFileClick(Sender: TObject); procedure MiRescanClick(Sender: TObject); procedure OnOptionsPopup(Sender: TObject); procedure ChangedDBDataByID(Sender: TObject; ID: Integer; Params: TEventFields; Value: TEventValues); function GetBigToolBar: Boolean; protected function L(StringToTranslate: string): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadControl(Info: TDatabaseInfo); property OnSelectClick: TNotifyEvent read FOnSelectClick write FOnSelectClick; property BigToolBar: Boolean read GetBigToolBar; end; implementation { TDatabaseInfoControl } procedure TDatabaseInfoControl.ChangedDBDataByID(Sender: TObject; ID: Integer; Params: TEventFields; Value: TEventValues); var Bit, Bitmap: TBitmap; procedure LoadCounter; begin FInfoLabel.Caption := NumberToShortNumber(FMediaCount); if (FMediaCount > 2) and (Trunc(Log10(FMediaCount)) <> Trunc(Log10(FMediaCount - 1))) then DoAlignInfo; end; begin if (SetNewIDFileData in Params) or (EventID_FileProcessed in Params) then begin if FCurrentFileName <> Value.FileName then begin FCurrentFileName := Value.FileName; Bit := TBitmap.Create; try Bit.PixelFormat := pf24bit; AssignJpeg(Bit, Value.JPEGImage); ApplyRotate(Bit, Value.Rotation); KeepProportions(Bit, FImage.Width - cShadowSize, FImage.Height - cShadowSize); Bitmap := TBitmap.Create; try DrawShadowToImage(Bitmap, Bit); Bitmap.AlphaFormat := afDefined; FImage.Picture.Graphic := Bitmap; FIsCustomImage := True; finally F(Bitmap); end; finally F(Bit); end; end; end; if FMediaCountReady then begin if [SetNewIDFileData] * Params <> [] then begin Inc(FMediaCount); LoadCounter; end; if [EventID_Param_Delete] * Params <> [] then begin Dec(FMediaCount); LoadCounter; end; end; end; procedure TDatabaseInfoControl.CheckTimerOnTimer(Sender: TObject); var ActualUpdatingCollection: Boolean; begin ActualUpdatingCollection := (UserDirectoryUpdaterCount > 0) or (UpdaterStorage.ActiveItemsCount > 0); if FIsUpdatingCollection <> ActualUpdatingCollection then begin FIsUpdatingCollection := ActualUpdatingCollection; DoAlignInfo; end; if not FMediaCountReady or FIsUpdatingCollection then begin FImage.Hint := UpdaterStorage.CurrentUpdaterState; FLsMain.Hint := FImage.Hint; FImage.ShowHint := True; FLsMain.ShowHint := True; end else begin FImage.ShowHint := False; FLsMain.ShowHint := False; end; if FIsCustomImage and not ActualUpdatingCollection then LoadColectionImage; end; constructor TDatabaseInfoControl.Create(AOwner: TComponent); begin inherited; StyleElements := [seFont, seClient, seBorder]; ParentBackground := False; BevelOuter := bvNone; FMediaCountReady := False; FMediaCount := 0; FCollectionPicture := nil; CollectionEvents.RegisterChangesID(Self, ChangedDBDataByID); FIsUpdatingCollection := True; FCurrentFileName := ''; FIsCustomImage := False; end; destructor TDatabaseInfoControl.Destroy; begin F(FInfo); F(FCollectionPicture); CollectionEvents.UnRegisterChangesID(Self, ChangedDBDataByID); inherited; end; procedure TDatabaseInfoControl.DoAlignInfo; var L: Integer; ShowLoadingSign: Boolean; begin FMinimized := not BigToolBar; ShowLoadingSign := not FMediaCountReady or FIsUpdatingCollection; DisableAlign; try if FInfo <> nil then FDatabaseName.Text := FInfo.Title else FDatabaseName.Text := ''; FDatabaseName.RefreshBuffer(True); FInfoLabel.Caption := ''; FImage.Height := Height - 2; FImage.Width := FImage.Height; LoadColectionImage; if not FMinimized then begin FDatabaseName.Left := FImage.Left + FImage.Width + 3; FDatabaseName.Top := Height div 2 - (FDatabaseName.Height + 2 + FLsMain.Height) div 2; if ShowLoadingSign then begin FLsMain.Left := FImage.Left + FImage.Width + 3; FLsMain.Top := FDatabaseName.Top + FDatabaseName.Height + 3; FLsMain.Visible := True; FImage.Hint := UpdaterStorage.CurrentUpdaterState; FLsMain.Hint := FImage.Hint; end else begin FLsMain.Left := FImage.Left + FImage.Width - FLsMain.Width; FLsMain.Visible := False; end; FInfoLabel.Visible := True; FInfoLabel.Top := FLsMain.Top + FLsMain.Height div 2 - FInfoLabel.Height div 2; FInfoLabel.Left := FLsMain.Left + FLsMain.Height + 3; end else begin FInfoLabel.Visible := False; FInfoLabel.Left := 0; if ShowLoadingSign then begin FLsMain.Left := FImage.Left + FImage.Width + 3; FLsMain.Top := Height div 2 - FLsMain.Height div 2; FLsMain.Visible := True; end else begin FLsMain.Left := FImage.Left + FImage.Width - FLsMain.Width; FLsMain.Visible := False; end; FDatabaseName.Left := FLsMain.Left + FLsMain.Width + 3; FDatabaseName.Top := Height div 2 - FDatabaseName.Height div 2; end; if not FMediaCountReady then LoadImagesCount else FInfoLabel.Caption := NumberToShortNumber(FMediaCount); L := Max(FDatabaseName.Left + FDatabaseName.Width, FInfoLabel.Left + FInfoLabel.Width); FSeparator.Left := L + 3; FSeparator.Height := Height; FSelectImage.Left := FSeparator.Left + FSeparator.Width; FSelectImage.Height := Height; Width := FSelectImage.Width + FSelectImage.Left + 2; finally EnableAlign; end; end; function TDatabaseInfoControl.GetBigToolBar: Boolean; begin Result := not AppSettings.Readbool('Options', 'UseSmallToolBarButtons', False); end; procedure TDatabaseInfoControl.DatabaseNameOnClick(Sender: TObject); begin ShowDatabaseProperties; end; procedure TDatabaseInfoControl.ImageClick(Sender: TObject); begin if FIsUpdatingCollection and (FCurrentFileName <> '') then begin Viewer.ShowImageInDirectoryEx(FCurrentFileName); Viewer.Show; Viewer.Restore; end else ShowDatabaseProperties; end; procedure TDatabaseInfoControl.LoadControl(Info: TDatabaseInfo); var PNG: TPngImage; MI: TMenuItem; begin F(FInfo); if Info <> nil then FInfo := TDatabaseInfo(Info.Clone); FMediaCountReady := False; FIsUpdatingCollection := True; DisableAlign; try if FImage = nil then begin FImage := TImage.Create(Self); FImage.Parent := Self; FImage.Top := 1; FImage.Left := 1; FImage.Center := True; FImage.Cursor := crHandPoint; FImage.OnClick := ImageClick; FDatabaseName := TWebLink.Create(Self); FDatabaseName.Parent := Self; FDatabaseName.IconWidth := 0; FDatabaseName.IconHeight := 0; FDatabaseName.Font.Size := 11; FDatabaseName.OnClick := DatabaseNameOnClick; FLsMain := TLoadingSign.Create(Self); FLsMain.Parent := Self; FLsMain.Width := 16; FLsMain.Height := 16; FLsMain.FillPercent := 50; FLsMain.Active := True; FInfoLabel := TLabel.Create(Self); FInfoLabel.Parent := Self; FInfoLabel.Caption := ''; FSeparator := TBevel.Create(Self); FSeparator.Parent := Self; FSeparator.Width := 2; FSeparator.Top := 0; FSelectImage := TImage.Create(Self); FSelectImage.Parent := Self; PNG := GetNavigateDownImage; try FSelectImage.Picture.Graphic := PNG; finally F(PNG); end; FSelectImage.Width := 20; FSelectImage.Center := True; FSelectImage.Cursor := crHandPoint; FSelectImage.OnClick := SelectDatabaseClick; FOptionsPopupMenu := TPopupActionBar.Create(Self); FOptionsPopupMenu.Images := Icons.ImageList; FOptionsPopupMenu.OnPopup := OnOptionsPopup; MI := TMenuItem.Create(FOptionsPopupMenu); MI.Caption := L('Navigate to collection file'); MI.OnClick := MiShowFileClick; MI.ImageIndex := DB_IC_EXPLORER; FOptionsPopupMenu.Items.Add(MI); MI := TMenuItem.Create(FOptionsPopupMenu); MI.Caption := '-'; FOptionsPopupMenu.Items.Add(MI); MiRescan := TMenuItem.Create(FOptionsPopupMenu); MiRescan.Caption := TA('Rescan', 'CollectionSettings'); MiRescan.OnClick := MiRescanClick; MiRescan.ImageIndex := DB_IC_REFRESH_THUM; FOptionsPopupMenu.Items.Add(MiRescan); FImage.PopupMenu := FOptionsPopupMenu; FDatabaseName.PopupMenu := FOptionsPopupMenu; FCheckTimer := TTimer.Create(Self); FCheckTimer.Interval := 1000; FCheckTimer.Enabled := True; FCheckTimer.OnTimer := CheckTimerOnTimer; end; DoAlignInfo; finally EnableAlign; end; end; function TDatabaseInfoControl.L(StringToTranslate: string): string; begin Result := TDBForm(Owner).L(StringToTranslate); end; procedure TDatabaseInfoControl.LoadColectionImage; var IconFileName: string; LB: TLayeredBitmap; Ico: HIcon; IconSize: Integer; GraphicClass: TGraphicClass; Graphic: TGraphic; B: TBitmap; begin if FInfo <> nil then IconFileName := FInfo.Icon; if IconFileName = '' then IconFileName := Application.ExeName + ',0'; IconSize := IIF(BigToolBar, 32, 16); if IsIconPath(IconFileName) then begin Ico := ExtractSmallIconByPath(IconFileName, BigToolBar); try LB := TLayeredBitmap.Create; try LB.LoadFromHIcon(Ico, IconSize, IconSize); F(FCollectionPicture); Exchange(FCollectionPicture, LB); finally F(LB); end; finally DestroyIcon(Ico); end; end else begin GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(IconFileName)); if GraphicClass = nil then Exit; try Graphic := GraphicClass.Create; try Graphic.LoadFromFile(IconFileName); if (Graphic.Width > IconSize) or (Graphic.Height > IconSize) then begin B := TBitmap.Create; try AssignGraphic(B, Graphic); KeepProportions(B, IconSize, IconSize); F(B); Exchange(FCollectionPicture, B); finally F(B); end; end else begin F(FCollectionPicture); Exchange(FCollectionPicture, Graphic); end; finally F(Graphic); end; except on e: Exception do EventLog(e); end; end; FImage.Picture.Graphic := FCollectionPicture; FIsCustomImage := False; end; procedure TDatabaseInfoControl.LoadImagesCount; begin TThreadTask<IDBContext>.Create(TThreadForm(Self.Owner), DBManager.DBContext, False, procedure(Thread: TThreadTask<IDBContext>; Data: IDBContext) var MediaRepository: IMediaRepository; MediaCount: Integer; begin CoInitialize(nil); try MediaRepository := Data.Media; MediaCount := MediaRepository.GetCount; Thread.SynchronizeTask( procedure begin FMediaCountReady := True; FMediaCount := MediaCount; DoAlignInfo; end ); finally CoUninitialize; end; end ); end; procedure TDatabaseInfoControl.MiRescanClick(Sender: TObject); begin ClearUpdaterCache(DBManager.DBContext); RecheckUserDirectories; CheckTimerOnTimer(Sender); end; procedure TDatabaseInfoControl.MiShowFileClick(Sender: TObject); begin with ExplorerManager.NewExplorer(False) do begin NavigateToFile(DBManager.DBContext.CollectionFileName); Show; end; end; procedure TDatabaseInfoControl.OnOptionsPopup(Sender: TObject); begin MiRescan.Enabled := UserDirectoryUpdaterCount = 0; end; procedure TDatabaseInfoControl.SelectDatabaseClick(Sender: TObject); begin if Assigned(FOnSelectClick) then FOnSelectClick(Self); end; procedure TDatabaseInfoControl.ShowDatabaseProperties; var Editor: ILinkEditor; Info: TDatabaseInfo; begin if FInfo = nil then Exit; Info := TDatabaseInfo(FInfo.Clone); Editor := TLinkListEditorDatabases.Create(TDBForm(Self.Owner)); try if FormLinkItemEditor.Execute(L('Edit collection'), Info, Editor) then begin FInfo.Assign(Info); DBManager.UpdateUserCollection(Info, -1); end; finally Editor := nil; F(Info); end; end; end.
//------------------------------------------------------------------------------ //CharaLoginCommunication UNIT //------------------------------------------------------------------------------ // What it does- // This unit houses routines for Character Server to Login Server // communication. // // Changes - // March 12th, 2007 - Aeomin - Created Header // March 18th, 2007 - RaX - Updated Header. // June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength // in various calls // //------------------------------------------------------------------------------ unit CharaLoginCommunication; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses CharacterServer, CharAccountInfo, CommClient, IdContext; procedure ValidateWithLoginServer( AClient : TInterClient; CharacterServer : TCharacterServer ); procedure SendValidateFlagToChara(AClient : TIdContext; Validated : Byte); procedure SendCharaWANIPToLogin(AClient : TInterClient; CharacterServer : TCharacterServer); procedure SendCharaLANIPToLogin(AClient : TInterClient; CharacterServer : TCharacterServer); procedure SendCharaOnlineUsersToLogin(AClient : TInterClient; CharacterServer : TCharacterServer); procedure SendAccountLogon( AClient : TInterClient; AnAccount : TCharAccountInfo; CharacterServer : TCharacterServer ); procedure SendAccountLogOut( AClient : TInterClient; AnAccount : TCharAccountInfo; CharacterServer : TCharacterServer ); procedure SendKickAccountChara(AClient : TIdContext; AccountID : LongWord); implementation uses BufferIO, Globals, PacketTypes, TCPServerRoutines; //------------------------------------------------------------------------------ //ValidateWithLoginServer PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send verification to Login Server. // // Changes - // March 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ procedure ValidateWithLoginServer( AClient : TInterClient; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2000, OutBuffer); WriteBufferLongWord(2, CharacterServer.Options.ID, OutBuffer); WriteBufferMD5String(6, GetMD5(CharacterServer.Options.LoginKey), OutBuffer); WriteBufferString(22, CharacterServer.Servername, 24, OutBuffer); WriteBufferWord(46, CharacterServer.Port, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2000)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendValidateFlagToChara PROCEDURE //------------------------------------------------------------------------------ // What it does- // An exception procedure which used by Login Server. // Tell Character Server whether the request is validated or not. // // Changes - // March 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ procedure SendValidateFlagToChara(AClient : TIdContext; Validated : Byte); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2001, OutBuffer); WriteBufferByte(2, Validated, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2001)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCharaWANIPToLogin PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send the WAN IP of Character Server to Login Server. // // Changes - // March 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ procedure SendCharaWANIPToLogin( AClient : TInterClient; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; Size : integer; begin Size := Length(CharacterServer.WANIP); WriteBufferWord(0,$2002,OutBuffer); WriteBufferWord(2,Size+4,OutBuffer); WriteBufferString(4,CharacterServer.WANIP,Size,OutBuffer); SendBuffer(AClient,OutBuffer,Size+4); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCharaLANIPToLogin PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send the LAN IP of Character Server to Login Server. // // Changes - // March 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ procedure SendCharaLANIPToLogin( AClient : TInterClient; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; Size : integer; begin Size := Length(CharacterServer.LANIP); WriteBufferWord(0,$2003,OutBuffer); WriteBufferWord(2,Size+4,OutBuffer); WriteBufferString(4,CharacterServer.LANIP,Size,OutBuffer); SendBuffer(AClient,OutBuffer,Size+4); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCharaOnlineUsersToLogin PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send the number of online players to Login Server. // // Changes - // March 12th, 2007 - Aeomin - Created Header // March 30th, 2007 - Tsusai - Changed OnlineUsers to GetOnlineUserCount // //------------------------------------------------------------------------------ procedure SendCharaOnlineUsersToLogin( AClient : TInterClient; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; begin WriteBufferWord(0,$2004,OutBuffer); WriteBufferWord(2,CharacterServer.GetOnlineUserCount,OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2004)); end; //------------------------------------------------------------------------------ procedure SendAccountLogon( AClient : TInterClient; AnAccount : TCharAccountInfo; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; begin FillChar(OutBuffer, PacketDB.GetLength($2005), 0); WriteBufferWord(0,$2005,OutBuffer); WriteBufferLongWord(2, AnAccount.AccountID , OutBuffer); WriteBufferLongWord(6, CharacterServer.Options.ID , OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2005)); end; procedure SendAccountLogOut( AClient : TInterClient; AnAccount : TCharAccountInfo; CharacterServer : TCharacterServer ); var OutBuffer : TBuffer; begin FillChar(OutBuffer, PacketDB.GetLength($2006), 0); WriteBufferWord(0,$2006,OutBuffer); WriteBufferLongWord(2, AnAccount.AccountID , OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2006)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendKickAccountChara PROCEDURE //------------------------------------------------------------------------------ // What it does- // Tell character server to kick an account (Duplicate Session Check) // // Changes - // April 10th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ procedure SendKickAccountChara(AClient : TIdContext; AccountID : LongWord); var OutBuffer : TBuffer; begin FillChar(OutBuffer, PacketDB.GetLength($2007), 0); WriteBufferWord(0, $2007, OutBuffer); WriteBufferLongWord(2, AccountID, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2007)); end; //------------------------------------------------------------------------------ end.
Program SWG2DBF; {$I GSF_FLAG.PAS} Uses Reader_U, Reader_C, { vDisk, vMEMO, vMenu, GSF_Shel, gsf_tool, gsf_date, vScreen, vKBd, CRT, GSF_DOS,} LZH,ZipUnit; TYPE SwagHeader = RECORD HeadSize : BYTE; {size of header} HeadChk : BYTE; {checksum for header} HeadID : ARRAY [1..5] OF CHAR; {compression type tag} NewSize : LONGINT; {compressed size} OrigSize : LONGINT; {original size} Time : WORD; {packed time} Date : WORD; {packed date} Attr : WORD; {file attributes and flags} BufCRC : LONGINT; {32-CRC of the Buffer } Swag : STRING[12]; {stored SWAG filename} Subject : STRING[40]; {snipet subject} Contrib : STRING[35]; {contributor} Keys : STRING[70]; {search keys, comma deliminated} FName : String[79]; {filename (variable length)} CRC : WORD; {16-bit CRC (immediately follows FName)} END; SWAGFooter = RECORD CopyRight : String[60]; { GDSOFT copyright } Title : String[65]; { SWG File Title } Count : INTEGER; END; Var HeaderBuf: SwagHeader; { Temporary buffer } NextPos:LongInt; { Next snipet position } fSize: LongInt; { File size } F,dbF: File; Name: String[8]; { Base : DBase3;} be,en,BytesLeft:word; StartLzh,i:Word; PackBuf: UserBufType; UnPackBuf:UserBufType; Result:Word; InCounter,OutCounter,SwgCounter:LongInt; Procedure GetBlock(Var Target; NoBytes: Word; Var Actual_Bytes: Word); Far; begin if NoBytes > BytesLeft then Actual_Bytes:=BytesLeft else Actual_Bytes:=NoBytes; move(PackBuf^[be],Target,Actual_Bytes); be:=be+Actual_Bytes; Dec(BytesLeft,Actual_Bytes); end; Procedure PutBlock(Var Source; NoBytes: Word; Var Actual_Bytes: Word); Far; begin move(Source,UnPackBuf^[StartLzh],NoBytes); Inc(StartLzh,NoBytes); en:=en+NoBytes; Actual_Bytes:=NoBytes; end; {----------------------------------------------} Procedure InsertToBuf(PackBuf:UserBufType;Var BufLen:Word; InsPos:Word;InsStr:String); Var i,L:word; begin L:=Length(InsStr); For i:=BufLen DownTo InsPos do PackBuf^[i+l]:=PackBuf^[i]; move(InsStr[1],PackBuf^[InsPos],L); Inc(BufLen,L); end; {----------------------------------------------} { Convert Integer to string & add leading zero } Function LeadZero(L:Longint;n:byte):String; Var i:integer; S:String; begin STR(L:n,S); For i:=1 to n do If S[i]=' ' then S[i]:='0'; LeadZero:=S; end; {-------------------------------------------} { Convert packed date to string } Function Date2str(D:Word):String; Var Day :Word; Month:Word; Year :Word; begin Day := ( D and $1F); Month:= ( D and $1E0) shr 5; Year := ( D and $FE00) shr 9; Date2str:=LeadZero(Day,2)+'-' +LeadZero(Month,2)+'-' +LeadZero((Year+80),2); Date2str:=LeadZero((Year+80),4) +LeadZero(Month,2)+ +LeadZero(Day,2); end; {===============================================} begin InCounter:=0; OutCounter:=0; SwgCounter:=0; { SetPublicVar; {Initialize Variables} { DrawTitleScreen; {Draw Title Screen } If not CheckWorkPath then begin {} Halt(1); end else begin OpenMainBase(AreaBase,'AREAS'); ScanAreas; end; For Each ('*.swg') do begin SwgName:=DirInfo.Name; If not Seek(SwgName) then CreateWorkBase(SwgName); ReadSwgHeader(SwgName); ReadNextMessage; end; If ParamStr(1)<>'' then begin Name:=ParamStr(1); i:=Pos('.',Name); If i>0 then Name[0]:=Chr(i-1); Base.Assign(Name); {пpисвоить БД имя} Base.Init; {подготовиться к созданию БД} Base.AddField('FROM','C',25,0); Base.AddField('ADDR','C',25,0); Base.AddField('SUBJ','C',52,0); Base.AddField('DATE','D', 8,0); Base.AddField('APDATE','D', 8,0); Base.AddField('TEXT','M',10,0); Base.AddField('KEYS','C',40,0); Base.AddField('NEW', 'L',1,0); if Base.Create then Base.Open(ReadWrite) else begin writeln('Не могу создать базу данных...'); exit; end; getmem(PackBuf, sizeof(BuffType)); getmem(UnPackBuf,sizeof(BuffType)); Assign(F,ParamStr(1)); Reset(F,1); FSize:=FileSize(F); NextPos:=0; While (nextPos+SizeOf(HeaderBuf)) < FSize do begin Seek(F,NextPos); BlockRead(F,HeaderBuf,SizeOf(HeaderBuf)); seek(f,NextPos+HeaderBuf.HeadSize+2); blockread(f,PackBuf^,HeaderBuf.NewSize); Base.Append; Base.WriteStr('FROM',HeaderBuf.Contrib); Base.WriteStr('SUBJ',HeaderBuf.Subject); Base.WriteStr('KEYS',HeaderBuf.Keys ); Base.WriteStr('DATE',Date2Str(HeaderBuf.Date)); Base.WriteStr('APDATE',Date2Str(HeaderBuf.Date)); Base.WriteLog('NEW', FALSE); (* SwagHeader = RECORD HeadSize : BYTE; {size of header} HeadChk : BYTE; {checksum for header} HeadID : ARRAY [1..5] OF CHAR; {compression type tag} NewSize : LONGINT; {compressed size} OrigSize : LONGINT; {original size} Time : WORD; {packed time} Date : WORD; {packed date} Attr : WORD; {file attributes and flags} BufCRC : LONGINT; {32-CRC of the Buffer } Swag : STRING[12]; {stored SWAG filename} Subject : STRING[40]; {snipet subject} Contrib : STRING[35]; {contributor} Keys : STRING[70]; {search keys, comma deliminated} FName : PathStr; {filename (variable length)} CRC : WORD; {16-bit CRC (immediately follows FName)} END; *) be:=0; en:=0; BytesLeft:=HeaderBuf.NewSize; StartLzh:=0; LZHUnPack(HeaderBuf.OrigSize,GetBlock,PutBlock); For i:=0 to HeaderBuf.OrigSize-1 do begin If UnPackBuf^[i] = #26 then begin StartLzh:=i; Break; end; end; Inc(InCounter,HeaderBuf.OrigSize); Inc(SwgCounter,HeaderBuf.NewSize); { Result := Zip(UnPackBuf, PackBuf, StartLzh); i:=0; While i < Result do begin If PackBuf^[i] = #26 then begin InsertToBuf(PackBuf,Result,i+1,'wG'); PackBuf^[i]:='S'; Inc(i,2); end; Inc(i); end; writeln('ZipSize=',Result); Inc(OutCounter,Result); } (* Base.WriteMemo('TEXT',{Un}PackBuf,{StartLzh}Result); *) Base.WriteMemo('TEXT',UnPackBuf,StartLzh{Result}); NextPos:=NextPos+HeaderBuf.HeadSize+HeaderBuf.NewSize+2; end; Close(F); Base.Close; writeln('SwgSize=',SwgCounter,' SourceSize=',InCounter, ' ZipSize=',OutCounter); end; end.
unit uInventoryCleanUp; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, StdCtrls, RadioButtonAll, Mask, LblEffct, ExtCtrls, Buttons, SuperComboADO, Db, ADODB, siComp, siLangRT, Grids, DBGrids, SMDBGrid; type TInventoryCleanUp = class(TFrmParent) btCancel: TButton; spHelp: TSpeedButton; pnlModel: TPanel; Label6: TLabel; Label1: TLabel; Label2: TLabel; cbxMethod: TComboBox; edModel: TEdit; quModel: TADODataSet; dsModel: TDataSource; quModelIDModel: TAutoIncField; quModelModel: TStringField; quModelDescription: TStringField; quModelCategory: TStringField; quModelStore: TStringField; btClearStore: TButton; Label3: TLabel; scStore: TSuperComboADO; btClearCatego: TButton; btAllModel: TButton; btnRefresh: TSpeedButton; cmCleanInv: TADOCommand; quModelInvType: TIntegerField; quModelStoreID: TIntegerField; grdBarcode: TSMDBGrid; quModelQtyOnHand: TFloatField; quModelQtyABS: TFloatField; lbQtyType: TLabel; cbxQtyType: TComboBox; lbSubCategory: TLabel; scSubCategory: TSuperComboADO; btnSubCategClear: TButton; lbModelGroup: TLabel; scModelGroup: TSuperComboADO; btnMGroupClear: TButton; scCategory: TSuperComboADO; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure spHelpClick(Sender: TObject); procedure btClearStoreClick(Sender: TObject); procedure btClearCategoClick(Sender: TObject); procedure btAllModelClick(Sender: TObject); procedure scStoreSelectItem(Sender: TObject); procedure scCategorySelectItem(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSubCategClearClick(Sender: TObject); procedure btnMGroupClearClick(Sender: TObject); procedure scSubCategorySelectItem(Sender: TObject); procedure scModelGroupSelectItem(Sender: TObject); private sAsk : String; sWhere : string; procedure ModelClose; procedure RefreshModel; function AdjustInventoryToZero(sWhereClause:string):Boolean; end; implementation uses uDM, uMsgBox, uAskManager, uMsgConstant, uSqlFunctions, uDMGlobal, uSystemConst, uNumericFunctions; {$R *.DFM} function TInventoryCleanUp.AdjustInventoryToZero(sWhereClause:string):Boolean; var iID : Integer; begin Screen.Cursor := crHourGlass; Try //Abro a Transacao DM.ADODBConnect.BeginTrans; with cmCleanInv do begin CommandText := 'INSERT InvResetHistory ( ResetDate, IDStore, IDModel, Qty ) ' + 'SELECT :ResetDate, I.StoreID, I.ModelID, I.QtyOnHand ' + 'FROM Inventory I (NOLOCK) ' + 'INNER JOIN Model M (NOLOCK) ON (I.ModelID = M.IDModel) ' + 'WHERE ' + sWhereClause; Parameters.ParamByName('ResetDate').Value:= Now; Execute; end; with quModel do begin First; While not EOF do begin iID := DM.GetNextID(MR_INVENTORY_MOV_ID); DM.RunSQL('INSERT InventoryMov ( IDInventoryMov, InventMovTypeID, DocumentID, StoreID, ModelID, MovDate, Qty, IDUser) '+ 'VALUES ('+IntToStr(iID)+', '+ quModelInvType.AsString +', '+ '0, '+ quModelStoreID.AsString +', '+ quModelIDModel.AsString +', '+ QuotedStr(FormatDateTime('mm/dd/yyyy hh:mm:ss AM/PM',(Now)))+', '+ MyFormatDouble(quModelQtyABS.AsFloat, '.') +', '+ IntToStr(DM.fUser.ID)+')'); Next; end; end; { 'INSERT InventoryMov ( InventMovTypeID, DocumentID, StoreID, ModelID, ' + ' MovDate, Qty, IDUser ) ' + 'SELECT ' + '( CASE WHEN I.QtyOnHand > 0 THEN 12 ELSE 11 END ), 0, I.StoreID, ' + ' I.ModelID, :Date, ABS(I.QtyOnHand), :IDUser ' + 'FROM Inventory I ' + 'INNER JOIN Model M ON (I.ModelID = M.IDModel) ' + 'WHERE I.QtyOnHand <> 0 ' + 'AND M.ModelType IN (''R'',''S'',''K'') ' + 'AND ' + sWhereClause } //Gravo os resultados DM.ADODBConnect.CommitTrans; Result := True; Except on E: Exception do begin Result := False; DM.ADODBConnect.RollbackTrans; ShowMessage(E.Message); end; end; Screen.Cursor := crDefault; end; procedure TInventoryCleanUp.ModelClose; begin with quModel do if Active then Close; end; procedure TInventoryCleanUp.RefreshModel; var sOldSql, sLike: String; begin Screen.Cursor := crHourGlass; ModelClose; with quModel do begin sOldSql := CommandText; sWhere := ' M.Desativado = 0 AND M.ModelType IN (''R'',''S'',''K'') '; sLike := 'None'; case cbxMethod.ItemIndex of 0: sLike := edModel.Text + '%'; 1: sLike := '%' + edModel.Text; 2: sLike := '%' + edModel.Text + '%'; else sLike := 'None'; end; //Add Model if sLike <> 'None' then sWhere := sWhere + ' AND M.Model Like ' + QuotedStr(sLike); //Add a Store if scStore.LookUpValue <> '' then sWhere := sWhere + ' AND I.StoreID = ' + scStore.LookUpValue; //Add Categ if scCategory.LookUpValue <> '' then sWhere := sWhere + ' AND M.GroupID = ' + scCategory.LookUpValue; //Sub Categ if scSubCategory.LookUpValue <> '' then sWhere := sWhere + ' AND M.IDModelGroup = ' + scSubCategory.LookUpValue; //Group if scModelGroup.LookUpValue <> '' then sWhere := sWhere + ' AND M.IDModelSubGroup = ' + scModelGroup.LookUpValue; case cbxQtyType.ItemIndex of 0: sWhere := sWhere + ' AND I.QtyOnHand > 0'; 1: sWhere := sWhere + ' AND I.QtyOnHand < 0'; 2: sWhere := sWhere + ' '; end; CommandText := ChangeWhereClause(sOldSQL, sWhere, True); Open; end; Screen.Cursor := crDefault; end; procedure TInventoryCleanUp.FormShow(Sender: TObject); begin inherited; scStore.LookUpValue := IntToStr(DM.fStore.IDDefault); //scCategory.SetAll; btClose.SetFocus; RefreshModel; end; procedure TInventoryCleanUp.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; ModelClose; Action := caFree; end; procedure TInventoryCleanUp.btCloseClick(Sender: TObject); var bClose : Boolean; begin inherited; bClose := False; if MsgBox(MSG_QST_CLEAN_UP_INVENTORY, vbYesNo + vbSuperCritical) = vbYes then with TFrmAskManager.Create(self) do if Start(sAsk) then if AdjustInventoryToZero(sWhere) then begin MsgBox(MSG_INF_INV_CLEANED, vbOKOnly + vbInformation); bClose := True; end; if bClose then Close; end; procedure TInventoryCleanUp.btCancelClick(Sender: TObject); begin inherited; Close; end; procedure TInventoryCleanUp.spHelpClick(Sender: TObject); begin inherited; Application.HelpContext(1830); end; procedure TInventoryCleanUp.btClearStoreClick(Sender: TObject); begin inherited; scStore.LookUpValue := ''; scStore.Text := '<' + btClearStore.Caption + '>'; RefreshModel; end; procedure TInventoryCleanUp.btClearCategoClick(Sender: TObject); begin inherited; scCategory.LookUpValue := ''; scCategory.Text := '<' + btClearCatego.Caption + '>'; RefreshModel; end; procedure TInventoryCleanUp.btAllModelClick(Sender: TObject); begin inherited; cbxMethod.ItemIndex := -1; edModel.Clear; RefreshModel; end; procedure TInventoryCleanUp.scStoreSelectItem(Sender: TObject); begin inherited; if scStore.LookUpValue <> '' then RefreshModel; end; procedure TInventoryCleanUp.scCategorySelectItem(Sender: TObject); begin inherited; if scCategory.LookUpValue <> '' then RefreshModel; end; procedure TInventoryCleanUp.btnRefreshClick(Sender: TObject); begin inherited; RefreshModel; end; procedure TInventoryCleanUp.FormCreate(Sender: TObject); begin inherited; case DMGlobal.IDLanguage of LANG_ENGLISH: sAsk := 'The Operation requires an Administrator''s authorization.'; LANG_PORTUGUESE: sAsk := 'A Operação Requere Autorização do Gerente.'; LANG_SPANISH: sAsk := 'La Operación Requiere Autorización del Gerente.'; end; end; procedure TInventoryCleanUp.btnSubCategClearClick(Sender: TObject); begin inherited; scSubCategory.LookUpValue := ''; scSubCategory.Text := '<' + btnSubCategClear.Caption + '>'; RefreshModel; end; procedure TInventoryCleanUp.btnMGroupClearClick(Sender: TObject); begin inherited; scModelGroup.LookUpValue := ''; scModelGroup.Text := '<' + btnMGroupClear.Caption + '>'; RefreshModel; end; procedure TInventoryCleanUp.scSubCategorySelectItem(Sender: TObject); begin inherited; if scSubCategory.LookUpValue <> '' then RefreshModel; end; procedure TInventoryCleanUp.scModelGroupSelectItem(Sender: TObject); begin inherited; if scModelGroup.LookUpValue <> '' then RefreshModel; end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0014.PAS Description: PACKTIME.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:37 *) {>I noticed that Pascal has Functions called unpacktime() and packtime(). >Does anyone know how these two Functions work? I need either a source >code example of the equiValent or just a plain algorithm to tell me how >these two Functions encode or Decode and date/time into a LongInt. The packed time Format is a 32 bit LongInt as follows: bits field ---- ----- 0-5 = seconds 6-11 = minutes 12-16 = hours 17-21 = days 22-25 = months 26-31 = years DateTime is a Record structure defined Within the Dos Unit With the following structure: DateTime = Record year,month,day,hour,min,sec : Word end; The GetFtime Procedure loads the date/time stamp of an opened File into a LongInt. UnPackTime extracts the Various bit patterns into the DateTime Record structure. PackTime will take the Values you Assign to the DateTime Record structure and pack them into a LongInt - you could then use SetFTime to update the File date stamp. A small sample Program follows. } Program prg30320; Uses Dos; Var TextFile : Text; Filetime : LongInt; dt : DateTime; begin Assign(TextFile,'TextFile.txt'); ReWrite(TextFile); WriteLn(TextFile,'Hi, I''m a Text File'); GetFtime(TextFile,Filetime); Close(TextFile); UnPackTime(Filetime,dt); WriteLn('File was written: ',dt.month,'/',dt.day,'/',dt.year, ' at ',dt.hour,':',dt.min,':',dt.sec); ReadLn; end. { The following example shows how to pick apart the packed date/time. } Program PKTIME; Uses Dos; Var dt : DateTime; pt : LongInt; Year : 0..127; { Years sInce 1980 } Month : 1..12; { Month number } Day : 1..31; { Day of month } Hour : 0..23; { Hour of day } Min : 0..59; { Minute of hour } Sec2 : 0..29; { Seconds divided by 2 } Procedure GetDateTime(Var dt : DateTime); { Get current date and time. Allow For crossing midnight during execution. } Var y, m, d, dow : Word; Sec100 : Word; begin GetDate(y, m, d, dow); GetTime(dt.Hour, dt.Min, dt.Sec, Sec100); GetDate(dt.Year, dt.Month, dt.Day, dow); if dt.Day <> d then GetTime(dt.Hour, dt.Min, dt.Sec, Sec100); end; begin GetDateTime(dt); PackTime(dt, pt); Year := (pt shr 25) and $7F; Month := (pt shr 21) and $0F; Day := (pt shr 16) and $1F; Hour := (pt shr 11) and $1F; Min := (pt shr 5) and $3F; Sec2 := pt and $1F; WriteLn(Month, '/', Day, '/', Year+1980); WriteLn(Hour, ':', Min, ':', Sec2*2); end.
unit RTFReportEngine; interface uses System.Generics.Collections, Classes, SysUtils, Data.DB; type EParserException = class(Exception) end; TRTFLoopControl = record Identifier: String; SymbolToConsumeAtEachIteration: String; class function Create(aIdentifier, aSymbolToConsumeAtEachIteration: String) : TRTFLoopControl; static; end; TRTFReportEngine = class strict private FOutput: string; FVariables: TDictionary<string, string>; function MatchStartTag: Boolean; function MatchEndTag: Boolean; function MatchIdentifier(var aIdentifier: String): Boolean; function MatchReset(var aDataSet: String): Boolean; function MatchField(var aDataSet: String; var aFieldName: String): Boolean; function MatchSymbol(const Symbol: String): Boolean; private FInputString: string; FCharIndex: Int64; FCurrentLine: Integer; FCurrentColumn: Integer; FLoopStack: TStack<Integer>; FLoopIdentStack: TStack<TRTFLoopControl>; FDatasets: TArray<TDataSet>; FCurrentDataset: TDataSet; procedure Error(const Message: String); function ExecuteFunction(AFunctionName, AValue: String): String; function SetDataSetByName(const Name: String): Boolean; function GetFieldText(const FieldName: String): String; public procedure Parse(const InputString: string; const Data: TArray<TDataSet>); procedure AppendOutput(const AValue: string); constructor Create; destructor Destroy; override; procedure SetVar(const AName: string; AValue: string); function GetVar(const AName: string): string; procedure ClearVariables; function GetOutput: string; end; implementation const IdenfierAllowedFirstChars = ['a' .. 'z', 'A' .. 'Z', '_']; IdenfierAllowedChars = IdenfierAllowedFirstChars + ['0' .. '9']; { TParser } procedure TRTFReportEngine.AppendOutput(const AValue: string); begin FOutput := FOutput + AValue; end; procedure TRTFReportEngine.ClearVariables; begin FVariables.Clear; end; constructor TRTFReportEngine.Create; begin inherited; FOutput := ''; FVariables := TDictionary<string, string>.Create; FLoopStack := TStack<Integer>.Create; FLoopIdentStack := TStack<TRTFLoopControl>.Create; end; destructor TRTFReportEngine.Destroy; begin FLoopIdentStack.Free; FLoopStack.Free; FVariables.Free; inherited; end; function TRTFReportEngine.SetDataSetByName(const Name: String): Boolean; var ds: TDataSet; begin Result := False; for ds in FDatasets do begin if SameText(ds.Name, Name) then begin FCurrentDataset := ds; Result := True; Break; end; end; end; function TRTFReportEngine.GetFieldText(const FieldName: String): String; var lField: TField; begin if not Assigned(FCurrentDataset) then Error('Current dataset not set'); lField := FCurrentDataset.FieldByName(FieldName); if not Assigned(lField) then Error(Format('Fieldname not found: "%s.%s"', [FCurrentDataset.Name, FieldName])); Result := lField.AsWideString; end; function TRTFReportEngine.GetOutput: string; begin Result := FOutput; end; function TRTFReportEngine.GetVar(const AName: string): string; begin if not FVariables.TryGetValue(AName, Result) then Result := ''; end; function TRTFReportEngine.MatchEndTag: Boolean; begin Result := (FInputString.Chars[FCharIndex] = '\') and (FInputString.Chars[FCharIndex + 1] = '\'); if Result then Inc(FCharIndex, 2); end; function TRTFReportEngine.MatchField(var aDataSet: String; var aFieldName: String): Boolean; begin Result := False; if not MatchSymbol(':') then Exit; if not MatchIdentifier(aDataSet) then Error('Expected dataset name'); if not MatchSymbol('.') then Error('Expected "."'); if not MatchIdentifier(aFieldName) then Error('Expected field name'); Result := True; end; function TRTFReportEngine.MatchIdentifier(var aIdentifier: String): Boolean; begin aIdentifier := ''; Result := False; if CharInSet(FInputString.Chars[FCharIndex], IdenfierAllowedFirstChars) then begin while CharInSet(FInputString.Chars[FCharIndex], IdenfierAllowedChars) do begin aIdentifier := aIdentifier + FInputString.Chars[FCharIndex]; Inc(FCharIndex); end; Result := True; end end; function TRTFReportEngine.MatchReset(var aDataSet: String): Boolean; begin if not MatchSymbol('reset') then Exit(False); Result := MatchSymbol('(') and MatchIdentifier(aDataSet) and MatchSymbol(')'); end; function TRTFReportEngine.MatchStartTag: Boolean; begin Result := (FInputString.Chars[FCharIndex] = '\') and (FInputString.Chars[FCharIndex + 1] = '\'); if Result then Inc(FCharIndex, 2); end; function TRTFReportEngine.MatchSymbol(const Symbol: String): Boolean; var lSymbolIndex: Integer; lSavedCharIndex: Int64; begin if Symbol.IsEmpty then Exit(True); lSavedCharIndex := FCharIndex; lSymbolIndex := 0; // lChar := FInputString.Chars[FCharIndex]; while FInputString.Chars[FCharIndex] = Symbol.Chars[lSymbolIndex] do begin Inc(FCharIndex); Inc(lSymbolIndex); // lChar := FInputString.Chars[FCharIndex] end; Result := (lSymbolIndex > 0) and (lSymbolIndex = Length(Symbol)); if not Result then FCharIndex := lSavedCharIndex; end; procedure TRTFReportEngine.Parse(const InputString: string; const Data: TArray<TDataSet>); var lChar: Char; lVarName: string; lFuncName: String; lIdentifier: String; lDataSet: string; lFieldName: string; lIgnoreOutput: Boolean; begin lIgnoreOutput := False; FDatasets := Data; FLoopStack.Clear; FLoopIdentStack.Clear; FOutput := ''; FCharIndex := 0; FCurrentLine := 1; FCurrentColumn := 1; FInputString := InputString; while FCharIndex < InputString.Length do begin lChar := InputString.Chars[FCharIndex]; if lChar = #13 then begin Inc(FCurrentLine); FCurrentColumn := 1; end; Inc(FCurrentColumn); if MatchStartTag then begin if not lIgnoreOutput and MatchSymbol('loop') then begin if not MatchSymbol('(') then Error('Expected "("'); if not MatchIdentifier(lIdentifier) then Error('Expected identifier after "loop("'); if not MatchSymbol(')') then Error('Expected ")" after "' + lIdentifier + '"'); if not MatchEndTag then Error('Expected closing tag for "loop(' + lIdentifier + ')"'); if not SetDataSetByName(lIdentifier) then Error('Unknown dataset: ' + lIdentifier); FLoopStack.Push(FCharIndex); // lChar := FInputString.Chars[FCharIndex]; if MatchSymbol('}'#13#10'\par ') then begin FLoopIdentStack.Push(TRTFLoopControl.Create(lIdentifier, '}'#13#10'\par ')); AppendOutput('}'#13#10' '); end else begin FLoopIdentStack.Push(TRTFLoopControl.Create(lIdentifier, '')); end; lIgnoreOutput := FCurrentDataset.Eof; Continue; end; if MatchSymbol('endloop') then begin if not MatchEndTag then Error('Expected closing tag'); lIdentifier := FLoopIdentStack.Peek.Identifier; if not SetDataSetByName(lIdentifier) then Error('Invalid dataset name: ' + lIdentifier); FCurrentDataset.Next; if FCurrentDataset.Eof then begin FLoopIdentStack.Pop; FLoopStack.Pop; if lIgnoreOutput then MatchSymbol('}'); // otherwhise the rtf structure is open lIgnoreOutput := False; end else begin FCharIndex := FLoopStack.Peek; MatchSymbol(FLoopIdentStack.Peek.SymbolToConsumeAtEachIteration); AppendOutput('}'#13#10' '); end; Continue; end; if not lIgnoreOutput and MatchField(lDataSet, lFieldName) then begin if not SetDataSetByName(lDataSet) then Error('Unknown dataset: ' + lDataSet); AppendOutput(GetFieldText(lFieldName)); Continue; end; if not lIgnoreOutput and MatchReset(lDataSet) then begin SetDataSetByName(lDataSet); FCurrentDataset.First; Continue; end; if not lIgnoreOutput and MatchIdentifier(lVarName) then begin if MatchSymbol(':') then begin if lVarName.IsEmpty then Error('Invalid variable name'); if not MatchIdentifier(lFuncName) then Error('Invalid function name'); if not MatchEndTag then Error('Expected end tag'); AppendOutput(ExecuteFunction(lFuncName, GetVar(lVarName))); end else begin if not MatchEndTag then Error('Expected end tag'); AppendOutput(GetVar(lVarName)); end; end; end else begin // output verbatim if not lIgnoreOutput then AppendOutput(lChar); Inc(FCharIndex); end; end; end; procedure TRTFReportEngine.SetVar(const AName: string; AValue: string); begin FVariables.AddOrSetValue(AName, AValue); end; function CapitalizeString(const s: string; const CapitalizeFirst: Boolean): string; const ALLOWEDCHARS = ['a' .. 'z', '_']; var Index: Integer; bCapitalizeNext: Boolean; begin bCapitalizeNext := CapitalizeFirst; Result := lowercase(s); if Result <> EmptyStr then for Index := 1 to Length(Result) do if bCapitalizeNext then begin Result[Index] := UpCase(Result[Index]); bCapitalizeNext := False; end else if NOT CharInSet(Result[Index], ALLOWEDCHARS) then bCapitalizeNext := True; end; procedure TRTFReportEngine.Error(const Message: String); begin raise EParserException.CreateFmt('%s - at line %d col %d', [Message, FCurrentLine, FCurrentColumn]); end; function TRTFReportEngine.ExecuteFunction(AFunctionName, AValue: String): String; begin AFunctionName := lowercase(AFunctionName); if AFunctionName = 'upper' then Exit(UpperCase(AValue)); if AFunctionName = 'lower' then Exit(lowercase(AValue)); if AFunctionName = 'capitalize' then Exit(CapitalizeString(AValue, True)); raise EParserException.CreateFmt('Unknown function [%s]', [AFunctionName]); end; { TRTFLoopControl } class function TRTFLoopControl.Create(aIdentifier, aSymbolToConsumeAtEachIteration: String) : TRTFLoopControl; begin Result.Identifier := aIdentifier; Result.SymbolToConsumeAtEachIteration := aSymbolToConsumeAtEachIteration; end; end.
unit UDMaps; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls, UCrpe32; type TCrpeMapsDlg = class(TForm) pnlMaps: TPanel; lblNumber: TLabel; lbNumbers: TListBox; editCount: TEdit; lblCount: TLabel; GroupBox1: TGroupBox; btnBorder: TButton; btnFormat: TButton; editTop: TEdit; lblTop: TLabel; lblLeft: TLabel; editLeft: TEdit; lblSection: TLabel; editWidth: TEdit; lblWidth: TLabel; lblHeight: TLabel; editHeight: TEdit; cbSection: TComboBox; btnOk: TButton; btnClear: TButton; pcMaps: TPageControl; tsLayout: TTabSheet; tsType: TTabSheet; tsText: TTabSheet; editTitle: TEdit; lblTitle: TLabel; sbDetail: TSpeedButton; sbGroup: TSpeedButton; sbCrossTab: TSpeedButton; sbOlap: TSpeedButton; cbDontSummarizeValues: TCheckBox; lblDetail: TLabel; lblGroup: TLabel; lblCrossTab: TLabel; lblOlap: TLabel; sbRanged: TSpeedButton; sbBarChart: TSpeedButton; sbPieChart: TSpeedButton; sbGraduated: TSpeedButton; lblRanged: TLabel; lblBarChart: TLabel; lblPieChart: TLabel; lblGraduated: TLabel; sbDotDensity: TSpeedButton; sbIndividualValue: TSpeedButton; lblDotDensity: TLabel; lblIndividualValue: TLabel; gbRanged: TGroupBox; lblNumberOfIntervals: TLabel; editNumberOfIntervals: TEdit; lblDistributionMethod: TLabel; cbDistributionMethod: TComboBox; lblColorHighestInterval: TLabel; lblColorLowestInterval: TLabel; cbAllowEmptyIntervals: TCheckBox; gbLegend: TGroupBox; gbLegendTitle: TGroupBox; lblLegendTitle: TLabel; lblLegendSubTitle: TLabel; rbAuto: TRadioButton; rbSpecific: TRadioButton; editLegendTitle: TEdit; editLegendSubTitle: TEdit; rbFull: TRadioButton; rbCompact: TRadioButton; rbNone: TRadioButton; gbPieChart: TGroupBox; cbPieProportional: TCheckBox; gbDotDensity: TGroupBox; lblDotSize: TLabel; editDotSize: TEdit; lblPieSize: TLabel; editPieSize: TEdit; rgUnits: TRadioGroup; ColorDialog1: TColorDialog; gbBarChart: TGroupBox; lblBarSize: TLabel; editBarSize: TEdit; gbConditions: TGroupBox; cbOrientation: TComboBox; lblOrientation: TLabel; cbGroupSelected: TCheckBox; btnSummaryFields: TButton; btnConditionFields: TButton; cbColorHighestInterval: TColorBox; cbColorLowestInterval: TColorBox; procedure btnClearClick(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateMaps; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure editSizeEnter(Sender: TObject); procedure editSizeExit(Sender: TObject); procedure cbSectionChange(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure rbFullClick(Sender: TObject); procedure rbCompactClick(Sender: TObject); procedure rbNoneClick(Sender: TObject); procedure rgUnitsClick(Sender: TObject); procedure cbColorHighestIntervalChange(Sender: TObject); procedure rbAutoClick(Sender: TObject); procedure rbSpecificClick(Sender: TObject); procedure editLegendTitleChange(Sender: TObject); procedure editLegendSubTitleChange(Sender: TObject); procedure editTitleChange(Sender: TObject); procedure sbRangedClick(Sender: TObject); procedure sbDotDensityClick(Sender: TObject); procedure sbBarChartClick(Sender: TObject); procedure sbPieChartClick(Sender: TObject); procedure sbGraduatedClick(Sender: TObject); procedure sbIndividualValueClick(Sender: TObject); procedure editNumberOfIntervalsChange(Sender: TObject); procedure cbDistributionMethodChange(Sender: TObject); procedure cbAllowEmptyIntervalsClick(Sender: TObject); procedure editDotSizeChange(Sender: TObject); procedure editPieSizeChange(Sender: TObject); procedure cbPieProportionalClick(Sender: TObject); procedure sbDetailClick(Sender: TObject); procedure sbGroupClick(Sender: TObject); procedure sbCrossTabClick(Sender: TObject); procedure sbOlapClick(Sender: TObject); procedure cbDontSummarizeValuesClick(Sender: TObject); procedure btnFormatClick(Sender: TObject); procedure cbColorLowestIntervalChange(Sender: TObject); procedure editBarSizeChange(Sender: TObject); procedure btnSummaryFieldsClick(Sender: TObject); procedure btnConditionFieldsClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; MapIndex : smallint; PrevSize : string; CustomHighestColor : TColor; CustomLowestColor : TColor; end; var CrpeMapsDlg: TCrpeMapsDlg; bMaps : boolean; implementation {$R *.DFM} uses UCrpeUtl, UDBorder, UDFormat, UDMapSumField, UDMapCondField; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.FormCreate(Sender: TObject); begin bMaps := True; LoadFormPos(Self); btnOk.Tag := 1; MapIndex := -1; cbColorHighestInterval.Selected := clNone; cbColorLowestInterval.Selected := clNone; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.FormShow(Sender: TObject); begin pcMaps.ActivePage := tsType; pcMaps.ActivePage := tsLayout; UpdateMaps; end; {------------------------------------------------------------------------------} { UpdateMaps } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.UpdateMaps; var i : smallint; OnOff : boolean; begin MapIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin OnOff := (Cr.Maps.Count > 0); {Get Boxes Index} if OnOff then begin if Cr.Maps.ItemIndex > -1 then MapIndex := Cr.Maps.ItemIndex else MapIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff = True then begin {Fill Section ComboBox} cbSection.Items.AddStrings(Cr.SectionFormat.Names); for i := 0 to Cr.Maps.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Cr.Maps.Count); lbNumbers.ItemIndex := MapIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.lbNumbersClick(Sender: TObject); var OnOff : Boolean; begin MapIndex := lbNumbers.ItemIndex; OnOff := (Cr.Maps[MapIndex].Handle <> 0); btnBorder.Enabled := OnOff; btnFormat.Enabled := OnOff; {Layout} case Cr.Maps.Item.Layout of mlDetail : sbDetailClick(Self); mlGroup : sbGroupClick(Self); mlCrossTab : sbCrossTabClick(Self); mlOlap : sbOlapClick(Self); end; cbDontSummarizeValues.Checked := Cr.Maps.Item.DontSummarizeValues; {Type} case Cr.Maps.Item.MapType of mttRanged : sbRangedClick(Self); mttBarChart : sbBarChartClick(Self); mttPieChart : sbPieChartClick(Self); mttGraduated : sbGraduatedClick(Self); mttDotDensity : sbDotDensityClick(Self); mttIndividualValue : sbIndividualValueClick(Self); end; {Text} editTitle.Text := Cr.Maps.Item.Title; case Cr.Maps.Item.Legend of mlFull : rbFullClick(Self); mlCompact : rbCompactClick(Self); mlNone : rbNoneClick(Self); end; case Cr.Maps.Item.LegendTitleType of mltAuto : rbAutoClick(Self); mltSpecific : rbSpecificClick(Self); end; {Formatting} cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Maps.Item.Section); rgUnitsClick(Self); end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TSpeedButton then TSpeedButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TColorBox then TColorBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TRadioButton then TRadioButton(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { sbDetailClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbDetailClick(Sender: TObject); begin sbDetail.Down := True; gbConditions.Visible := False; Cr.Maps.Item.Layout := mlDetail; end; {------------------------------------------------------------------------------} { sbGroupClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbGroupClick(Sender: TObject); begin sbGroup.Down := True; gbConditions.Visible := False; Cr.Maps.Item.Layout := mlGroup; end; {------------------------------------------------------------------------------} { sbCrossTabClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbCrossTabClick(Sender: TObject); begin sbCrossTab.Down := True; Cr.Maps.Item.Layout := mlCrossTab; gbConditions.Visible := True; cbOrientation.ItemIndex := Ord(Cr.Maps.Item.Orientation); cbGroupSelected.Checked := Cr.Maps.Item.GroupSelected; end; {------------------------------------------------------------------------------} { sbOlapClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbOlapClick(Sender: TObject); begin sbOlap.Down := True; Cr.Maps.Item.Layout := mlOlap; gbConditions.Visible := True; cbOrientation.ItemIndex := Ord(Cr.Maps.Item.Orientation); cbGroupSelected.Checked := Cr.Maps.Item.GroupSelected; end; {------------------------------------------------------------------------------} { editNumberOfIntervalsChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editNumberOfIntervalsChange(Sender: TObject); begin if IsNumeric(editNumberOfIntervals.Text) then Cr.Maps.Item.NumberOfIntervals := StrToInt(editNumberOfIntervals.Text) end; {------------------------------------------------------------------------------} { cbDistributionMethodChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbDistributionMethodChange(Sender: TObject); begin Cr.Maps.Item.DistributionMethod := TCrMapDistributionMethod(cbDistributionMethod.ItemIndex); end; {------------------------------------------------------------------------------} { cbColorHighestIntervalChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbColorHighestIntervalChange(Sender: TObject); begin Cr.Maps.Item.ColorHighestInterval := cbColorHighestInterval.Selected; UpdateMaps; end; {------------------------------------------------------------------------------} { cbColorLowestIntervalChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbColorLowestIntervalChange(Sender: TObject); begin Cr.Maps.Item.ColorLowestInterval := cbColorLowestInterval.Selected; UpdateMaps; end; {------------------------------------------------------------------------------} { cbAllowEmptyIntervalsClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbAllowEmptyIntervalsClick(Sender: TObject); begin Cr.Maps.Item.AllowEmptyIntervals := cbAllowEmptyIntervals.Checked; end; {------------------------------------------------------------------------------} { sbRangedClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbRangedClick(Sender: TObject); begin sbRanged.Down := True; Cr.Maps.Item.MapType := mttRanged; gbPieChart.Visible := False; gbBarChart.Visible := False; gbDotDensity.Visible := False; gbRanged.Visible := True; editNumberOfIntervals.Text := IntToStr(Cr.Maps.Item.NumberOfIntervals); cbDistributionMethod.ItemIndex := Ord(Cr.Maps.Item.DistributionMethod); cbColorHighestInterval.Selected := Cr.Maps.Item.ColorHighestInterval; cbColorLowestInterval.Selected := Cr.Maps.Item.ColorLowestInterval; cbAllowEmptyIntervals.Checked := Cr.Maps.Item.AllowEmptyIntervals; end; {------------------------------------------------------------------------------} { sbDotDensityClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbDotDensityClick(Sender: TObject); begin sbDotDensity.Down := True; Cr.Maps.Item.MapType := mttDotDensity; gbPieChart.Visible := False; gbBarChart.Visible := False; gbDotDensity.Visible := True; gbRanged.Visible := False; editDotSize.Text := IntToStr(Cr.Maps.Item.DotSize); end; {------------------------------------------------------------------------------} { sbBarChartClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbBarChartClick(Sender: TObject); begin sbBarChart.Down := True; Cr.Maps.Item.MapType := mttBarChart; gbPieChart.Visible := False; gbBarChart.Visible := True; gbDotDensity.Visible := False; gbRanged.Visible := False; editBarSize.Text := IntToStr(Cr.Maps.Item.BarSize); end; {------------------------------------------------------------------------------} { sbPieChartClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbPieChartClick(Sender: TObject); begin sbPieChart.Down := True; Cr.Maps.Item.MapType := mttPieChart; gbPieChart.Visible := True; gbBarChart.Visible := False; gbDotDensity.Visible := False; gbRanged.Visible := False; editPieSize.Text := IntToStr(Cr.Maps.Item.PieSize); cbPieProportional.Checked := Cr.Maps.Item.PieProportional; end; {------------------------------------------------------------------------------} { sbGraduatedClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbGraduatedClick(Sender: TObject); begin sbGraduated.Down := True; Cr.Maps.Item.MapType := mttGraduated; gbPieChart.Visible := False; gbBarChart.Visible := False; gbDotDensity.Visible := False; gbRanged.Visible := False; end; {------------------------------------------------------------------------------} { sbIndividualValueClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.sbIndividualValueClick(Sender: TObject); begin sbIndividualValue.Down := True; Cr.Maps.Item.MapType := mttIndividualValue; gbPieChart.Visible := False; gbBarChart.Visible := False; gbDotDensity.Visible := False; gbRanged.Visible := False; end; {------------------------------------------------------------------------------} { editDotSizeChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editDotSizeChange(Sender: TObject); begin if IsNumeric(editDotSize.Text) then Cr.Maps.Item.DotSize := StrToInt(editDotSize.Text) end; {------------------------------------------------------------------------------} { editBarSizeChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editBarSizeChange(Sender: TObject); begin if IsNumeric(editBarSize.Text) then Cr.Maps.Item.BarSize := StrToInt(editBarSize.Text) end; {------------------------------------------------------------------------------} { editPieSizeChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editPieSizeChange(Sender: TObject); begin if IsNumeric(editPieSize.Text) then Cr.Maps.Item.PieSize := StrToInt(editPieSize.Text) end; {------------------------------------------------------------------------------} { cbPieProportionalClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbPieProportionalClick(Sender: TObject); begin Cr.Maps.Item.PieProportional := cbPieProportional.Checked; end; {------------------------------------------------------------------------------} { cbDontSummarizeValuesClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbDontSummarizeValuesClick(Sender: TObject); begin Cr.Maps.Item.DontSummarizeValues := cbDontSummarizeValues.Checked; end; {------------------------------------------------------------------------------} { editSizeEnter } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { editSizeExit } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editSizeExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.Maps.Item.Top := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Maps.Item.Left := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Maps.Item.Width := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Maps.Item.Height := InchesStrToTwips(TEdit(Sender).Text); UpdateMaps; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.Maps.Item.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Maps.Item.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Maps.Item.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Maps.Item.Height := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { editTitleChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editTitleChange(Sender: TObject); begin Cr.Maps.Item.Title := editTitle.Text; end; {------------------------------------------------------------------------------} { rbFullClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rbFullClick(Sender: TObject); begin rbAuto.Enabled := True; rbSpecific.Enabled := True; editLegendTitle.Enabled := rbSpecific.Checked; editLegendTitle.Color := ColorState(rbSpecific.Checked); editLegendSubTitle.Enabled := rbSpecific.Checked; editLegendSubTitle.Color := ColorState(rbSpecific.Checked); Cr.Maps.Item.Legend := mlFull; end; {------------------------------------------------------------------------------} { rbCompactClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rbCompactClick(Sender: TObject); begin rbAuto.Enabled := False; rbSpecific.Enabled := False; editLegendTitle.Enabled := False; editLegendTitle.Color := ColorState(False); editLegendSubTitle.Enabled := False; editLegendSubTitle.Color := ColorState(False); Cr.Maps.Item.Legend := mlCompact; end; {------------------------------------------------------------------------------} { rbNoneClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rbNoneClick(Sender: TObject); begin rbAuto.Enabled := False; rbSpecific.Enabled := False; editLegendTitle.Enabled := False; editLegendTitle.Color := ColorState(False); editLegendSubTitle.Enabled := False; editLegendSubTitle.Color := ColorState(False); Cr.Maps.Item.Legend := mlNone; end; {------------------------------------------------------------------------------} { rbAutoClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rbAutoClick(Sender: TObject); begin Cr.Maps.Item.LegendTitleType := mltAuto; editLegendTitle.Color := ColorState(False); editLegendTitle.Enabled := False; editLegendSubTitle.Color := ColorState(False); editLegendSubTitle.Enabled := False; end; {------------------------------------------------------------------------------} { rbSpecificClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rbSpecificClick(Sender: TObject); begin Cr.Maps.Item.LegendTitleType := mltSpecific; editLegendTitle.Color := ColorState(True); editLegendTitle.Enabled := True; editLegendSubTitle.Color := ColorState(True); editLegendSubTitle.Enabled := True; end; {------------------------------------------------------------------------------} { editLegendTitleChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editLegendTitleChange(Sender: TObject); begin Cr.Maps.Item.LegendTitle := editLegendTitle.Text; end; {------------------------------------------------------------------------------} { editLegendSubTitleChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.editLegendSubTitleChange(Sender: TObject); begin Cr.Maps.Item.LegendSubTitle := editLegendSubTitle.Text; end; {------------------------------------------------------------------------------} { btnSummaryFieldsClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnSummaryFieldsClick(Sender: TObject); begin CrpeMapSummaryFieldsDlg := TCrpeMapSummaryFieldsDlg.Create(Application); CrpeMapSummaryFieldsDlg.Crs := Cr.Maps.Item.SummaryFields; CrpeMapSummaryFieldsDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnConditionFieldsClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnConditionFieldsClick(Sender: TObject); begin CrpeMapConditionFieldsDlg := TCrpeMapConditionFieldsDlg.Create(Application); CrpeMapConditionFieldsDlg.Crs := Cr.Maps.Item.ConditionFields; CrpeMapConditionFieldsDlg.ShowModal; end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editTop.Text := TwipsToInchesStr(Cr.Maps.Item.Top); editLeft.Text := TwipsToInchesStr(Cr.Maps.Item.Left); editWidth.Text := TwipsToInchesStr(Cr.Maps.Item.Width); editHeight.Text := TwipsToInchesStr(Cr.Maps.Item.Height); end else {twips} begin editTop.Text := IntToStr(Cr.Maps.Item.Top); editLeft.Text := IntToStr(Cr.Maps.Item.Left); editWidth.Text := IntToStr(Cr.Maps.Item.Width); editHeight.Text := IntToStr(Cr.Maps.Item.Height); end; end; {------------------------------------------------------------------------------} { cbSectionChange } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.cbSectionChange(Sender: TObject); begin Cr.Maps.Item.Section := cbSection.Items[cbSection.ItemIndex]; end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.Maps.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.Maps.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnClearClick(Sender: TObject); begin Cr.Maps.Clear; UpdateMaps; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateMaps call} if (not IsStrEmpty(Cr.ReportName)) and (MapIndex > -1) then begin editSizeExit(editTop); editSizeExit(editLeft); editSizeExit(editWidth); editSizeExit(editHeight); end; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeMapsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bMaps := False; Release; end; end.
{----------------------------------------------------------------------------- Unit Name: dlgFindInFiles Author: Kiriakos Vlahos Date: 20-May-2005 Purpose: Find in Files dialog History: Based on code from GExperts and covered by its licence GExperts License Agreement GExperts is copyright 1996-2005 by GExperts, Inc, Erik Berry, and several other authors who have submitted their code for inclusion. This license agreement only covers code written by GExperts, Inc and Erik Berry. You should contact the other authors concerning their respective copyrights and conditions. The rules governing the use of GExperts and the GExperts source code are derived from the official Open Source Definition, available at http://www.opensource.org. The conditions and limitations are as follows: * Usage of GExperts binary distributions is permitted for all developers. You may not use the GExperts source code to develop proprietary or commercial products including plugins or libraries for those products. You may use the GExperts source code in an Open Source project, under the terms listed below. * You may not use the GExperts source code to create and distribute custom versions of GExperts under the "GExperts" name. If you do modify and distribute custom versions of GExperts, the binary distribution must be named differently and clearly marked so users can tell they are not using the official GExperts distribution. A visible and unmodified version of this license must appear in any modified distribution of GExperts. * Custom distributions of GExperts must include all of the custom changes as a patch file that can be applied to the original source code. This restriction is in place to protect the integrity of the original author's source code. No support for modified versions of GExperts will be provided by the original authors or on the GExperts mailing lists. * All works derived from GExperts must be distributed under a license compatible with this license and the official Open Source Definition, which can be obtained from http://www.opensource.org/. * Please note that GExperts, Inc. and the other contributing authors hereby state that this package is provided "as is" and without any express or implied warranties, including, but not without limitation, the implied warranties of merchantability and fitness for a particular purpose. In other words, we accept no liability for any damage that may result from using GExperts or programs that use the GExperts source code. -----------------------------------------------------------------------------} unit dlgFindInFiles; interface uses Classes, Controls, Graphics, Forms, StdCtrls, cFindInFiles, JvAppStorage; type TFindInFilesDialog = class(TForm) lblFind: TLabel; cbText: TComboBox; gbxOptions: TGroupBox; cbNoCase: TCheckBox; cbNoComments: TCheckBox; gbxWhere: TGroupBox; rbOpenFiles: TRadioButton; rbDirectories: TRadioButton; gbxDirectories: TGroupBox; lblMasks: TLabel; cbMasks: TComboBox; cbInclude: TCheckBox; btnOK: TButton; btnCancel: TButton; cbWholeWord: TCheckBox; rbCurrentOnly: TRadioButton; btnHelp: TButton; cbRegEx: TCheckBox; cbDirectory: TComboBox; btnBrowse: TButton; lblDirectory: TLabel; procedure btnBrowseClick(Sender: TObject); procedure rbDirectoriesClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure cbDirectoryDropDown(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private FFindInFilesExpert: TFindInFilesExpert; procedure EnableDirectoryControls(New: Boolean); procedure LoadFormSettings; procedure SaveFormSettings; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RetrieveSettings(var Value: TGrepSettings); property FindInFilesExpert: TFindInFilesExpert read FFindInFilesExpert; end; implementation {$R *.dfm} uses SysUtils, Windows, Messages, Menus, JvBrowseFolder, {GX_GrepResults, GX_GrepOptions,} Math, JclFileUtils, JclStrings, uEditAppIntfs, frmFindResults, dmCommands; function GetScrollbarWidth: Integer; begin Result := GetSystemMetrics(SM_CXVSCROLL); end; procedure TFindInFilesDialog.btnBrowseClick(Sender: TObject); var Temp: string; begin Temp := cbDirectory.Text; if BrowseDirectory(Temp, 'Directory To Search', 0) then cbDirectory.Text := Temp; end; procedure TFindInFilesDialog.EnableDirectoryControls(New: Boolean); begin cbDirectory.Enabled := New; cbMasks.Enabled := New; cbInclude.Enabled := New; btnBrowse.Enabled := New; if not New then begin cbDirectory.Color := clBtnface; cbMasks.Color := clBtnface; end else begin cbDirectory.Color := clWindow; cbMasks.Color := clWindow; end end; procedure TFindInFilesDialog.rbDirectoriesClick(Sender: TObject); begin EnableDirectoryControls(rbDirectories.Checked); end; procedure TFindInFilesDialog.btnHelpClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TFindInFilesDialog.cbDirectoryDropDown(Sender: TObject); var i: Integer; MaxWidth: Integer; Bitmap: Graphics.TBitmap; begin MaxWidth := cbDirectory.Width; Bitmap := Graphics.TBitmap.Create; try Bitmap.Canvas.Font.Assign(cbDirectory.Font); for i := 0 to cbDirectory.Items.Count - 1 do MaxWidth := Max(MaxWidth, Bitmap.Canvas.TextWidth(cbDirectory.Items[i]) + 10); finally; FreeAndNil(Bitmap); end; if cbDirectory.Items.Count > cbDirectory.DropDownCount then Inc(MaxWidth, GetScrollbarWidth); MaxWidth := Min(400, MaxWidth); if MaxWidth > cbDirectory.Width then SendMessage(cbDirectory.Handle, CB_SETDROPPEDWIDTH, MaxWidth, 0) else SendMessage(cbDirectory.Handle, CB_SETDROPPEDWIDTH, 0, 0) end; procedure TFindInFilesDialog.btnOKClick(Sender: TObject); resourcestring SSpecifiedDirectoryDoesNotExist = 'The search directory %s does not exist'; var i: Integer; Dirs: TStringList; begin if rbDirectories.Checked then begin if Trim(cbDirectory.Text) = '' then cbDirectory.Text := GetCurrentDir; Dirs := TStringList.Create; try StrToStrings(cbDirectory.Text, ';', Dirs, False); for i := 0 to Dirs.Count - 1 do begin Dirs[i] := ExpandFileName(PathAddSeparator(Dirs[i])); if not DirectoryExists(Dirs[i]) then raise Exception.CreateResFmt(@SSpecifiedDirectoryDoesNotExist, [Dirs[i]]); if i < Dirs.Count - 1 then Dirs[i] := Dirs[i] + ';' end; cbDirectory.Text := StringReplace(Dirs.Text, #13#10, '', [rfReplaceAll]); finally FreeAndNil(Dirs); end; end; ModalResult := mrOk; end; constructor TFindInFilesDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); LoadFormSettings; end; destructor TFindInFilesDialog.Destroy; begin SaveFormSettings; inherited Destroy; end; procedure TFindInFilesDialog.SaveFormSettings; begin AddMRUString(cbText.Text, FFindInFilesExpert.SearchList, False); AddMRUString(cbDirectory.Text, FFindInFilesExpert.DirList, True); AddMRUString(cbMasks.Text, FFindInFilesExpert.MaskList, False); FFindInFilesExpert.GrepNoCase := cbNoCase.Checked; FFindInFilesExpert.GrepNoComments := cbNoComments.Checked; FFindInFilesExpert.GrepSub := cbInclude.Checked; FFindInFilesExpert.GrepWholeWord := cbWholeWord.Checked; FFindInFilesExpert.GrepRegEx := cbRegEx.Checked; if rbCurrentOnly.Checked then FFindInFilesExpert.GrepSearch := 0 else if rbOpenFiles.Checked then FFindInFilesExpert.GrepSearch := 1 else if rbDirectories.Checked then FFindInFilesExpert.GrepSearch := 2; end; procedure TFindInFilesDialog.LoadFormSettings; function RetrieveEditorBlockSelection: string; var Temp: string; i: Integer; begin if Assigned(GI_ActiveEditor) then Temp := GI_ActiveEditor.SynEdit.SelText else Temp := ''; // Only use the currently selected text if the length is between 1 and 80 if (Length(Trim(Temp)) >= 1) and (Length(Trim(Temp)) <= 80) then begin i := Min(Pos(#13, Temp), Pos(#10, Temp)); if i > 0 then Temp := Copy(Temp, 1, i - 1); Temp := Temp; end else Temp := ''; Result := Temp; end; procedure SetSearchPattern(Str: string); begin cbText.Text := Str; cbText.SelectAll; end; procedure SetupPattern; var Selection: string; begin Selection := RetrieveEditorBlockSelection; if (Trim(Selection) = '') and CommandsDataModule.PyIDEOptions.SearchTextAtCaret then begin if Assigned(GI_ActiveEditor) then with GI_ActiveEditor.SynEdit do Selection := GetWordAtRowCol(CaretXY) else Selection := ''; end; if (Selection = '') and (cbText.Items.Count > 0) then Selection := cbText.Items[0]; SetSearchPattern(Selection); end; begin FFindInFilesExpert := FindResultsWindow.FindInFilesExpert; cbText.Items.Assign(FFindInFilesExpert.SearchList); cbDirectory.Items.Assign(FFindInFilesExpert.DirList); cbMasks.Items.Assign(FFindInFilesExpert.MaskList); if FFindInFilesExpert.GrepSave then begin cbNoCase.Checked := FFindInFilesExpert.GrepNoCase; cbNoComments.Checked := FFindInFilesExpert.GrepNoComments; cbInclude.Checked := FFindInFilesExpert.GrepSub; cbWholeWord.Checked := FFindInFilesExpert.GrepWholeWord; cbRegEx.Checked := FFindInFilesExpert.GrepRegEx; case FFindInFilesExpert.GrepSearch of 0: rbCurrentOnly.Checked := True; 1: rbOpenFiles.Checked := True; 2: rbDirectories.Checked := True; end; if cbText.Items.Count > 0 then cbText.Text := cbText.Items[0]; if cbDirectory.Items.Count > 0 then cbDirectory.Text := cbDirectory.Items[0]; if cbMasks.Items.Count > 0 then cbMasks.Text := cbMasks.Items[0]; end; SetupPattern; rbOpenFiles.Enabled := GI_EditorFactory.Count > 0; rbCurrentOnly.Enabled := GI_EditorFactory.Count > 0; EnableDirectoryControls(rbDirectories.Checked); end; procedure TFindInFilesDialog.RetrieveSettings(var Value: TGrepSettings); begin Value.NoComments := cbNoComments.Checked; Value.NoCase := cbNoCase.Checked; Value.WholeWord := cbWholeWord.Checked; Value.RegEx := cbRegEx.Checked; Value.Pattern := cbText.Text; Value.IncludeSubdirs := cbInclude.Checked; Value.Mask := ''; Value.Directories := ''; if rbCurrentOnly.Checked then Value.FindInFilesAction := gaCurrentOnlyGrep else if rbOpenFiles.Checked then Value.FindInFilesAction := gaOpenFilesGrep else begin Value.FindInFilesAction := gaDirGrep; Value.Mask := cbMasks.Text; Value.Directories := cbDirectory.Text; end; end; procedure TFindInFilesDialog.FormShow(Sender: TObject); begin Constraints.MaxHeight := Height; Constraints.MinHeight := Height; Constraints.MinWidth := Width; end; end.
unit Layout; interface uses Types, Classes, Graphics, Style; type TNode = class; TNodeList = class; TBox = class; TBoxList = class; TContext = class; TContextClass = class of TContext; TLayout = class; // TBox = class public Node: TNode; Left: Integer; Top: Integer; Width: Integer; Height: Integer; Offset: TPoint; Boxes: TBoxList; { Name: string; Text: string; Context: TDisplay; } constructor Create; destructor Destroy; override; end; // TBoxList = class(TList) private function GetBox(inIndex: Integer): TBox; procedure SetBox(inIndex: Integer; const Value: TBox); function GetMax: Integer; public function NewBox: TBox; property Box[inIndex: Integer]: TBox read GetBox write SetBox; default; property Max: Integer read GetMax; end; // TNode = class class function GetContextClass: TContextClass; virtual; public Nodes: TNodeList; Style: TStyle; Text: string; constructor Create; virtual; destructor Destroy; override; { Element: string; // attributes // styles function NextBox(inContext: TContext; var inBox: TBox): Boolean; virtual; abstract; procedure InitBoxes; virtual; abstract; procedure Render(inRenderer: TRenderer; const inBox: TBox); virtual; abstract; } procedure InitBox(inLayout: TLayout; var inBox: TBox); virtual; property ContextClass: TContextClass read GetContextClass; end; // TNodeList = class(TList) protected function GetMax: Integer; function GetNode(inIndex: Integer): TNode; procedure SetNode(inIndex: Integer; const Value: TNode); public property Max: Integer read GetMax; property Node[inIndex: Integer]: TNode read GetNode write SetNode; default; end; // TContext = class private Layout: TLayout; Boxes: TBoxList; protected function AdjustSize(inSize: TPoint; inBox: TBox): TPoint; virtual; abstract; function BuildBox(inNode: TNode): TBox; virtual; public function BuildBoxes(inNodes: TNodeList; inIndex: Integer): Integer; procedure MeasureBox(inBox: TBox); constructor Create(inLayout: TLayout; inBoxes: TBoxList); end; // TBlockContext = class(TContext) protected function AdjustSize(inSize: TPoint; inBox: TBox): TPoint; override; function BuildBox(inNode: TNode): TBox; override; end; // TInlineContext = class(TContext) protected function AdjustSize(inSize: TPoint; inBox: TBox): TPoint; override; function BuildBox(inNode: TNode): TBox; override; end; // TLayout = class protected function BuildContextBoxes(inContextClass: TContextClass; inNodes: TNodeList; inIndex: Integer; inBoxes: TBoxList): Integer; public Canvas: TCanvas; constructor Create(inCanvas: TCanvas); function BuildBoxes(inNodes: TNodeList): TBoxList; end; implementation uses Math; { TBox } constructor TBox.Create; begin end; destructor TBox.Destroy; begin Boxes.Free; inherited; end; { TBoxList } function TBoxList.NewBox: TBox; begin Result := TBox.Create; Add(Result); end; function TBoxList.GetBox(inIndex: Integer): TBox; begin Result := TBox(Items[inIndex]); end; function TBoxList.GetMax: Integer; begin Result := Pred(Count); end; procedure TBoxList.SetBox(inIndex: Integer; const Value: TBox); begin Items[inIndex] := Value; end; { TNode } class function TNode.GetContextClass: TContextClass; begin Result := TBlockContext; end; constructor TNode.Create; begin Style := TStyle.Create; end; destructor TNode.Destroy; begin Style.Free; inherited; end; procedure TNode.InitBox(inLayout: TLayout; var inBox: TBox); begin // end; { TNodeList } function TNodeList.GetMax: Integer; begin Result := Pred(Count); end; function TNodeList.GetNode(inIndex: Integer): TNode; begin Result := TNode(Items[inIndex]); end; procedure TNodeList.SetNode(inIndex: Integer; const Value: TNode); begin Items[inIndex] := Value; end; { TLayout } constructor TLayout.Create(inCanvas: TCanvas); begin Canvas := inCanvas; end; function TLayout.BuildContextBoxes(inContextClass: TContextClass; inNodes: TNodeList; inIndex: Integer; inBoxes: TBoxList): Integer; begin with inContextClass.Create(Self, inBoxes) do try Result := BuildBoxes(inNodes, inIndex); finally Free; end; end; function TLayout.BuildBoxes(inNodes: TNodeList): TBoxList; procedure FillBoxes(inBoxes: TBoxList); var i: Integer; begin i := 0; while (i < inNodes.Count) do i := BuildContextBoxes(inNodes[i].ContextClass, inNodes, i, inBoxes); end; begin Result := TBoxList.Create; if (inNodes <> nil) then FillBoxes(Result); end; { TContext } constructor TContext.Create(inLayout: TLayout; inBoxes: TBoxList); begin Layout := inLayout; Boxes := inBoxes; //Width := Renderer.Width; //SetContext; end; function TContext.BuildBoxes(inNodes: TNodeList; inIndex: Integer): Integer; begin while (inIndex < inNodes.Count) and (Self is inNodes[inIndex].ContextClass) do begin BuildBox(inNodes[inIndex]); Inc(inIndex); end; Result := inIndex; end; function TContext.BuildBox(inNode: TNode): TBox; begin Result := Boxes.NewBox; with Result do begin Node := inNode; Boxes := Layout.BuildBoxes(inNode.Nodes); end; MeasureBox(Result); inNode.InitBox(Layout, Result); end; procedure TContext.MeasureBox(inBox: TBox); function AddPt(inP0, inP1: TPoint): TPoint; begin Result := Point(inP0.X + inP1.X, inP1.Y + inP1.Y); end; procedure MeasureBoxes(inBoxes: TBoxList); var i: Integer; begin for i := 0 to inBoxes.Max do MeasureBox(inBoxes[i]); end; function CalcBoxSize(inBoxes: TBoxList): TPoint; var i: Integer; begin Result := Point(0, 0); for i := 0 to inBoxes.Max do Result := AddPt(Result, inBoxes[i].Offset); // Result := AdjustSize(Result, inBoxes[i]); end; begin if {(inBox.Height <= 0) and} (inBox.Boxes.Count > 0) then begin MeasureBoxes(inBox.Boxes); with CalcBoxSize(inBox.Boxes) do begin inBox.Width := X; inBox.Height := Y; end; end; end; { TBlockContext } function TBlockContext.AdjustSize(inSize: TPoint; inBox: TBox): TPoint; begin Result.X := inSize.X + inBox.Width; Result.Y := inSize.Y + inBox.Height; end; function TBlockContext.BuildBox(inNode: TNode): TBox; begin Result := inherited BuildBox(inNode); { with Result do begin //Height := 100; //Width := 300; //Offset := Point(0, Height); end; } end; { TInlineContext } function TInlineContext.AdjustSize(inSize: TPoint; inBox: TBox): TPoint; begin Result.X := inSize.X + inBox.Width; Result.Y := Max(inSize.Y, inBox.Height); end; function TInlineContext.BuildBox(inNode: TNode): TBox; begin Result := inherited BuildBox(inNode); { with Result do begin //Height := 100; //Width := 50; //Offset := Point(Width, 0); end; } end; end.
unit uParseManager; {$I ..\Include\IntXLib.inc} interface uses SysUtils, uIParser, uEnums, uPow2Parser, uClassicParser, uFastParser, uIntX, uIntXLibTypes; type /// <summary> /// Used to retrieve needed parser. /// </summary> TParseManager = class sealed(TObject) public /// <summary> /// Constructor. /// </summary> class constructor Create(); /// <summary> /// Returns parser instance for given parse mode. /// </summary> /// <param name="mode">Parse mode.</param> /// <returns>Parser instance.</returns> /// <exception cref="EArgumentOutOfRangeException"><paramref name="mode" /> is out of range.</exception> class function GetParser(mode: TParseMode): IIParser; /// <summary> /// Returns current parser instance. /// </summary> /// <returns>Current parser instance.</returns> class function GetCurrentParser(): IIParser; class var /// <summary> /// Classic parser instance. /// </summary> FClassicParser: IIParser; /// <summary> /// Fast parser instance. /// </summary> FFastParser: IIParser; end; implementation // static class constructor class constructor TParseManager.Create(); var Pow2Parser: IIParser; mclassicParser: IIParser; begin // Create new pow2 parser instance Pow2Parser := TPow2Parser.Create(); // Create new classic parser instance mclassicParser := TClassicParser.Create(Pow2Parser); // Fill publicity visible parser fields FClassicParser := mclassicParser; FFastParser := TFastParser.Create(Pow2Parser, mclassicParser); end; class function TParseManager.GetParser(mode: TParseMode): IIParser; begin case (mode) of TParseMode.pmFast: begin result := FFastParser; Exit; end; TParseMode.pmClassic: begin result := FClassicParser; Exit; end else begin raise EArgumentOutOfRangeException.Create('mode'); end; end; end; class function TParseManager.GetCurrentParser(): IIParser; begin result := GetParser(TIntX.GlobalSettings.ParseMode); end; end.
namespace RemObjects.Elements.System; interface uses java.util.concurrent; type FutureAnnnotation = public interface(java.lang.annotation.Annotation) end; // Action = java.lang.Runnable; // Func<T> = java.util.concurrent.Callable<T> FutureHelper = public static class public class method IsDone<T>(aFuture: Task1<T>): Boolean; class method Execute<T>(aFuture: Callable<T>): Task1<T>; class method ExecuteAsync<T>(aMethod: Callable<T>; aWantResult: Boolean): Task1<T>; class method IsDone(aFuture: Task): Boolean; class method Execute(aMethod: Runnable): Task; class method ExecuteAsync(aMethod: Runnable; aWantResult: Boolean): Task; end; NonThreadedTask = public class(Task) private public method Start(aScheduler: Executor); override; method Wait(aTimeoutMSec: Integer): Boolean; override; method Wait; override; end; NonThreadedTask1<T> = public class(Task1<T>) private public end; implementation class method FutureHelper.IsDone<T>(aFuture: Task1<T>): Boolean; begin exit aFuture.IsCompleted; end; class method FutureHelper.Execute<T>(aFuture: Callable<T>): Task1<T>; begin result := new NonThreadedTask1<T>(aFuture); result.Start; end; class method FutureHelper.ExecuteAsync<T>(aMethod: Callable<T>; aWantResult: Boolean): Task1<T>; begin result := new Task1<T>(aMethod); result.Start; end; class method FutureHelper.IsDone(aFuture: Task): Boolean; begin exit aFuture.IsCompleted; end; class method FutureHelper.Execute(aMethod: Runnable): Task; begin result := new NonThreadedTask(aMethod); result.Start; end; class method FutureHelper.ExecuteAsync(aMethod: Runnable; aWantResult: Boolean): Task; begin result := new Task(aMethod); result.Start; end; method NonThreadedTask.Wait(aTimeoutMSec: Integer): Boolean; begin var lRun := false; locking self do begin if fState = TaskState.Queued then begin fState := TaskState.Started; lRun := true; end; end; if lRun then run; exit inherited; end; method NonThreadedTask.Wait; begin var lRun := false; locking self do begin if fState = TaskState.Queued then begin fState := TaskState.Started; lRun := true; end; end; if lRun then run; inherited; end; method NonThreadedTask.Start(aScheduler: Executor); begin locking fLock do begin if fState <> TaskState.Created then raise new IllegalStateException('Task already started/queued/done'); fState := TaskState.Queued; end; end; end.
unit CatStrings; { Catarinka - String Operation functions Copyright (c) 2003-2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details IScan, SplitString, GetTextBetweenTags functions by Peter Below Note: random functions included with this library are not suitable for cryptographic purposes. } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} {$IFDEF USECROSSVCL} WinAPI.Windows, {$ENDIF} System.Classes, System.SysUtils, System.StrUtils {$IFDEF MSWINDOWS} ,System.AnsiStrings; {$ELSE} ; {$ENDIF} {$ELSE} Classes, SysUtils, StrUtils; {$ENDIF} // Useful for declaring a single record variable, instead of declaring two // variables like var somename, somevalue:string; type TCatNameValue = record name: string; value: string; end; // Useful for returning a boolean value together with a string like an error // message or an integer when calling a function type TCatFuncResult = record B: boolean; I: integer; S: string; end; type TCatCaseLabel = record name: string; id: integer; end; function After(const s, substr: string): string; function ASCIIToInt(const s: string): integer; function Base64Encode(const s: string): string; function Base64Decode(const s: string): string; function Before(const s, substr: string): string; function BeginsWith(const s, prefix: string; IgnoreCase: Boolean = false) : Boolean; overload; function BeginsWith(const s: string; const prefixes: array of string; IgnoreCase: Boolean = false): Boolean; overload; function BoolToStr(const b: Boolean): string; function BoolToYN(const b: Boolean): string; function CatAppendStr(var s:string;const astr:string;const sep:string=','):string; function CatWrapText(const text: string; const chars: integer): TStringList; function CharSetToStr(const c: TSysCharSet): string; function CombineIntArray(const p:array of integer):integer; function CommaTextToStr(const s: string): string; function ContainsAnyOfChars(const s: string; const aSet: TSysCharSet): Boolean; function ContainsAnyOfStrings(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; function ContainsAllOfStrings(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; function EndsWith(const s, prefix: string; IgnoreCase: Boolean = false) : Boolean; overload; function EndsWith(const s: string; const prefixes: array of string; IgnoreCase: Boolean = false): Boolean; overload; function ExtractFromString(const s, startstr, endstr: string): string; function ExtractNumbers(const s: string): string; function GetLineNumberByPos(const s: string; const Position: integer): integer; function GetStringLine(const s:string;const line:integer):TCatFuncResult; function GetToken(const aString, SepChar: string; const TokenNum: Integer): string; function GetValidCompName(const s: string): string; function HexToInt(const Hex: string; const WarnError: Boolean = false): integer; function HexToStr(const s: string): string; function Hex16ToStr(const s: string): string; function IIF(const Cond: Boolean; const TrueStr: String; const FalseStr: string = ''): string; overload; function IIF(const Cond: Boolean; const TrueInt: integer; const FalseInt: integer = 0): integer; overload; function IScan(ch: Char; const s: string; fromPos: integer): integer; function IsAlpha(const s: string): Boolean; function IsAlphaNumeric(const s: string): Boolean; function IsHexStr(const s: string): Boolean; function IsInteger(const s: string): Boolean; function IsLowercase(const s: string): Boolean; function IsUppercase(const s: string): Boolean; function IsRoman(const s: string): Boolean; function LastChar(const s: string): Char; function LeftPad(const s: string; const c: Char; const len: integer): string; function LeftStr(s: string; c: longword): string; function MatchIntInArray(const i: integer; aArray: array of integer): Boolean; function MatchStrInArray(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; function MemStreamToStr(m: TMemoryStream): String; function Occurs(substr, s: string): integer; function RandomCase(const s: string; const ToUpperSet: TSysCharSet = ['a' .. 'z']; const ToLowerSet: TSysCharSet = ['A' .. 'Z']): string; function RandomString(const len: integer; const chars: string = 'abcdefghijklmnopqrstuvwxyz'): string; function RemoveLastChar(const s: string): string; function RemoveNumbers(const s: string): string; function RemoveQuotes(const s: string): string; function RemoveShortcuts(const s: string): string; function RepeatString(const s: string; count: cardinal): string; function ReplaceChars(const s: string; const aSet: TSysCharSet; const repwith: Char = '_'): string; function ReplaceStr(const s, substr, repstr: string): string; function RestStr(const s: string; const index: longword): string; function RightPad(const s: string; const c: Char; const len: integer): string; function StrDecrease(const s: string; const step: integer = 1): string; function StrIncrease(const s: string; const step: integer = 1): string; function StripChars(const s: string; const aSet: TSysCharSet): string; function StripEnclosed(const s: string;const beginChar,endChar: Char): string; function StrMaxLen(const s: string; const MaxLen: integer; const AddEllipsis: Boolean = false): string; function StrToAlphaNum(const s: string): string; function StrArrayToCommaText(aArray: array of string):string; function StrToBool(const s: string): Boolean; function StrToCharSet(const s: string): TSysCharSet; function StrToCommaText(const s: string): string; function StrToHex(const s: string): string; function StrToHex16(const s: string): string; function StrToNameValue(const s: string; const aSeparator:string='='): TCatNameValue; function StrToYN(const s:string):string; function SwapCase(const s: string): string; function TitleCase(const s: string): string; {$IFDEF MSWINDOWS} // TODO: not compatible for crosscompilation procedure GetTextBetweenTags(const s, tag1, tag2: string; const list: TStrings; const includetags: Boolean = false); {$ENDIF} procedure MergeStrings(const dest, source: TStrings); procedure SplitString(const s: string; separator: Char; substrings: TStringList); {$IFDEF CHARINSET_UNAVAILABLE} function CharInSet(c: Char; CharSet: TSysCharSet): Boolean; {$ENDIF} // string list related functions function CompareStrings(sl: TStringList; Index1, Index2: integer): integer; procedure StripBlankLines(const sl: TStringList); { Case Statement with String: Since Delphi 7 to XE and most Pascal compilers don't support case statement with string, many developers created workaround methods that work similar, but I never found one I really liked, so I came up with this. It is ugly, but works very well. CatCaseLabelOf() requires an array of TCatCaseLabel Usage example: procedure TForm1.Button1Click(Sender: TObject); const c_ana = 1; c_roberto = 2; c_lucia = 3; const labels : array [1..3] of TCatCaseLabel = ( (name:'ana';id:c_ana), (name:'lucia';id:c_lucia), (name:'roberto';id:c_roberto) ); begin case CatCaseLabelOf(edit1.text,labels) of c_ana: form1.caption:='ana!'; c_roberto: form1.caption:='roberto!'; c_lucia: form1.caption:='lucia!'; else form1.Caption:=edit1.text+' not in case list!'; end; end; CatCaseOf() is a simple alternative of the above and works with an array of strings Usage example: case CatCaseOf(inputstring, ['1:dog', '2:cat', '3:bird', '3:horse']) of 1: result := 'dog'; 2: result := 'cat'; 3: result := 'bird or horse'; else result := 'nomatch'; end; CatCaseWildOf() in CatMatch.pas allows case statement based on wildcard strings } function CatCaseOf(const s: string; labels: array of string; const casesensitive: Boolean = true): integer; function CatCaseLabelOf(const s: string; labels: array of TCatCaseLabel; const casesensitive: Boolean = true): integer; function CatCaseLabelOf_GetName(const id: integer; labels: array of TCatCaseLabel): string; const CRLF = #13 + #10; implementation uses CatBase64; {$IFDEF CHARINSET_UNAVAILABLE} // Before D2009 function CharInSet(c: Char; CharSet: TSysCharSet): Boolean; begin if c in CharSet then result := true else result := false; end; {$ENDIF} function After(const s, substr: string): string; var i: integer; begin i := pos(substr, s); if i = 0 then result := emptystr else result := Copy(s, i + length(substr), length(s)); end; function ASCIIToInt(const s: string): integer; var i, len: integer; c: Char; begin result := 0; len := length(s); for i := len downto 1 do begin c := s[i]; result := result + ord(c) shl ((len - i) shl 8); end; end; function Base64Encode(const s: string): string; begin Result := CatBase64.Base64Encode(s); end; function Base64Decode(const s: string): string; begin Result := CatBase64.Base64Decode(s); end; function Before(const s, substr: string): string; var i: integer; begin i := pos(substr, s); if i = 0 then result := s else result := Copy(s, 1, i - 1); end; function BeginsWith(const s, prefix: string; IgnoreCase: Boolean = false): Boolean; begin if IgnoreCase = false then result := AnsiStartsStr(prefix, s) else result := AnsiStartsText(prefix, s); end; function BeginsWith(const s: string; const prefixes: array of string; IgnoreCase: Boolean = false): Boolean; var b: integer; begin result := false; for b := Low(prefixes) to High(prefixes) do begin if BeginsWith(s, prefixes[b], IgnoreCase) = true then begin result := true; break; end; end; end; function BoolToStr(const b: Boolean): string; begin if b = true then result := 'True' else result := 'False'; end; function BoolToYN(const b: Boolean): string; begin if b = true then result := 'Yes' else result := 'No'; end; function StrToYN(const s:string):string; begin result := BoolToYN(StrToBool(s)); end; // Appends a string with a separator string function CatAppendStr(var s:string;const astr:string;const sep:string=','):string; begin if s = emptystr then s := astr else begin s := s + sep + astr; end; end; function CatCaseOf(const s: string; labels: array of string; const casesensitive: Boolean = true): integer; var i: integer; astr: string; begin result := -1; // label not found astr := s; if casesensitive = false then begin astr := lowercase(astr); for i := low(labels) to high(labels) do labels[i] := lowercase(labels[i]); end; for i := low(labels) to high(labels) do begin if astr = after(labels[i],':') then result := StrToIntDef(before(labels[i],':'), -1); if result <> -1 then break; end; end; function CatCaseLabelOf(const s: string; labels: array of TCatCaseLabel; const casesensitive: Boolean = true): integer; overload; var i: integer; astr: string; begin result := -1; // label not found astr := s; if casesensitive = false then begin astr := lowercase(astr); for i := low(labels) to high(labels) do labels[i].name := lowercase(labels[i].name); end; for i := low(labels) to high(labels) do begin if astr = labels[i].name then result := labels[i].id; if result <> -1 then break; end; end; function CatCaseLabelOf_GetName(const id: integer; labels: array of TCatCaseLabel): string; var i: integer; begin result := EmptyStr; // label not found for i := low(labels) to high(labels) do begin if id = labels[i].id then result := labels[i].name; if result <> EmptyStr then break; end; end; // Wraps a text and returns it as a stringlist function CatWrapText(const text: string; const chars: integer): TStringList; var sl: TStringList; P, ln: integer; s, newln: string; begin sl := TStringList.Create; result := sl; if length(text) = 0 then Exit; ln := 0; sl.Add(emptystr); s := text + ' '; P := pos(' ', s); while P <> 0 do begin newln := Copy(s, 1, P); if (length(sl.Strings[ln]) + length(newln)) < (chars + 1) then sl.Strings[ln] := sl.Strings[ln] + newln else begin sl.Add(newln); inc(ln); end; Delete(s, 1, P); P := pos(' ', s); end; end; function ContainsAnyOfChars(const s: string; const aSet: TSysCharSet): Boolean; var i: integer; begin result := false; for i := 1 to length(s) do begin if (CharInSet(s[i], aSet)) then begin result := true; break; end; end; end; function ContainsAllOfStrings(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; var b: integer; begin result := true; if IgnoreCase then begin s := lowercase(s); for b := Low(aArray) to High(aArray) do aArray[b] := lowercase(aArray[b]); end; for b := Low(aArray) to High(aArray) do begin if pos(aArray[b], s) = 0 then begin result := false; break; end; end; end; function ContainsAnyOfStrings(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; var b: integer; begin result := false; if IgnoreCase then begin s := lowercase(s); for b := Low(aArray) to High(aArray) do aArray[b] := lowercase(aArray[b]); end; for b := Low(aArray) to High(aArray) do begin if pos(aArray[b], s) <> 0 then begin result := true; break; end; end; end; // Useful for sorting a string list containing filenames // Usage sl.CustomSort(CompareStrings); function CompareStrings(sl: TStringList; Index1, Index2: integer): integer; begin if Length(sl[Index1]) = Length(sl[Index2]) then begin if sl[Index1] = sl[Index2] then result := 0 else if sl[Index1] < sl[Index2] then result := -1 else result := 1; end else if Length(sl[Index1]) < Length(sl[Index2]) then result := -1 else result := 1; end; function CombineIntArray(const p:array of integer):integer; var i:integer; s:string; begin s := EmptyStr; for i := low(p) to high(p) do begin if (p[i] > -1) then s := s+IntToStr(p[i]); end; result := StrToInt(s); end; function EndsWith(const s, prefix: string; IgnoreCase: Boolean = false) : Boolean; begin if IgnoreCase = false then result := AnsiEndsStr(prefix, s) else result := AnsiEndsText(prefix, s); end; function EndsWith(const s: string; const prefixes: array of string; IgnoreCase: Boolean = false): Boolean; var b: integer; begin result := false; for b := Low(prefixes) to High(prefixes) do begin if EndsWith(s, prefixes[b], IgnoreCase) then begin result := true; break; end; end; end; function GetLineNumberByPos(const s: string; const Position: integer): integer; var i, ln: integer; begin result := -1; if (Position = -1) then Exit; i := 1; ln := 0; while i < Position do begin if (s[i] = #13) then ln := ln + 1; i := i + 1; end; result := ln; end; function GetStringLine(const s:string;const line:integer):TCatFuncResult; var sl: TStringList; i: integer; begin result.B := false; result.S := emptystr; sl := TStringList.Create; sl.Text := s; for i := 0 to sl.Count -1 do begin if i = line then begin result.B := true; result.S := sl[i]; break; end; end; sl.Free; end; // Returns a valid Pascal component name (stripping invalid chars) function GetValidCompName(const s: string): string; var i: integer; begin result := emptystr; for i := 1 to length(s) do begin if (CharInSet(s[i], ['0' .. '9', 'A' .. 'Z', 'a' .. 'z', '_'])) then result := result + Copy(s, i, 1); end; end; function HexToInt(const Hex: string; const WarnError: Boolean = false): integer; begin if IsHexStr(Hex) then result := StrToInt('$' + Hex) else begin if WarnError = true then raise EConvertError.Create('Invalid character in hex string') else result := 0; end; end; function IIF(const Cond: Boolean; const TrueStr: String; const FalseStr: String = ''): string; overload; begin if Cond = true then result := TrueStr else result := FalseStr; end; function IIF(const Cond: Boolean; const TrueInt: integer; const FalseInt: integer = 0): integer; overload; begin if Cond = true then result := TrueInt else result := FalseInt; end; function IsAlpha(const s: string): Boolean; var i: integer; begin result := true; for i := 1 to length(s) do if CharInSet(s[i], ['A' .. 'Z', 'a' .. 'z']) = false then begin result := false; break; end; end; function IsAlphaNumeric(const s: string): Boolean; var i: integer; alpha, num: Boolean; begin alpha := false; num := false; for i := 1 to length(s) do begin if CharInSet(s[i], ['A' .. 'Z', 'a' .. 'z']) then alpha := true else if CharInSet(s[i], ['0' .. '9']) then num := true; end; result := alpha and num; end; function IsInteger(const s: string): Boolean; var v, c: integer; begin Val(s, v, c); if v = 0 then begin // avoid compiler warning end; result := c = 0; end; // Returns true if the string contains valid hexadecimal digits function IsHexStr(const s: string): Boolean; var i: integer; begin result := true; for i := 1 to length(s) do if not(CharInSet(s[i], ['0' .. '9', 'A' .. 'F', 'a' .. 'f'])) then begin result := false; break; end; end; function IsUppercase(const s: string): Boolean; var i: integer; begin result := false; for i := 1 to length(s) do if CharInSet(s[i], ['a' .. 'z']) then Exit; result := true; end; function IsLowercase(const s: string): Boolean; var i: integer; begin result := false; for i := 1 to length(s) do if CharInSet(s[i], ['A' .. 'Z']) then Exit; result := true; end; function IsRoman(const s: string): Boolean; var i: integer; begin result := true; for i := 1 to length(s) do begin if CharInSet(UpCase(s[i]), ['I', 'V', 'X', 'L', 'C', 'D', 'M']) = false then begin result := false; Exit; end; end; end; function LastChar(const s: string): Char; begin if s = emptystr then result := #0 else result := s[length(s)]; end; function LeftPad(const s: string; const c: Char; const len: integer): string; var i: integer; begin result := s; i := len - length(s); if i < 1 then Exit; result := s + StringOfChar(c, i); end; function RightPad(const s: string; const c: Char; const len: integer): string; var i: integer; begin result := s; i := len - length(s); if i < 1 then Exit; result := StringOfChar(c, i) + s; end; function LeftStr(s: string; c: longword): string; begin result := Copy(s, 1, c); end; function MatchIntInArray(const i: integer; aArray: array of integer): Boolean; var b: integer; begin result := false; for b := Low(aArray) to High(aArray) do begin if i = aArray[b] then begin result := true; break; end; end; end; function MatchStrInArray(s: string; aArray: array of string; IgnoreCase: Boolean = false): Boolean; var b: integer; begin result := false; if IgnoreCase then begin s := lowercase(s); for b := Low(aArray) to High(aArray) do aArray[b] := lowercase(aArray[b]); end; for b := Low(aArray) to High(aArray) do begin if s = aArray[b] then begin result := true; break; end; end; end; procedure MergeStrings(const dest, source: TStrings); var i: integer; begin for i := 0 to -1 + source.count do if dest.IndexOf(source[i]) = -1 then dest.Add(source[i]); end; function Occurs(substr, s: string): integer; var i: integer; begin result := 0; for i := 1 to length(s) do if Copy(s, i, length(substr)) = substr then inc(result); end; function RandomCase(const s: string; const ToUpperSet: TSysCharSet = ['a' .. 'z']; const ToLowerSet: TSysCharSet = ['A' .. 'Z']): string; var i: integer; begin Randomize(); result := s; for i := 1 to length(result) do if Random(2) = 1 then if CharInSet(result[i], ToLowerSet) then inc(result[i], 32) else if CharInSet(result[i], ToUpperSet) then Dec(result[i], 32); end; function RandomString(const len: integer; const chars: string = 'abcdefghijklmnopqrstuvwxyz'): string; begin Randomize; result := emptystr; repeat result := result + chars[Random(length(chars)) + 1]; until (length(result) = len); end; // Strips a quote pair off a string if it exists // The leading and trailing quotes will only be removed if both exist // Otherwise, the string is left unchanged function RemoveQuotes(const s: string): string; var i: integer; begin result := s; i := length(s); if i = 0 then Exit; if (CharInSet(s[1], ['"', '''']) = true) and (s[1] = LastChar(s)) then begin Delete(result, 1, 1); SetLength(result, length(result) - 1); end; end; // Removes the last character from a string function RemoveLastChar(const s: string): string; var len: integer; astr: string; begin astr := s; len := length(astr); if len > 0 then Delete(astr, len, 1); result := astr; end; function RemoveNumbers(const s: string): string; var i, l: integer; begin SetLength(result, length(s)); l := 0; for i := 1 to length(s) do if not(CharInSet(s[i], ['0' .. '9'])) then begin inc(l); result[l] := s[i]; end; SetLength(result, l); end; function RemoveShortcuts(const s: string): string; begin result := ReplaceStr(s, '&', emptystr); end; function RepeatString(const s: string; count: cardinal): string; var i: integer; begin for i := 1 to count do result := result + s; end; function ReplaceStr(const s, substr, repstr: string): string; begin result := stringreplace(s, substr, repstr, [rfReplaceAll]); end; function StrIncrease(const s: string; const step: integer = 1): string; var i, c: integer; tmpstr: WideString; begin tmpstr := ''; for i := 1 to length(s) do begin c := ord(s[i]); inc(c, step); tmpstr := tmpstr + widechar(c); end; result := tmpstr; end; function StrDecrease(const s: string; const step: integer = 1): string; var i, c: integer; tmpstr: WideString; begin tmpstr := ''; for i := 1 to length(s) do begin c := ord(s[i]); Dec(c, step); tmpstr := tmpstr + widechar(c); end; result := tmpstr; end; function RestStr(const s: string; const index: longword): string; var l: integer; begin l := length(s); if l > 0 then result := Copy(s, index, l) else result := emptystr; end; procedure StripBlankLines(const sl: TStringList); var i: integer; begin for i := (sl.count - 1) downto 0 do begin if (Trim(sl[i]) = emptystr) then sl.Delete(i); end; end; function StrToCommaText(const s: string): string; var sl: TStringList; begin sl := TStringList.Create; sl.text := s; result := sl.CommaText; sl.free; end; function StripChars(const s: string; const aSet: TSysCharSet): string; var i, P: integer; begin P := 0; SetLength(result, length(s)); for i := 1 to length(s) do begin if not(CharInSet(s[i], aSet)) then begin inc(P); result[P] := s[i]; end; end; SetLength(result, P); end; function ReplaceChars(const s: string; const aSet: TSysCharSet; const repwith: Char = '_'): string; var i, P: integer; begin P := 0; SetLength(result, length(s)); for i := 1 to length(s) do begin inc(P); result[P] := s[i]; if (CharInSet(s[i], aSet)) then result[P] := repwith; end; SetLength(result, P); end; function CommaTextToStr(const s: string): string; var sl: TStringList; begin sl := TStringList.Create; sl.CommaText := s; result := sl.GetText; sl.free; end; function StrMaxLen(const s: string; const MaxLen: integer; const AddEllipsis: Boolean = false): string; var i: integer; begin result := s; if length(result) <= MaxLen then Exit; SetLength(result, MaxLen); if AddEllipsis = true then begin for i := MaxLen downto MaxLen - 2 do result[i] := '.'; end; end; function StrToAlphaNum(const s: string): string; var i: integer; tmpstr: string; begin tmpstr := emptystr; for i := 1 to length(s) do begin if (CharInSet(s[i], ['0' .. '9', 'A' .. 'Z', 'a' .. 'z'])) then tmpstr := tmpstr + Copy(s, i, 1); end; result := tmpstr; end; function StrArrayToCommaText(aArray: array of string):string; var b: integer; sl: TStringList; begin sl := TStringList.Create; for b := Low(aArray) to High(aArray) do sl.add(aArray[b]); result := sl.CommaText; sl.Free; end; function StrToBool(const s: string): Boolean; begin if MatchStrInArray(Trim(lowercase(s)), ['true', '1', 'yes', 't', 'y', 'on']) then result := true else result := false; end; function StrToCharSet(const s: string): TSysCharSet; var P: PAnsiChar; begin result := []; if s = emptystr then Exit; P := PAnsiChar(AnsiString(s)); while P^ <> #0 do begin Include(result, P^); inc(P); end; end; function CharSetToStr(const c: TSysCharSet): string; var i: integer; begin result := emptystr; for i := 0 to 255 do if CharInSet(Chr(i),c) then result := result + Chr(i); end; function StrToHex(const s: string): string; var i: integer; begin result := emptystr; for i := 1 to length(s) do result := result + IntToHex(ord(Copy(s, i, 1)[1]), 2); end; function StrToHex16(const s: string): string; var i: integer; str: string; begin str := emptystr; for i := 1 to length(s) do str := str + IntToHex(integer(s[i]), 4); result := str; end; function HexToStr(const s: string): string; var i: integer; h: string; begin result := emptystr; try for i := 1 to length(s) div 2 do begin h := Copy(s, (i - 1) * 2 + 1, 2); result := result + Char(StrToInt('$' + h)); end; except result := emptystr; end; end; function Hex16ToStr(const s: string): string; var i: integer; c: string; begin result := emptystr; i := 1; while i < length(s) do begin c := Copy(s, i, 4); result := result + Chr(StrToInt('$' + c)); inc(i, 4); end; end; function StripEnclosed(const s: string;const beginChar,endChar:char): string; var i: integer; strip: boolean; begin result := emptystr; strip := false; for i := 1 to length(s) do begin if s[i] = beginChar then strip := true; if strip then begin if s[i] = endChar then begin strip := false; Continue; end; end else result := result + s[i]; end; end; function SwapCase(const s: string): string; const ToUpperSet: TSysCharSet = ['a' .. 'z']; const ToLowerSet: TSysCharSet = ['A' .. 'Z']; var i: integer; begin result := s; for i := 1 to length(result) do begin if CharInSet(result[i], ToLowerSet) then Inc(result[i], 32) else if CharInSet(result[i], ToUpperSet) then Dec(result[i], 32); end; end; function TitleCase(const s: string): string; var i: integer; begin if s = emptystr then result := emptystr else begin result := Uppercase(s[1]); for i := 2 to length(s) do if s[i - 1] = ' ' then result := result + Uppercase(s[i]) else result := result + lowercase(s[i]); end; end; function StrToNameValue(const s: string; const aSeparator:string='='): TCatNameValue; begin result.name := Before(s, aSeparator); result.value := After(s, aSeparator); end; // CONTRIBUTED ------------------------------------------------------------// // Peter Below, 11.27.1996 function IScan(ch: Char; const s: string; fromPos: integer): integer; var i: integer; begin result := 0; for i := fromPos to length(s) do begin if s[i] = ch then begin result := i; break; end; end; end; // PB, 08.07.1997 procedure SplitString(const s: string; separator: Char; substrings: TStringList); var i, n: integer; begin if Assigned(substrings) and (length(s) > 0) then begin i := 1; repeat n := IScan(separator, s, i); if n = 0 then n := length(s) + 1; substrings.Add(Copy(s, i, n - i)); i := n + 1; until i > length(s); end; end; // Based on an example by PB procedure GetTextBetweenTags(const s, tag1, tag2: string; const list: TStrings; const includetags: Boolean = false); var pScan, pEnd, pTag1, pTag2: PAnsiChar; foundText, searchtext: string; begin searchtext := Uppercase(s); pTag1 := PAnsiChar(AnsiString(Uppercase(tag1))); pTag2 := PAnsiChar(AnsiString(Uppercase(tag2))); pScan := PAnsiChar(AnsiString(searchtext)); repeat {$IFDEF DXE2_OR_UP} {$IFDEF MSWINDOWS} pScan := System.AnsiStrings.StrPos(pScan, pTag1); {$ELSE} // FIXME {$ENDIF} {$ELSE} pScan := StrPos(pScan, pTag1); {$ENDIF} if pScan <> nil then begin inc(pScan, length(tag1)); {$IFDEF DXE2_OR_UP} {$IFDEF MSWINDOWS} pEnd := System.AnsiStrings.StrPos(pScan, pTag2); {$ELSE} // FIXME!!! {$ENDIF} {$ELSE} pEnd := StrPos(pScan, pTag2); {$ENDIF} if pEnd <> nil then begin SetString(foundText, PAnsiChar(AnsiString(s)) + (pScan - PAnsiChar(AnsiString(searchtext))), pEnd - pScan); if includetags then list.Add(Uppercase(tag1) + foundText + Uppercase(tag2)) else list.Add(foundText); list.text := list.GetText; pScan := pEnd + length(tag2); end else pScan := nil; end; until pScan = nil; end; // Based on an example by Mike Orriss function ExtractFromString(const s, startstr, endstr: string): string; var ps, pe: integer; begin ps := pos(startstr, s); pe := pos(endstr, s); if (pe <= ps) or (ps = 0) then result := emptystr else begin inc(ps, length(startstr)); result := Copy(s, ps, pe - ps); end; end; function ExtractNumbers(const s: string): string; var i, l: integer; begin SetLength(result, length(s)); l := 0; for i := 1 to length(s) do if (CharInSet(s[i], ['0' .. '9'])) then begin inc(l); result[l] := s[i]; end; SetLength(result, l); end; // Based on an example from Thomas Scheffczyk function GetToken(const aString, SepChar: String; const TokenNum: Integer): String; var Token, tmpstr: String; StrLen, num, EndofToken: integer; begin tmpstr := aString; StrLen := length(tmpstr); num := 1; EndofToken := StrLen; while ((num <= TokenNum) and (EndofToken <> 0)) do begin EndofToken := pos(SepChar, tmpstr); if EndofToken <> 0 then begin Token := Copy(tmpstr, 1, EndofToken - 1); Delete(tmpstr, 1, EndofToken); inc(num); end else Token := tmpstr; end; if num >= TokenNum then result := Token else result := emptystr; end; function MemStreamToStr(m: TMemoryStream): String; begin SetString(Result, PAnsiChar(AnsiString(m.Memory)), M.Size); end; // ------------------------------------------------------------------------// end.
namespace TestApplication; interface uses proholz.xsdparser, RemObjects.Elements.EUnit; type HtmlParseTest = public class(TestBaseClass) private const parserResults = new List<ParserResult>; const parserNonPartedResults = new List<ParserResult>; const parserPartedResults = new List<ParserResult>; // * // * @return Obtains the filePath of the file associated with this test class. class method getFilePath(fileName: String): String; class constructor; begin var html5: ParserResult := new ParserResult(getFilePath('html_5.xsd')); var partedHtml5: ParserResult := new ParserResult(getFilePath('html_5_types.xsd')); Var l1 := html5.getElements.Count; Var l2 := partedHtml5.getElements.Count; parserResults.add(html5); parserResults.add(partedHtml5); parserNonPartedResults.add(html5); parserPartedResults.add(partedHtml5); end; public method testSchemaGetMethods; // * // * Verifies the excepted element count. method testElementCount; // * // * Tests if the first element, which should be the html as all the expected contents. method testFirstElementContents; // * // * Tests the first element attribute count against the expected count. method testFirstElementAttributes; // * // * Verifies if there is any unexpected unsolved references in the parsing. method testUnsolvedReferences; // * // * Verifies the contents of a {@link XsdSimpleType} object against the expected values. method testSimpleTypes; // * // * Verifies if all the html_5 html5Elements have a attribute with the name 'class'. method testClassAttribute; // * // * Verifies if there is an attributeGroup named classAttributeGroup that is the parent of all the existing attributeGroups. method testClassParent; end; ParserResult = assembly class private var elements: List<XsdElement>; var schemas: List<XsdSchema>; var unsolved: List<UnsolvedReferenceItem>; assembly constructor(fileName: String); method getElements: List<XsdElement>; virtual; method getSchemas: List<XsdSchema>; virtual; method getUnsolved: List<UnsolvedReferenceItem>; virtual; end; implementation method HtmlParseTest.testSchemaGetMethods; begin for each parserResult: ParserResult in parserNonPartedResults do begin var schema: XsdSchema := parserResult.getSchemas().First; Check.AreEqual(104, schema.getChildrenElements().count()); Check.AreEqual(5, schema.getChildrenSimpleTypes().count()); Check.AreEqual(1, schema.getChildrenAnnotations().count()); Check.AreEqual(11, schema.getChildrenAttributeGroups().count()); Check.AreEqual(0, schema.getChildrenAttributes().count()); Check.AreEqual(2, schema.getChildrenComplexTypes().count()); Check.AreEqual(8, schema.getChildrenGroups().count()); Check.AreEqual(0, schema.getChildrenImports().count()); Check.AreEqual(0, schema.getChildrenIncludes().count()); end; for each parserRes: ParserResult in parserPartedResults do begin var schema0: XsdSchema := parserRes.getSchemas().First; Assert.AreEqual(0, schema0.getChildrenElements().count()); Assert.AreEqual(5, schema0.getChildrenSimpleTypes().count()); Assert.AreEqual(1, schema0.getChildrenAnnotations().count()); Assert.AreEqual(11, schema0.getChildrenAttributeGroups().count()); Assert.AreEqual(0, schema0.getChildrenAttributes().count()); Assert.AreEqual(2, schema0.getChildrenComplexTypes().count()); Assert.AreEqual(8, schema0.getChildrenGroups().count()); Assert.AreEqual(0, schema0.getChildrenImports().count()); Assert.AreEqual(1, schema0.getChildrenIncludes().count()); var schema1: XsdSchema := parserRes.getSchemas().ElementAt(1); Assert.AreEqual(7, schema1.getChildrenElements().count()); Assert.AreEqual(0, schema1.getChildrenSimpleTypes().count()); Assert.AreEqual(0, schema1.getChildrenAnnotations().count()); Assert.AreEqual(0, schema1.getChildrenAttributeGroups().count()); Assert.AreEqual(0, schema1.getChildrenAttributes().count()); Assert.AreEqual(0, schema1.getChildrenComplexTypes().count()); Assert.AreEqual(0, schema1.getChildrenGroups().count()); Assert.AreEqual(0, schema1.getChildrenImports().count()); Assert.AreEqual(1, schema1.getChildrenIncludes().count()); end; end; method HtmlParseTest.testElementCount; begin for each parserRes: ParserResult in parserResults index i do begin case i of 0 : Check.AreEqual(parserRes.getElements().Count(), 104); 1 : Check.AreEqual(parserRes.getElements().Count(), 7); //Check.AreEqual(parserRes.getElements().Count(), 0); end; end; for each parserRes: ParserResult in parserNonPartedResults do begin Check.AreEqual(parserRes.getElements().Count(), 104); // Check.AreEqual(parserRes.getElements().Count(), 104); Check.AreEqual(parserRes.getSchemas().Count(), 1); end; for each parserRes: ParserResult in parserPartedResults index i do begin case i of 0 : begin Check.AreEqual(parserRes.getElements().Count(), 7); Check.AreEqual(parserRes.getSchemas().Count(), 2); end; end; end; end; method HtmlParseTest.testFirstElementContents; begin for each parserResult: ParserResult in parserResults do begin var htmlElement: XsdElement := parserResult.getElements().First; Assert.AreEqual('html', htmlElement.getName()); Assert.AreEqual(1, Integer(htmlElement.getMinOccurs())); Assert.AreEqual('1', htmlElement.getMaxOccurs()); var firstElementChild: XsdComplexType := htmlElement.getXsdComplexType(); Assert.AreEqual(firstElementChild.getXsdChildElement().GetType(), typeOf(XsdChoice)); var complexTypeChild: XsdChoice := firstElementChild.getChildAsChoice(); Assert.IsNil(firstElementChild.getChildAsAll()); Assert.IsNil(firstElementChild.getChildAsGroup()); Assert.IsNil(firstElementChild.getChildAsSequence()); var choiceElements: List<XsdElement> := complexTypeChild.getChildrenElements().toList(); Assert.AreEqual(2, choiceElements.Count()); var child1: XsdElement := choiceElements.ElementAt(0); var child2: XsdElement := choiceElements.ElementAt(1); Assert.AreEqual('body', child1.getName()); Assert.AreEqual('head', child2.getName()); end; end; method HtmlParseTest.testFirstElementAttributes; begin // for each parserRes: ParserResult in parserResults do begin var htmlElement: XsdElement := parserResults.ElementAt(0).getElements().ElementAt(0); Assert.AreEqual('html', htmlElement.getName()); var firstElementChild: XsdComplexType := htmlElement.getXsdComplexType(); var elementAttributes: List<XsdAttribute> := firstElementChild.getXsdAttributes().toList(); Assert.AreEqual(elementAttributes.Count, 1); end; method HtmlParseTest.testUnsolvedReferences; begin end; method HtmlParseTest.testSimpleTypes; begin for each parserResult: ParserResult in parserResults do begin var htmlElement: XsdElement := parserResult.getElements().ElementAt(5); Assert.AreEqual('meta', htmlElement.getName()); var metaChild: XsdComplexType := htmlElement.getXsdComplexType(); var attributeOptional: XsdAttribute := metaChild .getXsdAttributes() .Where(attribute1 -> attribute1.getName().equals('http_equiv')).First(); Assert.IsTrue(attributeOptional <> nil); var attribute: XsdAttribute := attributeOptional; Assert.AreEqual(true, assigned(attribute.getXsdSimpleType())); var simpleType: XsdSimpleType := attribute.getXsdSimpleType(); Assert.IsNil(simpleType.getRestriction()); Assert.IsNil(simpleType.getList()); Assert.assertNotNull(simpleType.getUnion()); var &union: XsdUnion := simpleType.getUnion(); Assert.AreEqual(2, &union.getUnionElements().Count()); var innerSimpleType1: XsdSimpleType := &union.getUnionElements().ElementAt(0); Assert.assertNotNull(innerSimpleType1.getRestriction()); Assert.IsNil(innerSimpleType1.getList()); Assert.IsNil(innerSimpleType1.getUnion()); var restriction: XsdRestriction := innerSimpleType1.getRestriction(); var enumeration: List<XsdEnumeration> := restriction.getEnumeration(); Assert.AreEqual(4, enumeration.Count()); Assert.AreEqual('content-language', enumeration.ElementAt(0).getValue()); Assert.AreEqual('content-type', enumeration.ElementAt(1).getValue()); Assert.AreEqual('default-style', enumeration.ElementAt(2).getValue()); Assert.AreEqual('refresh', enumeration.ElementAt(3).getValue()); Assert.IsNil(restriction.getFractionDigits()); Assert.IsNil(restriction.getLength()); Assert.IsNil(restriction.getMaxExclusive()); Assert.IsNil(restriction.getMaxInclusive()); Assert.IsNil(restriction.getMaxLength()); Assert.IsNil(restriction.getMinExclusive()); Assert.IsNil(restriction.getMinInclusive()); Assert.IsNil(restriction.getMinLength()); Assert.IsNil(restriction.getPattern()); Assert.IsNil(restriction.getTotalDigits()); Assert.IsNil(restriction.getWhiteSpace()); end; end; method HtmlParseTest.testClassAttribute; begin for each parserResult: ParserResult in parserResults do begin parserResult .getElements() .forEach(element -> Assert.IsTrue(element .getXsdComplexType() .getXsdAttributeGroup() .any(attributeGroup -> attributeGroup .getAllAttributes() .any(attribute -> attribute.getName().equals('class')) ) ) ); end; end; method HtmlParseTest.testClassParent; begin for each parserRes: ParserResult in parserResults do begin var classAttribute: XsdAttribute := parserRes .getElements().First .getXsdComplexType() .getXsdAttributes() .Where(attribute -> assigned(attribute.getName()) and attribute.getName().equals('class')).First; Assert.IsTrue(classAttribute <> nil); var classAttributeXsd: XsdAttribute := classAttribute; Assert.AreEqual('classAttributeGroup', XsdAttributeGroup(classAttributeXsd.getParent()).getName()); end; end; class method HtmlParseTest.getFilePath(fileName: String): String; begin var fullname := Path.Combine('../../resources', Path.ChangeExtension(fileName,'.xsd')); exit fullname; end; constructor ParserResult(fileName: String); begin var parser: XsdParserCore := new XsdParser(fileName); elements := parser.getResultXsdElements().toList(); schemas := parser.getResultXsdSchemas().toList(); unsolved := parser.getUnsolvedReferences().ToList; end; method ParserResult.getElements: List<XsdElement>; begin exit elements; end; method ParserResult.getSchemas: List<XsdSchema>; begin exit schemas; end; method ParserResult.getUnsolved: List<UnsolvedReferenceItem>; begin exit unsolved; end; end.
unit uFrmCountInventoryConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, CheckLst, DB, ADODB; type TFrmCountInventoryConfig = class(TFrmParentAll) btOk: TButton; clbCategory: TCheckListBox; edtNumItem: TEdit; lbNumItem: TLabel; Label1: TLabel; cmbPrint: TComboBox; quCategory: TADOQuery; quCategoryIDGroup: TIntegerField; quCategoryName: TStringField; cmdUpdPrint: TADOCommand; cmdUpdCategory: TADOCommand; cmdUpdNumItens: TADOCommand; Label9: TLabel; Label2: TLabel; quGetCategory: TADOQuery; quGetPrint: TADOQuery; quGetPrintPropertyValue: TStringField; quGetCategoryPropertyValue: TStringField; quGetNumber: TADOQuery; quGetNumberPropertyValue: TStringField; btCheckAll: TSpeedButton; btUnCheckAll: TSpeedButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btCheckAllClick(Sender: TObject); procedure btUnCheckAllClick(Sender: TObject); private sCategory : String; fCategList: TStringList; //Get procedure GetCategoryList; procedure GetCategory; procedure GetNumberOfItens; procedure GetPrintWhen; //Set procedure SetCategoryRights; //Update procedure UpdateNumberOfItens; procedure UpdatePrintWhen; procedure UpdateCategory; procedure CategoryOpen; procedure CategoryClose; procedure CheckAll(AType: Boolean); function VerifyCheckID(AID: Integer):Boolean; function ApplyUpdate:Boolean; public function Start:Boolean; end; implementation uses uDM, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmCountInventoryConfig } function TFrmCountInventoryConfig.Start: Boolean; begin GetNumberOfItens; GetPrintWhen; GetCategory; GetCategoryList; ShowModal; Result := (ModalResult = mrOk); end; procedure TFrmCountInventoryConfig.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(fCategList); Action := caFree; end; procedure TFrmCountInventoryConfig.GetCategoryList; var i: Integer; begin with quCategory do try Open; First; while not Eof do begin i := clbCategory.Items.Add(quCategoryName.AsString); clbCategory.Checked[i] := VerifyCheckID(quCategoryIDGroup.AsInteger); Next; end; finally Close; end; end; procedure TFrmCountInventoryConfig.SetCategoryRights; var i: Integer; begin CategoryOpen; sCategory := ''; with clbCategory do for i := 0 to Items.Count-1 do if Checked[i] then if quCategory.Locate('Name', Items[i], []) then begin if sCategory <> '' then sCategory := sCategory + ', ' + quCategoryIDGroup.AsString else sCategory := ' ' + quCategoryIDGroup.AsString; end; end; procedure TFrmCountInventoryConfig.CategoryOpen; begin with quCategory do if not Active then Open; end; procedure TFrmCountInventoryConfig.CategoryClose; begin with quCategory do if Active then Close; end; procedure TFrmCountInventoryConfig.GetNumberOfItens; begin with quGetNumber do begin if Active then Close; Parameters.ParamByName('Property').Value := 'InvCountConfigNumItens'; Open; end; edtNumItem.Text := quGetNumberPropertyValue.AsString; end; procedure TFrmCountInventoryConfig.GetPrintWhen; begin with quGetPrint do begin if Active then Close; Parameters.ParamByName('Property').Value := 'InvCountConfigPrintWhen'; Open; end; cmbPrint.ItemIndex := StrToInt(quGetPrintPropertyValue.AsString); end; procedure TFrmCountInventoryConfig.GetCategory; begin with quGetCategory do begin if Active then Close; Parameters.ParamByName('Property').Value := 'InvCountConfigCategory'; Open; end; fCategList.CommaText := StringReplace(quGetCategoryPropertyValue.AsString,',','',[rfReplaceAll]); end; function TFrmCountInventoryConfig.ApplyUpdate: Boolean; begin try Result := True; SetCategoryRights; UpdateCategory; UpdateNumberOfItens; UpdatePrintWhen; except on E: Exception do begin Result := False; MsgBox('Error on Apply Updates_' + E.Message, vbCritical + vbOkOnly ); end; end; end; procedure TFrmCountInventoryConfig.UpdateNumberOfItens; begin with cmdUpdNumItens do begin Parameters.ParamByName('PropertyValue').Value := edtNumItem.Text; Parameters.ParamByName('Property').Value := 'InvCountConfigNumItens'; Execute; end; end; procedure TFrmCountInventoryConfig.UpdatePrintWhen; begin with cmdUpdPrint do begin Parameters.ParamByName('PropertyValue').Value := cmbPrint.ItemIndex; Parameters.ParamByName('Property').Value := 'InvCountConfigPrintWhen'; Execute; end; end; procedure TFrmCountInventoryConfig.UpdateCategory; begin with cmdUpdCategory do begin Parameters.ParamByName('PropertyValue').Value := sCategory; Parameters.ParamByName('Property').Value := 'InvCountConfigCategory'; Execute; end; end; procedure TFrmCountInventoryConfig.btOkClick(Sender: TObject); begin inherited; if not ApplyUpdate then ModalResult := mrNone; end; function TFrmCountInventoryConfig.VerifyCheckID(AID: Integer): Boolean; var i: Integer; begin Result := False; for i := 0 to fCategList.Count -1 do if IntToStr(AID) = fCategList.Strings[i] then begin Result := True; Break; end; end; procedure TFrmCountInventoryConfig.FormCreate(Sender: TObject); begin inherited; fCategList := TStringList.Create; end; procedure TFrmCountInventoryConfig.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmCountInventoryConfig.CheckAll(AType: Boolean); var i: Integer; begin for i:= 0 to clbCategory.Count -1 do clbCategory.Checked[i] := AType; end; procedure TFrmCountInventoryConfig.btCheckAllClick(Sender: TObject); begin inherited; CheckAll(True); end; procedure TFrmCountInventoryConfig.btUnCheckAllClick(Sender: TObject); begin inherited; CheckAll(False); end; end.
unit uCEPManager; interface uses System.Classes, System.SysUtils, System.JSON, System.JSON.Types, System.JSON.Writers, System.JSON.Readers, AtendeCliente1; type TMyCEP = class(TObject) fCEP: string; fLogradouro: string; fBairro: string; fCidade: string; fUF: string; end; type TCEPManager = class(TObject) private { private declarations } protected { protected declarations } public { public declarations } class function CEP2JSON(eERP: enderecoERP): TJSONObject; class function JSON2CEP(jsonCEP: string): TMyCEP; published { published declarations } end; implementation { TCEPManager } class function TCEPManager.CEP2JSON(eERP: enderecoERP): TJSONObject; var StringWriter: TStringWriter; Writer: TJsonTextWriter; begin StringWriter := TStringWriter.Create(); Writer := TJsonTextWriter.Create(StringWriter); try Writer.Formatting := TJsonFormatting.Indented; Writer.WriteStartObject; Writer.WritePropertyName('CEP'); Writer.WriteValue(eERP.cep); Writer.WritePropertyName('Logradouro'); Writer.WriteValue(eERP.end_); Writer.WritePropertyName('Bairro'); Writer.WriteValue(eERP.bairro); Writer.WritePropertyName('Cidade'); Writer.WriteValue(eERP.cidade); Writer.WritePropertyName('UF'); Writer.WriteValue(eERP.uf); Writer.WriteEndObject; Result := TJSONObject.ParseJSONValue (TEncoding.ASCII.GetBytes(StringWriter.ToString), 0) as TJSONObject; finally Writer.Free; StringWriter.Free; end; end; class function TCEPManager.JSON2CEP(jsonCEP: string): TMyCEP; var StringReader: TStringReader; Reader: TJsonTextReader; begin Result := TMyCEP.Create; StringReader := TStringReader.Create(jsonCEP); Reader := TJsonTextReader.Create(StringReader); try while Reader.Read do begin if Reader.TokenType = TJsonToken.PropertyName then begin if Reader.Value.AsString = 'CEP' then Result.fCEP := Reader.ReadAsString; if Reader.Value.AsString = 'Logradouro' then Result.fLogradouro := Reader.ReadAsString; if Reader.Value.AsString = 'Bairro' then Result.fBairro := Reader.ReadAsString; if Reader.Value.AsString = 'Cidade' then Result.fCidade := Reader.ReadAsString; if Reader.Value.AsString = 'UF' then Result.fUF := Reader.ReadAsString; end; end; finally StringReader.Free; Reader.Free; end; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmInspectorItems Purpose : This unit contains the actual implementations of the rmInspectorItem items. Date : 01-18-2001 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmInspectorItems; interface {$I CompilerDefines.INC} {$D+} uses rmInspector, Controls, stdctrls, classes; { TrmStringInspectorItem TrmComplexInspectorItem TrmComboInspectorItem TrmIntegerInspectorItem TrmDateInspectorItem TrmCheckBoxInspectorItem } type TrmStringInspectorItem = class(TrmCustomInspectorItem) private fValue: string; fPassChar: char; fMaxLen: integer; procedure SetValue(const Value: string); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public constructor Create(AOwner:TComponent); override; function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property MaxLength : integer read fMaxLen write fMaxLen; property PasswordChar : char read fPassChar write fPassChar; property Value: string read fValue write SetValue; end; TrmComplexInspectorItem = class(TrmCustomInspectorItem) private fValue: String; procedure SetValue(const Value: String); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property Value: String read fValue write SetValue; end; TrmComboInspectorItem = class(TrmCustomInspectorItem) private fValue: String; fItems: TStrings; function GetItems: TStrings; procedure SetItems(const Value: TStrings); procedure SetValue(const Value: String); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property Value: String read fValue write SetValue; property Items: TStrings read GetItems write SetItems; end; TrmIntegerInspectorItem = class(TrmCustomInspectorItem) private fValue: Integer; fUseRange: boolean; fMaxValue: integer; fMinValue: integer; procedure SetMaxValue(const Value: integer); procedure SetMinValue(const Value: integer); procedure SetUseRange(const Value: boolean); procedure SetValue(const Value: integer); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public constructor Create(AOwner:TComponent); override; function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property MinValue:integer read fMinValue write SetMinValue default 0; property MaxValue:integer read fMaxValue write SetMaxValue default 1; property UseRange:boolean read fUseRange write SetUseRange default false; property Value: integer read fValue write SetValue; end; TrmDateInspectorItem = class(TrmCustomInspectorItem) private fValue: TDate; fDateFormat: string; procedure SetValue(const Value: TDate); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property Value: TDate read fValue write SetValue; property DateFormat:string read fDateFormat write fDateFormat; end; TrmCheckBoxInspectorItem = class(TrmCustomInspectorItem) private fValue: Boolean; procedure SetValue(const Value: Boolean); protected function GetStringValue: string; override; procedure SetStringValue(const Value: string); override; public function EditorClass: TWinControlClass; override; procedure GetValueFromEditor(Editor: TWinControl); override; procedure SetValueIntoEditor(Editor: TWinControl); override; procedure SetupEditor(Inspector:TrmInspector; Editor:TWinControl); override; published property Value: Boolean read fValue write SetValue; end; implementation uses windows, SysUtils, Forms, rmBaseEdit, rmBtnEdit, rmBtnCombo, rmCalendar, rmLibrary, rmCheckBox; type TrmInspectorInvasion = class(TrmInspector) end; TrmInspectorBtnCombo = class(TrmBtnCombo) protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; end; TrmInspectorCheckBox = class(TrmCheckBox) protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Keypress(var Key: Char); override; end; TrmInspectorEdit = class(TrmCustomEdit) protected procedure keypress(var Key: Char); override; published property Anchors; property AutoSelect; property AutoSize; property BiDiMode; property BorderStyle; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; { TrmStringInspectorItem } constructor TrmStringInspectorItem.create(AOwner: TComponent); begin inherited; fMaxLen := 0; fPassChar := #0; end; function TrmStringInspectorItem.EditorClass: TWinControlClass; begin result := TrmInspectorEdit; end; function TrmStringInspectorItem.GetStringValue: string; begin result := fValue; end; procedure TrmStringInspectorItem.GetValueFromEditor(Editor: TWinControl); begin if Editor is TrmInspectorEdit then Value := TrmInspectorEdit(Editor).Text; end; procedure TrmStringInspectorItem.SetStringValue(const Value: string); begin fValue := value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmStringInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmInspectorEdit then begin with TrmInspectorEdit(Editor) do begin BorderStyle := bsNone; Font := Inspector.Font; WantTabs := true; MaxLength := fMaxLen; PasswordChar := fPassChar; end; end; end; procedure TrmStringInspectorItem.SetValue(const Value: string); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmStringInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if Editor is TrmInspectorEdit then TrmInspectorEdit(Editor).Text := Value; end; { TrmComplexInspectorItem } function TrmComplexInspectorItem.EditorClass: TWinControlClass; begin Result := TrmBtnEdit; end; function TrmComplexInspectorItem.GetStringValue: string; begin result := fValue; end; procedure TrmComplexInspectorItem.GetValueFromEditor(Editor: TWinControl); begin //Do Nothing... end; procedure TrmComplexInspectorItem.SetStringValue(const Value: string); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmComplexInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmBtnEdit then begin with TrmBtnEdit(Editor) do begin borderstyle := bsNone; Readonly := true; font := Inspector.Font; WantTabs := true; OnBtn1Click := Inspector.DoComplexEdit; end; end; end; procedure TrmComplexInspectorItem.SetValue(const Value: String); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmComplexInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if Editor is TrmBtnEdit then TrmBtnEdit(Editor).text := fValue; end; { TrmComboInspectorItem } constructor TrmComboInspectorItem.create(AOwner: TComponent); begin inherited; fItems := TStringList.Create; end; destructor TrmComboInspectorItem.destroy; begin fItems.free; inherited; end; function TrmComboInspectorItem.EditorClass: TWinControlClass; begin result := TrmInspectorBtnCombo; end; function TrmComboInspectorItem.GetItems: TStrings; begin result := fItems; end; function TrmComboInspectorItem.GetStringValue: string; begin result := fValue; end; procedure TrmComboInspectorItem.GetValueFromEditor(Editor: TWinControl); begin if editor is TrmInspectorBtnCombo then fValue := TrmInspectorBtnCombo(Editor).Text; end; procedure TrmComboInspectorItem.SetItems(const Value: TStrings); begin fItems.assign(Value); end; procedure TrmComboInspectorItem.SetStringValue(const Value: string); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmComboInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmInspectorBtnCombo then begin with TrmInspectorBtnCombo(Editor) do begin borderstyle := bsNone; readonly := true; font := Inspector.font; EllipsisBtnVisible := false; WantTabs := true; Items.Assign(Self.Items); end; end; end; procedure TrmComboInspectorItem.SetValue(const Value: String); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmComboInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if editor is TrmInspectorBtnCombo then TrmInspectorBtnCombo(Editor).Text := fvalue; end; { TrmIntegerInspectorItem } constructor TrmIntegerInspectorItem.create(AOwner: TComponent); begin inherited; fMaxValue := 1; fMinValue := 0; fUseRange := false; end; function TrmIntegerInspectorItem.EditorClass: TWinControlClass; begin Result := TrmInspectorEdit; end; function TrmIntegerInspectorItem.GetStringValue: string; begin Result := inttostr(fValue); end; procedure TrmIntegerInspectorItem.GetValueFromEditor(Editor: TWinControl); begin if Editor is TrmInspectorEdit then AsString := TrmInspectorEdit(Editor).Text; end; procedure TrmIntegerInspectorItem.SetMaxValue(const Value: integer); begin if Value > fMinValue then fMaxValue := Value; if fUseRange and (fValue > fMaxValue) then fValue := fMaxValue; end; procedure TrmIntegerInspectorItem.SetMinValue(const Value: integer); begin if Value < fMaxValue then fMinValue := Value; if fUseRange and (fValue < fMinValue) then fValue := fMinValue; end; procedure TrmIntegerInspectorItem.SetStringValue(const Value: string); var wTemp : integer; begin wTemp := strtoint(Value); if fUseRange then begin if (wTemp <= fMaxValue) and (wTemp >= fMinValue) then fValue := wTemp else raise exception.create('Value must be between '+inttostr(fMinValue)+' and '+inttostr(fMaxValue)); end else fValue := wTemp; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmIntegerInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmInspectorEdit then begin with TrmInspectorEdit(Editor) do begin Font := Inspector.Font; BorderStyle := bsNone; WantTabs := true; end; end; end; procedure TrmIntegerInspectorItem.SetUseRange(const Value: boolean); begin fUseRange := Value; end; procedure TrmIntegerInspectorItem.SetValue(const Value: integer); begin if fUseRange then begin if (Value <= fMaxValue) and (Value >= MinValue) then fValue := Value else raise exception.create('Value must be between '+inttostr(fMinValue)+' and '+inttostr(fMaxValue)); end else fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmIntegerInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if Editor is TrmInspectorEdit then TrmInspectorEdit(Editor).Text := AsString; end; { TrmDateInspectorItem } function TrmDateInspectorItem.EditorClass: TWinControlClass; begin result := TrmComboCalendar; end; function TrmDateInspectorItem.GetStringValue: string; begin result := datetostr(fValue); end; procedure TrmDateInspectorItem.GetValueFromEditor(Editor: TWinControl); begin if Editor is TrmComboCalendar then Value := TrmComboCalendar(Editor).SelectedDate; end; procedure TrmDateInspectorItem.SetStringValue(const Value: string); begin fValue := StrToDate(Value); if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmDateInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmComboCalendar then begin with TrmComboCalendar(Editor) do begin Font := Inspector.Font; BorderStyle := bsNone; WantTabs := true; DateFormat := fDateFormat; end; end; end; procedure TrmDateInspectorItem.SetValue(const Value: TDate); begin fValue := Value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmDateInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if Editor is TrmComboCalendar then TrmComboCalendar(Editor).SelectedDate := Value; end; { TrmInspectorEdit } procedure TrmInspectorEdit.keypress(var Key: Char); begin inherited; if key = #9 then key := #0; end; { TrmInspectorBtnCombo } procedure TrmInspectorBtnCombo.KeyDown(var Key: Word; Shift: TShiftState); begin if (not DroppedDown and ((key = vk_Down) or (key = vk_up)) and (shift = [])) then begin if Owner is TrmInspector then TrmInspectorInvasion(Owner).EditorKeyDown(Self, key, shift); end else inherited; end; { TrmCheckBoxInspectorItem } function TrmCheckBoxInspectorItem.EditorClass: TWinControlClass; begin result := TrmInspectorCheckBox; end; function TrmCheckBoxInspectorItem.GetStringValue: string; begin result := booltostr(fValue); end; procedure TrmCheckBoxInspectorItem.GetValueFromEditor(Editor: TWinControl); begin if Editor is TrmInspectorCheckBox then AsString := BoolTostr(TrmInspectorCheckBox(Editor).checked); end; procedure TrmCheckBoxInspectorItem.SetStringValue(const Value: string); begin fValue := strtoBool(Value); if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmCheckBoxInspectorItem.SetupEditor(Inspector: TrmInspector; Editor: TWinControl); begin if Editor is TrmInspectorCheckBox then begin with TrmInspectorCheckBox(Editor) do begin Font := Inspector.Font; Caption := 'Ryan'; CBXAlignment := cbxCentered; WantTabs := true; WantArrows := true; Flat := true; ShowFocusRect := false; end; end; end; procedure TrmCheckBoxInspectorItem.SetValue(const Value: Boolean); begin fValue := value; if assigned(InspectorControl) then InspectorControl.Invalidate; end; procedure TrmCheckBoxInspectorItem.SetValueIntoEditor(Editor: TWinControl); begin if Editor is TrmInspectorCheckBox then TrmInspectorCheckBox(Editor).checked := strtobool(AsString); end; { TrmInspectorCheckBox } { TrmInspectorCheckBox } procedure TrmInspectorCheckBox.KeyDown(var Key: Word; Shift: TShiftState); begin if ((key = vk_Down) or (key = vk_up)) and (shift = []) then begin if Owner is TrmInspector then TrmInspectorInvasion(Owner).EditorKeyDown(Self, key, shift); end else inherited; end; procedure TrmInspectorCheckBox.keypress(var Key: Char); begin inherited; if key = #9 then key := #0; end; initialization RegisterClasses([ TrmStringInspectorItem, TrmComplexInspectorItem, TrmComboInspectorItem, TrmIntegerInspectorItem, TrmDateInspectorItem, TrmCheckboxInspectorItem ]); end.
unit DSA.Tree.AVLTree; interface uses System.SysUtils, System.Rtti, System.Math, DSA.List_Stack_Queue.ArrayList, DSA.Interfaces.DataStructure, DSA.Interfaces.Comparer, DSA.Utils; type { TAVLTree } TAVLTree<K, V> = class private type { TNode } TNode = class public key: K; Value: V; Left, Right: TNode; Height: integer; constructor Create(newkey: K; newValue: V); end; TPtrV = TPtr_V<V>; TArrayList_K = TArrayList<K>; var __root: TNode; __size: integer; __comparer: IComparer<K>; function __add(node: TNode; key: K; Value: V): TNode; /// <summary> 获得节点node的平衡因子 </summary> function __getBalanceFactor(node: TNode): integer; /// <summary> 获得节点node的高度 </summary> function __getHeight(node: TNode): integer; function __getNode(node: TNode; key: K): TNode; function __remove(node: TNode; key: K): TNode; function __minimum(node: TNode): TNode; procedure __inOrder(node: TNode; list: TArrayList_K); /// <summary> 判断以node为根的二叉树是否是一棵平衡二叉树, 递归算法。 </summary> function __isBalanced(node: TNode): boolean; /// <summary> /// 对节点y进行向右旋转操作,返回旋转后新的根节点x /// </summary> /// <remarks> /// <code> /// 右旋转操作: /// <para> y x </para> /// <para> / \ / \ </para> /// <para> x T4 向右旋转 z y </para> /// <para> / \ - - - - - -> / \ / \ </para> /// <para> z T3 T1 T2 T3 T4 </para> /// <para> / \ </para> /// <para> T1 T2 </para> /// </code> /// </remarks> function __rightRotate(node: TNode): TNode; /// <summary> /// 对节点y进行向左旋转操作,返回旋转后新的根节点x /// </summary> /// <remarks> /// <code> /// 左旋转操作: /// <para> y x </para> /// <para> / \ / \ </para> /// <para> T1 x 向左旋转 y z </para> /// <para> / \ - - - - - -> / \ / \ </para> /// <para> T2 z T1 T2 T3 T4 </para> /// <para> / \ </para> /// <para> T3 T4 </para> /// </code> /// </remarks> function __leftRotate(node: TNode): TNode; public constructor Create(); function Contains(key: K): boolean; /// <summary> 判断该二叉树是否是一棵平衡二叉树 </summary> function IsBalanced: boolean; /// <summary> 判断该二叉树是否是一棵二分搜索树 </summary> function IsBST: boolean; function Get(key: K): TPtrV; function GetSize: integer; function IsEmpty: boolean; function Remove(key: K): TPtrV; procedure Add(key: K; Value: V); procedure Set_(key: K; newValue: V); function KeySets: TArrayList_K; end; procedure Main; implementation type TAVLTree_str_int = TAVLTree<string, integer>; procedure Main; var words: TArrayList_str; alt: TAVLTree_str_int; i: integer; str: string; begin words := TArrayList_str.Create(); if TDsaUtils.ReadFile(FILE_PATH + A_File_Name, words) then begin Writeln('Total words: ', words.GetSize); end; alt := TAVLTree_str_int.Create; for i := 0 to words.GetSize - 1 do begin if alt.Contains(words[i]) then alt.Set_(words[i], alt.Get(words[i]).PValue^ + 1) else alt.Add(words[i], 1); end; Writeln('Total different words: ', alt.GetSize); TDsaUtils.DrawLine; Writeln('Frequency of pride: ', alt.Get('pride').PValue^); Writeln('Frequency of prejudice: ', alt.Get('prejudice').PValue^); Writeln('IsBST: ', alt.IsBST); Writeln('IsBalanced :', alt.IsBalanced); for str in alt.KeySets.ToArray do begin alt.Remove(str); if (not alt.IsBalanced) or (not alt.IsBST) then Writeln(alt.GetSize); end; end; { TAVLTree } procedure TAVLTree<K, V>.Add(key: K; Value: V); begin __root := __add(__root, key, Value); end; function TAVLTree<K, V>.Contains(key: K): boolean; begin Result := __getNode(__root, key) <> nil; end; constructor TAVLTree<K, V>.Create(); begin inherited; __comparer := TComparer<K>.Default; end; function TAVLTree<K, V>.Get(key: K): TPtrV; var node: TNode; begin node := __getNode(__root, key); if node = nil then Result.PValue := nil else Result.PValue := @node.Value; end; function TAVLTree<K, V>.GetSize: integer; begin Result := __size; end; function TAVLTree<K, V>.IsBalanced: boolean; begin Result := __isBalanced(__root); end; function TAVLTree<K, V>.IsBST: boolean; var list: TArrayList_K; i: integer; bool: boolean; begin bool := True; list := TArrayList_K.Create(); __inOrder(__root, list); for i := 1 to list.GetSize - 1 do if __comparer.Compare(list.Get(i - 1), list.Get(i)) > 0 then bool := False else bool := True; Result := bool; end; function TAVLTree<K, V>.IsEmpty: boolean; begin Result := __size = 0; end; function TAVLTree<K, V>.Remove(key: K): TPtrV; var node: TNode; begin node := __getNode(__root, key); if node = nil then begin Result.PValue := nil; Exit; end; __root := __remove(__root, key); Result.PValue := @node.Value; end; procedure TAVLTree<K, V>.Set_(key: K; newValue: V); var node: TNode; Value: TValue; s: string; begin node := __getNode(__root, key); if node = nil then begin TValue.Make(@key, TypeInfo(K), Value); s := Value.ToString; raise Exception.Create(s + ' doesn''t exist!'); end else node.Value := newValue; end; function TAVLTree<K, V>.KeySets: TArrayList_K; var list: TArrayList_K; begin list := TArrayList_K.Create; __inOrder(__root, list); Result := list; end; function TAVLTree<K, V>.__add(node: TNode; key: K; Value: V): TNode; var bool: integer; balanceFactor, Left, Right: integer; begin if node = nil then begin Inc(__size); Result := TNode.Create(key, Value); Exit; end; bool := __comparer.Compare(key, node.key); if bool < 0 then node.Left := __add(node.Left, key, Value) else if bool > 0 then node.Right := __add(node.Right, key, Value) else node.Value := Value; // 更新Height node.Height := Max(__getHeight(node.Left), __getHeight(node.Right)) + 1; // 计算平衡因子 balanceFactor := __getBalanceFactor(node); // 平衡维护 // LL if (balanceFactor > 1) and (__getBalanceFactor(node.Left) >= 0) then begin Result := __rightRotate(node); Exit; end; // RR if (balanceFactor < -1) and (__getBalanceFactor(node.Right) <= 0) then begin Result := __leftRotate(node); Exit; end; // LR if (balanceFactor > 1) and (__getBalanceFactor(node.Left) < 0) then begin node.Left := __leftRotate(node.Left); Result := __rightRotate(node); Exit; end; // RL if (balanceFactor < -1) and (__getBalanceFactor(node.Right) > 0) then begin node.Right := __rightRotate(node.Right); Result := __leftRotate(node); Exit; end; Result := node; end; function TAVLTree<K, V>.__getBalanceFactor(node: TNode): integer; begin if node = nil then begin Result := 0; Exit; end; Result := __getHeight(node.Left) - __getHeight(node.Right); end; function TAVLTree<K, V>.__getHeight(node: TNode): integer; begin if node = nil then begin Result := 0; Exit; end; Result := node.Height; end; function TAVLTree<K, V>.__getNode(node: TNode; key: K): TNode; var bool: integer; begin if node = nil then Exit(nil); bool := __comparer.Compare(key, node.key); if bool < 0 then Result := __getNode(node.Left, key) else if bool > 0 then Result := __getNode(node.Right, key) else Result := node; end; function TAVLTree<K, V>.__minimum(node: TNode): TNode; begin if node.Left = nil then begin Result := node; Exit; end; Result := __minimum(node.Left); end; procedure TAVLTree<K, V>.__inOrder(node: TNode; list: TArrayList_K); begin if node = nil then Exit; __inOrder(node.Left, list); list.AddLast(node.key); __inOrder(node.Right, list); end; function TAVLTree<K, V>.__isBalanced(node: TNode): boolean; var balanceFactor: integer; begin if node = nil then begin Result := True; Exit; end; balanceFactor := __getBalanceFactor(node); if Abs(balanceFactor) > 1 then Exit(False); Result := __isBalanced(node.Left) and __isBalanced(node.Right); end; function TAVLTree<K, V>.__leftRotate(node: TNode): TNode; var x, y, T2: TNode; begin y := node; x := y.Right; T2 := x.Left; // 向左旋转过程 x.Left := y; y.Right := T2; // 更新height y.Height := Max(__getHeight(y.Left), __getHeight(y.Right)) + 1; x.Height := Max(__getHeight(x.Left), __getHeight(x.Right)) + 1; Result := x; end; function TAVLTree<K, V>.__remove(node: TNode; key: K): TNode; var leftNode, rightNode, succesorNode, minNode, retNode: TNode; bool, balanceFactor: integer; begin leftNode := nil; rightNode := nil; succesorNode := nil; if node = nil then begin Result := nil; Exit; end; bool := __comparer.Compare(key, node.key); if bool < 0 then begin node.Left := __remove(node.Left, key); retNode := node; end else if bool > 0 then begin node.Right := __remove(node.Right, key); retNode := node; end else // e = node.e begin if node.Left = nil then begin rightNode := node.Right; FreeAndNil(node); Dec(__size); retNode := rightNode; end else if node.Right = nil then begin leftNode := node.Left; FreeAndNil(node); Dec(__size); retNode := leftNode; end else begin // 待删除节点左右子树均不空的情况 // 找到比待删除节点大的最小节点,即待删除节点右子树的最小节点 // 用这个节点顶替待删除节点的位置 minNode := __minimum(node.Right); succesorNode := TNode.Create(minNode.key, minNode.Value); succesorNode.Right := __remove(node.Right, succesorNode.key); succesorNode.Left := node.Left; FreeAndNil(node); retNode := succesorNode; end; end; if retNode = nil then begin Result := nil; Exit; end; // 更新Height retNode.Height := 1 + Max(__getHeight(retNode.Left), __getHeight(retNode.Right)); // 计算平衡因子 balanceFactor := __getBalanceFactor(retNode); // 平衡维护 // LL if (balanceFactor > 1) and (__getBalanceFactor(retNode.Left) >= 0) then begin Result := __rightRotate(retNode); Exit; end; // RR if (balanceFactor < -1) and (__getBalanceFactor(retNode.Right) <= 0) then begin Result := __leftRotate(retNode); Exit; end; // LR if (balanceFactor > 1) and (__getBalanceFactor(retNode.Left) < 0) then begin retNode.Left := __leftRotate(retNode.Left); Result := __rightRotate(retNode); Exit; end; // RL if (balanceFactor < -1) and (__getBalanceFactor(retNode.Right) > 0) then begin retNode.Right := __rightRotate(retNode.Right); Result := __leftRotate(retNode); Exit; end; Result := retNode; end; function TAVLTree<K, V>.__rightRotate(node: TNode): TNode; var x, y, T3: TNode; begin y := node; x := y.Left; T3 := x.Right; // 右旋转过程 x.Right := y; y.Left := T3; // 更新height y.Height := Max(__getHeight(y.Left), __getHeight(y.Right)) + 1; x.Height := Max(__getHeight(x.Left), __getHeight(x.Right)) + 1; Result := x; end; { TAVLTree.TNode } constructor TAVLTree<K, V>.TNode.Create(newkey: K; newValue: V); begin Self.key := newkey; Self.Value := newValue; Left := nil; Right := nil; Height := 1; end; end.
unit ufrmDisplayPOSMonitor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, Mask, ActnList, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, System.Actions, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC; type TfrmDisplayPOSMonitor = class(TfrmMasterBrowse) pnl1: TPanel; lbl1: TLabel; dtNow: TcxDateEdit; lbl3: TLabel; edtShift: TEdit; pnl3: TPanel; lbl11: TcxLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure dtNowKeyPress(Sender: TObject; var Key: Char); procedure lbl10Click(Sender: TObject); procedure lbl11Click(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure edtShiftKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private // FFinalPayment : TNewFinalPayment; FUnitId : Integer; iY, FLeftMain : Integer; FtopMain : Integer; // procedure ParseHeaderGrid(); // procedure ParseDataGrid(); procedure ShowDetailCashback(); procedure ShowGrandTotalCashback(); public { Public declarations } procedure ShowWithId(aUnitId: Integer; aTop: integer; aLeft : integer); end; var frmDisplayPOSMonitor: TfrmDisplayPOSMonitor; implementation uses ufrmPopupDetailCashback; {$R *.dfm} const {POS CODE CASHIER ID CASHIER NAME CASH PAYMENT ASSALAM COUPON BOTTLE COUPON LAIN - LAIN DEBET CARD CREDIT CARD DISCOUNT CARD TOT. CASH BACH TOT. CASH GRAND } _kolPosCode : Integer = 0; _kolCashierId : Integer = 1; _kolCashierNm : Integer = 2; _kolCashPayment : Integer = 3; _kolKuponGoro : Integer = 4; _kolKuponBottle : Integer = 5; _kolKuponLain : Integer = 6; _kolCredit : Integer = 7; _kolDebet : Integer = 8; _kolDiscCC : Integer = 9; _kolCashBackTot : Integer = 10; _kolCashGrandTot : Integer = 11; _kolBegBalance : Integer = 12; _fixedRow : Integer = 2; _colCount : Integer = 12; procedure TfrmDisplayPOSMonitor.ShowWithId(aUnitId: Integer; aTop: integer; aLeft : integer); begin FUnitId := aUnitId; FtopMain := aTop; FLeftMain := aLeft; Self.Show; end; procedure TfrmDisplayPOSMonitor.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDisplayPOSMonitor.FormCreate(Sender: TObject); begin inherited; lblHeader.Caption := 'DISPLAY POS MONITOR'; // FFinalPayment := TNewFinalPayment.Create(nil); dtNow.Date := now; // ParseHeaderGrid; // iY := strgGrid.FixedRows; end; procedure TfrmDisplayPOSMonitor.FormDestroy(Sender: TObject); begin inherited; frmDisplayPOSMonitor := nil; // FreeAndNil(FFinalPayment); end; procedure TfrmDisplayPOSMonitor.dtNowKeyPress(Sender: TObject; var Key: Char); begin // if (Key = Chr(VK_RETURN)) and (edtShift.Text <> '' ) then // begin // ParseDataGrid; // end; end; //procedure TfrmDisplayPOSMonitor.ParseDataGrid; //var // i : Integer; // n : Integer; //begin { ParseHeaderGrid; FFinalPayment.FinalPaymentPOSItems.Clear; FFinalPayment.LoadPOSTransaction(FUnitId, dtNow.Date, edtShift.Text); n := strgGrid.FixedRows ; with FFinalPayment do begin for i := 0 to FinalPaymentPOSItems.Count - 1 do begin if i > 0 then strgGrid.AddRow; strgGrid.Cells[_kolPosCode, n] := FinalPaymentPOSItems[i].BeginningBalance.POS.Code; strgGrid.Cells[_kolCashierId, n] := FinalPaymentPOSItems[i].CashierCode; strgGrid.Cells[_kolCashierNm, n] := FinalPaymentPOSItems[i].CashierName; strgGrid.Cells[_kolCashPayment, n] := CurrToStr(FinalPaymentPOSItems[i].CashPayment); strgGrid.Cells[_kolKuponGoro, n] := CurrToStr(FinalPaymentPOSItems[i].VoucherGoro); strgGrid.Cells[_kolKuponBottle, n] := CurrToStr(FinalPaymentPOSItems[i].VoucherBotol); strgGrid.Cells[_kolKuponLain, n] := CurrToStr(FinalPaymentPOSItems[i].VoucherLain); strgGrid.Cells[_kolDebet, n] := CurrToStr(FinalPaymentPOSItems[i].CardDebit); strgGrid.Cells[_kolCredit, n] := CurrToStr(FinalPaymentPOSItems[i].CardCredit); strgGrid.Cells[_kolDiscCC, n] := CurrToStr(FinalPaymentPOSItems[i].TotalDiscCard); strgGrid.Cells[_kolCashBackTot, n] := CurrToStr(FinalPaymentPOSItems[i].CashBack); strgGrid.Cells[_kolCashGrandTot, n] := CurrToStr(FinalPaymentPOSItems[i].GrandTotal); strgGrid.Cells[_kolBegBalance, n] := CurrToStr(FinalPaymentPOSItems[i].BeginningBalance.ID); Inc(n) end; strgGrid.FloatingFooter.ColumnCalc[_kolCashPayment] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolKuponGoro] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolKuponBottle] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolKuponLain] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolDebet] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolCredit] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolDiscCC] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolCashBackTot] := acSUM; strgGrid.FloatingFooter.ColumnCalc[_kolCashGrandTot]:= acSUM; end; AutoSize := true; } //end; //procedure TfrmDisplayPOSMonitor.ParseHeaderGrid; //begin { with strgGrid do begin ColCount := _colCount; if FloatingFooter.Visible then RowCount := _fixedRow + 2 else RowCount := _fixedRow + 1; FixedRows := _fixedRow; MergeCells(_kolPosCode,0,1,2); Cells[_kolPosCode,0] := 'POS CODE'; MergeCells(_kolCashierId,0,2,1); Cells[_kolCashierId,0] := 'CASHIER'; Cells[_kolCashierId,1] := 'ID'; Cells[_kolCashierNm,1] := 'NAME'; MergeCells(_kolCashPayment,0,1,2); Cells[_kolCashPayment,0] := 'CASH PAYMENT'; MergeCells(_kolKuponGoro,0,3,1); Cells[_kolKuponGoro,0] := 'VOUCHER'; Cells[_kolKuponGoro,1] := 'ASSALAM'; Cells[_kolKuponBottle,1] := 'BOTTLE'; Cells[_kolKuponLain,1] := 'OTHER'; MergeCells(_kolCredit,0,3,1); Cells[_kolCredit,0] := 'CARD'; Cells[_kolCredit,1] := 'CREDIT'; Cells[_kolDebet,1] := 'DEBET'; Cells[_kolDiscCC,1] := 'DISCOUNT'; MergeCells(_kolCashBackTot,0,1,2); Cells[_kolCashBackTot,0] := 'TOT. CASHBACK'; MergeCells(_kolCashGrandTot,0,1,2); Cells[_kolCashGrandTot,0] := 'TOT. CASHGRAND'; Cells[_kolPosCode, _fixedRow] := '-'; Cells[_kolCashierId, _fixedRow] := '-'; Cells[_kolCashierNm, _fixedRow] := '-'; Cells[_kolCashPayment, _fixedRow] := '0'; Cells[_kolKuponGoro, _fixedRow] := '0'; Cells[_kolKuponBottle, _fixedRow] := '0'; Cells[_kolKuponLain, _fixedRow] := '0'; Cells[_kolDebet, _fixedRow] := '0'; Cells[_kolCredit, _fixedRow] := '0'; Cells[_kolDiscCC, _fixedRow] := '0'; Cells[_kolCashBackTot, _fixedRow] := '0'; Cells[_kolCashGrandTot, _fixedRow] := '0'; Cells[_kolBegBalance, _fixedRow] := '0'; end; } //end; procedure TfrmDisplayPOSMonitor.ShowDetailCashback; begin {if not Assigned(frmPopupDetailCashback) then frmPopupDetailCashback := TfrmPopupDetailCashback.Create(Application); frmPopupDetailCashback.Top := FtopMain + pnl3.Top - pnl3.Height; frmPopupDetailCashback.Left := FLeftMain + pnl3.Left + (pnl3.Width - frmPopupDetailCashback.Width); frmPopupDetailCashback.ShowWithUserId(FUnitId, strgGrid.Ints[_kolBegBalance, iy]); } end; procedure TfrmDisplayPOSMonitor.ShowGrandTotalCashback; begin // if not Assigned(frmPopupTransactionCashback) then // frmPopupTransactionCashback := TfrmPopupTransactionCashback.Create(Application); // // frmPopupTransactionCashback.Top := frmMain.Top + pnl3.Top - pnl3.Height; // frmPopupTransactionCashback.Left := frmMain.Left + pnl3.Left + (pnl3.Width - frmPopupTransactionCashback.Width); // frmPopupTransactionCashback.Free; end; procedure TfrmDisplayPOSMonitor.lbl10Click(Sender: TObject); begin ShowGrandTotalCashback; end; procedure TfrmDisplayPOSMonitor.lbl11Click(Sender: TObject); begin ShowDetailCashback; end; procedure TfrmDisplayPOSMonitor.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; // if(Key = Ord('T'))and(ssctrl in Shift) then // ShowGrandTotalCashback; if(Key = Ord('D'))and(ssctrl in Shift) then ShowDetailCashback; end; procedure TfrmDisplayPOSMonitor.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; iY := NewRow; end; procedure TfrmDisplayPOSMonitor.edtShiftKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; // if not (Key in [0..9, VK_RETURN, VK_BACK]) then // begin // Key := Ord(#0); // end; if (Key = VK_RETURN) and (dtNow.Text <> '') then begin edtShift.Enabled := False; // ClearAdvStringGrid(strgGrid); // cClearStringGrid(strgGrid,True); // ParseDataGrid; edtShift.Enabled := True; end; end; procedure TfrmDisplayPOSMonitor.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // inherited; if(Key = Ord('D')) and (ssctrl in Shift) then lbl11Click(Self) else if(Key = VK_F5) and (ssctrl in Shift) then actRefreshExecute(Self) else if(Key = VK_Escape) then Close end; end.
unit eIternalRequests; interface uses API_ORM, eCommon; type TIternalRequest = class(TEntity) private FHeaders: string; FLinkID: Integer; FPostData: string; FURL: string; function GetHeaderItem(const aName: string): string; function GetStrItem(const aStr, aName: string): string; function GetPostDataItem(const aName: string): string; procedure SetHeaderItem(const aName, aValue: string); procedure SetPostDataItem(const aName, aValue: string); procedure SetStrItem(var aProp: string; const aName, aValue: string); public class function GetStructure: TSructure; override; property HeaderItem[const aName: string]: string read GetHeaderItem write SetHeaderItem; property PostDataItem[const aName: string]: string read GetPostDataItem write SetPostDataItem; published property Headers: string read FHeaders write FHeaders; property LinkID: Integer read FLinkID write FLinkID; property PostData: string read FPostData write FPostData; property URL: string read FURL write FURL; end; TIternalRequestList = TEntityAbstractList<TIternalRequest>; implementation uses API_Strings, eLink, System.SysUtils; procedure TIternalRequest.SetStrItem(var aProp: string; const aName, aValue: string); var i: Integer; Index: Integer; PostDataArr: TArray<string>; begin Index := -1; PostDataArr := aProp.Split([';']); for i := 0 to Length(PostDataArr) - 1 do if TStrTool.ExtractKey(PostDataArr[i]) = aName then begin Index := i; Break; end; if Index = -1 then PostDataArr := PostDataArr + [Format('%s=%s', [aName, aValue])] else PostDataArr[Index] := Format('%s=%s', [aName, aValue]); aProp := string.Join(';', PostDataArr); end; procedure TIternalRequest.SetPostDataItem(const aName, aValue: string); begin SetStrItem(FPostData, aName, aValue); end; procedure TIternalRequest.SetHeaderItem(const aName, aValue: string); begin SetStrItem(FHeaders, aName, aValue); end; function TIternalRequest.GetPostDataItem(const aName: string): string; begin Result := GetStrItem(PostData, aName); end; function TIternalRequest.GetHeaderItem(const aName: string): string; begin Result := GetStrItem(Headers, aName); end; function TIternalRequest.GetStrItem(const aStr, aName: string): string; var StrArr: TArray<string>; StrRow: string; begin Result := ''; StrArr := aStr.Split([';']); for StrRow in StrArr do begin if aName = TStrTool.ExtractKey(StrRow) then Exit(TStrTool.ExtractValue(StrRow)); end; end; class function TIternalRequest.GetStructure: TSructure; begin Result.TableName := 'RQST_ITERNAL_REQUESTS'; AddForeignKey(Result.ForeignKeyArr, 'LINK_ID', TLink, 'ID'); end; end.
unit fSeleccionarZonaHoraria; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.Layouts, FMX.ListBox; type TfrmZonaHoraria = class(TForm) tbMain: TToolBar; recFondoToolBar: TRectangle; lblTitulo: TLabel; sbtRegresar: TSpeedButton; sbtGuardar: TSpeedButton; lstZona: TListBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lstZonaDblClick(Sender: TObject); procedure FormShow(Sender: TObject); private function getZona: string; public property Zona:string read getZona; end; var frmZonaHoraria: TfrmZonaHoraria; implementation {$R *.fmx} procedure TfrmZonaHoraria.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caFree; end; procedure TfrmZonaHoraria.FormShow(Sender: TObject); begin lstZona.ScrollToItem(lstZona.Selected); end; function TfrmZonaHoraria.getZona: string; begin if Assigned(lstZona.Selected) then Result := lstZona.Selected.Text else Result := 'America/Mexico_City'; end; procedure TfrmZonaHoraria.lstZonaDblClick(Sender: TObject); begin ModalResult := mrOk; end; end.
unit InflatablesList_Item_Base; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Graphics, AuxTypes, AuxClasses, MemoryBuffer, InflatablesList_Types, InflatablesList_Data, InflatablesList_ItemShop, InflatablesList_ItemPictures; type TILItemUpdatedFlag = (iliufMainList,iliufSmallList,iliufMiniList,iliufOverview, iliufTitle,iliufPictures,iliufFlags,iliufValues,iliufOthers,iliufShopList); TILItemUpdatedFlags = set of TILItemUpdatedFlag; TILItem_Base = class(TCustomListObject) protected fDataProvider: TILDataProvider; fOwnsDataProvider: Boolean; fStaticSettings: TILStaticManagerSettings; fIndex: Integer; // used in sorting, transient (not copied in copy constructor) fFilteredOut: Boolean; // transient fUpdateCounter: Integer; // transient fUpdated: TILItemUpdatedFlags; // transient fClearingSelected: Boolean; // transient // encryption fEncrypted: Boolean; // item will be encrypted during saving fDataAccessible: Boolean; // unencrypted or decrypted item fEncryptedData: TMemoryBuffer; // stores encrypted data until they are decrypted, user data stores item structure // internal events forwarded from item shops fOnShopListItemUpdate: TILIndexedObjectL1Event; // all events are transient fOnShopValuesUpdate: TILObjectL1Event; fOnShopAvailHistoryUpd: TILObjectL1Event; fOnShopPriceHistoryUpd: TILObjectL1Event; // internal events fOnMainListUpdate: TNotifyEvent; fOnSmallListUpdate: TNotifyEvent; fOnMiniListUpdate: TNotifyEvent; fOnOverviewUpdate: TNotifyEvent; fOnTitleUpdate: TNotifyEvent; fOnPicturesUpdate: TNotifyEvent; fOnFlagsUpdate: TNotifyEvent; fOnValuesUpdate: TNotifyEvent; fOnOthersUpdate: TNotifyEvent; fOnShopListUpdate: TNotifyEvent; fOnPasswordRequest: TILPasswordRequest; // item data... // general read-only info fUniqueID: TGUID; fTimeOfAddition: TDateTime; // stored pictures fPictures: TILItemPictures; // basic specs fItemType: TILItemType; fItemTypeSpec: String; // closer specification of type fPieces: UInt32; fUserID: String; fManufacturer: TILItemManufacturer; fManufacturerStr: String; fTextID: String; fNumID: Int32; // flags, tags fFlags: TILItemFlags; fTextTag: String; fNumTag: Int32; // extended specs fWantedLevel: UInt32; // 0..7 fVariant: String; // color, pattern, ... fVariantTag: String; // for automation fSurfaceFinish: TILItemSurfaceFinish; // glossy, matte, ... fMaterial: TILItemMaterial; // eg. pvc, silicone, ... fThickness: UInt32; // [um] - micrometers fSizeX: UInt32; // length (diameter if applicable) fSizeY: UInt32; // width (inner diameter if applicable) fSizeZ: UInt32; // height fUnitWeight: UInt32; // [g] // some other stuff fNotes: String; fReviewURL: String; fUnitPriceDefault: UInt32; fRating: UInt32; // 0..100 [%] fRatingDetails: String; // availability and prices (calculated from shops) fUnitPriceLowest: UInt32; fUnitPriceHighest: UInt32; fUnitPriceSelected: UInt32; fAvailableLowest: Int32; // negative value means "more than" fAvailableHighest: Int32; fAvailableSelected: Int32; // shops fShopCount: Integer; fShops: array of TILItemShop; // getters and setters procedure SetStaticSettings(Value: TILStaticManagerSettings); virtual; procedure SetIndex(Value: Integer); virtual; procedure SetEncrypted(Value: Boolean); virtual; abstract; // data getters and setters procedure SetItemType(Value: TILItemType); virtual; procedure SetItemTypeSpec(const Value: String); virtual; procedure SetPieces(Value: UInt32); virtual; procedure SetUserID(const Value: String); virtual; procedure SetManufacturer(Value: TILItemManufacturer); virtual; procedure SetManufacturerStr(const Value: String); virtual; procedure SetTextID(const Value: String); virtual; procedure SetNumID(Value: Int32); virtual; procedure SetFlags(Value: TILItemFlags); virtual; procedure SetTextTag(const Value: String); virtual; procedure SetNumTag(Value: Int32); virtual; procedure SetWantedLevel(Value: UInt32); virtual; procedure SetVariant(const Value: String); virtual; procedure SetVariantTag(const Value: String); virtual; procedure SetSurfaceFinish(Value: TILItemSurfaceFinish); virtual; procedure SetMaterial(Value: TILItemMaterial); virtual; procedure SetThickness(Value: UInt32); virtual; procedure SetSizeX(Value: UInt32); virtual; procedure SetSizeY(Value: UInt32); virtual; procedure SetSizeZ(Value: UInt32); virtual; procedure SetUnitWeight(Value: UInt32); virtual; procedure SetNotes(const Value: String); virtual; procedure SetReviewURL(const Value: String); virtual; procedure SetUnitPriceDefault(Value: UInt32); virtual; procedure SetRating(Value: UInt32); virtual; procedure SetRatingDetails(const Value: String); virtual; Function GetShop(Index: Integer): TILItemShop; virtual; // list methods Function GetCapacity: Integer; override; procedure SetCapacity(Value: Integer); override; Function GetCount: Integer; override; procedure SetCount(Value: Integer); override; // handlers for pictures events procedure PicPicturesChange(Sender: TObject); virtual; // handlers for item shop events procedure ShopClearSelectedHandler(Sender: TObject); virtual; procedure ShopUpdateOverviewHandler(Sender: TObject); virtual; procedure ShopUpdateShopListItemHandler(Sender: TObject); virtual; procedure ShopUpdateValuesHandler(Sender: TObject); virtual; procedure ShopUpdateAvailHistoryHandler(Sender: TObject); virtual; procedure ShopUpdatePriceHistoryHandler(Sender: TObject); virtual; // event callers procedure UpdateShopListItem(Index: Integer); virtual; procedure UpdateMainList; virtual; procedure UpdateSmallList; virtual; procedure UpdateMiniList; virtual; procedure UpdateOverview; virtual; procedure UpdateTitle; virtual; procedure UpdatePictures; virtual; procedure UpdateFlags; virtual; procedure UpdateValues; virtual; procedure UpdateOthers; virtual; procedure UpdateShopList; virtual; Function RequestItemsPassword(out Password: String): Boolean; virtual; // macro callers procedure UpdateList; virtual; // updates all lists procedure UpdateShops; virtual; // when list shop is added or deleted // other protected methods procedure InitializeData; virtual; procedure FinalizeData; virtual; procedure Initialize; virtual; procedure Finalize; virtual; public constructor Create(DataProvider: TILDataProvider); overload; constructor Create; overload; constructor CreateAsCopy(DataProvider: TILDataProvider; Source: TILItem_Base; CopyPics: Boolean; UniqueCopy: Boolean); overload; virtual; constructor CreateAsCopy(Source: TILItem_Base; CopyPics: Boolean; UniqueCopy: Boolean); overload; destructor Destroy; override; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; // shops Function LowIndex: Integer; override; Function HighIndex: Integer; override; Function ShopLowIndex: Integer; virtual; Function ShopHighIndex: Integer; virtual; Function ShopIndexOf(const Name: String): Integer; overload; virtual; Function ShopIndexOf(Shop: TILITemShop): Integer; overload; virtual; Function ShopAdd: Integer; virtual; procedure ShopExchange(Idx1,Idx2: Integer); virtual; procedure ShopDelete(Index: Integer); virtual; procedure ShopClear; virtual; // data helpers procedure ResetTimeOfAddition; virtual; procedure BroadcastReqCount; virtual; Function SetFlagValue(ItemFlag: TILItemFlag; NewValue: Boolean): Boolean; virtual; procedure GetPriceAndAvailFromShops; virtual; procedure FlagPriceAndAvail(OldPrice: UInt32; OldAvail: Int32); virtual; procedure GetAndFlagPriceAndAvail(OldPrice: UInt32; OldAvail: Int32); virtual; Function SomethingIsUnknown: Boolean; virtual; Function IsAvailable(HonorCount: Boolean): Boolean; virtual; // other methods procedure AssignInternalEvents( ShopListItemUpdate: TILIndexedObjectL1Event; ShopValuesUpdate, ShopAvailHistUpdate, ShopPriceHistUpdate: TILObjectL1Event; MainListUpdate, SmallListUpdate, MiniListUpdate, OverviewUpdate, TitleUpdate, PicturesUpdate, FlagsUpdate, ValuesUpdate, OthersUpdate, ShopListUpdate: TNotifyEvent; ItemsPasswordRequest: TILPasswordRequest); virtual; procedure ClearInternalEvents; virtual; procedure AssignInternalEventHandlers; virtual; // properties property StaticSettings: TILStaticManagerSettings read fStaticSettings write SetStaticSettings; property Index: Integer read fIndex write SetIndex; property FilteredOut: Boolean read fFilteredOut; // encryption property Encrypted: Boolean read fEncrypted write SetEncrypted; property DataAccessible: Boolean read fDataAccessible; property EncryptedData: TMemoryBuffer read fEncryptedData; // item data property UniqueID: TGUID read fUniqueID; property TimeOfAddition: TDateTime read fTimeOfAddition; property Pictures: TILItemPictures read fPictures; property ItemType: TILItemType read fItemType write SetItemType; property ItemTypeSpec: String read fItemTypeSpec write SetItemTypeSpec; property Pieces: UInt32 read fPieces write SetPieces; property UserID: String read fUserID write SetUserID; property Manufacturer: TILItemManufacturer read fManufacturer write SetManufacturer; property ManufacturerStr: String read fManufacturerStr write SetManufacturerStr; property NumID: Int32 read fNumID write SetNumID; property TextID: String read fTextID write SetTextID; property Flags: TILItemFlags read fFlags write SetFlags; property TextTag: String read fTextTag write SetTextTag; property NumTag: Int32 read fNumTag write SetNumTag; property WantedLevel: UInt32 read fWantedLevel write SetWantedLevel; property Variant: String read fVariant write SetVariant; property VariantTag: String read fVariantTag write SetVariantTag; property SurfaceFinish: TILItemSurfaceFinish read fSurfaceFinish write SetSurfaceFinish; property Material: TILItemMaterial read fMaterial write SetMaterial; property Thickness: UInt32 read fThickness write SetThickness; property SizeX: UInt32 read fSizeX write SetSizeX; property SizeY: UInt32 read fSizeY write SetSizeY; property SizeZ: UInt32 read fSizeZ write SetSizeZ; property UnitWeight: UInt32 read fUnitWeight write SetUnitWeight; property Notes: String read fNotes write SetNotes; property ReviewURL: String read fReviewURL write SetReviewURL; property UnitPriceDefault: UInt32 read fUnitPriceDefault write SetUnitPriceDefault; property Rating: UInt32 read fRating write SetRating; property RatingDetails: String read fRatingDetails write SetRatingDetails; property UnitPriceLowest: UInt32 read fUnitPriceLowest; property UnitPriceHighest: UInt32 read fUnitPriceHighest; property UnitPriceSelected: UInt32 read fUnitPriceSelected; property AvailableLowest: Int32 read fAvailableLowest; property AvailableHighest: Int32 read fAvailableHighest; property AvailableSelected: Int32 read fAvailableSelected; property ShopCount: Integer read GetCount; property Shops[Index: Integer]: TILItemShop read GetShop; default; end; implementation uses SysUtils, InflatablesList_Utils; procedure TILItem_Base.SetStaticSettings(Value: TILStaticManagerSettings); var i: Integer; begin fStaticSettings := IL_ThreadSafeCopy(Value); fPictures.StaticSettings := fStaticSettings; For i := ShopLowIndex to ShopHighIndex do fShops[i].StaticSettings := fStaticSettings; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetIndex(Value: Integer); begin If fIndex <> Value then begin fIndex := Value; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetItemType(Value: TILItemType); begin If fItemType <> Value then begin fItemType := Value; UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetItemTypeSpec(const Value: String); begin If not IL_SameStr(fItemTypeSpec,Value) then begin fItemTypeSpec := Value; UniqueString(fItemTypeSpec); UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetPieces(Value: UInt32); var i: Integer; begin If fPieces <> Value then begin fPieces := Value; For i := ShopLowIndex to ShopHighIndex do fShops[i].RequiredCount := fPieces; BeginUpdate; try FlagPriceAndAvail(fUnitPriceSelected,fAvailableSelected); UpdateList; UpdateOverview; UpdateTitle; UpdateValues; // UpdteFlags is called in FlagPriceAndAvail only when needed finally EndUpdate; end; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetUserID(const Value: String); begin If not IL_SameStr(fUserID,Value) then begin fUserID := Value; UniqueString(fUserID); UpdateList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetManufacturer(Value: TILItemManufacturer); begin If fManufacturer <> Value then begin fManufacturer := Value; UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetManufacturerStr(const Value: String); begin If not IL_SameStr(fManufacturerStr,Value) then begin fManufacturerStr := Value; UniqueString(fManufacturerStr); UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetTextID(const Value: String); begin If not IL_SameStr(fTextID,Value) then begin fTextID := Value; UniqueString(fTextID); UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetNumID(Value: Int32); begin If fNumID <> Value then begin fNumID := Value; UpdateList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetFlags(Value: TILItemFlags); begin If fFlags <> Value then begin fFlags := Value; BeginUpdate; try FlagPriceAndAvail(fUnitPriceSelected,fAvailableSelected); UpdateList; UpdateFlags; finally EndUpdate; end; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetTextTag(const Value: String); begin If not IL_SameStr(fTextTag,Value) then begin fTextTag := Value; UniqueString(fTextTag); UpdateMainList; UpdateSmallList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetNumTag(Value: Int32); begin If fNumTag <> Value then begin fNumTag := Value; UpdateMainList; UpdateSmallList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetWantedLevel(Value: UInt32); begin If fWantedLevel <> Value then begin fWantedLevel := Value; UpdateMainList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetVariant(const Value: String); begin If not IL_SameStr(fVariant,Value) then begin fVariant := Value; UniqueString(fVariant); UpdateMainList; UpdateSmallList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetVariantTag(const Value: String); begin If not IL_SameStr(fVariantTag,Value) then begin fVariantTag := Value; UniqueString(fVariantTag); end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetSurfaceFinish(Value: TILItemSurfaceFinish); begin If fSurfaceFinish <> Value then begin fSurfaceFinish := Value; UpdateMainList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetMaterial(Value: TILItemMaterial); begin If fMaterial <> Value then begin fMaterial := Value; UpdateMainList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetThickness(Value: UInt32); begin If fThickness <> Value then begin fThickness := Value; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetSizeX(Value: UInt32); begin If fSizeX <> Value then begin fSizeX := Value; UpdateList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetSizeY(Value: UInt32); begin If fSizeY <> Value then begin fSizeY := Value; UpdateList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetSizeZ(Value: UInt32); begin If fSizeZ <> Value then begin fSizeZ := Value; UpdateList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetUnitWeight(Value: UInt32); begin If fUnitWeight <> Value then begin fUnitWeight := Value; UpdateOverview; UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetNotes(const Value: String); begin If not IL_SameStr(fNotes,Value) then begin fNotes := Value; UniqueString(fNotes); end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetReviewURL(const Value: String); begin If not IL_SameStr(fReviewURL,Value) then begin fReviewURL := Value; UniqueString(fReviewURL); UpdateMainList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetUnitPriceDefault(Value: UInt32); begin If fUnitPriceDefault <> Value then begin fUnitPriceDefault := Value; UpdateMainList; UpdateSmallList; UpdateOverview; UpdateValues; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetRating(Value: UInt32); begin If fRating <> Value then begin fRating := Value; UpdateMainList; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetRatingDetails(const Value: String); begin If not IL_SameStr(fRatingDetails,Value) then begin fRatingDetails := Value; UniqueString(fRatingDetails); UpdateMainList; UpdateOthers; end; end; //------------------------------------------------------------------------------ Function TILItem_Base.GetShop(Index: Integer): TILItemShop; begin If CheckIndex(Index) then Result := fShops[Index] else raise Exception.CreateFmt('TILItem_Base.GetShop: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ Function TILItem_Base.GetCapacity: Integer; begin Result := Length(fShops); end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetCapacity(Value: Integer); var i: Integer; begin If Value < fShopCount then begin For i := Value to Pred(fShopCount) do fShops[i].Free; fShopCount := Value; end; SetLength(fShops,Value); end; //------------------------------------------------------------------------------ Function TILItem_Base.GetCount: Integer; begin Result := fShopCount; end; //------------------------------------------------------------------------------ procedure TILItem_Base.SetCount(Value: Integer); begin // do nothing end; //------------------------------------------------------------------------------ procedure TILItem_Base.PicPicturesChange(Sender: TObject); begin UpdateList; UpdatePictures; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopClearSelectedHandler(Sender: TObject); var i: Integer; begin If not fClearingSelected then begin fClearingSelected := True; try BeginUpdate; try If Sender is TILItemShop then For i := ShopLowIndex to ShopHighIndex do If fShops[i] <> Sender then fShops[i].Selected := False; // update overview will be called by shop that called this routine Exclude(fUpdated,iliufOverview); finally EndUpdate; end; finally fClearingSelected := False; end; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopUpdateOverviewHandler(Sender: TObject); begin UpdateOverview; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopUpdateShopListItemHandler(Sender: TObject); var Index: Integer; begin If Sender is TILItemShop then begin Index := ShopIndexOf(TILItemShop(Sender)); If CheckIndex(Index) then UpdateShopListItem(Index); end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopUpdateValuesHandler(Sender: TObject); begin If Assigned(fOnShopValuesUpdate) and (Sender is TILItemShop) then begin If not fClearingSelected then GetAndFlagPriceAndAvail(fUnitPriceSelected,fAvailableSelected); fOnShopValuesUpdate(Self,Sender); end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopUpdateAvailHistoryHandler(Sender: TObject); begin If Assigned(fOnShopAvailHistoryUpd) and (Sender is TILItemShop) then fOnShopAvailHistoryUpd(Self,Sender); end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopUpdatePriceHistoryHandler(Sender: TObject); begin If Assigned(fOnShopPriceHistoryUpd) and (Sender is TILItemShop) then fOnShopPriceHistoryUpd(Self,Sender); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateShopListItem(Index: Integer); begin If Assigned(fOnShopListItemUpdate) and CheckIndex(Index) then fOnShopListItemUpdate(Self,fShops[Index],Index); end; //------------------------------------------------------------------------------ Function TILItem_Base.RequestItemsPassword(out Password: String): Boolean; begin If Assigned(fOnPasswordRequest) then Result := fOnPasswordRequest(Self,Password) else Result := False; end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateMainList; begin If Assigned(fOnMainListUpdate) and (fUpdateCounter <= 0) then fOnMainListUpdate(Self); Include(fUpdated,iliufMainList); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateSmallList; begin If Assigned(fOnSmallListUpdate) and (fUpdateCounter <= 0) then fOnSmallListUpdate(Self); Include(fUpdated,iliufSmallList); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateMiniList; begin If Assigned(fOnMiniListUpdate) and (fUpdateCounter <= 0) then fOnMiniListUpdate(Self); Include(fUpdated,iliufMiniList); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateOverview; begin If Assigned(fOnOverviewUpdate) and (fUpdateCounter <= 0) then fOnOverviewUpdate(Self); Include(fUpdated,iliufOverview); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateTitle; begin If Assigned(fOnTitleUpdate) and (fUpdateCounter <= 0) then fOnTitleUpdate(Self); Include(fUpdated,iliufTitle); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdatePictures; begin If Assigned(fOnPicturesUpdate) and (fUpdateCounter <= 0) then fOnPicturesUpdate(Self); Include(fUpdated,iliufPictures); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateFlags; begin If Assigned(fOnFlagsUpdate) and (fUpdateCounter <= 0) then fOnFlagsUpdate(Self); Include(fUpdated,iliufFlags); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateValues; begin If Assigned(fOnValuesUpdate) and (fUpdateCounter <= 0) then fOnValuesUpdate(Self); Include(fUpdated,iliufValues); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateOthers; begin If Assigned(fOnOthersUpdate) and (fUpdateCounter <= 0) then fOnOthersUpdate(Self); Include(fUpdated,iliufOthers); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateShopList; begin If Assigned(fOnShopListUpdate) and (fUpdateCounter <= 0) then fOnShopListUpdate(Self); Include(fUpdated,iliufShopList); end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateList; begin UpdateMainList; UpdateSmallList; UpdateMiniList; end; //------------------------------------------------------------------------------ procedure TILItem_Base.UpdateShops; begin GetAndFlagPriceAndAvail(fUnitPriceSelected,fAvailableSelected); UpdateMainList; // there can be shop count shown UpdateSmallList; // there is price that depends on shops // mini list does not contain anything shop-related UpdateOverview; // -//- UpdateValues; // shop count is shown there UpdateShopList; end; //------------------------------------------------------------------------------ procedure TILItem_Base.InitializeData; begin CreateGUID(fUniqueID); fTimeOfAddition := Now; // basic specs fPictures := TILItemPictures.Create(Self); fPictures.StaticSettings := fStaticSettings; fPictures.AssignInternalEvents(PicPicturesChange); fItemType := ilitUnknown; fItemTypeSpec := ''; fPieces := 1; fUserID := ''; fManufacturer := ilimUnknown; fManufacturerStr := ''; fTextID := ''; fNumID := 0; // flags fFlags := []; fTextTag := ''; fNumTag := 0; // ext. specs fWantedLevel := 0; fVariant := ''; fVariantTag := ''; fSurfaceFinish := ilisfUnknown; fMaterial := ilimtUnknown; fThickness := 0; fSizeX := 0; fSizeY := 0; fSizeZ := 0; fUnitWeight := 0; // other info fNotes := ''; fReviewURL := ''; fUnitPriceDefault := 0; fRating := 0; fRatingDetails := ''; fUnitPriceLowest := 0; fUnitPriceHighest := 0; fUnitPriceSelected := 0; fAvailableLowest := 0; fAvailableHighest := 0; fAvailableSelected := 0; // shops fShopCount := 0; SetLength(fShops,0); end; //------------------------------------------------------------------------------ procedure TILItem_Base.FinalizeData; var i: Integer; begin FreeAndNil(fPictures); // remove shops For i := LowIndex to HighIndex do fShops[i].Free; fShopCount := 0; SetLength(fShops,0); end; //------------------------------------------------------------------------------ procedure TILItem_Base.Initialize; begin FillChar(fStaticSettings,SizeOf(TILStaticManagerSettings),0); fIndex := -1; fFilteredOut := False; fUpdateCounter := 0; fUpdated := []; fClearingSelected := False; fEncrypted := False; fDataAccessible := True; InitBuffer(fEncryptedData); InitializeData; end; //------------------------------------------------------------------------------ procedure TILItem_Base.Finalize; begin FinalizeData; FreeBuffer(fEncryptedData); end; //============================================================================== constructor TILItem_Base.Create(DataProvider: TILDataProvider); begin inherited Create; fDataProvider := DataProvider; fOwnsDataProvider := False; Initialize; end; //------------------------------------------------------------------------------ constructor TILItem_Base.Create; begin Create(TILDataProvider.Create); fOwnsDataProvider := True; end; //------------------------------------------------------------------------------ constructor TILItem_Base.CreateAsCopy(DataProvider: TILDataProvider; Source: TILItem_Base; CopyPics: Boolean; UniqueCopy: Boolean); var i: Integer; begin Create(DataProvider); fStaticSettings := IL_ThreadSafeCopy(Source.StaticSettings); fEncrypted := Source.Encrypted; fDataAccessible := Source.DataAccessible; If fEncrypted and not fDataAccessible then CopyBuffer(Source.EncryptedData,fEncryptedData); If not UniqueCopy then begin fUniqueID := Source.UniqueID; fTimeOfAddition := Source.TimeOfAddition; end; fItemType := Source.ItemType; fItemTypeSpec := Source.ItemTypeSpec; UniqueString(fItemTypeSpec); fPieces := Source.Pieces; fUserID := Source.UserID; UniqueString(fUserID); fManufacturer := Source.Manufacturer; fManufacturerStr := Source.ManufacturerStr; UniqueString(fManufacturerStr); fTextID := Source.TextID; UniqueString(fTextID); fNumID := Source.NumID; fFlags := Source.Flags; fTextTag := Source.TextTag; UniqueString(fTextTag); fNumTag := Source.NumTag; fWantedLevel := Source.WantedLevel; fVariant := Source.Variant; UniqueString(fVariant); fVariantTag := Source.VariantTag; UniqueString(fVariantTag); fSurfaceFinish := Source.SurfaceFinish; fMaterial := Source.Material; fThickness := Source.Thickness; fSizeX := Source.SizeX; fSizeY := Source.SizeY; fSizeZ := Source.SizeZ; fUnitWeight := Source.UnitWeight; fNotes := Source.Notes; UniqueString(fNotes); fReviewURL := Source.ReviewURL; UniqueString(fReviewURL); fUnitPriceDefault := Source.UnitPriceDefault; fRating := Source.Rating; fRatingDetails := Source.RatingDetails; UniqueString(fRatingDetails); fUnitPriceLowest := Source.UnitPriceLowest; fUnitPriceHighest := Source.UnitPriceHighest; fUnitPriceSelected := Source.UnitPriceSelected; fAvailableLowest := Source.AvailableLowest; fAvailableHighest := Source.AvailableHighest; fAvailableSelected := Source.AvailableSelected; // deffered picture copy If CopyPics then begin { must be called here because the copy process needs item descriptor, and that need some of the data fields to be filled } FreeAndNil(fPictures); fPictures := TILItemPictures.CreateAsCopy(Self,Source.Pictures,UniqueCopy); fPictures.AssignInternalEvents(PicPicturesChange); end; // copy shops SetLength(fShops,Source.ShopCount); fShopCount := Source.ShopCount; For i := Low(fShops) to High(fShops) do begin fShops[i] := TILItemShop.CreateAsCopy(Source[i],UniqueCopy); fShops[i].RequiredCount := fPieces; fShops[i].AssignInternalEvents( ShopClearSelectedHandler, ShopUpdateOverviewHandler, ShopUpdateShopListItemHandler, ShopUpdateValuesHandler, ShopUpdateAvailHistoryHandler, ShopUpdatePriceHistoryHandler); end; end; //------------------------------------------------------------------------------ constructor TILItem_Base.CreateAsCopy(Source: TILItem_Base; CopyPics: Boolean; UniqueCopy: Boolean); begin CreateAsCopy(TILDataProvider.Create,Source,CopyPics,UniqueCopy); fOwnsDataProvider := True; end; //------------------------------------------------------------------------------ destructor TILItem_Base.Destroy; begin Finalize; If fOwnsDataProvider then FreeAndNil(fDataProvider); inherited; end; //------------------------------------------------------------------------------ procedure TILItem_Base.BeginUpdate; begin If fUpdateCounter <= 0 then fUpdated := []; Inc(fUpdateCounter); end; //------------------------------------------------------------------------------ procedure TILItem_Base.EndUpdate; begin Dec(fUpdateCounter); If fUpdateCounter <= 0 then begin fUpdateCounter := 0; If iliufMainList in fUpdated then UpdateMainList; If iliufSmallList in fUpdated then UpdateSmallList; If iliufMiniList in fUpdated then UpdateMiniList; If iliufOverview in fUpdated then UpdateOverview; If iliufTitle in fUpdated then UpdateTitle; If iliufPictures in fUpdated then UpdatePictures; If iliufFlags in fUpdated then UpdateFlags; If iliufValues in fUpdated then UpdateValues; If iliufOthers in fUpdated then UpdateOthers; If iliufShopList in fUpdated then UpdateShopList; fUpdated := []; end; end; //------------------------------------------------------------------------------ Function TILItem_Base.LowIndex: Integer; begin Result := Low(fShops); end; //------------------------------------------------------------------------------ Function TILItem_Base.HighIndex: Integer; begin Result := Pred(fShopCount); end; //------------------------------------------------------------------------------ Function TILItem_Base.ShopLowIndex: Integer; begin Result := LowIndex; end; //------------------------------------------------------------------------------ Function TILItem_Base.ShopHighIndex: Integer; begin Result := HighIndex; end; //------------------------------------------------------------------------------ Function TILItem_Base.ShopIndexOf(const Name: String): Integer; var i: Integer; begin Result := -1; For i := ShopLowIndex to ShopHighIndex do If IL_SameText(fShops[i].Name,Name) then begin Result := i; Break{For i}; end; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function TILItem_Base.ShopIndexOf(Shop: TILItemShop): Integer; var i: Integer; begin Result := -1; For i := ShopLowIndex to ShopHighIndex do If fShops[i] = Shop then begin Result := i; Break{For i}; end; end; //------------------------------------------------------------------------------ Function TILItem_Base.ShopAdd: Integer; begin Grow; Result := fShopCount; fShops[Result] := TILItemShop.Create; fShops[Result].StaticSettings := fStaticSettings; fShops[Result].RequiredCount := fPieces; fShops[Result].AssignInternalEvents( ShopClearSelectedHandler, ShopUpdateOverviewHandler, ShopUpdateShopListItemHandler, ShopUpdateValuesHandler, ShopUpdateAvailHistoryHandler, ShopUpdatePriceHistoryHandler); Inc(fShopCount); UpdateShops; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopExchange(Idx1,Idx2: Integer); var Temp: TILItemShop; begin If Idx1 <> Idx2 then begin // sanity checks If not CheckIndex(Idx1) then raise Exception.CreateFmt('TILItem_Base.ShopExchange: Index 1 (%d) out of bounds.',[Idx1]); If not CheckIndex(Idx2) then raise Exception.CreateFmt('TILItem_Base.ShopExchange: Index 2 (%d) out of bounds.',[Idx1]); Temp := fShops[Idx1]; fShops[Idx1] := fShops[Idx2]; fShops[Idx2] := Temp; UpdateShopListItem(Idx1); UpdateShopListItem(Idx2); end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopDelete(Index: Integer); var i: Integer; begin If CheckIndex(Index) then begin FreeAndNil(fShops[Index]); For i := Index to Pred(ShopHighIndex) do fShops[i] := fShops[i + 1]; Dec(fShopCount); Shrink; UpdateShops; end else raise Exception.CreateFmt('TILItem_Base.ShopDelete: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILItem_Base.ShopClear; var i: Integer; begin For i := ShopLowIndex to ShopHighIndex do FreeAndNil(fShops[i]); SetLength(fShops,0); fShopCount := 0; UpdateShops; end; //------------------------------------------------------------------------------ procedure TILItem_Base.ResetTimeOfAddition; begin fTimeOfAddition := Now; end; //------------------------------------------------------------------------------ procedure TILItem_Base.BroadcastReqCount; var i: Integer; begin For i := ShopLowIndex to ShopHighIndex do fShops[i].RequiredCount := fPieces; end; //------------------------------------------------------------------------------ Function TILItem_Base.SetFlagValue(ItemFlag: TILItemFlag; NewValue: Boolean): Boolean; begin BeginUpdate; try Result := IL_SetItemFlagValue(fFlags,ItemFlag,NewValue); If (ItemFlag = ilifWanted) and (Result <> NewValue) then FlagPriceAndAvail(fUnitPriceSelected,fAvailableSelected); If Result <> NewValue then UpdateList; UpdateFlags; finally EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.GetPriceAndAvailFromShops; var i: Integer; Selected: Boolean; LowPrice: Int64; HighPrice: Int64; LowAvail: Int64; HighAvail: Int64; Function AvailIsLess(A,B: Int32): Boolean; begin If Abs(A) = Abs(B) then Result := B > 0 else Result := Abs(A) < Abs(B); end; Function AvailIsMore(A,B: Int32): Boolean; begin If Abs(A) = Abs(B) then Result := A < 0 else Result := Abs(A) > Abs(B); end; begin // first make sure only one shop is selected Selected := False; For i := ShopLowIndex to ShopHighIndex do If fShops[i].Selected and not Selected then Selected := True else fShops[i].Selected := False; // get price and avail extremes (availability must be non-zero) and selected LowPrice := 0; HighPrice := 0; LowAvail := 0; HighAvail := 0; fUnitPriceSelected := 0; fAvailableSelected := 0; For i := ShopLowIndex to ShopHighIndex do begin If (fShops[i].Available <> 0) and (fShops[i].Price > 0) then begin If (fShops[i].Price < LowPrice) or (LowPrice <= 0) then LowPrice := fShops[i].Price; If (fShops[i].Price > HighPrice) or (HighPrice <= 0) then HighPrice := fShops[i].Price; If AvailIsLess(fShops[i].Available,LowAvail) or (LowAvail <= 0) then LowAvail := fShops[i].Available; If AvailIsMore(fShops[i].Available,HighAvail) or (HighAvail <= 0) then HighAvail := fShops[i].Available; end; If fShops[i].Selected then begin fUnitPriceSelected := fShops[i].Price; fAvailableSelected := fShops[i].Available; end; end; fUnitPriceLowest := LowPrice; fUnitPriceHighest := HighPrice; fAvailableLowest := LowAvail; fAvailableHighest := HighAvail; UpdateList; UpdateOverview; UpdateValues; end; //------------------------------------------------------------------------------ procedure TILItem_Base.FlagPriceAndAvail(OldPrice: UInt32; OldAvail: Int32); begin If (ilifWanted in fFlags) and (fShopCount > 0) then begin Exclude(fFlags,ilifNotAvailable); If IsAvailable(False) then begin If not IsAvailable(True) then Include(fFlags,ilifNotAvailable); If fUnitPriceSelected <> OldPrice then Include(fFlags,ilifPriceChange); end else Include(fFlags,ilifNotAvailable); If fAvailableSelected <> OldAvail then Include(fFlags,ilifAvailChange); UpdateList; UpdateFlags; end; end; //------------------------------------------------------------------------------ procedure TILItem_Base.GetAndFlagPriceAndAvail(OldPrice: UInt32; OldAvail: Int32); begin BeginUpdate; try GetPriceAndAvailFromShops; FlagPriceAndAvail(OldPrice,OldAvail); finally EndUpdate; end; end; //------------------------------------------------------------------------------ Function TILItem_Base.SomethingIsUnknown: Boolean; begin Result := (fItemType = ilitUnknown) or (fManufacturer = ilimUnknown) or (fMaterial = ilimtUnknown) or (fSurfaceFinish = ilisfUnknown); end; //------------------------------------------------------------------------------ Function TILItem_Base.IsAvailable(HonorCount: Boolean): Boolean; begin If fUnitPriceSelected > 0 then begin If HonorCount then begin If fAvailableSelected > 0 then Result := UInt32(fAvailableSelected) >= fPieces else Result := UInt32(Abs(fAvailableSelected) * 2) >= fPieces; end else Result := fAvailableSelected <> 0; end else Result := False; end; //------------------------------------------------------------------------------ procedure TILItem_Base.AssignInternalEvents(ShopListItemUpdate: TILIndexedObjectL1Event; ShopValuesUpdate,ShopAvailHistUpdate,ShopPriceHistUpdate: TILObjectL1Event; MainListUpdate,SmallListUpdate,MiniListUpdate,OverviewUpdate,TitleUpdate, PicturesUpdate,FlagsUpdate,ValuesUpdate,OthersUpdate,ShopListUpdate: TNotifyEvent; ItemsPasswordRequest: TILPasswordRequest); begin fOnShopListItemUpdate := IL_CheckHandler(ShopListItemUpdate); fOnShopValuesUpdate := IL_CheckHandler(ShopValuesUpdate); fOnShopAvailHistoryUpd := IL_CheckHandler(ShopAvailHistUpdate); fOnShopPriceHistoryUpd := IL_CheckHandler(ShopPriceHistUpdate); fOnMainListUpdate := IL_CheckHandler(MainListUpdate); fOnSmallListUpdate := IL_CheckHandler(SmallListUpdate); fOnMiniListUpdate := IL_CheckHandler(MiniListUpdate); fOnOverviewUpdate := IL_CheckHandler(OverviewUpdate); fOnTitleUpdate := IL_CheckHandler(TitleUpdate); fOnPicturesUpdate := IL_CheckHandler(PicturesUpdate); fOnFlagsUpdate := IL_CheckHandler(FlagsUpdate); fOnValuesUpdate := IL_CheckHandler(ValuesUpdate); fOnOthersUpdate := IL_CheckHandler(OthersUpdate); fOnShopListUpdate := IL_CheckHandler(ShopListUpdate); fOnPasswordRequest := IL_CheckHandler(ItemsPasswordRequest); end; //------------------------------------------------------------------------------ procedure TILItem_Base.ClearInternalEvents; begin fOnShopListItemUpdate := nil; fOnShopValuesUpdate := nil; fOnShopAvailHistoryUpd := nil; fOnShopPriceHistoryUpd := nil; fOnMainListUpdate := nil; fOnSmallListUpdate := nil; fOnMiniListUpdate := nil; fOnOverviewUpdate := nil; fOnTitleUpdate := nil; fOnPicturesUpdate := nil; fOnFlagsUpdate := nil; fOnValuesUpdate := nil; fOnShopListUpdate := nil; fOnPasswordRequest := nil; end; //------------------------------------------------------------------------------ procedure TILItem_Base.AssignInternalEventHandlers; var i: Integer; begin // assigns handlers to internal events in all item shops For i := ShopLowIndex to ShopHighIndex do fShops[i].AssignInternalEvents( ShopClearSelectedHandler, ShopUpdateOverviewHandler, ShopUpdateShopListItemHandler, ShopUpdateValuesHandler, ShopUpdateAvailHistoryHandler, ShopUpdatePriceHistoryHandler); end; end.
unit uniteRequete; // Encapsule les données entrées par l’utilisateur interface uses SysUtils; type Requete = class private //Adresse de la source adresseDemandeur : String; //Date reception de la requete dateReception : TDateTime; //Version HTTP 1.0 ou 1.1 versionProtocole : String; //methose GET methode : String; //URL demande url : String; public //Le constructeur de la classe requête qui donne les valeur à la requête tel que l'adresse du demandeur, la date, la version du protocole, la méthode utilisée et le lien URL. //@param unAdresseDemandeur qui représente l'adresse IP du demandeur. //@param uneDateReception qui représente la date et l'heure du moment. //@param uneVersionProtocole qui est la version HTTP du protocole utilisé. Pouvant être 1.1. //@param uneMethode que représente la méthode utilisé pour l'envoi de la requête. //@param unURL qui représente le lien URL. constructor create(unAdresseDemandeur:String;uneDateReception:TDateTime;uneVersionProtocole:String;uneMethode:String;unURL:String); //Accesseur getAdresseDemandeur qui retourne un String de l'adresse. //@return returne l'adresse IP du demandeur function getAdresseDemandeur:String; //Accesseur getDateReception qui retourne la date et l'heure du moment. //@return retourne la date el l'heure en chaine de caractère. function getDateReception:TDateTime; //Accesseur de la version du protocole utilisé par le client pouvant être HTTP 1.1 par exemple. //@return retourne la version du protocole en chaine de caractère. function getVersionProtocole:String; //Accesseur l'adresse IP du demandeur qui renvoi un String de l'adresse. //return une chaîne de caractère de la méthode utilisés. function getMethode:String; //Accesseur de la page d'Internet demande par le client //@return retourne la page d'Internet en chaine de caractère. function getUrl:String; end; implementation constructor Requete.create(unAdresseDemandeur:String;uneDateReception:TDateTime;uneVersionProtocole:String;uneMethode:String;unURL:String); begin adresseDemandeur:=unAdresseDemandeur; dateReception:=uneDateReception; versionProtocole:=uneVersionProtocole; methode:=uneMethode; url:=unURL; end; function Requete.getAdresseDemandeur:String; begin result:=adresseDemandeur; end; function Requete.getDateReception:TDateTime; begin result:=dateReception; end; function Requete.getVersionProtocole:String; begin result:=versionProtocole; end; function Requete.getMethode:String; begin result:=methode; end; function Requete.getUrl:String; begin result:=url; end; end.
program pointers; { Pointers quick notes. } uses SysUtils, Variants; const tab: char = #9; tab2: string = #9#9; nl: char = LineEnding; var a: integer = 20; b: integer = 2540; {Pointer is a reference to variable (data)} {Typed Pointer can be de-referenced directly with Integer variables } //ptr: ^integer; {or} ptr: PInteger; {Untyped Pointer is a simple data type that can hold the address of Any data type. Untyped Pointer needs further casting to target pointer type, ex. PInteger(ptrA)} //ptr: Pointer; begin Writeln(''); {Get address of "a" data.} ptr := @a; {Same thing.} ptr := addr(a); {Pointers CaN't take address of constant expressions. Error: Can't take the address of constant expressions} //ptr := addr(123); {De-referencing a Pointer} //Writeln('ptr^:', tab2 + tab, ptr^); {If Poiner is untyped (var ptr: Pointer) you get the following error: "Error: Can't read or write variables of this type". Just de-referencing a Pointer variable is not sufficient. To de-reference Pointer correctly you have to: - use appropriate type of pointer and data it points (for Integer data use PInteger or ^Integer Pointer); - or cast Pointer to appropriate type (for Integer data - PInteger(ptr).} {After cast, then de-reference: prints data value (20)} Writeln('PInteger(ptr)^:', tab2, PInteger(ptr)^); Writeln(''); {We can change data the pointer referenced to, by passing other variable address to the pointer.} ptr := @b; {Now it contains address of "b" data.} {Invalid - will not compile.} //Writeln(ptr); {Error: Can't read or write variables of this type} {You have to use Format procedure to print the Pointer address} writeln(Format('Address of pointer: %p.', [@ptr]) + ''); writeln(Format('Address of data: %p.', [ptr]) + ''); writeln(Format('Content of data (dereferenced pointer): %d', [ptr^]) + ''); Writeln(''); end.
unit frmSelectObjectsForEditingUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmCustomSelectObjectsUnit, VirtualTrees, StdCtrls, Buttons, ExtCtrls, ScreenObjectUnit, Menus; type TfrmSelectObjectsForEditing = class(TfrmCustomSelectObjects) btnOK: TBitBtn; rgViewDirection: TRadioGroup; btnDelete: TBitBtn; pmChangeStates: TPopupMenu; miCheckSelected: TMenuItem; UncheckSelected1: TMenuItem; btnEditFeature: TButton; procedure FormCreate(Sender: TObject); override; procedure vstObjectsChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure btnOKClick(Sender: TObject); procedure rgViewDirectionClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure miCheckSelectedClick(Sender: TObject); procedure UncheckSelected1Click(Sender: TObject); procedure btnEditFeatureClick(Sender: TObject); private { TODO : Consider replacing this with a TScreenObjectList} // FListOfScreenObjects: TList; procedure SetData; procedure UpdateScreenObjectList; { Private declarations } protected function ShouldCheckBoxBeChecked(ScreenObject: TScreenObject): boolean; override; procedure HandleChecked(AScreenObject: TScreenObject); override; procedure HandleUnchecked(AScreenObject: TScreenObject); override; function CanSelect(ScreenObject: TScreenObject): boolean; override; public destructor Destroy; override; { Public declarations } end; implementation uses frmGoPhastUnit, frmScreenObjectPropertiesUnit, GoPhastTypes, UndoItemsScreenObjects, frmEditFeatureFormulaUnit; {$R *.dfm} procedure TfrmSelectObjectsForEditing.btnDeleteClick(Sender: TObject); var ListOfScreenObjects: TScreenObjectList; Index: Integer; ScreenObject: TScreenObject; Undo: TUndoDeleteScreenObjects; begin inherited; if FListOfScreenObjects.Count > 0 then begin ListOfScreenObjects:= TScreenObjectList.Create; try ListOfScreenObjects.Capacity := FListOfScreenObjects.Count; for Index := 0 to FListOfScreenObjects.Count - 1 do begin ScreenObject := FListOfScreenObjects[Index]; ListOfScreenObjects.Add(ScreenObject); end; Undo := TUndoDeleteScreenObjects.Create(ListOfScreenObjects); frmGoPhast.UndoStack.Submit(Undo); finally ListOfScreenObjects.Free; end; end; end; procedure TfrmSelectObjectsForEditing.btnEditFeatureClick(Sender: TObject); var ScreenObjects: TScreenObjectList; index: Integer; frmEditFeatureFormula: TfrmEditFeatureFormula; begin inherited; if not frmGoPhast.CanEdit then Exit; frmGoPhast.CanEdit := False; try if FListOfScreenObjects.Count > 0 then begin ScreenObjects := TScreenObjectList.Create; try ScreenObjects.Capacity := FListOfScreenObjects.Count; for index := 0 to FListOfScreenObjects.Count - 1 do begin ScreenObjects.Add( TScreenObject(FListOfScreenObjects[index])); end; frmEditFeatureFormula := TfrmEditFeatureFormula.Create(nil); try frmEditFeatureFormula.GetData(ScreenObjects); frmEditFeatureFormula.ShowModal; finally frmEditFeatureFormula.Free end; finally ScreenObjects.Free; end; end; finally frmGoPhast.CanEdit := True; end; end; procedure TfrmSelectObjectsForEditing.btnOKClick(Sender: TObject); begin inherited; SetData; end; function TfrmSelectObjectsForEditing.CanSelect( ScreenObject: TScreenObject): boolean; begin result := Ord(ScreenObject.ViewDirection) = rgViewDirection.ItemIndex; end; destructor TfrmSelectObjectsForEditing.Destroy; begin FListOfScreenObjects.Free; inherited; end; procedure TfrmSelectObjectsForEditing.UncheckSelected1Click(Sender: TObject); begin inherited; vstObjects.BeginUpdate; try UpdateStringTreeViewCheckedState(vstObjects, vstObjects.RootNode, csUnCheckedNormal); // SetStateOfMultipleNodes(vstObjects.RootNode, csCheckedNormal); finally vstObjects.EndUpdate; end; end; procedure TfrmSelectObjectsForEditing.UpdateScreenObjectList; var ScreenObject: TScreenObject; Index: Integer; begin FListOfScreenObjects.Clear; for Index := 0 to frmGoPhast.PhastModel.ScreenObjectCount - 1 do begin ScreenObject := frmGoPhast.PhastModel.ScreenObjects[Index]; if ScreenObject.Deleted then begin Continue; end; if ScreenObject.Selected and (Ord(ScreenObject.ViewDirection) = rgViewDirection.ItemIndex) then begin FListOfScreenObjects.Add(ScreenObject); end; end; end; procedure TfrmSelectObjectsForEditing.FormCreate(Sender: TObject); begin FListOfScreenObjects:= TList.Create; inherited; UpdateScreenObjectList; GetData; btnEditFeature.Enabled := frmGoPhast.ModelSelection in ModflowSelection; end; procedure TfrmSelectObjectsForEditing.HandleChecked( AScreenObject: TScreenObject); begin if FListOfScreenObjects.IndexOf(AScreenObject)< 0 then begin FListOfScreenObjects.Add(AScreenObject) end; end; procedure TfrmSelectObjectsForEditing.HandleUnchecked( AScreenObject: TScreenObject); begin FListOfScreenObjects.Remove(AScreenObject); end; procedure TfrmSelectObjectsForEditing.miCheckSelectedClick(Sender: TObject); begin inherited; vstObjects.BeginUpdate; try UpdateStringTreeViewCheckedState(vstObjects, vstObjects.RootNode, csCheckedNormal); // SetStateOfMultipleNodes(vstObjects.RootNode, csCheckedNormal); finally vstObjects.EndUpdate; end; end; procedure TfrmSelectObjectsForEditing.rgViewDirectionClick(Sender: TObject); begin inherited; if FListOfScreenObjects <> nil then begin UpdateScreenObjectList; GetData; end; end; procedure TfrmSelectObjectsForEditing.SetData; begin if not frmGoPhast.CanEdit then Exit; frmGoPhast.CanEdit := False; try if FListOfScreenObjects.Count > 0 then begin Assert(frmScreenObjectProperties <> nil); frmScreenObjectProperties.GetDataForMultipleScreenObjects( FListOfScreenObjects); frmScreenObjectProperties.ShowModal end; finally frmGoPhast.CanEdit := True; end; end; function TfrmSelectObjectsForEditing.ShouldCheckBoxBeChecked( ScreenObject: TScreenObject): boolean; begin result := FListOfScreenObjects.IndexOf(ScreenObject) >= 0; end; procedure TfrmSelectObjectsForEditing.vstObjectsChecked( Sender: TBaseVirtualTree; Node: PVirtualNode); begin inherited; if FSettingData or FSettingData2 or FSettingData3 then begin Exit; end; if (Sender.NodeParent[Node] = nil) then begin Exit; end; if not FOkToDoCheck then begin Exit; end; Screen.Cursor := crHourGlass; FSettingData := True; Sender.BeginUpdate; try HandleCheckChange(Node, Sender); finally Sender.EndUpdate; FSettingData := False; Screen.Cursor := crDefault; end; end; end.
unit nfsPropTextAndImageCenter; interface uses Classes, SysUtils, Contnrs, Controls, StdCtrls, ExtCtrls, Graphics; type TnfsPropTextAndImageCenter = class(TPersistent) private fOnChanged: TNotifyEvent; fImageMargin: TMargins; fUseTextAndImageCenter: Boolean; fImageLeft: Boolean; fImageRight: Boolean; procedure setUseTextAndImageCenter(const Value: Boolean); procedure MarginChanged(Sender: TObject); procedure setImageLeft(const Value: Boolean); procedure setImageRight(const Value: Boolean); protected public constructor Create; destructor Destroy; override; published property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property ImageMargin: TMargins read fImageMargin write fImageMargin; property UseTextAndImageCenter: Boolean read fUseTextAndImageCenter write setUseTextAndImageCenter default false; property ImageLeft: Boolean read fImageLeft write setImageLeft default true; property ImageRight: Boolean read fImageRight write setImageRight default false; end; implementation { TnfsPropTextAndImageCenter } constructor TnfsPropTextAndImageCenter.Create; begin fOnChanged := nil; fImageMargin := TMargins.Create(nil); fImageMargin.Right := 5; fImageMargin.Left := 5; fImageMargin.OnChange := MarginChanged; fImageLeft := true; fImageRight := false; end; destructor TnfsPropTextAndImageCenter.Destroy; begin FreeAndNil(fImageMargin); inherited; end; procedure TnfsPropTextAndImageCenter.MarginChanged(Sender: TObject); begin if Assigned(fOnChanged) then fOnChanged(Self); end; procedure TnfsPropTextAndImageCenter.setImageLeft(const Value: Boolean); begin fImageLeft := Value; fImageRight := not fImageLeft; if Assigned(fOnChanged) then fOnChanged(Self); end; procedure TnfsPropTextAndImageCenter.setImageRight(const Value: Boolean); begin fImageRight := Value; fImageLeft := not fImageRight; if Assigned(fOnChanged) then fOnChanged(Self); end; procedure TnfsPropTextAndImageCenter.setUseTextAndImageCenter( const Value: Boolean); begin fUseTextAndImageCenter := Value; if Assigned(fOnChanged) then fOnChanged(Self); end; end.
unit uArrayListOfLine; interface uses uArrayList, uLine; { Automatic dynamic lines array } type ArrayListOfLine = class(ArrayList) public procedure add(l: Line); overload; procedure put(l: Line; index: integer); overload; function remove(index: integer): Line; overload; procedure remove(l: Line); overload; function get(index: integer): Line; overload; function find(l: Line): integer; overload; end; implementation // ArrayListOfLine procedure ArrayListOfLine.add(l: Line); begin inherited add(l); end; // ArrayListOfLine procedure ArrayListOfLine.put(l: Line; index: integer); begin inherited put(l, index); end; // ArrayListOfLine function ArrayListOfLine.remove(index: integer): Line; begin remove := inherited remove(index) as Line; end; // ArrayListOfLine procedure ArrayListOfLine.remove(l: Line); var i: integer; begin for i := 0 to size() - 1 do begin if (arr[i] as Line) = l then begin remove(i); break; end; end; end; // ArrayListOfLine function ArrayListOfLine.get(index: integer): Line; begin get := inherited get(index) as Line; end; // ArrayListOfLine function ArrayListOfLine.find(l: Line): integer; var i: integer; begin find := -1; for i := 0 to len - 1 do if l = get(i) then begin find := i; break; end; end; end.
unit Demo.MaterialBarChart.TopX; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_MaterialBarChart_TopX = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_MaterialBarChart_TopX.GenerateChart; var Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_BAR_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Move'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percentage') ]); Chart.Data.AddRow(['King''s pawn (e4)', 44]); Chart.Data.AddRow(['Queen''s pawn (d4)', 31]); Chart.Data.AddRow(['Knight to King 3 (Nf3)', 12]); Chart.Data.AddRow(['Queen''s bishop pawn (c4)', 10]); Chart.Data.AddRow(['Other', 3]); // Options Chart.Options.Title('Chess opening moves'); Chart.Options.Subtitle('popularity by percentage'); Chart.Options.Legend('position', 'none'); Chart.Options.Axes('x', '{0: {side: ''top'', label: ''Percentage''}}'); Chart.Options.Bar('groupWidth', '90%'); Chart.Options.SetAsQuotedStr('bars', 'horizontal'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="width:80%; height:10%"></div>' + '<div id="Chart" style="width:80%; height:80%;margin: auto"></div>' + '<div style="width:80%; height:10%"></div>' ); GChartsFrame.DocumentGenerate('Chart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_MaterialBarChart_TopX); end.
unit ColisionCheckGA; interface uses GeometricAlgebra, Multivector, ColisionCheckBase; {$INCLUDE source/Global_Conditionals.inc} type CColisionCheckGA = class (CColisionCheckBase) private Temp: TMultiVector; function IsVertexInsideOrOutside2DEdge(var _PGA: TGeometricAlgebra; const _LS, _V: TMultiVector): byte; public constructor Create(var _PGA: TGeometricAlgebra); destructor Destroy; override; function Are2DTrianglesColiding(var _PGA: TGeometricAlgebra; const _TLS1, _TLS2, _TLS3, _TV1, _TV2, _TV3: TMultiVector): boolean; end; implementation uses GlobalVars; constructor CColisionCheckGA.Create(var _PGA: TGeometricAlgebra); begin Temp := TMultiVector.Create(_PGA.Dimension); end; destructor CColisionCheckGA.Destroy; begin Temp.Free; inherited Destroy; end; function CColisionCheckGA.IsVertexInsideOrOutside2DEdge(var _PGA: TGeometricAlgebra; const _LS, _V: TMultiVector): byte; begin _PGA.OuterProduct(Temp,_LS,_V); if Epsilon(Temp.UnsafeData[11]) <= 0 then begin Result := 1; end else begin Result := 0; end; end; // _TLS1,2,3 are line segments of one of the triangles. _TV1,2,3 are the vertexes (flats) from the other triangle. // It requires homogeneous/projective model from the geometric algebra. function CColisionCheckGA.Are2DTrianglesColiding(var _PGA: TGeometricAlgebra; const _TLS1, _TLS2, _TLS3, _TV1, _TV2, _TV3: TMultiVector): boolean; var VertexConfig1,VertexConfig2,VertexConfig3: byte; SegConfig1,SegConfig2,SegConfig3: byte; begin Result := true; // assume true for optimization {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Colision detection starts here.'); _TLS1.Debug(GlobalVars.OrigamiFile,'Triangle A Line Segment 1'); _TLS2.Debug(GlobalVars.OrigamiFile,'Triangle A Line Segment 2'); _TLS3.Debug(GlobalVars.OrigamiFile,'Triangle A Line Segment 3'); _TV1.Debug(GlobalVars.OrigamiFile,'Triangle B Vertex 1'); _TV2.Debug(GlobalVars.OrigamiFile,'Triangle B Vertex 2'); _TV3.Debug(GlobalVars.OrigamiFile,'Triangle B Vertex 3'); {$endif} {$endif} // Collect vertex configurations. 1 is outside and 0 is inside. // Vertex 1 VertexConfig1 := IsVertexInsideOrOutside2DEdge(_PGA,_TLS1, _TV1) or (2 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS2, _TV1)) or (4 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS3, _TV1)); if VertexConfig1 = 0 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Vertex 1 is inside the Triangle'); {$endif} {$endif} exit; // return true, the vertex is inside the triangle. end; // Vertex 2 VertexConfig2 := IsVertexInsideOrOutside2DEdge(_PGA,_TLS1, _TV2) or (2 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS2, _TV2)) or (4 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS3, _TV2)); if VertexConfig2 = 0 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Vertex 2 is inside the Triangle'); {$endif} {$endif} exit; // return true, the vertex is inside the triangle. end; // Vertex 3 VertexConfig3 := IsVertexInsideOrOutside2DEdge(_PGA,_TLS1, _TV3) or (2 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS2, _TV3)) or (4 * IsVertexInsideOrOutside2DEdge(_PGA,_TLS3, _TV3)); if VertexConfig3 = 0 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Vertex 3 is inside the Triangle'); {$endif} {$endif} exit; // return true, the vertex is inside the triangle. end; // Now let's check the line segments SegConfig1 := VertexConfig1 xor (VertexConfig2 and VertexConfig1); if SegConfig1 = VertexConfig1 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Segment 12 is inside the Triangle'); {$endif} {$endif} exit; // return true, the line segment crosses the triangle. end; SegConfig2 := VertexConfig2 xor (VertexConfig3 and VertexConfig2); if SegConfig2 = VertexConfig2 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Segment 23 is inside the Triangle'); {$endif} {$endif} exit; // return true, the line segment crosses the triangle. end; SegConfig3 := VertexConfig3 xor (VertexConfig1 and VertexConfig3); if SegConfig3 = VertexConfig3 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Segment 31 is inside the Triangle'); {$endif} {$endif} exit; // return true, the line segment crosses the triangle. end; // Now let's check the triangle, if it contains the other or not. if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then begin {$ifdef ORIGAMI_TEST} {$ifdef ORIGAMI_COLISION_TEST} GlobalVars.OrigamiFile.Add('Triangle is inside the Triangle'); {$endif} {$endif} exit; // return true, the triangle contains the other triangle. end; Result := false; // return false. There is no colision between the two triangles. end; end.
unit SelectPage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ADSchemaUnit, ADSchemaTypes; type TSelectForm = class(TForm) ListBoxSelect: TListBox; BtnOK: TBitBtn; procedure FormShow(Sender: TObject); procedure BtnOKClick(Sender: TObject); private { Private declarations } public { Public declarations } schema : ADSchema; selectedValue : string; procedure LoadInOtherThread(); end; TLoadThread = class(TThread) protected procedure Execute; override; end; var SelectForm: TSelectForm; implementation {$R *.dfm} procedure TLoadThread.Execute; begin SelectForm.LoadInOtherThread; end; procedure TSelectForm.LoadInOtherThread(); var entries : ADEntryList; status : ADSchemaStatus; i : integer; begin if schema <> nil then begin entries := schema.GetAll(AttributeEntry, ['cn'], status); if status.StatusType <> SuccessStatus then begin ShowMessage('Unable to load attribute list!'); status.Free; if entries <> nil then entries.Destroy; Exit; end; status.Free; if entries = nil then Exit; if entries.EntriesCount = 0 then begin entries.Destroy; Exit; end; for i := 0 to entries.EntriesCount - 1 do begin ListBoxSelect.Items.Add(entries.Items[i].Name); end; entries.Destroy; end; end; procedure TSelectForm.BtnOKClick(Sender: TObject); begin if ListBoxSelect.ItemIndex = -1 then begin ShowMessage('Please Select the attribute!'); Exit; end; selectedValue := ListBoxSelect.Items[ListBoxSelect.ItemIndex]; ModalResult := mrOk; end; procedure TSelectForm.FormShow(Sender: TObject); var newThread : TLoadThread; begin newThread := TLoadThread.Create(true); newThread.Synchronize(LoadInOtherThread); end; end.
unit uNewSubGroup; interface uses SysUtils, Classes, uTSBaseClass, uNewGroup; type TSubGroup = class(TSBaseClass) private FGroup: TGroup; FID: Integer; FKode: string; FNama: string; FSafetyStock: Double; FUnitID: Integer; function FLoadFromDB( aSQL : String ): Boolean; procedure SetUnitID(const Value: Integer); public constructor Create(aOwner : TComponent); override; destructor Destroy; override; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function ExecuteGenerateSQL: Boolean; function GetFieldNameFor_Group: string; dynamic; function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_Kode: string; dynamic; function GetFieldNameFor_Nama: string; dynamic; function GetFieldNameFor_SafetyStock: string; dynamic; function GetFieldNameFor_SUBGRUP_MERCHANGRUP_UNT_ID: string; function GetFieldNameFor_UnitID: string; function GetHeaderFlag: Integer; function LoadByID(aID : Integer; aUnitID : Integer): Boolean; function LoadByKode(aKode: string; aUnitID, aGrpId, aGrpUnitID: Integer): Boolean; function RemoveFromDB: Boolean; procedure UpdateData(aGroup_ID : Integer; aID : Integer; aKode : string; aNama : string; aSafetyStock : Double; aUnitID : Integer); property Group: TGroup read FGroup write FGroup; property ID: Integer read FID write FID; property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; property SafetyStock: Double read FSafetyStock write FSafetyStock; property UnitID: Integer read FUnitID write SetUnitID; end; implementation uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain; { ********************************** TSubGroup *********************************** } constructor TSubGroup.Create(aOwner : TComponent); begin inherited create(aOwner); FGroup := TGroup.Create(Self); ClearProperties; end; destructor TSubGroup.Destroy; begin FGroup.free; inherited Destroy; end; procedure TSubGroup.ClearProperties; begin ID := 0; FGroup.ClearProperties; Kode := ''; Nama := ''; UnitID := 0; SafetyStock := 0; end; function TSubGroup.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TSubGroup.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TSubGroup.CustomTableName: string; begin result := 'REF$SUB_GRUP'; end; function TSubGroup.FLoadFromDB( aSQL : String ): Boolean; begin result := false; State := csNone; ClearProperties; with cOpenQuery(aSQL) do Begin if not EOF then begin FGroup.LoadByID(FieldByName(GetFieldNameFor_Group).asInteger, FieldByName(GetFieldNameFor_UnitID).asInteger); FID := FieldByName(GetFieldNameFor_ID).asInteger; FKode := FieldByName(GetFieldNameFor_Kode).asString; FNama := FieldByName(GetFieldNameFor_Nama).asString; FSafetyStock := FieldByName(GetFieldNameFor_SafetyStock).AsFloat; FUnitID := FieldByName(GetFieldNameFor_UnitID).asInteger; Self.State := csLoaded; Result := True; end; Free; End; end; function TSubGroup.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; result.Append( '' ); result.Append( 'Create Table TSubGroup ( ' ); result.Append( 'TRMSBaseClass_ID Integer not null, ' ); result.Append( 'Group_ID Integer Not Null, ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Kode Varchar(30) Not Null Unique, ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'SafetyStock Integer Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TSubGroup.ExecuteGenerateSQL: Boolean; var S: string; // i: Integer; // SS: Tstrings; begin //result := TstringList.create; Result := False; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; {SS := CustomSQLTaskPrior; if SS <> nil then Begin result.AddStrings(SS); end; //SS := Nil; } if not ExecuteCustomSQLTaskPrior then begin cRollbackTrans; Exit; end else begin If FID <= 0 then begin //Generate Insert SQL FID := cGetNextID(GetFieldNameFor_ID, CustomTableName); S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_Group + ', ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_SafetyStock + ',' + GetFieldNameFor_UnitID + ',' + GetFieldNameFor_SUBGRUP_MERCHANGRUP_UNT_ID + ' ) values (' + InttoStr( FGroup.ID) + ', ' + IntToStr( FID) + ', ' + QuotedStr(FKode ) + ',' + QuotedStr(FNama ) + ',' + QuotedStr(FloatToStr(FSafetyStock)) + ', ' + IntToStr( FUnitID) + ',' + IntToStr( FUnitID) + ');' end else begin //generate Update SQL S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Group + ' = ' + IntToStr( FGroup.ID) + ', ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode ) + ', ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama ) + ', ' + GetFieldNameFor_SafetyStock + ' = ' + QuotedStr(FloatToStr(FSafetyStock)) + ', ' + GetFieldNameFor_SUBGRUP_MERCHANGRUP_UNT_ID + ' = ' + IntToStr(FUnitID) + ' where ' + GetFieldNameFor_UnitID + ' = ' + IntToStr( FUnitID) + ' and ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; end; end; {result.append( S ); //generating Collections SQL SS := CustomSQLTask; if SS <> nil then Begin result.AddStrings(SS); end; } if not cExecSQL(S, dbtPOS, False) then begin cRollbackTrans; Exit; end else Result := ExecuteCustomSQLTask; end; function TSubGroup.GetFieldNameFor_Group: string; begin Result := 'SUBGRUP_MERCHANGRUP_ID';// <<-- Rubah string ini untuk mapping end; function TSubGroup.GetFieldNameFor_ID: string; begin Result := 'SUBGRUP_ID';// <<-- Rubah string ini untuk mapping end; function TSubGroup.GetFieldNameFor_Kode: string; begin Result := 'SUBGRUP_CODE';// <<-- Rubah string ini untuk mapping end; function TSubGroup.GetFieldNameFor_Nama: string; begin Result := 'SUBGRUP_NAME';// <<-- Rubah string ini untuk mapping end; function TSubGroup.GetFieldNameFor_SafetyStock: string; begin Result := 'SafetyStock';// <<-- Rubah string ini untuk mapping end; function TSubGroup.GetFieldNameFor_SUBGRUP_MERCHANGRUP_UNT_ID: string; begin Result := 'SUBGRUP_MERCHANGRUP_UNT_ID'; end; function TSubGroup.GetFieldNameFor_UnitID: string; begin Result := 'SUBGRUP_UNT_ID'; end; function TSubGroup.GetHeaderFlag: Integer; begin result := 84; end; function TSubGroup.LoadByID(aID : Integer; aUnitID : Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID) + ' and ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID)); end; function TSubGroup.LoadByKode(aKode: string; aUnitID, aGrpId, aGrpUnitID: Integer): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode) + ' and ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID) + ' and ' + GetFieldNameFor_Group + ' = ' + IntToStr(aGrpId) + ' and ' + GetFieldNameFor_SUBGRUP_MERCHANGRUP_UNT_ID + ' = ' + IntToStr(aGrpUnitID) ); end; function TSubGroup.RemoveFromDB: Boolean; var sErr: string; sSQL: String; begin Result := False; sSQL := 'DELETE FROM REF$SUB_GRUP WHERE (SUBGRUP_ID = ' + IntToStr(FID) + ') AND SUBGRUP_UNT_ID = ' + IntToStr(FUnitID) + ';'; try if cExecSQL(sSQL, dbtPOS, False) then result := True;//SimpanBlob(sSQL, GetHeaderFlag); except on E: EFDDBEngineException do begin sErr := e.Message; if sErr <> '' then raise Exception.Create(sErr) else raise Exception.Create('Error Code: '+IntToStr(e.ErrorCode)+#13#10+e.SQL); end; end; end; procedure TSubGroup.SetUnitID(const Value: Integer); begin if (Value <> Group.UnitID) and (Value <> 0) then begin raise Exception.Create('Unit ID <> Group Unit ID'); end else FUnitID := Value; end; procedure TSubGroup.UpdateData(aGroup_ID : Integer; aID : Integer; aKode : string; aNama : string; aSafetyStock : Double; aUnitID : Integer); begin FGroup.LoadByID(aGroup_ID, aUnitID); FID := aID; FKode := trim(aKode); FNama := trim(aNama); FSafetyStock := aSafetyStock; FUnitID := aUnitID; State := csCreated; end; end.
unit Horse.Logger; interface uses System.SysUtils, System.SyncObjs, Horse, System.Classes, System.Generics.Collections; type THorseLoggerConfig = record LogDir: string; LogFormat: string; constructor Create(ALogFormat: string; ALogDir: string); overload; constructor Create(ALogFormat: string); overload; end; THorseLogger = class(TThread) private FCriticalSection: TCriticalSection; FEvent: TEvent; FLogDir: string; FLogCache: TList<string>; procedure SaveLogCache; procedure FreeInternalInstances; function ExtractLogCache: TArray<string>; class var FHorseLogger: THorseLogger; class function ValidateValue(AValue: Integer): string; overload; class function ValidateValue(AValue: string): string; overload; class function ValidateValue(AValue: TDateTime): string; overload; class function BuildLogger(AConfig: THorseLoggerConfig): THorseCallback; class function GetDefaultHorseLogger: THorseLogger; public procedure AfterConstruction; override; procedure BeforeDestruction; override; function SetLogDir(ALogDir: string): THorseLogger; function NewLog(ALog: string): THorseLogger; procedure Execute; override; class destructor UnInitialize; class function GetDefault: THorseLogger; class function New(AConfig: THorseLoggerConfig): THorseCallback; overload; class function New: THorseCallback; overload; end; const DEFAULT_HORSE_LOG_FORMAT = '${request_remote_addr} [${time}] ${request_user_agent}'+ ' "${request_method} ${request_path_info} ${request_version}"'+ ' ${response_status} ${response_content_length}'; implementation uses Web.HTTPApp, System.DateUtils; { THorseLoggerConfig } constructor THorseLoggerConfig.Create(ALogFormat: string; ALogDir: string); begin LogFormat := ALogFormat; LogDir := ALogDir; end; constructor THorseLoggerConfig.Create(ALogFormat: string); begin Create(ALogFormat, ExtractFileDir(ParamStr(0))); end; { THorseLogger } procedure THorseLogger.AfterConstruction; begin inherited; FLogCache := TList<string>.Create; FEvent := TEvent.Create; FCriticalSection := TCriticalSection.Create; end; procedure THorseLogger.BeforeDestruction; begin inherited; FreeInternalInstances; end; class function THorseLogger.BuildLogger(AConfig: THorseLoggerConfig): THorseCallback; begin Result := procedure(ARequest: THorseRequest; AResponse: THorseResponse; ANext: TProc) var LWebRequest: TWebRequest; LWebResponse: TWebResponse; LBeforeDateTime: TDateTime; LAfterDateTime: TDateTime; LMilliSecondsBetween: Integer; LLog: string; begin LBeforeDateTime := Now(); try ANext(); finally LAfterDateTime := Now(); LMilliSecondsBetween := MilliSecondsBetween(LAfterDateTime, LBeforeDateTime); LWebRequest := THorseHackRequest(ARequest).GetWebRequest; LWebResponse := THorseHackResponse(AResponse).GetWebResponse; LLog := AConfig.LogFormat; LLog := LLog.Replace('${time}', ValidateValue(LBeforeDateTime)); LLog := LLog.Replace('${execution_time}', ValidateValue(LMilliSecondsBetween)); LLog := LLog.Replace('${request_method}', ValidateValue(LWebRequest.Method)); LLog := LLog.Replace('${request_version}', ValidateValue(LWebRequest.ProtocolVersion)); LLog := LLog.Replace('${request_url}', ValidateValue(LWebRequest.URL)); LLog := LLog.Replace('${request_query}', ValidateValue(LWebRequest.Query)); LLog := LLog.Replace('${request_path_info}', ValidateValue(LWebRequest.PathInfo)); LLog := LLog.Replace('${request_path_translated}', ValidateValue(LWebRequest.PathTranslated)); LLog := LLog.Replace('${request_cookie}', ValidateValue(LWebRequest.Cookie)); LLog := LLog.Replace('${request_accept}', ValidateValue(LWebRequest.Accept)); LLog := LLog.Replace('${request_from}', ValidateValue(LWebRequest.From)); LLog := LLog.Replace('${request_host}', ValidateValue(LWebRequest.Host)); LLog := LLog.Replace('${request_referer}', ValidateValue(LWebRequest.Referer)); LLog := LLog.Replace('${request_user_agent}', ValidateValue(LWebRequest.UserAgent)); LLog := LLog.Replace('${request_connection}', ValidateValue(LWebRequest.Connection)); LLog := LLog.Replace('${request_derived_from}', ValidateValue(LWebRequest.DerivedFrom)); LLog := LLog.Replace('${request_remote_addr}', ValidateValue(LWebRequest.RemoteAddr)); LLog := LLog.Replace('${request_remote_host}', ValidateValue(LWebRequest.RemoteHost)); LLog := LLog.Replace('${request_script_name}', ValidateValue(LWebRequest.ScriptName)); LLog := LLog.Replace('${request_server_port}', ValidateValue(LWebRequest.ServerPort)); LLog := LLog.Replace('${request_remote_ip}', ValidateValue(LWebRequest.RemoteIP)); LLog := LLog.Replace('${request_internal_path_info}', ValidateValue(LWebRequest.InternalPathInfo)); LLog := LLog.Replace('${request_raw_path_info}', ValidateValue(LWebRequest.RawPathInfo)); LLog := LLog.Replace('${request_cache_control}', ValidateValue(LWebRequest.CacheControl)); LLog := LLog.Replace('${request_script_name}', ValidateValue(LWebRequest.ScriptName)); LLog := LLog.Replace('${request_authorization}', ValidateValue(LWebRequest.Authorization)); LLog := LLog.Replace('${request_content_encoding}', ValidateValue(LWebRequest.ContentEncoding)); LLog := LLog.Replace('${request_content_type}', ValidateValue(LWebRequest.ContentType)); LLog := LLog.Replace('${request_content_length}', ValidateValue(LWebRequest.ContentLength)); LLog := LLog.Replace('${request_content_version}', ValidateValue(LWebRequest.ContentVersion)); LLog := LLog.Replace('${response_version}', ValidateValue(LWebResponse.Version)); LLog := LLog.Replace('${response_reason}', ValidateValue(LWebResponse.ReasonString)); LLog := LLog.Replace('${response_server}', ValidateValue(LWebResponse.Server)); LLog := LLog.Replace('${response_realm}', ValidateValue(LWebResponse.Realm)); LLog := LLog.Replace('${response_allow}', ValidateValue(LWebResponse.Allow)); LLog := LLog.Replace('${response_location}', ValidateValue(LWebResponse.Location)); LLog := LLog.Replace('${response_log_message}', ValidateValue(LWebResponse.LogMessage)); LLog := LLog.Replace('${response_title}', ValidateValue(LWebResponse.Title)); LLog := LLog.Replace('${response_content_encoding}', ValidateValue(LWebResponse.ContentEncoding)); LLog := LLog.Replace('${response_content_type}', ValidateValue(LWebResponse.ContentType)); LLog := LLog.Replace('${response_content_length}', ValidateValue(LWebResponse.ContentLength)); LLog := LLog.Replace('${response_content_version}', ValidateValue(LWebResponse.ContentVersion)); LLog := LLog.Replace('${response_status}', ValidateValue(LWebResponse.StatusCode)); THorseLogger.GetDefault.NewLog(LLog); end; end; end; procedure THorseLogger.Execute; var LWait: TWaitResult; begin inherited; while not(Self.Terminated) do begin LWait := FEvent.WaitFor(INFINITE); FEvent.ResetEvent; case LWait of wrSignaled: begin SaveLogCache; end else Continue; end; end; end; class function THorseLogger.GetDefault: THorseLogger; begin Result := GetDefaultHorseLogger; end; class function THorseLogger.GetDefaultHorseLogger: THorseLogger; begin if not Assigned(FHorseLogger) then begin FHorseLogger := THorseLogger.Create(True); FHorseLogger.FreeOnTerminate := True; FHorseLogger.Start; end; Result := FHorseLogger; end; function THorseLogger.ExtractLogCache: TArray<string>; var LLogCacheArray: TArray<string>; begin FCriticalSection.Enter; try LLogCacheArray := FLogCache.ToArray; FLogCache.Clear; FLogCache.TrimExcess; finally FCriticalSection.Leave; end; Result := LLogCacheArray; end; procedure THorseLogger.FreeInternalInstances; begin FLogCache.Free; FEvent.Free; FCriticalSection.Free; end; class function THorseLogger.New(AConfig: THorseLoggerConfig): THorseCallback; begin THorseLogger.GetDefault.SetLogDir(AConfig.LogDir); Result := BuildLogger(AConfig); end; class function THorseLogger.New: THorseCallback; var LLogFormat: string; begin LLogFormat := DEFAULT_HORSE_LOG_FORMAT; Result := THorseLogger.New(THorseLoggerConfig.Create(LLogFormat)); end; function THorseLogger.NewLog(ALog: string): THorseLogger; begin Result := Self; FCriticalSection.Enter; try FLogCache.Add(ALog); finally FCriticalSection.Leave; FEvent.SetEvent; end; end; procedure THorseLogger.SaveLogCache; var LFilename: string; LLogCacheArray: TArray<string>; LTextFile: TextFile; I: Integer; begin FCriticalSection.Enter; try if not DirectoryExists(FLogDir) then ForceDirectories(FLogDir); LFilename := FLogDir + PathDelim + 'access_' + FormatDateTime('yyyy-mm-dd', Now()) + '.log'; AssignFile(LTextFile, LFilename); if (FileExists(LFilename)) then Append(LTextFile) else Rewrite(LTextFile); try LLogCacheArray := ExtractLogCache; for I := Low(LLogCacheArray) to High(LLogCacheArray) do begin writeln(LTextFile, LLogCacheArray[I]); end; finally CloseFile(LTextFile); end; finally FCriticalSection.Leave; end; end; function THorseLogger.SetLogDir(ALogDir: string): THorseLogger; begin Result := Self; FLogDir := ALogDir.TrimRight([PathDelim]); end; class destructor THorseLogger.UnInitialize; begin if Assigned(FHorseLogger) then begin FHorseLogger.Terminate; FHorseLogger.FEvent.SetEvent; end; end; class function THorseLogger.ValidateValue(AValue: TDateTime): string; begin Result := FormatDateTime('dd/MMMM/yyyy hh:mm:ss:zzz', AValue); end; class function THorseLogger.ValidateValue(AValue: string): string; begin if AValue.IsEmpty then Result := '-' else Result := AValue; end; class function THorseLogger.ValidateValue(AValue: Integer): string; begin Result := AValue.ToString; end; end.
unit Dialog_EditLevl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, RzEdit,Class_Levl,Class_DBPool,ADODB; type TDialogEditLevl = class(TForm) Button1: TButton; Button2: TButton; Edit_Name: TRzEdit; Edit_Prev: TRzEdit; Edit_Next: TRzEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FEditCode:Integer; FLevl :TLevl; protected procedure SetInitialize; procedure SetCommonParams; public function CheckLicit:Boolean; procedure DoSaveDB; procedure InsertDB; procedure UpdateDB; procedure RendLevl; end; var DialogEditLevl: TDialogEditLevl; function FuncEditLevl(AEditCode:Integer;ALevl:TLevl):Integer; implementation uses UtilLib,UtilLib_UiLib,Dialog_ListLevl; {$R *.dfm} function FuncEditLevl(AEditCode:Integer;ALevl:TLevl):Integer; begin try DialogEditLevl:=TDialogEditLevl.Create(nil); DialogEditLevl.FLevl:=ALevl; DialogEditLevl.FEditCode:=AEditCode; Result:=DialogEditLevl.ShowModal; finally FreeAndNil(DialogEditLevl); end; end; { TDialogEditLevl } procedure TDialogEditLevl.SetCommonParams; const ArrCaption:array[0..1] of string =('新增会员等级','编辑会员等级'); begin Caption:=ArrCaption[FEditCode]; end; procedure TDialogEditLevl.SetInitialize; begin SetCommonParams; if FEditCode=1 then begin RendLevl; end; end; procedure TDialogEditLevl.FormCreate(Sender: TObject); begin UtilLib_UiLib.SetCommonDialogParams(Self); end; procedure TDialogEditLevl.FormShow(Sender: TObject); begin SetInitialize; end; function TDialogEditLevl.CheckLicit: Boolean; begin Result:=False; if Trim(Edit_Name.Text)='' then begin ShowMessage('请填写会员等级名称'); Exit; end; if Trim(Edit_Prev.Text)='' then begin ShowMessage('请填写会员消费上限'); Exit; end; if Trim(Edit_Next.Text)='' then begin ShowMessage('请填写会员消费下限'); Exit; end; Result:=True; end; procedure TDialogEditLevl.DoSaveDB; begin if not CheckLicit then Exit; case FEditCode of 0:InsertDB; 1:UpdateDB; end; end; procedure TDialogEditLevl.InsertDB; var ADOCon:TADOConnection; begin if ShowBox('是否保存会员等级')<>Mrok then Exit; try ADOCon:=TDBPool.GetConnect(); FLevl:=TLevl.Create; FLevl.LevlIdex:=FLevl.GetNextCode(ADOCon); FLevl.LevlName:=Trim(Edit_Name.Text); FLevl.LevlPrev:=StrToFloat(Edit_Prev.Text); FLevl.LevlNext:=StrToFloat(Edit_Next.Text); FLevl.InsertDB(ADOCon); ShowMessage('保存成功'); DialogListLevl.DoListRef; Edit_Name.Clear; Edit_Prev.Clear; Edit_Next.Clear; finally FreeAndNil(ADOCon); end; end; procedure TDialogEditLevl.UpdateDB; var ADOCon:TADOConnection; begin if ShowBox('是否更改会员等级')<>Mrok then Exit; try ADOCon:=TDBPool.GetConnect(); FLevl.LevlName:=Trim(Edit_Name.Text); FLevl.LevlPrev:=StrToFloat(Edit_Prev.Text); FLevl.LevlNext:=StrToFloat(Edit_Next.Text); FLevl.UpdateDB(ADOCon); ShowMessage('保存成功'); ModalResult:=mrOk; finally FreeAndNil(ADOCon); end; end; procedure TDialogEditLevl.Button1Click(Sender: TObject); begin DoSaveDB; end; procedure TDialogEditLevl.Button2Click(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TDialogEditLevl.RendLevl; begin if FLevl=nil then Exit; Edit_Name.Text:=FLevl.LevlName; Edit_Prev.Text:=FloatToStr(FLevl.LevlPrev); Edit_Next.Text:=FloatToStr(FLevl.LevlNext); end; end.
{* * olol2tab - utility that converts olol files to tab-indented text files * Copyright (C) 2011 Kostas Michalopoulos * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * Kostas Michalopoulos <badsector@runtimelegend.com> *} program olol2tab; {$MODE OBJFPC}{$H+} var f: Text; Cmd, Arg, s: string; Tabs: Integer; procedure LoadNode; var Cmd, Arg, s: string; i: Integer; begin while not Eof(f) do begin Readln(f, s); if Length(s) < 4 then continue; Cmd:=Copy(s, 1, 4); Arg:=Copy(s, 6, Length(s)); if Cmd='DONE' then break else if Cmd='NODE' then begin for i:=1 to Tabs do Write(#9); WriteLn(Arg); Inc(Tabs); LoadNode; Dec(Tabs); end; end; end; begin if ParamCount=0 then begin Writeln('Usage: olol2tab <olol file>'); exit; end; Assign(f, ParamStr(1)); {$I-} Reset(f); {$I+} if IOResult <> 0 then begin Writeln('Failed to open ', ParamStr(1), ' for input'); exit; end; while not Eof(f) do begin Readln(f, s); if Length(s) < 4 then continue; Cmd:=Copy(s, 1, 4); Arg:=Copy(s, 6, Length(s)); if Cmd='STOP' then break; if Cmd='NODE' then LoadNode; end; Close(f); end.
unit FMX.Helpers; interface uses System.Types, FMX.Ani, System.JSON,FMX.Layouts, FMX.Types, System.SysUtils,FMX.ImgList, FMX.TabControl,System.UITypes, System.Generics.Collections, FMX.Dialogs, FMX.Objects,FMX.Graphics,System.Classes, FMX.MultiResBitmap, System.Net.URLClient,System.Net.HttpClient, System.Net.HttpClientComponent; type TTabControlelper = class helper for TTabControl procedure BotaoClick(Sender :TObject); procedure BarButtons(Align :TAlignLayout = TAlignLayout.Top); end; type TGridPanelLayoutHelper = class helper for TGridPanelLayout constructor Create(AOwner :TComponent;const Row, Col :Integer); overload; procedure CreateGrid(const Row,Col:Integer); end; type TRectangleHelper = class helper for TRectangle procedure LoadFromFile(const aFileName :string); procedure LoadFromURL(const aFileName :string); end; type TBitmapHelper = class helper for TBitmap procedure LoadFromURL(const aFileName :string); end; type TImageHelper = class helper for TImage procedure ImageByName(Name :String); function Size(const ASize :Single) :TImage; function AddText(aText:String): TImage; procedure LoadFromURL(const aFileName :string); procedure GeraQrCode; end; type TJSONArrayHelper = class helper for TJSONArray function LoadFromURL(const aFileName :string):TJSONArray; end; type TlayoutHelper = class helper for TLayout procedure Finish(Sender :TObject); procedure AnimaCard(Card :TRectangle); Overload; procedure AnimaCard(Card :TRectangle; aProperty :String); Overload; end; var ImageList :TImageList; implementation uses System.IOUtils; var ListFoco :TObjectList<TRectangle>; ListIcone :TObjectList<TImage>; ListText : TObjectList<TText>; { TRectangleHelper } procedure TRectangleHelper.LoadFromFile(const aFileName: string); begin Self.Fill.Bitmap.WrapMode := TWrapMode.TileStretch; Self.Fill.Kind := TBrushKind.Bitmap; Self.Fill.Bitmap.Bitmap.LoadFromFile(aFileName); end; procedure TRectangleHelper.LoadFromURL(const aFileName: string); var MyFile :TFileStream; NetHTTPClient : TNetHTTPClient; begin Self.Fill.Bitmap.WrapMode := TWrapMode.TileStretch; Self.Fill.Kind := TBrushKind.Bitmap; TThread.CreateAnonymousThread( procedure() begin MyFile := TFileStream.Create( TPath.Combine( TPath.GetDocumentsPath, TPath.GetFileName(aFileName)) ,fmCreate); try NetHTTPClient := TNetHTTPClient.Create(nil); NetHTTPClient.Get(aFileName,MyFile); finally NetHTTPClient.DisposeOf; end; TThread.Synchronize(TThread.CurrentThread, procedure () begin try Self.Fill.Bitmap.Bitmap.LoadFromStream(MyFile); except Self.Fill.Bitmap.Bitmap := nil; end; MyFile.DisposeOf; end); end).Start; end; { TJSONArrayHelper } function TJSONArrayHelper.LoadFromURL(const aFileName: string): TJSONArray; var JsonStream :TStringStream; NetHTTPClient : TNetHTTPClient; begin try JsonStream := TStringStream.Create; NetHTTPClient := TNetHTTPClient.Create(nil); NetHTTPClient.Get(aFileName,JsonStream); if TJSONObject.ParseJSONValue(JsonStream.DataString) is TJSONArray then Result := TJSONObject.ParseJSONValue(JsonStream.DataString) as TJSONArray else if TJSONObject.ParseJSONValue(JsonStream.DataString) is TJSONObject then Result := TJSONObject.ParseJSONValue('['+JsonStream.DataString+']') as TJSONArray; finally JsonStream.Free; NetHTTPClient.Free; end; end; { TBitmapHelper } procedure TBitmapHelper.LoadFromURL(const aFileName: string); var MyFile :TFileStream; NetHTTPClient : TNetHTTPClient; begin TThread.CreateAnonymousThread( procedure() begin MyFile := TFileStream.Create( TPath.Combine( TPath.GetDocumentsPath, //TPath.GetFileNameWithoutExtension(aFileName)+ 'qrcode.png' ) ,fmCreate); try NetHTTPClient := TNetHTTPClient.Create(nil); NetHTTPClient.Get(aFileName,MyFile); finally NetHTTPClient.DisposeOf; end; TThread.Synchronize(TThread.CurrentThread, procedure () begin try Self.LoadFromStream(MyFile); except Self := nil; end; MyFile.DisposeOf; end); end).Start; end; { TGridPanelLayoutHelper } constructor TGridPanelLayoutHelper.Create(AOwner :TComponent;const Row, Col :Integer); begin inherited Create(AOwner); Self.Align := TAlignLayout.Client; CreateGrid(Row, Col ); end; procedure TGridPanelLayoutHelper.CreateGrid(const Row, Col: Integer); var I :Integer; begin Self.RowCollection.BeginUpdate; Self.ColumnCollection.BeginUpdate; for I := 0 to Self.ControlsCount -1 do Self.Controls[0].Free; Self.RowCollection.Clear; Self.ColumnCollection.Clear; for I := 0 to Row -1 do begin Self.RowCollection.Add; Self.RowCollection.Items[i]; Self.RowCollection.Items[I].Value := 100; Self.RowCollection.Items[I].SizeStyle := TGridPanelLayout.TSizeStyle.Percent; end; for I := 0 to Col -1 do begin Self.ColumnCollection.Add; Self.ColumnCollection.Items[i]; Self.ColumnCollection.Items[I].Value := 100; Self.ColumnCollection.Items[I].SizeStyle := TGridPanelLayout.TSizeStyle.Percent; end; Self.ColumnCollection.EndUpdate; Self.RowCollection.EndUpdate; end; { TImageHelper } function TImageHelper.AddText(aText: String): TImage ; begin Hint := Hint + atext; Result := Self; end; procedure TImageHelper.GeraQrCode; begin Bitmap.LoadFromURL(Hint); end; procedure TImageHelper.ImageByName(Name: String); var Item : TCustomBitmapItem; Size :TSize; begin if ImageList.BitmapItemByName(Name,Item,Size) then Self.Bitmap := Item.MultiResBitmap.Bitmaps[1.0] end; procedure TImageHelper.LoadFromURL(const aFileName: string); begin Bitmap.LoadFromURL(aFileName); end; function TImageHelper.Size(const ASize: Single) :TImage ; begin Hint := 'https://chart.apis.google.com/chart?cht=qr&chs='+ InttoStr(Trunc(aSize))+'x'+InttoStr(Trunc(aSize))+'&'; Result := Self; end; { TTabControlelper } procedure TTabControlelper.BarButtons(Align: TAlignLayout); var I :Integer; Bar,BotaoFundo,Foco :TRectangle; Icone :TImage; Fundo :TLayout; Grid :TGridPanelLayout; Text :TText; begin Bar := TRectangle.Create(TFmxObject(Self.Parent)); Bar.Align := Align; BAr.Height := 60; Bar.Fill.Color := TAlphaColorRec.Black; Bar.Stroke.Color := Bar.Fill.Color; TFmxObject(Self.Parent).AddObject(Bar); Self.TabPosition := TTabPosition.None; Self.GotoVisibleTab(0); Grid := TGridPanelLayout.Create(Bar,1,Self.TabCount); Bar.AddObject(Grid); for I := 0 to Pred(Self.TabCount) do begin BotaoFundo := TRectangle.Create(Grid); BotaoFundo.Align := TAlignLayout.Client; BotaoFundo.Fill.Color := TAlphaColorRec.Null; BotaoFundo.Stroke.Color := BotaoFundo.Fill.Color; BotaoFundo.OnClick := BotaoClick; BotaoFundo.Tag := I; Fundo := TLayout.Create(BotaoFundo); Fundo.Align := TAlignLayout.Client; BotaoFundo.AddObject(Fundo); Icone := TImage.Create(Fundo); Icone.ImageByName(IntToStr(I)); Icone.Height := 20; Icone.Tag := I; Icone.HitTest := False; Icone.Width := Icone.Height; Icone.Align := TAlignLayout.Center; Fundo.AddObject(Icone); ListIcone.Add(Icone); Text := TText.Create(BotaoFundo); Text.Text := Self.Tabs[I].Text; Text.Tag := I; Text.HitTest := False; Text.Width := 200; Text.TextSettings.HorzAlign := TTextAlign.Center; Text.Height := 20; Text.Align := Align; ListText.Add(Text); Text.TextSettings.Font.Size := 10; BotaoFundo.AddObject(Text); Foco := TRectangle.Create(BotaoFundo); if Align = TAlignLayout.Bottom then Foco.Align := TAlignLayout.Top else Foco.Align := TAlignLayout.Bottom; Foco.Stroke.Thickness := 0; Foco.Height := 4; Foco.Tag := I; ListFoco.Add(Foco); if I = 0 then begin Foco.Fill.Color := TAlphaColorRec.Cornflowerblue; Text.TextSettings.FontColor := Foco.Fill.Color; end else begin Foco.Fill.Color := TAlphaColorRec.Black; Text.TextSettings.FontColor :=TAlphaColorRec.Darkgray; end; Icone.Bitmap.ReplaceOpaqueColor(Text.TextSettings.FontColor); Foco.Stroke.Color := BotaoFundo.Fill.Color; BotaoFundo.AddObject(Foco); Grid.AddObject(BotaoFundo); end; end; procedure TTabControlelper.BotaoClick(Sender: TObject); var I :Integer; begin ListFoco[Self.Tag].Fill.Color := TAlphaColorRec.Black; ListText[Self.Tag].TextSettings.FontColor := TAlphaColorRec.Darkgray; ListIcone[Self.Tag].Bitmap.ReplaceOpaqueColor(TAlphaColorRec.Darkgray); // Self.BeginUpdate; for I := 0 to ListFoco.Count -1 do begin if ListFoco[I].Tag = TRectangle(Sender).Tag then begin ListFoco[I].Fill.Color := TAlphaColorRec.Cornflowerblue; ListText[I].TextSettings.FontColor :=ListFoco[I].Fill.Color; ListIcone[I].Bitmap.ReplaceOpaqueColor(ListFoco[I].Fill.Color); Self.GotoVisibleTab(ListFoco[I].Tag,TTabTransition.Slide); Self.Tag := TRectangle(Sender).Tag ; end else begin ListFoco[I].Fill.Color := TAlphaColorRec.Black; ListText[I].TextSettings.FontColor := TAlphaColorRec.Darkgray; ListIcone[I].Bitmap.ReplaceOpaqueColor(TAlphaColorRec.Darkgray); end; end; // Self.EndUpdate; end; { TlayoutHelper } procedure TlayoutHelper.AnimaCard(Card: TRectangle); var FloatHeight, FloatWidth, FloatOpacity, FloatPositionX : TFloatAnimation; begin Card.Align := TAlignLayout.Center; Card.Stroke.Thickness := 0; Card.Height := 10; Card.Width := 10; if Self.ControlsCount = 1 then begin FloatPositionX := TFloatAnimation.Create(Self.Controls[0]); Self.Controls[0].AddObject(FloatPositionX); FloatPositionX.Duration := 0.3; FloatPositionX.PropertyName := 'Position.X'; FloatPositionX.StartValue := 0; if Tag = 0 then begin FloatPositionX.StopValue := Self.Width * -1; Tag := 1; end else begin FloatPositionX.StopValue := Self.Width * 2; Tag := 0; end; FloatPositionX.OnFinish := Finish; FloatOpacity := TFloatAnimation.Create(Self.Controls[0]); Self.Controls[0].AddObject(FloatOpacity); FloatOpacity.Duration := 0.3; FloatOpacity.PropertyName := 'Opacity'; FloatOpacity.StartValue := 1; FloatOpacity.StopValue := 0; FloatOpacity.Start; FloatPositionX.Start; end; Self.AddObject(Card); FloatHeight := TFloatAnimation.Create(Card); Card.AddObject(FloatHeight); FloatHeight.Duration := 0.3; FloatHeight.PropertyName := 'Size.Height'; FloatHeight.StartValue := 0; FloatHeight.StopValue := Self.Height - 10; FloatWidth := TFloatAnimation.Create(Card); Card.AddObject(FloatWidth); FloatWidth.Duration := 0.3; FloatWidth.PropertyName := 'Size.Width'; FloatWidth.StartValue := 0; FloatWidth.StopValue := Self.Width - 10; FloatOpacity := TFloatAnimation.Create(Card); Card.AddObject(FloatOpacity); FloatOpacity.Duration := 0.3; FloatOpacity.PropertyName := 'Opacity'; FloatOpacity.StartValue := 0; FloatOpacity.StopValue := 1; FloatOpacity.Start; FloatWidth.Start; FloatHeight.Start; end; procedure TlayoutHelper.AnimaCard(Card: TRectangle; aProperty: String); var FloatPositionX, FloatOpacity :TFloatAnimation; begin Card.Height := Self.Height; Card.Width := Self.Width - 10; Card.Align := TAlignLayout.None; Card.Stroke.Thickness := 0; Card.Opacity := 0; if aProperty = 'left' then Card.Position.X := Self.Width else Card.Position.X := Self.Width * -1; if Self.ControlsCount = 1 then begin FloatPositionX := TFloatAnimation.Create(Self.Controls[0]); Self.Controls[0].AddObject(FloatPositionX); FloatPositionX.Duration := 0.3; FloatPositionX.PropertyName := 'Position.X'; FloatPositionX.StartValue := 0; if aProperty = 'left' then begin FloatPositionX.StopValue := Self.Width * -1; end else begin FloatPositionX.StopValue := Self.Width * 2; end; FloatPositionX.OnFinish := Finish; FloatOpacity := TFloatAnimation.Create(Self.Controls[0]); Self.Controls[0].AddObject(FloatOpacity); FloatOpacity.Duration := 0.3; FloatOpacity.PropertyName := 'Opacity'; FloatOpacity.StartValue := 1; FloatOpacity.StopValue := 0; FloatOpacity.Start; FloatPositionX.Start; end; Self.AddObject(Card); FloatPositionX := TFloatAnimation.Create(Card); Card.AddObject(FloatPositionX); FloatPositionX.Duration := 0.3; FloatPositionX.PropertyName := 'Position.X'; FloatPositionX.StartFromCurrent := True; FloatPositionX.StopValue := 10; FloatOpacity := TFloatAnimation.Create(Card); Card.AddObject(FloatOpacity); FloatOpacity.Duration := 0.3; FloatOpacity.PropertyName := 'Opacity'; FloatOpacity.StartValue := 0; FloatOpacity.StopValue := 1; FloatOpacity.Start; FloatPositionX.Start; end; procedure TlayoutHelper.Finish(Sender: TObject); begin Self.Controls[0].free; end; initialization ListFoco := TObjectList<TRectangle>.Create; ListIcone := TObjectList<TImage>.Create; ListText := TObjectList<TText>.Create; ImageList := TImageList.Create(nil); end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFDomDocument; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefDomDocumentRef = class(TCefBaseRefCountedRef, ICefDomDocument) protected function GetType: TCefDomDocumentType; function GetDocument: ICefDomNode; function GetBody: ICefDomNode; function GetHead: ICefDomNode; function GetTitle: ustring; function GetElementById(const id: ustring): ICefDomNode; function GetFocusedNode: ICefDomNode; function HasSelection: Boolean; function GetSelectionStartOffset: Integer; function GetSelectionEndOffset: Integer; function GetSelectionAsMarkup: ustring; function GetSelectionAsText: ustring; function GetBaseUrl: ustring; function GetCompleteUrl(const partialURL: ustring): ustring; public class function UnWrap(data: Pointer): ICefDomDocument; end; implementation uses uCEFMiscFunctions, uCEFDomNode; function TCefDomDocumentRef.GetBaseUrl: ustring; begin Result := CefStringFreeAndGet(PCefDomDocument(FData)^.get_base_url(PCefDomDocument(FData))) end; function TCefDomDocumentRef.GetBody: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomDocument(FData)^.get_body(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetCompleteUrl(const partialURL: ustring): ustring; var p: TCefString; begin p := CefString(partialURL); Result := CefStringFreeAndGet(PCefDomDocument(FData)^.get_complete_url(PCefDomDocument(FData), @p)); end; function TCefDomDocumentRef.GetDocument: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomDocument(FData)^.get_document(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetElementById(const id: ustring): ICefDomNode; var i: TCefString; begin i := CefString(id); Result := TCefDomNodeRef.UnWrap(PCefDomDocument(FData)^.get_element_by_id(PCefDomDocument(FData), @i)); end; function TCefDomDocumentRef.GetFocusedNode: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomDocument(FData)^.get_focused_node(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetHead: ICefDomNode; begin Result := TCefDomNodeRef.UnWrap(PCefDomDocument(FData)^.get_head(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetSelectionAsMarkup: ustring; begin Result := CefStringFreeAndGet(PCefDomDocument(FData)^.get_selection_as_markup(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetSelectionAsText: ustring; begin Result := CefStringFreeAndGet(PCefDomDocument(FData)^.get_selection_as_text(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetSelectionEndOffset: Integer; begin Result := PCefDomDocument(FData)^.get_selection_end_offset(PCefDomDocument(FData)); end; function TCefDomDocumentRef.GetSelectionStartOffset: Integer; begin Result := PCefDomDocument(FData)^.get_selection_start_offset(PCefDomDocument(FData)); end; function TCefDomDocumentRef.GetTitle: ustring; begin Result := CefStringFreeAndGet(PCefDomDocument(FData)^.get_title(PCefDomDocument(FData))); end; function TCefDomDocumentRef.GetType: TCefDomDocumentType; begin Result := PCefDomDocument(FData)^.get_type(PCefDomDocument(FData)); end; function TCefDomDocumentRef.HasSelection: Boolean; begin Result := PCefDomDocument(FData)^.has_selection(PCefDomDocument(FData)) <> 0; end; class function TCefDomDocumentRef.UnWrap(data: Pointer): ICefDomDocument; begin if data <> nil then Result := Create(data) as ICefDomDocument else Result := nil; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit ExLibMd0; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Menus, AdLibMdm, OOMisc; type TForm1 = class(TForm) popModemList: TPopupMenu; Deletemodem1: TMenuItem; popDetailFiles: TPopupMenu; Deletefile1: TMenuItem; Newfile1: TMenuItem; lbxModemList: TListBox; lbxDetailFiles: TListBox; lblModemListCount: TLabel; lblDetailLoadTime: TLabel; lblDetailFileCount: TLabel; Label4: TLabel; Label3: TLabel; Label2: TLabel; Label1: TLabel; edtModemCapFolder: TEdit; tvDetails: TTreeView; procedure FormCreate(Sender: TObject); procedure lbxDetailFilesClick(Sender: TObject); procedure lbxModemListDblClick(Sender: TObject); procedure Deletemodem1Click(Sender: TObject); procedure Deletefile1Click(Sender: TObject); procedure Newfile1Click(Sender: TObject); procedure lbxDetailFilesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure lbxDetailFilesDragDrop(Sender, Source: TObject; X, Y: Integer); procedure lbxModemListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } StartTime : DWORD; procedure RefreshDetailList; end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin // edtModemCapFolder.Text := GetEnvironmentVariable('MODEMCAP'); if edtModemCapFolder.Text = '' then edtModemCapFolder.Text := 'e:\modemcap'; RefreshDetailList; end; procedure TForm1.RefreshDetailList; var sr: TSearchRec; begin lbxDetailFiles.Items.Clear; if FindFirst(edtModemCapFolder.Text + '/*.xml', faAnyFile, sr) = 0 then begin lbxDetailFiles.Items.Add(sr.Name); while FindNext(sr) = 0 do lbxDetailFiles.Items.Add(sr.Name); end else ShowMessage('Modemcap detail files not found'); FindClose(sr); lblDetailFileCount.Caption := IntToStr(lbxDetailFiles.Items.Count) + ' files'; end; procedure TForm1.lbxDetailFilesClick(Sender: TObject); var LibModem : TApdLibModem; ModemList : TStringList; I : Integer; begin if lbxDetailFiles.ItemIndex > -1 then begin LibModem := nil; ModemList := TStringList.Create; Screen.Cursor := crHourglass; try lbxModemList.Clear; LibModem := TApdLibModem.Create(Self); LibModem.LibModemPath := edtModemCapFolder.Text; StartTime := AdTimeGetTime; ModemList.Assign(LibModem.GetModems(lbxDetailFiles.Items[lbxDetailFiles.ItemIndex])); for I := 0 to pred(ModemList.Count) do lbxModemList.Items.Add(ModemList[I]); lblModemListCount.Caption := IntToStr(lbxModemList.Items.Count) + ' modems' + #13#10 + Format('%f3 seconds', [(AdTimeGetTime - StartTime) / 1000]); tvDetails.Items.Clear; finally LibModem.Free; ModemList.Free; Screen.Cursor := crDefault; end; end; end; procedure TForm1.lbxModemListDblClick(Sender: TObject); var LibModem : TApdLibModem; LmModem : TLmModem; i : Integer; j : Integer; CurModem : TTreeNode; TempNode1 : TTreeNode; TempNode2 : TTreeNode; TempNode3 : TTreeNode; begin if lbxModemList.ItemIndex = -1 then exit; LibModem := nil; Screen.Cursor := crHourglass; try LibModem := TApdLibModem.Create(self); LibModem.LibModemPath := edtModemCapFolder.Text; StartTime := AdTimeGetTime; i :=Libmodem.GetModem(lbxDetailFiles.Items[lbxDetailFiles.ItemIndex], lbxModemList.Items[lbxModemList.ItemIndex], LmModem); lblDetailLoadTime.Caption := Format('%f3 seconds', [(AdTimeGetTime - StartTime) / 1000]); tvDetails.Items.Clear; if i <> ecOK then begin ShowMessage('Modem not found, i = ' + IntToStr(i)); Exit; end; with LmModem do begin CurModem := tvDetails.Items.Add (nil, FriendlyName); tvDetails.Items.AddChild (CurModem, 'Manufacturer = ' + Manufacturer); tvDetails.Items.AddChild (CurModem, 'Model = ' + Model); tvDetails.Items.AddChild (CurModem, 'Modem ID = ' + ModemID); tvDetails.Items.AddChild (CurModem, 'Provider Name = ' + ProviderName); tvDetails.Items.AddChild (CurModem, 'Inheritance = ' + Inheritance); tvDetails.Items.AddChild (CurModem, 'Attached To = ' + AttachedTo); tvDetails.Items.AddChild (CurModem, 'Inactivity Format = ' + InactivityFormat); tvDetails.Items.AddChild (CurModem, 'Reset = ' + Reset); tvDetails.Items.AddChild (CurModem, 'DCB = ' + DCB); tvDetails.Items.AddChild (CurModem, 'Properties = ' + Properties); tvDetails.Items.AddChild (CurModem, 'Forwared Delay = ' + IntToStr (ForwardDelay)); tvDetails.Items.AddChild (CurModem, 'Variable Terminator = ' + VariableTerminator); tvDetails.Items.AddChild (CurModem, 'Inf Path = ' + InfPath); tvDetails.Items.AddChild (CurModem, 'Inf Section = ' + InfSection); tvDetails.Items.AddChild (CurModem, 'Driver Description = ' + DriverDesc); tvDetails.Items.AddChild (CurModem, 'Responses Key Name = ' + ResponsesKeyName); tvDetails.Items.AddChild (CurModem, 'Default = ' + Default); tvDetails.Items.AddChild (CurModem, 'Call Setup Fail Timeout = ' + IntToStr (CallSetupFailTimeout)); tvDetails.Items.AddChild (CurModem, 'Inactivity Timeout = ' + IntToStr (InactivityTimeout)); if SupportsWaitForBongTone then tvDetails.Items.AddChild (CurModem, 'Supports Bong Tone = True') else tvDetails.Items.AddChild (CurModem, 'Supports Bong Tone = False'); if SupportsWaitForQuiet then tvDetails.Items.AddChild (CurModem, 'Supports Wait forQuiet = True') else tvDetails.Items.AddChild (CurModem, 'Supports Wait for Quiet = False'); if SupportsWaitForDialTone then tvDetails.Items.AddChild (CurModem, 'Supports Wait for Dial Tone = True') else tvDetails.Items.AddChild (CurModem, 'Supports Wait for Dial Tone = False'); if SupportsSpeakerVolumeLow then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume Low = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume Low = False'); if SupportsSpeakerVolumeMed then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume Med = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume Med = False'); if SupportsSpeakerVolumeHigh then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume High = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Volume High = False'); if SupportsSpeakerModeOff then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode Off = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode Off = False'); if SupportsSpeakerModeOn then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode On = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode On = False'); if SupportsSpeakerModeSetup then tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode Setup = True') else tvDetails.Items.AddChild (CurModem, 'Supports Speaker Mode Setup = False'); if SupportsSetDataCompressionNegot then tvDetails.Items.AddChild (CurModem, 'Supports Set Data Compression Negotiation = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Data Compresssion Negotiation = False'); if SupportsSetErrorControlProtNegot then tvDetails.Items.AddChild (CurModem, 'Supports Set Error Control Protocol Negotiation = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Error Control Protocol Negotiation = False'); if SupportsSetForcedErrorControl then tvDetails.Items.AddChild (CurModem, 'Supports Set Forced Error Control = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Forced Error Control = False'); if SupportsSetCellular then tvDetails.Items.AddChild (CurModem, 'Supports Set Cellular = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Cellular = False'); if SupportsSetHardwareFlowControl then tvDetails.Items.AddChild (CurModem, 'Supports Set Hardware Flow Control = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Hardware Flow Control = False'); if SupportsSetSoftwareFlowControl then tvDetails.Items.AddChild (CurModem, 'Supports Set Software Flow Control = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Software Flow Control = False'); if SupportsCCITTBellToggle then tvDetails.Items.AddChild (CurModem, 'Supports Set CCITT Bell Toggle = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set CCITT Bell Toggle = False'); if SupportsSetSpeedNegotiation then tvDetails.Items.AddChild (CurModem, 'Supports Set Speed Negotiation = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Speed Negotiation = False'); if SupportsSetTonePulse then tvDetails.Items.AddChild (CurModem, 'Supports Set Tone Pulse = True') else tvDetails.Items.AddChild (CurModem, 'Supports Set Tone Pulse = False'); if SupportsBlindDial then tvDetails.Items.AddChild (CurModem, 'Supports Blind Dial = True') else tvDetails.Items.AddChild (CurModem, 'Supports Blind Dial = False'); if SupportsSetV21V23 then tvDetails.Items.AddChild (CurModem, 'Supports V21 V23 = True') else tvDetails.Items.AddChild (CurModem, 'Supports V21 V23 = False'); if SupportsModemDiagnostics then tvDetails.Items.AddChild (CurModem, 'Supports Modem Diagnostics = True') else tvDetails.Items.AddChild (CurModem, 'Supports Modem Diagnostics = False'); tvDetails.Items.AddChild (CurModem, 'Max DTE Rate = ' + IntToStr (MaxDTERate)); tvDetails.Items.AddChild (CurModem, 'Max DCE Rate = ' + IntToStr (MaxDCERate)); tvDetails.Items.AddChild (CurModem, 'Current Country = ' + CurrentCountry); tvDetails.Items.AddChild (CurModem, 'Maximum Port Speed = ' + IntToStr (MaximumPortSpeed)); tvDetails.Items.AddChild (CurModem, 'Power Delay = ' + IntToStr (PowerDelay)); tvDetails.Items.AddChild (CurModem, 'Config Delay = ' + IntToStr (ConfigDelay)); tvDetails.Items.AddChild (CurModem, 'Baud Rate = ' + IntToStr (BaudRate)); // Get Responses TempNode1 := tvDetails.Items.AddChild (CurModem, 'Responses'); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'OK'); for j := 0 to Responses.OK.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.OK[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'NegotiationProgress'); for j := 0 to Responses.NegotiationProgress.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.NegotiationProgress[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Connect'); for j := 0 to Responses.Connect.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Connect[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Error'); for j := 0 to Responses.Error.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Error[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'No Carrier'); for j := 0 to Responses.NoCarrier.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.NoCarrier[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'No Dial Tone'); for j := 0 to Responses.NoDialTone.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.NoDialTone[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Busy'); for j := 0 to Responses.Busy.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Busy[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'No Answer'); for j := 0 to Responses.NoAnswer.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.NoAnswer[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Ring'); for j := 0 to Responses.Ring.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Ring[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 1'); for j := 0 to Responses.VoiceView1.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView1[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 2'); for j := 0 to Responses.VoiceView2.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView2[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 3'); for j := 0 to Responses.VoiceView3.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView3[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 4'); for j := 0 to Responses.VoiceView4.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView4[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 5'); for j := 0 to Responses.VoiceView5.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView5[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 6'); for j := 0 to Responses.VoiceView6.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView6[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 7'); for j := 0 to Responses.VoiceView7.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView7[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice View 8'); for j := 0 to Responses.VoiceView8.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.VoiceView8[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Ring Duration'); for j := 0 to Responses.RingDuration.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.RingDuration[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Ring Break'); for j := 0 to Responses.RingBreak.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.RingBreak[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Date'); for j := 0 to Responses.Date.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Date[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Time'); for j := 0 to Responses.Time.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Time[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Number'); for j := 0 to Responses.Number.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Number[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Name'); for j := 0 to Responses.Name.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Name[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Message'); for j := 0 to Responses.Msg.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Msg[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Single Ring'); for j := 0 to Responses.SingleRing.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.SingleRing[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Double Ring'); for j := 0 to Responses.DoubleRing.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.DoubleRing[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Triple Ring'); for j := 0 to Responses.TripleRing.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.TripleRing[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice'); for j := 0 to Responses.Voice.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Voice[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Fax'); for j := 0 to Responses.Fax.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Fax[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Data'); for j := 0 to Responses.Data.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Data[j]).Response); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Other'); for j := 0 to Responses.Other.Count - 1 do tvDetails.Items.AddChild (TempNode2, PLmResponseData (Responses.Other[j]).Response); TempNode1 := tvDetails.Items.AddChild (CurModem, 'Answer'); for j := 0 to Answer.Count - 1 do begin tvDetails.Items.AddChild (TempNode1, 'Command = ' + PLmModemCommand (Answer[j]).Command); tvDetails.Items.AddChild (TempNode1, 'Sequence = ' + IntToStr (PLmModemCommand (Answer[j]).Sequence)); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Fax'); for j := 0 to Fax.Count - 1 do begin tvDetails.Items.AddChild (TempNode1, 'Command = ' + PLmModemCommand (Fax[j]).Command); tvDetails.Items.AddChild (TempNode1, 'Sequence = ' + IntToStr (PLmModemCommand (Fax[j]).Sequence)); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Hangup'); for j := 0 to Hangup.Count - 1 do begin tvDetails.Items.AddChild (TempNode1, 'Command = ' + PLmModemCommand (Hangup[j]).Command); tvDetails.Items.AddChild (TempNode1, 'Sequence = ' + IntToStr (PLmModemCommand (Hangup[j]).Sequence)); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Init'); for j := 0 to Init.Count - 1 do begin tvDetails.Items.AddChild (TempNode1, 'Command = ' + PLmModemCommand (Init[j]).Command); tvDetails.Items.AddChild (TempNode1, 'Sequence = ' + IntToStr (PLmModemCommand (Init[j]).Sequence)); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Monitor'); for j := 0 to Monitor.Count - 1 do begin tvDetails.Items.AddChild (TempNode1, 'Command = ' + PLmModemCommand (Monitor[j]).Command); tvDetails.Items.AddChild (TempNode1, 'Sequence = ' + IntToStr (PLmModemCommand (Monitor[j]).Sequence)); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Settings'); tvDetails.Items.AddChild (TempNode1, 'Prefix = ' + Settings.Prefix); tvDetails.Items.AddChild (TempNode1, 'Terminator = ' + Settings.Terminator); tvDetails.Items.AddChild (TempNode1, 'Dial Prefix = ' + Settings.DialPrefix); tvDetails.Items.AddChild (TempNode1, 'Dial Suffix = ' + Settings.DialSuffix); tvDetails.Items.AddChild (TempNode1, 'Speaker Volume High = ' + Settings.SpeakerVolume_High); tvDetails.Items.AddChild (TempNode1, 'Speaker Volume Low = ' + Settings.SpeakerVolume_Low); tvDetails.Items.AddChild (TempNode1, 'Speaker Volume Medium = ' + Settings.SpeakerVolume_Med); tvDetails.Items.AddChild (TempNode1, 'Speaker Mode Dial = ' + Settings.SpeakerMode_Dial); tvDetails.Items.AddChild (TempNode1, 'Speaker Mode Off = ' + Settings.SpeakerMode_Off); tvDetails.Items.AddChild (TempNode1, 'Speaker Mode On = ' + Settings.SpeakerMode_On); tvDetails.Items.AddChild (TempNode1, 'Speaker Mode Setup = ' + Settings.SpeakerMode_Setup); tvDetails.Items.AddChild (TempNode1, 'Flow Control Hard = ' + Settings.FlowControl_Hard); tvDetails.Items.AddChild (TempNode1, 'Flow Control Off = ' + Settings.FlowControl_Off); tvDetails.Items.AddChild (TempNode1, 'Flow Control Soft = ' + Settings.FlowControl_Soft); tvDetails.Items.AddChild (TempNode1, 'Error Control Forced = ' + Settings.ErrorControl_Forced); tvDetails.Items.AddChild (TempNode1, 'Error Control Off = ' + Settings.ErrorControl_Off); tvDetails.Items.AddChild (TempNode1, 'Error Control On = ' + Settings.ErrorControl_On); tvDetails.Items.AddChild (TempNode1, 'Error Control Cellular = ' + Settings.ErrorControl_Cellular); tvDetails.Items.AddChild (TempNode1, 'Error Control Cellular Forced = ' + Settings.ErrorControl_Cellular_Forced); tvDetails.Items.AddChild (TempNode1, 'Compression Off = ' + Settings.Compression_Off); tvDetails.Items.AddChild (TempNode1, 'Compression On = ' + Settings.Compression_On); tvDetails.Items.AddChild (TempNode1, 'Modulation Bell = ' + Settings.Modulation_Bell); tvDetails.Items.AddChild (TempNode1, 'Modulation CCITT = ' + Settings.Modulation_CCITT); tvDetails.Items.AddChild (TempNode1, 'Modulation CCITT V23 = ' + Settings.Modulation_CCITT_V23); tvDetails.Items.AddChild (TempNode1, 'Speed Negotiation On = ' + Settings.SpeedNegotiation_On); tvDetails.Items.AddChild (TempNode1, 'Speed Negotiation Off = ' + Settings.SpeedNegotiation_Off); tvDetails.Items.AddChild (TempNode1, 'Pulse = ' + Settings.Pulse); tvDetails.Items.AddChild (TempNode1, 'Tone = ' + Settings.Tone); tvDetails.Items.AddChild (TempNode1, 'Blind Off = ' + Settings.Blind_Off); tvDetails.Items.AddChild (TempNode1, 'Blind On = ' + Settings.Blind_On); tvDetails.Items.AddChild (TempNode1, 'Call Setup Fail Timer = ' + Settings.CallSetupFailTimer); tvDetails.Items.AddChild (TempNode1, 'Inactivity Timeout = ' + Settings.InactivityTimeout); tvDetails.Items.AddChild (TempNode1, 'Compatibility Flags = ' + Settings.CompatibilityFlags); tvDetails.Items.AddChild (TempNode1, 'Config Delay = ' + IntToStr (Settings.ConfigDelay)); TempNode1 := tvDetails.Items.AddChild (CurModem, 'Voice'); tvDetails.Items.AddChild (TempNode1, 'Voice Profile = ' + Voice.VoiceProfile); tvDetails.Items.AddChild (TempNode1, 'Handset Close Delay = ' + IntToStr (Voice.HandsetCloseDelay)); tvDetails.Items.AddChild (TempNode1, 'Speaker Phone Specs = ' + Voice.SpeakerPhoneSpecs); tvDetails.Items.AddChild (TempNode1, 'Abort Play = ' + Voice.AbortPlay); tvDetails.Items.AddChild (TempNode1, 'Caller ID OutSide = ' + Voice.CallerIDOutSide); tvDetails.Items.AddChild (TempNode1, 'Caller ID Private = ' + Voice.CallerIDPrivate); tvDetails.Items.AddChild (TempNode1, 'Terminate Play = ' + Voice.TerminatePlay); tvDetails.Items.AddChild (TempNode1, 'Terminate Record = ' + Voice.TerminateRecord); tvDetails.Items.AddChild (TempNode1, 'Voice Manufacturer ID = ' + Voice.VoiceManufacturerID); tvDetails.Items.AddChild (TempNode1, 'Voice Product ID Wave In = ' + Voice.VoiceProductIDWaveIn); tvDetails.Items.AddChild (TempNode1, 'Voice Product ID Wave Out = ' + Voice.VoiceProductIDWaveOut); tvDetails.Items.AddChild (TempNode1, 'Voice Switch Features = ' + Voice.VoiceSwitchFeatures); tvDetails.Items.AddChild (TempNode1, 'Voice Baud Rate = ' + IntToStr (Voice.VoiceBaudRate)); tvDetails.Items.AddChild (TempNode1, 'Voice Mixer Mid = ' + Voice.VoiceMixerMid); tvDetails.Items.AddChild (TempNode1, 'Voice Mixer Pid = ' + Voice.VoiceMixerPid); tvDetails.Items.AddChild (TempNode1, 'Voice Mixer Line ID = ' + Voice.VoiceMixerLineID); TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Close Handset'); for j := 0 to Voice.CloseHandset.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.CloseHandset[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.CloseHandset[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Enable Caller ID'); for j := 0 to Voice.EnableCallerID.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.EnableCallerID[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.EnableCallerID[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Enable Distinctive Ring'); for j := 0 to Voice.EnableDistinctiveRing.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.EnableDistinctiveRing[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.EnableDistinctiveRing[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Generate Digit'); for j := 0 to Voice.GenerateDigit.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.GenerateDigit[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.GenerateDigit[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Handset Play Format'); for j := 0 to Voice.HandsetPlayFormat.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.HandsetPlayFormat[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.HandsetPlayFormat[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Handset Record Format'); for j := 0 to Voice.HandsetRecordFormat.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.HandsetRecordFormat[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.HandsetRecordFormat[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Line Set Play Format'); for j := 0 to Voice.LineSetPlayFormat.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.LineSetPlayFormat[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.LineSetPlayFormat[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Line Set Record Format'); for j := 0 to Voice.LineSetRecordFormat.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.LineSetRecordFormat[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.LineSetRecordFormat[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Open Handset'); for j := 0 to Voice.OpenHandset.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.OpenHandset[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.OpenHandset[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Speaker Phone Disable'); for j := 0 to Voice.SpeakerPhoneDisable.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.SpeakerPhoneDisable[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.SpeakerPhoneDisable[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Speaker Phone Enable'); for j := 0 to Voice.SpeakerPhoneEnable.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.SpeakerPhoneEnable[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.SpeakerPhoneEnable[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Speaker Phone Mute'); for j := 0 to Voice.SpeakerPhoneMute.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.SpeakerPhoneMute[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.SpeakerPhoneMute[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Speaker Phone Set Volume Gain'); for j := 0 to Voice.SpeakerPhoneSetVolumeGain.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.SpeakerPhoneSetVolumeGain[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.SpeakerPhoneSetVolumeGain[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Speaker Phone UnMute'); for j := 0 to Voice.SpeakerPhoneUnMute.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.SpeakerPhoneUnMute[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.SpeakerPhoneUnMute[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'StartPlay'); for j := 0 to Voice.StartPlay.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.StartPlay[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.StartPlay[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Start Record'); for j := 0 to Voice.StartRecord.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.StartRecord[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.StartRecord[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Stop Play'); for j := 0 to Voice.StopPlay.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.StopPlay[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.StopPlay[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Stop Record'); for j := 0 to Voice.StopRecord.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.StopRecord[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.StopRecord[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice Answer'); for j := 0 to Voice.VoiceAnswer.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.VoiceAnswer[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.VoiceAnswer[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice Dial Number Setup'); for j := 0 to Voice.VoiceDialNumberSetup.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.VoiceDialNumberSetup[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.VoiceDialNumberSetup[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Voice To Data Answer'); for j := 0 to Voice.VoiceToDataAnswer.Count - 1 do begin tvDetails.Items.AddChild (TempNode2, 'Command = ' + PLmModemCommand (Voice.VoiceToDataAnswer[j]).Command); tvDetails.Items.AddChild (TempNode2, 'Sequence = ' + IntToStr (PLmModemCommand (Voice.VoiceToDataAnswer[j]).Sequence)); end; TempNode2 := tvDetails.Items.AddChild (TempNode1, 'Wave Driver'); tvDetails.Items.AddChild (TempNode2, 'Baud Rate = ' + Voice.WaveDriver.BaudRate); tvDetails.Items.AddChild (TempNode2, 'Wave Hardware ID = ' + Voice.WaveDriver.WaveHardwareID); tvDetails.Items.AddChild (TempNode2, 'Wave Devices = ' + Voice.WaveDriver.WaveDevices); tvDetails.Items.AddChild (TempNode2, 'Lower Mid = ' + Voice.WaveDriver.LowerMid); tvDetails.Items.AddChild (TempNode2, 'Lower Wave In Pid = ' + Voice.WaveDriver.LowerWaveInPid); tvDetails.Items.AddChild (TempNode2, 'Lower Wave Out Pid = ' + Voice.WaveDriver.LowerWaveOutPid); tvDetails.Items.AddChild (TempNode2, 'Wave Out Mixer Dest = ' + Voice.WaveDriver.WaveOutMixerDest); tvDetails.Items.AddChild (TempNode2, 'Wave Out Mixer Source = ' + Voice.WaveDriver.WaveOutMixerSource); tvDetails.Items.AddChild (TempNode2, 'Wave In Mixer Dest = ' + Voice.WaveDriver.WaveInMixerDest); tvDetails.Items.AddChild (TempNode2, 'Wave In Mixer Source = ' + Voice.WaveDriver.WaveInMixerSource); TempNode3 := tvDetails.Items.AddChild (TempNode2, 'Wave Format'); for j := 0 to Voice.WaveDriver.WaveFormat.Count - 1 do begin tvDetails.Items.AddChild (TempNode3, 'Speed ' + IntToStr (j + 1) + ' = ' + PLmWaveFormat (Voice.WaveDriver.WaveFormat[j]).Speed); tvDetails.Items.AddChild (TempNode3, 'ChipSet ' + IntToStr (j + 1) + ' = ' + PLmWaveFormat (Voice.WaveDriver.WaveFormat[j]).ChipSet); tvDetails.Items.AddChild (TempNode3, 'Sample Size ' + IntToStr (j + 1) + ' = ' + PLmWaveFormat (Voice.WaveDriver.WaveFormat[j]).SampleSize); end; TempNode1 := tvDetails.Items.AddChild (CurModem, 'Hardware'); tvDetails.Items.AddChild (TempNode1, 'Autoconfig Override = ' + Hardware.AutoConfigOverride); tvDetails.Items.AddChild (TempNode1, 'ComPort = ' + Hardware.ComPort); tvDetails.Items.AddChild (TempNode1, 'Invalid RDP = ' + Hardware.InvalidRDP); tvDetails.Items.AddChild (TempNode1, 'I/O Base Address = ' + IntToStr (Hardware.IoBaseAddress)); tvDetails.Items.AddChild (TempNode1, 'Interrupt Number = ' + IntToStr (Hardware.InterruptNumber)); if Hardware.PermitShare then tvDetails.Items.AddChild (TempNode1, 'Permit Share = True') else tvDetails.Items.AddChild (TempNode1, 'Permit Share = False'); tvDetails.Items.AddChild (TempNode1, 'RxFIFO = ' + Hardware.RxFIFO); tvDetails.Items.AddChild (TempNode1, 'Rx/TX Buffer Size = ' + IntToStr (Hardware.RxTxBufferSize)); tvDetails.Items.AddChild (TempNode1, 'Tx FIFO = ' + Hardware.TxFIFO); tvDetails.Items.AddChild (TempNode1, 'PCMCIA = ' + Hardware.Pcmcia); tvDetails.Items.AddChild (TempNode1, 'Bus Type = ' + Hardware.BusType); tvDetails.Items.AddChild (TempNode1, 'PCCARD Attribute Memory Address = ' + IntToStr (Hardware.PCCARDAttributeMemoryAddress)); tvDetails.Items.AddChild (TempNode1, 'PCCARD Attribute Memory Size = ' + IntToStr (Hardware.PCCARDAttributeMemorySize)); tvDetails.Items.AddChild (TempNode1, 'PCCARD Attribute Memory Offset = ' + IntToStr (Hardware.PCCARDAttributeMemoryOffset)); end; finally LibModem.Free; Screen.Cursor := crDefault; end; lbxModemList.DragMode := dmAutomatic; caption := 'automatic'; end; procedure TForm1.Deletemodem1Click(Sender: TObject); var DetailFile, ModemName : string; LibModem : TApdLibModem; begin if lbxModemList.ItemIndex = -1 then exit; ModemName := lbxModemList.Items[lbxModemList.ItemIndex]; LibModem := nil; Screen.Cursor := crHourglass; try DetailFile := lbxDetailFiles.Items[lbxDetailFiles.ItemIndex]; LibModem := TApdLibModem.Create(self); LibModem.LibModemPath := edtModemCapFolder.Text; LibModem.DeleteModem(DetailFile, ModemName); Caption := Format('%f3 seconds', [(AdTimeGetTime - StartTime) / 1000]); { force everything to repaint } lbxDetailFilesClick(nil); finally LibModem.Free; Screen.Cursor := crDefault; end; end; procedure TForm1.Deletefile1Click(Sender: TObject); var DetailFile : string; begin if lbxDetailFiles.ItemIndex = -1 then exit; DetailFile := lbxDetailFiles.Items[lbxDetailFiles.ItemIndex]; if MessageDlg('Delete ' + DetailFile + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin DeleteFile(AddBackslash(edtModemCapFolder.Text) + DetailFile); RefreshDetailList; end; end; procedure TForm1.Newfile1Click(Sender: TObject); var NewName : string; LibModem : TApdLibModem; begin NewName := 'MyModems.xml'; if InputQuery('New modem detail file', 'Enter new name '#13#10 + '(.xml auto-added, path is modemcap folder)', NewName) then begin LibModem := nil; try LibModem := TApdLibModem.Create(self); LibModem.LibModemPath := edtModemCapFolder.Text; LibModem.CreateNewDetailFile(NewName); finally LibModem.Free; end; RefreshDetailList; end; end; procedure TForm1.lbxDetailFilesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source = lbxModemList; end; procedure TForm1.lbxDetailFilesDragDrop(Sender, Source: TObject; X, Y: Integer); var DropFileIndex : Integer; DragToFileName, DragFromFileName, DraggedModemName : string; LibModem : TApdLibModem; Modem : TLmModem; begin if Source = lbxModemList then begin DraggedModemName := lbxModemList.Items[lbxModemList.ItemIndex]; DragFromFileName := lbxDetailFiles.Items[lbxDetailFiles.ItemIndex]; DropFileIndex := lbxDetailFiles.ItemAtPos(Point(X, Y), False); DragToFileName := lbxDetailFiles.Items[DropFileIndex]; LibModem := nil; try LibModem := TApdLibModem.Create(self); LibModem.LibModemPath := edtModemCapFolder.Text; StartTime := AdTimeGetTime; if LibModem.GetModem(DragFromFileName, DraggedModemName, Modem) = ecOK then LibModem.AddModem(DragToFileName, Modem); Caption := Format('%f3 seconds', [(AdTimeGetTime - StartTime) / 1000]); finally LibModem.Free; end; end; end; procedure TForm1.lbxModemListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Shift = [ssDouble] then begin lbxModemList.DragMode := dmManual; Caption := 'manual'; end; end; end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit enhancers; {$MODE Delphi} interface uses iLBC_define,constants,filter,C2Delphi_header; {----------------------------------------------------------------* * Find index in array such that the array element with said * index is the element of said array closest to "value" * according to the squared-error criterion *---------------------------------------------------------------} procedure NearestNeighbor( index:pInteger; { (o) index of array element closest to value } narray:PAreal; { (i) data array } value:real;{ (i) value } arlength:integer{ (i) dimension of data array } ); procedure mycorr1( corr:pareal; { (o) correlation of seq1 and seq2 } seq1:pareal; { (i) first sequence } dim1:integer; { (i) dimension first seq1 } seq2:pareal; { (i) second sequence } dim2:integer { (i) dimension seq2 } ); procedure enh_upsample( useq1:pareal; { (o) upsampled output sequence } seq1:pareal;{ (i) unupsampled sequence } dim1:integer; { (i) dimension seq1 } hfl:integer { (i) polyphase filter length=2*hfl+1 } ); procedure refiner( seg:pareal; { (o) segment array } updStartPos:pareal; { (o) updated start point } idata:pareal; { (i) original data buffer } idatal:integer; { (i) dimension of idata } centerStartPos:integer; { (i) beginning center segment } estSegPos:real;{ (i) estimated beginning other segment } period:real { (i) estimated pitch period } ); procedure smath( odata:PAreal; { (o) smoothed output } sseq:PAreal;{ (i) said second sequence of waveforms } hl:integer; { (i) 2*hl+1 is sseq dimension } alpha0:real{ (i) max smoothing energy fraction } ); procedure getsseq( sseq:PAreal; { (o) the pitch-synchronous sequence } idata:PAreal; { (i) original data } idatal:integer; { (i) dimension of data } centerStartPos:integer; { (i) where current block starts } period:pareal; { (i) rough-pitch-period array } plocs:pareal; { (i) where periods of period array are taken } periodl:integer; { (i) dimension period array } hl:integer { (i) 2*hl+1 is the number of sequences } ); procedure enhancer( odata:pareal; { (o) smoothed block, dimension blockl } idata:pareal; { (i) data buffer used for enhancing } idatal:integer; { (i) dimension idata } centerStartPos:integer; { (i) first sample current block within idata } alpha0:real; { (i) max correction-energy-fraction (in [0,1]) } period:pareal; { (i) pitch period array } plocs:pareal; { (i) locations where period array values valid } periodl:integer { (i) dimension of period and plocs } ); function xCorrCoef( target:PAreal; { (i) first array } regressor:PAreal; { (i) second array } subl:integer { (i) dimension arrays } ):real; function enhancerInterface( nout:PAreal; { (o) enhanced signal } nin:PAreal; { (i) unenhanced signal } iLBCdec_inst:piLBC_Dec_Inst_t { (i) buffers etc } ):integer; implementation procedure NearestNeighbor( index:pInteger; { (o) index of array element closest to value } narray:PAreal; { (i) data array } value:real;{ (i) value } arlength:integer{ (i) dimension of data array } ); var i:integer; bestcrit,crit:real; begin crit:=narray[0]-value; bestcrit:=crit*crit; index^:=0; for i:=1 to arlength-1 do begin crit:=narray[i]-value; crit:=crit*crit; if (crit<bestcrit) then begin bestcrit:=crit; index^:=i; end; end; end; {----------------------------------------------------------------* * compute cross correlation between sequences *---------------------------------------------------------------} procedure mycorr1( corr:pareal; { (o) correlation of seq1 and seq2 } seq1:pareal; { (i) first sequence } dim1:integer; { (i) dimension first seq1 } seq2:pareal; { (i) second sequence } dim2:integer { (i) dimension seq2 } ); var i,j:integer; begin for i:=0 to dim1-dim2 do begin corr[i]:=0.0; for j:=0 to dim2-1 do begin corr[i] := corr[i] + seq1[i+j] * seq2[j]; end; end; end; {----------------------------------------------------------------* * upsample finite array assuming zeros outside bounds *---------------------------------------------------------------} procedure enh_upsample( useq1:pareal; { (o) upsampled output sequence } seq1:pareal;{ (i) unupsampled sequence } dim1:integer; { (i) dimension seq1 } hfl:integer { (i) polyphase filter length=2*hfl+1 } ); var pu,ps:preal; i,j,k,q,filterlength,hfl2:integer; polyp:array [0..ENH_UPS0-1] of preal; { pointers to polyphase columns } pp:preal; begin { define pointers for filter } filterlength:=2*hfl+1; if ( filterlength > dim1 ) then begin hfl2:=(dim1 div 2); for j:=0 to ENH_UPS0-1 do begin polyp[j]:=@polyphaserTbl[j*filterlength+hfl-hfl2]; end; hfl:=hfl2; filterlength:=2*hfl+1; end else begin for j:=0 to ENH_UPS0-1 do begin polyp[j]:=@polyphaserTbl[j*filterlength]; end; end; { filtering: filter overhangs left side of sequence } pu:=@useq1[0]; for i:=hfl to filterlength-1 do begin for j:=0 to ENH_UPS0-1 do begin pu^:=0.0; pp := polyp[j]; ps := @seq1[i]; for k:=0 to i do begin pu^ := pu^ + ps^ * pp^; dec(ps); inc(pp); end; inc(pu); end; end; { filtering: simple convolution=inner products } for i:=filterlength to dim1-1 do begin for j:=0 to ENH_UPS0-1 do begin pu^:=0.0; pp := polyp[j]; ps := @seq1[i]; for k:=0 to filterlength-1 do begin pu^ :=pu^ + ps^ * pp^; dec(ps); inc(pp); end; inc(pu); end; end; { filtering: filter overhangs right side of sequence } for q:=1 to hfl do begin for j:=0 to ENH_UPS0-1 do begin pu^:=0.0; inc(polyp[j],q); pp := polyp[j]; dec(polyp[j],q); ps := @seq1[dim1-1]; for k:=0 to filterlength-q-1 do begin pu^ := pu^ + ps^ * pp^; dec(ps); inc(pp); end; inc(pu); end; end; end; {----------------------------------------------------------------* * find segment starting near idata+estSegPos that has highest * correlation with idata+centerStartPos through * idata+centerStartPos+ENH_BLOCKL-1 segment is found at a * resolution of ENH_UPSO times the original of the original * sampling rate *---------------------------------------------------------------} procedure refiner( seg:pareal; { (o) segment array } updStartPos:pareal; { (o) updated start point } idata:pareal; { (i) original data buffer } idatal:integer; { (i) dimension of idata } centerStartPos:integer; { (i) beginning center segment } estSegPos:real;{ (i) estimated beginning other segment } period:real { (i) estimated pitch period } ); var estSegPosRounded,searchSegStartPos,searchSegEndPos,corrdim:integer; tloc,tloc2,i,st,en,fraction:integer; vect:array [0..ENH_VECTL-1] of real; corrVec:array [0..ENH_CORRDIM-1] of real; maxv:real; corrVecUps:array [0..ENH_CORRDIM*ENH_UPS0-1] of real; begin { defining array bounds } estSegPosRounded:=Trunc((estSegPos - 0.5)); searchSegStartPos:=estSegPosRounded-ENH_SLOP; if (searchSegStartPos<0) then begin searchSegStartPos:=0; end; searchSegEndPos:=estSegPosRounded+ENH_SLOP; if (searchSegEndPos+ENH_BLOCKL >= idatal) then begin searchSegEndPos:=idatal-ENH_BLOCKL-1; end; corrdim:=searchSegEndPos-searchSegStartPos+1; { compute upsampled correlation (corr33) and find location of max } mycorr1(@corrVec,@idata[searchSegStartPos], corrdim+ENH_BLOCKL-1,@idata[centerStartPos],ENH_BLOCKL); enh_upsample(@corrVecUps[0],@corrVec[0],corrdim,ENH_FL0); tloc:=0; maxv:=corrVecUps[0]; for i:=1 to ENH_UPS0*corrdim-1 do begin if (corrVecUps[i]>maxv) then begin tloc:=i; maxv:=corrVecUps[i]; end; end; { make vector can be upsampled without ever running outside bounds } updStartPos[0]:= searchSegStartPos + tloc/ENH_UPS0+1.0; tloc2:=trunc(tloc/ENH_UPS0); if (tloc>tloc2*ENH_UPS0) then begin inc(tloc2); end; st:=searchSegStartPos+tloc2-ENH_FL0; if (st<0) then begin fillchar(vect,-st*sizeof(real),0); move(idata[0],vect[-st], (ENH_VECTL+st)*sizeof(real)); end else begin en:=st+ENH_VECTL; if (en>idatal) then begin move( idata[st],vect[0],(ENH_VECTL-(en-idatal))*sizeof(real)); fillchar(vect[ENH_VECTL-(en-idatal)],(en-idatal)*sizeof(real), 0); end else begin move( idata[st],vect[0], ENH_VECTL*sizeof(real)); end; end; fraction:=tloc2*ENH_UPS0-tloc; { compute the segment (this is actually a convolution) } mycorr1(seg,@vect[0],ENH_VECTL,@polyphaserTbl[(2*ENH_FL0+1)*fraction], 2*ENH_FL0+1); end; {----------------------------------------------------------------* * find the smoothed output data *---------------------------------------------------------------} procedure smath( odata:PAreal; { (o) smoothed output } sseq:PAreal;{ (i) said second sequence of waveforms } hl:integer; { (i) 2*hl+1 is sseq dimension } alpha0:real{ (i) max smoothing energy fraction } ); var i,k:integer; psseq:PAreal; w00,w10,w11,A,B,C,err,errs:real; surround:array [0..BLOCKL_MAX-1] of real; { shape contributed by other than current } wt:array [0..2*ENH_HL+1 -1] of real; { waveform weighting to get surround shape } denom:real; begin { create shape of contribution from all waveforms except the current one } for i:=1 to 2*hl+1 do begin wt[i-1] := 0.5*(1 - cos(2*PI*i/(2*hl+2))); end; wt[hl]:=0.0; { for clarity, not used } for i:=0 to ENH_BLOCKL-1 do begin surround[i]:=sseq[i]*wt[0]; end; for k:=1 to hl-1 do begin psseq:=@sseq[k*ENH_BLOCKL]; for i:=0 to ENH_BLOCKL-1 do begin surround[i]:=surround[i]+psseq[i]*wt[k]; end; end; for k:=hl+1 to 2*hl do begin psseq:=@sseq[k*ENH_BLOCKL]; for i:=0 to ENH_BLOCKL-1 do begin surround[i]:=surround[i]+psseq[i]*wt[k]; end; end; { compute some inner products } w00 :=0.0; w10 :=0.0; w11 :=0.0; psseq:=@sseq[hl*ENH_BLOCKL]; { current block } for i:=0 to ENH_BLOCKL-1 do begin w00:=w00+psseq[i]*psseq[i]; w11:=w11+surround[i]*surround[i]; w10:=w10+surround[i]*psseq[i]; end; if (abs(w11) < 1.0) then begin w11:=1.0; end; C := sqrt( w00/w11); { first try enhancement without power-constraint } errs:=0.0; psseq:=@sseq[hl*ENH_BLOCKL]; for i:=0 to ENH_BLOCKL-1 do begin odata[i]:=C*surround[i]; err:=psseq[i]-odata[i]; errs:=errs+err*err; end; { if constraint violated by first try, add constraint } if (errs > alpha0 * w00) then begin if ( w00 < 1) then begin w00:=1; end; denom := (w11*w00-w10*w10)/(w00*w00); if (denom > 0.0001) then { eliminates numerical problems for if smooth } begin A := sqrt( (alpha0- alpha0*alpha0/4)/denom); B := -alpha0/2 - A * w10/w00; B := B+1; end else begin { essentially no difference between cycles; smoothing not needed } A:= 0.0; B:= 1.0; end; { create smoothed sequence } psseq:=@sseq[hl*ENH_BLOCKL]; for i:=0 to ENH_BLOCKL-1 do begin odata[i]:=A*surround[i]+B*psseq[i]; end; end; end; {----------------------------------------------------------------* * get the pitch-synchronous sample sequence *---------------------------------------------------------------} procedure getsseq( sseq:PAreal; { (o) the pitch-synchronous sequence } idata:PAreal; { (i) original data } idatal:integer; { (i) dimension of data } centerStartPos:integer; { (i) where current block starts } period:pareal; { (i) rough-pitch-period array } plocs:pareal; { (i) where periods of period array are taken } periodl:integer; { (i) dimension period array } hl:integer { (i) 2*hl+1 is the number of sequences } ); var i,centerEndPos,q:integer; blockStartPos:array [0..2*ENH_HL+1-1] of real; lagBlock:array [0..2*ENH_HL+1-1] of integer; plocs2:array [0..ENH_PLOCSL-1] of real; psseq:^real; begin centerEndPos:=centerStartPos+ENH_BLOCKL-1; { present } NearestNeighbor(@lagBlock[hl],plocs,0.5*(centerStartPos+centerEndPos),periodl); blockStartPos[hl]:=centerStartPos; psseq:=@sseq[ENH_BLOCKL*hl]; move(idata[centerStartPos],psseq^, ENH_BLOCKL*sizeof(real)); { past } for q:=hl-1 downto 0 do begin blockStartPos[q]:=blockStartPos[q+1]-period[lagBlock[q+1]]; NearestNeighbor(@lagBlock[q],plocs, blockStartPos[q]+ENH_BLOCKL_HALF-period[lagBlock[q+1]], periodl); if (blockStartPos[q]-ENH_OVERHANG>=0) then begin refiner(@sseq[q*ENH_BLOCKL], @blockStartPos[q], idata, idatal, centerStartPos, blockStartPos[q], period[lagBlock[q+1]]); end else begin psseq:=@sseq[q*ENH_BLOCKL]; fillchar(psseq^, ENH_BLOCKL*sizeof(real), 0); end; end; { future } for i:=0 to periodl-1 do begin plocs2[i]:=plocs[i]-period[i]; end; for q:=hl+1 to 2*hl do begin NearestNeighbor(@lagBlock[q],@plocs2, blockStartPos[q-1]+ENH_BLOCKL_HALF,periodl); blockStartPos[q]:=blockStartPos[q-1]+period[lagBlock[q]]; if (blockStartPos[q]+ENH_BLOCKL+ENH_OVERHANG<idatal) then begin refiner(@sseq[ENH_BLOCKL*q], @blockStartPos[q], idata, idatal, centerStartPos, blockStartPos[q], period[lagBlock[q]]); end else begin psseq:=@sseq[q*ENH_BLOCKL]; fillchar(psseq^, ENH_BLOCKL*sizeof(real), 0); end; end; end; {----------------------------------------------------------------* * perform enhancement on idata+centerStartPos through * idata+centerStartPos+ENH_BLOCKL-1 *---------------------------------------------------------------} procedure enhancer( odata:pareal; { (o) smoothed block, dimension blockl } idata:pareal; { (i) data buffer used for enhancing } idatal:integer; { (i) dimension idata } centerStartPos:integer; { (i) first sample current block within idata } alpha0:real; { (i) max correction-energy-fraction (in [0,1]) } period:pareal; { (i) pitch period array } plocs:pareal; { (i) locations where period array values valid } periodl:integer { (i) dimension of period and plocs } ); var sseq:array [0..(2*ENH_HL+1)*ENH_BLOCKL-1] of real; begin { get said second sequence of segments } getsseq(@sseq,idata,idatal,centerStartPos,period, plocs,periodl,ENH_HL); { compute the smoothed output from said second sequence } smath(odata,@sseq,ENH_HL,alpha0); end; {----------------------------------------------------------------* * cross correlation *---------------------------------------------------------------} function xCorrCoef( target:PAreal; { (i) first array } regressor:PAreal; { (i) second array } subl:integer { (i) dimension arrays } ):real; var i:integer; ftmp1, ftmp2:real; begin ftmp1 := 0.0; ftmp2 := 0.0; for i:=0 to subl-1 do begin ftmp1 :=ftmp1 + target[i]*regressor[i]; ftmp2 :=ftmp2 + regressor[i]*regressor[i]; end; if (ftmp1 > 0.0) then begin result:=(ftmp1*ftmp1/ftmp2); end else begin result:=0.0; end; end; {----------------------------------------------------------------* * interface for enhancer *---------------------------------------------------------------} function enhancerInterface( nout:PAreal; { (o) enhanced signal } nin:PAreal; { (i) unenhanced signal } iLBCdec_inst:piLBC_Dec_Inst_t { (i) buffers etc } ):integer; var enh_buf,enh_period:PAreal; iblock, isample:integer; lag, ilag, i, ioffset:integer; cc, maxcc:real; ftmp1, ftmp2:real; inPtr, enh_bufPtr1, enh_bufPtr2:^real; plc_pred:array [0..ENH_BLOCKL-1] of real; lpState:array[0..5] of real; downsampled:array [0..((ENH_NBLOCKS*ENH_BLOCKL+120) div 2) - 1] of real; inLen:integer; start, plc_blockl, inlag:integer; begin lag:=0; inLen:=ENH_NBLOCKS*ENH_BLOCKL+120; enh_buf:=@iLBCdec_inst^.enh_buf; enh_period:=@iLBCdec_inst^.enh_period; move(enh_buf[iLBCdec_inst^.blockl],enh_buf[0], (ENH_BUFL-iLBCdec_inst^.blockl)*sizeof(real)); move(nin[0],enh_buf[ENH_BUFL-iLBCdec_inst^.blockl], iLBCdec_inst^.blockl*sizeof(real)); if (iLBCdec_inst^.mode=30) then plc_blockl:=ENH_BLOCKL else plc_blockl:=40; { when 20 ms frame, move processing one block } ioffset:=0; if (iLBCdec_inst^.mode=20) then ioffset:=1; i:=3-ioffset; move(enh_period[i], enh_period[0], (ENH_NBLOCKS_TOT-i)*sizeof(real)); { Set state information to the 6 samples right before the samples to be downsampled. } move(enh_buf[(ENH_NBLOCKS_EXTRA+ioffset)*ENH_BLOCKL-126],lpState,6*sizeof(real)); { Down sample a factor 2 to save computations } DownSample(@enh_buf[(ENH_NBLOCKS_EXTRA+ioffset)*ENH_BLOCKL-120], @lpFilt_coefsTbl, inLen-ioffset*ENH_BLOCKL, @lpState, @downsampled); { Estimate the pitch in the down sampled domain. } for iblock := 0 to ENH_NBLOCKS-ioffset-1 do begin lag := 10; maxcc := xCorrCoef(@downsampled[60+iblock*ENH_BLOCKL_HALF], @downsampled[60+iblock*ENH_BLOCKL_HALF-lag], ENH_BLOCKL_HALF); for ilag:=11 to 59 do begin cc := xCorrCoef(@downsampled[60+iblock* ENH_BLOCKL_HALF], @downsampled[60+iblock* ENH_BLOCKL_HALF-ilag], ENH_BLOCKL_HALF); if (cc > maxcc) then begin maxcc := cc; lag := ilag; end; end; { Store the estimated lag in the non-downsampled domain } enh_period[iblock+ENH_NBLOCKS_EXTRA+ioffset] := lag*2; end; { PLC was performed on the previous packet } if (iLBCdec_inst^.prev_enh_pl=1) then begin inlag:=trunc(enh_period[ENH_NBLOCKS_EXTRA+ioffset]); lag := inlag-1; maxcc := xCorrCoef(nin, @nin[lag], plc_blockl); for ilag:=inlag to inlag+1 do begin cc := xCorrCoef(nin, @nin[ilag], plc_blockl); if (cc > maxcc) then begin maxcc := cc; lag := ilag; end; end; enh_period[ENH_NBLOCKS_EXTRA+ioffset-1]:=lag; { compute new concealed residual for the old lookahead, mix the forward PLC with a backward PLC from the new frame } inPtr:=@nin[lag-1]; enh_bufPtr1:=@plc_pred[plc_blockl-1]; if (lag>plc_blockl) then begin start:=plc_blockl; end else begin start:=lag; end; for isample := start downto 1 do begin enh_bufPtr1^ := inPtr^; dec(enh_bufPtr1); dec(inPtr); end; enh_bufPtr2:=@enh_buf[ENH_BUFL-1-iLBCdec_inst^.blockl]; for isample := (plc_blockl-1-lag) downto 0 do begin enh_bufPtr1^ := enh_bufPtr2^; dec(enh_bufPtr1); dec(enh_bufPtr2); end; { limit energy change } ftmp2:=0.0; ftmp1:=0.0; for i:=0 to plc_blockl-1 do begin ftmp2:=ftmp2+enh_buf[ENH_BUFL-1-iLBCdec_inst^.blockl-i]*enh_buf[ENH_BUFL-1-iLBCdec_inst^.blockl-i]; ftmp1:=ftmp1+plc_pred[i]*plc_pred[i]; end; ftmp1:=sqrt(ftmp1/plc_blockl); ftmp2:=sqrt(ftmp2/plc_blockl); if (ftmp1>2.0*ftmp2) and (ftmp1>0.0) then begin for i:=0 to plc_blockl-9 do begin plc_pred[i]:=plc_pred[i]*2.0*ftmp2/ftmp1; end; for i:=plc_blockl-10 to plc_blockl-1 do begin plc_pred[i]:=plc_pred[i]*(i-plc_blockl+10)*(1.0-2.0*ftmp2/ftmp1)/(10)+2.0*ftmp2/ftmp1; end; end; enh_bufPtr1:=@enh_buf[ENH_BUFL-1-iLBCdec_inst^.blockl]; for i:=0 to plc_blockl-1 do begin ftmp1 := (i+1) / (plc_blockl+1); enh_bufPtr1^ :=enh_bufPtr1^ * ftmp1; enh_bufPtr1^ :=enh_bufPtr1^ + (1.0-ftmp1)*plc_pred[plc_blockl-1-i]; dec(enh_bufPtr1); end; end; if (iLBCdec_inst^.mode=20) then begin { Enhancer with 40 samples delay } for iblock := 0 to 1 do begin enhancer(@nout[iblock*ENH_BLOCKL], enh_buf, ENH_BUFL, (5+iblock)*ENH_BLOCKL+40, ENH_ALPHA0, enh_period, @enh_plocsTbl, ENH_NBLOCKS_TOT); end; end else if (iLBCdec_inst^.mode=30) then begin { Enhancer with 80 samples delay } for iblock := 0 to 2 do begin enhancer(@nout[iblock*ENH_BLOCKL], enh_buf, ENH_BUFL, (4+iblock)*ENH_BLOCKL, ENH_ALPHA0, enh_period, @enh_plocsTbl, ENH_NBLOCKS_TOT); end; end; result:=lag*2; end; end.
namespace CallingWin32DLL; interface uses System.Threading, System.Windows.Forms; type Program = assembly static class private class method OnThreadException(sender: Object; e: ThreadExceptionEventArgs); public class method Main; end; implementation /// <summary> /// The main entry point for the application. /// </summary> [STAThread] class method Program.Main; begin Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += OnThreadException; using lMainForm := new MainForm do Application.Run(lMainForm); end; /// <summary> /// Default exception handler /// </summary> class method Program.OnThreadException(sender: Object; e: ThreadExceptionEventArgs); begin MessageBox.Show(e.Exception.Message); end; end.
unit FreeOTFEDLLMainAPI; // API ported from: // FreeOTFE4PDAAPIConsts.h // FreeOTFEAPITypes.h // FreeOTFE4PDA.h // FreeOTFE4PDAAPI.h interface uses DriverAPI, FreeOTFEDriverConsts, Windows; const // Taken from diskio.h: // Older values; replaced by IOCTL_... versions DISK_IOCTL_GETINFO = 1; DISK_IOCTL_SETINFO = 5; DISK_IOCTL_READ = 2; DISK_IOCTL_WRITE = 3; DISK_IOCTL_INITIALIZED = 4; DISK_IOCTL_FORMAT_MEDIA = 6; DISK_IOCTL_GETNAME = 9; const IOCTL_DISK_BASE = FILE_DEVICE_DISK; const IOCTL_DISK_GETINFO = (((IOCTL_DISK_BASE) * $10000) or ((FILE_ANY_ACCESS) * $4000) or (($700) * $4) or (METHOD_BUFFERED)); const IOCTL_DISK_READ = (((IOCTL_DISK_BASE) * $10000) or ((FILE_READ_ACCESS) * $4000) or (($702) * $4) or (METHOD_BUFFERED)); const IOCTL_DISK_WRITE = (((IOCTL_DISK_BASE) * $10000) or ((FILE_WRITE_ACCESS) * $4000) or (($703) * $4) or (METHOD_BUFFERED)); type // From: // http://msdn.microsoft.com/en-us/library/aa930126.aspx //typedef struct _SG_BUF { // PUCHAR sb_buf; // DWORD sb_len; //} SG_BUF, *PSG_BUF; PSG_BUF = ^TSG_BUF; TSG_BUF = record sb_buf: PByte; sb_len: DWORD; end; // Declared upfront, as used by PFN_REQDONE, but uses TSG_REQ PSG_REQ = ^TSG_REQ; // From: // http://4pda.ru/forum/index.php?showtopic=41047 //typedef DWORD (* PFN_REQDONE)(struct _SG_REQ *); PFN_REQDONE = function(sg_reg: PSG_REQ): DWORD; CDECL; // From: // http://msdn.microsoft.com/en-us/library/ms920817.aspx //typedef struct _SG_REQ { // DWORD sr_start; // DWORD sr_num_sec; // DWORD sr_num_sg; // DWORD sr_status; // PFN_REQDONE sr_callback; // SG_BUF sr_sglist[1]; //} SG_REQ, *PSG_REQ; TSG_REQ = record sr_start: DWORD; sr_num_sec: DWORD; sr_num_sg: DWORD; sr_status: DWORD; sr_callback: PFN_REQDONE; sr_sglist: array [1..1] of TSG_BUF; end; const IOCTL_FREEOTFE_USER_DEV_HANDLE_SET = (((FILE_DEVICE_UNKNOWN) * $10000) or ((FILE_READ_DATA) * $4000) or (($815) * $4) or (METHOD_BUFFERED)); const IOCTL_FREEOTFE_USER_DEV_HANDLE_GET = (((FILE_DEVICE_UNKNOWN) * $10000) or ((FILE_READ_DATA) * $4000) or (($816) * $4) or (METHOD_BUFFERED)); const IOCTL_FREEOTFE_SET_FORCE_DISMOUNT = (((FILE_DEVICE_UNKNOWN) * $10000) or ((FILE_READ_DATA) * $4000) or (($817) * $4) or (METHOD_BUFFERED)); type // Commented out as not used in the PC DLL version // // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // // - i.e. it's not a "packed record" // PDIOC_USER_DEVICE_HANDLE = ^TDIOC_USER_DEVICE_HANDLE; // TDIOC_USER_DEVICE_HANDLE = record // UserSpaceDeviceHandle: THandle; // end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_FORCE_DISMOUNTS = ^TDIOC_FORCE_DISMOUNTS; TDIOC_FORCE_DISMOUNTS = record ForceDismounts: Boolean; end; //DWORD DSK_Init( // LPCTSTR pContext, // LPCVOID lpvBusContext //); const DLLEXPORT_MAIN_DSK_Init = 'DSK_Init'; type PDSK_Init = function(pContext: LPCTSTR; lpvBusContext: Pointer): DWORD; CDECL; //BOOL DSK_Deinit( // DWORD hDevice //); const DLLEXPORT_MAIN_DSK_Deinit = 'DSK_Deinit'; type PDSK_Deinit = function(hDevice: DWORD): Boolean; CDECL; //DWORD DSK_Open( // DWORD hDevice, // DWORD AccessCode, // DWORD ShareMode //); const DLLEXPORT_MAIN_DSK_Open = 'DSK_Open'; type PDSK_Open = function(hDevice: DWORD; AccessCode: DWORD; ShareMode: DWORD): DWORD; CDECL; //BOOL DSK_Close( // DWORD hOpen //); const DLLEXPORT_MAIN_DSK_Close = 'DSK_Close'; type PDSK_Close = function(hOpen: DWORD): Boolean; CDECL; //BOOL DSK_IOControl( // DWORD hOpen, // DWORD dwCode, // PBYTE pBufIn, // DWORD dwLenIn, // PBYTE pBufOut, // DWORD dwLenOut, // PDWORD pdwActualOut //); const DLLEXPORT_MAIN_DSK_IOControl = 'DSK_IOControl'; type PDSK_IOControl = function(hOpen: DWORD; dwCode: DWORD; pBufIn: PBYTE; dwLenIn: DWORD; pBufOut: PBYTE; dwLenOut: DWORD; pdwActualOut: PDWORD): Boolean; CDECL; //DWORD DSK_Seek( // DWORD hOpen, // long Amount, // WORD Type //); const DLLEXPORT_MAIN_DSK_Seek = 'DSK_Seek'; type PDSK_Seek = function(hOpen: DWORD; Amount: Integer; xType: Word): DWORD; CDECL; //DWORD DSK_Read( // DWORD hOpen, // LPVOID pBuffer, // DWORD Count //); const DLLEXPORT_MAIN_DSK_Read = 'DSK_Read'; type PDSK_Read = function(hOpen: DWORD; pBuffer: PByte; Count: DWORD): DWORD; CDECL; //DWORD DSK_Write( // DWORD hOpen, // LPCVOID pBuffer, // DWORD Count //); const DLLEXPORT_MAIN_DSK_Write = 'DSK_Write'; type PDSK_Write = function(hOpen: DWORD; pBuffer: PByte; Count: DWORD): DWORD; CDECL; //void DSK_PowerDown( // DWORD hDevice //); const DLLEXPORT_MAIN_DSK_PowerDown = 'DSK_PowerDown'; type PDSK_PowerDown = function(hDevice: DWORD): DWORD; CDECL; //void DSK_PowerUp( // DWORD hDevice //); const DLLEXPORT_MAIN_DSK_PowerUp = 'DSK_PowerUp'; type PDSK_PowerUp = function(hDevice: DWORD): DWORD; CDECL; //#define DLLEXPORT_MAIN_DERIVEKEY TEXT("MainDeriveKey") //typedef DWORD (* PMainDLLFnDeriveKey)( // IN DWORD SizeBufferIn, // IN DIOC_DERIVE_KEY_IN* DIOCBufferIn, // IN DWORD SizeBufferOut, // OUT DIOC_DERIVE_KEY_OUT* DIOCBufferOut //); const DLLEXPORT_MAIN_DERIVEKEY = 'MainDeriveKey'; type PMainDLLFnDeriveKey = function(SizeBufferIn: DWORD; DIOCBufferIn: PDIOC_DERIVE_KEY_IN_PC_DLL; SizeBufferOut: DWORD; DIOCBufferOut: PDIOC_DERIVE_KEY_OUT): DWORD; CDECL; //#define DLLEXPORT_MAIN_MACDATA TEXT("MainMACData") //typedef DWORD (* PMainDLLFnMACData)( // IN DWORD SizeBufferIn, // IN DIOC_GENERATE_MAC_IN* DIOCBufferIn, // IN DWORD SizeBufferOut, // OUT DIOC_GENERATE_MAC_OUT* DIOCBufferOut //); const DLLEXPORT_MAIN_MACDATA = 'MainMACData'; type PMainDLLFnMACData = function(SizeBufferIn: DWORD; DIOCBufferIn: PDIOC_GENERATE_MAC_IN_PC_DLL; SizeBufferOut: DWORD; DIOCBufferOut: PDIOC_GENERATE_MAC_OUT): DWORD; CDECL; implementation end.
unit uFormLinkItemSelector; interface uses Generics.Defaults, Generics.Collections, System.DateUtils, System.Math, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ImgList, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.AppEvnts, Dmitry.Utils.System, Dmitry.Controls.Base, Dmitry.Controls.WebLink, Dmitry.Controls.WatermarkedEdit, UnitDBDeclare, uMemory, uRuntime, uDBForm, uFormInterfaces, uGraphicUtils, uVCLHelpers; type TAniDirection = (adVert, adHor); TAniOption = (aoRemove); TAniOptions = set of TAniOption; TAnimationInfo = record Control: TControl; EndPosition: Integer; StartPosition: Integer; TillTime: TDateTime; Direction: TAniDirection; Options: TAniOptions; end; TFormLinkItemSelector = class(TDBForm, ILinkItemSelectForm, IFormLinkItemEditorData) AeMain: TApplicationEvents; TmrAnimation: TTimer; PnEditorPanel: TPanel; PnMain: TPanel; BtnClose: TButton; BtnSave: TButton; WlApplyChanges: TWebLink; WlCancelChanges: TWebLink; WlRemove: TWebLink; BvActionSeparator: TBevel; PnTop: TPanel; BvEditSeparator: TBevel; procedure FormCreate(Sender: TObject); procedure AeMainMessage(var Msg: tagMSG; var Handled: Boolean); procedure FormDestroy(Sender: TObject); procedure TmrAnimationTimer(Sender: TObject); procedure WlAddElementsClick(Sender: TObject); procedure WebLinkMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure WebLinkMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure WlApplyChangesClick(Sender: TObject); procedure WlCancelChangesClick(Sender: TObject); procedure WlRemoveClick(Sender: TObject); procedure BtnCloseClick(Sender: TObject); procedure BtnSaveClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FLinkHeight: Integer; FLinks: TList<TWebLink>; FLabels: TList<Tlabel>; FData: TList<TDataObject>; FEditData: TDataObject; FEditor: ILinkEditor; FActions: TList<string>; FActionLinks: TList<TWebLink>; FListWidth: Integer; FLinkPositions: TDictionary<TWebLink, Integer>; FAnimations: TList<TAnimationInfo>; FDragLink: TWebLink; FDragLabel: Tlabel; FStartMousePos: TPoint; FStartLinkPos: TPoint; FStartInfoPos: TPoint; FIsEditMode: Boolean; FDragMode: Boolean; FEditIndex: Integer; procedure CreateNewLine(var DataObject: TDataObject; Elements: TListElements); procedure CreateListElements(Elements: TListElements); procedure CheckLinksOrder; procedure LoadLinkList; procedure LoadActionsList; procedure AddLinkFromObject(DataObject: TDataObject); procedure MoveControlTo(Control: TControl; Position: Integer; Direction: TAniDirection; Options: TAniOptions = []); procedure MoveControlToIndex(Control: TControl; Index: Integer); procedure SwitchToEditMode; procedure SwitchToListMode; function GetFormHeight: Integer; property FormHeight: Integer read GetFormHeight; protected function GetFormID: string; override; procedure InterfaceDestroyed; override; public { Public declarations } function Execute(ListWidth: Integer; Title: string; Data: TList<TDataObject>; Editor: ILinkEditor): Boolean; function GetDataList: TList<TDataObject>; function GetEditorData: TDataObject; function GetTopPanel: TPanel; function GetEditorPanel: TPanel; procedure ApplyChanges; end; var FormLinkItemSelector: TFormLinkItemSelector; implementation const LinksLimit = 20; PaddingTop = 8; LinksDy = 6; AnimationDuration = 1 / (24 * 60 * 60 * 2); //0.5s AnimationDurationMs = 500; function Circ(Progress: Extended): Extended; begin Result := 1 - Sin(ArcCos(Progress)) end; function MakeEaseInOut(Progress: Extended): Extended; begin if (progress < 0.5) then Result := Circ(2 * progress) / 2 else Result := (2 - Circ(2 * (1 - progress))) / 2 end; function makeEaseOut(Progress: Extended): Extended; begin Result := 1 - Circ(1 - progress) end; {$R *.dfm} procedure TFormLinkItemSelector.AeMainMessage(var Msg: tagMSG; var Handled: Boolean); const TopDy = 8; var P: TPoint; Diff, NewTop: Integer; function MouseYToTop(MouseY: Integer): Integer; var Progress: Double; Top: Integer; begin if MouseY < PaddingTop then begin Progress := (PaddingTop - MouseY) / 100; Progress := Min(1, Max(0, Progress)); Result := Round(PaddingTop - PaddingTop * makeEaseOut(Progress)); Exit; end; Top := PaddingTop + (FLinks.Count - 1) * (FLinkHeight + LinksDy); if MouseY > Top then begin Progress := (MouseY - Top) / 100; Progress := Min(1, Max(0, Progress)); Result := Round(Top + PaddingTop * makeEaseOut(Progress)); Exit; end; Result := MouseY; end; begin if Active then begin if Msg.message = WM_MOUSEMOVE then begin if FDragLink <> nil then begin GetCursorPos(P); Diff := P.Y - FStartMousePos.Y; NewTop := FStartLinkPos.Y + Diff; FDragLink.Top := MouseYToTop(NewTop); NewTop := FStartInfoPos.Y + Diff; FDragLabel.Top := MouseYToTop(NewTop); CheckLinksOrder; end; end; if Msg.message = WM_LBUTTONUP then begin if FDragLink <> nil then begin MoveControlToIndex(FDragLink, FDragLink.Tag); MoveControlToIndex(FDragLabel, FDragLabel.Tag); FDragLink := nil; end; end; end; end; procedure TFormLinkItemSelector.ApplyChanges; var Data: TDataObject; Elements: TListElements; begin Data := FData[FEditIndex]; FEditor.UpdateItemFromEditor(Self, Data, Self); Elements := TListElements.Create; try Elements.Add(leWebLink, FLinks[FEditIndex]); Elements.Add(leInfoLabel, FLabels[FEditIndex]); FEditor.CreateNewItem(Self, Data, '', Elements); finally F(Elements); end; SwitchToListMode; end; procedure TFormLinkItemSelector.BtnCloseClick(Sender: TObject); begin Close; ModalResult := mrCancel; end; procedure TFormLinkItemSelector.BtnSaveClick(Sender: TObject); begin if FIsEditMode then ApplyChanges; if FEditor.OnApply(Self) then begin Close; ModalResult := mrOk; end; end; procedure TFormLinkItemSelector.CheckLinksOrder; var I, LinkReplacePosStart, LinkReplacePosEnd, TmpTag: Integer; Link: TWebLink; Info: Tlabel; begin if FDragLink = nil then Exit; for I := 0 to FLinks.Count - 1 do begin Link := FLinks[I]; Info := FLabels[I]; if Link <> FDragLink then begin LinkReplacePosStart := PaddingTop + I * (FLinkHeight + LinksDy) - LinksDy + (LinksDy div 2 - FLinkHeight div 2); LinkReplacePosEnd := LinkReplacePosStart + FLinkHeight + LinksDy; if (LinkReplacePosStart < FDragLink.Top) and (FDragLink.Top < LinkReplacePosEnd) then begin FDragMode := True; FData.Exchange(Link.Tag, FDragLink.Tag); TmpTag := Link.Tag; Link.Tag := FDragLink.Tag; FDragLink.Tag := TmpTag; TmpTag := Info.Tag; Info.Tag := FDragLabel.Tag; FDragLabel.Tag := TmpTag; MoveControlToIndex(Link, Link.Tag); MoveControlToIndex(Info, Info.Tag); FLinks.Sort(TComparer<TWebLink>.Construct( function (const L, R: TWebLink): Integer begin Result := L.Tag - R.Tag; end )); FLabels.Sort(TComparer<Tlabel>.Construct( function (const L, R: Tlabel): Integer begin Result := L.Tag - R.Tag; end )); Break; end; end; end; end; function TFormLinkItemSelector.Execute(ListWidth: Integer; Title: string; Data: TList<TDataObject>; Editor: ILinkEditor): Boolean; begin FEditor := Editor; FListWidth := ListWidth; Caption := Title; FData := Data; FEditor.SetForm(Self); if PnTop.ControlCount = 0 then begin PnTop.Height := 0; PnTop.Hide; end; WlApplyChanges.RefreshBuffer(True); WlCancelChanges.RefreshBuffer(True); WlRemove.RefreshBuffer(True); WlCancelChanges.Left := WlApplyChanges.AfterRight(PaddingTop); WlRemove.Left := WlCancelChanges.AfterRight(PaddingTop); LoadActionsList; LoadLinkList; SwitchToListMode; ShowModal; Result := ModalResult = mrOk; end; procedure TFormLinkItemSelector.FormClose(Sender: TObject; var Action: TCloseAction); begin FEditor.SetForm(nil); Action := caHide; end; procedure TFormLinkItemSelector.FormCreate(Sender: TObject); var Metrics: TTextMetric; function GetFontHeight: Integer; begin if GetTextMetrics(Canvas.Handle, Metrics) then Result := Metrics.tmHeight else Result := Canvas.TextHeight('Iy'); end; begin FLinkHeight := GetFontHeight; if IsWindowsVista and not FolderView and HasFont(Canvas, 'MyriadPro-Regular') then begin Font.Name := 'MyriadPro-Regular'; FLinkHeight := GetFontHeight; end; FEditIndex := -1; FDragLink := nil; FDragLabel := nil; FEditData := nil; FEditor := nil; FIsEditMode := False; FDragMode := False; FLinks := TList<TWebLink>.Create; FLabels := TList<Tlabel>.Create; FLinkPositions := TDictionary<TWebLink, Integer>.Create; FAnimations := TList<TAnimationInfo>.Create; FActions := TList<string>.Create; FActionLinks := TList<TWebLink>.Create; BtnClose.Caption := L('Cancel', ''); BtnSave.Caption := L('Save', ''); WlApplyChanges.Text := L('Apply'); WlCancelChanges.Text := L('Cancel'); WlRemove.Text := L('Remove'); WlApplyChanges.LoadFromResource('DOIT'); WlCancelChanges.LoadFromResource('CANCELACTION'); WlRemove.LoadFromResource('DELETE_FILE'); end; procedure TFormLinkItemSelector.FormDestroy(Sender: TObject); begin F(FLinkPositions); F(FLinks); F(FLabels); F(FAnimations); F(FEditData); F(FActions); F(FActionLinks); end; procedure TFormLinkItemSelector.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin if FIsEditMode then WlCancelChangesClick(Sender) else Close; end; end; function TFormLinkItemSelector.GetDataList: TList<TDataObject>; begin Result := FData; end; function TFormLinkItemSelector.GetEditorData: TDataObject; begin Result := FEditData; end; function TFormLinkItemSelector.GetEditorPanel: TPanel; begin Result := PnEditorPanel; end; function TFormLinkItemSelector.GetFormHeight: Integer; begin Result := PaddingTop * 2 + FLinks.Count * (FLinkHeight + LinksDy) + BtnSave.Height + 5 * 2 + WlRemove.Height + 3 * 2; end; function TFormLinkItemSelector.GetFormID: string; begin Result := 'LinkListEditor'; end; function TFormLinkItemSelector.GetTopPanel: TPanel; begin Result := PnTop; end; procedure TFormLinkItemSelector.InterfaceDestroyed; begin inherited; Release; end; procedure TFormLinkItemSelector.CreateListElements(Elements: TListElements); var WL: TWebLink; IL: Tlabel; begin WL := TWebLink.Create(Self); WL.Parent := PnMain; WL.Tag := FLinks.Count; WL.Height := FLinkHeight; WL.Width := ClientWidth; WL.Left := PaddingTop; WL.Font.Assign(Font); WL.OnMouseDown := WebLinkMouseDown; WL.OnMouseUp := WebLinkMouseUp; FLinks.Add(WL); Elements.Add(leWebLink, WL); IL := Tlabel.Create(Self); IL.Parent := PnMain; IL.Tag := FLabels.Count; IL.AutoSize := False; IL.Anchors := [akLeft, akTop, akRight]; IL.Alignment := taRightJustify; IL.Enabled := False; FLabels.Add(IL); Elements.Add(leInfoLabel, IL); end; procedure TFormLinkItemSelector.CreateNewLine(var DataObject: TDataObject; Elements: TListElements); var WL: TWebLink; IL: Tlabel; begin CreateListElements(Elements); FEditor.CreateNewItem(Self, DataObject, '', Elements); WL := TWebLink(Elements[leWebLink]); IL := Tlabel(Elements[leInfoLabel]); WL.RefreshBuffer(True); IL.Left := WL.Left + WL.Width + PaddingTop; IL.Width := ClientWidth - IL.Left - IL.Width - PaddingTop; MoveControlToIndex(WL, WL.Tag); MoveControlToIndex(IL, IL.Tag); MoveControlTo(Self, FormHeight, adVert); if FLinks.Count = LinksLimit then for WL in FActionLinks do WL.Enabled := False; end; procedure TFormLinkItemSelector.AddLinkFromObject(DataObject: TDataObject); var Elements: TListElements; procedure AddLink(Link: TWebLink); begin FLinks.Add(Link); FLinkPositions.Remove(Link); FLinkPositions.Add(Link, Link.Top); end; begin Elements := TListElements.Create; try CreateNewLine(DataObject, Elements); finally F(Elements); end; end; procedure TFormLinkItemSelector.LoadActionsList; begin FEditor.FillActions(Self, procedure(Actions: array of string; ProcessActionLink: TProcessActionLinkProcedure) var LinkLeft: Integer; Action: string; WL: TWebLink; begin LinkLeft := PaddingTop; for Action in Actions do begin WL := TWebLink.Create(Self); WL.Parent := PnMain; WL.Left := LinkLeft; WL.Top := BvActionSeparator.Top + PaddingTop; WL.Anchors := [akLeft, akBottom]; WL.Text := 'Add new'; WL.OnClick := WlAddElementsClick; WL.RefreshBuffer(True); WL.Tag := FActions.Count; ProcessActionLink(Action, WL); FActions.Add(Action); FActionLinks.Add(WL); LinkLeft := LinkLeft + WL.Width + PaddingTop; end; end ); end; procedure TFormLinkItemSelector.LoadLinkList; var DataItem: TDataObject; begin for DataItem in FData do AddLinkFromObject(DataItem); end; procedure TFormLinkItemSelector.MoveControlTo(Control: TControl; Position: Integer; Direction: TAniDirection; Options: TAniOptions = []); var AnimationInfo: TAnimationInfo; I: Integer; begin for I := 0 to FAnimations.Count - 1 do if (FAnimations[I].Control = Control) and (FAnimations[I].Direction = Direction) then begin FAnimations.Delete(I); Break; end; if Visible then begin AnimationInfo.Control := Control; AnimationInfo.Direction := Direction; AnimationInfo.Options := Options; AnimationInfo.EndPosition := Position; if Control is TForm then begin if AnimationInfo.Direction = adVert then begin AnimationInfo.EndPosition := Position + PnTop.Height; AnimationInfo.StartPosition := Control.ClientHeight; end; if AnimationInfo.Direction = adHor then AnimationInfo.StartPosition := Control.ClientWidth; end else begin if AnimationInfo.Direction = adVert then AnimationInfo.StartPosition := Control.Top; if AnimationInfo.Direction = adHor then AnimationInfo.StartPosition := Control.Left; end; AnimationInfo.TillTime := IncMilliSecond(Now, AnimationDurationMs); FAnimations.Add(AnimationInfo); TmrAnimation.Enabled := True; end else begin if Control is TForm then begin if Direction = adVert then Control.ClientHeight := Position + PnTop.Height; if Direction = adHor then Control.ClientWidth := Position; end else begin if Direction = adVert then Control.Top := Position; if Direction = adHor then Control.Left := Position; end; end; end; procedure TFormLinkItemSelector.MoveControlToIndex(Control: TControl; Index: Integer); var NewPos: Integer; Link: TWebLink; begin NewPos := PaddingTop + Index * (FLinkHeight + LinksDy); if Control is TWebLink then begin Link := TWebLink(Control); FLinkPositions.Remove(Link); FLinkPositions.Add(Link, NewPos); end; MoveControlTo(Control, NewPos, adVert); end; procedure TFormLinkItemSelector.TmrAnimationTimer(Sender: TObject); var I, NewPos: Integer; Animation: TAnimationInfo; Progress: Double; Control: TControl; CStart, CEnd: Cardinal; begin CStart := GetTickCount; TmrAnimation.Enabled := False; DisableAlign; try for I := FAnimations.Count - 1 downto 0 do begin Animation := FAnimations[I]; Progress := 1 - (Animation.TillTime - Now) / AnimationDuration; Progress := Min(1, Max(0, Progress)); NewPos := Animation.StartPosition + Round(makeEaseOut(Progress) * (Animation.EndPosition - Animation.StartPosition)); Control := Animation.Control; if Control is TForm then begin if Animation.Direction = adVert then Control.ClientHeight := NewPos; if Animation.Direction = adHor then Control.ClientWidth := NewPos; end else begin if Animation.Direction = adVert then Control.Top := NewPos; if Animation.Direction = adHor then Control.Left := NewPos; end; if Progress = 1 then begin if aoRemove in Animation.Options then Control.Free; FAnimations.Delete(I); Continue; end; end; finally EnableAlign; end; if FAnimations.Count = 0 then Exit; CEnd := GetTickCount; TmrAnimation.Interval := Max(1, 10 - Max(10, (CEnd - CStart))); TmrAnimation.Enabled := True; end; procedure TFormLinkItemSelector.WlAddElementsClick(Sender: TObject); var Data: TDataObject; Elements: TListElements; WL: TWebLink; begin if FIsEditMode then Exit; WL := TWebLink(Sender); Data := nil; FEditor.CreateNewItem(Self, Data, FActions[WL.Tag], nil); if Data <> nil then begin Elements := TListElements.Create; try CreateNewLine(Data, Elements); FData.Add(Data); finally F(Elements); end; end; end; procedure TFormLinkItemSelector.WebLinkMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; begin if FIsEditMode or FDragMode then Exit; GetCursorPos(P); if (Abs(P.X - FStartMousePos.X) <= 3) and (Abs(P.Y - FStartMousePos.Y) <= 3) then begin FIsEditMode := True; FEditIndex := TWebLink(Sender).Tag; SwitchToEditMode; end; end; procedure TFormLinkItemSelector.SwitchToEditMode; var I: Integer; ToWidth, ToHeight: Integer; WL: TWebLink; begin FLinks[FEditIndex].Enabled := False; F(FEditData); FEditData := FData[FEditIndex].Clone; BtnClose.BringToFront; BtnSave.BringToFront; PnEditorPanel.Tag := NativeInt(FEditData); PnEditorPanel.HandleNeeded; PnEditorPanel.AutoSize := True; FEditor.CreateEditorForItem(Self, FData[FEditIndex], Self); PnEditorPanel.Left := 8; PnEditorPanel.Top := PaddingTop + FLinkHeight + LinksDy; if PnTop.Visible then ToWidth := ClientWidth else ToWidth := PnEditorPanel.Left + PnEditorPanel.Width + PaddingTop * 2; ToHeight := PnEditorPanel.Top + PnEditorPanel.Height + PaddingTop + WlApplyChanges.Height + PaddingTop + BtnClose.Height + PaddingTop; MoveControlTo(Self, ToWidth, adHor); MoveControlTo(Self, ToHeight, adVert); MoveControlTo(FLinks[FEditIndex], PaddingTop, adVert); for I := 0 to FLinks.Count - 1 do if I <> FEditIndex then MoveControlTo(FLinks[I], ToWidth, adHor); for I := 0 to FLabels.Count - 1 do MoveControlTo(FLabels[I], ToWidth, adHor); MoveControlTo(BvActionSeparator, ToWidth, adHor); for WL in FActionLinks do MoveControlTo(WL, ToHeight, adVert); MoveControlTo(BvEditSeparator, PnEditorPanel.Height - BvEditSeparator.Height, adVert); MoveControlTo(WlApplyChanges, ToHeight + PnTop.Height - BtnSave.Height - WlApplyChanges.Height - PaddingTop * 2, adVert); MoveControlTo(WlCancelChanges, ToHeight + PnTop.Height - BtnSave.Height - WlCancelChanges.Height - PaddingTop * 2, adVert); MoveControlTo(WlRemove, ToHeight + PnTop.Height - BtnSave.Height - WlRemove.Height - PaddingTop * 2, adVert); PnEditorPanel.Show; end; procedure TFormLinkItemSelector.SwitchToListMode; var I, ActionsTop: Integer; ToWidth, ToHeight, Left: Integer; WL: TWebLink; begin FIsEditMode := False; if FEditIndex > -1 then FLinks[FEditIndex].Enabled := True; PnEditorPanel.Hide; ToWidth := FListWidth; ToHeight := FormHeight; MoveControlTo(Self, ToWidth, adHor); MoveControlTo(Self, ToHeight, adVert); for I := 0 to FLinks.Count - 1 do begin MoveControlToIndex(FLinks[I], FLinks[I].Tag); MoveControlTo(FLinks[I], PaddingTop, adHor); Left := PaddingTop + FLinks[I].Width + PaddingTop; FLabels[I].Width := ClientWidth - PaddingTop - FLinks[I].Width - PaddingTop * 2; MoveControlToIndex(FLabels[I], FLabels[I].Tag); MoveControlTo(FLabels[I], Left, adHor); end; ActionsTop := (ToHeight - ClientHeight) + BtnClose.Top - FActionLinks[0].Height - PaddingTop + 2; MoveControlTo(BvActionSeparator, PaddingTop, adHor); MoveControlTo(BvActionSeparator, ActionsTop - 5, adVert); Left := PaddingTop; for WL in FActionLinks do begin WL.RefreshBuffer(True); MoveControlTo(WL, Left, adHor); Left := Left + WL.Width + PaddingTop; end; for WL in FActionLinks do MoveControlTo(WL, ActionsTop, adVert); MoveControlTo(BvEditSeparator, ToHeight, adVert); MoveControlTo(WlApplyChanges, ToHeight, adVert); MoveControlTo(WlCancelChanges, ToHeight, adVert); MoveControlTo(WlRemove, ToHeight, adVert); end; procedure TFormLinkItemSelector.WlApplyChangesClick(Sender: TObject); begin ApplyChanges; end; procedure TFormLinkItemSelector.WlCancelChangesClick(Sender: TObject); begin SwitchToListMode; end; procedure TFormLinkItemSelector.WlRemoveClick(Sender: TObject); var I: Integer; LinkToDelete: TWebLink; LabelToDelete: TLabel; Data: TDataObject; WL: TWebLink; begin Data := FData[FEditIndex]; if FEditor.OnDelete(Self, Data, PnEditorPanel) then begin LinkToDelete := FLinks[FEditIndex]; LinkToDelete.BringToFront; MoveControlTo(LinkToDelete, FormHeight, adVert, [aoRemove]); FLinks.Remove(LinkToDelete); LabelToDelete := FLabels[FEditIndex]; LabelToDelete.BringToFront; MoveControlTo(LabelToDelete, FormHeight, adVert, [aoRemove]); FLabels.Remove(LabelToDelete); Data.Free; FData.Delete(FEditIndex); for I := 0 to FLinks.Count - 1 do FLinks[I].Tag := I; for I := 0 to FLabels.Count - 1 do FLabels[I].Tag := I; for WL in FActionLinks do WL.Enabled := True; FEditIndex := -1; SwitchToListMode; end; end; procedure TFormLinkItemSelector.WebLinkMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FDragMode := False; FDragLink := TWebLink(Sender); FDragLink.BringToFront; FDragLabel := FLabels[FDragLink.Tag]; FDragLabel.BringToFront; FStartMousePos.X := X; FStartMousePos.Y := Y; FStartMousePos := FDragLink.ClientToScreen(FStartMousePos); FStartLinkPos := FDragLink.BoundsRect.TopLeft; FStartInfoPos := FDragLabel.BoundsRect.TopLeft; end; end; initialization FormInterfaces.RegisterFormInterface(ILinkItemSelectForm, TFormLinkItemSelector); end.
unit ProdutoRepository; interface uses BasicRepository, ProdutoVO, System.Generics.Collections, System.SysUtils, ViewGrupoVO, ViewSubgrupoVO, ObsVO; type TProdutoRepository = class(TBasicRepository) class function getProduto: TList<TProdutoVO>; class function getProdutoByIdSubGrupo(idOfSubGrupo: Integer): TList<TProdutoVO>; class function getById(idOfProduto: Integer): TProdutoVO; class function getByCodigo(codigoOfProduto: Integer): TProdutoVO; class function getByEan(eanOfProduto: string): TProdutoVO; class function getGrupo: TList<TViewGrupoVO>; class function getSubGrupoByIdGrupo(idOfGrupo: Integer): TList<TViewSubgrupoVO>; class function getSubGrupoById(idOfSubgrupo: Integer): TViewSubgrupoVO; class function getObsByIdProduto(idOfProduto: Integer): TList<TObsVO>; class procedure ObsInserir(Obs: TObsVO); end; implementation { TProdutoRepository } class function TProdutoRepository.getByCodigo( codigoOfProduto: Integer): TProdutoVO; var Filtro: string; begin Filtro:= 'CODIGO = ' + IntToStr(codigoOfProduto) + ' AND ATIVO = ' + QuotedStr('S'); Result:= ConsultarUmObjeto<TProdutoVO>(Filtro,False); end; class function TProdutoRepository.getByEan(eanOfProduto: string): TProdutoVO; var Filtro: string; begin Filtro:= 'EAN = ' + QuotedStr(eanOfProduto) + ' AND ATIVO = ' + QuotedStr('S'); Result:= ConsultarUmObjeto<TProdutoVO>(Filtro,False); end; class function TProdutoRepository.getById(idOfProduto: Integer): TProdutoVO; var Filtro: string; begin Filtro:= 'ID = ' + IntToStr(idOfProduto) + ' AND ATIVO = ' + QuotedStr('S'); Result:= ConsultarUmObjeto<TProdutoVO>(Filtro,False); end; class function TProdutoRepository.getGrupo: TList<TViewGrupoVO>; var Filtro: string; begin Filtro:= 'ID > 0 ORDER BY NOME DESC'; Result:= Consultar<TViewGrupoVO>(False,Filtro); end; class function TProdutoRepository.getObsByIdProduto( idOfProduto: Integer): TList<TObsVO>; var Filtro: string; begin Filtro:= 'ID_PRODUTO = ' + IntToStr(idOfProduto) + ' ORDER BY OBS'; Result:= Consultar<TObsVO>(False,Filtro); end; class function TProdutoRepository.getProduto: TList<TProdutoVO>; var Filtro: string; begin Filtro:= 'ID > 0 AND ATIVO = ' + QuotedStr('S') + ' AND PESAVEL = ' + QuotedStr('N'); Result:= Consultar<TProdutoVO>(False,Filtro); end; class function TProdutoRepository.getProdutoByIdSubGrupo( idOfSubGrupo: Integer): TList<TProdutoVO>; var Filtro: string; begin if idOfSubGrupo > 0 then Filtro:= 'ID_SUBGRUPO = ' + IntToStr(idOfSubGrupo) + ' AND ATIVO = ' + QuotedStr('S') + ' ORDER BY DESCRICAO_PDV DESC' else Filtro:= 'ID_SUBGRUPO > 0 AND ATIVO = ' + QuotedStr('S') + ' ORDER BY DESCRICAO_PDV DESC'; Result:= Consultar<TProdutoVO>(False,Filtro); end; class function TProdutoRepository.getSubGrupoById( idOfSubgrupo: Integer): TViewSubgrupoVO; var Filtro: string; begin Filtro:= 'ID = ' + IntToStr(idOfSubgrupo); Result:= ConsultarUmObjeto<TViewSubgrupoVO>(Filtro,False); end; class function TProdutoRepository.getSubGrupoByIdGrupo( idOfGrupo: Integer): TList<TViewSubgrupoVO>; var Filtro: string; begin if idOfGrupo > 0 then Filtro:= 'ID_GRUPO = ' + IntToStr(idOfGrupo) + ' ORDER BY NOME' else Filtro:= 'ID_GRUPO > 0 ORDER BY NOME'; Result:= Consultar<TViewSubgrupoVO>(False,Filtro); end; class procedure TProdutoRepository.ObsInserir(Obs: TObsVO); begin Obs.Id:= Inserir(Obs); end; end.
(* Maze generator in Pascal. * Joe Wingbermuehle * 2010-09-29 *) program maze; const (* Size of the maze, must be odd. *) width = 39; height = 23; type CellType = (Space, Wall); MazeType = array [0 .. width - 1, 0 .. height - 1] of CellType; var maze : MazeType; (* Initialize the maze matrix. *) procedure init_maze; var x, y : integer; begin for y := 0 to height - 1 do for x := 0 to width - 1 do maze[x, y] := Wall; end; (* Carve the maze starting at x, y. *) procedure carve_maze(x, y : integer); var x1, y1 : integer; x2, y2 : integer; dx, dy : integer; dir, cnt : integer; begin dir := random(4); cnt := 0; while cnt < 4 do begin dx := 0; dy := 0; case dir of 0: dx := 1; 1: dy := 1; 2: dx := -1; else dy := -1; end; x1 := x + dx; y1 := y + dy; x2 := x1 + dx; y2 := y1 + dy; if (x2 > 0) and (x2 < width) and (y2 > 0) and (y2 < height) and (maze[x1, y1] = Wall) and (maze[x2, y2] = Wall) then begin maze[x1, y1] := Space; maze[x2, y2] := Space; carve_maze(x2, y2); end; dir := (dir + 1) mod 4; cnt := cnt + 1; end; end; (* Generate the maze. *) procedure generate_maze; begin maze[1, 1] := Space; carve_maze(1, 1); maze[1, 0] := Space; maze[width - 2, height - 1] := Space; end; (* Show the maze. *) procedure show_maze; var x, y : integer; begin for y := 0 to height - 1 do begin for x := 0 to width - 1 do if maze[x, y] = Space then write(' ') else write('[]'); writeln(''); end; end; begin randomize; init_maze; generate_maze; show_maze; end.
unit uKat_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, StdCtrls, cxControls, cxGroupBox, cxButtons, uConsts, ibase, cxMaskEdit, cxButtonEdit, cxCheckBox; type TfrmKat_AE = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameLabel: TLabel; Name_Edit: TcxTextEdit; procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex : byte; procedure FormIniLanguage(); public ID_NAME : int64; DB_Handle : TISC_DB_HANDLE; constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce; end; implementation {$R *.dfm} constructor TfrmKat_AE.Create(AOwner:TComponent; LanguageIndex : byte); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); PLanguageIndex:= LanguageIndex; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure TfrmKat_AE.FormIniLanguage; begin NameLabel.caption:= uConsts.bs_FullName[PLanguageIndex]; OkButton.Caption:= uConsts.bs_Accept[PLanguageIndex]; CancelButton.Caption:= uConsts.bs_Cancel[PLanguageIndex]; end; procedure TfrmKat_AE.OkButtonClick(Sender: TObject); begin If (name_edit.text = '') then begin ShowMessage('Необхідно заповнити усі поля!'); exit; end; ModalResult:=mrOk; end; procedure TfrmKat_AE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmKat_AE.FormShow(Sender: TObject); begin Name_Edit.SetFocus; end; procedure TfrmKat_AE.ShortName_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then OkButton.SetFocus; end; end.
unit filter_intf; interface uses AppStruClasses, Forms, Classes, Ibase, Messages, Windows, Dialogs, SysUtils, MainForm, FilterPredefines, Controls, pFibDataBase, pFibDataSet, pFibQuery, Variants; type TUPFilter=class(TFMASAppModule,IFMASModule,IFMASTemporaryDataStorage,IFMASFilterControl) private KeySession:Int64; FFilterParams:TParamsContainer; WorkMainForm:TForm; PredefinedForm:TForm; function CheckExistDefValue:Boolean; public Count:Integer; procedure Run; procedure ClearTmpData; procedure OnLanguageChange(var Msg:TMessage); message FMAS_MESS_CHANGE_LANG; procedure OnGridStylesChange(var Msg:TMessage); message FMAS_MESS_CHANGE_GSTYLE; procedure SetFilterParams(FilterParams:TParamsContainer); procedure UpdateFilterControls; function GetFilterParams:TParamsContainer; {$WARNINGS OFF} destructor Destroy; override; constructor Create(AOwner: TComponent);override; {$WARNINGS ON} end; implementation uses AssociationList; { TUPFilter } {$WARNINGS OFF} function TUPFilter.CheckExistDefValue: Boolean; var LD:TpFibDataBase; LT:TpFibTransaction; CheckDS:TpFibDataSet; ShowFilter:Boolean; begin LD:=TpFibDataBase.Create(nil); LD.SQLDialect:=3; LT:=TpFibTransaction.Create(nil); LT.DefaultDatabase:=LD; LD.DefaultTransaction:=LT; LD.DefaultUpdateTransaction:=LT; LD.Handle:=TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle']))^; LT.StartTransaction; CheckDS:=TpFibDataSet.Create(nil); CheckDS.Database:=LD; CheckDS.Transaction:=LT; CheckDS.SelectSQL.Text:='select * from UP_DT_KERNELL_FILTER_DEFINE where id_order_type='+IntToStr(PInteger(self.InParams.Items['Id_order_type'])^); CheckDS.Open; ShowFilter:=false; if CheckDS.RecordCount>0 then ShowFilter:=true; LT.Commit; LD.Close; LT.Free; LD.Free; Result:=ShowFilter; end; procedure TUPFilter.ClearTmpData; var LD:TpFibDataBase; LT:TpFibTransaction; CheckDS:TpFibQuery; begin LD:=TpFibDataBase.Create(nil); LD.SQLDialect:=3; LT:=TpFibTransaction.Create(nil); LT.DefaultDatabase:=LD; LD.DefaultTransaction:=LT; LD.DefaultUpdateTransaction:=LT; LD.Handle:=TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle']))^; LT.StartTransaction; CheckDS:=TpFibQuery.Create(nil); CheckDS.Database:=LD; CheckDS.Transaction:=LT; CheckDS.SQL.Text:='DELETE FROM UP_DT_KERNELL_MOVINGS where KEY_SESSION='+IntToStr(PInt64(self.InParams.Items['KEY_SESSION'])^); CheckDS.ExecQuery; LT.Commit; LD.Close; LT.Free; LD.Free; end; constructor TUPFilter.Create(AOwner: TComponent); begin inherited Create(Aowner); end; destructor TUPFilter.Destroy; begin if self.InParams.IndexOf('ClearOnFree')>0 then begin if PInteger(self.InParams.Items['ClearOnFree'])^ =1 then self.ClearTmpData; end; if Assigned(self.WorkMainForm) then self.WorkMainForm.Free; if Assigned(self.PredefinedForm) then self.PredefinedForm.Free; if Assigned(FFilterParams) then self.FFilterParams.Free; inherited Destroy; end; {$WARNINGS ON} function TUPFilter.GetFilterParams: TParamsContainer; var FilterParams: TParamsContainer; Date_beg, Date_End, ActualDate, DATE_END_AFTER:Variant; CHECK_MMDATE_BEG_VALUE, CHECK_MMDATE_END_VALUE, CHECK_MMDATE_VALUE, CHECK_POSTSALARY_VALUE, POSTSALARY_VALUE, PCARD_VALUE, CHECK_WORKCOND_VALUE, WORKCOND_VALUE, CHECK_ID_WORK_REASON, ID_WORK_REASON, CHECK_PCARD_VALUE, CHECK_CATEGORY_VALUE, CATEGORY_VALUE, CHECK_DATE_END_AFTER:Variant; begin FilterParams:=TParamsContainer.Create(true); CHECK_PCARD_VALUE:=TFilterMainForm(WorkMainForm).CheckPrivateCard.Checked; FilterParams.Add('CHECK_PCARD_VALUE', PVariant(@CHECK_PCARD_VALUE)); CHECK_MMDATE_BEG_VALUE:=TFilterMainForm(WorkMainForm).CheckMMDateBeg.Checked; FilterParams.Add('CHECK_MMDATE_BEG_VALUE', PVariant(@CHECK_MMDATE_BEG_VALUE)); CHECK_MMDATE_END_VALUE:=TFilterMainForm(WorkMainForm).CheckMMDateEnd.Checked; FilterParams.Add('CHECK_MMDATE_END_VALUE', PVariant(@CHECK_MMDATE_END_VALUE)); CHECK_MMDATE_VALUE:=TFilterMainForm(WorkMainForm).CheckMMDate.Checked; FilterParams.Add('CHECK_MMDATE_VALUE', PVariant(@CHECK_MMDATE_VALUE)); CHECK_POSTSALARY_VALUE:=TFilterMainForm(WorkMainForm).CheckPostSalary.Checked; FilterParams.Add('CHECK_POSTSALARY_VALUE', PVariant(@CHECK_POSTSALARY_VALUE)); PCARD_VALUE:=TFilterMainForm(WorkMainForm).PCardValue.Value; FilterParams.Add('PCARD_VALUE', PVariant(@PCARD_VALUE)); Date_beg:=TFilterMainForm(WorkMainForm).MMDateBeg.Value; FilterParams.Add('MMDATE_BEG_VALUE', PVariant(@Date_beg)); Date_end:=TFilterMainForm(WorkMainForm).MMDateEnd.Value; FilterParams.Add('MMDATE_END_VALUE', PVariant(@Date_end)); ActualDate:=TFilterMainForm(WorkMainForm).MMDate.Value; FilterParams.Add('MMDATE_VALUE', PVariant(@ActualDate)); POSTSALARY_VALUE:=TFilterMainForm(WorkMainForm).PostSalaryValue.Value; FilterParams.Add('POSTSALARY_VALUE', PVariant(@POSTSALARY_VALUE)); CHECK_WORKCOND_VALUE:=TFilterMainForm(WorkMainForm).CheckWorkCond.Checked; FilterParams.Add('CHECK_WORKCOND_VALUE', PVariant(@CHECK_WORKCOND_VALUE)); WORKCOND_VALUE:=TFilterMainForm(WorkMainForm).WorkCondValue.Value; FilterParams.Add('WORKCOND_VALUE', PVariant(@WORKCOND_VALUE)); CHECK_ID_WORK_REASON:=TFilterMainForm(WorkMainForm).CheckWorkReason.Checked; FilterParams.Add('CHECK_ID_WORK_REASON', PVariant(@CHECK_ID_WORK_REASON)); ID_WORK_REASON:=TFilterMainForm(WorkMainForm).WorkReasonValue.Value; FilterParams.Add('ID_WORK_REASON', PVariant(@ID_WORK_REASON)); //Добавил фильтр Турчин ID_WORK_REASON:=TFilterMainForm(WorkMainForm).WorkReasonValue.Value; FilterParams.Add('CHECK_CATEGORY_VALUE', PVariant(@CHECK_CATEGORY_VALUE)); ID_WORK_REASON:=TFilterMainForm(WorkMainForm).WorkReasonValue.Value; FilterParams.Add('CATEGORY_VALUE', PVariant(@CATEGORY_VALUE)); CHECK_DATE_END_AFTER:=TFilterMainForm(WorkMainForm).CheckDateEndAfter.Checked; FilterParams.Add('CHECK_DATE_END_AFTER', PVariant(@CHECK_DATE_END_AFTER)); DATE_END_AFTER:=TFilterMainForm(WorkMainForm).DateEndAfter.Value; FilterParams.Add('DATE_END_AFTER', PVariant(@DATE_END_AFTER)); //------------------------------------------------------------ {FilterParams.Add('CHECK_WORKMODE_VALUE' integer(CheckWorkMode.Checked); FilterParams.Add('WORKMODE_VALUE' WorkModeValue.Value; FilterParams.Add('CHECK_FORMPAY_VALUE' integer(CheckFormPayValue.Checked); FilterParams.Add('FORMPAY_VALUE' FormPayValue.Value; FilterParams.Add('CHECK_BUDGET_VALUE' integer(CheckBudgetValue.Checked); FilterParams.Add('BUDGET_VALUE' BudgetValue.Value; FilterParams.Add('CHECK_DEPARTMENT_VALUE' integer(CheckDepartmentValue.Checked); FilterParams.Add('DEPARTMENT_VALUE' DepartmentValue.Value; FilterParams.Add('CHECK_EXISTRATE' integer(CheckExistRate.Checked); FilterParams.Add('EXISTRATE_VALUE' ExistRateValue.Value; FilterParams.Add('CHECK_BUDGETRATE' integer(CheckBudgetRate.Checked); FilterParams.Add('BUDGETRATE_VALUE' BudgetRate.Value; FilterParams.Add('EXISTRATEDATE_VALUE' VarAsType(ExistRateDateValue.Value,varDate); FilterParams.Add('EXISTTYPERATE_VALUE' ExistTypeRateValue.ItemIndex; //FilterParams.Add('EXISTPERCENT_RATE_VALUE').Value :=null; //FilterParams.Add('EXISTSUM_RATE_VALUE').Value :=null; FilterParams.Add('CHECK_NOTEXISTSRATE').Value :=integer(CheckNotExistsRate.Checked); FilterParams.Add('NOTEXISTRATE_VALUE').Value :=NotExistRateValue.Value; FilterParams.Add('NOTEXISTRATEDATE_VALUE').Value :=VarAsType(NotExistRateDateValue.Value,varDate); FilterParams.Add('NOTEXISTTYPERATE_VALUE').Value :=NotExistTypeRateValue.ItemIndex; FilterParams.Add('NOTEXISTSUM_RATE_VALUE').Value :=null; FilterParams.Add('NOTEXISTPERCENT_RATE_VALUE').Value:=null; FilterParams.Add('CHECK_IS_MAIN_VALUE').Value :=Integer(CheckIsMain.Checked); FilterParams.Add('IS_MAIN_VALUE').Value :=IsMainValue.ItemIndex; FilterParams.Add('CHECK_CATEGORY_VALUE').Value :=integer(CheckCategory.Checked); FilterParams.Add('CATEGORY_VALUE').Value :=CategoryValue.Value; FilterParams.Add('CHECK_SEX_VALUE').Value :=CheckSex.Checked; FilterParams.Add('SEX_VALUE').Value :=SexValue.Value; FilterParams.Add('CHECK_ID_MAN').Value :=CheckIdMen.Checked; FilterParams.Add('ID_MEN').Value :=ManValue.Value; FilterParams.Add('CHECK_CHILD_DEPARTMENT').Value :=Integer(CHECK_CHILD_DEPARTMENT.Checked); FilterParams.Add('CHECK_STAJ_VALUE').Value :=Integer(CheckStaj.Checked); FilterParams.Add('ID_STAJ_VALUE').Value :=TypeStajValue.Value; FilterParams.Add('STAJ_VALUE_MIN').Value :=StajValueMin.Value; FilterParams.Add('STAJ_VALUE_MAX').Value :=StajValueMax.Value; FilterParams.Add('STAJ_DATE').Value :=VarAsType(StajDate.Value,varDate); FilterParams.Add('CHECK_RATES').Value :=Integer(CheckRates.Checked); FilterParams.Add('RATE_MIN').Value :=RateMinValue.Value; FilterParams.Add('RATE_MAX').Value :=RateMaxValue.Value; FilterParams.Add('IS_IN_SOVM').Value :=Integer(cxIsInSovm.Checked); FilterParams.Add('IS_EXT_SOVM').Value :=Integer(cxIsExtSovm.Checked); FilterParams.Add('check_post_razr').Value :=Integer(CheckPostRazr.Checked); FilterParams.Add('post_razr').Value :=PostRazr.Value; FilterParams.Add('check_post_sum').Value :=Integer(CheckPostSum.Checked); FilterParams.Add('min_post_sum').Value :=MinPostSumValue.Value; FilterParams.Add('max_post_sum').Value :=MaxPostSumValue.Value;} Result :=FilterParams; end; procedure TUPFilter.OnGridStylesChange(var Msg: TMessage); begin //Для будущей реализации end; procedure TUPFilter.OnLanguageChange(var Msg: TMessage); begin //Для будущей реализации end; procedure TUPFilter.Run; begin self.KeySession:=PInt64(self.InParams.Items['KEY_SESSION'])^; if self.CheckExistDefValue then begin if not Assigned(PredefinedForm) then begin PredefinedForm:=TfrmGetFilterPredefine.Create(TComponent(self.InParams.Items['AOwner']^), TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle']))^, PInteger(self.InParams.Items['Id_order_type'])^); end; if Assigned(PredefinedForm) then begin if PredefinedForm.ShowModal=mrYes then begin if not Assigned(WorkMainForm) then begin WorkMainForm:=TFilterMainForm.Create(TComponent(self.InParams.Items['AOwner']^), TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle'])^), PInteger(self.InParams.Items['Id_User'])^, PInt64(self.InParams.Items['KEY_SESSION'])^, PInteger(self.InParams.Items['Id_order_type'])^, TfrmGetFilterPredefine(PredefinedForm).id_predefine); end; if Assigned(WorkMainForm) then WorkMainForm.ShowModal; self.Count:=TFilterMainForm(WorkMainForm).Count; end; end; end else begin if not Assigned(WorkMainForm) then begin WorkMainForm:=TFilterMainForm.Create(TComponent(self.InParams.Items['AOwner']^), TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle'])^), PInteger(self.InParams.Items['Id_User'])^, PInt64(self.InParams.Items['KEY_SESSION'])^, PInteger(self.InParams.Items['Id_order_type'])^, -1); UpdateFilterControls; end; if Assigned(WorkMainForm) then WorkMainForm.ShowModal; self.Count:=TFilterMainForm(WorkMainForm).Count; end; self.OutParams['Count']:=PInteger(@self.Count); end; procedure TUPFilter.SetFilterParams(FilterParams: TParamsContainer); begin self.FFilterParams:=FilterParams; end; procedure TUPFilter.UpdateFilterControls; var InfoDS:TpFibDataSet; begin if Assigned(FFilterParams) then begin InfoDS:=TpFibDataSet.Create(nil); InfoDS.Database:=TFilterMainForm(WorkMainForm).WorkDatabase; InfoDS.Transaction:=TFilterMainForm(WorkMainForm).ReadTransaction; if (FFilterParams.Items['CHECK_PCARD_VALUE']<>nil) and (FFilterParams.Items['PCARD_VALUE']<>nil) then begin InfoDS.SelectSQL.Text:='select first 1 id_pcard from private_cards where tn='+IntToStr(PVariant(FFilterParams.Items['PCARD_VALUE'])^); InfoDS.Open; if InfoDS.RecordCount>0 then begin TFilterMainForm(WorkMainForm).PCardValue.Value:=InfoDS.FieldByName('id_pcard').Value; TFilterMainForm(WorkMainForm).PCardValue.DisplayText:=PVariant(FFilterParams.Items['PCARD_VALUE'])^; TFilterMainForm(WorkMainForm).CheckPrivateCard.Checked:=PVariant(FFilterParams.Items['CHECK_PCARD_VALUE'])^; end; InfoDS.Close; end; if (FFilterParams.Items['CHECK_ID_WORK_REASON']<>nil) and (FFilterParams.Items['ID_WORK_REASON']<>nil) then begin InfoDS.SelectSQL.Text:='select * from asup_ini_work_reason where id_work_reason='+IntToStr(PVariant(FFilterParams.Items['ID_WORK_REASON'])^); InfoDS.Open; if InfoDS.RecordCount>0 then begin TFilterMainForm(WorkMainForm).WorkReasonValue.Value:=PVariant(FFilterParams.Items['ID_WORK_REASON'])^; TFilterMainForm(WorkMainForm).WorkReasonValue.DisplayText:=InfoDS.FieldByName('name_full').Value; TFilterMainForm(WorkMainForm).CheckWorkReason.Checked:=PVariant(FFilterParams.Items['CHECK_ID_WORK_REASON'])^; end; InfoDS.Close; end; // Добавил Турчин if (FFilterParams.Items['CHECK_CATEGORY_VALUE']<>nil) and (FFilterParams.Items['CATEGORY_VALUE']<>nil) then begin InfoDS.SelectSQL.Text:='select * from SP_TYPE_POST where id_type_post='+IntToStr(PVariant(FFilterParams.Items['CATEGORY_VALUE'])^); InfoDS.Open; if InfoDS.RecordCount>0 then begin TFilterMainForm(WorkMainForm).CATEGORYValue.Value:=PVariant(FFilterParams.Items['CATEGORY_VALUE'])^; TFilterMainForm(WorkMainForm).CATEGORYValue.DisplayText:=InfoDS.FieldByName('NAME_TYPE_POST').Value; TFilterMainForm(WorkMainForm).CheckCATEGORY.Checked:=PVariant(FFilterParams.Items['CHECK_CATEGORY_VALUE'])^; end; InfoDS.Close; end; //---------------------------------------------------- if (FFilterParams.Items['CHECK_MMDATE_VALUE']<>nil) and (FFilterParams.Items['MMDATE_VALUE']<>nil) then begin TFilterMainForm(WorkMainForm).MMDate.Value:=VarToDateTime(PVariant(FFilterParams.Items['MMDATE_VALUE'])^); TFilterMainForm(WorkMainForm).CheckMMDate.Checked:=PVariant(FFilterParams.Items['CHECK_MMDATE_VALUE'])^; end; if (FFilterParams.Items['CHECK_DATE_END_AFTER']<>nil) and (FFilterParams.Items['DATE_END_AFTER']<>nil) then begin TFilterMainForm(WorkMainForm).DateEndAfter.Value:=VarToDateTime(PVariant(FFilterParams.Items['DATE_END_AFTER'])^); TFilterMainForm(WorkMainForm).CheckDateEndAfter.Checked:=PVariant(FFilterParams.Items['CHECK_DATE_END_AFTER'])^; end; InfoDS.Free; end; end; initialization //Регистрация класса в глобальном реестре RegisterAppModule(TUPFilter,'up_filter'); end.
unit Files.MMF; //------------------------------------------------------------------------------ // модуль реализует управление отображаемыми в память файлами //------------------------------------------------------------------------------ // в конструкторе задаются: // AFileName - имя файла // ARecordSize - размер записи файла (не может быть 0) // AReadOnly - открыть файл в режиме "только чтение" // // *** поддерживается оператор IN для типизированных указателей *** // // свойство Length - текущее количество элементов массива (эквивалент System.Length()) // - не доступно для записи для файлов "только чтение" // - !!!ВАЖНО!!! если при задании размера возникла исключительная ситуация // то файлы останутся неотображёнными (используйте ReMap()) // // свойство Item (свойство по умолчанию) - возвращает указатель по индексу // // *** !!! критически важно !!! *** // изменение свойсва Length повлечёт переотображение файла; // таким образом указатели станут недействительны //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, Windows, Math, UFiles; // GetFileSize //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! класс MMF //------------------------------------------------------------------------------ TMMFile = class private //! FRecordSize: Integer; //! FReadOnly: Boolean; //! FFileHandle: THandle; //! FMMHandle: THandle; //! FMapAddr: System.PByte; //! FLength: Integer; //! procedure Map(); //! procedure UnMap(); //! procedure SetLength( Value: Integer ); //! function GetItem( Index: Integer ): Pointer; public //! {! AFileName - имя файла ARecordSize - размер записи файла (не может быть 0) AReadOnly - открыть файл в режиме "только чтение" } constructor Create( const AFileName: string; const ARecordSize: Integer; const AReadOnly: Boolean ); //! destructor Destroy(); override; //! procedure ReMap(); //! property Length: Integer read FLength write SetLength; //! property Item[Index: Integer]: Pointer read GetItem; default; public type TMMFileEnumerator = class private FMMFile: TMMFile; FRef: System.PByte; FIdx: Integer; function GetCurrent(): Pointer; inline; public constructor Create(AMMFile: TMMFile); property Current: Pointer read GetCurrent; function MoveNext(): Boolean; inline; end; public //! function GetEnumerator(): TMMFileEnumerator; end; //------------------------------------------------------------------------------ implementation resourcestring RCWrongRecordSize = 'Размер записи некорректен'; RCNotMultiple = 'Размер файла не кратен размеру записи'; RCTooLarge = 'Количество записей в файле превышает 2147483647'; RCNoLengthChange = 'В режиме "только чтение" изменение количества записей невозможно'; RCWrongRecordCount = 'Запрошенное количество записей некорректно'; RCWrongIndex = 'Запрошенный индекс записи некорректен'; //------------------------------------------------------------------------------ // TMMFile //------------------------------------------------------------------------------ constructor TMMFile.Create( const AFileName: string; const ARecordSize: Integer; const AReadOnly: Boolean ); var //! Div64, Mod64: UInt64; //------------------------------------------------------------------------------ begin inherited Create(); // FRecordSize := ARecordSize; FReadOnly := AReadOnly; // if (ARecordSize <= 0) then raise Exception.CreateRes(@RCWrongRecordSize); if AReadOnly and (not FileExists(AFileName)) then Exit; // не создавать пустой ReadOnly файл FFileHandle := CreateFile( PChar(AFileName), IfThen(AReadOnly, GENERIC_READ, GENERIC_READ or GENERIC_WRITE), FILE_SHARE_READ or FILE_SHARE_DELETE, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ); if (FFileHandle = INVALID_HANDLE_VALUE) then RaiseLastOSError(); DivMod(TFileHandler.GetFileSize(AFileName), ARecordSize, Div64, Mod64); if (Mod64 <> 0) then raise Exception.CreateRes(@RCNotMultiple); if (Div64 > MaxInt) then raise Exception.CreateRes(@RCTooLarge); FLength := Div64; Map(); end; destructor TMMFile.Destroy(); begin UnMap(); CloseHandle(FFileHandle); // inherited Destroy(); end; procedure TMMFile.ReMap(); begin UnMap(); Map(); end; procedure TMMFile.Map(); begin if (FLength = 0) then Exit; FMMHandle := CreateFileMapping(FFileHandle, nil, IfThen(FReadOnly, PAGE_READONLY, PAGE_READWRITE), 0, 0, nil); if (FMMHandle = 0) then RaiseLastOSError(); FMapAddr := MapViewOfFile(FMMHandle, IfThen(FReadOnly, FILE_MAP_READ, FILE_MAP_WRITE), 0, 0, 0); if not Assigned(FMapAddr) then RaiseLastOSError(); end; procedure TMMFile.UnMap(); begin UnmapViewOfFile(FMapAddr); FMapAddr := nil; CloseHandle(FMMHandle); FMMHandle := 0; end; procedure TMMFile.SetLength( Value: Integer ); var //! OldLength: Integer; //------------------------------------------------------------------------------ begin OldLength := FLength; if FReadOnly then raise Exception.CreateRes(@RCNoLengthChange); if (Value < 0) then raise Exception.CreateRes(@RCWrongRecordCount); UnMap(); if not SetFilePointerEx(FFileHandle, Int64(Value) * Int64(FRecordSize), nil, FILE_BEGIN) then RaiseLastOSError(); if not SetEndOfFile(FFileHandle) then RaiseLastOSError(); FLength := Value; Map(); // документация microsoft говорит что контент при расширении неопределён, так что... if (Value > OldLength) then FillChar((FMapAddr + NativeInt(OldLength) * NativeInt(FRecordSize))^, (Value - OldLength) * FRecordSize, 0); end; function TMMFile.GetItem( Index: Integer ): Pointer; begin if (Index < 0) or (Index >= FLength) then raise Exception.CreateRes(@RCWrongIndex); Result := FMapAddr + NativeInt(Index) * NativeInt(FRecordSize); end; function TMMFile.GetEnumerator(): TMMFileEnumerator; begin Result := TMMFileEnumerator.Create(Self); end; //------------------------------------------------------------------------------ // TMMFile.TKeyEnumerator //------------------------------------------------------------------------------ constructor TMMFile.TMMFileEnumerator.Create( AMMFile: TMMFile ); begin FMMFile := AMMFile; FRef := AMMFile.FMapAddr - AMMFile.FRecordSize; FIdx := AMMFile.FLength; end; function TMMFile.TMMFileEnumerator.GetCurrent(): Pointer; begin Result := FRef; end; function TMMFile.TMMFileEnumerator.MoveNext(): Boolean; begin Result := FIdx <> 0; if Result then begin FRef := FRef + FMMFile.FRecordSize; Dec(FIdx); end; end; end.
unit uUsuarioDAOClient; interface uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, Usuario; type TUsuarioDAOClient = class(TDSAdminClient) private FListCommand: TDBXCommand; FInsertCommand: TDBXCommand; FUpdateCommand: TDBXCommand; FDeleteCommand: TDBXCommand; FAtualizaAcessoCommand: TDBXCommand; FFindByLoginAndSenhaCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function List: TDBXReader; function Insert(usuario: TUsuario): Boolean; function Update(usuario: TUsuario; oldLogin: string): Boolean; function Delete(usuario: TUsuario): Boolean; function AtualizaAcesso(usuario: TUsuario): Boolean; function FindByLoginAndSenha(Login: string; Senha: string): TUsuario; end; implementation function TUsuarioDAOClient.List: TDBXReader; begin if FListCommand = nil then begin FListCommand := FDBXConnection.CreateCommand; FListCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListCommand.Text := 'TUsuarioDAO.List'; FListCommand.Prepare; end; FListCommand.ExecuteUpdate; Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TUsuarioDAOClient.Insert(usuario: TUsuario): Boolean; begin if FInsertCommand = nil then begin FInsertCommand := FDBXConnection.CreateCommand; FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsertCommand.Text := 'TUsuarioDAO.Insert'; FInsertCommand.Prepare; end; if not Assigned(usuario) then FInsertCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(usuario), True); if FInstanceOwner then usuario.Free finally FreeAndNil(FMarshal) end end; FInsertCommand.ExecuteUpdate; Result := FInsertCommand.Parameters[1].Value.GetBoolean; end; function TUsuarioDAOClient.Update(usuario: TUsuario; oldLogin: string): Boolean; begin if FUpdateCommand = nil then begin FUpdateCommand := FDBXConnection.CreateCommand; FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod; FUpdateCommand.Text := 'TUsuarioDAO.Update'; FUpdateCommand.Prepare; end; if not Assigned(usuario) then FUpdateCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(usuario), True); if FInstanceOwner then usuario.Free finally FreeAndNil(FMarshal) end end; FUpdateCommand.Parameters[1].Value.SetWideString(oldLogin); FUpdateCommand.ExecuteUpdate; Result := FUpdateCommand.Parameters[2].Value.GetBoolean; end; function TUsuarioDAOClient.Delete(usuario: TUsuario): Boolean; begin if FDeleteCommand = nil then begin FDeleteCommand := FDBXConnection.CreateCommand; FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteCommand.Text := 'TUsuarioDAO.Delete'; FDeleteCommand.Prepare; end; if not Assigned(usuario) then FDeleteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(usuario), True); if FInstanceOwner then usuario.Free finally FreeAndNil(FMarshal) end end; FDeleteCommand.ExecuteUpdate; Result := FDeleteCommand.Parameters[1].Value.GetBoolean; end; function TUsuarioDAOClient.AtualizaAcesso(usuario: TUsuario): Boolean; begin if FAtualizaAcessoCommand = nil then begin FAtualizaAcessoCommand := FDBXConnection.CreateCommand; FAtualizaAcessoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FAtualizaAcessoCommand.Text := 'TUsuarioDAO.AtualizaAcesso'; FAtualizaAcessoCommand.Prepare; end; if not Assigned(usuario) then FAtualizaAcessoCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FAtualizaAcessoCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FAtualizaAcessoCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(usuario), True); if FInstanceOwner then usuario.Free finally FreeAndNil(FMarshal) end end; FAtualizaAcessoCommand.ExecuteUpdate; Result := FAtualizaAcessoCommand.Parameters[1].Value.GetBoolean; end; function TUsuarioDAOClient.FindByLoginAndSenha(Login: string; Senha: string): TUsuario; begin if FFindByLoginAndSenhaCommand = nil then begin FFindByLoginAndSenhaCommand := FDBXConnection.CreateCommand; FFindByLoginAndSenhaCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFindByLoginAndSenhaCommand.Text := 'TUsuarioDAO.FindByLoginAndSenha'; FFindByLoginAndSenhaCommand.Prepare; end; FFindByLoginAndSenhaCommand.Parameters[0].Value.SetWideString(Login); FFindByLoginAndSenhaCommand.Parameters[1].Value.SetWideString(Senha); FFindByLoginAndSenhaCommand.ExecuteUpdate; if not FFindByLoginAndSenhaCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDBXClientCommand(FFindByLoginAndSenhaCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TUsuario(FUnMarshal.UnMarshal(FFindByLoginAndSenhaCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FFindByLoginAndSenhaCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; constructor TUsuarioDAOClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TUsuarioDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TUsuarioDAOClient.Destroy; begin FreeAndNil(FListCommand); FreeAndNil(FInsertCommand); FreeAndNil(FUpdateCommand); FreeAndNil(FDeleteCommand); FreeAndNil(FAtualizaAcessoCommand); FreeAndNil(FFindByLoginAndSenhaCommand); inherited; end; end.
unit uClassAlunoPreVenda; interface type TAlunoPreVenda = class private FIdAluno: Integer; FIdPreVenda: Integer; FQuantidadeFotos: integer; FIdProduto: Integer; FQuantidade: integer; procedure SetIdAluno(const Value: Integer); procedure SetIdPreVenda(const Value: Integer); procedure SetIdProduto(const Value: Integer); procedure SetQuantidade(const Value: integer); public property IdPreVenda : Integer read FIdPreVenda write SetIdPreVenda; property IdAluno : Integer read FIdAluno write SetIdAluno; property IdProduto : Integer read FIdProduto write SetIdProduto; property Quantidade : integer read FQuantidade write SetQuantidade; end; implementation { TAlunoPreVenda } procedure TAlunoPreVenda.SetIdAluno(const Value: Integer); begin FIdAluno := Value; end; procedure TAlunoPreVenda.SetIdPreVenda(const Value: Integer); begin FIdPreVenda := Value; end; procedure TAlunoPreVenda.SetIdProduto(const Value: Integer); begin FIdProduto := Value; end; procedure TAlunoPreVenda.SetQuantidade(const Value: integer); begin FQuantidade := Value; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, uPSComponent; type { TPascalScriptEvalForm } TPascalScriptEvalForm = class(TForm) BtnCompileAndRun: TButton; ScriptText: TMemo; ResultText: TMemo; PSScript1: TPSScript; procedure BtnCompileAndRunClick(Sender: TObject); procedure PSScript1Compile(Sender: TPSScript); private { private declarations } public { public declarations } end; var MainForm1: TPascalScriptEvalForm; implementation {$R *.lfm} { TPascalScriptEvalForm } procedure MyWriteln(const s: string); begin ShowMessage(s); end; procedure TPascalScriptEvalForm.PSScript1Compile(Sender: TPSScript); begin // スクリプトからアクセスできる関数を定義する. Sender.AddFunction(@MyWriteln, 'procedure ShowMessage(s: string);'); end; // https://github.com/remobjects/pascalscript/blob/master/Samples/RemObjects%20SDK%20Client/fMain.pas procedure TPascalScriptEvalForm.BtnCompileAndRunClick(Sender: TObject); procedure OutputMessages; var l: Longint; begin for l := 0 to PSScript1.CompilerMessageCount - 1 do begin ResultText.Lines.Add('Compiler: '+ PSScript1.CompilerErrorToStr(l)); end; end; begin ResultText.Lines.Clear; PSScript1.Script.Assign(ScriptText.Lines); ResultText.Lines.Add('Compiling'); if PSSCript1.Compile then begin OutputMessages; ResultText.Lines.Add('Compiled succesfully'); if not PSScript1.Execute then begin ScriptText.SelStart := PSScript1.ExecErrorPosition; ResultText.Lines.Add(PSScript1.ExecErrorToString + ' at ' + Inttostr(PSScript1.ExecErrorProcNo) + '.' + Inttostr(PSScript1.ExecErrorByteCodePosition)); end else ResultText.Lines.Add('Succesfully executed'); end else begin OutputMessages; ResultText.Lines.Add('Compiling failed'); end; end; end.
unit ModOpTest; interface uses DUnitX.TestFramework, uIntXLibTypes, uIntX; type [TestFixture] TModOpTest = class(TObject) public [Test] procedure Simple(); [Test] procedure Neg(); [Test] procedure Zero(); procedure ZeroException(); [Test] procedure CallZeroException(); [Test] procedure Big(); [Test] procedure BigDec(); [Test] procedure BigDecNeg(); end; implementation [Test] procedure TModOpTest.Simple(); var int1, int2: TIntX; begin int1 := 16; int2 := 5; Assert.IsTrue(int1 mod int2 = 1); end; [Test] procedure TModOpTest.Neg(); var int1, int2: TIntX; begin int1 := -16; int2 := 5; Assert.IsTrue(int1 mod int2 = -1); int1 := 16; int2 := -5; Assert.IsTrue(int1 mod int2 = 1); int1 := -16; int2 := -5; Assert.IsTrue(int1 mod int2 = -1); end; [Test] procedure TModOpTest.Zero(); var int1, int2: TIntX; begin int1 := 0; int2 := 25; Assert.IsTrue(int1 mod int2 = 0); int1 := 0; int2 := -25; Assert.IsTrue(int1 mod int2 = 0); int1 := 16; int2 := 25; Assert.IsTrue(int1 mod int2 = 16); int1 := -16; int2 := 25; Assert.IsTrue(int1 mod int2 = -16); int1 := 16; int2 := -25; Assert.IsTrue(int1 mod int2 = 16); int1 := -16; int2 := -25; Assert.IsTrue(int1 mod int2 = -16); int1 := 50; int2 := 25; Assert.IsTrue(int1 mod int2 = 0); int1 := -50; int2 := -25; Assert.IsTrue(int1 mod int2 = 0); end; procedure TModOpTest.ZeroException(); var int1, int2: TIntX; begin int1 := 1; int2 := 0; int1 := int1 mod int2; end; [Test] procedure TModOpTest.CallZeroException(); var TempMethod: TTestLocalMethod; begin TempMethod := ZeroException; Assert.WillRaise(TempMethod, EDivByZero); end; [Test] procedure TModOpTest.Big(); var temp1, temp2, tempM: TIntXLibUInt32Array; int1, int2, intM: TIntX; begin SetLength(temp1, 4); temp1[0] := 0; temp1[1] := 0; temp1[2] := $80000000; temp1[3] := $7FFFFFFF; SetLength(temp2, 3); temp2[0] := 1; temp2[1] := 0; temp2[2] := $80000000; SetLength(tempM, 3); tempM[0] := 2; tempM[1] := $FFFFFFFF; tempM[2] := $7FFFFFFF; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); intM := TIntX.Create(tempM, False); Assert.IsTrue(int1 mod int2 = intM); end; [Test] procedure TModOpTest.BigDec(); var int1, int2: TIntX; begin int1 := TIntX.Create('100000000000000000000000000000000000000000000'); int2 := TIntX.Create('100000000000000000000000000000000000000000'); Assert.IsTrue(int1 mod int2 = 0); end; [Test] procedure TModOpTest.BigDecNeg(); var int1, int2: TIntX; begin int1 := TIntX.Create('-100000000000000000000000000000000000000000001'); int2 := TIntX.Create('100000000000000000000000000000000000000000'); Assert.IsTrue(int1 mod int2 = -1); end; initialization TDUnitX.RegisterTestFixture(TModOpTest); end.
// // Generated by JavaToPas v1.5 20180804 - 082349 //////////////////////////////////////////////////////////////////////////////// unit java.util.Date; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.time.chrono.ChronoLocalDate; type JDate = interface; JDateClass = interface(JObjectClass) ['{9B883261-5119-41F8-BE6A-A25A2405E924}'] function UTC(year : Integer; month : Integer; date : Integer; hrs : Integer; min : Integer; sec : Integer) : Int64; deprecated; cdecl;// (IIIIII)J A: $9 function after(when : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1 function before(when : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1 function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1 function compareTo(anotherDate : JDate) : Integer; cdecl; // (Ljava/util/Date;)I A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function from(instant : JInstant) : JDate; cdecl; // (Ljava/time/Instant;)Ljava/util/Date; A: $9 function getDate : Integer; deprecated; cdecl; // ()I A: $1 function getDay : Integer; deprecated; cdecl; // ()I A: $1 function getHours : Integer; deprecated; cdecl; // ()I A: $1 function getMinutes : Integer; deprecated; cdecl; // ()I A: $1 function getMonth : Integer; deprecated; cdecl; // ()I A: $1 function getSeconds : Integer; deprecated; cdecl; // ()I A: $1 function getTime : Int64; cdecl; // ()J A: $1 function getTimezoneOffset : Integer; deprecated; cdecl; // ()I A: $1 function getYear : Integer; deprecated; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function init : JDate; cdecl; overload; // ()V A: $1 function init(date : Int64) : JDate; cdecl; overload; // (J)V A: $1 function init(s : JString) : JDate; deprecated; cdecl; overload; // (Ljava/lang/String;)V A: $1 function init(year : Integer; month : Integer; date : Integer) : JDate; deprecated; cdecl; overload;// (III)V A: $1 function init(year : Integer; month : Integer; date : Integer; hrs : Integer; min : Integer) : JDate; deprecated; cdecl; overload;// (IIIII)V A: $1 function init(year : Integer; month : Integer; date : Integer; hrs : Integer; min : Integer; sec : Integer) : JDate; deprecated; cdecl; overload;// (IIIIII)V A: $1 function parse(s : JString) : Int64; deprecated; cdecl; // (Ljava/lang/String;)J A: $9 function toGMTString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1 function toInstant : JInstant; cdecl; // ()Ljava/time/Instant; A: $1 function toLocaleString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure setDate(date : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setHours(hours : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setMinutes(minutes : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setMonth(month : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setSeconds(seconds : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setTime(time : Int64) ; cdecl; // (J)V A: $1 procedure setYear(year : Integer) ; deprecated; cdecl; // (I)V A: $1 end; [JavaSignature('java/util/Date')] JDate = interface(JObject) ['{2C99C323-8C1D-40B2-B059-53401DAD0A3F}'] function after(when : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1 function before(when : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1 function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1 function compareTo(anotherDate : JDate) : Integer; cdecl; // (Ljava/util/Date;)I A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getDate : Integer; deprecated; cdecl; // ()I A: $1 function getDay : Integer; deprecated; cdecl; // ()I A: $1 function getHours : Integer; deprecated; cdecl; // ()I A: $1 function getMinutes : Integer; deprecated; cdecl; // ()I A: $1 function getMonth : Integer; deprecated; cdecl; // ()I A: $1 function getSeconds : Integer; deprecated; cdecl; // ()I A: $1 function getTime : Int64; cdecl; // ()J A: $1 function getTimezoneOffset : Integer; deprecated; cdecl; // ()I A: $1 function getYear : Integer; deprecated; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function toGMTString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1 function toInstant : JInstant; cdecl; // ()Ljava/time/Instant; A: $1 function toLocaleString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure setDate(date : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setHours(hours : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setMinutes(minutes : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setMonth(month : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setSeconds(seconds : Integer) ; deprecated; cdecl; // (I)V A: $1 procedure setTime(time : Int64) ; cdecl; // (J)V A: $1 procedure setYear(year : Integer) ; deprecated; cdecl; // (I)V A: $1 end; TJDate = class(TJavaGenericImport<JDateClass, JDate>) end; implementation end.
unit PaymentCountUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, StdCtrls, cxDropDownEdit, cxEditRepositoryItems, cxCalendar, cxMRUEdit, cxProgressBar, cxLookAndFeelPainters, cxButtons, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc,IBase, cxLabel, cxDBLabel,cxButtonEdit,Unit_PaymentCountConsts, ZMessages,PackageLoad, ComCtrls, pFIBErrorHandler, FIB,dmPaymentCount, uNotPassedOrdersList,ZProc,uCountListForm; {Если AccountType=1-то это обычный расчет, если AccountType=2 то это срочный расчет } function StartPaymentCount(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE; AccountType:Integer):Variant;stdcall; exports StartPaymentCount; type TPaymentCountForm = class(TForm) PageControl: TPageControl; ParamInputPage: TTabSheet; cxEditRepository1: TcxEditRepository; MonthBoxRepository: TcxEditRepositoryComboBoxItem; CountProcessPage: TTabSheet; CountProgressBar: TcxProgressBar; StartBtn: TcxButton; PeopleDataSet: TpFIBDataSet; NextBtn: TcxButton; CancelBtn: TcxButton; ConvertQuery: TpFIBDataSet; ConvertQueryKOD_SETUP: TFIBIntegerField; PeopleDataSource: TDataSource; StatusGroupBox: TGroupBox; FamiliaCaption: TLabel; ManDBLabel: TcxDBLabel; TnLabel: TLabel; TnDbLabel: TcxDBLabel; ManSelectBox: TGroupBox; ManEdit: TcxButtonEdit; GetCurPeriod: TpFIBQuery; GetGroupQuery: TpFIBQuery; GetMonthBoundsQuery: TpFIBQuery; ClearTmpProc: TpFIBStoredProc; UVProc: TpFIBStoredProc; AllPeopleBtn: TRadioButton; ManSelBtn: TRadioButton; PeopleDataSetOUT_FAMILIA: TFIBStringField; PeopleDataSetOUT_TN: TFIBIntegerField; PeopleDataSetID_MAN: TFIBIntegerField; { procedure NextBtnClick(Sender: TObject); procedure StartBtnClick(Sender: TObject); procedure ManEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AllPeopleBtnClick(Sender: TObject); procedure ManSelBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject);} private { Private declarations } public { constructor Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);reintroduce;} end; var PaymentCountForm: TPaymentCountForm; Year: Integer; Month: Integer; KodSetup2:Integer; DateBeg: TDate; DateEnd: TDate; IdMan : Integer; KodSetup1: Integer; implementation {$R *.dfm} function StartPaymentCount(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE; AccountType:Integer):Variant;stdcall; var {form:TPaymentCountForm;} form:TCountListForm; begin { form:=TPaymentCountForm.Create(AOwner,DB_HANDLE);} form:=TCountListForm.Create(AOwner,DB_HANDLE,AccountType); form.Show; { form.Free;} { StartPaymentCount:=null;} end; {procedure TPaymentCountForm.NextBtnClick(Sender: TObject); var S:String; form:TNotPassedOrdersForm; begin CountProcessPage.TabVisible:=True; PageControl.ActivePage:=CountProcessPage; MainDm.ReadTransaction.StartTransaction; GetCurPeriod.ExecQuery; MainDM.ReadTransaction.Commit; MainDm.CheckOrdersDataSet.Open; if ( not MainDm.CheckOrdersDataSet.IsEmpty) then begin ZShowMessage('Попередження', 'Знайдено непераді накази!',mtInformation,[mbOk]); form:=TNotPassedOrdersForm.Create(Self); if (form.ShowModal=mrCancel) then Self.ModalResult:=mrCancel; end; Year:=GetCurPeriod['Year_Set'].Value; Month:=GetCurPeriod['Month_Set'].Value; GetMonthBoundsQuery.Params.ParamByName('YEAR').Value:=Year; GetMonthBoundsQuery.Params.ParamByName('MONTH').Value:=Month; MainDm.ReadTransaction.StartTransaction; GetMonthBoundsQuery.ExecQuery; MainDM.ReadTransaction.Commit; DateBeg:=GetMonthBoundsQuery['MONTH_BEG'].value; DateEnd:=GetMonthBoundsQuery['MONTH_END'].value; S:=DateToStr(DateBeg); ConvertQuery.ParamByName('DATE_IN').Value:=S; ConvertQuery.Open; KodSetup1:=ConvertQuery['KOD_SETUP']; KodSetup2:=KodSetup1; end; constructor TPaymentCountForm.Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE); begin inherited Create(AOwner); MainDm:=TMainDm.Create(Self); MainDm.MainDataBase.Connected:=False; MainDm.MainDatabase.Handle:=DB_HANDLE; MainDm.ReadTransaction.StartTransaction; CountProcessPage.TabVisible:=False; Self.Caption:=FormCaption; Self.ParamInputPage.Caption:=ParamTabCaption; Self.CountProcessPage.Caption:=ProcesssTabCaption; Self.ManSelectBox.Caption:=ManBoxCaption; Self.NextBtn.Caption:=NextButtonCaption; Self.CancelBtn.Caption:=CancelButtonCaption; Self.StatusGroupBox.Caption:=StatusBoxCaption; Self.FamiliaCaption.Caption:=FamiliaLabelCaption; Self.TnLabel.Caption:=TnCaption; Self.StartBtn.Caption:=StartButtonCaption; Self.AllPeopleBtn.Caption:=AllPeopleBtnCaption; IdMan:=-1; end; procedure TPaymentCountForm.StartBtnClick(Sender: TObject); Var ManTotal: Integer; IdGroupAccount: Integer; begin ZProc.SetBeginAction(MainDm.MainDatabase.Handle,1); ClearTmpProc.StoredProcName:='Z_CLEAR_TMP_ACCOUNT'; GetGroupQuery.ExecQuery; IdGroupAccount:=GetGroupQuery['ID_GROUP_ACCOUNT'].value; if (IdMan<>-1)then MainDm.FillSpisokForCountQuery.ParamByName('IN_ID_MAN').value:=IdMan; MainDm.FillSpisokForCountQuery.ParamByName('DATE_BEG').Value:=DateToStr(DateBeg); MainDm.FillSpisokForCountQuery.ParamByName('DATE_END').Value:=DateToStr(DateEnd); MainDm.FillSpisokForCountQuery.ParamByName('KOD_SETUP2').Value:=KodSetup2; MainDm.WriteTransaction.StartTransaction; try MainDM.FillSpisokForCountQuery.ExecQuery; MainDm.WriteTransaction.Commit; except on E:Exception do begin ShowMessage(E.Message); MainDM.WriteTransaction.Rollback; end; end; PeopleDataSet.Open; PeopleDataSet.FetchAll; ManTotal:=PeopleDataSet.RecordCount; CountProgressBar.Properties.Max:=ManTotal; PeopleDataSet.First; TnDbLabel.Visible:=True; ManDbLabel.Visible:=True; while (not PeopleDataSet.Eof) do begin MainDm.WriteTransaction.StartTransaction; //ClearTmpProc.ExecProc; CountProc.ParamByName('DATE_BEG').Value:=DateToStr(DateBeg); CountProc.ParamByName('DATE_END').Value:=DateToStr(DateEnd); CountProc.ParamByName('ID_MAN').Value:= PeopleDataSet['ID_MAN']; CountProc.ParamByName('ID_GROUP_ACCOUNT').Value:=IdGroupAccount; CountProc.ParamByName('NIGHT_PERCENT').Value:=40; CountProc.ParamByName('KOD_SETUP_1').Value:=KodSetup1; CountProc.ParamByName('KOD_SETUP_2').Value:=KodSetup2; CountProc.ParamByName('DO_INDEX').Value:='T'; try CountProc.ExecProc; MainDM.WriteTransaction.Commit; except on E:Exception do begin ZShowMessage('Помилка!',E.Message,mtError,[mbOk]); MainDM.WriteTransaction.Rollback; end; end; PeopleDataSet.Next; Application.ProcessMessages; CountProgressBar.Position:=CountProgressBar.Position+1; end; ShowMessage('Розрахунок закінчено!'); ZProc.SetEndAction(MainDm.MainDatabase.Handle,'T'); if ZShowMessage('Фором. відомостей','Сформувати відомості?',mtConfirmation, [mbOk,mbCancel])=mrOk then begin UVProc.SQL.Text:= 'EXECUTE PROCEDURE Z_ACCOUNT_TO_TMPSHPRO 1'; MainDM.WriteTransaction.StartTransaction; try UVProc.ExecProc; except on E:Exception do begin ZShowMessage('Помилка!', E.Message,mtInformation,[mbOk]); MainDM.WriteTransaction.Rollback; Exit; end; end; MainDM.WriteTransaction.Commit; UVProc.SQL.Text:='EXECUTE PROCEDURE UV_FORMSHEET 0,1'; MainDM.WriteTransaction.StartTransaction; try UVProc.ExecProc; except on E:Exception do begin ZShowMessage('Помилка!', E.Message,mtInformation,[mbOk]); MainDM.WriteTransaction.Rollback; Exit; end; end; MainDM.WriteTransaction.Commit; ZShowMessage('Сформовано!','Відомотсті вдало сформовано!',mtInformation, [mbOk]); end; end; procedure TPaymentCountForm.ManEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var PeopleArray:Variant; begin // PeopleArray:=AllPeopleUnit.GetMan(Self,MainDm.MainDataBAse.Handle); PeopleArray:=LoadPeopleModal(self,MainDM.MainDataBase.Handle); ManEdit.Text:=PeopleArray[1]+' ' +PeopleArray[2]+' '+PeopleArray[3]; IdMan:=PeopleArray[0]; PeopleDataSet.Filter:='ID_MAN='+IntToStr(IdMan); end; procedure TPaymentCountForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if (MainDm.ReadTransaction.InTransaction) then MainDM.ReadTransaction.Commit; if (MainDM.WriteTransaction.InTransaction) then MainDM.WriteTransaction.Commit; // if MainDatabase.Connected then MainDatabase.False; // ReadTransaction.Active:=False; // ReadTransaction.Free; // WriteTransaction.Free; end; procedure TPaymentCountForm.AllPeopleBtnClick(Sender: TObject); begin IdMan:=-1; ManEdit.Enabled:=False; end; procedure TPaymentCountForm.ManSelBtnClick(Sender: TObject); begin ManEdit.Enabled:=True; end; procedure TPaymentCountForm.CancelBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end;} end.
unit untAutorMDL; interface type TAutorMDL = class private FId: Integer; FLogin: string; FNome: string; procedure SetId(const Value: Integer); procedure SetLogin(const Value: string); procedure SetNome(const Value: string); public property Id: Integer read FId write SetId; property Login: string read FLogin write SetLogin; property Nome: string read FNome write SetNome; end; implementation { TAutor } procedure TAutorMDL.SetId(const Value: Integer); begin FId := Value; end; procedure TAutorMDL.SetLogin(const Value: string); begin FLogin := Value; end; procedure TAutorMDL.SetNome(const Value: string); begin FNome := Value; end; end.
unit uCombatVet; interface type TCombatVet = Class(TObject) private FServiceBranch: String; FOIF_OEF: String; FExpirationDate: String; FEligibilityDate: String; FStatus: String; FSeperationDate: String; FDFN : String; FLocation: String; FIsEligible: Boolean; procedure ClearProperties; public procedure UpdateData; constructor Create(DFN : String); property ServiceBranch : String read FServiceBranch write FServiceBranch; property Status : String read FStatus write FStatus; property ServiceSeparationDate : String read FSeperationDate write FSeperationDate; property EligibilityDate : String read FEligibilityDate write FEligibilityDate; property ExpirationDate : String read FExpirationDate write FExpirationDate; property OEF_OIF : String read FOIF_OEF write FOIF_OEF; property Location : String read FLocation write FLocation; property IsEligible : Boolean read FIsEligible write FIsEligible; End; implementation uses ORNet, VAUtils, ORFn; { TCombatVet } procedure TCombatVet.ClearProperties; begin FServiceBranch := ''; FStatus := ''; FSeperationDate := ''; FExpirationDate := ''; FOIF_OEF := ''; end; constructor TCombatVet.Create(DFN: String); begin FDFN := DFN; UpdateData; end; procedure TCombatVet.UpdateData; begin sCallV('OR GET COMBAT VET',[FDFN]); FIsEligible := True; if RPCBrokerV.Results[0] = 'NOTCV' then begin FIsEligible := False; ClearProperties; Exit; end; FServiceBranch := Piece(RPCBrokerV.Results[0],U,2); FStatus := Piece(RPCBrokerV.Results[1],U,2); FSeperationDate := Piece(RPCBrokerV.Results[2],U,2); FExpirationDate := Piece(RPCBrokerV.Results[3],U,2); FOIF_OEF := RPCBrokerV.Results[4]; end; end.
unit MyCat.Memory.UnSafe.Row; interface uses System.SysUtils, MyCat.Net.Mysql; type // * // * Modify by zagnix // * An Unsafe implementation of Row which is backed by raw memory instead of Java objects. // * // * Each tuple has three parts: [null bit set] [values] [variable length portion] // * // * The bit set is used for null tracking and is aligned to 8-byte word boundaries. It stores // * one bit per field. // * // * In the `values` region, we store one 8-byte word per field. For fields that hold fixed-length // * primitive types, such as long, double, or int, we store the value directly in the word. For // * fields with non-primitive or variable-length values, we store a relative offset (w.r.t. the // * base address of the row) that points to the beginning of the variable-length field, and length // * (they are combined into a long). // * // * Instances of `UnsafeRow` act as pointers to row data stored in this format. // * TUnsafeRow = class(TMySQLPacket) public class function CalculateBitSetWidthInBytes(NumFields: Integer) : Integer; static; class function CalculateFixedPortionByteSize(NumFields: Integer) : Integer; static; private FBaseObject: TObject; FBaseOffset: Int64; // The number of fields in this row, used for calculating the bitset width (and in assertions) FNumFields: Integer; // The size of this row's backing data, in bytes) FSizeInBytes: Integer; // The width of the null tracking bit set, in bytes FBitSetWidthInBytes: Integer; function GetFieldOffset(Ordinal: Integer): Int64; procedure AssertIndexIsValid(Index: Integer); public // * // * Construct a new UnsafeRow. The resulting row won't be usable until `pointTo()` has been called, // * since the value returned by this constructor is equivalent to a null pointer. // * // * @param numFields the number of fields in this row // * constructor Create(NumFields: Integer); // * // * Update this UnsafeRow to point to different backing data. // * // * @param baseObject the base object // * @param baseOffset the offset within the base object // * @param sizeInBytes the size of this row's backing data, in bytes // * procedure PointTo(BaseObject: TObject; BaseOffset: Int64; SizeInBytes: Integer); overload; // * // * Update this UnsafeRow to point to the underlying byte array. // * // * @param buf byte array to point to // * @param sizeInBytes the number of bytes valid in the byte array // * procedure PointTo(Buffer: TBytes; SizeInBytes: Integer); overload; property BaseObject: TObject read FBaseObject; property BaseOffset: Int64 read FBaseOffset; property NumFields: Integer read FNumFields; property SizeInBytes: Integer read FSizeInBytes; end; // public final class UnsafeRow extends MySQLPacket { // // // ////////////////////////////////////////////////////////////////////////////// // // Public methods // ////////////////////////////////////////////////////////////////////////////// // // // // // public void setTotalSize(int sizeInBytes) { // this.sizeInBytes = sizeInBytes; // } // // public void setNotNullAt(int i) { // assertIndexIsValid(i); // BitSetMethods.unset(baseObject, baseOffset, i); // } // // // public void setNullAt(int i) { // assertIndexIsValid(i); // BitSetMethods.set(baseObject, baseOffset, i); // // To preserve row equality, zero out the value when setting the column to null. // // Since this row does does not currently support updates to variable-length values, we don't // // have to worry about zeroing out that data. // Platform.putLong(baseObject, getFieldOffset(i), 0); // } // // public void update(int ordinal, Object value) { // throw new UnsupportedOperationException(); // } // // public void setInt(int ordinal, int value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // Platform.putInt(baseObject, getFieldOffset(ordinal), value); // } // // public void setLong(int ordinal, long value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // Platform.putLong(baseObject, getFieldOffset(ordinal), value); // } // // public void setDouble(int ordinal, double value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // if (Double.isNaN(value)) { // value = Double.NaN; // } // Platform.putDouble(baseObject, getFieldOffset(ordinal), value); // } // // public void setBoolean(int ordinal, boolean value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // Platform.putBoolean(baseObject, getFieldOffset(ordinal), value); // } // // public void setShort(int ordinal, short value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // Platform.putShort(baseObject, getFieldOffset(ordinal), value); // } // // public void setByte(int ordinal, byte value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // Platform.putByte(baseObject, getFieldOffset(ordinal), value); // } // // public void setFloat(int ordinal, float value) { // assertIndexIsValid(ordinal); // setNotNullAt(ordinal); // if (Float.isNaN(value)) { // value = Float.NaN; // } // Platform.putFloat(baseObject, getFieldOffset(ordinal), value); // } // // // public boolean isNullAt(int ordinal) { // assertIndexIsValid(ordinal); // return BitSetMethods.isSet(baseObject, baseOffset, ordinal); // } // // // public boolean getBoolean(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getBoolean(baseObject, getFieldOffset(ordinal)); // } // // // public byte getByte(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getByte(baseObject, getFieldOffset(ordinal)); // } // // // public short getShort(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getShort(baseObject, getFieldOffset(ordinal)); // } // // // public int getInt(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getInt(baseObject, getFieldOffset(ordinal)); // } // // // public long getLong(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getLong(baseObject, getFieldOffset(ordinal)); // } // // // public float getFloat(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getFloat(baseObject, getFieldOffset(ordinal)); // } // // // public double getDouble(int ordinal) { // assertIndexIsValid(ordinal); // return Platform.getDouble(baseObject, getFieldOffset(ordinal)); // } // // // public UTF8String getUTF8String(int ordinal) { // if (isNullAt(ordinal)) return null; // final long offsetAndSize = getLong(ordinal); // final int offset = (int) (offsetAndSize >> 32); // final int size = (int) offsetAndSize; // return UTF8String.fromAddress(baseObject, baseOffset + offset, size); // } // public byte[] getBinary(int ordinal) { // if (isNullAt(ordinal)) { // return null; // } else { // final long offsetAndSize = getLong(ordinal); // final int offset = (int) (offsetAndSize >> 32); // final int size = (int) offsetAndSize; // final byte[] bytes = new byte[size]; // Platform.copyMemory( // baseObject, // baseOffset + offset, // bytes, // Platform.BYTE_ARRAY_OFFSET, // size // ); // return bytes; // } // } // // // // /** // * Copies this row, returning a self-contained UnsafeRow that stores its data in an internal // * byte array rather than referencing data stored in a data page. // */ // public UnsafeRow copy() { // UnsafeRow rowCopy = new UnsafeRow(numFields); // final byte[] rowDataCopy = new byte[sizeInBytes]; // Platform.copyMemory( // baseObject, // baseOffset, // rowDataCopy, // Platform.BYTE_ARRAY_OFFSET, // sizeInBytes // ); // rowCopy.pointTo(rowDataCopy, Platform.BYTE_ARRAY_OFFSET, sizeInBytes); // return rowCopy; // } // // /** // * Creates an empty UnsafeRow from a byte array with specified numBytes and numFields. // * The returned row is invalid until we call copyFrom on it. // */ // public static UnsafeRow createFromByteArray(int numBytes, int numFields) { // final UnsafeRow row = new UnsafeRow(numFields); // row.pointTo(new byte[numBytes], numBytes); // return row; // } // // /** // * Copies the input UnsafeRow to this UnsafeRow, and resize the underlying byte[] when the // * input row is larger than this row. // */ // public void copyFrom(UnsafeRow row) { // // copyFrom is only available for UnsafeRow created from byte array. // assert (baseObject instanceof byte[]) && baseOffset == Platform.BYTE_ARRAY_OFFSET; // if (row.sizeInBytes > this.sizeInBytes) { // // resize the underlying byte[] if it's not large enough. // this.baseObject = new byte[row.sizeInBytes]; // } // Platform.copyMemory( // row.baseObject, row.baseOffset, this.baseObject, this.baseOffset, row.sizeInBytes); // // update the sizeInBytes. // this.sizeInBytes = row.sizeInBytes; // } // // /** // * Write this UnsafeRow's underlying bytes to the given OutputStream. // * // * @param out the stream to write to. // * @param writeBuffer a byte array for buffering chunks of off-heap data while writing to the // * output stream. If this row is backed by an on-heap byte array, then this // * buffer will not be used and may be null. // */ // public void writeToStream(OutputStream out, byte[] writeBuffer) throws IOException { // if (baseObject instanceof byte[]) { // int offsetInByteArray = (int) (Platform.BYTE_ARRAY_OFFSET - baseOffset); // out.write((byte[]) baseObject, offsetInByteArray, sizeInBytes); // } else { // int dataRemaining = sizeInBytes; // long rowReadPosition = baseOffset; // while (dataRemaining > 0) { // int toTransfer = Math.min(writeBuffer.length, dataRemaining); // Platform.copyMemory( // baseObject, rowReadPosition, writeBuffer, Platform.BYTE_ARRAY_OFFSET, toTransfer); // out.write(writeBuffer, 0, toTransfer); // rowReadPosition += toTransfer; // dataRemaining -= toTransfer; // } // } // } // // @Override // public int hashCode() { // return Murmur3_x86_32.hashUnsafeWords(baseObject, baseOffset, sizeInBytes, 42); // } // // @Override // public boolean equals(Object other) { // if (other instanceof UnsafeRow) { // UnsafeRow o = (UnsafeRow) other; // return (sizeInBytes == o.sizeInBytes) && // ByteArrayMethods.arrayEquals(baseObject, baseOffset, o.baseObject, o.baseOffset, // sizeInBytes); // } // return false; // } // // /** // * Returns the underlying bytes for this UnsafeRow. // */ // public byte[] getBytes() { // if (baseObject instanceof byte[] && baseOffset == Platform.BYTE_ARRAY_OFFSET // && (((byte[]) baseObject).length == sizeInBytes)) { // return (byte[]) baseObject; // } else { // byte[] bytes = new byte[sizeInBytes]; // Platform.copyMemory(baseObject, baseOffset, bytes, Platform.BYTE_ARRAY_OFFSET, sizeInBytes); // return bytes; // } // } // // public static final byte NULL_MARK = (byte) 251; // public static final byte EMPTY_MARK = (byte) 0; // // @Override // public ByteBuffer write(ByteBuffer bb, FrontendConnection c, // boolean writeSocketIfFull) { // bb = c.checkWriteBuffer(bb,c.getPacketHeaderSize(),writeSocketIfFull); // BufferUtil.writeUB3(bb, calcPacketSize()); // bb.put(packetId); // for (int i = 0; i < numFields; i++) { // if (!isNullAt(i)) { // byte[] fv = this.getBinary(i); // if (fv.length == 0) { // bb = c.checkWriteBuffer(bb, 1, writeSocketIfFull); // bb.put(UnsafeRow.EMPTY_MARK); // } else { // bb = c.checkWriteBuffer(bb, BufferUtil.getLength(fv), // writeSocketIfFull); // BufferUtil.writeLength(bb, fv.length); // /** // * 把数据写到Writer Buffer中 // */ // bb = c.writeToBuffer(fv, bb); // } // } else { // //Col null value // bb = c.checkWriteBuffer(bb,1,writeSocketIfFull); // bb.put(UnsafeRow.NULL_MARK); // } // } // return bb; // } // // @Override // public int calcPacketSize() { // int size = 0; // for (int i = 0; i < numFields; i++) { // byte[] v = this.getBinary(i); // size += (v == null || v.length == 0) ? 1 : BufferUtil.getLength(v); // } // return size; // } // // public BigDecimal getDecimal(int ordinal, int scale) { // if (isNullAt(ordinal)) { // return null; // } // byte[] bytes = getBinary(ordinal); // BigInteger bigInteger = new BigInteger(bytes); // BigDecimal javaDecimal = new BigDecimal(bigInteger, scale); // return javaDecimal; // } // // /** // * update <strong>exist</strong> decimal column value to new decimal value // * // * NOTE: decimal max precision is limit to 38 // * @param ordinal // * @param value // * @param precision // */ // public void updateDecimal(int ordinal, BigDecimal value) { // assertIndexIsValid(ordinal); // // fixed length // long cursor = getLong(ordinal) >>> 32; // assert cursor > 0 : "invalid cursor " + cursor; // // zero-out the bytes // Platform.putLong(baseObject, baseOffset + cursor, 0L); // Platform.putLong(baseObject, baseOffset + cursor + 8, 0L); // // if (value == null) { // setNullAt(ordinal); // // keep the offset for future update // Platform.putLong(baseObject, getFieldOffset(ordinal), cursor << 32); // } else { // // final BigInteger integer = value.unscaledValue(); // byte[] bytes = integer.toByteArray(); // assert (bytes.length <= 16); // // // Write the bytes to the variable length portion. // Platform.copyMemory(bytes, Platform.BYTE_ARRAY_OFFSET, baseObject, baseOffset + cursor, bytes.length); // setLong(ordinal, (cursor << 32) | ((long) bytes.length)); // } // // } // // /** // public Decimal getDecimal(int ordinal, int precision, int scale) { // if (isNullAt(ordinal)) { // return null; // } // if (precision <= Decimal.MAX_LONG_DIGITS()) { // return Decimal.createUnsafe(getLong(ordinal), precision, scale); // } else { // byte[] bytes = getBinary(ordinal); // BigInteger bigInteger = new BigInteger(bytes); // BigDecimal javaDecimal = new BigDecimal(bigInteger, scale); // return Decimal.apply(javaDecimal, precision, scale); // } // } // // public void setDecimal(int ordinal, Decimal value, int precision) { // assertIndexIsValid(ordinal); // if (precision <= Decimal.MAX_LONG_DIGITS()) { // // compact format // if (value == null) { // setNullAt(ordinal); // } else { // setLong(ordinal, value.toUnscaledLong()); // } // } else { // // fixed length // long cursor = getLong(ordinal) >>> 32; // assert cursor > 0 : "invalid cursor " + cursor; // // zero-out the bytes // Platform.putLong(baseObject, baseOffset + cursor, 0L); // Platform.putLong(baseObject, baseOffset + cursor + 8, 0L); // // if (value == null) { // setNullAt(ordinal); // // keep the offset for future update // Platform.putLong(baseObject, getFieldOffset(ordinal), cursor << 32); // } else { // // final BigInteger integer = value.toJavaBigDecimal().unscaledValue(); // byte[] bytes = integer.toByteArray(); // assert(bytes.length <= 16); // // // Write the bytes to the variable length portion. // Platform.copyMemory( // bytes, Platform.BYTE_ARRAY_OFFSET, baseObject, baseOffset + cursor, bytes.length); // setLong(ordinal, (cursor << 32) | ((long) bytes.length)); // } // } // } // // */ // @Override // protected String getPacketInfo() { // return "MySQL RowData Packet"; // } // // // This is for debugging // @Override // public String toString() { // StringBuilder build = new StringBuilder("["); // for (int i = 0; i < sizeInBytes; i += 8) { // if (i != 0) build.append(','); // build.append(Long.toHexString(Platform.getLong(baseObject, baseOffset + i))); // } // build.append(']'); // return build.toString(); // } // // public boolean anyNull() { // return BitSetMethods.anySet(baseObject, baseOffset, bitSetWidthInBytes / 8); // } // // } implementation { TUnsafeRow } procedure TUnsafeRow.AssertIndexIsValid(Index: Integer); begin Assert(Index >= 0, Format('index (%d) should >= 0', [Index])); Assert(Index < FNumFields, Format('index (%d) should < %d', [Index, FNumFields])); end; class function TUnsafeRow.CalculateBitSetWidthInBytes (NumFields: Integer): Integer; begin Result := ((NumFields + 63) div 64) * 8; end; class function TUnsafeRow.CalculateFixedPortionByteSize (NumFields: Integer): Integer; begin Result := 8 * NumFields + CalculateBitSetWidthInBytes(NumFields); end; constructor TUnsafeRow.Create(NumFields: Integer); begin FNumFields := NumFields; FBitSetWidthInBytes := CalculateBitSetWidthInBytes(NumFields); end; function TUnsafeRow.GetFieldOffset(Ordinal: Integer): Int64; begin Result := FBaseOffset + FBitSetWidthInBytes + Ordinal * 8; end; procedure TUnsafeRow.PointTo(Buffer: TBytes; SizeInBytes: Integer); begin PointTo(Buffer, Platform.BYTE_ARRAY_OFFSET, SizeInBytes); end; procedure TUnsafeRow.PointTo(BaseObject: TObject; BaseOffset: Int64; SizeInBytes: Integer); begin Assert(FNumFields >= 0, Format('NumFields(%d) should >= 0', [FNumFields])); FBaseObject := BaseObject; FBaseOffset := BaseOffset; FSizeInBytes := SizeInBytes; end; end.
unit uUsuarioController; interface uses SysUtils, StrUtils, Dialogs, uUsuarioModel, uPadraoController, uPermissoesModel; type TUsuarioController = class(TPadraoController) function GravarRegistro(AUsuarioModel: TUsuarioModel): Integer; function ExcluirRegistro(ACodigo: Integer): Boolean; function GravarRegistroPermissoes(APermissoesModel: TPermissoesModel): Boolean; function ExcluirRegistroPermissoes(ACodigo: Integer): Boolean; end; implementation { TUsuarioController } function TUsuarioController.ExcluirRegistro(ACodigo: Integer): Boolean; begin Result := True; if FQuery.Active then FQuery.Close; FQuery.SQL.Text := 'DELETE FROM USUARIO WHERE CODIGO = :codigo'; FQuery.ParamByName('codigo').AsInteger := ACodigo; try FQuery.ExecSQL(); frMain.FLogController.GravaLog('Excluiu Usuário '+ ACodigo.ToString); except on E: Exception do begin Result := False; frMain.FLogController.GravaLog('Erro ao excluir Usuário '+ ACodigo.ToString); ShowMessage('Ocorreu um erro ao excluir o registro'); end; end; end; function TUsuarioController.ExcluirRegistroPermissoes( ACodigo: Integer): Boolean; begin Result := True; if FQuery.Active then FQuery.Close; FQuery.SQL.Text := 'DELETE FROM PERMISSOES WHERE USUARIO_CODIGO = :usuario_codigo'; FQuery.ParamByName('usuario_codigo').AsInteger := ACodigo; try FQuery.ExecSQL(); except on E: Exception do begin Result := False; ShowMessage('Ocorreu um erro ao excluir o registro'); end; end; end; function TUsuarioController.GravarRegistro( AUsuarioModel: TUsuarioModel): Integer; var LSQL: String; LCodigo: Integer; LInsert: Boolean; begin LInsert := AUsuarioModel.Codigo = 0; if LInsert then begin LCodigo := RetornaPrimaryKey('CODIGO', 'USUARIO'); LSQL := 'INSERT INTO USUARIO VALUES (:codigo, :nome, :administrador, :cpf, :senha, :celular)'; end else begin LCodigo := AUsuarioModel.Codigo; LSQL := 'UPDATE USUARIO SET NOME = :nome, ADMINISTRADOR = :administrador, '+ 'CPF = :cpf, SENHA = :senha, CELULAR = :celular '+ 'WHERE CODIGO = :codigo'; end; if FQuery.Active then FQuery.Close; FQuery.SQL.Text := LSQL; FQuery.ParamByName('codigo').AsInteger := LCodigo; FQuery.ParamByName('nome').AsString := AUsuarioModel.Nome; FQuery.ParamByName('administrador').AsBoolean := AUsuarioModel.Administrador; FQuery.ParamByName('cpf').AsString := AUsuarioModel.CPF; FQuery.ParamByName('senha').AsString := AUsuarioModel.Senha; FQuery.ParamByName('celular').AsString := AUsuarioModel.Celular; try FQuery.ExecSQL(); frMain.FLogController.GravaLog( IfThen(LInsert, 'Inseriu ', 'Editou ') + 'Usuário: código: ' + LCodigo.ToString + ' nome: ' + AUsuarioModel.Nome + ' cpf: ' + AUsuarioModel.CPF + ' celular: ' + AUsuarioModel.Celular); Result := LCodigo; except on E: Exception do begin Result := 0; frMain.FLogController.GravaLog( 'Erro ao '+ IfThen(LInsert, 'Inserir ', 'Editar ') + 'Usuário: código: ' + LCodigo.ToString + ' nome: ' + AUsuarioModel.Nome + ' cpf: ' + AUsuarioModel.CPF + ' celular: ' + AUsuarioModel.Celular); ShowMessage('Ocorreu um erro na inclusão do usuário.'); end; end; end; function TUsuarioController.GravarRegistroPermissoes( APermissoesModel: TPermissoesModel): Boolean; var LSQL: String; LCodigo: Integer; LInsert: Boolean; begin Result := True; LInsert := APermissoesModel.Codigo = 0; if LInsert then begin LCodigo := RetornaPrimaryKey('CODIGO', 'PERMISSOES'); LSQL := 'INSERT INTO PERMISSOES VALUES (:codigo, :usuario_codigo, ' + ':acessoautor, :acessoeditora, ' + ':acessolivro, :acessoemprestimo, '+ ':acessousuario, :acessopermissoes)'; end else begin LCodigo := APermissoesModel.Codigo; LSQL := 'UPDATE PERMISSOES SET USUARIO_CODIGO = :usuario_codigo,' + 'ACESSO_AUTOR = :acessoautor, ACESSO_EDITORA = :acessoeditora, ' + 'ACESSO_LIVRO = :acessolivro, ACESSO_EMPRESTIMO = :acessoemprestimo, '+ 'ACESSO_USUARIO = :acessousuario, ACESSO_PERMISSOES = :acessopermissoes '+ 'WHERE USUARIO_CODIGO = :usuario_codigo'; end; if FQuery.Active then FQuery.Close; FQuery.SQL.Text := LSQL; if LInsert then FQuery.ParamByName('codigo').AsInteger := LCodigo; FQuery.ParamByName('usuario_codigo').AsInteger := APermissoesModel.Usuario.Codigo; FQuery.ParamByName('acessoautor').AsBoolean := APermissoesModel.AcessoAutor; FQuery.ParamByName('acessoeditora').AsBoolean := APermissoesModel.AcessoEditora; FQuery.ParamByName('acessolivro').AsBoolean := APermissoesModel.AcessoLivro; FQuery.ParamByName('acessoemprestimo').AsBoolean := APermissoesModel.AcessoEmprestimo; FQuery.ParamByName('acessousuario').AsBoolean := APermissoesModel.AcessoUsuario; FQuery.ParamByName('acessopermissoes').AsBoolean := APermissoesModel.AcessoPermissoes; try FQuery.ExecSQL(); except on E: Exception do begin Result := False; ShowMessage('Ocorreu um erro na inclusão do usuário.'); end; end; end; end.
unit uSpTypeStrEDBO; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, ImgList, dxBar, dxBarExtItems, cxGridLevel, cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ibase, uSpTypeStrAdd, DogLoaderUnit; type TfmSpTypeStrEDBO = class(TForm) Grid: TcxGrid; GridDBView: TcxGridDBTableView; GridDBViewDB_id_type_str_edbo: TcxGridDBColumn; GridDBViewDB_name_typestr_EDBO: TcxGridDBColumn; GridLevel: TcxGridLevel; BarManager: TdxBarManager; SelButton: TdxBarLargeButton; ExitButton: TdxBarLargeButton; DisabledLargeImages: TImageList; PopupImageList: TImageList; LargeImages: TImageList; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; Default_StyleSheet: TcxGridTableViewStyleSheet; DevExpress_Style: TcxGridTableViewStyleSheet; AddButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DelButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; procedure ExitButtonClick(Sender: TObject); procedure SelButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DelButtonClick(Sender: TObject); private { Private declarations } public DB_handle : TISC_DB_HANDLE; edbo_types : integer; constructor Create(AOwner:TComponent);reintroduce; end; var fmSpTypeStrEDBO: TfmSpTypeStrEDBO; implementation uses DM_TypeStreetSynch; {$R *.dfm} constructor TfmSpTypeStrEDBO.Create(AOwner:TComponent); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); RefreshButtonClick(self); // EditButton.Visible := ivNever; Screen.Cursor:=crDefault; end; procedure TfmSpTypeStrEDBO.ExitButtonClick(Sender: TObject); begin close; end; procedure TfmSpTypeStrEDBO.SelButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfmSpTypeStrEDBO.RefreshButtonClick(Sender: TObject); begin DM.DataSetOur.Close; DM.DataSetOur.SQLs.SelectSQL.Text := 'select Name_full as StreetTypeFullName,id_type_street as Id_StreetType, name_short from ini_type_street order by Name_full'; DM.DataSetOur.Open; end; procedure TfmSpTypeStrEDBO.AddButtonClick(Sender: TObject); var ViewForm : TfmSpTypeStrAdd; locate_id : integer; begin ViewForm := TfmSpTypeStrAdd.Create(self); ViewForm.DB_handle := DM.DB.Handle; ViewForm.TextFullName.Text := ''; ViewForm.TextShortName.Text := ''; ViewForm.id_type_street := null; ViewForm.OkButton.Caption := 'Додати'; ViewForm.ShowModal; if ViewForm.ModalResult = mrOk then begin DM.StProc.StoredProcName := 'INI_TYPE_STREET_IU'; DM.WriteTransaction.StartTransaction; DM.StProc.Prepare; DM.StProc.ParamByName('ID_TYPE_STREET').AsVariant := ViewForm.id_type_street; DM.StProc.ParamByName('NAME_FULL').AsString := ViewForm.TextFullName.Text; DM.StProc.ParamByName('NAME_SHORT').AsString := ViewForm.TextShortName.Text; DM.StProc.ExecProc; locate_id := DM.StProc.ParamByName('ID_TYPE_STREET_OUT').AsInteger; try DM.WriteTransaction.Commit; except DM.WriteTransaction.Rollback; ShowMessage('Виникли помилки у работі процедури INI_TYPE_STREET_IU!'); raise; end; end; RefreshButtonClick(self); DM.DataSetOur.Locate('Id_StreetType', locate_id, []); end; procedure TfmSpTypeStrEDBO.EditButtonClick(Sender: TObject); var ViewForm : TfmSpTypeStrAdd; locate_id : integer; begin ViewForm := TfmSpTypeStrAdd.Create(self); ViewForm.DB_handle := DM.DB.Handle; ViewForm.OkButton.Caption := 'Змінити'; if(DM.DataSetOur['name_short']<> null) then ViewForm.TextShortName.Text := DM.DataSetOur['name_short'] else ViewForm.TextShortName.Text := ''; if(DM.DataSetOur['StreetTypeFullName']<> null) then ViewForm.TextFullName.Text := DM.DataSetOur['StreetTypeFullName'] else ViewForm.TextFullName.Text := ''; if DM.DataSetOur['Id_StreetType'] <> null then ViewForm.id_type_street := DM.DataSetOur['Id_StreetType'] else ViewForm.id_type_street := null; ViewForm.ShowModal; if ViewForm.ModalResult = mrOk then begin DM.StProc.StoredProcName := 'INI_TYPE_STREET_IU'; DM.WriteTransaction.StartTransaction; DM.StProc.Prepare; DM.StProc.ParamByName('ID_TYPE_STREET').AsVariant := ViewForm.id_type_street; DM.StProc.ParamByName('NAME_FULL').AsString := ViewForm.TextFullName.Text; DM.StProc.ParamByName('NAME_SHORT').AsString := ViewForm.TextShortName.Text; DM.StProc.ExecProc; DM.StProc.ExecProc; try DM.WriteTransaction.Commit; except DM.WriteTransaction.Rollback; ShowMessage('Возникли ошибки при работе процедуры INI_TYPE_STREET_IU!'); raise; end; end; locate_id := DM.DataSetOur['Id_StreetType']; RefreshButtonClick(self); DM.DataSetOur.Locate('Id_StreetType', locate_id, []); end; procedure TfmSpTypeStrEDBO.DelButtonClick(Sender: TObject); var locate_id : integer; begin if DM.DataSetOur.RecordCount = 0 then exit; if MessageDlg('Увага', 'Ви дійсно хочете видалити тип вулиці?', mtConfirmation, [mbYes, mbNo]) = mrYes then begin DM.StProc.StoredProcName := 'INI_TYPE_STREET_DEL'; DM.WriteTransaction.StartTransaction; DM.StProc.Prepare; DM.StProc.ParamByName('id_type_street').AsVariant := DM.DataSetOur['Id_StreetType']; DM.StProc.ExecProc; try Dm.WriteTransaction.Commit; except DM.WriteTransaction.Rollback; ShowMessage('Виникли помилки у роботі процедури INI_TYPE_STREET_DEL!'); raise; end; end; locate_id := DM.DataSetOur['Id_StreetType']; RefreshButtonClick(self); DM.DataSetOur.Locate('Id_StreetType', locate_id, []); end; end.
PROGRAM WG_Hash; USES {$IFDEF FPC} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Strings, WinCrt, WinGraph; CONST EF = CHR(0); (*end of file character*) maxWordLen = 30; (*max. number of characters per word*) chars = ['a' .. 'z', 'ä', 'ö', 'ü', 'ß', 'A' .. 'Z', 'Ä', 'Ö', 'Ü']; size = 421; TYPE Word = STRING[maxWordLen]; NodePtr = ^Node; Node = RECORD key: STRING; next: NodePtr; END; (*Record*) ListPtr = NodePtr; HashTable = ARRAY[0..size-1] OF ListPtr; VAR txt: TEXT; (*text file*) curLine: STRING; (*current line from file txt*) curCh: CHAR; (*current character*) curLineNr: INTEGER; (*current line number*) curColNr: INTEGER; (*current column number*) ht : HashTable; option : Integer; function NewHashNode(key: String; next: NodePtr) : NodePtr; var n: NodePtr; begin New(n); n^.key := key; n^.next := next; NewHashNode := n; end; (*NewNode*) (* returns the hashcode of a key *) function HashCode1(key: String): Integer; begin HashCode1 := Ord(key[1]) MOD size; end; (*HashCode1*) (* compiler hashcode.. *) function HashCode2(key: String): Integer; begin if Length(key) = 1 then HashCode2 := (Ord(key[1]) * 7 + 1) * 17 MOD size else HashCode2 := (Ord(key[1]) * 7 + Ord(key[2]) + Length(key)) * 17 MOD size end; (*HashCode2) (* returns the hashcode of a key *) function HashCode3(key: String): Integer; var hc, i : Integer; begin hc := 0; for i := 1 to Length(key) do begin {Q-} {R-} hc := 31 * hc + Ord(key[i]); {R+} {Q+} end; (* for *) HashCode3 := Abs(hc) MOD size; end; (*HashCode3*) (* Lookup combines search and prepend *) procedure Lookup(key: String); var i: Integer; n: NodePtr; begin IF option = 1 THEN i := HashCode1(key) ELSE IF option = 2 THEN i := HashCode2(key) ELSE IF option = 3 THEN i := HashCode3(key) ELSE BEGIN WriteLn('Invalid option'); Halt; END; n := ht[i]; while (n <> Nil) do begin if (n^.key = key) THEN BEGIN exit; end; n := n^.next; end; n := NewHashNode(key, ht[i]); ht[i] := n; end; (* Lookup *) FUNCTION LowerCase(ch: CHAR): STRING; BEGIN CASE ch OF 'A'..'Z': LowerCase := CHR(ORD(ch) + (ORD('a') - ORD('A'))); 'Ä', 'ä': LowerCase := 'ae'; 'Ö', 'ö': LowerCase := 'oe'; 'Ü', 'ü': LowerCase := 'ue'; 'ß': LowerCase := 'ss'; ELSE (*all the others*) LowerCase := ch; END; (*CASE*) END; (*LowerCase*) PROCEDURE GetNextChar; (*updates curChar, ...*) BEGIN IF curColNr < Length(curLine) THEN BEGIN curColNr := curColNr + 1; curCh := curLine[curColNr] END (*THEN*) ELSE BEGIN (*curColNr >= Length(curLine)*) IF NOT Eof(txt) THEN BEGIN ReadLn(txt, curLine); curLineNr:= curLineNr + 1; curColNr := 0; curCh := ' '; (*separate lines by ' '*) END (*THEN*) ELSE (*Eof(txt)*) curCh := EF; END; (*ELSE*) END; (*GetNextChar*) PROCEDURE GetNextWord(VAR w: Word; VAR lnr: INTEGER); BEGIN WHILE (curCh <> EF) AND NOT (curCh IN chars) DO BEGIN GetNextChar; END; (*WHILE*) lnr := curLineNr; IF curCh <> EF THEN BEGIN w := LowerCase(curCh); GetNextChar; WHILE (curCh <> EF) AND (curCh IN chars) DO BEGIN w := Concat(w , LowerCase(curCh)); GetNextChar; END; (*WHILE*) END (*THEN*) ELSE (*curCh = EF*) w := ''; END; (*GetNextWord*) (* Counts nodes *) FUNCTION CountNodes(n : ListPtr) : INTEGER; VAR count : INTEGER; BEGIN count := 0; WHILE n <> NIL DO BEGIN Inc(count); n := n^.next; END; CountNodes := count; END; (* Draw function with eclipse *) PROCEDURE Draw(table : HashTable; dc : HDC; r : TRect); VAR i, j : INTEGER; stepX : REAL; w, h : INTEGER; maxVal, count : INTEGER; x, y : REAL; hFactor : REAL; BEGIN w := r.right - r.left; h := r.bottom - r.top; count := 1; maxVal := count; FOR i := Low(table) TO High(table) DO BEGIN count := CountNodes(table[i]); IF maxVal < count THEN BEGIN maxVal := count; END; END; IF maxVal = 0 THEN BEGIN maxVal := 1; END; stepX := w / (High(table) - Low(table) + 1); hFactor := (h / stepX) / maxVal; x := r.left; count := 0; FOR i := Low(table) TO High(table) DO BEGIN count := CountNodes(table[i]); y := r.bottom; FOR j := 1 TO Round(hFactor * count) DO BEGIN Ellipse(dc, Round(x), Round(y + stepX), Round(x + stepX), Round(y)); y := y - stepX; END; x := x + stepX; END; END; (* Function to call the actual drawing function *) PROCEDURE DrawHash(dc: HDC; wnd: HWnd; r: TRect); BEGIN Draw(ht, dc, r); END; PROCEDURE Init; VAR i : INTEGER; BEGIN FOR i := 0 TO size - 1 DO BEGIN ht[i] := NIL; END; END; VAR txtName: STRING; w: Word; (*current word*) lnr: INTEGER; (*line number of current word*) n: LONGINT; (*number of words*) BEGIN option := 1; n := 0; Init(); IF ParamCount = 0 THEN BEGIN WriteLn; WriteLn; Write('name of text file > '); ReadLn(txtName); END ELSE BEGIN txtName := ParamStr(1); WriteLn(txtName); END; WriteLn; WriteLn('Choose HashFunction: '); WriteLn('1. func (bad)'); WriteLn('2. func (better)'); WriteLn('3. func (best)'); Write('> '); ReadLn(option); Assign(txt, txtName); Reset(txt); curLine := ''; curLineNr := 0; curColNr := 1; GetNextChar; GetNextWord(w, lnr); WHILE Length(w) > 0 DO BEGIN LookUp(w); n := n + 1; GetNextWord(w, lnr); END; redrawProc := DrawHash; WGMain; WriteLn; WriteLn('number of words: ', n); Close(txt); END.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit essConnectPanel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Contnrs, Math, LCLIntf, LCLType, Messages, Graphics, Controls, Forms, Dialogs, ExtCtrls, uViewIntegrator, uRtfdComponents, uLayoutConcepts, uLayoutConnector; type // Available linestyles TessConnectionStyle = (csThin, csNormal, csThinDash); //Different kinds of arrowheads TessConnectionArrowStyle = TArrowStyle; { Specifies a connection between two managed objects. } TConnection = class public FFrom, FTo: TControl; FConnectStyle: TessConnectionStyle; ArrowStyle : TessConnectionArrowStyle; end; TBasePathLayout = class; { Wrapper around a control managed by essConnectPanel } TManagedObject = class private FSelected: Boolean; procedure SetSelected(const Value: Boolean); private FControl: TControl; // Old eventhandlers FOnMouseDown :TMouseEvent; FOnMouseMove :TMouseMoveEvent; FOnMouseUp :TMouseEvent; FOnClick :TNotifyEvent; FOnDblClick :TNotifyEvent; property Selected: Boolean read FSelected write SetSelected; public destructor Destroy; override; end; { Component that manages a list of contained controls that can be connected with somekind of line and allows the user to move it around and gives the containd control grabhandles when selected. Further it manages the layout of the contained controls. } { TessConnectPanel } TessConnectPanel = class(TCustomPanel) private FIsModified, FIsMoving, FIsRectSelecting, FSelectedOnly: Boolean; FMemMousePos: TPoint; FSelectRect: TRect; FBackBitmap: TBitmap; TempHidden : TObjectList; ClientDragging: Boolean; FNeedCheckSize: Boolean; FPathLayout: TBasePathLayout; FPathStyle :TPathLayoutStyle; procedure SetPathStyle(AValue:TPathLayoutStyle); procedure SetSelectedOnly(const Value : boolean); protected FManagedObjects: TList; FConnections: TObjectList; procedure CreateParams(var Params: TCreateParams); override; procedure Click; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; function FindManagedControl( AControl: TControl ): TManagedObject; procedure SelectObjectsInRect(SelRect: TRect); procedure OnManagedObjectMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OnManagedObjectMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure OnManagedObjectMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OnManagedObjectClick(Sender: TObject); procedure OnManagedObjectDblClick(Sender: TObject); procedure ChildMouseDrag(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Paint; override; public OnContentChanged : TNotifyEvent; constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Add a control to the managed list function AddManagedObject(AObject: TControl): TControl; // Return the first of the selected controls if any. function GetFirstSelected : TControl; // Returns a objectlist containing the selected controls. // The list should be freed by the caller. function GetSelectedControls : TObjectList; // Returns a list containing all the managed controls. // The list should be freed by the caller. function GetManagedObjects: TList; // Returns a list with all interobject connections. // The list should be freed by the caller. function GetConnections : TList; // Add a connection from Src to Dst with the supplied style function ConnectObjects(Src, Dst: TControl; AStyle:TessConnectionStyle = csNormal; Arrow : TessConnectionArrowStyle = asEmptyClosed): Boolean; // Free all managed objects and the managed controls. procedure ClearManagedObjects; // Unselect all selected objects procedure ClearSelection; procedure SetFocus; override; procedure RecalcSize; property PathLayout: TBasePathLayout read FPathLayout; property IsModified: Boolean read FIsModified write FIsModified; // Bitmap to be used as background property BackBitmap : TBitmap read FBackBitmap write FBackBitmap; //Only draw selected property SelectedOnly : boolean read FSelectedOnly write SetSelectedOnly; property PathStyle: TPathLayoutStyle read FPathStyle write SetPathStyle; published property Align; property Alignment; property Anchors; property BevelInner; property BevelOuter; property BevelWidth; property BiDiMode; property UseDockManager default True; property DockSite; property DragCursor; property DragKind; property FullRepaint; property ParentBiDiMode; property OnDockDrop; property OnDockOver; property OnEndDock; property OnGetSiteInfo; property OnStartDock; property OnUnDock; property BorderWidth; property BorderStyle; property Caption; property Color default clWhite; property Constraints; property DragMode; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; TBasePathLayout = class private FOwner: TObject; public constructor Create(AOwner: TessConnectPanel); // intermediate which keeps program working. function GetConnection(const AOwner: TControl; const rOwner: TControl; const rTarget: TControl; WantMid: boolean): TDecoratedConnection; virtual; abstract; // Will be final version // function GetBaseAnchors(A: TAssociation): TDecoratedConnection; overload; virtual; abstract; // stage 2 rearrange anchors according to space available procedure ArrangeAnchors; virtual; abstract; // stage 3 generate paths between finalised points. procedure CalculatePath(con: TDecoratedConnection); virtual; abstract; procedure RefreshPath(con: TDecoratedConnection); virtual; abstract; procedure DrawConnection(con: TDecoratedConnection; ACanvas: TCanvas); virtual; abstract; end; procedure Register; implementation uses uPathLayout; type TCrackControl = class(TControl) end; procedure Register; begin RegisterComponents('Eldean', [TessConnectPanel]); end; constructor TBasePathLayout.Create(AOwner: TessConnectPanel); begin FOwner := AOwner; end; { TessConnectPanel } function TessConnectPanel.AddManagedObject(AObject: TControl): TControl; var crkObj : TCrackControl; newObj: TManagedObject; begin Result := nil; if (AObject.Left + AObject.Width) > Width then Width := Max(Width,AObject.Left + AObject.Width + 50); if (AObject.Top + AObject.Height) > Height then Height := Max(Height,AObject.Top + AObject.Height + 50); AObject.Parent := Self; AObject.Visible := True; if FindManagedControl(AObject) = nil then begin newObj := TManagedObject.Create; newObj.FControl := AObject; FManagedObjects.Add(newObj); crkObj := TCrackControl(AObject); newObj.FOnMouseDown := crkObj.OnMouseDown; newObj.FOnMouseMove := crkObj.OnMouseMove; newObj.FOnMouseUp := crkObj.OnMouseUp; newObj.FOnClick := crkObj.OnClick; newObj.FOnDblClick := crkObj.OnDblClick; crkObj.OnMouseDown := @OnManagedObjectMouseDown; crkObj.OnMouseMove := @OnManagedObjectMouseMove; crkObj.OnMouseUp := @OnManagedObjectMouseUp; crkObj.OnClick := @OnManagedObjectClick; crkObj.OnDblClick := @OnManagedObjectDblClick; Result := AObject; end; end; procedure TessConnectPanel.ClearManagedObjects; var i: Integer; begin FConnections.Clear; for i:=0 to FManagedObjects.Count -1 do TManagedObject(FManagedObjects[i]).Free; FManagedObjects.Clear; SetBounds(0,0,0,0); FIsModified := False; end; procedure TessConnectPanel.ClearSelection; var i: Integer; begin for i:=0 to FManagedObjects.Count -1 do TManagedObject(FManagedObjects[i]).Selected := False; end; procedure TessConnectPanel.Click; begin inherited; ClearSelection; end; function TessConnectPanel.ConnectObjects(Src, Dst: TControl; AStyle: TessConnectionStyle; Arrow : TessConnectionArrowStyle): Boolean; var conn: TConnection; con: TDecoratedConnection; begin con := FPathLayout.GetConnection(self, src, dst, (arrow = asEmptyClosed)); con.IsDirty := True; con.Style := TPathStyle(ord(AStyle)); con.ArrowStyle := TArrowStyle(ord( Arrow)); FConnections.Add(con); end; constructor TessConnectPanel.Create(AOwner: TComponent); begin inherited; FManagedObjects := TList.Create; FConnections := TObjectList.Create(True); Color := clWhite; TempHidden := TObjectList.Create(False); UseDockManager := True; FPathLayout := TOrthoPathLayout.Create(Self); end; procedure TessConnectPanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); // Params.Style := Params.Style and (not WS_CLIPCHILDREN); end; destructor TessConnectPanel.Destroy; begin FreeAndNil(TempHidden); if Assigned(FManagedObjects) then FreeAndNil(FManagedObjects); if Assigned(FConnections) then FreeAndNil(FConnections); if Assigned(FPathLayout) then FreeAndNil(FPathLayout); inherited; end; function TessConnectPanel.FindManagedControl( AControl: TControl): TManagedObject; var i: Integer; curr: TManagedObject; begin Result := nil; for i:=0 to FManagedObjects.Count -1 do begin curr := TManagedObject(FManagedObjects[i]); if curr.FControl = AControl then begin Result := curr; exit; end; end; end; function TessConnectPanel.GetConnections: TList; var i: Integer; begin Result := TList.Create; for i := 0 to FConnections.Count-1 do Result.Add(FConnections[I]); end; function TessConnectPanel.GetManagedObjects: TList; var i: Integer; begin Result := TList.Create; for i := 0 to FManagedObjects.Count-1 do Result.Add(TManagedObject(FManagedObjects[i]).FControl); end; function TessConnectPanel.GetFirstSelected: TControl; var Tmp : TObjectList; begin Result := nil; Tmp := GetSelectedControls; if Tmp.Count>0 then Result := Tmp[0] as TControl; Tmp.Free; end; function TessConnectPanel.GetSelectedControls: TObjectList; var I : Integer; begin Result := TObjectList.Create(False); for I := 0 to FManagedObjects.Count-1 do if TManagedObject(FManagedObjects[I]).FSelected then Result.Add( TManagedObject(FManagedObjects[I]).FControl ); end; procedure TessConnectPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pt: TPoint; begin inherited; pt.x:=x; pt.y:=y; FMemMousePos.x := pt.x; FMemMousePos.y := pt.y; if (Button = mbLeft) then begin FIsRectSelecting := True; FSelectRect.TopLeft := FMemMousePos; FSelectRect.BottomRight := FMemMousePos; Canvas.Brush.Style := bsClear; Canvas.Pen.Color := clSilver; Canvas.Pen.Mode := pmXor; Canvas.Pen.Width := 0; Canvas.Rectangle(FSelectRect); end; end; procedure TessConnectPanel.MouseMove(Shift: TShiftState; X, Y: Integer); var pt: TPoint; begin inherited; pt.x:=x; pt.y:=y; if FIsRectSelecting then begin FMemMousePos := pt; Canvas.Brush.Style := bsClear; Canvas.Pen.Color := clSilver; Canvas.Pen.Mode := pmXor; Canvas.Pen.Width := 0; Canvas.Rectangle(FSelectRect); FSelectRect.BottomRight := FMemMousePos; Canvas.Rectangle(FSelectRect); end; end; procedure TessConnectPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if FIsRectSelecting then begin Canvas.Brush.Style := bsClear; Canvas.Pen.Mode := pmXor; Canvas.Pen.Width := 0; Canvas.Rectangle(FSelectRect); FIsRectSelecting := False; // Do Select everything inside the rect. SelectObjectsInRect(FSelectRect); end; end; procedure TessConnectPanel.OnManagedObjectClick(Sender: TObject); begin end; procedure TessConnectPanel.OnManagedObjectDblClick(Sender: TObject); begin SetCurrentEntity(TRTFDBOX(Sender).Entity) end; procedure TessConnectPanel.ChildMouseDrag(Sender: TObject; Shift: TShiftState; X, Y: Integer); var pt,pt1: TPoint; r: TRect; mcont: TManagedObject; p2: TPoint; i,dx,dy, mdx, mdy: Integer; curr: TCrackControl; MovedRect : TRect; procedure InMakeVisible(C : TRect); begin mdx := TScrollBox(Parent).HorzScrollBar.Position; mdy := TScrollBox(Parent).VertScrollBar.Position; if (dx>0) and (C.BottomRight.X >= TScrollBox(Parent).HorzScrollBar.Position + Parent.Width) then TScrollBox(Parent).HorzScrollBar.Position := C.BottomRight.X - Parent.Width; if (dy>0) and (C.BottomRight.Y >= TScrollBox(Parent).VertScrollBar.Position + Parent.Height) then TScrollBox(Parent).VertScrollBar.Position := C.BottomRight.Y - Parent.Height; if (dx<0) and (C.Left <= TScrollBox(Parent).HorzScrollBar.Position) then TScrollBox(Parent).HorzScrollBar.Position := C.Left; if (dy<0) and (C.Top <= TScrollBox(Parent).VertScrollBar.Position) then TScrollBox(Parent).VertScrollBar.Position := C.Top; mdy := mdy - TScrollBox(Parent).VertScrollBar.Position; mdx := mdx - TScrollBox(Parent).HorzScrollBar.Position; if (mdx <> 0) or (mdy <> 0) then begin p2 := Mouse.CursorPos; p2.X := p2.X + mdx; p2.Y := p2.Y + mdy; Mouse.CursorPos := p2; end; end; begin pt1 := Mouse.CursorPos; pt.x := pt1.x; pt.Y := pt1.y; dx := pt.x - FMemMousePos.x; dy := pt.y - FMemMousePos.y; IntersectRect(r{%H-},Parent.ClientRect,BoundsRect); r.TopLeft := Parent.ClientToScreen(r.TopLeft); r.BottomRight := Parent.ClientToScreen(r.BottomRight); if (Abs(Abs(dx)+Abs(dy)) > 5) or (FIsMoving) then begin FMemMousePos := pt; FIsMoving := True; fNeedCheckSize := True; MovedRect:=Rect(MaxInt,0,0,0); for i:=0 to FManagedObjects.Count -1 do begin if TManagedObject(FManagedObjects[i]).Selected then begin mcont := TManagedObject(FManagedObjects[i]); curr := TCrackControl(mcont.FControl); if curr.Left+dx >= 0 then curr.Left := curr.Left + dx; if curr.Top+dy >= 0 then curr.Top := curr.Top + dy; if (curr.Left + curr.Width + 50) > Width then Width := (curr.Left + curr.Width + 50); if (curr.Top + curr.Height + 50) > Height then Height := (curr.Top + curr.Height + 50); if MovedRect.Left=MaxInt then MovedRect := curr.BoundsRect else UnionRect(MovedRect,curr.BoundsRect,MovedRect); curr.Invalidate; IsModified := True; end; invalidate; end; if MovedRect.Left <> MaxInt then InMakeVisible(MovedRect); end; end; procedure TessConnectPanel.OnManagedObjectMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pt: TPoint; inst: TManagedObject; begin if not(ssCtrl in shift) then ClearSelection; inst := FindManagedControl(Sender as TControl); inst.SetSelected(true); ClientDragging := True; pt := Mouse.CursorPos; FMemMousePos.x := pt.x; FMemMousePos.y := pt.y; end; procedure TessConnectPanel.OnManagedObjectMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ClientDragging then ChildMouseDrag(Sender,Shift,x,y); end; procedure TessConnectPanel.OnManagedObjectMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var inst: TManagedObject; begin ClientDragging := False; if fNeedCheckSize then begin ReCalcSize; fNeedCheckSize := False; end; inst := FindManagedControl(Sender as TControl); if not(ssCtrl in shift) then ClearSelection; inst.SetSelected(true); end; procedure TessConnectPanel.Paint; const HANDLESIZE: Integer = 5; var Rect, r2: TRect; TopColor, BottomColor: TColor; i: Integer; con: TDecoratedConnection; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; function CenterOf(const r: TRect): TPoint; begin Result.x := (r.Left + r.Right) div 2; Result.y := (r.Top + r.Bottom) div 2; end; procedure MakeRectangle(var r: TRect; x1,y1,x2,y2: Integer); begin r.Left := x1; r.Right := x2; r.Top := y1; r.Bottom := y2; end; begin Canvas.Pen.Mode := pmCopy; Rect := GetClientRect; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, Rect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; if Assigned(FBackBitmap) then Canvas.Brush.Bitmap := FBackBitmap else Canvas.Brush.Color := Color; Canvas.FillRect(Rect); Canvas.Brush.Style := bsSolid; Canvas.Pen.Color := clBlack; Canvas.Pen.Width := 3; // Draw connections. recalc on fly if dirty i.e parent of either end is moving for i:=0 to FConnections.Count -1 do begin con := (FConnections[i] as TDecoratedConnection); if con.IsDirty then con.Refresh; FPathLayout.DrawConnection(con, Canvas); end; // TODO Path optimisations, will need correct handling of IsDirty // which should be set on the connection by the moving Managed object[s] // it should follow roughly below. { if not FIsMoving or not AllConnectionsClean then begin for i:=0 to FConnections.Count -1 do begin con := (FConnections[i] as TDecoratedConnection); if con.IsDirty then begin FPathLayout.ArrangeAnchors; // this is here but not implemented // FPathLayout.RemoveSmallKinks; etc etc // con.IsDirty := False; don't do this yet; // Flag changed end; end; // see if redraw is required end; } Canvas.Pen.Style := psSolid; Canvas.Brush.Bitmap := nil; Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := clBlack; //Grab-handles if not ClientDragging then if not FSelectedOnly then for i:=0 to FManagedObjects.Count -1 do begin if TManagedObject(FManagedObjects[i]).Selected and (TManagedObject(FManagedObjects[i]).FControl.Visible) then begin Rect := TManagedObject(FManagedObjects[i]).FControl.BoundsRect; MakeRectangle(r2{%H-}, Rect.Left -HANDLESIZE, Rect.Top -HANDLESIZE, Rect.Left+HANDLESIZE, Rect.Top+HANDLESIZE); Canvas.FillRect(r2); MakeRectangle(r2, Rect.Right -HANDLESIZE, Rect.Top -HANDLESIZE, Rect.Right+HANDLESIZE, Rect.Top+HANDLESIZE); Canvas.FillRect(r2); MakeRectangle(r2, Rect.Left -HANDLESIZE, Rect.Bottom -HANDLESIZE, Rect.Left+HANDLESIZE, Rect.Bottom+HANDLESIZE); Canvas.FillRect(r2); MakeRectangle(r2, Rect.Right -HANDLESIZE, Rect.Bottom -HANDLESIZE, Rect.Right+HANDLESIZE, Rect.Bottom+HANDLESIZE); Canvas.FillRect(r2); end; end; end; procedure TessConnectPanel.RecalcSize; var i, xmax, ymax: Integer; begin xmax := 300; ymax := 150; for i:=0 to ControlCount -1 do begin if (Controls[i].Align <> alNone) or (not Controls[i].Visible) then Continue; xmax := Max(xmax,Controls[i].Left + Controls[i].Width + 50); ymax := Max(ymax,Controls[i].Top + Controls[i].Height + 50); end; SetBounds(Left,Top,xmax,ymax); if Assigned(OnContentChanged) then OnContentChanged(nil); end; procedure TessConnectPanel.SelectObjectsInRect(SelRect: TRect); var i: Integer; r1,r2: TRect; begin r1 := SelRect; if (SelRect.Top > SelRect.Bottom) then begin SelRect.Top := r1.Bottom; SelRect.Bottom := r1.Top; end; if (SelRect.Left > SelRect.Right) then begin SelRect.Left := r1.Right; SelRect.Right := r1.Left; end; for i:=0 to FManagedObjects.Count -1 do begin r1 := TCrackControl(TManagedObject(FManagedObjects[i]).FControl).BoundsRect; IntersectRect(r2{%H-},SelRect,r1); if EqualRect(r1,r2) and TManagedObject(FManagedObjects[i]).FControl.Visible then TManagedObject(FManagedObjects[i]).Selected := True; end; end; procedure TessConnectPanel.SetFocus; var F : TCustomForm; X,Y : integer; begin F := GetParentForm(Self); // Try to see if we can call inherited, otherwise there is a risc of getting // 'Cannot focus' exception when starting from delphi-tools. if CanFocus and (Assigned(F) and F.Active) then begin // To avoid having the scrollbox resetting its positions after a setfocus call. X := (Parent as TScrollBox).HorzScrollBar.Position; Y := (Parent as TScrollBox).VertScrollBar.Position; inherited; (Parent as TScrollBox).HorzScrollBar.Position := X; (Parent as TScrollBox).VertScrollBar.Position := Y; end; // if GetCaptureControl <> Self then SetCaptureControl(Self); end; procedure TessConnectPanel.WMEraseBkgnd(var Message: TWmEraseBkgnd); var can : Tcanvas; begin can := tcanvas.create; try can.handle := message.DC; if Assigned(FBackBitmap) then Can.Brush.Bitmap := FBackBitmap else Can.Brush.Color := Color; Can.FillRect(ClientRect); finally can.free; end; Message.Result := 1; end; procedure TessConnectPanel.SetPathStyle(AValue: TPathLayoutStyle); begin if AValue <> FPathStyle then begin FPathStyle := AValue; if Assigned(Self.PathLayout) then FPathLayout.Free; case AValue of plsOrtho: FPathLayout := TOrthoPathLayout.Create(Self); plsVector: FPathLayout := TVectorPathLayout.Create(Self); plsRoundedOrtho: FPathLayout := TRoundedPathLayout.Create(Self); end; Invalidate; end end; procedure TessConnectPanel.SetSelectedOnly(const Value : boolean); var I : integer; begin if FSelectedOnly <> Value then begin FSelectedOnly := Value; if FSelectedOnly then begin TempHidden.Clear; for i:=0 to FManagedObjects.Count -1 do if (not TManagedObject(FManagedObjects[i]).Selected) and TManagedObject(FManagedObjects[i]).FControl.Visible then begin TManagedObject(FManagedObjects[i]).FControl.Visible := False; TempHidden.Add( TObject(FManagedObjects[i])); end; end else begin for I := 0 to TempHidden.Count-1 do TManagedObject(TempHidden[I]).FControl.Visible := True; TempHidden.Clear; end; end; end; { TManagedObject } destructor TManagedObject.Destroy; begin if Assigned(FControl) then FreeAndNil(FControl); inherited; end; procedure TManagedObject.SetSelected(const Value: Boolean); begin FControl.Parent.Invalidate; FSelected := Value; if FSelected then FControl.BringToFront; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 12/2/2004 9:26:44 PM JPMugaas Bug fix. Rev 1.4 11/11/2004 10:25:24 PM JPMugaas Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions from the UDP client with SOCKS. You must call OpenProxy before using RecvFrom or SendTo. When you are finished, you must use CloseProxy to close any connection to the Proxy. Connect and disconnect also call OpenProxy and CloseProxy. Rev 1.3 11/11/2004 3:42:52 AM JPMugaas Moved strings into RS. Socks will now raise an exception if you attempt to use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP at all. Rev 1.2 2004.05.20 11:39:12 AM czhower IdStreamVCL Rev 1.1 6/4/2004 5:13:26 PM SGrobety EIdMaxCaptureLineExceeded message string Rev 1.0 2004.02.03 4:19:50 PM czhower Rename Rev 1.15 10/24/2003 4:21:56 PM DSiders Addes resource string for stream read exception. Rev 1.14 2003.10.16 11:25:22 AM czhower Added missing ; Rev 1.13 10/15/2003 11:11:06 PM DSiders Added resource srting for exception raised in TIdTCPServer.SetScheduler. Rev 1.12 10/15/2003 11:03:00 PM DSiders Added resource string for circular links from transparent proxy. Corrected spelling errors. Rev 1.11 10/15/2003 10:41:34 PM DSiders Added resource strings for TIdStream and TIdStreamProxy exceptions. Rev 1.10 10/15/2003 8:48:56 PM DSiders Added resource strings for exceptions raised when setting thread component properties. Rev 1.9 10/15/2003 8:35:28 PM DSiders Added resource string for exception raised in TIdSchedulerOfThread.NewYarn. Rev 1.8 10/15/2003 8:04:26 PM DSiders Added resource strings for exceptions raised in TIdLogFile, TIdReply, and TIdIOHandler. Rev 1.7 10/15/2003 1:03:42 PM DSiders Created resource strings for TIdBuffer.Find exceptions. Rev 1.6 2003.10.14 1:26:44 PM czhower Uupdates + Intercept support Rev 1.5 10/1/2003 10:49:02 PM GGrieve Rework buffer for Octane Compability Rev 1.4 7/1/2003 8:32:32 PM BGooijen Added RSFibersNotSupported Rev 1.3 7/1/2003 02:31:34 PM JPMugaas Message for invalid IP address. Rev 1.2 5/14/2003 6:40:22 PM BGooijen RS for transparent proxy Rev 1.1 1/17/2003 05:06:04 PM JPMugaas Exceptions for scheduler string. Rev 1.0 11/13/2002 08:42:02 AM JPMugaas } unit IdResourceStringsCore; interface {$i IdCompilerDefines.inc} resourcestring RSNoBindingsSpecified = 'バインディングが指定されていません。'; RSCannotAllocateSocket = 'ソケットを割り当てられません。'; RSSocksUDPNotSupported = 'UDP はこの SOCKS バージョンではサポートされていません。'; RSSocksRequestFailed = '要求は拒否または失敗しました。'; RSSocksRequestServerFailed = '要求は拒否されました。SOCKS サーバーが接続できないためです。'; RSSocksRequestIdentFailed = '要求は拒否されました。クライアント プログラムと identd のユーザー ID が異なるためです。'; RSSocksUnknownError = '不明な SOCKS エラーです。'; RSSocksServerRespondError = 'SOCKS サーバーが応答しませんでした。'; RSSocksAuthMethodError = '不正な socks 認証方式です。'; RSSocksAuthError = 'Socks サーバーに対する認証エラー。'; RSSocksServerGeneralError = '一般 SOCKS サーバー エラーです。'; RSSocksServerPermissionError = 'ルールセットによりこれ以上接続できません。'; RSSocksServerNetUnreachableError = 'ネットワークに到達できません。'; RSSocksServerHostUnreachableError = 'ホストに到達できません。'; RSSocksServerConnectionRefusedError = '接続が拒否されました。'; RSSocksServerTTLExpiredError = 'TTL を超えています。'; RSSocksServerCommandError = 'コマンドはサポートされていません:'; RSSocksServerAddressError = 'アドレス タイプがサポートされていません。'; RSInvalidIPAddress = 'IP アドレスが無効です'; RSInterceptCircularLink = '%s: 循環リンクは使用できません'; RSNotEnoughDataInBuffer = 'バッファに十分なデータがありません。(%d/%d)'; RSTooMuchDataInBuffer = 'バッファに十分なデータがありません。'; RSCapacityTooSmall = 'Capacity は Size 以上でなければなりません。'; RSBufferIsEmpty = 'バッファにデータがありません。'; RSBufferRangeError = 'インデックスが範囲外です。'; RSFileNotFound = 'ファイル "%s" が見つかりません'; RSNotConnected = '接続されていません'; RSObjectTypeNotSupported = 'オブジェクト型がサポートされていません。'; RSIdNoDataToRead = '読み取るデータがありません。'; RSReadTimeout = '読み取りがタイム アウトしました。'; RSReadLnWaitMaxAttemptsExceeded = '読み取り最大試行行数を超えています。'; RSAcceptTimeout = 'accept がタイムアウトしました。'; RSReadLnMaxLineLengthExceeded = '行の最大サイズを超えています。'; RSRequiresLargeStream = '2 GB より大きいストリームを送信するには、LargeStream を True に設定します'; RSDataTooLarge = 'データがストリームには大きすぎます'; RSConnectTimeout = '接続がタイムアウトしました。'; RSICMPNotEnoughtBytes = '受信したバイト数が不十分です'; RSICMPNonEchoResponse = 'エコー タイプ以外の応答を受信しました'; RSThreadTerminateAndWaitFor = 'TerminateAndWaitFor を FreeAndTerminate スレッドで呼び出しできません'; RSAlreadyConnected = 'すでに接続されています。'; RSTerminateThreadTimeout = 'スレッド終了のタイムアウト'; RSNoExecuteSpecified = '実行ハンドラが見つかりません。'; RSNoCommandHandlerFound = 'コマンド ハンドラが見つかりません。'; RSCannotPerformTaskWhileServerIsActive = 'サーバーの稼働中にタスクを実行できません。'; RSThreadClassNotSpecified = 'スレッド クラスが指定されていません。'; RSMaximumNumberOfCaptureLineExceeded = '最大許容行数を超えています'; // S.G. 6/4/2004: IdIOHandler.DoCapture RSNoCreateListeningThread = 'リスン スレッドを作成できません。'; RSInterceptIsDifferent = 'IOHandler には別のインターセプトがすでに割り当てられています'; //scheduler RSchedMaxThreadEx = 'このスケジューラの最大スレッド数を超えています。'; //transparent proxy RSTransparentProxyCannotBind = '透過プロキシをバインドできません。'; RSTransparentProxyCanNotSupportUDP = 'UDP はこのプロキシでサポートされていません。'; //Fibers RSFibersNotSupported = 'このシステムではファイバーはサポートされていません。'; // TIdICMPCast RSIPMCastInvalidMulticastAddress = '指定された IP アドレスは有効なマルチキャスト アドレス (224.0.0.0 から 239.255.255.255 まで) ではありません。'; RSIPMCastNotSupportedOnWin32 = 'この関数は Win32 ではサポートされていません。'; RSIPMCastReceiveError0 = 'IP ブロードキャスト受信エラー = 0。'; // Log strings RSLogConnected = '接続しました。'; RSLogDisconnected = '接続解除されました。'; RSLogEOL = '<EOL>'; // End of Line RSLogCR = '<CR>'; // Carriage Return RSLogLF = '<LF>'; // Line feed RSLogRecv = '受信 '; // Receive RSLogSent = '送信済み '; // Send RSLogStat = 'Stat '; // Status RSLogFileAlreadyOpen = 'ログ ファイルが開かれている間はファイル名を設定できません。'; RSBufferMissingTerminator = 'バッファの終了文字を指定する必要があります。'; RSBufferInvalidStartPos = 'バッファの開始位置が無効です。'; RSIOHandlerCannotChange = '接続した IOHandler を変更できません。'; RSIOHandlerTypeNotInstalled = 'タイプ %s の IOHandler がインストールされていません。'; RSReplyInvalidCode = 'リプライ コードが不正です: %s'; RSReplyCodeAlreadyExists = 'リプライ コードはすでに存在します: %s'; RSThreadSchedulerThreadRequired = 'スレッドをこのスケジューラに指定する必要があります。'; RSNoOnExecute = 'OnExecute イベントが必要です。'; RSThreadComponentLoopAlreadyRunning = 'スレッドが既に実行中の場合は Loop プロパティを設定できません。'; RSThreadComponentThreadNameAlreadyRunning = 'スレッドが既に実行中の場合は ThreadName を設定できません。'; RSStreamProxyNoStack = 'データ型変換用のスタックが作成されていません。'; RSTransparentProxyCyclic = '透過プロキシの循環エラーです。'; RSTCPServerSchedulerAlreadyActive = 'サーバーがアクティブであるときにスケジューラを変更できません。'; RSUDPMustUseProxyOpen = 'proxyOpen を使用する必要があります。'; //ICMP stuff RSICMPTimeout = 'タイムアウト'; //Destination Address -3 RSICMPNetUnreachable = 'ネットワークに到達できません。'; RSICMPHostUnreachable = 'ホストに到達できません。'; RSICMPProtUnreachable = 'プロトコルに到達できません。'; RSICMPPortUnreachable = 'ポートに到達できません'; RSICMPFragmentNeeded = 'フラグメント化が必要ですが、"Don'#39't Fragment" フラグが設定されています'; RSICMPSourceRouteFailed = '送信元ルートで障害が発生しました'; RSICMPDestNetUnknown = '宛先ネットワークが不明です'; RSICMPDestHostUnknown = '宛先ホストが不明です'; RSICMPSourceIsolated = '送信元ホストへのルートがありません'; RSICMPDestNetProhibitted = '宛先ネットワークとの通信が管理上禁止されています'; RSICMPDestHostProhibitted = '宛先ホストとの通信が管理上禁止されています'; RSICMPTOSNetUnreach = 'サービスのタイプに対応する宛先ネットワークに到達できません'; RSICMPTOSHostUnreach = 'サービスのタイプに対応する宛先ホストに到達できません'; RSICMPAdminProhibitted = '通信が管理上禁止されています'; RSICMPHostPrecViolation = 'ホスト優先度の侵害'; RSICMPPrecedenceCutoffInEffect = '優先度による遮断が有効です'; //for IPv6 RSICMPNoRouteToDest = '宛先へのルートが存在しません'; RSICMPAAdminDestProhibitted = '宛先との通信は管理上禁止されています'; RSICMPSourceFilterFailed = '送信元アドレスが侵入/侵出ポリシーに違反しています'; RSICMPRejectRoutToDest = '宛先へのルートを破棄します'; // Destination Address - 11 RSICMPTTLExceeded = '転送中に存続時間 (TTL) を超過しました'; RSICMPHopLimitExceeded = '転送中にホップ限度を超えました'; RSICMPFragAsmExceeded = 'フラグメントの再構成時間を超過しました。'; //Parameter Problem - 12 RSICMPParamError = 'パラメータの問題 (オフセット %d)'; //IPv6 RSICMPParamHeader = '誤りのあるヘッダー フィールドを検出しました (オフセット %d)'; RSICMPParamNextHeader = '認識できない "次のヘッダー" タイプを検出しました (オフセット %d)'; RSICMPUnrecognizedOpt = '認識できない IPv6 オプションを検出しました (オフセット %d)'; //Source Quench Message -4 RSICMPSourceQuenchMsg = '送信元抑制メッセージ'; //Redirect Message RSICMPRedirNet = 'ネットワークのデータグラムをリダイレクトします。'; RSICMPRedirHost = 'ホストのデータグラムをリダイレクトします。'; RSICMPRedirTOSNet = 'サービスおよびネットワークのタイプに対応するデータグラムをリダイレクトします。'; RSICMPRedirTOSHost = 'サービスおよびホストのタイプに対応するデータグラムをリダイレクトします。'; //echo RSICMPEcho = 'Echo'; //timestamp RSICMPTimeStamp = 'タイムスタンプ'; //information request RSICMPInfoRequest = '情報要求'; //mask request RSICMPMaskRequest = 'アドレス マスク要求'; // Traceroute RSICMPTracePacketForwarded = '発信パケットが正常に転送されました'; RSICMPTraceNoRoute = '発信パケットのルートがありません。パケットは破棄されました'; //conversion errors RSICMPConvUnknownUnspecError = '不明または明示されていないエラーです'; RSICMPConvDontConvOptPresent = '"Don'#39't Convert" オプションがあります'; RSICMPConvUnknownMandOptPresent = '不明な必須オプションがあります'; RSICMPConvKnownUnsupportedOptionPresent = 'サポートされていない既知のオプションがあります'; RSICMPConvUnsupportedTransportProtocol = 'サポートされていないトランスポート プロトコルです'; RSICMPConvOverallLengthExceeded = '全長を超えています'; RSICMPConvIPHeaderLengthExceeded = 'IP ヘッダー長を超えています'; RSICMPConvTransportProtocol_255 = 'トランスポート プロトコル &gt; 255'; RSICMPConvPortConversionOutOfRange = 'ポート変換が範囲外です'; RSICMPConvTransportHeaderLengthExceeded = 'トランスポート ヘッダー長を超えています'; RSICMPConv32BitRolloverMissingAndACKSet = '"32 Bit Rollover" オプションがなく、ACK フラグが設定されています'; RSICMPConvUnknownMandatoryTransportOptionPresent = 'トランスポートに関する不明な必須オプションがあります'; //mobile host redirect RSICMPMobileHostRedirect = 'モバイル ホスト リダイレクト'; //IPv6 - Where are you RSICMPIPv6WhereAreYou = 'IPv6 Where-Are-You'; //IPv6 - I am here RSICMPIPv6IAmHere = 'IPv6 I-Am-Here'; // Mobile Regestration request RSICMPMobReg = 'モバイル登録要求'; //Skip RSICMPSKIP = 'SKIP'; //Security RSICMPSecBadSPI = 'SPI が無効です'; RSICMPSecAuthenticationFailed = '認証に失敗しました'; RSICMPSecDecompressionFailed = '解凍に失敗しました'; RSICMPSecDecryptionFailed = '暗号解読に失敗しました'; RSICMPSecNeedAuthentication = '認証が必要です'; RSICMPSecNeedAuthorization = '権限が必要です'; //IPv6 Packet Too Big RSICMPPacketTooBig = 'パケットが大きすぎます (MTU = %d)'; { TIdCustomIcmpClient } // TIdSimpleServer RSCannotUseNonSocketIOHandler = 'ソケット以外の IOHandler を使用できません'; implementation end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: ParallaxOcclusionMappingUnit.pas,v 1.5 2007/02/05 22:21:11 clootie Exp $ *----------------------------------------------------------------------------*) //================================================================================================= // File: ParallaxOcclusionMapping.cpp // // Author: Natalya Tatarchuk // ATI Research, Inc. // 3D Application Research Group // // Implementation of the algorithm as described in "Dynamic Parallax Occlusion Mapping with // Approximate Soft Shadows" paper, by N. Tatarchuk, ATI Research, to appear in the proceedings // of ACM Symposium on Interactive 3D Graphics and Games, 2006. // // Copyright (c) ATI Research, Inc. All rights reserved. //================================================================================================= {$I DirectX.inc} unit ParallaxOcclusionMappingUnit; interface uses Windows, SysUtils, StrSafe, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders //-------------------------------------------------------------------------------------- // Global variables and parameters //-------------------------------------------------------------------------------------- const s_iMAX_STRING_SIZE = 100; const s_iDECL_SIZE = 56; const s_iNUM_TEXTURES = 7; // Number of loaded texturs in the program //-------------------------------------------------------------------------------------- // Texture pair ids for use for this sample //-------------------------------------------------------------------------------------- type TPOM_TextureIDs = ( pomStones, pomRocks, pomWall, pomFourBumps, pomBumps, pomDents, pomSaint ); //-------------------------------------------------------------------------------------- // Id numbers for different rendering techniques used //-------------------------------------------------------------------------------------- TTechniqueIDs = ( tidPOM, // Parallax occlusion mapping tidBumpmap, // Bump mapping tidPM // Parallax mapping with offset limiting ); var g_nCurrentTextureID: TPOM_TextureIDs = pomStones; g_nCurrentTechniqueID: TTechniqueIDs = tidPOM; //-------------------------------------------------------------------------------------- // Texture pair names for use for this sample //-------------------------------------------------------------------------------------- const g_strBaseTextureNames: array [TPOM_TextureIDs] of PWideChar = ( 'stones.bmp', 'rocks.jpg', 'wall.jpg', 'wood.jpg', 'concrete.bmp', 'concrete.bmp', 'wood.jpg' ); g_strNMHTextureNames: array [TPOM_TextureIDs] of PWideChar = ( 'stones_NM_height.tga', 'rocks_NM_height.tga', 'wall_NM_height.tga', 'four_NM_height.tga', 'bump_NM_height.tga', 'dent_NM_height.tga', 'saint_NM_height.tga' ); type PIDirect3DTexture9Array = ^TIDirect3DTexture9Array; TIDirect3DTexture9Array = array[TPOM_TextureIDs] of IDirect3DTexture9; // [0..MaxInt div SizeOf(IDirect3DTexture9) - 1] //-------------------------------------------------------------------------------------- var g_pD3DDevice: IDirect3DDevice9; // A pointer to the current D3D device used for rendering g_pFont: ID3DXFont; // Font for drawing text g_pSprite: ID3DXSprite; // Sprite for batching draw text calls g_bShowHelp: Boolean = False; // If true, it renders the UI control text g_Camera: CModelViewerCamera; // A model viewing camera g_pEffect: ID3DXEffect; // D3DX effect interface g_pMesh: ID3DXMesh; // Mesh object g_pBaseTextures: PIDirect3DTexture9Array = nil; // Array of base map texture surfaces g_pNMHTextures: PIDirect3DTexture9Array = nil; // Array of normal / height map texture surfaces // a height map in the alpha channel g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // manages the 3D UI g_SampleUI: CDXUTDialog; // dialog for sample specific controls g_mWorldFix: TD3DXMatrixA16; g_LightControl: CDXUTDirectionWidget; // Scene light g_fLightScale: Single; // Light brightness scale parameter //-------------------------------------------------------------------------------------- // UI scalar parameters //-------------------------------------------------------------------------------------- const s_fLightScaleUIScale = 10.0; const s_iLightScaleSliderMin = 0; const s_iLightScaleSliderMax = 20; var g_iHeightScaleSliderMin: Integer = 0; g_iHeightScaleSliderMax: Integer = 100; g_fHeightScaleUIScale: Single = 100.0; const s_iSliderMin = 8; const s_iSliderMax = 130; //-------------------------------------------------------------------------------------- // Material properties parameters: //-------------------------------------------------------------------------------------- var g_colorMtrlDiffuse: TD3DXColor = (r:1.0; g:1.0; b:1.0; a:1.0); g_colorMtrlAmbient: TD3DXColor = (r:0.35; g:0.35; b:0.35; a:0); g_colorMtrlSpecular: TD3DXColor = (r:1.0; g:1.0; b:1.0; a:1.0); g_fSpecularExponent: Single = 60.0; // Material's specular exponent g_fBaseTextureRepeat: Single = 1.0; // The tiling factor for base and normal map textures g_bVisualizeLOD: Boolean = False; // Toggles visualization of level of detail colors g_bVisualizeMipLevel: Boolean = False; // Toggles visualization of mip level g_bDisplayShadows: Boolean = True; // Toggles display of self-occlusion based shadows g_bAddSpecular: Boolean = True; // Toggles rendering with specular or without g_bRenderPOM: Boolean = True; // Toggles whether using normal mapping or parallax occlusion mapping g_nLODThreshold: Integer = 3; // The mip level id for transitioning between the full computation // for parallax occlusion mapping and the bump mapping computation g_nMinSamples: Integer = 8; // The minimum number of samples for sampling the height field profile g_nMaxSamples: Integer = 50; // The maximum number of samples for sampling the height field profile g_fShadowSoftening: Single = 0.58; // Blurring factor for the soft shadows computation g_fHeightScale: Single; // This parameter controls the height map range for displacement mapping //-------------------------------------------------------------------------------------- // Mesh file names for use //-------------------------------------------------------------------------------------- const g_strMeshFileName0 = 'Disc.x'; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_HEIGHT_SCALE_SLIDER = 5; IDC_HEIGHT_SCALE_STATIC = 6; IDC_TOGGLE_SHADOWS = 7; IDC_SELECT_TEXTURES_COMBOBOX = 8; IDC_TOGGLE_SPECULAR = 9; IDC_SPECULAR_EXPONENT_SLIDER = 10; IDC_SPECULAR_EXPONENT_STATIC = 11; IDC_MIN_NUM_SAMPLES_SLIDER = 12; IDC_MIN_NUM_SAMPLES_STATIC = 13; IDC_MAX_NUM_SAMPLES_SLIDER = 14; IDC_MAX_NUM_SAMPLES_STATIC = 15; IDC_TECHNIQUE_COMBO_BOX = 16; IDC_RELOAD_BUTTON = 20; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; procedure RenderText(fTime: Double); procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation //-------------------------------------------------------------------------------------- // Select a pair of base and normal map / height map textures to use and // setup related height map range parameters, given a texture index // Note: all texture surfaces in g_pBaseTextures and g_pNMHTextures MUST // be created prior to calling this function. //-------------------------------------------------------------------------------------- procedure SetPOMTextures(iTextureIndex: TPOM_TextureIDs); begin g_nCurrentTextureID := iTextureIndex; // Bind the new active textures to the correct texture slots in the shaders: if Assigned(g_pD3DDevice) and Assigned(g_pEffect) then begin V(g_pEffect.SetTexture('g_baseTexture', g_pBaseTextures[g_nCurrentTextureID])); V(g_pEffect.SetTexture('g_nmhTexture', g_pNMHTextures[g_nCurrentTextureID])); end; // Setup height map range slider parameters (need to be setup per-texture, as very height-map specific: case iTextureIndex of pomStones: begin // Stones texture pair: g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 100.0; g_fHeightScale := 0.02; g_fSpecularExponent := 60.0; g_fBaseTextureRepeat := 1.0; g_nMinSamples := 8; g_nMaxSamples := 50; end; pomRocks: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 100.0; g_fHeightScale := 0.1; g_fSpecularExponent := 100.0; g_fBaseTextureRepeat := 1.0; g_nMinSamples := 8; g_nMaxSamples := 100; end; pomWall: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 100.0; g_fHeightScale := 0.06; g_fSpecularExponent := 60.0; g_fBaseTextureRepeat := 1.0; g_nMinSamples := 8; g_nMaxSamples := 50; end; pomFourBumps: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 10.0; g_fHeightScale := 0.2; g_fSpecularExponent := 100.0; g_fBaseTextureRepeat := 1.0; g_nMinSamples := 12; g_nMaxSamples := 100; end; pomBumps: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 10.0; g_fHeightScale := 0.2; g_fSpecularExponent := 100.0; g_fBaseTextureRepeat := 4.0; g_nMinSamples := 12; g_nMaxSamples := 100; end; pomDents: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 10.0; g_fHeightScale := 0.2; g_fSpecularExponent := 100.0; g_fBaseTextureRepeat := 4.0; g_nMinSamples := 12; g_nMaxSamples := 100; end; pomSaint: begin g_iHeightScaleSliderMin := 0; g_iHeightScaleSliderMax := 10; g_fHeightScaleUIScale := 100.0; g_fHeightScale := 0.08; g_fSpecularExponent := 100.0; g_fBaseTextureRepeat := 1.0; g_nMinSamples := 12; g_nMaxSamples := 100; end; end; end; //-------------------------------------------------------------------------------------- // Initialize the app: initialize the light controls and the GUI // elements for this application. //-------------------------------------------------------------------------------------- procedure InitApp; const // UI elements parameters: ciPadding = 24; // vertical padding between controls ciLeft = 5; // Left align border (x-coordinate) of the controls ciWidth = 125; // widget width ciHeight = 22; // widget height // Slider parameters: ciSliderLeft = 15; ciSliderWidth = 100; var iY: Integer; sz: array[0..s_iMAX_STRING_SIZE-1] of WideChar; pTechniqueComboBox: CDXUTComboBox; pTextureComboBox: CDXUTComboBox; begin // Initialize the light control: g_LightControl.SetLightDirection(D3DXVector3( Sin(D3DX_PI * 2 - D3DX_PI / 6), 0, -Cos(D3DX_PI * 2 - D3DX_PI / 6))); g_fLightScale := 1.0; // Initialize POM textures and height map parameters: SetPOMTextures(pomStones); // Initialize dialogs // g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); // Initialize user interface elements // // Top toggle buttons // g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', ciLeft, iY, ciWidth, ciHeight); Inc(iY, ciPadding); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', ciLeft, iY, ciWidth, ciHeight); Inc(iY, ciPadding); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', ciLeft, iY, ciWidth, ciHeight, VK_F2); // Inc(iY, 24); // Reload button only works in debug: {$IFDEF _DEBUG} g_HUD.AddButton(IDC_RELOAD_BUTTON, 'Reload effect', ciLeft, iY, ciWidth, ciHeight); {$ENDIF} iY := 10; g_SampleUI.SetCallback(OnGUIEvent); // Technique selection combo box pTechniqueComboBox := nil; g_SampleUI.AddComboBox(IDC_TECHNIQUE_COMBO_BOX, ciLeft, iY, 200, 24, Ord('O'), False, @pTechniqueComboBox); if Assigned(pTechniqueComboBox) then begin pTechniqueComboBox.SetDropHeight(100); pTechniqueComboBox.AddItem('Parallax Occlusion Mapping', Pointer(tidPOM)); pTechniqueComboBox.AddItem('Bump Mapping', Pointer(tidBUMPMAP)); pTechniqueComboBox.AddItem('Parallax Mapping with Offset Limiting', Pointer(tidPM)); end; // Add control for height range // iY := iY + ciPadding; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Height scale: %f', [g_fHeightScale]); g_SampleUI.AddStatic(IDC_HEIGHT_SCALE_STATIC, sz, ciLeft, iY, ciWidth, ciHeight); iY := iY + ciPadding; g_SampleUI.AddSlider(IDC_HEIGHT_SCALE_SLIDER, ciSliderLeft, iY, ciSliderWidth, ciHeight, g_iHeightScaleSliderMin, g_iHeightScaleSliderMax, Trunc(g_fHeightScale * g_fHeightScaleUIScale)); // Texture selection combo box: iY := iY + ciPadding; pTextureComboBox := nil; //todo: Fill bug request for L'O' in original sample g_SampleUI.AddComboBox(IDC_SELECT_TEXTURES_COMBOBOX, ciLeft, iY, 200, 24, Ord('T'), False, @pTextureComboBox); if Assigned(pTextureComboBox) then begin pTextureComboBox.SetDropHeight(100); pTextureComboBox.AddItem('Stones', Pointer(pomStones )); pTextureComboBox.AddItem('Rocks', Pointer(pomROCKS )); pTextureComboBox.AddItem('Wall', Pointer(pomWALL )); pTextureComboBox.AddItem('Sphere, Triangle, Torus, Pyramid', Pointer(pomFOURBUMPS )); pTextureComboBox.AddItem('Bumps', Pointer(pomBUMPS )); pTextureComboBox.AddItem('Dents', Pointer(pomDENTS )); pTextureComboBox.AddItem('Relief', Pointer(pomSAINT )); end; // Toggle shadows checkbox iY := iY + ciPadding; g_SampleUI.AddCheckBox(IDC_TOGGLE_SHADOWS, 'Toggle self-occlusion shadows rendering: ON', ciLeft, iY, 350, 24, g_bDisplayShadows, Ord('C'), False); // Toggle specular checkbox iY := iY + ciPadding; g_SampleUI.AddCheckBox(IDC_TOGGLE_SPECULAR, 'Toggle specular: ON', ciLeft, iY, 350, 24, g_bAddSpecular, Ord('C'), False); // Specular exponent slider: iY := iY + ciPadding; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Specular exponent: %f', [g_fSpecularExponent]); g_SampleUI.AddStatic(IDC_SPECULAR_EXPONENT_STATIC, sz, ciLeft, iY, ciWidth, ciHeight); iY := iY + ciPadding; g_SampleUI.AddSlider(IDC_SPECULAR_EXPONENT_SLIDER, ciSliderLeft, iY, ciSliderWidth, ciHeight, s_iSliderMin, s_iSliderMax, Trunc(g_fSpecularExponent)); // Number of samples: minimum iY := iY + ciPadding; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Minium number of samples: %d', [g_nMinSamples]); g_SampleUI.AddStatic(IDC_MIN_NUM_SAMPLES_STATIC, sz, ciLeft, iY, ciWidth * 2, ciHeight); g_SampleUI.GetStatic(IDC_MIN_NUM_SAMPLES_STATIC).Element[0].dwTextFormat := DT_LEFT or DT_TOP or DT_WORDBREAK; iY := iY + ciPadding; g_SampleUI.AddSlider(IDC_MIN_NUM_SAMPLES_SLIDER, ciSliderLeft, iY, ciSliderWidth, ciHeight, s_iSliderMin, s_iSliderMax, g_nMinSamples); // Number of samples: maximum iY := iY + ciPadding; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Maximum number of samples: %d', [g_nMaxSamples]); g_SampleUI.AddStatic(IDC_MAX_NUM_SAMPLES_STATIC, sz, ciLeft, iY, ciWidth * 2, ciHeight); g_SampleUI.GetStatic(IDC_MAX_NUM_SAMPLES_STATIC).Element[0].dwTextFormat := DT_LEFT or DT_TOP or DT_WORDBREAK; iY := iY + ciPadding; g_SampleUI.AddSlider(IDC_MAX_NUM_SAMPLES_SLIDER, ciSliderLeft, iY, ciSliderWidth, ciHeight, s_iSliderMin, s_iSliderMax, g_nMaxSamples); end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by // returning E_FAIL. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result := False; // The ParallaxOcculsionMapping technique requires PS 3.0 so reject any device that // doesn't support at least PS 3.0. Typically, the app would fallback but // ParallaxOcculsionMapping is the purpose of this sample if (pCaps.PixelShaderVersion < D3DPS_VERSION(3, 0)) then Exit; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; Result := True; end; //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // If device doesn't support VS 3.0 then switch to SWVP if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) and ((pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(3, 0))) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // Turn off VSynch pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE; // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // Loads the effect file from disk. Note: D3D device must be created and set // prior to calling this method. //-------------------------------------------------------------------------------------- function LoadEffectFile: HRESULT; var dwShaderFlags: DWORD; str: array[0..MAX_PATH-1] of WideChar; pErrors: ID3DXBuffer; begin SAFE_RELEASE(g_pEffect); if (g_pD3DDevice = nil) then begin Result:= E_FAIL; Exit; end; dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOP; {$ENDIF} Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'ParallaxOcclusionMapping.fx'); if V_Failed(Result) then Exit; //todo: FIX ME!!! // D3DXCreateBuffer(1024, pErrors); Result := D3DXCreateEffectFromFileW(g_pD3DDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, @pErrors); if FAILED(Result) then begin // Output shader compilation errors to the shell: WriteLn(PChar(pErrors.GetBufferPointer)); Result:= E_FAIL; Exit; end; SAFE_RELEASE(pErrors); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED) // and aren't tied to the back buffer size //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var pData: PD3DXVector3; vCenter: TD3DXVector3; fObjectRadius: Single; mRotation: TD3DXMatrixA16; str: array[0..MAX_PATH-1] of WideChar; vecEye, vecAt: TD3DXVector3; iTextureIndex: TPOM_TextureIDs; begin g_pD3DDevice := pd3dDevice; Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the font Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; // Load the mesh Result := LoadMesh(pd3dDevice, g_strMeshFileName0, g_pMesh); if V_Failed(Result) then Exit; V(g_pMesh.LockVertexBuffer(0, Pointer(pData))); V(D3DXComputeBoundingSphere(pData, g_pMesh.GetNumVertices, s_iDECL_SIZE, vCenter, fObjectRadius )); V(g_pMesh.UnlockVertexBuffer); // Align the starting frame of the mesh to be slightly toward the viewer yet to // see the grazing angles: D3DXMatrixTranslation(g_mWorldFix, -vCenter.x, -vCenter.y, -vCenter.z); D3DXMatrixRotationY(mRotation, -D3DX_PI / 3.0); D3DXMatrixMultiply(g_mWorldFix, g_mWorldFix, mRotation); // g_mWorldFix *= mRotation; D3DXMatrixRotationX(mRotation, D3DX_PI / 3.0); D3DXMatrixMultiply(g_mWorldFix, g_mWorldFix, mRotation); // g_mWorldFix *= mRotation; // Initialize the light control Result:= CDXUTDirectionWidget.StaticOnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; g_LightControl.Radius := fObjectRadius; Result:= LoadEffectFile; if V_Failed(Result) then Exit; // Load all textures used by the program from disk New(g_pBaseTextures); // g_pBaseTextures := ( IDirect3DTexture9** ) malloc( SizeOf( IDirect3DTexture9* ) * s_iNUM_TEXTURES); ZeroMemory(g_pBaseTextures, SizeOf(TIDirect3DTexture9Array)); if (g_pBaseTextures = nil) then //Clootie: Delphi will raise an exception here, so actually this code will never execute begin // ERROR allocating the array for base texture pointers storage! WriteLn('ERROR allocating the array for base texture pointers storage!'); Result:= E_FAIL; Exit; end; New(g_pNMHTextures); // g_pNMHTextures = ( IDirect3DTexture9** ) malloc( sizeof( IDirect3DTexture9* ) * s_iNUM_TEXTURES ); ZeroMemory(g_pNMHTextures, SizeOf(TIDirect3DTexture9Array)); if (g_pNMHTextures = nil) then begin // ERROR allocating the array for normal map / height map texture pointers storage! WriteLn('ERROR allocating the array for normal map / height map texture pointers storage!'); Result:= E_FAIL; Exit; end; for iTextureIndex := Low(iTextureIndex) to High(iTextureIndex) do begin // Load the pair of textures (base and combined normal map / height map texture) into // memory for each type of POM texture pairs // Load the base mesh: Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, g_strBaseTextureNames[iTextureIndex]); if V_Failed(Result) then Exit; Result:= D3DXCreateTextureFromFileExW(pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, nil, nil, g_pBaseTextures[iTextureIndex]); if V_Failed(Result) then Exit; // Load the normal map / height map texture Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, g_strNMHTextureNames[iTextureIndex]); if V_Failed(Result) then Exit; Result:= D3DXCreateTextureFromFileExW(pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, nil, nil, g_pNMHTextures[iTextureIndex]); if V_Failed(Result) then Exit; end; SetPOMTextures( g_nCurrentTextureID); // Setup the camera's view parameters vecEye := D3DXVector3(0.0, 0.0, -15.0); vecAt := D3DXVector3(0.0, 0.0, -0.0); g_Camera.SetViewParams(vecEye, vecAt); g_Camera.SetRadius(fObjectRadius*3.0, fObjectRadius*0.5, fObjectRadius*10.0); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also // optimizes the mesh for the graphics card's vertex cache, which improves // performance by organizing the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- var // Create a new vertex declaration to hold all the required data vertexDecl: array [0..5] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0), (Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0), (Stream: 0; Offset: 20; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0), (Stream: 0; Offset: 32; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TANGENT; UsageIndex: 0), (Stream: 0; Offset: 44; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_BINORMAL; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; pTempMesh: ID3DXMesh; bHadNormal: Boolean; bHadTangent: Boolean; bHadBinormal: Boolean; vertexOldDecl: TFVFDeclaration; iChannelIndex: LongWord; rgdwAdjacency: PDWORD; pNewMesh: ID3DXMesh; begin // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName); if V_Failed(Result) then Exit; Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh); if V_Failed(Result) then Exit; // Clone mesh to match the specified declaration: if FAILED(pMesh.CloneMesh(pMesh.GetOptions, @vertexDecl, pd3dDevice, pTempMesh)) then begin SAFE_RELEASE(pTempMesh); Result:= E_FAIL; Exit; end; //====================================================================// // Check if the old declaration contains normals, tangents, binormals // //====================================================================// bHadNormal := False; bHadTangent := False; bHadBinormal := False; if Assigned(pMesh) and SUCCEEDED(pMesh.GetDeclaration(vertexOldDecl)) then begin // Go through the declaration and look for the right channels, hoping for a match: for iChannelIndex := 0 to D3DXGetDeclLength(@vertexOldDecl) - 1 do begin if (vertexOldDecl[iChannelIndex].Usage = D3DDECLUSAGE_NORMAL) then bHadNormal := True; if (vertexOldDecl[iChannelIndex].Usage = D3DDECLUSAGE_TANGENT) then bHadTangent := True; if (vertexOldDecl[iChannelIndex].Usage = D3DDECLUSAGE_BINORMAL) then bHadBinormal := True; end; end; if (pTempMesh = nil) and not (bHadNormal and bHadTangent and bHadBinormal) then begin // We failed to clone the mesh and we need the tangent space for our effect: Result:= E_FAIL; Exit; end; //==============================================================// // Generate normals / tangents / binormals if they were missing // //==============================================================// SAFE_RELEASE(pMesh); pMesh := pTempMesh; if not bHadNormal then begin // Compute normals in case the meshes have them D3DXComputeNormals(pMesh, nil); end; GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3); try // if (rgdwAdjacency = nil) then Result:= E_OUTOFMEMORY; V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency)); // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil)); if not bHadTangent and not bHadBinormal then begin // Compute tangents, which are required for normal mapping if FAILED(D3DXComputeTangentFrameEx(pMesh, DWORD(D3DDECLUSAGE_TEXCOORD), 0, DWORD(D3DDECLUSAGE_TANGENT), 0, DWORD(D3DDECLUSAGE_BINORMAL), 0, DWORD(D3DDECLUSAGE_NORMAL), 0, 0, rgdwAdjacency, -1.01, -0.01, -1.01, pNewMesh, nil)) then begin Result:= E_FAIL; Exit; end; SAFE_RELEASE(pMesh); pMesh := pNewMesh; end; finally FreeMem(rgdwAdjacency); end; ppMesh := pMesh; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT) // or that are tied to the back buffer size //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; const ciHUDLeftBorderOffset = 170; const ciHUDVerticalSize = 170; const ciUILeftBorderOffset = 0; const ciUITopBorderOffset = 40; const ciUIVerticalSize = 600; const ciUIHorizontalSize = 300; var fAspectRatio: Single; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; if Assigned(g_pFont) then begin Result:= g_pFont.OnResetDevice; if V_Failed(Result) then Exit; end; if Assigned(g_pEffect) then begin Result:= g_pEffect.OnResetDevice; if V_Failed(Result) then Exit; end; // Create a sprite to help batch calls when drawing many lines of text Result:= D3DXCreateSprite(pd3dDevice, g_pSprite); if V_Failed(Result) then Exit; g_LightControl.OnResetDevice(pBackBufferSurfaceDesc ); // Setup the camera's projection parameters fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 5000.0); g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON); g_HUD.SetLocation(pBackBufferSurfaceDesc.Width - ciHUDLeftBorderOffset, 0); g_HUD.SetSize(ciHUDLeftBorderOffset, ciHUDVerticalSize); g_SampleUI.SetLocation(ciUILeftBorderOffset, ciUITopBorderOffset); g_SampleUI.SetSize(ciUIHorizontalSize, ciUIVerticalSize); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; begin // Update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); end; //-------------------------------------------------------------------------------------- // Render the scene using the D3D9 device //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var mWorldViewProjection: TD3DXMatrixA16; vLightDir: TD3DXVector3; vLightDiffuse: TD3DXColor; iPass, cPasses: LongWord; m, mWorld, mView, mProjection: TD3DXMatrixA16; arrowColor: TD3DXColor; vWhite: TD3DXColor; vEye: TD3DXVector4; vTemp: TD3DXVector3; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // Clear the render target and the zbuffer V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DXColorToDWord(D3DXCOLOR(0.0, 0.25, 0.25, 0.55)), 1.0, 0)); // Render the scene if FAILED(pd3dDevice.BeginScene) then begin // Failed to being rendering scene, not much we can do not: WriteLn('BeginScene FAILED'); Exit; end; if Assigned(g_pEffect) then begin // Get the projection & view matrix from the camera class D3DXMatrixMultiply(mWorld, g_mWorldFix, g_Camera.GetWorldMatrix^); mProjection := g_Camera.GetProjMatrix^; mView := g_Camera.GetViewMatrix^; // mWorldViewProjection = mWorld * mView * mProj; D3DXMatrixMultiply(m, mView, mProjection); D3DXMatrixMultiply(mWorldViewProjection, mWorld, m); // Get camera position: vTemp := g_Camera.GetEyePt^; vEye.x := vTemp.x; vEye.y := vTemp.y; vEye.z := vTemp.z; vEye.w := 1.0; // Render the light arrow so the user can visually see the light dir arrowColor := D3DXColor(1,1,0,1); V(g_LightControl.OnRender(arrowColor, mView, mProjection, g_Camera.GetEyePt^)); vLightDir := g_LightControl.LightDirection; D3DXColorScale(vLightDiffuse, D3DXColor(1, 1, 1, 1), g_fLightScale); // vLightDiffuse := g_fLightScale * D3DXColor(1, 1, 1, 1); V(g_pEffect.SetValue('g_LightDir', @vLightDir, SizeOf(TD3DXVECTOR3))); V(g_pEffect.SetValue('g_LightDiffuse', @vLightDiffuse, SizeOf(TD3DXVECTOR4))); // Update the effect's variables. Instead of using strings, it would // be more efficient to cache a handle to the parameter by calling // ID3DXEffect::GetParameterByName V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection)); V(g_pEffect.SetMatrix('g_mWorld', mWorld)); V(g_pEffect.SetMatrix('g_mView', mView)); V(g_pEffect.SetVector('g_vEye', vEye)); V(g_pEffect.SetValue ('g_fHeightMapScale', @g_fHeightScale, SizeOf(Single))); vWhite := D3DXColor(1,1,1,1); V(g_pEffect.SetValue('g_materialDiffuseColor', @vWhite, SizeOf(TD3DXCOLOR))); V(g_pEffect.SetValue('g_materialAmbientColor', @g_colorMtrlAmbient, SizeOf(TD3DXCOLOR))); V(g_pEffect.SetValue('g_materialDiffuseColor', @g_colorMtrlDiffuse, SizeOf(TD3DXCOLOR))); V(g_pEffect.SetValue('g_materialSpecularColor', @g_colorMtrlSpecular, SizeOf(TD3DXCOLOR))); V(g_pEffect.SetValue('g_fSpecularExponent', @g_fSpecularExponent, SizeOf(Single))); V(g_pEffect.SetValue('g_fBaseTextureRepeat', @g_fBaseTextureRepeat, SizeOf(Single))); V(g_pEffect.SetValue('g_nLODThreshold', @g_nLODThreshold, SizeOf(Integer))); V(g_pEffect.SetValue('g_nMinSamples', @g_nMinSamples, SizeOf(Integer))); V(g_pEffect.SetValue('g_nMaxSamples', @g_nMaxSamples, SizeOf(Integer))); V(g_pEffect.SetValue('g_fShadowSoftening', @g_fShadowSoftening, SizeOf(Single))); V(g_pEffect.SetBool('g_bVisualizeLOD', g_bVisualizeLOD)); V(g_pEffect.SetBool('g_bVisualizeMipLevel', g_bVisualizeMipLevel)); V(g_pEffect.SetBool('g_bDisplayShadows', g_bDisplayShadows)); V(g_pEffect.SetBool('g_bAddSpecular', g_bAddSpecular)); // Render the scene: case g_nCurrentTechniqueID of tidPOM: V(g_pEffect.SetTechnique('RenderSceneWithPOM')); tidBumpmap: V(g_pEffect.SetTechnique('RenderSceneWithBumpMap')); tidPM: V(g_pEffect.SetTechnique('RenderSceneWithPM')); end; V(g_pEffect._Begin(@cPasses, 0)); for iPass := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(iPass)); V(g_pMesh.DrawSubset(0)); V(g_pEffect.EndPass); end; V( g_pEffect._End); end; g_HUD.OnRender(fElapsedTime); g_SampleUI.OnRender(fElapsedTime); RenderText(fTime); V(pd3dDevice.EndScene); end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont // interface for efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText(fTime: Double); var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work fine however the // pFont->DrawText() will not be batched together. Batching calls will improves perf. txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pSprite, 15); try // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(2, 0); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats(True)); txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); // Draw help if g_bShowHelp then begin pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; txtHelper.SetInsertionPos(2, pd3dsdBackBuffer.Height-15*6); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0)); txtHelper.DrawTextLine('Controls:'); txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Rotate model: Left mouse button'#10+ 'Rotate light: Right mouse button'#10+ 'Rotate camera: Middle mouse button'#10+ 'Zoom camera: Mouse wheel scroll'#10); txtHelper.SetInsertionPos(250, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Hide help: F1'#10+ 'Quit: ESC'#10); end else begin txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper._End; finally txtHelper.Free; end; end; //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass the message to be handled to the light control: g_LightControl.HandleMessages( hWnd, uMsg, wParam, lParam ); // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin if bKeyDown then begin case nChar of VK_F1: g_bShowHelp := not g_bShowHelp; end; end; end; //-------------------------------------------------------------------------------------- // Switches to a specified pair of the POM texture pair from user input //-------------------------------------------------------------------------------------- procedure casePOMTextures(const pSelectedItem: PDXUTComboBoxItem); var strLabel: array[0..s_iMAX_STRING_SIZE-1] of WideChar; pHeightRangeSlider: CDXUTSlider; pHeightRangeStatic: CDXUTStatic; pSpecularSlider: CDXUTSlider; pSpecularStatic: CDXUTStatic; pMinSlider: CDXUTSlider; pMinStatic: CDXUTStatic; pMaxSlider: CDXUTSlider; pMaxStatic: CDXUTStatic; begin SetPOMTextures(TPOM_TextureIDs(pSelectedItem.pData)); // Update the appropriate slider controls' bounds and values: pHeightRangeSlider := g_SampleUI.GetSlider(IDC_HEIGHT_SCALE_SLIDER); if Assigned(pHeightRangeSlider) then begin pHeightRangeSlider.SetRange(g_iHeightScaleSliderMin, g_iHeightScaleSliderMax); pHeightRangeSlider.Value := Trunc(g_fHeightScale * g_fHeightScaleUIScale); end; // Update the static parameter value: pHeightRangeStatic := g_SampleUI.GetStatic(IDC_HEIGHT_SCALE_STATIC); if Assigned(pHeightRangeStatic) then begin // StringCchFormat(strLabel, s_iMAX_STRING_SIZE, 'Height scale: %0.2f', [g_fHeightScale]); StringCchFormat(strLabel, s_iMAX_STRING_SIZE, 'Height scale: %f', [g_fHeightScale]); pHeightRangeStatic.Text := strLabel; end; // Update the appropriate slider controls' bounds and values: pSpecularSlider := g_SampleUI.GetSlider(IDC_SPECULAR_EXPONENT_SLIDER); if Assigned(pSpecularSlider) then begin pSpecularSlider.Value := Trunc(g_fSpecularExponent); end; pSpecularStatic := g_SampleUI.GetStatic(IDC_SPECULAR_EXPONENT_STATIC); if Assigned(pSpecularStatic) then begin StringCchFormat(strLabel, s_iMAX_STRING_SIZE, 'Specular exponent: %f', [g_fSpecularExponent]); pSpecularStatic.Text := strLabel; end; // Mininum number of samples slider pMinSlider := g_SampleUI.GetSlider( IDC_MIN_NUM_SAMPLES_SLIDER); if Assigned(pMinSlider) then begin pMinSlider.Value := g_nMinSamples; end; pMinStatic := g_SampleUI.GetStatic(IDC_MIN_NUM_SAMPLES_STATIC); if Assigned(pMinStatic) then begin StringCchFormat(strLabel, s_iMAX_STRING_SIZE, 'Minium number of samples: %d', [g_nMinSamples]); pMinStatic.Text := strLabel; end; // Maximum number of samples slider pMaxSlider := g_SampleUI.GetSlider(IDC_MAX_NUM_SAMPLES_SLIDER); if Assigned(pMaxSlider) then begin pMaxSlider.Value := g_nMaxSamples; end; pMaxStatic := g_SampleUI.GetStatic(IDC_MAX_NUM_SAMPLES_STATIC); if Assigned(pMaxStatic) then begin StringCchFormat(strLabel, s_iMAX_STRING_SIZE, 'Maximum number of samples: %d', [g_nMaxSamples]); pMaxStatic.Text := strLabel; end; end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var sz: array[0..s_iMAX_STRING_SIZE-1] of WideChar; pSelectedItem: PDXUTComboBoxItem; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_SPECULAR_EXPONENT_SLIDER: begin g_fSpecularExponent := g_SampleUI.GetSlider(IDC_SPECULAR_EXPONENT_SLIDER).Value; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Specular exponent: %f', [g_fSpecularExponent]); g_SampleUI.GetStatic(IDC_SPECULAR_EXPONENT_STATIC).Text := sz; end; IDC_HEIGHT_SCALE_SLIDER: begin g_fHeightScale := g_SampleUI.GetSlider(IDC_HEIGHT_SCALE_SLIDER).Value / g_fHeightScaleUIScale; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Height scale: %f', [g_fHeightScale]); g_SampleUI.GetStatic(IDC_HEIGHT_SCALE_STATIC).Text := sz; end; IDC_MIN_NUM_SAMPLES_SLIDER: begin g_nMinSamples := g_SampleUI.GetSlider(IDC_MIN_NUM_SAMPLES_SLIDER).Value; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Minimum number of samples: %d', [g_nMinSamples]); g_SampleUI.GetStatic(IDC_MIN_NUM_SAMPLES_STATIC).Text := sz; end; IDC_MAX_NUM_SAMPLES_SLIDER: begin g_nMaxSamples := g_SampleUI.GetSlider(IDC_MAX_NUM_SAMPLES_SLIDER).Value; StringCchFormat(sz, s_iMAX_STRING_SIZE, 'Maximum number of samples: %d', [g_nMaxSamples]); g_SampleUI.GetStatic(IDC_MAX_NUM_SAMPLES_STATIC).Text := sz; end; IDC_TOGGLE_SHADOWS: begin // Toggle shadows static button: g_bDisplayShadows := CDXUTCheckBox(pControl).Checked; if g_bDisplayShadows then g_SampleUI.GetCheckBox(IDC_TOGGLE_SHADOWS).Text := 'Toggle self-occlusion shadows rendering: ON ' else g_SampleUI.GetCheckBox(IDC_TOGGLE_SHADOWS).Text := 'Toggle self-occlusion shadows rendering: OFF '; end; IDC_TECHNIQUE_COMBO_BOX: begin pSelectedItem := CDXUTComboBox(pControl).GetSelectedItem; if (pSelectedItem <> nil) then g_nCurrentTechniqueID := TTechniqueIDs(pSelectedItem.pData); end; IDC_TOGGLE_SPECULAR: begin // Toggle specular static button: g_bAddSpecular := CDXUTCheckBox(pControl).Checked; if g_bAddSpecular then g_SampleUI.GetCheckBox(IDC_TOGGLE_SPECULAR).Text := 'Toggle specular: ON' else g_SampleUI.GetCheckBox(IDC_TOGGLE_SPECULAR).Text := 'Toggle specular: OFF'; end; IDC_SELECT_TEXTURES_COMBOBOX: begin pSelectedItem := CDXUTComboBox(pControl).GetSelectedItem; if (pSelectedItem <> nil) then casePOMTextures(pSelectedItem); end; IDC_RELOAD_BUTTON: begin V(LoadEffectFile); end; end; end; //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9ResetDevice callback //-------------------------------------------------------------------------------------- procedure OnLostDevice; stdcall; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; CDXUTDirectionWidget.StaticOnLostDevice; if Assigned(g_pFont) then g_pFont.OnLostDevice; if Assigned(g_pEffect) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pSprite); end; //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9CreateDevice callback //-------------------------------------------------------------------------------------- procedure OnDestroyDevice; stdcall; var iTextureIndex: TPOM_TextureIDs; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; CDXUTDirectionWidget.StaticOnDestroyDevice; SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); SAFE_RELEASE(g_pMesh); for iTextureIndex := Low(iTextureIndex) to High(iTextureIndex) do begin SAFE_RELEASE(g_pBaseTextures[iTextureIndex]); SAFE_RELEASE(g_pNMHTextures[iTextureIndex]); end; Dispose(g_pBaseTextures); Dispose(g_pNMHTextures); g_pD3DDevice := nil; end; procedure CreateCustomDXUTobjects; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_LightControl:= CDXUTDirectionWidget.Create; // Scene light g_Camera:= CModelViewerCamera.Create; // A model viewing camera g_HUD:= CDXUTDialog.Create; // manages the 3D UI g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls end; procedure DestroyCustomDXUTobjects; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_LightControl); FreeAndNil(g_Camera); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); end; end.