text
stringlengths
14
6.51M
unit MediaTran; interface uses Windows; const DLL_MediaTransmit = 'MediaTransmit.dll'; type TusRole = ( WORK_AS_SERVER, WORK_AS_CLIENT, WORK_AS_SUPPLY ); TdwMode = ( SAVE_VIDEO_DATA, SAVE_AUDIO_DATA ); TMPEG4_VERSION = ( MPEG4_V1, MPEG4_V2, MPEG4_V3, MPEG4_XVID, WMV9 ); VIDINFO = record dwWidth: longword; dwHeight: longword; nCompressor: TMPEG4_VERSION; end; PVIDINFO = ^VIDINFO; // callback function api ////////////////////////////////////////////////////////////////////////// TEvCaptureAbnormity = procedure(nCallID: LongWord; nError: LongWord); stdcall; TEvInComingRequest = function(dwIp: longword; usPort: word; biCardNo: BYTE; biCmd: BYTE; lpInData: PBYTE; biInSize: word; lpOutData: pbyte; var biOutSize: word): BYTE; stdcall; TEvCmdRespond = procedure(nCallId: longword; biCmd: char; nResult: longword; pRetData: pbyte); stdcall; //server function api //////////////////////////////////////////////////////////////////////////////////////////////////////// ///注册用于接收请求的回调函数 function MTARegNotifier(evNotifier: TEvInComingRequest): bool; stdcall; external DLL_MediaTransmit; ////初始化开发包,分配相应系统资源 function MTALoadLibrary(usLocalPort: word; usRole: TusRole): bool; stdcall; external DLL_MediaTransmit; //// 释放开发包分配的系统资源 procedure MTAFreeLibrary(); stdcall; external DLL_MediaTransmit; ////////发送视频数据帧。该函数须实时调用 function MTAWriteVideo(nCardNo: byte; pData: pbyte; lSize: longword; bIFrm: longbool): longbool; stdcall; external DLL_MediaTransmit; /////// 设置请求超时的时间长度 procedure MTASetRequestTimeOut(usTimeOut: word); stdcall; external DLL_MediaTransmit; //////////////////////////////////////////////////////////////////////////////////////////// // client delphi api //////////////////////////////////////////////////////////////// ////创建视频显示窗口和Overlay显示表面 function MTACreateVideoDevice(hParentWnd: HWND; hNotifyWnd: HWND; rect: TRect; nWidth: longword; nHeight: longword; nSpace: longword; bUseOverlay: longword): longword; stdcall; external DLL_MediaTransmit; /////申请呼叫资源 function MTANewCall(pRemoteIp: pchar; usRemotePortL: WORD; biCardNo: BYTE): longword; stdcall; external DLL_MediaTransmit; /////////发起呼叫,请求媒体传送服务 function MTAMakeCall(nCallID: Longword; biReqType: byte; bWANCall: boolean; lpSndData: pbyte; biSndSize: byte; hEventNotify: Thandle; evCallNotify: TEvCmdRespond): boolean; stdcall; external DLL_MediaTransmit; ///清除呼叫,释放系统资源 procedure MTAClearCall(nCallId: longword; bWait: boolean); stdcall; external DLL_MediaTransmit; //// 服务端强制停止一路呼叫 procedure MTADiscardCall(biCard: BYTE; dwRemoteIp: longword; usRemotePort: longword; bWait: boolean); stdcall; external DLL_MediaTransmit; ///// 设置视频窗口的显示切分模式 function MTASetSplitMode(nMode: longword): longword; stdcall; external DLL_MediaTransmit; function MTAPageDown(): longword; stdcall; external DLL_MediaTransmit; function MTAPageUp(): longword; stdcall; external DLL_MediaTransmit; function MTAGetPageNo(): longword; stdcall; external DLL_MediaTransmit; function MTASetVideoOut(nCallID: longword; nIndex: longword; pVidInfo: PVIDINFO): boolean; stdcall; external DLL_MediaTransmit; procedure MTASetLastError(Errno: integer); stdcall; external DLL_MediaTransmit; function MTAGetIndexByCallID(nCallID: longword): longword; stdcall; external DLL_MediaTransmit; function MTAStartCapture(nCallID: LongWord; pFileName: PChar; dwMode: LongWord; evCapAbnormity: TEvCaptureAbnormity): LongWord; stdcall; external DLL_MediaTransmit; procedure MTAStopCapture(Errno: integer); stdcall; external DLL_MediaTransmit; function MTANewPlayBack(lpFileName: pchar): longword; stdcall; external DLL_MediaTransmit; function MTAFreePalyBack(nPlayBackId: LongWord): LongWord; stdcall; external DLL_MediaTransmit; function MTAOpenFile(nPlayBackID: LongWord; lpFileName: pchar): LongWord; stdcall; external DLL_MediaTransmit; function MTACloseFile(nPlayBackID: LongWord): LongWord; stdcall; external DLL_MediaTransmit; function MTAStartPlay(nPlayBackID: LongWord; dwMode: LongWord): LongWord; stdcall; external DLL_MediaTransmit; ////////////////////////////////////////////////////////////////////////////////////////////////// var VideoInfo: VIDINFO; pVideoInfo: PVIDINFO; implementation end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.objectset.bind; interface uses DB, Rtti, Classes, SysUtils, TypInfo, Variants, StrUtils, /// orm ormbr.mapping.rttiutils, ormbr.factory.interfaces, ormbr.mapping.classes, ormbr.rtti.helper, ormbr.objects.helper, ormbr.mapping.attributes, ormbr.types.mapping; type IBindObject = interface ['{5B46A5E9-FE26-4FB0-A6EF-758D00BC0600}'] procedure SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject); overload; procedure SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject; AAssociation: TAssociationMapping); overload; end; TBindObject = class(TInterfacedObject, IBindObject) private class var FInstance: IBindObject; FContext: TRttiContext; procedure SetPropertyValue(AResultSet: IDBResultSet; AObject: TObject; AColumn: TColumnMapping); private constructor CreatePrivate; public { Public declarations } constructor Create; class function GetInstance: IBindObject; procedure SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject); overload; procedure SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject; AAssociation: TAssociationMapping); overload; end; implementation uses ormbr.mapping.explorer, ormbr.types.blob; { TBindObject } constructor TBindObject.Create; begin raise Exception.Create('Para usar o MappingEntity use o método TBindObject.GetInstance()'); end; constructor TBindObject.CreatePrivate; begin inherited; FContext := TRttiContext.Create; end; class function TBindObject.GetInstance: IBindObject; begin if not Assigned(FInstance) then FInstance := TBindObject.CreatePrivate; Result := FInstance; end; procedure TBindObject.SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject; AAssociation: TAssociationMapping); var LColumn: TColumnMapping; LColumns: TColumnMappingList; begin LColumns := TMappingExplorer.GetInstance.GetMappingColumn(AObject.ClassType); for LColumn in LColumns do begin if AAssociation.Multiplicity in [OneToOne, ManyToOne] then begin if AAssociation.ColumnsSelectRef.Count > 0 then begin if (AAssociation.ColumnsSelectRef.IndexOf(LColumn.ColumnName) > -1) or (AAssociation.ColumnsNameRef.IndexOf(LColumn.ColumnName) > -1) then begin SetPropertyValue(AResultSet, AObject, LColumn); end; end else SetPropertyValue(AResultSet, AObject, LColumn); end else if AAssociation.Multiplicity in [OneToMany, ManyToMany] then SetPropertyValue(AResultSet, AObject, LColumn); end; end; procedure TBindObject.SetPropertyValue(AResultSet: IDBResultSet; AObject: TObject; AColumn: TColumnMapping); var LValue: Variant; LBlobField: TBlob; LProperty: TRttiProperty; begin /// <summary> /// Só alimenta a propriedade se existir o campo correspondente. /// </summary> // if LField <> nil then // begin LValue := AResultSet.GetFieldValue(AColumn.ColumnName); LProperty := AColumn.PropertyRtti; case LProperty.PropertyType.TypeKind of tkString, tkWString, tkUString, tkWChar, tkLString, tkChar: if TVarData(LValue).VType <= varNull then LProperty.SetValue(AObject, string('')) else LProperty.SetValue(AObject, string(LValue)); tkInteger, tkSet, tkInt64: if TVarData(LValue).VType <= varNull then LProperty.SetValue(AObject, Integer(0)) else LProperty.SetValue(AObject, Integer(LValue)); tkFloat: begin if TVarData(LValue).VType <= varNull then LProperty.SetValue(AObject, Integer(0)) else if LProperty.PropertyType.Handle = TypeInfo(TDateTime) then LProperty.SetValue(AObject, TDateTime(LValue)) else if LProperty.PropertyType.Handle = TypeInfo(TTime) then LProperty.SetValue(AObject, TDateTime(LValue)) else LProperty.SetValue(AObject, Currency(LValue)) end; tkRecord: begin if LProperty.IsBlob then begin if (not VarIsEmpty(LValue)) and (not VarIsNull(LValue)) then begin LBlobField := LProperty.GetValue(AObject).AsType<TBlob>; LBlobField.SetBytes(LValue); LProperty.SetValue(AObject, TValue.From<TBlob>(LBlobField)); end; end else LProperty.SetNullableValue(AObject, LProperty.PropertyType.Handle, LValue); end; tkEnumeration: begin if AColumn.FieldType = ftFixedChar then LProperty.SetValue(AObject, LProperty.GetEnumStringValue(LValue)) else if Acolumn.FieldType = ftString then LProperty.SetValue(AObject, LProperty.GetEnumStringValue(LValue)) else if Acolumn.FieldType = ftInteger then LProperty.SetValue(AObject, LProperty.GetEnumIntegerValue(LValue)); end; end; // end; end; procedure TBindObject.SetFieldToProperty(AResultSet: IDBResultSet; AObject: TObject); var LColumn: TColumnMapping; LColumns: TColumnMappingList; begin LColumns := TMappingExplorer.GetInstance.GetMappingColumn(AObject.ClassType); for LColumn in LColumns do SetPropertyValue(AResultSet, AObject, LColumn); end; end.
Procedure ListarMaterias ( Var Lista : TPuntero; aVecDias : tVecDias ); Function BuscaLeg ( Var Legajo : Longint ) : Longint; Var Enc : Boolean; Regalu : tRegAlu; Alu : tArchAlu; Pm,Pi,Pf : Longint; Begin Assign( alu,'DAT\Alumnos.dat' ); Reset ( alu ); Pi := 1; Pf := FileSize ( alu ) - 1; Enc:=false; While not(enc) do Begin Pm := (pi+pf) div 2; Seek (alu,pm); Read (alu,regalu); If legajo=regalu.leg*10+regalu.dig Then enc:=true else begin if legajo < regalu.leg*10+regalu.dig then pf:=pm-1 else pi:=pm+1 end; {Else} End; {While} BuscaLeg := Pm; Close ( alu ); End; Function BuscaPosMat ( Var vMat : TVecMat; lTopVMat : Longint; Materia : LongInt ) : Byte; Var PosMat,Pm,Pi,Pf : Longint; Begin Pi := 1; Pf := lTopVMat; PosMat := 0; While PosMat = 0 Do Begin Pm := ( Pi + Pf ) Div 2; If vMat [ Pm ].CodMat = Materia Then PosMat := Pm Else If vMat [ Pm ].CodMat > Materia Then Pf := Pm - 1 Else Pi := PM + 1 End; { While } BuscaPosMat := PosMat; End; Procedure InsertaNodo ( Var aMat : tVecMat; Legajo, Curso, Materia, PosMateria : Longint ); Var PtrCurso, PtrCursoAux : TPunteroCurso; PtrAux, PtrLeg, PtrLegAux : TPunteroLeg; rCurso : tRegCurso; Begin If ( aMat [ PosMateria ].PtrCurso = Nil ) Or ( Curso < aMat [ PosMateria ].PtrCurso^.Curso ) Then Begin New ( PtrCurso ); PtrCurso^.Curso := Curso; PtrCurso^.Pos := BuscaPosCurso ( Curso,rCurso ); PtrCurso^.PtrLeg := Nil; PtrCurso^.Sgte := aMat [ PosMateria ].PtrCurso; aMat [ PosMateria ].PtrCurso := PtrCurso; End Else Begin PtrCursoAux := aMat [ PosMateria ].PtrCurso; While ( PtrCursoAux^.Sgte <> Nil ) AND ( PtrCursoAux^.Sgte^.Curso < Curso ) Do PtrCursoAux := PtrCursoAux^.Sgte; If PtrCursoAux^.Curso = Curso Then PtrCurso := PtrCursoAux Else Begin New ( PtrCurso ); PtrCurso^.Curso := Curso; PtrCurso^.Pos := BuscaPosCurso ( Curso,rCurso ); PtrCurso^.PtrLeg := Nil; PtrCurso^.Sgte := PtrCursoAux^.Sgte; PtrCursoAux^.Sgte := PtrCurso; End; End; If ( PtrCurso^.PtrLeg = Nil ) OR ( Legajo < PtrCurso^.PtrLeg^.Leg ) Then Begin New ( PtrLeg ); PtrLeg^.Leg := Legajo; PtrLeg^.Pos := BuscaLeg ( Legajo ); PtrLeg^.Sgte := PtrCurso^.PtrLeg; PtrCurso^.PtrLeg := PtrLeg; End Else Begin PtrLegAux := PtrCurso^.PtrLeg; While ( PtrAux^.Sgte <> Nil ) AND ( PtrAux^.Sgte^.Leg > Legajo ) Do PtrLegAux := PtrLegAux^.Sgte; New ( PtrLeg ); PtrLeg^.Leg := Legajo; PtrLeg^.Pos := BuscaLeg ( Legajo ); PtrLeg^.Sgte := PtrLegAux^.Sgte; PtrLegAux^.Sgte := PtrLeg; End; End; { Procedimiento InsertaNodo } Procedure ImprimirMaterias ( Var aMat : tVecMat; lTopVecMat : Byte ); Var fMat : tArchMat; rMat : tRegMat; fCurso : tArchCurso; rCurso : tRegCurso; fAlum : tArchAlu; rAlum : tRegAlu; fProfe : tArchProfe; rProfe : tRegProfe; i : Byte; PtrCursoAux : TPunteroCurso; PtrLegAux : TPunteroLeg; Begin Assign ( fMat,'DAT\Materia.Dat' ); Assign ( fCurso,'DAT\Curso.Dat' ); Assign ( fProfe,'DAT\Profesor.Dat' ); Assign ( fAlum,'DAT\Alumnos.Dat' ); Reset ( fMat ); Reset ( fCurso ); Reset ( fProfe ); Reset ( fAlum ); For I := 1 to lTopVecMat Do Begin While aMat [ I ].PtrCurso <> NIL Do Begin ClrScr; WriteLn ( ' Codigo Materia Nombre Materia Curso' ); WriteLn ( aMat [ I ].CodMat:15,' ',BuscaNombreMat ( aMat [ I ].CodMat ):30,aMat [ I ].PtrCurso^.Curso:13 ); Seek ( fCurso,aMat [ I ].PtrCurso^.Pos ); Read ( fCurso,rCurso ); WriteLn; WriteLn ( ' Anexo Dia1 Dia2 Profesor' ); WriteLn ( rCurso.Anexo:14,aVecDias [ rCurso.Dia1 ]:17,aVecDias [ rCurso.Dia2 ]:11,rCurso.Profesor:18 ); WriteLn; WriteLn ( ' Legajo Nombre Mail' ); While aMat [ I ].PtrCurso^.PtrLeg <> NIL Do Begin Seek ( fAlum,aMat [ I ].PtrCurso^.PtrLeg^.Pos ); Read ( fAlum,rAlum ); WriteLn ( aMat [ I ].PtrCurso^.PtrLeg^.Leg:10,rAlum.NyA:30,rAlum.eMail:30 ); PtrLegAux := aMat [ I ].PtrCurso^.PtrLeg; aMat [ I ].PtrCurso^.PtrLeg := aMat [ I ].PtrCurso^.PtrLeg^.Sgte; Dispose ( PtrLegAux ); End; WriteLn; PtrCursoAux := aMat [ I ].PtrCurso; aMat [ I ].PtrCurso := aMat [ I ].PtrCurso^.Sgte; Dispose ( PtrCursoAux ); ReadKey; End; CLrScr; End; Close ( fMat ); Close ( fCurso ); Close ( fProfe ); Close ( fAlum ); End; Var fMat : tArchMat; aMat : tVecMat; rMat : tRegMat; i : Byte; PtrListaAux : TPuntero; Legajo, lTopVecMat : Longint; Materia : Longint; Curso : Word; PosMateria : Byte; Begin { Carga el contenido del archivo Materia.Dat en el vector aVecMat } Assign ( fMat,'DAT\Materia.Dat' ); Reset ( fMat ); lTopVecMat := FileSize ( fMat ); For I := 1 to lTopVecMat Do Begin Read ( fMat,rMat ); aMat [ I ].CodMat := rMat.CodigoMateria; aMat [ I ].PtrCurso := Nil; End; { For I := lTopVecMat+1 To 40 Do Begin aMat [ I ].CodMat := 0; aMat [ I ].PtrCurso := Nil; End; } Close ( fMat ); PtrListaAux := Lista; While PtrListaAux <> Nil Do Begin Legajo := PtrListaAux^.Leg; I := 0; While ( i < 5 ) AND ( PtrListaAux^.vCurso [ i+1 ] <> 0 ) Do Begin Inc ( I ); Curso := PtrListaAux^.vCurso [ i ]; Materia := BuscaMateria ( Curso ); PosMateria := BuscaPosMat ( aMat,lTopVecMat,Materia ); InsertaNodo ( aMat,Legajo,Curso,Materia,PosMateria ); End; PtrListaAux := PtrListaAux^.Sgte; End; ImprimirMaterias ( aMat,lTopVecMat ); End;
{ NPC Generator v1.8 Created by matortheeternal *What it does* Basically, this script will generate a bunch of NPCs using random values for various fields including facemorphs, face parts, hair color, head parts, tint layers, texture lighting, etc. This should allow you to generate NPCs in bulk without having to go through the lengthy and tiresome process of setting values in the CK or another utility. *Notes* - Make sure you re-generate NPC face geometry data in the Creation Kit before testing the NPCs ingame. Not doing so will result in weirdly colored NPCs. To do this you have to open the file(s) the generated NPCs are in, select their records in the Creation Kit, and then press Ctrl+Alt+F4. - You can generate NPCs using assets from your other mods by opening them in TES5Edit before you run the script. E.g. open ApachiiHairs in TES5Edit, run the script, and the generated NPCs will have a high chance of using hairs from the ApachiiHairs mod. - Generated NPCs are un-implemented in the game. To put them into Skyrim you'll have to place them into cells in the CK or use the player.placeatme command. Their formIDs will be in the format xx010800 --> xx010864, with the two xx's corresponding to the load order of the esp with the generated NPCs, if a new file was created. - You can set user variables in the constants section (line 33). } unit userscript; uses mteFunctions; const vs = 'v1.8'; // to skip a step, set the corresponding boolean constant to true skipnaming = false; skipheadparts = false; skiphaircolor = false; skipheight = false; skipweight = false; skipoutfit = false; skiplighting = false; skipmorphs = false; skipfaceparts = false; skiptintlayers = false; processesps = true; // to allow the processing of esps for NPC assets set this value to true pre = 'npcg'; // set editor ID prefix here debug = true; // debug messages var npcfile, npcrecord, racerecord, layer, baselayer: IInterface; number, created, weight, scarchance, lastnamechance, heightlow, heighthigh, race: integer; gender, kwadd, fadd, name, hair, brow, eyes, scar, fhair: string; slFemaleHairs, slFemaleBrows, slFemaleEyes, slFemaleScars, slFemaleFaces, slMaleHairs, slMaleFacialHairs, slMaleBrows, slMaleEyes, slMaleScars, slMaleFaces, slHairColors, slOutfits, slRaces, slMasters, slOutfitsBase, slDarkElfColors, slHighElfColors, slWoodElfColors, slNPCs, slHumanColors, slOrcColors, slRedguardColors, slTintColors, slMaleVoices, slFemaleVoices: TStringList; slAltmerMaleNames, slAltmerFemaleNames, slAltmerFamilyNames, slArgonianMaleNames, slArgonianFemaleNames, slArgonianFamilyNames, slBosmerMaleNames, slBosmerFemaleNames, slBosmerFamilyNames, slBretonMaleNames, slBretonFemaleNames, slBretonFamilyNames, slDunmerMaleNames, slDunmerFemaleNames, slDunmerFamilyNames, slImperialMaleNames, slImperialFemaleNames, slImperialFamilyNames, slKhajiitMaleNames, slKhajiitFemaleNames, slKhajiitFamilyNames, slNordMaleNames, slNordFemaleNames, slNordFamilyNames, slOrcMaleNames, slOrcFemaleNames, slOrcFamilyNames, slRedguardFemaleNames, slRedguardMaleNames, slRedguardFamilyNames, slGeneralMaleNames, slGeneralFemaleNames, slGeneralFamilyNames: TStringList; generate, female, variableheight, done, skipbethhairs, skipbethbrows, skipbetheyes, skipbethfhairs: boolean; nose1, nose2, jaw1, jaw2, jaw3, cheek1, cheek2, eye1, eye2, eye3, brow1, brow2, brow3, lip1, lip2, chin1, chin2, chin3, height: real; btnOk, btnCancel: TButton; lbl01, lbl02, lbl03, lbl04, lbl05, lbl06, lbl07: TLabel; ed01, ed02, ed03, ed04, ed05: TEdit; cb01, cb02: TComboBox; kb01, kb02, kb03, kb04, kb05: TCheckBox; g1: TGroupBox; //========================================================================= // OkButtonControl: Disables the OK button if invalid values entered procedure OkButtonControl; var enable: boolean; x: integer; begin enable := true; try if StrToInt(ed01.Text) > 100 then enable := false; if (StrToInt(StringReplace(ed02.Text, '%', '', [rfReplaceAll])) > 100) then enable := false; if (StrToInt(StringReplace(ed03.Text, '%', '', [rfReplaceAll])) > 100) then enable := false; x := StrToInt(StringReplace(ed04.Text, '+', '', [rfReplaceAll])); x := StrToInt(StringReplace(ed05.Text, '+', '', [rfReplaceAll])); except on Exception do enable := false; btnOk.Enabled := false; end; if enable then btnOk.Enabled := true else btnOk.Enabled := false; end; //========================================================================= // vnpcControl: Enables/disables edit boxes for variable height procedure vnpcControl(Sender: TObject); begin if kb01.State = cbChecked then begin ed04.Enabled := true; ed05.Enabled := true; end else begin ed04.Enabled := false; ed05.Enabled := false; end; end; //========================================================================= // OptionsForm: The main options form procedure OptionsForm; var frm: TForm; begin generate := false; frm := TForm.Create(nil); try frm.Caption := 'NPC Generator '+vs; frm.Width := 300; frm.Height := 400; frm.Position := poScreenCenter; frm.BorderStyle := bsDialog; lbl01 := TLabel.Create(frm); lbl01.Parent := frm; lbl01.Top := 8; lbl01.Left := 8; lbl01.Width := 90; lbl01.Height := 25; lbl01.Caption := 'Number of NPCs: '; ed01 := TEdit.Create(frm); ed01.Parent := frm; ed01.Top := lbl01.Top; ed01.Left := 106; ed01.Width := 50; ed01.Text := 50; ed01.OnChange := OkButtonControl; lbl02 := TLabel.Create(frm); lbl02.Parent := frm; lbl02.Top := lbl01.Top + 30; lbl02.Left := 8; lbl02.Width := 90; lbl02.Height := 25; lbl02.Caption := 'Gender: '; cb01 := TComboBox.Create(frm); cb01.Parent := frm; cb01.Top := lbl02.Top; cb01.Left := ed01.Left; cb01.Width := 75; cb01.Style := csDropDownList; cb01.Items.Text := 'Random'#13'Male'#13'Female'; cb01.ItemIndex := 0; lbl03 := TLabel.Create(frm); lbl03.Parent := frm; lbl03.Top := lbl02.Top + 30; lbl03.Left := 8; lbl03.Width := 90; lbl03.Height := 25; lbl03.Caption := 'Race: '; cb02 := TComboBox.Create(frm); cb02.Parent := frm; cb02.Top := lbl03.Top; cb02.Left := ed01.Left; cb02.Width := 100; cb02.Style := csDropDownList; cb02.Items.Text := 'Random'+#13+slRaces.Text; cb02.ItemIndex := 0; g1 := TGroupBox.Create(frm); g1.Parent := frm; g1.Top := lbl03.Top + 36; g1.Left := 8; g1.Width := 284; g1.Height := 85; g1.Caption := 'Asset parameters'; g1.ClientWidth := 274; g1.ClientHeight := 75; kb01 := TCheckBox.Create(g1); kb01.Parent := g1; kb01.Top := 20; kb01.Left := 8; kb01.Width := 130; kb01.Caption := 'Skip Bethesda hairs'; kb02 := TCheckBox.Create(g1); kb02.Parent := g1; kb02.Top := kb01.Top; kb02.Left := kb01.Left + kb01.Width + 8; kb02.Width := 130; kb02.Caption := 'Skip Bethesda eyes'; kb03 := TCheckBox.Create(g1); kb03.Parent := g1; kb03.Top := kb01.Top + kb01.Height + 8; kb03.Left := kb01.Left; kb03.Width := 130; kb03.Caption := 'Skip Bethesda brows'; kb04 := TCheckBox.Create(g1); kb04.Parent := g1; kb04.Top := kb03.Top; kb04.Left := kb02.Left; kb04.Width := 130; kb04.Caption := 'Skip Bethesda fhairs'; lbl04 := TLabel.Create(frm); lbl04.Parent := frm; lbl04.Top := g1.Top + 95; lbl04.Left := 8; lbl04.Width := 90; lbl04.Height := 25; lbl04.Caption := 'Scar chance: '; ed02 := TEdit.Create(frm); ed02.Parent := frm; ed02.Top := lbl04.Top; ed02.Left := ed01.Left; ed02.Width := 50; ed02.Text := '15%'; ed02.OnChange := OkButtonControl; lbl05 := TLabel.Create(frm); lbl05.Parent := frm; lbl05.Top := lbl04.Top + 30; lbl05.Left := 8; lbl05.Width := 90; lbl05.Height := 25; lbl05.Caption := 'Last name chance: '; ed03 := TEdit.Create(frm); ed03.Parent := frm; ed03.Top := lbl05.Top; ed03.Left := ed01.Left; ed03.Width := 50; ed03.Text := '15%'; ed03.OnChange := OkButtonControl; kb05 := TCheckBox.Create(frm); kb05.Parent := frm; kb05.Top := lbl05.Top + 30; kb05.Left := 8; kb05.Width := 100; kb05.Caption := 'Vary NPC height'; kb05.OnClick := vnpcControl; ed04 := TEdit.Create(frm); ed04.Parent := frm; ed04.Top := kb05.Top + 30; ed04.Left := 16; ed04.Width := 30; ed04.Text := '-5'; ed04.Enabled := false; ed04.OnChange := OkButtonControl; lbl06 := TLabel.Create(frm); lbl06.Parent := frm; lbl06.Top := ed04.Top; lbl06.Left := ed04.Left + ed04.Width + 16; lbl06.Width := 20; lbl06.Caption := 'to'; ed05 := TEdit.Create(frm); ed05.Parent := frm; ed05.Top := ed04.Top; ed05.Left := lbl06.Left + lbl06.Width + 16; ed05.Width := 30; ed05.Text := '+5'; ed05.Enabled := false; ed05.OnChange := OkButtonControl; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Left := 70; btnOk.Top := ed04.Top + 40; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 16; btnCancel.Top := btnOk.Top; if frm.ShowModal = mrOk then begin generate := true; number := StrToInt(ed01.Text); gender := Lowercase(cb01.Text); if not SameText(cb02.Text, 'Random') then race := slRaces.Objects[cb02.ItemIndex - 1]; if kb01.State = cbChecked then skipbethhairs := true; if kb02.State = cbChecked then skipbetheyes := true; if kb03.State = cbChecked then skipbethbrows := true; if kb04.State = cbChecked then skipbethfhairs := true; scarchance := StrToInt(StringReplace(ed02.Text, '%', '', [rfReplaceAll])); lastnamechance := StrToInt(StringReplace(ed03.Text, '%', '', [rfReplaceAll])); if kb05.State = cbChecked then variableheight := true else variableheight := false; if variableheight then begin heightlow := StrToInt(StringReplace(ed04.Text, '+', '', [rfReplaceAll])); heighthigh := StrToInt(StringReplace(ed05.Text, '+', '', [rfReplaceAll])); end; end; finally frm.Free; end; end; //========================================================================= // NameNPC: generates a random name for an NPC of the entered race function NameNPC(race: string): string; var name: strsing; begin if female then begin if race = 'HighElfRace' then begin name := slAltmerFemaleNames[random(slAltmerFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slAltmerFamilyNames.Count > 0) then name := name + ' ' + slAltmerFamilyNames[random(slAltmerFamilyNames.Count)]; end; if race = 'ArgonianRace' then begin name := slArgonianFemaleNames[random(slArgonianFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slArgonianFamilyNames.Count > 0) then name := name + ' ' + slArgonianFamilyNames[random(slArgonianFamilyNames.Count)]; end; if race = 'WoodElfRace' then begin name := slBosmerFemaleNames[random(slBosmerFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slBosmerFamilyNames.Count > 0) then name := name + ' ' + slBosmerFamilyNames[random(slBosmerFamilyNames.Count)]; end; if race = 'BretonRace' then begin name := slBretonFemaleNames[random(slBretonFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slBretonFamilyNames.Count > 0) then name := name + ' ' + slBretonFamilyNames[random(slBretonFamilyNames.Count)]; end; if race = 'DarkElfRace' then begin name := slDunmerFemaleNames[random(slDunmerFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slDunmerFamilyNames.Count > 0) then name := name + ' ' + slDunmerFamilyNames[random(slDunmerFamilyNames.Count)]; end; if race = 'ImperialRace' then begin name := slImperialFemaleNames[random(slImperialFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slImperialFamilyNames.Count > 0) then name := name + ' ' + slImperialFamilyNames[random(slImperialFamilyNames.Count)]; end; if race = 'KhajiitRace' then begin name := slKhajiitFemaleNames[random(slKhajiitFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slKhajiitFamilyNames.Count > 0) then name := name + ' ' + slKhajiitFamilyNames[random(slKhajiitFamilyNames.Count)]; end; if race = 'NordRace' then begin name := slNordFemaleNames[random(slNordFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slNordFamilyNames.Count > 0) then name := name + ' ' + slNordFamilyNames[random(slNordFamilyNames.Count)]; end; if race = 'OrcRace' then begin name := slOrcFemaleNames[random(slOrcFemaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slOrcFamilyNames.Count > 0) then name := name + ' ' + slOrcFamilyNames[random(slOrcFamilyNames.Count)]; end; if race = 'RedguardRace' then begin name := slRedguardFemaleNames[random(slRedguardFemaleNames.Count)]; if (random(100) + 1 > (lastnamechance/4)) and (slRedguardFamilyNames.Count > 0) then name := name + ' ' + slRedguardFamilyNames[random(slRedguardFamilyNames.Count)]; end; end else begin if race = 'HighElfRace' then begin name := slAltmerMaleNames[random(slAltmerMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slAltmerFamilyNames.Count > 0) then name := name + ' ' + slAltmerFamilyNames[random(slAltmerFamilyNames.Count)]; end; if race = 'ArgonianRace' then begin name := slArgonianMaleNames[random(slArgonianMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slArgonianFamilyNames.Count > 0) then name := name + ' ' + slArgonianFamilyNames[random(slArgonianFamilyNames.Count)]; end; if race = 'WoodElfRace' then begin name := slBosmerMaleNames[random(slBosmerMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slBosmerFamilyNames.Count > 0) then name := name + ' ' + slBosmerFamilyNames[random(slBosmerFamilyNames.Count)]; end; if race = 'BretonRace' then begin name := slBretonMaleNames[random(slBretonMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slBretonFamilyNames.Count > 0) then name := name + ' ' + slBretonFamilyNames[random(slBretonFamilyNames.Count)]; end; if race = 'DarkElfRace' then begin name := slDunmerMaleNames[random(slDunmerMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slDunmerFamilyNames.Count > 0) then name := name + ' ' + slDunmerFamilyNames[random(slDunmerFamilyNames.Count)]; end; if race = 'ImperialRace' then begin name := slImperialMaleNames[random(slImperialMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slImperialFamilyNames.Count > 0) then name := name + ' ' + slImperialFamilyNames[random(slImperialFamilyNames.Count)]; end; if race = 'KhajiitRace' then begin name := slKhajiitMaleNames[random(slKhajiitMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slKhajiitFamilyNames.Count > 0) then name := name + ' ' + slKhajiitFamilyNames[random(slKhajiitFamilyNames.Count)]; end; if race = 'NordRace' then begin name := slNordMaleNames[random(slNordMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slNordFamilyNames.Count > 0) then name := name + ' ' + slNordFamilyNames[random(slNordFamilyNames.Count)]; end; if race = 'OrcRace' then begin name := slOrcMaleNames[random(slOrcMaleNames.Count)]; if (random(100) + 1 < lastnamechance) and (slOrcFamilyNames.Count > 0) then name := name + ' ' + slOrcFamilyNames[random(slOrcFamilyNames.Count)]; end; if race = 'RedguardRace' then begin name := slRedguardMaleNames[random(slRedguardMaleNames.Count)]; if (random(100) + 1 > (lastnamechance/4)) and (slRedguardFamilyNames.Count > 0) then name := name + ' ' + slRedguardFamilyNames[random(slRedguardFamilyNames.Count)]; end; end; Result := name; end; //========================================================================= // CopyTintLayer: copy values from a tint layer to another tint layer function CopyTintLayer(source: IInterface; e: IInterface; index: integer): integer; begin senv(e, 'TINI', index); Add(e, 'TINC', True); Add(e, 'TINV', True); senv(e, 'TINV', genv(source, 'TINV')); senv(e, 'TINC\[0]', genv(source, 'TINC\[0]')); senv(e, 'TINC\[1]', genv(source, 'TINC\[1]')); senv(e, 'TINC\[2]', genv(source, 'TINC\[2]')); end; //========================================================================= // CreateTintLayer: create a tint layer randomly via a list of CLFM records function CreateTintLayer(e: IInterface; index: integer; list: TStringList; search: string; skipchance: integer; tinv: string): integer; var s: string; rn, tinvlow, tinvhigh: integer; tintrecord: IInterface; begin randomize(); tinvlow := StrToInt(Copy(tinv, 1, Pos('-', tinv) - 1)); tinvhigh := StrToInt(Copy(tinv, Pos('-', tinv) + 1, Length(tinv))); senv(e, 'TINI', index); Add(e, 'TINC', True); Add(e, 'TINV', True); senv(e, 'TINV', random(tinvhigh - tinvlow) + tinvlow); if (random(100) + 1 < skipchance) then begin seev(e, 'TINC\[0]', '255'); seev(e, 'TINC\[1]', '255'); seev(e, 'TINC\[2]', '255'); senv(e, 'TINV', 0); exit; end; done := false; While not done do begin rn := random(list.Count); if not SameText(search, '') then begin if (Pos(search, list[rn]) > 0) then done := true; end else done := true; end; s := IntToHex(list.Objects[rn], 8); tintrecord := RecordByFormID(FileByLoadOrder(StrToInt(Copy(s, 1, 2))), list.Objects[rn], True); senv(e, 'TINC\[0]', genv(tintrecord, 'CNAM\Red')); senv(e, 'TINC\[1]', genv(tintrecord, 'CNAM\Green')); senv(e, 'TINC\[2]', genv(tintrecord, 'CNAM\Blue')); end; //========================================================================= // ChooseHeadPart: choose a head part randomly from a list of headparts function ChooseHeadPart(headpart: IInterface; list: TStringList): integer; var s, rs: string; e: IInterface; fails: integer; begin rs := geev(racerecord, 'EDID'); done := false; fails := 0; While not done do begin SetNativeValue(headpart, list.Objects[random(list.Count)]); s := geev(LinksTo(ElementBySignature(LinksTo(headpart), 'RNAM')), 'EDID'); if rs = 'NordRace' then begin if s = 'HeadPartsHumansandVampires' then done := true; if s = 'HeadPartsHuman' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'BretonRace' then begin if s = 'HeadPartsHumansandVampires' then done := true; if s = 'HeadPartsHuman' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'ImperialRace' then begin if s = 'HeadPartsHumansandVampires' then done := true; if s = 'HeadPartsHuman' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'ArgonianRace' then begin if s = 'HeadPartsArgonianandVampire' then done := true; if s = 'HeadPartsArgonian' then done := true; end; if rs = 'WoodElfRace' then begin if s = 'HeadPartsElvesandVampires' then done := true; if s = 'HeadPartsWoodElf' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'DarkElfRace' then begin if s = 'HeadPartsElvesandVampires' then done := true; if s = 'HeadPartsDarkElf' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'HighElfRace' then begin if s = 'HeadPartsElvesandVampires' then done := true; if s = 'HeadPartsHighElf' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'RedguardRace' then begin if s = 'HeadPartsRedguardandVampire' then done := true; if s = 'HeadPartsHumansandVampires' then done := true; if s = 'HeadPartsHuman' then done := true; if s = 'HeadPartsAllRacesMinusBeast' then done := true; end; if rs = 'KhajiitRace' then begin if s = 'HeadPartsKhajiitandVampire' then done := true; if s = 'HeadPartsKhajiit' then done := true; end; if rs = 'OrcRace' then begin if s = 'HeadPartsOrcandVampire' then done := true; if s = 'HeadPartsOrc' then done := true; end; Inc(fails); if fails > 50 then done := true; // terminate if suitable headpart not found after 50 attempts end; end; //========================================================================= // Initialize: Handle stringlists, data, OptionsForm, and NPC generation function Initialize: integer; var i, j, k: integer; e, f, group: IInterface; s: string; r: real; begin // welcome messages AddMessage(#13#10#13#10); AddMessage('-------------------------------------------------------'); AddMessage('NPC Generator '+vs+': Generates random NPCs.'); AddMessage('-------------------------------------------------------'); // creating stringlists slMasters := TStringList.Create; slMasters.Sorted := True; slMasters.Duplicates := dupIgnore; slOutfitsBase := TStringList.Create; slOutfits := TStringList.Create; slOutfits.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\outfits.txt'); slRaces := TStringList.Create; slFemaleHairs := TStringList.Create; slFemaleBrows := TStringList.Create; slFemaleEyes := TStringList.Create; slFemaleScars := TStringList.Create; slFemaleFaces := TStringList.Create; slMaleHairs := TStringList.Create; slMaleBrows := TStringList.Create; slMaleFacialHairs := TStringList.Create; slMaleEyes := TStringList.Create; slMaleScars := TStringList.Create; slMaleFaces := TStringList.Create; slHairColors := TStringList.Create; slDarkElfColors := TStringList.Create; slHighElfColors := TStringList.Create; slHumanColors := TStringList.Create; slWoodElfColors := TStringList.Create; slRedguardColors := TStringList.Create; slOrcColors := TStringList.Create; slTintColors := TStringList.Create; slMaleVoices := TStringList.Create; slFemaleVoices := TStringList.Create; slAltmerMaleNames := TStringList.Create; slAltmerMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\AltmerMaleNames.txt'); slAltmerFemaleNames := TStringList.Create; slAltmerFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\AltmerFemaleNames.txt'); slAltmerFamilyNames := TStringList.Create; slAltmerFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\AltmerFamilyNames.txt'); slArgonianMaleNames := TStringList.Create; slArgonianMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ArgonianMaleNames.txt'); slArgonianFemaleNames := TStringList.Create; slArgonianFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ArgonianFemaleNames.txt'); slArgonianFamilyNames := TStringList.Create; slArgonianFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ArgonianFamilyNames.txt'); slBosmerMaleNames := TStringList.Create; slBosmerMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BosmerMaleNames.txt'); slBosmerFemaleNames := TStringList.Create; slBosmerFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BosmerFemaleNames.txt'); slBosmerFamilyNames := TStringList.Create; slBosmerFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BosmerFamilyNames.txt'); slBretonMaleNames := TStringList.Create; slBretonMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BretonMaleNames.txt'); slBretonFemaleNames := TStringList.Create; slBretonFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BretonFemaleNames.txt'); slBretonFamilyNames := TStringList.Create; slBretonFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\BretonFamilyNames.txt'); slDunmerMaleNames := TStringList.Create; slDunmerMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\DunmerMaleNames.txt'); slDunmerFemaleNames := TStringList.Create; slDunmerFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\DunmerFemaleNames.txt'); slDunmerFamilyNames := TStringList.Create; slDunmerFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\DunmerFamilyNames.txt'); slImperialMaleNames := TStringList.Create; slImperialMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ImperialMaleNames.txt'); slImperialFemaleNames := TStringList.Create; slImperialFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ImperialFemaleNames.txt'); slImperialFamilyNames := TStringList.Create; slImperialFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\ImperialFamilyNames.txt'); slKhajiitMaleNames := TStringList.Create; slKhajiitMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\KhajiitMaleNames.txt'); slKhajiitFemaleNames := TStringList.Create; slKhajiitFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\KhajiitFemaleNames.txt'); slKhajiitFamilyNames := TStringList.Create; slKhajiitFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\KhajiitFamilyNames.txt'); slNordMaleNames := TStringList.Create; slNordMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\NordMaleNames.txt'); slNordFemaleNames := TStringList.Create; slNordFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\NordFemaleNames.txt'); slNordFamilyNames := TStringList.Create; slNordFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\NordFamilyNames.txt'); slOrcMaleNames := TStringList.Create; slOrcMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\OrcMaleNames.txt'); slOrcFemaleNames := TStringList.Create; slOrcFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\OrcFemaleNames.txt'); slOrcFamilyNames := TStringList.Create; slOrcFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\OrcFamilyNames.txt'); slRedguardMaleNames := TStringList.Create; slRedguardMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\RedguardMaleNames.txt'); slRedguardFemaleNames := TStringList.Create; slRedguardFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\RedguardFemaleNames.txt'); slRedguardFamilyNames := TStringList.Create; slRedguardFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\RedguardFamilyNames.txt'); slGeneralMaleNames := TStringList.Create; slGeneralMaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\GeneralMaleNames.txt'); slGeneralFemaleNames := TStringList.Create; slGeneralFemaleNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\GeneralFemaleNames.txt'); slGeneralFamilyNames := TStringList.Create; slGeneralFamilyNames.LoadFromFile(ProgramPath + 'Edit Scripts\npcg\GeneralFamilyNames.txt'); if slGeneralMaleNames.Count > 0 then begin for i := 0 to slGeneralMaleNames.Count - 1 do begin slAltmerMaleNames.Add(slGeneralMaleNames[i]); slArgonianMaleNames.Add(slGeneralMaleNames[i]); slBosmerMaleNames.Add(slGeneralMaleNames[i]); slBretonMaleNames.Add(slGeneralMaleNames[i]); slDunmerMaleNames.Add(slGeneralMaleNames[i]); slImperialMaleNames.Add(slGeneralMaleNames[i]); slKhajiitMaleNames.Add(slGeneralMaleNames[i]); slNordMaleNames.Add(slGeneralMaleNames[i]); slOrcMaleNames.Add(slGeneralMaleNames[i]); slRedguardMaleNames.Add(slGeneralMaleNames[i]); end; end; if slGeneralFemaleNames.Count > 0 then begin for i := 0 to slGeneralFemaleNames.Count - 1 do begin slAltmerFemaleNames.Add(slGeneralFemaleNames[i]); slArgonianFemaleNames.Add(slGeneralFemaleNames[i]); slBosmerFemaleNames.Add(slGeneralFemaleNames[i]); slBretonFemaleNames.Add(slGeneralFemaleNames[i]); slDunmerFemaleNames.Add(slGeneralFemaleNames[i]); slImperialFemaleNames.Add(slGeneralFemaleNames[i]); slKhajiitFemaleNames.Add(slGeneralFemaleNames[i]); slNordFemaleNames.Add(slGeneralFemaleNames[i]); slOrcFemaleNames.Add(slGeneralFemaleNames[i]); slRedguardFemaleNames.Add(slGeneralFemaleNames[i]); end; end; if slGeneralFamilyNames.Count > 0 then begin for i := 0 to slGeneralFamilyNames.Count - 1 do begin slAltmerFamilyNames.Add(slGeneralFamilyNames[i]); slArgonianFamilyNames.Add(slGeneralFamilyNames[i]); slBosmerFamilyNames.Add(slGeneralFamilyNames[i]); slBretonFamilyNames.Add(slGeneralFamilyNames[i]); slDunmerFamilyNames.Add(slGeneralFamilyNames[i]); slImperialFamilyNames.Add(slGeneralFamilyNames[i]); slKhajiitFamilyNames.Add(slGeneralFamilyNames[i]); slNordFamilyNames.Add(slGeneralFamilyNames[i]); slOrcFamilyNames.Add(slGeneralFamilyNames[i]); slRedguardFamilyNames.Add(slGeneralFamilyNames[i]); end; end; // stringlists created AddMessage('Stringlists created.'); // load races for i := 0 to FileCount - 1 do begin f := FileByIndex(i); group := GroupBySignature(f, 'RACE'); //races for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); if (geev(e, 'DATA\Flags\Playable') = '1') and (slRaces.IndexOf(geev(e, 'EDID')) = -1) then slRaces.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; end; AddMessage('Races loaded. Displaying options form.'); // options form OptionsForm; if not generate then exit; // load stringlist data from available files AddMessage('Loading data from available master files.'+#13#10); for i := 0 to FileCount - 1 do begin f := FileByIndex(i); s := GetFileName(f); if (Pos('.esm', s) > 0) then slMasters.Add(s) else begin if processesps and (Pos('.esp', s) > 0) then begin if MessageDlg('Process assets in: '+s+' ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then slMasters.Add(s); end else Continue; end; group := GroupBySignature(f, 'OTFT'); //outfits for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); slOutfitsBase.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; group := GroupBySignature(f, 'CLFM'); //colors for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); s := geev(e, 'EDID'); if (Pos('HairColor', s) > 0) then slHairColors.AddObject(s, TObject(FormID(e))) else if (Pos('HighElf', s) > 0) then slHighElfColors.AddObject(s, TObject(FormID(e))) else if (Pos('DarkElf', s) > 0) then slDarkElfColors.AddObject(s, TObject(FormID(e))) else if (Pos('WoodElf', s) > 0) then slWoodElfColors.AddObject(s, TObject(FormID(e))) else if (Pos('Orc', s) > 0) then slOrcColors.AddObject(s, TObject(FormID(e))) else if (Pos('Human', s) > 0) then slHumanColors.AddObject(s, TObject(FormID(e))) else if (Pos('Redguard', s) > 0) then slRedguardColors.AddObject(s, TObject(FormID(e))) else if (Pos('Tint', s) > 0) and not SameText('RedTintPink', s) then slTintColors.AddObject(s, TObject(FormID(e))); end; group := GroupBySignature(f, 'VTYP'); //voices for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); s := geev(e, 'EDID'); if (Pos('Unique', s) > 0) then Continue; if (Pos('Old', s) > 0) then Continue; if (Pos('Orc', s) > 0) then Continue; if (Pos('Child', s) > 0) then Continue; if (Pos('Khajiit', s) > 0) then Continue; if (Pos('Nord', s) > 0) then Continue; if (Pos('DarkElf', s) > 0) then Continue; if (Pos('Argonian', s) > 0) then Continue; if (Pos('ElfHaughty', s) > 0) then Continue; if (Pos('EvenToned', s) > 0) then Continue; if (Pos('Female', s) = 1) then slFemaleVoices.AddObject(s, TObject(FormID(e))) else if (Pos('Male', s) = 1) then slMaleVoices.AddObject(s, TObject(FormID(e))); end; s := GetFileName(f); group := GroupBySignature(f, 'HDPT'); //head parts for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); if geev(e, 'DATA - Flags\Playable') = '1' then begin if geev(e, 'DATA - Flags\Male') = '1' then begin if geev(e, 'PNAM') = 'Hair' then begin if skipbethhairs and (Pos(s, bethesdaFiles) > 0) then continue; slMaleHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Facial Hair' then begin if skipbethfhairs and (Pos(s, bethesdaFiles) > 0) then continue; slMaleFacialHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Eyebrows' then begin if skipbethbrows and (Pos(s, bethesdaFiles) > 0) then continue; slMaleBrows.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Eyes' then begin if skipbetheyes and (Pos(s, bethesdaFiles) > 0) then continue; slMaleEyes.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Scar' then slMaleScars.AddObject(geev(e, 'EDID'), TObject(FormID(e))); if geev(e, 'PNAM') = 'Face' then slMaleFaces.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'DATA - Flags\Female') = '1' then begin if geev(e, 'PNAM') = 'Hair' then begin if skipbethhairs and (Pos(s, bethesdaFiles) > 0) then continue; slFemaleHairs.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Eyebrows' then begin if skipbethbrows and (Pos(s, bethesdaFiles) > 0) then continue; slFemaleBrows.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Eyes' then begin if skipbetheyes and (Pos(s, bethesdaFiles) > 0) then continue; slFemaleEyes.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; if geev(e, 'PNAM') = 'Scar' then slFemaleScars.AddObject(geev(e, 'EDID'), TObject(FormID(e))); if geev(e, 'PNAM') = 'Face' then slFemaleFaces.AddObject(geev(e, 'EDID'), TObject(FormID(e))); end; end; end; end; // have user select or create npc file npcfile := FileSelect('Choose the file you want to use as your NPC file below'); if not Assigned(npcfile) then begin AddMessage(' No npc file assigned, terminating script.'); exit; end else AddMessage(' NPCs will be stored in the file: '+GetFileName(npcfile)+#13#10); for i := 0 to slMasters.Count - 1 do if not SameText(GetFileName(npcfile), slMasters[i]) then AddMasterIfMissing(npcfile, slMasters[i]); Add(npcfile, 'NPC_', true); // npc creation loop created := 0; if number > 0 then begin AddMessage(#13#10+'Beginning NPC creation loop...'); While (created < number) do begin // create npc record AddMessage(' Creating NPC #'+IntToStr(created + 1)); npcrecord := Add(GroupBySignature(npcfile, 'NPC_'), 'NPC_', True); Add(npcrecord, 'EDID', True); Add(npcrecord, 'FULL', True); seev(npcrecord, 'EDID', pre + IntToStr(created)); // set basic npc record values // object bounds seev(npcrecord, 'OBND\X1', -22); seev(npcrecord, 'OBND\Y1', -14); seev(npcrecord, 'OBND\Z1', 0); seev(npcrecord, 'OBND\X2', 22); seev(npcrecord, 'OBND\Y2', 14); seev(npcrecord, 'OBND\Z2', 128); // configuration data seev(npcrecord, 'ACBS\Flags', '000011'); seev(npcrecord, 'ACBS\Speed Multiplier', '100'); seev(npcrecord, 'ACBS\Level', '1'); // ai data seev(npcrecord, 'AIDT\Confidence', 'Average'); seev(npcrecord, 'AIDT\Responsibility', 'No crime'); seev(npcrecord, 'AIDT\Energy Level', '50'); // other stuff seev(npcrecord, 'NAM8', 'Normal'); // sound level senv(npcrecord, 'CNAM', $0001326B); // citizen class senv(npcrecord, 'ZNAM', $00068848); // csHumanMeleeLvl2 // player skills Add(npcrecord, 'DNAM', True); seev(npcrecord, 'DNAM\Health', '100'); seev(npcrecord, 'DNAM\Magicka', '70'); seev(npcrecord, 'DNAM\Stamina', '70'); group := ElementByIndex(ElementBySignature(npcrecord, 'DNAM'), 0); for i := 0 to ElementCount(group) - 1 do SetNativeValue(ElementByIndex(group, i), 15); // done setting basic values, start random/user defined values AddMessage(' Basic NPC values set.'); // decide gender of npc female := false; if (SameText(gender, 'random') and (Random(2) = 1)) or (SameText(gender, 'female')) then begin seev(npcrecord, 'ACBS\Flags', '100011'); female := true; AddMessage(' NPC is female.'); end; if not female then AddMessage(' NPC is male.'); // decide race of npc if not Assigned(race) then begin senv(npcrecord, 'RNAM', slRaces.Objects[random(slRaces.Count)]); racerecord := LinksTo(ElementByPath(npcrecord, 'RNAM')); Add(npcrecord, 'ATKR', True); senv(npcrecord, 'ATKR', FormID(racerecord)); s := geev(racerecord, 'FULL'); if s = 'Orc' then AddMessage(' NPC is an Orc.') else if s = 'Imperial' then AddMessage(' NPC is an Imperial.') else AddMessage(' NPC is a '+s); end else begin senv(npcrecord, 'RNAM', race); racerecord := LinksTo(ElementBySignature(npcrecord, 'RNAM')); Add(npcrecord, 'ATKR', True); senv(npcrecord, 'ATKR', FormID(racerecord)); s := geev(racerecord, 'FULL'); if s = 'Orc' then AddMessage(' NPC is an Orc.') else if s = 'Imperial' then AddMessage(' NPC is an Imperial.') else AddMessage(' NPC is a '+s); end; // give npc a voice s := geev(racerecord, 'EDID'); Add(npcrecord, 'VTCK', True); if s = 'HighElfRace' then begin if female then begin if random(3) = 0 then senv(npcrecord, 'VTCK', $00013AF1) //FemaleElfHaughty else senv(npcrecord, 'VTCK', $00013ADD); //FemaleEvenToned end else begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AF0) //MaleElfHaughty else senv(npcrecord, 'VTCK', $00013AD2); //MaleEvenToned end; end else if s = 'DarkElfRace' then begin if female then begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AF3) //FemaleDarkElf else senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]); end else begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AF2) //MaleDarkElf else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end; end else if s = 'WoodElfRace' then begin if female then begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013ADD) //FemaleEvenToned else senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]); end else begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AD2) //MaleEvenToned else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end; end else if s = 'ImperialRace' then begin if female then senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]) else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end else if s = 'NordRace' then begin if female then begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AE7) //FemaleNord else senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]); end else begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AE6) //MaleNord else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end; end else if s = 'RedguardRace' then begin if female then begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013ADD) //FemaleEvenToned else senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]); end else begin if random(2) = 0 then senv(npcrecord, 'VTCK', $00013AD2) //MaleEvenToned else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end; end else if s = 'KhajiitRace' then begin if female then senv(npcrecord, 'VTCK', $00013AED) //FemaleKhajiit else senv(npcrecord, 'VTCK', $00013AEC); //MaleKhajiit end else if s = 'OrcRace' then begin if female then senv(npcrecord, 'VTCK', $00013AEB) //FemaleOrc else senv(npcrecord, 'VTCK', $00013AEA); //MaleOrc end else if s = 'ArgonianRace' then begin if female then senv(npcrecord, 'VTCK', $00013AEF) //FemaleArgonian else senv(npcrecord, 'VTCK', $00013AEE); //MaleArgonian end else if s = 'BretonRace' then begin if female then senv(npcrecord, 'VTCK', slFemaleVoices.Objects[random(slFemaleVoices.Count)]) else senv(npcrecord, 'VTCK', slMaleVoices.Objects[random(slMaleVoices.Count)]); end; AddMessage(' NPC has voice: '+geev(LinksTo(ElementBySignature(npcrecord, 'VTCK')), 'EDID')); // name npc if not skipnaming then begin s := geev(racerecord, 'EDID'); name := NameNPC(s); senv(npcrecord, 'FULL', name); s := StringReplace(pre + Trim(name), ' ', '', [rfReplaceAll]); s := StringReplace(s, '''', '', [rfReplaceAll]); s := StringReplace(s, '-', '', [rfReplaceAll]); senv(npcrecord, 'EDID', s); AddMessage(' NPC is now known as: '+name); end; // set NPC head parts if not skipheadparts then begin s := geev(racerecord, 'EDID'); group := Add(npcrecord, 'Head Parts', True); ElementAssign(group, HighInteger, nil, False); if female then begin ChooseHeadPart(ElementByIndex(group, 1), slFemaleHairs); ChooseHeadPart(ElementByIndex(group, 0), slFemaleEyes); if not SameText(s, 'KhajiitRace') then begin ElementAssign(group, HighInteger, nil, False); ChooseHeadPart(ElementByIndex(group, 0), slFemaleBrows); end; if (1 + Random(100) < scarchance) then begin ElementAssign(group, HighInteger, nil, False); ChooseHeadPart(ElementByIndex(group, 0), slFemaleScars); AddMessage(' '+name+' has some battle scars.'); end; end else begin s := geev(racerecord, 'EDID'); ChooseHeadPart(ElementByIndex(group, 1), slMaleHairs); ChooseHeadPart(ElementByIndex(group, 0), slMaleEyes); if not SameText(s, 'KhajiitRace') then begin ElementAssign(group, HighInteger, nil, False); ChooseHeadPart(ElementByIndex(group, 0), slMaleBrows); end; if (random(6) > 0) and not SameText(s, 'ArgonianRace') then begin ElementAssign(group, HighInteger, nil, False); ChooseHeadPart(ElementByIndex(group, 0), slMaleFacialHairs); end; if (1 + Random(100) < scarchance) then begin ElementAssign(group, HighInteger, nil, False); ChooseHeadPart(ElementByIndex(group, 0), slMaleScars); AddMessage(' '+name+' has some battle scars.'); end; end; AddMessage(' '+name+' has eyes and a face!'); end; // set NPC hair color if not skiphaircolor then begin senv(npcrecord, 'HCLF', slHairColors.Objects[random(slHairColors.Count)]); AddMessage(' '+name+' has dyed their hair.'); end; // set NPC height if not skipheight then begin if female then height := genv(racerecord, 'DATA\Female Height') else height := genv(racerecord, 'DATA\Male Height'); if variableheight then height := height + ((Random(heighthigh - heightlow + 1) + heightlow)/100); senv(npcrecord, 'NAM6', height); if height > 1.01 then AddMessage(' '+name+' is tall.') else if height > 0.99 then AddMessage(' '+name+' is average height.') else if height < 0.99 then AddMessage(' '+name+' is short.'); end; // set NPC weight if not skipweight then begin weight := 20 + Random(81); senv(npcrecord, 'NAM7', weight); if female then AddMessage(' '+name+' now has some skin on her bones.') else AddMessage(' '+name+' now has some skin on his bones.'); end; // set NPC outfit if not skipoutfit then begin if slOutfits.Count > 0 then begin Add(npcrecord, 'DOFT', True); k := -1; While (k = -1) do begin s := slOutfits[random(slOutfits.Count)]; k := slOutfitsBase.IndexOf(s); if (k = -1) then begin if debug then AddMessage(' !Entry '+s+' in "NPCG outfits.txt" is nonexistent.'); end; end; senv(npcrecord, 'DOFT', slOutfitsBase.Objects[k]); end; AddMessage(' '+name+' has been clothed.'); end; // set NPC texture lighting if not skiplighting then begin Add(npcrecord, 'QNAM', True); for i := 0 to ElementCount(ElementBySignature(npcrecord, 'QNAM')) - 1 do senv(npcrecord, 'QNAM\['+IntToStr(i)+']', ((Random(500001) + 30000)/1000000)); AddMessage(' '+name+' has texture lighting.'); end; // set NPC face morphs, product of two random numbers to reduce extreme facial deformation if not skipmorphs then begin Add(npcrecord, 'NAM9', True); for i := 0 to ElementCount(ElementBySignature(npcrecord, 'NAM9')) - 2 do begin r := (random(10)/10) * (random(10)/10); if random(2) = 1 then r := -r; senv(npcrecord, 'NAM9\['+IntToStr(i)+']', r); end; AddMessage(' '+name+' has had their face stretched out!'); end; // set NPC face parts if not skipfaceparts then begin Add(npcrecord, 'NAMA', True); senv(npcrecord, 'NAMA\[0]', (Random(20) + 1)); senv(npcrecord, 'NAMA\[1]', -1); senv(npcrecord, 'NAMA\[2]', (Random(20) + 1)); senv(npcrecord, 'NAMA\[3]', (Random(20) + 1)); AddMessage(' '+name+' has had their face scrambled!'); end; // set NPC tint layers if not skiptintlayers then begin s := geev(racerecord, 'EDID'); Add(npcrecord, 'Tint Layers', True); if s = 'ArgonianRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); baselayer := ElementByIndex(group, 0); CreateTintLayer(baselayer, 16, slTintColors, '', 40, '8-33'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CopyTintLayer(baselayer, layer, 32); //ArgonianNeck same as SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 80, '10-50'); //ArgonianEyeSocketUpper layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 80, '10-50'); //ArgonianEyeSocketLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 70, '10-50'); //ArgonianCheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 80, '10-50'); //ArgonianNostrils01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 80, '10-50'); //ArgonianEyeLiner layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 70, '10-50'); //ArgonianLips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 70, '10-50'); //ArgonianChin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 80, '60-100'); //ArgonianStripes01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 80, '60-100'); //ArgonianStripes02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '60-100'); //ArgonianStripes03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '60-100'); //ArgonianStripes04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 80, '60-100'); //ArgonianStripes05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 80, '10-50'); //ArgonianLaughline layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 80, '10-50'); //ArgonianForehead {layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 70, '10-50'); //ArgonianNeck} layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 80, '10-50'); //ArgonianCheeksLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 100, '60-100'); //ArgonianDirt end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 6, slTintColors, '', 80, '10-40'); //ArgonianEyeSocketUpper layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 80, '10-40'); //ArgonianEyeSocketLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 70, '10-40'); //ArgonianCheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 80, '10-40'); //ArgonianNostrils01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 80, '10-40'); //ArgonianEyeLiner layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 70, '10-40'); //ArgonianLips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 70, '10-40'); //ArgonianChin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 80, '60-100'); //ArgonianStripes01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 80, '60-100'); //ArgonianStripes02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 80, '10-40'); //ArgonianCheeksLower {layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 70, '10-40'); //ArgonianNeck} layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 80, '10-40'); //ArgonianForehead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 80, '1-10'); //ArgonianLaughline layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 80, '60-100'); //ArgonianStripes03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 100, '60-100'); //ArgonianDirt baselayer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(baselayer, 38, slTintColors, '', 40, '8-33'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CopyTintLayer(baselayer, layer, 27); //ArgonianNeck same as SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 90, '60-100'); //ArgonianStripes04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 90, '60-100'); //ArgonianStripes05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 90, '60-100'); //ArgonianStripes06 end; end else if s = 'OrcRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 13, slOrcColors, 'OrcSkinFemale', 0, '30-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines.dds layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 70, '10-40'); //FemaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 90, '1-10'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 95, '60-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 100, '40-80'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '60-100'); //FemaleHeadOrcWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 95, '60-100'); //FemaleHeadOrcWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 95, '60-100'); //FemaleHeadOrcWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 95, '60-100'); //FemaleHeadOrcWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 95, '60-100'); //FemaleHeadOrcWarPaint_05 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slOrcColors, 'OrcSkin0', 0, '30-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 90, '5-20'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 70, '10-40'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 94, '60-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 94, '60-100'); //MaleHeadOrcWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 94, '60-100'); //MaleHeadOrcWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 94, '60-100'); //MaleHeadOrcWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 94, '60-100'); //MaleHeadOrcWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 61, slTintColors, '', 94, '60-100'); //MaleHeadOrcWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 end; end else if s = 'HighElfRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 24, slHighElfColors, 'HighElfSkinFemale', 33, '30-90'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 70, '10-30'); //FemaleHeadHighElf_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 96, '60-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '60-100'); //FemaleHeadHighElfWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 95, '60-100'); //FemaleHeadHighElfWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 95, '60-100'); //FemaleHeadHighElfWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 95, '60-100'); //FemaleHeadHighElfWarPaint_04 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 5, slHighElfColors, 'HighElfSkin0', 10, '30-90'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 85, '5-25'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 70, '10-50'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 96, '60-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 end; end else if s = 'DarkElfRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 24, slDarkElfColors, 'DarkElfSkinFemale', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 40, '50-90'); //FemaleHeadDarkElf_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 95, '50-100'); //FemaleHeadDarkElfWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 95, '50-100'); //FemaleHeadDarkElfWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 95, '50-100'); //FemaleHeadDarkElfWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 95, '50-100'); //FemaleHeadDarkElfWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '50-100'); //FemaleHeadDarkElfWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 62, slTintColors, '', 100, '50-100'); //FemaleHeadBothiahTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 64, slTintColors, '', 95, '50-100'); //FemaleDarkElfWarPaint_06 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slDarkElfColors, 'DarkElfSkin0', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 61, slTintColors, '', 95, '50-100'); //MaleHeadDarkElfWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 63, slTintColors, '', 100, '50-100'); //MaleHeadBothiahTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 end; end else if s = 'WoodElfRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 24, slWoodElfColors, 'WoodElfSkinFemale', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 30, '20-90'); //FemaleHeadWoodElf_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 100, '50-100'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 95, '50-100'); //FemaleHeadWoodElfWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 95, '50-100'); //FemaleHeadWoodElfWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 95, '50-100'); //FemaleHeadWoodElfWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 95, '50-100'); //FemaleHeadWoodElfWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '50-100'); //FemaleHeadWoodElfWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slWoodElfColors, 'WoodElfSkin0', 0, '50-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '50-100'); //MaleHeadWoodElfWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 95, '50-100'); //MaleHeadWoodElfWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 95, '50-100'); //MaleHeadWoodElfWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 95, '50-100'); //MaleHeadWoodElfWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 95, '50-100'); //MaleHeadWoodElfWarPaint_05 end; end else if s = 'RedguardRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 23, slHumanColors, 'HumanSkinDark', 0, '50-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 30, '30-80'); //FemaleHeadRedguard_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 70, '5-20'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '50-100'); //FemaleHeadRedguardWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 95, '50-100'); //FemaleHeadRedguardWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 95, '50-100'); //FemaleHeadRedguardWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 95, '50-100'); //FemaleHeadRedguardWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 95, '50-100'); //FemaleHeadRedguardWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 61, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 62, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 70, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinDark', 10, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 90, '5-20'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //MaleHeadRedguard_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 63, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 64, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 65, slTintColors, '', 95, '50-100'); //MaleHeadRedguardWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 66, slTintColors, '', 95, '50-100'); //MaleHeadRedguardWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 67, slTintColors, '', 95, '50-100'); //MaleHeadRedguardWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 68, slTintColors, '', 95, '50-100'); //MaleHeadRedguardWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 69, slTintColors, '', 95, '50-100'); //MaleHeadRedguardWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 71, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01 end; end else if s = 'ImperialRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 13, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadImperial_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 95, '50-100'); //FemaleHeadImperialWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 95, '50-100'); //FemaleHeadImperialWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 95, '50-100'); //FemaleHeadImperialWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '50-100'); //FemaleHeadImperialWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 95, '50-100'); //FemaleHeadImperialWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 95, '50-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 95, '50-100'); //MaleHeadImperialWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 95, '50-100'); //MaleHeadImperialWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 95, '50-100'); //MaleHeadImperialWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 95, '50-100'); //MaleHeadImperialWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '50-100'); //MaleHeadImperialWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 end; end else if s = 'NordRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 24, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 30, '20-80'); //FemaleHeadHighElf_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 70, '5-20'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 95, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 95, '50-100'); //FemaleHeadNordWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 95, '50-100'); //FemaleHeadNordWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 95, '50-100'); //FemaleHeadNordWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 95, '50-100'); //FemaleHeadNordWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 95, '50-100'); //FemaleHeadNordWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 65, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 66, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 70, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 73, slTintColors, '', 100, '1-10'); //FemaleHeadBlackBloodTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 74, slTintColors, '', 100, '1-10'); //FemaleHeadBlackBloodTattoo_02 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 100, '5-20'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //MaleHead_Frekles_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 100, '1-10'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 95, '40-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 95, '40-100'); //MaleHeadNordWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 61, slTintColors, '', 95, '40-100'); //MaleHeadNordWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 62, slTintColors, '', 95, '40-100'); //MaleHeadNordWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 63, slTintColors, '', 95, '40-100'); //MaleHeadNordWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 64, slTintColors, '', 95, '40-100'); //MaleHeadNordWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 67, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 68, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 69, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 71, slTintColors, '', 100, '1-10'); //MaleHeadBlackBloodTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 72, slTintColors, '', 100, '1-10'); //MaleHeadBlackBloodTattoo_02 end; end else if s = 'KhajiitRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 4, slTintColors, '', 40, '5-20'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketUpper layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 80, '5-30'); //KhajiitEyeliner layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 14, slTintColors, '', 80, '5-30'); //KhajiitCheekColorLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 15, slTintColors, '', 80, '5-30'); //KhajiitForehead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 16, slTintColors, '', 80, '5-30'); //KhajiitChin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 80, '5-30'); //KhajiitCheekColor layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 80, '5-30'); //KhajiitLipColor layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 80, '5-30'); //KhajiitLaughline layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 80, '5-30'); //KhajiitNeck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 95, '30-100'); //KhajiitStripes01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 95, '30-100'); //KhajiitStripes02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 95, '30-100'); //KhajiitStripes03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 95, '30-100'); //KhajiitStripes04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 95, '30-100'); //KhajiitPaint01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 95, '30-100'); //KhajiitPaint02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 95, '30-100'); //KhajiitPaint03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 95, '30-100'); //KhajiitPaint04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 80, '5-20'); //KhajiitNose01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 1, slTintColors, '', 40, '5-20'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 2, slTintColors, '', 80, '5-30'); //KhajiitCheekColorLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketUpper layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 80, '5-30'); //KhajiitCheekColor layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 80, '5-30'); //KhajiitForehead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 80, '5-30'); //KhajiitChin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 80, '5-30'); //KhajiitEyeliner layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 80, '5-30'); //KhajiitLipColor layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 80, '5-30'); //KhajiitLaughline layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 80, '5-30'); //KhajiitEyeSocketLower layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 80, '5-30'); //KhajiitNeck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 80, '5-30'); //KhajiitNose01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 95, '30-100'); //KhajiitStripes01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 95, '30-100'); //KhajiitStripes02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 95, '30-100'); //KhajiitStripes03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 95, '30-100'); //KhajiitStripes04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 95, '30-100'); //KhajiitPaint01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 95, '30-100'); //KhajiitPaint02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 95, '30-100'); //KhajiitPaint03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 95, '30-100'); //KhajiitPaint04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 end; end else if s = 'BretonRace' then begin if female then begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 16, slHumanColors, 'HumanFemaleSkinWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 17, slTintColors, '', 90, '5-20'); //FemaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 18, slTintColors, '', 90, '5-20'); //FemaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 19, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 20, slTintColors, '', 90, '5-20'); //FemaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 21, slTintColors, '', 70, '10-40'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 22, slTintColors, '', 90, '5-20'); //FemaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 23, slTintColors, '', 30, '20-80'); //FemaleHeadBreton_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 24, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 25, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 26, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 27, slTintColors, '', 90, '5-20'); //FemaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 100, '1-10'); //FemaleNordEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 40, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 41, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 42, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 43, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 44, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 45, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 46, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 47, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 48, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 49, slTintColors, '', 96, '50-100'); //FemaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 50, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 51, slTintColors, '', 96, '50-100'); //FemaleHeadImperialWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 52, slTintColors, '', 96, '50-100'); //FemaleHeadImperialWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 53, slTintColors, '', 96, '50-100'); //FemaleHeadImperialWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 54, slTintColors, '', 96, '50-100'); //FemaleHeadBretonWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 55, slTintColors, '', 96, '50-100'); //FemaleHeadBretonWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 56, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 57, slTintColors, '', 100, '1-10'); //FemaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 69, slTintColors, '', 96, '50-100'); //FemaleHeadForswornTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 70, slTintColors, '', 96, '50-100'); //FemaleHeadForswornTattoo_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 71, slTintColors, '', 96, '50-100'); //FemaleHeadForswornTattoo_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 72, slTintColors, '', 96, '50-100'); //FemaleHeadForswornTattoo_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 74, slTintColors, '', 100, '1-10'); //FemaleHeadBothiahTattoo_01 end else begin group := ElementByName(npcrecord, 'Tint Layers'); layer := ElementByIndex(group, 0); CreateTintLayer(layer, 2, slHumanColors, 'HumanSkinBaseWhite', 0, '40-100'); //SkinTone layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 3, slTintColors, '', 90, '5-20'); //MaleUpperEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 4, slTintColors, '', 90, '5-20'); //MaleLowerEyeSocket layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 5, slTintColors, '', 100, '5-20'); //RedGuardMaleEyeLinerStyle_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 6, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 7, slTintColors, '', 90, '5-20'); //MaleHead_Cheeks2 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 8, slTintColors, '', 90, '5-20'); //MaleHead_FrownLines layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 9, slTintColors, '', 90, '5-20'); //MaleHeadNord_Lips layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 10, slTintColors, '', 90, '5-20'); //MaleHead_Nose layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 11, slTintColors, '', 90, '5-20'); //MaleHeadHuman_ForeHead layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 12, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Chin layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 13, slTintColors, '', 90, '5-20'); //MaleHeadHuman_Neck layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 28, slTintColors, '', 90, '10-40'); //MaleHead_Frekles_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 29, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 30, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 31, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 32, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 33, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 34, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_06 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 35, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_07 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 36, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_08 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 37, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_09 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 38, slTintColors, '', 96, '50-100'); //MaleHeadWarPaint_10 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 39, slTintColors, '', 100, '1-10'); //MaleHeadDirt_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 58, slTintColors, '', 100, '1-10'); //MaleHeadDirt_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 59, slTintColors, '', 100, '1-10'); //MaleHeadDirt_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 60, slTintColors, '', 96, '50-100'); //MaleHeadBretonWarPaint_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 61, slTintColors, '', 96, '50-100'); //MaleHeadBretonWarPaint_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 62, slTintColors, '', 96, '50-100'); //MaleHeadBretonWarPaint_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 63, slTintColors, '', 96, '50-100'); //MaleHeadBretonWarPaint_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 64, slTintColors, '', 96, '50-100'); //MaleHeadBretonWarPaint_05 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 65, slTintColors, '', 96, '50-100'); //MaleHeadForswornTattoo_01 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 66, slTintColors, '', 96, '50-100'); //MaleHeadForswornTattoo_02 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 67, slTintColors, '', 96, '50-100'); //MaleHeadForswornTattoo_03 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 68, slTintColors, '', 96, '50-100'); //MaleHeadForswornTattoo_04 layer := ElementAssign(group, HighInteger, nil, False); CreateTintLayer(layer, 73, slTintColors, '', 100, '1-10'); //MaleHeadBothiahTattoo_01 end; end; if not female then AddMessage(' '+name+' has been dipped in a jar of paint, he''s ready to go!'); if female then AddMessage(' '+name+' has been dipped in a jar of paint, she''s ready to go!'); end; Inc(created); end; end; end; //========================================================================= // Finalize: Free stringlists, print closing messages function Finalize: integer; begin slMasters.Free; slOutfitsBase.Free; slOutfits.Free; slRaces.Free; slFemaleHairs.Free; slFemaleBrows.Free; slFemaleEyes.Free; slFemaleScars.Free; slFemaleFaces.Free; slMaleHairs.Free; slMaleBrows.Free; slMaleFacialHairs.Free; slMaleEyes.Free; slMaleScars.Free; slMaleFaces.Free; slHairColors.Free; slDarkElfColors.Free; slHighElfColors.Free; slHumanColors.Free; slWoodElfColors.Free; slRedguardColors.Free; slOrcColors.Free; slTintColors.Free; slMaleVoices.Free; slFemaleVoices.Free; slAltmerMaleNames.Free; slAltmerFemaleNames.Free; slAltmerFamilyNames.Free; slArgonianMaleNames.Free; slArgonianFemaleNames.Free; slArgonianFamilyNames.Free; slBosmerMaleNames.Free; slBosmerFemaleNames.Free; slBosmerFamilyNames.Free; slBretonMaleNames.Free; slBretonFemaleNames.Free; slBretonFamilyNames.Free; slDunmerMaleNames.Free; slDunmerFemaleNames.Free; slDunmerFamilyNames.Free; slImperialMaleNames.Free; slImperialFemaleNames.Free; slImperialFamilyNames.Free; slKhajiitMaleNames.Free; slKhajiitFemaleNames.Free; slKhajiitFamilyNames.Free; slNordMaleNames.Free; slNordFemaleNames.Free; slNordFamilyNames.Free; slOrcMaleNames.Free; slOrcFemaleNames.Free; slOrcFamilyNames.Free; slRedguardFemaleNames.Free; slRedguardMaleNames.Free; slRedguardFamilyNames; slGeneralMaleNames.Free; slGeneralFemaleNames.Free; slGeneralFamilyNames.Free; // closing messages AddMessage(#13#10); AddMessage('-------------------------------------------------------'); if not generate then AddMessage('Process terminated.'); if generate then AddMessage('The generator is done!'); if generate then AddMessage('Don''t forget to generate NPC FacegenData in the CK with Ctrl+Alt+F4!'); AddMessage(#13#10#13#10); end; end.
unit ModuleViewIntf; interface uses System.UITypes, System.Classes, Winapi.Windows, Vcl.Controls, Vcl.Graphics, TabData, Bible, HtmlView, Vcl.Tabs, Vcl.DockTabSet, ChromeTabs, ChromeTabsTypes, ChromeTabsUtils, ChromeTabsControls, ChromeTabsClasses, ChromeTabsLog; type IModuleView = interface ['{DEADBEEF-31AB-4F3A-B16F-57B47258402A}'] procedure BrowserHotSpotCovered(viewer: THTMLViewer; src: string); procedure CloseActiveTab(); procedure CopyBrowserSelectionToClipboard(); function GetActiveTabInfo(): TViewTabInfo; procedure UpdateViewTabs(); procedure ToggleStrongNumbers(); // getters function GetBrowser: THTMLViewer; function GetViewTabs: TChromeTabs; function GetBibleTabs: TDockTabSet; function GetViewName: string; // setters procedure SetViewName(viewName: string); // properties property ViewTabs: TChromeTabs read GetViewTabs; property Browser: THTMLViewer read GetBrowser; property BibleTabs: TDockTabSet read GetBibleTabs; property ViewName: string read GetViewName write SetViewName; end; implementation end.
program compilefail49(output); {procedure call instead of function call to set initial value of the for statement} var a,b,Counter:integer; procedure threetimes(a:integer); begin writeln(3 * a); end; function sixtimes(a:integer):integer; begin sixtimes := 6 * a; end; begin b := 7; for a := threetimes(b) to sixtimes(b) do begin writeln(a); end; end.
{$A+,B-,D+,E+,F+,G-,I+,L+,N-,O-,R+,S+,V+,X-} {$M 8192,0,655360} {File : SCRNSAV1.PAS, Vs. 1.1, for TP 7.0. Test of screen saver. This is only a simple example, don't expect too much. Look for all lines with +++ comment. The GetEvent and Idle method of TApplication need changes. This program disables TV GetEvent while in screen saver mode, (but see SCRNSAV2.PAS). Screen saver mode is canceled by pressing any key. Mouse moves do nothing. If the mechanism to invoke the screen server is ok for you, then just put your favorite flashy wonderful screen saver into the ScreenSaver method. Warning: There is a call to Randomize at invocation of the screen saver. This might interfere with other parts of your program. Hacked on 30-JUN-93 by Wolfgang Gross, gross@aecds.exchi.uni-heidelberg.de Comments by Rutger van de GeVEL, rutger@kub.nl. Changed: 13-JUL-93 bugs, minor improvements } program TestScreenSaver; uses CRT,DOS,Objects,memory,Drivers,Views,Menus,Dialogs,App,gadgets,msgbox; const cmAboutDialog = 101; cmTestDialog = 102; {change these constants as convenient +++} ScrnSaverText : String = 'Screen saver test lurking ...' ; {+++} GracePeriod : longint = 5000; {ask DOS time after graceperiod} {+++} {time values in centiseconds +++} {Invoke screen saver after program is idle for ScrnSaverDelay centisecs. Text stays on screen for ScnrSaverPeriod centisecs. } ScrnSaverDelay : longint = 50; {+++} ScrnSaverPeriod: longint = 50; {+++} type TMyApp = object(TApplication) KickTime : longint; {seconds} {+++} GraceCounter : word; {ask DOS time only if > graceperiod} {+++} Heap: PHeapView; Clock : PClockView; constructor init; procedure getevent( VAR event : TEvent ); virtual; procedure HandleEvent(var Event: TEvent); virtual; procedure InitMenuBar; virtual; procedure InitStatusLine; virtual; procedure AboutDialog; procedure TestDialog; procedure Idle;virtual; procedure ScreenSaver; {+++} end; FUNCTION Time:longint; {+++ we need this function +++} {Return real day time in centiseconds. One might get in trouble with measurements spanning midnight. Smallest reliable interval: 55 msec} VAR Hour,Minute,Second,Sec100: WORD; {+++} BEGIN {+++} GetTime(Hour,Minute,Second,Sec100); {+++} Time:=longint(Sec100)+100*(longint(Second) {+++} +60*(longint(Minute)+60*longint(hour))); {+++} END; {+++} CONSTRUCTOR TMyApp.Init; VAR R : TRect; BEGIN TApplication.Init; KickTime := 0; GraceCounter := 0; {+++} GetExtent(R); R.A.X := R.B.X - 9; R.B.Y := R.A.Y + 1; Clock := New(PClockView, Init(R)); Insert(Clock); GetExtent(R); Dec(R.B.X); R.A.X := R.B.X - 9; R.A.Y := R.B.Y - 1; Heap := New(PHeapView, Init(R)); Insert(Heap); END; {PROC TMyApp.Init} procedure TMyApp.GetEvent ( VAR Event : TEvent ); BEGIN inherited GetEvent(Event); {reset counter if events pending +++} IF Event.What<>evNothing THEN {+++} BEGIN GraceCounter := 0; KickTime := 0 END; {+++} END; {PROC TMyApp.GetEvent} procedure TMyApp.HandleEvent(var Event: TEvent); begin {HandleEvent} inherited HandleEvent(Event); if (Event.What = evCommand) then begin case Event.Command of cmAboutDialog : AboutDialog; cmTestDialog : TestDialog; else Exit; end; ClearEvent(Event); end end; {PROC TMyApp.HandleEvent} PROCEDURE TMyApp.Idle; BEGIN inherited Idle; Heap^.Update; Clock^.Update; IF GraceCounter < GracePeriod {start calling DOS time after +++} THEN Inc(GraceCounter) {grace period since it's too +++} ELSE {time consuming. +++} BEGIN IF KickTime=0 THEN KickTime := Time; {+++} IF (Abs(Time-KickTime)>ScrnSaverDelay) {+++} THEN ScreenSaver; {+++} END; END; {PROC TMyApp.Idle} procedure TMyApp.InitMenuBar; VAR R : TRect; begin {InitMenuBar} GetExtent(R); R.B.Y := R.A.Y+1; MenuBar := New(PMenuBar, Init(R, NewMenu( NewSubMenu('~'#240'~', 1000, NewMenu( NewItem('~A~bout', '', kbNoKey, cmAboutDialog, 1001,nil)), NewSubMenu('~F~ile', 1100, NewMenu( NewItem('~T~estDialog', '', kbF3, cmTestDialog, 1010, NewLine( NewItem('E~x~it', '', kbAltx, cmquit, 1020,nil)))), nil))))); end; {PROC TMyApp.InitMenuBar} procedure TMyApp.InitStatusLine; var R : TRect; begin {InitStatusLine} GetExtent(R); R.A.Y := R.B.Y - 1; StatusLine := New(PStatusLine,Init(R, NewStatusDef(0,$FFFF, NewStatusKey('',kbF10,cmMenu, NewStatusKey('~Alt-X~ Exit',kbAltX,cmQuit, NewStatusKey('~F3~ Testbox',kbF3,cmTestDialog, nil))), nil) )); end; {PROC TMyApp.InitStatusLine} procedure TMyApp.AboutDialog; var D : PDialog; R : TRect; Control : PView; C : word; begin {AboutDialog} R.Assign(0, 0, 40, 11); D := New(PDialog, Init(R, 'About')); with D^ do begin Options := Options or ofCentered; R.Grow(-1, -1); Dec(R.B.Y, 3); Insert(New(PStaticText, Init(R, #13 + ^C'Turbo Vision Screen Saver Demo'#13 + #13 + ^C'GetEvent disabled.'#13 + #13 + ^C'W. Gross 1993'#13 ))); R.Assign(15, 8, 25, 10); Insert(New(PButton, Init(R, 'O~K', cmOk, bfDefault))); end; if ValidView(D) <> nil then begin c := Desktop^.ExecView(D); Dispose(D, Done); end; end; {PROC TMyApp.AboutDialog} procedure TMyApp.TestDialog; var D: PDialog; c : word; begin c := messagebox ( 'This is just a dummy dialog.', nil, mfinformation+mfOkbutton ); end; {PROC TMyApp.TestDialog} PROCEDURE TMyApp.ScreenSaver; {+++} VAR LastTime : longint; ch : char; {+++} BEGIN {+++} doneevents; donevideo; Randomize; {+++} LastTime := 0; TextBackGround(Black); {+++} {+++} REPEAT {+++} IF (Abs(Time-LastTime)>ScrnSaverPeriod) THEN {+++} BEGIN {+++} ClrScr; {+++} TextColor(Random(14)+1); {+++} Gotoxy ( Random(80-length(ScrnSaverText)), {+++} Random(24)); {+++} write ( ScrnSaverText ); LastTime := Time; {+++} END; {+++} UNTIL KeyPressed; {+++} {+++} ch := ReadKey; {eat char} {+++} KickTime := 0; GraceCounter := 0; {+++} initevents; initvideo; {+++} inherited redraw; {+++} {+++} END; {PROC TMyApp.ScreenSaver} {+++} var MyApp : TMyApp; begin {SCRNSAV1} MyApp.Init; MyApp.Run; MyApp.Done; end. {SCRNSAV1}
unit Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Vcl.StdActns, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan; type TFormMain = class(TForm) GroupBox1: TGroupBox; lbxFilesToAdd: TListBox; lbTitleFilesToAdd: TLabel; Splitter1: TSplitter; lbTitleFilesToRemove: TLabel; lbxFilesToRemove: TListBox; btnMergeAllFiles: TButton; lbTitleImport: TLabel; edtImportURL: TEdit; GroupBox2: TGroupBox; Memo1: TMemo; btnImportFromWeb: TButton; lbWebImport: TLabel; IdHTTP1: TIdHTTP; Splitter2: TSplitter; ActionManager1: TActionManager; actEditCut1: TEditCut; actEditCopy1: TEditCopy; actFileSaveAs1: TFileSaveAs; PopupMenu1: TPopupMenu; Copy1: TMenuItem; Cut1: TMenuItem; actEditSelectAll1: TEditSelectAll; actEditUndo1: TEditUndo; actEditDelete1: TEditDelete; SelectAll1: TMenuItem; Delete1: TMenuItem; Undo1: TMenuItem; N1: TMenuItem; SaveAs1: TMenuItem; procedure actFileSaveAs1Accept(Sender: TObject); procedure btnImportFromWebClick(Sender: TObject); procedure btnMergeAllFilesClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure lbxFilesToAddDblClick(Sender: TObject); procedure lbxFilesToRemoveDblClick(Sender: TObject); private isImportedItemsToRemoveFromWeb: Boolean; procedure fillStringsWithTextFileNames(sl: TStrings; const dir: string); function mergeEverything(filesToAdd, filesToRemove: TStrings): string; procedure mergeAppendLinesFromAddFiles(slResultData: TStrings; filesToAdd: TStrings); procedure mergeDeleteLinesFromRemoveFiles(slResultData: TStrings; removeItemsList: TStrings); procedure mergeDeleteLinesFromList(slResultData: TStrings; slLinesToRemove: TStringList); public end; var FormMain: TFormMain; implementation {$R *.dfm} uses System.IOUtils, System.Types, Helper.TGroupBox, System.JSON, Global.AppConfiguration, Form.PreviewItem; const LIST_WEB_PREFIX = '[WEB] '; procedure TFormMain.actFileSaveAs1Accept(Sender: TObject); begin ShowMessage('not implemented yet. FielName: ' + actFileSaveAs1.Dialog.FileName); end; procedure TFormMain.btnImportFromWebClick(Sender: TObject); var cmd: string; sl: TStringList; idx: Integer; begin sl := TStringList.Create; IdHTTP1.Request.UserAgent := 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; MAAU)'; sl.Text := IdHTTP1.Get(edtImportURL.Text); lbWebImport.Caption := Format('Zaimportowano: %d linii', [sl.Count]); cmd := LIST_WEB_PREFIX + edtImportURL.Text; idx := lbxFilesToRemove.Items.IndexOf(cmd); if idx >= 0 then begin (lbxFilesToRemove.Items.Objects[idx] as TStringList).Free; lbxFilesToRemove.Items.Delete(idx); end; lbxFilesToRemove.AddItem(cmd, sl); isImportedItemsToRemoveFromWeb := True; end; procedure TFormMain.btnMergeAllFilesClick(Sender: TObject); begin if not isImportedItemsToRemoveFromWeb then ShowMessage('Nie zaimporotwano listy elementów do usuniącia w Web-a'); Memo1.Clear; Memo1.Lines.Text := mergeEverything(lbxFilesToAdd.Items, lbxFilesToRemove.Items); end; procedure TFormMain.FormCreate(Sender: TObject); begin fillStringsWithTextFileNames(lbxFilesToAdd.Items, '.\add\'); fillStringsWithTextFileNames(lbxFilesToRemove.Items, '.\remove\'); TAppConfiguration.loadSecureConfiguration(); edtImportURL.Text := TAppConfiguration.secureUrlUnsubscribe; end; procedure TFormMain.FormResize(Sender: TObject); var sumHeight: Integer; hg: Integer; begin sumHeight := GroupBox1.ChildrensSumHeight([lbxFilesToAdd, lbxFilesToRemove]); hg := (GroupBox1.ClientHeight - sumHeight) div 2; lbxFilesToAdd.Height := hg; end; procedure TFormMain.fillStringsWithTextFileNames(sl: TStrings; const dir: string); var files: TStringDynArray; i: Integer; begin files := System.IOUtils.TDirectory.GetFiles(dir, '*.txt', TSearchOption.soTopDirectoryOnly); sl.BeginUpdate; for i := 0 to Length(files) - 1 do sl.Add(files[i]); sl.EndUpdate; end; procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction); var i: Integer; begin for i := 0 to lbxFilesToRemove.Count - 1 do if lbxFilesToRemove.Items[i].StartsWith(LIST_WEB_PREFIX) then (lbxFilesToRemove.Items.Objects[i] as TStringList).Free; end; procedure TFormMain.lbxFilesToAddDblClick(Sender: TObject); var idx: Integer; ItemName: string; ItemContent: string; begin idx := lbxFilesToAdd.ItemIndex; if idx >= 0 then begin ItemName := lbxFilesToAdd.Items[idx]; if ItemName.StartsWith(LIST_WEB_PREFIX) then ItemContent := (lbxFilesToAdd.Items.Objects[idx] as TStringList).Text else ItemContent := TFile.ReadAllText(ItemName); TFormPreview.Execute(ItemContent); end; end; procedure TFormMain.lbxFilesToRemoveDblClick(Sender: TObject); var idx: Integer; ItemName: string; ItemContent: string; begin idx := lbxFilesToRemove.ItemIndex; if idx >= 0 then begin ItemName := lbxFilesToRemove.Items[idx]; if ItemName.StartsWith(LIST_WEB_PREFIX) then ItemContent := (lbxFilesToRemove.Items.Objects[idx] as TStringList).Text else ItemContent := TFile.ReadAllText(ItemName); TFormPreview.Execute(ItemContent); end; end; function TFormMain.mergeEverything(filesToAdd, filesToRemove: TStrings): string; var slResultData: TStringList; begin slResultData := TStringList.Create; try mergeAppendLinesFromAddFiles(slResultData, filesToAdd); mergeDeleteLinesFromRemoveFiles(slResultData, filesToRemove); Result := slResultData.Text; finally slResultData.Free; end; end; procedure TFormMain.mergeAppendLinesFromAddFiles(slResultData: TStrings; filesToAdd: TStrings); var fname: string; fileText: string; begin for fname in filesToAdd do begin fileText := TFile.ReadAllText(fname); slResultData.Text := slResultData.Text + fileText; end; end; procedure TFormMain.mergeDeleteLinesFromRemoveFiles(slResultData: TStrings; removeItemsList: TStrings); var slContent: TStringList; i: Integer; ItemName: string; isMemoryItem: Boolean; memoryList: TStringList; begin slContent := TStringList.Create; try for i := 0 to removeItemsList.Count - 1 do begin ItemName := removeItemsList[i]; isMemoryItem := ItemName.StartsWith(LIST_WEB_PREFIX); if isMemoryItem then begin memoryList := removeItemsList.Objects[i] as TStringList; mergeDeleteLinesFromList(slResultData, memoryList); end else begin slContent.Clear; slContent.Text := TFile.ReadAllText(ItemName); mergeDeleteLinesFromList(slResultData, slContent); end; end; finally slContent.Free; end; end; procedure TFormMain.mergeDeleteLinesFromList(slResultData: TStrings; slLinesToRemove: TStringList); var sLineToRemove: string; idx: Integer; begin for sLineToRemove in slLinesToRemove do if not sLineToRemove.Trim.IsEmpty then begin idx := slResultData.IndexOf(sLineToRemove.Trim); if idx >= 0 then slResultData.Delete(idx); end; end; end.
unit XLSReadII; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$R-} interface uses Classes, SysUtils, Windows, Messages, BIFFRecsII, CellFormats, SheetData, XLSStream, XLSReadWriteII, XLSUtils, Dialogs, DecodeFormula, MSODrawing, XLSFonts, ExcelMaskII, AnchorObject, Picture, Note, XLSChart, Validate, Math, XLSRWIIResourceStrings, SST; type TSharedFormula = record Row1,Row2: word; Col1,Col2: byte; Len: word; Formula: PByteArray; end; type TXLSReadII = class(TObject) protected PBuf: PByteArray; FXLS: TXLSReadWriteII; FCurrSheet: integer; FXLSStream: TXLSStream; FBoundsheets: TStringList; FBoundsheetIndex: integer; Header: TBIFFHeader; FSharedFormulas: array of TSharedFormula; FMSOReadGroup: TMSOReadGroup; FMSOReadDrawing: TMSOReadDrawing; FCurrAnchor: TAnchorObject; FPosStack: array[0..4] of integer; FIsReadingWorksheet: boolean; FISAPIRead: boolean; // File prefix procedure RREC_FILEPASS; procedure RREC_FILESHARING; procedure RREC_INTERFACEHDR; procedure RREC_ADDMENU; procedure RREC_DELMENU; procedure RREC_INTERFACEEND; procedure RREC_WRITEACCESS; procedure RREC_CODEPAGE; procedure RREC_DSF; procedure RREC_TABID; procedure RREC_WINDOWPROTECT; procedure RREC_PROTECT; procedure RREC_PASSWORD; procedure RREC_PROT4REV; procedure RREC_PROT4REVPASS; procedure RREC_WINDOW1; procedure RREC_BACKUP; procedure RREC_HIDEOBJ; procedure RREC_1904; procedure RREC_PRECISION; procedure RREC_REFRESHALL; procedure RREC_BOOKBOOL; procedure RREC_PALETTE; procedure RREC_FONT; procedure RREC_FORMAT; procedure RREC_XF; procedure RREC_STYLE; procedure RREC_NAME; procedure RREC_SUPBOOK; procedure RREC_EXTERNNAME; procedure RREC_EXTERNCOUNT; procedure RREC_EXTERNSHEET; procedure RREC_USESELFS; procedure RREC_BOUNDSHEET; procedure RREC_COUNTRY; procedure RREC_MSODRAWINGGROUP; procedure RREC_SST; procedure RREC_EXTSST; procedure RREC_EOF; // Sheet prefix procedure RREC_CALCMODE; procedure RREC_CALCCOUNT; procedure RREC_REFMODE; procedure RREC_ITERATION; procedure RREC_DELTA; procedure RREC_SAVERECALC; procedure RREC_PRINTHEADERS; procedure RREC_PRINTGRIDLINES; procedure RREC_GRIDSET; procedure RREC_GUTS; procedure RREC_DEFAULTROWHEIGHT; procedure RREC_WSBOOL; procedure RREC_HORIZONTALPAGEBREAKS; procedure RREC_VERTICALPAGEBREAKS; procedure RREC_HEADER; procedure RREC_FOOTER; procedure RREC_HCENTER; procedure RREC_VCENTER; procedure RREC_PLS; procedure RREC_SETUP; procedure RREC_LEFTMARGIN; procedure RREC_RIGHTMARGIN; procedure RREC_TOPMARGIN; procedure RREC_BOTTOMMARGIN; procedure RREC_DEFCOLWIDTH; procedure RREC_COLINFO; procedure RREC_DIMENSIONS; // Sheet data procedure RREC_INTEGER_20; procedure RREC_NUMBER_20; procedure RREC_LABEL_20; procedure RREC_ROW; procedure RREC_BLANK; procedure RREC_BOOLERR; procedure RREC_FORMULA; procedure RREC_FORMULA_30; procedure RREC_NUMBER; procedure RREC_RK; procedure RREC_MULRK; procedure RREC_MULBLANK; procedure RREC_LABELSST; procedure RREC_LABEL; procedure RREC_RSTRING; procedure RREC_TXO; procedure RREC_NOTE; procedure READ_SHRFMLA; // Sheet suffix procedure RREC_MSODRAWING; procedure RREC_MSODRAWINGSELECTION; procedure RREC_OBJ; procedure RREC_WINDOW2; procedure RREC_SCL; procedure RREC_PANE; procedure RREC_SELECTION; procedure RREC_DV; procedure RREC_DVAL; procedure RREC_HLINK; procedure RREC_MERGEDCELLS; procedure Clear; procedure ClearSharedFmla; function DecodeRK(Value: longint): double; procedure ReadNote(NoteId: integer); procedure ReadFormulaStr(Col,Row,FormatIndex: integer; Value: double; Formula: PByteArray; Len: integer); procedure FixupSharedFormula(ACol,ARow: integer); procedure ReadMSOGroupPicture(Pict: TXLSPicture); procedure ReadMSOSheetObject(Obj: TAnchorObject; ObjId: integer); public constructor Create(XLS: TXLSReadWriteII); destructor Destroy; override; procedure Read; property ISAPIRead: boolean read FISAPIRead write FISAPIRead; end; implementation type PWordBool = ^WordBool; type TByte8Array = array[0..7] of byte; type TByte4Array = array[0..3] of byte; constructor TXLSReadII.Create(XLS: TXLSReadWriteII); begin FXLS := XLS; FXLSStream := TXLSStream.Create; FXLSStream.SaveVBA := XLS.PreserveMacros; FBoundsheets := TStringList.Create; FMSOReadGroup := TMSOReadGroup.Create; FMSOReadGroup.OnPicture := ReadMSOGroupPicture; FMSOReadDrawing := TMSOReadDrawing.Create; FMSOReadDrawing.OnSheetObject := ReadMSOSheetObject; FCurrAnchor := TAnchorObject.Create(Nil); end; destructor TXLSReadII.Destroy; begin FMSOReadDrawing.Free; FMSOReadGroup.Free; FXLSStream.Free; FBoundsheets.Free; FCurrAnchor.Free; ClearSharedFmla; inherited Destroy; end; procedure TXLSReadII.Clear; begin FCurrSheet := -1; FBoundsheets.Clear; FBoundsheetIndex := -1; end; procedure TXLSReadII.ClearSharedFmla; var i: integer; begin for i := 0 to High(FSharedFormulas) do FreeMem(FSharedFormulas[i].Formula); SetLength(FSharedFormulas,0); end; function TXLSReadII.DecodeRK(Value: longint): double; var RK: TRK; begin RK.DW[0] := 0; RK.DW[1] := Value and $FFFFFFFC; case (Value and $3) of 0: Result := RK.V; 1: Result := RK.V / 100; 2: Result := Integer(RK.DW[1]) / 4; 3: Result := Integer(RK.DW[1]) / 400; else Result := RK.V; end; end; procedure TXLSReadII.Read; var Cnt,ProgressCount: integer; begin Clear; FXLS.WriteDefaultData := False; try FXLSStream.ISAPIRead := FISAPIRead; FXLSStream.ExtraObjects := FXLS.ExtraObjects; FXLS.Version := FXLSStream.OpenRead(FXLS.Filename); GetMem(PBuf,FXLS.MaxBuffsize); FXLSStream.ReadHeader(Header); if (Header.RecID and $FF) <> BIFFRECID_BOF then raise Exception.Create(ersBOFMissing); if Header.Length > 256 then raise Exception.Create(ersInvalidBOFSize); FXLSStream.Read(PBuf^,Header.Length); if PRecBOF8(PBuf).SubStreamType = $0010 then FCurrSheet := 0; FXLS.IsMac := (FXLS.Version >= xvExcel97) and ((PRecBOF8(PBuf).FileHistoryFlags and $00000010) = $00000010); ProgressCount := 0; Cnt := 0; if Assigned(FXLS.OnProgress) then FXLS.OnProgress(Self,0); try while FXLSStream.ReadHeader(Header) = SizeOf(TBIFFHeader) do begin Inc(Cnt); if Header.Length > FXLS.MaxBuffsize then begin FXLSStream.Seek(Header.Length,soFromCurrent); Continue; end else FXLSStream.Read(PBuf^,Header.Length); Inc(ProgressCount); if ProgressCount >= 100 then begin if Assigned(FXLS.OnProgress) then FXLS.OnProgress(Self,Round((FXLSStream.Pos / FXLSStream.Size) * 100)); ProgressCount := 0; end; case Header.RecID of BIFFRECID_EOF: begin FIsReadingWorksheet := False; ClearSharedFmla; if (FBoundsheets.Count <= 0) or (FBoundsheetIndex >= (FBoundsheets.Count - 1)) then Break; end; // File prefix BIFFRECID_FILEPASS: RREC_FILEPASS; BIFFRECID_FILESHARING: RREC_FILESHARING; BIFFRECID_INTERFACEHDR: RREC_INTERFACEHDR; BIFFRECID_INTERFACEEND: RREC_INTERFACEEND; BIFFRECID_WRITEACCESS: RREC_WRITEACCESS; BIFFRECID_CODEPAGE: RREC_CODEPAGE; BIFFRECID_DSF: RREC_DSF; BIFFRECID_TABID: RREC_TABID; BIFFRECID_WINDOWPROTECT: RREC_WINDOWPROTECT; BIFFRECID_PROTECT: RREC_PROTECT; BIFFRECID_PASSWORD: RREC_PASSWORD; BIFFRECID_PROT4REV: RREC_PROT4REV; BIFFRECID_PROT4REVPASS: RREC_PROT4REVPASS; BIFFRECID_WINDOW1: RREC_WINDOW1; BIFFRECID_BACKUP: RREC_BACKUP; BIFFRECID_HIDEOBJ: RREC_HIDEOBJ; BIFFRECID_1904: RREC_1904; BIFFRECID_PRECISION: RREC_PRECISION; BIFFRECID_REFRESHALL: RREC_REFRESHALL; BIFFRECID_BOOKBOOL: RREC_BOOKBOOL; BIFFRECID_PALETTE: RREC_PALETTE; BIFFRECID_FONT,$0231: RREC_FONT; BIFFRECID_FORMAT: RREC_FORMAT; BIFFRECID_XF_30, BIFFRECID_XF_40, BIFFRECID_XF: RREC_XF; BIFFRECID_STYLE: RREC_STYLE; BIFFRECID_NAME,$0218: RREC_NAME; BIFFRECID_SUPBOOK: RREC_SUPBOOK; BIFFRECID_EXTERNNAME,$0223: RREC_EXTERNNAME; BIFFRECID_EXTERNCOUNT: RREC_EXTERNCOUNT; BIFFRECID_EXTERNSHEET: RREC_EXTERNSHEET; BIFFRECID_USESELFS: RREC_USESELFS; BIFFRECID_BOUNDSHEET: RREC_BOUNDSHEET; BIFFRECID_COUNTRY: RREC_COUNTRY; BIFFRECID_MSODRAWINGGROUP: RREC_MSODRAWINGGROUP; BIFFRECID_SST: RREC_SST; BIFFRECID_EXTSST: RREC_EXTSST; // Sheet prefix BIFFRECID_CALCMODE: RREC_CALCMODE; BIFFRECID_CALCCOUNT: RREC_CALCCOUNT; BIFFRECID_REFMODE: RREC_REFMODE; BIFFRECID_ITERATION: RREC_ITERATION; BIFFRECID_DELTA: RREC_DELTA; BIFFRECID_SAVERECALC: RREC_SAVERECALC; BIFFRECID_PRINTHEADERS: RREC_PRINTHEADERS; BIFFRECID_PRINTGRIDLINES: RREC_PRINTGRIDLINES; BIFFRECID_GRIDSET: RREC_GRIDSET; BIFFRECID_GUTS: RREC_GUTS; BIFFRECID_DEFAULTROWHEIGHT: RREC_DEFAULTROWHEIGHT; BIFFRECID_WSBOOL: RREC_WSBOOL; BIFFRECID_HORIZONTALPAGEBREAKS:RREC_HORIZONTALPAGEBREAKS; BIFFRECID_VERTICALPAGEBREAKS: RREC_VERTICALPAGEBREAKS; BIFFRECID_HEADER: RREC_HEADER; BIFFRECID_FOOTER: RREC_FOOTER; BIFFRECID_HCENTER: RREC_HCENTER; BIFFRECID_VCENTER: RREC_VCENTER; BIFFRECID_PLS: RREC_PLS; BIFFRECID_SETUP: RREC_SETUP; BIFFRECID_LEFTMARGIN: RREC_LEFTMARGIN; BIFFRECID_RIGHTMARGIN: RREC_RIGHTMARGIN; BIFFRECID_TOPMARGIN: RREC_TOPMARGIN; BIFFRECID_BOTTOMMARGIN: RREC_BOTTOMMARGIN; BIFFRECID_DEFCOLWIDTH: RREC_DEFCOLWIDTH; BIFFRECID_COLINFO: RREC_COLINFO; BIFFRECID_DIMENSIONS_20, BIFFRECID_DIMENSIONS: RREC_DIMENSIONS; // Sheet cells/data BIFFRECID_INTEGER_20: RREC_INTEGER_20; BIFFRECID_NUMBER_20: RREC_NUMBER_20; BIFFRECID_LABEL_20: RREC_LABEL_20; BIFFRECID_ROW: RREC_ROW; BIFFRECID_BLANK: RREC_BLANK; BIFFRECID_BOOLERR: RREC_BOOLERR; BIFFRECID_FORMULA: RREC_FORMULA; BIFFRECID_FORMULA_30, BIFFRECID_FORMULA_40: RREC_FORMULA_30; BIFFRECID_MULBLANK: RREC_MULBLANK; BIFFRECID_RK, BIFFRECID_RK7: RREC_RK; BIFFRECID_MULRK: RREC_MULRK; BIFFRECID_NUMBER: RREC_NUMBER; BIFFRECID_LABELSST: RREC_LABELSST; BIFFRECID_LABEL: RREC_LABEL; BIFFRECID_RSTRING: RREC_RSTRING; BIFFRECID_TXO: RREC_TXO; BIFFRECID_NOTE: RREC_NOTE; // Sheet suffix BIFFRECID_MSODRAWING: RREC_MSODRAWING; BIFFRECID_MSODRAWINGSELECTION: RREC_MSODRAWINGSELECTION; BIFFRECID_OBJ: RREC_OBJ; BIFFRECID_WINDOW2: RREC_WINDOW2; BIFFRECID_SCL: RREC_SCL; BIFFRECID_PANE: RREC_PANE; BIFFRECID_SELECTION: RREC_SELECTION; BIFFRECID_DVAL: RREC_DVAL; BIFFRECID_HLINK: RREC_HLINK; BIFFRECID_MERGEDCELLS: RREC_MERGEDCELLS; else begin // ********** Fungerade inte med chart. Kommer inte ihåg varför jag ändrade... // ********** Kopierat från B020621. Original sparat som XLSReadII_sparad_021016.pas if (Header.RecID and $FF) = BIFFRECID_BOF then begin if not FIsReadingWorksheet then FIsReadingWorksheet := PRecBOF8(PBuf).SubStreamType = $0010; if PRecBOF8(PBuf).SubStreamType = $0020 then begin if FCurrSheet < 0 then begin Inc(FBoundsheetIndex); with FXLS.FileCharts.Add(FXLS) do begin SheetName := FBoundsheets[FBoundsheetIndex]; Records.Read(FXLSStream,PBuf); end; end else if FIsReadingWorksheet then FXLS.Sheets[FCurrSheet].FileCharts[FXLS.Sheets[FCurrSheet].FileCharts.Count - 1].Records.Read(FXLSStream,PBuf) else begin with FXLS.FileCharts.Add(FXLS) do begin SheetName := FBoundsheets[FBoundsheetIndex]; Records.Read(FXLSStream,PBuf); end; end; end else begin Inc(FBoundsheetIndex); { if PRecBOF8(PBuf).SubStreamType <> $0010 then FXLSStream.Seek(Integer(FBoundsheets.Objects[FBoundsheetIndex]),soFromBeginning) else begin } Inc(FCurrSheet); if FCurrSheet > 0 then FXLS.Sheets.Add; FXLS.Sheets[FCurrSheet].Name := FBoundsheets[FBoundsheetIndex]; end; end; // ********** end; end; Move(FPosStack[0],FPosStack[1],(Length(FPosStack) - 1) * SizeOf(Integer)); FPosStack[0] := FXLSStream.Pos; end; except on E: Exception do raise Exception.CreateFmt('Error on reading record # %d' + #13 + E.Message,[Cnt]); end; if Assigned(FXLS.OnProgress) then FXLS.OnProgress(Self,100); finally FXLSStream.Close; FreeMem(PBuf); end; end; // Sheet cells procedure TXLSReadII.RREC_BLANK; begin with PRecBLANK(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteBlank(Col,Row,FormatIndex); end; procedure TXLSReadII.RREC_ROW; begin if Assigned(FXLS.OnRowHeight) and (PRecROW(PBuf).Height <> 255) then FXLS.OnRowHeight(Self,PRecROW(PBuf).Row,PRecROW(PBuf).FormatIndex,PRecROW(PBuf).Height); with PRecROW(PBuf)^ do FXLS.Sheets[FCurrSheet].AddRow(Row,Col1,Col2,Height,Options,FormatIndex); end; procedure TXLSReadII.RREC_BOOLERR; begin with PRecBOOLERR(PBuf)^ do begin if Error = 0 then FXLS.Sheets[FCurrSheet].WriteBoolean(Col,Row,FormatIndex,Boolean(BoolErr)) else begin case BoolErr of $00: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errNull); $07: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errDiv0); $0F: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errValue); $17: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errRef); $1D: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errName); $24: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errNum); $2A: FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errNA); else FXLS.Sheets[FCurrSheet].WriteError(Col,Row,FormatIndex,errError); end; end; end; end; procedure TXLSReadII.ReadFormulaStr(Col,Row,FormatIndex: integer; Value: double; Formula: PByteArray; Len: integer); var ExtSz: integer; Fmla: PByteArray; S: string; begin ExtSz := 0; GetMem(Fmla,Len); try // Formula points to PBuf, which is overwritten by the next read of the file. Move(Formula^,Fmla^,Len); case TByte8Array(Value)[0] of 0: begin FXLSStream.ReadHeader(Header); if (Header.RecID = BIFFRECID_SHRFMLA) or (Header.RecID = $04BC) then begin ExtSz := SizeOf(TBIFFHeader) + Header.Length; FXLSStream.Read(PBuf^,Header.Length); FXLSStream.ReadHeader(Header); end; if Header.RecID = BIFFRECID_STRING then begin FXLSStream.Read(PBuf^,Header.Length); S := DecodeUnicodeStr(FXLS.Version,@PRecSTRING(PBuf).Data,PRecSTRING(PBuf).Len); if ExtSz > 0 then begin Inc(ExtSz,SizeOf(TBIFFHeader) + Header.Length); FXLSStream.Seek(-ExtSz,soFromCurrent); end; end else if Header.RecID = BIFFRECID_STRING_20 then begin FXLSStream.Read(PBuf^,Header.Length); S := DecodeUnicodeStr(FXLS.Version,@PRec2STRING(PBuf).Data,PRec2STRING(PBuf).Len); end else begin FXLSStream.Seek(-SizeOf(TBIFFHeader),soFromCurrent); Exit; end; FXLS.Sheets[FCurrSheet].WriteRawStrFormula(Col,Row,FormatIndex,Fmla,Len,S); end; 1: FXLS.Sheets[FCurrSheet].WriteRawBoolFormula(Col,Row,FormatIndex,Fmla,Len,Boolean(Integer(TByte8Array(Value)[2]))); 2: FXLS.Sheets[FCurrSheet].WriteRawErrFormula(Col,Row,FormatIndex,Fmla,Len,TByte8Array(Value)[2]); // 3 = Empty cell. There is no STRING record following the formula. 3: FXLS.Sheets[FCurrSheet].WriteRawStrFormula(Col,Row,FormatIndex,Fmla,Len,''); end; finally FreeMem(Fmla); end; end; procedure TXLSReadII.RREC_FORMULA; var P: PByteArray; begin if FXLS.Version < xvExcel30 then with PRec2FORMULA(PBuf)^ do begin if (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaStr(Col,Row,-1,Value,@Data,ParseLen) else FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,-1,@Data,ParseLen,Value); end else with PRecFORMULA(PBuf)^ do begin // ATTN: Under some circumstances (don't know why) the Shared Formula bit is set // in the Options field, even if the formula not is part of a shared formula group. // There is no SHRFMLA record following the FORMULA record. // The formula contaions a complete expression. // This seems to only occure in XLS-97 files. // Bug in Excel? // One way to check this is to se if the first PTG in the formula is ptgExp, = part of shared formula. if ((Options and $0008) = $0008) and (Data[0] = ptgExp) then begin FXLSStream.ReadHeader(Header); if (Header.RecID = BIFFRECID_SHRFMLA) or (Header.RecID = BIFFRECID_SHRFMLA_20) then READ_SHRFMLA else FXLSStream.Seek(-SizeOf(TBIFFHeader),soFromCurrent); FixupSharedFormula(Col,Row); end else if Data[0] = ptgExp then begin FXLSStream.ReadHeader(Header); if Header.RecID = BIFFRECID_ARRAY then begin GetMem(P,Header.Length); try FXLSStream.Read(P^,Header.Length); FXLS.Sheets[FCurrSheet].WriteRawArrayFormula(Col,Row,FormatIndex,@Data,ParseLen,Value,P,Header.Length); finally FreeMem(P); end; Exit; end else FXLSStream.Seek(-SizeOf(TBIFFHeader),soFromCurrent); end; if (TByte8Array(Value)[0] in [$00,$01,$02,$03]) and (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaStr(Col,Row,FormatIndex,Value,@Data,ParseLen) else if ParseLen <> 0 then begin // This detects NAN values. A NAN number may cause an "Invalid Floating Point Operation" exception when used. if (TByte8Array(Value)[0] = $02) and (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,ParseLen,0) else FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,ParseLen,Value); end; end; end; procedure TXLSReadII.RREC_FORMULA_30; begin with PRecFORMULA3(PBuf)^ do begin FXLS.Sheets[FCurrSheet].WriteRawNumFormula(Col,Row,FormatIndex,@Data,ParseLen,Value); if (TByte8Array(Value)[6] = $FF) and (TByte8Array(Value)[7] = $FF) then ReadFormulaStr(Col,Row,FormatIndex,Value,@Data,ParseLen); end; end; procedure TXLSReadII.RREC_NUMBER; begin with PRecNUMBER(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteNumber(Col,Row,FormatIndex,Value); end; procedure TXLSReadII.RREC_INTEGER_20; begin with PRec2INTEGER(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteNumber(Col,Row,-1,Value); end; procedure TXLSReadII.RREC_LABEL_20; var S: string; begin with PRec2LABEL(PBuf)^ do begin SetLength(S,Len); Move(Data,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].WriteSSTString(Col,Row,-1,S); end; end; procedure TXLSReadII.RREC_NUMBER_20; begin with PRec2NUMBER(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteNumber(Col,Row,-1,Value); end; procedure TXLSReadII.RREC_LABELSST; begin with PRecLABELSST(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteSSTStringIndex(Col,Row,FormatIndex,SSTIndex); end; procedure TXLSReadII.RREC_LABEL; var P: PByteArray; S: string; WS: WideString; begin with PRecLABEL(PBuf)^ do begin if (Len > 0) and (Data[0] = 1) then begin P := PByteArray(Integer(@Data) + 1); SetLength(WS,Len); Move(P^,Pointer(WS)^,Len * 2); FXLS.Sheets[FCurrSheet].WriteSSTWideString(Col,Row,FormatIndex,WS); end else if (Len > 0) and (Data[0] = 0) then begin P := PByteArray(Integer(@Data) + 1); SetLength(S,Len); Move(P^,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].WriteSSTString(Col,Row,FormatIndex,S); end else begin SetLength(S,Len); Move(Data,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].WriteSSTString(Col,Row,FormatIndex,S); end; end; end; procedure TXLSReadII.RREC_RSTRING; var S: string; begin with PRecLABEL(PBuf)^ do begin SetLength(S,Len); Move(Data,Pointer(S)^,Len); FXLS.Sheets[FCurrSheet].WriteSSTString(Col,Row,FormatIndex,S); end; end; procedure TXLSReadII.RREC_MULBLANK; var i: integer; begin with PRecMULBLANK(PBuf)^ do begin for i := 0 to (Header.Length - 6) div 2 - 1 do FXLS.Sheets[FCurrSheet].WriteBlank(Col1 + i,Row,FormatIndexes[i]); end; end; procedure TXLSReadII.RREC_RK; begin with PRecRK(PBuf)^ do FXLS.Sheets[FCurrSheet].WriteNumber(Col,Row,FormatIndex,DecodeRK(Value)); end; procedure TXLSReadII.RREC_MULRK; var i: integer; begin with PRecMULRK(PBuf)^ do begin for i := 0 to (Header.Length - 6) div 6 - 1 do FXLS.Sheets[FCurrSheet].WriteNumber(Col1 + i,Row,RKs[i].FormatIndex,DecodeRK(RKs[i].Value)); end; end; procedure TXLSReadII.FixupSharedFormula(ACol,ARow: integer); var i: integer; begin // ATTN: Ranges of shared formulas may overlap. The last one written seems // to be the correct, therefore all shared formulas has to be searched. for i := 0 to High(FSharedFormulas) do begin with FSharedFormulas[i] do begin if (ACol >= Col1) and (ACol <= Col2) and (ARow >= Row1) and (ARow <= Row2) then begin Move(Formula^,PRecFORMULA(PBuf).Data,Len); PRecFORMULA(PBuf).ParseLen := Len; ConvertShrFmla(FXLS.Version = xvExcel97,@PRecFORMULA(PBuf).Data,PRecFORMULA(PBuf).ParseLen,ACol,ARow); Break; end; end; end; end; procedure TXLSReadII.READ_SHRFMLA; var i: integer; begin // ATTN: If Excel saves a SHRFMLA where some cells have been deleted, // (Ex: If you have 10 formulas in a row, saves it, open the sheet again, // deletes 4 of them and saves it again) then may the deleted formulas // still be saved in the SHRFMLA record! // The only way to check this is to look for the corresponding FORMULA // records. There is only FORMULA records for formulas that exsists on // the sheet. I think :-) SetLength(FSharedFormulas,Length(FSharedFormulas) + 1); i := High(FSharedFormulas); FXLSStream.Read(FSharedFormulas[i],6); FXLSStream.Read(FSharedFormulas[i].Len,2); // Reserved data FXLSStream.Read(FSharedFormulas[i].Len,2); GetMem(FSharedFormulas[i].Formula,FSharedFormulas[i].Len); FXLSStream.Read(FSharedFormulas[i].Formula^,FSharedFormulas[i].Len); end; procedure TXLSReadII.RREC_TXO; begin // TXO is read in ReadNote. end; // IMPORTANT, BUG IN EXCEL: Sometimes, when there is many notes, Excel don't // writes correct record id:s. (MSODRAWING is replaced by CONTINUE!). // Therefore, this record order must be assumed: // MSODRAWING // OBJ // MSODRAWING // TXO // CONTINUE // CONTINUE (if text > max record size) // CONTINUE procedure TXLSReadII.ReadNote(NoteId: integer); var i,Pos,Count,Len: integer; S,NoteText: string; Note: TNote; procedure AddText; begin if PBuf[0] = 0 then begin SetLength(S,Header.Length - 1); Move(Pointer(Integer(PBuf) + 1)^,Pointer(S)^,Header.Length - 1); end else S := WideCharLenToString(PWideChar(Integer(PBuf) + 1),Header.Length - 1); NoteText := NoteText + S; end; begin Pos := FXLSStream.Pos; FXLSStream.Seek(FPosStack[1],soFromBeginning); FXLSStream.ReadHeader(Header); // Bug in Excel, read the MSODRAWING. if Header.RecID <> BIFFRECID_MSODRAWING then FMSOReadDrawing.Read(FXLSStream,PBuf,Header.Length,FCurrAnchor); FXLSStream.Seek(Pos,soFromBeginning); // Skip second MSODRAWING FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); // TXO FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); Len := PRecTXO(PBuf).TextLen; // First CONTINUE (possibly more than one). FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); if PByte(PBuf)^ = 0 then Count := Len div (FXLS.MaxBuffSize - 1) else Count := (Len * 2) div (FXLS.MaxBuffSize - 1); NoteText := ''; AddText; for i := 1 to Count do AddText; // Skip second CONTINUE. FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); Note := FXLS.Sheets[FCurrSheet].Notes.Add; TAnchorObject(Note).Assign(FCurrAnchor); TAnchorObject(Note).HasValidPosition := True; Note.ItemId := NoteId; Note.Text.Text := NoteText; end; procedure TXLSReadII.RREC_NOTE; var i: integer; begin for i := 0 to FXLS.Sheets[FCurrSheet].Notes.Count - 1 do begin if (PRecNOTE(PBuf).ObjId ) = FXLS.Sheets[FCurrSheet].Notes[i].ItemId then begin FXLS.Sheets[FCurrSheet].Notes[i].CellRow := PRecNOTE(PBuf).Row; FXLS.Sheets[FCurrSheet].Notes[i].CellCol := PRecNOTE(PBuf).Col; FXLS.Sheets[FCurrSheet].Notes[i].HasNoteRecord := True; FXLS.Sheets[FCurrSheet].Notes[I].AlwaysVisible := (PRecNOTE(PBuf).Options and $0002) = $0002; Exit; end; end; end; procedure TXLSReadII.RREC_1904; begin FXLS.DateSystem1904 := PWord(PBuf)^ = 1; end; procedure TXLSReadII.RREC_ADDMENU; begin // Not used end; procedure TXLSReadII.RREC_BACKUP; begin FXLS.Backup := PWordBool(PBuf)^; end; procedure TXLSReadII.RREC_BOOKBOOL; begin FXLS.OptionsDialog.SaveExtLinkVal := PWordBool(PBuf)^; end; procedure TXLSReadII.RREC_PALETTE; var i: integer; begin if PRecPALETTE(PBuf).Count > (Length(TExcelColorPalette) - 8) then PRecPALETTE(PBuf).Count := Length(TExcelColorPalette) - 8; for i := 0 to PRecPALETTE(PBuf).Count - 1 do TExcelColorPalette[i + 8] := PRecPALETTE(PBuf).Color[i]; { if FXLS.Version in [xvExcel30,xvExcel40] then begin if PRecPALETTE(PBuf).Count > Length(TExcelColorPalette30) then PRecPALETTE(PBuf).Count := Length(TExcelColorPalette30); for i := 0 to PRecPALETTE(PBuf).Count - 1 do TExcelColorPalette30[i] := PRecPALETTE(PBuf).Color[i]; end; } end; procedure TXLSReadII.RREC_BOUNDSHEET; var S: string; begin if FXLS.Version < xvExcel97 then with PRecBOUNDSHEET7(PBuf)^ do begin SetLength(S,NameLen); Move(Name,Pointer(S)^,NameLen); end else with PRecBOUNDSHEET8(PBuf)^ do begin if Name[0] = 1 then begin SetLength(S,((NameLen * 2) and $00FF) + 1); Move(Name,Pointer(S)^,((NameLen * 2) and $00FF) + 1) end else begin SetLength(S,(NameLen and $00FF) + 1); Move(Name,Pointer(S)^,(NameLen and $00FF) + 1); end; end; FBoundsheets.AddObject(S,TObject(PRecBOUNDSHEET8(PBuf).BOFPos)); end; procedure TXLSReadII.RREC_CALCCOUNT; begin FXLS.Sheets[FCurrSheet].CalcCount := PWord(PBuf)^; end; procedure TXLSReadII.RREC_CALCMODE; begin case PWord(PBuf)^ of $0000: FXLS.OptionsDialog.CalcMode := cmManual; $0001: FXLS.OptionsDialog.CalcMode := cmAutomatic; $FFFF: FXLS.OptionsDialog.CalcMode := cmAutoExTables; end; end; procedure TXLSReadII.RREC_CODEPAGE; begin FXLS.Codepage := PWord(PBuf)^; end; procedure TXLSReadII.RREC_COLINFO; begin with FXLS.Sheets[FCurrSheet].ColumnFormats.Add do begin Col1 := PRecCOLINFO(PBuf).Col1; Col2 := PRecCOLINFO(PBuf).Col2; Width := PRecCOLINFO(PBuf).Width; FormatIndex := PRecCOLINFO(PBuf).FormatIndex; Hidden := (PRecCOLINFO(PBuf).Options and $0001) = $0001; UnknownOptionsFlag := (PRecCOLINFO(PBuf).Options and $0002) = $0002; OutlineLevel := (PRecCOLINFO(PBuf).Options shr 8) and $0007; CollapsedOutline := (PRecCOLINFO(PBuf).Options and $1000) = $1000; end; end; procedure TXLSReadII.RREC_COUNTRY; begin FXLS.DefaultCountryIndex := PRecCOUNTRY(PBuf).DefaultCountryIndex; FXLS.WinIniCountry := PRecCOUNTRY(PBuf).WinIniCountry; end; procedure TXLSReadII.RREC_DEFAULTROWHEIGHT; begin FXLS.Sheets[FCurrSheet].DefaultRowHeight := PRecDEFAULTROWHEIGHT(PBuf).Height; end; procedure TXLSReadII.RREC_DEFCOLWIDTH; begin FXLS.Sheets[FCurrSheet].DefaultColWidth := PWord(PBuf)^; end; procedure TXLSReadII.RREC_DELMENU; begin // Not used. end; procedure TXLSReadII.RREC_DELTA; begin FXLS.Sheets[FCurrSheet].Delta := PDouble(PBuf)^; end; procedure TXLSReadII.RREC_DIMENSIONS; begin if FXLS.Version >= xvExcel97 then begin with PRecDIMENSIONS8(PBuf)^ do begin FXLS.Sheets[FCurrSheet].FirstCol := FirstCol; FXLS.Sheets[FCurrSheet].LastCol := Max(0,LastCol - 1); FXLS.Sheets[FCurrSheet].FirstRow := FirstRow; FXLS.Sheets[FCurrSheet].LastRow := Max(0,LastRow - 1); end; end else if FXLS.Version > xvExcel21 then begin with PRecDIMENSIONS7(PBuf)^ do begin FXLS.Sheets[FCurrSheet].FirstCol := FirstCol; FXLS.Sheets[FCurrSheet].LastCol := Max(0,LastCol - 1); FXLS.Sheets[FCurrSheet].FirstRow := FirstRow; FXLS.Sheets[FCurrSheet].LastRow := Max(0,LastRow - 1); end; end else begin with PRecDIMENSIONS2(PBuf)^ do begin FXLS.Sheets[FCurrSheet].FirstCol := FirstCol; FXLS.Sheets[FCurrSheet].LastCol := Max(0,LastCol - 1); FXLS.Sheets[FCurrSheet].FirstRow := FirstRow; FXLS.Sheets[FCurrSheet].LastRow := Max(0,LastRow - 1); end; end; end; procedure TXLSReadII.RREC_DSF; begin // Not used. end; procedure TXLSReadII.RREC_EOF; begin // This shall never happens. raise Exception.Create(ersEOFUnexpected); end; // 20,00,00,01,0B,00,00,00,01,00,00,00,00,00,00,06,3B,00,00,00,00,58,04,00,00,06,00, procedure TXLSReadII.RREC_NAME; var i: integer; S: string; P: PByteArray; begin case FXLS.Version of xvExcel97: begin S := DecodeUnicodeStr(FXLS.Version,PByteArray(@PRecNAME(PBuf).Data),PRecNAME(PBuf).LenName); // Name is unicode if PRecNAME(PBuf).Data[0] = 1 then P := @PRecNAME(PBuf).Data[PRecNAME(PBuf).LenName * 2 + 1] else P := @PRecNAME(PBuf).Data[PRecNAME(PBuf).LenName + 1]; i := FXLS.NameDefs.AddNAME(PRecNAME(PBuf).Options,PRecNAME(PBuf).SheetIndex,PRecNAME(PBuf).TabIndex,S,P,PRecNAME(PBuf).LenNameDef); with FXLS.AreaNames.Add do begin AreaNameIgnoreDup := S; AddRaw(@P[0],PRecNAME(PBuf).LenNameDef); WorkbookName := FXLS.NameDefs.WorkbookNames[i]; end; end; end; end; procedure TXLSReadII.RREC_SUPBOOK; var P: PByteArray; S,Filename: string; Cnt,L: integer; List: TStringList; begin List := TStringList.Create; try P := PBuf; Cnt := PWord(PBuf)^; P := Pointer(Integer(P) + 2); if P[0] in [$00,$01,$02] then begin SetLength(Filename,2); Filename[1] := Char(PByteArray(P)[0]); Filename[2] := Char(PByteArray(P)[1]); end else begin L := PWord(P)^; P := Pointer(Integer(P) + 2); Filename := DecodeUnicodeStr(FXLS.Version,P,L); while Cnt > 0 do begin if PByteArray(P)[0] = $01 then P := Pointer(Integer(P) + L); P := Pointer(Integer(P) + L + 1); L := PWord(P)^; P := Pointer(Integer(P) + 2); S := DecodeUnicodeStr(FXLS.Version,P,L); List.Add(S); Dec(Cnt); end; end; FXLS.NameDefs.AddSUPBOOK(Filename,List); finally List.Free; end; end; procedure TXLSReadII.RREC_EXTERNNAME; var S: string; Len: word; PData: PByteArray; begin case FXLS.Version of xvExcel97: begin S := DecodeUnicodeStr(FXLS.Version,PByteArray(@PRecEXTERNNAME8(PBuf).Data),PRecEXTERNNAME8(PBuf).LenName); if PByteArray(@PRecEXTERNNAME8(PBuf).Data)[0] = 1 then PData := Pointer(Integer(PBuf) + 7 + PRecEXTERNNAME8(PBuf).LenName * 2 + 1) else PData := Pointer(Integer(PBuf) + 7 + PRecEXTERNNAME8(PBuf).LenName + 1); if (PRecEXTERNNAME8(PBuf).Options and $FFFE) = 0 then begin Len := PWordArray(PData)[0]; PData := Pointer(Integer(PData) + 2); end else Len := Header.Length - 8 - PRecEXTERNNAME8(PBuf).LenName; FXLS.NameDefs.AddEXTERNNAME_Read(PRecEXTERNNAME8(PBuf).Options,S,PData,Len); end; end; end; procedure TXLSReadII.RREC_EXTERNCOUNT; begin if FXLS.Version = xvExcel97 then FXLS.NameDefs.ExternCount := PWord(PBuf)^; end; procedure TXLSReadII.RREC_EXTERNSHEET; var i: integer; begin case FXLS.Version of xvExcel97: begin with PRecEXTERNSHEET8(PBuf)^ do begin for i := 0 to XTICount - 1 do FXLS.NameDefs.AddEXTERNSHEET(XTI[i].SupBook,XTI[i].FirstTab,XTI[i].LastTab,True); end; end; xvExcel50: begin end; end; end; procedure TXLSReadII.RREC_EXTSST; begin // Not used. end; procedure TXLSReadII.RREC_FONT; var S: string; begin with FXLS.Fonts.Add do begin if FXLS.Version in [xvExcel30,xvExcel40] then begin CharSet := 0; if PRecFONT30(PBuf).ColorIndex > High(TExcelColorPalette) then Color := xcBlack else Color := TExcelColor(PRecFONT30(PBuf).ColorIndex); S := DecodeUnicodeStr(FXLS.Version,@PRecFONT30(PBuf).Name,PRecFONT30(PBuf).NameLen); Name := S; Size := PRecFONT(PBuf).Height div 20; Style := []; if (PRecFONT30(PBuf).Attributes and $0001) = $0001 then Style := Style + [xfsBold]; if (PRecFONT30(PBuf).Attributes and $0002) = $0002 then Style := Style + [xfsItalic]; if (PRecFONT30(PBuf).Attributes and $0004) = $0004 then Underline := xulSingle; if (PRecFONT30(PBuf).Attributes and $0008) = $0008 then Style := Style + [xfsStrikeOut]; end else begin CharSet := PRecFONT(PBuf).CharSet; if PRecFONT(PBuf).ColorIndex > $00FF then Color := xcBlack else Color := TExcelColor(PRecFONT(PBuf).ColorIndex); SetLength(S,PRecFONT(PBuf).NameLen); S := DecodeUnicodeStr(FXLS.Version,@PRecFONT(PBuf).Name,PRecFONT(PBuf).NameLen); Name := S; Size := PRecFONT(PBuf).Height div 20; Style := []; if PRecFONT(PBuf).Bold >= $02BC then Style := Style + [xfsBold]; Underline := TXUnderline(PRecFONT(PBuf).Underline); if (PRecFONT(PBuf).Attributes and $02) = $02 then Style := Style + [xfsItalic]; if (PRecFONT(PBuf).Attributes and $08) = $08 then Style := Style + [xfsStrikeout]; SubSuperScript := TXSubSuperscript(PRecFONT(PBuf).SubSuperScript); end; // Font #4 does not exsists (and is not stored in the XLS file). if FXLS.Fonts.Count = 4 then FXLS.Fonts.Add; end; end; procedure TXLSReadII.RREC_FOOTER; var S: string; begin if Header.Length = 0 then Exit; if FXLS.Version >= xvExcel97 then begin S := DecodeUnicodeStr(FXLS.Version,@PRecSTRING(PBuf).Data,PRecSTRING(PBuf).Len); end else begin SetLength(S,PRecSTRING1Byte(PBuf).Len); Move(PRecSTRING1Byte(PBuf).Data,Pointer(S)^,Length(S)); end; FXLS.Sheets[FCurrSheet].PrintSettings.Footer := S; end; procedure TXLSReadII.RREC_FORMAT; var S: string; begin if FXLS.Version < xvExcel97 then begin SetLength(S,PRecFORMAT(PBuf).Len); Move(PRecFORMAT(PBuf).Data,Pointer(S)^,PRecFORMAT(PBuf).Len); end else begin if PRecFORMAT97(PBuf).Data[0] = $00 then begin SetLength(S,PRecFORMAT97(PBuf).Len + 1); Move(PRecFORMAT97(PBuf).Data,Pointer(S)^,PRecFORMAT97(PBuf).Len + 1); if Lowercase(S) = #0 + 'general' then S := '@'; end else begin SetLength(S,PRecFORMAT97(PBuf).Len * 2 + 1); Move(PRecFORMAT97(PBuf).Data,Pointer(S)^,PRecFORMAT97(PBuf).Len * 2 + 1); end; end; if FXLS.Version < xvExcel50 then FXLS.AddNumberFormat40(S) else if FXLS.Version < xvExcel97 then FXLS.AddNumberFormat(S,PRecFORMAT(PBuf).Index) else FXLS.AddWideNumberFormat(S,PRecFORMAT(PBuf).Index); end; procedure TXLSReadII.RREC_GRIDSET; begin FXLS.Sheets[FCurrSheet].Gridset := PWord(PBuf)^; end; procedure TXLSReadII.RREC_GUTS; begin FXLS.Sheets[FCurrSheet].RowGutter := PRecGUTS(PBuf).SizeRow; FXLS.Sheets[FCurrSheet].ColGutter := PRecGUTS(PBuf).SizeCol; FXLS.Sheets[FCurrSheet].RowOutlineGutter := PRecGUTS(PBuf).LevelRow; FXLS.Sheets[FCurrSheet].ColOutlineGutter := PRecGUTS(PBuf).LevelCol; end; procedure TXLSReadII.RREC_HCENTER; begin if PWord(PBuf)^ <> 0 then FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options + [psoHorizCenter]; end; procedure TXLSReadII.RREC_HEADER; var S: string; begin if Header.Length = 0 then Exit; if FXLS.Version >= xvExcel97 then begin S := DecodeUnicodeStr(FXLS.Version,@PRecSTRING(PBuf).Data,PRecSTRING(PBuf).Len); end else begin SetLength(S,PRecSTRING1Byte(PBuf).Len); Move(PRecSTRING1Byte(PBuf).Data,Pointer(S)^,Length(S)); end; FXLS.Sheets[FCurrSheet].PrintSettings.Header := S; end; procedure TXLSReadII.RREC_HIDEOBJ; begin case PWord(PBuf)^ of 0: FXLS.OptionsDialog.ShowObjects := soShowAll; 1: FXLS.OptionsDialog.ShowObjects := soPlaceholders; 2: FXLS.OptionsDialog.ShowObjects := soHideAll; end; end; procedure TXLSReadII.RREC_HLINK; var L1,L2: integer; Row,Col: integer; Text,Link: string; P: PByteArray; begin Row := PRecHLINK(PBuf).Row1; Col := PRecHLINK(PBuf).Col1; case PRecHLINK(PBuf).Options2 of $0003: begin L1 := PWord(Integer(PBuf) + SizeOf(TRecHLINK) + 16)^; P := PByteArray(Integer(PBuf) + SizeOf(TRecHLINK) + 16 + 4); Text := WideCharLenToString(PWideChar(P),(L1 div 2) - 1); Link := Text; end; $0017: begin L1 := PWord(Integer(PBuf) + SizeOf(TRecHLINK))^; P := PByteArray(Integer(PBuf) + SizeOf(TRecHLINK) + 4); Text := WideCharLenToString(PWideChar(P),L1 - 1); L2 := PWord(Integer(PBuf) + SizeOf(TRecHLINK) + L1 * 2 + 16 + 4)^; P := PByteArray(Integer(PBuf) + SizeOf(TRecHLINK) + L1 * 2 + 16 + 4 + 4); Link := WideCharLenToString(PWideChar(P),(L2 div 2) - 1); end; else Exit; end; FXLS.Sheets[FCurrSheet].Hyperlinks.AddObject(Text + #9 + Link,TObject(ColRowToRC(Col,Row))); end; procedure TXLSReadII.RREC_FILEPASS; begin raise Exception.Create(ersPasswordProtect); end; procedure TXLSReadII.RREC_FILESHARING; begin FXLS.ReadOnly := PRecFILESHARING(PBuf).ReadOnly = 1; end; procedure TXLSReadII.RREC_INTERFACEEND; begin // Not used. end; procedure TXLSReadII.RREC_INTERFACEHDR; begin // Not used. end; procedure TXLSReadII.RREC_ITERATION; begin if Boolean(PWord(PBuf)^) then FXLS.Sheets[FCurrSheet].Options := FXLS.Sheets[FCurrSheet].Options + [soIteration] else FXLS.Sheets[FCurrSheet].Options := FXLS.Sheets[FCurrSheet].Options - [soIteration]; end; procedure TXLSReadII.RREC_MERGEDCELLS; var i,Count: integer; begin Count := PRecMERGEDCELLS(PBuf).Count; for i := 0 to Count - 1 do begin with TMergedCell(FXLS.Sheets[FCurrSheet].MergedCells.Add) do begin Row1 := PRecMERGEDCELLS(PBuf).Cells[i].Row1; Row2 := PRecMERGEDCELLS(PBuf).Cells[i].Row2; Col1 := PRecMERGEDCELLS(PBuf).Cells[i].Col1; Col2 := PRecMERGEDCELLS(PBuf).Cells[i].Col2; end; end; end; procedure TXLSReadII.RREC_MSODRAWING; begin FCurrAnchor.Clear; FMSOReadDrawing.Read(FXLSStream,PBuf,Header.Length,FCurrAnchor); end; procedure TXLSReadII.RREC_MSODRAWINGGROUP; var L: integer; P: Pointer; H: TBIFFHeader; begin if FXLS.Version >= xvExcel97 then begin L := Header.Length; try repeat FXLSStream.ReadHeader(H); if (H.RecId in [BIFFRECID_CONTINUE,BIFFRECID_MSODRAWINGGROUP]) then begin ReAllocMem(PBuf,L + H.Length); P := Pointer(Integer(PBuf) + L); FXLSStream.Read(P^,H.Length); Inc(L,H.Length); end; until (not (H.RecId in [BIFFRECID_CONTINUE,BIFFRECID_MSODRAWINGGROUP])); FXLSStream.Seek(-SizeOf(TBIFFHeader),soFromCurrent); FMSOReadGroup.PicturesInMemory := poInMemory in FXLS.PictureOptions; FMSOReadGroup.Read(FXLSStream,PBuf,L,FCurrAnchor); finally ReAllocMem(PBuf,FXLS.MaxBuffsize); end; end; end; procedure TXLSReadII.RREC_MSODRAWINGSELECTION; begin end; procedure TXLSReadII.RREC_OBJ; var P: PByteArray; Len,L,ItemId: integer; Id: word; begin Len := Header.Length; P := PBuf; ItemId := -1; while Len > 0 do begin Id := PWord(P)^; case ID of OBJ_Cmo: ItemId := PRecOBJ(PBuf).ObjId; OBJ_Nts: begin ReadNOTE(ItemId); Exit; end; end; P := Pointer(Integer(P) + 2); L := PWord(P)^; P := Pointer(Integer(P) + 2); P := Pointer(Integer(P) + L); Dec(Len,L + 4); end; end; procedure TXLSReadII.RREC_PASSWORD; begin // It seems to be possible to include this record even if the sheet not is // password protected Exit; if PWord(PBuf)^ <> 0 then raise Exception.Create(ersPasswordProtect); end; procedure TXLSReadII.RREC_PLS; begin // Not used end; procedure TXLSReadII.RREC_PRECISION; begin FXLS.OptionsDialog.PrecisionAsDisplayed := not Boolean(PWord(PBuf)^); end; procedure TXLSReadII.RREC_PRINTGRIDLINES; begin if Boolean(PWord(PBuf)^) then FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options + [psoGridlines] else FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options - [psoGridlines]; end; procedure TXLSReadII.RREC_PRINTHEADERS; begin if Boolean(PWord(PBuf)^) then FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options + [psoRowColHeading] else FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options - [psoRowColHeading]; end; procedure TXLSReadII.RREC_PROT4REV; begin FXLS.Prot4Rev := Boolean(PWord(PBuf)^); end; procedure TXLSReadII.RREC_PROT4REVPASS; begin end; procedure TXLSReadII.RREC_PROTECT; begin // Not used. end; procedure TXLSReadII.RREC_REFMODE; begin if Boolean(PWord(PBuf)^) then FXLS.Sheets[FCurrSheet].Options := FXLS.Sheets[FCurrSheet].Options - [soR1C1Mode] else FXLS.Sheets[FCurrSheet].Options := FXLS.Sheets[FCurrSheet].Options + [soR1C1Mode]; end; procedure TXLSReadII.RREC_REFRESHALL; begin FXLS.RefreshAll := Boolean(PWord(PBuf)^); end; procedure TXLSReadII.RREC_SAVERECALC; begin FXLS.SaveRecalc := Boolean(PWord(PBuf)^); end; procedure TXLSReadII.RREC_SELECTION; begin // Not used. end; procedure TXLSReadII.RREC_DV; var P: PByteArray; i,Len: integer; Options: longword; function GetPtrText: string; begin Len := PWord(P)^; P := PByteArray(Integer(P) + 2); if Len > 0 then begin if P[0] = 0 then begin P := PByteArray(Integer(P) + 1); SetLength(Result,Len); Move(P^,Pointer(Result)^,Len); P := PByteArray(Integer(P) + Len); end else if P[0] = 1 then begin P := PByteArray(Integer(P) + 1); SetLength(Result,Len * 2); Move(P^,Pointer(Result)^,Len * 2); P := PByteArray(Integer(P) + Len * 2); // TODO convert from multibyte. end else raise Exception.Create(ersUnhandledStrDV); end else Result := ''; end; begin with FXLS.Sheets[FCurrSheet].Validations.Add do begin P := PBuf; Options := PInteger(P)^; ValidationType := TValidationType(Options and $000F); ValidationStyle := TValidationStyle((Options shr 4) and $0007); ValidationOperator := TValidationOperator((Options shr 20) and $000F); P := PByteArray(Integer(P) + 4); InputTitle := GetPtrText; ErrorTitle := GetPtrText; InputMsg := GetPtrText; ErrorMsg := GetPtrText; Len := PWord(P)^; P := PByteArray(Integer(P) + 4); SetRawExpression1(P,Len); DecodeFmla(xvExcel97,P,Len,0,0,Nil); P := PByteArray(Integer(P) + Len); Len := PWord(P)^; P := PByteArray(Integer(P) + 4); SetRawExpression2(P,Len); P := PByteArray(Integer(P) + Len); Len := PWord(P)^; if Len > $0FFF then Len := 0; P := PByteArray(Integer(P) + 2); for i := 0 to Len - 1 do begin with Areas.Add do begin Row1 := PWordArray(P)[0]; Row2 := PWordArray(P)[1]; Col1 := PWordArray(P)[2]; Col2 := PWordArray(P)[3]; P := PByteArray(Integer(P) + SizeOf(TArea)); end; end; end; end; procedure TXLSReadII.RREC_DVAL; var i: integer; begin for i := 0 to PRecDVAL(PBuf).DVCount - 1 do begin FXLSStream.ReadHeader(Header); FXLSStream.Read(PBuf^,Header.Length); RREC_DV; end; end; procedure TXLSReadII.RREC_BOTTOMMARGIN; begin FXLS.Sheets[FCurrSheet].PrintSettings.MarginBottom := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_LEFTMARGIN; begin FXLS.Sheets[FCurrSheet].PrintSettings.MarginLeft := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_RIGHTMARGIN; begin FXLS.Sheets[FCurrSheet].PrintSettings.MarginRight := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_TOPMARGIN; begin FXLS.Sheets[FCurrSheet].PrintSettings.MarginTop := PRecMARGIN(PBuf).Value; end; procedure TXLSReadII.RREC_SETUP; begin with FXLS.Sheets[FCurrSheet].PrintSettings do begin PaperSize := TPaperSize(pRecSETUP(PBuf).PaperSize); ScalingFactor := PRecSETUP(PBuf).Scale; StartingPage := PRecSETUP(PBuf).PageStart; Options := []; if (PRecSETUP(PBuf).Options and $0001) = $0001 then Options := Options + [psoLeftToRight]; if (PRecSETUP(PBuf).Options and $0002) = $0002 then Options := Options + [psoPortrait]; if (PRecSETUP(PBuf).Options and $0008) = $0008 then Options := Options + [psoNoColor]; if (PRecSETUP(PBuf).Options and $0010) = $0010 then Options := Options + [psoDraftQuality]; if (PRecSETUP(PBuf).Options and $0020) = $0020 then Options := Options + [psoNotes]; HeaderMargin := PRecSETUP(PBuf).HeaderMargin; FooterMargin := PRecSETUP(PBuf).FooterMargin; Copies := PRecSETUP(PBuf).Copies; Resolution := PRecSETUP(PBuf).Resolution; end; end; procedure TXLSReadII.RREC_SST; begin FXLSStream.Seek(-(SizeOf(TBIFFHeader) + Header.Length),soFromCurrent); FXLS.Sheets.ReadSST(FXLSStream); end; procedure TXLSReadII.RREC_STYLE; begin // Only save Built-in styles. if (PRecSTYLE(PBuf).FormatIndex and $8000) = $8000 then FXLS.Styles.Add(PRecSTYLE(PBuf)); end; procedure TXLSReadII.RREC_TABID; begin // Not used. end; procedure TXLSReadII.RREC_USESELFS; begin // Not used. end; procedure TXLSReadII.RREC_VCENTER; begin if Boolean(PWord(PBuf)^) then FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options + [psoVertCenter] else FXLS.Sheets[FCurrSheet].PrintSettings.Options := FXLS.Sheets[FCurrSheet].PrintSettings.Options - [psoVertCenter]; end; procedure TXLSReadII.RREC_WINDOW1; begin with FXLS.Workbook do begin Left := PRecWINDOW1(PBuf).Left; Top := PRecWINDOW1(PBuf).Top; Width := PRecWINDOW1(PBuf).Width; Height := PRecWINDOW1(PBuf).Height; Options := []; if (PRecWINDOW1(PBuf).Options and $01) = $01 then Options := Options + [woHidden]; if (PRecWINDOW1(PBuf).Options and $02) = $02 then Options := Options + [woIconized]; if (PRecWINDOW1(PBuf).Options and $08) = $08 then Options := Options + [woHScroll]; if (PRecWINDOW1(PBuf).Options and $10) = $10 then Options := Options + [woVScroll]; if (PRecWINDOW1(PBuf).Options and $20) = $20 then Options := Options + [woTabs]; SelectedTab := PRecWINDOW1(PBuf).SelectedTabIndex; end; end; procedure TXLSReadII.RREC_WINDOW2; begin with FXLS.Sheets[FCurrSheet] do begin Options := []; if (PRecWINDOW2_7(PBuf).Options and $0001) = $0001 then Options := Options + [soShowFormulas]; if (PRecWINDOW2_7(PBuf).Options and $0002) = $0002 then Options := Options + [soGridlines]; if (PRecWINDOW2_7(PBuf).Options and $0004) = $0004 then Options := Options + [soRowColHeadings]; if (PRecWINDOW2_7(PBuf).Options and $0008) = $0008 then FXLS.Sheets[FCurrSheet].Pane.PaneType := ptFrozen; if (PRecWINDOW2_7(PBuf).Options and $0010) = $0010 then Options := Options + [soShowZeros]; if FXLS.Version >= xvExcel97 then Zoom := PRecWINDOW2_8(PBuf).Zoom; if FXLS.Version >= xvExcel97 then ZoomPreview := PRecWINDOW2_8(PBuf).ZoomPreview; end; end; procedure TXLSReadII.RREC_SCL; begin FXLS.Sheets[FCurrSheet].Zoom := Round((PRecSCL(PBuf).Numerator / PRecSCL(PBuf).Denominator) * 100); end; procedure TXLSReadII.RREC_PANE; begin FXLS.Sheets[FCurrSheet].FixedRows := PRecPANE(PBuf).Y; FXLS.Sheets[FCurrSheet].FixedCols := PRecPANE(PBuf).X; with PRecPANE(PBuf)^ do begin FXLS.Sheets[FCurrSheet].Pane.ActivePane := PaneNumber; FXLS.Sheets[FCurrSheet].Pane.SplitColX := X; FXLS.Sheets[FCurrSheet].Pane.SplitRowY := Y; FXLS.Sheets[FCurrSheet].Pane.LeftCol := LeftCol; FXLS.Sheets[FCurrSheet].Pane.TopRow := TopRow; if FXLS.Sheets[FCurrSheet].Pane.PaneType = ptNone then FXLS.Sheets[FCurrSheet].Pane.PaneType := ptSplit; end; end; procedure TXLSReadII.RREC_WINDOWPROTECT; begin FXLS.BookProtected := Boolean(PWord(PBuf)^); end; procedure TXLSReadII.RREC_WRITEACCESS; var Sz: word; P: PWideChar; S: string; begin if (PBuf[0] = $20) and (PBuf[1] = $20) then FXLS.UserName := '' else if FXLS.Version <= xvExcel40 then begin SetLength(S,31); Move(PBuf[0],Pointer(S)^,31); FXLS.UserName := Trim(S); end else if FXLS.Version <= xvExcel50 then begin Sz := PBuf[0]; if PBuf[1] = 0 then begin SetLength(S,Sz); Move(PBuf[2],Pointer(S)^,Length(S)); FXLS.UserName := S; end else begin P := PWIdeChar(Integer(PBuf) + 2); FXLS.UserName := WideCharLenToString(P,Sz); end; end else begin Sz := PWordArray(PBuf)[0]; if PBuf[2] = 0 then begin SetLength(S,Sz); Move(PBuf[3],Pointer(S)^,Length(S)); FXLS.UserName := S; end else begin P := PWideChar(Integer(PBuf) + 3); FXLS.UserName := WideCharLenToString(P,Sz); end; end; end; procedure TXLSReadII.RREC_WSBOOL; begin with FXLS.Sheets[FCurrSheet] do begin WorkspaceOptions := []; if (PWord(PBuf)^ and $0001) = $0001 then WorkspaceOptions := WorkspaceOptions + [woShowAutoBreaks]; if (PWord(PBuf)^ and $0010) = $0010 then WorkspaceOptions := WorkspaceOptions + [woApplyStyles]; if (PWord(PBuf)^ and $0040) = $0040 then WorkspaceOptions := WorkspaceOptions + [woRowSumsBelow]; if (PWord(PBuf)^ and $0100) = $0100 then WorkspaceOptions := WorkspaceOptions + [woFitToPage]; if (PWord(PBuf)^ and $0400) = $0400 then WorkspaceOptions := WorkspaceOptions + [woOutlineSymbols]; end; end; procedure TXLSReadII.RREC_HORIZONTALPAGEBREAKS; var i: integer; begin if FXLS.Version >= xvExcel97 then begin for i := 0 to PRecHORIZONTALPAGEBREAKS(PBuf).Count - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.HorizPagebreaks.Add do begin Row := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val1 - 1; Col1 := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val2 - 1; Col2 := PRecHORIZONTALPAGEBREAKS(PBuf).Breaks[i].Val3 - 1; end; end; end else if FXLS.Version = xvExcel50 then begin for i := 1 to PWordArray(PBuf)[0] - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.HorizPagebreaks.Add do begin Row := PWordArray(PBuf)[i] - 1; Col1 := 0; Col2 := 255; end; end; end; end; procedure TXLSReadII.RREC_VERTICALPAGEBREAKS; var i: integer; begin if FXLS.Version >= xvExcel97 then begin for i := 0 to PRecVERTICALPAGEBREAKS(PBuf).Count - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.VertPagebreaks.Add do begin Col := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val1 - 1; Row1 := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val2 - 1; Row2 := PRecVERTICALPAGEBREAKS(PBuf).Breaks[i].Val3 - 1; end; end; end else if FXLS.Version = xvExcel50 then begin for i := 1 to PWordArray(PBuf)[0] - 1 do begin with FXLS.Sheets[FCurrSheet].PrintSettings.VertPagebreaks.Add do begin Col := PWordArray(PBuf)[i] - 1; Row1 := 0; Row2 := 65535; end; end; end; end; procedure TXLSReadII.RREC_XF; begin if FXLS.Version >= xvExcel97 then FXLS.Formats.Add.FromXF8(PBuf) else if FXLS.Version >= xvExcel50 then FXLS.Formats.Add.FromXF7(PBuf) else if FXLS.Version >= xvExcel40 then FXLS.Formats.Add.FromXF4(PBuf) else // Add a dummy format FXLS.Formats.Add; end; procedure TXLSReadII.ReadMSOGroupPicture(Pict: TXLSPicture); begin FXLS.Pictures.Add.Assign(Pict); end; procedure TXLSReadII.ReadMSOSheetObject(Obj: TAnchorObject; ObjId: integer); begin if Obj is TSheetPicture then with FXLS.Sheets[FCurrSheet].SheetPictures.Add do begin Assign(TSheetPicture(Obj)); XLSPicture := FXLS.Pictures.PictureByItemId(ObjId); XLSPicture.RefCount := XLSPicture.RefCount + 1; end else if Obj is TNote then with FXLS.Sheets[FCurrSheet].Notes.Add do begin Assign(TNote(Obj)); ItemId := ObjId; HasNoteRecord := False; end else with FXLS.Sheets[FCurrSheet].FileCharts.Add(FXLS) do begin Records.Anchor.Assign(Obj); end; end; end.
unit Order.ShippmentProcesor; interface uses System.Classes, Data.DB, Shippment, DataProxy.Order, Order.Validator; type TShipmentProcessor = class(TComponent) private public procedure ShipOrder (Shippment: TShippment); end; implementation uses DataProxy.OrderDetails, Data.DataProxy, DataProxy.Factory; procedure TShipmentProcessor.ShipOrder (Shippment: TShippment); var isValid: Boolean; OrderDetails: TOrderDetailsProxy; Order: TOrderProxy; OrderValidator: TOrderValidator; TotalQuantity: Integer; begin OrderValidator := TOrderValidator.Create; try Order := DataProxyFactory.GetDataProxy_Order1(Shippment.OrderID); Order.Open; OrderDetails := DataProxyFactory.GetDataProxy_OrderDetails(Shippment.OrderID); OrderDetails.Open; TotalQuantity := OrderDetails.GetTotalQuantity; WriteLn ( ' TotalQuantity: ', TotalQuantity); Order.Edit; Order.ShippedDate.Value := Shippment.ShipmentDate; Order.ShipVia.Value := Shippment.ShipperID; isValid := OrderValidator.isValid(Order); if isValid then Order.Post; Order.Free; finally OrderValidator.Free; end; {$IFDEF CONSOLEAPP} WriteLn('Order has been processed....'); {$ENDIF} end; end.
unit xxmGeckoModule; interface uses nsXPCOM, nsTypes; type TxxmGeckoModule=class(TInterfacedObject, nsIModule) private FCompMgr:nsIComponentManager; protected procedure GetClassObject(aCompMgr: nsIComponentManager; const aClass: TGUID; const aIID: TGUID; out aResult); safecall; procedure RegisterSelf(aCompMgr: nsIComponentManager; aLocation: nsIFile; const aLoaderStr: PAnsiChar; const aType: PAnsiChar); safecall; procedure UnregisterSelf(aCompMgr: nsIComponentManager; aLocation: nsIFile; const aLoaderStr: PAnsiChar); safecall; function CanUnload(aCompMgr: nsIComponentManager): LongBool; safecall; public constructor Create(ACompMgr:nsIComponentManager); destructor Destroy; override; property CompMgr:nsIComponentManager read FCompMgr; end; TxxmGeckoComponent=class(TInterfacedObject) private FModule:TxxmGeckoModule; protected property Module:TxxmGeckoModule read FModule; public constructor Create(AOwner:TxxmGeckoModule); end; TxxmGeckoComponentClass=class of TxxmGeckoComponent; TxxmGeckoComponentFactory=class(TInterfacedObject, nsIFactory) private FOwner:TxxmGeckoModule; FClass:TxxmGeckoComponentClass; protected procedure CreateInstance(aOuter: nsISupports; const iid: TGUID; out _result); safecall; procedure LockFactory(lock: PRBool); safecall; public constructor Create(AOwner:TxxmGeckoModule;AClass:TxxmGeckoComponentClass); end; procedure RegisterComponent(AName,AContract:string;ACID:TGUID;AClass:TxxmGeckoComponentClass); function NSGetModule(aCompMgr: nsIComponentManager; location: nsIFile; out return_cobj: nsIModule): nsresult; cdecl; exports NSGetModule; implementation uses nsInit, nsError, ComObj, SysUtils; var RegisteredComponents:array of record Name,Contract:string; CID:TGUID; CCl:TxxmGeckoComponentClass; end; procedure RegisterComponent(AName,AContract:string;ACID:TGUID;AClass:TxxmGeckoComponentClass); var l:integer; begin l:=Length(RegisteredComponents); SetLength(RegisteredComponents,l+1); RegisteredComponents[l].Name:=AName; RegisteredComponents[l].Contract:=AContract; RegisteredComponents[l].CID:=ACID; RegisteredComponents[l].CCl:=AClass; end; function NSGetModule(aCompMgr: nsIComponentManager; location: nsIFile; out return_cobj: nsIModule): nsresult; cdecl; begin return_cobj:=TxxmGeckoModule.Create(aCompMgr); Result:=NS_OK; end; { TxxmGeckoModule } procedure TxxmGeckoModule.GetClassObject(aCompMgr: nsIComponentManager; const aClass, aIID: TGUID; out aResult); var i,l:integer; begin l:=Length(RegisteredComponents); i:=0; while (i<l) and not(IsEqualGUID(RegisteredComponents[i].CID,aClass)) do inc(i); if (i<l) then begin if not((TxxmGeckoComponentFactory.Create(Self,RegisteredComponents[i].Ccl) as IInterface).QueryInterface(aIID,aResult)=S_OK) then Error(reIntfCastError); end else Error(reInvalidOp); end; procedure TxxmGeckoModule.RegisterSelf(aCompMgr: nsIComponentManager; aLocation: nsIFile; const aLoaderStr, aType: PAnsiChar); var r:nsIComponentRegistrar; i:integer; begin r:=aCompMgr as nsIComponentRegistrar; for i:=0 to Length(RegisteredComponents)-1 do r.RegisterFactoryLocation( RegisteredComponents[i].CID, PAnsiChar(RegisteredComponents[i].Name), PAnsiChar(RegisteredComponents[i].Contract), aLocation,aLoaderStr,aType); //nsIXULAppInfo? //HKEY_CURRENT_USER\Software\Mozilla\Firefox\Extensions? //HKEY_LOCAL_MACHINE\Software\Mozilla\Firefox\Extensions? end; procedure TxxmGeckoModule.UnregisterSelf(aCompMgr: nsIComponentManager; aLocation: nsIFile; const aLoaderStr: PAnsiChar); var r:nsIComponentRegistrar; i:integer; begin r:=aCompMgr as nsIComponentRegistrar; for i:=0 to Length(RegisteredComponents)-1 do r.UnregisterFactoryLocation( RegisteredComponents[i].CID, aLocation); end; function TxxmGeckoModule.CanUnload( aCompMgr: nsIComponentManager): LongBool; begin //TODO: Result:=true; end; constructor TxxmGeckoModule.Create(ACompMgr: nsIComponentManager); begin inherited Create; FCompMgr:=ACompMgr; end; destructor TxxmGeckoModule.Destroy; begin FCompMgr:=nil; inherited; end; { TxxmGeckoComponent } constructor TxxmGeckoComponent.Create(AOwner: TxxmGeckoModule); begin inherited Create; FModule:=AOwner; end; { TxxmGeckoComponentFactory } constructor TxxmGeckoComponentFactory.Create(AOwner: TxxmGeckoModule; AClass: TxxmGeckoComponentClass); begin inherited Create; FOwner:=AOwner; FClass:=AClass; end; procedure TxxmGeckoComponentFactory.CreateInstance(aOuter: nsISupports; const iid: TGUID; out _result); begin if not((FClass.Create(FOwner) as IInterface).QueryInterface(iid,_result)=S_OK) then Error(reIntfCastError); end; procedure TxxmGeckoComponentFactory.LockFactory(lock: PRBool); begin //not implemented Error(reInvalidOp); end; initialization XPCOMGlueStartup(nil); finalization XPCOMGlueShutdown; end.
unit Unit2; interface uses SysUtils, Grids; Type Tkey=integer; Tinf=record fio: string[40]; key: Tkey; end; TSel=^Sel; Sel=record inf: Tinf; a: Tsel; end; Tobj=class(TObject) sp,sp1: Tsel; Constructor Create; Procedure Add(inf:TInf); Procedure Read(var inf:TInf); Procedure Sort; end; implementation Constructor TObj.Create; begin Inherited Create; new(sp1); sp1^.a:=Nil; end; Procedure Tobj.Add; begin new(sp); sp.inf:=inf; sp.a:=sp1.a; sp1.a:=sp; end; Procedure Tobj.Read; begin sp:=sp1^.a; inf:=sp^.inf; sp1^.a:=sp^.a; Dispose(sp); end; procedure TObj.sort; procedure revafter(spi:Tsel); var p:Tsel; begin p:=spi.a.a; spi.a.a:=p.a; p.a:=spi.a; spi.a:=p; end; var spt:Tsel; begin spt:=nil; repeat sp:=sp1; while sp.a.a<>spt do begin if sp.a.inf.key>sp.a.a.inf.key then revafter(sp); sp:=sp.a; end; spt:=sp.a; until spt=sp1.a.a; end; end.
unit IconChg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, SetIcons, ShlObj; type TdlgIconChange = class(TForm) btnOk: TButton; btnCancel: TButton; Label1: TLabel; btnBrowse: TButton; lstIcon: TListBox; dlgBrowse: TOpenDialog; procedure lstIconDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure FormDestroy(Sender: TObject); procedure btnBrowseClick(Sender: TObject); private FIconFile: string; FItemIDList: PItemIDList; procedure SetIconFile(const Value: string); procedure SetItemIDList(const Value: PItemIDList); procedure DeleteIcons; public property IconFile: string read FIconFile write SetIconFile; property ItemIDList: PItemIDList read FItemIDList write SetItemIDList; end; var dlgIconChange: TdlgIconChange; implementation {$R *.DFM} { TdlgIconChange } // フォーム終わり procedure TdlgIconChange.FormDestroy(Sender: TObject); begin DeleteIcons; end; // アイコン削除 procedure TdlgIconChange.DeleteIcons; var i: Integer; begin for i := 0 to lstIcon.Items.Count - 1 do TIcon(lstIcon.Items.Objects[i]).Free; lstIcon.Clear; end; // アイコンセット procedure TdlgIconChange.SetIconFile(const Value: string); var Icon: TIcon; LIcon, SIcon: HIcon; i: Integer; begin if FIconFile = Value then Exit; ItemIDList := nil; DeleteIcons; i := 0; while True do begin if not GetIconHandle(PChar(Value), ftIconPath, i, LIcon, SIcon) then Break; Icon := TIcon.Create; Icon.Handle := LIcon; DestroyIcon(SIcon); lstIcon.Items.AddObject('', Icon); Inc(i); end; if lstIcon.Items.Count > 0 then lstIcon.ItemIndex := 0; FIconFile := Value; end; // 項目識別子セット procedure TdlgIconChange.SetItemIDList(const Value: PItemIDList); var Icon: TIcon; LIcon, SIcon: HIcon; begin if FItemIDList = Value then Exit; IconFile := ''; DeleteIcons; if Value <> nil then begin if GetIconHandle(Value, ftPIDL, 0, LIcon, SIcon) then begin Icon := TIcon.Create; Icon.Handle := LIcon; DestroyIcon(SIcon); lstIcon.Items.AddObject('', Icon); lstIcon.ItemIndex := 0; end; end; FItemIDList := Value; end; // アイコン描画 procedure TdlgIconChange.lstIconDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var icoWrk: TIcon; x: Integer; begin with (Control as TListBox),Canvas do begin FillRect(Rect); icoWrk := TIcon(Items.Objects[Index]); if icoWrk <> nil then begin x := Rect.Left + (Rect.Right - Rect.Left - 32) div 2; Draw(x, Rect.Top + 1, icoWrk); end; end; end; // 参照 procedure TdlgIconChange.btnBrowseClick(Sender: TObject); var Ext: string; begin with dlgBrowse do begin if FileExists(IconFile) then begin FileName := IconFile; InitialDir := ExtractFileDir(IconFile); Ext := ExtractFileExt(IconFile); Ext := AnsiLowerCase(Ext); if (Ext = '.exe') or (Ext = '.ico') or (Ext = '.dll') or (Ext = '.icl') then FilterIndex := 1 else FilterIndex := 2; end; if Execute then IconFile := FileName end; end; end.
unit UPicOpcode; interface uses SysUtils, Classes,dialogs; type TMcOpcodeKind =(mkReg,mkBit,mkLitControl,mkJump,mkNoOperand); TMcDest =(md_W,md_F); TMcOpcode =(opInvalid,opADDWF, opANDWF, opCLRF, opCLRW, opCOMF, opDECF, opDECFSZ, opINCF,opINCFSZ,opIORWF, opMOVF, opMOVWF, opNOP, opRLF, opRRF, opSUBWF, opSWAPF, opXORWF,opBCF,opBSF, opBTFSC, opBTFSS, opADDLW, opANDLW, opCALL, opCLRWDT, opGOTO, opIORLW,opMOVLW , opRETFIE, opRETLW, opRETURN, opSLEEP, opSUBLW, opXORLW); TInstData = record mOpCode:TMcOpcode; mInstink:TMcOpcodeKind; case integer of 0:(mFile:integer; case integer of 0:( mDest:TMcDest); 1:( mBitIdx:integer); ); 1:( mLiteral:integer); end; TPicOpcode =class private FList :TStrings; FLabelsList:TList; // procedure Add(AOpcode:integer;const AName:string); public constructor Create; destructor Destroy;override; // procedure Decode(AOpList:array of byte;ACount:integer); end; function InstDecode(AOpcode:Integer;var AOpkink:TMcOpcodeKind):TMcOpcode; function ExpandInst(AOpcode:Integer;var AOut:TInstData):boolean; procedure MCDecode(AOpList:array of byte;ACount:integer;AList:TStrings); const OPCODENAMES:array[TMcOpcode] of string = ('Invalid','addwf','andwf','clrf','clrw','comf','decf','decfsz','incf','incfsz','iorwf', 'movf','movwf','nop','rlf','rrf','subwf','swapf','xorwf','bcf','bsf','btfsc', 'btfss','addlw','andlw','call','clrwdt','goto','iorlw','movlw ','retfie','retlw', 'return','sleep','sublw','xorlw'); const OPCODVALUES:array[TMcOpcode] of integer = ($FFFF,$0700,$0500,$0180,$0100,$0900,$0300,$0B00,$0A00,$0F00,$0400,$0800,$0080, $0000,$0D00,$0C00,$0200,$0E00,$0600,$1000,$1400,$1800,$1C00,$3E00,$3900, $2000,$0064,$2800,$3800,$3000,$0009,$3400,$0008,$0063,$3C00,$3A00); implementation var FSRTable:TList; type PFSRReg=^TFSRReg; TFSRReg=record mName:string; Bits:array[0..7]of string; end; { TPicOpcode } constructor TPicOpcode.Create; begin FLabelsList:= TList.Create; FList:= TStringList.Create; end; destructor TPicOpcode.Destroy; begin FList.Free; FLabelsList.Free; inherited; end; function InstDecode(AOpcode: Integer;var AOpkink:TMcOpcodeKind): TMcOpcode; const OPARR:array [0..15] of TMcOpcode =(opInvalid,opInvalid,opSUBWF, opDECF,opIORWF , opANDWF ,opXORWF ,opADDWF ,opMOVF ,opCOMF ,opINCF,opDECFSZ, opRRF ,opRLF ,opSWAPF ,opINCFSZ); var t:integer; begin case AOpcode and $3000 of 0:begin AOpkink := mkReg; t := AOpcode and $F00; if t >= $200 then Result := OPARR[t shr 8] else case AOpcode and $180 of $180: Result := opCLRF; $100: Result := opCLRW; $080: Result := opMOVWF; else case AOpcode and $7F of $09: Result := opRETFIE; $08: Result := opRETURN; $63: Result := opSLEEP; $64: Result := opCLRWDT; $00: Result := opNOP; else Result := opInvalid; end; end; end; $1000:begin AOpkink := mkBit; case AOpcode and $C00 of $000: Result := opBCF; $400: Result := opBSF; $800: Result := opBTFSC; $C00: Result := opBTFSS; end; end; $3000:begin AOpkink := mkLitControl; case AOpcode and $C00 of $000: Result := opMOVLW; $400: Result := opRETLW; $800: case AOpcode and $300 of $000: Result := opIORLW; $100: Result := opANDLW; $200: Result := opXORLW; else Result := opInvalid; end; $C00:if (AOpcode and $200 )<> 0 then Result := opADDLW else Result := opSUBLW; end; end; $2000:begin AOpkink := mkJump; if (AOpcode and $800 )<> 0 then Result := opGOTO else Result := opCALL; end; end; end; function ExpandInst(AOpcode:Integer;var AOut:TInstData):boolean; var Opkink:TMcOpcodeKind; begin with AOut do begin mOpCode := InstDecode(AOpcode,mInstink); Result := mOpCode <>opInvalid; if not Result then Exit; if mOpCode in [opNop,opReturn,opClrW,opCLRWDT,opSleep,opRetfie ] then mInstink := mkNoOperand else case mInstink of mkReg:begin mFile := AOpcode and $7F; mDest := TMcDest((AOpcode shr 7) and 1) ; end; mkBit:begin mFile := AOpcode and $7F; mBitIdx := (AOpcode shr 7) and 7 ; end; mkLitControl:begin mLiteral := AOpcode and $FF; end; mkJump:begin mLiteral := AOpcode and $7FF; end; end; end; end; function FileDecode(Address:integer):string; begin if Address >= FSRTable.Count then Result:='0x'+InttoHex(Address,2) else Result:=PFSRReg(FSRTable[Address]).mName; end; function FileBitsDecode(Address,Bit:integer):string; var t:string; begin if Address >= FSRTable.Count then Result:='0x'+InttoHex(Address,2)+','+inttostr(Bit) else with PFSRReg(FSRTable[Address])^ do begin t:=Bits[7-Bit]; if t='' then t:=inttostr(Bit); Result:=mName+','+t; end; end; procedure MCDecode(AOpList:array of byte;ACount:integer;AList:TStrings); type TLabelName= array[0..3 ] of char; const DESTLOC :array[TMcDest] of char =('W','F'); var LabelsList:TList; DumpList:TStrings; I,L,Pz,Lab:integer; V:Word; InstData:TInstData; S:string; P:Pointer; begin if Length(AOpList) < ACount then Exit; LabelsList:=TList.Create; DumpList:=TStringList.Create; AList.BeginUpdate; try Pz:=1; for I := 0 to ACount div 2 -1 do begin V:=AOpList[I*2]or (AOpList[I*2+1] shl 8); if ExpandInst(V,InstData )then with InstData do case mInstink of mkReg:begin if InstData.mOpCode in [opMOVWF,opCLRF] then S := Format('%-7s%s',[OPCODENAMES[mOpCode],FileDecode(mFile)]) else S := Format('%-7s%s,%s',[OPCODENAMES[mOpCode],FileDecode(mFile),DESTLOC[mDest]]) end; mkBit:begin S := Format('%-7s%s',[OPCODENAMES[mOpCode],FileBitsDecode(mFile,mBitIdx)]); end; mkLitControl:begin S := Format('%-7s0x%.2x',[OPCODENAMES[mOpCode],mLiteral]); end; mkJump:begin // S := Format('%s 0x%.x',[OPCODENAMES[mOpCode],mLiteral]); if mLiteral >= LabelsList.Count then LabelsList.Count:=mLiteral+1; Lab:=Integer(LabelsList[mLiteral]); if Lab=0 then begin Lab:=Pz; Inc(Pz); LabelsList[mLiteral]:=Pointer(Lab); end; S := Format('%-7sL%d',[OPCODENAMES[mOpCode],Lab]); end; mkNoOperand:begin S := Format('%s',[OPCODENAMES[mOpCode]]); end; end else S := Format('unknown: 0x%.4x',[V]); DumpList.Add(S); end; // DumpList.Count:= Pz; LabelsList.Count:= DumpList.Count; for I := 0 to DumpList.Count -1 do begin if LabelsList[I] <> nil then AList.Add( Format('L%-4s %s',[Inttostr(Integer(LabelsList[I]))+':',DumpList[I]])) else AList.Add(' '+DumpList[I]); end; finally AList.EndUpdate; DumpList.Free; LabelsList.Free; end; end; procedure LoadTables(); var tsp:TStringList; procedure AddFSR(Address:integer;const S:string); var I:integer; P:PFSRReg; begin if Address >= FSRTable.Count then begin FSRTable.Count:=Address+1; end; New(P); FSRTable[Address]:=P; tsp.DelimitedText := S; P.mName :=tsp[0]; for I:= 1 to tsp.Count-1 do begin if I = 9 then break; P.Bits[I-1]:=tsp[I]; end; end; begin FSRTable:=TList.Create; tsp:=TStringList.Create; try // tsp.Delimiter:=';'; AddFSR(0,'INDF'); AddFSR(1,'TMR0'); AddFSR(2,'PCL'); AddFSR(3,'STATUS IRP RP1 RP0 TO PD Z DC C'); AddFSR(4,'FSR'); AddFSR(5,'PORTA'); AddFSR(6,'PORTB'); AddFSR(7,'PORTC'); AddFSR(8,'PORTD'); AddFSR(9,'PORTE'); AddFSR($A,'PCLATH'); // AddFSR($B,''); // AddFSR(,''); // AddFSR(,''); finally tsp.Free; end; end; initialization LoadTables; end.
unit RaceHorsePopulation; {$mode objfpc}{$H+} interface uses Classes, SysUtils, resource, RaceHorse; const HORSE_POPULATION_SIZE = 60; type TRaceHorsePopulation = class(TPersistent) private fRaceHorseCollection: TCollection; public constructor CreateRandom( PopulationSize: integer; StartPosition: single; TrackWidth: integer); function LoadHorse( GateIndex: integer; StartPosition: single): TRaceHorse; procedure WriteToFile; constructor CreateFromFile; constructor CreateFromResource; procedure SortRandomly; published property RaceHorseCollection: TCollection read fRaceHorseCollection write fRaceHorseCollection; end; implementation var HorseNames: array [1..HORSE_POPULATION_SIZE] of string = ( 'Fast Fourier', 'Famous Amos', 'Bourbon Believer', 'Whisky River', 'Victory Vodka', 'Tequila Teaser', 'Rum Forest Rum', 'Gone For Gin', 'Hay Now', 'Oats For Otis', 'Streaking And Peaking', 'Kentucky Colonel', 'Sam I Am', 'Happy Hippy', 'Bourbon Barrel Beer', 'Bluegrass Boss', 'Derby Dreamer', 'Say No More', 'Happy Horton', 'Slippery Slope', 'Pony Express', 'Stewball', 'Old Spice', 'Freddie Freeloader', 'Rocket Ready', 'Meadow Man', 'Paddock Pappy', 'Italian Stallion', 'Distillery Dan', 'Mountain Man', 'One Eyed Jack', 'Suicide King', 'Le Roi de Coeur', 'Talk Like A Pirate', 'Rickhouse Racer', 'Lucky Louie', 'Diamond Mine', 'Gold Dust Guy', 'Black Widow', 'Deadwood Dealer', 'Woodstock Wanderer', 'Aisle Of White', 'Restless Ridgling', 'Finnicky Filly', 'Pedal Steel Pony', 'Swimming Pool Shark', 'Lanky Lifeguard', 'Femme Fatale', 'Midnight Marauder', 'Come Back Shane', 'OK Corral', 'Duncan Dough Nut', 'Phil M Noir', 'Endless Summer', 'Channel Won', 'Honeymooner', 'Southern Dancer', 'Goes To Eleven', 'Dynasty Diva', 'Rogue Agent' ); constructor TRaceHorsePopulation.CreateRandom( PopulationSize: integer; StartPosition: single; TrackWidth: integer); var i: integer; horse: TRaceHorse; begin RaceHorseCollection := TCollection.Create(TRaceHorse); for i := 1 to PopulationSize do begin horse := TRaceHorse(RaceHorseCollection.Add); horse.Name := HorseNames[i]; horse.RandomizeSpeedInfo(StartPosition, TrackWidth); end; end; function TRaceHorsePopulation.LoadHorse( GateIndex: integer; StartPosition: single): TRaceHorse; var horse: TRaceHorse; begin horse := TRaceHorse(RaceHorseCollection.Items[GateIndex - 1]); horse.LoadHorse(StartPosition); result := horse; end; procedure TRaceHorsePopulation.WriteToFile; var horseCount: integer; i: integer; horse: TRaceHorse; json: string; fsOut: TFileStream; begin fsOut := TFileStream.Create('HorsePopulation.data', fmCreate); horseCount := RaceHorseCollection.Count; fsOut.WriteDWord(horseCount); for i := 1 to horseCount do begin horse := TRaceHorse(RaceHorseCollection.Items[i - 1]); json := horse.ToJson; fsOut.WriteAnsiString(json); end; fsOut.Free; end; constructor TRaceHorsePopulation.CreateFromFile; var horseCount: integer; i: integer; horse: TRaceHorse; json: string; fsIn: TFileStream; begin RaceHorseCollection := TCollection.Create(TRaceHorse); fsIn := TFileStream.Create('HorsePopulation.data', fmOpenRead); horseCount := fsIn.ReadDWord; for i := 1 to horseCount do begin json := fsIn.ReadAnsiString; horse := TRaceHorse(RaceHorseCollection.Add); horse.FromJson(json); end; fsIn.Free; end; constructor TRaceHorsePopulation.CreateFromResource; var horseCount: integer; i: integer; horse: TRaceHorse; json: string; rsIn: TResourceStream; begin RaceHorseCollection := TCollection.Create(TRaceHorse); rsIn := TResourceStream.Create(HInstance, 'HORSEPOPULATION', MAKEINTRESOURCE(RT_RCDATA)); horseCount := rsIn.ReadDWord; for i := 1 to horseCount do begin json := rsIn.ReadAnsiString; horse := TRaceHorse(RaceHorseCollection.Add); horse.FromJson(json); end; rsIn.Free; end; function RandomCompare( {%H-}Item1: TCollectionItem; {%H-}Item2: TCollectionItem): integer; begin result := Random(10) - 5; end; procedure TRaceHorsePopulation.SortRandomly; begin; RaceHorseCollection.Sort(@RandomCompare); end; end.
unit pointeraddresslist; {$mode delphi} { the pointeraddresslist will hold a map of all addresses that contain an pointer and the value they hold. It's similar to the reversepointerlist, with the exception that I expect this to eat a TON more RAM since there are more addresses with a pointer then there are unique pointer values (multiple addresses point to the same address) Also, this first implementation will make use of the default available maps object } interface uses Classes, SysUtils, maps, ComCtrls, bigmemallochandler, CEFuncProc; resourcestring rsPALInvalidScandataFile = 'Invalid scandata file'; rsPALInvalidScandataVersion = 'Invalid scandata version'; type TPointerListHandler=class private bma: TBigMemoryAllocHandler; pmap: TMap; modulelist: tstringlist; modulebases: array of ptruint; is32bit: boolean; public procedure reorderModuleIdList(ml: tstrings); //changes the order of modules so they match the provided list (addresses stay unchanged of course) function getAddressFromModuleIndexPlusOffset(moduleindex: integer; offset: integer): ptruint; function getPointer(address: ptruint): ptruint; //return 0 if not found constructor createFromStream(s: TStream; progressbar: tprogressbar=nil); destructor destroy; override; end; implementation uses pointervaluelist; function TPointerListHandler.getAddressFromModuleIndexPlusOffset(moduleindex: integer; offset: integer): ptruint; begin if moduleindex>=0 then result:=modulebases[moduleindex]+offset else result:=offset; //if moduleindex=-1 it's an non module base end; function TPointerListHandler.getPointer(address: ptruint): ptruint; var base: ptruint; pbase: PByteArray; begin base:=address and qword(not qword($ffff)); if pmap.GetData(base, pbase) then begin if is32bit then result:=pdword(@pbase[address-base])^ else result:=pqword(@pbase[address-base])^ end else result:=0; end; procedure TPointerListHandler.reorderModuleIdList(ml: tstrings); //sorts the modulelist based on the given modulelist var oldindex: integer; oldmodulename: string; oldaddress :ptruint; i: integer; begin //example: //in ml: game.exe is loaded at 20000000 (module 1) //in modulelist: game is loaded at 30000000 (module 2) //during the scan the moduleid's of ml are requested but they need to return the address as it was //so if the pscan requests moduleid1+10 it must return 30000010 //make room for the list if it's smaller while modulelist.Count<ml.count do begin i:=modulelist.add('missing'); setlength(modulebases, length(modulebases)+1); modulebases[length(modulebases)-1]:=0; end; for i:=0 to ml.count-1 do begin //find this module in the current module list oldindex:=modulelist.IndexOf(ml[i]); if oldindex=-1 then //it wasn'tin the list, add it with address 0 begin oldindex:=modulelist.Add(ml[i]); setlength(modulebases, length(modulebases)+1); modulebases[length(modulebases)-1]:=0; end; if oldindex<>i then begin //swap oldaddress:=modulebases[oldindex]; oldmodulename:=modulelist[oldindex]; modulebases[oldindex]:=modulebases[i]; modulelist[oldindex]:=modulelist[i]; modulebases[i]:=oldaddress; modulelist[i]:=oldmodulename; end; end; end; constructor TPointerListHandler.createFromStream(s: TStream; progressbar: tprogressbar=nil); var i,x: integer; mlistlength: integer; mname: pchar; count: qword; totalcount: qword; ml: dword; value: ptruint; nrofpointers: integer; lastupdate: qword; address: qword; base: qword; offset: dword; pbase: pbytearray; limit: integer; begin //create and fill in the pointerlist based on a reversepointerlist if s.ReadByte<>$ce then raise exception.create(rsPALInvalidScandataFile); if s.ReadByte<>ScanDataVersion then raise exception.create(rsPALInvalidScandataVersion); bma:=TBigMemoryAllocHandler.create; pmap:=TMap.Create(ituPtrSize, sizeof(ptruint)); modulelist:=TStringList.create; modulelist.CaseSensitive:=false; mlistlength:=s.ReadDWord; setlength(modulebases, mlistlength); for i:=0 to mlistlength-1 do begin x:=s.ReadDWord; getmem(mname, x+1); s.ReadBuffer(mname^, x); mname[x]:=#0; modulebases[i]:=s.ReadQWord; //seperate array for quicker lookup modulelist.AddObject(mname, tobject(modulebases[i])); FreeMemAndNil(mname); end; if s.ReadByte=1 then //specific base as static only begin s.ReadQWord; //basestart s.ReadQWord; //basestop end; ml:=s.ReadDWord; //maxlevel (for determining if 32 or 64-bit) if ml=7 then begin is32bit:=true; limit:=65536-sizeof(dword); end else begin is32bit:=false; limit:=65536-sizeof(qword); end; totalcount:=s.ReadQWord; count:=0; if progressbar<>nil then begin progressbar.position:=0; progressbar.Max:=100; end; lastupdate:=GetTickCount64; while count<totalcount do begin value:=ptruint(s.ReadQWord); nrofpointers:=s.ReadDWord; for i:=0 to nrofpointers-1 do begin address:=s.ReadQWord; base:=address and qword(not qword($ffff)); if not pmap.GetData(base, pbase) then begin pbase:=bma.alloc(65536); pmap.Add(base, pbase); end; if (address-base)<limit then begin if is32bit then PDWord(@pbase[address-base])^:=value else PQWord(@pbase[address-base])^:=value end; //todo: else add some overlap support. But for now, only allow alligned pointers if s.ReadByte=1 then //has static info s.ReadQWord; //discard data end; inc(count, nrofpointers); if (progressbar<>nil) and (gettickcount64>lastupdate+1000) then begin progressbar.position:=trunc(count/totalcount*100); lastupdate:=GetTickCount64; end; end; end; destructor TPointerListHandler.destroy; begin if pmap<>nil then pmap.free; bma.free; inherited destroy; end; end.
program auflager; uses crt,strings; const maxf:integer=10; type kraft = record f,fx,fy:real; lx,ly:real; alpha:real; end; var f: array [0..10] of kraft; fa,fb:kraft; anzahl_F:integer; ende:boolean; maxmb,maxq,maxt:real; maxmb_berechnet,auflager_berechnet,daten_vorhanden:boolean; s:string; procedure out_f(s:string; F:kraft); begin writeln( s,' Betrag: ',F.f:3:3,' N;',' Richtung:',F.alpha*180/pi:3:3,' Grad;'); writeln(' Fx: ',f.fx:3:3,' N; Fy: ',F.fy:3:3,' N;'); end; procedure wartetaste; begin writeln; writeln('Bitte eine Taste drcken.'); repeat until keypressed; readln end; procedure fehler(s:string); begin clrscr; textcolor(lightred+blink); gotoxy(30,12); writeln(s); delay(2000); textbackground(black); textcolor(white); end; procedure read1r(s:string; var x:real); begin write(s); readln(x) end; procedure init_debug; begin { einfacher Tr„ger fr testzwecke, '0' im Men drcken } anzahl_f:=2; with fa do begin lx:=0; ly:=0; f:=0; alpha:=0; fx:=0; fy:=0; end; with fb do begin lx:=5; ly:=0; f:=0; alpha:=0; fx:=0; fy:=0; end; with f[1] do begin lx:=2.5; ly:=0; f:=1000*sqrt(2); alpha:=pi/4; fx:=-1000; fy:=-1000; end; with f[2] do begin lx:=10; ly:=0; f:=1000; alpha:=pi/2; fx:=0; fy:=-1000; end; daten_vorhanden:=true; maxmb_berechnet:=false; auflager_berechnet:=false; clrscr; writeln('Testdaten installiert'); wartetaste; end; procedure init; var i:integer; n:real; s:string; ok:boolean; begin clrscr; ok:=false; maxmb_berechnet:=false; auflager_berechnet:=false; if daten_vorhanden then begin write('Bereits Daten eingegeben; diese l”schen(j/n) ?'); repeat until keypressed; if readkey='j' then ok:=true; end else ok:=true; writeln; { A ..... Festlager B ..... Loslager Fa u. Fb immer in positiver Richtung A()---------------------------()B /\ /\ } if ok then begin with fa do begin writeln('Position Festlager eingeben (Nullpunkt beliebig):'); read1r('X-Koordinate:',lx); read1r('Y-Koordinate:',ly); f:=0; fx:=0; fy:=0; end; with fb do begin writeln; writeln('Position Loslager eingeben:'); read1r('X-Koordinate:',lx); read1r('Y-Koordinate:',ly); read1r('Winkel zur positiven X-Achse:',alpha); alpha:=alpha*pi/180; f:=0; fx:=0; fy:=0; end; writeln; repeat writeln; read1r('Anzahl der angreifenden Kr„fte (1..10; 0 => Ende):',n); gotoxy(wherex,wherey-2); until n<=10; writeln; writeln; if n=0 then halt; anzahl_f:=round(n); for i:=1 to anzahl_f do begin with f[i] do begin f:=0; fx:=0; fy:=0; alpha:=0; writeln('Kraft nummer ',i); writeln; read1r('X-Koordinate:',lx); read1r('Y-Koordinate:',ly); { read1r('Betrag in Newton',f); read1r('Winkel zur positiven X-Achse in Grad:',alpha); } read1r('X-komponente in Newton:',fx); read1r('Y-komponente in Newton:',fy); f := sqrt(sqr(fx)+sqr(fy)); if fx<>0 then alpha := arctan(fy/fx) else alpha := pi*fy/abs(2*fy); writeln; end; end; end; daten_vorhanden:=true; end; procedure berechne_auflager; var i:integer; lx,ly:real; em,efx,efy:real; begin if daten_vorhanden then begin { zuerst E M(a)=0; => fb } clrscr; writeln; writeln; writeln(' Berechne...'); EM:=0; Efx:=0; Efy:=0; for i:=1 to anzahl_F do begin with f[i] do begin EM := EM + fy*(lx-fa.lx) + fx*(ly-fa.ly); EFx := EFx + fx; EFy := EFy + fy; end; end; with fb do begin if (lx-fa.lx)<>0 then fy:= - EM / (lx - fa.lx); if alpha<>0 then begin f := abs(fy); fx := cos(alpha)*fy; fy := sin(alpha)*fy; end else begin f := abs(fy); fx:=0; alpha:=pi/2; end; end; { jetzt fa.x u. fa.y aus E Fx = 0; u. E Fy = 0; } with fa do begin fx:= - fb.fx - EFx; fy:= - fb.fy - EFy; f := sqrt(sqr(fx)+sqr(fy)); alpha:=arctan(fy/fx); end; auflager_berechnet:=true; write('Ok'); wartetaste; end else begin clrscr; writeln('Zuerst Daten eingeben!'); wartetaste; end; end; procedure ausgabe_auflager; var s:string; begin if auflager_berechnet then begin clrscr; writeln('Auflagerreaktionen'); writeln('=================='); writeln; writeln; out_f('Festlager Fa:',fa); writeln; out_f('Loslager Fb:',fb); writeln; writeln('Taste drcken'); repeat until keypressed; readln; end else begin clrscr; writeln('Auflager noch nicht berechnet!'); wartetaste; end; end; procedure mb(x:real; var mbx,q,t:real); var mfa,mfb:real; i:integer; begin mbx:=0; q:=0; t:=0; mfa:=0; mfb:=0; i:=1; repeat if f[i].lx<x then begin with f[i] do begin t:=t+fx; q:=q+fy; mbx:=mbx+fy*(x-lx); end; end; inc(i); until i>anzahl_f; if fa.lx<x then begin t:=t+fa.fx; q:=q+fa.fy; mfa:=fa.fy*(x-fa.lx); end else mfa:=0; if fb.lx<x then begin t:=t+fb.fx; q:=q+fb.fy; mfb:=fb.fy*(x-fb.lx); end else mfb:=0; mbx:=mfa + mfb + mbx; end; procedure berechne_mbq_beliebig; var x,q,t,mbx:real; i:integer; ende:boolean; begin ende:=false; clrscr; if auflager_berechnet then begin repeat writeln; read1r('Schnitt-X-Koordinate bitte eingeben (in meter):',x); mb(x,mbx,q,t); writeln('Mb an der stelle x=',x:3:3,'m betr„gt ',mbx:3:3,'Nm'); writeln('Q an der stelle x=',x:3:3,'m betr„gt ',q:3:3,'N'); writeln('T an der stelle x=',x:3:3,'m betr„gt ',t:3:3,'N'); write('Nochmal (j/n) ?'); repeat until keypressed; if readkey='n' then ende:=true; writeln; until ende; end else begin writeln('Zuerst schritte 1 u. 2 ausfhren !'); wartetaste; end; end; procedure berechne_maxmbq; var mbx,q,t,x_q,x_t,x_mb,xu,xo,x,sx,l:real; begin clrscr; x:=0; sx:=0; maxQ:=0; maxT:=0; maxMb:=0; mbx:=0; q:=0; t:=0; x_q:=0; x_t:=0; x_mb:=0; if fa.lx>fb.lx then l:=fa.lx else l:=fb.lx; read1r('untere Grenze:',xu); read1r('obere Grenze :',xo); read1r('Schrittweite bitte eingeben (in meter):',sx); writeln; x:=xu; while(x<(xo-sx)) do begin mb(x,mbx,q,t); if abs(mbx)>abs(maxMb) then begin maxMb:=mbx; x_mb:=x; end; if abs(t)>abs(maxt) then begin maxt:=t; x_t:=x; end; if abs(q)>abs(maxq) then begin maxq:=q; x_q:=x; end; x:=x+sx; writeln('x=',x:3:3); gotoxy(wherex,wherey-1); end; writeln; writeln; writeln('maxMb an der stelle x=',x_mb:3:3,'m betr„gt ',maxmb:3:3,'Nm'); writeln('maxQ an der stelle x=',x_q:3:3,'m betr„gt ',maxq:3:3,'N'); writeln('maxT an der stelle x=',x_t:3:3,'m betr„gt ',maxt:3:3,'N'); wartetaste; maxmb_berechnet:=true; end; procedure berechne_f_beliebig; begin end; procedure berechne_maxf; begin end; procedure dimensioniere; begin end; procedure menu; var wahl,c:integer; s:string; begin wahl:=-1; clrscr; writeln(' Tr„ber V1.0'); writeln(' ==========='); writeln; writeln; writeln; writeln(' 1......Dateneingabe'); writeln(' 2......Auflagerreaktionen berechnen'); writeln(' 3......Auflagerreaktionen anzeigen'); writeln(' 4......Biegemoment Mb u. Querkraft Q an einer beliebigen'); writeln(' Stelle x anzeigen'); writeln(' 5......max. Mb berechnen und anzeigen'); writeln(' 6......Durchbiegung an einer beliebigen Stelle x'); writeln(' berechnen und anzeigen'); writeln(' 7......maximale Durchbiegung anzeigen'); writeln(' 8......Dimensionierung'); writeln; writeln(' 9......Programmende'); gotoxy(50,24); write('(C) 1994 by Stefan Eletzhofer'); gotoxy(10,20); while (wahl<0) or (wahl>9) and (c<>0) do begin write('Ihre Wahl:'); readln(s); val(s,wahl,c); end; case wahl of 0: init_debug; 1: if auflager_berechnet then begin init; auflager_berechnet:=false end else init; 2: if daten_vorhanden then berechne_auflager else fehler('Zuerst Daten eingeben!'); 3: if auflager_berechnet then ausgabe_auflager else fehler('Zuerst Auflager berechnen!'); 4: if auflager_berechnet then berechne_mbq_beliebig else fehler('Zuerst Auflager berechnen!'); 5: if auflager_berechnet then berechne_maxmbq else fehler('Zuerst Auflager berechnen!'); 6: if auflager_berechnet then berechne_f_beliebig else fehler('Zuerst Auflager berechnen!'); 7: if auflager_berechnet then berechne_maxf else fehler('Zuerst Auflager berechnen!'); 8: if maxmb_berechnet then dimensioniere else fehler('Zuerst maximales Biegemoment berechnen!'); 9: ende:=true; end; end; begin highvideo; textbackground(black); textcolor(white); ende:=false; maxmb_berechnet:=false; auflager_berechnet:=false; daten_vorhanden:=false; repeat menu; until ende; end.
unit PXMLForm; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VirtualTrees, ExtCtrls, XMLDoc, XMLIntf, ComCtrls, Menus, ButtonGroup, InputFilterFunctions; type { DataType for caching the schema file in an array for faster access to needed data (faster than searching the XML file every time) } PPXMLElement = ^rPXMLElement; rPXMLElement = record Tag : String; Parent : PPXMLElement; XNode : IXMLNode; Root : PPXMLElement; Display : String; end; rXMLTreeData = record Node : IXMLNode; DisplayKey : String; SchemaLink : PPXMLElement; end; PXMLTreeData = ^rXMLTreeData; TXMLGrpButtonItem = class(TGrpButtonItem) public Data : PPXMLElement; end; TfrmPXML = class(TForm) pnlButtons: TPanel; btnCancel: TButton; btnOK: TButton; sadPXML: TSaveDialog; pnlData: TPanel; scbValues: TScrollBox; lblValue: TLabel; lblAttr: TLabel; lblDescription: TLabel; lblNoValue: TLabel; lblNoAttr: TLabel; pnlValue: TPanel; edtValue: TEdit; pnlTree: TPanel; vstPXML: TVirtualStringTree; sptHor: TSplitter; redDescription: TRichEdit; pomPXML: TPopupMenu; pomPXMLDelete: TMenuItem; pnlElements: TPanel; bugElements: TButtonGroup; sptVert: TSplitter; pnlFilter: TPanel; lblFilter: TLabel; rabSelection: TRadioButton; rabPackage: TRadioButton; rabApplication: TRadioButton; pnlValueText: TPanel; memValue: TMemo; procedure FormShow(Sender: TObject); procedure vstPXMLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rabSelectionClick(Sender: TObject); procedure bugElementsButtonClicked(Sender: TObject; Index: Integer); procedure pomPXMLDeleteClick(Sender: TObject); procedure vstPXMLMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure vstPXMLChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure vstPXMLInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure FormCreate(Sender: TObject); procedure vstPXMLGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private // Recursively adds XML Data to the VirtualTree starting with the passed node procedure AddDataToTree(Tree : TBaseVirtualTree; Data : IXMLNode; Node : PVirtualNode); // Updates the XML Data in Doc with the values in the current attribute panels procedure UpdateXMLData; // Clears the currently displayed attribute panels procedure ResetPanels; // Adds attribute panels for the passed node (reads schema for missing attributes) // and adds those, too procedure AddPanels(Data : PXMLTreeData); // Search for a node by caption (element name), returns NULL on failure function FindNode(Tree : TBaseVirtualTree; const S : String; Base : PVirtualNode) : PVirtualNode; overload; function FindNode(const S : String; Node : IXMLNode) : IXMLNode; overload; // Find a selected node with the passed caption, returns either the selected // node, a parent of the selected node (if applicable) or NULL function FindSelectedNode(Tree: TBaseVirtualTree; const S: String) : PVirtualNode; // Counts occurences of nodes with the passed caption in child nodes of Base function CountNodes(Tree : TBaseVirtualTree; const S : String; Base : PVirtualNode) : Integer; // Show applicable element buttons for the current situation procedure ShowElementButtons; public // Clears the whole Form, dispatches all Objects procedure Clear; // Load a XML file to the Form function LoadFromFile(const FileName : String) : Boolean; // Create a new XML file (loads the default file) function CreateNewFile : String; // Adds a new XML node to the doc and tree function AddEmptyNode(Tree : TBaseVirtualTree; Element : PPXMLElement) : PVirtualNode; // Generates a list of PPXMLElements from the schema file procedure GetElementNames(Node : IXMLNode; ParentElement : PPXMLElement; RootElement : PPXMLElement); end; // --- Panels ------------------------------------------------------------------ EUnknownPanelType = class (Exception); TItemPanel = class(TCustomPanel) Attr : IXMLNode; Node : IXMLNode; public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); reintroduce; virtual; destructor Free; virtual; abstract; procedure SetOptional(const Optional : Boolean); virtual; abstract; procedure SetTypeData(const Arguments : TStrings); virtual; abstract; procedure UpdateData; virtual; abstract; end; TStringItemPanel = class (TItemPanel) lblKey: TLabel; edtValue: TEdit; chars: TStringList; public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); override; destructor Free; override; procedure SetOptional(const Optional : Boolean); override; procedure SetTypeData(const Arguments : TStrings); override; procedure UpdateData; override; private procedure GenericKeyPress(Sender: TObject; var Key: Char); end; TSetItemPanel = class (TItemPanel) lblKey: TLabel; cobValue: TComboBox; public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); override; destructor Free; override; procedure SetOptional(const Optional : Boolean); override; procedure SetTypeData(const Arguments : TStrings); override; procedure UpdateData; override; end; TBooleanItemPanel = class (TItemPanel) cbxValue: TCheckBox; public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); override; destructor Free; override; procedure SetOptional(const Optional : Boolean); override; procedure SetTypeData(const Arguments : TStrings); override; procedure UpdateData; override; end; TCategoryItemPanel = class (TSetItemPanel) public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); override; function GetCategory() : String; end; TSubcategoryItemPanel = class (TSetItemPanel) public constructor Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode; Category : String); reintroduce; end; const NO_DESCRIPTION_LINE : String = 'no description available for this element'; DATA_MISSING_STR : String = '--INSERT DATA HERE-'; DELIMITER_STR : String = ','; OPTIONAL_COLOR : TColor = clGrayText; REQUIRED_COLOR : TColor = clWindowText; SCHEMA_ATTRIBUTES : Array [0..2] of String = ('elemdesc','min','max'); ROOT_ELEMENT_NAMES : Array [0..2] of String = ('package','application','category'); FULL_TEXT_ELEMENT : String = 'description'; // hard-coded until better implemented in schema MAX_DEFAULT_VALUE : Integer = 1; MIN_DEFAULT_VALUE : Integer = 1; NEW_DEFAULT_FILE : String = 'tools\PXML_default.xml'; CATEGORIES_FILE : String = 'tools\Categories.txt'; var frmPXML: TfrmPXML; Doc : TXMLDocument; Schema : TXMLDocument; CurrentPanels : Array of TItemPanel; PXMLElements : Array of PPXMLElement; CurrentNode : PVirtualNode; IsExistingFile : Boolean; Successful : Boolean; InputFilter : TInputFilters; implementation uses {$Ifdef Win32}ControlHideFix,{$Endif} MainForm, FormatUtils, Math; {$R *.dfm} // DONE: Parse scheme file or some custom file to check for elements without text attribute // TODO: Validate PXML (using scheme) - check for files (binary, icons, pics) // DONE: Functionality to add and remove elements // DONE: Parse external file for descriptions // DONE: Validate strings using regex or something like that // DONE: Custom ItemPanel classes for special fields (dropDown, etc.) // DONE: Add info about multiple elements of the same kind to scheme and loading functionality here // TODO: Context-sensitive context menu for adding elements // DONE: Fill element dropDown (preferrebly from schema file) // TODO: Panel type for paths (tricky to do as relative from PND) // DONE: Panel type for category and sub-category // DONE: Select added element // DONE: Get correct application element by selection in browser // DONE: Hotkey for deleting elements from the list // --- Functions --------------------------------------------------------------- procedure TfrmPXML.AddDataToTree(Tree : TBaseVirtualTree; Data: IXMLNode; Node: PVirtualNode); var I : Integer; PData : PXMLTreeData; begin if (Node <> nil) then begin PData := Tree.GetNodeData(Node); PData.Node := Data; end; for I := 0 to Data.ChildNodes.Count - 1 do begin if not (Data.ChildNodes[I].NodeType in [ntText,ntComment]) then AddDataToTree(Tree,Data.ChildNodes[I],Tree.AddChild(Node)); end; end; procedure TfrmPXML.Clear; var I : Integer; begin Doc.Free; Schema.Free; Doc := nil; Schema := nil; CurrentNode := nil; vstPXML.Clear; for I := 0 to bugElements.Items.Count - 1 do bugElements.Items[0].Free; bugElements.Items.Clear; for I := 0 to High(PXMLElements) do Dispose(PXMLElements[I]); Finalize(PXMLElements); ResetPanels; end; function TfrmPXML.LoadFromFile(const FileName : String) : Boolean; begin Clear; Doc := TXMLDocument.Create(frmPXML); Doc.Options := [doNodeAutoIndent]; Doc.LoadFromFile(FileName); Schema := TXMLDocument.Create(frmPXML); if Length(ExtractFileDrive(frmMain.Settings.SchemaFile)) > 0 then // full path Schema.LoadFromFile(frmMain.Settings.SchemaFile) else Schema.LoadFromFile(ExtractFilePath(Application.ExeName) + frmMain.Settings.SchemaFile); GetElementNames(Schema.DocumentElement,nil,nil); AddDataToTree(vstPXML,Doc.DocumentElement,nil); vstPXML.FullExpand(); ShowElementButtons; IsExistingFile := true; ShowModal; Result := Successful; end; function TfrmPXML.CreateNewFile : String; begin Clear; Doc := TXMLDocument.Create(frmPXML); Doc.Options := [doNodeAutoIndent]; Doc.LoadFromFile(ExtractFilePath(Application.ExeName) + NEW_DEFAULT_FILE); Schema := TXMLDocument.Create(frmPXML); if Length(ExtractFileDrive(frmMain.Settings.SchemaFile)) > 0 then // full path Schema.LoadFromFile(frmMain.Settings.SchemaFile) else Schema.LoadFromFile(ExtractFilePath(Application.ExeName) + frmMain.Settings.SchemaFile); GetElementNames(Schema.DocumentElement,nil,nil); AddDataToTree(vstPXML,Doc.DocumentElement,nil); vstPXML.FullExpand(); ShowElementButtons; IsExistingFile := false; ShowModal; if Successful then Result := sadPXML.FileName else Result := ''; end; procedure TfrmPXML.UpdateXMLData; var I : Integer; PData : PXMLTreeData; begin if CurrentNode = nil then Exit; for I := 0 to High(CurrentPanels) do begin CurrentPanels[I].UpdateData; end; PData := vstPXML.GetNodeData(CurrentNode); if PData.Node.IsTextElement then begin if pnlValue.Visible then begin if Length(edtValue.Text) = 0 then edtValue.Text := DATA_MISSING_STR; PData.Node.NodeValue := edtValue.Text; end else begin if memValue.Lines.Count = 0 then memValue.Lines.Add(DATA_MISSING_STR); PData.Node.NodeValue := memValue.Lines.Text; end; end; end; procedure TfrmPXML.ResetPanels; var I : Integer; begin for I := High(CurrentPanels) downto 0 do begin try CurrentPanels[I].Free; finally SetLength(CurrentPanels,High(CurrentPanels)); end; end; lblNoValue.Visible := true; lblNoAttr.Visible := true; pnlValue.Visible := false; pnlValueText.Visible := false; redDescription.Clear; redDescription.Lines.Add(NO_DESCRIPTION_LINE); end; procedure TfrmPXML.AddPanels(Data: PXMLTreeData); var temp : String; I,K : Integer; SchemaNode, AttrNode, SchAttrNode : IXMLNode; List : TStrings; Found : Boolean; PData : PXMLTreeData; begin if Data = nil then Exit; if (Data.Node.IsTextElement) OR (Data.Node.NodeType = ntComment) then begin try // fails on nodes without data temp := Data.Node.Text; if Data.Node.NodeName = FULL_TEXT_ELEMENT then begin memValue.Lines.Text := temp; pnlValueText.Visible := true; end else begin edtValue.Text := temp; pnlValue.Visible := true; end; lblNoValue.Visible := false; except // suppress error end; end; // get root parent node of selected node (application or package, childs of PXML node) SchemaNode := Data.Node; while SchemaNode.ParentNode.NodeName <> Schema.DocumentElement.NodeName do begin SchemaNode := SchemaNode.ParentNode; end; // get the equivalent of the selected node from the schema file SchemaNode := FindNode(Data.Node.NodeName,FindNode(SchemaNode.NodeName,Schema.DocumentElement)); // not found if SchemaNode = nil then begin frmMain.LogLine('Node not found in schema file (caused either by an ' + 'outdated schema or invalid PXML file)',frmMain.LOG_WARNING_COLOR); // display all found attributes (as default string panels) for I := 0 to Data.Node.AttributeNodes.Count - 1 do begin lblNoAttr.Visible := false; AttrNode := Data.Node.AttributeNodes.Get(I); SetLength(CurrentPanels,Length(CurrentPanels)+1); CurrentPanels[High(CurrentPanels)] := TStringItemPanel.Create(scbValues,AttrNode,Data.Node); end; Exit; end; // schema node was found List := TStringList.Create; for I := 0 to SchemaNode.AttributeNodes.Count - 1 do begin List.Clear; SchAttrNode := SchemaNode.AttributeNodes.Get(I); Found := false; for K := 0 to High(SCHEMA_ATTRIBUTES) do // check for special schema attributes begin if SchAttrNode.NodeName = SCHEMA_ATTRIBUTES[K] then begin if K = 0 then // elemdesc begin temp := ExtractFilePath(Application.ExeName) + SchAttrNode.Text; if FileExists(temp) then begin redDescription.Clear; redDescription.Lines.LoadFromFile(temp); end; end; Found := true; Break; end; end; if not Found then // any regular attribute begin // check whether already present (either load or clone from scheme) AttrNode := Data.Node.AttributeNodes.FindNode(SchAttrNode.NodeName); if AttrNode = nil then begin AttrNode := SchAttrNode.CloneNode(true); AttrNode.Text := ''; Data.Node.AttributeNodes.Add(AttrNode); end; // now attribute is guaranteed to be present Tokenize(SchAttrNode.Text,DELIMITER_STR,List); // check for errors - add default panel SetLength(CurrentPanels,Length(CurrentPanels)+1); CurrentPanels[High(CurrentPanels)] := nil; if List.Count < 2 then begin CurrentPanels[High(CurrentPanels)] := TStringItemPanel.Create(scbValues,AttrNode,Data.Node); Continue; end; // add panel for it try // create panel by type temp := List.Strings[1]; if temp = 'string' then CurrentPanels[High(CurrentPanels)] := TStringItemPanel.Create(scbValues,AttrNode,Data.Node) else if temp = 'set' then CurrentPanels[High(CurrentPanels)] := TSetItemPanel.Create(scbValues,AttrNode,Data.Node) else if temp = 'boolean' then CurrentPanels[High(CurrentPanels)] := TBooleanItemPanel.Create(scbValues,AttrNode,Data.Node) else if temp = 'category' then CurrentPanels[High(CurrentPanels)] := TCategoryItemPanel.Create(scbValues,AttrNode,Data.Node) else if temp = 'subcategory' then begin PData := vstPXML.GetNodeData(vstPXML.GetFirstSelected().Parent); for K := 0 to PData.Node.AttributeNodes.Count - 1 do begin if PData.Node.AttributeNodes.Get(K).NodeName = 'name' then begin try temp := PData.Node.AttributeNodes.Get(K).NodeValue; except temp := ''; end; CurrentPanels[High(CurrentPanels)] := TSubcategoryItemPanel.Create(scbValues,AttrNode,Data.Node,temp); Break; end; end; if CurrentPanels[High(CurrentPanels)] = nil then begin CurrentPanels[High(CurrentPanels)] := TStringItemPanel.Create(scbValues,AttrNode,Data.Node); Continue; end; end else raise EUnknownPanelType.Create('Unknown attribute type "' + temp + '"'); // set optional flag CurrentPanels[High(CurrentPanels)].SetOptional(List.Strings[0] = 'optional'); if List.Count > 2 then begin List.Delete(0); // optional|required List.Delete(0); // type CurrentPanels[High(CurrentPanels)].SetTypeData(List); end; except on E : EUnknownPanelType do begin MessageDlg(E.Message,mtError,[mbOK],0); SetLength(CurrentPanels,High(CurrentPanels)); end else begin CurrentPanels[High(CurrentPanels)].Free; SetLength(CurrentPanels,High(CurrentPanels)); end; end; end; end; List.Free; if Length(CurrentPanels) > 0 then lblNoAttr.Visible := false; end; function TfrmPXML.FindNode(Tree: TBaseVirtualTree; const S: String; Base: PVirtualNode) : PVirtualNode; var Node : PVirtualNode; PData : PXMLTreeData; begin Node := Base; while Node <> nil do begin PData := Tree.GetNodeData(Node); if SameText(PData.DisplayKey,S) then begin Result := Node; Exit; end; Result := FindNode(Tree,S,Tree.GetFirstChild(Node)); if Result <> nil then Exit; Node := Tree.GetNextSibling(Node); end; Result := nil; end; function TfrmPXML.FindSelectedNode(Tree: TBaseVirtualTree; const S: String) : PVirtualNode; var Node : PVirtualNode; PData : PXMLTreeData; begin Result := nil; Node := Tree.GetFirstSelected(); while Node <> nil do begin PData := Tree.GetNodeData(Node); if (PData <> nil) AND SameText(PData.DisplayKey,S) then begin Result := Node; Exit; end; Node := Node.Parent; end; end; function TfrmPXML.FindNode(const S: string; Node: IXMLNode) : IXMLNode; var I : Integer; begin Result := nil; try if SameText(Node.NodeName,S) then begin Result := Node; Exit; end; except // end; for I := 0 to Node.ChildNodes.Count - 1 do begin if Node.ChildNodes[I].NodeType <> ntText then Result := FindNode(S,Node.ChildNodes[I]); if Result <> nil then Exit; end; end; function TfrmPXML.CountNodes(Tree : TBaseVirtualTree; const S : String; Base : PVirtualNode) : Integer; var Node : PVirtualNode; PData : PXMLTreeData; begin Result := 0; Node := Base; while Node <> nil do begin PData := Tree.GetNodeData(Node); if SameText(PData.DisplayKey,S) then Inc(Result); Inc(Result,CountNodes(Tree,S,Tree.GetFirstChild(Node))); Node := Tree.GetNextSibling(Node); end; end; function TfrmPXML.AddEmptyNode(Tree : TBaseVirtualTree; Element : PPXMLElement) : PVirtualNode; // Copies a node from the schema to the active XML Doc, stripping all schema // attributes and data (essentially creating a blank node) function CreateNode(Tree : TBaseVirtualTree; const CopyData : PPXMLElement; const ParentTreeNode : PVirtualNode) : PVirtualNode; var PData, PData2 : PXMLTreeData; temp : IXMLNode; I,K : Integer; begin Result := Tree.AddChild(ParentTreeNode); PData := Tree.GetNodeData(Result); PData.Node := CopyData.XNode.CloneNode(false); PData.SchemaLink := CopyData; if ParentTreeNode = nil then begin Doc.DocumentElement.ChildNodes.Add(PData.Node); end else begin PData2 := Tree.GetNodeData(ParentTreeNode); PData2.Node.ChildNodes.Add(PData.Node); end; // strip schema data attributes from node I := 0; while I < PData.Node.AttributeNodes.Count do begin PData.Node.AttributeNodes[I].Text := ''; for K := 0 to High(SCHEMA_ATTRIBUTES) do begin if PData.Node.AttributeNodes[I].NodeName = SCHEMA_ATTRIBUTES[K] then begin PData.Node.AttributeNodes.Delete(I); Dec(I); Break; end; end; Inc(I); end; // add value node (which did not get copied) - if present in archetype for I := 0 to CopyData.XNode.ChildNodes.Count - 1 do begin if CopyData.XNode.ChildNodes[I].NodeType = ntText then begin temp := CopyData.XNode.ChildNodes[I].CloneNode(true); temp.NodeValue := ''; PData.Node.ChildNodes.Add(temp); end; end; end; var ParentNode, RootParentNode : PVirtualNode; XNode, XRootParentNode : IXMLNode; I : Integer; begin Result := nil; // get package or application element if Element.Root <> nil then begin XRootParentNode := Element.Root.XNode; RootParentNode := FindSelectedNode(Tree,Element.Root.Tag); if RootParentNode = nil then begin RootParentNode := FindNode(Tree,Element.Root.Tag,Tree.GetFirst()); if RootParentNode = nil then RootParentNode := AddEmptyNode(Tree,Element.Root); end; end else begin XRootParentNode := Schema.DocumentElement; RootParentNode := nil; end; // get archetype node from scheme XNode := Element.XNode; // check whether parents exist in tree and create it if (XNode.ParentNode <> XRootParentNode) AND (XNode.ParentNode <> Schema.DocumentElement) then ParentNode := AddEmptyNode(Tree,Element.Parent) else ParentNode := RootParentNode; // check whether node already exists or may exist multiple times Result := FindNode(Tree,Element.Tag,Tree.GetFirstChild(ParentNode)); if Result <> nil then begin for I := 0 to XNode.AttributeNodes.Count - 1 do begin if XNode.AttributeNodes[I].NodeName = SCHEMA_ATTRIBUTES[2] then // max begin if (CountNodes(Tree,Element.Tag,Tree.GetFirstChild(ParentNode)) >= XNode.AttributeNodes[I].NodeValue) AND (XNode.AttributeNodes[I].NodeValue > 0) then Exit else // it's okay, we did not hit the limit yet begin Result := nil; Break; end; end; end; // max attribute not found if (Result <> nil) AND (CountNodes(Tree,Element.Tag,Tree.GetFirstChild(ParentNode)) >= MAX_DEFAULT_VALUE) then Exit; end; // create the actual node (finally!) Result := CreateNode(Tree,Element,ParentNode); end; procedure TfrmPXML.GetElementNames(Node : IXMLNode; ParentElement : PPXMLElement; RootElement : PPXMLElement); var I,K : Integer; temp : PPXMLElement; IsRoot : Boolean; begin for I := 0 to Node.ChildNodes.Count - 1 do begin if not (Node.ChildNodes[I].NodeType in [ntText,ntComment]) then begin New(temp); temp.Tag := Node.ChildNodes[I].NodeName; temp.Root := RootElement; temp.Parent := ParentElement; temp.XNode := Node.ChildNodes[I]; if RootElement <> nil then temp.Display := Node.ChildNodes[I].NodeName + ' (' + RootElement.Tag + ')' else temp.Display := Node.ChildNodes[I].NodeName; SetLength(PXMLElements,Length(PXMLElements)+1); PXMLElements[High(PXMLElements)] := temp; IsRoot := false; for K := 0 to High(ROOT_ELEMENT_NAMES) do if temp.Tag = ROOT_ELEMENT_NAMES[K] then IsRoot := true; if IsRoot then GetElementNames(Node.ChildNodes[I],temp,temp) else GetElementNames(Node.ChildNodes[I],temp,RootElement) end; end; end; procedure TfrmPXML.ShowElementButtons; var I : Integer; temp : TXMLGrpButtonItem; S : String; PData : PXMLTreeData; Node : PVirtualNode; begin for I := 0 to bugElements.Items.Count - 1 do bugElements.Items[0].Free; bugElements.Items.Clear; // determine what buttons to show S := ''; if rabSelection.Checked then begin Node := vstPXML.GetFirstSelected(); if Node = nil then Node := vstPXML.GetFirst(); if Node = nil then // this should never happen (and probably won't) Exit; PData := vstPXML.GetNodeData(Node); // check whether element can have child elements (aka there are elements with this as parent) for I := 0 to High(PXMLElements) do if (PXMLElements[I].Parent <> nil) AND (PXMLElements[I].Parent.Tag = PData.DisplayKey) then begin S := PData.DisplayKey; Break; end; // else use parent element if Length(S) = 0 then begin Node := Node.Parent; PData := vstPXML.GetNodeData(Node); S := PData.DisplayKey; end; end else if rabPackage.Checked then S := 'package' else if rabApplication.Checked then S := 'application'; for I := 0 to High(PXMLElements) do begin if ((Length(S) = 0) OR (PXMLElements[I].Parent = nil) OR (PXMLElements[I].Parent.Tag = S)) then begin temp := TXMLGrpButtonItem.Create(bugElements.Items); temp.Caption := PXMLElements[I].Tag; temp.Data := PXMLElements[I]; end; end; end; // --- Tree -------------------------------------------------------------------- procedure TfrmPXML.vstPXMLChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin UpdateXMLData; ResetPanels; CurrentNode := Sender.GetFirstSelected(); AddPanels(Sender.GetNodeData(CurrentNode)); if rabSelection.Checked then ShowElementButtons; end; procedure TfrmPXML.vstPXMLGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var PData : PXMLTreeData; begin PData := vstPXML.GetNodeData(Node); case Column of 0 : CellText := PData.DisplayKey; end; end; procedure TfrmPXML.vstPXMLInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var PData : PXMLTreeData; XNode : IXMLNode; I : Integer; begin PData := Sender.GetNodeData(Node); PData.DisplayKey := PData.Node.NodeName; XNode := PData.Node; while XNode.ParentNode <> Doc.DocumentElement do XNode := XNode.ParentNode; for I := 0 to High(PXMLElements) do if (PXMLElements[I].Tag = PData.DisplayKey) AND ((PXMLElements[I].Root = nil) OR (PXMLElements[I].Root.Tag = XNode.NodeName)) then PData.SchemaLink := PXMLElements[I]; end; procedure TfrmPXML.vstPXMLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ((vstPXML.Focused) AND (Key = 46) AND (vstPXML.GetFirstSelected() <> nil)) then pomPXMLDeleteClick(Sender); end; procedure TfrmPXML.vstPXMLMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Node : PVirtualNode; begin if Button = mbRight then begin Node := (Sender as TBaseVirtualTree).GetNodeAt(X,Y); if Node <> nil then begin (Sender as TBaseVirtualTree).ClearSelection; (Sender as TBaseVirtualTree).Selected[Node] := true; pomPXML.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y); end; end; end; // --- Buttons ----------------------------------------------------------------- procedure TfrmPXML.btnCancelClick(Sender: TObject); begin Successful := false; Close; end; procedure TfrmPXML.btnOKClick(Sender: TObject); begin UpdateXMLData; ResetPanels; Successful := true; if IsExistingFile then begin Doc.SaveToFile(Doc.FileName); Close; end else begin if sadPXML.Execute then begin Doc.SaveToFile(sadPXML.FileName); Close; end; end; end; procedure TfrmPXML.bugElementsButtonClicked(Sender: TObject; Index: Integer); var temp : PPXMLElement; begin temp := (bugElements.Items[Index] as TXMLGrpButtonItem).Data; vstPXML.Selected[AddEmptyNode(vstPXML,temp)] := true; end; // --- Context Menu ------------------------------------------------------------ procedure TfrmPXML.pomPXMLDeleteClick(Sender: TObject); var Node : PVirtualNode; PData : PXMLTreeData; begin ResetPanels; CurrentNode := nil; Node := vstPXML.GetFirstSelected(); PData := vstPXML.GetNodeData(Node); PData.Node.ParentNode.ChildNodes.Remove(PData.Node); vstPXML.DeleteSelectedNodes; end; procedure TfrmPXML.rabSelectionClick(Sender: TObject); begin ShowElementButtons; end; // --- Form -------------------------------------------------------------------- procedure TfrmPXML.FormClose(Sender: TObject; var Action: TCloseAction); begin ResetPanels; Clear; end; procedure TfrmPXML.FormCreate(Sender: TObject); var dummy : TButtonEvent; begin vstPXML.NodeDataSize := SizeOf(rXMLTreeData); CurrentNode := nil; Doc := nil; Schema := nil; {$Ifdef Win32} KeyPreview := true; dummy := TButtonEvent.Create; OnKeyDown := dummy.KeyDown; dummy.Free; {$Endif} SetLength(TrueBoolStrs,2); TrueBoolStrs[0] := 'true'; TrueBoolStrs[1] := '1'; SetLength(FalseBoolStrs,2); FalseBoolStrs[0] := 'false'; FalseBoolStrs[1] := '0'; end; procedure TfrmPXML.FormShow(Sender: TObject); begin if not IsExistingFile then MessageDlg('The necessary structure for a valid PXML file will be auto-generated.'#13#10 + 'You must enter valid data to all those nodes (execpt where optional).'#13#10 + 'It is also recommended you add optional data such as an icon to make your PND'#13#10 + 'more recognizable. You can do so with the buttons at the bottom of the window.'#13#10 + 'Click on nodes in the structure on the left to show input fields to their values.'#13#10 + 'Don''t forget to update mandatory package information, such as id and name, on'#13#10 + 'the application and package tags!', mtInformation,[mbOK],0); end; // --- TItemPanel -------------------------------------------------------------- constructor TItemPanel.Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); begin inherited Create(NewParent); Parent := NewParent; Align := alTop; AlignWithMargins := true; Height := 21; Top := frmPXML.lblDescription.Top - Height; BevelOuter := bvNone; Caption := ''; Attr := AttrNode; Node := ParentNode; end; // --- TStringItemPanel -------------------------------------------------------- constructor TStringItemPanel.Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); begin inherited Create(NewParent,AttrNode,ParentNode); chars := nil; lblKey := TLabel.Create(self); with lblKey do begin Caption := Attr.NodeName + '='; Align := alLeft; Left := 0; Parent := self; AlignWithMargins := true; with Margins do begin Left := 4; Right := 4; Top := 3; Bottom := 0; end; end; edtValue := TEdit.Create(self); with edtValue do begin Align := alClient; Parent := self; Text := Attr.Text; end; end; destructor TStringItemPanel.Free; begin if Length(edtValue.Text) = 0 then Node.AttributeNodes.Delete(Attr.NodeName); lblKey.Free; edtValue.Free; chars.Free; inherited Destroy; end; procedure TStringItemPanel.SetOptional(const Optional: Boolean); begin if Optional then lblKey.Font.Color := OPTIONAL_COLOR else lblKey.Font.Color := REQUIRED_COLOR; end; procedure TStringItemPanel.SetTypeData(const Arguments: TStrings); var temp : String; I : Integer; begin temp := Arguments.Strings[0]; if temp = 'version' then edtValue.OnKeyPress := InputFilter.VersionKeyPress else if temp = 'email' then edtValue.OnKeyPress := InputFilter.EmailKeyPress else if temp = 'folder' then edtValue.OnKeyPress := InputFilter.FolderKeyPress else if temp = 'language' then edtValue.OnKeyPress := InputFilter.LanguageKeyPress else if temp = 'mime' then edtValue.OnKeyPress := InputFilter.MimeKeyPress else if temp = 'integer' then edtValue.OnKeyPress := InputFilter.IntegerKeyPress else if temp = 'id' then edtValue.OnKeyPress := InputFilter.IDKeyPress else begin chars := TStringList.Create; for I := 0 to Arguments.Count - 1 do if Length(Arguments.Strings[I]) = 1 then // only add single chars chars.Add(Arguments.Strings[I]); if chars.Count > 0 then edtValue.OnKeyPress := GenericKeyPress else begin chars.Free; chars := nil; end; end; end; procedure TStringItemPanel.UpdateData; begin Attr.NodeValue := edtValue.Text; end; procedure TStringItemPanel.GenericKeyPress(Sender: TObject; var Key: Char); begin if (Key = #8) OR (chars.IndexOf(Key) = -1) then InputFilter.DisregardKey(Key); end; // --- TBooleanItemPanel ------------------------------------------------------- constructor TBooleanItemPanel.Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); begin inherited Create(NewParent,AttrNode,ParentNode); cbxValue := TCheckBox.Create(self); with cbxValue do begin Caption := Attr.NodeName; Align := alClient; Left := 0; Parent := self; AlignWithMargins := true; with Margins do begin Left := 4; Right := 4; Top := 3; Bottom := 0; end; AllowGrayed := true; try Checked := StrToBool(Attr.Text); except // value faulty or not present State := cbGrayed; end; end; end; destructor TBooleanItemPanel.Free; begin if cbxValue.State = cbGrayed then Node.AttributeNodes.Delete(Attr.NodeName); cbxValue.Free; inherited Destroy; end; procedure TBooleanItemPanel.SetOptional(const Optional: Boolean); begin // Changing the colour of the text is not supported on newer versions of Windows if Optional then cbxValue.Caption := cbxValue.Caption + ' (optional)'; end; procedure TBooleanItemPanel.SetTypeData(const Arguments: TStrings); begin // no arguments taken end; procedure TBooleanItemPanel.UpdateData; begin Attr.NodeValue := BoolToStr(cbxValue.Checked,true); end; // --- TSetItemPanel ----------------------------------------------------------- constructor TSetItemPanel.Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode); begin inherited Create(NewParent,AttrNode,ParentNode); lblKey := TLabel.Create(self); with lblKey do begin Caption := Attr.NodeName + '='; Align := alLeft; Left := 0; Parent := self; AlignWithMargins := true; with Margins do begin Left := 4; Right := 4; Top := 3; Bottom := 0; end; end; cobValue := TComboBox.Create(self); with cobValue do begin Align := alClient; Parent := self; Text := Attr.Text; end; end; destructor TSetItemPanel.Free; begin if Length(cobValue.Text) = 0 then Node.AttributeNodes.Delete(Attr.NodeName); lblKey.Free; cobValue.Free; inherited Destroy; end; procedure TSetItemPanel.SetOptional(const Optional: Boolean); begin if Optional then lblKey.Font.Color := OPTIONAL_COLOR else lblKey.Font.Color := REQUIRED_COLOR; end; procedure TSetItemPanel.SetTypeData(const Arguments: TStrings); begin cobValue.Items.AddStrings(Arguments); end; procedure TSetItemPanel.UpdateData; begin Attr.NodeValue := cobValue.Text; end; // --- TCategoryItemPanel ------------------------------------------------------ constructor TCategoryItemPanel.Create(NewParent: TWinControl; AttrNode: IXMLNode; ParentNode: IXMLNode); var F : TextFile; S : String; begin inherited Create(NewParent,AttrNode,ParentNode); try AssignFile(F,ExtractFilePath(Application.ExeName) + CATEGORIES_FILE); Reset(F); while not EOF(F) do begin ReadLn(F,S); cobValue.Items.Add(S); ReadLn(F,S); // Skip sub-categories end; finally CloseFile(F); end; end; function TCategoryItemPanel.GetCategory : String; begin Result := cobValue.Text; end; // --- TSubcategoryItemPanel --------------------------------------------------- constructor TSubcategoryItemPanel.Create(NewParent : TWinControl; AttrNode, ParentNode : IXMLNode; Category : String); var F : TextFile; S : String; L : TStrings; begin inherited Create(NewParent,AttrNode,ParentNode); try AssignFile(F,ExtractFilePath(Application.ExeName) + CATEGORIES_FILE); Reset(F); while not EOF(F) do begin ReadLn(F,S); if S = Category then begin ReadLn(F,S); L := TStringList.Create; L.Delimiter := '|'; L.DelimitedText := S; cobValue.Items.AddStrings(L); Break; end; end; finally CloseFile(F); end; end; end.
unit MainFrm; {$mode objfpc}{$H+} interface uses Classes, sysutils, Forms, Controls, ComCtrls, ExtCtrls, StdCtrls, ActnList, Buttons, audioplayer; type { TfrmMain } TfrmMain = class(TForm) actAudio: TAction; actVideo: TAction; actMetrics: TAction; actNav: TAction; alMain: TActionList; btnAudio: TButton; btnVideo: TButton; btnNav: TButton; btnMetrics: TButton; ilMain: TImageList; Label1: TLabel; ListView1: TListView; pcMain: TPageControl; panMain: TPanel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; tsMetrics: TTabSheet; tsVideo: TTabSheet; tsNav: TTabSheet; tsAudio: TTabSheet; procedure actAudioExecute(Sender: TObject); procedure actMetricsExecute(Sender: TObject); procedure actNavUpdate(Sender: TObject); procedure actVideoUpdate(Sender: TObject); procedure FormShow(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); private { private declarations } public { public declarations } end; var frmMain: TfrmMain; AudioPlr: TAudioPlayer; implementation {$R *.lfm} { TfrmMain } procedure TfrmMain.actAudioExecute(Sender: TObject); begin pcMain.ActivePage := tsAudio; end; procedure TfrmMain.actMetricsExecute(Sender: TObject); begin pcmain.ActivePage := tsMetrics; end; procedure TfrmMain.actNavUpdate(Sender: TObject); begin actNav.Visible := False; end; procedure TfrmMain.actVideoUpdate(Sender: TObject); begin actVideo.Visible := False; end; procedure TfrmMain.FormShow(Sender: TObject); begin //if not Assigned(AudioPlr) then //AudioPlr := TAudioPlayer.Create(self); end; procedure TfrmMain.SpeedButton3Click(Sender: TObject); begin Label1.Caption := IntToStr(StrToInt(Label1.Caption) + 1); end; end.
unit URegraCRUDCidade; interface uses URegraCRUD ,URepositorioDB ,URepositorioCidade ,UEntidade ,UCidade ,UEstado ; type TRegraCRUDCidade = class (TRegraCRUD) private procedure ValidaEstado(const coESTADO: TESTADO); protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; public constructor Create ; override ; end; implementation uses SysUtils , UUtilitarios , UMensagens , UConstantes ; { TRegraCRUDCidade } constructor TRegraCRUDCidade.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioCidade.Create); end; procedure TRegraCRUDCidade.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin with TCIDADE(coENTIDADE) do begin ValidaEstado(ESTADO); end; end; procedure TRegraCRUDCidade.ValidaEstado(const coESTADO: TESTADO); begin if (coESTADO = nil) or (coESTADO.ID = 0) then raise EValidacaoNegocio.Create(STR_CIDADE_ESTADO_NAO_INFORMADO); end; procedure TRegraCRUDCidade.ValidaInsercao(const coENTIDADE: TENTIDADE); var coCidade : TCIDADE; begin inherited; coCidade := TCIDADE(coENTIDADE); if Trim(coCidade.NOME) = EmptyStr Then raise EValidacaoNegocio.Create(STR_CIDADE_NOME_NAO_INFORMADO); ValidaEstado(coCidade.ESTADO); end; end.
{******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de AIDF e AIMDF The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (alberteije@gmail.com) @version 2.0 *******************************************************************************} unit UAidfAimdf; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, AidfAimdfVO, AidfAimdfController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvExStdCtrls, JvEdit, JvValidateEdit, JvBaseEdits, Math, StrUtils, Controller; type [TFormDescription(TConstantes.MODULO_CONTABILIDADE, 'Aidf Aimdf')] TFAidfAimdf = class(TFTelaCadastro) BevelEdits: TBevel; EditNumeroAutorizacao: TLabeledEdit; EditDataAutorizacao: TLabeledDateEdit; EditDataValidade: TLabeledDateEdit; ComboBoxFormularioDisponivel: TLabeledComboBox; EditNumero: TLabeledCalcEdit; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; procedure ControlaBotoes; override; procedure ControlaPopupMenu; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FAidfAimdf: TFAidfAimdf; implementation uses ULookup, Biblioteca, UDataModule; {$R *.dfm} {$REGION 'Controles Infra'} procedure TFAidfAimdf.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TAidfAimdfVO; ObjetoController := TAidfAimdfController.Create; inherited; end; procedure TFAidfAimdf.ControlaBotoes; begin inherited; BotaoImprimir.Visible := False; end; procedure TFAidfAimdf.ControlaPopupMenu; begin inherited; MenuImprimir.Visible := False; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFAidfAimdf.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditNumero.SetFocus; end; end; function TFAidfAimdf.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditNumero.SetFocus; end; end; function TFAidfAimdf.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('AidfAimdfController.TAidfAimdfController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('AidfAimdfController.TAidfAimdfController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFAidfAimdf.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try ObjetoVO := TAidfAimdfVO.Create; TAidfAimdfVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TAidfAimdfVO(ObjetoVO).Numero := EditNumero.AsInteger; TAidfAimdfVO(ObjetoVO).DataAutorizacao := EditDataAutorizacao.Date; TAidfAimdfVO(ObjetoVO).DataValidade := EditDataValidade.Date; TAidfAimdfVO(ObjetoVO).NumeroAutorizacao := EditNumeroAutorizacao.Text; TAidfAimdfVO(ObjetoVO).FormularioDisponivel := IfThen(ComboBoxFormularioDisponivel.ItemIndex = 0, 'S', 'N'); if StatusTela = stInserindo then begin TController.ExecutarMetodo('AidfAimdfController.TAidfAimdfController', 'Insere', [TAidfAimdfVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TAidfAimdfVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('AidfAimdfController.TAidfAimdfController', 'Altera', [TAidfAimdfVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFAidfAimdf.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TAidfAimdfVO(TController.BuscarObjeto('AidfAimdfController.TAidfAimdfController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditNumero.Text := IntToStr(TAidfAimdfVO(ObjetoVO).Numero); EditDataAutorizacao.Date := TAidfAimdfVO(ObjetoVO).DataAutorizacao; EditDataValidade.Date := TAidfAimdfVO(ObjetoVO).DataValidade; EditNumeroAutorizacao.Text := TAidfAimdfVO(ObjetoVO).NumeroAutorizacao; ComboBoxFormularioDisponivel.ItemIndex := AnsiIndexStr(TAidfAimdfVO(ObjetoVO).FormularioDisponivel, ['S', 'N']); // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit stringutils; // This unit is intended to be a drop-in replacement for the ropes // unit, but using straight strings instead of ropes interface //{$DEFINE TESTS} uses unicode, utf8, genericutils; type TUTF8StringPointer = record private {$IFOPT C+} FData: PUTF8String; {$ENDIF} FIndex: Cardinal; FLength: TZeroableUTF8SequenceLength; public {$IFOPT C+} function IsZeroWidth(): Boolean; {$ENDIF} {$IFOPT C+} function IsEOF(): Boolean; {$ENDIF} {$IFOPT C+} function GetByte(): Byte; {$ENDIF} {$IFOPT C+} procedure AssertIdentity(const Data: PUTF8String); {$ENDIF} procedure AdvanceToAfter(); inline; // changes to a zero-width pointer; only valid if FLength > 0 procedure AdvanceToAfter(const Character: TUnicodeCodepoint); inline; // changes to a zero-width pointer function AdvanceToNext(constref Data: UTF8String): TUnicodeCodepoint; procedure SetToZeroWidth(); inline; // changes to a zero-width pointer end; operator = (constref Op1, Op2: TUTF8StringPointer): Boolean; operator < (constref Op1, Op2: TUTF8StringPointer): Boolean; operator <= (constref Op1, Op2: TUTF8StringPointer): Boolean; type UTF8StringEnumerator = class private FTarget: PUTF8String; FPosition: Cardinal; FAdvance: TZeroableUTF8SequenceLength; {$IFOPT C+} FDidRead: Boolean; {$ENDIF} function GetCurrent(): TUnicodeCodepoint; inline; function GetAdvance(): TUTF8SequenceLength; inline; public constructor Create(const NewTarget: PUTF8String); {$IFOPT C+} procedure AssertIdentity(const Target: PUTF8String); {$ENDIF} function MoveNext(): Boolean; inline; // you must call this first, and never twice in a row without an intervening call to Current or ReturnToPointer() property Current: TUnicodeCodepoint read GetCurrent; // you must only call this once after each call to MoveNext() or ReturnToPointer() function GetPointer(): TUTF8StringPointer; inline; // you must call this after first calling Current or ReturnToPointer() procedure ReturnToPointer(constref NewPosition: TUTF8StringPointer); // after this call, you must call MoveNext() or GetPointer() property CurrentLength: TUTF8SequenceLength read GetAdvance; // only valid after Current or GetPointer()/ReturnToPointer() function GetCurrentAsUTF8(): UTF8String; inline; // when CurrentLength is valid (note: expensive) function GetRawPointer(): Pointer; inline; // only valid when CurrentLength is valid; do not read more than CurrentLength bytes from this point end; CutUTF8String = record private FValue: UTF8String; function GetIsEmpty(): Boolean; inline; function GetAsString(): UTF8String; inline; public class function CreateFrom(const NewString: TUnicodeCodepointArray): CutUTF8String; static; class function CreateFrom(const NewString: UTF8String): CutUTF8String; static; function GetAsStringSlow(): UTF8String; inline; property IsEmpty: Boolean read GetIsEmpty; property AsString: UTF8String read GetAsString; // destroys self end; UTF8StringHelper = type helper for UTF8String private function GetLength(): Cardinal; inline; function GetIsEmpty(): Boolean; inline; function GetAsString(): UTF8String; public procedure AppendDestructively(var NewString: CutUTF8String); // destroys argument procedure AppendDestructively(var NewString: UTF8String); // destroys argument procedure Append(const NewString: PUTF8String); procedure Append(const NewString: TUnicodeCodepoint); deprecated 'highly inefficient - use a ShortString instead if possible'; procedure Append(const NewString: TUnicodeCodepointArray); procedure Append(const NewData: Pointer; const NewLength: QWord); function Extract(constref NewStart, NewEnd: TUTF8StringPointer): CutUTF8String; // includes NewEnd if it is non-zero-width, excludes otherwise // this does a memory copy into a new string function CountCharacters(constref NewStart, NewEnd: TUTF8StringPointer): Cardinal; // includes NewEnd if it is non-zero-width, excludes otherwise // note: this one is expensive (it iterates over the string, parsing UTF8) procedure InplaceReplace(const Character: TUnicodeCodepoint; var Position: TUTF8StringPointer); // changes Position to a zero-width pointer function GetEnumerator(): UTF8StringEnumerator; inline; // for some reason this doesn't get seen by for-in loops property Length: Cardinal read GetLength; property IsEmpty: Boolean read GetIsEmpty; property AsString: UTF8String read GetAsString; end; operator enumerator (var Value: UTF8String): UTF8StringEnumerator; inline; // needed for for-in loops type UTF8StringUtils = specialize DefaultUtils <UTF8String>; function CodepointArrayToUTF8String(const Value: TUnicodeCodepointArray): UTF8String; // there's no UTF8StringToCodepointArray -- use the enumerator implementation uses sysutils; {$IFOPT C+} function TUTF8StringPointer.IsZeroWidth(): Boolean; begin Result := FLength = 0; end; {$ENDIF} {$IFOPT C+} function TUTF8StringPointer.IsEOF(): Boolean; begin Result := (FLength = 0) and (FIndex = Length(FData^)+1); end; {$ENDIF} {$IFOPT C+} function TUTF8StringPointer.GetByte(): Byte; begin Assert(FIndex > 0); Assert(FLength > 0); Assert(FIndex <= Length(FData^)); Result := Ord(FData^[FIndex]); end; {$ENDIF} {$IFOPT C+} procedure TUTF8StringPointer.AssertIdentity(const Data: PUTF8String); begin Assert(FData = Data); end; {$ENDIF} procedure TUTF8StringPointer.AdvanceToAfter(); begin Assert(FLength <> 0); Inc(FIndex, FLength); FLength := 0; end; procedure TUTF8StringPointer.AdvanceToAfter(const Character: TUnicodeCodepoint); {$IFOPT C+} var CheckedCodepoint: TUnicodeCodepoint; CheckedLength: TUTF8SequenceLength; {$ENDIF} begin {$IFOPT C+} CheckedCodepoint := UTF8ToCodepoint(FData, FIndex, CheckedLength); Assert(CheckedCodepoint = Character); if (FLength > 0) then Assert(CheckedLength = FLength); {$ENDIF} Inc(FIndex, CodepointToUTF8Length(Character)); FLength := 0; end; function TUTF8StringPointer.AdvanceToNext(constref Data: UTF8String): TUnicodeCodepoint; {$IFOPT C+} var CheckedLength: TUTF8SequenceLength; {$ENDIF} begin {$IFOPT C+} Assert(@Data = FData); {$ENDIF} Assert(FLength > 0); {$IFOPT C+} UTF8ToCodepoint(@Data, FIndex, CheckedLength); Assert(CheckedLength = FLength); {$ENDIF} Inc(FIndex, FLength); Assert(FIndex <= Length(Data)); Result := UTF8ToCodepoint(@Data, FIndex, TUTF8SequenceLength(FLength)); Assert(FIndex + FLength - 1 <= Length(Data)); end; procedure TUTF8StringPointer.SetToZeroWidth(); begin Assert(FLength <> 0); FLength := 0; end; operator = (constref Op1, Op2: TUTF8StringPointer): Boolean; begin {$IFOPT C+} Assert(Op1.FData = Op2.FData); {$ENDIF} Result := (Op1.FIndex = Op2.FIndex) and (Op1.FLength = Op2.Flength); end; operator < (constref Op1, Op2: TUTF8StringPointer): Boolean; begin {$IFOPT C+} Assert(Op1.FData = Op2.FData); {$ENDIF} Result := (Op1.FIndex < Op2.FIndex) or ((Op1.FIndex = Op2.FIndex) and (Op1.FLength < Op2.FLength)); end; operator <= (constref Op1, Op2: TUTF8StringPointer): Boolean; begin {$IFOPT C+} Assert(Op1.FData = Op2.FData); {$ENDIF} Result := (Op1.FIndex < Op2.FIndex) or ((Op1.FIndex = Op2.FIndex) and (Op1.FLength <= Op2.FLength)); end; constructor UTF8StringEnumerator.Create(const NewTarget: PUTF8String); begin Assert(Assigned(NewTarget)); FTarget := NewTarget; FPosition := 0; FAdvance := 1; {$IFOPT C+} FDidRead := True; {$ENDIF} end; {$IFOPT C+} procedure UTF8StringEnumerator.AssertIdentity(const Target: PUTF8String); begin Assert(FTarget = Target); end; {$ENDIF} function UTF8StringEnumerator.MoveNext(): Boolean; begin {$IFDEF VERBOSE} Writeln(' - MoveNext()'); {$ENDIF} {$IFOPT C+} Assert(FDidRead); {$ENDIF} Assert(FAdvance > 0); Inc(FPosition, FAdvance); Result := FPosition <= Length(FTarget^); {$IFOPT C+} if (not Result) then FAdvance := High(FAdvance); {$ENDIF} {$IFOPT C+} FDidRead := not Result; {$ENDIF} end; function UTF8StringEnumerator.GetCurrent(): TUnicodeCodepoint; begin {$IFOPT C+} Assert(not FDidRead); {$ENDIF} Assert(FAdvance > 0); Result := UTF8ToCodepoint(FTarget, FPosition, TUTF8SequenceLength(FAdvance)); {$IFOPT C+} FDidRead := True; {$ENDIF} {$IFDEF VERBOSE} Writeln(' - GetCurrent(): ', CodepointToUTF8(Result).AsString); {$ENDIF} end; function UTF8StringEnumerator.GetPointer(): TUTF8StringPointer; begin {$IFDEF VERBOSE} Writeln(' - GetPointer()'); {$ENDIF} {$IFOPT C+} Assert(FDidRead); {$ENDIF} Assert(FPosition > 0); {$IFOPT C+} Result.FData := FTarget; {$ENDIF} Result.FIndex := FPosition; if (FPosition <= Length(FTarget^)) then Result.FLength := FAdvance else Result.FLength := 0; end; procedure UTF8StringEnumerator.ReturnToPointer(constref NewPosition: TUTF8StringPointer); begin {$IFDEF VERBOSE} Writeln(' - ReturnToPointer()'); {$ENDIF} Assert(NewPosition.FIndex > 0); {$IFOPT C+} Assert((not NewPosition.IsZeroWidth()) or (NewPosition.IsEOF())); {$ENDIF} {$IFOPT C+} Assert(NewPosition.FData = FTarget); {$ENDIF} FPosition := NewPosition.FIndex; FAdvance := NewPosition.FLength; // $R- {$IFOPT C+} FDidRead := True; {$ENDIF} end; function UTF8StringEnumerator.GetRawPointer(): Pointer; inline; begin Result := @FTarget^[FPosition]; end; function UTF8StringEnumerator.GetAdvance(): TUTF8SequenceLength; begin Assert(FAdvance > 0); {$IFOPT C+} Assert(FDidRead); {$ENDIF} Result := TUTF8SequenceLength(FAdvance); end; function UTF8StringEnumerator.GetCurrentAsUTF8(): UTF8String; begin Assert(FAdvance > 0); Result := Copy(FTarget^, FPosition, FAdvance); end; class function CutUTF8String.CreateFrom(const NewString: TUnicodeCodepointArray): CutUTF8String; begin Result.FValue := CodepointArrayToUTF8String(NewString); end; class function CutUTF8String.CreateFrom(const NewString: UTF8String): CutUTF8String; begin Result.FValue := NewString; end; function CutUTF8String.GetIsEmpty(): Boolean; begin Result := Length(FValue) = 0; end; function CutUTF8String.GetAsString(): UTF8String; begin Result := FValue; {$IFOPT C+} FValue := ''; {$ENDIF} end; function CutUTF8String.GetAsStringSlow(): UTF8String; begin Result := FValue; end; function UTF8StringHelper.GetLength(): Cardinal; begin Result := System.Length(Self); // $R- end; function UTF8StringHelper.GetIsEmpty(): Boolean; begin Result := Self = ''; end; function UTF8StringHelper.GetAsString(): UTF8String; begin Result := Self; end; procedure UTF8StringHelper.AppendDestructively(var NewString: CutUTF8String); begin Self := Self + NewString.FValue; {$IFOPT C+} NewString.FValue := ''; {$ENDIF} end; procedure UTF8StringHelper.AppendDestructively(var NewString: UTF8String); begin Self := Self + NewString; {$IFOPT C+} NewString := ''; {$ENDIF} end; procedure UTF8StringHelper.Append(const NewString: PUTF8String); begin Self := Self + NewString^; end; procedure UTF8StringHelper.Append(const NewString: TUnicodeCodepoint); begin Self := Self + CodepointToUTF8(NewString); end; procedure UTF8StringHelper.Append(const NewString: TUnicodeCodepointArray); var Index, NewLength, NewOffset: Cardinal; NewStringSegment: TUTF8Sequence; begin Assert(System.Length(NewString) > 0); NewLength := System.Length(Self); // $R- Assert(NewLength < High(NewOffset)); // Length() return an Integer, so this is true NewOffset := NewLength+1; // $R- for Index := Low(NewString) to High(NewString) do // $R- Inc(NewLength, CodepointToUTF8Length(NewString[Index])); SetLength(Self, NewLength); for Index := Low(NewString) to High(NewString) do // $R- begin NewStringSegment := CodepointToUTF8(NewString[Index]); Move(NewStringSegment.Start, Self[NewOffset], NewStringSegment.Length); Inc(NewOffset, NewStringSegment.Length); end; Assert(NewOffset = System.Length(Self)+1); end; procedure UTF8StringHelper.Append(const NewData: Pointer; const NewLength: QWord); var Index: Cardinal; begin Index := System.Length(Self); // $R- if ((NewLength > High(System.Length(Self))) or (NewLength > High(System.Length(Self))-Index)) then raise Exception.Create('too much data'); SetLength(Self, Index+NewLength); Move(NewData^, Self[Index+1], NewLength); // $R- end; function UTF8StringHelper.Extract(constref NewStart, NewEnd: TUTF8StringPointer): CutUTF8String; var EffectiveLength: Integer; begin {$IFOPT C+} Assert(NewStart.FData = @Self); Assert(NewEnd.FData = @Self); {$ENDIF} Assert(NewStart.FIndex <= System.Length(Self)); Assert(NewStart.FIndex > 0); Assert(NewEnd.FIndex + NewEnd.FLength <= System.Length(Self)+1); Assert(NewEnd.FIndex + NewEnd.FLength > 0); Assert(NewStart.FIndex <= NewEnd.FIndex); EffectiveLength := NewEnd.FIndex + NewEnd.FLength - NewStart.FIndex; // $R- Assert(EffectiveLength >= 0); if (EffectiveLength > 0) then Result.FValue := Copy(Self, NewStart.FIndex, EffectiveLength) else Result.FValue := ''; end; function UTF8StringHelper.CountCharacters(constref NewStart, NewEnd: TUTF8StringPointer): Cardinal; var Index, EndIndex: Cardinal; begin Index := NewStart.FIndex; Assert(NewEnd.FIndex + NewEnd.FLength < High(EndIndex)); EndIndex := NewEnd.FIndex + NewEnd.FLength; // $R- Result := 0; while (Index < EndIndex) do begin Inc(Result); Inc(Index, UTF8ToUTF8Length(@Self, Index)); end; Assert(Index = EndIndex); end; procedure UTF8StringHelper.InplaceReplace(const Character: TUnicodeCodepoint; var Position: TUTF8StringPointer); var Value: TUTF8Sequence; begin {$IFOPT C+} Assert(Position.FData = @Self); {$ENDIF} Assert(Position.FIndex <= System.Length(Self)); Assert(Position.FIndex > 0); Value := CodepointToUTF8(Character); Assert(Position.FIndex + Value.Length <= System.Length(Self)); Move(Value.Start, Self[Position.FIndex], Value.Length); Inc(Position.FIndex, Value.Length); Position.FLength := 0; end; function UTF8StringHelper.GetEnumerator(): UTF8StringEnumerator; inline; begin Result := UTF8StringEnumerator.Create(@Self); end; operator enumerator (var Value: UTF8String): UTF8StringEnumerator; inline; begin Result := UTF8StringEnumerator.Create(@Value); end; function CodepointArrayToUTF8String(const Value: TUnicodeCodepointArray): UTF8String; var Index, NewLength, Offset: Cardinal; Character: TUTF8Sequence; begin if (Length(Value) = 0) then begin Result := ''; exit; end; NewLength := 0; for Index := Low(Value) to High(Value) do // $R- Inc(NewLength, CodepointToUTF8Length(Value[Index])); SetLength(Result, NewLength); Offset := 1; for Index := Low(Value) to High(Value) do // $R- begin Character := CodepointToUTF8(Value[Index]); Move(Character.Start, Result[Offset], Character.Length); Inc(Offset, Character.Length); end; end; {$IFDEF DEBUG} procedure TestIterator(); var S: UTF8String; Index: TUnicodeCodepointRange; Position: Cardinal; SubS: TUTF8Sequence; C: TUnicodeCodepoint; begin SetLength(S, ($80 * 1) + (($7FF-$7F) * 2) + ((($FFFF-$7FF) - ($E000-$D800)) * 3) + (($10FFFF - $FFFF) * 4)); Position := 1; for Index := $0 to $D7FF do begin SubS := CodepointToUTF8(Index); Move(SubS.Start, S[Position], SubS.Length); Inc(Position, SubS.Length); end; for Index := $E000 to $10FFFF do begin SubS := CodepointToUTF8(Index); Move(SubS.Start, S[Position], SubS.Length); Inc(Position, SubS.Length); end; Assert(Position = Length(S)+1); Index := -1; for C in S do begin Inc(Index); if (Index = $D800) then Index := $E000; Assert(C = Index, 'Expected U+' + IntToHex(Index, 4) + ' but found U+' + IntToHex(C.Value, 4)); end; Assert(Index = $10FFFF); end; {$ENDIF} initialization {$IFDEF TESTS} TestIterator(); {$ENDIF} end.
unit AsyncIO.Test.Socket; interface procedure RunSocketTest; implementation uses System.SysUtils, System.DateUtils, AsyncIO, AsyncIO.ErrorCodes, AsyncIO.Net.IP, System.Math; procedure TestAddress; var addr4: IPv4Address; addr6: IPv6Address; addr: IPAddress; begin addr4 := IPv4Address.Loopback; addr := addr4; WriteLn('IPv4 loopback: ' + addr); addr6 := IPv6Address.Loopback; addr := addr6; WriteLn('IPv6 loopback: ' + addr); addr := IPAddress('192.168.42.2'); WriteLn('IP address: ' + addr); WriteLn(' is IPv4: ' + BoolToStr(addr.IsIPv4, True)); WriteLn(' is IPv6: ' + BoolToStr(addr.IsIPv6, True)); addr := IPAddress('abcd::1%42'); WriteLn('IP address: ' + addr); WriteLn(' is IPv4: ' + BoolToStr(addr.IsIPv4, True)); WriteLn(' is IPv6: ' + BoolToStr(addr.IsIPv6, True)); WriteLn(' has scope: ' + IntToStr(addr.AsIPv6.ScopeID)); WriteLn; end; procedure TestEndpoint; var endp: IPEndpoint; begin endp := Endpoint(IPAddressFamily.v6, 1234); WriteLn('IPv6 listening endpoint: ' + endp); endp := Endpoint(IPAddress('192.168.42.1'), 9876); WriteLn('IPv4 connection endpoint: ' + endp); endp := Endpoint(IPAddress('1234:abcd::1'), 0); WriteLn('IPv6 connection endpoint: ' + endp); WriteLn; end; procedure TestResolve; var qry: IPResolver.Query; res: IPResolver.Results; ip: IPResolver.Entry; begin qry := Query(IPProtocol.TCPProtocol.v6, 'google.com', '80', [ResolveAllMatching]); res := IPResolver.Resolve(qry); WriteLn('Resolved ' + qry.HostName + ':' + qry.ServiceName + ' as'); for ip in res do begin WriteLn(' ' + ip.Endpoint.Address); end; end; type EchoClient = class private FRequest: string; FRequestData: TBytes; FResponseData: TBytes; FSocket: IPStreamSocket; FStream: AsyncSocketStream; procedure HandleConnect(const ErrorCode: IOErrorCode); procedure HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); procedure HandleWrite(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); public constructor Create(const Service: IOService; const ServerEndpoint: IPEndpoint; const Request: string); end; procedure TestEcho; var qry: IPResolver.Query; res: IPResolver.Results; ip: IPResolver.Entry; ios: IOService; client: EchoClient; r: Int64; begin qry := Query(IPProtocol.TCP.v6, 'localhost', '7', [ResolveAllMatching]); res := IPResolver.Resolve(qry); for ip in res do // TODO - make connect take resolver result set, connect until success break; ios := nil; client := nil; try ios := NewIOService; WriteLn('Connecting to ' + ip.Endpoint); client := EchoClient.Create(ios, ip.Endpoint, 'Hello Internet!'); r := ios.Run; WriteLn; WriteLn('Done'); WriteLn(Format('%d handlers executed', [r])); finally client.Free; end; end; type EchoServer = class private FData: TBytes; FAcceptor: IPAcceptor; FPeerSocket: IPStreamSocket; FStream: AsyncSocketStream; procedure HandleAccept(const ErrorCode: IOErrorCode); procedure HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); procedure HandleWrite(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); public constructor Create(const Service: IOService; const LocalEndpoint: IPEndpoint); end; procedure TestEchoServer; var ip: IPEndpoint; ios: IOService; server: EchoServer; r: Int64; begin ios := nil; server := nil; try ip := Endpoint(IPAddressFamily.v6, 7); ios := NewIOService; WriteLn('Listening on ' + ip); server := EchoServer.Create(ios, ip); r := ios.Run; WriteLn; WriteLn('Done'); WriteLn(Format('%d handlers executed', [r])); finally server.Free; end; end; procedure RunSocketTest; begin // TestAddress; // TestEndpoint; // TestResolve; // TestEcho; TestEchoServer; end; { EchoClient } procedure EchoClient.HandleConnect(const ErrorCode: IOErrorCode); begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); WriteLn('Client connected'); WriteLn('Local endpoint: ' + FSocket.LocalEndpoint); WriteLn('Remote endpoint: ' + FSocket.RemoteEndpoint); WriteLn('Sending echo request'); FRequestData := TEncoding.Unicode.GetBytes(FRequest); // we'll use a socket stream for the actual read/write operations FStream := NewAsyncSocketStream(FSocket); AsyncWrite(FStream, FRequestData, TransferAll(), HandleWrite); end; constructor EchoClient.Create( const Service: IOService; const ServerEndpoint: IPEndpoint; const Request: string); begin inherited Create; FRequest := Request; FSocket := NewTCPSocket(Service); FSocket.AsyncConnect(ServerEndpoint, HandleConnect); end; procedure EchoClient.HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); var s: string; responseMatches: boolean; begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); s := TEncoding.Unicode.GetString(FResponseData, 0, BytesTransferred); WriteLn('Echo reply: "' + s + '"'); // compare request and reply responseMatches := (Length(FRequestData) = Length(FResponseData)) and CompareMem(@FRequestData[0], @FResponseData[0], Length(FRequestData)); if (responseMatches) then WriteLn('Response matches, yay') else WriteLn('RESPONSE DOES NOT MATCH'); FSocket.Close(); // and we're done... FStream.Socket.Service.Stop; end; procedure EchoClient.HandleWrite(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); // half close FSocket.Shutdown(SocketShutdownWrite); // zero our response buffer so we know we got the right stuff back FResponseData := nil; SetLength(FResponseData, Length(FRequestData)); AsyncRead(FStream, FResponseData, TransferAtLeast(Length(FResponseData)), HandleRead); end; { EchoServer } constructor EchoServer.Create(const Service: IOService; const LocalEndpoint: IPEndpoint); begin inherited Create; FAcceptor := NewTCPAcceptor(Service, LocalEndpoint); FPeerSocket := NewTCPSocket(Service); FAcceptor.AsyncAccept(FPeerSocket, HandleAccept); end; procedure EchoServer.HandleAccept(const ErrorCode: IOErrorCode); begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); WriteLn('Client connected'); WriteLn('Local endpoint: ' + FPeerSocket.LocalEndpoint); WriteLn('Remote endpoint: ' + FPeerSocket.RemoteEndpoint); WriteLn('Receiving echo request'); FData := nil; SetLength(FData, 512); FPeerSocket.AsyncReceive(FData, HandleRead); end; procedure EchoServer.HandleRead(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); WriteLn(Format('Received %d bytes', [BytesTransferred])); SetLength(FData, BytesTransferred); // use stream to write result so we reply it all FStream := NewAsyncSocketStream(FPeerSocket); AsyncWrite(FStream, FData, TransferAll(), HandleWrite); end; procedure EchoServer.HandleWrite(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64); begin if (ErrorCode) then RaiseLastOSError(ErrorCode.Value); WriteLn(Format('Sent %d bytes', [BytesTransferred])); WriteLn('Shutting down...'); // deviate from echo protocol, shut down once write completes FPeerSocket.Shutdown(); FPeerSocket.Close(); FPeerSocket.Service.Stop; end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcTimers.pas } { File version: 5.18 } { Description: Timer functions } { } { Copyright: Copyright (c) 1999-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 1999/11/10 0.01 Initial version. } { 2005/08/19 4.02 Compilable with FreePascal 2.0.1 } { 2005/08/26 4.03 Improvements to timer functions. } { 2005/08/27 4.04 Revised for Fundamentals 4. } { 2007/06/08 4.05 Compilable with FreePascal 2.04 Win32 i386 } { 2009/10/09 4.06 Compilable with Delphi 2009 Win32/.NET. } { 2010/06/27 4.07 Compilable with FreePascal 2.4.0 OSX x86-64 } { 2011/05/04 4.08 Split from cDateTime unit. } { 2015/01/16 4.09 Added GetTickAccuracy. } { 2015/01/17 5.10 Revised for Fundamentals 5. } { 2018/07/17 5.11 Word32 changes. } { 2019/04/02 5.12 Compilable with Delphi 10.2 Linux64. } { 2019/06/08 5.13 Use CLOCK_MONOTONIC on Delphi Posix. } { 2019/06/08 5.14 Add GetTick64. } { 2019/10/06 5.15 MicroTick functions. } { 2020/01/28 5.16 MilliTick and MicroDateTime functions. } { 2020/01/31 5.17 Use DateTime implementations on iOS. } { 2020/03/10 5.18 Use MachAbsoluteTime on OSX. } { } { Supported compilers: } { } { Delphi 5/6/2005/2006/2007 Win32 } { Delphi 2009 .NET } { Delphi 7 Win32 5.11 2019/02/24 } { Delphi XE7 Win32 5.10 2016/01/17 } { Delphi XE7 Win64 5.10 2016/01/17 } { Delphi 10.2 Linux64 5.12 2019/04/02 } { FreePascal 3.0.4 Win32 5.11 2019/02/24 } { FreePascal 2.6.2 Linux i386 } { FreePascal 2.4.0 OSX x86-64 } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$IFDEF DEBUG} {$IFDEF TEST} {$DEFINE TIMERS_TEST} {$ENDIF} {$ENDIF} unit flcTimers; interface uses { System } SysUtils, { Fundamentals } flcStdTypes; { } { Errors } { } type ETimers = class(Exception); { } { Tick timer } { } { The tick timer returns millisecond units. } { On some systems the tick is only accurate to 10-20ms. } { TickDelta calculates the elapsed ticks between D1 to D2. } { EstimateTickAccuracy estimates the tick accuracy. } { } const TickFrequency = 1000; function GetTick: Word32; function GetTick64: Word64; function TickDelta(const D1, D2: Word32): Int32; function TickDeltaW(const D1, D2: Word32): Word32; function TickDelta64(const D1, D2: Word64): Int64; function TickDelta64W(const D1, D2: Word64): Word64; function EstimateTickAccuracy(const ReTest: Boolean = False): Word32; { } { High-precision timer } { } { StartTimer returns an encoded time (running timer). } { StopTimer returns an encoded elapsed time (stopped timer). } { ResumeTimer returns an encoded time (running timer), given an encoded } { elapsed time (stopped timer). } { StoppedTimer returns an encoded elapsed time of zero, ie a stopped timer } { with no time elapsed. } { MillisecondsElapsed returns elapsed time for a timer in milliseconds. } { MicrosecondsElapsed returns elapsed time for a timer in microseconds. } { DelayMicroSeconds goes into a tight loop for the specified duration. It } { should be used where short and accurate delays are required. } { GetHighPrecisionFrequency returns the resolution of the high-precision } { timer in units per second. } { GetHighPrecisionTimerOverhead calculates the overhead associated with } { calling both StartTimer and StopTimer. Use this value as Overhead when } { calling AdjustTimerForOverhead. } { } type THPTimer = Int64; function GetHighPrecisionTimer: Int64; function GetHighPrecisionFrequency: Int64; procedure StartTimer(out Timer: THPTimer); procedure StopTimer(var Timer: THPTimer); procedure ResumeTimer(var StoppedTimer: THPTimer); procedure InitStoppedTimer(var Timer: THPTimer); procedure InitElapsedTimer(var Timer: THPTimer; const Milliseconds: Integer); function MillisecondsElapsed(const Timer: THPTimer; const TimerRunning: Boolean = True): Integer; function MicrosecondsElapsed(const Timer: THPTimer; const TimerRunning: Boolean = True): Int64; procedure WaitMicroseconds(const MicroSeconds: Integer); function EstimateHighPrecisionTimerOverhead: Int64; procedure AdjustTimerForOverhead(var StoppedTimer: THPTimer; const Overhead: Int64 = 0); { } { MicroTick } { Timer in microsecond units, based on HighPrecisionTimer. } { } function GetMicroTick: Word64; function GetMicroTick32: Word32; function MicroTickDelta(const T1, T2: Word64): Int64; function MicroTickDeltaW(const T1, T2: Word64): Word64; function MicroTick32Delta(const T1, T2: Word32): Int32; function MicroTick32DeltaW(const T1, T2: Word32): Word32; { } { MilliTick } { Timer in millisecond units, based on HighPrecisionTimer. } { } function GetMilliTick: Word64; function GetMilliTick32: Word32; function MilliTickDelta(const T1, T2: Word64): Int64; function MilliTickDeltaW(const T1, T2: Word64): Word64; function MilliTick32Delta(const T1, T2: Word32): Int32; function MilliTick32DeltaW(const T1, T2: Word32): Word32; { } { MicroDateTime } { Represents DateTime as microseconds. } { } function DateTimeToMicroDateTime(const DT: TDateTime): Word64; function GetMicroNow: Word64; function GetMicroNowUT: Word64; { } { Tests } { } {$IFDEF TIMERS_TEST} procedure Test; {$ENDIF} implementation {$IFDEF WindowsPlatform} uses Windows, DateUtils; {$ENDIF} {$IFDEF UNIX} {$IFDEF FREEPASCAL} uses BaseUnix, Unix, System.DateUtils; {$ENDIF} {$ENDIF} {$IFDEF POSIX} {$IFDEF DELPHI} uses Posix.Time, {$IFDEF MACOS} Macapi.CoreServices, {$ENDIF} System.DateUtils; {$ENDIF} {$ENDIF} { } { Tick timer } { } {$IFDEF WindowsPlatform} {$DEFINE WinGetTick} {$IFDEF DELPHI} {$IFNDEF DELPHIXE2_UP} {$UNDEF WinGetTick} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF WinGetTick} {$DEFINE Defined_GetTick} function GetTick: Word32; begin Result := Word32(GetTickCount); end; function GetTick64: Word64; begin Result := Word64(GetTickCount64); end; {$ENDIF} {$IFDEF POSIX} {$IFDEF DELPHI} {$IFNDEF IOS} {$IFNDEF MACOS} {$DEFINE Defined_GetTick} function GetTick: Word32; var TimeVal : timespec; Ticks64 : Word64; Ticks32 : Word32; begin clock_gettime(CLOCK_MONOTONIC, @TimeVal); Ticks64 := Word64(Word64(TimeVal.tv_sec) * 1000); Ticks64 := Word64(Ticks64 + Word64(TimeVal.tv_nsec) div 1000000); Ticks32 := Word32(Ticks64 and $FFFFFFFF); Result := Ticks32; end; function GetTick64: Word64; var TimeVal : timespec; Ticks64 : Word64; begin clock_gettime(CLOCK_MONOTONIC, @TimeVal); Ticks64 := Word64(Word64(TimeVal.tv_sec) * 1000); Ticks64 := Word64(Ticks64 + Word64(TimeVal.tv_nsec) div 1000000); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFNDEF IOS} {$IFDEF MACOS} const {$IFDEF UNDERSCOREIMPORTNAME} _PU = '_'; {$ELSE} _PU = ''; {$ENDIF} const LibcLib = '/usr/lib/libc.dylib'; function MachAbsoluteTime: UInt64; cdecl external LibcLib name _PU + 'mach_absolute_time'; {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFNDEF IOS} {$IFDEF MACOS} {$DEFINE Defined_GetTick} function GetTick: Word32; var Ticks64 : Word64; Ticks32 : Word32; begin Ticks64 := Word64(AbsoluteToNanoseconds(MachAbsoluteTime)); Ticks64 := Word64(Ticks64 div 1000000); Ticks32 := Word32(Ticks64 and $FFFFFFFF); Result := Ticks32; end; function GetTick64: Word64; var Ticks64 : Word64; begin Ticks64 := Word64(AbsoluteToNanoseconds(MachAbsoluteTime)); Ticks64 := Word64(Ticks64 div 1000000); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$ENDIF} {$IFNDEF Defined_GetTick} function GetTick: Word32; const MilliSecPerDay = 24 * 60 * 60 * 1000; var N : Double; T : Int64; begin N := Now; N := N * MilliSecPerDay; T := Trunc(N); Result := Word32(T and $FFFFFFFF); end; function GetTick64: Word64; const MilliSecPerDay = 24 * 60 * 60 * 1000; var N : Double; T : Word64; begin N := Now; N := N * MilliSecPerDay; T := Word64(Trunc(N)); Result := T; end; {$ENDIF} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} // Overflow checking needs to be off here to correctly handle tick values that // wrap around the maximum value. function TickDelta(const D1, D2: Word32): Int32; begin Result := Int32(D2 - D1); end; function TickDeltaW(const D1, D2: Word32): Word32; begin Result := Word32(D2 - D1) end; function TickDelta64(const D1, D2: Word64): Int64; begin Result := Int64(D2 - D1); end; function TickDelta64W(const D1, D2: Word64): Word64; begin Result := Word64(D2 - D1); end; {$IFDEF QOn}{$Q+}{$ENDIF} var TickAccuracyCached : Boolean = False; TickAccuracy : Word32 = 0; function EstimateTickAccuracy(const ReTest: Boolean): Word32; const SecondAsDateTime = 1.0 / (24.0 * 60.0 * 60.0); MaxLoopCount = 1000000000; MaxWaitSeconds = 2; var TickStart, TickStop : Word32; TimeStart, TimeStop : TDateTime; LoopCount : Word32; Accuracy : Word32; begin // return cached test result if not ReTest and TickAccuracyCached then begin Result := TickAccuracy; exit; end; // wait for tick to change LoopCount := 1; TickStart := GetTick; TimeStart := Now; repeat Inc(LoopCount); TickStop := GetTick; TimeStop := Now; until (LoopCount = MaxLoopCount) or (TickStop <> TickStart) or (TimeStop >= TimeStart + MaxWaitSeconds * SecondAsDateTime); if TickStop = TickStart then raise ETimers.Create('Tick accuracy test failed'); // wait for tick to change LoopCount := 1; TickStart := GetTick; TimeStart := Now; repeat Inc(LoopCount); TickStop := GetTick; TimeStop := Now; until (LoopCount = MaxLoopCount) or (TickStop <> TickStart) or (TimeStop >= TimeStart + MaxWaitSeconds * SecondAsDateTime); if TickStop = TickStart then raise ETimers.Create('Tick accuracy test failed'); // calculate accuracy Accuracy := TickDelta(TickStart, TickStop); if (Accuracy <= 0) or (Accuracy > MaxWaitSeconds * TickFrequency * 2) then raise ETimers.Create('Tick accuracy test failed'); // cache result TickAccuracyCached := True; TickAccuracy := Accuracy; Result := Accuracy; end; { } { High-precision timing } { } {$IFDEF WindowsPlatform} {$DEFINE Defined_GetHighPrecisionCounter} const SHighResTimerError = 'High resolution timer error'; var HighPrecisionTimerInit : Boolean = False; HighPrecisionMillisecondFactor : Int64; HighPrecisionMicrosecondFactor : Int64; function CPUClockFrequency: Int64; var Freq : Windows.TLargeInteger; begin Freq := 0; if not QueryPerformanceFrequency(Freq) then raise ETimers.Create(SHighResTimerError); if Freq = 0 then raise ETimers.Create(SHighResTimerError); Result := Int64(Freq); end; procedure InitHighPrecisionTimer; var F : Int64; begin F := CPUClockFrequency; HighPrecisionMillisecondFactor := F div 1000; HighPrecisionMicrosecondFactor := F div 1000000; HighPrecisionTimerInit := True; end; function GetHighPrecisionCounter: Int64; var Ctr : Windows.TLargeInteger; begin if not HighPrecisionTimerInit then InitHighPrecisionTimer; QueryPerformanceCounter(Ctr); Result := Int64(Ctr); end; {$ENDIF} {$IFDEF POSIX} {$IFDEF DELPHI} {$IFNDEF IOS} {$IFNDEF MACOS} {$DEFINE Defined_GetHighPrecisionCounter} const HighPrecisionMillisecondFactor = 1000; HighPrecisionMicrosecondFactor = 1; function GetHighPrecisionCounter: Int64; var TimeVal : timespec; Ticks64 : Int64; begin clock_gettime(CLOCK_MONOTONIC, @TimeVal); Ticks64 := Int64(Int64(TimeVal.tv_sec) * 1000000); Ticks64 := Int64(Ticks64 + Int64(TimeVal.tv_nsec) div 1000); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFNDEF IOS} {$IFDEF MACOS} {$DEFINE Defined_GetHighPrecisionCounter} const HighPrecisionMillisecondFactor = 1000; HighPrecisionMicrosecondFactor = 1; function GetHighPrecisionCounter: Int64; var Ticks64 : Word64; begin Ticks64 := Word64(AbsoluteToNanoseconds(MachAbsoluteTime)); Ticks64 := Word64(Ticks64 div 1000); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF UNIX} {$IFDEF FREEPASCAL} {$DEFINE Defined_GetHighPrecisionCounter} const HighPrecisionMillisecondFactor = 1000; HighPrecisionMicrosecondFactor = 1; function GetHighPrecisionCounter: Int64; var TV : TTimeVal; TZ : PTimeZone; Ticks64 : Int64; begin TZ := nil; fpGetTimeOfDay(@TV, TZ); Ticks64 := Int64(Int64(TV.tv_sec) * 1000000); Ticks64 := Int64(Ticks64 + Int64(TV.tv_usec)); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$IFNDEF Defined_GetHighPrecisionCounter} {$DEFINE Defined_GetHighPrecisionCounter} const HighPrecisionMillisecondFactor = 1000; HighPrecisionMicrosecondFactor = 1; function GetHighPrecisionCounter: Int64; const MicroSecPerDay = Int64(24) * 60 * 60 * 1000 * 1000; var N : Double; T : Int64; begin N := Now; N := N * MicroSecPerDay; T := Trunc(N); Result := T; end; {$ENDIF} function GetHighPrecisionTimer: Int64; begin Result := GetHighPrecisionCounter; end; {$IFDEF WindowsPlatform} function GetHighPrecisionFrequency: Int64; begin Result := CPUClockFrequency; end; {$ELSE} function GetHighPrecisionFrequency: Int64; begin Result := 1000000; end; {$ENDIF} procedure StartTimer(out Timer: THPTimer); begin Timer := GetHighPrecisionCounter; end; {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} procedure StopTimer(var Timer: THPTimer); begin Timer := Int64(GetHighPrecisionCounter - Timer); end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} procedure ResumeTimer(var StoppedTimer: THPTimer); var T : THPTimer; begin StartTimer(T); {$IFDEF DELPHI5} StoppedTimer := T - StoppedTimer; {$ELSE} StoppedTimer := Int64(T - StoppedTimer); {$ENDIF} end; {$IFDEF QOn}{$Q+}{$ENDIF} procedure InitStoppedTimer(var Timer: THPTimer); begin Timer := 0; end; {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} procedure InitElapsedTimer(var Timer: THPTimer; const Milliseconds: Integer); begin {$IFDEF DELPHI5} Timer := GetHighPrecisionCounter - (Milliseconds * HighPrecisionMillisecondFactor); {$ELSE} Timer := Int64(GetHighPrecisionCounter - (Milliseconds * HighPrecisionMillisecondFactor)); {$ENDIF} end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} function MillisecondsElapsed(const Timer: THPTimer; const TimerRunning: Boolean = True): Integer; begin if not TimerRunning then Result := Timer div HighPrecisionMillisecondFactor else {$IFDEF DELPHI5} Result := Integer((GetHighPrecisionCounter - Timer) div HighPrecisionMillisecondFactor); {$ELSE} Result := Integer(Int64(GetHighPrecisionCounter - Timer) div HighPrecisionMillisecondFactor); {$ENDIF} end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFDEF WindowsPlatform} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} function MicrosecondsElapsed(const Timer: THPTimer; const TimerRunning: Boolean = True): Int64; begin if not TimerRunning then Result := Timer div HighPrecisionMicrosecondFactor else {$IFDEF DELPHI5} Result := Int64((GetHighPrecisionCounter - Timer) div HighPrecisionMicrosecondFactor); {$ELSE} Result := Int64(Int64(GetHighPrecisionCounter - Timer) div HighPrecisionMicrosecondFactor); {$ENDIF} end; {$IFDEF QOn}{$Q+}{$ENDIF} {$ELSE} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} function MicrosecondsElapsed(const Timer: THPTimer; const TimerRunning: Boolean = True): Int64; begin if not TimerRunning then Result := Timer else Result := Int64(GetHighPrecisionCounter - Timer); end; {$IFDEF QOn}{$Q+}{$ENDIF} {$ENDIF} {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} {$IFDEF DELPHI5}{$IFOPT O+}{$DEFINE OOn}{$ELSE}{$UNDEF OOn}{$ENDIF}{$OPTIMIZATION OFF}{$ENDIF} procedure WaitMicroseconds(const Microseconds: Integer); var I : Int64; N : Integer; F : Int64; J : Int64; begin if Microseconds <= 0 then exit; // start high precision timer as early as possible in procedure for minimal // overhead I := GetHighPrecisionCounter; // sleep milliseconds N := (MicroSeconds - 100) div 1000; // number of ms with at least 900us N := N - 2; // last 2ms in tight loop if N > 0 then Sleep(N); // tight loop remaining time {$IFDEF DELPHI5} F := Microseconds * HighPrecisionMicrosecondFactor; {$ELSE} F := Int64(Microseconds * HighPrecisionMicrosecondFactor); {$ENDIF} repeat J := GetHighPrecisionCounter; {$IFDEF DELPHI5} until J - I >= F; {$ELSE} until Int64(J - I) >= F; {$ENDIF} end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFDEF DELPHI5}{$IFDEF OOn}{$OPTIMIZATION ON}{$ENDIF}{$ENDIF} function EstimateHighPrecisionTimerOverhead: Int64; var T : THPTimer; I : Integer; H : Int64; begin // start and stop timer a thousand times and find smallest overhead StartTimer(T); StopTimer(T); H := T; for I := 1 to 1000 do begin StartTimer(T); StopTimer(T); if T < H then H := T; end; Result := H; end; {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} {$IFDEF DELPHI5}{$IFOPT O+}{$DEFINE OOn}{$ELSE}{$UNDEF OOn}{$ENDIF}{$OPTIMIZATION OFF}{$ENDIF} procedure AdjustTimerForOverhead(var StoppedTimer: THPTimer; const Overhead: Int64); begin if Overhead <= 0 then {$IFDEF DELPHI5} StoppedTimer := StoppedTimer - GetHighPrecisionTimerOverhead {$ELSE} StoppedTimer := Int64(StoppedTimer - EstimateHighPrecisionTimerOverhead) {$ENDIF} else {$IFDEF DELPHI5} StoppedTimer := StoppedTimer - Overhead; {$ELSE} StoppedTimer := Int64(StoppedTimer - Overhead); {$ENDIF} if StoppedTimer < 0 then StoppedTimer :=0; end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFDEF DELPHI5}{$IFDEF OOn}{$OPTIMIZATION ON}{$ENDIF}{$ENDIF} { } { MicroTick } { } {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} // 64 bits = 45964 year interval function GetMicroTick: Word64; var T : Word64; begin T := Word64(GetHighPrecisionCounter); T := T div Word64(HighPrecisionMicrosecondFactor); Result := T; end; function GetMicroTick32: Word32; var T : Word64; begin T := Word64(GetHighPrecisionCounter); T := T div Word64(HighPrecisionMicrosecondFactor); Result := Word32(T); end; function MicroTickDelta(const T1, T2: Word64): Int64; begin Result := Int64(T2 - T1); end; function MicroTickDeltaW(const T1, T2: Word64): Word64; begin Result := Word64(T2 - T1); end; function MicroTick32Delta(const T1, T2: Word32): Int32; begin Result := Int32(T2 - T1); end; function MicroTick32DeltaW(const T1, T2: Word32): Word32; begin Result := Word32(T2 - T1); end; {$IFDEF QOn}{$Q+}{$ENDIF} { } { MilliTick } { } {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} function GetMilliTick: Word64; var T : Word64; begin T := Word64(GetHighPrecisionCounter); T := T div Word64(HighPrecisionMillisecondFactor); Result := T; end; function GetMilliTick32: Word32; var T : Word64; begin T := Word64(GetHighPrecisionCounter); T := T div Word64(HighPrecisionMillisecondFactor); Result := Word32(T); end; function MilliTickDelta(const T1, T2: Word64): Int64; begin Result := Int64(T2 - T1); end; function MilliTickDeltaW(const T1, T2: Word64): Word64; begin Result := Word64(T2 - T1); end; function MilliTick32Delta(const T1, T2: Word32): Int32; begin Result := Int32(T2 - T1); end; function MilliTick32DeltaW(const T1, T2: Word32): Word32; begin Result := Word32(T2 - T1); end; {$IFDEF QOn}{$Q+}{$ENDIF} { } { MicroDateTime } { } const MicroDateTimeFactor = Word64(86400000000); // Microseconds per day: 24 * 60 * 60 * 1000 * 1000; function DateTimeToMicroDateTime(const DT: TDateTime): Word64; var F : Double; D : Word64; FT : Double; T : Word64; begin F := DT; if (F < -1.0e-12) or (F >= 106751990.0) then raise ETimers.Create('Invalid date'); D := Trunc(F); D := D * MicroDateTimeFactor; FT := Frac(F); FT := FT * MicroDateTimeFactor; T := Trunc(FT); Result := D + T; end; function GetMicroNow: Word64; begin Result := DateTimeToMicroDateTime(Now); end; {$IFDEF DELPHIXE2_UP} {$DEFINE SupportTimeZone} {$ENDIF} function GetMicroNowUT: Word64; var DT : TDateTime; begin {$IFDEF SupportTimeZone} DT := System.DateUtils.TTimeZone.Local.ToUniversalTime(Now); {$ELSE} DT := Now; {$ENDIF} Result := DateTimeToMicroDateTime(DT); end; { } { Tests } { } {$IFDEF TIMERS_TEST} {$ASSERTIONS ON} {$WARNINGS OFF} procedure Test_TickDelta; begin Assert(TickDelta(0, 10) = 10); Assert(TickDelta($FFFFFFFF, 10) = 11); Assert(TickDelta(10, 0) = -10); Assert(TickDelta($FFFFFFF6, 0) = 10); Assert(TickDeltaW(0, 10) = 10); Assert(TickDeltaW($FFFFFFFF, 10) = 11); Assert(TickDeltaW(10, 0) = $FFFFFFF6); Assert(TickDeltaW($FFFFFFF6, 0) = 10); Assert(TickDelta64(0, 10) = 10); Assert(TickDelta64($FFFFFFFFFFFFFFFF, 10) = 11); Assert(TickDelta64(10, 0) = -10); Assert(TickDelta64($FFFFFFFFFFFFFFF6, 0) = 10); Assert(TickDelta64W(0, 10) = 10); Assert(TickDelta64W($FFFFFFFFFFFFFFFF, 10) = 11); Assert(TickDelta64W(10, 0) = $FFFFFFFFFFFFFFF6); Assert(TickDelta64W($FFFFFFFFFFFFFFF6, 0) = 10); end; procedure Test_TickTimer; var A, B : Word32; I : Integer; begin // estimate tick accuracy A := EstimateTickAccuracy; Assert(A > 0); Assert(A < 500); // test tick timer using sleep A := GetTick; I := 1; repeat Sleep(1); Inc(I); B := GetTick; until (I = 2000) or (B <> A); Assert(B <> A); Assert(I < 500); Assert(TickDelta(A, B) > 0); Assert(TickDelta(A, B) < 100); end; procedure Test_TickTimer2; var A, B : Word32; P, Q : TDateTime; I : Integer; begin // test tick timer using clock A := GetTick; I := 1; P := Now; repeat Inc(I); Q := Now; B := GetTick; until (I = 100000000) or (B <> A) or (Q >= P + 2.0 / (24.0 * 60.0 * 60.0)); // two seconds Assert(B <> A); Assert(TickDelta(A, B) > 0); Assert(TickDelta(A, B) < 5000); end; procedure Test_TickTimer3; var A, B : Word32; T : THPTimer; begin // test timer using WaitMicroseconds StartTimer(T); A := GetTick; WaitMicroseconds(50000); // 50ms wait, sometimes fails for less than 20ms wait under Windows B := GetTick; StopTimer(T); Assert(TickDelta(A, B) > 0); Assert(TickDeltaW(A, B) > 0); Assert(TickDelta(A, B) = TickDeltaW(A, B)); Assert(MillisecondsElapsed(T, False) >= 45); Assert(TickDelta(A, B) >= 15); end; procedure Test_HighPrecisionTimer; var T : THPTimer; E : Integer; begin Assert(GetHighPrecisionFrequency > 0); // test timer using Sleep StartTimer(T); Sleep(20); StopTimer(T); E := MillisecondsElapsed(T, False); Assert(E >= 18); Assert(E < 2000); end; procedure Test_HighPrecisionTimer2; var T : THPTimer; A, B : Word32; I : Integer; begin // test timer using TickTimer StartTimer(T); for I := 1 to 4 do begin A := GetTick; repeat B := GetTick; until B <> A; end; StopTimer(T); Assert(TickDelta(A, B) > 0); Assert(TickDelta(A, B) = TickDeltaW(A, B)); Assert(MillisecondsElapsed(T, False) >= 2); end; procedure Test; begin Test_TickDelta; Test_TickTimer; Test_TickTimer2; Test_TickTimer3; Test_HighPrecisionTimer; Test_HighPrecisionTimer2; end; {$ENDIF} end.
unit ULiturgy; interface uses System.Generics.Collections, System.Generics.Defaults, Data.DBXJSON, System.JSON, Classes, UFastKeysSS, UProject, UUtilsJSON, USlideTemplate; type TLiturgy = class(TJSONPersistent) private FName: string; FProjectProperties: TFastKeyValuesSS; FSlideTemplates: TStringList; FMenuOrder: integer; protected function GetAsJSonObject: TJSONObject; override; procedure SetAsJSonObject(const Value: TJSONObject); override; public constructor Create(strName: string); virtual; destructor Destroy; override; procedure FillProjectProperties(project: TProject); procedure FillProjectSlides(project: TProject; AFilterSlideTypeOptions: TSlideTypeOptions); function GetSlideTypeOptions: TSlideTypeOptions; property Name: string read FName; property MenuOrder: integer read FMenuOrder write FMenuOrder; property ProjectProperties: TFastKeyValuesSS read FProjectProperties; property SlideTemplates: TStringList read FSlideTemplates; end; ILiturgyComparer = interface(IComparer<TLiturgy>) end; TLiturgyComparer = class(TComparer<TLiturgy>, ILiturgyComparer) public function Compare(const Left, Right: TLiturgy): Integer; override; end; TLiturgies = class(TObjectList<TLiturgy>) public function Add(strName: string; iMenuOrder: integer): TLiturgy; function FindByName(strName: string): TLiturgy; procedure SaveLiturgies; procedure LoadLiturgies; end; function GetLiturgies: TLiturgies; procedure FillLiturgies; implementation uses SysUtils, USlide, USettings, UUtils; var gl_Liturgies: TLiturgies = nil; function GetLiturgies: TLiturgies; var comparer: ILiturgyComparer; begin if not Assigned(gl_Liturgies) then begin gl_Liturgies := TLiturgies.Create(); FillLiturgies; // gl_Liturgies.SaveLiturgies; // gl_Liturgies.LoadLiturgies; comparer := TLiturgyComparer.Create; gl_Liturgies.Sort(comparer); end; Result := gl_Liturgies; end; procedure FillLiturgies; var liturgy: TLiturgy; begin //// Leeg liturgy := GetLiturgies.Add('Leeg', 0); liturgy.ProjectProperties['speaker'] := ''; liturgy.ProjectProperties['collecte1'] := ''; liturgy.ProjectProperties['collecte2'] := ''; //// Orde van dienst A morgendienst liturgy := GetLiturgies.Add('Orde van dienst A morgendienst', 10); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Wet - 10 geboden'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE_CHILDREN); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - 15.00'); liturgy.SlideTemplates.Add('Afscheid - 16.30'); liturgy.SlideTemplates.Add('Afscheid - 19.00'); //// Orde van dienst A middagdienst liturgy := GetLiturgies.Add('Orde van dienst A middagdienst', 20); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Geloofsbelijdenis lezen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - week'); //// Orde van dienst B morgendienst liturgy := GetLiturgies.Add('Orde van dienst B morgendienst', 30); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 vanmorgen'); liturgy.SlideTemplates.Add('Kompas 7-8 vanmorgen'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas vanmorgen'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Wet - 10 geboden'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // dienst van het woord liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 naar de zalen'); liturgy.SlideTemplates.Add('Kompas 7-8 naar de zalen'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas naar de zalen'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // Dienst van de Tafel / Dienst van de Dankbaarheid // liturgy.SlideTemplates.Add('Doop picto'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE_CHILDREN); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 terug'); liturgy.SlideTemplates.Add('Kompas 7-8 terug'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas terug'); // liturgy.SlideTemplates.Add('Avondmaal picto'); // Zending en zege liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - 15.00'); liturgy.SlideTemplates.Add('Afscheid - 16.30'); liturgy.SlideTemplates.Add('Afscheid - 19.00'); //// Orde van dienst B middagdienst liturgy := GetLiturgies.Add('Orde van dienst B middagdienst', 40); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Geloofsbelijdenis lezen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); // liturgy.SlideTemplates.Add('Doop picto'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE); // liturgy.SlideTemplates.Add('Avondmaal picto'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - week'); //// Orde van dienst C morgendienst liturgy := GetLiturgies.Add('Orde van dienst C morgendienst', 50); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 vanmorgen'); liturgy.SlideTemplates.Add('Kompas 7-8 vanmorgen'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas vanmorgen'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Schuldbelijdenis en Genadeverkondiging'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // dienst van het woord liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 naar de zalen'); liturgy.SlideTemplates.Add('Kompas 7-8 naar de zalen'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas naar de zalen'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // Dienst van de Tafel / Dienst van de Dankbaarheid liturgy.SlideTemplates.Add('Wet - 10 geboden'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // liturgy.SlideTemplates.Add('Doop picto'); liturgy.SlideTemplates.Add('Gebed'); // liturgy.SlideTemplates.Add('Geloofsbelijdenis lezen'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE_CHILDREN); liturgy.SlideTemplates.Add('Kidsbijbelclub 0-6 terug'); liturgy.SlideTemplates.Add('Kompas 7-8 terug'); liturgy.SlideTemplates.Add('Kidsbijbelclub en Kompas terug'); // liturgy.SlideTemplates.Add('Avondmaal picto'); // Zending en zege liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - 15.00'); liturgy.SlideTemplates.Add('Afscheid - 16.30'); liturgy.SlideTemplates.Add('Afscheid - 19.00'); //// Orde van dienst C middagdienst liturgy := GetLiturgies.Add('Orde van dienst C middagdienst', 60); liturgy.ProjectProperties['speaker'] := 'Voorganger: ds A.J. van Zuijlekom'; liturgy.ProjectProperties['collecte1'] := 'Eredienst'; liturgy.ProjectProperties['collecte2'] := 'Diaconaal doel'; // aanvang liturgy.SlideTemplates.Add('AED in geval van nood'); liturgy.SlideTemplates.Add('Welkom'); liturgy.SlideTemplates.Add('Mededelingen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Stilte moment'); liturgy.SlideTemplates.Add('Votum en zegengroet Lb 416'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // dienst van het woord liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add('Lezen'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Tekst'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); liturgy.SlideTemplates.Add('Preek'); liturgy.SlideTemplates.Add('Zingen-zit-PPT'); // Dienst van de Tafel / Dienst van de Dankbaarheid // liturgy.SlideTemplates.Add('Doop picto'); liturgy.SlideTemplates.Add('Geloofsbelijdenis lezen'); liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Gebed'); liturgy.SlideTemplates.Add(CTEMPLATE_COLLECTE); // Zending en zege liturgy.SlideTemplates.Add('Zingen-staan-PPT'); liturgy.SlideTemplates.Add('Zegen Amen Lb 416'); liturgy.SlideTemplates.Add('Afscheid - week'); end; { TLiturgies } function TLiturgies.Add(strName: string; iMenuOrder: integer): TLiturgy; begin Result := FindByName(strName); if Result = nil then begin Result := TLiturgy.Create(strName); inherited Add(Result); end; Result.MenuOrder := iMenuOrder; end; function TLiturgies.FindByName(strName: string): TLiturgy; var i: Integer; begin for i := 0 to Count -1 do begin if Items[i].Name = strName then begin Result := Items[i]; Exit; end; end; Result := nil; end; procedure TLiturgies.LoadLiturgies; var slFiles: TStringList; strDir: string; i: Integer; liturgy: TLiturgy; begin strDir := GetSettings.GetContentDir + 'liturgies\'; slFiles := TStringList.Create; try FindFilesWithExtensions(slFiles, false, strDir, '', '.json'); for i := 0 to slFiles.Count -1 do begin liturgy := Add(ChangeFileExt(slFiles[i], ''), -1); liturgy.AsJSon := LoadUnicodeFromFile( strDir + slFiles[i] ); end; finally slFiles.Free; end; end; procedure TLiturgies.SaveLiturgies; var strDir: string; i: Integer; begin strDir := GetSettings.GetContentDir + 'liturgies\'; ForceDirectories(strDir); for i := 0 to Count -1 do begin SaveUnicodeToFile(strDir + Items[i].Name + '.json', Items[i].AsJSon); end; end; { TLiturgy } constructor TLiturgy.Create(strName: string); begin inherited Create; FName := strName; FProjectProperties := TFastKeyValuesSS.Create; FSlideTemplates := TStringList.Create; end; destructor TLiturgy.Destroy; begin FSlideTemplates.Free; FProjectProperties.Free; inherited; end; procedure TLiturgy.FillProjectProperties(project: TProject); var i: integer; begin for i := 0 to ProjectProperties.Count -1 do begin project.Properties[ProjectProperties.KeyOfIndex[i]] := ProjectProperties.ValueOfIndex[i]; end; end; procedure TLiturgy.FillProjectSlides(project: TProject; AFilterSlideTypeOptions: TSlideTypeOptions); var i: integer; template: TSlideTemplate; slide: TSlide; begin for i := 0 to SlideTemplates.Count -1 do begin template := GetSlideTemplates.FindByName(SlideTemplates[i]); if Assigned(template) and (template.TypeOption in AFilterSlideTypeOptions) then begin slide := template.DoOnAdd(false); try if Assigned(slide) then begin project.Slides.Add(slide.AsJSon); end; finally slide.Free; end; end; end; end; function TLiturgy.GetAsJSonObject: TJSONObject; begin Result := inherited GetAsJSonObject; Result.AddPair('Name', EscapeString(FName)); Result.AddPair('MenuOrder', TJSONNumber.Create(FMenuOrder)); Result.AddPair('ProjectProperties', FProjectProperties.AsJSonObject); Result.AddPair(CreateStringListPair('SlideTemplates', FSlideTemplates)); end; function TLiturgy.GetSlideTypeOptions: TSlideTypeOptions; var i: integer; template: TSlideTemplate; begin Result := []; for i := 0 to SlideTemplates.Count -1 do begin template := GetSlideTemplates.FindByName(SlideTemplates[i]); if Assigned(template) then begin include(Result, template.TypeOption); end; end; end; procedure TLiturgy.SetAsJSonObject(const Value: TJSONObject); begin inherited; FName := UUtilsJSON.GetAsString(Value, 'Name'); FMenuOrder := UUtilsJSON.GetAsInteger(Value, 'MenuOrder'); FProjectProperties.AsJSonObject := UUtilsJSON.GetAsObject(Value, 'ProjectProperties'); UUtilsJSON.GetAsStringList(Value, 'SlideTemplates', FSlideTemplates); end; { TLiturgyComparer } function TLiturgyComparer.Compare(const Left, Right: TLiturgy): Integer; begin if Left.MenuOrder < Right.MenuOrder then Result := -1 else if Left.MenuOrder > Right.MenuOrder then Result := 1 else Result := 0; end; initialization gl_Liturgies := nil; finalization gl_Liturgies.Clear; FreeAndNil(gl_Liturgies); end.
program AlgLista4Ex4; // Exercicio 4 da lista 4 de algoritmos. Autor: Henrique Colodetti Escanferla. type vetor=array[1..27]of integer; // Criação do tipo de variavel vetor de 27 posições de inteiros. var v:vetor; // Variaveis globais: v=> guardará numeros aleatorios de 1 a 365. n,prob:real; // n=> receberá comandos do usuario; prob=> guarda o resultado pedido; den=> nº de randomizações de "v". tamv:integer; // tamv=> tamanho util de "v"; procedure preenche(var v:vetor; tamv:integer); // "preenche" randomizará nºs e os colocará num dado vetor. begin // Inicio deste procedimento. while tamv<>0 do begin // Inicio deste loop. v[tamv]:=random(266); // Chama-se "random" que gera nº d 1 a 365 e coloca em "v". tamv:=tamv-1; // Prox indice de "v". end; // Fim deste loop. end; // Fim deste procedimento. function repeticoes(v:vetor; tamv:integer; num:real):boolean; // "repeticoes" le vetor e valor acusando incidencia de pelo menos 2 vezes um mesmo valor no veor "v". var cont:integer; // Variaveis locais: cont=> contará o nº de repetições. begin // Inicio desta função. repeticoes:=false; // Começa como falso. cont:=0; // Começa com zero. while tamv<>0 do // Se "num" repetir o loop acaba. begin // Inicio deste loop. if v[tamv]=num then cont:=cont+1; // Houve ocorrencia de "num". tamv:=tamv-1; // Prox. indice do vetor. end; // Fim deste loop. if cont>1 then repeticoes:=true; // Resultado positivo. end; // Fim desta função. begin // Começo do processo. prob:=0; // Começa com zero. n:=0; // Começa com zero while n<10000000 do // 10^7 dá um resultado de precisão boa. begin // Inicio deste loop. tamv:=27; // Começa com 27. preenche(v,tamv); // Chama-se "preenche". while tamv<>0 do begin // Inicio deste loop. if repeticoes(v,tamv,v[tamv]) then // Chama-se "repeticoes". begin // Inicio deste if-then. prob:=prob+1; // Incrementa o numerador pois o resultado é positivo. tamv:=1; // Interrompe o loop pois o resultado é positivo. end; // Fim deste if-then. tamv:=tamv-1; // Proximo indice de "v". end; // Fim deste loop. n:=n+1; // Conta-se um ciclo. end; // Fim deste loop. prob:=prob/10000000; // Calculo de "prob". É o nº de eventos confirmados sobre o nº de tentativas. writeln('O resultado é ',prob:9:6); // app do resultado. end. // Fim do processo.
unit colors; INTERFACE uses graph; procedure convert(r,g,b:real; var c:integer); procedure rgb_to_hsv(r,g,b:real; var h,s,v:real); procedure hsv_to_rgb(h,s,v:real; var r,g,b:real); procedure init_palette_farbe; procedure init_palette_grau; IMPLEMENTATION const UNDEFINED:real=-1e30; function maximum(a,b,c:real):real; begin if a<=b then begin if b<=c then maximum:=c else maximum:=b; end else begin if a<=c then maximum:=c else maximum:=a; end; end; function minimum(a,b,c:real):real; begin if a>=b then begin if b>=c then minimum:=c else minimum:=b; end else begin if a>=c then minimum:=c else minimum:=a; end; end; procedure init_palette_grau; var i:integer; begin for i:=0 to 255 do setrgbpalette(i,i,i,i); end; procedure init_palette_farbe; var i:integer; h,s,v,r,g,b:real; begin setrgbpalette(0,0,0,0); setrgbpalette(64,255,255,255); setrgbpalette(128,153,153,153); setrgbpalette(192,76,76,76); for i:=1 to 63 do begin s:=0.5; v:=0.5; h:=360*i/64; hsv_to_rgb(h,s,v,r,g,b); setrgbpalette(i,round(r*255),round(g*255),round(b*255)); s:=1; v:=0.5; hsv_to_rgb(h,s,v,r,g,b); setrgbpalette(i+64,round(r*255),round(g*255),round(b*255)); s:=0.5; v:=1; hsv_to_rgb(h,s,v,r,g,b); setrgbpalette(i+128,round(r*255),round(g*255),round(b*255)); s:=1; v:=1; hsv_to_rgb(h,s,v,r,g,b); setrgbpalette(i+192,round(r*255),round(g*255),round(b*255)); end; end; procedure rgb_to_hsv; var delta,max,min:real; begin max:=maximum(r,g,b); min:=minimum(r,g,b); v:=max; if max<>0 then s:=(max-min)/max else s:=0; if s=0 then h:=UNDEFINED else begin delta:=max-min; if r=max then h:=(g-b)/delta else if g=max then h:=2+(b-r)/delta else if b=max then h:=4+(r-g)/delta; h:=h*60; if h<0 then h:=h+360; end; end; procedure hsv_to_rgb; var i,f,p,q,t:real; begin if s=0 then if h=UNDEFINED then begin r:=v; h:=v; b:=v; end else begin writeln('hsv_to_rgb: s=0 und h<>0 !'); halt(255) end else begin if h=360 then h:=0; h:=h/60; i:=int(h); f:=frac(h); p:=v*(1-s); q:=v*(1-(s*f)); t:=v*(1-(s*(1-f))); case round(i) of 0: begin r:=v; g:=t; b:=p end; 1: begin r:=q; g:=v; b:=p end; 2: begin r:=p; g:=v; b:=t end; 3: begin r:=p; g:=q; b:=v end; 4: begin r:=t; g:=p; b:=v end; 5: begin r:=v; g:=p; b:=q end; end; end; end; procedure convert; var h,s,v:real; begin rgb_to_hsv(r,g,b,h,s,v); if v<0.2 then if v<0.25 then c:=0 else if v>0.8 then c:=64 else if v>0.5 then c:=192 else c:=128 else begin c:=round(64*h/360); if c=0 then c:=1; if c>63 then c:=63; if v>0.5 then c:=c or $80; if s>0.5 then c:=c or $40; end; end; begin end.
unit KeyContainer; interface type HCkKeyContainer = Pointer; HCkPrivateKey = Pointer; HCkPublicKey = Pointer; HCkString = Pointer; function CkKeyContainer_Create: HCkKeyContainer; stdcall; procedure CkKeyContainer_Dispose(handle: HCkKeyContainer); stdcall; procedure CkKeyContainer_getContainerName(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; function CkKeyContainer__containerName(objHandle: HCkKeyContainer): PWideChar; stdcall; procedure CkKeyContainer_getDebugLogFilePath(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; procedure CkKeyContainer_putDebugLogFilePath(objHandle: HCkKeyContainer; newPropVal: PWideChar); stdcall; function CkKeyContainer__debugLogFilePath(objHandle: HCkKeyContainer): PWideChar; stdcall; function CkKeyContainer_getIsMachineKeyset(objHandle: HCkKeyContainer): wordbool; stdcall; function CkKeyContainer_getIsOpen(objHandle: HCkKeyContainer): wordbool; stdcall; procedure CkKeyContainer_getLastErrorHtml(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; function CkKeyContainer__lastErrorHtml(objHandle: HCkKeyContainer): PWideChar; stdcall; procedure CkKeyContainer_getLastErrorText(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; function CkKeyContainer__lastErrorText(objHandle: HCkKeyContainer): PWideChar; stdcall; procedure CkKeyContainer_getLastErrorXml(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; function CkKeyContainer__lastErrorXml(objHandle: HCkKeyContainer): PWideChar; stdcall; function CkKeyContainer_getLastMethodSuccess(objHandle: HCkKeyContainer): wordbool; stdcall; procedure CkKeyContainer_putLastMethodSuccess(objHandle: HCkKeyContainer; newPropVal: wordbool); stdcall; function CkKeyContainer_getVerboseLogging(objHandle: HCkKeyContainer): wordbool; stdcall; procedure CkKeyContainer_putVerboseLogging(objHandle: HCkKeyContainer; newPropVal: wordbool); stdcall; procedure CkKeyContainer_getVersion(objHandle: HCkKeyContainer; outPropVal: HCkString); stdcall; function CkKeyContainer__version(objHandle: HCkKeyContainer): PWideChar; stdcall; procedure CkKeyContainer_CloseContainer(objHandle: HCkKeyContainer); stdcall; function CkKeyContainer_CreateContainer(objHandle: HCkKeyContainer; name: PWideChar; machineKeyset: wordbool): wordbool; stdcall; function CkKeyContainer_DeleteContainer(objHandle: HCkKeyContainer): wordbool; stdcall; function CkKeyContainer_FetchContainerNames(objHandle: HCkKeyContainer; bMachineKeyset: wordbool): wordbool; stdcall; function CkKeyContainer_GenerateKeyPair(objHandle: HCkKeyContainer; bKeyExchangePair: wordbool; keyLengthInBits: Integer): wordbool; stdcall; function CkKeyContainer_GenerateUuid(objHandle: HCkKeyContainer; outStr: HCkString): wordbool; stdcall; function CkKeyContainer__generateUuid(objHandle: HCkKeyContainer): PWideChar; stdcall; function CkKeyContainer_GetNthContainerName(objHandle: HCkKeyContainer; bMachineKeyset: wordbool; index: Integer; outStr: HCkString): wordbool; stdcall; function CkKeyContainer__getNthContainerName(objHandle: HCkKeyContainer; bMachineKeyset: wordbool; index: Integer): PWideChar; stdcall; function CkKeyContainer_GetNumContainers(objHandle: HCkKeyContainer; bMachineKeyset: wordbool): Integer; stdcall; function CkKeyContainer_GetPrivateKey(objHandle: HCkKeyContainer; bKeyExchangePair: wordbool): HCkPrivateKey; stdcall; function CkKeyContainer_GetPublicKey(objHandle: HCkKeyContainer; bKeyExchangePair: wordbool): HCkPublicKey; stdcall; function CkKeyContainer_ImportPrivateKey(objHandle: HCkKeyContainer; key: HCkPrivateKey; bKeyExchangePair: wordbool): wordbool; stdcall; function CkKeyContainer_ImportPublicKey(objHandle: HCkKeyContainer; key: HCkPublicKey; bKeyExchangePair: wordbool): wordbool; stdcall; function CkKeyContainer_OpenContainer(objHandle: HCkKeyContainer; name: PWideChar; needPrivateKeyAccess: wordbool; machineKeyset: wordbool): wordbool; stdcall; function CkKeyContainer_SaveLastError(objHandle: HCkKeyContainer; path: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkKeyContainer_Create; external DLLName; procedure CkKeyContainer_Dispose; external DLLName; procedure CkKeyContainer_getContainerName; external DLLName; function CkKeyContainer__containerName; external DLLName; procedure CkKeyContainer_getDebugLogFilePath; external DLLName; procedure CkKeyContainer_putDebugLogFilePath; external DLLName; function CkKeyContainer__debugLogFilePath; external DLLName; function CkKeyContainer_getIsMachineKeyset; external DLLName; function CkKeyContainer_getIsOpen; external DLLName; procedure CkKeyContainer_getLastErrorHtml; external DLLName; function CkKeyContainer__lastErrorHtml; external DLLName; procedure CkKeyContainer_getLastErrorText; external DLLName; function CkKeyContainer__lastErrorText; external DLLName; procedure CkKeyContainer_getLastErrorXml; external DLLName; function CkKeyContainer__lastErrorXml; external DLLName; function CkKeyContainer_getLastMethodSuccess; external DLLName; procedure CkKeyContainer_putLastMethodSuccess; external DLLName; function CkKeyContainer_getVerboseLogging; external DLLName; procedure CkKeyContainer_putVerboseLogging; external DLLName; procedure CkKeyContainer_getVersion; external DLLName; function CkKeyContainer__version; external DLLName; procedure CkKeyContainer_CloseContainer; external DLLName; function CkKeyContainer_CreateContainer; external DLLName; function CkKeyContainer_DeleteContainer; external DLLName; function CkKeyContainer_FetchContainerNames; external DLLName; function CkKeyContainer_GenerateKeyPair; external DLLName; function CkKeyContainer_GenerateUuid; external DLLName; function CkKeyContainer__generateUuid; external DLLName; function CkKeyContainer_GetNthContainerName; external DLLName; function CkKeyContainer__getNthContainerName; external DLLName; function CkKeyContainer_GetNumContainers; external DLLName; function CkKeyContainer_GetPrivateKey; external DLLName; function CkKeyContainer_GetPublicKey; external DLLName; function CkKeyContainer_ImportPrivateKey; external DLLName; function CkKeyContainer_ImportPublicKey; external DLLName; function CkKeyContainer_OpenContainer; external DLLName; function CkKeyContainer_SaveLastError; external DLLName; end.
unit controller.status; {$mode delphi}{$H+} interface uses SysUtils, Classes, httpdefs, fpHTTP, fpWeb, controller.base, controller.dto; type (* enum representing an image's lifecycle *) TImageStatus = ( isInProgress, isCompleted, isFailed ); { TStatusController } TStatusController = class(TBaseController) strict private procedure InitStatusTable; //action for fetching a status procedure FetchAction(Sender : TObject; ARequest : TRequest; AResponse : TResponse; var Handled : Boolean); strict protected procedure DoInitialize(); override; function DoInitializeActions(): TActions; override; public (* inserts a new status record for the provided image token, and can be used if there are no previous status records *) function UpdateStatus(Const AImageToken : String; Const ANewStatus : TImageStatus; Out Error : String) : Boolean; (* provided an image token, will lookup the status of a given image, and return it to the caller. a failure indicates the token is invalid or an error occurred *) function Fetch(Const AImageToken : String; Out Status : TImageStatus; Out Error : String) : Boolean; end; (* helper method for converting a status enum to a string representation *) function ImageStatusToString(Const AStatus : TImageStatus) : String; (* helper method for converting a status string back to an enum value *) function StringToImageStatus(Const AStatus : String) : TImageStatus; var StatusController: TStatusController; const IMAGE_STATUS_LOOKUP : array[0 .. 2] of String = ( 'In-Progress', 'Completed', 'Failed' ); implementation uses controller.registration, controller.status.dto, fpjson, jsonparser; function ImageStatusToString(const AStatus: TImageStatus): String; begin Result := IMAGE_STATUS_LOOKUP[Ord(AStatus)]; end; function StringToImageStatus(const AStatus: String): TImageStatus; var I: Integer; begin Result := isInProgress; for I := 0 to High(IMAGE_STATUS_LOOKUP) do if IMAGE_STATUS_LOOKUP[I].ToLower = AStatus.ToLower then begin Result := TImageStatus(I); Exit; end; //if we didn't find it above it means we have an invalid string Raise Exception.Create('ImageStatusToString::[' + AStatus + '] is not a valid status'); end; {$R *.lfm} { TStatusController } procedure TStatusController.InitStatusTable; var LError: String; begin //initialize our table if it doesn't exist if not ExecuteSQL( 'CREATE TABLE IF NOT EXISTS status(' + ' id Integer NOT NULL PRIMARY KEY AUTOINCREMENT,' + ' registration_id integer,' + ' status varchar(128) NOT NULL,' + ' create_date datetime NOT NULL DEFAULT (datetime(''now'')),' + ' FOREIGN KEY(registration_id) REFERENCES registration(id));', LError ) then LogError(LError); end; procedure TStatusController.FetchAction(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean); var LRequest : TStatusRequest; LResponse : TStatusResponse; LStatus : TImageStatus; LError: String; begin try LResponse.Status := isInProgress; AResponse.ContentType := 'application/json'; AResponse.SetCustomHeader('Access-Control-Allow-Origin', '*'); Handled := True; LogRequester('FetchAction::', ARequest); //try and parse the token LRequest.FromJSON(ARequest.Content); //try to fetch the status if not Fetch(LRequest.Token, LStatus, LError) then begin AResponse.Content := GetErrorJSON('unable to fetch status'); LogError(LError); end else begin LResponse.Status := LStatus; AResponse.Content := LResponse.ToJSON; end; except on E : Exception do begin LogError(E.Message); AResponse.Content := GetErrorJSON('unable to fetch status - server error'); end end; end; procedure TStatusController.DoInitialize(); begin inherited DoInitialize(); InitStatusTable; end; function TStatusController.DoInitializeActions(): TActions; var I : Integer; LAction : TAction; begin Result:=inherited DoInitializeActions(); //set the starting index to the last index of result I := High(Result); //if base added some default actions, then increment the index if I >= 0 then Inc(I); //initialize the status route actions SetLength(Result, Succ(Length(Result))); //only have a single fetching action for web callers LAction.Name := 'fetch'; LAction.Action := FetchAction; Result[I] := LAction; end; function TStatusController.UpdateStatus(const AImageToken: String; const ANewStatus: TImageStatus; out Error: String): Boolean; var LRegistration : TRegistrationController; LID: Integer; begin Result := False; LRegistration := TRegistrationController.Create(nil); try try LogInfo('UpdateStatus::requesting new status [' + ImageStatusToString(ANewStatus) + '] for token [' + AImageToken + ']'); //check if we can find the requested image token and get the internal //id so we can properly update if not LRegistration.LookupImageID(AImageToken, LID) then begin Error := 'UpdateStatus::[' + AImageToken + '] not found'; Exit; end; //attempt to update the status if not ExecuteSQL( 'INSERT INTO status (registration_id, status) SELECT ' + IntToStr(LID) + ',' + ' ' + QuotedStr(ImageStatusToString(ANewStatus)) + ';', Error ) then begin Error := 'UpdateStatus::' + Error; Exit; end; Result := True; except on E : Exception do Error := 'UpdateStatus::' + E.Message; end; finally LRegistration.Free; end; end; function TStatusController.Fetch(const AImageToken: String; out Status: TImageStatus; out Error: String): Boolean; var LRegistration : TRegistrationController; LID: Integer; LData: TDatasetResponse; LStatus: TJSONData; begin Result := False; LRegistration := TRegistrationController.Create(nil); try if not LRegistration.LookupImageID(AImageToken, LID) then begin Error := 'Fetch::[' + AImageToken + '] not found'; Exit; end; //attempt to fetch the most recent status if not GetSQLResultsJSON( 'SELECT status FROM status WHERE registration_id = ' + IntToStr(LID) + ' ORDER BY id DESC LIMIT 1;', LData, Error ) then Exit; if LData.Count < 1 then begin Error := 'Fetch::unable to fetch status for image [' + AImageToken + '];'; Exit; end; LStatus := GetJSON(LData[0]); try //try to parse the response if not Assigned(LStatus) or (LStatus.JSONType <> jtObject) then begin Error := 'Fetch::malformed json'; Exit; end; //convert to status Status := StringToImageStatus(TJSONObject(LStatus).Get('status')); //success Result := True; finally if Assigned(LStatus) then LStatus.Free; end; finally LRegistration.Free; end; end; initialization RegisterHTTPModule(GetControllerRoute('status'), TStatusController); end.
(* Output: a and b = false a or b = true (a or b) and b = true *) program Test8; var a, b, c: boolean; begin a := true; b := false; c := a and b; writeln('a and b = ', c); c := a or b; writeln('a or b = ' , c); a := false; b := true; c := (a or b) and b; writeln('(a or b) and b = ' , c); end.
unit Fonts; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, ComCtrls; type TFontsDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; FontName: TComboBox; UpDown1: TUpDown; FontSize: TEdit; Sample: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FontNameChange(Sender: TObject); procedure FontSizeChange(Sender: TObject); procedure FormActivate(Sender: TObject); private procedure GetFontNames; public { Public declarations } end; var FontsDlg: TFontsDlg; implementation {$R *.DFM} function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; stdcall; begin if odd(LogFont.lfPitchAndFamily) then TStrings(Data).Add(LogFont.lfFaceName); Result := 1; end; procedure TFontsDlg.GetFontNames; var DC: HDC; begin DC := GetDC(0); EnumFonts(DC, nil, @EnumFontsProc, Pointer(FontName.Items)); ReleaseDC(0, DC); FontName.Sorted := True; end; procedure TFontsDlg.FormCreate(Sender: TObject); begin GetFontNames; end; procedure TFontsDlg.FormShow(Sender: TObject); begin Sample.Font.Name := FontName.Items[FontName.ItemIndex]; Sample.Font.Size := StrToInt(FontSize.Text); end; procedure TFontsDlg.FontNameChange(Sender: TObject); begin Sample.Font.Name := FontName.Items[FontName.ItemIndex]; end; procedure TFontsDlg.FontSizeChange(Sender: TObject); begin Sample.Font.Size := StrToInt(FontSize.Text); end; procedure TFontsDlg.FormActivate(Sender: TObject); begin OkBtn.SetFocus; end; end.
unit gmDatasource; interface {$REGION 'DatasetHelper Note'} { TDataSet helper classes to simplify access to TDataSet fields and make TDataSet work with a for-in-loop. Author: Uwe Raabe - ur@ipteam.de Techniques used: - class helpers - enumerators - invokable custom variants This unit implements some "Delphi Magic" to simplify the use of TDataSets and its fields. Just by USING this unit you can access the individual fields of a TDataSet like they were properties of a class. For example let's say a DataSet has fields First_Name and Last_Name. The normal approach to access the field value would be to write something like this: DataSet.FieldValues['First_Name'] or DataSet.FieldByName('First_Name'].Value With this unit you can simply write DataSet.CurrentRec.First_Name You can even assign DataSet.CurrentRec to a local variable of type variant to shorten the needed typing and clarify the meaning (let PersonDataSet be a TDataSet descendant with fields as stated above). var Person: Variant; FullName: string; begin Person := PersonDataSet.CurrentRec; ... FullName := Trim(Format('%s %s', [Person.First_Name, Person.Last_Name])); ... end; If you write to such a property, the underlying DatsSet is automatically set into Edit mode. Obviously you still have to know the field names of the dataset, but this is just the same as if you are using FieldByName. The second benefit of this unit shows up when you try to iterate over a DataSet. This reduces to simply write the following (let Lines be a TStrings decendant taking the full names of all persons): var Person: Variant; begin ... // Active state of PersonDataSet is saved during the for loop. // If PersonDataSet supports bookmarks, the position is also saved. for Person in PersonDataSet do begin Lines.Add(Trim(Format('%s %s', [Person.First_Name, Person.Last_Name]))); end; ... end; You can even set these "variant-field-properties" during the for loop as the DataSet will automatically Post your changes within the Next method. How it works: We use a class helper to add the CurrentRec property and the enumerator to the TDataSet class. The CurrentRec property is also used by the enumerator to return the current record when iterating. The TDataSetEnumerator does some housekeeping to restore the active state and position of the DataSet after the iteration, thus your code hasn't to do this each time. The tricky thing is making the variant to access the dataset fields as if they were properties. This is accomplished by introducing a custom variant type descending from TInvokeableVariantType. Besides the obligatory overwriting of Clear and Copy, which turn out to be quite simple, we implement the GetProperty and SetProperty methods to map the property names to field names. That's all! CAUTION! Don't do stupid things with the DataSet while there is some of these variants connected to it. Especially don't destroy it! The variant stuff is completely hidden in the implementation section, as for now I can see no need to expose it. } {$ENDREGION} uses Data.DB, Generics.Collections, Classes, System.SysUtils, gmClientDataset; type TgmDatasource = class; TDataSourceEnumerator = class private FBookmark: TBookmark; // FDataSet: TgmAureliusDataset; FDatasource: TgmDatasource; FMoveToFirst: Boolean; FWasActive: Boolean; function GetCurrent: Variant; public constructor Create(ADataSource: TgmDatasource); destructor Destroy; override; function MoveNext: Boolean; property Current: Variant read GetCurrent; end; TgmDatasource = class(TDatasource) private function GetCurrentRec: Variant; function GetgmDataset: TgmClientDataset; function GetFDMemTable: TgmFDMemTable; // procedure SetgmDataset(Value: TgmClientDataset); public function GetEnumerator: TDataSourceEnumerator; function FieldByName(const FieldName: string): TField; property CurrentRec: Variant read GetCurrentRec; property gmDataset: TgmClientDataset read GetgmDataset; property gmFDMemTable: TgmFDMemTable read GetFDMemTable; end; implementation uses Variants; type { A custom variant type that implements the mapping from the property names to the DataSet fields. } TVarDataRecordType = class(TInvokeableVariantType) public procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; function GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; override; function SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean; override; end; type { Our layout of the variants record data. We only hold a pointer to the DataSet. } TVarDataRecordData = packed record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; DataSet: TDataSet; Reserved4: LongInt; end; var { The global instance of the custom variant type. The data of the custom variant is stored in a TVarData record, but the methods and properties are implemented in this class instance. } VarDataRecordType: TVarDataRecordType = nil; { A global function the get our custom VarType value. This may vary and thus is determined at runtime. } function VarDataRecord: TVarType; begin result := VarDataRecordType.VarType; end; { A global function that fills the VarData fields with the correct values. } function VarDataRecordCreate(ADataSet: TDataSet): Variant; begin VarClear(result); TVarDataRecordData(result).VType := VarDataRecord; TVarDataRecordData(result).DataSet := ADataSet; end; procedure TVarDataRecordType.Clear(var V: TVarData); begin { No fancy things to do here, we are only holding a pointer to a TDataSet and we are not supposed to destroy it here. } SimplisticClear(V); end; procedure TVarDataRecordType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); begin { No fancy things to do here, we are only holding a pointer to a TDataSet and that can simply be copied here. } SimplisticCopy(Dest, Source, Indirect); end; function TVarDataRecordType.GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; var fld: TField; begin { Find a field with the property's name. If there is one, return its current value. } fld := TVarDataRecordData(V).DataSet.FindField(Name); result := (fld <> nil); if result then Variant(dest) := fld.Value; end; function TVarDataRecordType.SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean; var fld: TField; begin { Find a field with the property's name. If there is one, set its value. } fld := TVarDataRecordData(V).DataSet.FindField(Name); result := (fld <> nil); if result then begin { Well, we have to be in Edit mode to do this, don't we? } TVarDataRecordData(V).DataSet.Edit; fld.Value := Variant(Value); end; end; constructor TDataSourceEnumerator.Create(ADataSource: TgmDatasource); { The enumerator is automatically created and destroyed in the for-in loop. So we remember the active state and set a flag that the first MoveNext will not move to the next record, but stays on the first one instead. } begin inherited Create; FDataSource := ADataSource; Assert((FDataSource <> nil) and (FDataSource.DataSet is TgmClientDataset)); { save the Active state } FWasActive := FDataSource.DataSet.Active; { avoid flickering } FDataSource.DataSet.DisableControls; if FWasActive then begin { get a bookmark of the current position - even if it is invalid } FBookmark := FDataSource.DataSet.GetBookmark; FDataSource.DataSet.First; end else begin { FBookmark is initialized to nil anyway, so no need to set it here } FDataSource.DataSet.Active := true; end; FMoveToFirst := true; end; destructor TDataSourceEnumerator.Destroy; { Restore the DataSet to its previous state. } begin if FWasActive then begin { if we have a valid bookmark, use it } if FDataSource.DataSet.BookmarkValid(FBookmark) then FDataSource.DataSet.GotoBookmark(FBookmark); { I'm not sure, if FreeBokmark can handle nil pointers - so to be safe } if FBookmark <> nil then FDataSource.DataSet.FreeBookmark(FBookmark); end else FDataSource.DataSet.Active := false; { don't forget this one! } FDataSource.DataSet.EnableControls; inherited; end; function TDataSourceEnumerator.GetCurrent: Variant; begin { We simply return the CurrentRec property of the DataSet, which is exposed due to the class helper. } Result := TgmClientDataset(FDataSource.DataSet).CurrentRec; end; function TDataSourceEnumerator.MoveNext: Boolean; begin { Check if we have to move to the first record, which has been done already during Create. } if FMoveToFirst then FMoveToFirst := false else FDataSource.DataSet.Next; Result := not FDataSource.DataSet.EoF; end; function TgmDatasource.GetCurrentRec: Variant; begin { return one of our custom variants } Result := VarDataRecordCreate(Self.DataSet); end; function TgmDatasource.GetEnumerator: TDataSourceEnumerator; begin { return a new enumerator } Result := TDataSourceEnumerator.Create(Self); end; function TgmDatasource.FieldByName(const FieldName: string): TField; begin result := Dataset.FieldByName(FieldName); end; function TgmDatasource.GetgmDataset: TgmClientDataset; begin if Dataset<>nil then result := Dataset as TgmClientDataset else raise Exception.Create(format('Datasource %s: Dataset non assegnato!',[Name])); end; function TgmDatasource.GetFDMemTable: TgmFDMemTable; begin if Dataset<>nil then result := Dataset as TgmFDMemTable else raise Exception.Create(format('Datasource %s: Dataset non assegnato!',[Name])); end; { function TgmDatasource.GetgmDataset: TgmClientDataset; begin if Dataset<>nil then if Dataset is TgmFDMemTable then result := TgmFDMemTable(Dataset).refDataSet else result := Dataset as TgmClientDataset else raise Exception.Create(format('Datasource %s: Dataset non assegnato!',[Name])); end; procedure TgmDatasource.SetgmDataset(Value: TgmClientDataset); begin Dataset := Value; end; } initialization { Create our custom variant type, which will be registered automatically. } VarDataRecordType := TVarDataRecordType.Create; finalization { Free our custom variant type. } FreeAndNil(VarDataRecordType); end.
unit MainSettings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, RzShellDialogs; type TFrmSettings = class(TForm) EdtCopyDir: TEdit; EdtMoveDir: TEdit; Label1: TLabel; Label2: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; SelectDirDlg: TRzSelectFolderDialog; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmSettings: TFrmSettings; implementation {$R *.dfm} uses MainForm; procedure TFrmSettings.Button1Click(Sender: TObject); begin // Set the MainForm Variables Accordingly MainForm.CopyDir := EdtCopyDir.Text; MainForm.MoveDir := EdtMoveDir.Text; // Check the contents of EditBoxes Try if System.SysUtils.DirectoryExists (EdtCopyDir.Text) then begin // ShowMessage('Copy To Folder Exists'); Exit; end else ShowMessage('Copy To Folder does not exist' + #13#10 + 'It will be created'); System.SysUtils.ForceDirectories(EdtCopyDir.Text); if System.SysUtils.DirectoryExists (EdtMoveDir.Text) then begin // ShowMessage ('Move To Folder Exists'); Exit; end else ShowMessage('Move To Folder does not exist' + #13#10 + 'It will be created'); System.SysUtils.ForceDirectories(EdtMoveDir.Text); Finally Close; End; end; procedure TFrmSettings.Button2Click(Sender: TObject); begin if SelectDirDlg.Execute then SelectDirDlg.Title := 'Select Copy To Folder'; EdtCopyDir.Text := SelectDirDlg.SelectedPathName; end; procedure TFrmSettings.Button3Click(Sender: TObject); begin if SelectDirDlg.Execute then SelectDirDlg.Title := 'Select Move To Folder'; EdtMoveDir.Text := SelectDirDlg.SelectedPathName; end; procedure TFrmSettings.FormCreate(Sender: TObject); begin // Initilize the Folders EdtCopyDir.Text := MainForm.CopyDir; EdtMoveDir.Text := MainForm.MoveDir; end; end.
Unit ScrVars; {variable handling for ShockScript} Interface Uses ScrMisc, ScrErr, StrnTTT5, Parser, MyLib, TpString, IO; Const maxVars = 50; maxVarLength = 80; Type {record used to keep all variables} {all the variables are strings, each has a name, and a value assigned to it} varType = Record name : array [1..MaxVars] of string[30]; value : array [1..maxVars] of string[maxVarLength]; end; function getvar (st: string): string; function expandVars (st : string) : string; procedure setVars (myvars : string); procedure setVar (name, value: string); var vars : ^varType; implementation (*** GET VARIABLE *********************************************************) function getvar (st: string): string; var i : integer; gottenVar : string; begin gottenVar := ''; st := trim (st); upcaseStr (st); for i := 1 to maxVars do begin if vars^.name [i] = st then begin gottenVar := vars^.value [i]; i := maxVars; end; end; getvar := gottenVar; end; (*** EXPAND VARIABLES *****************************************************) function expandVars (st : string) : string; var i : integer; outputStr : string; origPos : integer; var2add : string; finished, validity : boolean; mymacro, param: string; myResult : real; begin outputStr := ''; If Pos('USER.',Upper(St))>0 Then Begin { record manipulation goes here } End Else for i := 1 to length (st) do begin if st [i] = '%' then begin origPos := i; i := i + 1; if st [i] = '%' then Begin outputStr := outputStr + '%'; {if %% then actually show %} End else if st [i] = '@' then {goodie, we've found an internal macro!} begin macro := ''; param := ''; myResult := 0.0; i := i + 1; while st [i] <> '[' do begin macro := macro + st [i]; i := i + 1; end; i := i + 1; while st [i] <> ']' do begin param := param + st [i]; i := i + 1; end; macro := param; myResult := getExpr (validity); if (validity = false) then tellError (CalcFailed) else outputStr := outputStr + Real_to_Str (myResult, decimals); end else begin finished := false; while (not finished) and (i <= length (st)) do begin i := i + 1; if st [i] = ' ' then begin var2add := getVar (copy (st, origPos+1, i - origPos - 1)); outputStr := outputStr + var2add + ' '; finished := true; end else if st [i] = '%' then begin var2add := getVar (copy (st, origPos+1, i - origPos - 1)); outputStr := outputStr + var2add; finished := true; end; end; if i > length (st) then begin var2add := getVar (copy (st, origPos, length (st)-origPos)); outputStr := outputStr + var2add; i := length (st); end; end; end else outputStr := outputStr + st [i]; end; expandVars := outputStr; end; procedure setVar (name, value: string); var i, emptySlot : integer; foundVar : boolean; begin foundVar := false; for i := 1 to maxVars do if vars^.name [i] = name then begin vars^.value [i] := value; foundVar := true; end; if not foundVar then begin value := expandVars (value); emptySlot := -1; for i := maxVars downto 1 do if vars^.name [i] = '' then emptySlot := i; if emptySlot = -1 then TellError (tooManyVars) else begin vars^.name [emptySlot] := name; vars^.value [emptySlot] := value; end end; end; procedure setVars (myvars : string); var var2set, value : string; i : integer; charSet : CharSetType; emptySlot : integer; begin if myvars = '' then begin println('** Defined variables:'); for i := 1 to maxVars do if vars^.name [i] <> '' then println(' ' + vars^.name [i]+ '='+ vars^.value[i]); end else begin charSet := [' ', '=']; SpecialSplit(myvars, var2set, value, charSet); if value = '' then begin {display specific value of a variable} end else SetVar (var2Set, value); end; end; var i : integer; begin New (vars); for i := 1 to maxVars do begin vars^.name [i] := ''; vars^.value [i] := ''; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.mapping.repository; interface uses Rtti, SysUtils, Generics.Collections, dbcbr.mapping.exceptions; type TRepository = class private FEntitys: TObjectDictionary<TClass, TList<TClass>>; FViews: TObjectDictionary<TClass, TList<TClass>>; FTriggers: TObjectDictionary<TClass, TList<TClass>>; function GetEntity: TEnumerable<TClass>; function GetView: TEnumerable<TClass>; function GetTrigger: TEnumerable<TClass>; protected property EntityList: TObjectDictionary<TClass, TList<TClass>> read FEntitys; property ViewList: TObjectDictionary<TClass, TList<TClass>> read FViews; property TriggerList: TObjectDictionary<TClass, TList<TClass>> read FTriggers; public constructor Create; destructor Destroy; override; property Entitys: TEnumerable<TClass> read GetEntity; property Views: TEnumerable<TClass> read GetView; property Trigger: TEnumerable<TClass> read GetTrigger; end; TMappingRepository = class private FRepository: TRepository; function FindEntity(AClass: TClass): TList<TClass>; public constructor Create(AEntity, AView: TArray<TClass>); destructor Destroy; override; function GetEntity(AClass: TClass): TEnumerable<TClass>; function FindEntityByName(const ClassName: string): TClass; property List: TRepository read FRepository; end; implementation { TMappingRepository } constructor TMappingRepository.Create(AEntity, AView: TArray<TClass>); var LClass: TClass; begin FRepository := TRepository.Create; // Entitys if AEntity <> nil then for LClass in AEntity do if not FRepository.EntityList.ContainsKey(LClass) then FRepository.EntityList.Add(LClass, TList<TClass>.Create); for LClass in FRepository.Entitys do if FRepository.EntityList.ContainsKey(LClass.ClassParent) then FRepository.EntityList[LClass.ClassParent].Add(LClass); // Views if AView <> nil then for LClass in AView do if not FRepository.ViewList.ContainsKey(LClass) then FRepository.ViewList.Add(LClass, TList<TClass>.Create); for LClass in FRepository.Views do if FRepository.ViewList.ContainsKey(LClass.ClassParent) then FRepository.ViewList[LClass.ClassParent].Add(LClass); end; destructor TMappingRepository.Destroy; begin FRepository.Free; inherited; end; function TMappingRepository.FindEntityByName(const ClassName: string): TClass; var LClass: TClass; begin Result := nil; for LClass in List.Entitys do if SameText(LClass.ClassName, ClassName) then Exit(LClass); end; function TMappingRepository.FindEntity(AClass: TClass): TList<TClass>; var LClass: TClass; LListClass: TList<TClass>; begin Result := TList<TClass>.Create; Result.AddRange(GetEntity(AClass)); for LClass in GetEntity(AClass) do begin LListClass := FindEntity(LClass); try Result.AddRange(LListClass); finally LListClass.Free; end; end; end; function TMappingRepository.GetEntity(AClass: TClass): TEnumerable<TClass>; begin if not FRepository.EntityList.ContainsKey(AClass) then EClassNotRegistered.Create(AClass); Result := FRepository.EntityList[AClass]; end; { TRepository } constructor TRepository.Create; begin FEntitys := TObjectDictionary<TClass, TList<TClass>>.Create([doOwnsValues]); FViews := TObjectDictionary<TClass, TList<TClass>>.Create([doOwnsValues]); end; destructor TRepository.Destroy; begin FEntitys.Free; FViews.Free; inherited; end; function TRepository.GetEntity: TEnumerable<TClass>; begin Result := FEntitys.Keys; end; function TRepository.GetTrigger: TEnumerable<TClass>; begin Result := FTriggers.Keys; end; function TRepository.GetView: TEnumerable<TClass>; begin Result := FViews.Keys; end; end.
unit KAddWord; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ActnList, CoreDescription; type TfrmAddWord = class(TForm) GroupBox1: TGroupBox; Panel1: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; actnLst: TActionList; actnSave: TAction; GroupBox2: TGroupBox; cbxDicts: TComboBox; SpeedButton1: TSpeedButton; actnAddDict: TAction; GroupBox3: TGroupBox; mmComment: TMemo; GroupBox4: TGroupBox; SpeedButton2: TSpeedButton; cbxAllRoots: TComboBox; edtName: TEdit; pnl: TPanel; BitBtn3: TBitBtn; actnSaveAndNew: TAction; procedure actnSaveExecute(Sender: TObject); procedure cbxDictsChange(Sender: TObject); procedure actnAddDictExecute(Sender: TObject); procedure cbxAllRootsChange(Sender: TObject); procedure actnSaveAndNewExecute(Sender: TObject); private FActiveDict: TDictionary; FActiveWord: TDictionaryWord; FActiveRoot: TRoot; public property ActiveDict: TDictionary read FActiveDict write FActiveDict; property ActiveRoot: TRoot read FActiveRoot write FActiveRoot; property ActiveWord: TDictionaryWord read FActiveWord write FActiveWord; procedure Clear; procedure Reload; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmAddWord: TfrmAddWord; implementation uses Facade, KDictDescriptions, BaseObjects; {$R *.dfm} { TForm1 } constructor TfrmAddWord.Create(AOwner: TComponent); begin inherited; end; destructor TfrmAddWord.Destroy; begin inherited; end; procedure TfrmAddWord.actnSaveExecute(Sender: TObject); var r: TRoot; begin if (trim(edtName.Text) <> '') and (trim(edtName.Text) <> '<Введите значение>') then if (trim(cbxAllRoots.Text) <> '') then begin // добавляем новый корень ActiveRoot := ActiveDict.Roots.GetItemByName(trim(cbxAllRoots.Text)) as TRoot; if not Assigned(ActiveRoot) then begin r := TRoot.Create(ActiveDict.Roots); r.Name := AnsiLowerCase(trim(cbxAllRoots.Text)); ActiveDict.Roots.Add(r, false, false); r.Update; FActiveRoot := r; end; if not Assigned(FActiveWord) then FActiveWord := TDictionaryWord.Create(FActiveRoot.Words); FActiveWord.Name := AnsiLowerCase(trim(edtName.Text)); FActiveWord.Comment := trim (mmComment.Text); if not Assigned (FActiveRoot.Words.GetItemByName(AnsiLowerCase(trim(edtName.Text)))) then begin FActiveRoot.Words.Add(FActiveWord, false, false); FActiveWord.Update; end; end else MessageBox(0, 'Не указан корень слова.', 'Ошибка', MB_APPLMODAL + MB_OK + MB_ICONSTOP) else MessageBox(0, 'Не указано значение слова.', 'Ошибка', MB_APPLMODAL + MB_OK + MB_ICONSTOP) end; procedure TfrmAddWord.cbxDictsChange(Sender: TObject); begin if cbxDicts.ItemIndex > -1 then begin FActiveDict := cbxDicts.Items.Objects[cbxDicts.ItemIndex] as TDictionary; FActiveDict.Roots.MakeList(cbxAllRoots.Items); end; end; procedure TfrmAddWord.Clear; begin cbxDicts.ItemIndex := 0; FActiveDict := cbxDicts.Items.Objects[cbxDicts.ItemIndex] as TDictionary; FActiveDict.Roots.MakeList(cbxAllRoots.Items); edtName.Text := '<Введите значение>'; mmComment.Clear; end; procedure TfrmAddWord.actnAddDictExecute(Sender: TObject); begin frmDicts := TfrmDicts.Create(Self); frmDicts.frmAllDicts.GUIAdapter.Add; frmDicts.ShowModal; (TMainFacade.GetInstance as TMainFacade).Dicts.MakeList(cbxDicts.Items); frmDicts.Free; end; procedure TfrmAddWord.Reload; begin (TMainFacade.GetInstance as TMainFacade).Dicts.MakeList(cbxDicts); if Assigned (FActiveDict) then begin cbxDicts.ItemIndex := cbxDicts.Items.IndexOfObject(FActiveDict); FActiveDict.Roots.MakeList(cbxAllRoots.Items, true, true); end else cbxDicts.ItemIndex := -1; if Assigned (FActiveWord) then begin edtName.Text := FActiveWord.Name; mmComment.Text := trim(FActiveWord.Comment); cbxAllRoots.ItemIndex := cbxAllRoots.Items.IndexOfObject(FActiveWord.Owner); end else edtName.Text := '<Введите значение>'; end; procedure TfrmAddWord.cbxAllRootsChange(Sender: TObject); begin if cbxAllRoots.ItemIndex > -1 then begin FActiveRoot := cbxAllRoots.Items.Objects[cbxAllRoots.ItemIndex] as TRoot; if (trim(edtName.Text) = '') or (trim(edtName.Text) = '<Введите значение>') then edtName.Text := FActiveRoot.Name; end else FActiveRoot := nil; end; procedure TfrmAddWord.actnSaveAndNewExecute(Sender: TObject); begin actnSave.Execute; ActiveWord := nil; frmAddWord.edtName.Text := ActiveRoot.Name; end; end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} { This file is based on base64.pp in the Free Component Library (FCL) Copyright (c) 1999-2000 by Michael Van Canneyt and Florian Klaempfl base64 encoder & decoder (c) 1999 Sebastian Guenther Simplified for use without the FCL by Ian Hickson, 2012 The source code of the Free Pascal Runtime Libraries and packages, and thus this derivative work, are distributed under the Library GNU General Public License (see the file COPYING.LGPL) with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. **********************************************************************} unit base64encoder; interface function Base64(const S: RawByteString): RawByteString; implementation const EncodingTable: String[64] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function Base64(const S: RawByteString): RawByteString; var Index, Offset: Cardinal; begin Result := ''; Index := 1; while (Index+2 <= Length(S)) do begin Offset := Length(Result); {BOGUS Warning: Type size mismatch, possible loss of data / range check error} SetLength(Result, Length(Result)+4); Result[Offset+1] := EncodingTable[1+(Ord(S[Index]) shr 2)]; Result[Offset+2] := EncodingTable[1+((Ord(S[Index]) and 3) shl 4 or (Ord(S[Index+1]) shr 4))]; Result[Offset+3] := EncodingTable[1+((Ord(S[Index+1]) and 15) shl 2 or (Ord(S[Index+2]) shr 6))]; Result[Offset+4] := EncodingTable[1+(Ord(S[Index+2]) and 63)]; Inc(Index, 3); end; if (Index <= Length(S)) then begin Assert(Length(S) - Index <= 2); Offset := Length(Result); {BOGUS Warning: Type size mismatch, possible loss of data / range check error} SetLength(Result, Length(Result)+4); case (Length(S)-Index) of 0: begin Result[Offset+1] := EncodingTable[1+(Ord(S[Index]) shr 2)]; Result[Offset+2] := EncodingTable[1+((Ord(S[Index]) and 3) shl 4)]; Result[Offset+3] := '='; Result[Offset+4] := '='; end; 1: begin Result[Offset+1] := EncodingTable[1+(Ord(S[Index]) shr 2)]; Result[Offset+2] := EncodingTable[1+((Ord(S[Index]) and 3) shl 4 or (Ord(S[Index+1]) shr 4))]; Result[Offset+3] := EncodingTable[1+((Ord(S[Index+1]) and 15) shl 2)]; Result[Offset+4] := '='; end; end; end; end; end.
unit frmSelectionlistunit; {$MODE Delphi} interface uses LCLIntf, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, LResources, betterControls; type { TfrmSelectionList } TSelectionToTextEvent=function(index: integer; listText: string): string of object; TfrmSelectionList = class(TForm) Edit1: TEdit; ListBox1: TListBox; Panel1: TPanel; btnOK: TButton; Label1: TLabel; procedure Edit1Change(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: char); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure ListBox1DblClick(Sender: TObject); procedure ListBox1SelectionChange(Sender: TObject; User: boolean); private { Private declarations } fcustomInput: boolean; fSelectionToText: TSelectionToTextEvent; fsearchbox: boolean; originalList: TStringlist; procedure setsearchbox(state: boolean); procedure setCustomInput(state: boolean); function getSelectedIndex: integer; procedure setSelectedIndex(i: integer); function getItem(index: integer): string; function getSelection: string; public { Public declarations } constructor create(AOwner: TComponent; functionList: TStrings); overload; property itemindex: integer read getselectedindex write setSelectedIndex; property items[index: integer]: string read getItem; property selected: string read getSelection; property searchbox: boolean read fsearchbox write setSearchBox; property customInput: boolean read fcustomInput write setCustomInput; property SelectionToText: TSelectionToTextEvent read fSelectionToText write fSelectionToText; end; function ShowSelectionList(owner: TComponent; title, caption: string; list: TStrings; var output: string; AllowCustomInput: boolean=false; SelectionToText: TSelectionToTextEvent=nil; formname: string=''): integer; implementation uses math, CEFuncProc; function ShowSelectionList(owner: TComponent; title, caption: string; list: TStrings; var output: string; AllowCustomInput: boolean=false; SelectionToText: TSelectionToTextEvent=nil; formname: string=''): integer; var sl: TfrmSelectionList; begin sl:=TfrmSelectionList.create(owner, list); sl.caption:=title; sl.label1.Caption:=caption; if formname<>'' then sl.name:=formname; sl.searchbox:=true; sl.customInput:=AllowCustomInput; sl.SelectionToText:=SelectionToText; if output<>'' then sl.edit1.Text:=output; result:=-1; if sl.ShowModal=mrOK then begin result:=sl.ListBox1.ItemIndex; if AllowCustomInput then output:=sl.Edit1.text else begin if result<>-1 then output:=sl.ListBox1.Items[result]; end; if result<>-1 then result:=list.IndexOf(output); end; freeandnil(sl); end; constructor TfrmSelectionList.create(AOwner: TComponent; functionList: TStrings); begin inherited create(AOwner); if functionList<>nil then begin listbox1.Items.AddStrings(functionlist); originallist:=tstringlist.Create; originallist.AddStrings(functionlist); end; clientwidth:=max(clientwidth, canvas.TextWidth('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')); end; function tfrmSelectionList.getSelection: string; begin result:=''; if fcustomInput then result:=edit1.text else begin if listbox1.itemindex<>-1 then result:=listbox1.items[listbox1.itemindex]; end; end; function TfrmSelectionList.getItem(index: integer):string; begin if (index<0) or (index>=listbox1.Count) then begin result:=''; exit; end else result:=listbox1.Items[index]; end; function TfrmSelectionList.getSelectedIndex: integer; begin result:=listbox1.ItemIndex; end; procedure tfrmselectionlist.setSelectedIndex(i: integer); begin if i<listbox1.items.count then listbox1.itemindex:=i; end; procedure TfrmSelectionList.ListBox1DblClick(Sender: TObject); begin if (listbox1.itemindex=-1) and (listbox1.items.count>0) then listbox1.itemindex:=0; if customInput or (listbox1.itemindex<>-1) then modalresult:=mrok; end; procedure TfrmSelectionList.Edit1KeyPress(Sender: TObject; var Key: char); begin listbox1.OnSelectionChange:=nil; listbox1.ItemIndex:=-1; listbox1.OnSelectionChange:=ListBox1SelectionChange; end; procedure TfrmSelectionList.FormCreate(Sender: TObject); begin end; procedure TfrmSelectionList.FormDestroy(Sender: TObject); begin SaveFormPosition(self); end; procedure TfrmSelectionList.FormShow(Sender: TObject); begin if fsearchbox then edit1.SetFocus; if listbox1.height<listbox1.ItemHeight*4 then height:=height+(listbox1.ItemHeight*4)-listbox1.height; LoadFormPosition(self); end; procedure TfrmSelectionList.Edit1Change(Sender: TObject); var i: integer; s: integer; begin if edit1.Focused then begin listbox1.OnSelectionChange:=nil; if edit1.text='' then begin listbox1.Items.Text:=originalList.Text; exit; end; listbox1.Items.BeginUpdate; listbox1.Items.Clear; s:=-1; for i:=0 to originalList.Count-1 do begin if pos(lowercase(edit1.text),lowercase(originallist[i]))>0 then begin listbox1.items.add(originallist[i]); if lowercase(originallist[i])=lowercase(edit1.text) then s:=listbox1.items.Count-1; end; end; listbox1.Items.EndUpdate; listbox1.ItemIndex:=s; btnok.enabled:=customInput or (listbox1.itemindex<>-1); listbox1.OnSelectionChange:=ListBox1SelectionChange; end; end; procedure TfrmSelectionList.ListBox1SelectionChange(Sender: TObject; User: boolean); begin if edit1.Focused then exit; edit1.OnChange:=nil; if listbox1.ItemIndex>=0 then begin if assigned(fSelectionToText) then begin edit1.text:=fSelectionToText(originalList.indexof(listbox1.Items[listbox1.ItemIndex]), listbox1.Items[listbox1.ItemIndex]); end else edit1.text:=listbox1.Items[listbox1.ItemIndex]; end; edit1.OnChange:=Edit1Change; btnok.enabled:=customInput or (listbox1.itemindex<>-1); end; procedure TfrmSelectionList.setsearchbox(state: boolean); begin edit1.Visible:=state; fsearchbox:=state; end; procedure TfrmSelectionList.setCustomInput(state: boolean); begin searchbox:=true; fcustomInput:=state; end; initialization {$i frmselectionlistunit.lrs} end.
unit uSimpleExample; interface type // How would you make this class open for extension? TVehicle = class procedure Go; virtual; procedure Stop; virtual; procedure Refuel; virtual; end; implementation { TVehicle } procedure TVehicle.Go; begin WriteLn('Go'); end; procedure TVehicle.Refuel; begin WriteLn('Refuel'); end; procedure TVehicle.Stop; begin WriteLn('Stop'); end; end.
unit CertStore; interface type HCkCertStore = Pointer; HCkCert = Pointer; HCkByteData = Pointer; HCkString = Pointer; function CkCertStore_Create: HCkCertStore; stdcall; procedure CkCertStore_Dispose(handle: HCkCertStore); stdcall; function CkCertStore_getAvoidWindowsPkAccess(objHandle: HCkCertStore): wordbool; stdcall; procedure CkCertStore_putAvoidWindowsPkAccess(objHandle: HCkCertStore; newPropVal: wordbool); stdcall; procedure CkCertStore_getDebugLogFilePath(objHandle: HCkCertStore; outPropVal: HCkString); stdcall; procedure CkCertStore_putDebugLogFilePath(objHandle: HCkCertStore; newPropVal: PWideChar); stdcall; function CkCertStore__debugLogFilePath(objHandle: HCkCertStore): PWideChar; stdcall; procedure CkCertStore_getLastErrorHtml(objHandle: HCkCertStore; outPropVal: HCkString); stdcall; function CkCertStore__lastErrorHtml(objHandle: HCkCertStore): PWideChar; stdcall; procedure CkCertStore_getLastErrorText(objHandle: HCkCertStore; outPropVal: HCkString); stdcall; function CkCertStore__lastErrorText(objHandle: HCkCertStore): PWideChar; stdcall; procedure CkCertStore_getLastErrorXml(objHandle: HCkCertStore; outPropVal: HCkString); stdcall; function CkCertStore__lastErrorXml(objHandle: HCkCertStore): PWideChar; stdcall; function CkCertStore_getLastMethodSuccess(objHandle: HCkCertStore): wordbool; stdcall; procedure CkCertStore_putLastMethodSuccess(objHandle: HCkCertStore; newPropVal: wordbool); stdcall; function CkCertStore_getNumCertificates(objHandle: HCkCertStore): Integer; stdcall; function CkCertStore_getNumEmailCerts(objHandle: HCkCertStore): Integer; stdcall; function CkCertStore_getVerboseLogging(objHandle: HCkCertStore): wordbool; stdcall; procedure CkCertStore_putVerboseLogging(objHandle: HCkCertStore; newPropVal: wordbool); stdcall; procedure CkCertStore_getVersion(objHandle: HCkCertStore; outPropVal: HCkString); stdcall; function CkCertStore__version(objHandle: HCkCertStore): PWideChar; stdcall; function CkCertStore_AddCertificate(objHandle: HCkCertStore; cert: HCkCert): wordbool; stdcall; function CkCertStore_CreateFileStore(objHandle: HCkCertStore; filename: PWideChar): wordbool; stdcall; function CkCertStore_CreateMemoryStore(objHandle: HCkCertStore): wordbool; stdcall; function CkCertStore_CreateRegistryStore(objHandle: HCkCertStore; regRoot: PWideChar; regPath: PWideChar): wordbool; stdcall; function CkCertStore_FindCertByRfc822Name(objHandle: HCkCertStore; name: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySerial(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySha1Thumbprint(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySubject(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySubjectCN(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySubjectE(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertBySubjectO(objHandle: HCkCertStore; str: PWideChar): HCkCert; stdcall; function CkCertStore_FindCertForEmail(objHandle: HCkCertStore; emailAddress: PWideChar): HCkCert; stdcall; function CkCertStore_GetCertificate(objHandle: HCkCertStore; index: Integer): HCkCert; stdcall; function CkCertStore_GetEmailCert(objHandle: HCkCertStore; index: Integer): HCkCert; stdcall; function CkCertStore_LoadPemFile(objHandle: HCkCertStore; pemPath: PWideChar): wordbool; stdcall; function CkCertStore_LoadPemStr(objHandle: HCkCertStore; pemString: PWideChar): wordbool; stdcall; function CkCertStore_LoadPfxData(objHandle: HCkCertStore; pfxData: HCkByteData; password: PWideChar): wordbool; stdcall; function CkCertStore_LoadPfxData2(objHandle: HCkCertStore; pByteData: pbyte; szByteData: LongWord; password: PWideChar): wordbool; stdcall; function CkCertStore_LoadPfxFile(objHandle: HCkCertStore; pfxFilename: PWideChar; password: PWideChar): wordbool; stdcall; function CkCertStore_OpenCurrentUserStore(objHandle: HCkCertStore; readOnly: wordbool): wordbool; stdcall; function CkCertStore_OpenFileStore(objHandle: HCkCertStore; filename: PWideChar; readOnly: wordbool): wordbool; stdcall; function CkCertStore_OpenLocalSystemStore(objHandle: HCkCertStore; readOnly: wordbool): wordbool; stdcall; function CkCertStore_OpenRegistryStore(objHandle: HCkCertStore; regRoot: PWideChar; regPath: PWideChar; readOnly: wordbool): wordbool; stdcall; function CkCertStore_OpenWindowsStore(objHandle: HCkCertStore; storeLocation: PWideChar; storeName: PWideChar; readOnly: wordbool): wordbool; stdcall; function CkCertStore_RemoveCertificate(objHandle: HCkCertStore; cert: HCkCert): wordbool; stdcall; function CkCertStore_SaveLastError(objHandle: HCkCertStore; path: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkCertStore_Create; external DLLName; procedure CkCertStore_Dispose; external DLLName; function CkCertStore_getAvoidWindowsPkAccess; external DLLName; procedure CkCertStore_putAvoidWindowsPkAccess; external DLLName; procedure CkCertStore_getDebugLogFilePath; external DLLName; procedure CkCertStore_putDebugLogFilePath; external DLLName; function CkCertStore__debugLogFilePath; external DLLName; procedure CkCertStore_getLastErrorHtml; external DLLName; function CkCertStore__lastErrorHtml; external DLLName; procedure CkCertStore_getLastErrorText; external DLLName; function CkCertStore__lastErrorText; external DLLName; procedure CkCertStore_getLastErrorXml; external DLLName; function CkCertStore__lastErrorXml; external DLLName; function CkCertStore_getLastMethodSuccess; external DLLName; procedure CkCertStore_putLastMethodSuccess; external DLLName; function CkCertStore_getNumCertificates; external DLLName; function CkCertStore_getNumEmailCerts; external DLLName; function CkCertStore_getVerboseLogging; external DLLName; procedure CkCertStore_putVerboseLogging; external DLLName; procedure CkCertStore_getVersion; external DLLName; function CkCertStore__version; external DLLName; function CkCertStore_AddCertificate; external DLLName; function CkCertStore_CreateFileStore; external DLLName; function CkCertStore_CreateMemoryStore; external DLLName; function CkCertStore_CreateRegistryStore; external DLLName; function CkCertStore_FindCertByRfc822Name; external DLLName; function CkCertStore_FindCertBySerial; external DLLName; function CkCertStore_FindCertBySha1Thumbprint; external DLLName; function CkCertStore_FindCertBySubject; external DLLName; function CkCertStore_FindCertBySubjectCN; external DLLName; function CkCertStore_FindCertBySubjectE; external DLLName; function CkCertStore_FindCertBySubjectO; external DLLName; function CkCertStore_FindCertForEmail; external DLLName; function CkCertStore_GetCertificate; external DLLName; function CkCertStore_GetEmailCert; external DLLName; function CkCertStore_LoadPemFile; external DLLName; function CkCertStore_LoadPemStr; external DLLName; function CkCertStore_LoadPfxData; external DLLName; function CkCertStore_LoadPfxData2; external DLLName; function CkCertStore_LoadPfxFile; external DLLName; function CkCertStore_OpenCurrentUserStore; external DLLName; function CkCertStore_OpenFileStore; external DLLName; function CkCertStore_OpenLocalSystemStore; external DLLName; function CkCertStore_OpenRegistryStore; external DLLName; function CkCertStore_OpenWindowsStore; external DLLName; function CkCertStore_RemoveCertificate; external DLLName; function CkCertStore_SaveLastError; external DLLName; end.
unit ControlListHelper; interface uses WinApi.Windows, WinApi.Messages, System.Math, System.Classes, System.Generics.Collections, Vcl.ControlList; type TControlListHelper = class helper for TCustomControlList public function _Columns : Integer; function _Rows : Integer; function _ItemAtPos(X, Y: Integer; iv: TDictionary<Integer, TRect>): Integer; function _GetItemRect(AIndex : Integer): TRect; procedure _PageDown; procedure _PageUp; procedure _PageLeft; procedure _PageRight; procedure _Home; procedure _End; end; implementation { TControlListHelper } /// <summary> /// For gesture usage ??? /// </summary> procedure TControlListHelper._PageDown; begin SendMessage(Handle, WM_KEYDOWN, VK_NEXT, 0); end; procedure TControlListHelper._PageUp; begin SendMessage(Handle, WM_KEYDOWN, VK_PRIOR, 0); end; procedure TControlListHelper._PageLeft; begin SendMessage(Handle, WM_KEYDOWN, VK_LEFT, 0); end; procedure TControlListHelper._PageRight; begin SendMessage(Handle, WM_KEYDOWN, VK_RIGHT, 0); end; procedure TControlListHelper._Home; begin SendMessage(Handle, WM_KEYDOWN, VK_HOME, 0); end; procedure TControlListHelper._End; begin SendMessage(Handle, WM_KEYDOWN, VK_END, 0); end; /// <summary> /// Get the rect of the drawed item on the TControlList /// </summary> /// <param name="AIndex"> /// Index of the item /// </param> /// <returns>a TRect /// </returns> function TControlListHelper._GetItemRect(AIndex : Integer): TRect; begin Result := TRect.Empty; case InternalColumnLayout of cltSingle: begin Result.Top := ItemHeight * AIndex; Result.Height := ItemHeight; Result.Width := IfThen(ItemWidth = 0, Width - 28, ItemWidth); end; cltMultiTopToBottom: begin var Cols : integer :=_Columns; Result.Left := (AIndex mod Cols) * ItemWidth; Result.Top := ((AIndex div Cols) * ItemHeight); Result.Height := ItemHeight; Result.Width := ItemWidth; end; cltMultiLeftToRight: begin var Rows : integer :=_Rows; Result.Left := (AIndex div Rows) * ItemWidth; Result.Top := (AIndex mod Rows) * ItemHeight; Result.Height := ItemHeight; Result.Width := ItemWidth; end; end; end; /// <summary> /// Get index of the TControlList item /// </summary> /// <param name="X"> /// X coordinate of the mouse /// </param> /// <param name="Y"> /// Y coordinate of the mouse /// </param> /// <param name="iv"> /// Items visible on the TControlList /// a TDictionary<Integer,TRect> to implement during OnDrawItem or AfterDrawItem event /// </param> /// <remarks> /// /// </remarks> /// <returns>Item index; -1 if invalid /// </returns> function TControlListHelper._ItemAtPos(X, Y: Integer; iv: TDictionary<Integer, TRect>): Integer; var I: Integer; ofHorz, ofVert: Integer; ARect: TRect; begin ofHorz := GetScrollPos(Handle, SB_HORZ); ofVert := GetScrollPos(Handle, SB_VERT); Result := -1; for I := 0 to ItemCount - 1 do begin if iv.TryGetValue(I, ARect) then begin if ARect.Contains(TPoint.Create(X + ofHorz, Y + ofVert)) then exit(I); end; end; end; /// <summary> /// Get number of columns of the TControlList /// </summary> /// <returns>Number of columns /// </returns> function TControlListHelper._Columns: Integer; begin case InternalColumnLayout of cltSingle : result:=1; cltMultiTopToBottom : result:=ClientWidth div ItemWidth; cltMultiLeftToRight : begin var nr : integer := _Rows; result:=ItemCount div nr; if (ItemCount mod nr)>0 then inc(Result); end; end; end; /// <summary> /// Get number of rows of the TControlList /// </summary> /// <returns>Number of rows /// </returns> function TControlListHelper._Rows: Integer; begin result:=1; case InternalColumnLayout of cltSingle : result:=ItemCount; cltMultiTopToBottom : begin var nc : integer := _Columns; result:=ItemCount div nc; if (ItemCount mod nc)>0 then inc(result); end; cltMultiLeftToRight : result:=ClientHeight div ItemHeight; end; end; end.
unit uInterfaces; interface type //Base interface for all objects IOSManAll = interface //String id of object. By default (in TOSManObject) returns "ModuleName.ClassName.InstanceAddress" function toString(): WideString; // Class name of object function getClassName(): WideString; end; //logger interface ILogger = interface(IOSManAll) procedure log(const logMessage: WideString); end; //Read only byte stream interface IInputStream = interface(IOSManAll) //maxBufSize: read buffer size //Readed data in zero-based one dimensional SafeArray of bytes (VT_ARRAY | VT_UI1) function read(const maxBufSize: integer): OleVariant; function get_eos(): WordBool; //"true" if end of stream reached, "false" otherwise property eos: WordBool read get_eos; end; IResourceInputStream = interface(IInputStream) //URL: String representation of resource address (web-address, local FS file name, etc). procedure open(const URL: WideString); end; //Interface for read transform filters (decompressors, parsers, decrypters, etc). ITransformInputStream = interface(IInputStream) //input stream for transformation procedure setInputStream(const inStream: OleVariant); end; //Write only byte stream interface IOutputStream = interface(IOSManAll) //Write data from zero-based one dimensional SafeArray of bytes (VT_ARRAY | VT_UI1) procedure write(const aBuf: OleVariant); procedure set_eos(const aEOS: WordBool); function get_eos: WordBool; //write "true" if all data stored and stream should to release system resources //once set to "true" no write oprerations allowed on stream property eos: WordBool read get_eos write set_eos; end; //Interface for output transform filters (compressors, exporters, ecrypters, etc). ITransformOutputStream = interface(IOutputStream) //output IOutputStream for transformed data procedure setOutputStream(const outStream: OleVariant); end; IResourceOutputStream = interface(IOutputStream) //URL: String representation of resource address (web-address, local FS file name, etc). procedure open(const URL: WideString); end; //Interface for Objects that stores results to IMap IMapWriter = interface(IOSManAll) //Map for storing results procedure setOutputMap(const outMap: OleVariant); end; IMapReader = interface(IOSManAll) //Map for storing results procedure setInputMap(const inMap: OleVariant); end; //interface for list of (key,value) string pairs. IKeyList = interface(IOSManAll) //delete item by key. If no such key, no actions performed procedure deleteByKey(const key: WideString); //delete item by index in list. If index out of bounds then exception raised procedure deleteById(const id: integer); //get all keys in list. Result is SafeArray of string variants. //Keys and Values interlived - [0]=key[0],[1]=value[0]...[10]=key[5],[11]=value[5],... function getAll: OleVariant; //replaces old list with new one. All old items deleted, new items added //kvArray interlived as in getAll() method procedure setAll(const kvArray: OleVariant); //returns true if key exists in list. function hasKey(const key: WideString): WordBool; //returns value assiciated with key. If no such key empty string('') returned function getByKey(const key: WideString): WideString; //add or replace key-value pair procedure setByKey(const key: WideString; const value: WideString); //returns value by index. If index out of bounds [0..count-1] exception raised function getValue(const id: integer): WideString; //sets value by index. If index out of bounds [0..count-1] exception raised procedure setValue(const id: integer; const value: WideString); //returns key by index. If index out of bounds [0..count-1] exception raised function getKey(const id: integer): WideString; //sets key by index. If index out of bounds [0..count-1] exception raised procedure setKey(const id: integer; const key: WideString); function get_count: integer; //returns number of pairs in list property count: integer read get_count; end; //List of references to objects. Used in IRelation.members IRefList = interface(IOSManAll) //idx - index in list. If idx out of bounds exception raised //refType - type of referenced object. One of 'node','way','relation' //refID - OSM ID of referenced object //refRrole - role in relation procedure getByIdx(idx: integer; out refType: WideString; out refId: Int64; out refRole: WideString); procedure setByIdx(idx: integer; const refType: WideString; refId: Int64; const refRole: WideString); procedure deleteByIdx(idx: integer); //returns interlived SafeArray of variants //[0]-refType[0](string), [1]-refId[0](int64), [2]-refRole[0](string), [3]-refType[1].... function getAll: OleVariant; //replace old list with new one. Deletes all old items then adds new //See getAll() result description for refTypesIdsRoles layout procedure setAll(refTypesIdsRoles: OleVariant); //idx - if idx => count then item appended to end of list, if idx<0 exception raised procedure insertBefore(idx: integer; const refType: WideString; refId: Int64; const refRole: WideString); function get_count: integer; //returns number of list items property count: integer read get_count; end; //base interface for all map objects (nodes, ways, relations) IMapObject = interface(IOSManAll) function get_tags: OleVariant; procedure set_tags(const newTags: OleVariant); function get_id: Int64; procedure set_id(const newId: Int64); function get_version: integer; procedure set_version(const newVersion: integer); function get_userId: integer; procedure set_userId(const newUserId: integer); function get_userName: WideString; procedure set_userName(const newUserName: WideString); function get_changeset: Int64; procedure set_changeset(const newChangeset: Int64); function get_timestamp: WideString; procedure set_timestamp(const newTimeStamp: WideString); //tags, associated with object. Supports IKeyList property tags: OleVariant read get_tags write set_tags; //OSM object ID. property id: Int64 read get_id write set_id; //OSM object version property version: integer read get_version write set_version; //OSM object userID property userId: integer read get_userId write set_userId; //OSM object userName property userName: WideString read get_userName write set_userName; //OSM object changeset property changeset: Int64 read get_changeset write set_changeset; //OSM object timestamp. Format "yyyy-mm-ddThh:nn:ssZ" like in OSM files property timestamp: WideString read get_timestamp write set_timestamp; end; INode = interface(IMapObject) function get_lat: Double; procedure set_lat(const value: Double); function get_lon: Double; procedure set_lon(const value: Double); //node latitude. If out of bounds [-91...+91] exception raised property lat: Double read get_lat write set_lat; //node longitude. If out of bounds [-181...181] exception raised property lon: Double read get_lon write set_lon; end; IWay = interface(IMapObject) function get_nodes: OleVariant; procedure set_nodes(const newNodes: OleVariant); //array of node OSM IDs. SafeArray of Int64 variants property nodes: OleVariant read get_nodes write set_nodes; end; IRelation = interface(IMapObject) function get_members: OleVariant; procedure set_members(const newMembers: OleVariant); //list of relation members. Supports IRefList property members: OleVariant read get_members write set_members; end; //filter called before put objects into strorage. //if result of filter function is true, then object stored, // otherwise object ignored. //onPutObject called before any other function. // If onPutObject returns false, then other filter functions(onPutNode, etc.) // not called for this object. IMapOnPutFilter = interface function onPutObject(const mapObject: OleVariant): boolean; function onPutNode(const node: OleVariant): boolean; function onPutWay(const way: OleVariant): boolean; function onPutRealtion(const relation: OleVariant): boolean; end; //responce for http-requests //Use IInputStream to read responce body. IHTTPResponce = interface(IInputStream) //get state of operation. // 0 - waiting for connect // 1 - connected // 2 - sending data to server // 3 - receiving data from server // 4 - transfer complete. Success/fail determined by getStatus() call. function getState(): integer; //get HTTP-status. It implemented as follows: // 1.If connection broken or not established in state < 3 then status '503 Service Unavailable' set; // 2.If connection broken in state=3 then status '504 Gateway Time-out' set; // 3.If state=3 (transfer operation pending) then status '206 Partial Content' set; // 4.If state=4 then status set to server-returned status function getStatus(): integer; //wait for tranfer completition. On function exit all pending // data send/receive completed and connection closed. procedure fetchAll(); end; //HTTP storage for NetMap IHTTPStorage = interface(IOSManAll) //property setters-getters function get_hostName(): WideString; procedure set_hostName(const aName: WideString); function get_timeout(): integer; procedure set_timeout(const aTimeout: integer); function get_maxRetry(): integer; procedure set_maxRetry(const aMaxRetry: integer); //returns IHTTPResponce for request 'method http://hostName/location' and POSTed extraData function send(const method, location, extraData: WideString): OleVariant; //hostname for OSM-API server. Official server is api.openstreetmap.org property hostName: WideString read get_hostName write set_hostName; //timeout for network operations (in ms). By default 20000ms (20 sec) property timeOut: integer read get_timeout write set_timeout; //max retries for connection/DNS requests. By default 3. property maxRetry: integer read get_maxRetry write set_maxRetry; end; //SQL storage for map data IStorage = interface(IOSManAll) function get_dbName(): WideString; procedure set_dbName(const newName: WideString); function get_readOnly(): boolean; procedure set_readOnly(roFlag: boolean); //returns opaque Query object function sqlPrepare(const sqlProc: WideString): OleVariant; //sqlQuery - opaque Query object //paramsNames,paramValues - query parameters. SafeArray of variants. //returns IQueryResult object //It can do batch execution if length(ParamValues)==k*length(paramsNames) and k>=1. //In such case only last resultset returned function sqlExec(const sqlQuery: OleVariant; const paramNames, paramValues: OleVariant): OleVariant; //creates IStoredIdList object function createIdList(): OleVariant; //initialize new storage - create database schema (tables, indexes, triggers...) procedure initSchema(); //set this property before open to use db in readonly mode property readOnly: boolean read get_readOnly write set_readOnly; //database resource locator (file name, server name, etc). property dbName: WideString read get_dbName write set_dbName; end; IStorageUser = interface(IOSManAll) function get_storage: OleVariant; procedure set_storage(const newStorage: OleVariant); //IStorage object property storage: OleVariant read get_storage write set_storage; end; IStoredIdList = interface(IOSManAll) function get_tableName: WideString; //returns true if `id` is in list function isIn(const id: Int64): boolean; //add `id` into list. If `id` already in list do nothing. procedure add(const id: Int64); //removes `id from list. If `id` not in list do nothing. procedure remove(const id: Int64); //read-only temporary table name. Use it in SQL-queries. property tableName: WideString read get_tableName; end; IMap = interface(IStorageUser) //create epmty node function createNode(): IDispatch; //create epmty way function createWay(): IDispatch; //create epmty relation function createRelation(): IDispatch; //store Node into Storage procedure putNode(const aNode: OleVariant); //store Way into Storage procedure putWay(const aWay: OleVariant); //store Relation into Storage procedure putRelation(const aRelation: OleVariant); //store MapObject (Node,Way or Relation) into Store procedure putObject(const aObj: OleVariant); //delete Node and its tags from Storage. Ways and Relations is not updated. procedure deleteNode(const nodeId: Int64); //delete Way, its tags and node-list from Storage. Relations is not updated. procedure deleteWay(const wayId: Int64); //delete Relation, its tags and ref-list from Storage. Parent and child Relations is not updated. procedure deleteRelation(const relationId: Int64); //get node by ID. If no node found returns false function getNode(const id: Int64): OleVariant; //get way by ID. If no way found returns false function getWay(const id: Int64): OleVariant; //get relation by ID. If no relation found returns false function getRelation(const id: Int64): OleVariant; //get nodes with Ids in nodeIdArray. If at least one object not found empty array returned (see OSM API wiki) function getNodes(const nodeIdArray: OleVariant): OleVariant; //get ways with Ids in wayIdArray. If at least one object not found empty array returned (see OSM API wiki) function getWays(const wayIdArray: OleVariant): OleVariant; //get relations with Ids in relationIdArray. If at least one object not found empty array returned (see OSM API wiki) function getRelations(const relationIdArray: OleVariant): OleVariant; //get filtered object set //returns IInputStream of MapObjects //filterOptions - SafeArray of variant in form [0]=OptName1,[1]=OptParam1,..[k]=OptParam[k],[k+1]=OptName2,.... // OptName must starts with ':' characher. //supported options: // :bbox - select only objects within bounding box. If there are several bboxes // specified then objects exported for all this boxes. // Params: // n,e,s,w - four floating values for north, east, south and west bounds // :bpoly - select objects in multipolygon. Objects selected after :bbox // filter passed. If there are several :bpoly specified then objects exported // for all this multipolygons ('concatination'). // Params: // mpoly - bounding IMultiPoly object. // :clipIncompleteWays - delete references to not-exported nodes from way node-list. // By default (without this option) full node-list exported. // Params: none. // :customFilter - user-defined filter. See IMapOnPutFilter interface. // Filter interface can be partially implemented. For not implemented method // <true> result assumed. If there are several :customFilters specified then // filters are called in ascending order. If filter returns <false> then // subsequent filters not called and object not passed (short AND evaluation). // Params: // cFilter - IMapOnPutFilter object. function getObjects(const filterOptions: OleVariant): OleVariant; function get_onPutFilter: OleVariant; procedure set_onPutFilter(const aFilter: OleVariant); //IMapOnPutFilter property onPutFilter: OleVariant read get_onPutFilter write set_onPutFilter; end; //results of query //read function maxBufSize argument is number of rows to read //returns SafeArray of variants in form (r1c1,r1c2,r1c3,...,r99c8,r99c9,r99c10) IQueryResult = interface(IInputStream) //read(n) redefienes read method of IInputStream // returns one-dimentional zero-based array up to n*k Variants. // where k - number of columns returned by query. First element in array is // first column of first result row value, second is second column value, etc.: // [col1_row1,col2_row1,...colk_row1,col1_row2,...colk_row2,....col1_rown,...colk_rown] //returns SafeArray of string variants containing query columns names function getColNames(): OleVariant; end; IAppExec = interface (IOSManAll) //property funcs function get_exitCode():integer; function get_processId():integer; function get_status():integer; //interface definition //terminate application procedure terminate(); //Application exit code. If application not terminated zero returned property exitCode:integer read get_exitCode; //Application Windows ProcessId. property processId:integer read get_processId; //termination status of application. 0 - running, 1 - terminated property status:integer read get_status; end; IGeoTools = interface(IOSManAll) //returns multipolygon Object function createPoly(): OleVariant; //returns distance in meters from node to nodeOrNodes //if nodeOrNodes is single node then distance between this nodes returned //if nodeOrNodes is array of nodes then distance between node and // polyline(polygon boundary) returned. This distance can be less then minimum // distace between nodes! Example: distance(n(1,1),[n(0,0),n(2,0)]) is 1, not 1.41 function distance(const node, nodeOrNodes: OleVariant): Double; //returns IAppExec object. If error occures exception raised function exec(const cmdLine:WideString):OleVariant; //returns array of Nodes of way. //if some objects not found in aMap then exception raised //aMap - source of Nodes and Way //aWayOrWayId - Way object or id of way. function wayToNodeArray(aMap, aWayOrWayId: OleVariant): OleVariant; //returns node rounded to certain bit level. //aBitLevel should be between 2 and 31. //Suitable for mp-format convertion procedure bitRound(aNode: OleVariant; aBitLevel: integer); function utf8to16(const U8:WideString):WideString; end; IMultiPoly = interface(IOSManAll) //add MapObject to polygon. Nodes not allowed, //node-members in Relation are ignored procedure addObject(const aMapObject: OleVariant); //returns true if all relations/way/nodes resolved, false otherwise function resolve(const srcMap: OleVariant): boolean; //IRefList of not resolved references function getNotResolved(): OleVariant; //IRefList of not closed nodes. function getNotClosed(): OleVariant; //returns simple polygons of multipolygon. Result is two arrays of polygons // [OuterPolyArray,InnerPolyArray]. InnerPolyArray can be empty (zero-length) // PolyArray is array of polygons [Poly1,Poly2,Poly3...]. // Each Poly is array of Node objects. Poly1=[P1Node1,P1Node2,...P1NodeN,P1Node1]. function getPolygons():OleVariant; //returns intersection of Poly boundary and NodeArray. //Result is array of arrrays of Node`s. Tag 'osman:note' filled with //'boundary' value for nodes layed on-bound, tags 'osman:node1' and 'osman:node2' //filled with bound nodes ids //If NodeArray and Poly has no intersection zero-length // array [] returned. //New Nodes in result has id=newNodeId,newNodeId-1,...,newNodeId-k //Example: // NodeArray=[n1(0,1) , n2(2,1) , n3(4,1)] // poly=(1,0, id=1) - (3,0, id=2) - (3,2, id=3) - (1,2, id=4) - (1,0, id=1) // newNodeId=-11 // result=[nA(1,1, id=-11, osman:note=boundary, osman:node1=4, osman:node2=1), // n2(2,1), nB(3,1, id=-12, osman:note=boundary, osman:node1=2, osman:node2=3)] function getIntersection(const aMap, aNodeArray: OleVariant; newNodeId: Int64): OleVariant; //returns true if node is in poly (including border) function isIn(const aNode: OleVariant): boolean; //returns multipoly area in square meters //if poly not resolved then exception raised function getArea(): Double; //returns polygon orientation //0 - for mixed orientation, 1 - clockwise, 2 - contraclockwise function getOrientation(): integer; //returns bounding box for poly. Returns SafeArray of four double variants // for N,E,S and W bounds respectively. If poly not resolved then // exception raised. function getBBox: OleVariant; end; implementation end.
{******************************************************} { rsSuperCheckBox V1.0 } { Copyright 1997 RealSoft Development } { support: www.realsoftdev.com } {******************************************************} unit Rscheck; interface {$I REALSOFT.INC} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; const MARGIN = 4; type TCheckStyle = ( csSquareX, csSquareCheck, csThinX, csRound, csDefault ); TrsSuperCheckBox = class(TCustomControl) private FLocator : boolean; FLocColor : TColor; FOldColor : TColor; FAutoText : boolean; FAutoBox : boolean; FAutoChk : boolean; FChecked : boolean; FCheckStyle : TCheckStyle; FGroupID : smallint; FGroupUn : boolean; FAlignment : TLeftRight; FBGColor : TColor; FCkColor : TColor; FOnChange : TNotifyEvent; FOnReturn: TNotifyEvent; FEnterToTab : boolean; procedure SetCheckStyle(AValue: TCheckStyle); procedure SetGroupID (AValue: smallint); procedure SetGroupUn (AValue: boolean); procedure SetChecked (AValue: boolean); procedure SetAutoText (AValue: boolean); procedure SetAutoBox (AValue: boolean); procedure SetAutoChk (AValue: boolean); procedure SetAlignment (AValue: TLeftRight); procedure SetBGColor (AValue: TColor); procedure SetCKColor (AValue: TColor); procedure DrawSquare; procedure DrawRound; procedure DrawCaption; protected procedure Paint; override; procedure KeyPress(var Key: Char); override; procedure Click; override; procedure Loaded; override; procedure DoEnter; override; procedure DoExit; override; procedure CMSetEnabled(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; public constructor Create(AOwner: TComponent); override; procedure Invalidate; override; published property Alignment: TLeftRight read FAlignment write SetAlignment default taRightJustify; property ColorFace: TColor read FBGColor write SetBGColor default clWhite; property ColorCheck: TColor read FCkColor write SetCkColor default clBlack; property CheckStyle: TCheckStyle read FCheckStyle write SetCheckStyle default csSquareX; property GroupID: smallint read FGroupID write SetGroupID default 0; property GroupCanUnChk: boolean read FGroupUn write SetGroupUn default true; property Checked: boolean read FChecked write SetChecked default false; property AutoSizeText: boolean read FAutoText write SetAutoText default true; property AutoSizeBox: boolean read FAutoBox write SetAutoBox default false; property AutoCheck: boolean read FAutoChk write SetAutoChk default false; property Locator: boolean read FLocator write FLocator default false; property LocColor: TColor read FLocColor write FLocColor default clAqua; property EnterToTab : boolean read FEnterToTab write FEnterToTab default true; property Align; property Caption; property Width; property ParentFont; property Font; property TabStop; property TabOrder; property Color; property Visible; property Enabled; property OnReturn: TNotifyEvent read FOnReturn write FOnReturn; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation procedure Register; begin RegisterComponents('RSD', [TrsSuperCheckBox]); end; {$IFDEF DEMO} function DelphiRunning : boolean; begin if((FindWindow('TApplication','Delphi') = 0) and (FindWindow('TApplication','Delphi 2.0') = 0) and (FindWindow('TApplication','Delphi 3') = 0) and (FindWindow('TApplication','Delphi 4') = 0)) or (FindWindow('TPropertyInspector',nil) = 0) or (FindWindow('TAppBuilder',nil) = 0) then result:= false else result:= true; end; {$ENDIF} function UnAccel(S: String) : String; var S2: string; x: smallint; begin S2:= ''; for x:= 1 to Length(S) do if (x<Length(S)) and ((S[x]='&') and (S[x+1]='&')) or (S[x]<>'&') then S2:= S2 + S[x]; result:= S2; end; constructor TrsSuperCheckBox.Create( AOwner: TComponent ); begin inherited Create( AOwner ); ControlStyle := [csClickEvents, csCaptureMouse, csSetCaption]; Width := 97; Height := 15; TabStop := true; FCheckStyle := csSquareX; FGroupID := 0; FGroupUn := true; FChecked := false; FAutoText := true; FAutoBox := false; FAutoChk := false; FLocator := false; FLocColor := clAqua; FAlignment := taRightJustify; FBGColor := clWhite; FCkColor := clBlack; FOldColor := FBGColor; FOnChange := Nil; FOnReturn := nil; FEntertoTab := true; end; procedure TrsSuperCheckBox.Loaded; {$IFDEF LOCATOR} var F: TWinControl; {$ENDIF} begin inherited Loaded; FOldColor:= FBGColor; {$IFDEF LOCATOR} F := GetParentForm( Self ); if F.Tag > 32767 then FLocator:= true; {$ENDIF} {$IFDEF DEMO} if not DelphiRunning then {for trial version only} showmessage('This program is using an unregistered copy of the TrsSuperCheckBox' + #13 + 'component from RealSoft. Please register at www.realsoftdev.com' + #13 + 'or call (949) 831-7879.'); {$ENDIF} end; procedure TrsSuperCheckBox.KeyPress(var Key: Char); var F: TWinControl; begin {Handle enter like TAB} if (Key = #13) then begin if FEnterToTab then begin F := GetParentForm( Self ); SendMessage(F.Handle, WM_NEXTDLGCTL, 0, 0); end; Key := #0; if assigned(FOnReturn) then FOnReturn(Self); end; if (Key = #32) then Click; inherited KeyPress(Key); end; procedure TrsSuperCheckBox.Click; begin if not Focused then SetFocus; if FChecked then begin if FGroupUn then Checked:= false end else Checked:= true; inherited Click; end; procedure TrsSuperCheckBox.DoEnter; begin if FAutoChk then Checked:= true; if FLocator = true then ColorFace:= FLocColor; invalidate; inherited DoEnter; end; procedure TrsSuperCheckBox.DoExit; begin if FLocator = true then ColorFace:= FOldColor; invalidate; inherited DoExit; end; procedure TrsSuperCheckBox.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(Message.CharCode, Caption) and CanFocus then begin SetFocus; Result := 1; end else inherited; end; procedure TrsSuperCheckBox.CMTextChanged(var Message: TMessage); begin inherited; invalidate; end; procedure TrsSuperCheckBox.CMSetEnabled(var Message: TMessage); begin inherited; Invalidate; end; procedure TrsSuperCheckBox.CMFontChanged(var Message: TMessage); begin inherited; invalidate; end; procedure TrsSuperCheckBox.Paint; begin inherited Paint; with Canvas do begin Brush.color:= Color; Brush.style:= bsSolid; FillRect(ClientRect); if Focused then DrawFocusRect(ClientRect); end; DrawCaption; if (FCheckStyle = csRound) then DrawRound else DrawSquare; end; procedure TrsSuperCheckBox.Invalidate; begin ControlStyle:= ControlStyle - [csOpaque]; inherited Invalidate; end; procedure TrsSuperCheckBox.DrawSquare; var R: TRect; SizeBox,y: smallint; begin if (FAutoBox) and (FCheckStyle <> csDefault) then begin SizeBox:= Height; y:= 0; end else begin SizeBox:= 13; y:= (Height - Sizebox) div 2; end; if FAlignment = taRightJustify then R:= Rect(0,y,SizeBox, SizeBox+y) else R:= Rect(Width-SizeBox,y,Width, SizeBox+y); with Canvas do begin {background} Brush.Color:= FBGColor; FillRect(R); {outer bevel} Pen.Width:= 1; Pen.Color:= clBtnShadow; MoveTo(R.Left, R.Bottom-1 ); LineTo(R.Left, R.Top ); MoveTo(R.Left, R.Top ); LineTo(R.Right-1, R.Top ); Pen.Color:= clBtnHighlight; MoveTo(R.Right-1, R.Top ); LineTo(R.Right-1, R.Bottom-1); MoveTo(R.Right-1, R.Bottom-1); LineTo(R.Left, R.Bottom-1 ); {inner bevel} InflateRect(R,-1,-1); Pen.Color:= clBlack; MoveTo(R.Left, R.Bottom-1 ); LineTo(R.Left, R.Top ); MoveTo(R.Left, R.Top ); LineTo(R.Right-1, R.Top ); Pen.Color:= clBtnFace; MoveTo(R.Right-1, R.Top ); LineTo(R.Right-1, R.Bottom-1); MoveTo(R.Right-1, R.Bottom-1); LineTo(R.Left, R.Bottom-1 ); {draw checkmark} if FChecked then begin if FAlignment = taRightJustify then R:= Rect(0,y,SizeBox, SizeBox+y) else R:= Rect(Width-SizeBox,y,Width, SizeBox+y); InflateRect(R,-4,-4); Pen.Color:= FCkColor; Pen.Width:= 2; if (FCheckStyle = csSquareX) then begin {default X (d.palette)} InflateRect(R,1,1); Pen.Width:= 1; MoveTo( R.left , R.Top ); LineTo( R.right , R.bottom ); MoveTo( R.left , R.bottom-1 ); LineTo( R.right , R.top-1 ); MoveTo( R.left+1 , R.Top ); LineTo( R.right , R.bottom-1 ); MoveTo( R.left , R.Top+1 ); LineTo( R.right-1 , R.bottom ); MoveTo( R.left , R.bottom-2 ); LineTo( R.right-1 , R.top-1 ); MoveTo( R.left+1 , R.bottom-1 ); LineTo( R.right , R.top ); end else if (FCheckStyle = csSquareCheck) then begin {dans ugly check} MoveTo(R.left, ((R.Bottom + R.Top) div 2)); LineTo(R.left, R.bottom); MoveTo(R.left, R.bottom); LineTo(R.right, R.top); end else if (FCheckStyle = csDefault) then begin {default check mark} Pen.Width:= 1; InflateRect(R,1,1); MoveTo( R.left , R.Top+2 ); LineTo( R.left+3 , R.bottom-2 ); MoveTo( R.left , R.Top+3 ); LineTo( R.left+3 , R.bottom-1 ); MoveTo( R.left , R.Top+4 ); LineTo( R.left+3 , R.bottom ); MoveTo( R.left+3 , R.Top+3 ); LineTo( R.right , R.top-1 ); MoveTo( R.left+3 , R.Top+4 ); LineTo( R.right , R.top ); MoveTo( R.left+3 , R.Top+5 ); LineTo( R.right , R.top+1 ); end else if (FCheckStyle = csThinX) then begin InflateRect(R,1,1); Pen.Width:= 1; MoveTo( R.left , R.Top ); LineTo( R.right , R.bottom ); MoveTo( R.left , R.bottom-1 ); LineTo( R.right , R.top-1 ); end; Pen.Width:= 1; end; end; end; procedure TrsSuperCheckBox.DrawRound; var R1, S1, S2: array [1..4] of TPoint; R: TRect; SizeBox,y: smallint; procedure CalcPoints; begin R1[1].X:= (R.Right + R.Left) div 2; R1[1].Y:= R.Top; R1[2].X:= R.Right; R1[2].Y:= (R.Bottom + R.Top) div 2; R1[3].X:= (R.Right + R.Left) div 2; R1[3].Y:= R.Bottom; R1[4].X:= R.Left; R1[4].Y:= (R.Bottom + R.Top) div 2; S1[1].X:= R1[1].X; S1[1].Y:= R1[1].Y; S1[2].X:= (R1[1].X + R1[2].X) div 2; S1[2].Y:= (R1[1].Y + R1[2].Y) div 2; S1[3].X:= (R1[4].X + R1[3].X) div 2; S1[3].Y:= (R1[4].Y + R1[3].Y) div 2; S1[4].X:= R1[4].X; S1[4].Y:= R1[4].Y; S2[1].X:= S1[2].X; S2[1].Y:= S1[2].Y; S2[2].X:= R1[2].X; S2[2].Y:= R1[2].Y; S2[3].X:= R1[3].X; S2[3].Y:= R1[3].Y; S2[4].X:= S1[3].X; S2[4].Y:= S1[3].Y; end; begin if FAutoBox then begin SizeBox:= Height; y:= 1; end else begin SizeBox:= 13; y:= (Height - Sizebox) div 2; end; if FAlignment = taRightJustify then R:= Rect(0,y,SizeBox, SizeBox+y) else R:= Rect(Width-SizeBox,y,Width, SizeBox+y); with Canvas do begin {** background **} Brush.Color:= FBGColor; Pen.Color:= FBGColor; if FAlignment = taRightJustify then Ellipse(0,y,SizeBox,SizeBox+y) else Ellipse(Width-SizeBox,y,Width,SizeBox+y); {** Outer **} CalcPoints; {gray} Pen.Width:= 1; Pen.Color:= clBtnShadow; Arc(R.Left, R.Top, R.Right, R.Bottom, S1[2].X, S1[2].Y, S1[3].X, S1[3].Y); {white} Pen.Color:= clBtnHighlight; Arc(R.Left, R.Top, R.Right, R.Bottom, S2[4].X, S2[4].Y, S2[1].X, S2[1].Y); {** Inner **} InflateRect(R, -1, -1); CalcPoints; {black} Pen.Color:= clBlack; Arc(R.Left, R.Top, R.Right, R.Bottom, S1[2].X, S1[2].Y, S1[3].X, S1[3].Y); {gray} Pen.Color:= clBtnFace; Arc(R.Left, R.Top, R.Right, R.Bottom, S2[4].X, S2[4].Y, S2[1].X, S2[1].Y); {** draw checkmark **} if FChecked then begin if FAlignment = taRightJustify then R:= Rect(0,y,SizeBox, SizeBox+y) else R:= Rect(Width-SizeBox,y,Width, SizeBox+y); InflateRect(R, -(SizeBox div 3) , -(SizeBox div 3)); Brush.Color:= FCkColor; Pen.Color:= FCkColor; Ellipse(R.Left, R.Top, R.Right, R.Bottom); end; end; end; procedure TrsSuperCheckBox.DrawCaption; var R: TRect; TH, TW: smallint; SizeBox, y: smallint; Text: array[0..255] of char; Flag: word; begin Canvas.Font.Assign(Font); TW:= Canvas.TextWidth(UnAccel(Caption)); TH:= Canvas.TextHeight(UnAccel(Caption)); if FAutoText and (Length(Caption) > 0) then begin Height:= TH+2; Width:= TW+TH+MARGIN+2; end; if FAutoBox then begin SizeBox:= Height-2; y:= 1; end else begin SizeBox:= 13; y:= 1; end; if FAutoText and (Length(Caption) = 0) then begin Width:= SizeBox; Height:= SizeBox; end; if FAlignment = taRightJustify then R:= Rect(SizeBox+MARGIN, y,Width, y+TH) else R:= Rect(0,y,Width-SizeBox-MARGIN, y+TH); if not Enabled then Canvas.Font.Color:= clGrayText else Canvas.Font.Color:= Font.Color; with Canvas do begin Brush.Style:= bsClear; Brush.Color:= Color; if FAlignment = taRightJustify then Flag:= DT_LEFT or DT_VCENTER or DT_SINGLELINE else Flag:= DT_RIGHT or DT_VCENTER or DT_SINGLELINE; end; StrPCopy(Text, Caption); DrawText(Canvas.Handle, Text, StrLen(Text), R, Flag) end; procedure TrsSuperCheckBox.SetCheckStyle(AValue: TCheckStyle); begin FCheckStyle:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetGroupID (AValue: smallint); begin FGroupID:= AValue; if FChecked then SetChecked(true); Invalidate; end; procedure TrsSuperCheckBox.SetGroupUn (AValue: boolean); begin FGroupUn:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetChecked (AValue: boolean); var x: smallint; begin if FChecked = AValue then Exit; if AValue then for x:= 0 to Parent.ControlCount-1 do if (Parent.Controls[x] is TrsSuperCheckBox) and (not (Parent.Controls[x] = Self)) then if ((Parent.Controls[x] as TrsSuperCheckBox).GroupID > 0) and ((Parent.Controls[x] as TrsSuperCheckBox).GroupID = FGroupID) and ((Parent.Controls[x] as TrsSuperCheckBox).checked) then begin (Parent.Controls[x] as TrsSuperCheckBox).Checked:= false; (Parent.Controls[x] as TrsSuperCheckBox).Invalidate; end; FChecked:= AValue; Invalidate; if Assigned(FOnChange) then FOnChange(Self); end; procedure TrsSuperCheckBox.SetAutotext (AValue: boolean); begin FAutoText:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetAutoBox (AValue: boolean); begin FAutoBox:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetAutoChk (AValue: boolean); begin FAutoChk:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetAlignment (AValue: TLeftRight); begin FAlignment:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetBGColor (AValue: TColor); begin FBGColor:= AValue; Invalidate; end; procedure TrsSuperCheckBox.SetCkColor (AValue: TColor); begin FCkColor:= AValue; Invalidate; end; end.
unit uBackup; interface uses FireDAC.Comp.Client, FireDAC.Phys.FB, FireDAC.Phys.IBWrapper, System.Classes, System.SysUtils, System.IOUtils, FireDAC.Phys.IBBase, Winapi.Windows, System.DateUtils, IdFTP, System.SyncObjs, IdFTPCommon; type TFtp = record private FPasta: String; FSenha: String; FHost: String; FUsuario: String; procedure SetHost(const Value: String); procedure SetPasta(const Value: String); procedure SetSenha(const Value: String); procedure SetUsuario(const Value: String); public property Host: String read FHost write SetHost; property Usuario: String read FUsuario write SetUsuario; property Senha: String read FSenha write SetSenha; property Pasta: String read FPasta write SetPasta; end; TBackup = class private FBackup: TFDIBBackup; FEnderecoBackupRede: String; FEnderecoBackup: String; FFtp: TFtp; procedure SetEnderecoBackup(const Value: String); procedure SetEnderecoBackupRede(const Value: String); procedure ppvEnviarParaFTP(ipArquivo: String); procedure SetFtp(const Value: TFtp); public constructor Create(ipConn: TFDConnection; ipDriverLink: TFDPhysFBDriverLink); destructor Destroy; override; // FTP property Ftp: TFtp read FFtp write SetFtp; property EnderecoBackup: String read FEnderecoBackup write SetEnderecoBackup; property EnderecoBackupRede: String read FEnderecoBackupRede write SetEnderecoBackupRede; procedure ppuRealizarBackup; end; TThreadBackup = class(TThread) private FEvent: TEvent; FBackup: TBackup; FDataUltimoBackup: TDateTime; FHoraBackup: TTime; FOnFinishBackup: TThreadProcedure; FOnStartBackup: TThreadProcedure; procedure SetBackup(const Value: TBackup); procedure SetDataUltimoBackup(const Value: TDateTime); procedure SetHoraBackup(const Value: TTime); procedure SetOnFinishBackup(const Value: TThreadProcedure); procedure SetOnStartBackup(const Value: TThreadProcedure); public property DataUltimoBackup: TDateTime read FDataUltimoBackup write SetDataUltimoBackup; property HoraBackup: TTime read FHoraBackup write SetHoraBackup; property Backup: TBackup read FBackup write SetBackup; property Event: TEvent read FEvent; property OnStartBackup: TThreadProcedure read FOnStartBackup write SetOnStartBackup; property OnFinishBackup: TThreadProcedure read FOnFinishBackup write SetOnFinishBackup; constructor Create; destructor Destroy; override; procedure Execute; override; end; implementation uses fPrincipal; { TBackup } constructor TBackup.Create(ipConn: TFDConnection; ipDriverLink: TFDPhysFBDriverLink); begin FBackup := TFDIBBackup.Create(nil); FBackup.DriverLink := ipDriverLink; FBackup.Protocol := ipLocal; FBackup.Database := ipConn.Params.Values['Database']; FBackup.UserName := ipConn.Params.Values['User_Name']; FBackup.Password := ipConn.Params.Values['Password']; FBackup.Host := ipConn.Params.Values['server']; end; destructor TBackup.Destroy; begin FBackup.Free; inherited; end; procedure TBackup.ppuRealizarBackup; var vaBackupFile, vaNomeArquivo: String; begin if EnderecoBackup = '' then raise Exception.Create('Informe um endereço de backup.'); FBackup.BackupFiles.Clear; vaNomeArquivo := 'song_' + DayOf(now).ToString + '.fbk'; vaBackupFile := FEnderecoBackup + vaNomeArquivo; FBackup.BackupFiles.Add(vaBackupFile); if TFile.Exists(vaBackupFile) then TFile.Delete(vaBackupFile); FBackup.Backup; if not TFile.Exists(vaBackupFile) then raise Exception.Create('O backup falhou. Detalhes: Não foi gerado o arquivo .fbk'); if FEnderecoBackupRede.Trim <> '' then begin CopyFile(PChar(vaBackupFile), PChar(FEnderecoBackupRede + vaNomeArquivo), false); if not TFile.Exists(FEnderecoBackupRede + vaNomeArquivo) then frmPrincipal.ppuAdicionarErroLog('O arquivo de backup não foi copiado para a pasta na rede'); end; if Ftp.Host.Trim <> '' then begin try ppvEnviarParaFTP(vaBackupFile); except on E: Exception do frmPrincipal.ppuAdicionarErroLog('Erro ao enviar o arquivo para o FTP. Detalhes: ' + E.Message); end; end; end; procedure TBackup.ppvEnviarParaFTP(ipArquivo: String); var vaFtp: TIdFTP; vaNomeArquivo: String; begin vaFtp := TIdFTP.Create(nil); try vaFtp.Host := Ftp.Host; vaFtp.UserName := Ftp.Usuario; vaFtp.Password := Ftp.Senha; vaFtp.Passive := true; vaFtp.Connect; if vaFtp.Connected then begin vaFtp.ChangeDir(Ftp.Pasta); // muito importante. Sem isso o arquivo fica corrompido. vaFtp.TransferType := ftBinary; vaNomeArquivo := TPath.GetFileName(ipArquivo); vaFtp.Put(ipArquivo, vaNomeArquivo); // FTP da oreades parece nao ter suporte para verificacao, mas deixei caso futuramente passe a ter. if vaFtp.SupportsVerification and (not vaFtp.VerifyFile(ipArquivo, vaNomeArquivo)) then raise Exception.Create('O arquivo que foi carregado para o FTP não confere com o arquivo local.'); end else raise Exception.Create('Não foi possível conectar no FTP.'); finally vaFtp.Disconnect; vaFtp.Free; end; end; procedure TBackup.SetEnderecoBackup(const Value: String); begin FEnderecoBackup := IncludeTrailingBackslash(Value); end; procedure TBackup.SetEnderecoBackupRede(const Value: String); begin FEnderecoBackupRede := IncludeTrailingBackslash(Value); end; procedure TBackup.SetFtp(const Value: TFtp); begin FFtp := Value; end; { TFtp } procedure TFtp.SetHost(const Value: String); begin FHost := Value; end; procedure TFtp.SetPasta(const Value: String); begin FPasta := Value; end; procedure TFtp.SetSenha(const Value: String); begin FSenha := Value; end; procedure TFtp.SetUsuario(const Value: String); begin FUsuario := Value; end; { TBackupThread } constructor TThreadBackup.Create; begin inherited Create(true); FEvent := TEvent.Create(nil, false, false, ''); end; destructor TThreadBackup.Destroy; begin FEvent.Free; FBackup.Free; inherited; end; procedure TThreadBackup.Execute; var vaDataAtual, vaProximoBkp: TDateTime; vaMinutoAtual, vaTempoEspera: Integer; vaHoraAtual: TTime; procedure plCalcularTempoEspera; begin // vamos acordar 5 minuto antes para ter uma folga caso o servidor trava por algum motivo vaTempoEspera := MilliSecondsBetween(vaHoraAtual, HoraBackup) - 300000; if vaTempoEspera < 0 then vaTempoEspera := 1000; FEvent.WaitFor(vaTempoEspera); end; begin inherited; while not Terminated do begin try vaDataAtual := now; vaHoraAtual := Time; if (DataUltimoBackup = 0) or (DayOf(DataUltimoBackup) <> DayOf(vaDataAtual)) or (HourOf(DataUltimoBackup) <> HourOf(vaDataAtual)) then begin vaMinutoAtual := MinuteOf(vaDataAtual); if (HourOf(vaDataAtual) = HourOf(HoraBackup)) then begin if (vaMinutoAtual = MinuteOf(HoraBackup)) then begin if Assigned(FOnStartBackup) then Synchronize(FOnStartBackup); Backup.ppuRealizarBackup; DataUltimoBackup := now; vaProximoBkp := IncHour(DataUltimoBackup, 23); vaProximoBkp := IncMinute(vaProximoBkp, 55); if Assigned(FOnFinishBackup) then Synchronize(FOnFinishBackup); FEvent.WaitFor(MilliSecondsBetween(vaProximoBkp, DataUltimoBackup)); // 23 hr e 55 min end else FEvent.WaitFor(MilliSecondsBetween(vaHoraAtual, HoraBackup)); end else plCalcularTempoEspera end else plCalcularTempoEspera; except on E: Exception do begin frmPrincipal.ppuAdicionarErroLog('Erro na thread do backup. Detalhes: ' + E.Message); Sleep(10000); end; end; end; end; procedure TThreadBackup.SetBackup(const Value: TBackup); begin FBackup := Value; end; procedure TThreadBackup.SetDataUltimoBackup(const Value: TDateTime); begin FDataUltimoBackup := Value; end; procedure TThreadBackup.SetHoraBackup(const Value: TTime); begin FHoraBackup := Value; end; procedure TThreadBackup.SetOnFinishBackup(const Value: TThreadProcedure); begin FOnFinishBackup := Value; end; procedure TThreadBackup.SetOnStartBackup(const Value: TThreadProcedure); begin FOnStartBackup := Value; end; end.
unit Unit5; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtDlgs; type TForm5 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form5: TForm5; implementation uses Unit1; {$R *.dfm} // Загрузить файл в Memo1 procedure TForm5.Button1Click(Sender: TObject); begin // if OpenTextFileDialog1.Execute then memo1.Lines.LoadFromFile(OpenTextFileDialog1.FileName) if FileExists( ExtractFilePath(ParamStr(0))+'Data\TaskList.txt' ) then begin // проверка существования файла Memo1.Lines.LoadFromFile( ExtractFilePath(ParamStr(0))+'Data\TaskList.txt' ) end; end; // Сохранить содержимое Memo1 в файл procedure TForm5.Button2Click(Sender: TObject); begin //if SaveTextFileDialog1.Execute then // Memo1.Lines.SaveToFile( SaveTextFileDialog1.FileName ); if Application.MessageBox('Вы уверены, что хотите записать в файл этот список задач ?', 'Внимание', MB_ICONQUESTION+MB_YESNO+MB_DEFBUTTON2)=idYes then Memo1.Lines.SaveToFile( ExtractFilePath(ParamStr(0))+'Data\TaskList.txt' ); end; procedure TForm5.Button3Click(Sender: TObject); begin // Вывод запроса на подтверждение очистки списка // MessageBox(handle, PChar('текст'),PChar('заголовок'), MB_ICONSTOP+MB_YESNOCANCEL+MB_DEFBUTTON2); if Application.MessageBox('Вы уверены, что хотите очистить список ?', 'Внимание', MB_ICONQUESTION+MB_YESNO+MB_DEFBUTTON2)=idYes then Memo1.Clear; end; // Перезадать список для планировщика по текущему содержимому Memo1 procedure TForm5.Button4Click(Sender: TObject); begin // Перезададим список для выбора значений в поле 'Задача' (2-я колонка, нумерация с 0) Form1.DBGrid1.Columns[3].PickList := Memo1.Lines; ShowMessage('Список названий задач для планировщика был перезадан'); end; end.
unit UnitTypes; interface type TUser = (uUser = 0, uOperator, uDesigner, uManager, uMaster, uAdmin); TGender = (gMale = 0, gFemale); TResourceContent = (rBook = 0, rMultiMedia, rWebPage); TListState = (lResource, lQuestionMatch, lInstructionMatch); TMatchState = (mActive, mDisabled, mImported); function UserToString(u : TUser) : string; function StringToUser(s : string) : TUser; function GenderToString(g : TGender) : string; function StringToGender(s : string) : TGender; function ResourceToString(r : TResourceContent) : string; function StringToResource(s : string) : TResourceContent; function StateToString(s : TMatchState) : string; function StringToState(s : string) : TMatchState; // translate function UserToPersian(u : TUser) : string; function ResourceToPersian(r : TResourceContent) : string; function StateToPersian(s : TMatchState) : string; implementation function UserToString(u : TUser) : string; begin case u of uUser: Result := 'user'; uOperator: Result := 'operator'; uDesigner: Result := 'designer'; uManager: Result := 'manager'; uMaster: Result := 'master'; uAdmin: Result := 'admin'; end; end; function StringToUser(s : string) : TUser; begin if (s = 'user') or (s = '') then Result := uUser else if s = 'operator' then Result := uOperator else if s = 'designer' then Result := uDesigner else if s = 'manager' then Result := uManager else if s = 'master' then Result := uMaster else if s = 'admin' then Result := uAdmin; end; function GenderToString(g : TGender) : string; begin case g of gMale: Result := 'male'; gFemale: Result := 'female'; end; end; function StringToGender(s : string) : TGender; begin if s = 'male' then Result := gMale else if s = 'female' then Result := gFemale; end; function ResourceToString(r : TResourceContent) : string; begin case r of rBook: Result := 'book'; rMultiMedia: Result := 'multimedia'; rWebPage: Result := 'webpage'; end; end; function StringToResource(s : string) : TResourceContent; begin if s = 'book' then Result := rBook else if s = 'multimedia' then Result := rMultiMedia else if s = 'webpage' then Result := rWebPage; end; function StateToString(s : TMatchState) : string; begin case s of mActive: Result := 'active'; mDisabled: Result := 'disabled'; mImported: Result := 'imported'; end; end; function StringToState(s : string) : TMatchState; begin if s = 'active' then Result := mActive else if s = 'disabled' then Result := mDisabled else if s = 'imported' then Result := mImported; end; function UserToPersian(u : TUser) : string; begin case u of uUser: Result := 'عضو'; uOperator: Result := 'عضویار'; uDesigner: Result := 'طراح'; uManager: Result := 'طراح‌یار'; uMaster: Result := 'مدیر'; uAdmin: Result := 'مدیر کل'; end; end; function ResourceToPersian(r : TResourceContent) : string; begin case r of rBook: Result := 'کتاب'; rMultiMedia: Result := 'چند رسانه‌ای'; rWebPage: Result := 'صفحه وب'; end; end; function StateToPersian(s : TMatchState) : string; begin case s of mActive: Result := 'فعال'; mDisabled: Result := 'غیر فعال'; mImported: Result := 'وارد شده'; end; end; end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, System.ImageList, Vcl.Menus, Vcl.ActnList, Vcl.Controls, Vcl.Forms, Vcl.ToolWin, Vcl.ExtCtrls, Vcl.Graphics, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ImgList, VirtualTrees, ChromeTabs, ChromeTabsClasses, ChromeTabsTypes, DataGrabber.ConnectionSettings, DataGrabber.Interfaces, DataGrabber.Settings, DataGrabber.ConnectionProfiles; { Main application form. TODO: - log executed statements to a local database - Use bindings in settings - Select <selected fields?> Where in - Smart grouping (detect common field prefixes/suffixes (eg. Date, ...Id,) - Working set of tables (cache meta info and links and make them customizable as a profile setting) - Statement builder, smart joining - Profile color for tab backgrounds } type TfrmMain = class(TForm) {$REGION 'designer controls'} aclMain : TActionList; actAddConnectionView : TAction; actCloseAllOtherTabs : TAction; actCloseTab : TAction; actInspectChromeTab : TAction; ctMain : TChromeTabs; imlSpinner : TImageList; mniCloseAllOtherTabs : TMenuItem; mniCloseTab : TMenuItem; pnlConnectionStatus : TPanel; pnlConnectionViews : TPanel; pnlConstantFieldsCount : TPanel; pnlEditMode : TPanel; pnlElapsedTime : TPanel; pnlEmptyFieldsCount : TPanel; pnlFieldCount : TPanel; pnlHiddenFieldsCount : TPanel; pnlRecordCount : TPanel; pnlStatusBar : TPanel; pnlTop : TPanel; ppmCVTabs : TPopupMenu; tlbMain : TToolBar; tlbTopRight : TToolBar; {$ENDREGION} {$REGION 'action handlers'} procedure actAddConnectionViewExecute(Sender: TObject); procedure actInspectChromeTabExecute(Sender : TObject); procedure actCloseAllOtherTabsExecute(Sender: TObject); {$ENDREGION} {$REGION 'event handlers'} procedure tlbMainCustomDraw( Sender : TToolBar; const ARect : TRect; var DefaultDraw : Boolean ); procedure FormShortCut( var Msg : TWMKey; var Handled : Boolean ); procedure ctMainActiveTabChanged( Sender : TObject; ATab : TChromeTab ); procedure ctMainButtonAddClick( Sender : TObject; var Handled : Boolean ); procedure ctMainButtonCloseTabClick( Sender : TObject; ATab : TChromeTab; var Close : Boolean ); procedure ctMainNeedDragImageControl( Sender : TObject; ATab : TChromeTab; var DragControl : TWinControl ); procedure actCloseTabExecute(Sender: TObject); {$ENDREGION} private FManager : IConnectionViewManager; FSettings : ISettings; procedure SettingsChanged(Sender: TObject); procedure UpdateTabs; protected function GetActiveConnectionView: IConnectionView; function GetActiveConnectionProfile: TConnectionProfile; function GetData: IData; function GetSettings: ISettings; function GetManager: IConnectionViewManager; procedure UpdateStatusBar; procedure OptimizeWidth(APanel: TPanel); procedure InitializeActions; procedure UpdateActions; override; procedure ShowToolWindow(AForm: TForm); procedure HideToolWindow(AForm: TForm); public procedure AfterConstruction; override; procedure BeforeDestruction; override; function AddConnectionView: IConnectionView; property Manager: IConnectionViewManager read GetManager; property ActiveConnectionView: IConnectionView read GetActiveConnectionView; property ActiveConnectionProfile: TConnectionProfile read GetActiveConnectionProfile; property Data: IData read GetData; property Settings: ISettings read GetSettings; end; var frmMain: TfrmMain; implementation {$R *.dfm} uses System.UITypes, Vcl.Clipbrd, Data.DB, Spring.Utils, DDuce.ObjectInspector.zObjectInspector, DataGrabber.Utils, DataGrabber.Resources, DataGrabber.Factories; {$REGION 'construction and destruction'} procedure TfrmMain.AfterConstruction; var FVI : TFileVersionInfo; begin inherited AfterConstruction; FVI := TFileVersionInfo.GetVersionInfo(Application.ExeName); Caption := Format('%s %s', [FVI.ProductName, FVI.ProductVersion]); FSettings := TDataGrabberFactories.CreateSettings(Self); FSettings.OnChanged.Add(SettingsChanged); FManager := TDataGrabberFactories.CreateManager(Self, FSettings); FSettings.FormSettings.AssignTo(Self); AddConnectionView; tlbMain.Images := FManager.ActionList.Images; tlbTopRight.Images := FManager.ActionList.Images; InitializeActions; end; procedure TfrmMain.BeforeDestruction; begin FSettings.FormSettings.Assign(Self); FManager := nil; FSettings := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'action handlers'} procedure TfrmMain.actAddConnectionViewExecute(Sender: TObject); begin AddConnectionView; end; procedure TfrmMain.actCloseAllOtherTabsExecute(Sender: TObject); var I : Integer; LActiveCV : IConnectionView; CV : IConnectionView; begin I := 0; LActiveCV := IConnectionView(ctMain.ActiveTab.Data); while (Manager.Count > 1) and (I < Manager.Count) do begin CV := IConnectionView(ctMain.Tabs[I].Data); if CV <> LActiveCV then begin Manager.DeleteConnectionView(CV); ctMain.Tabs.DeleteTab(ctMain.Tabs[I].Index, True); end else begin Inc(I); end; end; end; procedure TfrmMain.actCloseTabExecute(Sender: TObject); begin if Manager.Count > 1 then begin Manager.DeleteConnectionView(IConnectionView(ctMain.ActiveTab.Data)); ctMain.Tabs.DeleteTab(ctMain.ActiveTabIndex, True); end; end; procedure TfrmMain.actInspectChromeTabExecute(Sender: TObject); begin if Assigned(ctMain.ActiveTab) then begin InspectComponent(ctMain); end; end; {$ENDREGION} {$REGION 'event handlers'} procedure TfrmMain.tlbMainCustomDraw(Sender: TToolBar; const ARect: TRect; var DefaultDraw: Boolean); begin Sender.Canvas.FillRect(ARect); end; { Needed to route shortcuts to the actionlist in the data module. } procedure TfrmMain.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin Handled := Manager.ActionList.IsShortCut(Msg); end; {$REGION 'ctMain'} procedure TfrmMain.ctMainActiveTabChanged(Sender: TObject; ATab: TChromeTab); var CV : IConnectionView; begin if Assigned(ATab.Data) then begin CV := IConnectionView(ATab.Data); CV.Form.Show; CV.Form.SetFocus; Manager.ActiveConnectionView := CV; ATab.Caption := Format('%s-%s', [ CV.Form.Caption, CV.ActiveConnectionProfile.Name ]); end; end; procedure TfrmMain.ctMainButtonAddClick(Sender: TObject; var Handled: Boolean); begin AddConnectionView; Handled := True; end; procedure TfrmMain.ctMainButtonCloseTabClick(Sender: TObject; ATab: TChromeTab; var Close: Boolean); begin if Manager.Count > 1 then begin Close := Manager.DeleteConnectionView(IConnectionView(ATab.Data)); end else Close := False; end; procedure TfrmMain.ctMainNeedDragImageControl(Sender: TObject; ATab: TChromeTab; var DragControl: TWinControl); begin DragControl := pnlConnectionViews; end; {$ENDREGION} {$ENDREGION} {$REGION 'property access methods'} function TfrmMain.GetActiveConnectionProfile: TConnectionProfile; begin if Assigned(ActiveConnectionView) then Result := ActiveConnectionView.ActiveConnectionProfile else Result := nil; end; function TfrmMain.GetActiveConnectionView: IConnectionView; begin Result := Manager.ActiveConnectionView; end; function TfrmMain.GetData: IData; begin Result := Manager.ActiveData; end; function TfrmMain.GetSettings: ISettings; begin Result := FSettings; end; function TfrmMain.GetManager: IConnectionViewManager; begin Result := FManager; end; {$ENDREGION} {$REGION 'private methods'} procedure TfrmMain.OptimizeWidth(APanel: TPanel); var S: string; begin S := APanel.Caption; if Trim(S) <> '' then begin APanel.Width := GetTextWidth(APanel.Caption, APanel.Font) + 10; APanel.AlignWithMargins := True; end else begin APanel.Width := 0; APanel.AlignWithMargins := False; end; end; function TfrmMain.AddConnectionView: IConnectionView; var CV : IConnectionView; LTab : TChromeTab; begin LockPaint(Self); try CV := Manager.AddConnectionView; CV.Form.Parent := pnlConnectionViews; CV.Form.BorderStyle := bsNone; CV.Form.Align := alClient; CV.Form.Visible := True; LTab := ctMain.Tabs.Add; LTab.Data := Pointer(CV); finally UnlockPaint(Self); end; end; procedure TfrmMain.InitializeActions; begin TDataGrabberFactories.AddMainToolbarButtons(tlbMain, Manager); TDataGrabberFactories.AddTopRightToolbarButtons(tlbTopRight, Manager); end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmMain.SettingsChanged(Sender: TObject); begin FormStyle := FSettings.FormSettings.FormStyle; WindowState := FSettings.FormSettings.WindowState; end; procedure TfrmMain.ShowToolWindow(AForm: TForm); begin if Assigned(AForm) then begin LockPaint(AForm); try AForm.BorderStyle := bsSizeToolWin; AForm.Visible := True; ShowWindow(AForm.Handle, SW_SHOWNOACTIVATE); SetWindowPos( AForm.Handle, GetNextWindow(Self.Handle, GW_HWNDNEXT), 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE); finally UnLockPaint(AForm); end; AForm.Invalidate; end; end; procedure TfrmMain.HideToolWindow(AForm: TForm); begin if Assigned(AForm) then begin ShowWindow(AForm.Handle, SW_HIDE); end; end; procedure TfrmMain.UpdateActions; begin inherited UpdateActions; UpdateStatusBar; if Assigned(Manager.ActiveConnectionView) then begin UpdateTabs; actCloseTab.Enabled := Manager.Count > 1; actCloseAllOtherTabs.Enabled := Manager.Count > 1; end; end; {$ENDREGION} {$REGION 'public methods'} procedure TfrmMain.UpdateStatusBar; var S : string; TFC : Integer; CFC : Integer; EFC : Integer; HFC : Integer; RS : IResultSet; begin if Assigned(Data) and Assigned(ActiveConnectionView.ActiveDataView) and ActiveConnectionView.ActiveDataView.ResultSet.DataSet.Active then begin RS := ActiveConnectionView.ActiveDataView.ResultSet; pnlRecordCount.Caption := Format(SRecordCount, [RS.DataSet.RecordCount]); TFC := RS.DataSet.FieldCount; CFC := RS.ConstantFields.Count; EFC := RS.EmptyFields.Count; HFC := RS.HiddenFields.Count; pnlFieldCount.Caption := Format(SFieldCount, [TFC]); pnlConstantFieldsCount.Caption := Format(SConstantFieldCount, [CFC]); pnlEmptyFieldsCount.Caption := Format(SEmptyFieldCount, [EFC]); pnlHiddenFieldsCount.Caption := Format(SHiddenFieldCount, [HFC]); pnlElapsedTime.Caption := Format( '%5.0f ms', [Data.ElapsedTime.TotalMilliseconds] ); if Data.CanModify then S := SUpdateable else S := SReadOnly; end else begin pnlEditMode.Caption := ''; pnlRecordCount.Caption := ''; pnlFieldCount.Caption := ''; pnlElapsedTime.Caption := ''; pnlConstantFieldsCount.Caption := ''; pnlEmptyFieldsCount.Caption := ''; pnlHiddenFieldsCount.Caption := ''; end; if Assigned(Data) and Assigned(Data.Connection) and Data.Connection.Connected then begin pnlConnectionStatus.Caption := SConnected; pnlConnectionStatus.Font.Color := clGreen; end else begin pnlConnectionStatus.Caption := SDisconnected; pnlConnectionStatus.Font.Color := clBlack; end; if Data.CanModify then begin pnlEditMode.Font.Style := pnlEditMode.Font.Style + [fsBold]; pnlEditMode.Font.Color := clRed; end else begin pnlEditMode.Font.Style := pnlEditMode.Font.Style - [fsBold]; pnlEditMode.Font.Color := clGreen; end; pnlEditMode.Caption := S; OptimizeWidth(pnlConnectionStatus); OptimizeWidth(pnlEditMode); OptimizeWidth(pnlRecordCount); OptimizeWidth(pnlElapsedTime); OptimizeWidth(pnlFieldCount); OptimizeWidth(pnlEmptyFieldsCount); OptimizeWidth(pnlConstantFieldsCount); OptimizeWidth(pnlHiddenFieldsCount); FSettings.FormSettings.WindowState := WindowState; end; procedure TfrmMain.UpdateTabs; var V : IConnectionView; C : Integer; begin V := Manager.ActiveConnectionView; if Assigned(ctMain.ActiveTab) and Assigned(V) then begin ctMain.ActiveTab.Caption := Format('%s', [V.Form.Caption]); C := V.ActiveConnectionProfile.ProfileColor; ctMain.LookAndFeel.Tabs.Active.Style.StartColor := C; ctMain.LookAndFeel.Tabs.Active.Style.StopColor := C; end; end; {$ENDREGION} end.
program compilefail19(output); {parse failure - function missing colon between right paren and return type } function addone(r:integer) integer ; begin addone:=r+1; end; begin writeln(addone(3)); end.
unit xe_CUT011; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, xe_GNL, Dialogs, MSXML2_TLB, xe_structure, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, cxTextEdit, cxDropDownEdit, cxLabel, cxMemo, cxGridLevel, cxGridCustomTableView, cxGridTableView, IniFiles, cxGridBandedTableView, cxClasses, cxGridCustomView, cxGrid, Vcl.StdCtrls, cxRadioGroup, cxCheckBox, cxMaskEdit, cxGroupBox, cxButtons, Vcl.ExtCtrls, dxSkinsCore, dxSkinscxPCPainter, dxDateRanges, dxSkinOffice2010Silver, dxSkinSharp, cxCurrencyEdit, dxSkinMetropolisDark, dxSkinOffice2007Silver, dxScrollbarAnnotations; type TFrm_CUT011 = class(TForm) Panel1: TPanel; cboCuLevel: TcxComboBox; cxLabel17: TcxLabel; cxLabel5: TcxLabel; rdoCuGb1: TcxRadioButton; rdoCuGb2: TcxRadioButton; cxLabel1: TcxLabel; rdoCuGb3: TcxRadioButton; cxLabel2: TcxLabel; edtCuName: TcxTextEdit; cxLblStart: TcxLabel; meoStartAreaCUT: TcxMemo; cxtStartXval: TcxTextEdit; cxtStartYval: TcxTextEdit; cxtStartAreaDetail: TcxTextEdit; lblStartAreaName: TcxLabel; cxLabel4: TcxLabel; cxTextEdit2: TcxTextEdit; cxLblEnd: TcxLabel; meoEndAreaCUT: TcxMemo; cxtEndXval: TcxTextEdit; cxtEndYval: TcxTextEdit; cxtEndAreaDetail: TcxTextEdit; lblEndAreaName: TcxLabel; cxLabel6: TcxLabel; cxLabel7: TcxLabel; cxLabel8: TcxLabel; cxLabel9: TcxLabel; cxLabel10: TcxLabel; cxLabel11: TcxLabel; cxLabel12: TcxLabel; cxLabel15: TcxLabel; cxLabel16: TcxLabel; cxLabel18: TcxLabel; btnSave: TcxButton; btnInit: TcxButton; cboBranch: TcxComboBox; cxtSA2: TcxTextEdit; cxtSA3: TcxTextEdit; cxtEd2: TcxTextEdit; cxtEd3: TcxTextEdit; dtpResvDate: TcxLabel; RbButton23: TcxButton; RbButton24: TcxButton; lbl1: TcxLabel; edtOKC1: TcxTextEdit; edtOKC2: TcxTextEdit; edtOKC3: TcxTextEdit; edtOKC4: TcxTextEdit; chkBrTelYN: TcxCheckBox; pmCustSMS: TPopupMenu; nm_CustSMS: TMenuItem; btnBefore: TcxButton; cxLabel20: TcxLabel; cxLabel21: TcxLabel; cxLabel28: TcxLabel; cxLabel29: TcxLabel; cxLabel30: TcxLabel; cxLabel31: TcxLabel; cxLabel34: TcxLabel; cxLabel35: TcxLabel; cxLabel22: TcxLabel; cxLabel23: TcxLabel; cxLabel24: TcxLabel; cxLabel25: TcxLabel; cxLabel26: TcxLabel; cxLabel27: TcxLabel; cxLabel32: TcxLabel; cxLabel33: TcxLabel; pnlTitle: TPanel; BtnClose: TcxButton; clbCuSeq: TcxLabel; cxGroupBox1: TcxGroupBox; Panel2: TPanel; cboBubinCode: TcxComboBox; cxGroupBox2: TcxGroupBox; cxtEd1: TcxTextEdit; cxtSA1: TcxTextEdit; cxLabel19: TcxLabel; edtCuEmail: TcxTextEdit; cxLabelWkBrNo: TcxLabel; edtCuEmail_Potal: TcxTextEdit; cboEmail: TcxComboBox; cxGroupBox3: TcxGroupBox; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; cxCustTel: TcxGridBandedTableView; cxCustTelColumn1: TcxGridBandedColumn; cxCustTelColumn2: TcxGridBandedColumn; cxCustTelColumn3: TcxGridBandedColumn; cxCustTelColumn4: TcxGridBandedColumn; cxCustTelColumn5: TcxGridBandedColumn; cxCustTelColumn6: TcxGridBandedColumn; Shape8: TShape; Shape1: TShape; Shape2: TShape; Shape4: TShape; Shape5: TShape; Shape6: TShape; Shape7: TShape; Shape9: TShape; Shape10: TShape; Shape11: TShape; Shape12: TShape; Shape13: TShape; Shape14: TShape; Shape15: TShape; Shape18: TShape; Shape19: TShape; Shape20: TShape; Shape21: TShape; Shape22: TShape; Shape23: TShape; Shape24: TShape; Shape25: TShape; Shape26: TShape; Shape27: TShape; cxLblActive: TLabel; Shape28: TShape; cxLabel36: TcxLabel; cbOutBound: TcxComboBox; chkStickYn: TcxCheckBox; btnBlockWKList: TcxButton; btnCallBell: TcxButton; Shape29: TShape; cxLabel37: TcxLabel; cb_CarType: TcxComboBox; Shape30: TShape; Shape31: TShape; chkMileSmsYn: TcxCheckBox; Shape32: TShape; chkAppUseYn: TcxCheckBox; cxGroupBox4: TcxGroupBox; Shape3: TShape; cxGroupBox5: TcxGroupBox; cxLabel38: TcxLabel; cedtLimitCountA: TcxCurrencyEdit; cedtLimitAmtA: TcxCurrencyEdit; cxLabel39: TcxLabel; cedtLimitCountB: TcxCurrencyEdit; cedtLimitAmtB: TcxCurrencyEdit; cxLabel40: TcxLabel; cedtLimitCountC: TcxCurrencyEdit; cedtLimitAmtC: TcxCurrencyEdit; cboCuBubin: TcxComboBox; cxLabel3: TcxLabel; edt_CbPositionName: TcxTextEdit; cxLabel41: TcxLabel; Shape33: TShape; chk_RejectBaechaSmsYn: TcxCheckBox; cxGroupBox6: TcxGroupBox; cxLabel13: TcxLabel; cxLabel14: TcxLabel; cxLabel42: TcxLabel; edt_CardMemo: TcxTextEdit; meoCuCCMemo: TcxMemo; meoCuWorMemo: TcxMemo; chkMemoDisplay: TcxCheckBox; cxLabel43: TcxLabel; cxLabel44: TcxLabel; cxLabel45: TcxLabel; cxLabel46: TcxLabel; cxLabel47: TcxLabel; cxLabel48: TcxLabel; grpAIReCall: TcxGroupBox; rbAIReCallD: TcxRadioButton; rbAIReCallY: TcxRadioButton; rbAIReCallN: TcxRadioButton; cxLabel49: TcxLabel; img2: TImage; procedure FormCreate(Sender: TObject); procedure rdoCuGb3Click(Sender: TObject); procedure RbButton23Click(Sender: TObject); procedure RbButton24Click(Sender: TObject); procedure cboBranchClick(Sender: TObject); procedure btnInitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure meoStartAreaCUTExit(Sender: TObject); procedure meoStartAreaCUTKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure meoStartAreaCUTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSaveClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure chkBrTelYNClick(Sender: TObject); procedure cboBranchPropertiesChange(Sender: TObject); procedure nm_CustSMSClick(Sender: TObject); procedure meoEndAreaCUTExit(Sender: TObject); procedure meoEndAreaCUTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure meoEndAreaCUTKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cxtStartXvalPropertiesChange(Sender: TObject); procedure btnBeforeClick(Sender: TObject); procedure cboEmailPropertiesChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cxCustTelKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cxCustTelEditKeyPress(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Char); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure pnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormShow(Sender: TObject); procedure btnBlockWKListClick(Sender: TObject); procedure btnCallBellClick(Sender: TObject); procedure edtCuNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure img2Click(Sender: TObject); private { Private declarations } ls_ActiveControl: string; FCustBrTelYN: string; CustGroup : TCustGroup; igT11Top, igT11Left : Integer; // 법인정보 셋팅 procedure proc_bubin_init; // 고객 조회 procedure proc_Cust_Search; procedure SetCustBrTelYN(const Value: string); procedure SetCustLevelData; procedure DefaultCustLevel; function GetCustLevelSeq: string; procedure SetCustLevelSeq(ASeq: string); function proc_AIOB_CtrlYN : string; public { Public declarations } J30ShowS, J30ShowE : Boolean; //접수, 수정, 문의 에 따른 조회창 띄울지 여부값 lcsSta1, lcsSta2, lcsSta3: string; // 출1, 출2, 출3 lcsEnd1, lcsEnd2, lcsEnd3: string; // 도1, 도2, 도3 pCUT011Dock : TUNDOCKMNG; property CustBrTelYN: string read FCustBrTelYN write SetCustBrTelYN; // 창초기화 procedure proc_cust_Intit; // 접수화면의 기본 컨트롤을 초기화 한다. procedure FControlInitial(bBrNoSetType: boolean = False); // 선택된 지사정보에서 지사코드호를 추출 한다. function Proc_BRNOSearch: string; // 선택된 지사정보에서 대표번호를 추출 한다. function Proc_MainKeyNumberSearch: string; // 선택된 지사정보에서 본사코드를 추출 한다. function Proc_HDNOSearch: string; // 전문 결과처리 procedure proc_recieve(ls_rxxml: Widestring); // 출발지, 도착지 컨트롤에서 KeyDown 이벤트시에 호출됨. procedure Proc_AreaSearchKDown(iType: Integer); // 고객번호 중복체크(0 : 신규, 1 : 수정) function func_tel_check(iType: Integer): Boolean; // 고객저장(0 : 추가, 1 : 수정, 2 : 삭제, 3 : 법인정보만수정) procedure proc_save_customer(iType: Integer); procedure proc_search_brKeyNum(sBrNo, sKeyNum: string); procedure Hide_Panel(Panel: string; Showhide : integer); procedure Grid_Clear(Panel: string; Grid: Integer); procedure lcs_Clear(Panel: string); procedure Proc_AreaSearchKDown_Added(Key: Word); procedure SetStartAreaMap(const ASido, AGugun, ADong, ADetail, AX, AY: string); procedure SetEndAreaMap(const ASido, AGugun, ADong, ADetail, AX, AY: string); procedure Proc_Jon012Show; end; var Frm_CUT011: TFrm_CUT011; implementation {$R *.dfm} uses StrUtils, xe_Dm, xe_Func, xe_Msg, xe_xml, xe_gnl2, Main, xe_JON012, xe_JON30, xe_Lib, xe_Query, xe_SMS01, xe_Flash, xe_CUT014, xe_BTN, xe_BTN01, xe_AIC10, xe_packet; procedure TFrm_CUT011.FormCreate(Sender: TObject); var i: integer; EnvFile: TIniFile; begin EnvFile := TIniFile.Create(ENVPATHFILE); try Self.Left := EnvFile.ReadInteger('WinPos', 'Cut011Left', 0); Self.Top := EnvFile.ReadInteger('WinPos', 'Cut011Top', 0); igT11Top := Self.Top; igT11Left := Self.Left; if Self.Left < 0 then Self.Left := 0; if Self.Top < 0 then Self.Top := 0; finally EnvFile.Free; end; // 고객 검색 그리드 cxCustTel.DataController.SetRecordCount(0); for i := 0 to cxCustTel.ColumnCount - 1 do cxCustTel.Columns[i].DataBinding.ValueType := 'String'; cxCustTel.OptionsView.NoDataToDisplayInfoText := ''; // 접수화면의 기본 컨트롤을 초기화 한다. // False : 컨트롤초기화 안함. True : 지사코드 재로드 한다. FControlInitial(True); end; procedure TFrm_CUT011.FormDeactivate(Sender: TObject); begin cxLblActive.Color := GS_ActiveColor; cxLblActive.Visible := False; end; procedure TFrm_CUT011.FormDestroy(Sender: TObject); begin Frm_CUT011 := Nil; end; procedure TFrm_CUT011.FormShow(Sender: TObject); begin fSetFont(Frm_CUT011, GS_FONTNAME); Self.Top := igT11Top; Self.Left := igT11Left; end; // 접수화면의 기본 컨트롤을 초기화 한다. procedure TFrm_CUT011.FControlInitial(bBrNoSetType: boolean = False); var i : Integer; begin FCustBrTelYN := ''; btnCallBell.visible := False; edtCuName.Text := ''; // 고객명 cboCuBubin.Properties.Items.Clear; cboCuBubin.ItemIndex := -1; // 법인명(법인정보) cboBubinCode.Properties.Items.Clear; edt_CbPositionName.Text := '';//직책 meoStartAreaCUT.Clear; // 출발지 추가정보 cxtStartXval.Text := ''; // 출발지 X좌표 cxtStartYval.Text := ''; // 출발지 Y좌표 lblStartAreaName.Caption := ''; // 출발지 주소 cxtStartAreaDetail.Text := ''; // 출발지 상세지명(로컬저장용) meoEndAreaCUT.Clear; // 도착지 추가정보 cxtEndXval.Text := ''; // 도착지 X좌표 cxtEndYval.Text := ''; // 도착지 Y좌표 lblEndAreaName.Caption := ''; // 도착지 주소 cxtEndAreaDetail.Text := ''; // 도착지 상세지명(로컬저장용) cxTextEdit2.Text := ''; edtOKC1.Clear; edtOKC2.Clear; edtOKC3.Clear; edtOKC4.Clear; meoCuCCMemo.Text := ''; meoCuWorMemo.Text := ''; meoStartAreaCUT.Text := ''; lblStartAreaName.Caption := ''; cxtStartAreaDetail.Text := ''; cxtStartXval.Text := ''; cxtStartYval.Text := ''; meoEndAreaCUT.Text := ''; lblEndAreaName.Caption := ''; cxtEndXval.Text := ''; cxtEndYval.Text := ''; cxtEndAreaDetail.Text := ''; dtpResvDate.Caption := ''; cxLabel7.Caption := ''; cxLabel10.Caption := ''; cxLabel12.Caption := ''; cxLabel16.Caption := ''; rdoCuGb1.Checked := True; cboBranch.Enabled := True; cboBranch.Properties.ReadOnly := False; clbCuSeq.Caption := ''; cxCustTel.DataController.SetRecordCount(0); edtCuEmail.Text := ''; edtCuEmail_Potal.text := ''; cboEmail.ItemIndex := 0; lcsSta1 := ''; lcsSta2 := ''; lcsSta3 := ''; // 출1/시도, 출2/시군구, 출3/읍면동 lcsEnd1 := ''; lcsEnd2 := ''; lcsEnd3 := ''; // 도1/시도, 도2/시군구, 도3/읍면동 if Self.Tag in [49, 59, 69, 79] then //접수창에서 띄운경우 begin if cboBranch.Properties.Items.Count <> scb_DsBranchCode.Count then begin cboBranch.Tag := 10; // 지사 선택 정보가 변경되면 일부 컨트롤을 초기화 되는 현상을 방지한다. cboBranch.Properties.Items.Clear; // 지사명 // 지사리스트를 담는다. for i := 0 to scb_DsBranchCode.Count - 1 do //scb_FamilyDsBranchCode begin // 본사코드 // 지사코드 // 지사명 // 대표번호 if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB begin if pCUT011Dock.HDNO = scb_HeadCode[i] then cboBranch.Properties.Items.Add(scb_HeadCode[i] + '.' + scb_DsBranchCode[i] + ': ' + scb_DsBranchName[i] + '[' + scb_KeyNumber[i] + ']'); end else cboBranch.Properties.Items.Add(scb_HeadCode[i] + '.' + scb_DsBranchCode[i] + ': ' + scb_DsBranchName[i] + '[' + scb_KeyNumber[i] + ']'); end; if cboBranch.Properties.Items.Count > 0 then cboBranch.ItemIndex := 0; cboBranch.Tag := 0; // 지사 선택 정보가 변경되면 일부 컨트롤을 초기화 되는 현상을 방지한다. cxLabel21.Caption := ''; cxLabel23.Caption := ''; cxLabel25.Caption := ''; cxLabel27.Caption := ''; cxLabel29.Caption := ''; cxLabel31.Caption := ''; cxLabel33.Caption := ''; cxLabel35.Caption := ''; end; end else begin if Not pCUT011Dock.bUnDock then pCUT011Dock.HDNO := GT_SEL_BRNO.HDNO; if cboBranch.Properties.Items.Count <> scb_DsBranchCode.Count then begin cboBranch.Tag := 10; // 지사 선택 정보가 변경되면 일부 컨트롤을 초기화 되는 현상을 방지한다. cboBranch.Properties.Items.Clear; // 지사명 // 지사리스트를 담는다. for i := 0 to scb_DsBranchCode.Count - 1 do //scb_FamilyDsBranchCode begin // 본사코드 // 지사코드 // 지사명 // 대표번호 if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB begin if pCUT011Dock.HDNO = scb_HeadCode[i] then cboBranch.Properties.Items.Add(scb_HeadCode[i] + '.' + scb_DsBranchCode[i] + ': ' + scb_DsBranchName[i] + '[' + scb_KeyNumber[i] + ']'); end else cboBranch.Properties.Items.Add(scb_HeadCode[i] + '.' + scb_DsBranchCode[i] + ': ' + scb_DsBranchName[i] + '[' + scb_KeyNumber[i] + ']'); end; if cboBranch.Properties.Items.Count > 0 then cboBranch.ItemIndex := 0; cboBranch.Tag := 0; // 지사 선택 정보가 변경되면 일부 컨트롤을 초기화 되는 현상을 방지한다. cxLabel21.Caption := ''; cxLabel23.Caption := ''; cxLabel25.Caption := ''; cxLabel27.Caption := ''; cxLabel29.Caption := ''; cxLabel31.Caption := ''; cxLabel33.Caption := ''; cxLabel35.Caption := ''; end; end; edt_CardMemo.Text := ''; if TCK_USER_PER.JON_CUSTMEMO2 = '1' then edt_CardMemo.Enabled := True else edt_CardMemo.Enabled := False; cb_CarType.ItemIndex := 1; //2종이 기본값 rbAIReCallD.Checked := True; grpAIReCall.Enabled := False; img2.Visible := Not grpAIReCall.Enabled; end; procedure TFrm_CUT011.rdoCuGb3Click(Sender: TObject); begin cboCuBubin.Enabled := (rdoCuGb3.Checked) And ( TCK_USER_PER.JON_BUBININFO <> '1'); edt_CbPositionName.Enabled := cboCuBubin.Enabled ; end; procedure TFrm_CUT011.RbButton23Click(Sender: TObject); Var iRow : Integer; begin if (cxCustTel.DataController.RecordCount <= 15) then begin iRow := cxCustTel.DataController.AppendRecord; cxCustTel.DataController.Values[iRow, 0] := ''; cxCustTel.DataController.Values[iRow, 1] := '수신'; cxCustTel.DataController.Values[iRow, 2] := ''; cxCustTel.DataController.Values[iRow, 3] := '해제'; cxCustTel.DataController.SetFocus; end; end; procedure TFrm_CUT011.RbButton24Click(Sender: TObject); Var iSelRow : Integer; begin iSelRow := cxCustTel.DataController.FocusedRecordIndex; if iSelRow = -1 then Exit; if ( cxCustTel.DataController.Values[iSelRow, 0] <> '' ) And ( cxCustTel.DataController.Values[iSelRow, 0] <> Null ) then begin if GMessagebox(cxCustTel.DataController.Values[iSelRow, 0] + ' 번호를 삭제하시겠습니까?', CDMSQ) = idOK then cxCustTel.DataController.DeleteRecord(iSelRow); end else begin cxCustTel.DataController.DeleteRecord(iSelRow); end; end; procedure TFrm_CUT011.proc_bubin_init; var i: Integer; sBrNo, sKeyNum: string; begin sBrNo := Proc_BRNOSearch; sKeyNum := Proc_MainKeyNumberSearch; cboCuBubin.Properties.Items.Clear; cboBubinCode.Properties.Items.Clear; cboCuBubin.Properties.Items.Add('선택'); cboBubinCode.Properties.Items.Add(''); btnBlockWKList.Visible := False; for i := 0 to GT_BUBIN_INFO.brNo_KeyNum.Count - 1 do begin if GT_BUBIN_INFO.brNo_KeyNum.Strings[i] = Rpad(sbrNo, 5, ' ') + Rpad(StringReplace(sKeyNum, '-', '', [rfReplaceAll]), 15, ' ') then begin cboCuBubin.Properties.Items.Add(Trim(GT_BUBIN_INFO.cbCorpNm.Strings[i]) + ' / ' + Trim(GT_BUBIN_INFO.cbDeptNm.Strings[i])); cboBubinCode.Properties.Items.Add(GT_BUBIN_INFO.cbcode.Strings[i]); end; end; if rdoCuGb3.Checked then cboCuBubin.ItemIndex := 0 else cboCuBubin.ItemIndex := -1; end; function TFrm_CUT011.Proc_BRNOSearch: string; begin Result := Copy(cboBranch.Text, Pos('.', cboBranch.Text) + 1, Pos(':', cboBranch.Text) - (Pos('.', cboBranch.Text) + 1)); //지사코드 end; function TFrm_CUT011.Proc_MainKeyNumberSearch: string; var iPos2: Integer; sKeyNumber, sTmp: string; begin Result := ''; sTmp := cboBranch.Text; if sTmp = '' then Exit; while (True) do begin iPos2 := Pos('[', Copy(sTmp, 1, Length(sTmp))); if iPos2 = 0 then begin sKeyNumber := Copy(sTmp, 1, Length(sTmp) - 1); Break; end; sTmp := Copy(sTmp, iPos2 + 1, Length(sTmp)); end; Result := sKeyNumber; end; procedure TFrm_CUT011.proc_Cust_Search; var ls_TxLoad, sNode, sHdNo, sBrNo, sKeyNumber: string; ls_rxxml: WideString; xdom: msDOMDocument; lst_Node: IXMLDOMNodeList; slReceive: TStringList; rv_str: string; ErrCode: integer; begin if StrToIntDef(clbCuSeq.Caption, -1) = -1 then Exit; ls_rxxml := GTx_UnitXmlLoad('C034N1.XML'); xdom := ComsDOMDocument.Create; try if (not xdom.loadXML(ls_rxxml)) then begin Screen.Cursor := crDefault; ShowMessage('전문 Error입니다. 다시조회하여주십시요.'); Exit; end; sNode := '/cdms/header/UserID'; lst_Node := xdom.documentElement.selectNodes(sNode); lst_Node.item[0].attributes.getNamedItem('Value').Text := En_Coding(GT_USERIF.ID); sNode := '/cdms/header/ClientVer'; lst_Node := xdom.documentElement.selectNodes(sNode); lst_Node.item[0].attributes.getNamedItem('Value').Text := VERSIONINFO; sNode := '/cdms/header/ClientKey'; lst_Node := xdom.documentElement.selectNodes(sNode); lst_Node.item[0].attributes.getNamedItem('Value').Text := 'CUT111'; sNode := '/cdms/Service/Customers'; lst_Node := xdom.documentElement.selectNodes(sNode); sHdNo := Proc_HDNOSearch; sBrNo := Proc_BRNOSearch; sKeyNumber := Proc_MainKeyNumberSearch; lst_Node.item[0].attributes.getNamedItem('action').Text := 'SELECT'; lst_Node.item[0].attributes.getNamedItem('CuSeq').Text := clbCuSeq.Caption; lst_Node.item[0].attributes.getNamedItem('HdNo').Text := sHdNo; lst_Node.item[0].attributes.getNamedItem('BrNo').Text := sBrNo; lst_Node.item[0].attributes.getNamedItem('KeyNumber').Text := sKeyNumber; ls_TxLoad := '<?xml version="1.0" encoding="euc-kr"?>' + #13#10 + xDom.documentElement.xml; ls_TxLoad := StringReplace(ls_TxLoad, 'InDate=""', 'InDate="" BrTelYN="" CuEmail=""', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'CuSmsYN=""', 'CuSmsYN="" CuSmsMiDate="" CuVirtualYn="" CuVirtualTel="" CuVirtualDate=""', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'InDate=""', 'InDate="" AppCode="" AppLastRegDate="" AppLastDelDate="" AppLastFinishDate=""', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'AppLastFinishDate=""', 'AppLastFinishDate="" AppCuArea="" AppTermModel="" AppTermOS="" AppDelYn="" CuMemo=""', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'AppDelYn=""', 'AppDelYn="" AppGroup="" AppVersion=""' , [rfReplaceAll]); slReceive := TStringList.Create; try if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then begin rv_str := slReceive[0]; if rv_str <> '' then begin ls_rxxml := rv_str; Application.ProcessMessages; proc_recieve(ls_rxxml); end; end; finally Frm_Flash.Hide; FreeAndNil(slReceive); end; finally xdom := Nil; end; end; function TFrm_CUT011.Proc_HDNOSearch: string; begin Result := Copy(cboBranch.Text, 1, Pos('.', cboBranch.Text) - 1); // 본사코드 end; procedure TFrm_CUT011.proc_recieve(ls_rxxml: Widestring); var xdom: msDomDocument; ls_ClientKey, ls_Msg_Err, sTemp: string; lst_Result: IXMLDomNodeList; ls_Rcrd: TStringList; i, iRow, iEndCnt, iCancelCnt, iMileage, iPrizeCnt, ia: Integer; sBrNo, sCbCode, sMsg, OkCashBack, sEmail, sEmailPotal, sContent, sCarType, sAIOB, sDisplayMemo: string; sTmp : string ; bLimitUseYn : Boolean; begin try xdom := ComsDomDocument.Create; try if not xdom.loadXML(ls_rxxml) then Exit; lcsActiveEdit := 'meoEndAreaCUT'; // 활성화 된 출발지, 도착지 Edit 구분을 저장. ls_ClientKey := GetXmlClientKey(ls_rxxml); ls_ClientKey := Copy(ls_ClientKey, 6, Length(ls_ClientKey) - 5); case StrToIntDef(ls_ClientKey, 1) of 1: begin ls_Msg_Err := GetXmlErrorCode(ls_rxxml); sMsg := GetXmlErrorMsg(ls_rxxml); if ('0000' <> ls_Msg_Err) then begin GMessagebox(sMsg, CDMSE); Exit; end; lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Customers/Customer'); //직책, 배차문자수신거부 edt_CbPositionName.Text := lst_Result.item[0].attributes.getNamedItem('CbPositionName').Text; // sTmp := lst_Result.item[0].attributes.getNamedItem('RejectBaechaSmsYn').Text; // if sTmp = 'y' then chk_RejectBaechaSmsYn.Checked := True // else chk_RejectBaechaSmsYn.Checked := False; //AI 아웃바운드 옵션 배차지연콜 사용여부 20190716 KHS sTmp := Proc_MainKeyNumberSearch; if not GetAIOBKeyNumberYN(sTmp) then //고객이 선택되어 있어도 지사의 대표번호에서 사용안하면 체크해제 begin grpAIReCall.Enabled := False; end else begin sAIOB := lst_Result.item[0].attributes.getNamedItem('AiOutOption').Text; if sAIOB = 'y' then rbAIReCallY.Checked := True else if sAIOB = 'n' then rbAIReCallN.Checked := True else rbAIReCallD.Checked := True end; img2.Visible := Not grpAIReCall.Enabled; if Assigned(lst_Result.item[0].attributes.getNamedItem('MemoDisplayYn')) then // 상담메모자동표시 begin sDisplayMemo := lst_Result.item[0].attributes.getNamedItem('MemoDisplayYn').Text; if sDisplayMemo = 'y' then chkMemoDisplay.Checked := True else chkMemoDisplay.Checked := False; end; sCarType := lst_Result.item[0].attributes.getNamedItem('CarType').Text; if sCarType = '1' then cb_CarType.ItemIndex := 0 else cb_CarType.ItemIndex := 1; edtCuName.Text := lst_Result.item[0].attributes.getNamedItem('CmpNm').Text; case StrToIntDef(lst_Result.item[0].attributes.getNamedItem('CuType').Text, 0) of 0: rdoCuGb1.Checked := True; 1: rdoCuGb2.Checked := True; 3: rdoCuGb3.Checked := True; end; SetCustLevelSeq(lst_Result.item[0].attributes.getNamedItem('CuLevelCd').Text); sCbCode := lst_Result.item[0].attributes.getNamedItem('CbCode').Text; if (sCbCode <> '') then begin sBrNo := Proc_BRNOSearch; iRow := cboBubinCode.Properties.Items.IndexOf(sCbCode + ',' + sBrNo); if iRow > 0 then cboCuBubin.ItemIndex := iRow; end; sTemp := lst_Result.item[0].attributes.getNamedItem('CmpNo').Text; if Length(sTemp) = 13 then sTemp := Copy(sTemp, 1, 6) + '-' + Copy(sTemp, 7, 7); cxTextEdit2.Text := sTemp; OkCashBack := lst_Result.item[0].attributes.getNamedItem('CBNo').text; if Length(OkCashBack) = 16 then begin edtOKC1.Text := Copy(OkCashBack, 1, 4); edtOKC2.Text := Copy(OkCashBack, 5, 4); edtOKC3.Text := Copy(OkCashBack, 9, 4); edtOKC4.Text := Copy(OkCashBack, 13, 4); end else begin edtOKC1.Clear; edtOKC2.Clear; edtOKC3.Clear; edtOKC4.Clear; end; // 고객상황실설정 if Assigned(lst_Result.item[0].attributes.getNamedItem('BrTelYN')) then CustBrTelYN := lst_Result.item[0].attributes.getNamedItem('BrTelYN').Text; chkBrTelYN.Checked := (CustBrTelYN = 'y'); sTemp := lst_Result.item[0].attributes.getNamedItem('InDate').Text; if sTemp <> '' then begin sTemp := Copy(sTemp, 1, 4) + '-' + Copy(sTemp, 5, 2) + '-' + Copy(sTemp, 7, 2); dtpResvDate.Caption := sTemp; end else dtpResvDate.Caption := ''; iEndCnt := StrToIntDef(lst_Result.item[0].attributes.getNamedItem('CuEndCnt').Text, 0); iCancelCnt := StrToIntDef(lst_Result.item[0].attributes.getNamedItem('CuCancelCnt').Text, 0); iMileage := StrToIntDef(lst_Result.item[0].attributes.getNamedItem('CuMileage').Text, 0); iPrizeCnt := StrToIntDef(lst_Result.item[0].attributes.getNamedItem('CuPrizeCnt').text, 0); cxLabel7.Caption := IntToStr(iEndCnt) + ' / ' + IntToStr(iCancelCnt); sTemp := lst_Result.item[0].attributes.getNamedItem('CuLastEnd').Text; if sTemp <> '' then begin sTemp := Copy(sTemp, 1, 4) + '-' + Copy(sTemp, 5, 2) + '-' + Copy(sTemp, 7, 2); cxLabel10.Caption := sTemp; end else cxLabel10.Caption := ''; cxLabel12.Caption := FormatFloat('#,##0', StrToFloatDef(IntToStr(iMileage), 0.0)); cxLabel16.Caption := IntToStr(iPrizeCnt); sContent := StringReplace(lst_Result.item[0].attributes.getNamedItem('CuInfo').Text, '│', '|', [rfReplaceAll]); sContent := StringReplace(sContent, '|', '¶', [rfReplaceAll]); if Trim(sContent) <> '' then begin ls_Rcrd := TStringList.Create; try GetTextSeperationEx2('¶', sContent, ls_Rcrd); for ia := 0 to ls_Rcrd.Count - 1 do begin meoCuCCMemo.Lines.Add(ls_Rcrd[ia]); end; finally FreeAndNil(ls_Rcrd); end; end; sContent := StringReplace(lst_Result.item[0].attributes.getNamedItem('CuPdaInfo').Text, '│', '|', [rfReplaceAll]); sContent := StringReplace(sContent, '|', '¶', [rfReplaceAll]); if Trim(sContent) <> '' then begin ls_Rcrd := TStringList.Create; try GetTextSeperationEx2('¶', sContent, ls_Rcrd); for ia := 0 to ls_Rcrd.Count - 1 do begin meoCuWorMemo.Lines.Add(ls_Rcrd[ia]); end; finally FreeAndNil(ls_Rcrd); end; end; edt_CardMemo.Text := lst_Result.item[0].attributes.getNamedItem('CuMemo').Text; meoStartAreaCUT.Text := lst_Result.item[0].attributes.getNamedItem('CuArea5').Text; // 출1/시도, 출2/시군구, 출3/읍면동 lcsSta1 := lst_Result.item[0].attributes.getNamedItem('CuArea').Text; lcsSta2 := lst_Result.item[0].attributes.getNamedItem('CuArea2').Text; lcsSta3 := lst_Result.item[0].attributes.getNamedItem('CuArea3').Text; cxtSA1.Text := lcsSta1; cxtSA2.Text := lcsSta2; cxtSA3.Text := lcsSta3; lblStartAreaName.Caption := lcsSta1 + ' ' + lcsSta2 + ' ' + lcsSta3; cxtStartAreaDetail.Text := lst_Result.item[0].attributes.getNamedItem('CuArea4').Text; cxtStartXval.Text := lst_Result.item[0].attributes.getNamedItem('CuMapX').Text; cxtStartYval.Text := lst_Result.item[0].attributes.getNamedItem('CuMapY').Text; meoEndAreaCUT.Text := lst_Result.item[0].attributes.getNamedItem('CuEdArea5').Text; // 도1/시도, 도2/시군구, 도3/읍면동 lcsEnd1 := lst_Result.item[0].attributes.getNamedItem('CuEdArea').Text; lcsEnd2 := lst_Result.item[0].attributes.getNamedItem('CuEdArea2').Text; lcsEnd3 := lst_Result.item[0].attributes.getNamedItem('CuEdArea3').Text; cxtEd1.Text := lcsEnd1; cxtEd2.Text := lcsEnd2; cxtEd3.Text := lcsEnd3; lblEndAreaName.Caption := lcsEnd1 + ' ' + lcsEnd2 + ' ' + lcsEnd3; cxtEndAreaDetail.Text := lst_Result.item[0].attributes.getNamedItem('CuEdArea4').Text; cxtEndXval.Text := lst_Result.item[0].attributes.getNamedItem('CuEdMapX').Text; cxtEndYval.Text := lst_Result.item[0].attributes.getNamedItem('CuEdMapY').Text; sEmail := lst_Result.item[0].attributes.getNamedItem('CuEmail').Text; if sEmail <> '' then begin edtCuEmail.Text := LeftStr(sEmail, Pos('@', sEmail) - 1); sEmailPotal := copy(sEmail, length(edtCuEmail.Text + '@')+1,length(sEmail+'@') - length(edtCuEmail.Text + '@')); if cboEmail.Properties.Items.IndexOf(sEmailPotal) > -1 then cboEmail.ItemIndex := cboEmail.Properties.Items.IndexOf(sEmailPotal) else edtCuEmail_Potal.Text := sEmailPotal; end; // 2013.03.30 khs if lst_Result.item[0].attributes.getNamedItem('CuOrderOption').Text = 'y' then chkStickYn.Checked := True else chkStickYn.Checked := False; if lst_Result.item[0].attributes.getNamedItem('CuAppBlock').Text = 'y' then chkAppUseYn.Checked := True else chkAppUseYn.Checked := False; if Trim(lst_Result.item[0].attributes.getNamedItem('AppCode').Text) <> '' then begin cxLabel21.Caption := lst_Result.item[0].attributes.getNamedItem('AppCode').Text; cxLabel23.Caption := lst_Result.item[0].attributes.getNamedItem('AppLastRegDate').Text; cxLabel25.Caption := lst_Result.item[0].attributes.getNamedItem('AppLastDelDate').Text; cxLabel27.Caption := lst_Result.item[0].attributes.getNamedItem('AppLastFinishDate').Text; cxLabel29.Caption := lst_Result.item[0].attributes.getNamedItem('AppCuArea').Text; cxLabel31.Caption := lst_Result.item[0].attributes.getNamedItem('AppGroup').Text + '/' + lst_Result.item[0].attributes.getNamedItem('AppTermOS').Text + '/' + lst_Result.item[0].attributes.getNamedItem('AppTermModel').Text; cxLabel33.Caption := lst_Result.item[0].attributes.getNamedItem('AppVersion').Text; end; if lst_Result.item[0].attributes.getNamedItem('AppDelYn').Text = 'y' then cxLabel35.Caption := '어플삭제' else if lst_Result.item[0].attributes.getNamedItem('AppDelYn').Text = 'n' then cxLabel35.Caption := '미삭제' else cxLabel35.Caption := ''; if lst_Result.item[0].attributes.getNamedItem('CuOutBound').Text = '' then cbOutBound.ItemIndex := -1 else // 고객 아웃바운드 상태 if lst_Result.item[0].attributes.getNamedItem('CuOutBound').Text = '1' then cbOutBound.ItemIndex := 0 else if lst_Result.item[0].attributes.getNamedItem('CuOutBound').Text = '2' then cbOutBound.ItemIndex := 1 else if lst_Result.item[0].attributes.getNamedItem('CuOutBound').Text = '3' then cbOutBound.ItemIndex := 2; if lst_Result.item[0].attributes.getNamedItem('SelMileSendYn').Text = 'y' then chkMileSmsYn.Checked := True else chkMileSmsYn.Checked := False; if Assigned(lst_Result.item[0].attributes.getNamedItem('LimitUseYN')) then bLimitUseYn := lst_Result.item[0].attributes.getNamedItem('LimitUseYN').Text = 'y'; cxGroupBox5.Enabled := bLimitUseYn; if Assigned(lst_Result.item[0].attributes.getNamedItem('LimiDefaultCnt')) then cedtLimitCountA.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('LimiDefaultCnt').Text, 0); if Assigned(lst_Result.item[0].attributes.getNamedItem('LimiDefaultCharge')) then cedtLimitAmtA.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('LimiDefaultCharge').Text, 0); if Assigned(lst_Result.item[0].attributes.getNamedItem('CBLimitCnt')) then cedtLimitCountB.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('CBLimitCnt').Text, 0); if Assigned(lst_Result.item[0].attributes.getNamedItem('CBLimitCharge')) then cedtLimitAmtB.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('CBLimitCharge').Text, 0); if Assigned(lst_Result.item[0].attributes.getNamedItem('CBUseCnt')) then cedtLimitCountC.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('CBUseCnt').Text, 0); if Assigned(lst_Result.item[0].attributes.getNamedItem('CBUseCharge')) then cedtLimitAmtC.Value := StrToFloatDef(lst_Result.item[0].attributes.getNamedItem('CBUseCharge').Text, 0); lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Customers/TelNums'); if lst_Result.length > 0 then begin cxCustTel.BeginUpdate; cxCustTel.DataController.SetRecordCount(0); for i := 0 to lst_Result.length - 1 do begin iRow := cxCustTel.DataController.AppendRecord; cxCustTel.DataController.Values[iRow, 0] := strtocall(lst_Result.item[i].attributes.getNamedItem('CuTel').Text); if lst_Result.item[i].attributes.getNamedItem('CuSmsYN').Text = 'y' then begin cxCustTel.DataController.Values[iRow, 1] := '수신'; cxCustTel.DataController.Values[iRow, 2] := ''; end else begin cxCustTel.DataController.Values[iRow, 1] := '미수신'; cxCustTel.DataController.Values[iRow, 2] := Date8to10(lst_Result.item[i].attributes.getNamedItem('CuSmsMiDate').Text); end; if lst_Result.item[i].attributes.getNamedItem('CuVirtualYn').Text = 'y' then begin cxCustTel.DataController.Values[iRow, 3] := '할당'; cxCustTel.DataController.Values[iRow, 4] := lst_Result.item[i].attributes.getNamedItem('CuVirtualTel').Text; end else begin cxCustTel.DataController.Values[iRow, 3] := '해제'; cxCustTel.DataController.Values[iRow, 4] := ''; end; end; cxCustTel.EndUpdate; end; end; 2: begin ls_Msg_Err := GetXmlErrorCode(ls_rxxml); sMsg := GetXmlErrorMsg(ls_rxxml); if ('0000' = ls_Msg_Err) and ('1' = sMsg) then begin GMessagebox('성공하였습니다.', CDMSI); if Self.Tag = 49 then begin Frm_Main.Frm_JON01N[StrToInt(self.Hint)].Proc_KeyNumberSearch(Proc_MainKeyNumberSearch); end else if Self.Tag = 69 then // 69 : 수정창에서 고객수정 begin Frm_Main.Frm_JON01N[StrToInt(self.Hint)].edtCuName.Text := Trim(edtCuName.Text); Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cboCuLevel.ItemIndex := cboCuLevel.ItemIndex; if rdoCuGb1.Checked then Frm_Main.Frm_JON01N[StrToInt(self.Hint)].CbCuGb.ItemIndex := 0 else if rdoCuGb2.Checked then Frm_Main.Frm_JON01N[StrToInt(self.Hint)].CbCuGb.ItemIndex := 1 else if rdoCuGb3.Checked then Frm_Main.Frm_JON01N[StrToInt(self.Hint)].CbCuGb.ItemIndex := 2; sTmp := Trim(Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cxtCuTel.text); for i := 0 to cxCustTel.DataController.RowCount - 1 do begin if sTmp = CallToStr(cxCustTel.DataController.Values[i, 0]) then begin Frm_Main.Frm_JON01N[StrToInt(self.Hint)].ChkCuSmsNo.Tag := 99; if cxCustTel.DataController.Values[i, 1] = '미수신' then Frm_Main.Frm_JON01N[StrToInt(self.Hint)].ChkCuSmsNo.checked := True else Frm_Main.Frm_JON01N[StrToInt(self.Hint)].ChkCuSmsNo.checked := False; Frm_Main.Frm_JON01N[StrToInt(self.Hint)].ChkCuSmsNo.Tag := 0; break; end; end; if (rdoCuGb3.Checked) and (cboCuBubin.ItemIndex > 0) then begin sTmp := cboBubinCode.Properties.Items[cboCuBubin.ItemIndex]; sTmp := Copy(sTmp, 1, Pos(',', sTmp) - 1); Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cxtCuBubin.Hint := sTmp; sBrNo := Proc_BRNOSearch; iRow := GT_BUBIN_INFO.cbcode.IndexOf(Trim(sTmp) + ',' + sBrNo); if iRow > -1 then begin // 법인정보[법인명 + 부서명] Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cxtCuBubin.Text := Trim(GT_BUBIN_INFO.cbCorpNm[iRow]) + ' | ' + Trim(GT_BUBIN_INFO.cbDeptNm[iRow]); Frm_Main.Frm_JON01N[StrToInt(self.Hint)].lblCuBubinName.Caption := '법인고객 [ ' + Trim(Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cxtCuBubin.Text) + ' ]'; end; end; Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cb_CarType.ItemIndex := cb_CarType.ItemIndex; Frm_Main.Frm_JON01N[StrToInt(self.Hint)].chkCenterMng.checked := chkBrTelYN.checked; end else if Self.Tag = 59 then begin if ( cxCustTel.DataController.RecordCount = 1 ) And ( cxCustTel.DataController.Values[0, 0] <> '' ) then begin Frm_Main.Frm_JON01N[StrToInt(self.Hint)].cxtCuTel.Text := StringReplace(cxCustTel.DataController.Values[0, 0], '-', '', [rfReplaceAll]); Frm_Main.Frm_JON01N[StrToInt(self.Hint)].Proc_KeyNumberSearch(Proc_MainKeyNumberSearch); end; end; // Hide; // 코리아 드라이브 문진석 주임 요청으로 고객정보저장후 화면 그대로 표시/ 종료시 화면 닫기 처리 LYB 20141231 if ( Assigned(Frm_JON012) ) Or ( Frm_JON012 <> Nil ) then Frm_JON012.btnCloseClick(nil); end else begin GMessagebox(sMsg, CDMSE); end; end; end; finally xdom := Nil; end; except end; end; procedure TFrm_CUT011.proc_cust_Intit; begin // 6 : 접수창에서 고객수정으로 화면 오픈함 proc_bubin_init; btnCallBell.Visible := False; if Self.Tag in [4, 6, 49, 69] then begin btnSave.Caption := '수정'; proc_Cust_Search; cboBranch.Enabled := False; if (rdoCuGb2.Checked) then //업소이면 begin btnCallBell.Visible := True; btnCallBell.enabled := True; if Not Assigned(Frm_BTN) then Frm_BTN := TFrm_BTN.Create(Nil); Frm_BTN.proc_CallBell_BRANCH_INFO; if Frm_BTN.Scb_BankCd.count = 0 then Frm_BTN.proc_Bank; { if (Frm_BTN.Scb_CallBell_BrNo.indexOf(Proc_BRNOSearch) > -1) and //대표번호에 실착신번호 설정되었을 경우 (Frm_BTN.Scb_CallBell_KeyNumber.indexOf(Proc_MainKeyNumberSearch) > -1) then begin btnCallBell.Visible := True; if Frm_BTN.Scb_CallBell_WKID[Frm_BTN.Scb_CallBell_KeyNumber.indexOf(Proc_MainKeyNumberSearch)] <> '' then begin // Frm_BTN.proc_Bank; btnCallBell.enabled := True; end else btnCallBell.enabled := False; end; } end; end else if Self.Tag in [5, 7, 59, 79] then begin btnSave.Caption := '저장'; cboBranch.Enabled := True; pnlTitle.Caption := ' 고객정보등록'; btnBlockWKList.Visible := False; end; if cxCustTel.DataController.RecordCount > 0 then // btnBeforeClick(nil) // 처음 열었을때 과거이용내역 표시 안함 2021.02.22 최팀장님 요청 else begin if ( Assigned(Frm_JON012) ) Or ( Frm_JON012 <> Nil ) then Frm_JON012.btnCloseClick(nil); end; pnlTitle.Caption := ' 고객정보수정'; btnBlockWKList.Visible := True; cxCustTel.DataController.SetFocus; end; procedure TFrm_CUT011.cboBranchClick(Sender: TObject); begin if cboBranch.Tag in [5, 7] then proc_bubin_init; end; procedure TFrm_CUT011.btnInitClick(Sender: TObject); var iCuType, iIdx: Integer; begin if GMessagebox('작성된 모든게 초기화 됩니다.' + #13#10 + '하시겠습니까?', CDMSQ) = idok then begin if rdoCuGb1.Checked then iCuType := 1 else if rdoCuGb2.Checked then iCuType := 2 else if rdoCuGb3.Checked then iCuType := 3; iIdx := cboCuBubin.ItemIndex; self.Tag := 4; FControlInitial(False); proc_cust_Intit; if iCuType = 1 then rdoCuGb1.Checked := True else if iCuType = 2 then rdoCuGb2.Checked := True else if iCuType = 3 then rdoCuGb3.Checked := True; if iIdx > 0 then cboCuBubin.ItemIndex := iIdx; end; end; procedure TFrm_CUT011.cxCustTelEditKeyPress(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Char); begin if key in ['0'..'9', #13, #8, '-'] then else key := #0; end; procedure TFrm_CUT011.cxCustTelKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Var iSel, iRow : integer; begin case key of VK_RETURN, VK_DOWN: begin iSel := cxCustTel.DataController.FocusedRecordIndex; if (iSel = cxCustTel.DataController.RowCount - 1) and (cxCustTel.DataController.RowCount <= 11) then begin cxCustTel.BeginUpdate; iRow := cxCustTel.DataController.AppendRecord; cxCustTel.DataController.Values[iRow, 1] := '수신'; cxCustTel.DataController.Values[iRow, 3] := '해제'; cxCustTel.EndUpdate; key := 0; end; end; end; end; procedure TFrm_CUT011.FormActivate(Sender: TObject); begin cxLblActive.Color := GS_ActiveColor; cxLblActive.Visible := True; end; procedure TFrm_CUT011.FormClose(Sender: TObject; var Action: TCloseAction); var EnvFile: TIniFile; begin EnvFile := TIniFile.Create(ENVPATHFILE); try EnvFile.WriteInteger('WinPos', 'Cut011Left', Self.Left); EnvFile.WriteInteger('WinPos', 'Cut011Top' , Self.Top ); finally EnvFile.Free; end; Action := caFree; end; procedure TFrm_CUT011.meoStartAreaCUTExit(Sender: TObject); begin if Assigned(Frm_JON30) and (not (meoStartAreaCUT.Focused)) then Hide_Panel('meoStartAreaCUT',1); end; procedure TFrm_CUT011.meoStartAreaCUTKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin lcsActiveEdit := 'meoStartAreaCUT'; // 활성화 된 출발지, 도착지 Edit 구분을 저장. // 좌, 우, HOME, END 방향키는 이벤트 타지 않도록 한다. if (Key = 37) or (Key = 39) or (Key = 35) or (Key = 36) then Exit; if Key = VK_RETURN then begin Key := 0; Exit; end; if Key in [VK_DOWN, VK_UP] then begin Exit; // 그리드에 포커스 넘기는건 KeyUp Event에서 처리한다. end; if Key = VK_BACK then begin if (Length(meoStartAreaCUT.Text) <= 1) then begin // 키워드가 모두 지워진 상태에서 한번더 BACK 키를 누를경우 컨트롤 초기화 처리. lcs_Clear(lcsActiveEdit); gKWComp := ''; gmap_forword := ''; Grid_Clear(lcsActiveEdit,1); Grid_Clear(lcsActiveEdit,2); Grid_Clear(lcsActiveEdit,3); Hide_Panel(lcsActiveEdit,1); Exit; end else if (Length(meoStartAreaCUT.Text) <= 2) then begin gmap_forword := ''; { end else if (Length(meoStartAreaCUT.Text) < Length(map_ls_Text)) then begin map_ls_Text := ''; gmap_forword := ''; -} end; end; end; procedure TFrm_CUT011.Proc_AreaSearchKDown(iType: Integer); var sSearch: string; begin if iType = 0 then begin ls_ActiveControl := 'meoStartAreaCUT'; sSearch := meoStartAreaCUT.Text; end else if iType = 1 then begin ls_ActiveControl := 'meoEndAreaCUT'; sSearch := meoEndAreaCUT.Text; end; end; procedure TFrm_CUT011.meoStartAreaCUTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin TcxMemo(sender).Text := Enc_Control(TcxMemo(sender).Text); lcsActiveEdit := 'meoStartAreaCUT'; // 활성화 된 출발지, 도착지 Edit 구분을 저장. // 검색 그리드로 포커스 이동.. if Key in [VK_DOWN] then begin if Frm_JON30.AdvStringGrid1.Cells[0,1] = '' then begin if Frm_JON30.AdvStringGrid2.Cells[0,0] = '' then begin if Frm_JON30.AdvStringGrid3.Cells[0,0] <> '' then begin Frm_JON30.AdvStringGrid1.ShowSelection := False; Frm_JON30.AdvStringGrid2.ShowSelection := False; Frm_JON30.AdvStringGrid3.ShowSelection := True; Frm_JON30.AdvStringGrid3.SetFocus; //- Frm_JON30.AdvStringGrid3.FocusCell(0,0); end; end else begin Frm_JON30.AdvStringGrid1.ShowSelection := False; Frm_JON30.AdvStringGrid2.ShowSelection := True; Frm_JON30.AdvStringGrid3.ShowSelection := False; Frm_JON30.AdvStringGrid2.SetFocus; Frm_JON30.AdvStringGrid2.FocusCell(0,0); end; end else begin Frm_JON30.AdvStringGrid1.ShowSelection := True; Frm_JON30.AdvStringGrid2.ShowSelection := False; Frm_JON30.AdvStringGrid3.ShowSelection := False; //- Frm_JON30.AdvStringGrid1.FocusCell(1,1); Frm_JON30.AdvStringGrid1.SetFocus; end; end else if Key = VK_BACK then begin // Frm_JON30.gb2ndSearch := False; //확장검색 진행 막음 J30ShowS := False; end else if Key = VK_RETURN then begin if lcsActiveEdit = 'meoStartAreaCUT' then begin if Frm_JON30.Visible = True then begin if Frm_JON30.AdvStringGrid1.Cells[0,1] <> '' then begin Frm_JON30.Proc_SendParent(Frm_JON30.AdvStringGrid1.GetRealRow + 1, True); Hide_Panel(lcsActiveEdit,1); end; if (Frm_JON30.AdvStringGrid1.Cells[0,1] = '') and (Frm_JON30.AdvStringGrid2.Cells[0,0] <> '') then begin Frm_JON30.Proc_SendParent_ADV2(Frm_JON30.AdvStringGrid2.GetRealRow + 1, Frm_JON30.AdvStringGrid2.GetRealCol, True); Hide_Panel(lcsActiveEdit,1); end; meoEndAreaCUT.SetFocus; end; end; end else if (Key = vk_delete) then begin J30ShowS := False; end else // if (key <> 229) then // 20191224 한컴입력기 에서는 모든 한글이 229로 넘어옴 그래서 삭제 KHS begin gKWComp := ''; if J30ShowS = False then // begin // Frm_JON30.gb2ndSearch := False; //확장검색 진행 막음 Proc_AreaSearchKDown_Added(Key); // end; end; end; procedure TFrm_CUT011.btnSaveClick(Sender: TObject); var msg, sBrNo, sBrName, sTel, OkCashBack: string; begin sBrNo := Proc_BRNOSearch; if (GT_USERIF.LV = '10') and (not IsPassedManagementCu(sBrNo)) then begin msg := '[%s(%s)] 지사에서 고객관련 관리권한 이관(콜센터 상담원)을 설정 하지 않았습니다.' + #13#10'(해당 지사관리자에게 관리권한 이관[회사>지사관리>상세설정]을 요청바랍니다.)'; sBrName := GetBrName(sBrNo); GMessagebox(Format(msg, [sBrNo, sBrName]), CDMSE); Exit; end; if cxCustTel.DataController.RecordCount = 0 then begin GMessagebox('고객번호가 없습니다.' + #13#10 + '고객번호는 필수입니다.', CDMSE); Exit; end; if cxCustTel.DataController.Values[0,0] = null then begin GMessagebox('고객번호가 없습니다.' + #13#10 + '고객번호는 필수입니다.', CDMSE); Exit; end; sTel := StringReplace(cxCustTel.DataController.Values[0,0], '-', '', [rfReplaceAll]); if sTel = '' then begin GMessagebox('고객번호가 없습니다.' + #13#10 + '고객번호는 필수입니다.', CDMSE); Exit; end; OkCashBack := Format('%s%s%s%s', [edtOKC1.Text, edtOKC2.Text, edtOKC3.Text, edtOKC4.Text]); if (Length(OkCashBack) <> 0) and (Length(OkCashBack) <> 16) then begin GMessagebox('OK 캐쉬백 정보를 정확하게 입력해 주세요.', CDMSE); Exit; end; if Not func_EucKr_Check(edtCuName, 0) then Exit; if Not func_EucKr_Check(edtCuEmail, 0) then Exit; if Not func_EucKr_Check(edtCuEmail_Potal, 0) then Exit; if Not func_EucKr_Check(edt_CardMemo, 0) then Exit; if Not func_EucKr_Check(meoCuCCMemo, 0) then Exit; if Not func_EucKr_Check(meoCuWorMemo, 0) then Exit; if Not func_EucKr_Check(meoStartAreaCUT, 0) then Exit; if Not func_EucKr_Check(meoEndAreaCUT, 0) then Exit; if btnSave.Caption = '저장' then begin if func_tel_check(0) then proc_save_customer(0) end else begin if func_tel_check(1) then proc_save_customer(1); end; Hide_Panel('meoEndAreaCUT',1); end; procedure TFrm_CUT011.btnBlockWKListClick(Sender: TObject); var sCbCode : string; begin if Not Assigned(Frm_CUT014) Or (Frm_CUT014 = Nil) then Frm_CUT014 := TFrm_CUT014.Create(Nil); Frm_CUT014.proc_Init; if rdoCuGb1.Checked then Frm_CUT014.ACbCuGb := IntToStr(0) else if rdoCuGb2.Checked then Frm_CUT014.ACbCuGb := IntToStr(1) else if rdoCuGb3.Checked then Frm_CUT014.ACbCuGb := IntToStr(2); if rdoCuGb3.Checked then begin sCbCode := cboBubinCode.Properties.Items[cboCuBubin.ItemIndex]; sCbCode := Copy(sCbCode, 1, Pos(',', sCbCode) - 1); Frm_CUT014.ACuseq := sCbCode; end else Frm_CUT014.ACuseq := clbCuSeq.Caption; //고객코드 // Frm_CUT014.ACuseq := Frm_Main.Frm_JON01[Self.Tag].cxtCuBubin.Hint //법인코드 Frm_CUT014.AWkSabun:= ''; Frm_CUT014.AMemo := ''; Frm_CUT014.edtWkSabun.text := ''; Frm_CUT014.proc_BlockWKSearch('CUT011', 1); Frm_CUT014.Show; end; procedure TFrm_CUT011.btnCallBellClick(Sender: TObject); var sTmp : string; i, j, iTmp, iAddRow : integer; slTmp : TStringList; begin if ( Not Assigned(Frm_BTN01) ) Or ( Frm_BTN01 = Nil ) then Frm_BTN01 := TFrm_BTN01.Create(Nil) else Frm_BTN01.proc_Init; sTmp := ''; for i := 0 to Frm_BTN.Scb_CallBell_BrNo.Count - 1 do begin iTmp := scb_DsBranchCode.IndexOf(Frm_BTN.Scb_CallBell_BrNo[i]); if iTmp < 0 then Continue; if sTmp = Frm_BTN.Scb_CallBell_BrNo[i] then Continue; // 본사코드 // 지사코드 // 지사명 // 대표번호 if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB begin if Proc_HDNOSearch = scb_HeadCode[iTmp] then begin Frm_BTN01.cboBranch.Properties.Items.Add(scb_HeadCode[iTmp] + '.' + Frm_BTN.Scb_CallBell_BrNo[i] + ': ' + scb_DsBranchName[iTmp]); sTmp := Frm_BTN.Scb_CallBell_BrNo[i]; end; end else begin Frm_BTN01.cboBranch.Properties.Items.Add(scb_HeadCode[iTmp] + '.' + Frm_BTN.Scb_CallBell_BrNo[i] + ': ' + scb_DsBranchName[iTmp]); sTmp := Frm_BTN.Scb_CallBell_BrNo[i]; end; end; Frm_BTN01.cboBankCode.Properties.Items.Clear; Frm_BTN01.cboBankName.Properties.Items.Clear; Frm_BTN01.cboBankCode.Properties.Items.Assign(Frm_BTN.Scb_BankCd); Frm_BTN01.cboBankName.Properties.Items.Assign(Frm_BTN.Scb_BankNm); Frm_BTN01.cboBankName.ItemIndex := 0; if not Frm_BTN.func_CallBellUpso(Proc_BRNOSearch, clbCuSeq.caption) then begin //콜벨업소로 등록되지 않았다면 Frm_BTN01.clbCuSeq.Caption := clbCuSeq.caption; for j := 0 to Frm_BTN01.cboBranch.Properties.Items.Count - 1 do begin sTmp := Copy(Frm_BTN01.cboBranch.Properties.Items[j], Pos('.', Frm_BTN01.cboBranch.Properties.Items[j]) + 1, Pos(':', Frm_BTN01.cboBranch.Properties.Items[j]) - (Pos('.', Frm_BTN01.cboBranch.Properties.Items[j]) + 1)); //지사코드 if Proc_BRNOSearch = sTmp then begin Frm_BTN01.cboBranch.ItemIndex := j; Break; end; end; Frm_BTN01.cboKeynumber.ItemIndex := Frm_BTN01.cboKeynumber.Properties.Items.Indexof(StrToCall(Proc_MainKeyNumberSearch)); Frm_BTN01.cboUpsoWK.ItemIndex := 0; Frm_BTN01.edtUpsoName.Text := edtCuName.Text; Frm_BTN01.edtUpsoHP.Text := ''; Frm_BTN01.cboStatus.ItemIndex := 1; Frm_BTN01.btnSave.Enabled := True; Frm_BTN01.cxUpsoTel.BeginUpdate; Frm_BTN01.cxUpsoTel.DataController.SetRecordCount(0); slTmp := TStringList.Create; try for j := 0 to cxCustTel.DataController.RecordCount - 1 do begin iAddRow := Frm_BTN01.cxUpsoTel.DataController.AppendRecord; Frm_BTN01.cxUpsoTel.DataController.Values[iAddRow, 0] := strtocall(cxCustTel.DataController.Values[j, 0]); end; Frm_BTN01.cxUpsoTel.EndUpdate; Frm_BTN01.rb_Straight.Checked := True; Frm_BTN01.edtCalValue.Text := ''; Frm_BTN01.cboBankName.ItemIndex := 0; Frm_BTN01.edtBankNumberCust.Text := ''; Frm_BTN01.edtBankOwnerCust.Text := ''; Frm_BTN01.lcsCallBell1 := lcsSta1; Frm_BTN01.lcsCallBell2 := lcsSta2; Frm_BTN01.lcsCallBell3 := lcsSta3; Frm_BTN01.lbUpsoAreaName.Caption := lcsSta1 + ' ' + lcsSta2 + ' ' + lcsSta3; Frm_BTN01.edtUpsoAreaDetail.Caption := cxtStartAreaDetail.Text; Frm_BTN01.meoCallBellArea.Text := meoStartAreaCUT.text; Frm_BTN01.edtXval.Caption := cxtStartXval.Text; Frm_BTN01.edtYval.Caption := cxtStartYval.Text; if Trim(meoCuCCMemo.text) <> '' then begin GetTextSeperationEx2('¶', meoCuCCMemo.text, slTmp); for j := 0 to slTmp.Count - 1 do begin Frm_BTN01.meoCallBellUpsoMemo.Lines.Add(slTmp[j]); end; end; finally slTmp.Free; end; end; Frm_BTN01.btnSave.Caption := '수정'; Frm_BTN01.pnlTitle.Caption := ' 업소 수정'; Frm_BTN01.pnlTitle.Hint := 'Update'; Frm_BTN01.cboBranch.Enabled := False; Frm_BTN01.cboKeynumber.Enabled := False; if not Frm_BTN01.Showing then begin Frm_BTN01.Left := (Screen.Width - Frm_BTN01.Width) div 2; Frm_BTN01.top := (Screen.Height - Frm_BTN01.Height) div 2; if Frm_BTN01.top <= 10 then Frm_BTN01.top := 10; Frm_BTN01.Tag := 1; Frm_BTN01.Show; end; end; procedure TFrm_CUT011.btnCloseClick(Sender: TObject); begin Hide_Panel('meoEndAreaCUT',1); if ( Assigned(Frm_JON012) ) Or ( Frm_JON012 <> Nil ) then Frm_JON012.btnCloseClick(nil); if Assigned(Frm_JON012) then Frm_JON012.Close; // 과거이용내역 Close; end; function TFrm_CUT011.func_tel_check(iType: Integer): Boolean; var ls_TxLoad, ls_TxQry, rv_str, ls_Msg_Err : string; sHdNo, sBrNo, sKeyNum, sTel, sQueryTemp : string; ls_rxxml: WideString; i: Integer; xdom: msDomDocument; lst_Result: IXMLDomNodeList; ls_Rcrd: TStringList; slReceive: TStringList; ErrCode: integer; begin Result := False; sHdNo := Proc_HDNOSearch; if Trim(sHdNo) = '' then begin GMessagebox('지사정보가 올바르지 않습니다.' + #13#10 + '지사정보는 필수입니다.', CDMSE); Exit; end; sBrNo := Proc_BRNOSearch; if Trim(sBrNo) = '' then begin GMessagebox('지사정보가 없습니다.' + #13#10 + '지사정보는 필수입니다.', CDMSE); Exit; end; sKeyNum := Proc_MainKeyNumberSearch; if Trim(sKeyNum) = '' then begin GMessagebox('대표번호가 없습니다.' + #13#10 + '대표번호는 필수입니다.', CDMSE); Exit; end; for i := 0 to cxCustTel.DataController.RecordCount - 1 do begin sTel := StringReplace(cxCustTel.DataController.Values[i, 0], '-', '', [rfReplaceAll]); ls_TxLoad := GTx_UnitXmlLoad('SEL01.XML'); fGet_BlowFish_Query(GSQ_CUSTOMER_TEL_CHECK, sQueryTemp); ls_TxQry := Format(sQueryTemp, [sHdNo, sBrNo, sKeyNum, sTel]); ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'CUSTTELCHECK', [rfReplaceAll]); ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]); slReceive := TStringList.Create; try if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then begin rv_str := slReceive[0]; if rv_str <> '' then begin ls_rxxml := rv_str; Application.ProcessMessages; try xdom := ComsDomDocument.Create; if not xdom.loadXML(ls_rxxml) then Exit; ls_MSG_Err := GetXmlErrorCode(ls_rxxml); if ('0000' = ls_MSG_Err) then begin lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result'); ls_Rcrd := TStringList.Create; try GetTextSeperationEx('│', lst_Result.item[0].attributes.getNamedItem('Value').Text, ls_Rcrd); if iType = 0 then begin if ls_Rcrd[0] <> '' then begin Result := False; GMessagebox(strtocall(sTel) + ' 번호는 [' + ls_Rcrd[2] + '] [' + ls_Rcrd[1] + '] 고객으로 등록되어 있는 전화번호 입니다.' + #13#10 + '저장 할수 없습니다.', CDMSE); Exit; end; end else if iType = 1 then begin if (clbCuSeq.Caption <> ls_Rcrd[0]) then begin if ls_Rcrd[0] = '' then continue; Result := False; GMessagebox(strtocall(sTel) + ' 번호는 [' + ls_Rcrd[2] + '] [' + ls_Rcrd[1] + '] 고객으로 등록되어 있는 전화번호 입니다.' + #13#10 + '저장 할수 없습니다.', CDMSE); Exit; end; end; finally ls_Rcrd.Free; end; end else GMessagebox(ls_Msg_Err, CDMSE); xdom := Nil; except end; end; end; finally Frm_Flash.Hide; FreeAndNil(slReceive); end; end; Result := True; end; // 고객저장(0 : 추가, 1 : 수정, 2 : 삭제, 3 : 법인정보만수정) procedure TFrm_CUT011.proc_save_customer(iType: Integer); const ls_Param = '<param>ParamString</param>'; var rv_str, ls_TxLoad : string; sCuType, sCbCode, sCuLevel, sTemp, sTemp2, sSms, sParam, sInfo, sInfo2, sPdaInfo, sPdaInfo2, sBrNo, sHdNo, sKeyNumber, OkCashBack, sVirture, sEmail, Param, XmlData, ErrMsg: string; ls_rxxml, wInfo, wPdaInfo: WideString; i : Integer; asParam: array[1..41] of string; slReceive: TStringList; ErrCode: integer; begin sBrNo := Proc_BRNOSearch; sHdNo := Proc_HDNOSearch; sKeyNumber := Proc_MainKeyNumberSearch; if rdoCuGb2.Checked then sCuType := '1' else if rdoCuGb3.Checked then sCuType := '3' else sCuType := '0'; if (sCuType = '3') and (cboCuBubin.ItemIndex > 0) then begin sCbCode := cboBubinCode.Properties.Items[cboCuBubin.ItemIndex]; sCbCode := Copy(sCbCode, 1, Pos(',', sCbCode) - 1); end else sCbCode := ''; sCuLevel := GetCustLevelSeq; if cxCustTel.DataController.Values[0, 0] <> '' then begin sSms := IfThen(cxCustTel.DataController.Values[0, 1] = '미수신', 'n', 'y'); sTemp := Rpad(StringReplace(cxCustTel.DataController.Values[0, 0], '-', '', [rfReplaceAll]), 12, ' ') + Rpad(' ', 20, ' ') + sSms; sVirture := IfThen(cxCustTel.DataController.Values[0, 3] = '해제', 'n', 'y'); sTemp := sTemp + sVirture; end; if cxCustTel.DataController.RowCount >= 2 then begin for i := 1 to cxCustTel.DataController.RowCount - 1 do begin sSms := IfThen(cxCustTel.DataController.Values[i, 1] = '미수신', 'n', 'y'); sTemp := sTemp + '|' + Rpad(StringReplace(cxCustTel.DataController.Values[i, 0], '-', '', [rfReplaceAll]), 12, ' ') + Rpad(' ', 20, ' ') + sSms; sVirture := IfThen(cxCustTel.DataController.Values[i, 3] = '해제', 'n', 'y'); sTemp := sTemp + sVirture; if i > 4 then Break; end; end; sTemp := sTemp + '|'; sTemp2 := ''; if cxCustTel.DataController.RowCount > 6 then begin sSms := IfThen(cxCustTel.DataController.Values[6, 1] = '미수신', 'n', 'y'); sTemp2 := Rpad(StringReplace(cxCustTel.DataController.Values[6, 0], '-', '', [rfReplaceAll]), 12, ' ') + Rpad(' ', 20, ' ') + sSms; sVirture := IfThen(cxCustTel.DataController.Values[6, 3] = '해제', 'n', 'y'); sTemp2 := sTemp2 + sVirture; if cxCustTel.DataController.RowCount > 7 then begin for i := 7 to cxCustTel.DataController.RowCount - 1 do begin sSms := IfThen(cxCustTel.DataController.Values[i, 1] = '미수신', 'n', 'y'); sTemp2 := sTemp2 + '|' + Rpad(StringReplace(cxCustTel.DataController.Values[i, 0], '-', '', [rfReplaceAll]), 12, ' ') + Rpad(' ', 20, ' ') + sSms; sVirture := IfThen(cxCustTel.DataController.Values[i, 3] = '해제', 'n', 'y'); sTemp2 := sTemp2 + sVirture; end; end; sTemp2 := sTemp2 + '|'; end; wInfo := meoCuCCMemo.Text; wPdaInfo := meoCuWorMemo.Text; wPdaInfo := StringReplace(wPdaInfo, '●', '¶', [rfReplaceAll]); if Length(wInfo) > 100 then begin sInfo := Copy(wInfo, 1, 100); sInfo2 := Copy(wInfo, 101, Length(wInfo) - 100); sInfo := ReplaceAll(sInfo, #$D#$A, '¶'); sInfo := ReplaceAll(sInfo, #13#10, '¶'); sInfo := ReplaceAll(sInfo, #10#13, '¶'); sInfo := StringReplace(sInfo, '|', '¶', [rfReplaceAll]); sInfo2 := ReplaceAll(sInfo2, #$D#$A, '¶'); sInfo2 := ReplaceAll(sInfo2, #13#10, '¶'); sInfo2 := ReplaceAll(sInfo2, #10#13, '¶'); sInfo2 := StringReplace(sInfo2, '|', '¶', [rfReplaceAll]); end else begin sInfo := ReplaceAll(wInfo, #$D#$A, '¶'); sInfo := ReplaceAll(sInfo, #13#10, '¶'); sInfo := ReplaceAll(sInfo, #10#13, '¶'); sInfo := StringReplace(sInfo, '|', '¶', [rfReplaceAll]); sInfo2 := ''; end; if Length(wPdaInfo) > 100 then begin sPdaInfo := Copy(wPdaInfo, 1, 100); sPdaInfo2 := Copy(wPdaInfo, 101, Length(wPdaInfo) - 100); sPdaInfo := ReplaceAll(sPdaInfo, #$D#$A, '¶'); sPdaInfo := ReplaceAll(sPdaInfo, #13#10, '¶'); sPdaInfo := ReplaceAll(sPdaInfo, #10#13, '¶'); sPdaInfo := StringReplace(sPdaInfo, '|', '¶', [rfReplaceAll]); sPdaInfo2 := ReplaceAll(sPdaInfo2, #$D#$A, '¶'); sPdaInfo2 := ReplaceAll(sPdaInfo2, #13#10, '¶'); sPdaInfo2 := ReplaceAll(sPdaInfo2, #10#13, '¶'); sPdaInfo2 := StringReplace(sPdaInfo2, '|', '¶', [rfReplaceAll]); end else begin sPdaInfo := ReplaceAll(wPdaInfo, #$D#$A, '¶'); sPdaInfo := ReplaceAll(sPdaInfo, #13#10, '¶'); sPdaInfo := ReplaceAll(sPdaInfo, #10#13, '¶'); sPdaInfo := StringReplace(sPdaInfo, '|', '¶', [rfReplaceAll]); sPdaInfo2 := ''; end; OkCashBack := Format('%s%s%s%s', [edtOKC1.Text, edtOKC2.Text, edtOKC3.Text, edtOKC4.Text]); if Length(OkCashBack) <> 16 then OkCashBack := ''; lcsSta1 := cxtSA1.Text; lcsSta2 := cxtSA2.Text; lcsSta3 := cxtSA3.Text; lcsEnd1 := cxtEd1.Text; lcsEnd2 := cxtEd2.Text; lcsEnd3 := cxtEd3.Text; Param := IntToStr(iType); // 01 저장타입( 0: 등록, 1: 수정, 2: 삭제, 3: 법인정보만수정, 10:등록및수정) Param := Param + '│' + clbCuSeq.Caption; // 02 고객코드 Param := Param + '│' + sHdNo; // 03 본사코드 Param := Param + '│' + sBrNo; // 04 지사코드 Param := Param + '│' + sKeyNumber; // 05 대표번호 Param := Param + '│' + sCuType; // 06 고객타입(0 :일반, 1 : 업소, 3 : 법인 4 : 불량) Param := Param + '│' + edtCuName.Text; // 07 고객(업소명) Param := Param + '│' + StringReplace(cxTextEdit2.Text, '-', '', [rfReplaceAll]); // 08 주민등록(사업자)번호 Param := Param + '│' + En_Coding(GT_USERIF.ID); // 09 입력자 ID Param := Param + '│' + lcsSta1; // 10 출발지 1 Param := Param + '│' + lcsSta2; // 11 출발지 2 Param := Param + '│' + lcsSta3; // 12 출발지 3 Param := Param + '│' + cxtStartAreaDetail.Text; // 13 출발지 POI Param := Param + '│' + meoStartAreaCUT.Text; // 14 출발지 세부입력 Param := Param + '│' + cxtStartXval.Text; // 15 출발지 위도 Param := Param + '│' + cxtStartYval.Text; // 16 출발지 경도 Param := Param + '│' + En_Coding(sInfo); // 17 고객메모(상담원) Param := Param + '│' + En_Coding(sPdaInfo); // 18 고객정보(기사) Param := Param + '│' + lcsEnd1; // 19 도착지 1 Param := Param + '│' + lcsEnd2; // 20 도착지 2 Param := Param + '│' + lcsEnd3; // 21 도착지 3 Param := Param + '│' + cxtEndAreaDetail.Text; // 22 도착지 POI Param := Param + '│' + meoEndAreaCUT.Text; // 23 도착지 세부입력 Param := Param + '│' + cxtEndXval.Text; // 24 도착지 위도 Param := Param + '│' + cxtEndYval.Text; // 25 도착지 경도 Param := Param + '│' + sCbCode; // 26 법인코드 Param := Param + '│' + sCuLevel; // 27 고객등급(0 : 불량, 1 : 주의, 2 : 일반, 3 :업소) Param := Param + '│' + sTemp; // 28 cdms_customer_tel 저장 Param := Param + '│' + sTemp2; // 29 cdms_customer_tel 저장 7건 부터 Param := Param + '│' + En_Coding(sInfo2); // 30 고객메모2(상담원) Param := Param + '│' + En_Coding(sPdaInfo2); // 31 고객정보2(기사) Param := Param + '│' + OkCashBack; // 32 캐쉬백 카드 번호 Param := Param + '│' + CustBrTelYN; // 33 상황실번호보기 if edtCuEmail.Text <> '' then begin sEmail := edtCuEmail.Text + '@' ; if edtCuEmail_Potal.Visible then sEmail := sEmail + edtCuEmail_Potal.Text else sEmail := sEmail + cboEmail.Text; end else sEmail := ''; Param := Param + '│' + sEmail; // 34 고객EMAIL Param := Param + '│' + Trim(edt_CardMemo.Text); // 35 적요3 if cbOutBound.ItemIndex = -1 then Param := Param + '│' + '' else // 36 고객 아웃바운드상태 1 동의, 2거부, 3문자 if cbOutBound.ItemIndex = 0 then Param := Param + '│' + '1' else if cbOutBound.ItemIndex = 1 then Param := Param + '│' + '2' else if cbOutBound.ItemIndex = 2 then Param := Param + '│' + '3'; if chkAppUseYn.Checked then Param := Param + '│' + 'y' // 37 고객 어플 차단 여부 y 차단, n 미차단 else Param := Param + '│' + 'n'; if chkStickYn.Checked then Param := Param + '│' + 'y' // 38 오더 스틱여부 yn else Param := Param + '│' + 'n'; if cb_CarType.ItemIndex = 0 then Param := Param + '│' + '1' // 39 차종 else Param := Param + '│' + '2'; if chkMileSmsYn.Checked then Param := Param + '│' + 'y' // 40 고객마일전송 거부 여부 y/n else Param := Param + '│' + 'n'; if rbAIReCallY.Checked then Param := Param + '│' + 'y' else // 41 AIOB 배차지연콜 여부 yn if rbAIReCallN.Checked then Param := Param + '│' + 'n' else Param := Param + '│'; if chkMemoDisplay.Checked then Param := Param + '│' + 'y' // 42 //상담메모 자동 표시 사용여부 else Param := Param + '│' + 'n'; Param := Param + '│' + FloatToStr(cedtLimitCountB.Value); // 43 법인이용한도 횟수(월간) Param := Param + '│' + FloatToStr(cedtLimitAmtB.Value); // 44 법인이용한도 금액(월간) Param := Param + '│' + Trim(edt_CbPositionName.Text); // 45 직책명 // if chk_RejectBaechaSmsYn.Checked then Param := Param + '│' + 'y' // 45 배차문자수신거부 // else Param := Param + '│' + 'n'; if not RequestBase(GetCallable06('SET_CUSTOMER', 'MNG_CUSTOMER.SET_CUSTOMER', En_Coding(Param)), XmlData, ErrCode, ErrMsg) then begin GMessagebox(Format('고객정보 저장중 오류가 발생하였습니다.'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE); Exit; end; GMessagebox('저장되었습니다.', CDMSI); end; procedure TFrm_CUT011.proc_search_brKeyNum(sBrNo, sKeyNum: string); var i: Integer; begin cboBranch.Tag := 10; for i := 0 to cboBranch.Properties.Items.Count - 1 do begin if (Pos(sBrNo, cboBranch.Properties.Items[i]) > 0) and (Pos(sKeyNum, cboBranch.Properties.Items[i]) > 0) then begin cboBranch.ItemIndex := i; cboBranchPropertiesChange(cboBranch); Break; end; end; cboBranch.Tag := 0; //AI 아웃바운드 옵션 배차지연콜 사용여부 proc_AIOB_CtrlYN; end; procedure TFrm_CUT011.SetCustBrTelYN(const Value: string); begin FCustBrTelYN := LowerCase(Value); chkBrTelYN.Checked := (FCustBrTelYN = 'y'); end; procedure TFrm_CUT011.chkBrTelYNClick(Sender: TObject); begin CustBrTelYN := IfThen(chkBrTelYN.Checked, 'y', 'n'); end; procedure TFrm_CUT011.cboBranchPropertiesChange(Sender: TObject); begin GetCustGroup(Proc_MainKeyNumberSearch, CustGroup); SetCustLevelData; if cboBranch.Tag <> 10 then //AI 아웃바운드 옵션 배차지연콜 사용여부 proc_AIOB_CtrlYN; end; procedure TFrm_CUT011.SetCustLevelData; var I: Integer; begin cboCuLevel.Properties.Items.Clear; for I := 0 to Length(CustGroup.LevelInfo) - 1 do cboCuLevel.Properties.Items.Add(CustGroup.LevelInfo[I].LevelName); DefaultCustLevel; end; procedure TFrm_CUT011.DefaultCustLevel; begin SetCustLevelSeq(CustGroup.Default.LevelSeq); end; procedure TFrm_CUT011.edtCuNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin TcxTextEdit(Sender).Text := Enc_Control(TcxTextEdit(Sender).Text); end; function TFrm_CUT011.GetCustLevelSeq: string; var i : Integer; begin Result := ''; for I := 0 to Length(CustGroup.LevelInfo) - 1 do begin if CustGroup.LevelInfo[I].LevelName = cboCuLevel.Text then begin Result := CustGroup.LevelInfo[I].LevelSeq; Break; end; end; end; procedure TFrm_CUT011.SetCustLevelSeq(ASeq: string); var I: Integer; begin cboCuLevel.ItemIndex := -1; for I := 0 to Length(CustGroup.LevelInfo) - 1 do begin if CustGroup.LevelInfo[I].LevelSeq = ASeq then begin cboCuLevel.ItemIndex := I; Break; end; end; end; procedure TFrm_CUT011.nm_CustSMSClick(Sender: TObject); var sCustTel, sKeyNum, sTmp : string; iPos2 : Integer; iSelRow : Integer; begin // 고객 전화번호로 문자 전송하기. 2011.06.23 ADD. if cxCustTel.DataController.RowCount < 1 then Exit; iSelRow := cxCustTel.DataController.FocusedRecordIndex; try sTmp := cboBranch.Text; while (True) do begin iPos2 := Pos('[', Copy(sTmp, 1, Length(sTmp))); if iPos2 = 0 then begin sKeyNum := Copy(sTmp, 1, Pos(']', sTmp) - 1); Break; end; sTmp := Copy(sTmp, iPos2 + 1, Length(sTmp)); end; sCustTel := cxCustTel.DataController.Values[iSelRow, 0]; if StrToIntDef(copy(sCustTel, 1, 2), 0) <> 1 then begin GMessagebox('고객번호가 핸드폰이 아닙니다.' + #13#10 + '문자메세지를 보낼수 없습니다.', CDMSE); Exit; end; if Not Assigned(Frm_SMS01) then Frm_SMS01 := TFrm_SMS01.Create(Nil); Frm_SMS01.mm_message.Text := ''; sKeyNum := StringReplace(sKeyNum, '-', '', [rfReplaceAll]); Frm_SMS01.ed_send.Text := sKeyNum; Frm_SMS01.ls_sms.Items.Clear; Frm_SMS01.ls_sms.Items.Add(sCustTel); Frm_SMS01.Proc_Init; Frm_SMS01.sSendKind := ''; Frm_SMS01.rdo_SMS.visible := False; Frm_SMS01.rdo_PUSH.visible := False; // Frm_SMS01.PageControl1.ActivePageIndex := 1; Frm_SMS01.Show; except on E: Exception do Assert(False, E.Message); end; end; procedure TFrm_CUT011.pnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; PostMessage(Self.Handle, WM_SYSCOMMAND, $F012, 0); end; function TFrm_CUT011.proc_AIOB_CtrlYN: string; var sTmp : string; begin SetDebugeWrite('TFrm_CUT011.proc_AIOB_CtrlYN'); try sTmp := ''; sTmp := Proc_MainKeyNumberSearch; if not GetAIOBKeyNumberYN(sTmp) then //고객이 선택되어 있어도 지사의 대표번호에서 사용안하면 체크해제 begin grpAIReCall.Enabled := False; end else begin grpAIReCall.Enabled := True; end; img2.Visible := Not grpAIReCall.Enabled; Result := sTmp; except Result := ''; end; end; procedure TFrm_CUT011.Hide_Panel(Panel: string; Showhide: integer); begin if ( Not Assigned(Frm_JON30) ) Or ( Frm_JON30 = Nil ) then Exit; if Showhide = 0 then Frm_JON30.Show else if Showhide = 1 then begin if (Panel = 'meoStartAreaCUT') OR (Panel = 'meoEndAreaCUT') then begin Frm_JON30.Hide; end else begin Frm_JON30.Hide; end; end; if Panel = 'meoStartAreaCUT' then begin Frm_JON30.pnl_01START.Visible := True; Frm_JON30.pnl_02END.Visible := False; Frm_JON30.pnl_03VIA.Visible := False; end else if Panel = 'meoEndAreaCUT' then begin Frm_JON30.pnl_01START.Visible := False; Frm_JON30.pnl_02END.Visible := True; Frm_JON30.pnl_03VIA.Visible := False; end; end; procedure TFrm_CUT011.img2Click(Sender: TObject); begin if ( Not Assigned(Frm_AIC10) ) Or ( Frm_AIC10 = Nil ) then Frm_AIC10 := TFrm_AIC10.Create(Nil); Frm_AIC10.Show; end; procedure TFrm_CUT011.meoEndAreaCUTExit(Sender: TObject); begin if Assigned(Frm_JON30) and (not (meoEndAreaCUT.Focused)) then Hide_Panel('meoEndAreaCUT',1); end; procedure TFrm_CUT011.Grid_Clear(Panel: string; Grid: Integer); begin if Panel = 'meoStartAreaCUT' then begin if Grid = 1 then begin Frm_JON30.AdvStringGrid1.Clear; Frm_JON30.AdvStringGrid1.RowCount := 2; Frm_JON30.AdvStringGrid1.Cells[0, 0] := '시도'; Frm_JON30.AdvStringGrid1.Cells[1, 0] := '시군구'; Frm_JON30.AdvStringGrid1.Cells[2, 0] := '읍면동'; Frm_JON30.AdvStringGrid1.Cells[3, 0] := '세부지명'; Frm_JON30.AdvStringGrid1.Cells[4, 0] := '인근POI'; Frm_JON30.AdvStringGrid1.Cells[5, 0] := '거리(m)'; Frm_JON30.AdvStringGrid1.Cells[6, 0] := 'X좌표'; Frm_JON30.AdvStringGrid1.Cells[7, 0] := 'Y좌표'; Frm_JON30.AdvStringGrid1.ShowSelection := False; end else if Grid = 2 then begin Frm_JON30.AdvStringGrid2.Clear; Frm_JON30.AdvStringGrid2.RowCount := 1; Frm_JON30.AdvStringGrid2.ShowSelection := False; end else if Grid = 3 then begin Frm_JON30.AdvStringGrid3.Clear; Frm_JON30.AdvStringGrid3.RowCount := 1; Frm_JON30.AdvStringGrid3.ShowSelection := False; end; end else if Panel = 'meoEndAreaCUT' then begin if Grid = 1 then begin Frm_JON30.AdvStringGrid5.Clear; Frm_JON30.AdvStringGrid5.RowCount := 2; Frm_JON30.AdvStringGrid5.Cells[0, 0] := '시도'; Frm_JON30.AdvStringGrid5.Cells[1, 0] := '시군구'; Frm_JON30.AdvStringGrid5.Cells[2, 0] := '읍면동'; Frm_JON30.AdvStringGrid5.Cells[3, 0] := '세부지명'; Frm_JON30.AdvStringGrid5.Cells[4, 0] := '인근POI'; Frm_JON30.AdvStringGrid5.Cells[5, 0] := '거리(m)'; Frm_JON30.AdvStringGrid5.Cells[6, 0] := 'X좌표'; Frm_JON30.AdvStringGrid5.Cells[7, 0] := 'Y좌표'; Frm_JON30.AdvStringGrid5.ShowSelection := False; end else if Grid = 2 then begin Frm_JON30.AdvStringGrid4.Clear; Frm_JON30.AdvStringGrid4.RowCount := 1; Frm_JON30.AdvStringGrid4.ShowSelection := False; end else if Grid = 3 then begin Frm_JON30.AdvStringGrid6.Clear; Frm_JON30.AdvStringGrid6.RowCount := 1; Frm_JON30.AdvStringGrid6.ShowSelection := False; end; end; end; procedure TFrm_CUT011.lcs_Clear(Panel: string); begin if Panel = 'meoStartAreaCUT' then begin lcsSta1 := ''; lcsSta2 := ''; lcsSta3 := ''; cxtSA1.Text := ''; cxtSA2.Text := ''; cxtSA3.Text := ''; lblStartAreaName.Caption := ''; cxtStartAreaDetail.Text := ''; cxtStartXval.Text := ''; cxtStartYval.Text := ''; end else if Panel = 'meoEndAreaCUT' then begin lcsEnd1 := ''; lcsEnd2 := ''; lcsEnd3 := ''; cxtEd1.Text := ''; cxtEd2.Text := ''; cxtEd3.Text := ''; lblEndAreaName.Caption := ''; cxtEndAreaDetail.Text := ''; cxtEndXval.Text := ''; cxtEndYval.Text := ''; end; end; procedure TFrm_CUT011.Proc_AreaSearchKDown_Added(Key: Word); begin if (lcsActiveEdit = 'meoEndArea') and (GS_SEARCH_ENDNOSEARCH = True) then Exit; //도착지 검색 안함 2012.05.29 KHS if not (key in [vk_F7..vk_F12]) then begin if ((lcsActiveEdit = 'meoStartAreaCUT') and (Length(WideString(meoStartAreaCUT.Text)) >= 2)) or ((lcsActiveEdit = 'meoEndAreaCUT') and (Length(WideString(meoEndAreaCUT.Text)) >= 2)) then begin Application.ProcessMessages; if not Frm_JON30.noSearch then //advgrid3 클릭 시 재 검색 안됨. begin if GS_MAP_AREA_AUTOSHOW then begin Hide_Panel(lcsActiveEdit,0); end else if GS_MAP_AREA_AUTOSHOW = False then begin Frm_JON30.chk_Map(False); Hide_Panel(lcsActiveEdit,0); end; Frm_JON30.tmThread.Interval := 90; Frm_JON30.tmThread.Enabled := True; end else begin Frm_JON30.noSearch := False; end; end; end; end; procedure TFrm_CUT011.meoEndAreaCUTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin TcxMemo(sender).Text := Enc_Control(TcxMemo(sender).Text); lcsActiveEdit := 'meoEndAreaCUT'; // 활성화 된 출발지, 도착지 Edit 구분을 저장. if Key in [VK_DOWN] then begin if Frm_JON30.AdvStringGrid5.Cells[0,1] = '' then begin if Frm_JON30.AdvStringGrid4.Cells[0,0] = '' then begin if Frm_JON30.AdvStringGrid6.Cells[0,0] <> '' then begin Frm_JON30.AdvStringGrid5.ShowSelection := False; Frm_JON30.AdvStringGrid4.ShowSelection := False; Frm_JON30.AdvStringGrid6.ShowSelection := True; Frm_JON30.AdvStringGrid6.SetFocus; //- Frm_JON30.AdvStringGrid6.FocusCell(0,0); end; end else begin Frm_JON30.AdvStringGrid5.ShowSelection := False; Frm_JON30.AdvStringGrid4.ShowSelection := True; Frm_JON30.AdvStringGrid6.ShowSelection := False; Frm_JON30.AdvStringGrid4.SetFocus; Frm_JON30.AdvStringGrid4.FocusCell(0,0); end; end else begin Frm_JON30.AdvStringGrid5.ShowSelection := True; Frm_JON30.AdvStringGrid4.ShowSelection := False; Frm_JON30.AdvStringGrid6.ShowSelection := False; //- Frm_JON30.AdvStringGrid5.FocusCell(1,1); Frm_JON30.AdvStringGrid5.SetFocus; end; end else if Key = VK_BACK then begin // Frm_JON30.gb2ndSearch := False; //확장검색 진행 막음 J30ShowS := False; end else if Key = VK_RETURN then begin if lcsActiveEdit = 'meoEndAreaCUT' then begin if Frm_JON30.Visible = True then begin if Frm_JON30.AdvStringGrid5.Cells[0,1] <> '' then begin Frm_JON30.Proc_SendParent(Frm_JON30.AdvStringGrid5.GetRealRow + 1, True); Hide_Panel(lcsActiveEdit,1); end; if (Frm_JON30.AdvStringGrid5.Cells[0,1] = '') and (Frm_JON30.AdvStringGrid4.Cells[0,0] <> '') then begin Frm_JON30.Proc_SendParent_ADV2(Frm_JON30.AdvStringGrid4.GetRealRow + 1, Frm_JON30.AdvStringGrid4.GetRealCol, True); Hide_Panel(lcsActiveEdit,1); end; meoEndAreaCUT.SetFocus; end; end; end else if (Key = vk_delete) then begin J30ShowS := False; end else // if (key <> 229) then // 20191224 한컴입력기 에서는 모든 한글이 229로 넘어옴 그래서 삭제 KHS begin gKWComp := ''; if J30ShowS = False then // begin // Frm_JON30.gb2ndSearch := False; //확장검색 진행 막음 Proc_AreaSearchKDown_Added(Key); // end; end; end; procedure TFrm_CUT011.meoEndAreaCUTKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin lcsActiveEdit := 'meoEndAreaCUT'; // 활성화 된 출발지, 도착지 Edit 구분을 저장. // 좌, 우, HOME, END 방향키는 이벤트 타지 않도록 한다. if (Key = 37) or (Key = 39) or (Key = 35) or (Key = 36) then Exit; if Key = VK_RETURN then begin Key := 0; Exit; end; if Key in [VK_DOWN, VK_UP] then begin Exit; // 그리드에 포커스 넘기는건 KeyUp Event에서 처리한다. end; if Key = VK_BACK then begin if (Length(meoEndAreaCUT.Text) <= 1) then begin // 키워드가 모두 지워진 상태에서 한번더 BACK 키를 누를경우 컨트롤 초기화 처리. lcs_Clear(lcsActiveEdit); gKWComp := ''; gmap_forword := ''; Grid_Clear(lcsActiveEdit,1); Grid_Clear(lcsActiveEdit,2); Grid_Clear(lcsActiveEdit,3); Hide_Panel(lcsActiveEdit,1); Exit; end else if (Length(meoEndAreaCUT.Text) <= 2) then begin gmap_forword := ''; { end else if (Length(meoEndAreaCUT.Text) < Length(Frm_Main.Frm_JON01[StrToInt(self.Hint)].map_ls_Text)) then begin Frm_Main.Frm_JON01[StrToInt(self.Hint)].map_ls_Text := ''; gmap_forword := ''; -} end; end; end; procedure TFrm_CUT011.cxtStartXvalPropertiesChange(Sender: TObject); begin if Assigned(Frm_JON30) then begin if TcxTextEdit(Sender).Name = 'cxtStartYval' then begin if (cxtStartXval.Text = '') and (cxtStartYval.Text = '') then begin Hide_Panel(lcsActiveEdit,1); end else begin if GS_MAP_AREA_AUTOSHOW and (not Frm_JON30.Visible) then begin if J30ShowS = False then begin Frm_JON30.OnSelectedMap := SetStartAreaMap; Hide_Panel(lcsActiveEdit,0); end; end else if GS_MAP_AREA_AUTOSHOW = False then begin if J30ShowS = False then begin Frm_JON30.OnSelectedMap := SetStartAreaMap; Hide_Panel(lcsActiveEdit,0); end; end; if J30ShowS = False then begin Frm_JON30.StartPos(meoStartAreaCUT.Text, cxtStartXval.Text, cxtStartYval.Text); end; end; end else if TcxTextEdit(Sender).Name = 'cxtEndYval' then begin if J30ShowE = True then begin Exit; end; if (cxtEndXval.Text = '') and (cxtEndYval.Text = '') then begin Hide_Panel(lcsActiveEdit,1); end else begin if GS_MAP_AREA_AUTOSHOW and (not Frm_JON30.Visible) then begin if J30ShowE = False then begin Frm_JON30.OnSelectedMap := SetEndAreaMap; Hide_Panel(lcsActiveEdit,0); end; end else if GS_MAP_AREA_AUTOSHOW = False then begin if J30ShowE = False then begin Frm_JON30.OnSelectedMap := SetEndAreaMap; Hide_Panel(lcsActiveEdit,0); end; end; if J30ShowS = False then begin Frm_JON30.EndPos(meoEndAreaCUT.Text, cxtEndXval.Text, cxtEndYval.Text); end; end; end; end; if (cxtStartXval.Text = '') or (cxtStartYval.Text = '') or (cxtEndXval.Text = '') or (cxtEndYval.Text = '') then Exit; end; procedure TFrm_CUT011.SetEndAreaMap(const ASido, AGugun, ADong, ADetail, AX, AY: string); begin lcsEnd1 := ASido; lcsEnd2 := AGugun; lcsEnd3 := ADong; cxtEd1.Text := ASido; cxtEd2.Text := AGugun; cxtEd3.Text := ADong; if ASido <> '' then begin lblEndAreaName.Caption := ASido + ' ' + AGugun + ' ' + ADong; cxtEndAreaDetail.Text := ADetail; if ADetail = '' then meoEndAreaCUT.Text := ADong else meoEndAreaCUT.Text := ADetail; end; cxtEndXval.Text := AX; cxtEndYval.Text := AY; meoEndAreaCUT.SetFocus; end; procedure TFrm_CUT011.SetStartAreaMap(const ASido, AGugun, ADong, ADetail, AX, AY: string); begin lcsSta1 := ASido; lcsSta2 := AGugun; lcsSta3 := ADong; cxtSA1.Text := ASido; cxtSA2.Text := AGugun; cxtSA3.Text := ADong; if ASido <> '' then begin lblStartAreaName.Caption := ASido + ' ' + AGugun + ' ' + ADong; cxtStartAreaDetail.Text := ADetail; if ADetail = '' then meoStartAreaCUT.Text := ADong else meoStartAreaCUT.Text := ADetail; end; cxtStartXval.Text := AX; cxtStartYval.Text := AY; meoStartAreaCUT.SetFocus; end; procedure TFrm_CUT011.Proc_Jon012Show; begin if ( Not Assigned(Frm_JON012) ) Or (Frm_JON012 = Nil ) then Frm_JON012 := TFrm_JON012.Create(Self); Frm_JON012.iOpen_Gubun := 1; Frm_JON012.Hint := Self.Caption; Frm_JON012.Tag := 99; // 다중과거이용내역이 아닐경우 99. Frm_JON012.FResize := True; Frm_JON012.Width := StrToIntDef(GS_EnvFile.ReadString('UserHisForm', 'Width', '562'), 562); Frm_JON012.FResize := True; Frm_JON012.Height := StrToIntDef(GS_EnvFile.ReadString('UserHisForm', 'Height', '277'), 277); Frm_JON012.cxPageControl1.Pages[0].TabVisible := False; Frm_JON012.cxPageControl1.Pages[1].TabVisible := False; Frm_JON012.BtnSheet1.Visible := True; Frm_JON012.BtnSheet2.Visible := False; Frm_JON012.cxBtnAccept.Visible := False; Frm_JON012.sActivePage := 0; Frm_JON012.cxPageControl1.ActivePageIndex := 0; Frm_JON012.BtnSheet1.Down := True; Frm_JON012.sActivePage := 0; Frm_JON012.lbl8.Visible := True; Frm_JON012.cxBtnOldSelect.Visible := True; Frm_JON012.cxBtnColorSet.Visible := True; // Frm_JON012.cbStatesView.Visible := True; Frm_JON012.cxChkTitle.Visible := True; Frm_JON012.btn_SelStCd.Visible := True; Frm_JON012.cxBtnFixPos.Visible := True; // Frm_JON012.Pnl_Title.Color := $00D9E6D2; Frm_JON012.lb_wkname_title.Visible := False; Frm_JON012.gCUT011CuSeq := Trim(clbCuSeq.Caption); if rdoCuGb1.Checked then Frm_JON012.gCUT011CuGb := 0 else if rdoCuGb2.Checked then Frm_JON012.gCUT011CuGb := 1 else if rdoCuGb3.Checked then Frm_JON012.gCUT011CuGb := 2; // 현재 할당된 폼 배열값을 저장.(현재 조회한 고객 데이터가 있는지 여부를 체킹) fSetFont(Frm_JON012, GS_FONTNAME); fSetSkin(Frm_JON012); Frm_JON012.Show; end; procedure TFrm_CUT011.btnBeforeClick(Sender: TObject); begin if cxCustTel.DataController.RecordCount > 0 then begin Proc_Jon012Show; Frm_JON012.cxBtnOldSelectClick(nil); end; end; procedure TFrm_CUT011.cboEmailPropertiesChange(Sender: TObject); begin if cboEmail.ItemIndex > 0 then begin edtCuEmail_Potal.Visible := False; cboEmail.Left := 195; cboEmail.Width := 134; end else if cboEmail.ItemIndex = 0 then begin edtCuEmail_Potal.Visible := True; cboEmail.Left := 329; cboEmail.Width := 99; end; end; end.
{ hello.pas } program hello; begin WriteLn('Hello, World!'); end.
unit FormSelecionarDiretorio; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl; type TfrmSelecionarDiretorio = class(TForm) dlbDiretorio: TDirectoryListBox; dcbDrive: TDriveComboBox; Label1: TLabel; Label2: TLabel; btnCancelar: TButton; btnOk: TButton; procedure dcbDriveChange(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnOkClick(Sender: TObject); private { Private declarations } fDirSelecionado: String; cancelou: Boolean; public { Public declarations } Property Diretorio: String read fDirSelecionado write fDirSelecionado; Function Selecionar: Boolean; end; var frmSelecionarDiretorio: TfrmSelecionarDiretorio; implementation {$R *.dfm} procedure TfrmSelecionarDiretorio.btnCancelarClick(Sender: TObject); begin cancelou := True; Close; end; procedure TfrmSelecionarDiretorio.btnOkClick(Sender: TObject); begin cancelou := False; Close; end; procedure TfrmSelecionarDiretorio.dcbDriveChange(Sender: TObject); begin dlbDiretorio.Drive := dcbDrive.Drive; end; function TfrmSelecionarDiretorio.Selecionar: Boolean; begin frmSelecionarDiretorio.ShowModal; if Not cancelou then begin Result := True; Diretorio := dlbDiretorio.Directory; end else begin Result := False; Diretorio := ''; end; end; end.
unit ReportTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTimingTest, BaseTestCase; {$I config.inc} Type { TFileWriteTest } TFileWriteTest = class (TGroupTimingTest) private procedure WriteFile; procedure WriteMarkDown; procedure WriteHTML; procedure WriteForumBBCode; procedure ClearLog; published procedure WriteFiles; end; implementation { TFileWriteTest } procedure TFileWriteTest.WriteFile; begin sl.SaveToFile('Results' + DirectorySeparator + self.RGString + DirectorySeparator + REP_FILE_CSV); end; procedure TFileWriteTest.WriteMarkDown; begin ml.SaveToFile('Results' + DirectorySeparator + self.RGString + DirectorySeparator +REP_FILE_MD); end; procedure TFileWriteTest.WriteHTML; begin hl.Strings[HeaderPos] := '<h1>FPC SSE/AVX '+ RGString +' test cases.</h1>'; hl.Add('</tbody>'); hl.Add('</table>'); hl.Add('</div>'); hl.Add('</body>'); hl.Add('</html>'); hl.SaveToFile('Results' + DirectorySeparator + self.RGString + DirectorySeparator + REP_FILE_HTML); end; procedure TFileWriteTest.WriteForumBBCode; begin fhl.Add('[/table]'); fhl.SaveToFile('Results' + DirectorySeparator + self.RGString + DirectorySeparator + 'BBCODE_'+REP_FILE_HTML); end; procedure TFileWriteTest.ClearLog; begin sl.Free; ml.free; hl.free; fhl.free; DoInitLists; end; procedure TFileWriteTest.WriteFiles; begin WriteFile; WriteMarkDown; WriteHTML; WriteForumBBCode; ClearLog; end; initialization RegisterTest(REPORT_GROUP_VECTOR2F, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR2D, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR2I, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR3B, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR4B, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR4F, TFileWriteTest ); RegisterTest(REPORT_GROUP_MATRIX4F, TFileWriteTest ); RegisterTest(REPORT_GROUP_QUATERION, TFileWriteTest ); RegisterTest(REPORT_GROUP_BBOX, TFileWriteTest ); RegisterTest(REPORT_GROUP_BSPHERE, TFileWriteTest ); RegisterTest(REPORT_GROUP_AABB, TFileWriteTest ); RegisterTest(REPORT_GROUP_PLANE_HELP, TFileWriteTest ); RegisterTest(REPORT_GROUP_VECTOR4I, TFileWriteTest ); end.
unit CommonValueDictFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, BaseObjects, Registrator; type TfrmFilter = class(TFrame) gbx: TGroupBox; cbxActiveObject: TComboEdit; procedure cbxActiveObjectButtonClick(Sender: TObject); private FActiveObject: TIDObject; FAllObjects: TRegisteredIDObjects; procedure SetActiveObject(const Value: TIDObject); { Private declarations } public property ActiveObject: TIDObject read FActiveObject write SetActiveObject; property AllObjects: TRegisteredIDObjects read FAllObjects write FAllObjects; procedure Reload; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses CommonValueDictSelectForm; {$R *.dfm} procedure TfrmFilter.cbxActiveObjectButtonClick(Sender: TObject); begin if Assigned (AllObjects) then begin frmValueDictSelect := TfrmValueDictSelect.Create(Self); frmValueDictSelect.AllObjects := AllObjects; if Assigned (ActiveObject) then frmValueDictSelect.ActiveObject := ActiveObject; if frmValueDictSelect.ShowModal = mrOk then begin ActiveObject := frmValueDictSelect.ActiveObject; Reload; end; frmValueDictSelect.Free; end else MessageBox(0, 'Справочник для объекта не указан.' + #10#13 + 'Обратитесь к разработчику.', 'Сообщение', MB_OK + MB_APPLMODAL + MB_ICONWARNING) end; constructor TfrmFilter.Create(AOwner: TComponent); begin inherited; end; destructor TfrmFilter.Destroy; begin inherited; end; procedure TfrmFilter.Reload; begin if Assigned (ActiveObject) then begin cbxActiveObject.Text := trim(ActiveObject.List); cbxActiveObject.Hint := trim(ActiveObject.List); end else begin cbxActiveObject.Text := ''; cbxActiveObject.Hint := ''; end; end; procedure TfrmFilter.SetActiveObject(const Value: TIDObject); begin if FActiveObject <> Value then begin FActiveObject := Value; Reload; end; end; end.
unit UWebLog; interface uses Classes, SysUtils; type TWebLog = class(TObject) data: TStream; fCursor: Integer; fEof: Boolean; private fCount: Integer; fFileName: string; procedure CreateInfo; public constructor Create(const aFileName:string = ''); destructor Destroy; override; function Eof: Boolean; procedure MoveTo(aRow:integer); function Row: string; property Count: Integer read fCount; property FileName: string read fFileName; end; implementation { TWebLog } { *********************************** TWebLog ************************************ } constructor TWebLog.Create(const aFileName:string = ''); begin inherited Create; fFileName:=aFileName; fCursor:=0; fEof:=false; data:=TFileStream.Create(); TFileStream(data).LoadFromFile(aFileName,fmOpenRead); end; destructor TWebLog.Destroy; begin if data<>nil then data.Free(); inherited; end; procedure TWebLog.CreateInfo; var cSize: LongInt; s: AnsiChar; begin fCursor:=0; fEof:=false; //------------------------------- fCount:=0; cSize:=data.Read(s,sizeof(s)); if (cSize>0) then begin fCount:=1; while (cSize>0) do begin cSize:=data.Read(s,sizeof(s)); if (Ord(s)=10) then fCount:=fCount+1; end; end else fEof:=true; data.Position:=0; //------------------------------- end; function TWebLog.Eof: Boolean; begin result:=fEof; end; procedure TWebLog.MoveTo(aRow:integer); var s: string; i: Integer; cCount: Integer; begin data.Position:=0; for i:=0 to aRow-1 do s:=Row(); exit; end; function TWebLog.Row: string; var s: AnsiChar; cSize: LongInt; begin result:=''; cSize:=data.Read(s,sizeof(s)); if (cSize=0) then begin fEof:=true; exit; end; while ((Ord(s)<>10)and(cSize>0)) do begin result:=result+s; cSize:=data.Read(s,sizeof(s)); if (cSize=0) then fEof:=true; end; fCursor:=fCursor+1; end; end.
unit TestuOrderProcessor; interface uses TestFramework, uOrderInterfaces; type TestTOrderProcessor = class(TTestCase) strict private FOrderProcessor: IOrderProcessor; public procedure SetUp(); override; published procedure TestProcessOrder; end; implementation uses uOrder, Spring.Container, Spring.Services; procedure TestTOrderProcessor.SetUp(); begin GlobalContainer.Build(); FOrderProcessor := ServiceLocator.GetService<IOrderProcessor>(); end; procedure TestTOrderProcessor.TestProcessOrder; var Order: TOrder; ResultValue: Boolean; begin Order := TOrder.Create(); try ResultValue := FOrderProcessor.ProcessOrder(Order); Check(ResultValue); finally Order.Free; end; end; initialization RegisterTest(TestTOrderProcessor.Suite); end.
unit uDataModule; interface uses System.SysUtils, System.Classes, Data.DB, FireDAC.DApt, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.Comp.Client; type TDataModule1 = class(TDataModule) MySqlDriver: TFDPhysMySQLDriverLink; procedure DataModuleCreate(Sender: TObject); private { Private declarations } function ObterConnection: TFDConnection; public { Public declarations } procedure DestruirQuery(probQuery: TFDQuery); function ObterQuery: TFDQuery; end; var DataModule1: TDataModule1; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDataModule1.DataModuleCreate(Sender: TObject); var oParams: TStrings; begin FDManager.Close; oParams := TStringList.Create; try oParams.Add('Database=PD2.0'); oParams.Add('User_Name=mauacruz'); oParams.Add('Password=mcmac'); oParams.Add('Server=localhost'); oParams.Add('port=3306'); oParams.Add('Pooled=True'); FDManager.AddConnectionDef('PD2.0', 'MySQL', oParams); FDManager.Open; finally oParams.Free; end; end; procedure TDataModule1.DestruirQuery(probQuery: TFDQuery); begin //Destroi a conex„o instanciada para a query; probQuery.Connection.Free; probQuery.Connection := nil; //Destroi a query; FreeAndNil(probQuery); end; function TDataModule1.ObterConnection: TFDConnection; begin Result := TFDConnection.Create(nil); Result.ConnectionDefName := 'PD2.0'; Result.Connected := True; end; function TDataModule1.ObterQuery: TFDQuery; begin Result := TFDQuery.Create(nil); Result.Connection := ObterConnection; Result.SQL.Clear; end; end.
unit ObjectClone; interface type TObjectClone = record class function From<T: class>(ASource: T): T; static; end; implementation uses SysUtils, Classes, TypInfo, RTTI, Controls; class function TObjectClone.From<T>(ASource: T): T; var LContext: TRttiContext; LisComponent, LLookOutForNameProp: Boolean; LRttiType: TRttiType; LMethod: TRttiMethod; LMinVisibility: TMemberVisibility; LParams: TArray<TRttiParameter>; LProp: TRttiProperty; LSourceAsPointer, LResultAsPointer: Pointer; begin LRttiType := LContext.GetType(ASource.ClassType); // find a suitable constructor, though treat components specially LisComponent := (ASource is TComponent); for LMethod in LRttiType.GetMethods do begin if LMethod.IsConstructor then begin LParams := LMethod.GetParameters; if LParams = nil then Break; if (Length(LParams) = 1) and LisComponent and (LParams[0].ParamType is TRttiInstanceType) and SameText(LMethod.Name, 'Create') then Break; end; end; if LParams = nil then Result := LMethod.Invoke(ASource.ClassType, []).AsType<T> else Result := LMethod.Invoke(ASource.ClassType, [TComponent(ASource).Owner]).AsType<T>; try // many VCL control properties require the Parent property to be set first if ASource is TControl then TControl(Result).Parent := TControl(ASource).Parent; // loop through the props, copying values across for ones that are read/write Move(ASource, LSourceAsPointer, SizeOf(Pointer)); Move(Result, LResultAsPointer, SizeOf(Pointer)); LLookOutForNameProp := LisComponent and (TComponent(ASource).Owner <> nil); if LisComponent then LMinVisibility := mvPublished // an alternative is to build an exception list else LMinVisibility := mvPublic; for LProp in LRttiType.GetProperties do begin if (LProp.Visibility >= LMinVisibility) and LProp.IsReadable and LProp.IsWritable then begin if LLookOutForNameProp and (LProp.Name = 'Name') and (LProp.PropertyType is TRttiStringType) then LLookOutForNameProp := False else LProp.SetValue(LResultAsPointer, LProp.GetValue(LSourceAsPointer)); end; end; except Result.Free; raise; end; end; end.
unit UnitCluster; interface uses Math; var r : real; {радиус} sqrBlowV : real; {скорость столкновения} dt : real; {промежуток времени} maxV : real; {максимальная скорость вдоль любой из осей} maxX, maxY : real; {размеры камеры} type TPoint = record {частица в кластере} X, Y : real; {координаты} end; TCluster = class {кластер} public Xc, Yc : real; {центр масс} Vx, Vy : real; {скорости кластера} PointCount : integer; {количество элементов} Point : array of TPoint; {элементы кластера} Enabled : boolean; {true, если кластер корректен} procedure Step; {рассчёт движения} function IsBlowed(var other : TCluster) : boolean; {проверка на столкновение} procedure Connect(var other : TCluster); {объединение кластеров} procedure Clear; {удаление кластера} end; implementation procedure TCluster.Step; {рассчёт движения} var i, j : integer; d : real; {сдвиг шариков при столкновении со стенкой} flagx, flagy : boolean; {регистраторы столкновений со стенкой} tmpxc, tmpyc : real; {для подсчёта центра масс} begin {сдвиг за один шаг} for i := 0 to PointCount-1 do begin Point[i].X := Point[i].X + Vx * dt; Point[i].Y := Point[i].Y + Vy * dt; end; {рассчёт столкновений со стенками} flagy := False; flagx := False; for i := 0 to PointCount-1 do begin If Point[i].X < r then begin flagx := True; d := r - Point[i].X; For j := 0 to PointCount-1 do begin Point[j].X := Point[j].X + d; end; end; If Point[i].X > maxX - r then begin flagx := True; d := Point[i].X - maxX + r; For j := 0 to PointCount-1 do begin Point[j].X := Point[j].X - d; end; end; If Point[i].Y < r then begin flagy := True; d := r - Point[i].Y; For j := 0 to PointCount-1 do begin Point[j].Y := Point[j].Y + d; end; end; If Point[i].Y > maxY - r then begin flagy := True; d := Point[i].Y - maxY + r; For j := 0 to PointCount-1 do begin Point[j].Y := Point[j].Y - d; end; end; end; If (flagx = True) then Vx := -Vx; If (flagy = True) then Vy := -Vy; {рассчёт центра масс} tmpxc := 0; tmpyc := 0; For i := 0 to PointCount - 1 do begin tmpxc := tmpxc + Point[i].X; tmpyc := tmpyc + Point[i].Y; end; xc := tmpxc / PointCount; yc := tmpyc / PointCount; end; function TCluster.IsBlowed(var other : TCluster) : boolean; {проверка на столкновение} var i, j : integer; begin For i := 0 to PointCount-1 do begin For j := 0 to other.PointCount-1 do begin if (sqr(Vx - other.Vx) + sqr(Vy - other.Vy) <= sqrBlowV) then begin if (sqr(Point[i].X - other.Point[j].X) + sqr(Point[i].Y - other.Point[j].Y) < 4*sqr(r)) then begin IsBlowed := true; exit; end; end; end; end; IsBlowed := False; end; procedure TCluster.Connect(var other : TCluster); var i : integer; tmpxc, tmpyc : real; {для подсчёта центра масс} begin {Рассчёт скорости} Vx := ((Vx * PointCount)+ (other.Vx * other.PointCount)) / (PointCount + other.PointCount); Vy := ((Vy * PointCount)+ (other.Vy * other.PointCount)) / (PointCount + other.PointCount); {добавление точек} SetLength(Point, PointCount + other.PointCount); for i := 0 to other.PointCount-1 do begin Point[PointCount + i].X := other.Point[i].X; Point[PointCount + i].Y := other.Point[i].Y; end; PointCount := PointCount + other.PointCount; {рассчёт центра масс} tmpxc := 0; tmpyc := 0; For i := 0 to PointCount - 1 do begin tmpxc := tmpxc + Point[i].X; tmpyc := tmpyc + Point[i].Y; end; xc := tmpxc / PointCount; yc := tmpyc / PointCount; end; procedure TCluster.Clear; begin SetLength(Point, 0); PointCount := 0; end; end.
unit uCreateTorrent; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Contnrs, Buttons, ImgList, FileCtrl, uProcedures, uTorrentThreads, uTorrentMethods, uTasks, PluginApi, PluginManager; const WM_MYMSG = WM_USER + 200; type TTracker = record Name, Announce, Webpage: String; Down: Boolean; end; TfCreateTorrent = class(TForm) ComboBox1: TComboBox; btnAddFile: TButton; btnAddFolder: TButton; Tabs: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; ComboBox2: TComboBox; Label1: TLabel; Panel1: TPanel; btnCreate: TButton; mmoAnnounceURL: TMemo; mmWebSeeds: TMemo; mmoComment: TMemo; CheckBox1: TCheckBox; CheckBox2: TCheckBox; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; Timer1: TTimer; Label2: TLabel; StatusBar1: TStatusBar; sGauge1: TProgressBar; sGauge2: TProgressBar; procedure btnCreateClick(Sender: TObject); procedure btnAddFileClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CreateParams(var Params: TCreateParams); override; procedure btnAddFolderClick(Sender: TObject); function GetAnnounceURL: String; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TabSheet2Show(Sender: TObject); procedure TabSheet3Show(Sender: TObject); procedure TabSheet1Show(Sender: TObject); private Trackers: array of TTracker; GetedId: string; GetedStatus: string; GetedFileName: string; GetedProgressMax1: Int64; GetedProgressMax2: Int64; GetedProgressPosition1: Int64; GetedProgressPosition2: Int64; TorrentFileName: WideString; procedure GetInGeted(GetedData: WideString); procedure UpdateCreatingInfo; procedure WaitingCreation; procedure ReleaseCreateTorrentThread(BTCreateTorrent: IBTCreateTorrent; Id: string); procedure StopCreateTorrentThread(Id: string; BTCreateTorrent: IBTCreateTorrent); procedure StartTorrent; procedure MyMsg(var Message: TMessage); message WM_MYMSG; { Private declarations } public Stop: Boolean; ButtonSave: Boolean; { Public declarations } end; var fCreateTorrent: TfCreateTorrent; implementation uses uMainForm, uObjects; {$R *.dfm} procedure TfCreateTorrent.MyMsg(var Message: TMessage); var MessSelect: string; begin MessSelect := IntToStr(Message.LParam); if (pos('10007', MessSelect) > 0) then begin end; end; procedure TfCreateTorrent.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW; Params.WndParent := GetDesktopWindow; end; procedure TfCreateTorrent.btnAddFileClick(Sender: TObject); begin FormStyle := fsNormal; if OpenDialog1.Execute then begin ComboBox1.Text := PChar(OpenDialog1.Filename); btnCreate.Enabled := true; end; FormStyle := fsStayOnTop; end; function TfCreateTorrent.GetAnnounceURL: String; var i: Integer; found: Boolean; begin found := False; for i := 0 to high(Trackers) do if Trackers[i].Name = mmoAnnounceURL.Text then begin result := Trackers[i].Announce; found := true; end; if not found then begin result := mmoAnnounceURL.Text; end; end; procedure TfCreateTorrent.TabSheet1Show(Sender: TObject); begin ActiveControl := mmoAnnounceURL; end; procedure TfCreateTorrent.TabSheet2Show(Sender: TObject); begin ActiveControl := mmWebSeeds; end; procedure TfCreateTorrent.TabSheet3Show(Sender: TObject); begin ActiveControl := mmoComment; end; procedure TfCreateTorrent.btnAddFolderClick(Sender: TObject); var chosenDirectory: string; begin FormStyle := fsNormal; if SelectDirectory('Выберите каталог: ', '', chosenDirectory) then begin ComboBox1.Text := chosenDirectory; btnCreate.Enabled := true; end; FormStyle := fsStayOnTop; end; procedure TfCreateTorrent.btnCreateClick(Sender: TObject); var BTCreateTorrent: IBTCreateTorrent; X: Integer; FindBTPlugin: Boolean; Id: string; begin if ButtonSave then begin if ComboBox1.Text[length(ComboBox1.Text)] = '\' then ComboBox1.Text := copy(ComboBox1.Text, 1, length(ComboBox1.Text) - 1); if FileExists(ComboBox1.Text) then begin SaveDialog1.Filter := 'Torrent Files (*.torrent)|*.torrent'; SaveDialog1.Filename := ComboBox1.Text + '.torrent'; SaveDialog1.DefaultExt := 'Torrent files (*.torrent)'; FormStyle := fsNormal; if SaveDialog1.Execute then begin FormStyle := fsStayOnTop; TorrentFileName := SaveDialog1.Filename; ButtonSave := False; btnCreate.Caption := 'Остановить'; EnterCriticalSection(TorrentSection); try for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTCreateTorrent, BTCreateTorrent)) then begin FindBTPlugin := true; break; end; end; finally LeaveCriticalSection(TorrentSection); end; if FindBTPlugin then begin try Id := IntToStr(CreateTorrentID) except end; EnterCriticalSection(TorrentSection); try try BTCreateTorrent.SingleFileTorrent((Id), (ComboBox1.Text), (SaveDialog1.Filename), (mmoComment.Lines.Text), (GetAnnounceURL), (mmWebSeeds.Lines.Text), CheckBox2.checked, ComboBox2.ItemIndex, False, False, '', '', '', ''); except end; finally LeaveCriticalSection(TorrentSection); end; repeat application.ProcessMessages; EnterCriticalSection(TorrentSection); try try GetInGeted(BTCreateTorrent.GetInfoTorrentCreating(Id)); except end; finally LeaveCriticalSection(TorrentSection); end; if (Stop) and (not(GetedStatus = 'stoped')) then begin EnterCriticalSection(TorrentSection); try try BTCreateTorrent.StopCreateTorrentThread(Id); except end; finally LeaveCriticalSection(TorrentSection); end; end; WaitingCreation; if (Stop) and (not(GetedStatus = 'stoped')) then begin EnterCriticalSection(TorrentSection); try try BTCreateTorrent.StopCreateTorrentThread(Id); except end; finally LeaveCriticalSection(TorrentSection); end; end; sleep(10); until (GetedStatus = 'completed') or (GetedStatus = 'stoped'); end; ReleaseCreateTorrentThread(BTCreateTorrent, Id); if (GetedStatus = 'completed') then begin sGauge2.Position := sGauge2.Max; sGauge1.Position := sGauge1.Max; StatusBar1.Panels[0].Text := 'Создание торрент-файла успешно завершено!'; if CheckBox1.checked then StartTorrent; end; if (GetedStatus = 'stoped') then begin StatusBar1.Panels[0].Text := 'Остановлено.'; end; Stop := False; btnCreate.Enabled := true; ButtonSave := true; btnCreate.Caption := 'Создать'; end; end else if DirectoryExists(ComboBox1.Text) then begin SaveDialog1.Filter := 'Torrent Files (*.torrent)|*.torrent'; SaveDialog1.Filename := ComboBox1.Text + '.torrent'; SaveDialog1.DefaultExt := 'Torrent files (*.torrent)'; FormStyle := fsNormal; if SaveDialog1.Execute then begin FormStyle := fsStayOnTop; TorrentFileName := SaveDialog1.Filename; ButtonSave := False; btnCreate.Caption := 'Остановить'; EnterCriticalSection(TorrentSection); try for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTCreateTorrent, BTCreateTorrent)) then begin FindBTPlugin := true; break; end; end; finally LeaveCriticalSection(TorrentSection); end; if FindBTPlugin then begin try Id := IntToStr(CreateTorrentID) except end; EnterCriticalSection(TorrentSection); try try BTCreateTorrent.CreateFolderTorrent((Id), (ComboBox1.Text), (SaveDialog1.Filename), (mmoComment.Lines.Text), (GetAnnounceURL), (mmWebSeeds.Lines.Text), CheckBox2.checked, ComboBox2.ItemIndex, False, False, '', '', '', ''); except end; finally LeaveCriticalSection(TorrentSection); end; repeat application.ProcessMessages; EnterCriticalSection(TorrentSection); try try GetInGeted(BTCreateTorrent.GetInfoTorrentCreating(Id)); except end; finally LeaveCriticalSection(TorrentSection); end; if (Stop) and (not(GetedStatus = 'stoped')) then begin EnterCriticalSection(TorrentSection); try try BTCreateTorrent.StopCreateTorrentThread(Id); except end; finally LeaveCriticalSection(TorrentSection); end; end; WaitingCreation; if (Stop) and (not(GetedStatus = 'stoped')) then begin EnterCriticalSection(TorrentSection); try try BTCreateTorrent.StopCreateTorrentThread(Id); except end; finally LeaveCriticalSection(TorrentSection); end; end; sleep(10); until (GetedStatus = 'completed') or (GetedStatus = 'stoped'); try ReleaseCreateTorrentThread(BTCreateTorrent, Id); except end; if (GetedStatus = 'completed') then begin sGauge2.Position := sGauge2.Max; sGauge1.Position := sGauge1.Max; StatusBar1.Panels[0].Text := 'Создание торрент-файла успешно завершено!'; if CheckBox1.checked then StartTorrent; end; if (GetedStatus = 'stoped') then begin StatusBar1.Panels[0].Text := 'Остановлено.'; end; Stop := False; btnCreate.Enabled := true; ButtonSave := true; btnCreate.Caption := 'Создать'; end; end; end else begin Stop := False; btnCreate.Enabled := true; ButtonSave := true; btnCreate.Caption := 'Создать'; end; end else begin Stop := true; btnCreate.Enabled := False; ButtonSave := true; StatusBar1.Panels[0].Text := 'Приостановка процесса...'; btnCreate.Caption := 'Останавливается...'; end; end; procedure TfCreateTorrent.GetInGeted(GetedData: WideString); var GetedList: tstringlist; begin GetedList := tstringlist.Create; try try GetedList.Delimiter := ' '; GetedList.QuoteChar := '|'; GetedList.DelimitedText := GetedData; GetedId := GetedList[0]; GetedStatus := GetedList[1]; GetedFileName := GetedList[2]; except end; try GetedProgressMax1 := StrToInt64(GetedList[3]); except end; try GetedProgressMax2 := StrToInt64(GetedList[4]); except end; try GetedProgressPosition1 := StrToInt64(GetedList[5]); except end; try GetedProgressPosition2 := StrToInt64(GetedList[6]); except end; finally GetedList.Free; end; end; procedure TfCreateTorrent.UpdateCreatingInfo; begin if (GetedProgressMax2 >= 2147483647) or (GetedProgressPosition2 >= 2147483647) then begin try sGauge2.Max := GetedProgressMax2 div 1024; sGauge2.Position := GetedProgressPosition2 div 1024; except end; end else begin try sGauge2.Max := GetedProgressMax2; sGauge2.Position := GetedProgressPosition2; except end; end; if (GetedProgressMax1 >= 2147483647) or (GetedProgressPosition1 >= 2147483647) then begin try sGauge1.Max := GetedProgressMax1 div 1024; sGauge1.Position := GetedProgressPosition1 div 1024; except end; end else begin try sGauge1.Max := GetedProgressMax1; sGauge1.Position := GetedProgressPosition1; except end; end; // sGauge2.Suffix := '% (' + ExtractFileName(GetedFileName) + ')'; end; procedure TfCreateTorrent.WaitingCreation; begin if GetedStatus = 'start' then begin end; if GetedStatus = 'creating' then begin UpdateCreatingInfo; StatusBar1.Panels[0].Text := 'Хэширование...'; end; if GetedStatus = 'done' then begin sGauge1.Position := GetedProgressMax1; end; if GetedStatus = 'abort' then begin end; if Stop then begin StatusBar1.Panels[0].Text := 'Приостановка процесса...'; end; end; procedure TfCreateTorrent.ReleaseCreateTorrentThread(BTCreateTorrent : IBTCreateTorrent; Id: string); begin EnterCriticalSection(TorrentSection); try BTCreateTorrent.ReleaseCreateTorrentThread(Id); finally LeaveCriticalSection(TorrentSection); end; end; procedure TfCreateTorrent.StopCreateTorrentThread(Id: string; BTCreateTorrent: IBTCreateTorrent); begin EnterCriticalSection(TorrentSection); try try BTCreateTorrent.StopCreateTorrentThread(Id); except end; finally LeaveCriticalSection(TorrentSection); end; end; procedure TfCreateTorrent.StartTorrent; var BTPlugin: IBTServicePlugin; HashValue: string; Find: Boolean; i: Integer; InfoTorrent: WideString; InfoTorrentSL: tstringlist; TorrentDataSL: tstringlist; DataTask: TTask; Local_X: Integer; Local_X1: Integer; X: Integer; DataList: tstringlist; BTAddSeeding: IBTServiceAddSeeding; begin for Local_X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[Local_X], IBTServicePlugin, BTPlugin)) then begin try InfoTorrent := BTPlugin.GetInfoTorrentFile(TorrentFileName); except end; break; end; end; InfoTorrentSL := tstringlist.Create; try InfoTorrentSL.Text := (InfoTorrent); HashValue := (InfoTorrentSL[5]); except end; if Trim(HashValue) = '' then begin MessageBox(application.Handle, PChar('Нет доступа к торрент файлу или ошибка при открытии торрент-файла'), PChar(Options.Name), MB_OK or MB_ICONWARNING or MB_TOPMOST); exit; end; Find := False; with TasksList.LockList do try for i := 0 to Count - 1 do begin DataTask := Items[i]; if ansilowercase(DataTask.HashValue) = ansilowercase(HashValue) then begin if DataTask.Status <> tsDeleted then begin Find := true; break; end; end; end; finally TasksList.UnLockList; end; if Find then begin MessageBox(application.Handle, PChar('Этот торрент уже имеется в списке закачек'), PChar(Options.Name), MB_OK or MB_ICONWARNING or MB_TOPMOST); exit; end; Find := False; with TasksList.LockList do try for Local_X1 := 0 to Count - 1 do begin DataTask := Items[Local_X1]; if DataTask.Status <> tsDeleted then if DataTask.HashValue = HashValue then begin Find := true; break; end; end; finally TasksList.UnLockList; end; if Find then begin MessageBox(application.Handle, PChar('Торрент имеется в списке заданий'), PChar(Options.Name), MB_OK or MB_ICONWARNING or MB_TOPMOST); exit; end; TorrentDataSL := tstringlist.Create; try TorrentDataSL.Insert(0, BoolToStr(true)); TorrentDataSL.Insert(1, BoolToStr(False)); TorrentDataSL.Insert(2, TorrentFileName); TorrentDataSL.Insert(3, ExtractFilePath(ComboBox1.Text)); TorrentDataSL.Insert(4, IntToStr(50)); TorrentDataSL.Insert(5, InfoTorrentSL[0]); TorrentDataSL.Insert(6, InfoTorrentSL[6]); TorrentDataSL.Insert(7, InfoTorrentSL[7]); TorrentDataSL.Insert(8, InfoTorrentSL[8]); TorrentDataSL.Insert(9, InfoTorrentSL[2]); AddTorrent(TorrentDataSL.Text, HashValue, False, False); finally TorrentDataSL.Free; InfoTorrentSL.Free; end; Find := False; with TasksList.LockList do try for Local_X1 := 0 to Count - 1 do begin DataTask := Items[Local_X1]; if DataTask.Status <> tsDeleted then if DataTask.HashValue = HashValue then begin Find := true; break; end; end; finally TasksList.UnLockList; end; if Find then begin for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTServiceAddSeeding, BTAddSeeding)) then begin DataList := tstringlist.Create; EnterCriticalSection(TorrentSection); try try DataList.Insert(0, IntToStr(DataTask.Id)); DataList.Insert(1, DataTask.TorrentFileName); DataList.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); BTAddSeeding.AddSeeding(DataList.Text); except end; finally LeaveCriticalSection(TorrentSection); DataList.Free; end; break; end; end; TSeedingThread.Create(False, DataTask, False); DataTask.Status := tsSeeding; end; PostMessage(Options.MainFormHandle, WM_MYMSG, 0, 12345); LoadTorrentThreads.Add(TLoadTorrent.Create(False, DataTask, true)); end; procedure TfCreateTorrent.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; Options.StartSeeding := CheckBox1.checked; Options.PrivateTorrent := CheckBox2.checked; Options.Trackers := mmoAnnounceURL.Lines.Text; Options.PartSize := ComboBox2.ItemIndex; Dec(CreateTorrentID); Options.CreateTorrentHandle := 0; end; procedure TfCreateTorrent.FormCreate(Sender: TObject); begin Stop := False; ButtonSave := true; btnCreate.Enabled := False; Position := poMainFormCenter; CheckBox1.checked := Options.StartSeeding; CheckBox2.checked := Options.PrivateTorrent; mmoAnnounceURL.Lines.Text := Options.Trackers; ComboBox2.ItemIndex := Options.PartSize; Inc(CreateTorrentID); end; end.
program arrays; var n: array [1..20] of integer; var i sum: integer; var average : real; begin sum := 0; for i := 1 to 20 do begin n[ i ] := i; sum := sum + n[ i ]; end; average := sum / 20.0; writeln(average); end.
unit UPrincipal; interface uses classes.Constantes, System.PushNotification, System.JSON, FMX.DialogService, FMX.VirtualKeyBoard, FMX.Platform, System.Threading, System.Math, // {$IF DEFINED (ANDROID)} // System.Android.Service, // {$ENDIF} System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.Layouts, FMX.Controls.Presentation, FMX.MultiView, FMX.StdCtrls, FMX.Objects, FMX.ListBox, IPPeerClient, REST.Backend.PushTypes, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.PushDevice, FMX.ScrollBox, FMX.Memo; type TFrmPrincipal = class(TForm) ScrollBoxForm: TScrollBox; LayoutForm: TLayout; tabControlForm: TTabControl; tbiLogin: TTabItem; tbiMenu: TTabItem; LayoutMenu: TLayout; MultiViewMenu: TMultiView; LayoutMViewTop: TLayout; LabelUserEmail: TLabel; LabelUserName: TLabel; RectangleMViewUser: TRectangle; CircleUserImage: TCircle; LayoutUserImage: TLayout; ToolBarMenu: TToolBar; BtnMenu: TSpeedButton; LayoutMViewOpcoes: TLayout; ImageUser: TImage; BtnMenuCardapio: TSpeedButton; ImageMenuCardapio: TImage; LabelMenuCardapio: TLabel; LineCardapio: TLine; BtnMenuPedido: TSpeedButton; ImageMenuPedido: TImage; LabelMenuPedido: TLabel; BtnMenuCompras: TSpeedButton; ImageMenuCompras: TImage; LabelMenuCompras: TLabel; LineCompras: TLine; SpeedButton1: TSpeedButton; Image1: TImage; Label1: TLabel; procedure DoCarregarCardapio(Sender: TObject); procedure DoCarregarPedidos(Sender: TObject); procedure DoCarregarHistoricoCompras(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure ListBoxItemMeusDadosClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } // {$IF DEFINED (ANDROID)} // aServiceBurgerHeroes : TLocalServiceConnection; // {$ENDIF} aPushService : TPushService; aPushServiceConnection : TPushServiceConnection; procedure AtivarPushNotification; procedure CarregarPushNotification; procedure SetStyleBotton(const aSpeedButton: TSpeedButton); procedure DoServiceConnectionChange(Sender : TObject; PushChanges : TPushService.TChanges); procedure DoReceiveNotificationEvent(Sender : TObject; const ServiceNotification : TPushServiceNotification); public { Public declarations } end; var FrmPrincipal: TFrmPrincipal; implementation {$R *.fmx} uses UDM, UAbout; procedure TFrmPrincipal.AtivarPushNotification; begin {$IF DEFINED (ANDROID)} aPushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.GCM); aPushService.AppProps[TPushService.TAppPropNames.GCMAppID] := APP_CODIGO_REMETENTE; aPushServiceConnection := TPushServiceConnection.Create(aPushService); aPushServiceConnection.OnChange := DoServiceConnectionChange; aPushServiceConnection.OnReceiveNotification := DoReceiveNotificationEvent; TTask.Run( procedure begin try aPushServiceConnection.Active := True; except end; end ); {$ENDIF} {$IF DEFINED (IOS)} aPushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.APS); aPushServiceConnection := TPushServiceConnection.Create(aPushService); aPushServiceConnection.OnChange := DoServiceConnectionChange; aPushServiceConnection.OnReceiveNotification := DoReceiveNotificationEvent; TTask.Run( procedure begin try aPushServiceConnection.Active := True; except end; end ); {$ENDIF} end; procedure TFrmPrincipal.CarregarPushNotification; var aMessageTitle, aMessageText : String; aPushData : TPushData; x : Integer; begin // Recuperar notificação quando o APP estiver fechado aMessageTitle := EmptyStr; aMessageText := EmptyStr; aPushData := DM.PushEvents.StartupNotification; try if Assigned(aPushData) then begin aMessageTitle := 'Notificação'; aMessageText := Trim(aPushData.Message); // // Está funcionando // // IOS // if (Trim(DtmDados.PushEvents.StartupNotification.APS.Alert) <> EmptyStr) then // for x := 0 to aPushData.Extras.Count - 1 do // ; //aValor := aPushData.Extras[x].Key + '=' + aPushData.Extras[x].Value; // // ANDROID // if (Trim(DtmDados.PushEvents.StartupNotification.GCM.Message) <> EmptyStr) then // for x := 0 to aPushData.Extras.Count - 1 do // ; //aValor := aPushData.Extras[x].Key + '=' + aPushData.Extras[x].Value; // if (Trim(aMessageText) <> EmptyStr) then TDialogService.MessageDialog(aMessageText, TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); end; finally aPushData.DisposeOf; DM.ClearPush; end; end; procedure TFrmPrincipal.DoCarregarCardapio(Sender: TObject); begin SetStyleBotton(TSpeedButton(Sender)); end; procedure TFrmPrincipal.DoCarregarHistoricoCompras(Sender: TObject); begin SetStyleBotton(TSpeedButton(Sender)); end; procedure TFrmPrincipal.DoCarregarPedidos(Sender: TObject); begin SetStyleBotton(TSpeedButton(Sender)); end; procedure TFrmPrincipal.DoReceiveNotificationEvent(Sender: TObject; const ServiceNotification: TPushServiceNotification); var aMessageTitle, aMessageText , aJsonText : String; x : Integer; Obj : TJSONObject; Pair : TJSONPair; begin // Recuperar notificação quando o APP estiver aberto try aMessageText := EmptyStr; aJsonText := ServiceNotification.DataObject.ToJSON; for x := 0 to ServiceNotification.DataObject.Count - 1 do begin // IOS if ServiceNotification.DataKey = 'aps' then begin if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'title') then aMessageTitle := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value) else if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'alert') then aMessageText := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value); end else // ANDROID if ServiceNotification.DataKey = 'gcm' then begin if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'title') then aMessageTitle := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value) else if (ServiceNotification.DataObject.Pairs[x].JsonString.Value = 'message') then aMessageText := Trim(ServiceNotification.DataObject.Pairs[x].JsonValue.Value); end; end; if (Trim(aMessageText) <> EmptyStr) then DM.AlertNotification(APP_BURGER_HEROES, aMessageTitle, Trim(aMessageText)); except ; end; end; procedure TFrmPrincipal.DoServiceConnectionChange(Sender: TObject; PushChanges: TPushService.TChanges); var aDispositivoID , aDispositivoToken : String; begin if (TPushService.TChange.DeviceToken in PushChanges) then begin aDispositivoID := aPushService.DeviceTokenValue[TPushService.TDeviceIDNames.DeviceID]; aDispositivoToken := aPushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken]; // // if (Model.Ativo) and (Model.Id <> GUID_NULL) and (Trim(Model.TokenPush) <> EmptyStr) then // GravarTokenID; end; end; procedure TFrmPrincipal.FormActivate(Sender: TObject); begin CarregarPushNotification; end; procedure TFrmPrincipal.FormCreate(Sender: TObject); var aWidth : Single; begin aWidth := Round((Screen.Width / 4) * 3); MultiViewMenu.Width := aWidth; MultiViewMenu.HideMaster; tabControlForm.TabPosition := TTabPosition.None; AtivarPushNotification; end; procedure TFrmPrincipal.ListBoxItemMeusDadosClick(Sender: TObject); begin MultiViewMenu.HideMaster; Application.CreateForm(TFrmAbout, FrmAbout); FrmAbout.Show; end; procedure TFrmPrincipal.SetStyleBotton(const aSpeedButton: TSpeedButton); begin MultiViewMenu.HideMaster; BtnMenuCardapio.IsPressed := False; BtnMenuPedido.IsPressed := False; BtnMenuCompras.IsPressed := False; aSpeedButton.IsPressed := True; end; procedure TFrmPrincipal.SpeedButton1Click(Sender: TObject); begin // {$IF DEFINED (ANDROID)} // aServiceBurgerHeroes := TLocalServiceConnection.Create; // aServiceBurgerHeroes.StartService('ServiceBurgerHeroes'); // {$ENDIF} end; end.
unit Unit2; interface uses Grids, SysUtils; type RefToStackElement = ^StackElement; StackElement = record value: extended; previos: RefToStackElement; end; Stack = class(TObject) private { Private declarations } size: longint; recent_element: RefToStackElement; procedure destroy_recent_stack_element(); procedure swap(first, second: longint); function make_new_stack_element(temp: extended): RefToStackElement; function getValueById(id: longint): extended; function getRefById(id: longint): RefToStackElement; public { Public declarations } Constructor Create(); procedure Destroy(); procedure push_back(temp: extended); procedure bubble_sort(); procedure print(StringGrid1: TStringGrid); procedure swapExtremuls(); function pop_back(): extended; end; implementation Constructor Stack.Create(); begin size := 0; recent_element := nil; end; procedure Stack.swapExtremuls(); var max_pos, min_pos, i: longint; maxx, minn: extended; current: RefToStackElement; begin maxx := -100000; minn := 100000; current := recent_element; for i := 1 to size do begin if (current^.value > maxx) then begin maxx := current^.value; max_pos := i; end; if (current^.value < minn) then begin minn := current^.value; min_pos := i; end; current := current^.previos; end; swap(min_pos, max_pos); end; procedure Stack.Destroy(); begin while(size > 0) do begin pop_back(); end; end; function Stack.make_new_stack_element(temp: extended): RefToStackElement; var new_stack_element: RefToStackElement; begin GetMem(new_stack_element, sizeof(StackElement)); new_stack_element^.value := temp; new_stack_element^.previos := recent_element; make_new_stack_element := new_stack_element; end; procedure Stack.destroy_recent_stack_element(); var previous_stack_element: RefToStackElement; begin previous_stack_element := recent_element^.previos; FreeMem(recent_element, sizeof(StackElement)); recent_element := previous_stack_element; end; procedure Stack.push_back(temp: extended); begin recent_element := make_new_stack_element(temp); inc(size); end; function Stack.pop_back(): extended; begin pop_back := recent_element^.value; destroy_recent_stack_element(); dec(size); end; function Stack.getValueById(id: longint): extended; var current: RefToStackElement; i: longint; begin current := recent_element; i := 1; while (i < id) do begin current := current^.previos; inc(i); end; getValueById := current^.value; end; function Stack.getRefById(id: longint): RefToStackELement; var current: RefToStackElement; i: longint; begin current := recent_element; i := 1; while (i < id) do begin current := current^.previos; inc(i); end; getRefById := current; end; procedure Stack.swap(first, second: longint); var i: longint; current, first_ref, second_ref, temp_ref: RefToStackElement; begin first_ref := getRefById(first); second_ref := getRefById(second); temp_ref := first_ref^.previos; first_ref^.previos := second_ref^.previos; second_ref^.previos := temp_ref; if (first_ref^.previos = first_ref) then begin first_ref^.previos := second_ref; end; if (second_ref^.previos = second_ref) then begin second_ref^.previos := first_ref; end; if (recent_element = second_ref) then begin recent_element := first_ref; end else begin if (recent_element = first_ref) then begin recent_element := second_ref; end; end; current := recent_element; i := 1; while (i < size) do begin if ((current^.previos = first_ref) and (current <> second_ref)) then begin current^.previos := second_ref; end else begin if ((current^.previos = second_ref) and (current <> first_ref)) then begin current^.previos := first_ref; end; end; inc(i); current := current^.previos; end; end; procedure Stack.bubble_sort(); var i, j: longint; begin for i := 1 to size do begin for j := i + 1 to size do begin if (getValueById(i) > getValueById(j)) then begin swap(i, j); end; end; end; end; procedure Stack.print(StringGrid1: TStringGrid); var current: RefToStackElement; i: longint; begin current := recent_element; StringGrid1.ColCount := size; StringGrid1.RowCount := 1; for i := 1 to size do begin StringGrid1.Cells[i - 1, 0] := FloatToStrF(current^.value, fffixed, 8, 4); current := current^.previos; end; end; end.
unit VP500Panel; // ================================================ // VP500 patch clamp control panel // (c) J. Dempster, University of Strathclyde, 2004 // ================================================ // 3.03.04 // 5.04.04 // 4.08.04 Holding current now set correctly in pA // Holding current/potentials remembered between mode switches // 05.12.04 Junction potential up/down arrow buttons added interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ValidatedEdit, vp500Unit, vp500lib, SESLabIO, ExtCtrls, Spin ; type TVP500PanelFrm = class(TForm) GroupBox1: TGroupBox; cbClampMode: TComboBox; GroupBox4: TGroupBox; cbLPFilter: TComboBox; GroupBox5: TGroupBox; cbAmplifierGain: TComboBox; GroupBox3: TGroupBox; cbLowHeadstageGain: TRadioButton; rbHeadStageGain: TRadioButton; HoldingVIGrp: TGroupBox; edHoldingVI: TValidatedEdit; GroupBox7: TGroupBox; edJunctionPotential: TValidatedEdit; GroupBox10: TGroupBox; GroupBox9: TGroupBox; Label4: TLabel; edPercentBoost: TValidatedEdit; GroupBox8: TGroupBox; Label1: TLabel; Label3: TLabel; edPercentRs: TValidatedEdit; cbTauPercentRs: TComboBox; bAppyCompensation: TButton; GroupBox11: TGroupBox; GroupBox13: TGroupBox; Label6: TLabel; edCFast: TValidatedEdit; Label7: TLabel; edTauFast: TValidatedEdit; bCFastNeutralise: TButton; Label5: TLabel; GroupBox12: TGroupBox; Label8: TLabel; Label9: TLabel; edCSlow: TValidatedEdit; edTauSlow: TValidatedEdit; bCSlowNeutralise: TButton; GroupBox14: TGroupBox; Label10: TLabel; Label11: TLabel; edCCell: TValidatedEdit; edTauCell: TValidatedEdit; bCCellNeutralise: TButton; cbClampSpeed: TComboBox; lbClampSpeed: TLabel; bApplyHoldingIV: TButton; bApplyJunction: TButton; GroupBox2: TGroupBox; edSealResistance: TValidatedEdit; bCalcSealResistance: TButton; GroupBox6: TGroupBox; edRm: TValidatedEdit; edCm: TValidatedEdit; edRs: TValidatedEdit; Label2: TLabel; Label12: TLabel; Label13: TLabel; bCalcCellParameters: TButton; GroupBox15: TGroupBox; bZap: TButton; edZapDuration: TValidatedEdit; Label14: TLabel; ckNeutraliseLeak: TCheckBox; GroupBox16: TGroupBox; bInitialise: TButton; bOptimiseNeutralisation: TButton; GroupBox17: TGroupBox; edStatus: TEdit; Timer: TTimer; spJunctionPotential: TSpinButton; procedure FormShow(Sender: TObject); procedure cbClampModeChange(Sender: TObject); procedure cbClampSpeedChange(Sender: TObject); procedure cbAmplifierGainChange(Sender: TObject); procedure cbLowHeadstageGainClick(Sender: TObject); procedure cbLPFilterChange(Sender: TObject); procedure bAppyCompensationClick(Sender: TObject); procedure edPercentRsKeyPress(Sender: TObject; var Key: Char); procedure edPercentBoostKeyPress(Sender: TObject; var Key: Char); procedure cbTauPercentRsChange(Sender: TObject); procedure edCFastKeyPress(Sender: TObject; var Key: Char); procedure bCFastNeutraliseClick(Sender: TObject); procedure bCSlowNeutraliseClick(Sender: TObject); procedure bCCellNeutraliseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bApplyHoldingIVClick(Sender: TObject); procedure edHoldingVIKeyPress(Sender: TObject; var Key: Char); procedure bApplyJunctionClick(Sender: TObject); procedure edJunctionPotentialKeyPress(Sender: TObject; var Key: Char); procedure bCalcSealResistanceClick(Sender: TObject); procedure bCalcCellParametersClick(Sender: TObject); procedure bInitialiseClick(Sender: TObject); procedure bZapClick(Sender: TObject); procedure bOptimiseNeutralisationClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure spJunctionPotentialUpClick(Sender: TObject); procedure spJunctionPotentialDownClick(Sender: TObject); private { Private declarations } HardwareConf : THardwareConf ; Neutralization : TNeutralization ; Compensations : TCompensations ; JunctionPotential : Single ; HoldingVI : Array[0..3] of Single ; procedure UpdateClampModeLabels ; procedure UpdateCompensations ; procedure UpdateNeutralization ; procedure GetNeutralizationSettings ; procedure SetHoldingVI ; public { Public declarations } end; var VP500PanelFrm: TVP500PanelFrm; implementation uses Mdiform; {$R *.dfm} procedure TVP500PanelFrm.FormShow(Sender: TObject); // -------------------------------------- // Initialisations when form is displayed // -------------------------------------- var i,Err : Integer ; begin // Initialise VP500 hardware if another interface is being // used for digitisation if Main.SESLabIO.LabInterfaceType <> VP500 then VP500_InitialiseBoard ; HardwareConf.AmplifierStageGain := 0 ; // Get VP500 settings Err := VP500_GetHardwareConf( @HardwareConf ) ; VP500_CheckError( Err, 'VP500_GetHardwareConf' ) ; // Clamp mode cbClampMode.ItemIndex := HardwareConf.ClampMode ; cbClampSpeed.ItemIndex := HardwareConf.ClampSpeed ; // Update labels for clamp mode UpdateClampModeLabels ; // Head stage gain rbHeadStageGain.Checked := HardwareConf.HeadGainH ; // Amplifier gain cbAmplifierGain.ItemIndex := HardwareConf.AmplifierStageGain ; // LP filter cbLPFilter.ItemIndex := HardwareConf.AmplifierStageFilter ; // Get RC neutralisation settings GetNeutralizationSettings ; // Get compensation settings Err := VP500_GetCompensations( @Compensations ) ; edPercentRs.Value := Compensations.PercentRs ; cbTauPercentRs.ItemIndex := Compensations.TauPercentRs ; edPercentBoost.Value := Compensations.PercentBoost ; // Junction potential correction Err := VP500_GetJunction( @JunctionPotential ) ; edJunctionPotential.Value := JunctionPotential ; // Holding potential/current for i := 0 to High(HoldingVI) do HoldingVI[i] := 0.0 ; Err := VP500_GetVIHold( @HoldingVI[HardwareConf.ClampMode] ) ; edHoldingVI.Value := HoldingVI[HardwareConf.ClampMode] ; // Set holding V/I SetHoldingVI ; end; procedure TVP500PanelFrm.cbClampModeChange(Sender: TObject); // ------------------ // Clamp mode changed // ------------------ var Err : Integer ; begin HardwareConf.ClampMode := cbClampMode.ItemIndex ; Err := VP500_SetHardwareConf( @HardwareConf ) ; UpdateClampModeLabels ; // Update holding V/I with last settings for new mode edHoldingVI.Value := HoldingVI[HardwareConf.ClampMode] ; SetHoldingVI ; end; procedure TVP500PanelFrm.UpdateClampModeLabels ; // ---------------------------------------------- // Update labels/controls when clamp mode changed // ---------------------------------------------- begin if (HardwareConf.ClampMode = 1) or (HardwareConf.ClampMode = 2) then begin cbClampSpeed.Visible := True ; HoldingVIGrp.Caption := ' Holding Current ' ; edHoldingVI.Units := 'pA' ; edHoldingVI.Scale := 1000.0 ; end else begin cbClampSpeed.Visible := False ; HoldingVIGrp.Caption := ' Holding Potential ' ; edHoldingVI.Units := 'mV' ; edHoldingVI.Scale := 1.0 ; end ; lbClampSpeed.Visible := cbClampSpeed.Visible ; end ; procedure TVP500PanelFrm.cbClampSpeedChange(Sender: TObject); // -------------------- // Clamp speeed changed // -------------------- begin HardwareConf.ClampSpeed := cbClampSpeed.ItemIndex ; VP500_CheckError( VP500_SetHardwareConf( @HardwareConf ), 'VP500_SetHardwareConf' ) ; end; procedure TVP500PanelFrm.cbAmplifierGainChange(Sender: TObject); // ------------------ // Clamp gain changed // ------------------ begin HardwareConf.AmplifierStageGain := cbAmplifierGain.ItemIndex ; VP500_CheckError( VP500_SetHardwareConf( @HardwareConf ), 'VP500_SetHardwareConf' ) ; end; procedure TVP500PanelFrm.cbLowHeadstageGainClick(Sender: TObject); // ----------------------- // Head stage gain changed // ----------------------- begin HardwareConf.HeadGainH := rbHeadStageGain.Checked ; VP500_CheckError( VP500_SetHardwareConf( @HardwareConf ), 'VP500_SetHardwareConf' ) ; end; procedure TVP500PanelFrm.cbLPFilterChange(Sender: TObject); // ----------------------- // Low pass filter changed // ----------------------- begin HardwareConf.AmplifierStageFilter := cbLPFilter.ItemIndex ; VP500_CheckError( VP500_SetHardwareConf( @HardwareConf ), 'VP500_SetHardwareConf' ) ; end; procedure TVP500PanelFrm.UpdateCompensations ; // -------------------------- // Update VP500 compensations // -------------------------- begin Compensations.PercentRs := Round(edPercentRs.Value) ; Compensations.TauPercentRs := cbTauPercentRs.ItemIndex ; Compensations.PercentBoost := Round(edPercentBoost.Value) ; VP500_CheckError( VP500_SetCompensations( @Compensations ), 'VP500_SetCompensations' ) ; end ; procedure TVP500PanelFrm.GetNeutralizationSettings ; // ---------------------------------- // Read VP500 neutralization settings // ---------------------------------- var Err : Integer ; begin Err := VP500_GetNeutralization( @Neutralization ) ; VP500_CheckError( Err, 'VP500_GetNeutralization' ) ; edCFast.Value := Neutralization.CFast ; edTauFast.Value := Neutralization.TauFast ; edCSlow.Value := Neutralization.CSlow ; edTauSlow.Value := Neutralization.TauSlow ; edCCell.Value := Neutralization.CCell ; edTauCell.Value := Neutralization.TauCell ; end ; procedure TVP500PanelFrm.UpdateNeutralization ; // ------------------------------------ // Update VP500 neutralization settings // ------------------------------------ var Err : Integer ; begin Neutralization.CFast := edCFast.Value ; Neutralization.TauFast := edTauFast.Value ; Neutralization.CSlow:= edCSlow.Value ; Neutralization.TauSlow := edTauSlow.Value ; Neutralization.CCell := edCCell.Value ; Neutralization.TauCell := edTauCell.Value ; Err := VP500_SetNeutralization( @Neutralization ) ; VP500_CheckError( Err, 'VP500_SetNeutralization' ) ; end ; procedure TVP500PanelFrm.bAppyCompensationClick(Sender: TObject); // ---------------------------------- // Update VP500 compensation settings // ---------------------------------- begin UpdateCompensations ; end; procedure TVP500PanelFrm.edPercentRsKeyPress(Sender: TObject; var Key: Char); // ------------------------------- // % R series compensation changed // ------------------------------- begin if Key = #13 then UpdateCompensations ; end; procedure TVP500PanelFrm.edPercentBoostKeyPress(Sender: TObject; var Key: Char); // ------------------------------------------ // % cell capacity boost compensation changed // ------------------------------------------ begin if Key = #13 then UpdateCompensations ; end; procedure TVP500PanelFrm.cbTauPercentRsChange(Sender: TObject); begin // ------------------------------- // % Tau R series compensation changed // ------------------------------- begin UpdateCompensations ; end; end; procedure TVP500PanelFrm.edCFastKeyPress(Sender: TObject; var Key: Char); // -------------------------------------- // Neutralization changed - manual update // -------------------------------------- begin if Key = #13 then UpdateNeutralization ; end; procedure TVP500PanelFrm.bCFastNeutraliseClick(Sender: TObject); // --------------------------- // Neutralise C(fast) capacity // --------------------------- begin bCFastNeutralise.Enabled := False ; // Neutralise fast capacity VP500_CheckError( VP500_CFastNeutralization, 'VP500_CFastNeutralization' ) ; // Read new settings GetNeutralizationSettings ; bCFastNeutralise.Enabled := True ; end; procedure TVP500PanelFrm.bCSlowNeutraliseClick(Sender: TObject); // --------------------------- // Neutralise C(slow) capacity // --------------------------- begin bCSlowNeutralise.Enabled := False ; // Neutralise slow capacity VP500_CheckError( VP500_CSlowNeutralization, 'VP500_CSlowNeutralization' ) ; // Read new settings GetNeutralizationSettings ; bCSlowNeutralise.Enabled := True ; end; procedure TVP500PanelFrm.bCCellNeutraliseClick(Sender: TObject); // --------------------------- // Neutralise C(cell) capacity // --------------------------- begin bCCellNeutralise.Enabled := False ; // Neutralise cell capacity VP500_CheckError(VP500_CCellNeutralization, 'VP500_CCellNeutralization' ) ; // Read new settings GetNeutralizationSettings ; // Cancel leak neutralisation (if not required) if not ckNeutraliseLeak.Checked then begin Neutralization.Leak := 0.0 ; UpdateNeutralization ; GetNeutralizationSettings ; end ; bCCellNeutralise.Enabled := True ; end; procedure TVP500PanelFrm.bApplyHoldingIVClick(Sender: TObject); // ----------------------------- // Apply holding voltage/current // ----------------------------- begin SetHoldingVI ; end; procedure TVP500PanelFrm.edHoldingVIKeyPress(Sender: TObject; var Key: Char); // ----------------------------- // Apply holding voltage/current // ----------------------------- begin if Key = #13 then SetHoldingVI ; end; procedure TVP500PanelFrm.SetHoldingVI ; // --------------------------- // Set holding voltage/current // --------------------------- var Err : Integer ; begin Err := VP500_SetVIHold( edHoldingVI.Value ) ; VP500_CheckError( Err, 'VP500_SetVIHold' ) ; HoldingVI[HardwareConf.ClampMode] := edHoldingVI.Value ; end ; procedure TVP500PanelFrm.bApplyJunctionClick(Sender: TObject); // ----------------------------------- // Apply junction potential correction // ----------------------------- ----- var Err : Integer ; begin Err := VP500_SetJunction(edJunctionPotential.Value ) ; VP500_CheckError( Err, 'VP500_SetJunction' ) ; end; procedure TVP500PanelFrm.edJunctionPotentialKeyPress(Sender: TObject; var Key: Char); // ----------------------------------- // Apply junction potential correction // ----------------------------- ----- begin if Key = #13 then begin VP500_CheckError( VP500_SetJunction(edJunctionPotential.Value ), 'VP500_SetJunction' ) ; end ; end; procedure TVP500PanelFrm.bCalcSealResistanceClick(Sender: TObject); // ------------------------- // Calculate seal resistance // ------------------------- var SealImpedance : TSealImpedance ; begin bCalcSealResistance.Enabled := False ; SealImpedance.Amplitude := 10.0 ; // 10 mV amplitude SealImpedance.Period := 500 ; // 10 ms period //SealImpedance.SamplingRate := 1 ; // 50 kHz sampling rate SealImpedance.DirectionUp := True ; VP500_CheckError( VP500_CalcSealImpedance( @SealImpedance ), 'VP500_CalcSealImpedance' ) ; edSealResistance.Value := SealImpedance.SealImpedance ; bCalcSealResistance.Enabled := True ; end; procedure TVP500PanelFrm.bCalcCellParametersClick(Sender: TObject); // ------------------------- // Calculate cell parameters // ------------------------- var CellParameters : TCellParameters ; begin bCalcCellParameters.Enabled := False ; VP500_CheckError( VP500_CellParameters( @CellParameters ), 'VP500_CellParameters' ) ; edRm.Value := CellParameters.Rm ; edRs.Value := CellParameters.Rs ; edCm.Value := CellParameters.Cm ; bCalcCellParameters.Enabled := True ; end; procedure TVP500PanelFrm.bInitialiseClick(Sender: TObject); // --------------------------------------------------- // Initialise compensation and neutralisation circuits // --------------------------------------------------- begin // Reset settings VP500_CheckError( VP500_Reinitialization, 'VP500_CellParameters' ) ; // Get new settings GetNeutralizationSettings ; end; procedure TVP500PanelFrm.bZapClick(Sender: TObject); // --------------------------------------- // Apply whole cell break-in voltage pulse // --------------------------------------- begin bZap.Enabled := False ; VP500_CheckError( VP500_DoZap( Round( edZapDuration.Value ) ), 'VP500_DoZap' ) ; bZap.Enabled := True ; end; procedure TVP500PanelFrm.FormClose(Sender: TObject; var Action: TCloseAction); // --------------------------- // Tidy up when form is closed // --------------------------- begin Action := caFree ; end; procedure TVP500PanelFrm.bOptimiseNeutralisationClick(Sender: TObject); // --------------------------------------------------- // Final optimisation of neutralisation circuits // --------------------------------------------------- begin bOptimiseNeutralisation.Enabled := False ; // Optimise settings VP500_CheckError( VP500_OptimizeNeutralization, 'VP500_OptimizeNeutralization' ) ; // Read new settings GetNeutralizationSettings ; // Cancel leak neutralisation (if not required) if not ckNeutraliseLeak.Checked then begin Neutralization.Leak := 0.0 ; UpdateNeutralization ; GetNeutralizationSettings ; end ; bOptimiseNeutralisation.Enabled := True ; end; procedure TVP500PanelFrm.TimerTimer(Sender: TObject); // ------------------- // Update VP500 status // ------------------- var VP500Status : TVP500Status ; s : String ; begin VP500_GetVP500Status( @VP500Status ) ; s := '' ; if VP500Status.IHeadOverload then s := s + 'IHead OVR ' ; if VP500Status.VMOverload then s := s + 'VM OVR ' ; if VP500Status.ADC1Overload then s := s + 'ADC1 OVR ' ; if VP500Status.ADC2Overload then s := s + 'ADC2 OVR ' ; edStatus.Text := s ; end ; procedure TVP500PanelFrm.FormActivate(Sender: TObject); begin Timer.Enabled := True ; end; procedure TVP500PanelFrm.FormDeactivate(Sender: TObject); begin Timer.Enabled := False ; end; procedure TVP500PanelFrm.spJunctionPotentialUpClick(Sender: TObject); // ------------------------------------------------ // Increase junction potential correction by 0.1 mV // ------------------------------------------------ begin edJunctionPotential.Value := edJunctionPotential.Value + 0.1 ; VP500_CheckError( VP500_SetJunction(edJunctionPotential.Value ), 'VP500_SetJunction' ) ; end; procedure TVP500PanelFrm.spJunctionPotentialDownClick(Sender: TObject); // ------------------------------------------------ // Increase junction potential correction by 0.1 mV // ------------------------------------------------ begin edJunctionPotential.Value := edJunctionPotential.Value - 0.1 ; VP500_CheckError( VP500_SetJunction(edJunctionPotential.Value ), 'VP500_SetJunction' ) ; end; end.
{******************************************************************************* 作者: dmzn@163.com 2013-3-7 描述: 实时监控 *******************************************************************************} unit UFrameRealTime; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, CPort, USysProtocol, dxStatusBar, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, ImgList, ExtCtrls, cxCheckListBox, cxLabel, Voltmeter, UFrameBase, cxGraphics; type TfFrameRealTimeMon = class(TfFrameBase) TimerStart: TTimer; ImageList1: TImageList; PanelLeft: TPanel; PanelRight: TPanel; ListDevice: TcxCheckListBox; cxLabel1: TcxLabel; LabelHint: TcxLabel; TimerUI: TTimer; VBreakPipe: TVoltmeter; VBreakPot: TVoltmeter; VTotalPipe: TVoltmeter; procedure TimerStartTimer(Sender: TObject); procedure TimerUITimer(Sender: TObject); procedure PanelLeftResize(Sender: TObject); protected { Protected declarations } FActiveItem: Integer; //active index FPanel: TdxStatusBarStateIndicatorPanelStyle; //status panel procedure OnShowFrame; override; procedure LoadSystemConfig; procedure LoadDeviceConfig; //load data procedure BuildDeviceList; procedure RefreshDeviceStatus; //ui data procedure OnData(const nData: PDeviceItem); //to write db public { Public declarations } class function FrameID: integer; override; end; implementation {$R *.dfm} uses UMgrControl, ULibFun, UDataModule, UMgrDBConn, UMgrConnection, UFormCtrl, USysLoger, USysConst, USysDB; procedure WriteLog(const nMsg: string); begin gSysLoger.AddLog(TfFrameRealTimeMon, '', nMsg); end; class function TfFrameRealTimeMon.FrameID: integer; begin Result := cFI_FrameRealTime; end; procedure TfFrameRealTimeMon.OnShowFrame; begin FPanel := TdxStatusBarStateIndicatorPanelStyle(gStatusBar.Panels[2].PanelStyle); FActiveItem := -1; TimerStart.Enabled := True; end; //Desc: 延时启动 procedure TfFrameRealTimeMon.TimerStartTimer(Sender: TObject); begin TimerStart.Enabled := False; ActionDBConfig(True); if CheckDBConnection then begin gDBConnManager.AddParam(gDBPram); //enable param LoadSystemConfig; LoadDeviceConfig; BuildDeviceList; end; end; //Desc: 调整表盘位置 procedure TfFrameRealTimeMon.PanelLeftResize(Sender: TObject); const cInterval = 20; var nL,nT,nInt: Integer; begin nInt := Trunc(PanelLeft.ClientWidth / 2); nT := VBreakPipe.Width + VBreakPot.Width + cInterval; nL := nInt - Trunc(nT / 2); VBreakPipe.Left := nL; VBreakPot.Left := nL + VBreakPipe.Width + cInterval; VTotalPipe.Left := nInt - Trunc(VTotalPipe.Width / 2); nInt := Trunc((PanelLeft.ClientHeight - LabelHint.Height) / 2); nL := VBreakPipe.Height + VTotalPipe.Height + cInterval; nT := LabelHint.Height + nInt - Trunc(nL / 2); VBreakPipe.Top := nT; VBreakPot.Top := nT; VTotalPipe.Top := nT + VBreakPipe.Height + cInterval; end; //Desc: 载入系统参数 procedure TfFrameRealTimeMon.LoadSystemConfig; var nStr: string; begin with gSysParam do begin FTrainID := 'id'; FPrintSend := False; FPrintRecv := False; FQInterval := 1000; FCollectTM := 20; FResetTime := 0; FUIInterval := 20; FUIMaxValue := 600; FReportPage := 3; FChartCount := 5000; FChartTime := 10; end; nStr := 'Select * From %s'; nStr := Format(nStr, [sTable_SysDict]); with FDM.QueryTemp(nStr), gSysParam do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('D_Name').AsString; if CompareText(sFlag_TrainID, nStr) = 0 then FTrainID := FieldByName('D_Value').AsString; //xxxxx if CompareText(sFlag_QInterval, nStr) = 0 then FQInterval := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_CollectTime, nStr) = 0 then FCollectTM := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_ResetTime, nStr) = 0 then FResetTime := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_PrintSend, nStr) = 0 then FPrintSend := FieldByName('D_Value').AsString = sFlag_Yes; //xxxxx if CompareText(sFlag_PrintRecv, nStr) = 0 then FPrintRecv := FieldByName('D_Value').AsString = sFlag_Yes; //xxxxx if CompareText(sFlag_UIInterval, nStr) = 0 then FUIInterval := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_UIMaxValue, nStr) = 0 then FUIMaxValue := FieldByName('D_Value').AsFloat; //xxxxx if CompareText(sFlag_ChartCount, nStr) = 0 then FChartCount := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_ChartTime, nStr) = 0 then FChartTime := FieldByName('D_Value').AsInteger; //xxxxx if CompareText(sFlag_ReportPage, nStr) = 0 then FReportPage := FieldByName('D_Value').AsInteger; //xxxxx Next; end; end; end; //Desc: 载入配置信息 procedure TfFrameRealTimeMon.LoadDeviceConfig; var nStr: string; nPort: TCOMParam; nDev: TDeviceItem; nCar: TCarriageItem; begin nStr := 'Select * From %s'; nStr := Format(nStr, [sTable_Port]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin FillChar(nPort, SizeOf(nPort), #0); First; while not Eof do with nPort do begin FItemID := FieldByName('C_ID').AsString; FName := FieldByName('C_Name').AsString; FPostion := FieldByName('C_Position').AsInteger; FPortName := FieldByName('C_Port').AsString; FBaudRate := StrToBaudRate(FieldByName('C_Baund').AsString); FDataBits := StrToDataBits(FieldByName('C_DataBits').AsString); FStopBits := StrToStopBits(FieldByName('C_StopBits').AsString); gDeviceManager.AddParam(nPort); Next; end; end; nStr := 'Select * From %s'; nStr := Format(nStr, [sTable_Device]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin FillChar(nDev, SizeOf(nDev), #0); First; while not Eof do with nDev do begin FItemID := FieldByName('D_ID').AsString; FCOMPort := FieldByName('D_Port').AsString; FIndex := FieldByName('D_Index').AsInteger; FSerial := FieldByName('D_Serial').AsString; FCarriageID := FieldByName('D_Carriage').AsString; FColorBreakPipe := FieldByName('D_clBreakPipe').AsInteger; FColorBreakPot := FieldByName('D_clBreakPot').AsInteger; FColorTotalPipe := FieldByName('D_clTotalPot').AsInteger; gDeviceManager.AddDevice(nDev); Next; end; end; nStr := 'Select * From %s'; nStr := Format(nStr, [sTable_Carriage]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin FillChar(nCar, SizeOf(nCar), #0); First; while not Eof do with nCar do begin FItemID := FieldByName('C_ID').AsString; FName := FieldByName('C_Name').AsString; FPostion := FieldByName('C_Position').AsInteger; FTypeID := FieldByName('C_TypeID').AsInteger; FTypeName := FieldByName('C_TypeName').AsString; FModeID := FieldByName('C_ModeID').AsInteger; FModeName := FieldByName('C_ModeName').AsString; gDeviceManager.AddCarriage(nCar); Next; end; end; gDeviceManager.AdjustDevice; //adjust all gPortManager.OnData := OnData; if gSysParam.FAutoMin then gPortManager.StartReader; //启动服务 end; //Desc: 构建设备列表 procedure TfFrameRealTimeMon.BuildDeviceList; var i,nIdx: Integer; nList: TList; nPort: PCOMItem; nDev: PDeviceItem; begin nList := gDeviceManager.LockPortList; try for i:=0 to nList.Count - 1 do begin nPort := nList[i]; //xxxxx for nIdx:=0 to nPort.FDevices.Count - 1 do begin nDev := nPort.FDevices[nIdx]; if not nDev.FDeviceUsed then Continue; with ListDevice.Items.Add do begin Text := nDev.FCarriage.FName; ImageIndex := 0; Tag := Integer(nDev); end; FPanel.Indicators.Add.IndicatorType := sitRed; //default status end; end; if ListDevice.Items.Count > 0 then begin ListDevice.ItemIndex := 0; TimerUI.Tag := ListDevice.Items[0].Tag; TimerUI.Enabled := True; VTotalPipe.MaxValue := gSysParam.FUIMaxValue; VTotalPipe.Visible := True; VBreakPipe.MaxValue := gSysParam.FUIMaxValue; VBreakPipe.Visible := True; VBreakPot.MaxValue := gSysParam.FUIMaxValue; VBreakPot.Visible := True; end; finally gDeviceManager.ReleaseLock; end; end; //Date: 2013-3-15 //Parm: 数据;个数 //Desc: 在nData中检索最大值 function GetMaxData(const nData: array of TDeviceData; const nNum: Word): Word; var nIdx: Integer; begin Result := 0; for nIdx:=0 to nNum - 1 do if nData[nIdx].FData > Result then begin Result := nData[nIdx].FData; end; end; //Desc: 刷新数据 procedure TfFrameRealTimeMon.TimerUITimer(Sender: TObject); var nDev: PDeviceItem; begin if ListDevice.ItemIndex <> FActiveItem then begin FActiveItem := ListDevice.ItemIndex; TimerUI.Tag := ListDevice.Items[FActiveItem].Tag; nDev := Pointer(TimerUI.Tag); LabelHint.Caption := '设备监测数据: ' + nDev.FCarriage.FName; end else nDev := Pointer(TimerUI.Tag); VTotalPipe.Value := nDev.FTotalPipe; VBreakPipe.Value := GetMaxData(nDev.FBreakPipe, nDev.FBreakPipeNum); VBreakPot.Value := GetMaxData(nDev.FBreakPot, nDev.FBreakPotNum); RefreshDeviceStatus; //update device status end; //Desc: 在状态栏构建设备状态指示 procedure TfFrameRealTimeMon.RefreshDeviceStatus; var nIdx: Integer; nList: TList; nPort: PCOMParam; nDev: PDeviceItem; begin for nIdx:=ListDevice.Count - 1 downto 0 do begin nDev := Pointer(ListDevice.Items[nIdx].Tag); if GetTickCount - nDev.FLastActive > 3 * gSysParam.FQInterval then begin if FPanel.Indicators[nIdx].IndicatorType <> sitRed then WriteLog(Format('设备[%s:%d]离线', [nDev.FCOMPort, nDev.FIndex])); //loged FPanel.Indicators[nIdx].IndicatorType := sitRed; ListDevice.Items[nIdx].ImageIndex := 0; end else begin FPanel.Indicators[nIdx].IndicatorType := sitGreen; ListDevice.Items[nIdx].ImageIndex := 1; end; end; nList := gDeviceManager.LockPortList; try for nIdx:=nList.Count - 1 downto 0 do begin nPort := PCOMItem(nList[nIdx]).FParam; if (nPort.FLastActive > 0) and (GetTickCount - nPort.FLastActive > 2 * gSysParam.FQInterval) then begin nPort.FLastActive := 0; WriteLog(nPort.FRunFlag); end; end; finally gDeviceManager.ReleaseLock; end; end; //Desc: 将nData写入数据库 procedure TfFrameRealTimeMon.OnData(const nData: PDeviceItem); var nStr: string; nIdx: Integer; nDate: TDateTime; nDBConn: PDBWorker; begin nDBConn := gDBConnManager.GetConnection(sProgID, nIdx); try if not Assigned(nDBConn) then begin gPortManager.WriteReaderLog('连接HM数据库失败(DBConn Is Null).'); Exit; end; if not nDBConn.FConn.Connected then nDBConn.FConn.Connected := True; //conn db nDate := nData.FBreakPipeTimeBase; //init time base for nIdx:=0 to nData.FBreakPipeNum - 1 do begin nStr := MakeSQLByStr([SF('P_Train', gSysParam.FTrainID), SF('P_Device', nData.FItemID), SF('P_Carriage', nData.FCarriageID), SF('P_Value', nData.FBreakPipe[nIdx].FData, sfVal), SF('P_Number', nData.FBreakPipe[nIdx].FNum, sfVal), SF('P_Date', nDate) ], sTable_BreakPipe, '', True); //xxxxx gDBConnManager.WorkerExec(nDBConn, nStr); TPortReadManager.IncTime(nDate, nData.FBreakPipe[nIdx].FNum); end; nDate := nData.FBreakPotTimeBase; //init time base for nIdx:=0 to nData.FBreakPotNum - 1 do begin nStr := MakeSQLByStr([SF('P_Train', gSysParam.FTrainID), SF('P_Device', nData.FItemID), SF('P_Carriage', nData.FCarriageID), SF('P_Value', nData.FBreakPot[nIdx].FData, sfVal), SF('P_Number', nData.FBreakPot[nIdx].FNum, sfVal), SF('P_Date', nDate) ], sTable_BreakPot, '', True); //xxxxx gDBConnManager.WorkerExec(nDBConn, nStr); TPortReadManager.IncTime(nDate, nData.FBreakPot[nIdx].FNum); end; nStr := MakeSQLByStr([SF('P_Train', gSysParam.FTrainID), SF('P_Device', nData.FItemID), SF('P_Carriage', nData.FCarriageID), SF('P_Value', nData.FTotalPipe, sfVal), SF('P_Date', nData.FTotalPipeTimeNow) ], sTable_TotalPipe, '', True); gDBConnManager.WorkerExec(nDBConn, nStr); finally gDBConnManager.ReleaseConnection(sProgID, nDBConn); end; end; initialization gControlManager.RegCtrl(TfFrameRealTimeMon, TfFrameRealTimeMon.FrameID); end.
unit uFormMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uGnSettings, StdCtrls, ExtCtrls, uGnGeneral; type TEnumSetting = (esFirst, esSecond, esThird); TMySettings = class(TGnSettings) strict private FStringSetting: string; FBooleanSetting: Boolean; FEnumSetting: TEnumSetting; public [TGnIni('DefaultString')] property StringSetting: string read FStringSetting write FStringSetting; [TGnIni('True')] property BooleanSetting: Boolean read FBooleanSetting write FBooleanSetting; [TGnIni('esSecond')] property EnumSetting: TEnumSetting read FEnumSetting write FEnumSetting; end; TFormMain = class(TForm) bSave: TButton; bLoad: TButton; bDefault: TButton; eStringSetting: TLabeledEdit; chbBooleanSetting: TCheckBox; cbEnumSetting: TComboBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure bDefaultClick(Sender: TObject); procedure bLoadClick(Sender: TObject); procedure bSaveClick(Sender: TObject); strict private FMySettings: TMySettings; procedure SettingsToForm; procedure FormToSettings; public end; var FormMain: TFormMain; implementation {$R *.dfm} procedure TFormMain.bDefaultClick(Sender: TObject); begin FMySettings.Default; SettingsToForm; end; procedure TFormMain.bLoadClick(Sender: TObject); begin FMySettings.Load; SettingsToForm; end; procedure TFormMain.bSaveClick(Sender: TObject); begin FormToSettings; FMySettings.Save; end; procedure TFormMain.FormCreate(Sender: TObject); begin FMySettings := TMySettings.Create(Application.ExePath + 'MySettings.ini'); SettingsToForm; end; procedure TFormMain.FormDestroy(Sender: TObject); begin FMySettings.Destroy; end; procedure TFormMain.FormToSettings; begin FMySettings.StringSetting := eStringSetting.Text; FMySettings.BooleanSetting := chbBooleanSetting.Checked; case cbEnumSetting.ItemIndex of 0: FMySettings.EnumSetting := esFirst; 1: FMySettings.EnumSetting := esSecond; 2: FMySettings.EnumSetting := esThird; end; end; procedure TFormMain.SettingsToForm; begin eStringSetting.Text := FMySettings.StringSetting; chbBooleanSetting.Checked := FMySettings.BooleanSetting; case FMySettings.EnumSetting of esFirst: cbEnumSetting.ItemIndex := 0; esSecond: cbEnumSetting.ItemIndex := 1; esThird: cbEnumSetting.ItemIndex := 2; end; end; end.
unit BatchProcessing; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Contnrs, SyncObjs, NiceExceptions; type { TBatchProcessing } TBatchProcessing = class public constructor Create; public type TItemProcedure = procedure(const aItem: pointer); private fQue: TQueue; fQueLock: TCriticalSection; fExecuteds: TQueue; fExecutedsLock: TCriticalSection; fReleaser: TItemProcedure; procedure Initialize; procedure ReleaseExecuteds; procedure Finalize; public property Que: TQueue read fQue; property QueLock: TCriticalSection read fQueLock; property Executeds: TQueue read fExecuteds; property ExecutedsLock: TCriticalSection read fExecutedsLock; property Releaser: TItemProcedure read fReleaser write fReleaser; procedure Add(const aItem: pointer); function Extract: pointer; procedure MarkExecuted(const aItem: pointer); destructor Destroy; override; end; implementation { TBatchProcessing } constructor TBatchProcessing.Create; begin inherited Create; Initialize; end; procedure TBatchProcessing.Initialize; begin fQue := TQueue.Create; fQueLock := TCriticalSection.Create; fExecuteds := TQueue.Create; fExecutedsLock := TCriticalSection.Create; fReleaser := nil; end; procedure TBatchProcessing.ReleaseExecuteds; var p: pointer; begin ExecutedsLock.Enter; while Executeds.Count > 0 do begin p := Executeds.Pop; if Releaser <> nil then Releaser(p); end; ExecutedsLock.Leave; end; procedure TBatchProcessing.Finalize; begin FreeAndNil(fQue); FreeAndNil(fQueLock); ReleaseExecuteds; FreeAndNil(fExecuteds); FreeAndNil(fExecutedsLock); end; procedure TBatchProcessing.Add(const aItem: pointer); begin QueLock.Enter; Que.Push(aItem); QueLock.Leave; end; function TBatchProcessing.Extract: pointer; begin QueLock.Enter; result := nil; if Que.Count > 0 then result := Que.Pop; QueLock.Leave; end; procedure TBatchProcessing.MarkExecuted(const aItem: pointer); begin ExecutedsLock.Enter; Executeds.Push(aItem); ExecutedsLock.Leave; end; destructor TBatchProcessing.Destroy; begin Finalize; inherited Destroy; end; end.
{ Double Commander ------------------------------------------------------------------------- Configuration of HotDir Copyright (C) 2009-2014 Alexander Koblov (alexx2000@mail.ru) 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 fHotDir; {$mode objfpc}{$H+} interface uses SysUtils, Classes, Controls, Forms, StdCtrls, Buttons, EditBtn, ExtCtrls, Menus, Dialogs, KASPathEdit, uHotDir, types; type TProcedureWhenClickingAMenuItem = procedure(Sender: TObject) of object; { TfrmHotDir } TfrmHotDir = class(TForm) btnTestMenu: TBitBtn; btnCancel: TBitBtn; btnGoToDir: TBitBtn; bynOk: TBitBtn; btnRelativePath: TSpeedButton; btnRelativeTarget: TSpeedButton; cbSortHotDirPath: TComboBox; cbSortHotDirTarget: TComboBox; lblDirectoryHotlist: TLabel; lbleditHotDirName: TLabeledEdit; lbleditHotDirPath: TLabeledEdit; lbleditHotDirTarget: TLabeledEdit; lsHotDir: TListBox; MenuItem2: TMenuItem; miAddTarget: TMenuItem; miAddCommand: TMenuItem; miAddCommand2: TMenuItem; miDetectIfPathTargetExist: TMenuItem; miAddCopyOfSelected2: TMenuItem; miDeleteSelectedEntry2: TMenuItem; miDetectIfPathExist: TMenuItem; miImport: TMenuItem; miExport: TMenuItem; miExportToTotalCommanderk: TMenuItem; miExportToTotalCommandernk: TMenuItem; miSeparator5: TMenuItem; miExportToDoubleCommanderk: TMenuItem; miExportToDoubleCommandernk: TMenuItem; miSeparator6: TMenuItem; miExportToHotlistFile: TMenuItem; miTestResultingMenu: TMenuItem; miTools: TMenuItem; miSeparator4: TMenuItem; miSeparator3: TMenuItem; miDeleteAllHotDirs: TMenuItem; miImportFromHotlistFile: TMenuItem; miImportTotalCommander: TMenuItem; miImportDoubleCommander: TMenuItem; mnuMainfHotDir: TMainMenu; MenuItem1: TMenuItem; miAdd: TMenuItem; miDelete: TMenuItem; miBrowseToDirectory: TMenuItem; miTypeTheDirectory: TMenuItem; miActiveFrameDirectory: TMenuItem; miActiveInactiveFrameDirectory: TMenuItem; miAddCopyOfSelected: TMenuItem; miSeparator1: TMenuItem; miAddSeparator: TMenuItem; miAddSubmenu: TMenuItem; miDeleteSelectedEntry: TMenuItem; miSeparator2: TMenuItem; miDeleteJustSubMenu: TMenuItem; miDeleteCompleteSubMenu: TMenuItem; miBrowseToDirectory2: TMenuItem; miTypeTheDirectory2: TMenuItem; miActiveFrameDirectory2: TMenuItem; miActiveInactiveFrameDirectory2: TMenuItem; MenuItem7: TMenuItem; miAddSeparator2: TMenuItem; miAddSubmenu2: TMenuItem; OpenDialog: TOpenDialog; pmHotDirTestMenu: TPopupMenu; pmAddHotDirMenu: TPopupMenu; SaveDialog: TSaveDialog; TimerDragMove: TTimer; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: char); function ActualAddDirectories(ParamDispatcher:TKindOfHotDirEntry; sName, sPath, sTarget:string; PositionOfInsertion:longint):longint; procedure FormShow(Sender: TObject); procedure lsHotDirDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure lsHotDirEnter(Sender: TObject); procedure lsHotDirExit(Sender: TObject); procedure lsHotDirClick(Sender: TObject); procedure lsHotDirKeyPress(Sender: TObject; var Key: char); procedure lsHotDirDblClick(Sender: TObject); procedure lsHotDirDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure lsHotDirDragDrop(Sender, Source: TObject; X, Y: Integer); procedure lsHotDirMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure lsHotDirSetNumberOfItemsPerColumnAndItemHeight; procedure btnGenericEnter(Sender: TObject); procedure btnGenericExit(Sender: TObject); procedure btnTestMenuClick(Sender: TObject); procedure cbSortHotDirPathChange(Sender: TObject); procedure cbSortHotDirTargetChange(Sender: TObject); procedure miAddTargetClick(Sender: TObject); procedure PopulatePopupMenuWithCommands(pmMenuToPopulate:TPopupMenu); procedure miDeleteAllHotDirsClick(Sender: TObject); procedure miDeleteSelectedEntryClick(Sender: TObject); procedure miAddHotDirClick(Sender: TObject); procedure miDetectIfPathExistClick(Sender: TObject); procedure miImportFromAnythingClick(Sender: TObject); procedure miShowWhereItWouldGo(Sender: TObject); procedure miSimplyCopyCaption(Sender: TObject); procedure anyRelativeAbsolutePathClick(Sender: TObject); procedure lbleditHotDirExit(Sender: TObject); procedure lbleditHotDirEnter(Sender: TObject); procedure lbleditHotDirKeyPress(Sender: TObject; var Key: char); procedure lbleditHotDirMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure TimerDragMoveTimer(Sender: TObject); private { Private declarations } pmPathHelper:TPopupMenu; pmCommandHelper:TPopupMenu; HotDirListTemp: THotDirList; lsHotDirNbOfItemsPerColumn:longint; lsHotDirItemHeight:longint; //It looks like with Free Pascal/Lazarus, once the listbox style is set to OwnerDraw, the itemheight is returned to be zero instead of appropriate heigt... So we'll backup it prior to set style to ownerdraw... FlagAlreadyScrolled:boolean; public { Public declarations } ActiveFramePath,NotActiveFramePath:string; procedure Refresh_lsHotDir(IndexToSelect:longint; FlagCenterSelection:boolean); procedure SubmitToAddOrConfigToHotDirDlg(paramActionDispatcher:longint; paramActiveFramePath,paramNotActiveFramePath:string); end; implementation {$R *.lfm} uses //Lazarus, Free-Pascal, etc. Graphics, LCLType, //DC DCClassesUtf8, DCStrUtils, uGlobs, uLng, uDCUtils, uDebug, uGlobsPaths, uSpecialDir, fhotdirimportexport, fmain, uFormCommands; const CENTER_SELECTION = TRUE; NOTOUCH_SELECTION = FALSE; var Last_lsHotDirItemHeight:longint = 12; { TfrmHotDir.FormCreate } procedure TfrmHotDir.FormCreate(Sender: TObject); begin // Initialize property storage InitPropStorage(Self); ActiveFramePath:=''; NotActiveFramePath:=''; pmPathHelper:=TPopupMenu.Create(Self); gSpecialDirList.PopulateMenuWithSpecialDir(pmPathHelper,mp_PATHHELPER,nil); pmCommandHelper:=TPopupMenu.Create(Self); PopulatePopupMenuWithCommands(pmCommandHelper); btnRelativePath.Hint:=rsMsgHotDirTipSpecialDirBut; btnRelativeTarget.Hint:=rsMsgHotDirTipSpecialDirBut; cbSortHotDirPath.Hint := rsMsgHotDirTipOrderPath; cbSortHotDirTarget.Hint := rsMsgHotDirTipOrderTarget; miAddTarget.Checked := gHotDirAddTargetOrNot; {$IFNDEF MSWINDOWS} miExportToTotalCommanderk.Free; miExportToTotalCommandernk.Free; miSeparator5.Free; miImportTotalCommander.Free; {$ENDIF} end; { TfrmHotDir.FormActivate } procedure TfrmHotDir.FormActivate(Sender: TObject); begin {$IFDEF MSWINDOWS} //If when show up for the first time the element selected is 0, it looks like there is a problem with drawing routine //somewhere because it does not higlight the first element. By selecting the second one and then the first one, it make //the highlight of the first to work. Hum... if ((lsHotDir.ItemIndex=0) and (lsHotDir.Items.Count>1)) then begin lsHotDir.ItemIndex:=1; lsHotDir.ItemIndex:=0; end; {$ENDIF} end; { TfrmHotDir.FormResize} procedure TfrmHotDir.FormResize(Sender: TObject); {$IFDEF MSWINDOWS} var NumberOfColumn:integer; {$ENDIF} begin {$IFDEF MSWINDOWS} NumberOfColumn:=lsHotDir.Width div 300; if NumberOfColumn<1 then NumberOfColumn:=1; lsHotDir.Columns:=NumberOfColumn; {$ENDIF} lsHotDirSetNumberOfItemsPerColumnAndItemHeight; end; { TfrmHotDir.FormCloseQuery } procedure TfrmHotDir.FormCloseQuery(Sender: TObject; var CanClose: boolean); var Answer:integer; begin if (modalResult<>mrOk) AND (modalResult<>mrAll) AND (HotDirListTemp.FlagModified) then begin if modalResult<>mrIgnore then //Don't bother user if he voluntary hit CANCEL. It's clear he doesn't want to save! begin Answer:=MessageDlg(rsMsgHotDirModifiedWantToSave,mtConfirmation,[mbYes,mbNo,mbCancel],0); CanClose:=((Answer=mrYes) OR (Answer=mrNo)); if Answer=mrYes then modalResult:=mrOk; end; end; end; { TfrmHotDir.FormClose } procedure TfrmHotDir.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if (modalResult=mrOk) or (modalResult=mrAll) then HotDirListTemp.CopyListToHotDirList(gHotDirList); pmPathHelper.Free; pmCommandHelper.Free; end; { TfrmHotDir.FormKeyPress } procedure TfrmHotDir.FormKeyPress(Sender: TObject; var Key: char); begin case ord(Key) of $1B: //Escape? Let's quit, simply begin if (not lbleditHotDirName.Focused) AND (not lbleditHotDirPath.Focused) AND (not lbleditHotDirTarget.Focused) then begin close; Key:=#$00; end; end; end; end; { TfrmHotDir.ActualAddDirectories } function TfrmHotDir.ActualAddDirectories(ParamDispatcher:TKindOfHotDirEntry; sName, sPath, sTarget:string; PositionOfInsertion:longint):longint; var LocalHotDir:THotDir; begin LocalHotDir:=THotDir.Create; LocalHotDir.Dispatcher:=ParamDispatcher; LocalHotDir.MenuLevel:=0; LocalHotDir.HotDirName:=sName; LocalHotDir.HotDirPath:=IncludeTrailingPathDelimiter(sPath); if sTarget<>'' then LocalHotDir.HotDirTarget:=IncludeTrailingPathDelimiter(sTarget); if (PositionOfInsertion>=0) AND (PositionOfInsertion<HotDirListTemp.Count) then begin if PositionOfInsertion>0 then begin case HotDirListTemp.HotDir[PositionOfInsertion-1].Dispatcher of hd_STARTMENU: LocalHotDir.MenuLevel:=HotDirListTemp.HotDir[PositionOfInsertion-1].MenuLevel+1; else LocalHotDir.MenuLevel:=HotDirListTemp.HotDir[PositionOfInsertion-1].MenuLevel; end; end; HotDirListTemp.Insert(PositionOfInsertion,LocalHotDir); HotDirListTemp.FlagModified:=TRUE; result:=PositionOfInsertion; end else begin HotDirListTemp.Add(LocalHotDir); HotDirListTemp.FlagModified:=TRUE; result:=pred(HotDirListTemp.Count); end; end; { TfrmHotDir.FormShow } procedure TfrmHotDir.FormShow(Sender: TObject); begin Refresh_lsHotDir(lsHotDir.ItemIndex,CENTER_SELECTION); end; { TfrmHotDir.lsHotDirDrawItem } procedure TfrmHotDir.lsHotDirDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); function GetSpacesRequire(NbSpace:longint):string; var i:integer; begin result:=''; for i:=1 to NbSpace do result:=result+' '; result:=result+result+result+result; end; begin with Control as TListBox do begin Last_lsHotDirItemHeight:=ARect.Bottom-ARect.Top; Canvas.FillRect(ARect); Canvas.ClipRect:=ARect; case HotDirListTemp.HotDir[Index].Dispatcher of hd_NULL: begin end; hd_CHANGEPATH: begin if not (odSelected in State) then begin case HotDirListTemp.HotDir[Index].HotDirExisting of DirExistUnknown: Canvas.Font.Color:=clDefault; DirExist: Canvas.Font.Color:=clGreen; DirNotExist: Canvas.Font.Color:=clRed; end; end; Canvas.Font.Style:=[]; Canvas.TextRect(ARect,ARect.Left+2,ARect.Top,GetSpacesRequire(HotDirListTemp.HotDir[Index].MenuLevel)+HotDirListTemp.HotDir[Index].HotDirName); end; hd_SEPARATOR: begin end; hd_STARTMENU: begin Canvas.Font.Style:=[fsBold]; Canvas.TextRect(ARect,ARect.Left+2,ARect.Top,GetSpacesRequire(HotDirListTemp.HotDir[Index].MenuLevel)+HotDirListTemp.HotDir[Index].HotDirName); end; hd_ENDMENU: begin Canvas.TextRect(ARect,ARect.Left+2,ARect.Top,GetSpacesRequire(HotDirListTemp.HotDir[Index].MenuLevel)+'--'); end; hd_COMMAND: begin Canvas.Font.Style:=[]; Canvas.TextRect(ARect,ARect.Left+2,ARect.Top,GetSpacesRequire(HotDirListTemp.HotDir[Index].MenuLevel)+HotDirListTemp.HotDir[Index].HotDirName); end; end; end; end; { TfrmHotDir.lsHotDirEnter } procedure TfrmHotDir.lsHotDirEnter(Sender: TObject); begin lblDirectoryHotlist.Font.Style:=[fsBold]; end; { TfrmHotDir. } procedure TfrmHotDir.lsHotDirExit(Sender: TObject); begin lblDirectoryHotlist.Font.Style:=[]; end; { TfrmHotDir.lsHotDirClick } procedure TfrmHotDir.lsHotDirClick(Sender: TObject); begin if lsHotDir.ItemIndex<>-1 then begin case HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher of hd_NULL: begin end; hd_CHANGEPATH: begin lbleditHotDirName.EditLabel.Caption:=rsMsgHotDirSimpleName; lbleditHotDirName.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirName; lbleditHotDirName.Enabled:=TRUE; lbleditHotDirPath.EditLabel.Caption:=rsMsgHotDirJustPath; lbleditHotDirPath.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath; lbleditHotDirPath.Hint:=mbExpandFileName(lbleditHotDirPath.Text); cbSortHotDirPath.ItemIndex:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPathSort; lbleditHotDirPath.Visible:=TRUE; btnRelativePath.Tag:=2; lbleditHotDirTarget.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTarget; lbleditHotDirTarget.Hint:=mbExpandFileName(lbleditHotDirTarget.Text); cbSortHotDirTarget.ItemIndex:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTargetSort; lbleditHotDirTarget.Visible:=TRUE; end; hd_COMMAND: begin lbleditHotDirName.EditLabel.Caption:=rsMsgHotDirSimpleName; lbleditHotDirName.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirName; lbleditHotDirName.Enabled:=TRUE; lbleditHotDirPath.EditLabel.Caption:=rsMsgHotDirSimpleCommand; lbleditHotDirPath.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath; lbleditHotDirPath.Hint:=''; lbleditHotDirPath.Visible:=TRUE; btnRelativePath.Tag:=4; lbleditHotDirTarget.Visible:=FALSE; end; hd_SEPARATOR: begin lbleditHotDirName.EditLabel.Caption:=''; lbleditHotDirName.Text:=rsMsgHotDirSimpleSeparator; lbleditHotDirName.Enabled:=FALSE; lbleditHotDirPath.Visible:=FALSE; lbleditHotDirTarget.Visible:=FALSE; end; hd_STARTMENU: begin lbleditHotDirName.EditLabel.Caption:=rsMsgHotDirSimpleMenu; lbleditHotDirName.Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirName; lbleditHotDirName.Enabled:=TRUE; lbleditHotDirPath.Visible:=FALSE; lbleditHotDirTarget.Visible:=FALSE; end; hd_ENDMENU: begin lbleditHotDirName.EditLabel.Caption:=''; lbleditHotDirName.Text:=rsMsgHotDirSimpleEndOfMenu; lbleditHotDirName.Enabled:=FALSE; lbleditHotDirPath.Visible:=FALSE; lbleditHotDirTarget.Visible:=FALSE; end; end; btnRelativePath.Visible:=lbleditHotDirPath.Visible; cbSortHotDirPath.Visible:=lbleditHotDirPath.Visible AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher<>hd_COMMAND); btnRelativeTarget.Visible:=lbleditHotDirTarget.Visible; cbSortHotDirTarget.Visible:=lbleditHotDirTarget.Visible; btnGoToDir.Enabled:=lbleditHotDirPath.Visible AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher<>hd_COMMAND); miDeleteJustSubMenu.Enabled:=(HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_STARTMENU); miDeleteCompleteSubMenu.Enabled:=(HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_STARTMENU); miAddCopyOfSelected.Enabled:=((HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher<>hd_STARTMENU) AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher<>hd_ENDMENU)); miAddCopyOfSelected2.Enabled:=miAddCopyOfSelected.Enabled; miDeleteSelectedEntry.Enabled:=(HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher<>hd_ENDMENU); miDeleteSelectedEntry2.Enabled:=miDeleteSelectedEntry.Enabled; end; end; { TfrmHotDir.lsHotDirKeyPress } procedure TfrmHotDir.lsHotDirKeyPress(Sender: TObject; var Key: char); begin case Key of #13: begin Key:=#0; if lbleditHotDirName.CanFocus then lbleditHotDirName.SetFocus; end; end; end; { TfrmHotDir.lsHotDirDblClick } procedure TfrmHotDir.lsHotDirDblClick(Sender: TObject); begin if lsHotDir.ItemIndex>-1 then begin if (HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath<>'-') AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath<>'--') then begin ModalResult:=mrAll; end; end; end; { TfrmHotDir.lsHotDirDragOver } procedure TfrmHotDir.lsHotDirDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); const MOVEABLEZONEAREA=25; var NbItemsPerColumn,TestNN:longint; begin if lsHotDir.Columns<2 then begin if Y<MOVEABLEZONEAREA then begin lsHotDir.TopIndex:=lsHotDir.TopIndex-1; //No need to valite if on top already, code is doing it for us! end else begin if (Y+MOVEABLEZONEAREA)>lsHotDir.Height then begin lsHotDir.TopIndex:=lsHotDir.TopIndex+1; //No need to valite if at bottom already, code is doing it for us! end else begin if (Source = lsHotDir) and (lsHotDir.ItemIndex<>-1) then begin Accept:=not(HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_ENDMENU); //We don't want "MenuEnd" to be moveable. end else begin Accept:=FALSE; end; end; end; end else begin //Since we have more than one columns, the scrollbar is horizontal, so we want user to drag item out of the list via the right side, not bottom like in 1 column. //After trying many various attempts in different ways, this is the closest way I fond workable. if (X+MOVEABLEZONEAREA)>lsHotDir.Width then begin if not FlagAlreadyScrolled then begin FlagAlreadyScrolled:=TRUE; lsHotDir.TopIndex:=(lsHotDir.TopIndex+lsHotDirNbOfItemsPerColumn); TimerDragMove.Enabled:=TRUE; end; end else begin if X < MOVEABLEZONEAREA then begin if not FlagAlreadyScrolled then begin FlagAlreadyScrolled:=TRUE; lsHotDir.TopIndex:=(lsHotDir.TopIndex-lsHotDirNbOfItemsPerColumn); TimerDragMove.Enabled:=TRUE; end; end else begin FlagAlreadyScrolled:=FALSE; if (Source = lsHotDir) and (lsHotDir.ItemIndex<>-1) then begin Accept:=not(HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_ENDMENU); //We don't want "MenuEnd" to be moveable. end else begin Accept:=FALSE; end; end; end; end; end; { TfrmHotDir.lsHotDirDragDrop } procedure TfrmHotDir.lsHotDirDragDrop(Sender, Source: TObject; X, Y: Integer); var CurIndex, NewIndex: Integer; begin CurIndex := lsHotDir.ItemIndex; if CurIndex = -1 then Exit; NewIndex := lsHotDir.ItemAtPos(Point(X,Y),TRUE); if (NewIndex < 0) or (NewIndex >= lsHotDir.Count) then NewIndex := lsHotDir.Count - 1; case HotDirListTemp.HotDir[CurIndex].Dispatcher of hd_STARTMENU: begin HotDirListTemp.MoveHotDirMenu(CurIndex, NewIndex); Refresh_lsHotDir(NewIndex,NOTOUCH_SELECTION); end; hd_CHANGEPATH, hd_SEPARATOR, hd_COMMAND: begin HotDirListTemp.Move(CurIndex, NewIndex); Refresh_lsHotDir(NewIndex,NOTOUCH_SELECTION); end; end; end; { TfrmHotDir.lsHotDirMouseDown } procedure TfrmHotDir.lsHotDirMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin {$IFDEF MSWINDOWS} lsHotDirClick(lsHotDir); //Might looks stupid an unnecessary but it is to avoid the fact that "OnClick" is not triggered in some circonstances. //Example? Suppose the focus is on element #n. Suppose we press the down arrow to select n+1, if with the mouse we then click on element #n, //the element is really selected BUT the event "OnClick" is not triggered (at least on Windows Vista) BUT OnMouseDown is triggered. {$ENDIF} end; { TfrmHotDir.lsHotDirSetNumberOfItemsPerColumnAndItemHeight } procedure TfrmHotDir.lsHotDirSetNumberOfItemsPerColumnAndItemHeight; var FirstItemOfColumn, LastItemOfColumn, SearchingY:longint; begin LastItemOfColumn:=-1; FirstItemOfColumn:=lsHotDir.ItemAtPos(Point(4,4),TRUE); if FirstItemOfColumn<>-1 then begin SearchingY:=lsHotDir.Height-1; repeat LastItemOfColumn:=lsHotDir.ItemAtPos(Point(1,SearchingY),TRUE); dec(SearchingY); until (LastItemOfColumn<>-1) AND (SearchingY>0); end; if (FirstItemOfColumn<>-1) AND (LastItemOfColumn<>-1) then begin lsHotDirNbOfItemsPerColumn:=((LastItemOfColumn-FirstItemOfColumn)+1); lsHotDirItemHeight:=(lsHotDir.Height div lsHotDirNbOfItemsPerColumn); end else begin //We hope to don't fall here but if we ever fall here, at least variable will have a value! lsHotDirNbOfItemsPerColumn:=10; lsHotDirItemHeight:=Last_lsHotDirItemHeight; end; end; { TfrmHotDir.btnGenericEnter } procedure TfrmHotDir.btnGenericEnter(Sender: TObject); begin with sender as TBitBtn do Font.Style:=[fsBold]; end; { TfrmHotDir.btnGenericExit } procedure TfrmHotDir.btnGenericExit(Sender: TObject); begin with sender as TBitBtn do Font.Style:=[]; end; { TfrmHotDir.btnTestMenuClick } procedure TfrmHotDir.btnTestMenuClick(Sender: TObject); var p:TPoint; begin HotDirListTemp.PopulateMenuWithHotDir(pmHotDirTestMenu,@miShowWhereItWouldGo,nil,'',mpJUSTHOTDIRS,0); p:=lsHotDir.ClientToScreen(Classes.Point(0,0)); pmHotDirTestMenu.PopUp(p.X,p.Y); end; { TfrmHotDir.cbSortHotDirPathChange } procedure TfrmHotDir.cbSortHotDirPathChange(Sender: TObject); begin HotDirListTemp.FlagModified:=TRUE; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPathSort:=cbSortHotDirPath.ItemIndex; end; { TfrmHotDir.cbSortHotDirTargetChange } procedure TfrmHotDir.cbSortHotDirTargetChange(Sender: TObject); begin HotDirListTemp.FlagModified:=TRUE; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTargetSort:=cbSortHotDirTarget.ItemIndex; end; procedure TfrmHotDir.miAddTargetClick(Sender: TObject); begin gHotDirAddTargetOrNot := miAddTarget.Checked; end; { TfrmHotDir.PopulatePopupMenuWithCommands } procedure TfrmHotDir.PopulatePopupMenuWithCommands(pmMenuToPopulate:TPopupMenu); var FFormCommands: IFormCommands; LocalDummyComboBox:TComboBox; miMainTree:TMenuItem; IndexCommand:longint; procedure LocalPopulateUntil(ParamMenuItem:TMenuItem; LetterUpTo:Char); var LocalMenuItem:TMenuItem; MaybeItemName:string; begin MaybeItemName:='0000'; while (IndexCommand<LocalDummyComboBox.Items.Count) AND (MaybeItemName[4]<>LetterUpTo) do begin MaybeItemName:=LocalDummyComboBox.Items.Strings[IndexCommand]; if MaybeItemName[4]<>LetterUpTo then begin LocalMenuItem:=TMenuItem.Create(ParamMenuItem); LocalMenuItem.Caption:=MaybeItemName; LocalMenuItem.OnClick:=@miSimplyCopyCaption; ParamMenuItem.Add(LocalMenuItem); inc(IndexCommand); end; end; end; begin LocalDummyComboBox:=TComboBox.Create(Self); try LocalDummyComboBox.Clear; FFormCommands := frmMain as IFormCommands; FFormCommands.GetCommandsList(LocalDummyComboBox.Items); LocalDummyComboBox.Sorted := True; IndexCommand:=0; miMainTree:=TMenuItem.Create(pmMenuToPopulate); miMainTree.Caption:='cm_A..cm_C'; pmMenuToPopulate.Items.Add(miMainTree); LocalPopulateUntil(miMainTree,'D'); miMainTree:=TMenuItem.Create(pmMenuToPopulate); miMainTree.Caption:='cm_D..cm_L'; pmMenuToPopulate.Items.Add(miMainTree); LocalPopulateUntil(miMainTree,'M'); miMainTree:=TMenuItem.Create(pmMenuToPopulate); miMainTree.Caption:='cm_M..cm_Z'; pmMenuToPopulate.Items.Add(miMainTree); LocalPopulateUntil(miMainTree,'A'); finally LocalDummyComboBox.Free; end; end; { TfrmHotDir.miDeleteAllHotDirsClick } procedure TfrmHotDir.miDeleteAllHotDirsClick(Sender: TObject); var Index:longint; begin if MessageDlg(rsMsgHotDirDeleteAllEntries, mtConfirmation, [mbYes,mbNo], 0)=mrYes then begin for Index:=pred(HotDirListTemp.Count) downto 0 do HotDirListTemp.DeleteHotDir(Index); Refresh_lsHotDir(lsHotDir.ItemIndex,NOTOUCH_SELECTION); lbleditHotDirName.Text:=''; lbleditHotDirPath.Text:=''; lbleditHotDirTarget.Text:=''; end; end; { TfrmHotDir.miDeleteSelectedEntryClick } procedure TfrmHotDir.miDeleteSelectedEntryClick(Sender: TObject); var DeleteDispatcher:integer; begin if (lsHotDir.ItemIndex=-1) then Exit; with Sender as TComponent do DeleteDispatcher:=tag; case HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher of hd_NULL, hd_CHANGEPATH, hd_SEPARATOR, hd_COMMAND: begin HotDirListTemp.DeleteHotDir(lsHotDir.ItemIndex); Refresh_lsHotDir(lsHotDir.ItemIndex,NOTOUCH_SELECTION); end; hd_STARTMENU: begin HotDirListTemp.DeleteHotDirMenuDelimiters(lsHotDir.ItemIndex,DeleteDispatcher); Refresh_lsHotDir(lsHotDir.ItemIndex,NOTOUCH_SELECTION); end; hd_ENDMENU: begin end; end; end; { TfrmHotDir.miAddHotDirClick } procedure TfrmHotDir.miAddHotDirClick(Sender: TObject); var sName, sPath, initialPath: String; Dispatcher,PositionOfInsertion:longint; FlagNeedRefresh:boolean; begin with Sender as TComponent do Dispatcher:=tag; PositionOfInsertion:=lsHotDir.ItemIndex+1; //It's a ADD, not an INSERT so we ADD a-f-t-e-r! If're on last item, don't worry, "ActualAddDirectories" will return correct point of insertion sName:=''; sPath:=''; FlagNeedRefresh:=FALSE; case Dispatcher of 1: //Directory I will browse to begin initialPath:=''; if (lsHotDir.ItemIndex<>-1) then begin if HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_CHANGEPATH then initialPath:=mbExpandFileName(HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath); end; if initialPath='' then initialPath:=ActiveFramePath; if SelectDirectory(rsSelectDir, initialPath, sPath, False) then begin PositionOfInsertion:=ActualAddDirectories(hd_CHANGEPATH,GetLastDir(sPath),sPath,'',PositionOfInsertion); FlagNeedRefresh:=TRUE; end; end; 2: //Directory I will type begin PositionOfInsertion:=ActualAddDirectories(hd_CHANGEPATH, rsMsgHotDirName, rsMsgHotDirPath, rsMsgHotDirTarget, PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 3: //Directory of the active frame begin PositionOfInsertion:=ActualAddDirectories(hd_CHANGEPATH,GetLastDir(ActiveFramePath),ActiveFramePath,'',PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 4: //Directory of the active AND inactive frames begin PositionOfInsertion:=ActualAddDirectories(hd_CHANGEPATH,GetLastDir(ActiveFramePath),ActiveFramePath,NotActiveFramePath,PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 5: begin PositionOfInsertion:=ActualAddDirectories(hd_SEPARATOR,'','','',PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 6: begin PositionOfInsertion:=ActualAddDirectories(hd_STARTMENU,rsMsgHotDirSubMenuName,'','',PositionOfInsertion); inc(PositionOfInsertion); PositionOfInsertion:=ActualAddDirectories(hd_ENDMENU,'','','',PositionOfInsertion); dec(PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 7: begin with HotDirListTemp.HotDir[lsHotDir.ItemIndex] as THotDir do PositionOfInsertion:=ActualAddDirectories(Dispatcher,HotDirName,HotDirPath,HotDirTarget,PositionOfInsertion); FlagNeedRefresh:=TRUE; end; 8: //A command begin PositionOfInsertion:=ActualAddDirectories(hd_COMMAND, rsMsgHotDirCommandName, rsMsgHotDirCommandSample, '', PositionOfInsertion); FlagNeedRefresh:=TRUE; end; end; if FlagNeedRefresh then begin Refresh_lsHotDir(PositionOfInsertion,NOTOUCH_SELECTION); if lbleditHotDirName.CanFocus then lbleditHotDirName.SetFocus; end; end; { TfrmHotDir.miDetectIfPathExistClick } procedure TfrmHotDir.miDetectIfPathExistClick(Sender: TObject); var RememberSelected:longint; begin RememberSelected:=lsHotDir.ItemIndex; try lbleditHotDirName.Text:=''; lbleditHotDirName.Enabled:=FALSE; lbleditHotDirPath.Visible:=FALSE; cbSortHotDirPath.Visible:=FALSE; cbSortHotDirTarget.Visible:=FALSE; lbleditHotDirTarget.Visible:=FALSE; btnRelativePath.Visible:=FALSE; btnRelativeTarget.Visible:=FALSE; Application.ProcessMessages; with Sender as TComponent do HotDirListTemp.RefreshExistingProperty(lsHotDir, lbleditHotDirName, tag); finally lsHotDir.ItemIndex:=RememberSelected; Refresh_lsHotDir(lsHotDir.ItemIndex,NOTOUCH_SELECTION); end; end; { TfrmHotDir.miImportFromAnythingClick } procedure TfrmHotDir.miImportFromAnythingClick(Sender: TObject); const ACTION_WITH_TOTALCOMMANDER = $00; ACTION_WITH_DOUBLECOMMANDER = $01; ACTION_WITH_SIMPLEFILE = $02; ACTION_IMPORT = $00; ACTION_EXPORT = $04; ACTION_ERASE_EXISTING = $10; var WorkingHotDirList:THotDirList; Answer, NbOfAdditional, ActionDispatcher:longint; FilenameToWorkWith:string; FlagKeepGoing:boolean; begin with Sender as TComponent do ActionDispatcher:=tag; case (ActionDispatcher AND $03) of ACTION_WITH_TOTALCOMMANDER: begin OpenDialog.DefaultExt:='*.ini'; OpenDialog.FilterIndex:=1; OpenDialog.Title:=rsMsgHotDirLocateTC; FlagKeepGoing:=OpenDialog.Execute; end; ACTION_WITH_DOUBLECOMMANDER: begin OpenDialog.DefaultExt:='*.xml'; OpenDialog.FilterIndex:=2; OpenDialog.Title:=rsMsgHotDirLocateDC; FlagKeepGoing:=OpenDialog.Execute; end; ACTION_WITH_SIMPLEFILE: begin case (ActionDispatcher AND $0C) of ACTION_IMPORT: begin OpenDialog.FilterIndex:=3; OpenDialog.Title:=rsMsgHotDirLocatePreviousSave; FlagKeepGoing:=OpenDialog.Execute; end; ACTION_EXPORT: begin SaveDialog.FilterIndex:=1; SaveDialog.FileName:='New directory hotlist'; SaveDialog.Title:=rsMsgHotDirWhereToSave; FlagKeepGoing:=SaveDialog.Execute; end; end; end; end; if FlagKeepGoing then begin WorkingHotDirList:=THotDirList.Create; try case (ActionDispatcher AND $03) of ACTION_WITH_TOTALCOMMANDER: WorkingHotDirList.ImportTotalCommander(utf8string(OpenDialog.Filename)); ACTION_WITH_DOUBLECOMMANDER: WorkingHotDirList.ImportDoubleCommander(utf8string(OpenDialog.Filename)); ACTION_WITH_SIMPLEFILE: if (ActionDispatcher AND $C0)=ACTION_IMPORT then WorkingHotDirList.ImportDoubleCommander(utf8string(OpenDialog.Filename)); end; with Tfrmhotdirimportexport.Create(Application) do begin try case (ActionDispatcher AND $0C) of ACTION_IMPORT: begin WorkingHotDirList.LoadToStringList(lsImportedHotDir.Items); lsImportedHotDir.OnDrawItem:=@WorkingHotDirList.lsHotDirDrawItem; lsImportedHotDir.OnClick:=@WorkingHotDirList.lsImportationHotDirClick; btnSelectAll.Caption:=rsMsgHotDirImportall; btnSelectionDone.Caption:=rsMsgHotDirImportSel; Caption:=rsMsgHotDirImportHotlist; end; ACTION_EXPORT: begin HotDirListTemp.CopyListToHotDirList(WorkingHotDirList); WorkingHotDirList.LoadToStringList(lsImportedHotDir.Items); lsImportedHotDir.OnDrawItem:=@WorkingHotDirList.lsHotDirDrawItem; lsImportedHotDir.OnClick:=@WorkingHotDirList.lsImportationHotDirClick; btnSelectAll.Caption:=rsMsgHotDirExportall; btnSelectionDone.Caption:=rsMsgHotDirExportSel; Caption:=rsMsgHotDirExportHotlist; end; end; Answer:=ShowModal; if Answer=mrAll then lsImportedHotDir.SelectAll; if ((Answer=mrOk) or (Answer=mrAll)) AND (lsImportedHotDir.SelCount>0) then begin case (ActionDispatcher AND $0C) of ACTION_IMPORT: begin NbOfAdditional:=HotDirListTemp.AddFromAnotherListTheSelected(WorkingHotDirList,lsImportedHotDir); if NbOfAdditional>0 then begin Refresh_lsHotDir(lsHotDir.ItemIndex,CENTER_SELECTION); miDeleteSelectedEntry.Enabled:= (lsHotDir.Items.Count > 0); MessageDlg(rsMsgHotDirNbNewEntries+IntToStr(NbOfAdditional),mtInformation,[mbOk],0); end; end; ACTION_EXPORT: begin WorkingHotDirList.EliminateTheNonSelectedInList(lsImportedHotDir); if WorkingHotDirList.Count>0 then begin case (ActionDispatcher AND $03) of ACTION_WITH_TOTALCOMMANDER: if WorkingHotDirList.ExportTotalCommander(OpenDialog.FileName,((ActionDispatcher AND $10)=$10)) then ShowMessage(rsMsgHotDirTotalExported+IntToStr(WorkingHotDirList.count)) else ShowMessage(rsMsgHotDirErrorExporting); ACTION_WITH_DOUBLECOMMANDER: if WorkingHotDirList.ExportDoubleCommander(OpenDialog.FileName,((ActionDispatcher AND $10)=$10)) then ShowMessage(rsMsgHotDirTotalExported+IntToStr(WorkingHotDirList.count)) else ShowMessage(rsMsgHotDirErrorExporting); ACTION_WITH_SIMPLEFILE: if WorkingHotDirList.ExportDoubleCommander(SaveDialog.FileName,TRUE) then ShowMessage(rsMsgHotDirTotalExported+IntToStr(WorkingHotDirList.count)) else ShowMessage(rsMsgHotDirErrorExporting); end; end else begin ShowMessage(rsMsgHotDirNothingToExport); end; end; //ACTION_EXPORT: end; //case (ActionDispatcher AND $0C) of end; //If user confirmed OK and have selected something... finally Free; end; end; finally WorkingHotDirList.Free; end; end; end; { TfrmHotDir.miShowWhereItWouldGo } procedure TfrmHotDir.miShowWhereItWouldGo(Sender: TObject); var StringToShow:string; begin with Sender as TComponent do begin lsHotDir.ItemIndex:=tag; lsHotDir.TopIndex:=tag-((lsHotDir.Height div lsHotDirItemHeight) div 2); StringToShow:=rsMsgHotDirDemoName+'"'+HotDirListTemp.HotDir[tag].HotDirName+'"'; case HotDirListTemp.HotDir[tag].Dispatcher of hd_CHANGEPATH: begin StringToShow:=StringToShow+#$0D+#$0A+#$0D+#$0A+rsMsgHotDirDemoPath; StringToShow:=StringToShow+#$0D+#$0A+mbExpandFileName(HotDirListTemp.HotDir[tag].HotDirPath); if HotDirListTemp.HotDir[tag].HotDirTarget<>'' then begin StringToShow:=StringToShow+#$0D+#$0A+#$0D+#$0A+rsMsgHotDirDemoTarget; StringToShow:=StringToShow+#$0D+#$0A+mbExpandFileName(HotDirListTemp.HotDir[tag].HotDirTarget); end; end; hd_COMMAND: begin StringToShow:=StringToShow+#$0D+#$0A+#$0D+#$0A+rsMsgHotDirDemoCommand; StringToShow:=StringToShow+#$0D+#$0A+mbExpandFileName(HotDirListTemp.HotDir[tag].HotDirPath); end; end; MessageDlg(StringToShow,mtInformation,[mbOk],0); end; end; { TfrmHotDir.miSimplyCopyCaption } procedure TfrmHotDir.miSimplyCopyCaption(Sender: TObject); begin with Sender as TMenuItem do begin if lbleditHotDirPath.text='' then lbleditHotDirPath.Text:=Caption else lbleditHotDirPath.text:=Caption+' '+lbleditHotDirPath.text; end; end; { TfrmHotDir.anyRelativeAbsolutePathClick } procedure TfrmHotDir.anyRelativeAbsolutePathClick(Sender: TObject); begin with Sender as TComponent do begin case tag of 2: begin lbleditHotDirPath.SetFocus; gSpecialDirList.SetSpecialDirRecipientAndItsType(lbleditHotDirPath,pfPATH); pmPathHelper.PopUp(Mouse.CursorPos.X, Mouse.CursorPos.Y); if HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath<>lbleditHotDirPath.Text then begin HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath:=lbleditHotDirPath.Text; HotDirListTemp.FlagModified:=TRUE; end; end; 4: begin lbleditHotDirPath.SetFocus; gSpecialDirList.SetSpecialDirRecipientAndItsType(lbleditHotDirPath,pfPATH); pmCommandHelper.PopUp(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; 3: begin lbleditHotDirTarget.SetFocus; gSpecialDirList.SetSpecialDirRecipientAndItsType(lbleditHotDirTarget,pfPATH); pmPathHelper.PopUp(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; end; end; { TfrmHotDir.lbleditHotDirExit } procedure TfrmHotDir.lbleditHotDirExit(Sender: TObject); var FlagWillNeedARefresh:boolean; begin FlagWillNeedARefresh:=FALSE; with sender as TLabeledEdit do begin pmPathHelper.Tag:=0; Font.Style:=[]; EditLabel.Font.Style:=[]; //Text not in bold anymore case tag of 1: //Hot dir name begin try if (Text<>'') AND (Text[1]<>'-') then //Make sure we actually have something, not an attempf of submenu or end of menu begin if HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirName<>Text then //Make sure it's different than what it was begin HotDirListTemp.FlagModified:=TRUE; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirName:=Text; FlagWillNeedARefresh:=TRUE; end; end; except //Just in case the "Text" is empty to don't show error with Text[1] check. end; end; 2: //Hot dir path begin if (Text<>'') AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_CHANGEPATH) then Text:=IncludeTrailingPathDelimiter(Text); if HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath<>Text then //Make sure it's different than what it was begin HotDirListTemp.FlagModified:=TRUE; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath:=Text; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirExisting:=DirExistUnknown; end; end; 3: //Hot dir target begin if (Text<>'') AND (HotDirListTemp.HotDir[lsHotDir.ItemIndex].Dispatcher=hd_CHANGEPATH) then Text:=IncludeTrailingPathDelimiter(Text); if HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTarget<>Text then //Make sure it's different than what it was begin HotDirListTemp.FlagModified:=TRUE; HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTarget:=Text; end; end; end; if FlagWillNeedARefresh then Refresh_lsHotDir(lsHotDir.ItemIndex,NOTOUCH_SELECTION); end; end; { TfrmHotDir.lbleditHotDirEnter } procedure TfrmHotDir.lbleditHotDirEnter(Sender: TObject); begin with sender as TLabeledEdit do begin pmPathHelper.Tag:=tag; Font.Style:=[fsBold]; EditLabel.Font.Style:=[fsBold]; end; end; { TfrmHotDir.lbleditHotDirKeyPress } procedure TfrmHotDir.lbleditHotDirKeyPress(Sender: TObject; var Key: char); begin case ord(Key) of $0D: //Enter? Let's save the field and go to next one begin Key:=#00; with Sender as TLabeledEdit do begin case tag of 1: //HotDirName begin if lbleditHotDirPath.CanFocus then lbleditHotDirPath.SetFocus else if lsHotDir.CanFocus then lsHotDir.SetFocus; end; 2: //HotDirPath begin if lbleditHotDirTarget.CanFocus then lbleditHotDirTarget.SetFocus else if lsHotDir.CanFocus then lsHotDir.SetFocus;; end; 3: //HotDirTarget begin if lsHotDir.CanFocus then lsHotDir.SetFocus else if lsHotDir.CanFocus then lsHotDir.SetFocus; end; end; end; end; $1B: //Escape? Place back the fields like they were begin Key:=#00; with Sender as TLabeledEdit do begin case tag of 1: lsHotDirClick(lsHotDir); 2: Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirPath; 3: Text:=HotDirListTemp.HotDir[lsHotDir.ItemIndex].HotDirTarget; end; end; lsHotDir.SetFocus; end; end; end; { TfrmHotDir.lbleditHotDirMouseDown } procedure TfrmHotDir.lbleditHotDirMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin with Sender as TComponent do pmPathHelper.Tag:=tag; end; { TfrmHotDir.TimerDragMoveTimer } procedure TfrmHotDir.TimerDragMoveTimer(Sender: TObject); begin TimerDragMove.Enabled:=FALSE; FlagAlreadyScrolled:=FALSE; end; { TfrmHotDir.Refresh_lsHotDir } procedure TfrmHotDir.Refresh_lsHotDir(IndexToSelect:longint; FlagCenterSelection:boolean); var RememberFirstInList,MaybeTopPosition:Integer; begin if lsHotDir.Count>0 then RememberFirstInList:=lsHotDir.TopIndex else RememberFirstInList:=-1; lsHotDir.Clear; HotDirListTemp.LoadToStringList(lsHotDir.Items); lsHotDirSetNumberOfItemsPerColumnAndItemHeight; if FlagCenterSelection=NOTOUCH_SELECTION then begin if (RememberFirstInList<>-1) AND (RememberFirstInList<lsHotDir.Count) then lsHotDir.TopIndex:=RememberFirstInList; end; if (IndexToSelect<>-1) then begin if IndexToSelect<HotDirListTemp.Count then lsHotDir.ItemIndex:=IndexToSelect else lsHotDir.ItemIndex:=pred(HotDirListTemp.Count); end else begin if lsHotDir.Items.Count > 0 then lsHotDir.ItemIndex:= 0; end; //To help user to see the current selection, we could be ask to try to center it visually in the displayed list. if FlagCenterSelection=CENTER_SELECTION then begin if lsHotDir.Columns<2 then begin MaybeTopPosition:=lsHotDir.ItemIndex-((lsHotDir.Height div lsHotDirItemHeight) div 2); end else begin //In multi-column list, we don't have a control resolution of "1" which item starts the visual list. //So let's try at least to try to have the slected item in the column closer the middle. MaybeTopPosition:=0; while (MaybeTopPosition+lsHotDirNbOfItemsPerColumn) < lsHotDir.ItemIndex do MaybeTopPosition:=(MaybeTopPosition+lsHotDirNbOfItemsPerColumn); MaybeTopPosition:=MaybeTopPosition-(((lsHotDir.Columns-1) div 2) * lsHotDirNbOfItemsPerColumn); end; if MaybeTopPosition<0 then MaybeTopPosition:=0; lsHotDir.TopIndex:=MaybeTopPosition; end; lsHotDirClick(lsHotDir); end; { TfrmHotDir.SubmitToAddOrConfigToHotDirDlg } procedure TfrmHotDir.SubmitToAddOrConfigToHotDirDlg(paramActionDispatcher:longint; paramActiveFramePath,paramNotActiveFramePath:string); var CloserIndex:longint; sTempo:string; begin paramActiveFramePath:=ExcludeTrailingPathDelimiter(paramActiveFramePath); paramNotActiveFramePath:=ExcludeTrailingPathDelimiter(paramNotActiveFramePath); ActiveFramePath:=paramActiveFramePath; NotActiveFramePath:=paramNotActiveFramePath; //2014-05-19:Following lines removed because sometimes the path is very long and it makes the popup menu too wide for no reason or for reason not often useful. //miAddActiveFramePath.Caption:='Set active frame path ('+paramActiveFramePath+')'; //miAddNotActiveFramePath.Caption:='Set not active frame path ('+paramNotActiveFramePath+')'; HotDirListTemp:=THotDirList.Create; gHotDirList.CopyListToHotDirList(HotDirListTemp); case paramActionDispatcher of ACTION_ADDTOHOTLIST: begin if miAddTarget.Checked then sTempo:=paramNotActiveFramePath else sTempo:=''; CloserIndex:=ActualAddDirectories(hd_CHANGEPATH,GetLastDir(paramActiveFramePath),paramActiveFramePath,sTempo,HotDirListTemp.TryToGetCloserHotDir(paramActiveFramePath,paramActionDispatcher)); lbleditHotDirName.TabOrder:=0; lbleditHotDirPath.TabOrder:=1; lbleditHotDirTarget.TabOrder:=2; lsHotDir.TabOrder:=3; end; ACTION_CONFIGTOHOTLIST: begin CloserIndex:=HotDirListTemp.TryToGetCloserHotDir(paramActiveFramePath,paramActionDispatcher); HotDirListTemp.FlagModified:=FALSE; lsHotDir.TabOrder:=0; lbleditHotDirName.TabOrder:=1; lbleditHotDirPath.TabOrder:=2; lbleditHotDirTarget.TabOrder:=3; end else begin CloserIndex:=0; end; end; Refresh_lsHotDir(CloserIndex,CENTER_SELECTION); end; end.
unit OrganizationPoster; interface uses PersistentObjects, DBGate, BaseObjects, DB; type // статус организации TOrganizationStatusDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; // организация TOrganizationDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Organization, Facade, SysUtils; { TOrganizationDataPoster } constructor TOrganizationDataPoster.Create; begin inherited; Options := []; DataSourceString := 'TBL_ORGANIZATION_DICT'; DataDeletionString := ''; DataPostString := ''; KeyFieldNames := 'ORGANIZATION_ID'; FieldNames := 'ORGANIZATION_ID, VCH_ORG_FULL_NAME'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_ORG_FULL_NAME'; end; function TOrganizationDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TOrganizationDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TOrganization; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TOrganization; o.ID := ds.FieldByName('ORGANIZATION_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_ORG_FULL_NAME').AsString); ds.Next; end; ds.First; end; end; function TOrganizationDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; { TOrganizationStatusDataPoster } constructor TOrganizationStatusDataPoster.Create; begin inherited; Options := []; DataSourceString := 'TBL_ORG_STATUS_DICT'; DataDeletionString := ''; DataPostString := ''; KeyFieldNames := 'ORG_STATUS_ID'; FieldNames := 'ORG_STATUS_ID, VCH_ORG_STATUS_NAME'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_ORG_STATUS_NAME'; end; function TOrganizationStatusDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TOrganizationStatusDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TOrganizationStatus; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TOrganizationStatus; o.ID := ds.FieldByName('ORG_STATUS_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_ORG_STATUS_NAME').AsString); ds.Next; end; ds.First; end; end; function TOrganizationStatusDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
{ --- START LICENSE BLOCK --- jcr6.pas JCR6 for Turbo Pascal version: 19.03.01 Copyright (C) 2019 Jeroen P. Broks 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. --- END LICENSE BLOCK --- } Unit jcr6; {$UNDEF DEBUGCHAT} interface uses TReadStr, Conv; type tJCREntry = record name:string; storage:string; { Non 'Store' items cannot be read, but if if not called they should crash stuff } size:Longint; offset:Longint; jxsrcca:Boolean; end; type tJCRFile = record stream:file; size,offset:longint; cbyte,lbyte,pbyte:byte; packpos:LongInt; jxsrcca:boolean; gbyte:boolean; closed:boolean; end; var showcomments:boolean; procedure JCR_OpenDir(var ret:file;filename:string); procedure JCR_Next(var ret:file; var success:boolean; var entry:tJCREntry); procedure JCR_CloseDir(var ret:file); procedure JCR_Open(var ret:tJCRfile;resource,entry:string); procedure JCR_Close(Var ret:tJCRfile); function JCR_Eof(var ret:tJCRfile):boolean; function JCR_GetChar(var ret:tJCRfile):char; function JCR_GetByte(var ret:tJCRfile):byte; function JCR_GetInteger(var ret:tJCRfile):integer; function JCR_GetLongInt(var ret:tJCRfile):LongInt; function JCR_GetPascalString(var ret:tJCRfile):string; implementation procedure dbg(a:string); begin {$IFDEF DEBUGCHAT} writeln('Debug>':10,' ',a) {$ENDIF} end; procedure J_CRASH(error:string); begin WriteLn('JCR Error'); WriteLn(error); halt(1); end; procedure JCR_OpenDir; var ecatch:integer; header:array[0..5] of Char; fatoffset:longint; fat_size,fat_csize:longint; fat_storage:string; begin { Open the file and throw and error if it doesn't exist} assign(ret,filename); {$I-} reset(ret,1); {$I+} ECatch:=IOResult; if ECatch=2 then J_Crash('File not found: '+filename); if ECatch>0 then J_Crash('Error opening file'); { Is this an actual JCR6 file? } blockread(ret,header,5); if not( (header[0]='J') and (header[1]='C') and (header[2]='R') and (header[3]='6') and (header[4]=#26) ) then begin close(ret); J_Crash(filename+': has not be recognized as a JCR6 resource file') end; { Let's get the FAT offset } blockread(ret,fatoffset,sizeof(fatoffset)); if fatoffset<=0 then begin close(ret); J_CRASH('Invalid offset') end; { Now there is room for some extra config but this simplistic version of JCR6 will ignore all that crap and go straight into business } seek(ret,fatoffset); blockread(ret,fat_size ,sizeof(longint)); blockread(ret,fat_csize,sizeof(longint)); TrickyReadString(ret,fat_storage); if fat_storage<>'Store' then begin close(ret); J_Crash('Resource is packed with the ' + fat_storage+ ' algorithm, and this JCR6 unit only supports non-compressed resources') end; if fat_size<>fat_csize then begin close(ret); J_Crash('Invalid FAT size data'); end; { From here we can begin to work, so this procedure comes at an end } end; procedure JCR_Next; var SuperMaintag:byte; CommandTag:string; Needless:string; (* Used to skip unsupported stuff *) NeedlessByte:Byte; EntryTag:Byte; EntryField:string; Entryint:longint; entrystring:string; entrybyte:byte; { used for boolean readouts which this unit will ignore } begin repeat blockread(ret,SuperMainTag,1); Case SuperMainTag of $ff: begin success:=false; Exit end; $01: begin TrickyReadString(ret,Commandtag); if CommandTag='COMMENT' then begin TrickyReadString(ret,Needless); if showcomments then writeln('Comment: '+Needless); TrickyReadString(ret,Needless); if showcomments then writeln(Needless) end else if CommandTag='REQUIRE' then begin close(ret); J_Crash('REQUIRE statement in JCR6. That feature is NOT supported') end else if CommandTag='IMPORT' then begin { Not supported, but this can be ingored } BlockRead(ret,needlessbyte,1); TrickyReadString(ret,needless); TrickyReadString(ret,needless) end else if commandTag='FILE' then repeat success:=true; blockread(ret,entrytag,1); case entrytag of $01,$02,$03: begin trickyreadstring(ret,EntryField); dbg('Field='+Entryfield+' ('+jbstr(entrytag)+')'); with entry do begin case entrytag of 1: begin trickyreadstring(ret,entrystring); if EntryField='__Entry' then name:=entrystring; if EntryField='__Storage' then storage:=entrystring end; 2: begin blockread(ret,entrybyte,1) end; 3: begin blockread(ret,entryint,sizeof(longint)); if EntryField='__Size' then size:=entryint; if EntryField='__Offset' then offset:=entryint; end; end; end; end; $ff: begin end {crash prevention} else begin close(ret); J_Crash('Entry tagging error'); end; end; until entrytag=$ff else begin close(ret); J_Crash('I don''t know what to do with command tag: '+commandtag) end end else begin close(ret); J_Crash('Unknown tag: '+jbstr(supermaintag)) end; end until success; end; procedure JCR_closedir; begin close(ret); end; procedure JCR_Open; var e:tJCREntry; s:Boolean; ignore:byte; begin with ret do begin packpos:=0; closed:=false; {assign(stream,resource); reset(stream,1);} JCR_OpenDir(stream,resource); repeat JCR_Next(stream,s,e); if not s then begin close(stream); J_Crash('Entry '+entry+' not found in '+resource) end; if jupper(e.name)=jupper(entry) then begin size := e.size; offset := e.offset; seek(stream,offset); e.jxsrcca := (e.storage='jxsrcca'); jxsrcca:=e.jxsrcca; if (e.storage<>'jxsrcca') and (e.storage<>'Store') then begin close(stream); J_Crash('Storage method '+e.storage+' not supported for entry '+entry+' in '+resource) end; exit end until false; if e.jxsrcca then blockread(stream,ignore,1) { First byte is always added by Go, but it's useless } end end; procedure JCR_Close; begin Close(ret.stream); ret.closed:=true; end; function JCR_Eof; var p:longint; begin with ret do begin if jxsrcca then JCR_Eof:=packpos+1>=size {Very important no ; !!! Pascal forbids a ; when 'else' commes immediately after} else begin p:=filepos(stream); JCR_Eof:=p>=offset+size end end end; function JCR_GetByte; var c:Byte; begin with ret do begin if closed then J_CRASH('Trying to read a closed JCR6 entry'); if jxsrcca then begin if (not gbyte) or (pbyte>=lbyte) then begin {$IFDEF DEBUGCHAT} Writeln('Position: ',packpos,' NEW'); {$ENDIF} if not gbyte then blockread(stream,c,1); {nul-ignore} gbyte:=true; pbyte:=1; blockread(stream,cbyte,1); blockread(stream,lbyte,1); {$IFDEF DEBUGCHAT} Writeln('- cbyte: ',cbyte,'; lbyte: ',lbyte); Readln; {$ENDIF} JCR_GetByte:=cbyte end else begin inc(pbyte); JCR_GetByte:=cbyte end; inc(packpos) end else begin blockread(stream,c,1); JCR_GetByte:=c; end end {width} end; function JCR_GetChar; var c:char; begin c := chr(JCR_GetByte(ret)); {blockread(ret.stream,c,1);} JCR_GetChar:=c end; function JCR_GetInteger; var c:Integer; ia:array[0..2] of byte; i:integer absolute ia; begin if ret.jxsrcca then begin ia[0]:=JCR_GetByte(ret); ia[1]:=JCR_GetByte(ret); JCR_GetInteger:=i; end else begin blockread(ret.stream,c,2); {sizeof(c));} JCR_GetInteger:=c end end; function JCR_GetLongInt; var c:LongInt; ia:array[0..4] of byte; i:LongInt absolute ia; k:byte; begin if ret.jxsrcca then begin for k:=0 to 3 do ia[k]:=JCR_GetByte(ret); JCR_GetLongInt:=i; end else begin blockread(ret.stream,c,2); {sizeof(c));} JCR_GetLongInt:=c end end; function JCR_GetPascalString; var c:string; i:integer; a:array[0..255] of byte; s:string absolute a; begin if ret.jxsrcca then begin for i:=0 to 255 do a[i]:=JCR_GetByte(ret); JCR_GetPascalString:=s end else begin blockread(ret.stream,c,sizeof(c)); JCR_GetPascalString:=c end end; begin showcomments:=false; end.
unit uSchedulerExecuter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uScheduler, uStrUtils, pingsend, synaip, blcksock, uLog, uNetwork, httpsend, uBatchExecute, uConst, uReportBuilder, uMail, uAlarm; type TEventResult = record er_name: string; er_datetime: tdatetime; er_result: boolean; end; TThreadSchedulerExecuter = class(TThread) private { Private declarations } trExecuteEventArr: uScheduler.TSchedulerEventArr; trLogMsg: string; trBatchData: uBatchExecute.TBatchArray; trBatchName: string; trAlarmTemplateName: string; trBatchRes: uBatchExecute.TBatch; trAlarmTemplateRes: uAlarm.TAlarmTemplate; trSudoPwd: string; trEventName: string; trEventResult: boolean; trEventDT: tdatetime; trCurrThreadEvent: uScheduler.TSchedulerEvent; trarrAddAlarmForIA:array of TDateTime; // var for report generating trReportFilePath: string; trReport_dt_begin, trReport_dt_end: TDateTime; trReport_params: string; procedure trBuildReport; // ========================= procedure trWriteEventResult; procedure SyncWriteEventResult(event:TSchedulerEvent; event_result: boolean; event_dt: tdatetime); procedure ExecuterUpdate; procedure FindBatchByName; procedure FindAlarmTemplateByName; procedure AddAlarmForIA; procedure DoExecution(Res: boolean; trEvent:uScheduler.TSchedulerEvent); procedure DoAlarm(Res: boolean; trEvent:uScheduler.TSchedulerEvent); //procedure toLog; procedure trWriteLog(msg_str: string); //procedure toReportMSG; procedure trWriteReportMSG(msg_str: string); //procedure toReportData; procedure trWriteReportData(msg_str: string); function trCheckLastResult(ConstName: string; curr_res:boolean; max_count: integer): boolean; function trIsResultChanged(ConstName: string; curr_res:boolean; max_count: integer): boolean; procedure trSetNewResult(ConstName:string; curr_res:boolean); protected { Protected declarations } procedure Execute; override; end; const ev_report_prefix = 'ev_rprt_'; ev_execution_prefix = 'ev_exec_'; ev_alarm_prefix = 'ev_alrm_'; implementation { TThreadSchedulerExecuter } uses uMain; procedure TThreadSchedulerExecuter.trBuildReport; var bs: blcksock.TTCPBlockSocket; begin trReportFilePath := uReportBuilder.BuildReport(trReport_dt_begin, trReport_dt_end, trReport_params, False, bs); end; procedure TThreadSchedulerExecuter.Execute; var SR: TSocketResult; r:integer; r_str:string; tbs: blcksock.TBlockSocket; tps: pingsend.TPINGSend; event_inc_x: integer; trEvent: uScheduler.TSchedulerEvent; event_str, event_alarm_str, event_main_param: string; event_class, event_class2, event_class3: string; tmp_param1, tmp_param2, tmp_param3: string; x: integer; tmp_bool1: boolean; tmp_int1: integer; tmp_str1, tmp_str2: string; tmp_date1, tmp_date2: tdatetime; event_report_type, event_alarm_type: string; event_stat_type, event_stat_name: string; result_max_count: integer; HTTP: httpsend.THTTPSend; tmp_string_list: TStringList; OperationResult: boolean; found:boolean; begin SetLength(trExecuteEventArr, 0); while True do begin if Terminated then begin exit; end; //Synchronize(@ExecuterUpdate); ExecuterUpdate; for event_inc_x := 1 to length(trExecuteEventArr) do begin trEvent := trExecuteEventArr[event_inc_x - 1]; trCurrThreadEvent:=trEvent; event_str := trEvent.event_str; event_main_param := trEvent.event_main_param; event_alarm_str := trEvent.event_alarm_str; event_class := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 1); // 1 - network skanning // ====================================================================== if event_class = '1' then begin event_class2 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 2); // (1°1) get all ip's in network if event_class2 = '1' then begin tmp_param3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 3); // ping timeout tps := pingsend.TPINGSend.Create; tps.Timeout := StrToInt(tmp_param3); trWriteReportMSG('9 Begin network scan execution log: [' + trEvent.event_name + ']'); tmp_int1 := 0; for x := 1 to 255 do begin tmp_param2 := trim(event_main_param) + '.' + IntToStr(x); // ip to check tmp_bool1 := False; // ping if tps.Ping(tmp_param2) then begin tmp_bool1 := True; end; if tmp_bool1 then begin tmp_int1 := tmp_int1 + 1; trWriteReportMSG('9 - Online IP: ' + tmp_param2); end; end; trWriteReportMSG('9 > 255 checked, ' + IntToStr(tmp_int1) + ' online'); trWriteReportMSG('9 End network scan execution log: [' + trEvent.event_name + ']'); end; end; // =========================================================== // 2 - execute any process // ============================================================ if event_class = '2' then begin tmp_param3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 2); trBatchName := trim(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 3)); //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; if tmp_param3 = '1' then begin trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; end; end; end; // ================================================================= // 3 - report // ================================================================== if event_class = '3' then begin event_class2 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 2); if event_class2 = '1' then // report begin event_class3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 3); if event_class3 = '1' then // e-mail begin tmp_date2 := now; tmp_str1 := ReadConst('LastReportSendingEMailDate'); if tmp_str1 = '' then begin tmp_date1 := tmp_date2 - 7; end else begin tmp_date1 := strtofloat(tmp_str1); end; tmp_str2 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 4); //tmp_str1 := uReportBuilder.BuildReport( // tmp_date1, tmp_date2, tmp_str2, False, bs); trReport_dt_begin := tmp_date1; trReport_dt_end := tmp_date2; trReport_params := tmp_str2; //Synchronize(@trBuildReport); trBuildReport; tmp_str1 := trReportFilePath; if (tmp_str1 = '') or (not FileExists(tmp_str1)) then begin trWriteLog('Error creating report file!'); end else begin // sending file tmp_str2 := uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 3); if uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 4) <> '' then begin tmp_str2 := tmp_str2 + ':' + uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 4); end; tmp_int1 := uMail.SendMailAttachment(uStrUtils.GetFieldFromString( event_main_param, ParamLimiter, 1), // send from email uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 2), // send to email uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 7), // subject tmp_str2, // smtp host[:port] uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 5), // login uStrUtils.GetFieldFromString(event_main_param, ParamLimiter, 6), // password tmp_str1 // file path ); if tmp_int1 = 1 then begin // seems to be OK, must save last report generating datetime uConst.WriteConst('LastReportSendingEMailDate', floattostr(tmp_date2)); end else begin trWriteLog('Error sending report file! Check e-mail settings, please.'); end; try DeleteFile(tmp_str1); except end; end; end; end; end; // ================================================================== // 4 - on-demand monitoring // ================================================================== if event_class = '4' then begin event_class2 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 2); // (4°1) external (passive) if event_class2 = '1' then begin event_class3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 3); // (4°1°1) ping ---------------------------- if event_class3 = '1' then begin OperationResult := False; event_report_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 4); event_alarm_type := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 1); event_stat_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 6); event_stat_name := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 7); // 1 - direct log, 2 - stat. collect. tmp_param1 := event_main_param; // ip or network name tmp_param2 := tmp_param1; if not synaip.IsIP(tmp_param1) then begin tbs := blcksock.TBlockSocket.Create; tmp_param1 := tbs.ResolveName(tmp_param1); end; if (not synaip.IsIP(tmp_param1)) or (tmp_param1 = '0.0.0.0') then begin // (4°1°1) ping NEGATIVE - wrong IP // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG('0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if event_report_type = '1/4' then // first n errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG('0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // stat begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' name not resolved: ' + tmp_param2); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); Continue; end; tmp_int1 := pingsend.PingHost(tmp_param2); if tmp_int1 = -1 then // no answer begin // (4°1°1) ping NEGATIVE - no answer // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']: ping timeout'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']: ping timeout'); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']: ping timeout'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' host [' + tmp_param2 + ']: ping timeout'); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); end else begin // (4°1°1) ping POSITIVE OperationResult := True; // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']; ping ' + IntToStr(tmp_int1) + 'ms'); end; if event_report_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']; ping ' + IntToStr(tmp_int1) + 'ms'); end; end; if event_report_type = '1/5' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + ']; ping ' + IntToStr(tmp_int1) + 'ms'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,true); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('1 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' host [' + tmp_param2 + ']: ping success'); end; // execution DoExecution(true,trEvent); // alarm DoAlarm(true,trEvent); end; SyncWriteEventResult(trEvent, OperationResult, now); end; // ----------------------------------------------------------- // (4°1°2) is port opened ------------------------------------ if event_class3 = '2' then begin OperationResult := False; event_report_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 4); event_alarm_type := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 1); event_stat_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 6); event_stat_name := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 7); // 1 - direct log, 2 - stat. collect. tmp_param1 := event_main_param; // ip or network name tmp_param3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 8); // port tmp_param2 := tmp_param1; if not synaip.IsIP(tmp_param1) then begin tbs := blcksock.TBlockSocket.Create; tmp_param1 := tbs.ResolveName(tmp_param1); end; if (not synaip.IsIP(tmp_param1)) or (tmp_param1 = '0.0.0.0') then begin // (4°1°2) is port opened NEGATIVE - wrong IP // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' name not resolved: ' + tmp_param2); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); Continue; end; tmp_int1 := uNetwork.CheckPortOpened(tmp_param1, tmp_param3); if tmp_int1 <> 1 then // no answer begin // (4°1°2) is port opened NEGATIVE - no answer // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: closed'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: closed'); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: closed'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' host [' + tmp_param2 + '], port [' + tmp_param3 + ']: closed'); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); end else begin // (4°1°2) is port opened POSITIVE OperationResult := True; // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: open'); end; if event_report_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: open'); end; end; if event_report_type = '1/5' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; host [' + tmp_param2 + '], port [' + tmp_param3 + ']: open'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,true); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('1 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' host [' + tmp_param2 + '], port [' + tmp_param3 + ']: open'); end; // execution DoExecution(true,trEvent); // alarm DoAlarm(true,trEvent); end; SyncWriteEventResult(trEvent, OperationResult, now); end; // --------------------------------------------- // (4°1°5) http get any file ------------------- if event_class3 = '5' then begin OperationResult := False; event_report_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 4); // 1 - direct log, 2 - stat. collect. event_alarm_type := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 1); event_stat_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 6); event_stat_name := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 7); tmp_param1 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 8); // valid header HTTP := httpsend.THTTPSend.Create; tmp_bool1 := False; try if HTTP.HTTPMethod('GET', event_main_param) then begin if UPPERCASE(HTTP.Headers[0]) = UPPERCASE(tmp_param1) then begin tmp_bool1 := True; end; end; except end; try http.Free; except end; if not tmp_bool1 then // (4°1°5) http get any file NEGATIVE begin // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] not available'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] not available'); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] not available'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' page [' + event_main_param + '] not available'); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); end else begin // (4°1°5) http get any file POSITIVE OperationResult := True; // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] available'); end; if event_report_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] available'); end; end; if event_report_type = '1/5' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; page [' + event_main_param + '] available'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,true); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('1 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' page [' + event_main_param + '] available'); end; // execution DoExecution(true,trEvent); // alarm DoAlarm(true,trEvent); end; SyncWriteEventResult(trEvent, OperationResult, now); end; // (4°1°8) check IMS server ------------------- if event_class3 = '8' then begin OperationResult := False; event_report_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 4); event_alarm_type := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 1); event_stat_type := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 6); event_stat_name := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 7); // 1 - direct log, 2 - stat. collect. tmp_param1 := event_main_param; // ip or network name tmp_param3 := uStrUtils.GetFieldFromString(event_str, ParamLimiter, 8); // port tmp_param2 := tmp_param1; if not synaip.IsIP(tmp_param1) then begin tbs := blcksock.TBlockSocket.Create; tmp_param1 := tbs.ResolveName(tmp_param1); end; if (not synaip.IsIP(tmp_param1)) or (tmp_param1 = '0.0.0.0') then begin // (4°1°8) is port opened NEGATIVE - wrong IP // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; network name [' + tmp_param2 + '] not resolved!'); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' name not resolved: ' + tmp_param2); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); Continue; end; // IMS server check tmp_str2:=''; tmp_bool1:=false; SR:=uNetwork.PrepereSocketToConnect(tmp_param1, strtoint(tmp_param3)); if SR.res<>1 then begin tmp_str2:='Connection to IMS server at host '+tmp_param1+' port '+tmp_param3+' failed!'; tmp_bool1:=false; SR.S.Free; end else begin // test app version (must be identical) r:=SendStringViaSocket(SR.S,'app_ver'+GetAppVer(),5000); if r<>1 then begin tmp_str2:='Check version of IMS server failed!'; tmp_bool1:=false; SR.S.CloseSocket; SR.S.Free; end else begin r_str:=GetStringViaSocket(SR.S,5000); if r_str<>'APP VERSION VALID' then begin tmp_str2:='Main and reserve server version must be identical!'; tmp_bool1:=false; SR.S.CloseSocket; SR.S.Free; end else begin tmp_str2:='IMS server v.'+GetAppVer()+' is running on host '+tmp_param1+' port '+tmp_param3; tmp_bool1:=true; SendStringViaSocket(SR.S,'log_out',5000); end; end; end; if not tmp_bool1 then // NEGATIVE begin // (4°1°8) is port opened NEGATIVE - no answer // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; if event_report_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; end; if event_report_type = '1/4' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, false, result_max_count)) then begin trWriteReportMSG( '0 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,false); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('0 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' ' +tmp_str2); end; // execution DoExecution(false,trEvent); // alarm DoAlarm(false,trEvent); end else begin // (4°1°8) is port opened POSITIVE OperationResult := True; // report found:=false; if event_report_type = '1/1' then // full log begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; if event_report_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trCheckLastResult(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; end; if event_report_type = '1/5' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_str, ParamLimiter, 5)); if (trIsResultChanged(ev_report_prefix + trEvent.event_name, true, result_max_count)) then begin trWriteReportMSG( '1 Event: [' + trEvent.event_name + ']; '+tmp_str2); end; end; if not found then begin trSetNewResult(ev_report_prefix + trEvent.event_name,true); end; if event_stat_type = '1' then // statistic begin if event_stat_name = '' then begin tmp_str1 := trEvent.event_name; end else begin tmp_str1 := event_stat_name; end; trWriteReportData('1 ' + IntToStr(length(tmp_str1)) + ' ' + tmp_str1 + ' '+tmp_str2); end; // execution DoExecution(true,trEvent); // alarm DoAlarm(true,trEvent); end; SyncWriteEventResult(trEvent, OperationResult, now); end; // ----------------------------------------------------- end; end; // -------------------------------------------------------------- // ============================================================== end; setlength(trExecuteEventArr, 0); sleep(1000); end; end; procedure TThreadSchedulerExecuter.ExecuterUpdate; var x: integer; pNeedUpdate:boolean; begin cs1.Enter; trSudoPwd := uMain.sSudoPwd; cs1.Leave; cs6.Enter; pNeedUpdate:=uMain.NeedExecuterUpdate; cs6.Leave; if pNeedUpdate then // need execution update begin cs5.Enter; for x := 1 to length(uMain.arrExecuteEventArr) do begin setlength(trExecuteEventArr, length(trExecuteEventArr) + 1); trExecuteEventArr[length(trExecuteEventArr) - 1] := uMain.arrExecuteEventArr[x - 1]; end; setlength(uMain.arrExecuteEventArr, 0); cs5.Leave; cs6.Enter; uMain.NeedExecuterUpdate:=false; cs6.Leave; end; end; procedure TThreadSchedulerExecuter.FindBatchByName; begin cs9.Enter; trBatchRes := uBatchExecute.FindBatch(umain.arrBatchData, trBatchName); cs9.Leave; end; procedure TThreadSchedulerExecuter.FindAlarmTemplateByName; begin cs10.Enter; trAlarmTemplateRes := uAlarm.FindAlarm(umain.arrAlarmTemplates, trAlarmTemplateName); cs10.Leave; end; //procedure TThreadSchedulerExecuter.toLog; //begin // uLog.WriteLogMsg(trLogMsg); //end; procedure TThreadSchedulerExecuter.trWriteLog(msg_str: string); begin //trLogMsg := msg_str; //Synchronize(@toLog); uLog.WriteLogMsg(msg_str); end; //procedure TThreadSchedulerExecuter.toReportMSG; //begin // uLog.WriteReportMsg(trLogMsg); //end; procedure TThreadSchedulerExecuter.trWriteReportMSG(msg_str: string); begin //trLogMsg := msg_str; //Synchronize(@toReportMSG); uLog.WriteReportMsg(msg_str); end; //procedure TThreadSchedulerExecuter.toReportData; //begin // uLog.WriteReportData(trLogMsg); //end; procedure TThreadSchedulerExecuter.trWriteReportData(msg_str: string); begin //trLogMsg := msg_str; //Synchronize(@toReportData); uLog.WriteReportData(msg_str); end; function TThreadSchedulerExecuter.trCheckLastResult(ConstName: string; curr_res:boolean; max_count: integer): boolean; var last_str: string; last_res_cnt: integer; last_res: boolean; begin if max_count = 1 then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '1'); end else begin WriteConst(ConstName, '0'+ uMain.ParamLimiter + '1'); end; Result := True; exit; end; // if max_count>1 last_str := ReadConst(ConstName); if last_str = '' then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '1'); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + '1'); end; Result := False; exit; end; if uStrUtils.GetFieldFromString(last_str, ParamLimiter, 1)='1' then begin last_res :=true; end else begin last_res :=false; end; last_res_cnt := StrToInt(uStrUtils.GetFieldFromString(last_str, ParamLimiter, 2)); if last_res <> curr_res then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '1'); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + '1'); end; Result := False; exit; end; if last_res_cnt + 1 >= max_count then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '0'); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + '0'); end; Result := True; exit; end else begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + IntToStr(last_res_cnt + 1)); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + IntToStr(last_res_cnt + 1)); end; Result := False; exit; end; end; function TThreadSchedulerExecuter.trIsResultChanged(ConstName: string; curr_res:boolean; max_count: integer): boolean; var last_str: string; last_res_cnt: integer; last_res:boolean; begin {if max_count = 1 then begin WriteConst(ConstName, curr_res + uMain.ParamLimiter + '1'); Result := True; exit; end;} last_str := ReadConst(ConstName); if last_str = '' then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '1'); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + '1'); end; if max_count=1 then begin Result := true; end else begin Result := false; end; exit; end; if uStrUtils.GetFieldFromString(last_str, ParamLimiter, 1)='1' then begin last_res := true; end else begin last_res := false; end; last_res_cnt := StrToInt(uStrUtils.GetFieldFromString(last_str, ParamLimiter, 2)); // if result changed if last_res <> curr_res then begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + '1'); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + '1'); end; if max_count=1 then begin Result := true; end else begin Result := false; end; exit; end; // if result not changed if ((last_res_cnt + 1) = max_count) then begin Result := True; end else begin Result := False; end; if last_res_cnt>=999999 then begin last_res_cnt:=999998; end; if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + IntToStr(last_res_cnt + 1)); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + IntToStr(last_res_cnt + 1)); end; end; procedure TThreadSchedulerExecuter.trSetNewResult(ConstName:string; curr_res:boolean); begin if curr_res then begin WriteConst(ConstName, '1' + uMain.ParamLimiter + IntToStr(1)); end else begin WriteConst(ConstName, '0' + uMain.ParamLimiter + IntToStr(1)); end; end; procedure TThreadSchedulerExecuter.SyncWriteEventResult(event:TSchedulerEvent; event_result: boolean; event_dt: tdatetime); begin if uStrUtils.GetFieldFromString(event.event_alarm_str, ParamLimiter, 1)='1' then begin trEventName := event.event_name; trEventResult := event_result; trEventDT := event_dt; //Synchronize(@trWriteEventResult); trWriteEventResult; end; end; procedure TThreadSchedulerExecuter.trWriteEventResult; var x, l: integer; found: boolean; begin cs8.Enter; l := Length(uMain.arrEventResultArray); found := False; for x := 1 to l do begin if uMain.arrEventResultArray[x - 1].er_name = trEventName then begin found := True; uMain.arrEventResultArray[x - 1].er_result := trEventResult; uMain.arrEventResultArray[x - 1].er_datetime := trEventDT; Break; end; end; if not found then begin setlength(uMain.arrEventResultArray, l + 1); uMain.arrEventResultArray[l].er_name := trEventName; uMain.arrEventResultArray[l].er_result := trEventResult; uMain.arrEventResultArray[l].er_datetime := trEventDT; end; cs8.Leave; end; procedure TThreadSchedulerExecuter.DoExecution(Res: boolean; trEvent:uScheduler.TSchedulerEvent); var result_max_count:integer; event_execution_str,event_execution_type:string; tmp_string_list: TStringList; x:integer; found:boolean; begin event_execution_str:= trEvent.event_execution_str; event_execution_type := uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 1); trBatchName := trim(uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 3)); if event_execution_type = '1/1' then // always begin //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: batch [' + trBatchName + '] allowed to execution!'); tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; trSetNewResult(ev_execution_prefix + trEvent.event_name, Res); end; exit; end; if not res then begin found:=False; if event_execution_type = '1/2' then // errors only begin found:=True; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 2)); trBatchName := uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 3); if (trCheckLastResult(ev_execution_prefix + trEvent.event_name, false, result_max_count)) then begin //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: batch [' + trBatchName + '] allowed to execution!'); tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; end; end; end; if event_execution_type = '1/4' then // errors only begin found:=True; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 2)); trBatchName := uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 3); if (trIsResultChanged(ev_execution_prefix + trEvent.event_name, false, result_max_count)) then begin //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: batch [' + trBatchName + '] allowed to execution!'); tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; end; end; end; if not found then begin trSetNewResult(ev_execution_prefix + trEvent.event_name, Res); end; end else begin found:=False; if event_execution_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 2)); trBatchName := uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 3); if (trCheckLastResult(ev_execution_prefix + trEvent.event_name, true, result_max_count)) then begin //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: batch [' + trBatchName + '] allowed to execution!'); tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; end; end; end; if event_execution_type = '1/5' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 2)); trBatchName := uStrUtils.GetFieldFromString(event_execution_str, ParamLimiter, 3); if (trIsResultChanged(ev_execution_prefix + trEvent.event_name, true, result_max_count)) then begin //Synchronize(@FindBatchByName); FindBatchByName; if trBatchRes.batch_name = '' then begin trWriteLog('Internal error! Batch not found: ' + trBatchName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: batch [' + trBatchName + '] allowed to execution!'); tmp_string_list := uBatchExecute.ExecuteBatch(trBatchRes, trSudoPwd); for x := 1 to tmp_string_list.Count do begin if tmp_string_list[x - 1] = 'err' then begin trWriteLog('Internal error! Batch ' + trBatchName + ' decoding error!'); Break; end; trWriteReportMSG('4 ' + tmp_string_list[x - 1]); end; end; end; end; if not found then begin trSetNewResult(ev_execution_prefix + trEvent.event_name, Res); end; end; end; procedure TThreadSchedulerExecuter.DoAlarm(Res: boolean; trEvent:uScheduler.TSchedulerEvent); var result_max_count:integer; event_alarm_str,event_alarm_type:string; //tmp_string_list: TStringList; tmp_alarm_exec_res:TExecuteAlarmTemplateResult; x:integer; found:boolean; begin event_alarm_str:= trEvent.event_alarm_str; event_alarm_type := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 2); trAlarmTemplateName := trim(uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 4)); if event_alarm_type = '1/1' then // always begin //Synchronize(@FindAlarmTemplateByName); FindAlarmTemplateByName; if trAlarmTemplateRes.alarm_template_name = '' then begin trWriteLog('Internal error! Alarm template not found: ' + trAlarmTemplateName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: alarm template [' + trAlarmTemplateName + '] allowed to execution!'); tmp_alarm_exec_res := uAlarm.ExecuteAlarmTemplate(trAlarmTemplateRes,trEvent.event_name,trSudoPwd); setlength(trarrAddAlarmForIA,Length(tmp_alarm_exec_res.arrAddAlarmForIA)); for x := 1 to length(tmp_alarm_exec_res.arrAddAlarmForIA) do begin trarrAddAlarmForIA[x-1]:=tmp_alarm_exec_res.arrAddAlarmForIA[x-1]; end; //Synchronize(@AddAlarmForIA); AddAlarmForIA; for x := 1 to tmp_alarm_exec_res.arrRes.Count do begin if tmp_alarm_exec_res.arrRes[x - 1] = 'err' then begin trWriteLog('Internal error! Alarm template ' + trAlarmTemplateName + ' decoding error!'); Break; end; trWriteReportMSG('5 ' + tmp_alarm_exec_res.arrRes[x - 1]); end; trSetNewResult(ev_alarm_prefix + trEvent.event_name, Res); end; exit; end; if not res then begin found:=false; if event_alarm_type = '1/2' then // errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 3)); trAlarmTemplateName := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 4); if (trCheckLastResult(ev_alarm_prefix + trEvent.event_name, false, result_max_count)) then begin //Synchronize(@FindAlarmTemplateByName); FindAlarmTemplateByName; if trAlarmTemplateRes.alarm_template_name = '' then begin trWriteLog('Internal error! Alarm template not found: ' + trAlarmTemplateName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: alarm template [' + trAlarmTemplateName + '] allowed to execution!'); tmp_alarm_exec_res := uAlarm.ExecuteAlarmTemplate(trAlarmTemplateRes,trEvent.event_name, trSudoPwd); setlength(trarrAddAlarmForIA,Length(tmp_alarm_exec_res.arrAddAlarmForIA)); for x := 1 to length(tmp_alarm_exec_res.arrAddAlarmForIA) do begin trarrAddAlarmForIA[x-1]:=tmp_alarm_exec_res.arrAddAlarmForIA[x-1]; end; //Synchronize(@AddAlarmForIA); AddAlarmForIA; for x := 1 to tmp_alarm_exec_res.arrRes.Count do begin if tmp_alarm_exec_res.arrRes[x - 1] = 'err' then begin trWriteLog('Internal error! Alarm template ' + trAlarmTemplateName + ' decoding error!'); Break; end; trWriteReportMSG('5 ' + tmp_alarm_exec_res.arrRes[x - 1]); end; end; end; end; if event_alarm_type = '1/4' then // first errors only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 3)); trAlarmTemplateName := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 4); if (trIsResultChanged(ev_alarm_prefix + trEvent.event_name, false, result_max_count)) then begin //Synchronize(@FindAlarmTemplateByName); FindAlarmTemplateByName; if trAlarmTemplateRes.alarm_template_name = '' then begin trWriteLog('Internal error! Alarm template not found: ' + trAlarmTemplateName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: alarm template [' + trAlarmTemplateName + '] allowed to execution!'); tmp_alarm_exec_res := uAlarm.ExecuteAlarmTemplate(trAlarmTemplateRes,trEvent.event_name, trSudoPwd); setlength(trarrAddAlarmForIA,Length(tmp_alarm_exec_res.arrAddAlarmForIA)); for x := 1 to length(tmp_alarm_exec_res.arrAddAlarmForIA) do begin trarrAddAlarmForIA[x-1]:=tmp_alarm_exec_res.arrAddAlarmForIA[x-1]; end; //Synchronize(@AddAlarmForIA); AddAlarmForIA; for x := 1 to tmp_alarm_exec_res.arrRes.Count do begin if tmp_alarm_exec_res.arrRes[x - 1] = 'err' then begin trWriteLog('Internal error! Alarm template ' + trAlarmTemplateName + ' decoding error!'); Break; end; trWriteReportMSG('5 ' + tmp_alarm_exec_res.arrRes[x - 1]); end; end; end; end; if not found then begin trSetNewResult(ev_alarm_prefix + trEvent.event_name, Res); end; end else begin found:=false; if event_alarm_type = '1/3' then // positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 3)); trAlarmTemplateName := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 4); if (trCheckLastResult(ev_alarm_prefix + trEvent.event_name, true, result_max_count)) then begin //Synchronize(@FindAlarmTemplateByName); FindAlarmTemplateByName; if trAlarmTemplateRes.alarm_template_name = '' then begin trWriteLog('Internal error! Alarm template not found: ' + trAlarmTemplateName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: alarm template [' + trAlarmTemplateName + '] allowed to execution!'); tmp_alarm_exec_res := uAlarm.ExecuteAlarmTemplate(trAlarmTemplateRes,trEvent.event_name, trSudoPwd); setlength(trarrAddAlarmForIA,Length(tmp_alarm_exec_res.arrAddAlarmForIA)); for x := 1 to length(tmp_alarm_exec_res.arrAddAlarmForIA) do begin trarrAddAlarmForIA[x-1]:=tmp_alarm_exec_res.arrAddAlarmForIA[x-1]; end; //Synchronize(@AddAlarmForIA); AddAlarmForIA; for x := 1 to tmp_alarm_exec_res.arrRes.Count do begin if tmp_alarm_exec_res.arrRes[x - 1] = 'err' then begin trWriteLog('Internal error! Alarm template ' + trAlarmTemplateName + ' decoding error!'); Break; end; trWriteReportMSG('5 ' + tmp_alarm_exec_res.arrRes[x - 1]); end; end; end; end; if event_alarm_type = '1/5' then // first positive only begin found:=true; result_max_count := StrToInt(uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 3)); trAlarmTemplateName := uStrUtils.GetFieldFromString(event_alarm_str, ParamLimiter, 4); if (trIsResultChanged(ev_alarm_prefix + trEvent.event_name, true, result_max_count)) then begin //Synchronize(@FindAlarmTemplateByName); FindAlarmTemplateByName; if trAlarmTemplateRes.alarm_template_name = '' then begin trWriteLog('Internal error! Alarm template not found: ' + trAlarmTemplateName); end else begin trWriteReportMSG('9 Event [' + trEvent.event_name + ']: alarm template [' + trAlarmTemplateName + '] allowed to execution!'); tmp_alarm_exec_res := uAlarm.ExecuteAlarmTemplate(trAlarmTemplateRes,trEvent.event_name, trSudoPwd); setlength(trarrAddAlarmForIA,Length(tmp_alarm_exec_res.arrAddAlarmForIA)); for x := 1 to length(tmp_alarm_exec_res.arrAddAlarmForIA) do begin trarrAddAlarmForIA[x-1]:=tmp_alarm_exec_res.arrAddAlarmForIA[x-1]; end; //Synchronize(@AddAlarmForIA); AddAlarmForIA; for x := 1 to tmp_alarm_exec_res.arrRes.Count do begin if tmp_alarm_exec_res.arrRes[x - 1] = 'err' then begin trWriteLog('Internal error! Alarm template ' + trAlarmTemplateName + ' decoding error!'); Break; end; trWriteReportMSG('5 ' + tmp_alarm_exec_res.arrRes[x - 1]); end; end; end; end; if not found then begin trSetNewResult(ev_alarm_prefix + trEvent.event_name, Res); end; end; end; procedure TThreadSchedulerExecuter.AddAlarmForIA; var x:integer; arr_tmp: array of TAlarmForIA; begin cs16.Enter; // clear old records in arrAlarmForIA setlength(arr_tmp,Length(arrAlarmForIA)); for x:=1 to Length(arrAlarmForIA) do begin arr_tmp[x-1]:=arrAlarmForIA[x-1]; end; setlength(arrAlarmForIA,0); for x:=1 to Length(arr_tmp) do begin if (arr_tmp[x-1].alarm_dt<tdatetime(now-1)) then begin Continue; end; setlength(arrAlarmForIA,Length(arrAlarmForIA)+1); arrAlarmForIA[Length(arrAlarmForIA)-1]:=arr_tmp[x-1]; end; // copy new records to arrAlarmForIA for x:=1 to Length(trarrAddAlarmForIA) do begin setlength(arrAlarmForIA,length(arrAlarmForIA)+1); arrAlarmForIA[length(arrAlarmForIA)-1].alarm_dt:=trarrAddAlarmForIA[x-1]; arrAlarmForIA[length(arrAlarmForIA)-1].alarm_name:=trCurrThreadEvent.event_name; end; cs16.Leave; end; end.
unit Unit15; interface uses Windows, SysUtils, Controls, Forms, Fonctions, StdCtrls, StrUtils, HTTPGet, ExtCtrls, Classes, ComCtrls, ImgList, Inifiles, Gauges; type TForm15 = class(TForm) Button1 : TButton; StatusBar1 : TStatusBar; Label1 : TLabel; Label2 : TLabel; Label3 : TLabel; Label4 : TLabel; Label5 : TLabel; Panel1 : TPanel; Label6 : TLabel; Label7 : TLabel; Label8 : TLabel; Label9 : TLabel; Label10 : TLabel; HTTPGet1 : THTTPGet; ImageList1 : TImageList; Image1 : TImage; Image2 : TImage; Image3 : TImage; Image4 : TImage; Image5 : TImage; ProgressBar1 : TProgressBar; procedure Button1Click(Sender : TObject); procedure HTTPGet1DoneString(Sender : TObject; Result : string); procedure HTTPGet1Error(Sender : TObject); procedure HTTPGet1DoneFile(Sender : TObject; FileName : string; FileSize : Integer); procedure HTTPGet1Progress(Sender : TObject; TotalSize, Readed : Integer); procedure FormCreate(Sender : TObject); private { Déclarations privées } public DL_Fini, erreur : boolean; NewVersion : string; procedure Reset; end; var Form15 : TForm15; implementation uses Unit1; {$R *.dfm} function NewVersionAvailable(new : string; current : string) : boolean; var p1, p2 : TStringList; begin if (new <> current) then begin p1 := TStringList.Create; p2 := TStringList.Create; try p1.Delimiter := '.'; p2.Delimiter := '.'; p1.DelimitedText := new; p2.DelimitedText := current; if StrToInt(p2[0]) > StrToInt(p1[0]) then result := false else if StrToInt(p2[1]) > StrToInt(p1[1]) then result := false else if StrToInt(p2[2]) > StrToInt(p1[2]) then result := false else if StrToInt(p2[3]) > StrToInt(p1[3]) then result := false; except p1.Free; p2.Free; end; end else result:=false; end; procedure TForm15.Reset; begin ImageList1.GetBitmap(1, Image1.Picture.Bitmap); ImageList1.GetBitmap(1, Image2.Picture.Bitmap); ImageList1.GetBitmap(1, Image3.Picture.Bitmap); ImageList1.GetBitmap(1, Image4.Picture.Bitmap); ImageList1.GetBitmap(1, Image5.Picture.Bitmap); Label1.Caption := '...'; Label2.Caption := '...'; Label3.Caption := '...'; Label4.Caption := '...'; Label5.Caption := '...'; StatusBar1.Panels[0].Text := ''; ProgressBar1.Position := 0; end; procedure TForm15.Button1Click(Sender : TObject); begin Button1.Enabled := false; if FileExists(IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'Update\All4Cod.exe') then begin MessageBoxA(Handle, Pchar(form1.GetText('31') + #13 + Form1.GetText('32')), Pchar('All4Cod - ' + Form1.GetText('MSG')), 0 + MB_ICONINFORMATION + 0); exit; end; Label1.Caption := Form1.GetText('66'); Application.ProcessMessages; if DetectionConnexion then begin ImageList1.GetBitmap(0, Image1.Picture.Bitmap); Image1.Repaint; Label1.Caption := Form1.GetText('67'); Application.ProcessMessages; end else begin MessageBoxA(Handle, Pchar(Form1.GetText('33')), Pchar('All4Cod - ' + Form1.GetText('ERROR')), 0 + MB_ICONINFORMATION + 0); exit; end; Label2.Caption := Form1.GetText('66'); Application.ProcessMessages; with HTTPGet1 do begin erreur := false; NewVersion := ''; URL := 'http://www.opensofts.info/All4Cod/UPDATE'; DL_Fini := true; GetString; while ((not erreur) and (NewVersion = '')) do Application.ProcessMessages; if not erreur then begin ImageList1.GetBitmap(0, Image2.Picture.Bitmap); Image2.Repaint; Label2.Caption := Form1.GetText('67'); Application.ProcessMessages; end else begin MessageBoxA(Handle, Pchar(Form1.GetText('34')), Pchar('All4Cod - ' + Form1.GetText('ERROR')), 0 + MB_ICONINFORMATION + 0); Exit; end; end; Label3.Caption := Form1.GetText('66'); Application.ProcessMessages; if NewVersionAvailable(NewVersion, GetVersion) then begin Label3.Caption := Form1.GetText('67'); ImageList1.GetBitmap(0, Image3.Picture.Bitmap); Image3.Repaint; Application.ProcessMessages; end else begin MessageBoxA(Handle, Pchar(Form1.GetText('35') + #13 + Form1.GetText('36') + ' ' + GetVersion), Pchar('All4Cod - ' + Form1.GetText('MSG')), 0 + MB_ICONINFORMATION + 0); exit; end; Label4.Caption := Form1.GetText('66'); Application.ProcessMessages; with HTTPGet1 do begin if not (DirectoryExists(IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'Update')) then MkDir(IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'Update'); URL := 'http://www.opensofts.info/download.php?id=1'; FileName := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'Update\All4Cod.exe'; erreur := false; DL_Fini := false; GetFile; while (not (erreur or DL_Fini)) do Application.ProcessMessages; if not erreur then begin ImageList1.GetBitmap(0, Image4.Picture.Bitmap); Image4.Repaint; Label4.Caption := Form1.GetText('68'); end else begin MessageBoxA(Handle, Pchar(Form1.GetText('37')), Pchar('All4Cod - ' + Form1.GetText('ERROR')), 0 + MB_ICONINFORMATION + 0); Exit; end; end; ImageList1.GetBitmap(0, Image5.Picture.Bitmap); Image5.Repaint; label5.Caption := Form1.GetText('67'); Application.ProcessMessages; MessageBoxA(Handle, Pchar(Form1.GetText('38') + #13 + Form1.GetText('39')), Pchar('All4Cod - ' + Form1.GetText('MSG')), 0 + MB_ICONINFORMATION + 0); end; procedure TForm15.HTTPGet1DoneString(Sender : TObject; Result : string); begin NewVersion := Result; end; procedure TForm15.HTTPGet1Error(Sender : TObject); begin erreur := true; end; procedure TForm15.HTTPGet1DoneFile(Sender : TObject; FileName : string; FileSize : Integer); begin Dl_Fini := true; ProgressBar1.Position := 100; end; procedure TForm15.HTTPGet1Progress(Sender : TObject; TotalSize, Readed : Integer); begin if not (DL_Fini) then begin Label4.Caption := FormatFloat('0.00', 100 * Readed * (1 / TotalSize)) + ' %'; ProgressBar1.Position := Readed * 100 div TotalSize; if StatusBar1.Panels[0].Text = '' then StatusBar1.Panels[0].Text := Form1.GetText('69') + ' : ' + IntToStr(TotalSize div 1024) + ' Ko'; end; end; procedure TForm15.FormCreate(Sender : TObject); var ini : TIniFile; begin Icon.Handle := Application.Icon.Handle; ini := TIniFile.Create(Form1.CurrentFileLanguage); with ini do begin Caption := ReadString('MISEAJOUR', '0', ''); Label6.Caption := ReadString('MISEAJOUR', '1', ''); Label7.Caption := ReadString('MISEAJOUR', '2', ''); Label8.Caption := ReadString('MISEAJOUR', '3', ''); Label9.Caption := ReadString('MISEAJOUR', '4', ''); Label10.Caption := ReadString('MISEAJOUR', '5', ''); Button1.Caption := ReadString('MISEAJOUR', '6', ''); free; end; ProgressBar1.Parent := StatusBar1; ProgressBar1.SetBounds(StatusBar1.Panels[0].Width + 2, 2, StatusBar1.Width - StatusBar1.Panels[0].Width - 2, 17); end; end.
unit MachO; {<Utilities for reading (debug) sections from a Mach-O file (such as a Intel macOS64 executable or .dSYM file). For an introduction to the Mach-O file format: * https://h3adsh0tzz.com/2020/01/macho-file-format/ For the specification (no longer provided by Apple): * http://idea2ic.com/File_Formats/MachORuntime.pdf } interface uses System.Classes, System.SysUtils, System.Generics.Collections, Grijjy.MachOApi; type { Type of exception raised for errors encountered during parsing of a Mach-O file. } EMachOError = class(Exception); type { Represents a section in a Mach-O file } TSection = class {$REGION 'Internal Declarations'} private FStream: TStream; FSection: section_64; function GetSectionName: String; function GetSegmentName: String; protected constructor Create(const AStream: TStream; const ASection: section_64); {$ENDREGION 'Internal Declarations'} public function Load: TBytes; property SegmentName: String read GetSegmentName; property SectionName: String read GetSectionName; end; type { Limited Mach-O file parser. Only supports Intel 64-bit macOS Mach-O files. } TMachOFile = class {$REGION 'Internal Declarations'} private FStream: TStream; FSections: TObjectList<TSection>; FID: TGUID; FOwnsStream: Boolean; {$ENDREGION 'Internal Declarations'} public constructor Create; destructor Destroy; override; procedure Clear; procedure Load(const AFilename: String); overload; procedure Load(const AStream: TStream; const AOwnsStream: Boolean); overload; { Unique ID for this Mach-O file. An executable and corresponding dSYM must have the same ID. } property ID: TGUID read FID; property Sections: TObjectList<TSection> read FSections; end; implementation { TSection } constructor TSection.Create(const AStream: TStream; const ASection: section_64); begin Assert(Assigned(AStream)); inherited Create; FStream := AStream; FSection := ASection; end; function TSection.GetSectionName: String; var Name: array [0..16] of AnsiChar; begin Move(FSection.sectname, Name, 16); Name[16] := #0; Result := String(AnsiString(Name)); end; function TSection.GetSegmentName: String; var Name: array [0..16] of AnsiChar; begin Move(FSection.segname, Name, 16); Name[16] := #0; Result := String(AnsiString(Name)); end; function TSection.Load: TBytes; begin if (FSection.offset = 0) or (FSection.size = 0) then Exit(nil); SetLength(Result, FSection.size); FStream.Position := FSection.offset; FStream.ReadBuffer(Result[0], FSection.size); end; { TMachOFile } procedure TMachOFile.Clear; begin if (FOwnsStream) then FStream.Free; FStream := nil; FSections.Clear; FID := TGUID.Empty; end; constructor TMachOFile.Create; begin inherited; FSections := TObjectList<TSection>.Create; end; destructor TMachOFile.Destroy; begin FSections.Free; if (FOwnsStream) then FStream.Free; inherited; end; procedure TMachOFile.Load(const AStream: TStream; const AOwnsStream: Boolean); var Header: mach_header_64; I, J: Integer; CmdPos: Int64; CmdHeader: load_command; SegCmd: segment_command_64; Section: section_64; begin Assert(Assigned(AStream)); Clear; FStream := AStream; FOwnsStream := AOwnsStream; AStream.ReadBuffer(Header, SizeOf(Header)); if (Header.magic <> MH_MAGIC_64) then raise EMachOError.Create('Not a valid Mach-O file. Only 64-bit, little-endian Mach-O files are supported.'); if (Header.cputype <> CPU_TYPE_X86_64) then raise EMachOError.Create('Only 64-bit Intel CPU type supported.'); for I := 0 to Header.ncmds - 1 do begin CmdPos := AStream.Position; AStream.ReadBuffer(CmdHeader, SizeOf(CmdHeader)); if (CmdHeader.cmdsize < SizeOf(CmdHeader)) then raise EMachOError.Create('Invalid load command size.'); if (CmdHeader.cmd = LC_SEGMENT_64) then begin AStream.ReadBuffer(SegCmd.segname, SizeOf(SegCmd) - SizeOf(CmdHeader)); if (CmdHeader.cmdsize <> (SizeOf(SegCmd) + (Cardinal(SegCmd.nsects) * SizeOf(Section)))) then raise EMachOError.Create('Invalid LC_SEGMENT_64 size'); for J := 0 to SegCmd.nsects - 1 do begin AStream.ReadBuffer(Section, SizeOf(Section)); FSections.Add(TSection.Create(AStream, Section)); end; end else if (CmdHeader.cmd = LC_UUID) then begin if (CmdHeader.cmdsize <> (SizeOf(CmdHeader) + SizeOf(TGUID))) then raise EMachOError.Create('Invalid LC_UUID size'); if (FID <> TGUID.Empty) then raise EMachOError.Create('Duplicate LC_UUID command'); AStream.ReadBuffer(FID, SizeOf(FID)); end; AStream.Position := CmdPos + CmdHeader.cmdsize; end; if (FID = TGUID.Empty) then raise EMachOError.Create('Missing LC_UUID command'); end; procedure TMachOFile.Load(const AFilename: String); begin Load(TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite), True); end; end.
program arvore_para_pilha; {Objetivo: transformar uma lista não linear em uma linear e ir imprimindo na tela os contatos em ordem alfabética Responsável:Felipe Schreiber Fernandes Data:15/12/2016} uses minhaBiblioteca; type noAgenda=^regAgenda; pPilha=^pilha; regAgenda=record nome:string; tel:string; esq,dir:noAgenda; end; pilha=record nome:string; tel:string; anterior,proximo:pPilha; tree:noAgenda; end; function menu():integer; var opcao:integer; Begin Writeln('Escolha uma dessas opções:'); writeln(); writeln('1-Incluir novo contato'); writeln('2-Listar todos os contatos'); writeln('3-Sair'); opcao:=lerInteiro(1,3,'Digite uma das opções acima.Só pode ser um inteiro entre 1 e 3'); menu:=opcao; End; procedure incluir(raiz:noAgenda;novo:noAgenda); var incluiu:boolean; atual:noAgenda; aux:pPilha;{a variável auxiliar serve para fazer uma lista paralela que guarda a referência do anterior ao atual na árvore} primeiro,ultimo:pPilha; begin primeiro:=nil; ultimo:=nil; new(atual); atual:=raiz; incluiu:=false; repeat if atual=nil then begin if novo^.nome > ultimo^.nome then{compara se o novo deve ser inserido à esquerda ou à direita do último nó da árvore} begin ultimo^.tree^.dir:=novo;{o ultimo da pilha possui a referência do último nó da árvore, assim basta irmos para ele e inserir o novo} end else begin ultimo^.tree^.esq:=novo;{mesma lógica, só que para o caso em que ele tiver que ser inserido na esquerda} end; incluiu:=true; writeln('Contato inserido com sucesso'); end else begin incluiu:=false; if novo^.nome > atual^.nome then begin new(aux); aux^.tree:=atual; aux^.proximo:=nil; aux^.anterior:=nil; {cria uma nova variável auxiliar que será inserida na lista paralela e assim guardar a referência do nó atual da árvore} if primeiro=nil then begin primeiro:=aux; ultimo:=aux; end else begin ultimo^.proximo:=aux; aux^.anterior:=ultimo; ultimo:=aux; {coloca a nova variável auxiliar no final da lista} end; atual:=atual^.dir; end else begin {mesma lógica, só que para o caso em que tiver que ir para a esquerda} new(aux); aux^.tree:=atual; aux^.proximo:=nil; aux^.anterior:=nil; if primeiro=nil then begin primeiro:=aux; ultimo:=aux; end else begin ultimo^.proximo:=aux; aux^.anterior:=ultimo; ultimo:=aux; end; atual:=atual^.esq; end; end; until incluiu; end; procedure coletarDados(var raiz:noAgenda); var novo:noAgenda; choice:char; Begin repeat new(novo); novo^.nome:=lerString(1,30,ALFABETO+SPACE,'Digite o nome do contato a ser inserido.Só podem conter letras e no máximo 30 caracteres'); novo^.nome:=upcase(novo^.nome); writeln(); novo^.tel:=lerString(1,16,NUM,'Digite o número do contato a ser inserido.Só podem conter no máximo 16 números'); novo^.esq:=nil; novo^.dir:=nil; if raiz=nil then begin raiz:=novo; end else begin incluir(raiz,novo); end; writeln(); choice:=lerChar('snSN','Deseja inserir outro contato?Digite [S]im ou [N]ão'); choice:=upcase(choice); until choice='N'; End; procedure exibir(raiz:noAgenda); var atualArvore:noAgenda;{esse ponteiro percorre a árvore e passa o dados para o ponteiro auxiliar} aux:pPilha;{esse ponteiro armazena o telefone, o nome da pessoa, o próximo e o anterior da pilha bem como o seu correspondente na árvore} primeiro,ultimo:pPilha;{onde começa e onde termina a pilha} begin atualArvore:=raiz; primeiro:=nil; ultimo:=nil; if atualArvore=nil then begin writeln('Não há contatos na lista'); end else begin repeat if atualArvore<>nil then begin new(aux); aux^.tree:=atualArvore; aux^.nome:=atualArvore^.nome; aux^.tel:=atualArvore^.tel; aux^.proximo:=nil; aux^.anterior:=nil; if primeiro=nil then begin primeiro:=aux; ultimo:=aux; end else begin ultimo^.proximo:=aux; aux^.anterior:=ultimo; ultimo:=aux; end; if atualArvore^.esq<>nil then begin atualArvore:=atualArvore^.esq; end else begin if atualArvore^.dir<>nil then begin {quando apenas o ponteiro da direita é nil devemos desempilhar o nó da lista e ir para o seguinte, ou seja, o filho da direita} writeln('Nome: ',atualArvore^.nome,#9,'Tel: ',atualArvore^.tel);{imprime os dados do nó} ultimo:=aux^.anterior; dispose(aux);{retira o último da pilha, que é o que acabou de ser colocado} ultimo^.proximo:=nil; atualArvore:=atualArvore^.dir; end else begin writeln('Nome: ',aux^.nome,'Tel: ',aux^.tel); atualArvore:=aux^.anterior^.tree;{volta para a posição da árvore para a qual o anterior da pilha aponta.Observe que se o ladoesquerdo já foi desempilhado, então subiremos dois níveis na árvore} ultimo:=aux^.anterior; dispose(aux);{desempilha o último da pilha, que é o que acabou de ser colocado} ultimo^.proximo:=nil; {quando ambos os ponteiros esquerda e direita são nil temos que exibir o último que foi posto na pilha e também o nó} {Depois tirá-los da pilha} writeln('Nome: ',ultimo^.nome,'Tel: ',ultimo^.tel);{imprime os dados do nó} new(aux);{esse novo espaço criado é apenas para auxiliar no processo de rearranjar a pilha} aux:=ultimo; ultimo:=aux^.anterior; if ultimo <> nil then begin ultimo^.proximo:=nil; end else begin primeiro:=nil;{caso o último seja nil significa que chegamos ao topo da árvore} end; dispose(aux);{retira da pilha} if atualArvore^.dir<>nil then{após subir dois níveis da árvore é necessário checar se há filho há direita da posição atual} begin atualArvore:=atualArvore^.dir;{agora descemos para o lado direito do nó} end else begin atualArvore:=ultimo^.tree;{sobe mais um nível} end; end; end; end; until atualArvore=nil; end; end; procedure executar(var raiz:noAgenda); var option:integer;{armazena o valor retornado pela função menu} escolha:char; begin repeat repeat option:=menu(); case option of 1: Begin coletarDados(raiz); End; 2: Begin exibir(raiz); End; end; until option=3; writeln(); escolha:=lerChar('snSN','Deseja sair do programa?Digite [S]im ou [N]ão'); escolha:=upcase(escolha); until escolha='S'; end; {Programa Principal} var root:noAgenda; BEGIN root:=nil; executar(root); END.
{ License: wtfpl; see /copying or the Internet } { A function dictionary class } unit fdictionary; {$mode objfpc}{$H+} interface uses Classes, SysUtils, contnrs, strutils, parameterStuff; type eFunction = class(exception); p_metaParam = ^k_metaParam; k_metaParam = record parser: kEvaluator; end; kfunction = function (meta: p_metaParam; parameters: k_parameterList): string; kfunctionO = function (meta: p_metaParam; parameters: k_parameterList): string of object; { kfunctionDict } kfunctionDict = class namespace: string; storage: TFPHashList; function Get(Index: string): kfunction; {$ifdef CCLASSESINLINE}inline;{$endif} procedure Put(Index: string; Item: kfunction); {$ifdef CCLASSESINLINE}inline;{$endif} function Add(const AName: shortstring; Item: kfunction): integer; property Items[Index: string]: kfunction read Get write Put; default; constructor create; destructor destroy; end; implementation { kfunctionDict } function kfunctionDict.Add(const AName: shortstring; Item: kfunction): integer; begin result:= storage.Add(AName, Item) end; constructor kfunctionDict.create; begin inherited; storage:= TFPHashList.Create end; destructor kfunctionDict.destroy; begin inherited end; function kfunctionDict.Get(Index: string): kfunction; var y: pointer; begin y:= storage.Find(Index); if y <> nil then result:= kfunction(y) else ;//raise eFunction.create() end; procedure kfunctionDict.Put(Index: string; Item: kfunction); var z: pointer; begin z:= storage.Find(index); z:= Item end; end.
unit mouse; interface uses Windows, SysUtils, Classes, Graphics, forms, ExtCtrls; procedure SaveResourceAsFile(const ResName: string; ResType: pchar; const FileName: string); function SaveResourceAsTempFile(const ResName: string; ResType: pchar): string; function GetResourceAsAniCursor(const ResName: string): HCursor; function CreateTempFile: String; implementation function CreateTempFile: String; var TempFile,TempDir : array[1..256] of Char; Files,Dirs:PChar; begin Files:=@TempFile; Dirs:=@TempDir; GetTEmpPath(256,dirs); GetTempFileName(dirs,'~Tmp',0,Files); Result:=Copy(Files,1,Length(Files)); end; procedure SaveResourceAsFile(const ResName: string; ResType: pchar; const FileName: string); begin with TResourceStream.Create(hInstance, ResName, ResType) do try SaveToFile(FileName); finally Free; end; end; function SaveResourceAsTempFile(const ResName: string; ResType: pchar): string; begin Result := CreateTempFile; SaveResourceAsFile(ResName, ResType, Result); end; function GetResourceAsAniCursor(const ResName: string): HCursor; var CursorFile: string; begin CursorFile := SaveResourceAsTempFile(ResName, RT_RCDATA); //Result := LoadImage(0, PChar(CursorFile), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE or LR_LOADFROMFILE); Result := loadcursorfromfile(Pwidechar(CursorFile)); DeleteFile(CursorFile); if Result = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); end; end.
unit FHIR.XVersion.Tests; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, DUnitX.TestFramework, FHIR.Support.Stream, FHIR.Base.Objects, FHIR.Base.Parser, FHIR.R3.Parser, FHIR.R4.Parser, FHIR.XVersion.Convertors; type [TextFixture] TVersionConversionTests = Class (TObject) private procedure test4to3to4(res : TBytes); public [Setup] procedure Setup; [TearDown] procedure TearDown; [TestCase] Procedure TestPatient_34_simple; [TestCase] Procedure TestParameters_34; [TestCase] Procedure TestActivityDefinition_34; [TestCase] Procedure TestAllergyIntolerance_34; [TestCase] Procedure TestAppointment_34; [TestCase] Procedure TestAppointmentResponse_34; [TestCase] Procedure TestAuditEvent_34; [TestCase] Procedure TestBasic_34; [TestCase] Procedure TestBinary_34; [TestCase] Procedure TestBodyStructure_34; [TestCase] Procedure TestBundle_34; [TestCase] Procedure TestCapabilityStatement_34; [TestCase] Procedure TestCareTeam_34; [TestCase] Procedure TestClaim_34; [TestCase] Procedure TestClinicalImpression_34; [TestCase] Procedure TestCodeSystem_34; [TestCase] Procedure TestCommunication_34; [TestCase] Procedure TestCompartmentDefinition_34; [TestCase] Procedure TestComposition_34; [TestCase] Procedure TestConceptMap_34; [TestCase] Procedure TestCondition_34; [TestCase] Procedure TestConsent_34; [TestCase] Procedure TestDetectedIssue_34; [TestCase] Procedure TestDevice_34; [TestCase] Procedure TestDeviceComponent_34; [TestCase] Procedure TestDeviceMetric_34; [TestCase] Procedure TestDeviceUseStatement_34; [TestCase] Procedure TestDiagnosticReport_34; [TestCase] Procedure TestDocumentReference_34; [TestCase] Procedure TestEncounter_34; [TestCase] Procedure Testendpoint_34; [TestCase] Procedure TestEpisodeOfCare_34; [TestCase] Procedure TestExpansionProfile_34; [TestCase] Procedure TestFamilyMemberHistory_34; [TestCase] Procedure TestFlag_34; [TestCase] Procedure TestGoal_34; [TestCase] Procedure TestGraphDefinition_34; [TestCase] Procedure TestGroup_34; [TestCase] Procedure TestHealthcareService_34; [TestCase] Procedure TestImmunization_34; [TestCase] Procedure TestImplementationGuide_34; [TestCase] Procedure TestLinkage_34; [TestCase] Procedure TestList_34; [TestCase] Procedure TestLocation_34; [TestCase] Procedure TestMedicationAdministration_34; [TestCase] Procedure TestMedicationDispense_34; [TestCase] Procedure TestMedicationRequest_34; [TestCase] Procedure TestMedicationStatement_34; [TestCase] Procedure TestMessageDefinition_34; [TestCase] Procedure TestMessageHeader_34; [TestCase] Procedure TestNamingSystem_34; [TestCase] Procedure TestObservation_34; [TestCase] Procedure TestOperationDefinition_34; [TestCase] Procedure TestOperationOutcome_34; [TestCase] Procedure TestOrganization_34; [TestCase] Procedure TestPatient_34; [TestCase] Procedure TestPaymentNotice_34; [TestCase] Procedure TestPerson_34; [TestCase] Procedure TestPractitioner_34; [TestCase] Procedure TestPractitionerRole_34; [TestCase] Procedure TestQuestionnaire_34; [TestCase] Procedure TestQuestionnaireResponse_34; [TestCase] Procedure TestRiskAssessment_34; [TestCase] Procedure TestSchedule_34; [TestCase] Procedure TestSearchParameter_34; [TestCase] Procedure TestSequence_34; [TestCase] Procedure TestSlot_34; [TestCase] Procedure TestSpecimen_34; [TestCase] Procedure TestStructureDefinition_34; [TestCase] Procedure TestStructureMap_34; [TestCase] Procedure TestSubscription_34; [TestCase] Procedure TestSubstance_34; [TestCase] Procedure TestSupplyDelivery_34; [TestCase] Procedure TestValueSet_34; End; implementation { TVersionConversionTests } procedure TVersionConversionTests.Setup; begin // nothing end; procedure TVersionConversionTests.TearDown; begin // nothing end; procedure TVersionConversionTests.test4to3to4(res: TBytes); var b : TBytes; begin b := TFhirVersionConvertors.convertResource(res, ffJson, OutputStylePretty, 'en', fhirVersionRelease4, fhirVersionRelease3); b := TFhirVersionConvertors.convertResource(b, ffJson, OutputStylePretty, 'en', fhirVersionRelease3, fhirVersionRelease4); Assert.isTrue(length(b) > 0); end; procedure TVersionConversionTests.TestPatient_34_simple; begin test4to3to4(TEncoding.UTF8.GetBytes('{"resourceType" : "Patient", "gender" : "male"}')); end; procedure TVersionConversionTests.TestParameters_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\parameters-example.json')); end; procedure TVersionConversionTests.TestActivityDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\activitydefinition-example.json')); end; procedure TVersionConversionTests.TestAllergyIntolerance_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\allergyintolerance-example.json')); end; procedure TVersionConversionTests.TestAppointment_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\appointment-example.json')); end; procedure TVersionConversionTests.TestAppointmentResponse_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\appointmentresponse-example.json')); end; procedure TVersionConversionTests.TestAuditEvent_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\auditevent-example.json')); end; procedure TVersionConversionTests.TestBasic_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\basic-example.json')); end; procedure TVersionConversionTests.TestBinary_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\binary-example.json')); end; procedure TVersionConversionTests.TestBodyStructure_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\bodystructure-example-fetus.json')); end; procedure TVersionConversionTests.TestBundle_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\bundle-questionnaire.json')); end; procedure TVersionConversionTests.TestCapabilityStatement_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\capabilitystatement-example.json')); end; procedure TVersionConversionTests.TestCareTeam_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\careteam-example.json')); end; procedure TVersionConversionTests.TestClaim_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\claim-example.json')); end; procedure TVersionConversionTests.TestClinicalImpression_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\clinicalimpression-example.json')); end; procedure TVersionConversionTests.TestCodeSystem_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\codesystem-example.json')); end; procedure TVersionConversionTests.TestCommunication_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\communication-example.json')); end; procedure TVersionConversionTests.TestCompartmentDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\compartmentdefinition-example.json')); end; procedure TVersionConversionTests.TestComposition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\composition-example.json')); end; procedure TVersionConversionTests.TestConceptMap_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\conceptmap-example.json')); end; procedure TVersionConversionTests.TestCondition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\condition-example.json')); end; procedure TVersionConversionTests.TestConsent_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\consent-example.json')); end; procedure TVersionConversionTests.TestDetectedIssue_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\detectedissue-example.json')); end; procedure TVersionConversionTests.TestDevice_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\device-example.json')); end; procedure TVersionConversionTests.TestDeviceComponent_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\devicecomponent-example.json')); end; procedure TVersionConversionTests.TestDeviceMetric_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\devicemetric-example.json')); end; procedure TVersionConversionTests.TestDeviceUseStatement_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\deviceusestatement-example.json')); end; procedure TVersionConversionTests.TestDiagnosticReport_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\diagnosticreport-example.json')); end; procedure TVersionConversionTests.TestDocumentReference_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\documentreference-example.json')); end; procedure TVersionConversionTests.TestEncounter_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\encounter-example.json')); end; procedure TVersionConversionTests.Testendpoint_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\endpoint-example.json')); end; procedure TVersionConversionTests.TestEpisodeOfCare_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\episodeofcare-example.json')); end; procedure TVersionConversionTests.TestExpansionProfile_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\expansionprofile-example.json')); end; procedure TVersionConversionTests.TestFamilyMemberHistory_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\familymemberhistory-example.json')); end; procedure TVersionConversionTests.TestFlag_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\flag-example.json')); end; procedure TVersionConversionTests.TestGoal_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\goal-example.json')); end; procedure TVersionConversionTests.TestGraphDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\graphdefinition-example.json')); end; procedure TVersionConversionTests.TestGroup_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\group-example.json')); end; procedure TVersionConversionTests.TestHealthcareService_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\healthcareservice-example.json')); end; procedure TVersionConversionTests.TestImmunization_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\immunization-example.json')); end; procedure TVersionConversionTests.TestImplementationGuide_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\implementationguide-example.json')); end; procedure TVersionConversionTests.TestLinkage_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\linkage-example.json')); end; procedure TVersionConversionTests.TestList_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\list-example.json')); end; procedure TVersionConversionTests.TestLocation_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\location-example.json')); end; procedure TVersionConversionTests.TestMedicationAdministration_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\medicationadministration0301.json')); end; procedure TVersionConversionTests.TestMedicationDispense_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\medicationdispense0301.json')); end; procedure TVersionConversionTests.TestMedicationRequest_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\medicationrequest0301.json')); end; procedure TVersionConversionTests.TestMedicationStatement_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\medicationstatementexample1.json')); end; procedure TVersionConversionTests.TestMessageDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\messagedefinition-example.json')); end; procedure TVersionConversionTests.TestMessageHeader_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\messageheader-example.json')); end; procedure TVersionConversionTests.TestNamingSystem_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\namingsystem-example.json')); end; procedure TVersionConversionTests.TestObservation_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\observation-example.json')); end; procedure TVersionConversionTests.TestOperationDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\operationdefinition-example.json')); end; procedure TVersionConversionTests.TestOperationOutcome_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\operationoutcome-example.json')); end; procedure TVersionConversionTests.TestOrganization_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\organization-example.json')); end; procedure TVersionConversionTests.TestPatient_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\patient-example.json')); end; procedure TVersionConversionTests.TestPaymentNotice_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\paymentnotice-example.json')); end; procedure TVersionConversionTests.TestPerson_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\person-example.json')); end; procedure TVersionConversionTests.TestPractitioner_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\practitioner-example.json')); end; procedure TVersionConversionTests.TestPractitionerRole_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\practitionerrole-example.json')); end; procedure TVersionConversionTests.TestQuestionnaire_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\questionnaire-example.json')); end; procedure TVersionConversionTests.TestQuestionnaireResponse_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\questionnaireresponse-example-bluebook.json')); end; procedure TVersionConversionTests.TestRiskAssessment_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\riskassessment-example.json')); end; procedure TVersionConversionTests.TestSchedule_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\schedule-example.json')); end; procedure TVersionConversionTests.TestSearchParameter_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\searchparameter-example.json')); end; procedure TVersionConversionTests.TestSequence_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\sequence-example.json')); end; procedure TVersionConversionTests.TestSlot_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\slot-example.json')); end; procedure TVersionConversionTests.TestSpecimen_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\specimen-example.json')); end; procedure TVersionConversionTests.TestStructureDefinition_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\structuredefinition-example.json')); end; procedure TVersionConversionTests.TestStructureMap_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\structuremap-example.json')); end; procedure TVersionConversionTests.TestSubscription_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\subscription-example.json')); end; procedure TVersionConversionTests.TestSubstance_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\substance-example.json')); end; procedure TVersionConversionTests.TestSupplyDelivery_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\supplydelivery-example.json')); end; procedure TVersionConversionTests.TestValueSet_34; begin test4to3to4(FileToBytes('c:\work\org.hl7.fhir\build\publish\valueset-example.json')); end; initialization TDUnitX.RegisterTestFixture(TVersionConversionTests); end.
unit MBRTUPortAdapter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, syncobjs, contnrs, LoggerItf, MBRTUMasterDispatcherTypes, MBRTURequestBase, MBRTUObjItf, MBRTUPortThread; type { TMBRTUPortAdapter } TMBRTUPortAdapter = class(TObjectLogged) private FCSection : TCriticalSection; FOwnedRequests : Boolean; FPordIDStr : String; FPortParams : TMBDispPortParam; FPoolingObjList : TObjectList; FSingleObjQueue : TObjectQueue; FPortThread : TMBRTUPortThread; function GetActive: Boolean; function GetPoolingRequestCount: Integer; function GetPoolingRequests(Index : Integer): TMBRTURequestBase; procedure SetActive(AValue: Boolean); procedure SetOwnedRequests(AValue: Boolean); procedure RemoveRequestFromPoolingObj(ASubscriber : IMBMasterItf); procedure RemoveRequestFromSingleObj(ASubscriber : IMBMasterItf); // меняет только параметры порта(паритет, битданных и т.п.) но не его имя порта procedure SetPortParams(AValue: TMBDispPortParam); public constructor Create(APortParam : TMBDispPortParam); virtual; destructor Destroy; override; procedure AddPoolRequest(var ARequest : TMBRTURequestBase); procedure ClearPoolList; procedure SendSingleRequest(var ARequest : TMBRTURequestBase); procedure ClearSingleQueue; // удаляет все запросы подписчика procedure RemoveRequests(ASubscriber : IMBMasterItf); procedure Lock; procedure UnLock; procedure Start; procedure Stop; procedure Restart; property PordIDStr : String read FPordIDStr; // установка параметров не меняет имени порта. Имя порта задается только при создении порта. property PortParams : TMBDispPortParam read FPortParams write SetPortParams; property Active : Boolean read GetActive write SetActive; property OwnedRequests : Boolean read FOwnedRequests write SetOwnedRequests default True; property PoolingRequestCount : Integer read GetPoolingRequestCount; property PoolingRequests[Index : Integer] : TMBRTURequestBase read GetPoolingRequests; end; implementation uses MBRTUMasterDispatcherFunc; { TMBRTUPortAdapter } constructor TMBRTUPortAdapter.Create(APortParam: TMBDispPortParam); begin FCSection := TCriticalSection.Create; FOwnedRequests := True; FPortParams := APortParam; FPordIDStr := GetPortAdapterIDStr(FPortParams); FPoolingObjList := TObjectList.Create(FOwnedRequests); FSingleObjQueue := TObjectQueue.Create; FPortThread := nil ; end; destructor TMBRTUPortAdapter.Destroy; begin Stop; ClearSingleQueue; FreeAndNil(FSingleObjQueue); ClearPoolList; FreeAndNil(FPoolingObjList); FreeAndNil(FCSection); inherited Destroy; end; function TMBRTUPortAdapter.GetActive: Boolean; begin if Assigned(FPortThread) then begin Result := FPortThread.IsActive; end else Result := False; end; function TMBRTUPortAdapter.GetPoolingRequestCount: Integer; begin Result := FPoolingObjList.Count; end; function TMBRTUPortAdapter.GetPoolingRequests(Index : Integer): TMBRTURequestBase; begin Result := nil; if (FPoolingObjList.Count = 0) or (Index > (FPoolingObjList.Count-1)) or (Index < 0) then Result := nil; Result := TMBRTURequestBase(FPoolingObjList[Index]); end; procedure TMBRTUPortAdapter.SetActive(AValue: Boolean); begin if Active = AValue then Exit; if AValue then Start else Stop; end; procedure TMBRTUPortAdapter.Lock; begin FCSection.Enter; end; procedure TMBRTUPortAdapter.SetOwnedRequests(AValue: Boolean); begin if FOwnedRequests = AValue then Exit; FOwnedRequests := AValue; FPoolingObjList.OwnsObjects := AValue; end; procedure TMBRTUPortAdapter.UnLock; begin FCSection.Leave; end; procedure TMBRTUPortAdapter.AddPoolRequest(var ARequest: TMBRTURequestBase); begin Lock; try FPoolingObjList.Add(ARequest); finally UnLock; end; end; procedure TMBRTUPortAdapter.ClearPoolList; begin Lock; try FPoolingObjList.Clear; finally UnLock; end; end; procedure TMBRTUPortAdapter.SendSingleRequest(var ARequest: TMBRTURequestBase); begin Lock; try FSingleObjQueue.Push(ARequest); finally UnLock; end; end; procedure TMBRTUPortAdapter.ClearSingleQueue; var TempReq : TMBRTURequestBase; begin Lock; try TempReq := TMBRTURequestBase(FSingleObjQueue.Pop); if FOwnedRequests then FreeAndNil(TempReq); finally UnLock; end; end; procedure TMBRTUPortAdapter.RemoveRequests(ASubscriber: IMBMasterItf); begin if not Assigned(ASubscriber) then Exit; RemoveRequestFromPoolingObj(ASubscriber); RemoveRequestFromSingleObj(ASubscriber); end; procedure TMBRTUPortAdapter.RemoveRequestFromPoolingObj(ASubscriber: IMBMasterItf); var i : Integer; TempReq : TMBRTURequestBase; begin Lock; try i := FPoolingObjList.Count-1; while (i >= 0) do begin TempReq := TMBRTURequestBase(FPoolingObjList[i]); if TempReq.CallBackItf <> ASubscriber then begin Dec(i); Continue; end; FPoolingObjList.Delete(i); if FOwnedRequests then FreeAndNil(TempReq); Dec(i); end; finally UnLock; end; end; procedure TMBRTUPortAdapter.RemoveRequestFromSingleObj(ASubscriber: IMBMasterItf); var i : Integer; TempReq : TMBRTURequestBase; begin Lock; try i := FSingleObjQueue.Count-1; while (i >= 0) do begin TempReq := TMBRTURequestBase(FSingleObjQueue.Pop); if TempReq.CallBackItf <> ASubscriber then begin FSingleObjQueue.Push(TempReq); Dec(i); Continue; end; if FOwnedRequests then FreeAndNil(TempReq); Dec(i); end; finally UnLock; end; end; procedure TMBRTUPortAdapter.SetPortParams(AValue: TMBDispPortParam); begin FPortParams.BaudRate := AValue.BaudRate; FPortParams.DataBits := AValue.DataBits; FPortParams.Parity := AValue.Parity; FPortParams.StopBits := AValue.StopBits; end; procedure TMBRTUPortAdapter.Start; begin if Assigned(FPortThread) then Exit; FPortThread := TMBRTUPortThread.Create(FPortParams, FCSection, FPoolingObjList, FSingleObjQueue, FOwnedRequests); FPortThread.Logger := Logger; FPortThread.Start; end; procedure TMBRTUPortAdapter.Stop; begin if not Assigned(FPortThread) then Exit; FPortThread.Terminate; FPortThread.WaitFor; FreeAndNil(FPortThread); end; procedure TMBRTUPortAdapter.Restart; begin if Assigned(FPortThread) then Stop; Start; end; end.
unit MainFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MainInterface, StdCtrls; type TMainForm = class(TForm) Button1: TButton; private procedure InitUI; public constructor Create(AOwner: TComponent); override; end; TMainFormPlugin_noDLL = class(TObject, IMainFormPlugin) private FMainForm: TMainForm; protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(AMainForm: TMainForm); overload; procedure AddButton; end; TPluginHandler = class(TObject) private IPlugin: IMainFormPlugin; FMainForm: TMainForm; public constructor Create(AMainForm: TMainForm); overload; procedure LoadPlugin; procedure DoPlugin; end; var MainForm: TMainForm; implementation {$R *.dfm} { TMainForm } constructor TMainForm.Create(AOwner: TComponent); begin inherited; InitUI; end; procedure TMainForm.InitUI; var OMainPlugin: TMainFormPlugin_noDLL; oPluginHandler: TPluginHandler; begin // OMainPlugin := TMainFormPlugin_noDLL.Create(Self); // OMainPlugin.AddButton; oPluginHandler := TPluginHandler.Create(Self); oPluginHandler.LoadPlugin; oPluginHandler.DoPlugin; end; { TMainFormPlugin_noDLL } procedure TMainFormPlugin_noDLL.AddButton; var iBtn: TButton; begin iBtn := TButton.Create(FMainForm); iBtn.Name := 'btnPlugin'; iBtn.Caption := 'À©Õ¹'; iBtn.Parent := FMainForm; end; constructor TMainFormPlugin_noDLL.Create(AMainForm: TMainForm); begin FMainForm := AMainForm; end; function TMainFormPlugin_noDLL.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := -1; end; function TMainFormPlugin_noDLL._AddRef: Integer; begin Result := -1; end; function TMainFormPlugin_noDLL._Release: Integer; begin Result := -1; end; { TPluginHandler } constructor TPluginHandler.Create(AMainForm: TMainForm); begin FMainForm := AMainForm; end; procedure TPluginHandler.DoPlugin; begin IPlugin.AddButton; end; procedure TPluginHandler.LoadPlugin; var pMainFormPlugin: TMainFormPlugin; begin @pMainFormPlugin := GetProcAddress(LoadLibrary(PChar('E:\WorkCode\PluginDemo\bin\Plugin.dll')), 'CreatePlugin'); IPlugin := pMainFormPlugin(FMainForm); end; end.
unit uJogoDaVelha; interface uses uJogador, uEnum, Vcl.Dialogs, uJogada, System.SysUtils; type TJogoDaVelha = class private FoJogador1: TJogador; FoJogador2: TJogador; FoJogadorAtual: TJogador; FJogada: TJogada; function getJogador1: TJogador; function getJogador2: TJogador; procedure setJogador1(const Value: TJogador); procedure setJogador2(const Value: TJogador); function getJogada: TJogada; procedure setJogada(const Value: TJogada); public property jogador1: TJogador read getJogador1 write setJogador1; property jogador2: TJogador read getJogador2 write setJogador2; property jogada: TJogada read getJogada write setJogada; function GetJogadorAtual: TJogador; function Jogar: tSimbolo; procedure retornaVencedor; constructor Create; destructor Destroy; override; end; implementation { TJogoDaVelha } constructor TJogoDaVelha.Create; begin FJogada := TJogada.Create(); end; destructor TJogoDaVelha.Destroy; begin FreeAndNil(FJogada); end; function TJogoDaVelha.getJogada: TJogada; begin Result := FJogada; end; function TJogoDaVelha.getJogador1: TJogador; begin Result := FoJogador1; end; function TJogoDaVelha.getJogador2: TJogador; begin Result := FoJogador2; end; procedure TJogoDaVelha.setJogada(const Value: TJogada); begin FJogada := jogada; end; procedure TJogoDaVelha.setJogador1(const Value: TJogador); begin FoJogador1 := Value; end; procedure TJogoDaVelha.setJogador2(const Value: TJogador); begin FoJogador2 := Value; end; function TJogoDaVelha.GetJogadorAtual: TJogador; begin if FoJogadorAtual = FoJogador1 then Result := FoJogador2 else Result := FoJogador1; end; function TJogoDaVelha.Jogar: tSimbolo; begin FoJogadorAtual := GetJogadorAtual; Result := FoJogadorAtual.simbolo; end; procedure TJogoDaVelha.retornaVencedor; begin if (FJogada.fimDejogo) and (FJogada.contaJogada < 9) then ShowMessage('O jogador ' + FoJogadorAtual.nome + ' venceu!'); end; end.
unit OListPropertyFrm; interface uses Forms, cxLookAndFeelPainters, Classes, Controls, StdCtrls, cxButtons, ExtCtrls, cxRadioGroup, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit; type TOListPropertyForm = class(TForm) Cancel: TcxButton; OK: TcxButton; cxRadioButton1: TcxRadioButton; Panel1: TPanel; cxRadioButton2: TcxRadioButton; cxRadioButton3: TcxRadioButton; cxRadioButton4: TcxRadioButton; cxRadioButton5: TcxRadioButton; Panel3: TPanel; Start: TcxSpinEdit; Label1: TLabel; Panel4: TPanel; private procedure SetStyleOfList(const Value: String); function GetStyleOfList: String; { Private declarations } public { Public declarations } property StyleOfList: String read GetStyleOfList write SetStyleOfList; end; function GetOListPropertyForm(var _start: Integer; var _type: String; Element: Boolean): Integer; implementation {$R *.dfm} function GetOListPropertyForm; var Form: TOListPropertyForm; begin Form := TOListPropertyForm.Create(Application); try with Form do with Form do begin // назначение данных if Element then Caption := 'Свойства элемента'; Start.Value := _start; StyleOfList := _type; Result := ShowModal; if Result = mrOK then begin // сохранение данных _start := Start.value; _type := StyleOfList; end; end; finally Form.Free; end; end; { TLOListPropertyForm } function TOListPropertyForm.GetStyleOfList: String; begin if cxRadioButton1.Checked then Result := ''; if cxRadioButton2.Checked then Result := 'a'; if cxRadioButton3.Checked then Result := 'A'; if cxRadioButton4.Checked then Result := 'i'; if cxRadioButton5.Checked then Result := 'I'; end; procedure TOListPropertyForm.SetStyleOfList(const Value: String); begin if (Value = '1') or (Value = '') then cxRadioButton1.Checked := True; if Value = 'a' then cxRadioButton2.Checked := True; if Value = 'A' then cxRadioButton3.Checked := True; if Value = 'i' then cxRadioButton4.Checked := True; if Value = 'I' then cxRadioButton5.Checked := True; end; end.
// ************************************************************************************************** // Delphi Detours Library // Unit GenericsCast // http://code.google.com/p/delphi-detours-library/ // 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 GenericsCast.pas. // The Initial Developer of the Original Code is Mahdi Safsafi [SMP3]. // Portions created by Mahdi Safsafi . are Copyright (C) 2013-2014 Mahdi Safsafi . // All Rights Reserved. // // ************************************************************************************************** unit GenericsCast; interface uses System.Math, WinApi.Windows; type { T = Type ; TT = ToType } TGenericsCast < T, TT >= class(TObject) /// <summary> Cast T type to TT type . /// </summary> class function Cast(const T: T): TT; end; implementation { TGenericsCast<T, TT> } class function TGenericsCast<T, TT>.Cast(const T: T): TT; begin Result := Default (TT); CopyMemory(@Result, @T, Min(SizeOf(T), SizeOf(TT))); end; end.
unit SQLiteAdminMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ActnList, StdActns, ExtCtrls, SQLiteData; type TformSQLiteAdminMain = class(TForm) ActionList1: TActionList; actRun: TAction; EditCut1: TEditCut; EditPaste1: TEditPaste; EditSelectAll1: TEditSelectAll; EditUndo1: TEditUndo; EditDelete1: TEditDelete; OpenDialog1: TOpenDialog; actCopyRow: TAction; actNextRS: TAction; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Splitter1: TSplitter; Panel1: TPanel; ComboBox1: TComboBox; btnRun: TButton; txtDbPath: TEdit; btnDbBrowse: TButton; Label2: TLabel; txtCommand: TMemo; Label3: TLabel; txtParamNames: TMemo; Label4: TLabel; txtParamValues: TMemo; actAbort: TAction; procedure actRunExecute(Sender: TObject); procedure btnDbBrowseClick(Sender: TObject); procedure actCopyRowExecute(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure actNextRSExecute(Sender: TObject); procedure txtDbPathChange(Sender: TObject); procedure Splitter1Moved(Sender: TObject); procedure EditSelectAll1Execute(Sender: TObject); procedure actAbortExecute(Sender: TObject); private Fdb: TSQLiteConnection; FAbortRequest:boolean; FAbortCheck:cardinal; procedure ResetAbort; procedure CheckAbort; protected procedure DoCreate; override; procedure DoDestroy; override; public function CloseQuery: Boolean; override; end; var formSQLiteAdminMain: TformSQLiteAdminMain; implementation uses Clipbrd; {$R *.dfm} procedure TformSQLiteAdminMain.DoCreate; begin inherited; Fdb:=nil; if ParamCount>0 then txtDbPath.Text:=ParamStr(1); if ParamCount>1 then txtCommand.Lines.LoadFromFile(ParamStr(2)); end; procedure TformSQLiteAdminMain.DoDestroy; begin inherited; FreeAndNil(Fdb); end; procedure TformSQLiteAdminMain.actRunExecute(Sender: TObject); var st:TSQLiteStatement; b:boolean; i,j,ref1,ref2,firstres:integer; lv:TListView; li:TListItem; s,t:string; begin ResetAbort; Panel1.Visible:=false; for i:=0 to ComboBox1.Items.Count-1 do ComboBox1.Items.Objects[i].Free; ComboBox1.Items.Clear; if Fdb=nil then Fdb:=TSQLiteConnection.Create(txtDbPath.Text); firstres:=0; Screen.Cursor:=crHourGlass; try if txtCommand.SelLength=0 then begin s:=txtCommand.Text; ref2:=0; end else begin s:=txtCommand.SelText; ref2:=txtCommand.SelStart; end; ref1:=ref2; try while s<>'' do begin i:=1; st:=TSQLiteStatement.Create(Fdb,UTF8Encode(s),i); try ref1:=ref2; inc(ref2,i); s:=Copy(s,i+1,Length(s)-i); txtParamNames.Lines.BeginUpdate; try txtParamNames.Clear; for i:=1 to st.ParameterCount do txtParamNames.Lines.Add(st.ParameterName[i]); finally txtParamNames.Lines.EndUpdate; end; for i:=0 to txtParamValues.Lines.Count-1 do if TryStrToInt(txtParamValues.Lines[i],j) then st.Parameter[i+1]:=j else st.Parameter[i+1]:=txtParamValues.Lines[i]; b:=st.Read; lv:=TListView.Create(Self); lv.Parent:=Panel1; lv.HideSelection:=false; lv.MultiSelect:=true; lv.ReadOnly:=true; lv.RowSelect:=true; lv.ViewStyle:=vsReport; lv.Align:=alClient; lv.Items.BeginUpdate; try with lv.Columns.Add do begin Caption:='#'; Width:=-1; end; t:=''; //if b then for i:=0 to st.FieldCount-1 do begin with lv.Columns.Add do begin Caption:=st.FieldName[i]; Width:=-1; end; t:=t+' '+st.FieldName[i]; end; i:=0; while b do begin inc(i); li:=lv.Items.Add; li.Caption:=IntToStr(i); for j:=0 to st.FieldCount-1 do li.SubItems.Add(VarToStr(st[j])); b:=st.Read; CheckAbort; end; finally lv.Items.EndUpdate; end; if (firstres=0) and (st.FieldCount<>0) then // and (i<>0) then ? firstres:=ComboBox1.Items.Count; ComboBox1.Items.AddObject(IntToStr(ComboBox1.Items.Count+1)+'('+IntToStr(i)+')'+t,lv); if s<>'' then CheckAbort; finally st.Free; end; end; except txtCommand.SelLength:=0; txtCommand.SelStart:=ref1; txtCommand.SelLength:=ref2-ref1; txtCommand.SetFocus; raise; end; finally Screen.Cursor:=crDefault; if ComboBox1.Items.Count<>0 then begin ComboBox1.ItemIndex:=firstres; (ComboBox1.Items.Objects[firstres] as TListView).BringToFront; end; Panel1.Visible:=true; end; end; procedure TformSQLiteAdminMain.btnDbBrowseClick(Sender: TObject); begin OpenDialog1.FileName:=txtDbPath.Text; if OpenDialog1.Execute then txtDbPath.Text:=OpenDialog1.FileName; end; procedure TformSQLiteAdminMain.actCopyRowExecute(Sender: TObject); var s:string; i:integer; begin if ActiveControl is TCustomEdit then (ActiveControl as TCustomEdit).CopyToClipboard else if ActiveControl is TListView then with ActiveControl as TListView do begin s:=''; for i:=0 to Items.Count-1 do if Items[i].Selected then begin Items[i].SubItems.Delimiter:=#9; s:=s+//Items[i].Caption+#9+ Items[i].SubItems.DelimitedText+#13#10; end; Clipboard.AsText:=s; end; end; procedure TformSQLiteAdminMain.ComboBox1Change(Sender: TObject); begin (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TListView).BringToFront; end; procedure TformSQLiteAdminMain.actNextRSExecute(Sender: TObject); begin if ComboBox1.ItemIndex=ComboBox1.Items.Count-1 then ComboBox1.ItemIndex:=0 else ComboBox1.ItemIndex:=ComboBox1.ItemIndex+1; (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TListView).BringToFront; end; procedure TformSQLiteAdminMain.txtDbPathChange(Sender: TObject); begin FreeAndNil(Fdb); end; procedure TformSQLiteAdminMain.Splitter1Moved(Sender: TObject); begin btnRun.Top:=Splitter1.Top+8; end; procedure TformSQLiteAdminMain.EditSelectAll1Execute(Sender: TObject); begin if ActiveControl is TCustomEdit then (ActiveControl as TCustomEdit).SelectAll else if ActiveControl is TListView then (ActiveControl as TListView).SelectAll; end; procedure TformSQLiteAdminMain.actAbortExecute(Sender: TObject); begin FAbortRequest:=true; end; procedure TformSQLiteAdminMain.ResetAbort; begin FAbortRequest:=false; FAbortCheck:=GetTickCount; end; procedure TformSQLiteAdminMain.CheckAbort; begin if cardinal(GetTickCount-FAbortCheck)>=100 then begin Application.ProcessMessages; if FAbortRequest then raise Exception.Create('User aborted.'); end; end; function TformSQLiteAdminMain.CloseQuery: Boolean; begin Result:=inherited CloseQuery; FAbortRequest:=true; end; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, EditBtn, Spin, BZFileFinder; type { TMainForm } TMainForm = class(TForm) Panel1 : TPanel; Label1 : TLabel; edtFolder : TDirectoryEdit; Label2 : TLabel; edtFileMask : TEdit; GroupBox1 : TGroupBox; Panel2 : TPanel; GroupBox3 : TGroupBox; GroupBox2 : TGroupBox; GroupBox4 : TGroupBox; chkSizeActive : TCheckBox; chkDateActive : TCheckBox; chkContentActive : TCheckBox; pnlSizeCirterias : TPanel; pnlDateCriterias : TPanel; pnlContentCriterias : TPanel; Label3 : TLabel; edtContent : TEdit; chkContentCaseSensitive : TCheckBox; Label4 : TLabel; cbxSizeCriteria : TComboBox; Label5 : TLabel; cbxDateCriteria : TComboBox; Label6 : TLabel; Label7 : TLabel; Label8 : TLabel; Label9 : TLabel; speMinSize : TSpinEdit; speMaxSize : TSpinEdit; edtDateFrom : TDateEdit; edtDateTo : TDateEdit; chkRecursive : TCheckBox; Panel6 : TPanel; Panel7 : TPanel; btnStartSearch : TButton; btnQuit : TButton; lblStatus : TLabel; GroupBox5 : TGroupBox; lbxSearchResult : TListBox; Label10 : TLabel; lblNbFolderFound : TLabel; Label12 : TLabel; lblNbFilesFound : TLabel; chkgAttributs : TGroupBox; chkLookForDirectory : TCheckBox; chkLookForHidden : TCheckBox; chkLookForSystem : TCheckBox; chkLookForArchive : TCheckBox; chkLookForReadOnly : TCheckBox; chkLookForAnyFile : TCheckBox; procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); procedure btnQuitClick(Sender : TObject); procedure btnStartSearchClick(Sender : TObject); private protected FFileFinder : TBZFileFinder; procedure DoOnFileFinderFileFound(Sender : TObject; FileFound : TBZFileInformations); procedure DoOnFileFinderStart(Sender : TObject); procedure DoOnFileFinderCompleted(Sender : TObject; Stats : TBZSearchStatistics); procedure DoOnFileFinderChangeFolder(Sender : TObject; NewPath : String); public end; var MainForm : TMainForm; implementation {$R *.lfm} Uses BZSystem, BZUtils, FileCtrl; { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); begin FFileFinder := TBZFileFinder.Create(Self); FFileFinder.OnFileFound := @DoOnFileFinderFileFound; FFileFinder.OnCompleted := @DoOnFileFinderCompleted; FFileFinder.OnStart := @DoOnFileFinderStart; FFileFinder.OnChangeFolder := @DoOnFileFinderChangeFolder; end; procedure TMainForm.FormDestroy(Sender : TObject); begin FreeAndNil(FFileFinder); end; procedure TMainForm.btnQuitClick(Sender : TObject); begin Screen.Cursor := crHourGlass; Close; Screen.Cursor := crDefault; end; procedure TMainForm.btnStartSearchClick(Sender : TObject); begin FFileFinder.RootPath := edtFolder.Text; FFileFinder.FileMasks.Clear; FFileFinder.FileMasks.Add(edtFileMask.Text); FFileFinder.SearchOptions.IncludeSubfolder := chkRecursive.Checked; FFileFinder.SearchOptions.LookForDirectory := chkLookForDirectory.Checked; FFileFinder.SearchOptions.LookForAnyFile := chkLookForAnyFile.Checked; FFileFinder.SearchOptions.LookForReadOnlyFile := chkLookForReadOnly.Checked; FFileFinder.SearchOptions.LookForHiddenFile := chkLookForHidden.Checked; FFileFinder.SearchOptions.LookForSystemFile := chkLookForSystem.Checked; FFileFinder.SearchOptions.LookForArchiveFile := chkLookForArchive.Checked; btnStartSearch.Enabled := False; FFileFinder.Search; end; procedure TMainForm.DoOnFileFinderFileFound(Sender : TObject; FileFound : TBZFileInformations); var idx : Integer; begin //idx := FFileFinder.SearchResult.Count-1; //lbxSearchResult.Items.Add(FFileFinder.SearchResult.Strings[idx]); lbxSearchResult.Items.Add(FixPathDelimiter(IncludeTrailingPathDelimiter(FileFound.path))+FileFound.Name); Application.ProcessMessages; end; procedure TMainForm.DoOnFileFinderStart(Sender : TObject); begin Screen.Cursor := crHourGlass; lbxSearchResult.Items.Clear; Application.ProcessMessages; lblStatus.Caption := 'Recherche en cours, veuillez patienter quelques instants...' end; procedure TMainForm.DoOnFileFinderCompleted(Sender : TObject; Stats : TBZSearchStatistics); begin btnStartSearch.Enabled := True; Screen.Cursor := crDefault; lblNbFolderFound.Caption := Stats.NbPathFound.ToString; lblNbFilesFound.Caption := Stats.NbFilesFound.ToString; lblStatus.Caption := 'Recherche terminée.' end; procedure TMainForm.DoOnFileFinderChangeFolder(Sender : TObject; NewPath : String); begin lblStatus.Caption := 'Recherche en cours dans : '+ MinimizeName(NewPath, lblStatus.Canvas, lblStatus.ClientWidth - lblStatus.Canvas.TextWidth('Recherche en cours dans : ')); end; end.
(* @created(2019-12-27) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(27/12/2019 : Creation ) ) --------------------------------------------------------------------------------@br ------------------------------------------------------------------------------ Description : Simulation d'un shader GLSL Code source de référence de Wouter Van Nifterick ------------------------------------------------------------------------------ @bold(Notes :) Quelques liens : @unorderedList( @item(http://www.shadertoy.com) @item(http://glslsandbox.com) ) ------------------------------------------------------------------------------@br @bold(Credits :) @unorderedList( @item(J.Delauney (BeanzMaster)) @item(https://github.com/WouterVanNifterick/delphi-shader) ) ------------------------------------------------------------------------------@br LICENCE : GPL/MPL @br ------------------------------------------------------------------------------ *==============================================================================*) unit BZSoftwareShader_FuzzyMandelbrot; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BZClasses, BZMath, BZVectorMath, BZVectorMathUtils, //BZRayMarchMath, BZColors, BZGraphic, BZBitmap, BZCadencer, BZCustomShader; Type { TBZSoftShader_GroundAndDistortPhongSphere } TBZSoftShader_FuzzyMandelbrot = Class(TBZCustomSoftwareShader) protected public Constructor Create; override; Destructor Destroy; override; function Clone : TBZCustomSoftwareShader; override; function ShadePixelFloat:TBZColorVector; override; end; implementation { TBZSoftShader_GroundAndDistortPhongSphere } Constructor TBZSoftShader_FuzzyMandelbrot.Create; begin inherited Create; end; Destructor TBZSoftShader_FuzzyMandelbrot.Destroy; begin inherited Destroy; end; function TBZSoftShader_FuzzyMandelbrot.Clone : TBZCustomSoftwareShader; begin Result := TBZSoftShader_FuzzyMandelbrot.Create; Result.Assign(Self); end; function TBZSoftShader_FuzzyMandelbrot.ShadePixelFloat : TBZColorVector; function ComputePixel(Coord:TBZVector2f; aTime:Single) : TBZColorVector; const iterations : integer = 32; var {$CODEALIGN RECORDMIN=16} vZ, vC, uv, r : TBZVector2f; {$CODEALIGN RECORDMIN=4} color, scale : Single; iteration, i : Integer; begin r.Create(Resolution.X, Resolution.Y); uv := (Coord / r) * 2.0 - 1.0; //resolution Scale := sin(aTime*0.15)*4+2.0; vZ := vec2(0.5,0.5); vZ :=vZ + vec2((sin(iTime*0.25)*1.25)-0.75, cos(iTime*0.15)*0.5); vC := uv * Scale; iteration := 1; for i := 0 to iterations do begin vZ := vec2(vZ.x * vZ.x - vZ.y * vZ.y, 2.0 * vZ.x * vZ.y) + vC; if (vZ.DotProduct(vZ) > 4.0) then begin iteration := i; break; end; end; color := iteration / Iterations; Result.Create(color+0.2, color+0.4, color+0.8, 1.0); end; begin Result := ComputePixel(FragCoords, iTime); end; end.
unit WaitUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type { TWaitForm } TWaitForm = class(TForm) InfoLabel: TLabel; ProgressBar: TProgressBar; CloseBtn: TButton; procedure FormShow(Sender: TObject); private FOnExecute: TNotifyEvent; procedure WMUser(var Msg: TMessage); message WM_USER; public class procedure Execute(const Msg: string; OnExecute: TNotifyEvent); property OnExecute: TNotifyEvent read FOnExecute write FOnExecute; end; var WaitForm: TWaitForm; implementation {$R *.dfm} { TWaitForm } class procedure TWaitForm.Execute(const Msg: string; OnExecute: TNotifyEvent); var WaitForm: TWaitForm; begin WaitForm := TWaitForm.Create(nil); try WaitForm.InfoLabel.Caption := Msg; WaitForm.OnExecute := OnExecute; WaitForm.ShowModal; finally WaitForm.Free; end; end; procedure TWaitForm.FormShow(Sender: TObject); begin PostMessage(Handle, WM_USER, 0, 0); end; procedure TWaitForm.WMUser(var Msg: TMessage); begin if Assigned(OnExecute) then OnExecute(Self); end; end.
unit hcVersionText; interface function GetFileVersionText : string; overload; function GetFileVersionText(const sFileName:string): string; overload; implementation uses SysUtils, Windows; function GetFileVersionText : string; var VerMajor, VerMinor, VerRelease, VerBuild : word; VerInfoSize : DWORD; VerInfo : Pointer; VerValueSize : DWORD; VerValue : PVSFixedFileInfo; Dummy : DWORD; begin VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy); if VerInfoSize = 0 then begin Result := ''; end else begin GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin VerMajor := dwFileVersionMS shr 16; VerMinor := dwFileVersionMS and $FFFF; VerRelease := dwFileVersionLS shr 16; VerBuild := dwFileVersionLS and $FFFF; end; FreeMem(VerInfo, VerInfoSize); Result := Format('%d.%d.%d.%d', [VerMajor, VerMinor, VerRelease, VerBuild]); end; end; function GetFileVersionText(const sFileName :string) : string; var VerMajor, VerMinor, VerRelease, VerBuild : word; VerInfoSize : DWORD; VerInfo : Pointer; VerValueSize : DWORD; VerValue : PVSFixedFileInfo; Dummy : DWORD; begin VerInfoSize := GetFileVersionInfoSize(PChar(sFilename), Dummy); if VerInfoSize = 0 then begin Result := ''; end else begin GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(sFilename), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin VerMajor := dwFileVersionMS shr 16; VerMinor := dwFileVersionMS and $FFFF; VerRelease := dwFileVersionLS shr 16; VerBuild := dwFileVersionLS and $FFFF; end; FreeMem(VerInfo, VerInfoSize); Result := Format('%d.%d.%d.%d', [VerMajor, VerMinor, VerRelease, VerBuild]); end; end; end.
unit Data.Repositories.Repository; interface uses Generics.Collections , Data.Repositories.IRepository , Aurelius.Drivers.Interfaces , Aurelius.Engine.ObjectManager ; type TRepository<TEntity: class; TKey> = class abstract (TInterfacedObject, IRepository<TEntity, TKey>) protected FObjectManager: TObjectManager; public constructor Create(DBConnFac: IDBConnectionFactory); destructor Destroy(); reintroduce; virtual; function GetAll(): TList<TEntity>; virtual; function Get(Id: TKey): TEntity; virtual; procedure Add(Entity: TEntity); virtual; procedure Remove(Entity: TEntity); virtual; procedure Update(Entity: TEntity); virtual; end; implementation { TRepository<TEntity, TKey> } constructor TRepository<TEntity, TKey>.Create(DBConnFac: IDBConnectionFactory); begin FObjectManager := TObjectManager.Create(DBConnFac.CreateConnection); end; destructor TRepository<TEntity, TKey>.Destroy; begin FObjectManager.Free; inherited; end; procedure TRepository<TEntity, TKey>.Add(Entity: TEntity); begin FObjectManager.Save(Entity); FObjectManager.Flush; end; function TRepository<TEntity, TKey>.Get(Id: TKey): TEntity; begin // Result := FObjectManager.Find<TEntity>(Id); end; function TRepository<TEntity, TKey>.GetAll: TList<TEntity>; begin Result := FObjectManager.FindAll<TEntity>; end; procedure TRepository<TEntity, TKey>.Remove(Entity: TEntity); begin FObjectManager.Remove(Entity); FObjectManager.Flush; end; procedure TRepository<TEntity, TKey>.Update(Entity: TEntity); begin FObjectManager.Update(Entity); FObjectManager.Flush; end; end.
{$J+} {Writable constants} unit ExTbl09U; interface uses WinProcs, WinTypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OvcTCBmp, OvcTCGly, OvcTCBox, OvcTCmmn, OvcTCell, OvcTCStr, OvcTCEdt, OvcBase, OvcTable, StdCtrls, OvcUser, OvcData, OvcTCBEF, OvcTCPic, OvcPF; const MyMessage1 = WM_USER + 1; type MyDataRecord = record TF1 : String[10]; end; TForm1 = class(TForm) OvcTable1: TOvcTable; OvcController1: TOvcController; PF1: TOvcTCPictureField; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OvcTable1BeginEdit(Sender: TObject; RowNum: Longint; ColNum: Integer; var AllowIt: Boolean); private { Private declarations } public { Public declarations } procedure OnMyMessage1(var Msg : TMessage); message MyMessage1; end; var Form1: TForm1; MyData : array [1..9] of MyDataRecord; MyUserData : TOvcUserData; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var I, J : Integer; begin MyUserData := TOvcUserData.Create; MyUserData.UserCharSet[pmUser1] := ['A'..'C', '0'..'9']; Randomize; for I := 1 to 9 do with MyData[I] do begin TF1[0] := Chr(10); for J := 1 to 5 do TF1[J] := Chr(Ord('A') + (I - 1) mod 3); for J := 6 to 10 do TF1[J] := IntToStr(I)[1]; end; end; procedure TForm1.OvcTable1GetCellData(Sender: TObject; RowNum: Longint; ColNum: Integer; var Data: Pointer; Purpose: TOvcCellDataPurpose); begin Data := nil; if (RowNum > 0) and (RowNum < 10) then begin case ColNum of 1 : Data := @MyData[RowNum].TF1; end; end; end; procedure TForm1.OnMyMessage1(var Msg : TMessage); begin (PF1.CellEditor as TOvcPictureField).UserData := MyUserData; end; procedure TForm1.OvcTable1BeginEdit(Sender: TObject; RowNum: Longint; ColNum: Integer; var AllowIt: Boolean); begin { OnBeginEdit is called before the CellEditor exists, therefore you must post a message so that the cell can be created before trying to set the UserData property } AllowIt := True; if ColNum = 1 then PostMessage(Handle, MyMessage1, 0 , 0); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin MyUserData.Free; end; end.
// CORTE DE CONTROL // TOMEMOS DE EJEMPLO EL EJERCICIO 5 DE LA PRACTICA Realizar un programa que lea información de autos que están a la venta en una concesionaria. De cada auto se lee: marca, modelo y precio. La lectura finaliza cuando se ingresa la marca “ZZZ” que no debe procesarse. La información se ingresa ordenada por marca. Se pide calcular e informar: a. El precio promedio por marca. b. Marca y modelo del auto más caro. //ESTRUCTURA BASICA DEL CORTE DE CONTROL leer(auto); while (auto.marca <> 'ZZZ') do begin marcaActual := auto.marca while ( (auto.marca <> 'ZZZ') AND (marcaActual = auto.marca) ) do begin leer(auto); end; end; // A PARTIR DE LA ESTRUCTURA BÁSICA, TENEMOS QUE ENTENDER QUE SIGNIFICA CADA UNA DE LAS ITERACIONES DE LOS WHILE leer(auto); // SECTOR 1- ACA VAN TODAS LAS VARIABLES QUE SE USAN PARA CONTABILIZAR LOS TOTALES ENTRE TODOS LOS DATOS LEIDOS while (auto.marca <> 'ZZZ') do begin marcaActual := auto.marca // SECTOR 2- ACA VAN TODAS LAS VARIABLES QUE SE DEBEN INICIALIZAR CUANDO CAMBIA DE MARCA (OSEA CUANDO TE PIDEN ALGO POR MARCA) while ( (auto.marca <> 'ZZZ') AND (marcaActual = auto.marca) ) do begin // SECTOR 3- ACA SE VAN A ESTAR PROCESANDO TODOS LOS DATOS (EN ESTE CASO TODOS LOS AUTOS) leer(auto); end; {CUANDO SALE DEL WHILE INTERNO SIGNIFICA QUE CAMBIO DE MARCA} // SECTOR 4- ACA VA TODO LO QUE ME PIDEN ACTUALIZAR O INFORMAR POR MARCA end; {CUANDO SALE DEL WHILE GENERAL SIGNIFICA QUE YA NO LEE MAS DATOS} // SECTOR 5- ACA INFORMO TODO LO QUE ME PIDEN EN GENERAL Y SIN QUE DEPENDA DEL CORTE DE CONTROL DE MARCA POR EJEMPLO: si el ejercicio pide "a. El precio promedio por marca." - al decir por marca, sabemos que vamos a tener que informar en el SECTOR 4 - al pedir calcular precio promedio, necesitamos: - variable que sume los precios - variable que cuente el total de autos por marca estas variables entonces tendremos que incrementarlas en el SECTOR 3 - importante! donde inicializo estas variables? al pedir POR MARCA, vamos a inicializarlas en el SECTOR 2 POR EJEMPLO: si el ejercicio pide "b. Marca y modelo del auto más caro." - al no estar pidiendo algo especificamente por marca, sabemos que en el SECTOR 2 seguro no vamos a poner nada - claramente vamos a tener que calcular un maximo comparando por precio - necesito una variable max - necesito una variable marcaMax - necesito una variable modeloMax - estas variables al ser generales para todos los datos del programa, se inicializan en el SECTOR 1 - al estar pidiendo marca y modelo en general, voy a tener que usar el SECTOR 3 para ir actualizando - por ultimo, para informar, debemos hacerlo una vez que terminamos de procesar todos los datos, por lo tanto lo hacemos en el SECTOR 5 //PROXIMAMENTE PARTE 3
unit ClientProgressBarForm; interface uses Forms, StdCtrls, Classes, Controls, ComCtrls; type TfrmProgressBar = class(TForm) anmWait: TAnimate; Lbl: TLabel; private { Private declarations } public { Public declarations } procedure InitProgressBar(const AMessage: string; Avi: TCommonAVI); end; var frmProgressBar: TfrmProgressBar; implementation {$R *.DFM} procedure TFrmProgressBar.InitProgressBar(const AMessage: string; Avi: TCommonAVI); begin frmProgressBar.Lbl.Caption:=AMessage; frmProgressBar.anmWait.CommonAVI := Avi; frmProgressBar.anmWait.Active:=true; frmProgressBar.Show(); frmProgressBar.Update(); end; end.
unit Unit16; {==============================================================} { Example how to show uptime of system and when system started } { Platform Delphi 5 } { (c) Anatoly Podgoretsky, 2002 } { anatoly@podgoretsky.com } { http://www.podgoretsky.com } {==============================================================} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShellApi, ComObj, ExtCtrls, Buttons, ComCtrls; type TUptimeForm = class(TForm) Timer: TTimer; PageControl: TPageControl; TabSheet2: TTabSheet; GroupBox2: TGroupBox; GroupBox3: TGroupBox; BitBtn1: TBitBtn; StartLabel: TLabel; UptimeLabel: TLabel; BitBtn2: TBitBtn; BitBtn3: TBitBtn; BitBtn4: TBitBtn; procedure TimerTimer(Sender: TObject); procedure CloseButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BitBtn3Click(Sender: TObject); procedure BitBtn4Click(Sender: TObject); end; var UptimeForm: TUptimeForm; implementation {$R *.DFM} const MS = 1000; HOURSPERDAY = 24; MINPERHOUR = 60; SECPERMIN = 60; SECPERHOUR = MINPERHOUR * SECPERMIN; SECPERDAY = HOURSPERDAY * SECPERHOUR; procedure TUptimeForm.FormShow(Sender: TObject); begin StartLabel.Caption := DateTimeToStr(Now - GetTickCount / (SECPERDAY*MS)); TimerTimer(Self); end; procedure TUptimeForm.TimerTimer(Sender: TObject); var Uptime : Cardinal; TmpStr : string; begin Uptime := GetTickCount div MS; // DAYS TmpStr := IntToStr(Uptime div SECPERDAY) + ' giorni '; UpTime := Uptime mod SECPERDAY; // HOURS TmpStr := TmpStr + IntToStr(Uptime div SECPERHOUR) + ' ore '; UpTime := Uptime mod SECPERHOUR; // MINUTES TmpStr := TmpStr + IntToStr(Uptime div SECPERMIN) + ' minuti '; UpTime := Uptime mod SECPERMIN; // SECONDS TmpStr := TmpStr + IntToStr(Uptime) + ' secondi'; // RESULY UptimeLabel.Caption := TmpStr; end; procedure TUptimeForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TUptimeForm.BitBtn2Click(Sender: TObject); begin ShellExecute (HWND(nil), 'open', 'taskmgr', '', '', SW_SHOWNORMAL); end; procedure TUptimeForm.BitBtn1Click(Sender: TObject); begin Close; end; procedure TUptimeForm.BitBtn3Click(Sender: TObject); var shell: Variant; begin shell := CreateOleObject('Shell.Application'); shell.ShutdownWindows; end; procedure TUptimeForm.BitBtn4Click(Sender: TObject); var FullProgPath: PChar; begin FullProgPath := PChar(Application.ExeName); WinExec(FullProgPath, SW_SHOW); Application.Terminate; end; end.
{********************************************************************************************************} { } { XML Data Binding } { } { Generated on: 22/03/2010 17:16:46 } { Generated from: C:\Documents and Settings\Radecek\Desktop\Active\WMSReader\WMSReaderConfig.xml } { Settings stored in: C:\Documents and Settings\Radecek\Desktop\Active\WMSReader\WMSReaderConfig.xdb } { } {********************************************************************************************************} unit WMSReaderConfig; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLWMSReaderType = interface; IXMLConfigType = interface; IXMLWMSServerType = interface; IXMLFormParamsType = interface; { IXMLWMSReaderType } IXMLWMSReaderType = interface(IXMLNode) ['{37731752-4401-4AA3-95F9-1F72B6E6453F}'] { Property Accessors } function Get_Config: IXMLConfigType; function Get_FormParams: IXMLFormParamsType; { Methods & Properties } property Config: IXMLConfigType read Get_Config; property FormParams: IXMLFormParamsType read Get_FormParams; end; { IXMLConfigType } IXMLConfigType = interface(IXMLNodeCollection) ['{37C1B974-9AFE-44D8-810F-020713FC9B9B}'] { Property Accessors } function Get_WMSServer(Index: Integer): IXMLWMSServerType; { Methods & Properties } function Add: IXMLWMSServerType; function Insert(const Index: Integer): IXMLWMSServerType; property WMSServer[Index: Integer]: IXMLWMSServerType read Get_WMSServer; default; end; { IXMLWMSServerType } IXMLWMSServerType = interface(IXMLNode) ['{523EA2DC-83DB-47B7-8A02-C703120A2347}'] { Property Accessors } function Get_Name: WideString; function Get_Url: WideString; procedure Set_Name(Value: WideString); procedure Set_Url(Value: WideString); { Methods & Properties } property Name: WideString read Get_Name write Set_Name; property Url: WideString read Get_Url write Set_Url; end; { IXMLFormParamsType } IXMLFormParamsType = interface(IXMLNode) ['{5189D6D3-368A-46B0-8130-4839F059C9E9}'] { Property Accessors } function Get_Width: Integer; function Get_Height: Integer; function Get_ShowProperties: Integer; function Get_ShowPreview: Integer; function Get_SelectedPanelWidth: Integer; function Get_PropertiesPanelWidth: Integer; procedure Set_Width(Value: Integer); procedure Set_Height(Value: Integer); procedure Set_ShowProperties(Value: Integer); procedure Set_ShowPreview(Value: Integer); procedure Set_SelectedPanelWidth(Value: Integer); procedure Set_PropertiesPanelWidth(Value: Integer); { Methods & Properties } property Width: Integer read Get_Width write Set_Width; property Height: Integer read Get_Height write Set_Height; property ShowProperties: Integer read Get_ShowProperties write Set_ShowProperties; property ShowPreview: Integer read Get_ShowPreview write Set_ShowPreview; property SelectedPanelWidth: Integer read Get_SelectedPanelWidth write Set_SelectedPanelWidth; property PropertiesPanelWidth: Integer read Get_PropertiesPanelWidth write Set_PropertiesPanelWidth; end; { Forward Decls } TXMLWMSReaderType = class; TXMLConfigType = class; TXMLWMSServerType = class; TXMLFormParamsType = class; { TXMLWMSReaderType } TXMLWMSReaderType = class(TXMLNode, IXMLWMSReaderType) protected { IXMLWMSReaderType } function Get_Config: IXMLConfigType; function Get_FormParams: IXMLFormParamsType; public procedure AfterConstruction; override; end; { TXMLConfigType } TXMLConfigType = class(TXMLNodeCollection, IXMLConfigType) protected { IXMLConfigType } function Get_WMSServer(Index: Integer): IXMLWMSServerType; function Add: IXMLWMSServerType; function Insert(const Index: Integer): IXMLWMSServerType; public procedure AfterConstruction; override; end; { TXMLWMSServerType } TXMLWMSServerType = class(TXMLNode, IXMLWMSServerType) protected { IXMLWMSServerType } function Get_Name: WideString; function Get_Url: WideString; procedure Set_Name(Value: WideString); procedure Set_Url(Value: WideString); end; { TXMLFormParamsType } TXMLFormParamsType = class(TXMLNode, IXMLFormParamsType) protected { IXMLFormParamsType } function Get_Width: Integer; function Get_Height: Integer; function Get_ShowProperties: Integer; function Get_ShowPreview: Integer; function Get_SelectedPanelWidth: Integer; function Get_PropertiesPanelWidth: Integer; procedure Set_Width(Value: Integer); procedure Set_Height(Value: Integer); procedure Set_ShowProperties(Value: Integer); procedure Set_ShowPreview(Value: Integer); procedure Set_SelectedPanelWidth(Value: Integer); procedure Set_PropertiesPanelWidth(Value: Integer); end; { Global Functions } function GetWMSReader(Doc: IXMLDocument): IXMLWMSReaderType; function LoadWMSReader(const FileName: WideString): IXMLWMSReaderType; function NewWMSReader: IXMLWMSReaderType; const TargetNamespace = ''; implementation { Global Functions } function GetWMSReader(Doc: IXMLDocument): IXMLWMSReaderType; begin Result := Doc.GetDocBinding('WMSReader', TXMLWMSReaderType, TargetNamespace) as IXMLWMSReaderType; end; function LoadWMSReader(const FileName: WideString): IXMLWMSReaderType; begin Result := LoadXMLDocument(FileName).GetDocBinding('WMSReader', TXMLWMSReaderType, TargetNamespace) as IXMLWMSReaderType; end; function NewWMSReader: IXMLWMSReaderType; begin Result := NewXMLDocument.GetDocBinding('WMSReader', TXMLWMSReaderType, TargetNamespace) as IXMLWMSReaderType; end; { TXMLWMSReaderType } procedure TXMLWMSReaderType.AfterConstruction; begin RegisterChildNode('Config', TXMLConfigType); RegisterChildNode('FormParams', TXMLFormParamsType); inherited; end; function TXMLWMSReaderType.Get_Config: IXMLConfigType; begin Result := ChildNodes['Config'] as IXMLConfigType; end; function TXMLWMSReaderType.Get_FormParams: IXMLFormParamsType; begin Result := ChildNodes['FormParams'] as IXMLFormParamsType; end; { TXMLConfigType } procedure TXMLConfigType.AfterConstruction; begin RegisterChildNode('WMSServer', TXMLWMSServerType); ItemTag := 'WMSServer'; ItemInterface := IXMLWMSServerType; inherited; end; function TXMLConfigType.Get_WMSServer(Index: Integer): IXMLWMSServerType; begin Result := List[Index] as IXMLWMSServerType; end; function TXMLConfigType.Add: IXMLWMSServerType; begin Result := AddItem(-1) as IXMLWMSServerType; end; function TXMLConfigType.Insert(const Index: Integer): IXMLWMSServerType; begin Result := AddItem(Index) as IXMLWMSServerType; end; { TXMLWMSServerType } function TXMLWMSServerType.Get_Name: WideString; begin Result := AttributeNodes['name'].Text; end; procedure TXMLWMSServerType.Set_Name(Value: WideString); begin SetAttribute('name', Value); end; function TXMLWMSServerType.Get_Url: WideString; begin Result := AttributeNodes['url'].Text; end; procedure TXMLWMSServerType.Set_Url(Value: WideString); begin SetAttribute('url', Value); end; { TXMLFormParamsType } function TXMLFormParamsType.Get_Width: Integer; begin Result := AttributeNodes['Width'].NodeValue; end; procedure TXMLFormParamsType.Set_Width(Value: Integer); begin SetAttribute('Width', Value); end; function TXMLFormParamsType.Get_Height: Integer; begin Result := AttributeNodes['Height'].NodeValue; end; procedure TXMLFormParamsType.Set_Height(Value: Integer); begin SetAttribute('Height', Value); end; function TXMLFormParamsType.Get_ShowProperties: Integer; begin Result := AttributeNodes['ShowProperties'].NodeValue; end; procedure TXMLFormParamsType.Set_ShowProperties(Value: Integer); begin SetAttribute('ShowProperties', Value); end; function TXMLFormParamsType.Get_ShowPreview: Integer; begin Result := AttributeNodes['ShowPreview'].NodeValue; end; procedure TXMLFormParamsType.Set_ShowPreview(Value: Integer); begin SetAttribute('ShowPreview', Value); end; function TXMLFormParamsType.Get_SelectedPanelWidth: Integer; begin Result := AttributeNodes['SelectedPanelWidth'].NodeValue; end; procedure TXMLFormParamsType.Set_SelectedPanelWidth(Value: Integer); begin SetAttribute('SelectedPanelWidth', Value); end; function TXMLFormParamsType.Get_PropertiesPanelWidth: Integer; begin Result := AttributeNodes['PropertiesPanelWidth'].NodeValue; end; procedure TXMLFormParamsType.Set_PropertiesPanelWidth(Value: Integer); begin SetAttribute('PropertiesPanelWidth', Value); end; end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Model relacionado à tabela [COLABORADOR] The MIT License Copyright: Copyright (C) 2021 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 (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit Colaborador; interface uses MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TColaborador = class(TModelBase) private FId: Integer; FNome: string; FCpf: string; FTelefone: string; FCelular: string; FEmail: string; FComissaoVista: Extended; FComissaoPrazo: Extended; FNivelAutorizacao: string; FEntregadorVeiculo: string; public // procedure ValidarInsercao; override; // procedure ValidarAlteracao; override; // procedure ValidarExclusao; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('NOME')] [MVCNameAsAttribute('nome')] property Nome: string read FNome write FNome; [MVCColumnAttribute('CPF')] [MVCNameAsAttribute('cpf')] property Cpf: string read FCpf write FCpf; [MVCColumnAttribute('TELEFONE')] [MVCNameAsAttribute('telefone')] property Telefone: string read FTelefone write FTelefone; [MVCColumnAttribute('CELULAR')] [MVCNameAsAttribute('celular')] property Celular: string read FCelular write FCelular; [MVCColumnAttribute('EMAIL')] [MVCNameAsAttribute('email')] property Email: string read FEmail write FEmail; [MVCColumnAttribute('COMISSAO_VISTA')] [MVCNameAsAttribute('comissaoVista')] property ComissaoVista: Extended read FComissaoVista write FComissaoVista; [MVCColumnAttribute('COMISSAO_PRAZO')] [MVCNameAsAttribute('comissaoPrazo')] property ComissaoPrazo: Extended read FComissaoPrazo write FComissaoPrazo; [MVCColumnAttribute('NIVEL_AUTORIZACAO')] [MVCNameAsAttribute('nivelAutorizacao')] property NivelAutorizacao: string read FNivelAutorizacao write FNivelAutorizacao; [MVCColumnAttribute('ENTREGADOR_VEICULO')] [MVCNameAsAttribute('entregadorVeiculo')] property EntregadorVeiculo: string read FEntregadorVeiculo write FEntregadorVeiculo; end; implementation { TColaborador } end.
unit UManagerPageControl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, UxTheme, Themes, Math; const TabSheetPrefix = 'TabSheet'; type TManagerPageControlCloseButton = class(TObject) private published class procedure AssignEvents(var PageControl: TPageControl); class procedure CreateCloseButtonInNewTab(var PageControl: TPageControl); class procedure EventDrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); class procedure EventMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); class procedure EventMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); class procedure EventMouseLeave(Sender: TObject); class procedure EventMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); class procedure CriarAba(ClasseForm: TFormClass; var PageControl: TPageControl; Index: Integer); class function ExisteAba(PageControl: TPageControl; ClasseForm: TFormClass): Boolean; class procedure FecharAba(PageControl: TPageControl; NomeAba: String); end; var FCloseButtonsRect: array of TRect; FCloseButtonMouseDownIndex: Integer; FCloseButtonShowPushed: Boolean; implementation { http://stackoverflow.com/questions/2201850/how-to-implement-a-close-button-for-a-ttabsheet-of-a-tpagecontrol } class procedure TManagerPageControlCloseButton.AssignEvents(var PageControl: TPageControl); begin PageControl.OnDrawTab := TManagerPageControlCloseButton.EventDrawTab; PageControl.OnMouseDown := TManagerPageControlCloseButton.EventMouseDown; PageControl.OnMouseMove := TManagerPageControlCloseButton.EventMouseMove; PageControl.OnMouseLeave := TManagerPageControlCloseButton.EventMouseLeave; PageControl.OnMouseUp := TManagerPageControlCloseButton.EventMouseUp; PageControl.TabWidth := 150; PageControl.TabHeight := 20; PageControl.OwnerDraw := True; end; class procedure TManagerPageControlCloseButton.CreateCloseButtonInNewTab(var PageControl: TPageControl); var I: Integer; begin // should be done on every change of the page count SetLength(FCloseButtonsRect, PageControl.PageCount); FCloseButtonMouseDownIndex := -1; for I := 0 to Length(FCloseButtonsRect) - 1 do FCloseButtonsRect[I] := Rect(0, 0, 0, 0); PageControl.Repaint; { adicionado 20/08/2014 } end; class procedure TManagerPageControlCloseButton.EventDrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); var CloseBtnSize: Integer; PageControl: TPageControl; TabCaption: TPoint; CloseBtnRect: TRect; CloseBtnDrawState: Cardinal; CloseBtnDrawDetails: TThemedElementDetails; begin PageControl := TPageControl(Control); if InRange(TabIndex, 0, Length(FCloseButtonsRect) - 1) then begin CloseBtnSize := 14; TabCaption.Y := Rect.Top + 3; if Active then begin CloseBtnRect.Top := Rect.Top + 4; CloseBtnRect.Right := Rect.Right - 5; TabCaption.X := Rect.Left + 6; end else begin CloseBtnRect.Top := Rect.Top + 3; CloseBtnRect.Right := Rect.Right - 5; TabCaption.X := Rect.Left + 3; end; CloseBtnRect.Bottom := CloseBtnRect.Top + CloseBtnSize; CloseBtnRect.Left := CloseBtnRect.Right - CloseBtnSize; FCloseButtonsRect[TabIndex] := CloseBtnRect; PageControl.Canvas.FillRect(Rect); PageControl.Canvas.TextOut(TabCaption.X, TabCaption.Y, PageControl.Pages[TabIndex].Caption); if not(UseThemes) then begin if (FCloseButtonMouseDownIndex = TabIndex) and FCloseButtonShowPushed then CloseBtnDrawState := DFCS_CAPTIONCLOSE + DFCS_PUSHED else CloseBtnDrawState := DFCS_CAPTIONCLOSE; Windows.DrawFrameControl(PageControl.Canvas.Handle, FCloseButtonsRect[TabIndex], DFC_CAPTION, CloseBtnDrawState); end else begin Dec(FCloseButtonsRect[TabIndex].Left); if (FCloseButtonMouseDownIndex = TabIndex) and FCloseButtonShowPushed then CloseBtnDrawDetails := ThemeServices.GetElementDetails(twCloseButtonPushed) else CloseBtnDrawDetails := ThemeServices.GetElementDetails(twCloseButtonNormal); ThemeServices.DrawElement(PageControl.Canvas.Handle, CloseBtnDrawDetails, FCloseButtonsRect[TabIndex]); end; end; end; class procedure TManagerPageControlCloseButton.EventMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; PageControl: TPageControl; begin PageControl := TPageControl(Sender); if (Button = mbLeft) then begin for I := 0 to Length(FCloseButtonsRect) - 1 do begin if (PtInRect(FCloseButtonsRect[I], Point(X, Y))) then begin FCloseButtonMouseDownIndex := I; FCloseButtonShowPushed := True; PageControl.Repaint; end; end; end; end; class procedure TManagerPageControlCloseButton.EventMouseLeave(Sender: TObject); var PageControl: TPageControl; begin PageControl := TPageControl(Sender); FCloseButtonShowPushed := False; PageControl.Repaint; end; class procedure TManagerPageControlCloseButton.EventMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var PageControl: TPageControl; Inside: Boolean; begin PageControl := TPageControl(Sender); if (ssLeft in Shift) and (FCloseButtonMouseDownIndex >= 0) then begin Inside := PtInRect(FCloseButtonsRect[FCloseButtonMouseDownIndex], Point(X, Y)); if FCloseButtonShowPushed <> Inside then begin FCloseButtonShowPushed := Inside; PageControl.Repaint; end; end; end; class procedure TManagerPageControlCloseButton.EventMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var PageControl: TPageControl; TabSheet: TTabSheet; I: Integer; Componente: TComponent; begin PageControl := TPageControl(Sender); if (Button = mbLeft) and (FCloseButtonMouseDownIndex >= 0) then begin if (PtInRect(FCloseButtonsRect[FCloseButtonMouseDownIndex], Point(X, Y))) then begin // ShowMessage('Button ' + IntToStr(FCloseButtonMouseDownIndex + 1) + ' pressed!'); // PageControl.Pages[PageControl.ActivePageIndex].Free; TabSheet := PageControl.Pages[PageControl.ActivePageIndex]; for I := (TabSheet.ComponentCount - 1) downto 0 do begin Componente := TComponent(TabSheet.Components[I]); FreeAndNil(Componente); end; FreeAndNil(TabSheet); FCloseButtonMouseDownIndex := -1; PageControl.Repaint; end; end; end; class procedure TManagerPageControlCloseButton.CriarAba(ClasseForm: TFormClass; var PageControl: TPageControl; Index: Integer); var { http: // www.lucianopimenta.com/post.aspx?id=171 } TabSheet: TTabSheet; Form: TForm; begin TabSheet := TTabSheet.Create(PageControl); Form := ClasseForm.Create(TabSheet); TabSheet.PageControl := PageControl; TabSheet.Caption := Form.Caption; TabSheet.Name := TabSheetPrefix + Form.ClassName; TabSheet.ImageIndex := Index; // =============================================== { Form.Align := alClient; } Form.Position := poMainFormCenter; // =============================================== Form.BorderStyle := bsNone; { Form.BorderStyle := bsSingle; Form.BorderIcons := [biHelp]; } // =============================================== Form.Parent := TabSheet; Form.Show; PageControl.ActivePage := TabSheet; TManagerPageControlCloseButton.CreateCloseButtonInNewTab(PageControl); end; class function TManagerPageControlCloseButton.ExisteAba(PageControl: TPageControl; ClasseForm: TFormClass): Boolean; var I: Integer; Aba: TTabSheet; begin Result := False; for I := 0 to PageControl.PageCount - 1 do begin if (PageControl.Pages[I].Name = TabSheetPrefix + ClasseForm.ClassName) then begin Aba := PageControl.Pages[I]; PageControl.ActivePage := Aba; Result := True; Break; end; end; end; class procedure TManagerPageControlCloseButton.FecharAba(PageControl: TPageControl; NomeAba: String); var I: Integer; Aba: TTabSheet; begin for I := 0 to PageControl.PageCount - 1 do begin if (PageControl.Pages[I].Caption = NomeAba) then begin Aba := PageControl.Pages[I]; Aba.Destroy; PageControl.ActivePageIndex := 0; Break; end; end; end; end.
unit CompareProgressFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls; type TCompareProgressForm = class(TForm) Animate1: TAnimate; BitBtn1: TBitBtn; ProgressBar1: TProgressBar; Timer1: TTimer; procedure Timer1Timer(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var CompareProgressForm: TCompareProgressForm; implementation uses MainFormUnit; {$R *.dfm} procedure TCompareProgressForm.Timer1Timer(Sender: TObject); // Mise à jour des informations affichées begin if Visible then begin ProgressBar1.Position:=Round(MainForm.CompareProgress*1000); Caption:=Format('Looking for similar images (%d%% complete)...',[Round(100*MainForm.CompareProgress)]); end; end; procedure TCompareProgressForm.FormShow(Sender: TObject); begin Animate1.Active:=True; end; end.
unit MiscComponentsReg; interface procedure Register; implementation // {$R MiscComponentsReg.dcr} uses Classes, cmpRunOnce, cmpPersistentPosition, cmpNTAboutBox, cmpHyperlinkButton, cmpExSplitter, cmpMRUList, cmpThemedScrollBox, cmpCWRichEdit, cmpNewsRichEdit, cmpRuler, cmpSplitterPanel, cmpHexDump, cmpPersistentOptions, cmpIniFilePersistentOptions, cmpRegistryPersistentOptions, cmpXMLPersistentOptions, cmpPropertyListBox, cmpSizingPageControl, cmpColorSelector, cmpExWebBrowser, cmpCountryComboBox; (* cmpMessageDisplay; cmpSpellChecker, cmpCWSpellChecker, cmpTexturedPanel, cmpFileCopier, cmpTextDisplay, CustomAlignPanel, cmpSuDoku, cmpExToolbar, cmpUserDatabase, ExCoolBar, cmpExplorerTree, cmpCountryComboBox; *) procedure Register; begin RegisterComponents ('Colin Wilson''s Components', [ TRunOnce, TPersistentPosition, TNTAboutBox, THyperlinkButton, TExSplitter, TMRUList, TThemedScrollBox, TExRichEdit, TNewsRichEdit, TRuler, TSplitterPanel, THexDump, TPersistentOptions, TRegistryPersistentOptions, TIniFilePersistentOptions, TXMLPersistentOptions, TPropertyListBox, TUniPersistentOptions, TColorSelector, TSizingPageControl, TExWebBrowser, TCountryComboBox (* TMessageDisplay, TSpellChecker, TCWSpellChecker, TTexturedPanel, TFileCopier, TTextDisplay, TCustomAlignPanel, TSuDoku, TExToolbar, TUserDatabase, TExCoolBar, TExplorerTree, TCountryComboBox*) ]); end; end.
unit NoteSampleMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, XLSReadWriteII, Spin, StdCtrls; type TForm2 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; memNote: TMemo; Label1: TLabel; Label2: TLabel; Label3: TLabel; seCol: TSpinEdit; seRow: TSpinEdit; Label4: TLabel; XLS: TXLSReadWriteII; Label5: TLabel; edCellText: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.DFM} procedure TForm2.Button1Click(Sender: TObject); begin with XLS.Sheets[0].Notes.Add do begin CellCol := seCol.Value - 1; CellRow := seRow.Value - 1; Text.Assign(memNote.Lines); end; if edCellText.Text <> '' then XLS.Sheets[0].AsString[seCol.Value - 1,seRow.Value - 1] := edCellText.Text; memNote.Clear; end; procedure TForm2.Button2Click(Sender: TObject); begin XLS.Filename := 'NoteSample.xls'; XLS.Write; end; procedure TForm2.Button3Click(Sender: TObject); begin Close; end; end.
unit EmployeePoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, Employee; type // для своих сотрудников TPostDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; // для своих сотрудников TEmployeeDataPoster = class(TImplementedDataPoster) private FAllPosts: TPosts; procedure SetAllPosts(const Value: TPosts); public property AllPosts: TPosts read FAllPosts write SetAllPosts; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; // для внешних сотрудников TEmployeeOutsideDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils; { TEmployeeDataPoster } constructor TEmployeeDataPoster.Create; begin inherited; Options := []; DataSourceString := 'VW_EMPLOYEE'; DataDeletionString := ''; DataPostString := ''; KeyFieldNames := 'EMPLOYEE_ID'; FieldNames := 'EMPLOYEE_ID, VCH_EMPLOYEE_FULL_NAME, POST_ID'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_EMPLOYEE_FULL_NAME'; end; function TEmployeeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TEmployeeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TEmployee; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TEmployee; o.ID := ds.FieldByName('EMPLOYEE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_EMPLOYEE_FULL_NAME').AsString); o.Post := FAllPosts.ItemsByID[ds.FieldByName('POST_ID').AsInteger] as TPost; ds.Next; end; ds.First; end; end; function TEmployeeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; { TOutsideEmployeeDataPoster } constructor TEmployeeOutsideDataPoster.Create; begin inherited; Options := [soKeyInsert]; DataSourceString := 'TBL_EMPLOYEE_OUTSIDE'; DataDeletionString := 'TBL_EMPLOYEE_OUTSIDE'; DataPostString := 'SPD_ADD_EMPLOYEE_OUTSIDE'; KeyFieldNames := 'EMPLOYEE_OUTSIDE_ID'; FieldNames := 'EMPLOYEE_OUTSIDE_ID, VCH_EMPLOYEE_OUTSIDE_FULL_NAME'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_EMPLOYEE_OUTSIDE_FULL_NAME'; end; function TEmployeeOutsideDataPoster.DeleteFromDB( AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TEmployeeOutsideDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TEmployeeOutside; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TEmployeeOutside; o.ID := ds.FieldByName('EMPLOYEE_OUTSIDE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_EMPLOYEE_OUTSIDE_FULL_NAME').AsString); ds.Next; end; ds.First; end; end; function TEmployeeOutsideDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; eo: TEmployeeOutside; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); eo := AObject as TEmployeeOutside; ds.FieldByName('EMPLOYEE_OUTSIDE_ID').Value := eo.ID; ds.FieldByName('VCH_EMPLOYEE_OUTSIDE_FULL_NAME').Value := trim(eo.Name); ds.Post; eo.ID := ds.FieldByName('EMPLOYEE_OUTSIDE_ID').AsInteger; end; procedure TEmployeeDataPoster.SetAllPosts(const Value: TPosts); begin if FAllPosts <> Value then FAllPosts := Value; end; { TPostDataPoster } constructor TPostDataPoster.Create; begin inherited; Options := []; DataSourceString := 'TBL_POST'; DataDeletionString := ''; DataPostString := ''; KeyFieldNames := 'POST_ID'; FieldNames := 'POST_ID, VCH_POST'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_POST'; end; function TPostDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TPostDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TPost; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TPost; o.ID := ds.FieldByName('POST_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_POST').AsString); ds.Next; end; ds.First; end; end; function TPostDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
unit LuaClass; //Handles some of the common used class code {$mode delphi} interface uses Classes, SysUtils, controls, lua, lauxlib, lualib, math, AvgLvlTree, syncobjs; type TAddMetaDataFunction=procedure(L: PLua_state; metatable: integer; userdata: integer ); type TRecordEntry=record name: string; getf: lua_CFunction; setf: lua_CFunction; end; TRecordEntries=class private list: array of TRecordEntry; function getEntry(index: integer): TRecordEntry; procedure setEntry(index: integer; e: TRecordEntry); function getCount: integer; public procedure add(r: TRecordEntry); procedure clear; property Items[Index: Integer]: TRecordEntry read getEntry write setEntry; default; property Count: integer read getCount; end; function luaclass_createMetaTable(L: Plua_State;garbagecollectable: boolean=false): integer; procedure luaclass_addClassFunctionToTable(L: PLua_State; metatable: integer; userdata: integer; functionname: string; f: lua_CFunction); procedure luaclass_addPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; getfunction: lua_CFunction; setfunction: lua_CFunction); procedure luaclass_setDefaultArrayProperty(L: PLua_State; metatable: integer; userdata: integer; getf,setf: lua_CFunction); procedure luaclass_setDefaultStringArrayProperty(L: PLua_State; metatable: integer; userdata: integer; getf,setf: lua_CFunction); procedure luaclass_addArrayPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; getf: lua_CFunction; setf: lua_CFunction=nil); procedure luaclass_addRecordPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; RecordEntries: TRecordEntries); procedure luaclass_setAutoDestroy(L: PLua_State; metatable: integer; state: boolean); function luaclass_getClassObject(L: PLua_state; paramstart: pinteger=nil; paramcount: pinteger=nil): pointer; //inline; procedure luaclass_newClass(L: PLua_State; o: TObject; garbagecollectable: boolean=false); overload; procedure luaclass_newClass(L: PLua_State; o: pointer; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); overload; procedure luaclass_newClass(L: PLua_State; o: TObject; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); overload; procedure luaclass_newClassFunction(L: PLua_State; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); procedure luaclass_register(c: TClass; InitialAddMetaDataFunction: TAddMetaDataFunction); procedure luaclass_pushClass(L: PLua_State; o: TObject); stdcall; //for plugins implementation uses LuaClassArray, LuaObject, LuaComponent, luahandler; var lookuphelp: TPointerToPointerTree; //does not update after initialization (static) lookuphelp2: TPointerToPointerTree; //for classes that inherit from the main classes (can update after initialization, dynamic) lookuphelp2MREW: TMultiReadExclusiveWriteSynchronizer; objectcomparefunctionref: integer=0; type TClasslistentry=record c: TClass; f: TAddMetaDataFunction; end; PClassListEntry=^TClassListEntry; resourcestring rsInvalidClassObject='Invalid class object'; function TRecordEntries.getEntry(index: integer): TRecordEntry; begin if index<length(list) then result:=list[index] else begin result.name:=''; result.getf:=nil; result.setf:=nil; end; end; procedure TRecordEntries.setEntry(index: integer; e: TRecordEntry); begin if index<length(list) then list[index]:=e; end; procedure TRecordEntries.add(r: TRecordEntry); begin setlength(list, length(list)+1); list[length(list)-1]:=r; end; procedure TRecordEntries.clear; begin setlength(list,0); end; function TRecordEntries.getCount: integer; begin result:=length(list); end; procedure luaclass_register(c: TClass; InitialAddMetaDataFunction: TAddMetaDataFunction); //registers the classes that are accessible by lua. Used by findBestClassForObject var cle: PClasslistentry; t: TClass; begin if lookuphelp=nil then begin lookuphelp:=TPointerToPointerTree.Create; lookuphelp2:=TPointerToPointerTree.create; lookuphelp2MREW:=TMultiReadExclusiveWriteSynchronizer.Create; end; getmem(cle, sizeof(TClasslistentry)); cle.c:=c; cle.f:=InitialAddMetaDataFunction; lookuphelp.Values[c]:=cle; end; function findBestClassForObject(O: TObject): TAddMetaDataFunction; var best: PClassListEntry; oclass: Tclass; begin result:=nil; if o=nil then exit; oclass:=o.ClassType; best:=lookuphelp.Values[oclass]; if best<>nil then exit(best^.f); //not a main type, check the child types lookuphelp2MREW.beginread; best:=lookuphelp2.values[oclass]; lookuphelp2MREW.endread; if best<>nil then exit(best^.f); //find it in the static typestore oclass:=oclass.ClassParent; while oclass<>nil do begin best:=lookuphelp.Values[oclass]; if best<>nil then begin //add to the secondary list lookuphelp2MREW.Beginwrite; lookuphelp2.values[o.classtype]:=best; lookuphelp2MREW.endwrite; exit(best^.f); end; oclass:=oclass.ClassParent; end; end; procedure luaclass_newClassFunction(L: PLua_State; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); //converts the item at the top of the stack to a class object var userdata, metatable: integer; begin if Assigned(InitialAddMetaDataFunction) then begin userdata:=lua_gettop(L); metatable:=luaclass_createMetaTable(L, garbagecollectable); InitialAddMetaDataFunction(L, metatable, userdata); lua_setmetatable(L, userdata); end; end; procedure luaclass_newClass(L: PLua_State; o: pointer; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); begin if (o<>nil) and (Assigned(InitialAddMetaDataFunction)) then begin lua_newuserdata(L, o); luaclass_newClassFunction(L, InitialAddMetaDataFunction); end else lua_pushnil(L); end; procedure luaclass_newClass(L: PLua_State; o: TObject; InitialAddMetaDataFunction: TAddMetaDataFunction; garbagecollectable: boolean=false); begin luaclass_newClass(L, pointer(o), InitialAddMetaDataFunction, garbagecollectable); end; procedure luaclass_newClass(L: PLua_State; o: TObject; garbagecollectable: boolean=false); overload; var InitialAddMetaDataFunction: TAddMetaDataFunction; begin if o<>nil then begin InitialAddMetaDataFunction:=findBestClassForObject(o); luaclass_newClass(L, o, InitialAddMetaDataFunction, garbagecollectable); end else lua_pushnil(L); end; procedure luaclass_pushClass(L: PLua_State; o: TObject); stdcall; //for plugins begin luaclass_newClass(L,o); end; function luaclass_getClassObject(L: PLua_state; paramstart: pinteger=nil; paramcount: pinteger=nil): pointer;// inline; //called as first thing by class functions. This is in case a 6.2 code executed the function manually var t: integer; u: pointer; begin result:=nil; if lua_type(L, lua_upvalueindex(1))=LUA_TUSERDATA then begin u:=lua_touserdata(L, lua_upvalueindex(1)); result:=ppointer(u)^; if assigned(paramstart) then paramstart^:=1; if assigned(paramcount) then paramcount^:=lua_gettop(L); end else if lua_gettop(L)>=1 then begin t:=lua_type(L, 1); if t in [LUA_TUSERDATA, LUA_TLIGHTUSERDATA] then begin u:=lua_touserdata(L, 1); if t=LUA_TUSERDATA then result:=ppointer(u)^ else result:=u; if assigned(paramstart) then paramstart^:=2; if assigned(paramcount) then paramcount^:=lua_gettop(L)-1; end; end; if result=nil then raise exception.create(rsInvalidClassObject); { begin lua_pushstring(L, rsInvalidClassObject); lua_error(L); end; } end; procedure luaclass_setDefaultStringArrayProperty(L: PLua_State; metatable: integer; userdata: integer; getf, setf: lua_CFunction); //this makes it so x[0], x[1], x[2],...,x.0 , x.1 , x.2,... will call these specific get/set handlers begin lua_pushstring(L, '__defaultstringgetindexhandler'); if assigned(getf) then begin lua_pushvalue(L, userdata); lua_pushcclosure(L, getf, 1); end else lua_pushnil(L); lua_settable(L, metatable); lua_pushstring(L, '__defaultstringsetindexhandler'); if assigned(setf) then begin lua_pushvalue(L, userdata); lua_pushcclosure(L, setf, 1); end else lua_pushnil(L); lua_settable(L, metatable); end; procedure luaclass_setDefaultArrayProperty(L: PLua_State; metatable: integer; userdata: integer; getf, setf: lua_CFunction); //this makes it so x[0], x[1], x[2],...,x.0 , x.1 , x.2,... will call these specific get/set handlers begin lua_pushstring(L, '__defaultintegergetindexhandler'); if assigned(getf) then begin lua_pushvalue(L, userdata); lua_pushcclosure(L, getf, 1); end else lua_pushnil(L); lua_settable(L, metatable); lua_pushstring(L, '__defaultintegersetindexhandler'); if assigned(setf) then begin lua_pushvalue(L, userdata); lua_pushcclosure(L, setf, 1); end else lua_pushnil(L); lua_settable(L, metatable); end; procedure luaclass_addRecordPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; RecordEntries: TRecordEntries); var t,metatable2: integer; i: integer; begin lua_pushstring(L, propertyname); lua_newtable(L); t:=lua_gettop(L); metatable2:=luaclass_createMetaTable(L); //create a luaclass metatable for this new table lua_pushstring(L, '__norealclass'); lua_pushboolean(L, true); lua_settable(L, metatable2); //tell this metatable that it's not a "real" class, so it won't have to get properties or component names for i:=0 to RecordEntries.count-1 do luaclass_addPropertyToTable(L, metatable2, userdata, RecordEntries[i].name, RecordEntries[i].getf, RecordEntries[i].setf); lua_setmetatable(L, t); //pop the table from the stack and set it as metatatble to table T lua_settable(L, metatable); //pop the table and the string from the table and set that to the metatable end; procedure luaclass_addArrayPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; getf: lua_CFunction; setf: lua_CFunction=nil); var t: integer; begin lua_pushstring(L, propertyname); lua_newtable(L); t:=lua_gettop(L); luaclassarray_createMetaTable(L, userdata, getf, setf); lua_setmetatable(L, t); lua_settable(L, metatable); end; procedure luaclass_addPropertyToTable(L: PLua_State; metatable: integer; userdata: integer; propertyname: string; getfunction: lua_CFunction; setfunction: lua_CFunction); var t: integer; begin lua_pushstring(L, propertyname); lua_newtable(L); t:=lua_gettop(L); if assigned(getfunction) then begin lua_pushstring(L,'__get'); lua_pushvalue(L, userdata); lua_pushcclosure(L, getfunction, 1); lua_settable(L, t); end; if assigned(setfunction) then begin lua_pushstring(L,'__set'); lua_pushvalue(L, userdata); lua_pushcclosure(L, setfunction, 1); lua_settable(L, t); end; lua_settable(L, metatable); //add a lowercase variant if needed if propertyname[1] in ['A'..'Z'] then begin propertyname[1]:=lowercase(propertyname[1]); luaclass_addPropertyToTable(L, metatable, userdata, propertyname, getfunction, setfunction); end; end; procedure luaclass_addClassFunctionToTable(L: PLua_State; metatable: integer; userdata: integer; functionname: string; f: lua_CFunction); begin lua_pushstring(L, functionname); lua_pushvalue(L, userdata); lua_pushcclosure(L, f, 1); lua_settable(L, metatable); if functionname<>'' then begin //add a secondary method where the name starts with a capital functionname[1]:=uppercase(functionname[1])[1]; lua_pushstring(L, functionname); lua_pushvalue(L, userdata); lua_pushcclosure(L, f, 1); lua_settable(L, metatable); end; end; function luaclass_compare(L: PLua_State): integer; cdecl; //__eq //parameters: (O1, O2) //return nil or false for false var o1, o2: TObject; begin o1:=lua_ToCEUserData(L, 1); o2:=lua_ToCEUserData(L, 2); lua_pushboolean(L, o1=o2); result:=1; end; function luaclass_newindex(L: PLua_State): integer; cdecl; //set //parameters: (self, key, newvalue) var metatable: integer; begin result:=0; lua_getmetatable(L, 1); //get the metatable of self metatable:=lua_gettop(L); //store the metatable index lua_pushvalue(L, 2); //push the key lua_gettable(L, -2); //metatable[key] if lua_istable(L ,-1) then begin lua_pushstring(L, '__set'); lua_gettable(L, -2); //table['__set'] if lua_isfunction(L, -1) then begin lua_pushvalue(L, 3); //push newvalue (so stack now holds, function, newvalue) lua_call(L, 1, 0); exit; end; end; if lua_isnil(L, -1) then begin //not in the list lua_pop(L,1); //check if key is a number if lua_isnumber(L, 2) then begin //check if there is a __defaultintegergetindexhandler defined in the metatable lua_pushstring(L, '__defaultintegersetindexhandler'); lua_gettable(L, metatable); if lua_isfunction(L,-1) then begin //yes lua_pushvalue(L, 2); //key lua_pushvalue(L, 3); //value lua_call(L, 2,0); //call __defaultintegersetindexhandler(key, value); exit; end else lua_pop(L,1); end; if lua_type(L, 2)=LUA_TSTRING then begin //check if there is a __defaultstringsetindexhandler defined in the metatable lua_pushstring(L, '__defaultstringsetindexhandler'); lua_gettable(L, metatable); if lua_isfunction(L,-1) then begin lua_pushvalue(L, 2); //key lua_pushvalue(L, 3); //value lua_call(L, 2, 0); //call __defaultstringsetindexhandler(key, value) exit; end else lua_pop(L,1); end; end; //this entry was not in the list //Let's see if this is a published property or custom value lua_pushcfunction(L, lua_setProperty); lua_pushvalue(L, 1); //userdata lua_pushvalue(L, 2); //keyname lua_pushvalue(L, 3); //value lua_call(L,3,0); end; function luaclass_index(L: PLua_State): integer; cdecl; //get //parameters: (self, key) //called when a class object is indexed //return the metatable element with this name //wants to get the value of table[key] , but table isn'ty really a table var i: integer; metatable, metatable2: integer; s: string; o: TObject; begin //return the metatable element i:=lua_gettop(L); result:=0; if i=2 then begin lua_getmetatable(L, 1); //get the metatable from the table and push i on the stack metatable:=lua_gettop(L); lua_pushvalue(L, 2); //push the key on the stack //lua_rawget(L, metatable); lua_gettable(L, metatable); //get metatable[key] if lua_istable(L ,-1) then begin //perhaps an array //lua_getmetatable(L,-1); lua_pushstring(L, '__get'); lua_gettable(L, -2); if lua_isfunction(L, -1) then lua_call(L, 0, 1) else //return the table that was stored in the metatable (so undo the result of getting __get) lua_pop(L,1); end else begin if lua_isnil(L, -1) then begin //this entry was not in the list lua_pop(L,1); //check if the key can be a number if lua_isnumber(L, 2) then begin //check if there is a __defaultintegergetindexhandler defined in the metatable lua_pushstring(L, '__defaultintegergetindexhandler'); lua_gettable(L, metatable); if lua_isfunction(L,-1) then begin lua_pushvalue(L, 2); //key lua_call(L, 1, 1); //call __defaultintegergetindexhandler(key) result:=1; exit; end; end; lua_pushstring(L, '__norealclass'); lua_gettable(L, metatable); if lua_isboolean(L, -1) and lua_toboolean(L, -1) then begin lua_pop(L,1); lua_pushnil(L); result:=1; exit; end; //Let's see if this is a published property lua_pushcfunction(L, lua_getProperty); lua_pushvalue(L, 1); //userdata lua_pushvalue(L, 2); //keyname lua_call(L,2,1); result:=1; if lua_isnil(L, -1) then begin //not a property lua_pop(L,1); o:=tobject(lua_touserdata(L,1)^); if o is TComponent then begin lua_pushcfunction(L, component_findComponentByName); lua_pushvalue(L, 1); //userdata lua_pushvalue(L, 2); //keyname lua_call(L, 2, 1); //component_findComponentByName if not lua_isnil(L,-1) then exit(1); //still here so not a component of the component lua_pop(L,1); end; if lua_type(L, 2)=LUA_TSTRING then begin //check if there is a __defaultstringgetindexhandler defined in the metatable lua_pushstring(L, '__defaultstringgetindexhandler'); lua_gettable(L, metatable); if lua_isfunction(L,-1) then begin lua_pushvalue(L, 2); //key lua_call(L, 1, 1); //call __defaultstringgetindexhandler(key) exit(1); end else lua_pop(L,1); end; end; end; end; result:=1; end; end; function luaclass_garbagecollect(L: PLua_State): integer; cdecl; //gc var autodestroy: boolean; o: tobject; mt: integer; begin lua_getmetatable(L, 1); mt:=lua_gettop(L); lua_pushstring(L, '__autodestroy'); lua_gettable(L, mt); autodestroy:=lua_toboolean(L, -1); if autodestroy then begin //kill it lua_pushstring(L, 'destroy'); lua_gettable(L, mt); if lua_isfunction(L, -1) then lua_call(L, 0,0); end; result:=0; end; procedure luaclass_setAutoDestroy(L: PLua_State; metatable: integer; state: boolean); begin lua_pushstring(L, '__autodestroy'); lua_pushboolean(L, state); lua_settable(L, metatable); end; function luaclass_createMetaTable(L: Plua_State; garbagecollectable: boolean=false): integer; //creates a table to be used as a metatable //returns the stack index of the table begin lua_newtable(L); result:=lua_gettop(L); luaclass_setAutoDestroy(L, result, garbagecollectable); //default do not destroy when garbage collected. Let the user do it //set the index method lua_pushstring(L, '__index'); lua_pushcfunction(L, luaclass_index); lua_settable(L, result); lua_pushstring(L, '__newindex'); lua_pushcfunction(L, luaclass_newindex); lua_settable(L, result); lua_pushstring(L, '__gc'); lua_pushcfunction(L, luaclass_garbagecollect); lua_settable(L, result); lua_pushstring(L, '__eq'); if objectcomparefunctionref=0 then //get it begin lua_pushcfunction(L, luaclass_compare); objectcomparefunctionref := luaL_ref(L, LUA_REGISTRYINDEX); end; lua_rawgeti(L, LUA_REGISTRYINDEX, objectcomparefunctionref); lua_settable(L, result); end; end.
unit URegraCRUDOs; interface uses URegraCRUD , URepositorioDB , URepositorioOs , UEntidade , UCliente , UEquipamento , UOs ; type TRegraCRUDOs = class(TRegraCRUD) private procedure ValidaCliente(const coCLIENTE: TCLIENTE); procedure ValidaEquipamento(const coEQUIPAMENTO: TEquipamento); protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; end; implementation uses SysUtils , UUtilitarios , UMensagens , UConstantes ; { TRegraCRUDOs } constructor TRegraCRUDOs.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioOs.Create); end; procedure TRegraCRUDOs.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin with TOs(coENTIDADE) do begin ValidaCliente(CLIENTE); end; end; procedure TRegraCRUDOs.ValidaCliente(const coCLIENTE: TCLIENTE); begin if (coCLIENTE = nil) or (coCLIENTE.ID = 0) then raise EValidacaoNegocio.Create(STR_OS_CLIENTE_NAO_INFORMADO); end; procedure TRegraCRUDOs.ValidaEquipamento(const coEQUIPAMENTO: TEquipamento); begin if (coEQUIPAMENTO = nil) or (coEQUIPAMENTO.ID = 0) then raise EValidacaoNegocio.Create(STR_OS_EQUIPAMENTO_NAO_INFORMADO); end; procedure TRegraCRUDOs.ValidaInsercao(const coENTIDADE: TENTIDADE); var coOs: TOS; begin inherited; coOs := TOS(coENTIDADE); if (coOs.DATA_ENTRADA) = 0 Then raise EValidacaoNegocio.Create(STR_OS_DATA_ENTRADA_NAO_INFORMADO); ValidaCliente(coOs.CLIENTE); ValidaEquipamento(coOs.EQUIPAMENTO); end; end.