text
stringlengths
14
6.51M
unit cn_fr_ModeUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, DM_Mode, cn_Common_Types, cn_Common_Funcs, cnConsts, cxRadioGroup, cxControls, cxGroupBox, ExtCtrls, PrintLoader, cn_Common_Loader; type TfrmChooseReport = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; CalcRadioButton: TcxRadioButton; PayRadioButton: TcxRadioButton; Image1: TImage; Sch_Button: TcxRadioButton; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OkButtonClick(Sender: TObject); private PLanguageIndex: byte; DM:TDM_Choose; ID_DOG: int64; ID_STUD: int64; ID_DOG_ROOT: int64; NUM_DOG : string; ID_RATE_ACCOUNT, id_user : int64; User_Name : string; DATE_DOG : TDateTime; procedure FormIniLanguage; public constructor Create(AParameter:TcnSimpleParamsEx);reintroduce; end; var frmChooseReport: TfrmChooseReport; implementation {$R *.dfm} constructor TfrmChooseReport.Create(AParameter:TcnSimpleParamsEx); begin Screen.Cursor:=crHourGlass; inherited Create(AParameter.Owner); id_user := AParameter.ID_User; User_Name := AParameter.User_Name; DM:=TDM_Choose.Create(Self); DM.ReadDataSet.SQLs.SelectSQL.Text := 'select * from sys_options'; // просто чтобы убить транзакцию галимую DM.DB.Handle:=AParameter.Db_Handle; DM.ReadDataSet.Open; DM.ReadDataSet.Close; ID_DOG_ROOT := AParameter.cnParamsToPakage.ID_DOG_ROOT; ID_DOG := AParameter.cnParamsToPakage.ID_DOG; ID_STUD := AParameter.cnParamsToPakage.ID_STUD; NUM_DOG := AParameter.cnParamsToPakage.Num_Doc; DATE_DOG := AParameter.cnParamsToPakage.DATE_DOG; ID_RATE_ACCOUNT := AParameter.cnParamsToPakage.ID_RATE_ACCOUNT; Screen.Cursor:=crDefault; FormIniLanguage(); end; procedure TfrmChooseReport.FormIniLanguage; begin PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex(); caption := cnConsts.cn_Print_Caption[PLanguageIndex]; CalcRadioButton.Caption:= cnConsts.fr_Reports_CalcDocs[PLanguageIndex]; PayRadioButton.Caption:= cnConsts.fr_Reports_PayDocs[PLanguageIndex]; Sch_Button.Caption:= cnConsts.cn_RaxynokNaSplatyCaption[PLanguageIndex]; OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex]; CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex]; end; procedure TfrmChooseReport.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmChooseReport.FormClose(Sender: TObject; var Action: TCloseAction); begin dm.free; end; procedure TfrmChooseReport.OkButtonClick(Sender: TObject); var InParameter : TcnSimpleParamsEx; begin // -----------логирование работы с печатью------------------------------------ Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Print' + '''' + ')'; Dm.ReadDataSet.Open; DM.StProc.StoredProcName := 'CN_ACTION_HISTORY_INSERT'; DM.StProc.Transaction.StartTransaction; DM.StProc.Prepare; DM.StProc.ParamByName('ID_DOG_ROOT').AsInt64 := ID_DOG_ROOT; DM.StProc.ParamByName('ID_DOG').AsInt64 := ID_DOG; DM.StProc.ParamByName('ID_STUD').AsInt64 := ID_STUD; DM.StProc.ParamByName('ID_USER').AsInt64 := ID_User; DM.StProc.ParamByName('USER_NAME').AsString := User_Name; DM.StProc.ParamByName('ID_ACTION').AsInt64 := Dm.ReadDataSet['ID_ACTION']; DM.StProc.ExecProc; DM.StProc.Transaction.Commit; Dm.ReadDataSet.Close; if PayRadioButton.Checked then begin PrintLoader.LPrintDogs(Self, DM.DB, ID_STUD); exit; end; if CalcRadioButton.Checked then begin InParameter:= TcnSimpleParamsEx.Create; InParameter.Owner:=self; InParameter.Db_Handle:= DM.DB.Handle; InParameter.Formstyle:=fsNormal; InParameter.cnParamsToPakage.ID_DOG := ID_DOG; InParameter.cnParamsToPakage.ID_STUD := ID_STUD; InParameter.cnParamsToPakage.Num_Doc := NUM_DOG; InParameter.WaitPakageOwner:= frmChooseReport; RunFunctionFromPackage(InParameter, 'Contracts\cn_fr_Calc.bpl','frCalcReport'); InParameter.Free; Screen.Cursor := crDefault; exit; end; if Sch_Button.Checked then begin InParameter:= TcnSimpleParamsEx.Create; InParameter.Owner:=self; InParameter.Db_Handle:= DM.DB.Handle; InParameter.Formstyle:=fsNormal; InParameter.cnParamsToPakage.ID_DOG_ROOT := ID_DOG_ROOT; InParameter.cnParamsToPakage.ID_DOG := ID_DOG; InParameter.cnParamsToPakage.ID_STUD := ID_STUD; InParameter.cnParamsToPakage.Num_Doc := NUM_DOG; InParameter.cnParamsToPakage.ID_RATE_ACCOUNT := ID_RATE_ACCOUNT; InParameter.cnParamsToPakage.DATE_DOG := DATE_DOG; InParameter.WaitPakageOwner:= frmChooseReport; RunFunctionFromPackage(InParameter, 'Contracts\cn_SchToPay.bpl','ShowSchToPay'); InParameter.Free; Screen.Cursor := crDefault; exit; end; end; end.
program problem04; uses crt; (* Problem: Largest palindrome product Problem 4 @Author: Chris M. Perez @Date: 5/14/2017 *) function isPalindrome(arg: longint): Boolean; var temp: longint; reversed: longint = 0; begin temp := arg; while temp > 0 do begin reversed := reversed * 10 + temp mod 10; temp := temp div 10; end; exit(arg = reversed); end; var product: longint = 0; actual: longint = 0; last: longint = 0; i , j: longint; begin for i := 100 to 999 do begin for j := Round(100000 / i + 1) to 999 do begin product := i * j; if isPalindrome(product) then actual := product; if actual > last then last := actual end; end; Writeln(last); readkey; end.
unit o_GridDataList; interface uses SysUtils, Classes, o_baselistobj, o_GridData, o_VorgangposSorter, o_Vorgangpossort; type TGridDataList = class(TBaseListObj) private fSorter: TVorgangposSorter; function getGridData(Index: Integer): TGridData; procedure UebernehmeSortNrVonSorter; function getPrintidx(aIdx: string): string; public constructor Create; override; destructor Destroy; override; function Add: TGridData; property Item[Index: Integer]: TGridData read getGridData; procedure LadeSorter; procedure PosTauschen(aVonId, aNachId: Integer); function getIndex(aId: Integer): Integer; end; implementation { TGridDataList } function NachPrNrSortieren(Item1, Item2: Pointer): Integer; begin Result := 0; if TGridData(Item1).PrnNr < TGridData(Item2).PrnNr then Result := -1 else if TGridData(Item1).PrnNr > TGridData(Item2).PrnNr then Result := 1; end; constructor TGridDataList.Create; begin inherited; fSorter := TVorgangposSorter.Create; end; destructor TGridDataList.Destroy; begin FreeAndNil(fSorter); inherited; end; function TGridDataList.getGridData(Index: Integer): TGridData; begin Result := nil; if Index > _List.Count then exit; Result := TGridData(_List.Items[Index]); end; function TGridDataList.getIndex(aId: Integer): Integer; var i1: Integer; begin for i1 := 0 to _List.Count -1 do begin if TGridData(_List.Items[i1]).Id = aId then begin Result := i1; exit; end; end; end; procedure TGridDataList.LadeSorter; var i1: Integer; GridData: TGridData; SortPos: TVorgangposSort; begin fSorter.Clear; for i1 := 0 to _List.Count -1 do begin GridData := TGridData(_List.Items[i1]); SortPos := fSorter.Add(GridData.ParentId); SortPos.Id := GridData.Id; SortPos.Idx := GridData.Idx; SortPos.PrnNr := GridData.PrnNr; SortPos.Frm := GridData.Frm; SortPos.Nr := GridData.Nr; SortPos.ParentId := GridData.ParentId; end; fSorter.ErstelleSortNummern; UebernehmeSortNrVonSorter; _List.Sort(@NachPrNrSortieren); end; procedure TGridDataList.PosTauschen(aVonId, aNachId: Integer); var VonIndex: Integer; NachIndex: Integer; i1: Integer; begin VonIndex := getIndex(aVonId); NachIndex := getIndex(aNachId); if VonIndex > NachIndex then begin i1 := VonIndex - 1; while VonIndex > NachIndex do begin _List.Exchange(VonIndex, i1); dec(i1); dec(VonIndex); end; end; if VonIndex < NachIndex then begin i1 := VonIndex + 1; while VonIndex < NachIndex do begin _List.Exchange(VonIndex, i1); inc(i1); inc(VonIndex); end; end; fSorter.ErstelleSortNummern; UebernehmeSortNrVonSorter; end; procedure TGridDataList.UebernehmeSortNrVonSorter; var i1: Integer; GridData: TGridData; SortPos: TVorgangposSort; begin for i1 := 0 to _List.Count -1 do begin GridData := TGridData(_List.Items[i1]); SortPos := fSorter.GetPosSort(GridData.Id); if SortPos = nil then continue; GridData.Idx := getPrintidx(SortPos.Idx); GridData.Frm := SortPos.Frm; GridData.PrnNr := SortPos.PrnNr; GridData.Nr := SortPos.Nr; GridData.HasChild := SortPos.HasChild; end; end; function TGridDataList.getPrintidx(aIdx: string): string; var iPos: Integer; s: string; begin Result := aIdx; s := aIdx; iPos := Pos('.', s); while iPos > 0 do begin s := copy(s, iPos+1, Length(s)); Result := ' ' + Result; iPos := Pos('.', s); end; end; function TGridDataList.Add: TGridData; begin Result := TGridData.Create; _List.Add(Result); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_SYMBOL_OFFSET.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O+} unit PAXCOMP_OFFSET; interface uses {$I uses.def} TypInfo, SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS; type TOffsetRec = class public Id: Integer; Shift: Integer; Offset: Integer; Size: Integer; function Clone: TOffsetRec; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); end; TOffsetList = class(TTypedList) private Sorted: Boolean; function GetRecord(I: Integer): TOffsetRec; procedure SetRecord(I: Integer; value: TOffsetRec); public InitSize: Integer; constructor Create; function Add(Id, Shift, Offset, Size: Integer): TOffsetRec; procedure Clear; override; function Clone: TOffsetList; function GetSize: Integer; function GetOffset(Shift: Integer): Integer; function HasId(Id: Integer): Boolean; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function GetOffsetById(Id: Integer): Integer; property Records[I: Integer]: TOffsetRec read GetRecord write SetRecord; default; end; procedure TOffsetList_Sort(Self: TOffsetList); implementation // TOffsetRec ------------------------------------------------------------------ function TOffsetRec.Clone: TOffsetRec; begin result := TOffsetRec.Create; result.Id := Id; result.Shift := Shift; result.Offset := Offset; result.Size := Size; end; procedure TOffsetRec.SaveToStream(S: TStream); begin S.Write(Shift, SizeOf(Shift)); S.Write(Offset, SizeOf(Offset)); end; procedure TOffsetRec.LoadFromStream(S: TStream); begin S.Read(Shift, SizeOf(Shift)); S.Read(Offset, SizeOf(Offset)); end; // TOffsetList ----------------------------------------------------------------- constructor TOffsetList.Create; begin inherited; InitSize := 0; Sorted := false; end; function TOffsetList.Add(Id, Shift, Offset, Size: Integer): TOffsetRec; begin result := TOffsetRec.Create; result.Id := Id; result.Shift := Shift; result.Offset := Offset; result.Size := Size; L.Add(result); end; function TOffsetList.GetSize: Integer; var I, SZ: Integer; begin result := InitSize; for I := 0 to Count - 1 do begin SZ := Records[I].Size; Inc(result, SZ); end; end; function BinSearch(List: TOffsetList; const Key: Integer): Integer; var First: Integer; Last: Integer; Pivot: Integer; Found: Boolean; begin First := 0; Last := List.Count - 1; Found := False; Result := -1; while (First <= Last) and (not Found) do begin Pivot := (First + Last) div 2; if TOffsetRec(List.L[Pivot]).Shift = Key then begin Found := True; Result := Pivot; end else if TOffsetRec(List.L[Pivot]).Shift > Key then Last := Pivot - 1 else First := Pivot + 1; end; end; function TOffsetList.GetOffset(Shift: Integer): Integer; var I: Integer; R: TOffsetRec; begin result := -1; if Shift < StdSize then begin result := Shift; Exit; end; if Sorted then begin I := BinSearch(Self, Shift); if I = -1 then Exit; result := Records[I].Offset; Exit; end; for I := 0 to Count - 1 do begin R := Records[I]; if R.Shift = Shift then begin result := R.Offset; Exit; end; end; end; function TOffsetList.HasId(Id: Integer): Boolean; var I: Integer; R: TOffsetRec; begin for I := 0 to Count - 1 do begin R := Records[I]; if R.Id = Id then begin result := true; Exit; end; end; result := false; end; function TOffsetList.GetRecord(I: Integer): TOffsetRec; begin result := TOffsetRec(L[I]); end; procedure TOffsetList.SetRecord(I: Integer; value: TOffsetRec); begin L[I] := value; end; function TOffsetList.GetOffsetById(Id: Integer): Integer; var I: Integer; begin for I:=0 to Count - 1 do if Records[I].Id = Id then begin result := Records[I].Offset; Exit; end; raise Exception.Create(errInternalError); end; procedure TOffsetList.Clear; begin inherited; InitSize := 0; Sorted := false; end; function TOffsetList.Clone: TOffsetList; var I: Integer; R: TOffsetRec; begin result := TOffsetList.Create; for I := 0 to Count - 1 do begin R := Records[I].Clone; result.L.Add(R); end; end; procedure TOffsetList.SaveToStream(S: TStream); var I, K: Integer; begin K := Count; S.Write(K, SizeOf(Integer)); for I := 0 to K - 1 do Records[I].SaveToStream(S); end; procedure TOffsetList.LoadFromStream(S: TStream); var I, K: Integer; R: TOffsetRec; begin S.Read(K, SizeOf(Integer)); for I := 0 to K - 1 do begin R := TOffsetRec.Create; R.LoadFromStream(S); L.Add(R); end; end; procedure QuickSort(var List: TOffsetList; Start, Stop: Integer); var Left: Integer; Right: Integer; Mid: Integer; Pivot: TOffsetRec; Temp: TOffsetRec; begin Left := Start; Right := Stop; Mid := (Start + Stop) div 2; Pivot := List[mid]; repeat while List[Left].Shift < Pivot.Shift do Inc(Left); while Pivot.Shift < List[Right].Shift do Dec(Right); if Left <= Right then begin Temp := List[Left]; List[Left] := List[Right]; // Swops the two Strings List[Right] := Temp; Inc(Left); Dec(Right); end; until Left > Right; if Start < Right then QuickSort(List, Start, Right); // Uses if Left < Stop then QuickSort(List, Left, Stop); // Recursion end; procedure TOffsetList_Sort(Self: TOffsetList); begin if Self.Count > 0 then begin QuickSort(Self, 0, Self.Count - 1); Self.Sorted := true; end; end; end.
unit UEstadoVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UPaisVO; type [TEntity] [TTable('Estado')] TEstadoVO = class(TGenericVO) private FIdEstado: Integer; FnomeEstado: String; FIdPais : Integer; // Atributos Transientes FnomePais: String; // ---------------------- public PaisVO: TPAISVO; [TId('idEstado')] [TGeneratedValue(sAuto)] property idEstado: Integer read FIdEstado write FIdEstado; [TColumn('NOMEESTADO','Estado',250,[ldGrid], False)] property NomeEstado: String read FnomeEstado write FnomeEstado; [TColumn('idPais','idPais',0,[ldLookup,ldComboBox], False)] property idPais: integer read FIdPais write FIdPais; // Atributos Transientes [TColumn('NOMEPAIS','Pais',0,[ldGrid], True, 'Pais', 'idPais', 'idPais')] property NomePais: string read FNomePais write FNomePais; // ---------------------- function ValidarCamposObrigatorios:boolean; end; implementation { TEstadoVO } function TEstadoVO.ValidarCamposObrigatorios: boolean; begin Result := true; if (Self.FnomeEstado = '') then begin raise Exception.Create('O campo Nome é obrigatório!'); Result := false; end end; end.
function KeyLeads:String; {verificação das teclas Caps, Scroll e NUM que usa um evento do Delphi e naum o Timer} Var State : String; KeyState : TKeyboardState; begin State := ''; GetKeyboardState(KeyState); if (KeyState[VK_NUMLOCK] = 1) then begin State := State + 'Num Lock'; end; if (KeyState[VK_CAPITAL] = 1) then begin State := State + 'Caps Lock'; end; if (KeyState[VK_SCROLL] = 1) then begin State := State + 'Scroll Lock'; end; Result := State; end;
unit CIFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, NppForms, SHDocVw, StdCtrls, Registry, Buttons, ExtCtrls, ActnList, System.Actions, Vcl.Menus, System.ImageList, Vcl.ImgList; type TCIForm = class(TNppForm) Panel1: TPanel; actionLabel: TLabel; Panel2: TPanel; OkBtn: TBitBtn; CancelBtn: TBitBtn; GroupBox1: TGroupBox; Panel3: TPanel; ProductList: TComboBox; BranchList: TComboBox; ModuleList: TComboBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; ActionList1: TActionList; OkAction: TAction; PopupMenu: TPopupMenu; N1: TMenuItem; Label4: TLabel; FilterList: TComboBox; clearAction: TAction; Image1: TImage; ImageList1: TImageList; Image2: TImage; procedure FormCreate(Sender: TObject); procedure OkActionExecute(Sender: TObject); procedure OkActionUpdate(Sender: TObject); procedure clearActionExecute(Sender: TObject); procedure FilterListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); private const cnstDllKey = 'Software\cinotepad'; const cnstNoFilter = 'Не задан'; const cnstFilter1 = 'Стопперы деплоя|85;86;87;90;91;95;98;100;101;103;104;105;108;110;112;116;117;118;119;120'; const cnstFilter2 = 'Стопперы деплоя NEW|83;84;85;86;87;88;89;90;91;92;93;94;95;96;97;98;99;100;101;103;104;105;106;107;108;109;110;112;116;117;118;119;120;122;123;124'; const cnstInsp = 'Инспектор кода: '; const cnstCIFormKey = 'CIForm'; const cnstDevelop = 'develop'; const cnstCIFilterKey = 'CIFilterHistory'; const cnstCIProductKey = 'CIProductHistory'; const cnstCIBranchKey = 'CIBranchHistory'; const cnstCIModuleKey = 'CIModuleHistory'; function GetFileName: String; function GetFullFileName: String; procedure SaveSettings; procedure RestoreSettings; procedure RestoreFilter; { Private declarations } public { Public declarations } procedure Navigate(WebBrowser: TWebBrowser); property FileName: String read GetFileName; property FullFileName: String read GetFullFileName; end; var CIForm: TCIForm; implementation {$R *.dfm} function EncodeBase64(const inStr: AnsiString): AnsiString; function Encode_Byte(b: Byte): AnsiChar; const Base64Code: string[64] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; begin Result := Base64Code[(b and $3F)+1]; end; var i: Integer; begin i := 1; Result := ''; while i <= Length(InStr) do begin Result := Result + Encode_Byte(Byte(inStr[i]) shr 2); Result := Result + Encode_Byte((Byte(inStr[i]) shl 4) or (Byte(inStr[i+1]) shr 4)); if i+1 <= Length(inStr) then Result := Result + Encode_Byte((Byte(inStr[i+1]) shl 2) or (Byte(inStr[i+2]) shr 6)) else Result := Result + '='; if i+2 <= Length(inStr) then Result := Result + Encode_Byte(Byte(inStr[i+2])) else Result := Result + '='; Inc(i, 3); end; end; { TCIForm } function TCIForm.GetFileName: String; begin Npp.GetFileName(Result); end; function TCIForm.GetFullFileName: String; begin Npp.GetFullFileName(Result); end; procedure TCIForm.RestoreFilter; var Registry: TRegistry; FFilter: String; FHistory: TStringList; i: integer; begin FilterList.Clear; FilterList.AddItem(cnstNoFilter,nil); Registry := TRegistry.Create(KEY_ALL_ACCESS); FHistory := TStringList.Create; try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey(cnstDllKey + '\' + cnstCIFormKey, False) then begin FFilter := Registry.ReadString('Filter'); Registry.CloseKey; end; if Registry.OpenKey(cnstDllKey + '\' + cnstCIFilterKey, False) then begin FHistory.Clear; Registry.GetValueNames(FHistory); for i := 0 to FHistory.Count - 1 do FilterList.AddItem(Registry.ReadString(FHistory[i]),nil); Registry.CloseKey; end else if Registry.OpenKey(cnstDllKey + '\' + cnstCIFilterKey, True) then begin Registry.WriteString('Item0',cnstFilter1); Registry.WriteString('Item1',cnstFilter2); FilterList.AddItem(cnstFilter1,nil); FilterList.AddItem(cnstFilter2,nil); FilterList.ItemIndex := 0; Registry.CloseKey; end; FilterList.ItemIndex := 0; if not FFilter.IsEmpty then if FilterList.Items.Count > 0 then begin i := FilterList.Items.IndexOf(FFilter); if i < 0 then begin FilterList.AddItem(FFilter,nil); i := FilterList.Items.IndexOf(FFilter); end; if i >= 0 then FilterList.ItemIndex := i; end; finally Registry.Free; FHistory.Free; end; end; procedure TCIForm.RestoreSettings; var Registry: TRegistry; FProduct,FBranch,FModule: String; FHistory: TStringList; i: integer; begin Registry := TRegistry.Create(KEY_READ); FHistory := TStringList.Create; try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey(cnstDllKey + '\' + cnstCIFormKey, False) then begin FProduct := Registry.ReadString('Product'); FBranch := Registry.ReadString('Branch'); FModule := Registry.ReadString('Module'); Registry.CloseKey; if Registry.OpenKey(cnstDllKey + '\' + cnstCIProductKey, False) then begin FHistory.Clear; Registry.GetValueNames(FHistory); for i := 0 to FHistory.Count - 1 do ProductList.AddItem(Registry.ReadString(FHistory[i]),nil); Registry.CloseKey; end; if Registry.OpenKey(cnstDllKey + '\' + cnstCIBranchKey, False) then begin FHistory.Clear; Registry.GetValueNames(FHistory); for i := 0 to FHistory.Count - 1 do BranchList.AddItem(Registry.ReadString(FHistory[i]),nil); Registry.CloseKey; end; if Registry.OpenKey(cnstDllKey + '\' + cnstCIModuleKey, False) then begin FHistory.Clear; Registry.GetValueNames(FHistory); for i := 0 to FHistory.Count - 1 do ModuleList.AddItem(Registry.ReadString(FHistory[i]),nil); Registry.CloseKey; end; if ProductList.Items.Count > 0 then begin i := ProductList.Items.IndexOf(FProduct); if i < 0 then begin ProductList.AddItem(FProduct,nil); i := ProductList.Items.IndexOf(FProduct); end; if i >= 0 then ProductList.ItemIndex := i; end; if BranchList.Items.Count > 0 then begin i := BranchList.Items.IndexOf(FBranch); if i < 0 then begin BranchList.AddItem(FBranch,nil); i := BranchList.Items.IndexOf(FBranch); end; if i >= 0 then BranchList.ItemIndex := i; end; if ModuleList.Items.Count > 0 then begin i := ModuleList.Items.IndexOf(FModule); if i < 0 then begin ModuleList.AddItem(FModule,nil); i := ModuleList.Items.IndexOf(FModule); end; if i >= 0 then ModuleList.ItemIndex := i; end; end else begin ProductList.Clear; BranchList.Clear; BranchList.AddItem(cnstDevelop,nil); BranchList.ItemIndex := 0; ModuleList.Clear; end; finally Registry.Free; FHistory.Free; end; end; procedure TCIForm.SaveSettings; var Registry: TRegistry; i: integer; S: String; begin inherited; Registry := TRegistry.Create(KEY_ALL_ACCESS); try Registry.RootKey := HKEY_CURRENT_USER; if not Registry.KeyExists(cnstDllKey) then Registry.CreateKey(cnstDllKey); if Registry.OpenKey(cnstDllKey + '\' + cnstCIFormKey, True) then begin if FilterList.ItemIndex>=0 then Registry.WriteString('Filter',FilterList.Items[FilterList.ItemIndex]); if ProductList.Text <> '' then Registry.WriteString('Product',ProductList.Text); if BranchList.Text <> '' then Registry.WriteString('Branch',BranchList.Text); if ModuleList.Text <> '' then Registry.WriteString('Module',ModuleList.Text); Registry.CloseKey; end; S := Trim(ProductList.Text); if (S<>'') and (ProductList.Items.IndexOf(S)<0) then ProductList.AddItem(S,nil); if ProductList.Items.Count = 0 then Registry.DeleteKey(cnstDllKey + '\' + cnstCIProductKey) else if Registry.OpenKey(cnstDllKey + '\' + cnstCIProductKey, True) then begin for i := 0 to ProductList.Items.Count - 1 do Registry.WriteString('Item' + IntToStr(i),ProductList.Items[i]); Registry.CloseKey; end; S := Trim(BranchList.Text); if (S<>'') and (BranchList.Items.IndexOf(S)<0) then BranchList.AddItem(S,nil); if BranchList.Items.Count = 0 then Registry.DeleteKey(cnstDllKey + '\' + cnstCIBranchKey) else if Registry.OpenKey(cnstDllKey + '\' + cnstCIBranchKey, True) then begin for i := 0 to BranchList.Items.Count - 1 do Registry.WriteString('Item' + IntToStr(i),BranchList.Items[i]); Registry.CloseKey; end; S := Trim(ModuleList.Text); if (S<>'') and (ModuleList.Items.IndexOf(S)<0) then ModuleList.AddItem(S,nil); if ModuleList.Items.Count = 0 then Registry.DeleteKey(cnstDllKey + '\' + cnstCIModuleKey) else if Registry.OpenKey(cnstDllKey + '\' + cnstCIModuleKey, True) then begin for i := 0 to ModuleList.Items.Count - 1 do Registry.WriteString('Item' + IntToStr(i),ModuleList.Items[i]); Registry.CloseKey; end; finally Registry.Free; end; end; procedure TCIForm.FilterListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Bitmap: TBitmap; Offset: Integer; S: string; begin with (Control as TComboBox).Canvas do { Draw on control canvas, not on the form. } begin S := (Control as TComboBox).Items[Index]; FillRect(Rect); { Clear the rectangle. } Offset := 2; { Provide default offset. } if S.Contains('|') then begin Bitmap := Image1.Picture.Bitmap; S := S.Substring(0,S.IndexOf('|')); end else Bitmap := Image2.Picture.Bitmap; if Bitmap <> nil then begin //DrawIcon(Handle, Rect.Left + Offset, Rect.Top, Icon.Handle); BrushCopy( Bounds(Rect.Left + Offset, Rect.Top+1, Bitmap.Width, Bitmap.Height), Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clWhite); {render bitmap} Offset := Bitmap.width + 6; { Add four pixels between bitmap and text. } end; TextOut(Rect.Left + Offset, Rect.Top+1, S); end; end; procedure TCIForm.FormCreate(Sender: TObject); begin inherited; RestoreSettings; RestoreFilter; Caption := cnstInsp + FileName; end; procedure TCIForm.Navigate(WebBrowser: TWebBrowser); var in_stream: TMemoryStream; Flags, TargetFrameName, PostData, Headers: OleVariant; sData, sFilter: AnsiString; begin if WebBrowser.Busy then WebBrowser.Stop; if not FileExists(FullFileName) then Exit; in_stream := TMemoryStream.Create; try in_stream.LoadFromFile(FullFileName); in_stream.Position := 0; if FilterList.ItemIndex > 0 then begin sFilter := FilterList.Items[FilterList.ItemIndex]; sFilter := Copy(sFilter,Pos('|',sFilter)+1,MaxInt); //sFilter.Substring(sFilter.IndexOf('|')+1); end else sFilter := ''; SetString(sData, PAnsiChar(in_stream.Memory), in_stream.Size); sData := Format('platform=%s&product=%s&version=%s&module=%s&fileName=%s&inspectingFile=%s&filter_rules=%s', ['5NT', AnsiString(ProductList.Text), AnsiString(BranchList.Text), AnsiString(ModuleList.Text), ExtractFileName(FileName), EncodeBase64(sData),sFilter]); PostData := VarArrayCreate([1, Length(sData) + 1], varByte); System.Move(sData[1], VarArrayLock(PostData)^, Length(sData) + 1); VarArrayUnlock(PostData); Headers := 'Content-Type: application/x-www-form-urlencoded'#13#10; WebBrowser.Navigate('http://codeinsp:8081/inspectfileex/', Flags, TargetFrameName, PostData, Headers); finally in_stream.Free; end; end; procedure TCIForm.OkActionExecute(Sender: TObject); begin Self.Npp.SaveCurrentFile; SaveSettings; OkBtn.Enabled := False; actionLabel.Visible := True; Self.Refresh; end; procedure TCIForm.OkActionUpdate(Sender: TObject); begin inherited; OkAction.Enabled := (ProductList.Text <> '') and (BranchList.Text <> '') and (ModuleList.Text <> ''); end; procedure TCIForm.clearActionExecute(Sender: TObject); var Registry: TRegistry; begin ProductList.Clear; BranchList.Clear; ModuleList.Clear; Registry := TRegistry.Create(KEY_ALL_ACCESS); try Registry.RootKey := HKEY_CURRENT_USER; if not Registry.KeyExists(cnstDllKey) then Exit; Registry.DeleteKey(cnstDllKey + '\' + cnstCIProductKey); Registry.DeleteKey(cnstDllKey + '\' + cnstCIBranchKey) ; Registry.DeleteKey(cnstDllKey + '\' + cnstCIModuleKey) ; finally Registry.Free; end; end; end.
unit OpenCV.ImgProc; interface uses Winapi.Windows, OpenCV.Lib, OpenCV.Core; (* Image smooth methods *) const CV_BLUR_NO_SCALE = 0; CV_BLUR = 1; CV_GAUSSIAN = 2; CV_MEDIAN = 3; CV_BILATERAL = 4; (* Filters used in pyramid decomposition *) CV_GAUSSIAN_5x5 = 7; (* Special filters *) CV_SCHARR = -1; CV_MAX_SOBEL_KSIZE = 7; (* Constants for color conversion *) CV_BGR2BGRA = 0; CV_RGB2RGBA = CV_BGR2BGRA; CV_BGRA2BGR = 1; CV_RGBA2RGB = CV_BGRA2BGR; CV_BGR2RGBA = 2; CV_RGB2BGRA = CV_BGR2RGBA; CV_RGBA2BGR = 3; CV_BGRA2RGB = CV_RGBA2BGR; CV_BGR2RGB = 4; CV_RGB2BGR = CV_BGR2RGB; CV_BGRA2RGBA = 5; CV_RGBA2BGRA = CV_BGRA2RGBA; CV_BGR2GRAY = 6; CV_RGB2GRAY = 7; CV_GRAY2BGR = 8; CV_GRAY2RGB = CV_GRAY2BGR; CV_GRAY2BGRA = 9; CV_GRAY2RGBA = CV_GRAY2BGRA; CV_BGRA2GRAY = 10; CV_RGBA2GRAY = 11; CV_BGR2BGR565 = 12; CV_RGB2BGR565 = 13; CV_BGR5652BGR = 14; CV_BGR5652RGB = 15; CV_BGRA2BGR565 = 16; CV_RGBA2BGR565 = 17; CV_BGR5652BGRA = 18; CV_BGR5652RGBA = 19; CV_GRAY2BGR565 = 20; CV_BGR5652GRAY = 21; CV_BGR2BGR555 = 22; CV_RGB2BGR555 = 23; CV_BGR5552BGR = 24; CV_BGR5552RGB = 25; CV_BGRA2BGR555 = 26; CV_RGBA2BGR555 = 27; CV_BGR5552BGRA = 28; CV_BGR5552RGBA = 29; CV_GRAY2BGR555 = 30; CV_BGR5552GRAY = 31; CV_BGR2XYZ = 32; CV_RGB2XYZ = 33; CV_XYZ2BGR = 34; CV_XYZ2RGB = 35; CV_BGR2YCrCb = 36; CV_RGB2YCrCb = 37; CV_YCrCb2BGR = 38; CV_YCrCb2RGB = 39; CV_BGR2HSV = 40; CV_RGB2HSV = 41; CV_BGR2Lab = 44; CV_RGB2Lab = 45; CV_BayerBG2BGR = 46; CV_BayerGB2BGR = 47; CV_BayerRG2BGR = 48; CV_BayerGR2BGR = 49; CV_BayerBG2RGB = CV_BayerRG2BGR; CV_BayerGB2RGB = CV_BayerGR2BGR; CV_BayerRG2RGB = CV_BayerBG2BGR; CV_BayerGR2RGB = CV_BayerGB2BGR; CV_BGR2Luv = 50; CV_RGB2Luv = 51; CV_BGR2HLS = 52; CV_RGB2HLS = 53; CV_HSV2BGR = 54; CV_HSV2RGB = 55; CV_Lab2BGR = 56; CV_Lab2RGB = 57; CV_Luv2BGR = 58; CV_Luv2RGB = 59; CV_HLS2BGR = 60; CV_HLS2RGB = 61; CV_BayerBG2BGR_VNG = 62; CV_BayerGB2BGR_VNG = 63; CV_BayerRG2BGR_VNG = 64; CV_BayerGR2BGR_VNG = 65; CV_BayerBG2RGB_VNG = CV_BayerRG2BGR_VNG; CV_BayerGB2RGB_VNG = CV_BayerGR2BGR_VNG; CV_BayerRG2RGB_VNG = CV_BayerBG2BGR_VNG; CV_BayerGR2RGB_VNG = CV_BayerGB2BGR_VNG; CV_BGR2HSV_FULL = 66; CV_RGB2HSV_FULL = 67; CV_BGR2HLS_FULL = 68; CV_RGB2HLS_FULL = 69; CV_HSV2BGR_FULL = 70; CV_HSV2RGB_FULL = 71; CV_HLS2BGR_FULL = 72; CV_HLS2RGB_FULL = 73; CV_LBGR2Lab = 74; CV_LRGB2Lab = 75; CV_LBGR2Luv = 76; CV_LRGB2Luv = 77; CV_Lab2LBGR = 78; CV_Lab2LRGB = 79; CV_Luv2LBGR = 80; CV_Luv2LRGB = 81; CV_BGR2YUV = 82; CV_RGB2YUV = 83; CV_YUV2BGR = 84; CV_YUV2RGB = 85; CV_BayerBG2GRAY = 86; CV_BayerGB2GRAY = 87; CV_BayerRG2GRAY = 88; CV_BayerGR2GRAY = 89; // YUV 4:2:0 formats family; CV_YUV2RGB_NV12 = 90; CV_YUV2BGR_NV12 = 91; CV_YUV2RGB_NV21 = 92; CV_YUV2BGR_NV21 = 93; CV_YUV420sp2RGB = CV_YUV2RGB_NV21; CV_YUV420sp2BGR = CV_YUV2BGR_NV21; CV_YUV2RGBA_NV12 = 94; CV_YUV2BGRA_NV12 = 95; CV_YUV2RGBA_NV21 = 96; CV_YUV2BGRA_NV21 = 97; CV_YUV420sp2RGBA = CV_YUV2RGBA_NV21; CV_YUV420sp2BGRA = CV_YUV2BGRA_NV21; CV_YUV2RGB_YV12 = 98; CV_YUV2BGR_YV12 = 99; CV_YUV2RGB_IYUV = 100; CV_YUV2BGR_IYUV = 101; CV_YUV2RGB_I420 = CV_YUV2RGB_IYUV; CV_YUV2BGR_I420 = CV_YUV2BGR_IYUV; CV_YUV420p2RGB = CV_YUV2RGB_YV12; CV_YUV420p2BGR = CV_YUV2BGR_YV12; CV_YUV2RGBA_YV12 = 102; CV_YUV2BGRA_YV12 = 103; CV_YUV2RGBA_IYUV = 104; CV_YUV2BGRA_IYUV = 105; CV_YUV2RGBA_I420 = CV_YUV2RGBA_IYUV; CV_YUV2BGRA_I420 = CV_YUV2BGRA_IYUV; CV_YUV420p2RGBA = CV_YUV2RGBA_YV12; CV_YUV420p2BGRA = CV_YUV2BGRA_YV12; CV_YUV2GRAY_420 = 106; CV_YUV2GRAY_NV21 = CV_YUV2GRAY_420; CV_YUV2GRAY_NV12 = CV_YUV2GRAY_420; CV_YUV2GRAY_YV12 = CV_YUV2GRAY_420; CV_YUV2GRAY_IYUV = CV_YUV2GRAY_420; CV_YUV2GRAY_I420 = CV_YUV2GRAY_420; CV_YUV420sp2GRAY = CV_YUV2GRAY_420; CV_YUV420p2GRAY = CV_YUV2GRAY_420; // YUV 4:2:2 formats family; CV_YUV2RGB_UYVY = 107; CV_YUV2BGR_UYVY = 108; // CV_YUV2RGB_VYUY = 109; // CV_YUV2BGR_VYUY = 110; CV_YUV2RGB_Y422 = CV_YUV2RGB_UYVY; CV_YUV2BGR_Y422 = CV_YUV2BGR_UYVY; CV_YUV2RGB_UYNV = CV_YUV2RGB_UYVY; CV_YUV2BGR_UYNV = CV_YUV2BGR_UYVY; CV_YUV2RGBA_UYVY = 111; CV_YUV2BGRA_UYVY = 112; // CV_YUV2RGBA_VYUY = 113; // CV_YUV2BGRA_VYUY = 114; CV_YUV2RGBA_Y422 = CV_YUV2RGBA_UYVY; CV_YUV2BGRA_Y422 = CV_YUV2BGRA_UYVY; CV_YUV2RGBA_UYNV = CV_YUV2RGBA_UYVY; CV_YUV2BGRA_UYNV = CV_YUV2BGRA_UYVY; CV_YUV2RGB_YUY2 = 115; CV_YUV2BGR_YUY2 = 116; CV_YUV2RGB_YVYU = 117; CV_YUV2BGR_YVYU = 118; CV_YUV2RGB_YUYV = CV_YUV2RGB_YUY2; CV_YUV2BGR_YUYV = CV_YUV2BGR_YUY2; CV_YUV2RGB_YUNV = CV_YUV2RGB_YUY2; CV_YUV2BGR_YUNV = CV_YUV2BGR_YUY2; CV_YUV2RGBA_YUY2 = 119; CV_YUV2BGRA_YUY2 = 120; CV_YUV2RGBA_YVYU = 121; CV_YUV2BGRA_YVYU = 122; CV_YUV2RGBA_YUYV = CV_YUV2RGBA_YUY2; CV_YUV2BGRA_YUYV = CV_YUV2BGRA_YUY2; CV_YUV2RGBA_YUNV = CV_YUV2RGBA_YUY2; CV_YUV2BGRA_YUNV = CV_YUV2BGRA_YUY2; CV_YUV2GRAY_UYVY = 123; CV_YUV2GRAY_YUY2 = 124; // CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY; CV_YUV2GRAY_Y422 = CV_YUV2GRAY_UYVY; CV_YUV2GRAY_UYNV = CV_YUV2GRAY_UYVY; CV_YUV2GRAY_YVYU = CV_YUV2GRAY_YUY2; CV_YUV2GRAY_YUYV = CV_YUV2GRAY_YUY2; CV_YUV2GRAY_YUNV = CV_YUV2GRAY_YUY2; // alpha premultiplication; CV_RGBA2mRGBA = 125; CV_mRGBA2RGBA = 126; CV_COLORCVT_MAX = 127; (* Sub-pixel interpolation methods *) CV_INTER_NN = 0; CV_INTER_LINEAR = 1; CV_INTER_CUBIC = 2; CV_INTER_AREA = 3; CV_INTER_LANCZOS4 = 4; (* ... and other image warping flags *) CV_WARP_FILL_OUTLIERS = 8; CV_WARP_INVERSE_MAP = 16; (* Shapes of a structuring element for morphological operations *) CV_SHAPE_RECT = 0; CV_SHAPE_CROSS = 1; CV_SHAPE_ELLIPSE = 2; CV_SHAPE_CUSTOM = 100; (* Morphological operations *) CV_MOP_ERODE = 0; CV_MOP_DILATE = 1; CV_MOP_OPEN = 2; CV_MOP_CLOSE = 3; CV_MOP_GRADIENT = 4; CV_MOP_TOPHAT = 5; CV_MOP_BLACKHAT = 6; var (* Converts input array pixels from one color space to another *) // CVAPI(void) cvCvtColor( const CvArr* src, CvArr* dst, int code ); cvCvtColor: procedure(const src: pIplImage; dst: pIplImage; code: Integer); cdecl = nil; // (* calculates probabilistic density (divides one histogram by another) *) // CVAPI(procedure) cvCalcProbDensity( { /* equalizes histogram of 8-bit single-channel image */ CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); } cvEqualizeHist: procedure (const src, dst: pIplImage); cdecl = nil; { (* Computes rotation_matrix matrix *) CVAPI(CvMat)cv2DRotationMatrix(CvPoint2D32f center, Double angle, Double scale, CvMat * map_matrix); } cv2DRotationMatrix: function (center: TCvPoint2D32f; angle: double; scale: double; map_matrix: pCvMat): pCvMat; cdecl = nil; { /* Warps image with affine transform */ CVAPI(void) cvWarpAffine( const CvArr* src, CvArr* dst, const CvMat* map_matrix, int flags CV_DEFAULT(CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS), CvScalar fillval CV_DEFAULT(cvScalarAll(0)) ); } cvWarpAffine: procedure (const src: pIplImage; dst: pIplImage; const map_matrix: pCvMat; flags: Integer { = CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS }; fillval: TCvScalar { = cvScalarAll(0) } ); cdecl = nil; function CvLoadImgProcLib: Boolean; implementation var FImgProcLib: THandle = 0; function CvLoadImgProcLib: Boolean; begin Result := False; FImgProcLib := LoadLibrary(imgproc_Dll); if FImgProcLib > 0 then begin Result := True; cvCvtColor := GetProcAddress(FImgProcLib, 'cvCvtColor'); cvEqualizeHist := GetProcAddress(FImgProcLib, 'cvEqualizeHist'); cv2DRotationMatrix := GetProcAddress(FImgProcLib, 'cv2DRotationMatrix'); cvWarpAffine := GetProcAddress(FImgProcLib, 'cvWarpAffine'); end; end; end.
namespace NSMenu; interface uses AppKit, Foundation; type [IBObject] AppDelegate = public class(INSApplicationDelegate) private fMainWindowController: MainWindowController; protected public [IBAction] method addNewMenus(sender : id); [IBAction] method sayHello(sender : id); method sayGoodBye(sender : id); method applicationDidFinishLaunching(aNotification: NSNotification); end; implementation method AppDelegate.applicationDidFinishLaunching(aNotification: NSNotification); begin fMainWindowController := new MainWindowController(); fMainWindowController.showWindow(nil); end; method AppDelegate.addNewMenus(sender: id); begin var mItem : NSMenuItem := sender as NSMenuItem; var parent : NSMenuItem := mItem.parentItem; var menu : NSMenu := parent.submenu; //Remove The Add Menu Item menu.removeItem(mItem); //Add The Say GoodBye Menu Item var newItem := new NSMenuItem() withTitle("Say GoodBye") action(selector(sayGoodBye:)) keyEquivalent("b"); // Note: on 10.9, this needs newItem.setKeyEquivalentModifierMask(NSControlKeyMask or NSAlternateKeyMask or NSCommandKeyMask); newItem.setKeyEquivalentModifierMask(NSEventModifierFlags.NSControlKeyMask or NSEventModifierFlags.NSAlternateKeyMask or NSEventModifierFlags.NSCommandKeyMask); menu.addItem(newItem); end; method AppDelegate.sayHello(sender: id); begin if assigned(fMainWindowController) then begin fMainWindowController.sayHello(); end; end; method AppDelegate.sayGoodBye(sender: id); begin if assigned(fMainWindowController) then begin fMainWindowController.sayGoodBye(); end; end; end.
unit EcranTribu; interface uses Variables; { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher(Joueur : TJoueur); implementation uses GestionEcran, OptnAffichage, EcranAccueil, EcranElevage, EcranMilitaire, EcranCombat; { Actions effectuées lors d'un passage au tour suivant } procedure tourSuivant(Joueur : TJoueur); begin // On passe au jour suivant setTribu_numJour(Joueur, getTribu(Joueur).numJour + 1); // Augmentation du savoir acquis (croissance) setElevage_savoirAcquis(Joueur, getElevage(Joueur).savoirAcquis + getElevage(Joueur).savoirJour); // Les points de recrutement sont rechargés setTribu_ptsRecrutement(Joueur, getTribu(Joueur).ptsRecrutementJour); // Si une construction est en cours, on augmente le total d'équations résolues (travail) if getElevage(Joueur).construction = True then setElevage_equationsResolues(Joueur, getElevage(Joueur).equationsResolues + getElevage(Joueur).equationsJour); // Vérification des états d'avancement de la croissance et de la construction majConstruction(Joueur); majCroissance(Joueur); // Si l'archétype choisi est 'Analyste', le bonheur reste constant if getTribu(Joueur).archetype = 'Analyste' then setElevage_bonheur(Joueur, 1); { Simulation pour déterminer si le joueur subit un assaut } Randomize; // Une Tribu Probabiliste a moins de chance de se faire attaquer par surprise if getTribu(Joueur).archetype = 'Probabiliste' then if Random(100) = Random(100) then assautAleatoire(Joueur) else else if Random(40) = Random(40) then assautAleatoire(Joueur); // S'il s'agit d'une partie multijoueur, c'est au tour de l'autre joueur de jouer if getMultijoueur() = True then begin if Joueur = Joueur1 then afficher(Joueur2) else if Joueur = Joueur2 then afficher(Joueur1); end else afficher(Joueur1); end; { Récupère le choix du joueur et détermine l'action à effectuer } procedure choisir(Joueur : TJoueur); var choix : String; // Valeur entrée par la joueur begin { Déplace le curseur dans le cadre "Action" } deplacerCurseurXY(114,26); readln(choix); { Liste des choix disponibles } if (choix = '1') then begin EcranElevage.afficher(Joueur); end; if (choix = '2') then begin EcranMilitaire.afficher(Joueur); end; if (choix = '9') then tourSuivant(Joueur); if (choix = '0') then EcranAccueil.verifQuitter(Joueur) { Valeur saisie invalide } else begin setMessage('Action non reconnue'); afficher(Joueur); end; end; { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher(Joueur : TJoueur); begin effacerEcran(); { Partie supérieure de l'écran } afficherEnTete(Joueur); dessinerCadreXY(0,6, 119,28, simple, 15,0); afficherTitre('ECRAN DE GESTION DE LA TRIBU', 6); { Corps de l'écran } deplacerCurseurXY(3,10); write('Liste des Élevages :'); deplacerCurseurXY(3,11); write('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯'); afficherElevage(Joueur, 4,13); { Choix disponibles } afficherAction(3,22, '1', 'Gérer l''Élevage : ' + getElevage(Joueur).nom, 'vert'); afficherAction(3,23, '2', 'Gestion militaire et diplomatique', 'vert'); afficherAction(3,25, '9', 'Fin du tour', 'vert'); afficherAction(3,26, '0', 'Quitter la partie', 'jaune'); { Partie inférieure de l'écran } afficherMessage(); afficherCadreAction(); choisir(Joueur); end; end.
namespace com.example.android.wiktionary; {* * Copyright (C) 2007 The Android Open Source Project * * 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. *} interface uses android.app, android.appwidget, android.content, android.content.res, android.net, android.os, android.text.format, android.util, android.widget, java.util.regex; type /// <summary> /// Define a simple widget that shows the Wiktionary "Word of the day." To build /// an update we spawn a background Service to perform the API queries. /// </summary> WordWidget = public class(AppWidgetProvider) public method onUpdate(aContext: Context; appWidgetManager: AppWidgetManager; appWidgetIds: array of Integer); override; end; UpdateService nested in WordWidget = public class(Service) private //Regular expression that splits "Word of the day" entry into word //name, word type, and the first description bullet point. const WOTD_PATTERN = '(?s)\{\{wotd\|(.+?)\|(.+?)\|([^#\|]+).*?\}\}'; public method onStart(aIntent: Intent; startId: Integer); override; method buildUpdate(aContext: Context): RemoteViews; method onBind(aIntent: Intent): IBinder; override; end; implementation method WordWidget.onUpdate(aContext: Context; appWidgetManager: AppWidgetManager; appWidgetIds: array of Integer); begin // To prevent any ANR timeouts, we perform the update in a service aContext.startService(new Intent(aContext, typeOf(UpdateService))) end; method WordWidget.UpdateService.onStart(aIntent: Intent; startId: Integer); begin // Build the widget update for today var updateViews: RemoteViews := buildUpdate(self); // Push update for this widget to the home screen var thisWidget: ComponentName := new ComponentName(self, typeOf(WordWidget)); var manager: AppWidgetManager := AppWidgetManager.getInstance(self); manager.updateAppWidget(thisWidget, updateViews) end; /// <summary> /// Build a widget update to show the current Wiktionary /// "Word of the day." Will block until the online API returns. /// </summary> /// <param name="context"></param> /// <returns></returns> method WordWidget.UpdateService.buildUpdate(aContext: Context): RemoteViews; begin // Pick out month names from resources var res: Resources := aContext.Resources; var monthNames: array of String := res.StringArray[R.&array.month_names]; // Find current month and day var today: Time := new Time(); today.setToNow; // Build the page title for today, such as "March 21" var pageName: String := res.getString(R.string.template_wotd_title, monthNames[today.month], today.monthDay); var pageContent: String := nil; try // Try querying the Wiktionary API for today's word pageContent := SimpleWikiHelper.getPageContent(pageName, false); except on e: SimpleWikiHelper.ApiException do Log.e('WordWidget', 'Couldn''t contact API', e); on e: ParseException do Log.e('WordWidget', 'Couldn''t parse API response', e) end; var views: RemoteViews := nil; // Use a regular expression to parse out the word and its definition var matcher: Matcher := Pattern.compile(WOTD_PATTERN).matcher(pageContent); if matcher.find then begin // Build an update that holds the updated widget contents views := new RemoteViews(aContext.PackageName, R.layout.widget_word); var wordTitle: String := matcher.&group(1); views.setTextViewText(R.id.word_title, wordTitle); views.setTextViewText(R.id.word_type, matcher.&group(2)); views.setTextViewText(R.id.definition, matcher.&group(3).trim); // When user clicks on widget, launch to Wiktionary definition page var definePage: String := WideString.format('%s://%s/%s', ExtendedWikiHelper.WIKI_AUTHORITY, ExtendedWikiHelper.WIKI_LOOKUP_HOST, wordTitle); var defineIntent: Intent := new Intent(Intent.ACTION_VIEW, Uri.parse(definePage)); var lPendingIntent: PendingIntent := PendingIntent.getActivity(aContext, 0, defineIntent, 0); views.setOnClickPendingIntent(R.id.widget, lPendingIntent) end else begin // Didn't find word of day, so show error message views := new RemoteViews(aContext.PackageName, R.layout.widget_message); views.setTextViewText(R.id.message, aContext.String[R.string.widget_error]) end; exit views end; method WordWidget.UpdateService.onBind(aIntent: Intent): IBinder; begin // We don't need to bind to this service exit nil end; end.
program SpriteRotationTest; uses SwinGame, sgTypes; function SpriteLocationMatrix(s: Sprite): Matrix2D; var scale, newX, newY, w, h: Single; anchorMatrix: Matrix2D; begin scale := SpriteScale(s); w := SpriteLayerWidth(s, 0); h := SpriteLayerHeight(s, 0); anchorMatrix := TranslationMatrix(SpriteAnchorPoint(s)); result := IdentityMatrix(); result := MatrixMultiply(MatrixInverse(anchorMatrix), result); result := MatrixMultiply(RotationMatrix(SpriteRotation(s)), result); result := MatrixMultiply(anchorMatrix, result); newX := SpriteX(s) - (w * scale / 2.0) + (w / 2.0); newY := SpriteY(s) - (h * scale / 2.0) + (h / 2.0); result := MatrixMultiply(TranslationMatrix(newX / scale, newY / scale), result); result := MatrixMultiply(ScaleMatrix(scale), result); end; procedure Main(); var sprt, s2: Sprite; tri, initTri: Triangle; triB, initTriB: Triangle; r: Rectangle; q: Quad; begin OpenWindow('Sprite Rotation', 600, 600); OpenWindow('Other Window', 300, 300); sprt := CreateSprite(BitmapNamed('rocket_sprt.png')); SpriteSetMoveFromAnchorPoint(sprt, true); SpriteSetX(sprt, 300); SpriteSetY(sprt, 300); s2 := CreateSprite(BitmapNamed('rocket_sprt.png')); SpriteSetMoveFromAnchorPoint(s2, true); SpriteSetX(s2, 100); SpriteSetY(s2, 100); r := RectangleFrom(400, 100, 100, 50); q := QuadFrom(r); ApplyMatrix( MatrixMultiply(TranslationMatrix(0, 50), RotationMatrix(45)) , q); initTri := TriangleFrom(0, 0, BitmapWidth(BitmapNamed('rocket_sprt.png')), BitmapHeight(BitmapNamed('rocket_sprt.png')), 0, BitmapHeight(BitmapNamed('rocket_sprt.png'))); initTriB := TriangleFrom(BitmapWidth(BitmapNamed('rocket_sprt.png')), 0, BitmapWidth(BitmapNamed('rocket_sprt.png')), BitmapHeight(BitmapNamed('rocket_sprt.png')), 0, 0); repeat ProcessEvents(); ClearScreen(ColorWhite); DrawFramerate(0, 0); if KeyTyped(OKey) then SetCurrentWindow('Other Window'); if KeyTyped(MKey) then SetCurrentWindow('Sprite Rotation'); if KeyDown(LeftKey) then begin SpriteSetRotation(sprt, SpriteRotation(sprt) - 5); end; if KeyDown(RightKey) then begin SpriteSetRotation(sprt, SpriteRotation(sprt) + 5); end; if KeyDown(ShiftKey) then begin if KeyDown(UpKey) then begin SpriteSetScale(sprt, SpriteScale(sprt) + 0.1); end; if KeyDown(DownKey) then begin SpriteSetScale(sprt, SpriteScale(sprt) - 0.1); end; end else begin if KeyDown(UpKey) then begin SpriteSetDY(sprt, SpriteDY(sprt) - 0.1); end; if KeyDown(DownKey) then begin SpriteSetDY(sprt, SpriteDY(sprt) + 0.1); end; end; if KeyTyped(Num0Key) then SpriteSetRotation(sprt, 0); if KeyTyped(Num9Key) then SpriteSetRotation(sprt, 45); tri := initTri; triB := initTriB; ApplyMatrix(SpriteLocationMatrix(sprt), tri); ApplyMatrix(SpriteLocationMatrix(sprt), triB); FillTriangle(ColorGreen, tri); FillTriangle(ColorGreen, triB); tri := initTri; triB := initTriB; ApplyMatrix(SpriteLocationMatrix(s2), tri); ApplyMatrix(SpriteLocationMatrix(s2), triB); FillTriangle(ColorBlue, tri); FillTriangle(ColorBlue, triB); // FillQuad(RGBAColor(0,0,255,62), q); if SpriteRectCollision(sprt, r) then FillRectangle(ColorPink, r) else DrawRectangle(ColorPurple, r); DrawBitmap('ufo.png', 400, 300); if SpriteBitmapCollision(sprt, BitmapNamed('ufo.png'), 400, 300) then DrawRectangle(ColorPurple, 400, 300, BitmapWidth(BitmapNamed('ufo.png')), BitmapHeight(BitmapNamed('ufo.png'))); if SpriteAtPoint(sprt, MousePosition()) then FillCircle(ColorYellow, SpriteCollisionCircle(sprt)); DrawSprite(sprt); DrawSprite(s2); UpdateSprite(sprt); if SpriteCollision(sprt, s2) then begin DrawCircle(ColorRed, SpriteCollisionCircle(s2)); end; DrawCircle(ColorGreen, SpriteCollisionCircle(sprt)); DrawRectangle(ColorGreen, SpriteCollisionRectangle(sprt)); DrawLine(ColorGreen, LineFromVector(CenterPoint(sprt), MatrixMultiply(RotationMatrix(SpriteRotation(sprt)), VectorMultiply(SpriteVelocity(sprt), 10.0)))); RefreshScreen(); until WindowCloseRequested(); end; begin Main(); end.
unit ThDbTextArea; interface uses Classes, DB, DBCtrls, ThTextArea, ThDbData; type TThCustomDbTextArea = class(TThTextArea) private FData: TThDbData; protected function GetFieldName: string; function GetDataSource: TDataSource; procedure SetFieldName(const Value: string); procedure SetDataSource(const Value: TDataSource); protected procedure DataChange(Sender: TObject); function GetFieldText: string; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected property Data: TThDbData read FData; property FieldName: string read GetFieldName write SetFieldName; property DataSource: TDataSource read GetDataSource write SetDataSource; end; // TThDbTextArea = class(TThCustomDbTextArea) published property FieldName; property DataSource; end; implementation { TThCustomDbTextArea } constructor TThCustomDbTextArea.Create(AOwner: TComponent); begin inherited; FData := TThDbData.Create; FData.OnDataChange := DataChange; end; destructor TThCustomDbTextArea.Destroy; begin FData.Free; inherited; end; procedure TThCustomDbTextArea.DataChange(Sender: TObject); begin Lines.Text := GetFieldText; Invalidate; end; function TThCustomDbTextArea.GetFieldText: string; begin Result := Data.FieldText; end; procedure TThCustomDbTextArea.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; Data.Notification(AComponent, Operation); end; function TThCustomDbTextArea.GetFieldName: string; begin Result := Data.FieldName; end; function TThCustomDbTextArea.GetDataSource: TDataSource; begin Result := Data.DataSource; end; procedure TThCustomDbTextArea.SetFieldName(const Value: string); begin Data.FieldName := Value; end; procedure TThCustomDbTextArea.SetDataSource(const Value: TDataSource); begin if DataSource <> nil then DataSource.RemoveFreeNotification(Self); Data.DataSource := Value; if DataSource <> nil then DataSource.FreeNotification(Self); end; end.
unit Chapter09._09_Solution2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.UString, DeepStar.Utils; /// LCS问题 /// 动态规划 /// 时间复杂度: O(len(s1)*len(s2)) /// 空间复杂度: O(len(s1)*len(s2)) type TSolution = class(TObject) public function GetLCS(const s1, s2: UString): UString; end; procedure Main; implementation procedure Main; var s1, s2: UString; begin s1 := 'ABCD'; s2 := 'AEBD'; with TSolution.Create do begin WriteLn(GetLCS(s1, s2)); Free; end; end; { TSolution } function TSolution.GetLCS(const s1, s2: UString): UString; var m, n, j, k, i: integer; memo: TArr2D_int; res: UString; begin m := Length(s1); n := Length(s2); SetLength(memo, m, n); // 对memo的第0行和第0列进行初始化 for j := 0 to n - 1 do begin if s1.Chars[0] = s2.Chars[j] then begin for k := j to n - 1 do memo[0, k] := 1; Break; end; end; for i := 0 to m - 1 do begin if s1.Chars[i] = s2.Chars[0] then begin for k := i to m - 1 do memo[0, k] := 1; Break; end; end; // 动态规划的过程 for i := 1 to m - 1 do for j := 1 to n - 1 do if s1.Chars[i] = s2.Chars[j] then memo[i, j] := 1 + memo[i - 1, j - 1] else memo[i, j] := Max(memo[i - 1, j], memo[i, j - 1]); // 通过memo反向求解s1和s2的最长公共子序列 m := Length(s1) - 1; n := Length(s2) - 1; res := ''; while (m >= 0) and (n >= 0) do begin if s1.Chars[m] = s2.Chars[n] then begin res := s1.Chars[m] + res; m -= 1; n -= 1; end else if m = 0 then n -= 1 else if n = 0 then m -= 1 else begin if memo[m - 1, n] > memo[m, n - 1] then m -= 1 else n -= 1; end; end; Result := res; end; end.
unit mckLVColumnsEditor; interface {$I KOLDEF.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, {$IFDEF _D6orHigher} DesignIntf, DesignEditors, DesignConst, Variants {$ELSE} DsgnIntf {$ENDIF} ; type TfmLVColumnsEditor = class(TForm) private pnButtons: TPanel; pnView: TPanel; btAdd: TButton; btDel: TButton; btUp: TButton; btDown: TButton; chkStayOnTop: TCheckBox; lvColumns: TListView; procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure chkStayOnTopClick(Sender: TObject); procedure btAddClick(Sender: TObject); procedure btDelClick(Sender: TObject); procedure btUpClick(Sender: TObject); procedure btDownClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lvColumnsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); {$IFDEF VER90} {$DEFINE OLDDELPHI} {$ENDIF} {$IFDEF VER100} {$DEFINE OLDDELPHI} {$ENDIF} {$IFDEF OLDDELPHI} procedure lvColumnsChange(Sender: TObject; Item: TListItem; Change: TItemChange); {$ENDIF} procedure lvColumnsEdited(Sender: TObject; Item: TListItem; var S: String); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FListView: TComponent; procedure SetListView(const Value: TComponent); procedure AdjustButtons; procedure SelectLV; public { Public declarations } property ListView: TComponent read FListView write SetListView; procedure MakeActive( SelectAny: Boolean ); constructor Create( AOwner: TComponent ); override; end; var fmLVColumnsEditor: TfmLVColumnsEditor; implementation uses mirror, mckCtrls, mckObjs; procedure TfmLVColumnsEditor.AdjustButtons; var LI: TListItem; begin LI := lvColumns.Selected; if LI = nil then begin btAdd.Enabled := lvColumns.Items.Count = 0; btDel.Enabled := FALSE; btUp.Enabled := FALSE; btDown.Enabled := FALSE; end else begin btAdd.Enabled := TRUE; btDel.Enabled := TRUE; btUp.Enabled := LI.Index > 0; btDown.Enabled := LI.Index < lvColumns.Items.Count - 1; end; end; procedure TfmLVColumnsEditor.FormResize(Sender: TObject); begin lvColumns.Columns[ 0 ].Width := lvColumns.ClientWidth; end; procedure TfmLVColumnsEditor.MakeActive(SelectAny: Boolean); var F: TForm; D: IDesigner; FD: IFormDesigner; Col: TKOLListViewColumn; begin if lvColumns.Items.Count > 0 then if lvColumns.Selected = nil then if SelectAny then lvColumns.Selected := lvColumns.Items[ 0 ]; if lvColumns.Selected <> nil then begin Col := lvColumns.Selected.Data; F := (FListView as TKOLListView).Owner as TForm; if F <> nil then begin {$IFDEF _D6orHigher} F.Designer.QueryInterface(IFormDesigner,D); {$ELSE} D := F.Designer; {$ENDIF} if D <> nil then if QueryFormDesigner( D, FD ) then begin RemoveSelection( FD ); FD.SelectComponent( Col ); end; end; end; AdjustButtons; end; procedure TfmLVColumnsEditor.SetListView(const Value: TComponent); var LV: TKOLListView; begin FListView := Value; LV := FListView as TKOLListView; Caption := LV.Name + ' columns'; end; procedure TfmLVColumnsEditor.FormShow(Sender: TObject); var I: Integer; LI: TListItem; Col: TKOLListViewColumn; LV: TKOLListView; begin lvColumns.Items.BeginUpdate; TRY lvColumns.Items.Clear; if FListView <> nil then if FListView is TKOLListView then begin LV := FListView as TKOLListView; for I := 0 to LV.Cols.Count-1 do begin LI := lvColumns.Items.Add; Col := LV.Cols[ I ]; LI.Data := Col; LI.Caption := Col.Caption; end; end; FINALLY lvColumns.Items.EndUpdate; END; end; procedure TfmLVColumnsEditor.chkStayOnTopClick(Sender: TObject); begin if chkStayOnTop.Checked then FormStyle := fsStayOnTop else FormStyle := fsNormal; end; procedure TfmLVColumnsEditor.btAddClick(Sender: TObject); var LI: TListItem; Col: TKOLListViewColumn; LV: TKOLListView; I: Integer; S: String; begin if FListView = nil then Exit; if not( FListView is TKOLListView ) then Exit; LV := FListView as TKOLListView; LI := lvColumns.Selected; if LI = nil then begin Col := TKOLListViewColumn.Create( LV ); LI := lvColumns.Items.Add; LI.Data := Col; end else begin if LI.Index >= lvColumns.Items.Count then Col := TKOLListViewColumn.Create( LV ) else begin Col := TKOLListViewColumn.Create( LV ); LV.Cols.Move( lvColumns.Items.Count, LI.Index + 1 ); end; LI := lvColumns.Items.Insert( LI.Index + 1 ); LI.Data := Col; end; if LV <> nil then if LV.Owner is TForm then for I := 1 to MaxInt do begin S := 'Col' + IntToStr( I ); if (LV.Owner as TForm).FindComponent( S ) = nil then if LV.FindComponent( S ) = nil then begin Col.Name := S; break; end; end; if LV.HasOrderedColumns then Col.LVColOrder := LI.Index; lvColumns.Selected := nil; lvColumns.Selected := LI; lvColumns.ItemFocused := LI; LI.MakeVisible( FALSE ); LI.EditCaption; end; procedure TfmLVColumnsEditor.btDelClick(Sender: TObject); var LI: TListItem; J: Integer; Col: TKOLListViewColumn; begin LI := lvColumns.Selected; if LI <> nil then begin J := LI.Index; Col := LI.Data; Col.Free; LI.Free; if J >= lvColumns.Items.Count then Dec( J ); if J >= 0 then begin lvColumns.Selected := lvColumns.Items[ J ]; lvColumns.ItemFocused := lvColumns.Selected; end; end; AdjustButtons; if lvColumns.Items.Count = 0 then SelectLV; end; procedure TfmLVColumnsEditor.btUpClick(Sender: TObject); var LI, LI1: TListItem; I: Integer; LV: TKOLListView; Col: TKOLListViewColumn; begin if FListView = nil then Exit; if not(FListView is TKOLListView) then Exit; LV := FListView as TKOLListView; LI := lvColumns.Selected; if LI = nil then Exit; I := LI.Index - 1; LI1 := lvColumns.Items.Insert( I ); LI1.Caption := LI.Caption; LI1.Data := LI.Data; LV.Cols.Move( I + 1, I ); LI.Free; lvColumns.Selected := LI1; lvColumns.ItemFocused := LI1; Col := LI1.Data; if Col.LVColOrder = LI1.Index + 1 then Col.LVColOrder := LI1.Index; AdjustButtons; end; procedure TfmLVColumnsEditor.btDownClick(Sender: TObject); var LI, LI1: TListItem; LV: TKOLListView; Col: TKOLListViewColumn; begin if FListView = nil then Exit; if not(FListView is TKOLListView) then Exit; LV := FListView as TKOLListView; LI := lvColumns.Selected; if LI = nil then Exit; LV.Cols.Move( LI.Index, LI.Index + 1 ); LI1 := lvColumns.Items.Insert( LI.Index + 2 ); LI1.Caption := LI.Caption; LI1.Data := LI.Data; LI.Free; lvColumns.Selected := LI1; lvColumns.ItemFocused := LI1; Col := LI1.Data; if Col.LVColOrder = LI1.Index - 1 then Col.LVColOrder := LI1.Index; AdjustButtons; end; procedure TfmLVColumnsEditor.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT: btAdd.Click; VK_DELETE: if not lvColumns.IsEditing then btDel.Click; VK_RETURN: if (ActiveControl = lvColumns) and not lvColumns.IsEditing and (lvColumns.Selected <> nil) then lvColumns.Selected.EditCaption; VK_UP: if (GetKeyState( VK_CONTROL ) < 0) then btUp.Click else Exit; VK_DOWN: if (GetKeyState( VK_CONTROL ) < 0) then btDown.Click else Exit; else Exit; end; Key := 0; end; procedure TfmLVColumnsEditor.lvColumnsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then MakeActive( FALSE ); end; {$IFDEF OLDDELPHI} procedure TfmLVColumnsEditor.lvColumnsChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if lvColumns.Selected <> nil then MakeActive( FALSE ); end; {$ENDIF} procedure TfmLVColumnsEditor.lvColumnsEdited(Sender: TObject; Item: TListItem; var S: String); var Col: TKOLListViewColumn; begin if Item = nil then Exit; Col := Item.Data; Col.Caption := S; MakeActive( FALSE ); end; procedure TfmLVColumnsEditor.FormDestroy(Sender: TObject); var LV: TKOLListView; begin if FListView = nil then Exit; LV := FListView as TKOLListView; LV.ActiveDesign := nil; end; procedure TfmLVColumnsEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin Rpt( 'Closing Listview columns editor', WHITE ); SelectLV; modalResult := mrOK; end; procedure TfmLVColumnsEditor.SelectLV; var F: TForm; D: IDesigner; FD: IFormDesigner; begin if FListView <> nil then begin F := (FListView as TKOLListView).Owner as TForm; if F <> nil then begin Rpt( 'Form found: ' + F.Name, WHITE ); {$IFDEF _D6orHigher} // F.Designer.QueryInterface(IFormDesigner,D); // {$ELSE} // D := F.Designer; {$ENDIF} // if D <> nil then begin Rpt( 'IDesigner interface returned', WHITE ); if QueryFormDesigner( D, FD ) then begin Rpt( 'IFormDesigner interface quered', WHITE ); try RemoveSelection( FD ); FD.SelectComponent( FListView ); except Rpt( 'EXCEPTION *** Could not clear selection!', WHITE ) end; end; end; end; end; end; constructor TfmLVColumnsEditor.Create(AOwner: TComponent); begin CreateNew(AOwner); Left := 246; Top := 107; Width := 268; Height := 314; HorzScrollBar.Visible := False; VertScrollBar.Visible := False; BorderIcons := [biSystemMenu]; Caption := 'Columns'; //Color := clBtnFace; //Font.Charset := DEFAULT_CHARSET; //Font.Color := clWindowText; //Font.Height := -11; Font.Name := 'MS Sans Serif'; //Font.Style := []; KeyPreview := True; //OldCreateOrder := False; Scaled := False; OnClose := FormClose; OnDestroy := FormDestroy; OnKeyDown := FormKeyDown; OnResize := FormResize; OnShow := FormShow; PixelsPerInch := 96; //TextHeight := 13; pnButtons := TPanel.Create( Self ); with pnButtons do begin Parent := Self; Left := 150; Top := 0; Width := 110; Height := 287; Align := alRight; BevelOuter := bvNone; TabOrder := 0; btAdd := TButton.Create( pnButtons ); with btAdd do begin Parent := pnButtons; Left := 4; Top := 4; Width := 101; Height := 25; Caption := '&Add'; TabOrder := 0; OnClick := btAddClick; end; btDel := TButton.Create( pnButtons ); with btDel do begin Parent := pnButtons; Left := 4; Top := 36; Width := 101; Height := 25; Caption := '&Delete'; TabOrder := 1; OnClick := btDelClick; end; btUp := TButton.Create( pnButtons ); with btUp do begin Parent := pnButtons; Left := 4; Top := 68; Width := 49; Height := 25; Caption := '&Up'; TabOrder := 2; OnClick := btUpClick; end; btDown := TButton.Create( pnButtons ); with btDown do begin Parent := pnButtons; Left := 56; Top := 68; Width := 49; Height := 25; Caption := '&Down'; TabOrder := 3; OnClick := btDownClick; end; chkStayOnTop := TCheckBox.Create( pnButtons ); with chkStayOnTop do begin Parent := pnButtons; Left := 4; Top := 100; Width := 101; Height := 17; Caption := 'Stay On &Top'; TabOrder := 4; OnClick := chkStayOnTopClick; end; end; pnView := TPanel.Create( Self ); with pnView do begin Parent := Self; Left := 0; Top := 0; Width := 150; Height := 287; Align := alClient; BevelOuter := bvNone; BorderWidth := 4; TabOrder := 1; lvColumns := TListView.Create( pnView ); with lvColumns do begin Parent := pnView; Left := 4; Top := 4; Width := 142; Height := 279; Align := alClient; Columns.Add; HideSelection := False; {$IFNDEF VER90} RowSelect := True; {$ENDIF} ShowColumnHeaders := False; TabOrder := 0; ViewStyle := vsReport; OnEdited := lvColumnsEdited; {$IFDEF OLDDELPHI} OnChange := lvColumnsChange; {$ELSE} OnSelectItem := lvColumnsSelectItem; {$ENDIF} end; end; end; end.
program HelloWorld; uses sgTypes, SwinGame, sgBackendTypes, GeometryHelper; procedure KeepOnScreen(s: Sprite); begin if SpriteX(s) > ScreenWidth() - SpriteWidth(s) then begin SpriteSetDX(s, -SpriteDX(s)); SpriteSetX(s, ScreenWidth() - SpriteWidth(s)); end; if SpriteY(s) > ScreenHeight() - SpriteHeight(s) then begin SpriteSetDY(s, -SpriteDY(s)); SpriteSetY(s, ScreenHeight() - SpriteHeight(s)); end; if SpriteX(s) < 0 then begin SpriteSetDX(s, -SpriteDX(s)); SpriteSetX(s, 0); end; if SpriteY(s) < 0 then begin SpriteSetDY(s, -SpriteDY(s)); SpriteSetY(s, 0); end; end; procedure DoLineTest(testLines: LinesArray; const center: Point2D; radius: Longint; movement: Vector); type DoublePt = record ptOnCircle, ptOnLine: Point2D; end; var pt1, pt2, ptOnLine, ptOnCircle, hitPt, maxHitPtOnLine, maxHitPtOnCircle, outPt: Point2D; tmp: Array [0..3] of Point2D; chkPts: Array [0..3] of DoublePt; lineVec, normalMvmt, normalLine, toEdge, edge, ray, vOut: Vector; i, j, maxIdx, hits: Integer; dotProd, dist, maxDist: Single; begin exit; // Cast ray searching for points back from shape ray := InvertVector(movement); normalMvmt := VectorNormal(movement); maxIdx := -1; maxDist := -1; //Search all lines for hit points for i := 0 to High(testLines) do begin lineVec := LineAsVector(testLines[i]); //Get the normal of the line we hit normalLine := VectorNormal(lineVec); hits := 0; //tmp 0 and tmp 1 are the widest points to detect collision with line WidestPoints(CircleAt(center, radius), normalMvmt, tmp[0], tmp[1]); //tmp 2 and tmp 3 are the closest and furthest points from the line WidestPoints(CircleAt(center, radius), normalLine, tmp[2], tmp[3]); // for both points... for j := 0 to 3 do begin //DrawCircle(ColorWhite, tmp[j], 2); // Cast a ray back from the test points to find line pts... out on ptOnLine if RayIntersectionPoint(tmp[j], ray, testLines[i], ptOnLine) then begin //DrawCircle(ColorRed, ptOnLine, 1); //DrawLine(ColorRed, tmp[j], ptOnLine); chkPts[hits].ptOnLine := ptOnLine; chkPts[hits].ptOnCircle := tmp[j]; hits := hits + 1; end; end; // for each of the hits on this line... // search for the longest hit. for j := 0 to hits - 1 do begin //DrawCircle(ColorWhite, chkPts[j].ptOnCircle, 1); toEdge := VectorFromPoints(center, chkPts[j].ptOnCircle); //DrawLine(ColorRed, center, chkPts[j].ptOnCircle); dotProd := DotProduct(toEdge, normalLine); // 2d: Most distant edge pt is on a line this distance (dotProd) from the center edge := AddVectors(center, VectorMultiply(normalLine, dotProd)); //DrawPixel(ColorWhite, edge); // Draws pt on line to distant pt // Find the point we hit on the line... ptOnLine receives intersection point... if not LineIntersectionPoint(LineFromVector(edge, movement), testLines[i], ptOnLine) then continue; // Move back onto line segment... linePt -> closest point on line to intersect point //DrawCircle(ColorRed, ptOnLine, 1); // point on line, but not necessarily the line segment //DrawLine(ColorWhite, edge, ptOnLine); ptOnLine := ClosestPointOnLine(ptOnLine, testLines[i]); //FillCircle(ColorBlue, ptOnLine, 1); // point on segment // Find the most distant point on the circle, given the movement vector if not DistantPointOnCircleHeading(ptOnLine, CircleAt(center, radius), movement, ptOnCircle) then continue; //FillCircle(ColorBlue, ptOnCircle, 2); // point on segment //DrawLine(ColorBlue, ptOnLine, ptOnCircle); // GetTangentPoints(testLines[i].endPoint, center, radius, pt1, pt2); // DrawCircle(ColorRed, pt1, 2); // DrawCircle(ColorRed, pt2, 2); dist := PointPointDistance(ptOnLine, ptOnCircle); //WriteLn(dist); if (dist > maxDist) or (maxIdx = -1) then begin maxDist := dist; maxIdx := i; vOut := VectorFromPoints(ptOnCircle, ptOnLine); //dotProd := DotProduct(UnitVector(vOut), VectorTo(0.5,0.5)); vOut := VectorMultiply(UnitVector(vOut), VectorMagnitude(vOut) + 1.42); WriteLn(dotProd:4:2); end; end; end; if maxIdx > -1 then begin WriteLn('---'); DrawLine(ColorGreen, LineFromVector(center, vOut)); outPt := AddVectors(center, vOut); DrawCircle(ColorGreen, outPt.x, outPt.y, radius); end; end; procedure CheckCollisionWithLine(s: Sprite; const l: LineSegment); begin if CircleLineCollision(s, l) then begin CollideCircleLine(s, l); end; end; procedure CheckCollisionWithTriangle(s: Sprite; const t: Triangle); var lines: LinesArray; begin if CircleTriangleCollision(SpriteCircle(s), t) then begin CollideCircleTriangle(s, t); end; end; procedure Main(); var c1, rectPt, ptOut, temp, tmp, edge: Point2D; r1, r2: Longint; rect, rect1: Rectangle; s1, s2: Sprite; found: LineSegment; mouseMvmt, mouseOut, ptOnCircle, toCenter, oppositePt, toCircle: Vector; nrm, rm: Matrix2D; t1: Triangle; i, maxIDx: Integer; dist, dotProd: Single; checkPoints: array [0..2] of Point2D; testLines: LinesArray; begin OpenAudio(); OpenGraphicsWindow('Circle Collisions', 800, 600); LoadDefaultColors(); LoadBitmapNamed('ball', 'ball_small.png'); SetLength(testLines, 1); testLines[0] := LineFrom(300, 250, 500, 350); rm := RotationMatrix(1.0); nrm := RotationMatrix(-1.0); c1 := PointAt(100, 100); r1 := 50; r2 := 20; s1 := CreateSprite(BitmapNamed('ball')); SpriteSetX(s1, 100); SpriteSetY(s1, 600); SpriteSetMass(s1, 10); SpriteSetVelocity(s1, VectorTo(4, 4)); s2 := CreateSprite(BitmapNamed('ball')); SpriteSetX(s2, 200); SpriteSetY(s2, 200); SpriteSetMass(s2, 10); SpriteSetVelocity(s2, VectorTo(1, -5)); t1 := TriangleFrom(600, 100, 550, 200, 670, 175); mouseMvmt := VectorTo(1,1); rect := RectangleFrom(400, 300, 200, 200); rect1 := RectangleFrom(420, 420, 10, 20); ShowMouse(False); repeat // The game loop... ProcessEvents(); ClearScreen(ColorBlack); DrawRectangle(ColorRed, rect); DrawRectangle(ColorRed, rect1); DrawCircle(ColorRed, c1.x, c1.y, r1); DrawTriangle(ColorRed, t1); for i := 0 to High(testLines) do begin DrawLine(ColorRed, testLines[i]); end; temp := MousePosition(); DoLineTest(testLines, temp, r2, mouseMvmt); // if not CircleWithinRect(CircleAt(temp, r2), rect) then // begin // mouseOut := VectorIntoRectFromCircle(CircleAt(temp, r2), rect, mouseMvmt); // DrawLine(ColorWhite, temp, AddVectors(temp, mouseOut)); // DrawCircle(ColorWhite, AddVectors(temp, mouseOut), r2); // end; if CircleRectCollision(CircleAt(temp, r2), rect) then begin DrawCircle(ColorBlue, temp.x, temp.y, r2); mouseOut := VectorOutOfRectFromCircle(CircleAt(temp, r2), rect, mouseMvmt); DrawCircle(ColorGreen, temp.x + mouseOut.x, temp.y + mouseOut.y, r2); end else if CircleCircleCollision(CircleAt(temp, r2), CircleAt(c1, r1)) then begin DrawCircle(ColorWhite, c1.x, c1.y, r1); DrawCircle(ColorBlue, temp.x, temp.y, r2); mouseOut := VectorOutOfCircleFromCircle(CircleAt(temp, r2), CircleAt(c1, r1), mouseMvmt); mouseOut := AddVectors(temp, mouseOut); DrawCircle(ColorGreen, mouseOut.x, mouseOut.y, r2); end else if CircleTriangleCollision(CircleAt(temp, r2), t1) then begin //DrawTriangle(ColorWhite, t1); DrawCircle(ColorBlue, temp.x, temp.y, r2); mouseOut := VectorOverLinesFromCircle(CircleAt(temp, r2), LinesFrom(t1), mouseMvmt, maxIdx); mouseOut := AddVectors(temp, mouseOut); DrawCircle(ColorGreen, mouseOut.x, mouseOut.y, r2); DrawLine(ColorWhite, LinesFrom(t1)[maxIdx]); //LineOfLinesCircleHit(temp, r2, mouseMvmt, LinesFrom(t1), found); end else begin DrawCircle(ColorGreen, temp.x, temp.y, r2); end; // rectPt := ClosestPointOnRectFromCircle(temp, r2, rect); // // ptOut := DeepestPointOnCircleVsRectWithMovement(temp, r2, rect, mouseMvmt); // // mouseOut := VectorOutOfRectFromCircle(temp, r2, rect, mouseMvmt); if KeyDown(RightKey) then mouseMvmt := MatrixMultiply(rm, mouseMvmt); if KeyDown(LeftKey) then mouseMvmt := MatrixMultiply(nrm, mouseMvmt); if KeyDown(RKey) then begin tmp := AddVectors(InvertVector(mouseMvmt), temp); MoveMouse(Round(tmp.x), Round(tmp.y)); end else if KeyDown(FKey) then begin tmp := AddVectors(mouseMvmt, temp); MoveMouse(Round(tmp.x), Round(tmp.y)); end; // DrawCircle(ColorYellow, ptOut, 2); // //DrawLine(ColorWhite, temp, rectPt); // //DrawLine(ColorYellow, temp, ptOut); // // DrawLine(ColorBlue, temp.x, temp.y, temp.x + (mouseMvmt.x * 10), temp.y + (mouseMvmt.y * 10)); // //DrawLine(ColorYellow, temp.x, temp.y, temp.x + mouseOut.x, temp.y + mouseOut.y); // // temp := PointAt(temp, mouseOut); // DrawCircle(ColorYellow, temp, r2); // DrawSprite(s1); temp := CenterPoint(s1); DrawCircle(ColorBlue, SpriteCircle(s1)); DrawLine(ColorBlue, temp.x, temp.y, temp.x + (SpriteDX(s1) * 10), temp.y + (SpriteDY(s1) * 10)); UpdateSprite(s1); KeepOnScreen(s1); if CircleRectCollision(SpriteCircle(s1), rect) then CollideCircleRectangle(s1, rect) else if CircleCircleCollision(SpriteCircle(s1), CircleAt(c1, r1)) then CollideCircleCircle(s1, CircleAt(c1, r1)); DrawSprite(s2); temp := CenterPoint(s2); DrawCircle(ColorYellow, SpriteCircle(s2)); DrawLine(ColorYellow, temp.x, temp.y, temp.x + (SpriteDX(s2) * 10), temp.y + (SpriteDY(s2) * 10)); UpdateSprite(s2); KeepOnScreen(s2); if CircleRectCollision(SpriteCircle(s2), rect) then CollideCircleRectangle(s2, rect) else if CircleCircleCollision(SpriteCircle(s2), CircleAt(c1, r1)) then CollideCircleCircle(s2, CircleAt(c1, r1)); CheckCollisionWithLine(s1, testLines[0]); CheckCollisionWithLine(s2, testLines[0]); CheckCollisionWithTriangle(s1, t1); CheckCollisionWithTriangle(s2, t1); temp := MousePosition(); if CircleCircleCollision(CircleAt(temp, r2), SpriteCircle(s1)) then CollideCircleCircle(s1, CircleAt(temp, r2)); if CircleCircleCollision(CircleAt(temp, r2), SpriteCircle(s2)) then CollideCircleCircle(s2, CircleAt(temp, r2)); if SpriteCollision(s1, s2) then CollideCircles(s1, s2); temp := VectorOutOfRectFromPoint(temp, rect, mouseMvmt); DrawLine(ColorYellow, MousePosition(), AddVectors(temp, MousePosition())); temp := VectorOutOfRectFromRect(rect1, rect, mouseMvmt); DrawLine(ColorYellow, VectorTo(rect1.x, rect1.y), AddVectors(temp, VectorTo(rect1.x, rect1.y))); // temp := VectorIntoRectFromRect(rect1, rect, mouseMvmt); // DrawLine(ColorWhite, VectorTo(rect1.x, rect1.y), AddVectors(temp, VectorTo(rect1.x, rect1.y))); DrawFramerate(0,0); RefreshScreen(60); until WindowCloseRequested(); CloseAudio(); end; begin Main(); end.
PROGRAM Test3; PROCEDURE Union(a, b: ARRAY OF INTEGER; countA, countB: INTEGER; VAR result: ARRAY OF INTEGER; VAR countResult: INTEGER); VAR i, j: INTEGER; BEGIN i := 0; j := 0; countResult := 0; WHILE (i < countA) and (j < countB) DO BEGIN IF a[i] < b[j] THEN BEGIN result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; END; IF b[j] < a[i] THEN BEGIN result[countResult] := b[j]; countResult := countResult + 1; j := j + 1 END; IF a[i] = b [j] THEN BEGIN result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; j := j + 1 END; END; IF i < countA THEN BEGIN WHILE (i <= countA) DO BEGIN result[countResult] := a[i]; countResult := countResult + 1; i := i + 1; END; END; IF j < countB THEN BEGIN WHILE (j <= countB) DO BEGIN result[countResult] := b[j]; countResult := countResult + 1; j := j + 1; END; END; if countResult = 0 THEN result[0] := 1; END; FUNCTION QuickTest(a, b: INTEGER): BOOLEAN; BEGIN QuickTest := (a = b) END; var arrA: ARRAY [0..5] OF INTEGER; arrB: ARRAY [0..4] OF INTEGER; test: ARRAY [0..4] OF INTEGER; test2: ARRAY [0..4] OF INTEGER; test4: ARRAY OF INTEGER; countA: INTEGER; countB: INTEGER; result: ARRAY [0..10] OF INTEGER; countResult: INTEGER; i: INTEGER; haha: BOOLEAN; wtf: INTEGER; wtf2: STRING; wtf3: REAL; day, month, year: INTEGER; s: STRING; begin // wtf := 3; // WriteLn(Ord(wtf)); // wtf3 := 0.1993; // IF wtf3 < 1 THEN // WriteLn(wtf3); s := '10.12.1995'; // WriteLn(wtf2[3]); // WriteLn(Length(wtf2)); day := ((ord(s[1]) - 48) * 10 + (ord(s[2]) - 48)); month := ((ord(s[4]) - 48) * 10 + (ord(s[5]) - 48)); year := ((ord(s[7]) - 48) * 1000 + (ord(s[8]) - 48) * 100 + (ord(s[9]) - 48) * 10 + (ord(s[10]) - 48)); // IF (day <= 31) and (day > 0) THEN // IF (month <= 12) and (month > 0) THEN // IF (year <= 9999) and (year >= 1753) THEN BEGIN // WriteLn(day); // WriteLn(month); // WriteLn(year); // END; FOR i := 0 downto -10 DO BEGIN WriteLn(i); END; // WriteLn(day); // WriteLn(month); // WriteLn(year); // FOR i := 1 TO Length(wtf2) DO BEGIN // WriteLn(ord(wtf2[i]) - 48); // END; // wtf2 := '1'; // WriteLn(Ord(wtf2)); // wtf2 := '' + wtf; // SetLength(test4, 8); // WriteLn('asdf: ', Length(test4)); // FOR i := 0 TO Length(test4)-1 DO BEGIN // WriteLn(test4[i]) // END; // arrA[0] := 2; // arrA[1] := 2; // arrA[2] := 3; // arrA[3] := 3; // arrA[4] := 7; // arrB[0] := 3; // arrB[1] := 3; // arrB[2] := 37; // test[0] := 1; // test[1] := 2; // test2[0] := 1; // test2[1] := 2; // countA := 5; // countB := 3; // Union(arrA, arrB, countA, countB, result, countResult); // // FOR i := 0 TO countResult DO BEGIN // // WriteLn(result[i]) // // END; // WriteLn('finished'); // haha := QuickTest(1, 1); // WriteLn('haha: ', haha) end.
unit LiteButton; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, uColorTheme, uUtils, uParser; { Lite Button } type TLiteButton = class(TPanel, IUnknown, IThemeSupporter) private theme: ColorTheme; isPressed: boolean; isTriggerable: boolean; shouldReact: boolean; protected public constructor Create(AOwner: TComponent); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; // IThemeSupporter procedure setTheme(theme: ColorTheme); function getTheme(): ColorTheme; procedure updateColors(); function isActive(): boolean; procedure setActive(b: boolean); published property IsTrigger: boolean read isTriggerable write isTriggerable; property AutoReact: boolean read shouldReact write shouldReact; end; procedure Register; implementation procedure Register; begin RegisterComponents('Lite', [TLiteButton]); end; // Override constructor TLiteButton.Create(AOwner: TComponent); begin inherited Create(AOwner); isPressed := false; shouldReact := true; isTriggerable := false; theme := CT_DEFAULT_THEME; updateColors(); // other BevelOuter := bvNone; Font.Size := 15; Font.Name := 'Consolas'; Width := 144; Height := 32; end; // Override procedure TLiteButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if shouldReact then isPressed := not isPressed; // to work with updated state updateColors(); inherited MouseDown(Button, Shift, X, Y); end; // Override procedure TLiteButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not isTriggerable and shouldReact then isPressed := false; updateColors(); inherited MouseUp(Button, Shift, X, Y); end; // Override procedure TLiteButton.setTheme(theme: ColorTheme); begin self.theme := theme; // link end; // Override function TLiteButton.getTheme(): ColorTheme; begin getTheme := theme; end; // Override procedure TLiteButton.updateColors(); begin Font.Color := theme.text; if isPressed then Color := theme.active else Color := theme.interact; end; function TLiteButton.isActive(): boolean; begin isActive := isPressed; end; procedure TLiteButton.setActive(b: boolean); begin isPressed := b; end; end.
unit UnitRefreshDBRecordsThread; interface uses Winapi.ActiveX, System.Classes, System.SysUtils, Vcl.Forms, UnitPropeccedFilesSupport, UnitDBDeclare, uLogger, uMemory, uDBUtils, uDBContext, uDBEntities, uCollectionEvents, uDBForm, uDBThread, uConstants; type TRefreshIDRecordThreadOptions = record Info: TMediaItemCollection; end; type TRefreshDBRecordsThread = class(TDBThread) private { Private declarations } FContext: IDBContext; FInfo: TMediaItemCollection; ProgressWindow: TForm; BoolParam: Boolean; Count: Integer; IntParam: Integer; StrParam: string; DBEvent_Sender: TDBForm; DBEvent_ID: Integer; DBEvent_Params: TEventFields; DBEvent_Value: TEventValues; protected procedure Execute; override; public constructor Create(Context: IDBContext; Owner: TDBForm; Options: TRefreshIDRecordThreadOptions); destructor Destroy; override; procedure InitializeProgress; procedure DestroyProgress; procedure IfBreakOperation; procedure SetProgressPosition(Position: Integer); procedure SetProgressPositionSynch; procedure DoDBkernelEvent; procedure DoDBkernelEventRefreshList; procedure OnDBKernelEventProcedureSunch; end; implementation uses ProgressActionUnit; { TRefreshDBRecordsThread } constructor TRefreshDBRecordsThread.Create(Context: IDBContext; Owner: TDBForm; Options: TRefreshIDRecordThreadOptions); var I: Integer; begin inherited Create(Owner, False); FContext := Context; DBEvent_Sender := Owner; FInfo := TMediaItemCollection.Create; FInfo.Assign(Options.Info); for I := 0 to FInfo.Count - 1 do if FInfo[I].ID <> 0 then if FInfo[I].Selected then ProcessedFilesCollection.AddFile(FInfo[I].FileName); DoDBKernelEventRefreshList; end; procedure TRefreshDBRecordsThread.Execute; var I, J: Integer; C: Integer; begin inherited; FreeOnTerminate := True; CoInitializeEx(nil, COM_MODE); try Count := 0; for I := 0 to FInfo.Count - 1 do if FInfo[I].ID <> 0 then if FInfo[I].Selected then Inc(Count); SynchronizeEx(InitializeProgress); C := 0; for I := 0 to FInfo.Count - 1 do begin if FInfo[I].ID <> 0 then if FInfo[I].Selected then begin SynchronizeEx(IfBreakOperation); if BoolParam then begin for J := I to FInfo.Count - 1 do ProcessedFilesCollection.RemoveFile(FInfo[J].FileName); SynchronizeEx(DoDBkernelEventRefreshList); Continue; end; Inc(C); SetProgressPosition(C); try UpdateImageRecord(FContext, DBEvent_Sender, FInfo[I].FileName, FInfo[I].ID); except on E: Exception do EventLog(':TRefreshDBRecordsThread::Execute()/UpdateImageRecord throw exception: ' + E.message); end; IntParam := FInfo[I].ID; StrParam := FInfo[I].FileName; ProcessedFilesCollection.RemoveFile(FInfo[I].FileName); SynchronizeEx(DoDBKernelEventRefreshList); SynchronizeEx(DoDBKernelEvent); end; end; finally CoUninitialize; end; SynchronizeEx(DestroyProgress); end; procedure TRefreshDBRecordsThread.InitializeProgress; begin ProgressWindow := GetProgressWindow; with ProgressWindow as TProgressActionForm do begin CanClosedByUser := True; OneOperation := False; OperationCount := 1; OperationPosition := 1; MaxPosCurrentOperation := Count; XPosition := 0; Show; end; end; destructor TRefreshDBRecordsThread.Destroy; begin F(FInfo); inherited; end; procedure TRefreshDBRecordsThread.DestroyProgress; begin (ProgressWindow as TProgressActionForm).WindowCanClose := True; ProgressWindow.Release; end; procedure TRefreshDBRecordsThread.IfBreakOperation; begin BoolParam := (ProgressWindow as TProgressActionForm).Closed; end; procedure TRefreshDBRecordsThread.SetProgressPosition(Position: Integer); begin IntParam := Position; SynchronizeEx(SetProgressPositionSynch); end; procedure TRefreshDBRecordsThread.SetProgressPositionSynch; begin (ProgressWindow as TProgressActionForm).XPosition := IntParam; end; procedure TRefreshDBRecordsThread.DoDBkernelEvent; var EventInfo: TEventValues; begin EventInfo.ID := IntParam; CollectionEvents.DoIDEvent(DBEvent_Sender, IntParam, [EventID_Param_Image], EventInfo); end; procedure TRefreshDBRecordsThread.DoDBkernelEventRefreshList; var EventInfo: TEventValues; begin CollectionEvents.DoIDEvent(DBEvent_Sender, IntParam, [EventID_Repaint_ImageList], EventInfo); end; procedure TRefreshDBRecordsThread.OnDBKernelEventProcedureSunch; begin CollectionEvents.DoIDEvent(DBEvent_Sender, DBEvent_ID, DBEvent_Params, DBEvent_Value); end; end.
unit Images; interface uses Windows,Graphics, SysUtils, Classes; Type TStoredAs=(ByLines,ByCols); TImageInfo=class StoredAs:TStoredAs; width,height:word; end; TImageSource=class Protected FInfo:TImageInfo; Public Pal:Array[0..255] of TRGBQuad; Property Info:TImageInfo read FInfo; Function LoadBitmap(bw,bh:Integer):TBitmap; procedure GetLine(var buf);virtual;abstract; Procedure GetCol(var buf);virtual;abstract; Protected Constructor Create; Private Function LoadByLines(w,h:Integer):TBitmap; Function LoadByCols(w,h:Integer):TBitmap; Procedure WriteHeader(f:TStream); Destructor Destroy;override; end; implementation Constructor TImageSource.Create; begin Finfo:=TImageInfo.Create; end; Destructor TImageSource.Destroy; begin FInfo.Free; end; Function TImageSource.LoadBitmap(bw,bh:Integer):TBitmap; begin if (bw=-1) then bw:=Info.Width; if (bh=-1) then bh:=Info.Height; case Info.StoredAs of byLines: Result:=LoadByLines(bw,bh); byCols: Result:=LoadByCols(bw,bh); end; end; Procedure TImageSource.WriteHeader(f:TStream); var Bi:TBitmapInfoHeader; Bfh:TBitmapFileHeader; bw,bh,bw4:Integer; begin bw:=Info.Width; bh:=Info.Height; if bw and 3=0 then bw4:=bw else bw4:=bw and $FFFFFFFC+4; With Bfh do begin bfType:=$4D42; {'BM'} bfOffBits:=sizeof(bfh)+sizeof(bi)+sizeof(TRGBQuad)*256; bfReserved1:=0; bfReserved2:=0; bfSize:=bfOffBits+bh*bw4; end; FillChar(Bi,Sizeof(bi),0); With BI do begin biSize:=sizeof(BI); biWidth:=bw; biHeight:=bh; biPlanes:=1; biBitCount:=8; end; f.Write(bfh,sizeof(bfh)); f.Write(bi,sizeof(bi)); f.Write(Pal,sizeof(Pal)); end; Function TImageSource.LoadByLines(w,h:Integer):TBitmap; var i:Integer; Ms:TMemoryStream; pLine:Pchar; pos:Longint; bw,bh,bw4:Integer; begin Result:=nil; bw:=Info.Width; bh:=Info.Height; if bw and 3=0 then bw4:=bw else bw4:=bw and $FFFFFFFC+4; GetMem(Pline,bw4); ms:=TMemoryStream.Create; WriteHeader(ms); Try Pos:=ms.Position; for i:=Bh-1 downto 0 do begin GetLine(Pline^); ms.Position:=Pos+i*bw4; ms.Write(PLine^,bw4); end; ms.Position:=0; Result:=TBitmap.Create; Result.LoadFromStream(ms); Ms.Free; finally FreeMem(pLine); end; end; Function TImageSource.LoadByCols(w,h:Integer):TBitmap; Const HeaderSize=sizeof(TBitmapInfoHeader)+sizeof(TBitmapFileHeader)+256*sizeof(TRGBQuad); var i,j:Integer; Ms:TMemoryStream; pCol,pc:Pchar; pos:Longint; bw,bh,bw4:Integer; pbits,pb:pchar; begin Result:=nil; bw:=Info.Width; bh:=Info.Height; if bw and 3=0 then bw4:=bw else bw4:=bw and $FFFFFFFC+4; GetMem(PCol,bh); ms:=TMemoryStream.Create; ms.SetSize(HeaderSize+bw4*bh); WriteHeader(ms); Try Pos:=ms.Position; pBits:=ms.Memory; pBits:=PBits+Pos; for i:=0 to bw-1 do begin GetCol(PCol^); pc:=pCol; pb:=PBits+i; for j:=0 to bh-1 do begin PB^:=pc^; inc(pc); inc(pb,bw4); end; end; ms.Position:=0; Result:=TBitmap.Create; Result.LoadFromStream(ms); Ms.Free; finally FreeMem(PCol); end; end; end.
{******************************************************************************* Title: T2TiPDV Description: Permite a digitação e importação de um número inteiro. The MIT License Copyright: Copyright (C) 2012 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: alberteije@gmail.com @author T2Ti.COM @version 1.0 *******************************************************************************} unit UImportaNumero; {$mode objfpc}{$H+} interface uses Windows, Messages, SysUtils, Variants, Classes, db, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, curredit, ZDataset, UBase; type { TFImportaNumero } TFImportaNumero = class(TFBase) Image2: TImage; LabelEntrada: TLabel; EditEntrada: TCurrencyEdit; BotaoConfirma: TBitBtn; BotaoCancela: TBitBtn; Image1: TImage; procedure BotaoCancelaClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var FImportaNumero: TFImportaNumero; implementation Uses UCaixa; {$R *.lfm} procedure TFImportaNumero.FormActivate(Sender: TObject); begin Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); end; procedure TFImportaNumero.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then botaoCancela.Click; end; procedure TFImportaNumero.BotaoCancelaClick(Sender: TObject); begin Close; end; end.
unit DPM.Core.Package.SearchResults; interface uses Spring.Collections, JsonDataObjects, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Spec.Interfaces, DPM.Core.Package.Interfaces; type TDPMPackageSearchResultItem = class(TInterfacedObject, IPackageSearchResultItem) private FIsError : boolean; FAuthors : string; FCopyright : string; FDependencies : IList<IPackageDependency>; FDescription : string; FIcon : string; FId : string; FIsCommercial : Boolean; FIsTrial : Boolean; FIsTransitive : boolean; FLicense : string; FPlatform : TDPMPlatform; FCompilerVersion : TCompilerVersion; FProjectUrl : string; FRepositoryUrl : string; FRepositoryType : string; FRepositoryBranch : string; FRepositoryCommit : string; FReportUrl : string; FTags : string; FVersion : TPackageVersion; FLatestVersion : TPackageVersion; FLatestStableVersion : TPackageVersion; FVersionRange : TVersionRange; FDownloadCount : Int64; FInstalled : boolean; FIsReservedPrefix : boolean; FSourceName : string; FPublishedDate : string; protected function GetAuthors : string; function GetCopyright : string; function GetDependencies : IList<IPackageDependency>; function GetDescription : string; function GetIcon : string; function GetId : string; function GetPublishedDate : string; function GetReportUrl : string; function GetInstalled : Boolean; function GetLatestVersion : TPackageVersion; function GetLatestStableVersion : TPackageVersion; function GetIsReservedPrefix : Boolean; function GetIsCommercial : Boolean; function GetIsTrial : Boolean; function GetLicense : string; function GetPlatform : TDPMPlatform; function GetCompilerVersion : TCompilerVersion; function GetProjectUrl : string; function GetRepositoryUrl : string; function GetRepositoryType : string; function GetRepositoryBranch : string; function GetRepositoryCommit : string; function GetTags : string; function GetVersion : TPackageVersion; function GetDownloadCount : Int64; function GetSourceName : string; function GetIsError : boolean; function GetIsTransitive : Boolean; function GetIsLatestVersion : boolean; function GetIsLatestStableVersion : boolean; function GetIsStableVersion : boolean; function GetVersionRange : TVersionRange; function ToIdVersionString : string; procedure SetVersion(const value : TPackageVersion); procedure SetPublishedDate(const value : string); procedure SetRepositoryUrl(const value : string); procedure SetRepositoryType(const value : string); procedure SetRepositoryBranch(const value : string); procedure SetRepositoryCommit(const value : string); procedure SetReportUrl(const value : string); procedure SetInstalled(const value : Boolean); procedure SetLatestVersion(const value : TPackageVersion); procedure SetLatestStableVersion(const value : TPackageVersion); procedure SetIsTransitive(const value : Boolean); procedure SetVersionRange(const value : TVersionRange); constructor CreateFromJson(const sourceName : string; const jsonObject : TJsonObject); constructor CreateFromMetaData(const sourceName : string; const metaData : IPackageMetadata); constructor CreateFromError(const id : string; const version : TPackageVersion; const errorDescription : string); public class function FromJson(const sourceName : string; const jsonObject : TJsonObject) : IPackageSearchResultItem; class function FromMetaData(const sourceName : string; const metaData : IPackageMetadata) : IPackageSearchResultItem; class function FromError(const id : string; const version : TPackageVersion; const errorDescription : string) : IPackageSearchResultItem; end; TDPMPackageSearchResult = class(TInterfacedObject, IPackageSearchResult) private FSkip : Int64; FTotalCount : Int64; FResults : IList<IPackageSearchResultItem>; protected function GetResults: IList<IPackageSearchResultItem>; function GetTotalCount: Int64; function GetSkip: Int64; procedure SetSkip(const value : Int64); procedure SetTotalCount(const value : Int64); public constructor Create(const skip : Int64; const total : Int64); end; implementation uses System.SysUtils, DPM.Core.Package.Dependency; { TDPMPackageSearchResultItem } constructor TDPMPackageSearchResultItem.CreateFromError(const id : string; const version : TPackageVersion; const errorDescription : string); begin FIsError := true; FId := id; FVersion := version; FDescription := errorDescription; FVersionRange := TVersionRange.Empty; end; constructor TDPMPackageSearchResultItem.CreateFromJson(const sourceName : string; const jsonObject : TJsonObject); var depArr : TJsonArray; depId : string; depVersion : string; i: Integer; range : TVersionRange; dependency : IPackageDependency; begin FSourceName := sourceName; FCompilerVersion := StringToCompilerVersion(jsonObject.S['compiler']); if FCompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentOutOfRangeException.Create('Invalid compiler version returned from server : ' + jsonObject.S['compiler']); FPlatform := StringToDPMPlatform(jsonObject.S['platform']); if FPlatform = TDPMPlatform.UnknownPlatform then raise EArgumentOutOfRangeException.Create('Invalid platform returned from server : ' + jsonObject.S['platform']); FDependencies := TCollections.CreateList<IPackageDependency>; FId := jsonObject.S['id']; FVersion := TPackageVersion.Parse(jsonObject.S['version']); FAuthors := jsonObject.S['authors']; FCopyright := jsonObject.S['copyright']; FDescription := jsonObject.S['description']; FIcon := jsonObject.S['icon']; FIsCommercial := jsonObject.B['isCommercial']; FIsTrial := jsonObject.B['isTrial']; FLicense := jsonObject.S['license']; FProjectUrl := jsonObject.S['projectUrl']; FRepositoryUrl := jsonObject.S['repositoryUrl']; FRepositoryType := jsonObject.S['repositoryType']; FRepositoryBranch := jsonObject.S['repositoryBranch']; FRepositoryCommit := jsonObject.S['repositoryCommit']; FReportUrl := jsonObject.S['reportUrl']; FTags := jsonObject.S['tags']; FDownloadCount := jsonObject.L['totalDownloads']; FLatestVersion := TPackageVersion.Parse(jsonObject.S['latestVersion']); if jsonObject.Contains('latestStableVersion') and ( not jsonObject.IsNull('latestStableVersion') )then FLatestStableVersion := TPackageVersion.Parse(jsonObject.S['latestStableVersion']) else FLatestStableVersion := TPackageVersion.Empty; FIsReservedPrefix := jsonObject.B['isReservedPrefix']; FVersionRange := TVersionRange.Empty; if jsonObject.Contains('dependencies') and (not jsonObject.IsNull('dependencies')) then begin depArr := jsonObject.A['dependencies']; for i := 0 to depArr.Count -1 do begin depId := depArr.O[i].S['packageId']; depVersion := depArr.O[i].S['versionRange']; if TVersionRange.TryParse(depVersion, range) then begin dependency := TPackageDependency.Create(depId, range, FPlatform); FDependencies.Add(dependency); end; end; end; end; constructor TDPMPackageSearchResultItem.CreateFromMetaData(const sourceName : string; const metaData : IPackageMetadata); begin FSourceName := sourceName; FPlatform := metaData.Platform; FCompilerVersion := metaData.CompilerVersion; FDependencies := TCollections.CreateList<IPackageDependency>; FDependencies.AddRange(metaData.Dependencies); FAuthors := metaData.Authors; FCopyright := metaData.Copyright; FDescription := metaData.Description; FIcon := metaData.Icon; FId := metaData.Id; FIsCommercial := metaData.IsCommercial; FIsTrial := metaData.IsTrial; FLicense := metaData.License; FProjectUrl := metaData.ProjectUrl; FRepositoryUrl := metaData.RepositoryUrl; FRepositoryType := metaData.RepositoryType; FRepositoryBranch := metaData.RepositoryBranch; FRepositoryCommit := metaData.RepositoryCommit; FTags := metaData.Tags; FVersion := metaData.Version; FDownloadCount := -1; //indicates not set; FIsReservedPrefix := false; FVersionRange := TVersionRange.Empty; end; class function TDPMPackageSearchResultItem.FromError(const id : string; const version : TPackageVersion; const errorDescription : string) : IPackageSearchResultItem; begin result := TDPMPackageSearchResultItem.CreateFromError(id, version, errorDescription); end; class function TDPMPackageSearchResultItem.FromJson(const sourceName : string; const jsonObject : TJsonObject) : IPackageSearchResultItem; begin result := TDPMPackageSearchResultItem.CreateFromJson(sourceName, jsonObject); end; class function TDPMPackageSearchResultItem.FromMetaData(const sourceName : string; const metaData : IPackageMetadata) : IPackageSearchResultItem; begin result := TDPMPackageSearchResultItem.CreateFromMetaData(sourceName, metaData); end; function TDPMPackageSearchResultItem.GetAuthors : string; begin result := FAuthors; end; function TDPMPackageSearchResultItem.GetCompilerVersion: TCompilerVersion; begin result := FCompilerVersion; end; function TDPMPackageSearchResultItem.GetCopyright : string; begin result := FCopyright; end; function TDPMPackageSearchResultItem.GetDependencies : IList<IPackageDependency>; begin result := FDependencies; end; function TDPMPackageSearchResultItem.GetDescription : string; begin result := FDescription; end; function TDPMPackageSearchResultItem.GetDownloadCount : Int64; begin result := FDownloadCount; end; function TDPMPackageSearchResultItem.GetIcon : string; begin result := FIcon; end; function TDPMPackageSearchResultItem.GetId : string; begin result := FId; end; function TDPMPackageSearchResultItem.GetInstalled : Boolean; begin result := FInstalled; end; function TDPMPackageSearchResultItem.GetIsCommercial : Boolean; begin result := FIsCommercial; end; function TDPMPackageSearchResultItem.GetIsError : boolean; begin result := FIsError; end; function TDPMPackageSearchResultItem.GetIsLatestStableVersion: boolean; begin result := FVersion = FLatestStableVersion; end; function TDPMPackageSearchResultItem.GetIsLatestVersion: boolean; begin result := FVersion = FLatestVersion; end; function TDPMPackageSearchResultItem.GetIsReservedPrefix : Boolean; begin result := FIsReservedPrefix; end; function TDPMPackageSearchResultItem.GetIsStableVersion: boolean; begin result := FVersion.IsStable; end; function TDPMPackageSearchResultItem.GetIsTransitive : Boolean; begin result := FIsTransitive; end; function TDPMPackageSearchResultItem.GetIsTrial : Boolean; begin result := FIsTrial; end; function TDPMPackageSearchResultItem.GetLatestStableVersion: TPackageVersion; begin result := FLatestStableVersion; end; function TDPMPackageSearchResultItem.GetLatestVersion: TPackageVersion; begin result := FLatestVersion; end; function TDPMPackageSearchResultItem.GetLicense : string; begin result := FLicense; end; function TDPMPackageSearchResultItem.GetPlatform : TDPMPlatform; begin result := FPlatform; end; function TDPMPackageSearchResultItem.GetProjectUrl : string; begin result := FProjectUrl; end; function TDPMPackageSearchResultItem.GetPublishedDate : string; begin result := FPublishedDate; end; function TDPMPackageSearchResultItem.GetReportUrl : string; begin result := FReportUrl; end; function TDPMPackageSearchResultItem.GetRepositoryBranch: string; begin result := FRepositoryBranch; end; function TDPMPackageSearchResultItem.GetRepositoryCommit: string; begin result := FRepositoryCommit; end; function TDPMPackageSearchResultItem.GetRepositoryType: string; begin result := FRepositoryType; end; function TDPMPackageSearchResultItem.GetRepositoryUrl: string; begin result := FRepositoryUrl; end; function TDPMPackageSearchResultItem.GetSourceName : string; begin result := FSourceName; end; function TDPMPackageSearchResultItem.GetTags : string; begin result := FTags; end; function TDPMPackageSearchResultItem.GetVersion : TPackageVersion; begin result := FVersion; end; function TDPMPackageSearchResultItem.GetVersionRange: TVersionRange; begin result := FVersionRange; end; procedure TDPMPackageSearchResultItem.SetInstalled(const value : Boolean); begin FInstalled := value; end; procedure TDPMPackageSearchResultItem.SetIsTransitive(const value : Boolean); begin FIsTransitive := value; end; procedure TDPMPackageSearchResultItem.SetLatestStableVersion(const value: TPackageVersion); begin FLatestStableVersion := value; end; procedure TDPMPackageSearchResultItem.SetLatestVersion(const value: TPackageVersion); begin FLatestVersion := value; end; procedure TDPMPackageSearchResultItem.SetPublishedDate(const value : string); begin FPublishedDate := value; end; procedure TDPMPackageSearchResultItem.SetReportUrl(const value : string); begin FReportUrl := value; end; procedure TDPMPackageSearchResultItem.SetRepositoryBranch(const value: string); begin FRepositoryBranch := value; end; procedure TDPMPackageSearchResultItem.SetRepositoryCommit(const value: string); begin FRepositoryCommit := value; end; procedure TDPMPackageSearchResultItem.SetRepositoryType(const value: string); begin FRepositoryType := value; end; procedure TDPMPackageSearchResultItem.SetRepositoryUrl(const value: string); begin FRepositoryUrl := value; end; procedure TDPMPackageSearchResultItem.SetVersion(const value: TPackageVersion); begin FVersion := value; end; procedure TDPMPackageSearchResultItem.SetVersionRange(const value: TVersionRange); begin FVersionRange := value; end; function TDPMPackageSearchResultItem.ToIdVersionString: string; begin result := FId + ' [' + FVersion.ToStringNoMeta + ']'; end; { TDPMPackageSearchResult } constructor TDPMPackageSearchResult.Create(const skip : Int64; const total: Int64); begin FSkip := skip; FTotalCount := total; FResults := TCollections.CreateList<IPackageSearchResultItem>; end; function TDPMPackageSearchResult.GetResults: IList<IPackageSearchResultItem>; begin result := FResults; end; function TDPMPackageSearchResult.GetSkip: Int64; begin Result := FSkip; end; function TDPMPackageSearchResult.GetTotalCount: Int64; begin result := FTotalCount; end; procedure TDPMPackageSearchResult.SetSkip(const value: Int64); begin FSkip := value; end; procedure TDPMPackageSearchResult.SetTotalCount(const value: Int64); begin FTotalCount := value; end; initialization JsonSerializationConfig.NullConvertsToValueTypes := true; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_OLE.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_OLE; interface {$IFDEF PAXARM} implementation end. {$ENDIF} {$IFDEF FPC} implementation end. {$ENDIF} {$IFDEF MACOS} implementation end. {$ENDIF} uses {$IFDEF VARIANTS} Variants, {$ENDIF} SysUtils, {$IFDEF DPULSAR} {$IFDEF MACOS32} {$ELSE} Winapi.Windows, System.Win.ComObj, System.Win.ComConst, Winapi.ActiveX, {$ENDIF} {$ELSE} Windows, ComConst, ComObj, ActiveX, {$ENDIF} PAXCOMP_TYPES, PAXCOMP_SYS; procedure _GetOLEProperty(const D: Variant; PropName: PChar; var Result: Variant; ParamsCount: Integer); stdcall; procedure _SetOLEProperty(const D: Variant; PropName: PChar; const Value: Variant; ParamsCount: Integer); stdcall; const atVarMask = $3F; atTypeMask = $7F; atByRef = $80; var Unassigned: Variant; implementation uses PAXCOMP_CONSTANTS, PaxCompiler, AnsiStrings; type TOleHelperRec = class public DispId: Integer; Index: Integer; end; TOleHelperList = class(TTypedList) private function GetRecord(I: Integer): TOleHelperRec; public function Add(DispId: Integer; Index: Integer): TOleHelperRec; function FindIndex(DispId: Integer): Integer; property Records[I: Integer]: TOleHelperRec read GetRecord; default; end; function TOleHelperList.GetRecord(I: Integer): TOleHelperRec; begin result := TOleHelperRec(L[I]); end; function TOleHelperList.Add(DispId: Integer; Index: Integer): TOleHelperRec; begin result := TOleHelperRec.Create; result.DispId := DispId; result.Index := Index; L.Add(result); end; function TOleHelperList.FindIndex(DispId: Integer): Integer; var I: Integer; R: TOleHelperRec; begin result := -1; for I := 0 to Count - 1 do begin R := Records[I]; if R.DispId = DispId then begin result := R.Index; Exit; end; end; end; var FOleHelperList: TOleHelperList; function OLEHelperList : TOleHelperList; begin if not assigned(FOleHelperList) then FOleHelperList := TOleHelperList.create; result := FOleHelperList; end; const MaxDispArgs = 64; type TIntArr = array[0..100] of LongInt; PIntArr = ^TIntArr; TBoolArr = array[0..30] of Boolean; PBoolArr = ^TBoolArr; TStringArr = array[0..30] of String; PStringArr = ^TStringArr; TDoubleArr = array[0..30] of Double; PDoubleArr = ^TDoubleArr; TCurrencyArr = array[0..30] of Currency; PCurrencyArr = ^TCurrencyArr; TVariantArr = array[0..30] of Variant; PVariantArr = ^TVariantArr; {$IFDEF PAX64} procedure GetIDsOfNames(const Dispatch: IDispatch; Names: PAnsiChar; NameCount: Integer; DispIDs: PDispIDList); type PNamesArray = ^TNamesArray; TNamesArray = array[0..100] of PWideChar; TArrayOfNamesArray = array[0..20] of TNamesArray; procedure RaiseNameException; begin raise EOleError.CreateFmt(SNoMethod, [Names]); end; var N, SrcLen, DestLen: Integer; Src: PAnsiChar; Dest: PWideChar; NameRefs: TNamesArray; StackTop: Pointer; Temp: Integer; buff: array[0..20] of TNamesArray; begin Src := Names; N := 0; repeat SrcLen := SysUtils.StrLen(Src); DestLen := MultiByteToWideChar(0, 0, Src, SrcLen, nil, 0) + 1; Dest := @ buff[N]; if N = 0 then NameRefs[0] := Dest else NameRefs[NameCount - N] := Dest; MultiByteToWideChar(0, 0, Src, SrcLen, Dest, DestLen); Dest[DestLen-1] := #0; Inc(Src, SrcLen+1); Inc(N); until N = NameCount; Temp := Dispatch.GetIDsOfNames(GUID_NULL, @NameRefs, NameCount, GetThreadLocale, DispIDs); if Temp = Integer(DISP_E_UNKNOWNNAME) then RaiseNameException else OleCheck(Temp); end; {$ELSE} procedure GetIDsOfNames(const Dispatch: IDispatch; Names: PAnsiChar; NameCount: Integer; DispIDs: PDispIDList); procedure RaiseNameException; begin raise EOleError.CreateFmt(SNoMethod, [Names]); end; type PNamesArray = ^TNamesArray; TNamesArray = array[0..0] of PWideChar; var N, SrcLen, DestLen: Integer; Src: PAnsiChar; Dest: PWideChar; NameRefs: PNamesArray; StackTop: Pointer; Temp: Integer; begin Src := Names; N := 0; asm MOV StackTop, ESP MOV EAX, NameCount INC EAX SHL EAX, 2 // sizeof pointer = 4 SUB ESP, EAX LEA EAX, NameRefs MOV [EAX], ESP end; repeat SrcLen := AnsiStrings.StrLen(Src); DestLen := MultiByteToWideChar(0, 0, Src, SrcLen, nil, 0) + 1; asm MOV EAX, DestLen ADD EAX, EAX ADD EAX, 3 // round up to 4 byte boundary AND EAX, not 3 SUB ESP, EAX LEA EAX, Dest MOV [EAX], ESP end; if N = 0 then NameRefs[0] := Dest else NameRefs[NameCount - N] := Dest; MultiByteToWideChar(0, 0, Src, SrcLen, Dest, DestLen); Dest[DestLen-1] := #0; Inc(Src, SrcLen+1); Inc(N); until N = NameCount; Temp := Dispatch.GetIDsOfNames(GUID_NULL, NameRefs, NameCount, GetThreadLocale, DispIDs); if Temp = Integer(DISP_E_UNKNOWNNAME) then RaiseNameException else OleCheck(Temp); asm MOV ESP, StackTop end; end; {$ENDIF} procedure MyDispatchInvoke(const Dispatch: IDispatch; CallDesc: PCallDesc; DispIDs: PDispIDList; Params: Pointer; Result: PVariant; var ByRefs: TBoolArr; ParamsCount: Integer; const P: Variant; var SS: TStringArr; var II: TIntArr; var DD: TDoubleArr; var CC: TCurrencyArr; var VV: TVariantArr); type PVarArg = ^TVarArg; {$IFDEF PAX64} TVarArg = array[0..5] of DWORD; {$ELSE} TVarArg = array[0..3] of DWORD; {$ENDIF} TStringDesc = record BStr: PWideChar; PStr: PString; end; var I, J, K, ArgType, ArgCount, StrCount, DispID, InvKind, Status: Integer; VarFlag: Byte; ParamPtr: ^Integer; ArgPtr, VarPtr: PVarArg; DispParams: TDispParams; ExcepInfo: TExcepInfo; Strings: array[0..MaxDispArgs - 1] of TStringDesc; Args: array[0..MaxDispArgs - 1] of TVarArg; TypeInfoCount: Integer; TypeInfo: ITypeInfo2; pfdesc: PFuncDesc; FuncIndex: Cardinal; W: Word; VT: Integer; VCount: Integer; VTypes: array[0..30] of Integer; Processed: Boolean; B1, B2: Integer; begin FillChar(ByRefs, SizeOf(ByRefs), 0); FillChar(VTypes, SizeOf(VTypes), 0); if ParamsCount > 0 then begin Dispatch.GetTypeInfoCount(TypeInfoCount); if TypeInfoCount = 1 then begin if Dispatch.GetTypeInfo(0, GetThreadLocale, TypeInfo) = S_OK then begin DispID := DispIDs[0]; Processed := false; B1 := OleHelperList.FindIndex(DispId); if B1 >= 0 then B2 := B1 else begin B1 := 0; B2 := 1000; end; for FuncIndex := B1 to B2 do begin if Processed then break; if TypeInfo.GetFuncDesc(FuncIndex, pfdesc) <> S_OK then begin TypeInfo.ReleaseFuncDesc(pfdesc); break; end; if pfdesc^.cparams < ParamsCount then continue; if pfdesc^.memid = DispId then try OleHelperList.Add(DispId, FuncIndex); for I:=0 to ParamsCount - 1 do begin W := pfdesc^.lprgelemdescParam[I].paramdesc.wParamFlags; VTypes[I] := pfdesc^.lprgelemdescParam[I].tdesc.vt; // if (W = PARAMFLAG_FOUT) or (W = PARAMFLAG_FRETVAL) then if ((W and PARAMFLAG_FOUT) = PARAMFLAG_FOUT) or ((W and PARAMFLAG_FRETVAL) = PARAMFLAG_FRETVAL) then begin ByRefs[I] := true; CallDesc.ArgTypes[I] := CallDesc.ArgTypes[I] or atByRef; end; end; finally Processed := true; TypeInfo.ReleaseFuncDesc(pfdesc); end; end; // for-loop end; end; end; K := -1; for I := 1 to ParamsCount do begin VT := TVarData(P[I]).VType; VCount := VarArrayDimCount(P[I]); if VT = 0 then begin VT := VTypes[I-1]; if VT = 26 then VT := varOleStr; end; if VT = varUnknown then VT := varDispatch; if (VT in [VarInteger,VarSmallInt,VarByte]) and (VCount=0) then begin II[I] := P[I]; Inc(K); if ByRefs[I-1] then PIntArr(Params)^[K] := IntPax(@II[I]) else PIntArr(Params)^[K] := II[I]; end else if VT = VarError then begin Inc(K); end else if VT = VarOleStr then begin SS[I] := P[I]; Inc(K); if ByRefs[I-1] then PIntArr(Params)^[K] := IntPax(@SS[I]) else PIntArr(Params)^[K] := IntPax(SS[I]); // byval only end else if (VT = VarVariant) or (VT = VarDispatch) or (VCount > 0) then begin VV[I] := P[I]; Inc(K); if ByRefs[I-1] then PIntArr(Params)^[K] := IntPax(@VV[I]) else begin Move(VV[I], PIntArr(Params)^[K], SizeOf(Variant)); Inc(K); Inc(K); Inc(K); end; end else if VT = VarDouble then begin DD[I] := P[I]; Inc(K); if ByRefs[I-1] then PIntArr(Params)^[K] := Integer(@DD[I]) else begin Move(DD[I], PIntArr(Params)^[K], SizeOf(Double)); Inc(K); end; end else if VT = VarCurrency then begin CC[I] := P[I]; Inc(K); if ByRefs[I-1] then PIntArr(Params)^[K] := Integer(@CC[I]) else begin Move(CC[I], PIntArr(Params)^[K], SizeOf(Currency)); Inc(K); end; end; end; StrCount := 0; try ArgCount := CallDesc^.ArgCount; if ArgCount > MaxDispArgs then raise EOleException.CreateRes(@STooManyParams); if ArgCount <> 0 then begin ParamPtr := Params; ArgPtr := @Args[ArgCount]; I := 0; repeat Dec(IntPax(ArgPtr), SizeOf(TVarData)); ArgType := CallDesc^.ArgTypes[I] and atTypeMask; VarFlag := CallDesc^.ArgTypes[I] and atByRef; if ArgType = varError then begin ArgPtr^[0] := varError; ArgPtr^[2] := DWORD(DISP_E_PARAMNOTFOUND); end else begin if ArgType = varStrArg then begin with Strings[StrCount] do if VarFlag <> 0 then begin BStr := StringToOleStr(PString(ParamPtr^)^); PStr := PString(ParamPtr^); PVarData(ArgPtr).VType := varOleStr or VarByRef; PVarData(ArgPtr).VString := @BStr; end else begin BStr := StringToOleStr(PString(ParamPtr)^); PStr := nil; PVarData(ArgPtr).VType := varOleStr; PVarData(ArgPtr).VString := BStr; end; Inc(StrCount); end else if VarFlag <> 0 then begin if (ArgType = varVariant) and (PVarData(ParamPtr^)^.VType = varString) then VarCast(PVariant(ParamPtr^)^, PVariant(ParamPtr^)^, varOleStr); ArgPtr^[0] := ArgType or varByRef; ArgPtr^[2] := ParamPtr^; end else if ArgType = varVariant then begin if PVarData(ParamPtr)^.VType = varString then begin with Strings[StrCount] do begin BStr := StringToOleStr(string(PVarData(ParamPtr)^.VString)); PStr := nil; PVarData(ArgPtr).VType := varOleStr; PVarData(ArgPtr).VString := BStr; end; Inc(StrCount); end else begin VarPtr := PVarArg(ParamPtr); ArgPtr^[0] := VarPtr^[0]; ArgPtr^[1] := VarPtr^[1]; ArgPtr^[2] := VarPtr^[2]; ArgPtr^[3] := VarPtr^[3]; Inc(IntPax(ParamPtr), 12); end; end else begin ArgPtr^[0] := ArgType; ArgPtr^[2] := ParamPtr^; if (ArgType >= varDouble) and (ArgType <= varDate) then begin Inc(IntPax(ParamPtr), 4); ArgPtr^[3] := ParamPtr^; end; end; Inc(IntPax(ParamPtr), 4); end; Inc(I); until I = ArgCount; end; DispParams.rgvarg := @Args; DispParams.rgdispidNamedArgs := @DispIDs[1]; DispParams.cArgs := ArgCount; DispParams.cNamedArgs := CallDesc^.NamedArgCount; DispID := DispIDs[0]; InvKind := CallDesc^.CallType; if InvKind = DISPATCH_PROPERTYPUT then begin if Args[0][0] and varTypeMask = varDispatch then InvKind := DISPATCH_PROPERTYPUTREF; DispIDs[0] := DISPID_PROPERTYPUT; Dec(IntPax(DispParams.rgdispidNamedArgs), SizeOf(Integer)); Inc(DispParams.cNamedArgs); end else if (InvKind = DISPATCH_METHOD) and (ArgCount = 0) and (Result <> nil) then InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET; Status := Dispatch.Invoke(DispID, GUID_NULL, 0, InvKind, DispParams, Result, @ExcepInfo, nil); if Status <> 0 then DispatchInvokeError(Status, ExcepInfo); J := StrCount; while J <> 0 do begin Dec(J); with Strings[J] do if PStr <> nil then OleStrToStrVar(BStr, PStr^); end; finally K := StrCount; while K <> 0 do begin Dec(K); SysFreeString(Strings[K].BStr); end; end; end; { Call GetIDsOfNames method on the given IDispatch interface } { Central call dispatcher } procedure MyVarDispInvoke(Result: PVariant; const Instance: Variant; CallDesc : PCallDesc; Params: Pointer; var ByRefs: TBoolArr; ParamsCount: Integer; const InitParam: Variant; var SS: TStringArr; var II: TIntArr; var DD: TDoubleArr; var CC: TCurrencyArr; var VV: TVariantArr); procedure RaiseException; begin raise EOleError.Create(SVarNotObject); end; var Dispatch: Pointer; DispIDs: array[0..MaxDispArgs - 1] of Integer; begin if TVarData(Instance).VType = varDispatch then Dispatch := TVarData(Instance).VDispatch else if TVarData(Instance).VType = (varDispatch or varByRef) then Dispatch := Pointer(TVarData(Instance).VPointer^) else RaiseException; GetIDsOfNames(IDispatch(Dispatch), @CallDesc^.ArgTypes[CallDesc^.ArgCount], CallDesc^.NamedArgCount + 1, @DispIDs); if Result <> nil then VarClear(Result^); MyDispatchInvoke(IDispatch(Dispatch), CallDesc, @DispIDs, Params, Result, ByRefs, ParamsCount, InitParam, SS, II, DD, CC, VV); end; function DispatchProcedure(ModeCall: Byte; const Instance: Variant; const Name: String; var P: Variant; ParamsCount: Integer; var ByRefs: TBoolArr): Variant; var CallDesc: TCallDesc; Params: TIntArr; S: ShortString; I, VCount: Integer; VT: Byte; SS: TStringArr; II: TIntArr; DD: TDoubleArr; CC: TCurrencyArr; VV: TVariantArr; begin FillChar(CallDesc, SizeOf(TCallDesc ), 0); FillChar(Params, SizeOf(Params), 0); S := ShortString(Name); with CallDesc do begin CallType := ModeCall; NamedArgCount := 0; ArgCount := 0; for I := 1 to ParamsCount do begin VT := TVarData(P[I]).VType; VCount := VarArrayDimCount(P[I]); if VT = varUnknown then VT := varVariant; ArgTypes[ArgCount] := VT; if (VT = VarOleStr) and (VCount = 0) then ArgTypes[ArgCount] := VarStrArg else if (VT = VarVariant) or (VT = VarDispatch) or (VCount > 0) then ArgTypes[ArgCount] := VarVariant; ArgTypes[ ArgCount ] := ArgTypes[ ArgCount ];// or atTypeMask; Inc(ArgCount); end; Move(S[1], ArgTypes[ArgCount], Length(S)); end; MyVarDispInvoke(@Result, Instance, @CallDesc, @Params, ByRefs, ParamsCount, P, SS, II, DD, CC, VV); for I:=1 to ParamsCount do begin VT := TVarData(P[I]).VType; VCount := VarArrayDimCount(P[I]); if not ByRefs[I - 1] then continue; if (VT in [VarInteger,VarSmallInt,VarByte]) and (VCount=0) then P[I] := II[I] else if VT = VarOleStr then P[I] := SS[I] else if (VT = VarVariant) or (VT = VarDispatch) or (VCount > 0) then P[I] := VV[I] else if VT = VarDouble then P[I] := DD[I] else if VT = VarCurrency then P[I] := CC[I]; end; end; {$IFDEF PAX64} function GetParams: TPtrList; assembler; asm mov rax, r15 end; procedure _GetOLEProperty(const D: Variant; PropName: PChar; var Result: Variant; ParamsCount: Integer); stdcall; var L: TPtrList; I: Integer; Params: Variant; ModeCall: Byte; V: PVariant; ByRefs: TBoolArr; ATempPropName: String; begin L := GetParams; Params := VarArrayCreate([1, ParamsCount], varVariant); for I:=1 to ParamsCount do begin V := L[I - 1]; if VarType(V^) = varBoolean then begin if V^ then Params[I] := Integer(1) else Params[I] := Integer(0); end else Params[I] := V^; end; ModeCall := DISPATCH_METHOD + DISPATCH_PROPERTYGET; ATempPropName := PropName; result := DispatchProcedure(ModeCall, D, ATempPropName, Params, ParamsCount, ByRefs); ATempPropName := ''; for I:=1 to ParamsCount do begin if not ByRefs[I-1] then continue; V := L[I - 1]; V^ := Params[I]; end; end; procedure _SetOLEProperty(const D: Variant; PropName: PChar; const Value: Variant; ParamsCount: Integer); stdcall; var L: TPtrList; I: Integer; Params: Variant; V: PVariant; ModeCall: Byte; ByRefs: TBoolArr; A: array of PVariant; ATempPropName: String; begin L := GetParams; Params := VarArrayCreate([1, ParamsCount + 1], varVariant); for I:=1 to ParamsCount do begin V := A[I - 1]; if VarType(V^) = varBoolean then begin if V^ then Params[I] := Integer(1) else Params[I] := Integer(0); end else Params[I] := V^; end; if VarType(Value) = varBoolean then begin if Value then Params[ParamsCount + 1] := Integer(1) else Params[ParamsCount + 1] := Integer(0); end else Params[ParamsCount + 1] := Value; ModeCall := DISPATCH_PROPERTYPUT; ATempPropName := PropName; DispatchProcedure(ModeCall, D, ATempPropName, Params, ParamsCount + 1, ByRefs); ATempPropName := ''; end; {$ELSE} procedure _GetOLEProperty(const D: Variant; PropName: PChar; var Result: Variant; ParamsCount: Integer); stdcall; var P: Pointer; procedure Nested; var I: Integer; Params: Variant; ModeCall: Byte; V: PVariant; ByRefs: TBoolArr; A: array of PVariant; ATempPropName: String; begin SetLength(A, ParamsCount); for I:=0 to ParamsCount - 1 do begin A[I] := Pointer(P^); Inc(IntPax(P), 4); end; Params := VarArrayCreate([1, ParamsCount], varVariant); for I:=1 to ParamsCount do begin V := A[I - 1]; if VarType(V^) = varBoolean then begin if V^ then Params[I] := Integer(1) else Params[I] := Integer(0); end else Params[I] := V^; end; ModeCall := DISPATCH_METHOD + DISPATCH_PROPERTYGET; ATempPropName := PropName; result := DispatchProcedure(ModeCall, D, ATempPropName, Params, ParamsCount, ByRefs); ATempPropName := ''; for I:=1 to ParamsCount do begin if not ByRefs[I-1] then continue; A[I - 1]^ := Params[I]; end; end; // nested var RetSize: Integer; begin asm mov P, ebp end; Inc(Integer(P), 24); Nested; RetSize := 16 + ParamsCount * 4; asm // emulate ret RetSize mov ecx, RetSize mov esp, ebp pop ebp mov ebx, [esp] @@loop: pop edx sub ecx, 4 jnz @@loop pop edx jmp ebx end; end; procedure _SetOLEProperty(const D: Variant; PropName: PChar; const Value: Variant; ParamsCount: Integer); stdcall; var P: Pointer; procedure Nested; var I: Integer; Params: Variant; V: PVariant; ModeCall: Byte; ByRefs: TBoolArr; A: array of PVariant; ATempPropName: String; begin SetLength(A, ParamsCount); for I:=0 to ParamsCount - 1 do begin A[I] := Pointer(P^); Inc(Integer(P), 4); end; Params := VarArrayCreate([1, ParamsCount + 1], varVariant); for I:=1 to ParamsCount do begin V := A[I - 1]; if VarType(V^) = varBoolean then begin if V^ then Params[I] := Integer(1) else Params[I] := Integer(0); end else Params[I] := V^; end; if VarType(Value) = varBoolean then begin if Value then Params[ParamsCount + 1] := Integer(1) else Params[ParamsCount + 1] := Integer(0); end else Params[ParamsCount + 1] := Value; ModeCall := DISPATCH_PROPERTYPUT; ATempPropName := PropName; DispatchProcedure(ModeCall, D, ATempPropName, Params, ParamsCount + 1, ByRefs); ATempPropName := ''; end; // nested var RetSize: Integer; begin asm mov P, ebp end; Inc(Integer(P), 24); Nested; RetSize := 16 + ParamsCount * 4; asm // emulate ret RetSize mov ecx, RetSize mov esp, ebp pop ebp mov ebx, [esp] @@loop: pop edx sub ecx, 4 jnz @@loop pop edx jmp ebx end; end; {$ENDIF} initialization FOleHelperList := nil; // OleHelperList:= TOleHelperList.Create; finalization if assigned(FOleHelperList) then FOleHelperList.Free; end.
unit TestMVCBrModel; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.Classes, System.Generics.collections, MVCBr.Interf, MVCBr.Controller, MVCBr.Model, System.SysUtils; type // Test methods for class TModelFactory TestTModelFactory = class(TTestCase) strict private FModelFactory: TModelFactory; Type TTesteController = class(TControllerFactory) end; protected FController : IController; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetController; procedure TestGetOwned; procedure TestController; procedure TestThis; procedure TestGetID; procedure TestID; procedure TestUpdate; procedure TestAfterInit; end; implementation procedure TestTModelFactory.SetUp; begin FController := TTesteController.Create; FModelFactory := TModelFactory.Create; with FController do add(FModelFactory); end; procedure TestTModelFactory.TearDown; begin // FModelFactory.Free; FModelFactory := nil; end; procedure TestTModelFactory.TestGetController; var ReturnValue: IController; begin ReturnValue := FModelFactory.GetController; CheckNotNull(ReturnValue, 'Nao retornou'); CheckTrue(TMVCBr.IsSame(IController, TMVCBr.GetGuid(ReturnValue))); // TODO: Validate method results end; procedure TestTModelFactory.TestGetOwned; var ReturnValue: TComponent; begin ReturnValue := FModelFactory.GetOwner; CheckNotNull(ReturnValue, 'Nao retornou'); // TODO: Validate method results end; procedure TestTModelFactory.TestController; var ReturnValue: IModel; AController: IController; begin // TODO: Setup method call parameters ReturnValue := FModelFactory.Controller(AController); CheckNotNull(ReturnValue, 'Nao retornou'); // TODO: Validate method results end; procedure TestTModelFactory.TestThis; var ReturnValue: TObject; begin ReturnValue := FModelFactory.This; CheckNotNull(ReturnValue, 'Nao retornou'); // TODO: Validate method results end; procedure TestTModelFactory.TestGetID; var ReturnValue: string; begin ReturnValue := FModelFactory.GetID; CheckTrue(ReturnValue <> ''); // TODO: Validate method results end; procedure TestTModelFactory.TestID; var ReturnValue: IModel; AID: string; begin // TODO: Setup method call parameters AID := FModelFactory.getID; ReturnValue := FModelFactory.ID(AID); // TODO: Validate method results CheckNotNull(ReturnValue, 'Nao retornou'); end; procedure TestTModelFactory.TestUpdate; var ReturnValue: IModel; begin ReturnValue := FModelFactory.Update; // TODO: Validate method results CheckNotNull(ReturnValue, 'Nao retornou'); end; procedure TestTModelFactory.TestAfterInit; begin FModelFactory.AfterInit; // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTModelFactory.Suite); end.
unit UDVersion; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32, ComCtrls; type TCrpeVersionDlg = class(TForm) btnOk: TButton; pnlVersion: TPanel; gbCrpe: TGroupBox; lblDLL: TLabel; lblEngine: TLabel; lblFileVersion: TLabel; lblMajor: TLabel; lblMid: TLabel; lblMinor: TLabel; editDLL: TEdit; editEngine: TEdit; editFileVersion: TEdit; editMajor: TEdit; editMinor: TEdit; editRelease: TEdit; gbReport: TGroupBox; lblRMajor: TLabel; lblRMinor: TLabel; lblLetter: TLabel; editRMajor: TEdit; editRMinor: TEdit; editLetter: TEdit; gbWindows: TGroupBox; lblPlatform: TLabel; lblWMajor: TLabel; lblWMinor: TLabel; lblWBuild: TLabel; editPlatform: TEdit; editWMajor: TEdit; editWMinor: TEdit; editWBuild: TEdit; lblBuild: TLabel; editBuild: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure UpdateVersion; private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeVersionDlg: TCrpeVersionDlg; bVersion : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.FormCreate(Sender: TObject); begin bVersion := True; LoadFormPos(Self); btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.FormShow(Sender: TObject); begin UpdateVersion; end; {------------------------------------------------------------------------------} { UpdateVersion } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.UpdateVersion; var OnOff : Boolean; begin OnOff := Cr.OpenEngine; InitializeControls(OnOff); if OnOff then begin {Crpe} editDLL.Text := Cr.Version.Crpe.DLL; editEngine.Text := Cr.Version.Crpe.Engine; editFileVersion.Text := Cr.Version.Crpe.FileVersion; editMajor.Text := IntToStr(Cr.Version.Crpe.Major); editMinor.Text := IntToStr(Cr.Version.Crpe.Minor); editRelease.Text := IntToStr(Cr.Version.Crpe.Release); editBuild.Text := IntToStr(Cr.Version.Crpe.Build); {Report} editRMajor.Text := IntToStr(Cr.Version.Report.Major); editRMinor.Text := IntToStr(Cr.Version.Report.Minor); editLetter.Text := Cr.Version.Report.Letter; {Windows} editPlatform.Text := Cr.Version.Windows.Platform; editWMajor.Text := IntToStr(Cr.Version.Windows.Major); editWMinor.Text := IntToStr(Cr.Version.Windows.Minor); editWBuild.Text := Cr.Version.Windows.Build; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeVersionDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bVersion := False; Release; end; end.
(* Category: SWAG Title: POINTERS, LINKING, LISTS, TREES Original name: 0009.PAS Description: Generic Linked List Author: SWAG SUPPORT TEAM Date: 06-22-93 09:20 *) { UNIT LinkList; } {------------------------------------------------- Generic linked list object - -------------------------------------------------} {***************************************************************} { INTERFACE} {***************************************************************} TYPE { Generic Linked List Handler Definition } NodeValuePtr = ^NodeValue; NodeValue = OBJECT CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; END; NodePtr = ^Node; Node = RECORD Retrieve : NodeValuePtr; Next : NodePtr; END; { Specific Linked List Handler Definition } NodeListPtr = ^NodeList; NodeList = OBJECT Items : NodePtr; CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Add (A_Value : NodeValuePtr); (* Iterator Functions *) PROCEDURE StartIterator (VAR Ptr : NodePtr); PROCEDURE NextValue (VAR Ptr : NodePtr); FUNCTION AtEndOfList (Ptr : NodePtr) : Boolean; END; {***************************************************************} {IMPLEMENTATION} {***************************************************************} CONSTRUCTOR NodeValue.Init; BEGIN END; DESTRUCTOR NodeValue.Done; BEGIN END; CONSTRUCTOR NodeList.Init; BEGIN Items := NIL; END; DESTRUCTOR NodeList.Done; VAR Temp : NodePtr; BEGIN WHILE Items <> NIL DO BEGIN Temp := Items; IF Temp^.Retrieve <> NIL THEN Dispose (Temp^.Retrieve, Done); Items := Items^.Next; Dispose (Temp); END; END; PROCEDURE NodeList.Add (A_Value : NodeValuePtr); VAR Cell : NodePtr; Temp : NodePtr; BEGIN (* Go TO the END OF the linked list. *) Cell := Items; IF Cell <> NIL THEN WHILE Cell^.Next <> NIL DO Cell := Cell^.Next; New (Temp); Temp^.Retrieve := A_Value; Temp^.Next := NIL; IF Items = NIL THEN Items := Temp ELSE Cell^.Next := Temp; END; PROCEDURE NodeList.StartIterator (VAR Ptr : NodePtr); BEGIN Ptr := Items; END; PROCEDURE NodeList.NextValue (VAR Ptr : NodePtr); BEGIN IF Ptr <> NIL THEN Ptr := Ptr^.Next; END; FUNCTION NodeList.AtEndOfList (Ptr : NodePtr) : Boolean; BEGIN AtEndOfList := (Ptr = NIL); END; { END. } { DEMO PROGRAM } { PROGRAM LL_Demo; USES LinkList; } { Turbo Pascal Linked List Object Example } TYPE DataValuePtr = ^DataValue; DataValue = OBJECT (NodeValue) Value : Real; CONSTRUCTOR Init (A_Value : Real); FUNCTION TheValue : Real; END; DataList = OBJECT (NodeList) FUNCTION CurrentValue (Ptr : NodePtr) : Real; PROCEDURE SetCurrentValue (Ptr : NodePtr; Value : Real); END; VAR Itr : NodePtr; TestLink : DataList; {------ Unique methods to create for your linked list type -----} CONSTRUCTOR DataValue.Init (A_Value : Real); BEGIN Value := A_Value; END; FUNCTION DataValue.TheValue : Real; BEGIN TheValue := Value; END; FUNCTION DataList.CurrentValue (Ptr : NodePtr) : Real; BEGIN CurrentValue := DataValuePtr (Ptr^.Retrieve)^.TheValue; END; PROCEDURE DataList.SetCurrentValue (Ptr : NodePtr; Value : Real); BEGIN DataValuePtr (Ptr^.Retrieve)^.Value := Value; END; BEGIN TestLink.Init; {Create the list then add 5 values to it} TestLink.Add (New (DataValuePtr, Init (1.0))); TestLink.Add (New (DataValuePtr, Init (2.0))); TestLink.Add (New (DataValuePtr, Init (3.0))); TestLink.Add (New (DataValuePtr, Init (4.0))); TestLink.Add (New (DataValuePtr, Init (5.0))); TestLink.StartIterator (Itr); {Display the list on screen} WHILE NOT TestLink.AtEndOfList (Itr) DO BEGIN Write (TestLink.CurrentValue (Itr) : 5 : 1); TestLink.NextValue (Itr); END; WriteLn; TestLink.StartIterator (Itr); {Change some values in the list} TestLink.SetCurrentValue (Itr, 0.0); TestLink.NextValue (Itr); TestLink.SetCurrentValue (Itr, -1.0); TestLink.StartIterator (Itr); {Redisplay the list values} WHILE NOT TestLink.AtEndOfList (Itr) DO BEGIN Write (TestLink.CurrentValue (Itr) : 5 : 1); TestLink.NextValue (Itr); END; WriteLn; ReadLn; END.
unit DPM.IDE.Utils; interface uses System.classes, Vcl.Controls; // Find a control that is a child of Application.Mainform or it's children function FindIDEControl(const className : string; const controlName : string) : TControl; implementation uses System.SysUtils, Vcl.Forms; function DoFindIDEControl(const parentControl : TControl; const className : string; const controlName : string) : TControl; var i : integer; begin result := nil; if SameText(parentControl.ClassName, className) and SameText(parentControl.Name, controlName) then exit(parentControl); if not (parentControl is TWinControl) then exit; //TWinControls have children, so recurse in to check those too. for i := 0 to TWinControl(parentControl).ControlCount - 1 do begin result := DoFindIDEControl(TWinControl(parentControl).Controls[i], className, controlName); if result <> nil then break; end; end; function FindIDEControl(const className : string; const controlName : string) : TControl; begin result := DoFindIDEControl(Application.MainForm, className, controlName); end; end.
unit ufrmDialogBeginningBalancePOS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ExtCtrls, StdCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGraphics, cxControls, cxLookAndFeels, Data.DB, cxLookAndFeelPainters, cxContainer, cxEdit, cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, uClientClasses, uInterface, uModBeginningBalance, Datasnap.DBClient; type TFormMode = (fmAdd, fmEdit); TfrmDialogBeginBalancePOS = class(TfrmMasterDialog, ICRUDAble) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; cbpCashierID: TcxExtLookupComboBox; curredtBeginBalance: TcxCurrencyEdit; cbpPosCode: TcxExtLookupComboBox; edtCashierName: TcxTextEdit; edtDescrp: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbpCashierIDCloseUp(Sender: TObject); procedure curredtBeginBalanceEnter(Sender: TObject); procedure cbpCashierIDPropertiesEditValueChanged(Sender: TObject); private // FKasirUsrNm : string; // dataUser,dataSetupPos: TDataSet; FCDSSetupPOS: TClientDataSet; FCDSUser: TClientDataSet; procedure ClearForm; procedure InitLookUp; function IsValidate: Boolean; procedure SavingData; public Balance_ID: Integer; Balance_Shift_ID: Integer; Balance_Shift_Date: TDateTime; PosCode,CashierID, CashierName: string; Modal: Currency; Descrpt: string; FModBalance: TModBeginningBalance; function GetModBalance: TModBeginningBalance; procedure LoadData(AID: string); procedure LoadDropDownData(ACombo: TcxExtLookupComboBox; AColsOfData: Integer; aTgl : TDateTime); property ModBalance: TModBeginningBalance read GetModBalance write FModBalance; // FTgl: TDateTime; published end; var frmDialogBeginBalancePOS: TfrmDialogBeginBalancePOS; implementation uses uConstanta, uTSCommonDlg, uRetnoUnit, ufrmBeginningBalancePOS, uDXUtils, uDMClient, uAppUtils, uModSetupPOS, uModAuthUser, uDBUtils, uModShift, uModelHelper; {$R *.dfm} procedure TfrmDialogBeginBalancePOS.FormCreate(Sender: TObject); begin inherited; ClearForm; InitLookUp; Self.AssignKeyDownEvent; curredtBeginBalance.EditValue := 200000; end; procedure TfrmDialogBeginBalancePOS.actDeleteExecute(Sender: TObject); begin inherited; if TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then begin try DMClient.CrudClient.DeleteFromDB(ModBalance); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); ModalResult := mrOk; except TAppUtils.Error(ER_DELETE_FAILED); raise; end; end; { if (strgGrid.Cells[_kolBegBal_ID,strgGrid.Row] = '0') or (strgGrid.Cells[_kolPosCode,strgGrid.Row] = '') then Exit; if IsBeginningBalanceUsed(StrToInt(strgGrid.Cells[_kolBegBal_ID,strgGrid.Row]),masternewunit.id) then begin CommonDlg.ShowMessage('Kasir sudah transaksi, tidak bisa dihapus.'); Exit; end; if (CommonDlg.Confirm('Are you sure you wish to delete POS Beginning Balance (POS CODE: '+ strgGrid.Cells[1,strgGrid.Row] +')?') = mrYes) then begin with TBeginningBalance.Create(Self) do begin try if LoadByID(StrToInt(strgGrid.Cells[_kolBegBal_ID,strgGrid.Row]),masternewunit.id) then begin if RemoveFromDB then begin cCommitTrans; CommonDlg.ShowMessage(CONF_DELETE_SUCCESSFULLY); actRefreshBeginBalancePOSExecute(Self); end else begin cRollbackTrans; CommonDlg.ShowMessage(CONF_COULD_NOT_DELETE); end; end; finally Free; end; end; end; //end confirm } end; procedure TfrmDialogBeginBalancePOS.actSaveExecute(Sender: TObject); begin inherited; if IsValidate then SavingData; end; procedure TfrmDialogBeginBalancePOS.FormDestroy(Sender: TObject); begin inherited; frmDialogBeginBalancePOS := nil; end; procedure TfrmDialogBeginBalancePOS.footerDialogMasterbtnSaveClick( Sender: TObject); begin inherited; //init if(cbpPosCode.Text = '') then begin CommonDlg.ShowErrorEmpty('POS CODE'); cbpPosCode.SetFocus; Exit; end; if(cbpCashierID.Text = '') then begin CommonDlg.ShowErrorEmpty('CASHIER ID'); cbpCashierID.SetFocus; Exit; end; { if not IsValidDateKarenaEOD(dialogunit,frmBeginningBalancePOS.dt1.Date,FMasterIsStore) then Exit; IsProcessSuccessfull := False; with TBeginningBalance.CreateWithUser(Self,FLoginId,dialogunit) do begin try UpdateData(dialogunit, edtDescrp.Text, Balance_ID, StrToInt(CashierID), dialogunit, curredtBeginBalance.Value, StrToInt(cbpPosCode.Cells[0,cbpPosCode.Row]), Balance_Shift_ID, Balance_Shift_Date, 'OPEN' ); if IsPOSIniSudahDisettingBBnya and (FormMode=fmAdd) then begin CommonDlg.ShowError('POS Ini Sudah Disetting Beginning Balance-nya'); cbpPosCode.SetFocus; Exit; end; if IsKasirIniSudahDisettingBBnya and (FormMode=fmAdd) then begin CommonDlg.ShowError('Kasir Ini Sudah Disetting Beginning Balance-nya'); cbpCashierID.SetFocus; Exit; end; if IsKasirIniSudahDiShiftLain and (FormMode=fmAdd) then begin CommonDlg.ShowError('Kasir Ini Sudah Digunakan di shift lain'); cbpPosCode.SetFocus; Exit; end; IsProcessSuccessfull := SaveToDB; if IsProcessSuccessfull then begin cCommitTrans; end else begin cRollbackTrans; end; finally Free; end; end; } Close; end; procedure TfrmDialogBeginBalancePOS.FormShow(Sender: TObject); begin inherited; {if not Assigned(BeginningBalancePOS) then BeginningBalancePOS := TBeginningBalancePOS.Create; dataSetupPos := BeginningBalancePOS.GetListDataSetupPos(dialogunit); LoadDropDownData(cbpPosCode,dataSetupPos.RecordCount, Balance_Shift_Date); dataUser := BeginningBalancePOS.GetListDataUser(dialogunit); LoadDropDownData(cbpCashierID,dataUser.RecordCount, Balance_Shift_Date); if FormMode = fmEdit then begin cbpPosCode.Value := PosCode; cbpPosCode.Enabled := False; cbpCashierID.Text := FKasirUsrNm; cbpCashierID.Enabled := False; edtCashierName.Text := CashierName; curredtBeginBalance.Value := Modal; edtDescrp.Text := Descrpt; end else begin cbpCashierID.Enabled := True; cbpPosCode.Enabled := True; curredtBeginBalance.Value := BEGINNING_BALANCE_MODAL; edtDescrp.Text := ''; end; } end; procedure TfrmDialogBeginBalancePOS.LoadDropDownData(ACombo: TcxExtLookupComboBox; AColsOfData: Integer; aTgl : TDateTime); //var // sSQL: string; begin {ACombo.ClearGridData; ACombo.RowCount := 2; ACombo.ColCount := 2; if ACombo = cbpCashierID then begin ACombo.AddRow(['ID','CASHIER ID', 'CASHIER NAME']); if dataUser.RecordCount > 0 then begin ACombo.RowCount := dataUser.RecordCount + 1; dataUser.First; while not dataUser.Eof do begin try ACombo.AddRow([dataUser.FieldByName('USR_ID').AsString, dataUser.FieldByName('USR_USERNAME').AsString, dataUser.FieldByName('USR_FULLNAME').AsString]); if (LowerCase(TcxExtLookupComboBox(ACombo).Name) = LowerCase('cbpCashierID')) and (FormMode = fmEdit) then if dataUser.FieldByName('USR_ID').AsInteger = StrToInt(CashierID) then FKasirUsrNm := dataUser.FieldByName('USR_USERNAME').AsString; except end; dataUser.Next; end;// end while end// if comptt else begin ACombo.RowCount := 2; ACombo.AddRow(['','']); end; end; //end if acombo if ACombo = cbpPosCode then begin ACombo.AddRow(['ID','POS CODE']); sSQL := 'SELECT SETUPPOS_ID, SETUPPOS_TERMINAL_CODE ' + 'FROM SETUPPOS ' + 'WHERE SETUPPOS_IS_ACTIVE = 1 ' + ' and SETUPPOS_UNT_ID = ' + IntToStr(dialogunit) + ' and setuppos_date = ' + QuotD(aTgl) + ' ORDER BY SETUPPOS_TERMINAL_CODE'; with cOpenQuery(sSQL) do begin try LAST; FIRST; if RecordCount > 0 then begin ACombo.RowCount := RecordCount + 1; dataSetupPos.First; while not Eof do begin try ACombo.AddRow([FieldByName('SETUPPOS_ID').AsString, FieldByName('SETUPPOS_TERMINAL_CODE').AsString]); except end; Next; end;// end while end// if comptt else begin ACombo.RowCount := 2; ACombo.AddRow(['','']); end; finally Free; end; end; end; //end if acombo ACombo.SizeGridToData; ACombo.FixedRows:= 1; } end; procedure TfrmDialogBeginBalancePOS.cbpCashierIDCloseUp(Sender: TObject); begin inherited; // CashierID := cbpCashierID.Cells[0,cbpCashierID.Row]; end; procedure TfrmDialogBeginBalancePOS.cbpCashierIDPropertiesEditValueChanged( Sender: TObject); begin inherited; edtCashierName.EditValue := FCDSUser.FieldByName('USR_FULLNAME').AsString; end; procedure TfrmDialogBeginBalancePOS.ClearForm; begin ClearByTag([0]); ModBalance.BALANCE_SHIFT_DATE := frmBeginningBalancePOS.dtAkhirFilter.Date; ModBalance.BALANCE_STATUS := 'OPEN'; ModBalance.ISJOURNALIZED := 0; ModBalance.SHIFT := TModShift.CreateID(frmBeginningBalancePOS.FShiftID); end; procedure TfrmDialogBeginBalancePOS.curredtBeginBalanceEnter( Sender: TObject); begin inherited; curredtBeginBalance.SelectAll; end; function TfrmDialogBeginBalancePOS.GetModBalance: TModBeginningBalance; begin if not Assigned(FModBalance) then FModBalance := TModBeginningBalance.Create; Result := FModBalance; end; procedure TfrmDialogBeginBalancePOS.InitLookUp; begin FCDSUser := TDBUtils.DSToCDS(DMClient.DSProviderClient.AutUser_GetDSLookUp('OPERATOR POS'), Self); cbpCashierID.LoadFromCDS(FCDSUser,'AUT$USER_ID','CASHIER_NAME',['AUT$USER_ID','USR_FULLNAME'],Self); FCDSSetupPOS := TDBUtils.DSToCDS(DMClient.DSProviderClient.SetupPOS_GetDSLookUp(ModBalance.BALANCE_SHIFT_DATE, TRetno.UnitStore.ID), Self); cbpPosCode.LoadFromCDS(FCDSSetupPOS,'SETUPPOS_ID','POS_CODE',['SETUPPOS_ID'],Self); end; function TfrmDialogBeginBalancePOS.IsValidate: Boolean; begin Result := False; if VarIsNull(cbpPosCode.EditValue) then begin TAppUtils.Warning('POS CODE belum diisi'); exit; end else if VarIsNull(cbpCashierID.EditValue) then begin TAppUtils.Warning('CASHIER ID belum diisi'); exit; end else Result := True; end; procedure TfrmDialogBeginBalancePOS.LoadData(AID: string); begin if Assigned(FModBalance) then FreeAndNil(FModBalance); FModBalance := DMClient.CrudClient.Retrieve(TModBeginningBalance.ClassName, AID) as TModBeginningBalance; ModBalance.AUTUSER.Reload(); cbpPosCode.EditValue := ModBalance.SETUPPOS.ID; cbpCashierID.EditValue := ModBalance.AUTUSER.ID; edtCashierName.EditValue := ModBalance.AUTUSER.USR_FULLNAME; curredtBeginBalance.EditValue := ModBalance.BALANCE_MODAL; edtDescrp.EditValue := ModBalance.BALANCE_DESCRIPTION; end; procedure TfrmDialogBeginBalancePOS.SavingData; begin ModBalance.SETUPPOS := TModSetupPOS.CreateID(cbpPosCode.EditValue); ModBalance.AUTUSER := TModAuthUser.CreateID(cbpCashierID.EditValue); ModBalance.BALANCE_MODAL := curredtBeginBalance.EditValue; ModBalance.BALANCE_DESCRIPTION := VarToStr(edtDescrp.EditValue); ModBalance.AUTUNIT := TRetno.UnitStore; Try DMClient.CrudClient.SaveToDB(ModBalance); TAppUtils.Information(CONF_ADD_SUCCESSFULLY); ModalResult := mrOk; except TAppUtils.Error(ER_INSERT_FAILED); Raise; End; end; end.
unit xmltvdb.DateUtils; interface //uses // System.SysUtils ,System.DateUtils ,Soap.XSBuiltIns; type TUTCDateTime = Record strict private var FDT : TDateTime; private function GetAsUTC : TDateTime; function GetAsLocal : TDateTime; function GetAsISO8601String : String; procedure SetAsISO8601String(v : String); function GetAsISO8601StringRAW : String; procedure SetAsISO8601StringRAW(v : String); procedure SetAsUTC(dt : TDateTime); procedure SetAsLocal(dt : TDateTime); function GetAsNormal: TDateTime; procedure SetAsNormal(const Value: TDateTime); function GetAsISO8601StringShort: String; public function IsDST : Boolean; procedure SetToNow; property AsUTC : TDateTime read GetAsUTC Write SetAsUTC; property AsNormal : TDateTime read GetAsNormal Write SetAsNormal; property AsLocal : TDateTime read GetAsLocal Write SetAsLocal; property AsISO8601String : String read GetAsISO8601String Write SetAsISO8601String; property AsISO8601StringRAW : String read GetAsISO8601StringRAW Write SetAsISO8601StringRAW; property AsISO8601StringShort : String read GetAsISO8601StringShort Write SetAsISO8601StringRAW; End; TZymaDateTimeHelper = record helper for TDateTime function ToUCTDateTime : TUTCDateTime; function To24hStr : String; procedure From24hStr(str: String); function HourOfTheDay : integer; function IsNull: Boolean; procedure SetToNull; end; function SHA1FromString(const AString: string): string; implementation uses System.SysUtils, Soap.XSBuiltIns, System.DateUtils, System.StrUtils,IdHashSHA; function SHA1FromString(const AString: string): string; var SHA1: TIdHashSHA1; begin SHA1 := TIdHashSHA1.Create; try Result := SHA1.HashStringAsHex(AString); finally SHA1.Free; end; end; function DateTimeToISO8601(Value: TDateTime): String; const Neg: array[Boolean] of string= ('+', '-'); begin Result := FormatDateTime('yyyymmdd', Value) + 'T' + FormatDateTime('hhnnss', Value) + 'Z'; end; function DateTimeToISO8601NoSec(Value: TDateTime): String; const Neg: array[Boolean] of string= ('+', '-'); begin Result := FormatDateTime('yyyy-mm-dd', Value) + 'T' + FormatDateTime('hh:nn', Value) + 'Z'; end; { TUTCDateTime } function TUTCDateTime.GetAsISO8601StringShort: String; begin Result := DateTimeToISO8601NoSec(FDT); end; function TUTCDateTime.GetAsISO8601String: String; begin Result := DateTimeToXMLTime(FDT, False); end; function TUTCDateTime.GetAsISO8601StringRAW: String; begin Result := DateTimeToISO8601(FDT); end; function TUTCDateTime.GetAsLocal: TDateTime; begin Result := TTimeZone.Local.ToLocalTime(FDT); end; function TUTCDateTime.GetAsNormal: TDateTime; begin Result := TTimeZone.Local.ToLocalTime(FDT); if TTimeZone.Local.IsDaylightTime(FDT) then Result := IncHour(Result, -1); end; function TUTCDateTime.GetAsUTC: TDateTime; begin Result := FDT; end; function TUTCDateTime.IsDST: Boolean; begin Result := TTimeZone.Local.IsDaylightTime(FDT); end; procedure TUTCDateTime.SetAsISO8601String(v: String); begin FDT := XMLTimeToDateTime(v, True); end; procedure TUTCDateTime.SetAsISO8601StringRAW(v: String); var sp: TArray<String>; sDateTime : string; sDateTime2 : string; sFuseau:string; begin sp:= v.Split([' '] ); sDateTime := sp[0]; sFuseau := sp[1]; sDateTime2 := LeftStr(sDateTime,4) +'-' + MidStr(sDateTime,5,2) +'-' + MidStr(sDateTime,7,2)+'T'+ MidStr(sDateTime,9,2) +':' +MidStr(sDateTime,11,2) +':' +MidStr(sDateTime,13,2) ; if not sFuseau.IsEmpty then sDateTime2 := sDateTime2 + LeftStr(sFuseau,3) + ':' + MidStr(sFuseau,4,2); Self.SetAsISO8601String(sDateTime2); end; procedure TUTCDateTime.SetAsLocal(dt: TDateTime); var bInSaving : Boolean; begin if TTimeZone.Local.IsAmbiguousTime(dt) then bInSaving := false; //**+** on doit essaye de détecter la date heure (saving light ou non) FDT := TTimeZone.Local.ToUniversalTime(dt, true ); end; procedure TUTCDateTime.SetAsNormal(const Value: TDateTime); begin FDT := TTimeZone.Local.ToUniversalTime(Value, FALSE); end; procedure TUTCDateTime.SetAsUTC(dt: TDateTime); begin FDT := dt; end; procedure TUTCDateTime.SetToNow; begin FDT := TTimeZone.Local.ToUniversalTime(now); end; { TZymaDateTimeHelper } procedure TZymaDateTimeHelper.From24hStr(str: String); begin end; function TZymaDateTimeHelper.HourOfTheDay: integer; begin // **+** Result := HourOf(self); if Result = 0 then Result := 24; end; function TZymaDateTimeHelper.To24hStr: String; begin // **+** if HourOf(self) = 0 then begin Result := Format('%d-%d-%d %d:%d:%d', [0,0,0,0,0,0]) ; end else begin Result := Format('%d-%d-%d %d:%d:%d', [0,0,0,0,0,0]) ; end; end; function TZymaDateTimeHelper.ToUCTDateTime: TUTCDateTime; begin Result.AsLocal := Self; end; function TZymaDateTimeHelper.IsNull: Boolean; begin Result := (Self = EncodeDateTime(1899, 12, 30, 0, 0, 0, 0)); end; procedure TZymaDateTimeHelper.SetToNull; begin Self := 0; end; end.
unit orcoredll_unit1; interface // unit's public functions. use "C-style" stdcall stack // for better compatibility to other applications. function WideStringToAnsiString(const pw: PWideChar; const buf: PAnsiChar; var lenBuf: Cardinal): boolean; stdcall; function URLDecodeUTF8(const s: PAnsiChar; const buf: PWideChar; var lenBuf: Cardinal): boolean; stdcall; function URLDecodeUTF8A(const s: PAnsiChar; const buf: PAnsiChar; var lenBuf: Cardinal): boolean; stdcall; implementation uses SysUtils; { Convert unicode WideString to AnsiString @param pw widestring to be converted @outparam buf buffer for resulting ansistring @outparam lenBuf number of characters in buffer @return true if conversion was done or false if only lenBuf was updated } function WideStringToAnsiString(const pw: PWideChar; const buf: PAnsiChar; var lenBuf: Cardinal): boolean; stdcall; var sa: AnsiString; len: Cardinal; begin sa := WideCharToString(pw); len := Length(sa); if Assigned(buf) and (len < lenBuf) then begin // copy result into the buffer, buffer must have // space for last null byte. // lenBuf=num of chars in buffer, not counting null if (len > 0) then Move(PAnsiChar(sa)^, buf^, len * SizeOf(AnsiChar)); buf[len] := #0; lenBuf := len; Result := True; end else begin // tell calling program how big the buffer // shoule be to store all decoded characters, // including trailing null value. if (len > 0) then lenBuf := len+1; Result := False; end; end; { URLDecode utf8 encoded string. Resulting widestring is copied to inout 'buf' buffer. @param s encoded string @outparam buf buffer for decoded string or nil if should update lenBuf only @outparam lenBuf num of characters stored to buffer @return true if string was decoder or false if only lenBuf was updated. } function URLDecodeUTF8(const s: PAnsiChar; const buf: PWideChar; var lenBuf: Cardinal): boolean; stdcall; var sAnsi: String; // normal ansi string sUtf8: String; // utf8-bytes string sWide: WideString; // unicode string i, len: Cardinal; ESC: string[2]; CharCode: integer; c: char; begin sAnsi := s; // null-terminated str to pascal str SetLength(sUtf8, Length(sAnsi)); // Convert URLEncoded str to utf8 str, it must // use utf8 hex escaping for non us-ascii chars // + = space // %2A = * // %C3%84 = Ä (A with diaeresis) i := 1; len := 1; while (i <= Cardinal(Length(sAnsi))) do begin if (sAnsi[i] <> '%') then begin if (sAnsi[i] = '+') then begin c := ' '; end else begin c := sAnsi[i]; end; sUtf8[len] := c; Inc(len); end else begin Inc(i); // skip the % char ESC := Copy(sAnsi, i, 2); // Copy the escape code Inc(i, 1); // skip ESC, another +1 at end of loop try CharCode := StrToInt('$' + ESC); //if (CharCode > 0) and (CharCode < 256) then begin c := Char(CharCode); sUtf8[len] := c; Inc(len); //end; except end; end; Inc(i); end; Dec(len); // -1 to fix length (num of characters) SetLength(sUtf8, len); sWide := UTF8Decode(sUtf8); // utf8 string to unicode len := Length(sWide); if Assigned(buf) and (len < lenBuf) then begin // copy result into the buffer, buffer must have // space for last null byte. // lenBuf=num of chars in buffer, not counting null if (len > 0) then Move(PWideChar(sWide)^, buf^, len * SizeOf(WideChar)); buf[len] := #0; lenBuf := len; Result := True; end else begin // tell calling program how big the buffer // should be to store all decoded characters, // including trailing null value. if (len > 0) then lenBuf := len+1; Result := False; end; end; { URLDecode utf8 encoded string. Resulting widestring is copied to inout 'buf' buffer. @param s encoded string @outparam buf buffer for decoded string or nil if should update lenBuf only @outparam lenBuf num of characters stored to buffer @return true if string was decoder or false if only lenBuf was updated. } function URLDecodeUTF8A(const s: PAnsiChar; const buf: PAnsiChar; var lenBuf: Cardinal): boolean; stdcall; var len: Cardinal; pw: PWideChar; ok : boolean; begin // decode to widestring len := lenBuf * SizeOf(WideChar) + 1; pw := AllocMem(len); try ok := URLDecodeUTF8(s, pw, len); if Not(ok) then begin lenBuf := len; // num of chars in pw buffer Result := ok; Exit; end; // convert to ansistring len := len * SizeOf(AnsiChar) + 1; ok := WideStringToAnsiString(pw, buf, len); lenBuf := len; Result := ok; finally FreeMem(pw); end; end; end.
unit SDL_Tools; {:< Basic tools to make SDL Graphics programming easier} { Simple GUI is based upon Lachlans GUI (LK GUI). LK GUI's original source code remark is shown below. Written permission to re-license the library has been granted to me by the original author. } {*******************************************************} { } { Helper functions for drawing with SDL } { } { Copyright (c) 2009-10 Lachlan Kingsford } { } {*******************************************************} { Simple GUI ********** Copyright (c) 2016 Matthias J. Molski 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. } interface uses Math, SDL2, SDL2_SimpleGUI_Base; function calcdistance(x1, y1, x2, y2: extended): extended; procedure drawpixel(x, y: Word; screen: PSDL_Surface; r, g, b: UInt8); inline; procedure drawpixel(x, y: Word; screen: PSDL_Surface; r, g, b, a: UInt16); inline; procedure drawalphapixel(x, y: Word; screen: PSDL_Surface; r, g, b: UInt8; a: extended); inline; procedure drawline(x0, y0, x1, y1: Word; screen: PSDL_Surface; r, g, b: UInt16); inline; overload; (* SDL2 conv.: new and overridden procedures *) procedure fillrect(renderer: PSDL_Renderer; targetTex: PSDL_Texture; rect: PSDL_Rect; color: tRGBA); inline; // obsolete procedure drawline(renderer: PSDL_Renderer; targetTex: PSDL_Texture; x0, y0, x1, y1: Word; color: tRGBA); inline; overload; // obsolete implementation function calcdistance(x1, y1, x2, y2: extended): extended; inline; begin calcdistance := sqrt(sqr(max(x1, x2) - min(x1, x2)) + sqr(max(y1, y2) - min(y1, y2))); end; procedure drawpixel(x, y: Word; screen: PSDL_Surface; r, g, b: UInt8); inline; var target: PUint32; begin if ((y * screen^.w + x) < (screen^.h * screen^.w)) then begin target := (PUint32(screen^.pixels)) + Y * screen^.w + X; (Target)^ := UInt32(SDL_MapRGB(screen^.format, r, g, b)); end; end; procedure drawpixel(x, y: Word; screen: PSDL_Surface; r, g, b, a: UInt16); inline; var target: PUint32; begin if ((y * screen^.w + x) < (screen^.h * screen^.w)) then begin target := (PUint32(screen^.pixels)) + Y * screen^.w + X; (Target)^ := UInt32(SDL_MapRGBA(screen^.format, r, g, b, a)); end; end; procedure drawalphapixel(x, y: Word; screen: PSDL_Surface; r, g, b: UInt8; a: extended); inline; var target: PUint32; oldr, oldg, oldb: PUint8; begin if ((y * screen^.w + x) < (screen^.h * screen^.w)) then begin target := (PUint32(screen^.pixels)) + Y * screen^.w + X; new(oldr); new(oldg); new(oldb); SDL_GetRGB(target^, screen^.format, oldr, oldg, oldb); (Target)^ := UInt32(SDL_MapRGB(screen^.format, round((1 - a) * oldr^ + a * r), round((1 - a) * oldg^ + a * g), round((1 - a) * oldb^ + a * b))); dispose(oldr); dispose(oldg); dispose(oldb); end; end; //Based on http://freespace.virgin.net/hugo.elias/graphics/x_wuline.htm procedure drawline(x0, y0, x1, y1: Word; screen: PSDL_Surface; r, g, b: UInt16); var grad, xd, yd, xgap, xend, yend, xf, yf, brightness1, brightness2: extended; xtemp, ytemp, ix1, ix2, iy1, iy2: Integer; shallow: Boolean; begin //Draw endpoints //Note: Maybe replace with 'point' style endpoints? {drawalphapixel(x0, y0, screen, r, g, b, 1); drawalphapixel(x1, y1, screen, r, g, b, 1);} //Why this code works... //I don't know! The steep code was largely trial and error... //Width and height of the line xd := (x1 - x0); yd := (y1 - y0); //Check line gradient if abs(xd) > abs(yd) then shallow := True else shallow := False; if x0 > x1 then begin xtemp := x0; x0 := x1; x1 := xtemp; xtemp := y0; y0 := y1; y1 := xtemp; xd := x1 - x0; yd := y1 - y0; end; if (shallow) then grad := yd / xd else grad := xd / yd; //End Point 1 xend := trunc(x0 + 0.5); yend := y0 + grad * (xend - x0); xgap := 1 - frac(x0 + 0.5); ix1 := trunc(xend); iy1 := trunc(yend); brightness1 := (1 - frac(yend)) * xgap; brightness2 := frac(yend) * xgap; DrawAlphaPixel(ix1, iy1, screen, r, g, b, brightness1); DrawAlphaPixel(ix1, iy1 + 1, screen, r, g, b, brightness2); yf := yend + grad; xf := xend + grad; //End Point 2; xend := trunc(x1 + 0.5); yend := y1 + grad * (xend - x1); xgap := 1 - frac(x1 + 0.5); ix2 := trunc(xend); iy2 := trunc(yend); brightness1 := (1 - frac(yend)) * xgap; brightness2 := frac(yend) * xgap; DrawAlphaPixel(ix2, iy2, screen, r, g, b, brightness1); DrawAlphaPixel(ix2, iy2 + 1, screen, r, g, b, brightness2); if not (shallow) then if iy1 > iy2 then begin ytemp := iy2; iy2 := iy1; iy1 := ytemp; xtemp := ix2; ix2 := ix1; ix1 := xtemp; xf := xend + grad; end; //Main Loop if (shallow) then for xtemp := (ix1 + 1) to (ix2 - 1) do begin brightness1 := 1 - frac(yf); brightness2 := frac(yf); drawalphapixel(xtemp, trunc(yf), screen, r, g, b, brightness1); drawalphapixel(xtemp, trunc(yf) + 1, screen, r, g, b, brightness2); yf := yf + grad; end else for ytemp := (iy1 + 1) to (iy2 - 1) do begin brightness1 := 1 - frac(xf); brightness2 := frac(xf); drawalphapixel(trunc(xf), ytemp, screen, r, g, b, brightness1); drawalphapixel(trunc(xf) + 1, ytemp, screen, r, g, b, brightness2); xf := xf + grad; end; end; { SDL2 re-strct.: new functions and procedure for better performance } //function MakeRect(ax, ay, aw, ah: Word): PSDL_Rect; //const // ARect: TSDL_Rect = (x: 0; y: 0; w: 0; h: 0); //begin // with ARect do // begin // x := ax; // y := ay; // w := aw; // h := ah; // end; // Result := @ARect; //end; //procedure RenderFilledRect(renderer: PSDL_Renderer; rect: PSDL_Rect; color: tRGBA); //begin // SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); // SDL_RenderFillRect(renderer, rect); //end; // //procedure RenderLine(renderer: PSDL_Renderer; x0, y0, x1, y1: Word; // color: tRGBA); //begin // SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); // SDL_RenderDrawLine(renderer, x0, y0, x1, y1); //end; (* SDL2 conv.: implemenetation of new and overridden procedures *) procedure drawline(renderer: PSDL_Renderer; targetTex: PSDL_Texture; x0, y0, x1, y1: Word; color: tRGBA); begin SDL_SetRenderTarget(renderer, targetTex); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); SDL_RenderDrawLine(renderer, x0, y0, x1, y1); SDL_SetRenderTarget(renderer, nil); end; procedure fillrect(renderer: PSDL_Renderer; targetTex: PSDL_Texture; rect: PSDL_Rect; color: tRGBA); begin SDL_SetRenderTarget(renderer, targetTex); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); if rect = nil then SDL_RenderClear(Renderer) else SDL_RenderDrawRect(renderer, rect); SDL_SetRenderTarget(renderer, nil); end; begin end.
unit UItensLeituraGasVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UUnidadeVO; type [TEntity] [TTable('ItensLeituraGas')] TItensLeituraGasVO = class(TGenericVO) private FidItensLeituraGas : Integer; FidLeituraGas : Integer; FidUnidade : Integer; FvlMedido : currency; FvlCalculado : currency; FdtLeitura : TDateTime; FdsUnidade : String; public UnidadeVO : TUnidadeVO; [TId('idItensLeituraGas')] [TGeneratedValue(sAuto)] property idItensLeituraGas : Integer read FidItensLeituraGas write FidItensLeituraGas; [TColumn('idLeituraGas','Leitura Gás',0,[ldLookup,ldComboBox], False)] property idLeituraGas: integer read FidLeituraGas write FidLeituraGas; [TColumn('dtLeitura','Data',0,[ldGrid,ldLookup,ldComboBox], False)] property dtLeitura: TDateTime read FdtLeitura write FdtLeitura; [TColumn('idUnidade','Unidade',0,[ldLookup,ldComboBox], False)] property idUnidade: integer read FidUnidade write FidUnidade; [TColumn('vlMedido','Valor Medido',50,[ldGrid,ldLookup,ldComboBox], False)] property vlMedido: currency read FvlMedido write FvlMedido; [TColumn('vlCalculado','Valor Calculado',50,[ldGrid,ldLookup,ldComboBox], False)] property vlCalculado: currency read FvlCalculado write FvlCalculado; [TColumn('DSUNIDADE','Unidade',0,[], True, 'Unidade', 'idUnidade', 'idUnidade')] property DsUnidade: string read FdsUnidade write FdsUnidade; procedure ValidarCamposObrigatorios; end; implementation procedure TItensLeituraGasVO.ValidarCamposObrigatorios; begin if (self.dtLeitura = 0) then begin raise Exception.Create('O campo Data é obrigatório!'); end; if (self.vlMedido < 0) then begin raise Exception.Create('O campo Valor Medido é obrigatório!'); end; end; end.
unit docs.admin; interface uses Horse, Horse.GBSwagger; procedure registry(); implementation uses schemas.classes; procedure registry(); begin Swagger .Path('administrador') .Tag('Administradores') .GET('listar administradores', 'listar administradores') .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddResponse(200) .Schema(TUserAdminPagination) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(404, 'administrador não encontrada') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('administrador/{id_admin}') .Tag('Administradores') .GET('listar um administrador', 'listar administrador especifico') .AddParamPath('id_admin', 'id_admin') .Schema(SWAG_INTEGER) .required(true) .&End .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddResponse(200) .Schema(TUserAdmin) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(404, 'administrador não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('administrador/{id_admin}/foto') .Tag('Administradores') .GET('listar foto administrador', 'listar foto administrador especifico') .AddParamPath('id_admin', 'id_admin') .Schema(SWAG_INTEGER) .required(true) .&End .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddResponse(200) .Schema('image/png') .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(TMessage) .&End .AddResponse(404, 'administrador não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('administrador/criar') .Tag('Administradores') .Post('criar administrador', 'criar novo usuário administrador') .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddParamBody .Schema(TUserAdmin) .&End .AddResponse(201) .Schema(TRegion) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(TMessage) .&End .AddResponse(404, 'administrador não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('administrador/{id_admin}') .Tag('Administradores') .Put('alterar um administrador', 'um administrador') .AddParamPath('id_admin', 'id_admin') .Schema(SWAG_INTEGER) .&end .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddParamBody .Schema(TUserAdmin) .&End .AddResponse(200) .Schema(TRegion) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(TMessage) .&End .AddResponse(404, 'administrador não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('administrador/{id_admin}') .Tag('Administradores') .Delete('deletar um administrador', 'deletar um administrador') .AddParamPath('id_admin', 'id_admin') .Schema(SWAG_INTEGER) .&end .AddParamHeader('Authorization', 'Authorization') .Schema(TToken) .&End .AddResponse(200, 'administrador deletadado com sucesso') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(TMessage) .&End .AddResponse(404, 'administrador não existe') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; end; end.
unit ThDataConnectionProperty; interface uses Classes, DesignIntf, DesignEditors, ThDataConnection; type TThConnnectionStringPropertyEditor = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure Edit; override; end; procedure RegisterConnectionStringPropertyEditor; implementation uses ThConnectionStringEdit; procedure RegisterConnectionStringPropertyEditor; begin RegisterPropertyEditor(TypeInfo(TThConnectionString), TThDataConnection, 'ConnectionString', TThConnnectionStringPropertyEditor); end; { TThConnnectionStringPropertyEditor } function TThConnnectionStringPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [ paDialog ]; end; procedure TThConnnectionStringPropertyEditor.Edit; begin with TThConnectionStringEditForm.Create(nil) do try ConnectionString := Value; ShowModal; Value := ConnectionString; finally Free; end; end; procedure TThConnnectionStringPropertyEditor.GetValues(Proc: TGetStrProc); var i: Integer; begin with NeedConnectionStore do for i := 0 to Pred(ConnectionStrings.Count) do Proc(ConnectionStrings[i]); end; end.
unit u_PosSorter; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvUtil, Vcl.Grids, AdvObj, BaseGrid, AdvGrid, Vcl.StdCtrls, Vcl.ExtCtrls, o_GridDataList, o_GridData; type TForm1 = class(TForm) Panel1: TPanel; btn_LadeGrid: TButton; grd: TAdvStringGrid; btn_Neu: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure grdGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure btn_LadeGridClick(Sender: TObject); procedure grdKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); private fGridDataList: TGridDataList; procedure LadeGrid; procedure LadeGridData; procedure RefreshGrid; function SucheTauschRowUp(aListId: Integer): Integer; function SucheTauschRowDown(aListId: Integer): Integer; function getRowFromId(aId: Integer): Integer; procedure GotoRowFromId(aId: Integer); public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin grd.ColCount := 6; grd.Options := grd.Options + [goColSizing]; grd.Options := grd.Options + [goRowSelect]; grd.Options := grd.Options - [goRangeSelect]; grd.ShowSelection := false; grd.SortSettings.show := false; grd.DefaultRowHeight := 20; grd.SelectionRectangle := true; grd.ShowHint := true; grd.SortSettings.Show := true; grd.FixedColWidth := 10; grd.Cells[1,0] := 'ID'; grd.Cells[2,0] := 'PosIdx'; grd.Cells[3,0] := 'PrnNr'; grd.Cells[4,0] := 'PosNr'; grd.Cells[5,0] := 'Text'; grd.ColWidths[5] := 200; fGridDataList := TGridDataList.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin FreeAndNil(fGridDataList); end; procedure TForm1.FormShow(Sender: TObject); begin grd.SetFocus; end; procedure TForm1.grdGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin if (ACol = 3) or (ACol=4) then HAlign := taRightJustify; end; procedure TForm1.btn_LadeGridClick(Sender: TObject); begin LadeGrid; grd.SetFocus; end; procedure TForm1.LadeGridData; procedure Add(aBez: string; aParentId, aId: Integer); var x: TGridData; begin x := fGridDataList.Add; x.Bez := aBez; x.SortPos.Id := aId; x.SortPos.ParentId := aParentId; end; begin fGridDataList.Clear; Add('Hardware', 0, 1); Add('Drucker', 1, 2); Add('Epson SD', 2, 3); Add('Brother YZ', 2, 4); Add('Dell', 2, 9); Add('Software', 0, 5); Add('Optima', 5, 6); Add('Bleistift', 0, 7); Add('Kuli', 0, 8); Add('Drucker Zubehör', 1, 10); Add('Usb-Kabel', 10, 11); Add('Stromkabel', 10, 12); end; procedure TForm1.LadeGrid; begin grd.ClearNormalCells; LadeGridData; fGridDataList.LadeSorter; RefreshGrid; end; procedure TForm1.RefreshGrid; var i1: Integer; x: TGridData; begin grd.RowCount := fGridDataList.Count + 1; for i1 := 0 to fGridDataList.Count -1 do begin x := fGridDataList.Item[i1]; grd.Objects[0, i1+1] := x; grd.Cells[1, i1+1] := IntToStr(x.SortPos.Id); grd.Cells[2, i1+1] := x.SortPos.PrintIdx; grd.Cells[3, i1+1] := IntToStr(x.SortPos.PrnNr); grd.Cells[4, i1+1] := IntToStr(x.SortPos.Nr); grd.Cells[5, i1+1] := x.Bez; end; end; procedure TForm1.grdKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var GridData: TGridData; IdVon: Integer; IdNach: Integer; NewRow: Integer; begin if Shift = [ssCtrl] then begin IdVon := 0; IdNach := 0; NewRow := 0; if (Key = VK_UP) and (grd.Objects[0, grd.Row] <> nil) then begin GridData := TGridData(grd.Objects[0, grd.Row]); IdVon := GridData.SortPos.Id; NewRow := SucheTauschRowUp(GridData.SortPos.ListId); end; if (Key = VK_DOWN) and (grd.Objects[0, grd.Row] <> nil) then begin GridData := TGridData(grd.Objects[0, grd.Row]); IdVon := GridData.SortPos.Id; NewRow := SucheTauschRowDown(GridData.SortPos.ListId); end; if (IdVon > 0) and (NewRow > 0) then begin GridData := TGridData(grd.Objects[0, NewRow]); IdNach := GridData.SortPos.Id; fGridDataList.PosTauschen(IdVon, IdNach); RefreshGrid; GotoRowFromId(IdVon); //grd.GotoCell(0, NewRow); //caption := 'Von: ' + IntToStr(IdVon) + ' Nach: ' + IntToStr(IdNach); end; if (Key = VK_LEFT) and (grd.Objects[0, grd.Row] <> nil) then begin GridData := TGridData(grd.Objects[0, grd.Row]); IdVon := GridData.SortPos.Id; fGridDataList.EineEbeneNachOben(IdVon); RefreshGrid; GotoRowFromId(IdVon); end; if (Key = VK_RIGHT) and (grd.Objects[0, grd.Row] <> nil) then begin GridData := TGridData(grd.Objects[0, grd.Row]); IdVon := GridData.SortPos.Id; GridData := TGridData(grd.Objects[0, grd.Row-1]); if GridData = nil then exit; IdNach := GridData.SortPos.Id; fGridDataList.EineEbeneNachUnten(IdVon, IdNach); RefreshGrid; GotoRowFromId(IdVon); end; end; end; function TForm1.SucheTauschRowUp(aListId: Integer): Integer; var Row: Integer; GridData: TGridData; begin Result := -1; Row := grd.Row -1; while Row > 0 do begin if grd.Objects[0, Row] = nil then begin dec(Row); continue; end; GridData := TGridData(grd.Objects[0, Row]); if GridData.SortPos.ListId = aListId then begin Result := Row; exit; end; dec(Row); end; end; function TForm1.SucheTauschRowDown(aListId: Integer): Integer; var Row: Integer; GridData: TGridData; begin Result := -1; Row := grd.Row +1; while Row < grd.RowCount do begin if grd.Objects[0, Row] = nil then begin inc(Row); continue; end; GridData := TGridData(grd.Objects[0, Row]); if (GridData.SortPos.ListId = aListId) then begin Result := Row; exit; end; inc(Row); end; end; function TForm1.getRowFromId(aId: Integer): Integer; var GridData: TGridData; i1: Integer; begin Result := 1; for i1 := 1 to grd.Rowcount -1 do begin GridData := TGridData(grd.Objects[0, i1]); if GridData = nil then continue; if GridData.SortPos.Id = aId then begin Result := i1; exit; end; end; end; procedure TForm1.GotoRowFromId(aId: Integer); begin grd.GotoCell(0, getRowFromId(aId)); end; end.
unit Windows.Services; interface uses Xplat.Services, FMX.Platform.Win, System.UITypes, FMX.Types; type TWinPleaseWait = class(TInterfacedObject, IPleaseWaitService) private FCurrent: TCursor; FService: IFMXCursorService; private function GetService: IFMXCursorService; property Service: IFMXCursorService read GetService; public procedure StartWait; procedure StopWait; end; implementation uses FMX.Forms, FMX.Platform, Xplat.Inifiles; { TMacPleaseWait } function TWinPleaseWait.GetService: IFMXCursorService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXCursorService, IInterface(FService)) then Result := FService else Result := nil; end; procedure TWinPleaseWait.StartWait; begin if Assigned(Service) then begin FCurrent := Service.GetCursor; Service.SetCursor(crHourglass); Application.ProcessMessages; end; end; procedure TWinPleaseWait.StopWait; begin if Assigned(Service) then begin Service.SetCursor(FCurrent); Application.ProcessMessages; end; end; initialization TPlatformServices.Current.AddPlatformService(IPleaseWaitService, TWinPleaseWait.Create); TPlatformServices.Current.AddPlatformService(IIniFileService, TXplatIniFile.Create); finalization TPlatformServices.Current.RemovePlatformService(IPleaseWaitService); TPlatformServices.Current.RemovePlatformService(IIniFileService); end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, JNI, JNIUtils; type TForm1 = class(TForm) btn1: TButton; procedure btn1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FJavaVM : TJavaVM; FJavaEnv: TJNIEnv; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var Options: array [0 .. 4] of JavaVMOption; VM_args: JavaVMInitArgs; ErrCode: Integer; begin { 创建 Java 虚拟机 } FJavaVM := TJavaVM.Create(JNI_VERSION_1_8, ExtractFilePath(ParamStr(0)) + 'jre1.8.0_202\bin\client\jvm.dll'); Options[0].optionString := PAnsiChar(AnsiString('-Djava.class.path=' + ExtractFilePath(ParamStr(0)) + 'classes')); VM_args.version := JNI_VERSION_1_8; VM_args.Options := @Options; VM_args.nOptions := 1; VM_args.ignoreUnrecognized := True; ErrCode := FJavaVM.LoadVM(VM_args); if ErrCode < 0 then begin MessageBox(Handle, 'Create Java VM Error', 'Delphi 11 Call Java Class', MB_OK OR MB_ICONERROR); Halt; Exit; end; { 创建 Java 虚拟机运行环境 } FJavaEnv := TJNIEnv.Create(FJavaVM.Env); if FJavaEnv = nil then begin MessageBox(Handle, 'Create Java Env Error', 'Delphi 11 Call Java Class', MB_OK OR MB_ICONERROR); Exit; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin FJavaEnv.Free; FJavaVM.DestroyJavaVM; FJavaVM.Free; end; procedure TForm1.btn1Click(Sender: TObject); var jcls : JClass; strClass : UTF8String; strMetod : UTF8String; strSign : UTF8String; strArg, strResult: string; begin { 查询 Java 类名 } strClass := 'com/test/javafordelphi/JavaClassForDelphiTest'; jcls := FJavaEnv.FindClass(strClass); if jcls = nil then begin MessageBox(Handle, 'cant find java class', 'Delphi 11 Call Java Class', MB_OK OR MB_ICONERROR); Exit; end; { Java 函数名称、参数类型、参数 } strMetod := 'goTest'; // 函数名称 strSign := 'String (String)'; // 参数类型,返回值类型 strArg := '123'; // 输入参数 { 执行 Java 函数 } strResult := CallMethod(FJavaEnv, jcls, strMetod, strSign, [strArg], True); if strResult <> '' then begin MessageBox(Handle, PChar(Format('JavaClassForDelphiTest.goTest Result: %s', [strResult])), 'Delphi 11 Call Java Class', MB_OK OR MB_ICONINFORMATION); end; end; end.
Program IdadesFuncao; var vetor: array[1..20] of integer; idade: integer; i: integer; // Armazena Idades no Vetor procedure ArmazenaIdades (idade, i: integer); Begin vetor[i] := idade; End; //Calcula Média procedure CalculaMedia; var soma: integer; k: integer; media: real; Begin for k:=1 to i do begin soma := soma + vetor[k]; end; media:= soma/(i-1); writeln('A média das Idades é: ',media:2:0); End; //Mostra Maior Idade Digitada procedure MaiorIdade; var k: integer; maior: integer; Begin maior := 0; for k:=1 to i do begin if vetor[k] > maior then maior := vetor[k]; end; writeln('A maior idade é: ', maior); End; //Mostra Menor Idade Digitada procedure MenorIdade; var k: integer; menor: integer; Begin menor := 1000; for k:=1 to i do begin if (vetor[k] < menor) and (vetor[k] <> 0) then menor := vetor[k]; end; writeln('A menor idade é: ', menor); End; //Main Begin while True do Begin writeln('Digite a idade de um aluno ou digite 0 para parar: '); readln(idade); i := i + 1; ArmazenaIdades(idade, i); if idade = 0 then break; End; writeln; CalculaMedia(); writeln; MaiorIdade(); writeln; MenorIdade(); End.
unit uMsgBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; const vbOKOnly = 0; // Display OK button only. vbOKCancel = 1; // Display OK and Cancel buttons. vbAbortRetryIgnore = 2; // Display Abort, Retry, and Ignore buttons. vbYesNoCancel = 3; // Display Yes, No, and Cancel buttons. vbYesNo = 4; // Display Yes and No buttons. vbRetryCancel = 5; // Display Retry and Cancel buttons. vbCritical = 16; // Display Critical Message icon. vbQuestion = 32; // Display Query icon. vbWaring = 48; // Display Warning Message icon. vbExclamation = 48; // Display Warning Message icon. vbInformation = 64; // Display Information Message icon. vbSuperCritical = 80; //Display Super Critical Message icon. vbDefaultButton1 = 512; // First button is default. vbDefaultButton2 = 256; // Second button is default. vbDefaultButton3 = 0; // Third button is default. vbOK = 1; vbCancel = 2; vbAbort = 3; vbRetry = 4; vbIgnore = 5; vbYes = 6; vbNo = 7; TITLE_MAXWIDTH = 449; MSG_MAXWIDTH = 449; TITLEMSG_SPACING = 7; HEIGTH_Adjust = 80; WIDTH_Adjust = 78; SCREEN_MinWidth = 284; SCREEN_MinHeigth = 125; // MessageBox function MsgBox(Titles : String; Option: Integer) : Integer; type TFrmMsgBox = class(TForm) Critico: TImage; Informacao: TImage; Alerta: TImage; Questao: TImage; MSG: TLabel; Titulo: TLabel; Panel1: TPanel; Button3: TButton; Button2: TButton; Button1: TButton; tmrBlink: TTimer; procedure Button1Click(Sender: TObject); procedure tmrBlinkTimer(Sender: TObject); private { Private declarations } MyResult: Integer; Vez : Boolean; public { Public declarations } function Start(Titles : String; Option: Integer) : Integer; end; var FrmMsgBox: TFrmMsgBox; implementation uses xBase; {$R *.DFM} function MsgBox(Titles : String; Option: Integer) : Integer; begin Result := TFrmMsgBox.Create(Application).Start(Titles, Option) end; Function TFrmMsgBox.Start(Titles : String; Option: Integer) : Integer; var DialogUnits : TPoint; MinWidthTitulo, MinWidthMsg, Icon, Buttons, DefaultButton : Integer; IniLeft, WidthButton, MinHeightTitulo, MinHeightMsg, i, Cont : Integer; SubTitle : array[1..3] of String; Substr : String; TextRect: TRect; begin // Separa a string Titles, separadas por '_' // 1o vem o titulo em negrito // 2o vem o titulo de baixo // 3o vem o caption da tela, se nao passado ele atribui o default SubStr := ''; Cont := 1; SubTitle[1] := ''; SubTitle[2] := ''; SubTitle[3] := ''; for i := 1 to Length(Titles) do begin if (Titles[i] = '_') or (i = Length(Titles)) then begin if (i = Length(Titles)) then SubStr := SubStr + Titles[i]; SubTitle[Cont] := SubStr; Inc(Cont); SubStr := ''; end else begin SubStr := SubStr + Titles[i]; end; end; Titulo.Caption := SubTitle[1]; Msg.Caption := SubTitle[2]; if SubTitle[3] = '' then Caption := Application.Title else Caption := SubTitle[3]; DefaultButton := Round(Option / 256) * 256; Option := Option - DefaultButton; Icon := round(Option / 16) * 16; Option := Option - Icon; Buttons := Option; Critico.Visible := False; Questao.Visible := False; Alerta.Visible := False; Informacao.Visible := False; case Icon of vbCritical : Critico.Visible := True; vbSuperCritical : Critico.Visible := True; vbQuestion : Questao.Visible := True; vbExclamation : Alerta.Visible := True; vbInformation : Informacao.Visible := True; end; case Buttons of vbOKOnly : begin Button1.Visible := True; Button1.Tag := vbOK; Button1.Caption := '&Ok'; Button1.Cancel := True; Button2.Visible := False; Button3.Visible := False; end; vbOKCancel : begin Button1.Visible := True; Button1.Tag := vbCancel; Button1.Caption := '&Cancel'; Button1.Cancel := True; Button2.Visible := True; Button2.Tag := vbOK; Button2.Caption := '&Ok'; Button2.Cancel := False; Button3.Visible := False; end; vbAbortRetryIgnore : begin Button1.Visible := True; Button1.Tag := vbIgnore; Button1.Caption := '&Ignore'; Button1.Cancel := True; Button2.Visible := True; Button2.Tag := vbRetry; Button2.Caption := '&Repeat'; Button2.Cancel := False; Button3.Visible := True; Button3.Tag := vbAbort; Button3.Caption := '&Abort'; Button3.Cancel := False; end; vbYesNoCancel : begin Button1.Visible := True; Button1.Tag := vbCancel; Button1.Caption := '&Cancel'; Button1.Cancel := True; Button2.Visible := True; Button2.Tag := vbNo; Button2.Caption := '&No'; Button2.Cancel := False; Button3.Visible := True; Button3.Tag := vbYes; Button3.Caption := '&Yes'; Button2.Cancel := False; end; vbYesNo : begin Button1.Visible := True; Button1.Tag := vbNo; Button1.Caption := '&No'; Button1.Cancel := True; Button2.Visible := True; Button2.Tag := vbYes; Button2.Caption := '&Yes'; Button2.Cancel := False; Button3.Visible := False; end; vbRetryCancel : begin Button1.Visible := True; Button1.Tag := vbCancel; Button1.Caption := '&Cancel'; Button1.Cancel := True; Button2.Visible := True; Button2.Tag := vbRetry; Button2.Caption := '&Repeat'; Button2.Cancel := False; Button3.Visible := False; end; end; // define o botao default case DefaultButton of vbDefaultButton1 : begin Button1.Default := True; ActiveControl := Button1; end; vbDefaultButton2 : if Button2.Visible then begin Button2.Default := True; ActiveControl := Button2; end else begin Button1.Default := True; ActiveControl := Button1; end; vbDefaultButton3 : if Button3.Visible then begin Button3.Default := True; ActiveControl := Button3; end else begin if Button2.Visible then begin Button2.Default := True; ActiveControl := Button2; end else begin Button1.Default := True; ActiveControl := Button1; end; end; end; // Define se existe titulo, ou mensagem Titulo.Visible := not (Titulo.caption = ''); Msg.Visible := not (Msg.caption = ''); // Define a largura e altura da tela if Titulo.Visible then begin Canvas.Font := Titulo.Font; SetRect(TextRect, 0, 0, TITLE_MAXWIDTH, 0); DrawText(Canvas.Handle, PChar(Titulo.caption), Length(Titulo.caption), TextRect, DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK); MinWidthTitulo := textrect.right-textrect.left; MinHeightTitulo := textrect.bottom-textrect.top; // Define o Top da Msg Msg.Top := Titulo.Top + MinHeightTitulo + TITLEMSG_SPACING; Titulo.Height := MinHeightTitulo; Inc(MinWidthTitulo, WIDTH_Adjust); end else begin MinWidthTitulo := 0; MinHeightTitulo := 0; Msg.Top := Titulo.Top; end; if Msg.Visible then begin Canvas.Font := Msg.Font; SetRect(TextRect, 0, 0, MSG_MAXWIDTH, 0); DrawText(Canvas.Handle, PChar(Msg.caption), Length(Msg.caption), TextRect, DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK); MinWidthMsg := textrect.right-textrect.left; MinHeightMsg := textrect.bottom-textrect.top; Msg.Height := MinHeightMsg; Inc(MinWidthMsg, WIDTH_Adjust); Msg.BringToFront; end else begin MinWidthMsg := 0; MinHeightMsg := 0; end; Width := Max(SCREEN_MinWidth, MinWidthTitulo); Width := Max(Width, MinWidthMsg); Height := Max(SCREEN_MinHeigth, MinHeightTitulo + MinHeightMsg + HEIGTH_Adjust); // define a Posicao dos botoes na tela WidthButton := 0; if Button1.Visible then Inc(WidthButton, Button1.Width); if Button2.Visible then Inc(WidthButton, Button2.Width + 3); if Button3.Visible then Inc(WidthButton, Button3.Width + 3); IniLeft := Round(Width/2) - Round(WidthButton/2); if Button3.Visible then begin Button3.Left := IniLeft; IniLeft := IniLeft + Button3.Width + 3; end; if Button2.Visible then begin Button2.Left := IniLeft; IniLeft := IniLeft + Button2.Width + 3; end; if Button1.Visible then Button1.Left := IniLeft; // Define a posicao que a janela aparecera Left := (Screen.Width div 2) - (Width div 2); Top := (Screen.Height div 2) - (Height div 2); // LIga o timer que pisca if (Icon = vbSuperCritical) then begin tmrBlink.Enabled := True; Self.Color := clRed; end else begin tmrBlink.Enabled := False; Self.Color := clBtnFace; end; ShowModal; // Desliga o timer que pisca tmrBlink.Enabled := False; Result := MyResult; end; procedure TFrmMsgBox.Button1Click(Sender: TObject); begin MyResult := TButton(Sender).Tag; Close; end; procedure TFrmMsgBox.tmrBlinkTimer(Sender: TObject); begin if Vez then begin Self.Color := clRed; end else begin Self.Color := clBtnFace; end; Vez := not Vez; end; end.
unit DesignController; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls, DesignHandles; type TDesignController = class(TComponent) private FActive: Boolean; FContainer: TWinControl; FHandles: TDesignHandles; FHintWin: THintWindow; FMouseIsDown: Boolean; FMouseOffset: TPoint; FMouseLast: TPoint; FFullDrag: Boolean; protected function FindControl(inX, inY: Integer): TControl; procedure ApplicationMessage(var Msg: tagMSG; var Handled: Boolean); procedure DragControl(X, Y: Integer); procedure DragOutline(X, Y: Integer); procedure MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetActive(const Value: Boolean); procedure SetContainer(const Value: TWinControl); procedure SetFullDrag(const Value: Boolean); procedure UpdateHint; public constructor Create(AOwner: TComponent); override; property Active: Boolean read FActive write SetActive; property Container: TWinControl read FContainer write SetContainer; property FullDrag: Boolean read FFullDrag write SetFullDrag; end; implementation type TControlCracker = class(TControl); procedure SimplifyMessage(var ioMsg: TMessage; inHandler: TWinControl); overload; var ctrlMsgProc: TWndMethod; begin TMethod(ctrlMsgProc).code := @TControlCracker.WndProc; TMethod(ctrlMsgProc).data := inHandler; ctrlMsgProc(ioMsg); end; procedure SimplifyMessage(var ioMsg: TMsg; inHandler: TWinControl); overload; var m: TMessage; begin m.Msg := ioMsg.message; m.WParam := ioMsg.wParam; m.LParam := ioMsg.lParam; SimplifyMessage(m, inHandler); end; function FindHandle(inHandle: HWND; inContainer: TWinControl): TWinControl; var i: Integer; begin Result := nil; with inContainer do if Handle = inHandle then Result := inContainer else for i := 0 to Pred(ControlCount) do if (inContainer.Controls[i] is TWinControl) then begin Result := FindHandle(inHandle, TWinControl(Controls[i])); if Result <> nil then break; end; end; { TDesignController } constructor TDesignController.Create(AOwner: TComponent); begin inherited; FHandles := TDesignHandles.Create(Self); FHintWin := HintWindowClass.Create(Self); FHintWin.Brush.Color := clInfoBk; end; procedure TDesignController.SetContainer(const Value: TWinControl); begin if FContainer <> nil then with TPanel(FContainer) do begin OnMouseDown := nil; OnMouseMove := nil; OnMouseUp := nil; end; FContainer := Value; FHandles.Container := Value; if FContainer <> nil then with TPanel(FContainer) do begin OnMouseDown := MouseDown; OnMouseMove := MouseMove; OnMouseUp := MouseUp; end; end; procedure TDesignController.SetActive(const Value: Boolean); begin FActive := Value; if FActive then Application.OnMessage := ApplicationMessage else Application.OnMessage := nil; end; procedure TDesignController.ApplicationMessage(var Msg: tagMSG; var Handled: Boolean); begin case Msg.message of WM_MOUSEFIRST..WM_MOUSELAST: begin if FindHandle(Msg.hwnd, Container) <> nil then begin Handled := true; with Container.ScreenToClient(Msg.pt) do msg.lParam := X + Y shl 16; SimplifyMessage(msg, Container); end; end; end; end; function TDesignController.FindControl(inX, inY: Integer): TControl; var c, c0: TControl; p: TPoint; begin p := Point(inX, inY); c := Container.ControlAtPos(p, true, true); while (c <> nil) and (c is TWinControl) do begin Dec(p.X, c.Left); Dec(p.Y, c.Top); c0 := TWinControl(c).ControlAtPos(p, true, true); if (c0 = nil) or (c0.Owner <> c.Owner) then break; c := c0; end; if c = Container then c := nil; Result := c; end; procedure TDesignController.MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FHandles.Selected := FindControl(X, Y); Container.Update; FMouseIsDown := FHandles.Selected <> nil; if FHandles.Selected <> nil then begin FMouseOffset := Point(X - FHandles.Selected.Left, Y - FHandles.Selected.Top); FHandles.Selected.Parent.DisableAlign; if not FullDrag then begin FMouseLast := FHandles.Selected.BoundsRect.topLeft; FHandles.PaintHandles(TCustomForm(Container.Parent).Canvas, FMouseLast); end; end; end; procedure TDesignController.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var l, t: Integer; begin if FMouseIsDown then begin l := X - FMouseOffset.X; l := l - (l and 3); t := Y - FMouseOffset.Y; t := t - (t and 3); if FullDrag then DragControl(l, t) else DragOutline(l, t); end; end; procedure TDesignController.DragControl(X, Y: Integer); var r: TRect; begin with FHandles.Selected do if (X <> Left) or (Y <> Top) then begin r := BoundsRect; BoundsRect := Rect(X, Y, X + Width, Y + Height); if not EqualRect(BoundsRect, r) then begin Parent.Update; UpdateHint; FHandles.UpdateHandles; Update; end; end; end; procedure TDesignController.DragOutline(X, Y: Integer); begin with FHandles.Selected do if (X <> Left) or (Y <> Top) then begin UpdateHint; FHandles.PaintHandles(TCustomForm(Container.Parent).Canvas, FMouseLast); FMouseLast := Point(X, Y); FHandles.PaintHandles(TCustomForm(Container.Parent).Canvas, FMouseLast); end; end; procedure TDesignController.UpdateHint; var h: string; begin with FHandles.Selected do begin h := Format('%d, %d', [ Left, Top ]); with Mouse.CursorPos, FHintWin.Canvas do FHintWin.ActivateHint( Rect(X + 12, Y + 20, X + TextWidth(h) + 20, Y + TextHeight(h) + 20), h); FHintWin.Update; end; end; procedure TDesignController.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FMouseIsDown := false; FHintWin.ReleaseHandle; if FHandles.Selected <> nil then begin if not FullDrag then begin FHandles.PaintHandles(TCustomForm(Container.Parent).Canvas, FMouseLast); with FHandles.Selected, FMouseLast do BoundsRect := Rect(X, Y, X + Width, Y + Height); end; FHandles.Selected.Parent.EnableAlign; FHandles.UpdateHandles; end; end; procedure TDesignController.SetFullDrag(const Value: Boolean); begin FFullDrag := Value; end; end.
unit uGraphicUtils; interface uses System.Math, System.Classes, System.SysUtils, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Forms, Vcl.Imaging.pngimage, Dmitry.Graphics.Types, Dmitry.Utils.Files, GIFImage, uRAWImage, uBitmapUtils, uJpegUtils, uPngUtils, uAnimatedJPEG, uSettings; procedure BeginScreenUpdate(Hwnd: THandle); procedure EndScreenUpdate(Hwnd: THandle; Erase: Boolean); function MixColors(Color1, Color2: TColor; Percent: Integer): TColor; function MakeDarken(BaseColor: TColor; Multiply: Extended): TColor; overload; function MakeDarken(Color: TColor): TColor; overload; function ColorDiv2(Color1, COlor2: TColor): TColor; function ColorDarken(Color: TColor): TColor; procedure AssignGraphic(Dest: TBitmap; Src: TGraphic); procedure AssignToGraphic(Dest: TGraphic; Src: TBitmap); procedure LoadImageX(Image: TGraphic; Bitmap: TBitmap; BackGround: TColor); procedure InitGraphic(G: TGraphic); function IsAnimatedGraphic(G: TGraphic): Boolean; function IsWallpaper(FileName: string): Boolean; function HasFont(Canvas: TCanvas; FontName: string): Boolean; implementation function IsWallpaper(FileName: string): Boolean; var Str: string; begin Str := AnsiUpperCase(ExtractFileExt(FileName)); Result := (Str = '.HTML') or (Str = '.HTM') or (Str = '.GIF') or (Str = '.JPG') or (Str = '.JPEG') or (Str = '.JPE') or (Str = '.BMP'); Result := Result and FileExistsSafe(FileName); end; procedure InitGraphic(G: TGraphic); begin if G is TAnimatedJPEG then begin if AppSettings.ReadString('Options', 'StereoMode', '') <> '' then TAnimatedJPEG(G).IsRedCyan := True; end; end; function IsAnimatedGraphic(G: TGraphic): Boolean; var IsAniGIF: Boolean; IsAniJpeg: Boolean; begin IsAniGIF := (G is TGifImage) and (TGifImage(G).Images.Count > 1); IsAniJpeg := (G is TAnimatedJPEG) and (AppSettings.ReadString('Options', 'StereoMode', '') = ''); Result := IsAniGIF or IsAniJpeg; end; procedure BeginScreenUpdate(hwnd: THandle); begin if (hwnd = 0) then hwnd := Application.MainForm.Handle; SendMessage(Hwnd, WM_SETREDRAW, 0, 0); end; procedure EndScreenUpdate(Hwnd: THandle; Erase: Boolean); begin if (Hwnd = 0) then Hwnd := Application.MainForm.Handle; SendMessage(Hwnd, WM_SETREDRAW, 1, 0); RedrawWindow(Hwnd, nil, 0, { DW_FRAME + } RDW_INVALIDATE + RDW_ALLCHILDREN + RDW_NOINTERNALPAINT); if (Erase) then InvalidateRect(Hwnd, nil, True); end; function ColorDiv2(Color1, COlor2: TColor): TColor; begin Color1 := ColorToRGB(Color1); Color2 := ColorToRGB(Color2); Result := RGB((GetRValue(Color1) + GetRValue(Color2)) div 2, (GetGValue(Color1) + GetGValue(Color2)) div 2, (GetBValue(Color1) + GetBValue(Color2)) div 2); end; function ColorDarken(Color: TColor): TColor; begin Color := ColorToRGB(Color); Result := RGB(Round(GetRValue(Color) / 1.2), (Round(GetGValue(Color) / 1.2)), (Round(GetBValue(Color) / 1.2))); end; function MakeDarken(BaseColor: TColor; Multiply: Extended) : TColor; var R, G, B : Byte; begin BaseColor := ColorToRGB(BaseColor); R := GetRValue(BaseColor); G := GetGValue(BaseColor); B := GetBValue(BaseColor); R := Byte(Min(255, Round(R * Multiply))); G := Byte(Min(255, Round(G * Multiply))); B := Byte(Min(255, Round(B * Multiply))); Result := RGB(R, G, B); end; function MakeDarken(Color: TColor): TColor; begin Color := ColorToRGB(Color); Result := RGB(Byte(Round(0.75 * GetRValue(Color))), Byte(Round(0.75 * GetGValue(Color))), Byte(Round(0.75 * GetBValue(Color)))); end; function MixColors(Color1, Color2: TColor; Percent: Integer): TColor; var R, G, B: Byte; P: Extended; begin Color1 := ColorToRGB(Color1); Color2 := ColorToRGB(Color2); P := (Percent / 100); R := Byte(Round(P * GetRValue(Color1) + (P - 1) * GetRValue(Color2))); G := Byte(Round(P * GetGValue(Color1) + (P - 1) * GetGValue(Color2))); B := Byte(Round(P * GetBValue(Color1) + (P - 1) * GetBValue(Color2))); Result := RGB(R, G, B); end; procedure LoadGIFImage32bit(GIF : TGIFSubImage; Bitmap : TBitmap; BackGroundColorIndex : integer; BackGroundColor : TColor); var I, J: Integer; P: PARGB; R, G, B: Byte; begin BackGroundColor := ColorToRGB(BackGroundColor); R := GetRValue(BackGroundColor); G := GetGValue(BackGroundColor); B := GetBValue(BackGroundColor); Bitmap.PixelFormat := pf24bit; for I := 0 to GIF.Top - 1 do begin P := Bitmap.ScanLine[I]; for J := 0 to Bitmap.Width - 1 do begin P[J].R := R; P[J].G := G; P[J].B := B; end; end; for I := GIF.Top + GIF.Height to Bitmap.Height - 1 do begin P := Bitmap.ScanLine[I]; for J := 0 to Bitmap.Width - 1 do begin P[J].R := R; P[J].G := G; P[J].B := B; end; end; for I := GIF.Top to GIF.Top + GIF.Height - 1 do begin P := Bitmap.ScanLine[I]; for J := 0 to GIF.Left - 1 do begin P[J].R := R; P[J].G := G; P[J].B := B; end; end; for I := GIF.Top to GIF.Top + GIF.Height - 1 do begin P := Bitmap.ScanLine[I]; for J := GIF.Left + GIF.Width - 1 to Bitmap.Width - 2 do begin P[J].R := R; P[J].G := G; P[J].B := B; end; end; for I := 0 to GIF.Height - 1 do begin P := Bitmap.ScanLine[I + GIF.Top]; for J := 0 to GIF.Width - 1 do begin if GIF.Pixels[J, I] = BackGroundColorIndex then begin P[J + GIF.Left].R := R; P[J + GIF.Left].G := G; P[J + GIF.Left].B := B; end; end; end; end; procedure AssignGraphic(Dest: TBitmap; Src: TGraphic); begin if ((Src is TBitmap) and (TBitmap(Src).PixelFormat = pf32Bit)) or ((Src is TPngImage) and (TPngImage(Src).TransparencyMode <> ptmNone)) then Dest.PixelFormat := pf32Bit else Dest.PixelFormat := pf24Bit; if Src is TJpegImage then AssignJpeg(Dest, TJpegImage(Src)) else if Src is TRAWImage then Dest.Assign(TRAWImage(Src)) else if Src is TBitmap then AssignBitmap(Dest, TBitmap(Src)) else if Src is TPngImage then begin AssignPNG(Dest, TPngImage(Src)); end else Dest.Assign(Src); end; procedure AssignToGraphic(Dest: TGraphic; Src: TBitmap); begin if (Dest is TPngImage) and (Src.PixelFormat = pf32Bit) then begin SavePNGImageTransparent(TPngImage(Dest), Src); end else Dest.Assign(Src); end; procedure LoadImageX(Image: TGraphic; Bitmap: TBitmap; BackGround: TColor); begin if Image is TGIFImage then begin if not(Image as TGIFImage).Images[0].Empty then if (Image as TGIFImage).Images[0].Transparent then begin Bitmap.Assign(Image); if (Image as TGIFImage).Images[0].GraphicControlExtension <> nil then LoadGIFImage32bit((Image as TGIFImage).Images[0], Bitmap, (Image as TGIFImage).Images[0].GraphicControlExtension.TransparentColorIndex, BackGround); Exit; end; end; AssignGraphic(Bitmap, Image); end; function HasFont(Canvas: TCanvas; FontName: string): Boolean; var OldName: string; Metrics: TTextMetric; begin Result := False; OldName := Canvas.Font.Name; try Canvas.Font.Name := FontName; if GetTextMetrics(Canvas.Handle, Metrics) then Result := Metrics.tmHeight >= 8; finally Canvas.Font.Name := OldName; end; end; end.
unit ProxyUnit; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Spin, WinInet, IniFiles, UrlMon; type TProxySettings = class(TForm) OKBtn: TButton; CancelBtn: TButton; Proxy: TGroupBox; UseProxy: TCheckBox; ProxyServer: TLabeledEdit; Label1: TLabel; ProxyPort: TSpinEdit; Login: TLabeledEdit; Password: TLabeledEdit; procedure UseProxyClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure ReadSettings; procedure WriteSettings; procedure ApplySettings; end; var ProxySettings: TProxySettings; implementation {$R *.dfm} const SProxy='Proxy'; SLogin='Login'; SPassword='Password'; SPort='Port'; SServer='Server'; SUse='Use'; procedure TProxySettings.UseProxyClick(Sender: TObject); begin Proxy.Enabled:=UseProxy.Checked end; procedure TProxySettings.WriteSettings; begin with TIniFile.Create(ExpandFileName('settings.ini')) do try WriteBool(SProxy,SUse,UseProxy.Checked); WriteString(SProxy,SLogin,Login.Text); WriteString(SProxy,SPassword,Password.Text); WriteString(SProxy,SServer,ProxyServer.Text); WriteInteger(SProxy,SPort,ProxyPort.Value); finally Free end; end; procedure TProxySettings.ReadSettings; begin with TIniFile.Create(ExpandFileName('settings.ini')) do try UseProxy.Checked:=ReadBool(SProxy,SUse,False); Proxy.Enabled:=UseProxy.Checked; Login.Text:=ReadString(SProxy,SLogin,''); Password.Text:=ReadString(SProxy,SPassword,''); ProxyServer.Text:=ReadString(SProxy,SServer,''); ProxyPort.Value:=ReadInteger(SProxy,SPort,0); finally Free end; end; procedure TProxySettings.ApplySettings; var PIInfo: PInternetProxyInfo; begin New(PIInfo); with PIInfo^ do if UseProxy.Checked then begin dwAccessType := INTERNET_OPEN_TYPE_PROXY; lpszProxy := PChar(ProxyServer.Text+':'+ProxyPort.Text); lpszProxyBypass := ''; UrlMkSetSessionOption(INTERNET_OPTION_PROXY_USERNAME, PChar(Login.Text), Length(Login.Text)+1, 0); UrlMkSetSessionOption(INTERNET_OPTION_PROXY_PASSWORD, PChar(Password.Text), Length(Password.Text)+1, 0); end else dwAccessType := INTERNET_OPEN_TYPE_DIRECT; UrlMkSetSessionOption(INTERNET_OPTION_PROXY, PIInfo, SizeOf(PIInfo^), 0); Dispose(PIInfo); end; procedure TProxySettings.FormShow(Sender: TObject); begin ReadSettings end; procedure TProxySettings.OKBtnClick(Sender: TObject); begin WriteSettings; ApplySettings end; procedure TProxySettings.FormCreate(Sender: TObject); begin ReadSettings; ApplySettings end; end.
// // Generated by JavaToPas v1.4 20140515 - 182218 //////////////////////////////////////////////////////////////////////////////// unit android.test.ActivityUnitTestCase; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.app.Activity, android.content.Intent, Androidapi.JNI.os, android.app.Application, Androidapi.JNI.GraphicsContentViewText; type JActivityUnitTestCase = interface; JActivityUnitTestCaseClass = interface(JObjectClass) ['{7833F279-1681-46B5-BBEB-B1C49145B5CC}'] function getActivity : JActivity; cdecl; // ()Landroid/app/Activity; A: $1 function getFinishedActivityRequest : Integer; cdecl; // ()I A: $1 function getRequestedOrientation : Integer; cdecl; // ()I A: $1 function getStartedActivityIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1 function getStartedActivityRequest : Integer; cdecl; // ()I A: $1 function init(activityClass : JClass) : JActivityUnitTestCase; cdecl; // (Ljava/lang/Class;)V A: $1 function isFinishCalled : boolean; cdecl; // ()Z A: $1 procedure setActivityContext(activityContext : JContext) ; cdecl; // (Landroid/content/Context;)V A: $1 procedure setApplication(application : JApplication) ; cdecl; // (Landroid/app/Application;)V A: $1 end; [JavaSignature('android/test/ActivityUnitTestCase')] JActivityUnitTestCase = interface(JObject) ['{8B364EA9-C584-4522-B66C-849B2A5CE6FC}'] function getActivity : JActivity; cdecl; // ()Landroid/app/Activity; A: $1 function getFinishedActivityRequest : Integer; cdecl; // ()I A: $1 function getRequestedOrientation : Integer; cdecl; // ()I A: $1 function getStartedActivityIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1 function getStartedActivityRequest : Integer; cdecl; // ()I A: $1 function isFinishCalled : boolean; cdecl; // ()Z A: $1 procedure setActivityContext(activityContext : JContext) ; cdecl; // (Landroid/content/Context;)V A: $1 procedure setApplication(application : JApplication) ; cdecl; // (Landroid/app/Application;)V A: $1 end; TJActivityUnitTestCase = class(TJavaGenericImport<JActivityUnitTestCaseClass, JActivityUnitTestCase>) end; implementation end.
// // Generated by JavaToPas v1.5 20150831 - 132251 //////////////////////////////////////////////////////////////////////////////// unit javax.net.ssl.SSLEngine; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, javax.net.ssl.SSLEngineResult_HandshakeStatus, javax.net.ssl.SSLSession, javax.net.ssl.SSLEngineResult, java.nio.ByteBuffer, javax.net.ssl.SSLParameters; type JSSLEngine = interface; JSSLEngineClass = interface(JObjectClass) ['{0045BB6C-7660-41F1-959D-FAE23ECCD6FB}'] function getDelegatedTask : JRunnable; cdecl; // ()Ljava/lang/Runnable; A: $401 function getEnableSessionCreation : boolean; cdecl; // ()Z A: $401 function getEnabledCipherSuites : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getEnabledProtocols : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getHandshakeStatus : JSSLEngineResult_HandshakeStatus; cdecl; // ()Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $401 function getNeedClientAuth : boolean; cdecl; // ()Z A: $401 function getPeerHost : JString; cdecl; // ()Ljava/lang/String; A: $1 function getPeerPort : Integer; cdecl; // ()I A: $1 function getSSLParameters : JSSLParameters; cdecl; // ()Ljavax/net/ssl/SSLParameters; A: $1 function getSession : JSSLSession; cdecl; // ()Ljavax/net/ssl/SSLSession; A: $401 function getSupportedCipherSuites : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getSupportedProtocols : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getUseClientMode : boolean; cdecl; // ()Z A: $401 function getWantClientAuth : boolean; cdecl; // ()Z A: $401 function isInboundDone : boolean; cdecl; // ()Z A: $401 function isOutboundDone : boolean; cdecl; // ()Z A: $401 function unwrap(JByteBufferparam0 : JByteBuffer; TJavaArrayJByteBufferparam1 : TJavaArray<JByteBuffer>; Integerparam2 : Integer; Integerparam3 : Integer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;II)Ljavax/net/ssl/SSLEngineResult; A: $401 function unwrap(src : JByteBuffer; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function unwrap(src : JByteBuffer; dsts : TJavaArray<JByteBuffer>) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function wrap(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer; JByteBufferparam3 : JByteBuffer) : JSSLEngineResult; cdecl; overload;// ([Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $401 function wrap(src : JByteBuffer; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function wrap(srcs : TJavaArray<JByteBuffer>; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// ([Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 procedure beginHandshake ; cdecl; // ()V A: $401 procedure closeInbound ; cdecl; // ()V A: $401 procedure closeOutbound ; cdecl; // ()V A: $401 procedure setEnableSessionCreation(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setEnabledCipherSuites(TJavaArrayJStringparam0 : TJavaArray<JString>) ; cdecl;// ([Ljava/lang/String;)V A: $401 procedure setEnabledProtocols(TJavaArrayJStringparam0 : TJavaArray<JString>) ; cdecl;// ([Ljava/lang/String;)V A: $401 procedure setNeedClientAuth(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setSSLParameters(p : JSSLParameters) ; cdecl; // (Ljavax/net/ssl/SSLParameters;)V A: $1 procedure setUseClientMode(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setWantClientAuth(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 end; [JavaSignature('javax/net/ssl/SSLEngine')] JSSLEngine = interface(JObject) ['{DE6FCEEC-7D78-41A2-86D5-BFD718C4DCFE}'] function getDelegatedTask : JRunnable; cdecl; // ()Ljava/lang/Runnable; A: $401 function getEnableSessionCreation : boolean; cdecl; // ()Z A: $401 function getEnabledCipherSuites : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getEnabledProtocols : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getHandshakeStatus : JSSLEngineResult_HandshakeStatus; cdecl; // ()Ljavax/net/ssl/SSLEngineResult$HandshakeStatus; A: $401 function getNeedClientAuth : boolean; cdecl; // ()Z A: $401 function getPeerHost : JString; cdecl; // ()Ljava/lang/String; A: $1 function getPeerPort : Integer; cdecl; // ()I A: $1 function getSSLParameters : JSSLParameters; cdecl; // ()Ljavax/net/ssl/SSLParameters; A: $1 function getSession : JSSLSession; cdecl; // ()Ljavax/net/ssl/SSLSession; A: $401 function getSupportedCipherSuites : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getSupportedProtocols : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $401 function getUseClientMode : boolean; cdecl; // ()Z A: $401 function getWantClientAuth : boolean; cdecl; // ()Z A: $401 function isInboundDone : boolean; cdecl; // ()Z A: $401 function isOutboundDone : boolean; cdecl; // ()Z A: $401 function unwrap(JByteBufferparam0 : JByteBuffer; TJavaArrayJByteBufferparam1 : TJavaArray<JByteBuffer>; Integerparam2 : Integer; Integerparam3 : Integer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;II)Ljavax/net/ssl/SSLEngineResult; A: $401 function unwrap(src : JByteBuffer; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function unwrap(src : JByteBuffer; dsts : TJavaArray<JByteBuffer>) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function wrap(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer; JByteBufferparam3 : JByteBuffer) : JSSLEngineResult; cdecl; overload;// ([Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $401 function wrap(src : JByteBuffer; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 function wrap(srcs : TJavaArray<JByteBuffer>; dst : JByteBuffer) : JSSLEngineResult; cdecl; overload;// ([Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljavax/net/ssl/SSLEngineResult; A: $1 procedure beginHandshake ; cdecl; // ()V A: $401 procedure closeInbound ; cdecl; // ()V A: $401 procedure closeOutbound ; cdecl; // ()V A: $401 procedure setEnableSessionCreation(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setEnabledCipherSuites(TJavaArrayJStringparam0 : TJavaArray<JString>) ; cdecl;// ([Ljava/lang/String;)V A: $401 procedure setEnabledProtocols(TJavaArrayJStringparam0 : TJavaArray<JString>) ; cdecl;// ([Ljava/lang/String;)V A: $401 procedure setNeedClientAuth(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setSSLParameters(p : JSSLParameters) ; cdecl; // (Ljavax/net/ssl/SSLParameters;)V A: $1 procedure setUseClientMode(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure setWantClientAuth(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 end; TJSSLEngine = class(TJavaGenericImport<JSSLEngineClass, JSSLEngine>) end; implementation end.
unit uCompany; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uTSBaseClass; type TCompany = class(TSBaseClass) private FID: Integer; FKode: string; FNama: string; function FLoadFromDB( aSQL : String ): Boolean; public constructor Create(aOwner : TComponent); override; destructor Destroy; override; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function ExecuteGenerateSQL: Boolean; procedure GetCurCompany(var Code: string; var Nm: TEdit); function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_Kode: string; dynamic; function GetFieldNameFor_Nama: string; dynamic; function GetGeneratorName: string; function GetHeaderFlag: Integer; function LoadByID( aID : Integer ): Boolean; function LoadByKode(aKode : String): Boolean; procedure UpdateData(aID : Integer; aKode : string; aNama : string); property ID: Integer read FID write FID; property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; end; implementation { *********************************** TCompany *********************************** } constructor TCompany.Create(aOwner : TComponent); begin inherited create(aOwner); end; destructor TCompany.Destroy; begin inherited Destroy; end; procedure TCompany.ClearProperties; begin ID := 0; Kode := ''; Nama := ''; end; function TCompany.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TCompany.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TCompany.CustomTableName: string; begin result := 'COMPANY'; end; function TCompany.FLoadFromDB( aSQL : String ): Boolean; begin result := false; State := csNone; ClearProperties; // with cOpenQuery(aSQL) do // Begin // if not EOF then // begin // FID := FieldByName(GetFieldNameFor_ID).asInteger; // FKode := FieldByName(GetFieldNameFor_Kode).asString; // FNama := FieldByName(GetFieldNameFor_Nama).asString; // Self.State := csLoaded; // Result := True; // end; // Free; // end; end; function TCompany.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; // ini tdk perlu result.Append( '' ); result.Append( 'Create Table TCompany ( ' ); result.Append( 'TSBaseClass_ID Integer not null, ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Kode Varchar(30) Not Null Unique, ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TCompany.ExecuteGenerateSQL: Boolean; var S: string; begin result := False; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; if not ExecuteCustomSQLTaskPrior then Begin // cRollbackTrans; Exit; end else begin // if FID <= 0 then // begin // FID := cGetNextID(GetGeneratorName) ; // S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ') values (' // + IntToStr( FID) + ', ' // + Quot(FKode ) + ',' // + Quot(FNama ) + ');' // end else // begin // S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Kode + ' = ' + Quot(FKode) // + ' , ' + GetFieldNameFor_Nama + ' = ' + Quot( FNama ) // + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; // end; // // if not cExecSQL(S, False , GetHeaderFlag) then // begin // cRollbackTrans; // Exit; // end else if not SimpanBlob(S,GetHeaderFlag) then // begin // cRollbackTrans; // Exit; // end else begin // Result := ExecuteCustomSQLTask; // end; end; end; procedure TCompany.GetCurCompany(var Code: string; var Nm: TEdit); var sSQL : string; begin sSQL := 'SELECT '+ GetFieldNameFor_ID +' AS CODE,' + GetFieldNameFor_Nama +' AS NAME' + ' FROM COMPANY'; // GetdataIdNm('Company', sSQL, Code, Nm); end; function TCompany.GetFieldNameFor_ID: string; begin Result := 'COMP_ID';// <<-- Rubah string ini untuk mapping end; function TCompany.GetFieldNameFor_Kode: string; begin Result := 'COMP_CODE';// <<-- Rubah string ini untuk mapping end; function TCompany.GetFieldNameFor_Nama: string; begin Result := 'COMP_NAME';// <<-- Rubah string ini untuk mapping end; function TCompany.GetGeneratorName: string; begin Result := 'GEN_COMPANY_ID'; end; function TCompany.GetHeaderFlag: Integer; begin result := 497; end; function TCompany.LoadByID( aID : Integer ): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID) ); end; function TCompany.LoadByKode(aKode : String): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode)); end; procedure TCompany.UpdateData(aID : Integer; aKode : string; aNama : string); begin FID := aID; FKode := trim(aKode); FNama := trim(aNama); State := csCreated; end; end.
unit MainUnit; //*************************************************************************************** // XMVector Sample by Frank Luna (C) 2015 All Rights Reserved. //*************************************************************************************** // Pascal Translation by Sonnleitner Norbert (C) 2018 // Coding DirectX is fun, Coding Pascal is more fun, Coding DirectX with Pascal is the best //*************************************************************************************** {$mode delphi}{$H+} interface uses Windows, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, DirectX.Math; type { TForm1 } TForm1 = class(TForm) btnInitFunctions: TButton; btnTolerance: TButton; btnXMVec3: TButton; btnVectorOops: TButton; Memo1: TMemo; procedure btnInitFunctionsClick(Sender: TObject); procedure btnToleranceClick(Sender: TObject); procedure btnVectorOopsClick(Sender: TObject); procedure btnXMVec3Click(Sender: TObject); private public end; var Form1: TForm1; implementation uses Math; {$R *.lfm} function DebugXMVectorFloat(constref v: TXMVector): ansistring; begin Result := 'X: ' + formatfloat('0.000000000E+00', V.f32[0]) + ', Y: ' + formatfloat('0.000000000E+00', V.f32[1]) + ', Z: ' + formatfloat('0.000000000E+00', V.f32[2]) + ', W: ' + formatfloat('0.000000000E+00', V.f32[3]); end; function DebugXMVectorIntHex(constref v: TXMVector): ansistring; begin Result := 'X: ' + IntToHex(V.u32[0], 8) + ', Y: ' + IntToHex(V.u32[1], 8) + ', Z: ' + IntToHex(V.u32[2], 8) + ', W: ' + IntToHex(V.u32[3], 8); end; function DebugXMVectorInt(constref v: TXMVector): ansistring; begin Result := 'X: ' + formatfloat('0.000000000E+00', V.u32[0]) + ', Y: ' + formatfloat('0.000000000E+00', V.u32[1]) + ', Z: ' + formatfloat('0.000000000E+00', V.u32[2]) + ', W: ' + formatfloat('0.000000000E+00', V.u32[3]); end; { TForm1 } procedure TForm1.btnInitFunctionsClick(Sender: TObject); var p, q, u, v, w: TXMVECTOR; begin Memo1.Clear; p := XMVectorZero(); q := XMVectorSplatOne(); u := XMVectorSet(1.0, 2.0, 3.0, 0.0); v := XMVectorReplicate(-2.0); w := XMVectorSplatZ(u); Memo1.Lines.Add('p := XMVectorZero();'); Memo1.Lines.Add('p: ' + DebugXMVectorFloat(p)); Memo1.Lines.Add(''); Memo1.Lines.Add('q := XMVectorSplatOne();'); Memo1.Lines.Add('q: ' + DebugXMVectorFloat(q)); Memo1.Lines.Add(''); Memo1.Lines.Add('u := XMVectorSet(1.0, 2.0, 3.0, 0.0);'); Memo1.Lines.Add('u: ' + DebugXMVectorFloat(u)); Memo1.Lines.Add(''); Memo1.Lines.Add('v := XMVectorReplicate(-2.0);'); Memo1.Lines.Add('v: ' + DebugXMVectorFloat(v)); Memo1.Lines.Add(''); Memo1.Lines.Add('w := XMVectorSplatZ(u);'); Memo1.Lines.Add('w: ' + DebugXMVectorFloat(w)); end; procedure TForm1.btnToleranceClick(Sender: TObject); var u, n: TXMVECTOR; LU, powLU: single; begin Memo1.Clear; u := XMVectorSet(1.0, 1.0, 1.0, 0.0); n := XMVector3Normalize(u); LU := XMVectorGetX(XMVector3Length(n)); // Mathematically, the length should be 1. Is it numerically? Memo1.Lines.Add('LU: ' + formatfloat('0.000000000E+00', LU)); if (LU = 1.0) then Memo1.Lines.Add('Length 1') else Memo1.Lines.Add('Length not 1'); Memo1.Lines.Add(''); // Raising 1 to any power should still be 1. Is it? powLU := power(LU, 1.0e6); Memo1.Lines.Add('LU^(10^6): ' + formatfloat('0.000000000E+00', powLU)); end; procedure TForm1.btnVectorOopsClick(Sender: TObject); var p, q, u, v, w: TXMVECTOR; begin Memo1.Clear; p := XMVectorSet(2.0, 2.0, 1.0, 0.0); q := XMVectorSet(2.0, -0.5, 0.5, 0.1); u := XMVectorSet(1.0, 2.0, 4.0, 8.0); v := XMVectorSet(-2.0, 1.0, -3.0, 2.5); w := XMVectorSet(0.0, XM_PIDIV4, XM_PIDIV2, XM_PI); Memo1.Lines.Add('XMVectorAbs(v) = ' + DebugXMVectorFloat(XMVectorAbs(v))); Memo1.Lines.Add('XMVectorCos(w) = ' + DebugXMVectorFloat(XMVectorCos(w))); Memo1.Lines.Add('XMVectorLog(u) = ' + DebugXMVectorFloat(XMVectorLog(u))); Memo1.Lines.Add('XMVectorExp(p) = ' + DebugXMVectorFloat(XMVectorExp(p))); Memo1.Lines.Add('XMVectorPow(u, p) = ' + DebugXMVectorFloat(XMVectorPow(u, p))); Memo1.Lines.Add('XMVectorSqrt(u) = ' + DebugXMVectorFloat(XMVectorSqrt(u))); Memo1.Lines.Add('XMVectorSwizzle(u, 2, 2, 1, 3) = ' + DebugXMVectorFloat(XMVectorSwizzle(u, 2, 2, 1, 3))); Memo1.Lines.Add('XMVectorSwizzle(u, 2, 1, 0, 3) = ' + DebugXMVectorFloat(XMVectorSwizzle(u, 2, 1, 0, 3))); Memo1.Lines.Add('XMVectorMultiply(u, v) = ' + DebugXMVectorFloat(XMVectorMultiply(u, v))); Memo1.Lines.Add('XMVectorSaturate(q) = ' + DebugXMVectorFloat(XMVectorSaturate(q))); Memo1.Lines.Add('XMVectorMin(p, v = ' + DebugXMVectorFloat(XMVectorMin(p, v))); Memo1.Lines.Add('XMVectorMax(p, v) = ' + DebugXMVectorFloat(XMVectorMax(p, v))); end; procedure TForm1.btnXMVec3Click(Sender: TObject); var n, u, v, w, a, b, c, L, d, s, e: TXMVECTOR; projW, perpW: TXMVECTOR; equal, notEqual: boolean; angleVec: TXMVECTOR; angleRadians, angleDegrees: single; begin Memo1.Clear; n := XMVectorSet(1.0, 0.0, 0.0, 0.0); u := XMVectorSet(1.0, 2.0, 3.0, 0.0); v := XMVectorSet(-2.0, 1.0, -3.0, 0.0); w := XMVectorSet(0.707, 0.707, 0.0, 0.0); // Vector addition: XMVECTOR operator + a := u + v; // Vector subtraction: XMVECTOR operator - b := u - v; // Scalar multiplication: XMVECTOR operator * c := u * 10; // ||u|| L := XMVector3Length(u); // d = u / ||u|| d := XMVector3Normalize(u); // s = u dot v s := XMVector3Dot(u, v); // e = u x v e := XMVector3Cross(u, v); // Find proj_n(w) and perp_n(w) XMVector3ComponentsFromNormal(projW, perpW, w, n); // Does projW + perpW == w? equal := XMVector3Equal(projW + perpW, w); notEqual := XMVector3NotEqual(projW + perpW, w); // The angle between projW and perpW should be 90 degrees. angleVec := XMVector3AngleBetweenVectors(projW, perpW); angleRadians := XMVectorGetX(angleVec); angleDegrees := XMConvertToDegrees(angleRadians); Memo1.Lines.Add('u = ' + DebugXMVectorFloat(u)); Memo1.Lines.Add('v = ' + DebugXMVectorFloat(v)); Memo1.Lines.Add('w = ' + DebugXMVectorFloat(w)); Memo1.Lines.Add('n = ' + DebugXMVectorFloat(n)); Memo1.Lines.Add('a = u + v = ' + DebugXMVectorFloat(a)); Memo1.Lines.Add('b = u - v = ' + DebugXMVectorFloat(b)); Memo1.Lines.Add('c = 10 * u = ' + DebugXMVectorFloat(c)); Memo1.Lines.Add('d = u / ||u|| = ' + DebugXMVectorFloat(d)); Memo1.Lines.Add('e = u x v = ' + DebugXMVectorFloat(e)); Memo1.Lines.Add('L = ||u|| = ' + DebugXMVectorFloat(L)); Memo1.Lines.Add('s = u.v = ' + DebugXMVectorFloat(s)); Memo1.Lines.Add('projW = ' + DebugXMVectorFloat(projW)); Memo1.Lines.Add('perpW = ' + DebugXMVectorFloat(perpW)); Memo1.Lines.Add('projW + perpW == w = ' + BoolToStr(equal, True)); Memo1.Lines.Add('projW + perpW != w = ' + BoolToStr(notEqual, True)); Memo1.Lines.Add('angle = ' + formatfloat('0.000000000E+00', angleDegrees)); end; end.
unit sgDriver; //============================================================================= // sgDriver.pas //============================================================================= // // The Driver is responsible for acting as the interface between driver // code and swingame code. Swingame code uses the Driver to access the // current active driver. // // Changing this driver will probably cause graphics drivers to break. // // Notes: // - Pascal PChar is equivalent to a C-type string // - Pascal Word is equivalent to a Uint16 // - Pascal LongWord is equivalent to a Uint32 // - Pascal SmallInt is equivalent to Sint16 // //============================================================================= interface uses sgTypes; type GetErrorProcedure = function () : PChar; QuitProcedure = procedure(); InitProcedure = procedure(); GetKeyCodeProcedure = function(val : LongInt) : LongInt; DriverRecord = record GetError : GetErrorProcedure; Quit : QuitProcedure; Init : InitProcedure; GetKeyCode : GetKeyCodeProcedure; end; var Driver : DriverRecord = ( GetError: nil; Quit: nil; Init: nil ; GetKeyCode: nil); procedure LoadDefaultDriver(); implementation uses sgDriverSDL2; procedure LoadDefaultDriver(); begin LoadSDL2Driver(); end; procedure DefaultInitProcedure(); begin // WriteLn('Default Init'); LoadDefaultDriver(); Driver.Init(); end; function DefaultGetErrorProcedure () : PChar; begin LoadDefaultDriver(); result := Driver.GetError(); end; function DefaultGetKeyCodeProcedure (val : LongInt) : LongInt; begin LoadDefaultDriver(); result := Driver.GetKeyCode(val); end; procedure DefaultQuitProcedure(); begin LoadDefaultDriver(); Driver.Quit(); end; initialization if not Assigned(Driver.Init) then begin // WriteLn('Loading driver'); Driver.GetError := @DefaultGetErrorProcedure; Driver.Quit := @DefaultQuitProcedure; Driver.GetKeyCode := @DefaultGetKeyCodeProcedure; Driver.Init := @DefaultInitProcedure; end; end.
unit Odontologia.Modelo.Entidades.Usuario; interface uses SimpleAttributes; type [Tabela('DUSUARIO')] TDUSUARIO = class private FUSU_CODIGO: Integer; FUSU_LOGIN: String; FUSU_NIVEL: Integer; FUSU_CLAVE: String; FUSU_FOTO: String; FUSU_COD_EMPRESA: Integer; FUSU_COD_ESTADO: Integer; procedure SetUSU_CLAVE(const Value: String); procedure SetUSU_COD_EMPRESA(const Value: Integer); procedure SetUSU_COD_ESTADO(const Value: Integer); procedure SetUSU_CODIGO(const Value: Integer); procedure SetUSU_FOTO(const Value: String); procedure SetUSU_LOGIN(const Value: String); procedure SetUSU_NIVEL(const Value: Integer); published [Campo('USU_CODIGO'), Pk, AutoInc] property USU_CODIGO: Integer read FUSU_CODIGO write SetUSU_CODIGO; [Campo('USU_LOGIN')] property USU_LOGIN: String read FUSU_LOGIN write SetUSU_LOGIN; [Campo('USU_NIVEL')] property USU_NIVEL: Integer read FUSU_NIVEL write SetUSU_NIVEL; [Campo('USU_CLAVE')] property USU_CLAVE: String read FUSU_CLAVE write SetUSU_CLAVE; [Campo('USU_FOTO')] property USU_FOTO: String read FUSU_FOTO write SetUSU_FOTO; [Campo('USU_COD_EMPRESA')] property USU_COD_EMPRESA: Integer read FUSU_COD_EMPRESA write SetUSU_COD_EMPRESA; [Campo('USU_COD_ESTADO')] property USU_COD_ESTADO: Integer read FUSU_COD_ESTADO write SetUSU_COD_ESTADO; end; implementation { TDUSUARIO } procedure TDUSUARIO.SetUSU_CLAVE(const Value: String); begin FUSU_CLAVE := Value; end; procedure TDUSUARIO.SetUSU_CODIGO(const Value: Integer); begin FUSU_CODIGO := Value; end; procedure TDUSUARIO.SetUSU_COD_EMPRESA(const Value: Integer); begin FUSU_COD_EMPRESA := Value; end; procedure TDUSUARIO.SetUSU_COD_ESTADO(const Value: Integer); begin FUSU_COD_ESTADO := Value; end; procedure TDUSUARIO.SetUSU_FOTO(const Value: String); begin FUSU_FOTO := Value; end; procedure TDUSUARIO.SetUSU_LOGIN(const Value: String); begin FUSU_LOGIN := Value; end; procedure TDUSUARIO.SetUSU_NIVEL(const Value: Integer); begin FUSU_NIVEL := Value; end; end.
unit SQLiteClientDataSet; interface uses SysUtils, Classes, DB, DBClient, SQLiteDataSetProvider, SQLite3; type {$IFDEF VER180} PByte = PAnsiChar; {$ENDIF} PRecordNode = ^TRecordNode; TRecordNode = record Id: Int64; BdId: Integer; Next: PRecordNode; Prior: PRecordNode; end; PRecordBuffer = ^TRecordBuffer; TRecordBuffer = record Node: PRecordNode; BookFlag: TBookmarkFlag; end; TSQLiteClientDataSet = class(TWideDataSet) private FDataSetProvider: TSQLiteDataSetProvider; FBeforeGetRecords: TRemoteEvent; FAfterGetRecords: TRemoteEvent; FParams: TParams; FIndexFieldNames: String; FSelectAllStmt: TSQLiteStmt; FSelectOneStmt: TSQLiteStmt; FLocateStmt: TSQLiteStmt; FRootRow: PRecordNode; FLastRow: PRecordNode; FCurrentRec: PRecordNode; FCurrentOpenRec: PRecordNode; FRecordCount: Integer; FCursorOpen: Boolean; FRecordSize: Word; FActualRecordId: Integer; FDataSetToSQLiteBind: PDataSetToSQLiteBind; FMasterLink: TMasterDataLink; FLocalDataSetToSQLiteBind: TDataSetToSQLiteBind; PDataSetRec: PInsertSQLiteRec; FLastBindedFieldData: array of Variant; FLastLocateFields: TStrings; FLastLocateFieldsStr: String; FMaxRecordId: Integer; function GetDataSetProvider: TSQLiteDataSetProvider; procedure SetDataSetProvider(const Value: TSQLiteDataSetProvider); procedure DoAfterGetRecords(var OwnerData: OleVariant); procedure DoBeforeGetRecords(var OwnerData: OleVariant); function DoGetRecords(Count: Integer; out RecsOut: Integer): OleVariant; procedure SetParams(const Value: TParams); procedure SetIndexFieldNames(const Value: String); function GetSelectOrderBy: String; function GetWhereClause: String; function Navigate(GetMode: TGetMode): TGetResult; procedure MasterChanged(Sender: TObject); procedure MasterDisabled(Sender: TObject); protected procedure DataEvent(Event: TDataEvent; Info: Integer); override; function AllocRecordBuffer: PByte; override; procedure FreeRecordBuffer(var Buffer: PByte); override; procedure GetBookmarkData(Buffer: PByte; Data: Pointer); override; function GetBookmarkFlag(Buffer: PByte): TBookmarkFlag; override; function GetRecord(Buffer: PByte; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; function GetRecordSize: Word; override; procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalFirst; override; procedure InternalGotoBookmark(Bookmark: Pointer); override; procedure InternalHandleException; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer: PByte); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer: PByte); override; function IsCursorOpen: Boolean; override; procedure SetBookmarkData(Buffer: PByte; Data: Pointer); override; procedure SetBookmarkFlag(Buffer: PByte; Value: TBookmarkFlag); override; procedure SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); override; procedure BuildRowIdIndex; procedure SetParamsFromMaster(stmt: TSQLiteStmt; Master: TDataSet); function GetRecordCount: Integer; override; function OpenCurrentRecord: Boolean; function GetRecNo: Integer; override; function GetSQLiteTableName: String; procedure SetDataSetField(const Value: TDataSetField); override; procedure CreateDataSetFromFields; procedure InternalInsert; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; function Locate(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean; override; procedure CreateDataSet; published property IndexFieldNames: String read FIndexFieldNames write SetIndexFieldNames; property Params: TParams read FParams write SetParams; property DataSetProvider: TSQLiteDataSetProvider read GetDataSetProvider write SetDataSetProvider; property DataSetField; property BeforeGetRecords: TRemoteEvent read FBeforeGetRecords write FBeforeGetRecords; property AfterGetRecords: TRemoteEvent read FAfterGetRecords write FAfterGetRecords; property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeInsert; property AfterInsert; property BeforeEdit; property AfterEdit; property BeforePost; property AfterPost; property BeforeCancel; property AfterCancel; property BeforeDelete; property AfterDelete; property BeforeScroll; property AfterScroll; property BeforeRefresh; property AfterRefresh; property OnCalcFields; property OnDeleteError; property OnEditError; property OnFilterRecord; property OnNewRecord; property OnPostError; property Active; end; procedure Register; implementation uses StrUtils, Variants, Math, Windows; procedure Register; begin RegisterComponents('SQLiteCds', [TSQLiteDataSetProvider]); RegisterComponents('SQLiteCds', [TSQLiteClientDataSet]); end; function AllocRecordRow(PriorRow: PRecordNode): PRecordNode; begin Result := AllocMem(sizeof(TRecordNode)); FillChar(Result^, sizeof(TRecordNode), 0); Result.Prior := PriorRow; if PriorRow <> nil then PriorRow.Next := Result; end; procedure DestroyRecordList(var First: PRecordNode); var NextRec, CurrentRec: PRecordNode; begin CurrentRec := First; while (CurrentRec <> nil) do begin NextRec := CurrentRec.Next; FreeMem(CurrentRec); CurrentRec := NextRec; end; First := nil; end; { TSiagriClientDataSet } function TSQLiteClientDataSet.AllocRecordBuffer: PByte; var rsize: Word; begin rsize := GetRecordSize; Result := AllocMem(rsize); FillChar(Result^, rsize, 0); end; procedure TSQLiteClientDataSet.FreeRecordBuffer(var Buffer: PByte); begin FreeMem(Buffer); end; procedure TSQLiteClientDataSet.GetBookmarkData(Buffer: PByte; Data: Pointer); begin inherited; end; function TSQLiteClientDataSet.GetBookmarkFlag(Buffer: PByte): TBookmarkFlag; begin Result := PRecordBuffer(Buffer).BookFlag; end; function TSQLiteClientDataSet.GetDataSetProvider: TSQLiteDataSetProvider; begin Result := FDataSetProvider; end; function TSQLiteClientDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean; type PDateTimeRec = ^TDateTimeRec; var i, i64, index: Int64; d: Double; s: PAnsiChar; //fname: AnsiString; begin index := Field.FieldNo -1; Result := OpenCurrentRecord; if not Result and (State = dsInsert) then begin with TVarData(FLastBindedFieldData[index]) do case VType of varInteger: PInteger(Buffer)^ := Vinteger; varString: PAnsiChar(Buffer)^ := AnsiChar(vstring); end; Result := True; Exit; end; //fname := UTF8String(Field.FieldName); if not Result or (_SQLite3_Column_Type(FSelectOneStmt, index) = SQLITE_NULL) then begin Result := False; Exit; end; case Field.DataType of ftString, ftWideString: begin s := _SQLite3_Column_Text(FSelectOneStmt, index); Move(s[0], Buffer^, Length(s)+1); end; ftSmallInt, ftInteger: begin i := _SQLite3_Column_Int(FSelectOneStmt, index); Integer(Buffer^) := i; end; ftLargeint: begin i64 := _Sqlite3_Column_Int64(FSelectOneStmt, index); Int64(Buffer^) := i64; end; ftFloat: begin d := _Sqlite3_Column_Double(FSelectOneStmt, index); Double(Buffer^) := d; end; ftDate: begin i := _SQLite3_Column_Int(FSelectOneStmt, index); PDateTimeRec(Buffer).Time := 0; PDateTimeRec(Buffer).Date := i; end; ftTime: begin i := _SQLite3_Column_Int(FSelectOneStmt, index); PDateTimeRec(Buffer).Date := 0; PDateTimeRec(Buffer).Time := i; end; else Result := False; end; end; function TSQLiteClientDataSet.Navigate(GetMode: TGetMode): TGetResult; begin if RecordCount < 1 then Result := grEOF else begin Result:=grOK; case GetMode of gmNext: begin if FActualRecordId >= FMaxRecordId then Result := grEOF else begin Inc(FActualRecordId); if FActualRecordId = 1 then FCurrentRec := FRootRow else FCurrentRec := FCurrentRec.Next; end; end; gmPrior: begin if FActualRecordId <= 1 then begin Result := grBOF; FActualRecordId := 0; FCurrentRec := nil; end else begin Dec(FActualRecordId); if FActualRecordId = FMaxRecordId then FCurrentRec := FLastRow else FCurrentRec := FCurrentRec.Prior; end; end; gmCurrent: if (FActualRecordId <= 0) or (FActualRecordId > FMaxRecordId) then Result := grError else if not Assigned(FCurrentRec) then begin FCurrentRec := FRootRow; FActualRecordId := 1; end; end; end; end; function TSQLiteClientDataSet.OpenCurrentRecord: Boolean; procedure OpenOneStmt; var SQL: String; begin SQL := 'select * from ' + GetSQLiteTableName + ' where _ROWID_ = :R ' + GetSelectOrderBy; TSQLiteAux.PrepareSQL(SQL, FSelectOneStmt); end; var FCur: PRecordNode; begin FCur := PRecordBuffer(ActiveBuffer).Node; Result := Assigned(FCur) and (FCur.Id > 0); if not Result then Exit; if (FCurrentOpenRec <> FCur) then begin if FSelectOneStmt = nil then OpenOneStmt else TSQLiteAux.CheckError(_SQLite3_Reset(FSelectOneStmt)); TSQLiteAux.CheckError(_SQLite3_Bind_int64(FSelectOneStmt, 1, FCur.BdId)); if _SQLite3_Step(FSelectOneStmt) <> SQLITE_ROW then raise Exception.CreateFmt('Row %d not found', [FCur.BdId]); FCurrentOpenRec := FCur; end; end; function TSQLiteClientDataSet.GetRecNo: Integer; begin if Assigned(PRecordBuffer(ActiveBuffer).Node) then Result := PRecordBuffer(ActiveBuffer).Node.Id else Result := 0; end; function TSQLiteClientDataSet.GetRecord(Buffer: PByte; GetMode: TGetMode; DoCheck: Boolean): TGetResult; begin Result := Navigate(GetMode); if (Result = grOk) then begin PRecordBuffer(Buffer).Node := FCurrentRec; ClearCalcFields(Buffer); GetCalcFields(Buffer); end else begin if Assigned(PRecordBuffer(Buffer).Node) and (FRecordCount = 0) then begin PRecordBuffer(Buffer).Node.Id := 0; PRecordBuffer(Buffer).Node.BdId := 0; end; if (Result = grError) and DoCheck then DatabaseError('No Records'); end; end; function TSQLiteClientDataSet.GetRecordCount: Integer; begin Result := FRecordCount; end; function TSQLiteClientDataSet.GetRecordSize: Word; begin Result := Sizeof(Pointer) + SizeOf(TBookmarkFlag) + CalcFieldsSize; end; procedure TSQLiteClientDataSet.InternalAddRecord(Buffer: Pointer; Append: Boolean); begin inherited; end; procedure TSQLiteClientDataSet.InternalClose; begin inherited; _SQLite3_Finalize(FSelectAllStmt); FSelectAllStmt := nil; _SQLite3_Finalize(FSelectOneStmt); FSelectOneStmt := nil; _SQLite3_Finalize(FLocateStmt); FLocateStmt := nil; FCursorOpen := False; FActualRecordId := 0; FCurrentRec := nil; FCurrentOpenRec := nil; BindFields(False); if DefaultFields then DestroyFields; end; procedure TSQLiteClientDataSet.InternalDelete; begin inherited; TSQLiteAux.ExecuteSQL('delete from ' + GetSQLiteTableName + ' where _ROWID_ = ' + IntToStr(fcurrentrec.BdId)); if Assigned(FCurrentRec.Prior) then FCurrentRec.Prior.Next := FCurrentRec.Next; if Assigned(FCurrentRec.Next) then FCurrentRec.Next.Prior := FCurrentRec.Prior; FCurrentRec := FCurrentRec.Next; if Assigned(FCurrentRec) then FActualRecordId := FCurrentRec.Id else FActualRecordId := 0; if Assigned(FCurrentRec) then begin if FCurrentRec.Prior = nil then FRootRow := FCurrentRec; if FCurrentRec.Next = nil then FLastRow := FCurrentRec; end else begin FRootRow := nil; FLastRow := nil; end; if Assigned(FLastRow) then FMaxRecordId := FLastRow.Id; Dec(FRecordCount); end; procedure TSQLiteClientDataSet.InternalFirst; begin inherited; FActualRecordId := 0; FCurrentRec := nil; end; procedure TSQLiteClientDataSet.InternalGotoBookmark(Bookmark: Pointer); begin inherited; end; procedure TSQLiteClientDataSet.InternalHandleException; begin inherited; end; procedure TSQLiteClientDataSet.MasterChanged(Sender: TObject); begin BuildRowIdIndex; First; end; procedure TSQLiteClientDataSet.MasterDisabled(Sender: TObject); begin end; procedure TSQLiteClientDataSet.DataEvent(Event: TDataEvent; Info: Integer); begin case Event of deParentScroll: MasterChanged(Self); end; inherited; end; procedure TSQLiteClientDataSet.InternalInitFieldDefs; begin inherited; FieldDefs.Clear; if Assigned(FDataSetProvider) and Assigned(FDataSetProvider.DataSet) then FieldDefs.Assign(FDataSetToSQLiteBind.GetBinding(FDataSetProvider.DataSet).FieldsDefs) else if Assigned(DataSetField) then begin FieldDefs.Assign(FDataSetToSQLiteBind.GetBinding(GetSQLiteTableName).FieldsDefs) end else InitFieldDefsFromFields; end; procedure TSQLiteClientDataSet.InternalInitRecord(Buffer: PByte); var i: Integer; begin inherited; PRecordBuffer(Buffer).BookFlag := bfCurrent; PRecordBuffer(Buffer).Node := nil; _SQLite3_Reset(PDataSetRec.InsertStmt); _SQLite3_Clear_Bindings(PDataSetRec.InsertStmt); end; procedure TSQLiteClientDataSet.InternalInsert; var i: Integer; begin inherited; for i := 0 to Length(FLastBindedFieldData) - 1 do FLastBindedFieldData[i] := null; end; procedure TSQLiteClientDataSet.InternalLast; begin inherited; FActualRecordId := FMaxRecordId+1; FCurrentRec := nil; end; procedure TSQLiteClientDataSet.InternalOpen; var RecsOut: Integer; begin inherited; RecsOut := 0; FMaxRecordId := 0; if Assigned(FDataSetProvider) then FDataSetToSQLiteBind := Pointer(Integer(DoGetRecords(-1, RecsOut))) else if Assigned(DataSetField) then FDataSetToSQLiteBind := TSQLiteClientDataSet(DataSetField.DataSet).FDataSetToSQLiteBind else CreateDataSetFromFields; PDataSetRec := FDataSetToSQLiteBind.GetBinding(GetSQLiteTableName); BuildRowIdIndex; FCursorOpen := True; FLastLocateFields := nil; FLastLocateFieldsStr := ''; FieldDefs.Updated := False; FieldDefs.Update; FieldDefList.Update; if DefaultFields then CreateFields; BindFields(True); SetLength(FLastBindedFieldData, Fields.Count); end; procedure TSQLiteClientDataSet.InternalPost; var rowid: Int64; NewRow: PRecordNode; begin TSQLiteAux.CheckError(_SQLite3_Step(PDataSetRec.InsertStmt)); //rowid := _SQLite3_LastInsertRowID(Database); if State = dsInsert then begin NewRow := AllocRecordRow(FLastRow); if Assigned(FLastRow) then NewRow.Id := FLastRow.Id + 1 else NewRow.Id := 1; NewRow.BdId := _SQLite3_Last_Insert_RowID(Database); FLastRow := NewRow; if FRootRow = nil then FRootRow := NewRow; Inc(FRecordCount); FCurrentRec := NewRow; FActualRecordId := FCurrentRec.Id; FMaxRecordId := FLastRow.Id; //BuildRowIdIndex; end; inherited; end; procedure TSQLiteClientDataSet.InternalSetToRecord(Buffer: PByte); begin inherited; if Assigned(PRecordBuffer(Buffer).Node) then begin FActualRecordId := PRecordBuffer(Buffer).Node.Id; FCurrentRec := PRecordBuffer(Buffer).Node; end; end; function TSQLiteClientDataSet.IsCursorOpen: Boolean; begin Result := FCursorOpen; end; function TSQLiteClientDataSet.Locate(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean; function GenerateWhereLocate: String; var i: Integer; begin Result := GetWhereClause; for i := 0 to FLastLocateFields.Count - 1 do Result := Result + Format(' and %s = :%d', [FLastLocateFields[i], i]) end; procedure SetParams; var i,j: Integer; s: AnsiString; begin for i := 0 to FLastLocateFields.Count -1 do begin if KeyValues[i] = null then _SQLite3_Bind_null(FLocateStmt, i+1) else if TVarData(KeyValues[i]).VType = varDate then begin j := DateTimeToTimeStamp(KeyValues[i]).Date; _SQLite3_Bind_Int(FLocateStmt, i+1, j) end else begin s := VarToStr(KeyValues[i]); _SQLite3_Bind_text(FLocateStmt, i+1, @s[1], -1, SQLITE_TRANSIENT); end; end; end; var SQL: String; CurrentRec: PRecordNode; BdId: Integer; begin Result := False; if RecordCount = 0 then Exit; if not Assigned(FLastLocateFields) or (FLastLocateFieldsStr <> KeyFields) then begin if not Assigned(FLastLocateFields) then FLastLocateFields := TStringList.Create; FLastLocateFields.Delimiter := ';'; FLastLocateFields.DelimitedText := KeyFields; FLastLocateFieldsStr := KeyFields; if VarIsArray(KeyValues) then SQL := GenerateWhereLocate else SQL := KeyFields + ' = :1'; SQL := 'select _ROWID_ from ' + GetSQLiteTableName + SQL + GetSelectOrderBy; TSQLiteAux.PrepareSQL(SQL, FLocateStmt); end else _SQLite3_Reset(FLocateStmt); SetParams; if _SQLite3_Step(FLocateStmt) <> SQLITE_ROW then Result := False else begin BdId := _SQLite3_Column_Int64(FLocateStmt, 0); if BdId = 0 then Exit; CurrentRec := FRootRow; while (CurrentRec <> nil) and (CurrentRec.BdId <> BdId) do CurrentRec := CurrentRec.Next; FActualRecordId := CurrentRec.Id; if Assigned(CurrentRec) then begin FCurrentRec := CurrentRec; Resync([rmExact, rmCenter]); Result := True; end; end; end; function TSQLiteClientDataSet.DoGetRecords(Count: Integer; out RecsOut: Integer): OleVariant; var OwnerData: OleVariant; OleParams: OleVariant; begin DoBeforeGetRecords(OwnerData); if (Self.Params.Count > 0) then OleParams := PackageParams(Self.Params); Result := FDataSetProvider.GetRecords(Count, RecsOut, 0, '', OleParams, OwnerData); UnPackParams(OleParams, Self.Params); DoAfterGetRecords(OwnerData); end; procedure TSQLiteClientDataSet.DoBeforeGetRecords(var OwnerData: OleVariant); begin if Assigned(FBeforeGetRecords) then FBeforeGetRecords(Self, OwnerData); end; function TSQLiteClientDataSet.GetSelectOrderBy: String; begin Result := ''; if Trim(FIndexFieldNames) <> '' then Result := ' order by ' + StringReplace(FIndexFieldNames, ';', ',', [rfReplaceAll]); end; function TSQLiteClientDataSet.GetSQLiteTableName: String; function FindLastOf(const C: char; const S: String): Integer; var i: Integer; begin Result := -1; for i := Length(S) downto 1 do if S[i] = C then Result := i; end; var Rec: PINsertSQLiteRec; Root, DsName: String; P: Integer; MasterDataSet: TSQLiteClientDataSet; begin if Assigned(FDataSetProvider) then begin Result := FDataSetToSQLiteBind.GetBinding(FDataSetProvider.DataSet).Table; end else if Assigned(DataSetField) then begin MasterDataSet := TSQLiteClientDataSet(DataSetField.DataSet); Rec := FDataSetToSQLiteBind.GetBinding(MasterDataSet.DataSetProvider.DataSet); P := FindLastOf('_', Rec.Table)+1; Root := Copy(Rec.Table, 1, P-1); DsName := Copy(Rec.Table, P, MaxInt); DsName := StringReplace(DataSetField.FieldName, DsName, '', []); Result := Root + DsName; end else Result := FDataSetToSQLiteBind.GetBinding(Self).Table; end; function TSQLiteClientDataSet.GetWhereClause: String; var i: Integer; begin Result := ' where 1=1 '; with FDataSetToSQLiteBind.GetBinding(GetSQLiteTableName)^ do if Assigned(Params) and (Params.Count > 0) then begin for i := 0 to Params.Count - 1 do Result := Result + Format('and %s = :%s ', [Params[i].Name, Params[i].Name]); //Result := ' where ' + Copy(Result, 1, Length(Result)-4); end; end; procedure TSQLiteClientDataSet.BuildRowIdIndex; var SQL: String; CurrentRow, PriorRow: PRecordNode; FetchResult: Integer; begin SQL := 'select _ROWID_ from ' + GetSQLiteTableName + GetWhereClause + GetSelectOrderBy; PriorRow := nil; if (FRootRow = nil) then FRootRow := AllocRecordRow(PriorRow); CurrentRow := FRootRow; if not Assigned(FSelectAllStmt) then TSQLiteAux.PrepareSQL(SQL, FSelectAllStmt) else _SQLite3_Reset(FSelectAllStmt); if Assigned(DataSetField) then SetParamsFromMaster(FSelectAllStmt, DataSetField.DataSet); FRecordCount := 0; try FetchResult := _SQLite3_Step(FSelectAllStmt); while (FetchResult = SQLITE_ROW) do begin if (CurrentRow = nil) then CurrentRow := AllocRecordRow(PriorRow); CurrentRow.BdId := _SQLite3_Column_Int64(FSelectAllStmt, 0); CurrentRow.Id := FRecordCount+1; PriorRow := CurrentRow; CurrentRow := CurrentRow.Next; Inc(FRecordCount); FetchResult := _SQLite3_Step(FSelectAllStmt); end; // Don't need this memory anymore if FRecordCount = 0 then DestroyRecordList(FRootRow) else if PriorRow.Next <> nil then DestroyRecordList(PriorRow.Next); FLastRow := PriorRow; FCurrentRec := nil; FCurrentOpenRec := nil; if Assigned(FlastRow) then FMaxRecordId := FLastRow.Id else FMaxRecordId := 0; finally TSQLiteAux.CheckError(_SQLite3_Finalize(FSelectAllStmt)); FSelectAllStmt := nil; end; end; constructor TSQLiteClientDataSet.Create(AOwner: TComponent); begin inherited; FParams := TParams.Create(Self); FSelectAllStmt := nil; FSelectOneStmt := nil; FCurrentOpenRec := nil; FRootRow := nil; FLocalDataSetToSQLiteBind := nil; FRecordCount := 0; FRecordSize := 0; FCursorOpen := False; FActualRecordId := 0; FCurrentRec := nil; ObjectView := True; FMasterLink := TMasterDataLink.Create(Self); FMasterLink.OnMasterChange := MasterChanged; FMasterLink.OnMasterDisable := MasterDisabled; end; procedure TSQLiteClientDataSet.CreateDataSet; begin DataSetProvider := nil; DataSetField := nil; Active := True; end; procedure TSQLiteClientDataSet.CreateDataSetFromFields; begin FieldDefs.Updated := False; FieldDefs.Update; FLocalDataSetToSQLiteBind := TDataSetToSQLiteBind.Create; FDataSetToSQLiteBind := @FLocalDataSetToSQLiteBind; FDataSetToSQLiteBind.GetBinding(Self); end; destructor TSQLiteClientDataSet.Destroy; begin DestroyRecordList(FRootRow); FParams.Free; if Assigned(FLastLocateFields) then FLastLocateFields.Free; if Assigned(FLocalDataSetToSQLiteBind) then FLocalDataSetToSQLiteBind.Free; inherited; end; procedure TSQLiteClientDataSet.DoAfterGetRecords(var OwnerData: OleVariant); begin if Assigned(FAfterGetRecords) then FAfterGetRecords(Self, OwnerData); end; procedure TSQLiteClientDataSet.SetBookmarkData(Buffer: PByte; Data: Pointer); begin inherited; end; procedure TSQLiteClientDataSet.SetBookmarkFlag(Buffer: PByte; Value: TBookmarkFlag); begin inherited; PRecordBuffer(Buffer).BookFlag := Value; end; procedure TSQLiteClientDataSet.SetDataSetField(const Value: TDataSetField); begin if Assigned(FDataSetProvider) then FDataSetProvider := nil; inherited; end; procedure TSQLiteClientDataSet.SetDataSetProvider( const Value: TSQLiteDataSetProvider); begin if Assigned(DataSetField) then SetDataSetField(nil); FDataSetProvider := Value; end; procedure TSQLiteClientDataSet.SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); var pindex: Integer; //pname: AnsiString; begin inherited; //pname := ':' + Field.FieldName; //pindex := _SQLite3_Bind_Parameter_Index(FInsertStmt, PAnsiChar(pname)); pindex := Field.FieldNo; // if Field.IsNull then // TSQLiteAux.CheckError(_SQLite3_Bind_null(PDataSetRec.InsertStmt, pindex)) // else case Field.DataType of ftString, ftWideString: begin TSQLiteAux.CheckError(_SQLite3_Bind_text(PDataSetRec.InsertStmt, pindex, Buffer, -1, SQLITE_TRANSIENT)); FLastBindedFieldData[pindex-1] := AnsiString(PAnsiChar(Buffer)); end; ftOraBlob, ftOraClob, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic, ftFmtMemo: TSQLiteAux.CheckError(_SQLite3_Bind_Blob(PDataSetRec.InsertStmt, pindex, Buffer, sizeof(Buffer), nil)); ftSmallint, ftInteger, ftWord, ftBoolean: begin TSQLiteAux.CheckError(_SQLite3_Bind_Int(PDataSetRec.InsertStmt, pindex, PInteger(Buffer)^)); FLastBindedFieldData[pindex-1] := PInteger(Buffer)^; end; ftTime: TSQLiteAux.CheckError(_SQLite3_Bind_Int(PDataSetRec.InsertStmt, pindex, DateTimeToTimeStamp(PDateTime(Buffer)^).Time)); ftDate: TSQLiteAux.CheckError(_SQLite3_Bind_Int(PDataSetRec.InsertStmt, pindex, DateTimeToTimeStamp(PDateTime(Buffer)^).Date)); ftLargeint: TSQLiteAux.CheckError(_SQLite3_Bind_int64(PDataSetRec.InsertStmt, pindex, PInt64(Buffer)^)); ftDateTime, ftTimeStamp, ftFloat, ftCurrency: TSQLiteAux.CheckError(_SQLite3_Bind_Double(PDataSetRec.InsertStmt, pindex, PDouble(Buffer)^)); ftBCD: TSQLiteAux.CheckError(_SQLite3_Bind_Double(PDataSetRec.InsertStmt, pindex, Field.AsFloat)); else raise Exception.Create('Field type not supported'); end; end; procedure TSQLiteClientDataSet.SetIndexFieldNames(const Value: String); var TableName: String; begin if (FIndexFieldNames <> Value) then begin FIndexFieldNames := Value; TableName := GetSQLiteTableName; TSQLiteAux.ExecuteSQL('drop index if exists IndexFieldNames_' + TableName); TSQLiteAux.ExecuteSQL(Format('create index IndexFieldNames_%s on %s (%s)', [TableName, TableName, StringReplace(Value, ';', ',', [rfReplaceAll])])); end; end; procedure TSQLiteClientDataSet.SetParams(const Value: TParams); begin FParams.Assign(Value); end; procedure TSQLiteClientDataSet.SetParamsFromMaster(stmt: TSQLiteStmt; Master: TDataSet); var Params: TParams; i: Integer; pname, pvalue: AnsiString; pindex: Integer; begin Params := FDataSetToSQLiteBind.GetBinding(GetSQLiteTableName).Params; for i := 0 to Params.Count - 1 do begin pname := ':' + AnsiString(Params[i].Name); pindex := _SQLite3_Bind_Parameter_Index(stmt, PAnsiChar(pname)); pvalue := Master.FieldByName(Params[i].Name).AsAnsiString; _SQLite3_Bind_text(stmt, pindex, PAnsiChar(pvalue), -1, SQLITE_TRANSIENT); end; end; end.
{$I-,Q-,R-,S-} {Problema 12: Rompecabezas Comestible [Rob Kolstad, 2006] Bessie está haciendo una dieta en la cual ella no puede comer más de C (10 <= C <= 35,000) calorías por día. El Granjero Juan está molestándola poniéndole B (1 <= B <= 21) baldes de comida, cada uno de los cuales con algún número (potencialmente no único) de calorías (en el rango 1..35,000). Bessie no tiene auto-control: una vez que ella comienza a alimentarse de un balde, ella lo consume totalmente. Por ejemplo, considere un límite de 40 calorías y 6 baldes con tama˝os 7, 13, 17, 19, 29, y 31. Bessie podría comer 7 + 31 = 38 calorias, pero aún más podría comer tres baldes: 7 + 13 + 19 = 39 calorías. Ella no puede encontrar una combinación mejor. NOMBRE DEL PROBLEMA: eatpuz FORMATO DE ENTRADA: * Línea 1: Dos enteros separados por espacio: C y B. * Línea 2: B enteros separados por espacio que son respectivamente el número de calorías en el balde 1, 2, etc. ENTRADA EJEMPLO (archivo eatpuz.in): 40 6 7 13 17 19 29 31 FORMATO DE SALIDA: * Línea 1: Una sola línea con un solo entero que es el mayor número de calorías que Bessie puede consumir y aún cumplir con la dieta. SALIDA EJEMPLO (archivo eatpuz.out): 39 **** Para free Pascal **** } const max = 35001; type Trange = longint; ta = array[0..22] of boolean; var fe,fs : text; n,m,sol : longint; tab : array[0..22] of Trange; best : array[0..max] of Trange; mk : array[0..max] of ^ta; procedure open; var i : longint; begin assign(fe,'eatpuz.in'); reset(fe); assign(fs,'eatpuz.out'); rewrite(fs); readln(fe,n,m); for i:=1 to m do read(fe,tab[i]); close(fe); end; procedure work; var i,j,k,p : longint; begin new(mk[0]); fillchar(mk[0]^,sizeof(mk[0]^),false); for i:=1 to n do begin k:=0; p:=0; new(mk[i]); fillchar(mk[i]^,sizeof(mk[i]^),false); for j:=1 to m do if (i - tab[j] >= 0) and (best[i-tab[j]] + tab[j] > best[i]) and (not mk[i-tab[j]]^[j]) then begin best[i]:=best[i-tab[j]] + tab[j]; k:=i-tab[j]; p:=j; end; if best[i] < best[i-1] then begin best[i]:=best[i-1]; mk[i]^:=mk[i-1]^; end else begin mk[i]^:=mk[k]^; mk[i]^[p]:=true; end; end; end; procedure closer; begin writeln(fs,best[n]); close(fs); end; begin open; work; closer; end.
unit uWizImportPerson; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentWizImp, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, DBClient, ImgList, StdCtrls, ExtCtrls, Grids, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Buttons, ComCtrls, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TWizImportPerson = class(TParentWizImp) gbVendorCatalogue: TGroupBox; Label19: TLabel; cbxStore: TcxLookupComboBox; Label13: TLabel; Label2: TLabel; Label18: TLabel; cbxUser: TcxLookupComboBox; Label14: TLabel; Label3: TLabel; Label4: TLabel; cbPersonType: TComboBox; cbVerify: TComboBox; Label5: TLabel; procedure sgColumnsExit(Sender: TObject); private procedure SaveGridColumns; procedure GetGridColumn; function GetPortPersonType(Item : Integer): String; function GetImportType(Item : Integer): Integer; protected procedure AddColumnsToImport; override; procedure FillColumnsGrid; override; function TestBeforeNavigate:Boolean; override; function OnAfterChangePage:Boolean; override; function VerifyFieldsRequired: Boolean; function DoFinish:Integer; override; function AddSpecificFieldsToCDS(Position : Integer): Integer; override; procedure AddSpecificFriendFieldsToCDS(Position : Integer); override; procedure OnBeforeBackClick; override; end; implementation uses uMsgBox, uDMGlobalNTier, uParamFunctions, uDMImportExport, uParentWizard, uSystemConst; {$R *.dfm} { TWizImportPerson } procedure TWizImportPerson.AddColumnsToImport; begin sgColumns.Cells[0,1] := 'Name'; // Pessoa sgColumns.Cells[0,2] := 'FirstName'; // PessoaFirstName sgColumns.Cells[0,3] := 'LastName'; // PessoaLastName sgColumns.Cells[0,4] := 'ShortName'; // Pessoa sgColumns.Cells[0,5] := 'Legalname'; // NomeJuridico = Inscricao Estadual sgColumns.Cells[0,6] := 'Address'; // Endereco sgColumns.Cells[0,7] := 'Neighborhood'; // Bairro sgColumns.Cells[0,8] := 'City'; // Cidade sgColumns.Cells[0,9] := 'State'; // Estado sgColumns.Cells[0,10] := 'ZIP'; // CEP sgColumns.Cells[0,11] := 'Country'; // Pais sgColumns.Cells[0,12] := 'PhoneAreaCode'; //código do telefone sgColumns.Cells[0,13] := 'Phone'; //telefone sgColumns.Cells[0,14] := 'CellAreaCode'; //código do celular sgColumns.Cells[0,15] := 'Cellular'; // celular sgColumns.Cells[0,16] := 'Fax'; // Fax sgColumns.Cells[0,17] := 'Contact'; // Contato sgColumns.Cells[0,18] := 'Email'; sgColumns.Cells[0,19] := 'OBS'; sgColumns.Cells[0,20] := 'BirthDate'; // nascimento sgColumns.Cells[0,21] := 'SocialSecurity#'; //Identidade sgColumns.Cells[0,22] := 'TaxNumber'; // CGC sgColumns.Cells[0,23] := 'EmployeeID'; // CPF sgColumns.Cells[0,24] := 'DriverLicence'; // CartMotorista sgColumns.Cells[0,25] := 'DBA'; // Inscricao Estadual sgColumns.Cells[0,26] := 'FederalID#'; //CNPJ sgColumns.Cells[0,27] := 'SalesTax#'; //Insc. Municipal sgColumns.Cells[0,28] := 'CreationDate'; //Data criacao sgColumns.RowCount := 29; end; function TWizImportPerson.DoFinish: Integer; begin Result := inherited DoFinish; end; procedure TWizImportPerson.FillColumnsGrid; begin sgColumns.Cells[0,0] := 'Main Retail'; sgColumns.Cells[1,0] := 'Person File'; AddColumnsToImport; AddComboColumnsToImport; end; procedure TWizImportPerson.GetGridColumn; var sColumn, sError, sResult : String; sCaseCost : WordBool; i : integer; begin sColumn := DMImportExport.GetAppProperty('ColumnImportPersonSetup', SpecificConfig.Values['PersonType']); { sError := DMImportExport.GetConfigImport( 0, GetImportType(cbPersonType.ItemIndex), sColumn, sCaseCost); LogError.Text := sError; } if LogError.Text = '' then begin if sColumn = '' then Exit; for i:=1 to sgColumns.RowCount-1 do begin sResult := ParseParam(sColumn, Trim(sgColumns.Cells[0,i])); if sResult <> '' then sgColumns.Cells[1,i] := sResult; sColumn := DeleteParam(sColumn, Trim(sgColumns.Cells[0,i])); end; end; end; function TWizImportPerson.OnAfterChangePage: Boolean; var sError: String; begin Result := inherited OnAfterChangePage; if pgOption.ActivePage.Name = 'tsCrossColumn' then begin cbColumns.Visible := False; FillColumnsGrid; GetGridColumn; end else if pgOption.ActivePage.Name = 'tsSpecificConfig' then begin DMImportExport.ImportConn.Connected := True; DMImportExport.OpenStore; DMImportExport.OpenUser; end else if pgOption.ActivePage.Name = 'tsImport' then begin SaveGridColumns; ScreenStatusWait; DMImportExport.ImportConn.AppServer.ImportPersonTextFile(cdsFile.Data, LinkedColumns.Text,SpecificConfig.Text, sError); LogError.Text := sError; if sError <> '' then ShowError(sError) else MsgBox('Import Success!', vbInformation + vbOKOnly); ScreenStatusOk; end; end; procedure TWizImportPerson.SaveGridColumns; var sColumn, sError : String; i : integer; begin for i:=1 to sgColumns.RowCount-1 do if Trim(sgColumns.Cells[0,i]) <> '' then //if Pos(Trim(sgColumns.Cells[1,i]), sColumn) = 0 then sColumn := sColumn + sgColumns.Cells[0,i] + '=' + sgColumns.Cells[1,i] + ';'; if sColumn = '' then Exit; //DMImportExport.SetAppProperty('ColumnImportPersonSetup', SpecificConfig.Values['PersonType'], sColumn); sError := DMImportExport.InsertConfigImport( 0, GetImportType(cbPersonType.ItemIndex), sColumn, False); LogError.Text := sError; if LogError.Text <> '' then begin MsgBox(LogError.Text, vbCritical + vbOkOnly); end; end; function TWizImportPerson.TestBeforeNavigate: Boolean; begin Result := inherited TestBeforeNavigate; if pgOption.ActivePage.Name = 'tsSpecificConfig' then begin if not VerifyFieldsRequired then begin MsgBox('Field Required!', vbInformation + vbOKOnly); Result := False; Exit; end else begin AddSpecificConfigList('Store',cbxStore.EditValue); AddSpecificConfigList('PersonType',GetPortPersonType(cbPersonType.ItemIndex)); AddSpecificConfigList('User',cbxUser.EditValue); AddSpecificConfigList('Verify',cbVerify.Text); AddSpecificConfigList('IDUser', IntToStr(DMImportExport.FUser.ID)); end; end end; function TWizImportPerson.VerifyFieldsRequired: Boolean; begin Result := True; if (cbxStore.EditingText = '') or (cbPersonType.Text = '') or (cbxUser.EditingText = '') then Result := False; end; procedure TWizImportPerson.sgColumnsExit(Sender: TObject); begin inherited; //SaveGridColumns; end; function TWizImportPerson.GetPortPersonType(Item : Integer): String; var PortPersonType: String; begin {case Item of 0 : PortPersonType := 'Clientes'; 1 : PortPersonType := 'Fornecedor'; 2 : PortPersonType := 'Comissionados'; 3 : PortPersonType := 'Vendedor'; 4 : PortPersonType := 'Guias'; 5 : PortPersonType := 'Agências'; 6 : PortPersonType := 'Fabricantes'; 7 : PortPersonType := 'Outros'; 8 : PortPersonType := 'Prospects'; end;} case Item of 0 : PortPersonType := '.001'; //Clientes 1 : PortPersonType := '.002'; //Fornecedor 2 : PortPersonType := '.003'; //Comissionados 3 : PortPersonType := '.003.001'; //Vendedor 4 : PortPersonType := '.003.002'; //Guias 5 : PortPersonType := '.003.003'; //Agências 6 : PortPersonType := '.004'; //Fabricantes 7 : PortPersonType := '.003.004'; //Outros 8 : PortPersonType := '.001.001'; //Prospects end; Result := PortPersonType; end; function TWizImportPerson.AddSpecificFieldsToCDS( Position: Integer): Integer; begin Result := Position; end; procedure TWizImportPerson.AddSpecificFriendFieldsToCDS(Position: Integer); begin inherited; end; function TWizImportPerson.GetImportType(Item: Integer): Integer; begin case Item of 0 : Result := IMPORT_TYPE_COSTUMER; //Clientes 1 : Result := IMPORT_TYPE_VENDOR; //Fornecedor 2 : Result := IMPORT_TYPE_COMMISSIONED; //Comissionados 3 : Result := IMPORT_TYPE_SALESMAN; //Vendedor 4 : Result := IMPORT_TYPE_GUIDES; //Guias 5 : Result := IMPORT_TYPE_AGENCY; //Agências 6 : Result := IMPORT_TYPE_MANUFACTORER; //Fabricantes 7 : Result := IMPORT_TYPE_ANOTHER; //Outros 8 : Result := IMPORT_TYPE_PROSPECTS; //Prospects end; end; procedure TWizImportPerson.OnBeforeBackClick; begin if pgOption.ActivePage.Name = 'tsCrossColumn' then SaveGridColumns; inherited; end; end.
//============================================================================= // sgText.pas //============================================================================= // // The Font unit relates to writing text to the screen, // and to loading and styling the associated fonts. // //============================================================================= /// Supports the presentation (drawing) of text to screen using loaded `Font`s /// to style the text. Load a different ``Font`` for each unique text /// presentation style (colour and size) you need in your game. /// ///@module Text ///@static unit sgText; //============================================================================= interface uses sgTypes; //============================================================================= //---------------------------------------------------------------------------- // Font loading routines //---------------------------------------------------------------------------- /// Loads a font from file with the specified side. Fonts must be freed using /// the FreeFont routine once finished with. Once the font is loaded you /// can set its style using SetFontStyle. Fonts are then used to draw and /// measure text in your programs. /// /// @lib /// @sn loadFontFile:%s size:%s /// /// @class Font /// @constructor /// @csn initWithFontName:%s andSize:%s function LoadFont(const fontName: String; size: Longint): Font; /// Frees the resources used by the loaded Font. /// /// @lib /// /// @class Font /// @dispose procedure FreeFont(var fontToFree: Font); /// Loads and returns a font that can be used to draw text. The supplied /// ``filename`` is used to locate the font to load. The supplied ``name`` indicates the /// name to use to refer to this Font in SwinGame. The `Font` can then be /// retrieved by passing this ``name`` to the `FontNamed` function. /// /// @lib /// @sn loadFontNamed:%s fromFile:%s size:%s /// /// @class Font /// @constructor /// @csn initWithName:%s fromFile:%s size:%s function LoadFontNamed(const name, filename: String; size: Longint): Font; /// Determines if SwinGame has a font loaded for the supplied name. /// This checks against all fonts loaded, those loaded without a name /// are assigned the filename as a default. /// /// @lib function HasFont(const name: String): Boolean; /// Determines the name that will be used for a font loaded with /// the indicated fontName and size. /// /// @lib /// @sn fontName:%s size:%s function FontNameFor(const fontName: String; size: Longint): String; /// Returns the `Font` that has been loaded with the specified name, /// and font size using `LoadFont`. /// /// @lib FontNamedWithSize /// @sn fontNamed:%s withSize:%s function FontNamed(const name: String; size: Longint): Font; overload; /// Returns the `Font` that has been loaded with the specified name, /// see `LoadFontNamed`. /// /// @lib function FontNamed(const name: String): Font; overload; /// Releases the SwinGame resources associated with the font of the /// specified ``name``. /// /// @lib procedure ReleaseFont(const name: String); /// Releases all of the fonts that have been loaded. /// /// @lib procedure ReleaseAllFonts(); //--------------------------------------------------------------------------- // Font properties //--------------------------------------------------------------------------- /// Alters the style of the font. This is time consuming, so load /// fonts multiple times and set the style for each if needed. /// /// @lib /// @sn font:%s setStyle:%s /// /// @class Font /// @setter FontStyle procedure FontSetStyle(font: Font; value: FontStyle); /// Returns the style settings for the font. /// /// @lib /// /// @class Font /// @getter FontStyle function FontFontStyle(font: Font): FontStyle; /// Returns the width (in pixels) of the passed in text and the font it will be drawn with. /// /// @lib /// @sn font:%s widthOf:%s /// /// @class Font /// @method TextWidth function TextWidth(theFont: Font; const theText: String): Longint; overload; /// Returns the height (in pixels) of the passed in text and the font it will be drawn with. /// /// @lib /// @sn font:%s heightOf:%s /// /// @class Font /// @method TextHeight function TextHeight(theFont: Font; const theText: String): Longint; overload; /// Returns the font alignment for the passed in character (l = left. r = right, c = center). /// /// @lib function TextAlignmentFrom(const str: String): FontAlignment; //--------------------------------------------------------------------------- // Draw Text - using font //--------------------------------------------------------------------------- /// Draws the text at the specified point using the color and font indicated. /// /// @lib /// @sn drawText:%s color:%s font:%s x:%s y:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; theFont: Font; x, y: Single); overload; /// Draws the text at the specified point using the color and font indicated. /// /// @lib DrawTextWithFontNamed /// @sn drawText:%s color:%s fontNamed:%s x:%s y:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; const name: String; x, y: Single); overload; /// Draws theText at the specified point using the color and font indicated. /// /// @lib DrawTextWithFontNamedSize /// @sn drawText:%s color:%s fontNamed:%s size:%s x:%s y:%s procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x, y: Single); overload; /// Draws the text at the specified x,y location using the color, font, and options indicated. /// /// @lib DrawTextOpts /// @sn drawText:%s color:%s font:%s atX:%s y:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; theFont: Font; x, y: Single; const opts: DrawingOptions); overload; /// Draws the text at the specified x,y location using the color, font, and options indicated. /// /// @lib DrawTextWithFontNamedOpts /// @sn drawText:%s color:%s fontNamed:%s atX:%s y:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; const name: String; x, y: Single; const opts: DrawingOptions); overload; /// Draws the text at the specified x,y location using the color, font, and options indicated. /// /// @lib DrawTextWithFontNamedAndSizeOpts /// @sn drawText:%s color:%s fontNamed:%s size:%s atX:%s y:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x, y: Single; const opts: DrawingOptions); overload; /// Draws the text onto the bitmap using the color and font indicated, then returns the bitmap created. /// Drawing text is a slow operation, and drawing it to a bitmap, then drawing the bitmap to screen is a /// good idea if the text does not change frequently. /// /// @lib DrawTextToBitmapAtPointWithFontNamedAndSize /// @sn drawTextFont:%s string:%s textColor:%s backgroundColor:%s /// @doc_details function DrawTextToBitmap(font: Font; const str: String; clrFg, backgroundColor : Color) : Bitmap; //--------------------------------------------------------------------------- // Draw Text in an area //--------------------------------------------------------------------------- /// Draws the text in the specified rectangle using the fore and back colors, and the font indicated. /// /// @lib DrawTextInRect /// @sn drawText:%s textColor:%s backColor:%s font:%s align:%s inRect:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle); overload; /// Draws the text in the specified rectangle using the fore and back colors, and the font indicated. /// /// @lib DrawTextInRectWithFontNamed /// @sn drawText:%s textColor:%s backColor:%s fontNamed:%s align:%s inRect:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; align: FontAlignment; const area: Rectangle); overload; /// Draws theText in the specified rectangle using the fore and back colors, and the font indicated. /// /// @lib DrawTextInRectWithFontNamedAndSize /// @sn drawText:%s textColor:%s backColor:%s fontNamed:%s size:%s align:%s inRect:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle); overload; /// Draws the text in the rectangle using the fore and back colors, font and options indicated. /// /// @lib DrawTextInRectOpts /// @sn drawText:%s textColor:%s backColor:%s font:%s align:%s in:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; /// Draws the text in the rectangle using the fore and back colors, font and options indicated. /// /// @lib DrawTextInRectWithFontNamedOpts /// @sn drawText:%s textColor:%s backColor:%s fontNamed:%s align:%s in:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; /// Draws the text in the rectangle using the fore and back colors, font and options indicated. /// /// @lib DrawTextInRectWithFontNamedAndSizeOpts /// @sn drawText:%s textColor:%s backColor:%s fontNamed:%s size:%s align:%s in:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; //--------------------------------------------------------------------------- // Draw Text - without font //--------------------------------------------------------------------------- /// Draws text using a simple bitmap font that is built into SwinGame. /// /// @lib DrawSimpleText /// @sn drawText:%s color:%s x:%s y:%s procedure DrawText(const theText: String; textColor: Color; x, y: Single); overload; /// Draws text using a simple bitmap font that is built into SwinGame. /// /// @lib DrawSimpleTextOpts /// @sn drawText:%s color:%s atX:%s y:%s opts:%s /// @doc_details procedure DrawText(const theText: String; textColor: Color; x, y: Single; const opts: DrawingOptions); overload; /// /// @lib DrawFramerateWithSimpleFont /// @sn drawFramerateAtX:%s y:%s procedure DrawFramerate(x, y: Single); overload; //============================================================================= implementation uses SysUtils, Classes, stringhash, sgTrace, sgBackendTypes, // libsrc sgUtils, sgGeometry, sgGraphics, sgCamera, sgShared, sgResources, sgImages, sgDriverText, sgDrawingOptions; //============================================================================= const EOL = LineEnding; // from sgShared var _Fonts: TStringHash; //---------------------------------------------------------------------------- function LoadFont(const fontName: String; size: Longint): Font; begin result := LoadFontNamed(FontNameFor(fontName, size), fontName, size); end; procedure _DoFreeFont(var fontToFree: Font); var fp: FontPtr; begin fp := ToFontPtr(fontToFree); if Assigned(fp) then begin {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'After calling free notifier'); {$ENDIF} try {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'Before calling close font'); {$ENDIF} CallFreeNotifier(fontToFree); TextDriver.CloseFont(fp); fp^.id := NONE_PTR; Dispose(fp); fontToFree := nil; {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'At end of free font'); {$ENDIF} except RaiseException('Unable to free the specified font'); exit; end; end; end; procedure FreeFont(var fontToFree: Font); var fp: FontPtr; begin fp := ToFontPtr(fontToFree); if Assigned(fp) then ReleaseFont(fp^.name); fontToFree := nil; end; //---------------------------------------------------------------------------- function LoadFontNamed(const name, filename: String; size: Longint): Font; var obj: tResourceContainer; fnt: FontPtr; function _DoLoadFont(const fontName: String; size: Longint): Font; var filename: String; originalFilename: String; begin originalFilename := ''; {$IFDEF TRACE} TraceEnter('sgText', '_DoLoadFont(', fontName + ' ' + IntToStr(size)); {$ENDIF} filename := fontName; if not FileExists(filename) then begin filename := PathToResource(filename, FontResource); if not FileExists(filename) then begin originalFilename := filename; filename := filename + '.ttf'; if not FileExists(filename) then begin RaiseWarning('Unable to locate font ' + fontName + ' at ' + originalFilename); result := nil; exit; end; end; end; {$IFDEF TRACE} TraceIf(tlInfo, 'sgText', 'Info', '_DoLoadFont', 'About to load font from driver'); {$ENDIF} result := TextDriver.LoadFont(name, filename, size); {$IFDEF TRACE} TraceExit('sgText', '_DoLoadFont = ' + HexStr(result) ); {$ENDIF} end; begin {$IFDEF TRACE} TraceEnter('sgText', 'LoadFontNamed(', name + ' ' + IntToStr(size)); {$ENDIF} if _Fonts.containsKey(name) then begin result := FontNamed(name); {$IFDEF TRACE} TraceExit('sgText', 'Exit LoadFontNamed = ' + HexStr(result)); {$ENDIF} exit; end; fnt := _DoLoadFont(filename, size); if Assigned(fnt) then begin obj := tResourceContainer.Create(fnt); if not _Fonts.setValue(name, obj) then raise Exception.create('Error loaded Font resource - ' + name); end; result := fnt; {$IFDEF TRACE} TraceExit('sgText', 'LoadFontNamed = ' + HexStr(result)); {$ENDIF} end; function HasFont(const name: String): Boolean; begin result := _Fonts.containsKey(name); end; function FontNameFor(const fontName: String; size: Longint): String; begin result := fontName + '|' + IntToStr(size); end; function FontNamed(const name: String; size: Longint): Font; var filename: String; begin result := FontNamed(FontNameFor(name, size)); if (result = nil) then begin filename := PathToResource(name, FontResource); if FileExists(name) or FileExists(filename) then begin result := LoadFontNamed(name, name, size); end end; end; function FontNamed(const name: String): Font; var tmp : TObject; begin tmp := _Fonts.values[name]; if assigned(tmp) then result := Font(tResourceContainer(tmp).Resource) else result := nil; end; procedure ReleaseFont(const name: String); var fnt: Font; begin fnt := FontNamed(name); if Assigned(fnt) then begin _Fonts.remove(name).free(); _DoFreeFont(fnt); end; end; procedure ReleaseAllFonts(); begin ReleaseAll(_Fonts, @ReleaseFont); end; //---------------------------------------------------------------------------- procedure FontSetStyle(font: Font; value: FontStyle); var fp: FontPtr; begin fp := ToFontPtr(font); if not Assigned(fp) then begin RaiseWarning('No font supplied to FontSetStyle'); exit; end; //TTF_SetFontStyle(font^.fptr, Longint(value)); TextDriver.SetFontStyle(fp, value); end; function FontFontStyle(font: Font): FontStyle; var fp: FontPtr; begin fp := ToFontPtr(font); result := NormalFont; if not Assigned(fp) then begin RaiseWarning('No font supplied to FontFontStyle'); exit; end; result := TextDriver.GetFontStyle(fp); end; function IsSet(toCheck, checkFor: FontAlignment): Boolean; overload; begin result := (Longint(toCheck) and Longint(checkFor)) = Longint(checkFor); end; // // Converts a string into an array of lines. // Updates width and height so that the values are sufficient to create // a bitmap that will surround these with the given font. // -- note initial values for width and height need to be supplied. // function ToLineArray(str: String; font: FontPtr; var width, height: Longint): StringArray; var n, i, w, h, newHeight, baseHeight: Longint; subStr: String; begin // Break the String into its lines: SetLength(result, 0); n := -1; i := 0; newHeight := 0; // get a height value to use for each empty line TextDriver.SizeOfText(font, 'I', w, baseHeight); while n <> 0 do // n = position in string begin // Get until either "\n" or "\0": n := Pos(eol, str); //Copy all except EOL if n = 0 then subStr := str // no newlines else if n = 1 then subStr := '' // no text then new line else subStr := Copy(str, 1, n - 1); // a new line... copy to new string if n <> 0 then // there was some substr copied... begin //Remove the line from the original string str := Copy( str, n + Length(eol), Length(str) ); end; //Store in the lines array i := i + 1; SetLength(result, i); result[i - 1] := subStr; w := 0; // Get the size of the rendered text. if Length(subStr) > 0 then begin TextDriver.SizeOfText(font, subStr, w, h); newHeight += h; end else begin newHeight += baseHeight; end; if w > width then width := w; end; // Length(result) = Number of Lines. // we assume that height is the same for all lines. // newHeight += (Length(result) - 1) * TextDriver.LineSkip( font ); if newHeight > height then height := newHeight; end; /// This function prints "str" with font "font" and color "clrFg" /// * onto a rectangle of color "clrBg". /// * It does not pad the text. procedure PrintStrings(dest: Pointer; font: FontPtr; const str: String; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment) ; var lineSkip, width, height: Longint; lines: StringArray; i, w, h: Longint; x, y: Single; isWindow: Boolean; begin // If there's nothing to draw, return NULL if (Length(str) = 0) or (font = nil) then exit; if PtrKind(dest) = WINDOW_PTR then isWindow := true else isWindow := false; // Get basic metrics lineSkip := TextDriver.LineSkip( font ); width := Round(rc.width); height := 0; lines := ToLineArray(str, font, width, height); if (width <= 0) or (height <= 0) then exit; if (rc.width < 0) or (rc.height < 0) then begin rc.width := width; rc.height := height; end; // Clip bitmap if isWindow then PushClip(Window(dest), rc) else PushClip(Bitmap(dest), rc); x := rc.x; y := 0; // Actually render the text: for i := 0 to High(lines) do begin // Skip empty lines if (Length(lines[i]) = 0) or (lines[i] = ' ') then continue; // This lines metrics w := 0; h := 0; TextDriver.SizeOfText(font, lines[i], w, h); y := rc.y + i * lineSkip; if y - rc.y > rc.height then break; // drawing lines outside box // Determine position for line if IsSet(flags, AlignCenter) then begin x := rc.x + rc.width / 2 - w div 2; end else if IsSet(flags, AlignRight) then begin x := rc.x + rc.width - w; end; // if its left there is nothing to change... // Render the current line. TextDriver.PrintStrings(dest, font, lines[i], RectangleFrom(x, y, w, h), clrFg, clrBg, flags); end; if isWindow then PopClip(Window(dest)) else PopClip(Bitmap(dest)); end; function DrawTextToBitmap(font: Font; const str: String; clrFg, backgroundColor : Color) : Bitmap; var resultBitmap : Bitmap; bitmapSize : Rectangle; w, h: Longint; fp: FontPtr; begin fp := ToFontPtr(font); result := nil; // If there's nothing to draw, return NULL if (Length(str) = 0) or (fp = nil) then exit; bitmapSize.x := 0; bitmapSize.y := 0; w := 0; h := 0; ToLineArray(str, fp, w, h); bitmapSize.width := w; bitmapSize.height := h; //WriteLn(bitmapSize.width, 'x', bitmapSize.height); resultBitmap := CreateBitmap(Round(bitmapSize.width), Round(bitmapSize.height)); ClearSurface(resultBitmap, backgroundColor); PrintStrings(resultBitmap, fp, str, bitmapSize, clrFg, ColorTransparent, AlignLeft); result := resultBitmap; end; //---------------------------------------------------------------------------- // Draw Text //---------------------------------------------------------------------------- procedure DrawText(const theText: String; textColor: Color; x, y: Single; const opts: DrawingOptions); overload; begin if not Assigned(opts.dest) then exit; XYFromOpts(opts, x, y); TextDriver.stringColor(opts.dest, x, y, theText, textColor); end; procedure DrawText(const theText: String; textColor: Color; x, y: Single); overload; begin DrawText(theText, textColor, x, y, OptionDefaults()); end; //---------------------------------------------------------------------------- // Draw Text using font //---------------------------------------------------------------------------- procedure DrawText(const theText: String; textColor: Color; theFont: Font; x, y: Single; const opts: DrawingOptions); overload; var rect: Rectangle; fp: FontPtr; begin fp := ToFontPtr(theFont); if not Assigned(fp) then exit; if not Assigned(opts.dest) then begin RaiseWarning('Cannot draw text, as no destination was supplied'); exit; end; if Length(theText) <= 0 then exit; XYFromOpts(opts, x, y); rect.x := x; rect.y := y; rect.width := -1; //TextWidth(theFont, theText); // + 2; rect.height := -1; //TextHeight(theFont, theText); // + 2; PrintStrings(opts.dest, fp, theText, rect, textColor, ColorTransparent, AlignLeft); end; procedure DrawText(const theText: String; textColor: Color; theFont: Font; x, y: Single); overload; begin DrawText(theText, textColor, theFont, x, y, OptionDefaults()); end; procedure DrawText(const theText: String; textColor: Color; const name: String; x, y: Single); overload; begin DrawText(theText, textColor, FontNamed(name), x, y, OptionDefaults()); end; procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x, y: Single); overload; begin DrawText(theText, textColor, LoadFontNamed(FontNameFor(name, size), name, size), x, y, OptionDefaults()); end; procedure DrawText(const theText: String; textColor: Color; const name: String; x, y: Single; const opts: DrawingOptions); overload; begin DrawText(theText, textColor, FontNamed(name), x, y, opts); end; procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x, y: Single; const opts: DrawingOptions); overload; begin DrawText(theText, textColor, LoadFontNamed(FontNameFor(name, size), name, size), x, y, opts); end; //---------------------------------------------------------------------------- // Draw Text in Area //---------------------------------------------------------------------------- procedure DrawText(const theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; var fp: FontPtr; begin fp := ToFontPtr(theFont); if not Assigned(fp) then exit; if not Assigned(opts.dest) then begin RaiseWarning('Cannot draw text, as no destination was supplied'); exit; end; if Length(theText) <= 0 then exit; if (area.width <= 0) or (area.height <= 0) then exit; PrintStrings(opts.dest, fp, theText, area, textColor, backColor, align); end; procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; begin DrawText(theText, textColor, backColor, FontNamed(name), align, area, opts); end; procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload; begin DrawText(theText, textColor, backColor, LoadFontNamed(FontNameFor(name, size), name, size), align, area, opts); end; procedure DrawText(const theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle); overload; begin DrawText(theText, textColor, backColor, theFont, align, area, OptionDefaults()); end; procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; align: FontAlignment; const area: Rectangle); overload; begin DrawText(theText, textColor, backColor, FontNamed(name), align, area, OptionDefaults()); end; procedure DrawText(const theText: String; textColor, backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle); overload; begin DrawText(theText, textColor, backColor, LoadFontNamed(FontNameFor(name, size), name, size), align, area, OptionDefaults()); end; //---------------------------------------------------------------------------- // Text metrics //---------------------------------------------------------------------------- /// Calculates the width of a string when drawn with a given font. function TextWidth(theFont: Font; const theText: String): Longint; overload; var height: Longint; //SizeText returns both... store and ignore height fp: FontPtr; begin fp := ToFontPtr(theFont); result := 0; height := 0; if length(theText) = 0 then exit; if not Assigned(fp) then exit; ToLineArray(theText, fp, result, height); end; /// Calculates the height of a string when drawn with a given font. function TextHeight(theFont: Font; const theText: String): Longint; overload; var width: Longint; //SizeText returns both... store and ignore w fp: FontPtr; begin fp := ToFontPtr(theFont); result := 0; width := 0; if length(theText) = 0 then exit; if not Assigned(fp) then exit; ToLineArray(theText, fp, width, result); end; procedure DrawFramerate(x, y: Single); overload; var textColor : Color; average, highest, lowest : String; begin //Draw framerates CalculateFramerate(average, highest, lowest, textColor); DrawText('FPS: (' + highest + ', ' + lowest + ') ' + average, textColor, x + 2, y + 2, OptionToScreen()) end; function TextAlignmentFrom(const str: String): FontAlignment; var ch: Char; tstr: String; begin tstr := trim(str); if length(tstr) > 0 then ch := tstr[1] else ch := 'l'; case ch of 'c', 'C': result := AlignCenter; 'r', 'R': result := AlignRight; else result := AlignLeft; end; end; //============================================================================= //============================================================================= initialization begin InitialiseSwinGame(); _Fonts := TStringHash.Create(False, 1024); if TextDriver.Init() = -1 then begin begin RaiseException('Error opening font library. ' + TextDriver.GetError()); exit; end; end; end; //============================================================================= finalization begin ReleaseAllFonts(); FreeAndNil(_Fonts); TextDriver.Quit(); end; end.
{*****************************************************} { CRUD orientado a objetos, com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { set/2019 } {*****************************************************} unit U_Conexao; interface uses System.Classes, Vcl.Forms, Data.DB, Data.SqlExpr, Data.DBXOracle, System.SysUtils; type TConexao = class(TComponent) private { private declarations } FConnection: TSQLConnection; class var FInstance: TConexao; protected { protected declarations } public { public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetInstance: TConexao; function GetConnection: TSQLConnection; end; implementation { TConexao } constructor TConexao.Create(AOwner: TComponent); begin inherited Create(AOwner); FConnection := TSQLConnection.Create(Self); try FConnection.LoginPrompt := False; FConnection.DriverName := 'Oracle'; FConnection.Params.Values['VendorLib'] := 'oci.dll'; FConnection.Params.Values['LibraryName'] := 'dbxora.dll'; FConnection.Params.Values['DataBase'] := 'xe'; FConnection.Params.Values['User_Name'] := 'SYSTEM'; FConnection.Params.Values['Password'] := '123456'; FConnection.Params.Values['Decimal Separator'] := FormatSettings.DecimalSeparator; //evita problemas com campos float FConnection.Connected := True; except on E: Exception do raise Exception.CreateFmt('Erro ao conectar com o banco de dados: %s', [E.Message]); end; end; destructor TConexao.Destroy; begin FConnection.Free; inherited; end; function TConexao.GetConnection: TSQLConnection; begin Result := FConnection; end; class function TConexao.GetInstance: TConexao; begin if not Assigned(FInstance) then FInstance := TConexao.Create(Application); Result := FInstance; end; end.
unit uPctPetRegistryFch; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentButtonFch, mrConfigFch, DB, XiButton, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxDBEdit, mrDBEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, StdCtrls; type TPctPetRegistryFch = class(TParentButtonFch) edtRegistryNum: TmrDBEdit; scRegistry: TmrDBSuperCombo; procedure ConfigFchAfterStart(Sender: TObject); procedure ConfigFchBeforeApplyChanges(Sender: TObject; var Apply: Boolean); private { Private declarations } public { Public declarations } end; implementation uses uDMPetCenter, uDMPet, uParentCustomFch, mrMsgBox, uSystemTypes; {$R *.dfm} procedure TPctPetRegistryFch.ConfigFchAfterStart(Sender: TObject); begin inherited; scRegistry.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Registry;'); end; procedure TPctPetRegistryFch.ConfigFchBeforeApplyChanges(Sender: TObject; var Apply: Boolean); begin inherited; if (ActionType = atAppend) and DMPet.PetCenterConn.AppServer.PetRegistryExist(DataSet.FieldByName('IDPet').AsInteger, DataSet.FieldByName('IDRegistry').AsInteger) then begin MsgBox('Puppy already has an entry for this registry', vbInformation + vbOKOnly); Apply := False; Exit; end; DataSet.FieldByName('Registry').Value := scRegistry.EditingText; end; initialization RegisterClass(TPctPetRegistryFch); end.
unit Unit_Setup_Consts; interface resourcestring TFZ_SETUP_Caption = 'Властивості системи'; TFZ_SETUP_LabelShortName_Caption = 'Коротка назва:'; TFZ_SETUP_LabelFullName_Caption = 'Повна назва:'; TFZ_SETUP_LabelOkpo_Caption = 'ОКПО:'; TFZ_SETUP_LabelTown_Caption = 'Місто:'; TFZ_SETUP_LabelAddress_Caption = 'Адреса:'; TFZ_SETUP_LabelDirector_Caption = 'П.І.Б.:'; TFZ_SETUP_LabelTinDirector_Caption = 'Ід. код:'; TFZ_SETUP_LabelTelDirector_Caption = 'Телефон:'; TFZ_SETUP_LabelNameManeg_Caption = 'П.І.Б.:'; TFZ_SETUP_LabelGlBuhg_Caption = ''; TFZ_SETUP_LabelGlBuhgTin_Caption = 'Ід. код:'; TFZ_SETUP_LabelGlBuhgTel_Caption = 'Телефон:'; TFZ_SETUP_LabelCommonTel_Caption = 'Телефон підприємства:'; TFZ_SETUP_PageNameFirm_Caption = 'Підприємство'; TFZ_SETUP_PageAddress_Caption = 'Адреса'; TFZ_SETUP_PageDirector_Caption = 'Директор'; TFZ_SETUP_PageGlBuhg_Caption = 'Головний бухгалтер'; TFZ_SETUP_PageTerms_Caption = 'Періоди'; TFZ_SETUP_PagePriznak_Caption = 'Признаки'; TFZ_SETUP_P_Genary1_Caption = 'Питати дату до розрахунка'; TFZ_SETUP_P_Genary2_Caption = 'Друкувати дату у довідці на субсидію'; TFZ_SETUP_P_Genary3_Caption = 'При роботі 15 днів необлагаемый минимум не отбрасывается'; TFZ_SETUP_P_Genary4_Caption = 'Формування проміжних відомостей: термінові розрахунки не утримуються'; TFZ_SETUP_P_Genary5_Caption = 'Не враховувати копійки подохідного налога зовнішних сумісників'; TFZ_SETUP_P_Genary6_Caption = 'Лікарняні листи сплачубться лише за основним місцем роботи'; implementation end.
unit uEditForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxSpinEdit, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookAndFeelPainters, cxButtons, ConstSumsDM,ZTypes,ZMessages, Unit_ZGlobal_Consts, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc, Ibase, ZProc, Dates; type TEditForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; CancelBtn: TcxButton; Label6: TLabel; SumEdit: TcxMaskEdit; GroupBox2: TGroupBox; Label4: TLabel; YearEndEdit: TcxSpinEdit; Label5: TLabel; MonthEndEdit: TcxSpinEdit; NoEndCheckBox: TCheckBox; GroupBox3: TGroupBox; Label2: TLabel; YearBegEdit: TcxSpinEdit; Label3: TLabel; MonthBegEdit: TcxSpinEdit; OkBtn: TcxButton; ConstTypeEdit: TcxTextEdit; DB: TpFIBDatabase; StProc: TpFIBStoredProc; DefaultTransaction: TpFIBTransaction; procedure NoEndCheckBoxClick(Sender: TObject); procedure OkBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure YearBegEditPropertiesChange(Sender: TObject); private DM:TMainDM; FEditMode:TZControlFormStyle; PLanguageIndex:byte; PDb_handle:TISC_DB_HANDLE; PId, CPId, ye, me:integer; myYear, myMonth, myDay : word; public constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; EditMode:TZControlFormStyle;Id:integer;ConstType:string;CId:integer);reintroduce; property Id:integer read PId; end; var EditForm:TEditForm; implementation {$R *.dfm} constructor TEditForm.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; EditMode:TZControlFormStyle;Id:integer;ConstType:string;CId:integer); begin inherited Create(AOwner); FEditMode:=EditMode; PLanguageIndex:= LanguageIndex; PId:=Id; PDB_Handle:= DB_Handle; ConstTypeEdit.Text:=ConstType; CPId:=CId; case FEditMode of zcfsInsert: begin Caption:=Caption_Insert[PLanguageIndex]; DecodeDate(Date, myYear, myMonth, myDay); YearBegEdit.Value:=myYear; YearEndEdit.Value:=myYear; MonthEndEdit.Value:=myMonth; MonthBegEdit.Value:=myMonth; end; zcfsUpdate: begin with StProc do begin Caption:=Caption_Update[PLanguageIndex]; DB.Handle := PDb_handle; StoredProcName:='Z_CONST_SUMS_S_BY_ID'; Transaction.StartTransaction; Prepare; ParamByName('IN_ID').AsInteger:= PId; ExecProc; YearBegEdit.Value:=ParamByName('YEAR_BEG').AsInteger; SumEdit.Text:=FloatToStr(ParamByName('VALUE_SUM').AsFloat); MonthBegEdit.Value:=ParamByName('MONTH_BEG').AsInteger; ye:=ParamByName('YEAR_END').AsInteger; me:=ParamByName('MONTH_END').AsInteger; Transaction.Commit; if ye=2078 then begin if me=03 then begin NoEndCheckBoxClick(self); NoEndCheckBox.Checked:=True; MonthEndEdit.Value:=MonthBegEdit.Value; YearEndEdit.Value:=YearBegEdit.Value; NoEndCheckBox.State:=cbChecked; end; end else begin MonthEndEdit.Value:=me; YearEndEdit.Value:=ye; end; end; end; end end; procedure TEditForm.OkBtnClick(Sender: TObject); var YearEnd, MonthEnd:Integer; kod_setup_b:integer; kod_setup_e:integer; begin if (SumEdit.Text='') then begin ZShowMessage('Помилка!','Не заданє поле Сумма!',mtWarning,[mbOk]); SumEdit.SetFocus; end else begin if (NoEndCheckBox.Checked) then begin YearEnd:=2078; MonthEnd:=3; end else begin YearEnd:=YearEndEdit.Value; MonthEnd:=MonthEndEdit.Value; end; kod_setup_b:=PeriodToKodSetup(YearBegEdit.Value,MonthBegEdit.Value); kod_setup_e:=PeriodToKodSetup(YearEnd,MonthEnd); if(kod_setup_e<kod_setup_b)then begin ZShowMessage('Помилка!','Не вірно вказано період',mtWarning,[mbOk]); YearBegEdit.SetFocus; end else begin with StProc do try case FEditMode of zcfsInsert: begin DB.Handle := PDb_handle; StoredProcName:='Z_CONST_SUMS_I'; Transaction.StartTransaction; Prepare; ParamByName('ID_CONST_TYPE').AsInteger:= PId; ParamByName('YEAR_BEG').AsInteger:=YearBegEdit.Value; ParamByName('VALUE_SUMM').AsFloat:=StrToFloat(SumEdit.Text); ParamByName('YEAR_END').AsInteger:=YearEnd; ParamByName('MONTH_END').AsInteger:=MonthEnd; ParamByName('MONTH_BEG').AsInteger:=MonthBegEdit.Value; ExecProc; Transaction.Commit; end; zcfsUpdate: begin DB.Handle := PDb_handle; StoredProcName:='Z_CONST_SUMS_U'; Transaction.StartTransaction; Prepare; ParamByName('ID').AsInteger:= PId; ParamByName('ID_CONST_TYPE').AsInteger:=CpId; ParamByName('YEAR_BEG').AsInteger:=YearBegEdit.Value; ParamByName('VALUE_SUM').AsFloat:=StrToFloat(SumEdit.Text); ParamByName('YEAR_END').AsInteger:=YearEnd; ParamByName('MONTH_END').AsInteger:=MonthEnd; ParamByName('MONTH_BEG').AsInteger:=MonthBegEdit.Value; ExecProc; Transaction.Commit; end; end; except on e:exception do begin ZShowMessage('Перетин строків дії констант!','Перетин строків дії констант!',mtError,[mbOk]); Transaction.Rollback; end; end; ModalResult:=mrOk; end; end; end; procedure TEditForm.NoEndCheckBoxClick(Sender: TObject); begin if (NoEndCheckBox.Checked) then begin YearEndEdit.Enabled:=False; MonthEndEdit.Enabled:=False; end else begin YearEndEdit.Enabled:=True; MonthEndEdit.Enabled:=True; end end; procedure TEditForm.CancelBtnClick(Sender: TObject); begin Close; end; procedure TEditForm.YearBegEditPropertiesChange(Sender: TObject); var kod_setup_b:integer; kod_setup_e:integer; begin kod_setup_b:=PeriodToKodSetup(YearBegEdit.Value,MonthBegEdit.Value); kod_setup_e:=PeriodToKodSetup(YearEndEdit.Value,MonthEndEdit.Value); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [FISCAL_PARAMETRO] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit FiscalParametroVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TFiscalParametroVO = class(TVO) private FID: Integer; FID_FISCAL_ESTADUAL_PORTE: Integer; FID_FISCAL_ESTADUAL_REGIME: Integer; FID_FISCAL_MUNICIPAL_REGIME: Integer; FID_EMPRESA: Integer; FVIGENCIA: String; FDESCRICAO_VIGENCIA: String; FCRITERIO_LANCAMENTO: String; FAPURACAO: String; FMICROEMPREE_INDIVIDUAL: String; FCALC_PIS_COFINS_EFD: String; FSIMPLES_CODIGO_ACESSO: String; FSIMPLES_TABELA: String; FSIMPLES_ATIVIDADE: String; FPERFIL_SPED: String; FAPURACAO_CONSOLIDADA: String; FSUBSTITUICAO_TRIBUTARIA: String; FFORMA_CALCULO_ISS: String; //Transientes published property Id: Integer read FID write FID; property IdFiscalEstadualPorte: Integer read FID_FISCAL_ESTADUAL_PORTE write FID_FISCAL_ESTADUAL_PORTE; property IdFiscalEstadualRegime: Integer read FID_FISCAL_ESTADUAL_REGIME write FID_FISCAL_ESTADUAL_REGIME; property IdFiscalMunicipalRegime: Integer read FID_FISCAL_MUNICIPAL_REGIME write FID_FISCAL_MUNICIPAL_REGIME; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property Vigencia: String read FVIGENCIA write FVIGENCIA; property DescricaoVigencia: String read FDESCRICAO_VIGENCIA write FDESCRICAO_VIGENCIA; property CriterioLancamento: String read FCRITERIO_LANCAMENTO write FCRITERIO_LANCAMENTO; property Apuracao: String read FAPURACAO write FAPURACAO; property MicroempreeIndividual: String read FMICROEMPREE_INDIVIDUAL write FMICROEMPREE_INDIVIDUAL; property CalcPisCofinsEfd: String read FCALC_PIS_COFINS_EFD write FCALC_PIS_COFINS_EFD; property SimplesCodigoAcesso: String read FSIMPLES_CODIGO_ACESSO write FSIMPLES_CODIGO_ACESSO; property SimplesTabela: String read FSIMPLES_TABELA write FSIMPLES_TABELA; property SimplesAtividade: String read FSIMPLES_ATIVIDADE write FSIMPLES_ATIVIDADE; property PerfilSped: String read FPERFIL_SPED write FPERFIL_SPED; property ApuracaoConsolidada: String read FAPURACAO_CONSOLIDADA write FAPURACAO_CONSOLIDADA; property SubstituicaoTributaria: String read FSUBSTITUICAO_TRIBUTARIA write FSUBSTITUICAO_TRIBUTARIA; property FormaCalculoIss: String read FFORMA_CALCULO_ISS write FFORMA_CALCULO_ISS; //Transientes end; TListaFiscalParametroVO = specialize TFPGObjectList<TFiscalParametroVO>; implementation initialization Classes.RegisterClass(TFiscalParametroVO); finalization Classes.UnRegisterClass(TFiscalParametroVO); end.
unit ibSHProposalHintRetriever; interface uses Classes, SysUtils, SHDesignIntf, ibSHDesignIntf, ibSHSQLs, ibSHValues, ibSHConsts, ibSHMessages, pSHIntf; type TibBTProposalHintRetriever = class(TSHComponent, IpSHProposalHintRetriever, ISHDemon) private FCodeNormalizer: IibSHCodeNormalizer; FPriorDatabase: IInterface; FPriorObjectName: string; FPriorHint: string; FPriorResult: Boolean; FPriorIsReturningValuesSection: Boolean; function NormilizeName(const AObjectName: string): string; public procedure Notification(AComponent: TComponent; Operation: TOperation); override; class function GetClassIIDClassFnc: TGUID; override; {IpSHProposalHintRetriever} procedure AfterCompile(Sender: TObject); function GetHint(const AObjectName: string; var AHint: string; IsReturningValuesSection: Boolean): Boolean; end; implementation procedure Register; begin SHRegisterComponents([TibBTProposalHintRetriever]); end; { TibBTProposalHintRetriever } function TibBTProposalHintRetriever.NormilizeName( const AObjectName: string): string; begin if not Assigned(FCodeNormalizer) then if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, FCodeNormalizer) then ReferenceInterface(FCodeNormalizer, opInsert); if Assigned(FCodeNormalizer) then Result := FCodeNormalizer.SourceDDLToMetadataName(AObjectName) else Result := AObjectName; end; procedure TibBTProposalHintRetriever.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FCodeNormalizer) then FCodeNormalizer := nil; if AComponent.IsImplementorOf(FPriorDatabase) then FPriorDatabase := nil; end; inherited Notification(AComponent, Operation); end; class function TibBTProposalHintRetriever.GetClassIIDClassFnc: TGUID; begin Result := IpSHProposalHintRetriever; end; procedure TibBTProposalHintRetriever.AfterCompile(Sender: TObject); begin // // В Sender приезжает экземпляр TibBTDBObject // ReferenceInterface(FPriorDatabase, opRemove); FPriorDatabase := nil; FPriorObjectName := ''; FPriorHint := ''; FPriorResult := False; FPriorIsReturningValuesSection := False; end; function TibBTProposalHintRetriever.GetHint(const AObjectName: string; var AHint: string; IsReturningValuesSection: Boolean): Boolean; var vDatabase: IibSHDatabase; vObjectGUID: TGUID; vClassIIDList: TStrings; vIsReturningValuesSection: Integer; vSQL_TEXT: string; vComponentClass: TSHComponentClass; vDomain: IibSHDomain; vFunction: IibSHFunction; vDDLGenerator: IibSHDDLGenerator; vDomainComponent: TSHComponent; vFunctionComponent: TSHComponent; vDDLGeneratorComponent: TSHComponent; vObjectName: string; I: Integer; begin Result := False; if Supports(Designer.CurrentComponent, IibSHDatabase, vDatabase) then begin vObjectName := NormilizeName(AObjectName); if (FPriorDatabase = vDatabase) and (FPriorIsReturningValuesSection = IsReturningValuesSection) and SameText(vObjectName, FPriorObjectName) then begin Result := FPriorResult; AHint := FPriorHint; end else begin if FPriorDatabase <> vDatabase then begin ReferenceInterface(FPriorDatabase, opRemove); FPriorDatabase := nil; FPriorDatabase := vDatabase; ReferenceInterface(FPriorDatabase, opInsert); end; FPriorObjectName := vObjectName; FPriorIsReturningValuesSection := IsReturningValuesSection; vClassIIDList := vDatabase.GetSchemeClassIIDList(vObjectName); if vClassIIDList.Count > 0 then begin vObjectGUID := StringToGUID(vClassIIDList[0]); if IsEqualGUID(vObjectGUID, IibSHProcedure) then begin if IsReturningValuesSection then vIsReturningValuesSection := 1 else vIsReturningValuesSection := 0; if not vDatabase.ExistsPrecision then vSQL_TEXT := FormatSQL(SQL_GET_PROCEDURE_PARAMS1) else vSQL_TEXT := FormatSQL(SQL_GET_PROCEDURE_PARAMS3); vDDLGeneratorComponent := nil; vDomainComponent := nil; vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then vDDLGeneratorComponent := vComponentClass.Create(nil); try vComponentClass := Designer.GetComponent(IibSHDomain); if Assigned(vComponentClass) then begin vDomainComponent := vComponentClass.Create(nil); vDomainComponent.OwnerIID := vDatabase.InstanceIID; end; try if Assigned(vDDLGeneratorComponent) and Assigned(vDomainComponent) and Supports(vDDLGeneratorComponent, IibSHDDLGenerator, vDDLGenerator) and Supports(vDomainComponent, IibSHDomain, vDomain) and vDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [AObjectName, vIsReturningValuesSection], False) then begin AHint := ''; vDDLGenerator.GetDDLText(vDomain); while not vDatabase.DRVQuery.Eof do begin vDDLGenerator.SetBasedOnDomain(vDatabase.DRVQuery, vDomain, 'Domain'); if vDomain.DataType = 'BLOB' then AHint := AHint + Format(SParametersHintTemplate, [vDatabase.DRVQuery.GetFieldStrValue(0) + ' ' + vDomain.DataType]) else AHint := AHint + Format(SParametersHintTemplate, [vDatabase.DRVQuery.GetFieldStrValue(0) + ' ' + vDomain.DataTypeExt]); vDatabase.DRVQuery.Next; end; vDatabase.DRVQuery.Transaction.Commit; if Length(AHint) = 0 then AHint := Format(SParametersHintTemplate, [SNoParametersExpected]); Delete(AHint, Length(AHint) - 4, 5); AHint := AHint + '"'; Result := True; end; finally if Assigned(vDomain) then vDomain := nil; if Assigned(vDomainComponent) then vDomainComponent.Free; end; finally if Assigned(vDDLGenerator) then vDDLGenerator := nil; if Assigned(vDDLGeneratorComponent) then vDDLGeneratorComponent.Free; end; end else if IsEqualGUID(vObjectGUID, IibSHFunction) then begin vDDLGeneratorComponent := nil; vFunctionComponent := nil; vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then vDDLGeneratorComponent := vComponentClass.Create(nil); try vComponentClass := Designer.GetComponent(IibSHFunction); if Assigned(vComponentClass) then begin vFunctionComponent := vComponentClass.Create(nil); vFunctionComponent.OwnerIID := vDatabase.InstanceIID; end; try if Assigned(vDDLGeneratorComponent) and Assigned(vFunctionComponent) and Supports(vDDLGeneratorComponent, IibSHDDLGenerator, vDDLGenerator) and Supports(vFunctionComponent, IibSHFunction, vFunction) // and // vDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [AObjectName], False) then begin AHint := ''; vFunction.State := csSource; vFunction.Caption := AObjectName; vDDLGenerator.GetDDLText(vFunction); if vFunction.ReturnsArgument = 0 then for I := 1 to vFunction.Params.Count do AHint := AHint + Format(SParametersHintTemplate, [Trim(vFunction.GetParam(I).DataTypeExt)]) else for I := 0 to vFunction.Params.Count - 1 do if ((I + 1) <> vFunction.ReturnsArgument) then AHint := AHint + Format(SParametersHintTemplate, [Trim(vFunction.GetParam(I).DataTypeExt)]); if Length(AHint) = 0 then AHint := Format(SParametersHintTemplate, [SNoParametersExpected]); Delete(AHint, Length(AHint) - 4, 5); AHint := AHint + '"'; Result := True; end; finally if Assigned(vFunction) then vFunction := nil; if Assigned(vFunctionComponent) then vFunctionComponent.Free; end; finally if Assigned(vDDLGenerator) then vDDLGenerator := nil; if Assigned(vDDLGeneratorComponent) then vDDLGeneratorComponent.Free; end; end else if IsEqualGUID(vObjectGUID, IibSHTable) then begin if not vDatabase.ExistsPrecision then vSQL_TEXT := FormatSQL(SQL_GET_TABLE_FIELDS1) else vSQL_TEXT := FormatSQL(SQL_GET_TABLE_FIELDS3); vDDLGeneratorComponent := nil; vDomainComponent := nil; vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then vDDLGeneratorComponent := vComponentClass.Create(nil); try vComponentClass := Designer.GetComponent(IibSHDomain); if Assigned(vComponentClass) then begin vDomainComponent := vComponentClass.Create(nil); vDomainComponent.OwnerIID := vDatabase.InstanceIID; end; try if Assigned(vDDLGeneratorComponent) and Assigned(vDomainComponent) and Supports(vDDLGeneratorComponent, IibSHDDLGenerator, vDDLGenerator) and Supports(vDomainComponent, IibSHDomain, vDomain) and vDatabase.DRVQuery.ExecSQL(vSQL_TEXT, [AObjectName], False) then begin AHint := ''; vDDLGenerator.GetDDLText(vDomain); while not vDatabase.DRVQuery.Eof do begin vDDLGenerator.SetBasedOnDomain(vDatabase.DRVQuery, vDomain, 'Domain'); if vDomain.DataType = 'BLOB' then AHint := AHint + Format(SParametersHintTemplate, [vDatabase.DRVQuery.GetFieldStrValue(0) + ' ' + vDomain.DataType]) else AHint := AHint + Format(SParametersHintTemplate, [vDatabase.DRVQuery.GetFieldStrValue(0) + ' ' + vDomain.DataTypeExt]); vDatabase.DRVQuery.Next; end; vDatabase.DRVQuery.Transaction.Commit; if Length(AHint) = 0 then AHint := Format(SParametersHintTemplate, [SNoParametersExpected]); Delete(AHint, Length(AHint) - 4, 5); AHint := AHint + '"'; Result := True; end; finally if Assigned(vDomain) then vDomain := nil; if Assigned(vDomainComponent) then vDomainComponent.Free; end; finally if Assigned(vDDLGenerator) then vDDLGenerator := nil; if Assigned(vDDLGeneratorComponent) then vDDLGeneratorComponent.Free; end; end; end; FPriorHint := AHint; FPriorResult := Result; end;//not equal prior end; end; initialization Register; end.
PROGRAM DatingService (INPUT,OUTPUT,Datafile); {********************************************************************** Program Assignment 1 for Pascal 187 Author: Scott Janousek Duedate: Mon Feb 22, 1993 Username: [ScottJ] Instructor: Cris Pedregal Program Description: This program is software designed for the use of a computer dating service. Clients of both men and women are asked to input their specific data about themselves so that they may find a match. Questions which are given to the user include: name, sex, phone number, and degree of interest in 10 different fields of activities. Two people can then be compared by their DOI (Degree of Interest) in the following areas: photography, skydiving, philately, traveling, painting, reading, spelunking, gardening, hiking, and cooking. A match occurs if when clients have a DOI of 4 or greater in at least 6 common interests. If a match results then both of these users are matched and are designated as so. Otherwise no match is found. INPUT: the program prompts the user for : - Name, sex, Phone number, DOI in the following: 1 Photography 4 Traveling 7 Spelunking 10 Cooking 2 Skydiving 5 Painting 8 Gardening 3 Philately 6 Reading 9 Hiking OUTPUT: The program computes and prints out the following : - Either a match found with someone of the opposite sex - OR no match can be determined LIMITATIONS: [1] Max number of 50 clients in each sex [2] Information in Files may be incorrect **********************************************************************} CONST MaxClients = 50; { Maximum number of Clients } NewClient = 1; Unmatch = 2; ListMatch = 3; ListFree = 4; QuitProg = 5; ClientFile = 'CLIENTS.DAT'; { File to keep clients } TYPE FullName = packed array[1..20] of char; { Clients Name } Sextype = char; { Sex of Client } PhoneNumber = packed array[1..8] of char; DOI = integer; { Degree of Interest} InterestType = RECORD { Interests for Clients } Photo : DOI; { Photography } SkyDive : DOI; { SkyDiving } Philate : DOI; { Philately } Travel : DOI; { Traveling } Paint : DOI; { Painting } Read : DOI; { Reading } Spelunk : DOI; { Spelunking } Garden : DOI; { Gardening } Hike : DOI; { Hiking } Cook : DOI; { Cooking } END; ClientType = RECORD Gender : Sextype; Name : Fullname; Phone : PhoneNumber; Activity : InterestType; Match : Integer; END; Persontype = ARRAY [1..MaxClients] OF ClientType; MaleClient = ARRAY [1..MaxClients] OF ClientType; FemaleClient = ARRAY [1..MaxClients] OF ClientType; DOItype = SET OF 0..9; VAR DataFile : text; NumOfClients : integer; LastClient : integer; Option : integer; People : Persontype; Free : Boolean; Female : FemaleClient; Matched : Boolean; Male : MaleClient; i : integer; {*****************************************************************} FUNCTION GetUserInput : integer; VAR Userinput : char; number : integer; BEGIN { GetUserInput } REPEAT writeln; writeln(' MENU'); writeln; writeln('1. Add a New Client'); writeln('2. Unmatch a Member'); writeln('3. List Match'); writeln('4. Give a List of Free Clients'); writeln('5. Quit This Program'); writeln; write('=> '); readln(userinput); number:= ORD(userinput) - ORD('1') + 1; UNTIL (number >= NewClient) AND (number <= QuitProg); GetUserInput := number; END; { GetUserInput } PROCEDURE ReadClientInfo (VAR Datfile : text; VAR NumOfClients : Integer; VAR People : Persontype); PROCEDURE Read1Record (VAR Datfile : text; VAR Client : ClientType); BEGIN { Read1Record } Readln(Datfile, Client.Gender); Readln(Datfile, Client.Name); Readln(Datfile, Client.Phone); Readln(Datfile, Client.Activity.Photo); Readln(Datfile, Client.Activity.SkyDive); Readln(Datfile, Client.Activity.Philate); Readln(Datfile, Client.Activity.Travel); Readln(Datfile, Client.Activity.Paint); Readln(Datfile, Client.Activity.Read); Readln(Datfile, Client.Activity.Spelunk); Readln(Datfile, Client.Activity.Garden); Readln(Datfile, Client.Activity.Hike); Readln(Datfile, Client.Activity.Cook); Readln(Datfile, Client.Match); END; { Read1Record } BEGIN { ReadClientInfo } NumOfClients := 0; OPEN (Datfile, ClientFile, OLD); RESET(Datfile); Readln(Datfile); WHILE (Not EOF (Datfile)) AND (NumOfClients < MaxClients) DO BEGIN { Read the Client Records } Read1Record (Datfile, People [NumOfClients + 1]); NumOfClients := NumOfClients + 1; END; { Read the Client Records } LastClient := NumOfClients; END; { ReadClientInfo } PROCEDURE SortIntoGender (VAR NumOfClients: Integer; VAR Male: MaleClient; VAR Female: FemaleClient); VAR num : integer; BEGIN { SortIntoGender } num := 1; WHILE num <= NumOfClients DO BEGIN { Sort People into Gender } IF People [num].Gender = 'M' THEN BEGIN Male [num].Gender := People [num].Gender; Male [num].Name := People [num].Name; Male [num].Phone := People [num].Phone; Male [num].Activity := People [num].Activity; Male [num].Match := People [num].Match END ELSE BEGIN Female [num].Gender := People [num].Gender; Female [num].Name := People [num].Name; Female [num].Phone := People [num].Phone; Female [num].Activity := People [num].Activity; Female [num].Match := People [num].Match END; num := num + 1; END; { Sort People into their Gender } END; { SortIntoGender } PROCEDURE AddNewClient (VAR NumOfClients : Integer; VAR Clients : Persontype); VAR DOIchar : DOItype; ch : char; count : integer; BEGIN { AddNewClient } IF NumofClients >= MaxClients THEN writeln('Sorry, the Service is currently Full.') ELSE BEGIN { Add someone } NumOfClients := NumOfClients + 1; writeln; writeln; writeln('Add a NEW Client:'); writeln; writeln('Are you '); write('(M) a Male or (F) a Female : '); Readln(People [NumOfClients].gender); write('Please enter your Name : '); Readln(People [NumOfClients].name); write('What is your Phone Number : '); Readln(People [NumOfClients].phone); writeln; writeln; writeln('What is your Degree of Interest'); writeln('in the following Activities:'); writeln; writeln('Based on a scale of 0 to 9 ( 0 = No Interest, 9 = Deep Interest )'); writeln; write('Photography : '); Readln(People [NumOfClients].Activity.Photo); write('SkyDiving : '); Readln(People [NumOfClients].Activity.SkyDive); write('Philately : '); Readln(People [NumOfClients].Activity.Philate); write('Traveling : '); Readln(People [NumOfClients].Activity.Travel); write('Painting : '); Readln(People [NumOfClients].Activity.Paint); write('Reading : '); Readln(People [NumOfClients].Activity.Spelunk); write('Gardening : '); Readln(People [NumofClients].Activity.Garden); write('Hiking : '); Readln(People [NumOfClients].Activity.Hike); write('Cooking : '); Readln(People [NumOfClients].Activity.Cook); People [NumOfClients].match := 0; writeln; writeln; writeln(People [NumofClients].Name, ' is now on file ...'); END; { Add someone } END; { AddNewClient } PROCEDURE FindtheMatch (VAR NumOfClients: Integer; VAR Clients : Persontype); BEGIN { FindtheMatch } {IF NewOfClients <= MaxClients THEN BEGIN END; } END; { FindtheMatch } PROCEDURE PrintFree (VAR NumOfClients: Integer; VAR Clients : Persontype); BEGIN { PrintFree } writeln; writeln('Free Clients at this time'); writeln; writeln('Currently not matched'); writeln; NumOfClients := 1; WHILE (NumOfClients <= LastClient) DO BEGIN IF People [NumOfClients].Match = 0 THEN BEGIN { Print the Free Person } write('NAME : ', People [NumOfClients].Name:20); write('SEX : ', People [NumOfClients].Gender:3); write('PHONE : ', People [NumOfClients].Phone:15); writeln; END { Print the Free Person } ELSE writeln; NumOfClients := NumOfClients + 1; END; { End While Statement } END; { PrintFree } PROCEDURE Welcome; VAR i : integer; BEGIN { Welcome } writeln(chr(27),'[2J'); FOR i := 1 TO 5 DO writeln; writeln('Computer Dating Service'); writeln; writeln('Program Assignment 1'); writeln; writeln('Written and designed by:'); writeln('Scott Janousek'); writeln; END; { Welcome } BEGIN { Main Program } ReadClientInfo (DataFile, NumOfClients, People); SortIntoGender (NumOfClients, Male, Female); Welcome; REPEAT Option := GetUserInput; CASE option OF NewClient : AddNewClient (NumOfClients, People); Listmatch : FindtheMatch (NumOfClients, People); ListFree : PrintFree (NumOfClients, People); END; writeln; UNTIL option = QuitProg; writeln; writeln('Thank you for using this software.'); writeln('People Record'); FOR i := 1 to NumOfClients DO BEGIN writeln(People [i].Name); writeln(People [i].Gender); writeln(People [i].Phone); writeln(People [i].Activity.Photography); writeln(People [i].match); END; writeln('Male Record'); FOR i := 1 TO NumOfClients DO BEGIN Writeln(Male [i].Name); Writeln(Male [i].Gender); Writeln(Male [i].Phone); Writeln(Male [i].Activity.Photography); END; END. { Main Program }
unit dt_Type_Doc_Form; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, FIBDataSet, pFIBDataSet, Buttons, ToolWin, ComCtrls, Grids, DBGrids, FIBQuery, pFIBQuery, pFIBStoredProc, tagBaseTypes, Menus, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGridLevel, cxGrid, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxTextEdit; type Tdt_Type_Doc_Form1 = class(TForm) ToolBar1: TToolBar; AddButton: TSpeedButton; DelButton: TSpeedButton; EditButton: TSpeedButton; RefreshButton: TSpeedButton; CloseButton: TSpeedButton; DataSet: TpFIBDataSet; DataSource1: TDataSource; StoredProc: TpFIBStoredProc; SelectButton: TSpeedButton; PopupMenu: TPopupMenu; AddPopup: TMenuItem; EditPopup: TMenuItem; DelPopup: TMenuItem; N4: TMenuItem; RefreshPopup: TMenuItem; SelectPopup: TMenuItem; DBGrid1: TcxGrid; DBGrid1Level1: TcxGridLevel; DBGrid1DBTableView1: TcxGridDBTableView; DBGrid1DBTableView1ID_TYPE_DOC: TcxGridDBColumn; DBGrid1DBTableView1NAME_TYPE_DOC: TcxGridDBColumn; procedure FormCreate(Sender: TObject); procedure CloseButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure DelButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure SelectButtonClick(Sender: TObject); procedure DBGrid1KeyPress(Sender: TObject; var Key: Char); procedure DBGrid1DblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure AddPopupClick(Sender: TObject); procedure EditPopupClick(Sender: TObject); procedure DelPopupClick(Sender: TObject); procedure RefreshPopupClick(Sender: TObject); procedure SelectPopupClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var dt_Type_Doc_Form1 : Tdt_Type_Doc_Form1; Options : TSpravOptions; id_Type_Doc : integer; Name_Type_Doc : string; implementation uses DataModule, dt_Type_Doc_Form_Add; {$R *.DFM} procedure Tdt_Type_Doc_Form1.FormCreate(Sender: TObject); begin DataSet.Active := False; DataSet.Transaction := dm.ReadTransaction; DataSet.SQLs.SelectSQL.Text := 'select * from VIEW_DT_TYPE_DOC'; DataSet.Active := True; AddButton.Visible := Options.canAdd; SelectButton.Visible := Options.canSelect; ToolBar1.Visible := Options.HideButtons; EditButton.Visible := Options.canEdit; DelButton.Visible := Options.canDelete; AddPopup.Visible := Options.canAdd; SelectPopup.Visible := Options.canSelect; EditPopup.Visible := Options.canEdit; DelPopup.Visible := Options.canDelete; end; procedure Tdt_Type_Doc_Form1.CloseButtonClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure Tdt_Type_Doc_Form1.RefreshButtonClick(Sender: TObject); begin FormCreate(Sender); end; procedure Tdt_Type_Doc_Form1.AddButtonClick(Sender: TObject); var Name_Type_Doc : string; begin if dt_Type_Doc_Form_Add1 <> nil then exit; Application.CreateForm(Tdt_Type_Doc_Form_Add1, dt_Type_Doc_Form_Add1); dt_Type_Doc_Form_Add1.Caption := 'Додати тип документів'; dt_Type_Doc_Form_Add1.ShowModal; if dt_Type_Doc_Form_Add1.ModalResult = mrOk then begin Name_Type_Doc := dt_Type_Doc_Form_Add1.Name_Type_Doc.Text; StoredProc.Transaction := dm.WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('SP_DT_TYPE_DOC_ADD', [Name_Type_Doc]); StoredProc.Transaction.Commit; FormCreate(Sender); end; dt_Type_Doc_Form_Add1.Free; dt_Type_Doc_Form_Add1 := nil; end; procedure Tdt_Type_Doc_Form1.DelButtonClick(Sender: TObject); begin { case MessageDlg('Ви дійсно бажаєте знищити цей запис?', mtConfirmation, [mbYes, mbNo], 0) of mrYes : begin StoredProc.Transaction := dm.WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('SP_DT_TYPE_DOC_DEL', [DBGrid1.Columns[0].Field.asinteger]); StoredProc.Transaction.Commit; FormCreate(Sender); end; mrNo : Exit; end;} end; procedure Tdt_Type_Doc_Form1.EditButtonClick(Sender: TObject); {var id_Type_Doc : integer; Name_Type_Doc : string;} begin { if dt_Type_Doc_Form_Add1 <> nil then exit; Application.CreateForm(Tdt_Type_Doc_Form_Add1, dt_Type_Doc_Form_Add1); dt_Type_Doc_Form_Add1.Caption := 'Змінити тип документів'; dt_Type_Doc_Form_Add1.Name_Type_Doc.Text := DBGrid1.Columns[1].Field.AsString; dt_Type_Doc_Form_Add1.ShowModal; if dt_Type_Doc_Form_Add1.ModalResult = mrOk then begin id_Type_Doc := DBGrid1.Columns[0].Field.AsInteger; Name_Type_Doc := dt_Type_Doc_Form_Add1.Name_Type_Doc.Text; StoredProc.Transaction := dm.WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('SP_DT_TYPE_DOC_MODIFY', [id_Type_Doc, Name_Type_Doc]); StoredProc.Transaction.Commit; FormCreate(Sender); end; dt_Type_Doc_Form_Add1.Free; dt_Type_Doc_Form_Add1 := nil;} end; procedure Tdt_Type_Doc_Form1.SelectButtonClick(Sender: TObject); begin { id_Type_Doc := DBGrid1.Columns[0].Field.AsInteger; Name_Type_Doc := DBGrid1.Columns[1].Field.AsString; ModalResult := mrOK;} end; procedure Tdt_Type_Doc_Form1.DBGrid1KeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then CloseButtonClick(Sender); if SelectButton.Visible and (Key = #13) then SelectButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.DBGrid1DblClick(Sender: TObject); begin if SelectButton.Visible then SelectButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.FormDestroy(Sender: TObject); begin dt_Type_Doc_Form1 := NIL; end; procedure Tdt_Type_Doc_Form1.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure Tdt_Type_Doc_Form1.DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F5 then RefreshButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.AddPopupClick(Sender: TObject); begin AddButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.EditPopupClick(Sender: TObject); begin EditButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.DelPopupClick(Sender: TObject); begin DelButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.RefreshPopupClick(Sender: TObject); begin RefreshButtonClick(Sender); end; procedure Tdt_Type_Doc_Form1.SelectPopupClick(Sender: TObject); begin SelectButtonClick(Sender); end; end.
unit uniteProtocole; interface uses SysUtils, uniteReponse, uniteRequete, uniteConsigneur; //Traite les requêtes HTTP et fournit une réponse appropriée selon l'état du serveur type Protocole = class private //Le répertoire local qui contient tous les sites web de notre serveur repertoireDeBase:String; //Un consigneur permettant de consigner tous les messages leConsigneur:Consigneur; public //La methode traiterRequete analyse la requete et renvoie le code approprié au fureteur. //Elle reçoit la requete envoyée par le fureteur en paramètre et retourne un objet de type Reponse. // //@param uneRequete Reçoit la requête de l'utilisateur // //@return Reponse Traite la requête et retourne une réponse (Code d'erreur + message) // //@exception Exception Si la requête n'est pas une requête HTTP valide (si la 3ième partie n'est pas de la forme HTTP/x.y où x et y sont des entiers) function traiterRequete(uneRequete:Requete):Reponse; //Crée un objet Protocole qui traite les requêtes HTTP //et fournit une réponse appropriée selon l'état du serveur. // //@param unRepertoire le répertoire qui contient tous les sites web de notre serveur //@param unConsigneur sert à consigner des messages constructor create(unRepertoire:String;unConsigneur:Consigneur); //Accesseur du répertoire de base // //@return String retourne le répertoire de base function getRepertoire:String; //Mutateur du répertoire de base // //@param unRepertoire le répertoire de base procedure setRepertoire(unRepertoire:String); end; implementation function Protocole.traiterRequete(uneRequete:Requete):Reponse; begin result := Reponse.create('', '', 0, '', ''); end; constructor Protocole.create(unRepertoire:String;unConsigneur:Consigneur); begin end; function Protocole.getRepertoire:String; begin end; procedure Protocole.setRepertoire(unRepertoire:String); begin end; end.
{*****************************************************************} { } { by Jose Benedito - josebenedito@gmail.com } { www.jbsolucoes.net } {*****************************************************************} unit appmethods; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ceostypes, fpjson, jsonparser, ceosservermethods, ceosjson, db, BufDataSet, sqldb, mssqlconn, fgl; type { TCeosMethods } TCeosMethods = class(TCeosServerMethods) private published //exemplo metodos function Test(Request: TCeosRequestContent): TJSONStringType; function Test2(Request: TCeosRequestContent): TJSONStringType; function TestValmadson(Request: TCeosRequestContent): TJSONStringType; //exemplo de trafego de objetos json function GetObj(Request: TCeosRequestContent): TJSONStringType; function SetObj(Request: TCeosRequestContent): TJSONStringType; //json list serialization function GetObjList(Request: TCeosRequestContent): TJSONStringType; function SetObjList(Request: TCeosRequestContent): TJSONStringType; //exemplo de transferencia de datasets function DatasetJSON(Request: TCeosRequestContent): TJSONStringType; function ReadDataset(Request: TCeosRequestContent): TJSONStringType; //executa instruções SQL function QuerySQL(Request: TCeosRequestContent): TJSONStringType; end; TPerson = class(TObject) private FId: Int64; FName: string; published property Id: Int64 read FId write FId; property Name: string read FName write FName; end; { TList } generic TList<T> = class Items: array of T; procedure Add(Value: T); end; { TPessoa } TPessoa = class(TCollectionItem) private FIdade: integer; FNome: string; public constructor Create(ACollection: TCollection); override; published property Idade: integer read FIdade write FIdade; property Nome: string read FNome write FNome; end; { TListaPessoas } TListaPessoas = class(TCollection) private function GetItems(Index: integer): TPessoa; procedure SetItems(Index: integer; AValue: TPessoa); public constructor Create; public function Add: TPessoa; property Items[Index: integer]: TPessoa read GetItems write SetItems; default; end; implementation { TListaPessoas } function TListaPessoas.GetItems(Index: integer): TPessoa; begin Result := TPessoa(inherited Items[Index]); end; procedure TListaPessoas.SetItems(Index: integer; AValue: TPessoa); begin Items[Index].Assign(AValue); end; constructor TListaPessoas.Create; begin inherited Create(TPessoa); end; function TListaPessoas.Add: TPessoa; begin Result := inherited Add as TPessoa; end; { TPessoa } constructor TPessoa.Create(ACollection: TCollection); begin if Assigned(ACollection) then inherited Create(ACollection); end; { TList } procedure TList.Add(Value: T); begin SetLength(Items, Length(Items) + 1); Items[Length(Items) - 1] := Value; end; { TCeosMethods } function TCeosMethods.Test(Request: TCeosRequestContent): TJSONStringType; begin result := 'TESTE CEOSMW'; end; function TCeosMethods.Test2(Request: TCeosRequestContent): TJSONStringType; begin result := 'TESTE 2'; end; //object to json function TCeosMethods.GetObj(Request: TCeosRequestContent): TJSONStringType; var pessoa: TPerson; begin pessoa := TPerson.Create; try pessoa.Id := 10; pessoa.Name := Request.Args[0].AsString; result := ObjToJSON(pessoa); finally pessoa.free; end; end; //json to object function TCeosMethods.SetObj(Request: TCeosRequestContent): TJSONStringType; var pessoa: TPerson; s: string; begin pessoa := TPerson.Create; try JSONToObject(Request.Args[0].AsJSON, tobject(pessoa)); try if pessoa.id = 10 then raise exception.Create('Invalid ID!'); //exception sample s := format('id %d nome %s',[pessoa.Id, pessoa.Name]); result := s; finally freeandnil(pessoa); end; except on e:exception do raise exception.create(e.message); end; end; function TCeosMethods.GetObjList(Request: TCeosRequestContent): TJSONStringType; var Pessoas: TListaPessoas; Pessoa: TPessoa; begin try Pessoas := TListaPessoas.Create; Pessoa := Pessoas.Add; Pessoa.Idade := 20; Pessoa.Nome := 'JB'; Pessoa := Pessoas.Add; Pessoa.Idade := 20; Pessoa.Nome := 'FERNANDO'; result := ObjToJSON(Pessoas); finally Pessoas.free; end; end; function TCeosMethods.SetObjList(Request: TCeosRequestContent): TJSONStringType; var listapessoas: TListaPessoas; s: string; i: integer; begin listapessoas := TListaPessoas.Create; try JSONToObject(Request.Args[0].AsJSON, tobject(listapessoas)); try s := ''; for i := 0 to listapessoas.Count -1 do s := s + format('nome %s id %d ,',[listapessoas.Items[i].Nome, listapessoas.Items[i].Idade]); result := s; finally freeandnil(listapessoas); end; except on e:exception do raise exception.create(e.message); end; end; function TCeosMethods.TestValmadson(Request: TCeosRequestContent): TJSONStringType; begin result := 'EXEMPLO'; end; function TCeosMethods.DatasetJSON(Request: TCeosRequestContent): TJSONStringType; var Dset: TBufDataSet; i: integer; begin {$WARNINGS OFF} Dset := TBufDataSet.Create(nil); {$WARNINGS ON} try DSet.FieldDefs.Add('ID',ftInteger); DSet.FieldDefs.Add('NAME',ftString,20); Dset.CreateDataset; DSet.Open; for i := 0 to Request.Args.Count -1 do begin DSet.Append; DSet.FieldByName('ID').Value:= i+1; DSet.FieldByName('NAME').Value:= Request.Args[i].AsString; DSet.Post; end; result := DatasetToJSON(Dset); finally Dset.free; end; end; function TCeosMethods.ReadDataset(Request: TCeosRequestContent): TJSONStringType; var Dset: TBufDataSet; jo: tjsonobject; begin jo := tjsonparser.create(Request.Args[0].AsJSON).parse as tjsonobject; {$WARNINGS OFF} Dset := TBufDataSet.create(nil); {$WARNINGS ON} try if JSONToDataset(tdataset(Dset),jo) then begin Dset.first; result := 'OK '+ Dset.FieldByName('NAME').asstring end else result := 'NOK'; finally Dset.free; end; end; function TCeosMethods.QuerySQL(Request: TCeosRequestContent): TJSONStringType; var conn: TMSSQLConnection; tra: TSQLTransaction; qry: TSQLQuery; sSQL: string; bReturnFields: boolean; begin conn := TMSSQLConnection.Create(nil); tra := TSQLTransaction.Create(nil); qry := TSQLQuery.Create(nil); try conn.HostName := 'ABEL\SQLEXPRESS'; conn.DatabaseName := 'jb'; conn.UserName := 'sa'; conn.Password := 'jbs123'; conn.Transaction := tra; qry.DataBase := conn; try conn.open; conn.StartTransaction; sSQL := Request.Args[0].AsString; qry.SQL.Text := sSQL; bReturnFields := (Request.Args[1].AsInteger = 1); if IsSelect(sSQL) then begin qry.Open; result := DataSetToJSON(qry,bReturnFields); end else begin qry.ExecSQL; result := 'OK'; end; tra.Commit; except on e:exception do begin tra.Rollback; raise exception.Create(e.Message); end; end; finally conn.close; qry.free; tra.free; conn.free; end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Tests.Spec.Reader; interface uses DPM.Core.Spec.Interfaces, DUnitX.TestFramework; type {$M+} [TestFixture] TSpecReaderTests = class public [SetupFixture] procedure FixtureSetup; [TearDownFixture] procedure FixtureTearDown; published procedure Test_can_load_core_spec; end; implementation uses Winapi.ActiveX, System.SysUtils, TestLogger, DPM.Core.Spec.Reader; { TSpecReaderTests } procedure TSpecReaderTests.FixtureSetup; begin CoInitialize(nil); end; procedure TSpecReaderTests.FixtureTearDown; begin CoUninitialize; end; procedure TSpecReaderTests.Test_can_load_core_spec; var spec :IPackageSpec; reader :IPackageSpecReader; // lastError : string; filePath :string; begin reader := TPackageSpecReader.Create(TTestLogger.Create); filePath := ExtractFilePath(ParamStr(0)) + '..\..\..\DPM.Core.dspec'; spec := reader.ReadSpec(filePath); Assert.IsNotNull(spec); end; initialization //TDUnitX.RegisterTestFixture(TSpecReaderTests); end.
unit ufrmDialogCostCenter; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, Vcl.StdCtrls, uInterface, uModCostCenter, uTSCommonDlg, uClientClasses; type TfrmDialogCostCenter = class(TfrmMasterDialog, ICRUDAble) lblCode: TLabel; LblName: TLabel; edtCode: TEdit; edtName: TEdit; procedure FormCreate(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); private FCostCenter: TModCostCenter; function GetCostCenter: TModCostCenter; { Private declarations } public procedure LoadData(AID : String); property CostCenter: TModCostCenter read GetCostCenter write FCostCenter; { Public declarations } end; var frmDialogCostCenter: TfrmDialogCostCenter; implementation uses uAppUtils, uDXUtils, System.DateUtils, uDBUtils, uDMClient; {$R *.dfm} procedure TfrmDialogCostCenter.FormCreate(Sender: TObject); begin inherited; Self.AssignKeyDownEvent; end; procedure TfrmDialogCostCenter.actDeleteExecute(Sender: TObject); begin inherited; if TAppUtils.ConfirmHapus then begin if DMClient.CrudClient.DeleteFromDB(FCostCenter) then Self.ModalResult := mrOk; end; end; procedure TfrmDialogCostCenter.actSaveExecute(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit; if TAppUtils.ConfirmSimpan then begin try CostCenter.COCTER_CODE := edtCode.Text; CostCenter.COCTER_NAME := edtName.Text; if DMClient.CrudClient.SaveToDB(FCostCenter) then ModalResult := mrOk; except raise; end; end; end; function TfrmDialogCostCenter.GetCostCenter: TModCostCenter; begin if not Assigned(FCostCenter) then FCostCenter := TModCostCenter.Create; Result := FCostCenter; end; procedure TfrmDialogCostCenter.LoadData(AID : String); begin FreeAndNil(FCostCenter); edtCode.Text := ''; edtName.Text := ''; // with TCrudClient.Create(DMClient.RestConn, False) do // begin FCostCenter := DMClient.CrudClient.Retrieve(TModCostCenter.ClassName, AID) as TModCostCenter; if FCostCenter <> nil then begin edtCode.Text := FCostCenter.COCTER_CODE; edtName.Text := FCostCenter.COCTER_NAME; end; end; end.
{ @abstract(form for use with ) @author(Aaron Hochwimer <aaron@graphic-edge.co.nz>) @created(June 27, 2003) @lastmod(June 29, 2003) This unit provides the TformGEImporter - which is used in conjunction with the TGEImportFile component. } unit frmImport; interface uses Windows,Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.XPStyleActnCtrls, Vcl.ActnList, Vcl.ActnMan, Vcl.Menus, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Clipbrd // Third party components {,kbmMemTable}; type TformGEImporter = class(TForm) ActionManager: TActionManager; bCancel: TBitBtn; bClear: TBitBtn; bOk: TBitBtn; bReload: TBitBtn; cbDelimiter: TComboBox; cbxGroupDelimiter: TCheckBox; cbxOverwrite: TCheckBox; dbgImport: TDBGrid; dsImport: TDataSource; ebDateFormat: TEdit; ebHeaderSkip: TEdit; {kbmImport: TkbmMemTable;} lblDateFormat: TLabel; lblDelimiter: TLabel; lblHeaderSkip: TLabel; ///pmFieldNames: TPopupActionBarEx; pnlSettings: TPanel; sBarImport: TStatusBar; upHeaderSkip: TUpDown; procedure bClearClick(Sender: TObject); procedure bOkClick(Sender: TObject); procedure bReloadClick(Sender: TObject); procedure cbDelimiterChange(Sender: TObject); procedure cbxGroupDelimiterClick(Sender: TObject); procedure dbgImportDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure dbgImportTitleClick(Column: TColumn); procedure ebHeaderSkipExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure kbmImportAfterDelete(DataSet: TDataSet); procedure kbmImportAfterInsert(DataSet: TDataSet); procedure kbmImportAfterPost(DataSet: TDataSet); procedure pmFieldNamesPopup(Sender: TObject); procedure SelectField(Sender:TObject); procedure SelectIgnore(Sender:TObject); procedure upHeaderSkipClick(Sender: TObject; Button: TUDBtnType); private iHeaderSkip : integer; iSelected : integer; {programatically adds an entry to aMenu (the TMenu or TMenuItem you wish to add the item to. aEvent is the TNotify event that will be called when selecting the item. sCaption is the new menu items caption. bChangeCase will change the caption's first character to uppercase and the rest to lower case. This function will return a newly created TMenuitem. Example: AddMenuItem(popupmenu1,'New Item',nil,false);} function AddMenuItem(AMenu:TComponent;sCaption:string;aEvent:TNotifyEvent; bChangeCase:Boolean):TMenuItem; {sets up the colours to indicate which rows and columns will be ignored} procedure SetColours; {updates the display labels for the titles of the grid,dbgImport} procedure UpdateDisplayLabels; public allowsl : TStringList; bEditing : boolean; fsl : TStringList; {toggles all columns to 'ignore' status} procedure CheckAllIgnore(var bIgnoreAll:boolean;fsl:TstringList); {displays the record count of the dbgImport} procedure DisplayRecCount; procedure PrepImportTable; {loads the delimiter type - there are two different types of delimiters: '," 0= none ,1= ' ,2= " ,3='..',4=".." The choice between 1 and 3 say is made with the AllDelimiters flag} procedure SetDelimiters(sDelimiter:string; bAllDelimiters,bGroupDelimiters:boolean); procedure SetHeaderSkip(iSkip:integer); procedure SetupFieldDefs(sl:TStringList); end; implementation uses geImportFile; {$R *.dfm} // ----- TformGEImporter.bClearClick ------------------------------------------- procedure TformGEImporter.bClearClick(Sender: TObject); var i:integer; begin for i:= 0 to fsl.Count-1 do fsl[i] := sIGNORE; UpdateDisplayLabels; SetColours; end; // ----- TformGEImporter.bOkClick ---------------------------------------------- procedure TformGEImporter.bOkClick(Sender: TObject); var i:integer; bSomeEntries:boolean; begin bSomeEntries := false; for i:=0 to fsl.Count-1 do ///if (kbmImport.Fields[i].DisplayLabel <> sIGNORE) then begin bSomeEntries := true; break; end; if not bSomeEntries then begin MessageDlg('Cannot import if there are no columns assigned!', mtInformation, [mbOK], 0); ModalResult := mrNone; exit; end; end; // ----- TformGEImporter.bReloadClick ------------------------------------------ procedure TformGEImporter.bReloadClick(Sender: TObject); var clip:TStringList; begin if (MessageDlg('Are you sure you wish to reload the data?', mtConfirmation, [mbYes,mbNo], 0) = mrYes) then begin UpdateDisplayLabels; bEditing := false; if (TGEImportFile(owner).ImportFileType = ifClipboard) then begin clip := TStringList.Create; clip.Text := Clipboard.AsText; TGEImportFile(owner).ImportDataFromClipboard(clip); clip.Free; end else TGEImportFile(owner).ImportDataFromFile(0,false); bEditing := true; UpdateDisplayLabels; end; end; // ----- TformGEImporter.cbDelimiterChange ------------------------------------- procedure TformGEImporter.cbDelimiterChange(Sender: TObject); begin // evaluated the delimiter based on the selection - must do it here because of // the provision to "reload" the data with TGEImportFile(Owner) do begin case cbDelimiter.ItemIndex of 0: Delimiter := ''; 1,3: Delimiter := ''''; 2,4: Delimiter := '"'; end; case cbDelimiter.ItemIndex of 1,2: AllDelimiters:=true; 0,3,4: AllDelimiters:=false; end; end; end; // ----- TformGEImporter.cbxGroupDelimiterClick -------------------------------- procedure TformGEImporter.cbxGroupDelimiterClick(Sender: TObject); begin TGEImportFile(Owner).GroupDelimiters := cbxGroupDelimiter.Checked; end; // ----- TformGEImporter.dbgImportDrawColumnCell ------------------------------- procedure TformGEImporter.dbgImportDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin (* if (kbmImport.RecNo <= iHeaderSkip) and not (gdSelected in State) then begin dbgImport.Canvas.Brush.Color := clInfoBk; dbgImport.Canvas.FillRect(Rect); dbgimport.Canvas.TextOut(Rect.Left+2,Rect.Top+2,Column.Field.DisplayText); end else dbgImport.DefaultDrawColumnCell(Rect,DataCol,Column,State); *) end; // ----- TformGEImporter.dbgImportTitleClick ----------------------------------- procedure TformGEImporter.dbgImportTitleClick(Column:TColumn); begin dbgImport.SelectedIndex := Column.Field.FieldNo-1; ///pmFieldNames.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y); end; // ----- TformGEImporter.ebHeaderSkipExit -------------------------------------- procedure TformGEImporter.ebHeaderSkipExit(Sender: TObject); begin try iHeaderSkip := StrToInt(ebHeaderSkip.Text); if (iHeaderSkip < 0) then begin iHeaderskip := 0; ebHeaderSkip.Text := '0'; end; TGEImportFile(owner).HeaderSkip := iHeaderSkip; SetColours; dbgImport.Refresh; except ebHeaderSkip.Text := IntToStr(iHeaderSkip); end; end; // ----- TformGEImporter.FormCreate -------------------------------------------- procedure TformGEImporter.FormCreate(Sender: TObject); begin allowsl := TStringList.Create; fsl := TStringList.Create; end; // ----- TformGEImporter.FormDestroy ------------------------------------------- procedure TformGEImporter.FormDestroy(Sender: TObject); begin allowsl.free; fsl.free; end; // ----- TformGEImporter.FormShow ---------------------------------------------- procedure TformGEImporter.FormShow(Sender: TObject); begin if (ebDateFormat.Text = '') then ebDateFormat.Text := System.SysUtils.FormatSettings.ShortDateFormat; bEditing := true; UpdateDisplayLabels; end; // ----- TformGEImporter.kbmImportAfterDelete ---------------------------------- procedure TformGEImporter.kbmImportAfterDelete(DataSet: TDataSet); begin if bEditing then DisplayRecCount; end; // ----- TformGEImporter.kbmImportAfterInsert ---------------------------------- procedure TformGEImporter.kbmImportAfterInsert(DataSet: TDataSet); begin if bEditing then DisplayRecCount; end; // ----- TformGEImporter.kbmImportAfterPost ------------------------------------ procedure TformGEImporter.kbmImportAfterPost(DataSet: TDataSet); begin if bEditing then DisplayRecCount; end; // ----- TformImporter.pmFieldNamesPopup --------------------------------------- procedure TformGEImporter.pmFieldNamesPopup(Sender: TObject); var i : integer; sFieldName : string; mi : TMenuItem; begin iSelected := dbgimport.SelectedField.FieldNo-1; // clear out the menu ///pmFieldNames.Items.Clear; // add the first entry to the menu as Ignore ///mi := AddMenuItem(pmFieldNames,sIGNORE,SelectIgnore,false); mi.Checked := (sIGNORE = fsl.Strings[iSelected]); // adds separator ///AddMenuItem(pmFieldNames,'-',nil,false); // construct the menu from the list of allowable fields - minus any allocated // fields e.g. (allow - fsl)} for i := 0 to allowsl.count-1 do begin sFieldName := allowsl.Strings[i]; if (fsl.IndexOf(sFieldName) = -1) then ///AddMenuItem(pmFieldNames,sFieldName,SelectField,false); end; end; // ----- TformImporter.SelectField --------------------------------------------- procedure TformGEImporter.SelectField(Sender:Tobject); begin fsl.Strings[iSelected] := TMenuItem(Sender).Caption; ///kbmImport.Fields[iSelected].DisplayLabel:=fsl.Strings[iSelected]; SetColours; end; // ----- TformImporter.SelectIgnore -------------------------------------------- procedure TformGEImporter.SelectIgnore(Sender:Tobject); begin fsl.Strings[iSelected] := sIGNORE; ///kbmImport.Fields[iSelected].DisplayLabel:=fsl.Strings[iSelected]; SetColours; end; // ----- TformGEImporter.upHeaderSkipClick ------------------------------------- procedure TformGEImporter.upHeaderSkipClick(Sender: TObject; Button: TUDBtnType); begin if (Button = btNext) then begin Inc(iheaderskip); ebheaderSkip.Text := InttoStr(iHeaderskip); ebHeaderskipExit(nil); end else if (Button = btPrev) then begin if iHeaderSkip > 0 then begin Dec(iHeaderSkip); ebheaderSkip.Text := InttoStr(iHeaderskip); ebHeaderskipExit(nil); end; end; end; //------ AddMenuItem ----------------------------------------------------------- function TformGEImporter.AddMenuItem(AMenu:TComponent;sCaption:string;AEvent:TNotifyEvent; bChangeCase: Boolean):TMenuItem; var i:integer; begin result := TMenuItem.Create(aMenu.Owner); if bChangeCase then begin if (Pos('&',sCaption) = 1) then i:=1 else i:=0; sCaption := UpperCase(Copy(sCaption,1,i+1)) + LowerCase(Copy(sCaption,2+i,Length(sCaption))); end; // assign caption and event to result result.Caption := sCaption; result.OnClick := aEvent; if (aMenu is TPopupMenu) or (aMenu is TMainMenu) then TPopupMenu(aMenu).Items.Add(result) else if (aMenu is TMenuItem) then TMenuItem(aMenu).Add(result); end; // ----- TformGEImporter.SetColours -------------------------------------------- procedure TformGEImporter.SetColours; var i:integer; begin with dbgimport do begin Columns.RebuildColumns; for i:= 0 to Columns.Count-1 do begin Columns[i].Width := 100; Columns[i].Title.Alignment := taCenter; if (fsl.Strings[i] = sIGNORE) then Columns[i].Color := clInfoBk else Columns[i].Color := clWhite; end; end; end; // ----- TformGEImporter.UpdateDisplayLabels ----------------------------------- procedure TformGEImporter.UpdateDisplayLabels; var i:integer; begin // only loop over visible columns { for i:=0 to kbmImport.Fieldcount-1 do kbmImport.Fields[i].DisplayLabel := fsl.Strings[i] } end; // ------ TformImporter.CheckAllIgnore ----------------------------------------- procedure TformGEImporter.CheckAllIgnore(var bIgnoreAll:Boolean;fsl:TStringList); var i:integer; begin bIgnoreAll := true; (* for i:=0 to kbmImport.FieldCount-1 do begin if (fsl.Strings[i] <> sIGNORE) then begin bIgnoreAll := false; break; end; end; *) end; // ----- TformImporter.DisplayRecCount ----------------------------------------- procedure TformGEImporter.DisplayRecCount; begin ///sBarImport.Panels[0].Text := IntToStr(kbmImport.RecordCount); end; // ----- TformImporter.PrepImportTable ----------------------------------------- procedure TformGEImporter.PrepImportTable; begin (* with kbmImport do begin DisableControls; if Active then Close; Open; First; end; *) end; // ------ TFormImporter.SetDelimiters ------------------------------------------ procedure TformGEImporter.SetDelimiters(sDelimiter:string; bAllDelimiters,bGroupDelimiters:boolean); begin if (sDelimiter = '') then cbDelimiter.ItemIndex := 0 else if (sDelimiter = '"') then begin if bAllDelimiters then cbDelimiter.ItemIndex := 2 else cbDelimiter.ItemIndex := 4; end else begin if bAllDelimiters then cbDelimiter.ItemIndex := 1 else cbDelimiter.ItemIndex := 3; end; cbxGroupDelimiter.Checked := bGroupDelimiters; end; // ------ TFormImporter.SetHeaderSkip ------------------------------------------ procedure TformGEImporter.SetHeaderSkip(iSkip:integer); begin iHeaderSkip := iSkip; ebHeaderSkip.Text := IntToStr(iSkip); end; //------ TformImporter.SetupFieldDefs ------------------------------------------ procedure TformGEImporter.SetupFieldDefs(sl:TStringList); var i:integer; begin // now assign entries from Stored fields and stored units (* kbmImport.FieldDefs.Clear; for i:=0 to sl.Count-1 do begin with kbmImport.FieldDefs.AddFieldDef do begin Name := 'Field' + IntToStr(i); DataType:= ftstring; Size := 255; end; end; // add ignores where appropriate while (sl.Count > fsl.Count) do fsl.Add(SIGNORE); // prune other columns while (sl.Count < fsl.Count) do fsl.Delete(fsl.Count-1); kbmImport.Active:=true; *) SetColours; end; // ============================================================================= end.
unit OpenCV.ObjDetect; interface uses Winapi.Windows, OpenCV.Lib, OpenCV.Core; const CV_HAAR_FEATURE_MAX = 3; const CV_HAAR_DO_CANNY_PRUNING = 1; CV_HAAR_SCALE_IMAGE = 2; CV_HAAR_FIND_BIGGEST_OBJECT = 4; CV_HAAR_DO_ROUGH_SEARCH = 8; type TSumType = integer; pSumType = ^TSumType; Tsqsumtype = Double; psqsumtype = ^Tsqsumtype; TCvHidHaarFeatureRect = record p0, p1, p2, p3: pSumType; end; TCvHidHaarFeature = array [0 .. CV_HAAR_FEATURE_MAX - 1] of TCvHidHaarFeatureRect; pCvHidHaarTreeNode = ^TCvHidHaarTreeNode; TCvHidHaarTreeNode = record feature: TCvHidHaarFeature; threshold: Single; left: integer; right: integer; end; pCvHidHaarClassifier = ^TCvHidHaarClassifier; TCvHidHaarClassifier = record count: integer; // CvHaarFeature* orig_feature; node: pCvHidHaarTreeNode; alpha: pSingle; end; pCvHidHaarStageClassifier = ^TCvHidHaarStageClassifier; TCvHidHaarStageClassifier = record count: integer; threshold: Single; classifier: pCvHidHaarClassifier; two_rects: integer; next: pCvHidHaarStageClassifier; child: pCvHidHaarStageClassifier; parent: pCvHidHaarStageClassifier; end; TCvHidHaarClassifierCascade = record count: integer; isStumpBased: integer; has_tilted_features: integer; is_tree: integer; inv_window_area: Real; sum, sqsum, tilted: TCvMat; stage_classifier: pCvHidHaarStageClassifier; pq0, pq1, pq2, pq3: psqsumtype; p0, p1, p2, p3: pSumType; ipp_stages: pPointer; end; (* //****************************************************************************************\ //* Haar-like Object Detection functions * //****************************************************************************************/ *) Const CV_HAAR_MAGIC_VAL = $42500000; CV_TYPE_NAME_HAAR = 'opencv-haar-classifier'; // #define CV_IS_HAAR_CLASSIFIER( haar ) \ // ((haar) != NULL && \ // (((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL) type THaarFeature = record r: TCvRect; weight: Single; end; pCvHaarFeature = ^TCvHaarFeature; TCvHaarFeature = record tilted: Integer; rect: array [0 .. CV_HAAR_FEATURE_MAX - 1] of THaarFeature; end; pCvHaarClassifier = ^TCvHaarClassifier; TCvHaarClassifier = record count: Integer; haar_feature: pCvHaarFeature; threshold: pSingle; left: pInteger; right: pInteger; alpha: pSingle; end; pCvHaarStageClassifier = ^TCvHaarStageClassifier; TCvHaarStageClassifier = record count: Integer; threshold: Single; classifier: pCvHaarClassifier; next: Integer; child: Integer; parent: Integer; end; // TCvHidHaarClassifierCascade = TCvHidHaarClassifierCascade; pCvHidHaarClassifierCascade = ^TCvHidHaarClassifierCascade; pCvHaarClassifierCascade = ^TCvHaarClassifierCascade; TCvHaarClassifierCascade = record flags: Integer; count: Integer; orig_window_size: TCvSize; real_window_size: TCvSize; scale: Real; stage_classifier: pCvHaarStageClassifier; hid_cascade: pCvHidHaarClassifierCascade; end; TCvAvgComp = record rect: TCvRect; neighbors: Integer; end; var { // Loads haar classifier cascade from a directory. // It is obsolete: convert your cascade to xml and use cvLoad instead CVAPI(CvHaarClassifierCascade*) cvLoadHaarClassifierCascade( const char* directory, CvSize orig_window_size); } cvLoadHaarClassifierCascade: function(const directory: pCVChar; orig_window_size: TCvSize): pCvHaarClassifierCascade; cdecl = nil; // CVAPI(void) cvReleaseHaarClassifierCascade( CvHaarClassifierCascade** cascade ); cvReleaseHaarClassifierCascade: procedure(Var cascade: pCvHaarClassifierCascade); cdecl = nil; { CVAPI(CvSeq*) cvHaarDetectObjects( const CvArr* image, CvHaarClassifierCascade* cascade, CvMemStorage* storage, double scale_factor CV_DEFAULT(1.1), int min_neighbors CV_DEFAULT(3), int flags CV_DEFAULT(0), CvSize min_size CV_DEFAULT(cvSize(0,0)), CvSize max_size CV_DEFAULT(cvSize(0,0))); } cvHaarDetectObjects: function( { } const image: pIplImage; { } cascade: pCvHaarClassifierCascade; { } storage: pCvMemStorage; { } scale_factor: double { =1.1 }; { } min_neighbors: Integer { =3 }; { } flags: Integer { = 0 }; { } min_size: TCvSize { =CV_DEFAULT(cvSize(0,0)) }; { } max_size: TCvSize { =CV_DEFAULT(cvSize(0,0)) } ): pCvSeq; cdecl = nil; function CvLoadObjDetectLib: Boolean; implementation var FObjDetectLib: THandle = 0; function CvLoadObjDetectLib: Boolean; begin Result := False; FObjDetectLib := LoadLibrary(objdetect_dll); if FObjDetectLib > 0 then begin Result := True; cvLoadHaarClassifierCascade := GetProcAddress(FObjDetectLib, 'cvLoadHaarClassifierCascade'); cvReleaseHaarClassifierCascade := GetProcAddress(FObjDetectLib, 'cvReleaseHaarClassifierCascade'); cvHaarDetectObjects := GetProcAddress(FObjDetectLib, 'cvHaarDetectObjects'); end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.TreeView, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl; type TForm1 = class(TForm) Button1: TButton; ListBox1: TListBox; ComboBox1: TComboBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; TreeView1: TTreeView; TreeViewItem1: TTreeViewItem; TreeViewItem2: TTreeViewItem; TreeViewItem3: TTreeViewItem; Label1: TLabel; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; Label2: TLabel; CheckBox: TCheckBox; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtBase, NtBaseTranslator, NtResource, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; begin Label1.Text := _T('Hello world', 'HelloWorld'); end; procedure TForm1.FormCreate(Sender: TObject); begin NtResources._T('English', 'en'); NtResources._T('Finnish', 'fi'); NtResources._T('German', 'de'); NtResources._T('French', 'fr'); NtResources._T('Japanese', 'ja'); _T(Self); UpdateStrings; end; procedure TForm1.Button1Click(Sender: TObject); begin if TNtLanguageDialog.Select('en', lnBoth) then UpdateStrings; end; initialization NtEnabledProperties := STRING_TYPES; end.
unit L_SpecialFolders; //////////////////////////////////////////////////////////////////////////////////////////////////// interface {$REGION 'PVCS-header'} (* © DGMR raadgevende ingenieurs BV * * Created by: MCO on 31-01-2012 * * $Header: $ * * Description: TSpecialFolders is een class waar het pad van alle 'speciale' mappen * mee opgevraagd kan worden. Het zijn allemaal class properties, dus er * hoeft niet eerst een instantie aangemaakt te worden. * Deze class is betrouwbaarder dan EnvironmentVariables, Application.ExeName * of ParamStr(0), want EnvironmentVariables zijn niet altijd allemaal gedefinieerd, * en ParamStr(0) is niet beschikbaar vanuit een Dll. * Wanneer de Dll-properties vanuit een EXE worden aangeroepen, wordt het pad van * de EXE gebruikt. * Als met de functies TempExe, TempDll, en TempExeDll een nieuwe directory wordt * gemaakt, dan wordt deze geleegd bij het afsluiten van het programma. * Met de functie Settings kan het pad opgevraagd worden waar instellingen opgeslagen * zouden moeten worden, rekening houdend met de volgende factoren: * - sfUserSpecific: of het pad gebruikersgebonden moet zijn, of voor alle gebruikers moet gelden; * - sfMachineSpecific: of het pad alleen op de huidige machine moet gelden (local), * of ook met het gebruikersprofiel op het netwerk gekopieerd mag worden (roaming) * - sfExeSpecific: of de naam van de Exe aan het pad toegevoegd moet worden; * - sfDllSpecific: of de naam van de Dll (of van de Exe als we niet in een Dll zitten) * aan het pad toegevoegd moet worden. * De functie Settings zonder parameters haalt [sfUserSpecific, sfDllSpecific] op. * Examples: * TSpecialFolders.Settings; // C:\Users\MCo\AppData\Roaming\ENORM\ * TSpecialFolders.Settings([sfMachineSpecific, sfDllSpecific]); // C:\ProgramData\ENORM\ * TSpecialFolders.Settings([sfUserSpecific, sfMachineSpecific, sfExeSpecific, sfDllSpecific]); // C:\Users\MCo\AppData\Local\ISL2\SLC_A3\ * TSpecialFolders.Exe; // C:\Program Files (x86)\ISL\ISL2 V4.01\ * TSpecialFolders.ExeFullName; // C:\Program Files (x86)\ISL\ISL2 V4.01\ISL2.EXE * // C:\Program Files (x86)\ENORM V0.70\ENORM.EXE * TSpecialFolders.DLL; // C:\Program Files (x86)\ISL\ISL2 V4.01\ * TSpecialFolders.DLLFullName; // C:\Program Files (x86)\ISL\ISL2 V4.01\SLC_A3.dll * // C:\Program Files (x86)\ENORM V0.70\ENORM.EXE * TSpecialFolders.Temp; // C:\Users\MCo\AppData\Local\Temp\ * TSpecialFolders.TempExe; // C:\Users\MCo\AppData\Local\Temp\ISL2\ * // C:\Users\MCo\AppData\Local\Temp\ENORM\ * TSpecialFolders.TempDll; // C:\Users\MCo\AppData\Local\Temp\SLC_A3\ * // C:\Users\MCo\AppData\Local\Temp\ENORM\ * TSpecialFolders.TempExeDll; // C:\Users\MCo\AppData\Local\Temp\ISL2\SLC_A3\ * // C:\Users\MCo\AppData\Local\Temp\ENORM\ * TSpecialFolders.Windows; // C:\Windows\ * TSpecialFolders.System; // C:\Windows\system32\ * TSpecialFolders.AppData; // C:\Users\MCo\AppData\Roaming\ * TSpecialFolders.CommonAppData; // C:\ProgramData\ * // C:\Documents and Settings\All Users\Application Data\ * TSpecialFolders.AppDataLocal; // C:\Users\MCo\AppData\Local\ * // C:\Documents and Settings\MCo\Local Settings\Application Data\ * TSpecialFolders.ProgramFiles; // C:\Program Files\ <= 64-bits EXE on 64-bits OS or 32-bits EXE on 32-bits OS * // C:\Program Files (x86)\ <= 32-bits EXE on 64-bits OS * TSpecialFolders.CommonProgramFiles; // C:\Program Files (x86)\Common Files\ * TSpecialFolders.ProgramFilesX86; // C:\Program Files (x86)\ * TSpecialFolders.CommonProgramFilesX86; // C:\Program Files (x86)\Common Files\ * TSpecialFolders.Desktop; // C:\Users\MCo\Desktop\ * TSpecialFolders.CommonDesktop; // C:\Users\Public\Desktop\ * TSpecialFolders.Documents; // C:\Users\MCo\Documents\ * TSpecialFolders.CommonDocuments; // C:\Users\Public\Documents\ * TSpecialFolders.Pictures; // C:\Users\MCo\Pictures\ * TSpecialFolders.CommonPictures; // C:\Users\Public\Pictures\ * TSpecialFolders.Music; // C:\Users\MCo\Music\ * TSpecialFolders.CommonMusic; // C:\Users\Public\Music\ * TSpecialFolders.Video; // C:\Users\MCo\Videos\ * TSpecialFolders.CommonVideo; // C:\Users\Public\Videos\ * TSpecialFolders.AdminTools; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools\ * TSpecialFolders.CommonAdminTools; // C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\ * TSpecialFolders.Favorites; // C:\Users\MCo\Favorites\ * TSpecialFolders.CommonFavorites; // C:\Users\MCo\Favorites\ * TSpecialFolders.StartMenu; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Start Menu\ * TSpecialFolders.CommonStartMenu; // C:\ProgramData\Microsoft\Windows\Start Menu\ * TSpecialFolders.StartMenuPrograms; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\ * TSpecialFolders.CommonStartMenuPrograms; // C:\ProgramData\Microsoft\Windows\Start Menu\Programs\ * TSpecialFolders.StartUp; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\ * TSpecialFolders.CommonStartUp; // C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\ * TSpecialFolders.Templates; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Templates\ * TSpecialFolders.CommonTemplates; // C:\ProgramData\Microsoft\Windows\Templates\ * TSpecialFolders.Cookies; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Cookies\ * TSpecialFolders.DiscBurnArea; // C:\Users\MCo\AppData\Local\Microsoft\Windows\Burn\Burn\ * TSpecialFolders.History; // C:\Users\MCo\AppData\Local\Microsoft\Windows\History\ * TSpecialFolders.NetHood; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Network Shortcuts\ * TSpecialFolders.PrintHood; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Printer Shortcuts\ * TSpecialFolders.Recent; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\Recent\ * TSpecialFolders.SendTo; // C:\Users\MCo\AppData\Roaming\Microsoft\Windows\SendTo\ * * * $Log: $ *) {$ENDREGION} uses ShlObj, SHFolder; type TSettingsFlag = (sfUserSpecific, sfMachineSpecific, sfExeSpecific, sfDllSpecific); TSettingsFlags = set of TSettingsFlag; TSpecialFolders = class private class procedure AddTempFolder(const TempDir: string); class procedure DeleteTempFolders; class function GetModulePathName(const hInst: Cardinal): string; class function GetExe: string; static; inline; class function GetExeDir: string; static; inline; class function GetExeBaseName: string; static; inline; class function GetDll: string; static; inline; class function GetDllDir: string; static; inline; class function GetDllBaseName: string; static; inline; class function GetWindowsDir: string; static; class function GetWindowsSysDir: string; static; class function GetTempDir(const Index: Integer): string; static; class function GetCSIDLDir(const CSIDL: Integer): string; static; // Constant Special Item ID List protected class function GetHToken: Cardinal; virtual; public class function Settings(Flags: TSettingsFlags = [sfUserSpecific, sfDllSpecific]): string; class property Exe: string read GetExeDir; class property ExeFullName: string read GetExe; class property DLL: string read GetDllDir; class property DLLFullName: string read GetDll; class property Temp: string index 0 read GetTempDir; class property TempExe: string index 1 read GetTempDir; class property TempDll: string index 2 read GetTempDir; class property TempExeDll: string index 3 read GetTempDir; class property Windows: string read GetWindowsDir; class property System: string read GetWindowsSysDir; class property AppData: string index CSIDL_APPDATA read GetCSIDLDir; class property CommonAppData: string index CSIDL_COMMON_APPDATA read GetCSIDLDir; class property AppDataLocal: string index CSIDL_LOCAL_APPDATA read GetCSIDLDir; class property ProgramFiles: string index CSIDL_PROGRAM_FILES read GetCSIDLDir; class property ProgramFilesCommon: string index CSIDL_PROGRAM_FILES_COMMON read GetCSIDLDir; class property ProgramFilesX86: string index CSIDL_PROGRAM_FILESX86 read GetCSIDLDir; class property ProgramFilesX86Common: string index CSIDL_PROGRAM_FILES_COMMONX86 read GetCSIDLDir; class property Desktop: string index CSIDL_DESKTOPDIRECTORY read GetCSIDLDir; class property CommonDesktop: string index CSIDL_COMMON_DESKTOPDIRECTORY read GetCSIDLDir; class property Documents: string index CSIDL_PERSONAL read GetCSIDLDir; class property CommonDocuments: string index CSIDL_COMMON_DOCUMENTS read GetCSIDLDir; class property Pictures: string index CSIDL_MYPICTURES read GetCSIDLDir; class property CommonPictures: string index CSIDL_COMMON_PICTURES read GetCSIDLDir; class property Music: string index CSIDL_MYMUSIC read GetCSIDLDir; class property CommonMusic: string index CSIDL_COMMON_MUSIC read GetCSIDLDir; class property Video: string index CSIDL_MYVIDEO read GetCSIDLDir; class property CommonVideo: string index CSIDL_COMMON_VIDEO read GetCSIDLDir; class property AdminTools: string index CSIDL_ADMINTOOLS read GetCSIDLDir; class property CommonAdminTools: string index CSIDL_COMMON_ADMINTOOLS read GetCSIDLDir; class property Favorites: string index CSIDL_FAVORITES read GetCSIDLDir; class property CommonFavorites: string index CSIDL_COMMON_FAVORITES read GetCSIDLDir; class property StartMenu: string index CSIDL_STARTMENU read GetCSIDLDir; class property CommonStartMenu: string index CSIDL_COMMON_STARTMENU read GetCSIDLDir; class property StartMenuPrograms: string index CSIDL_PROGRAMS read GetCSIDLDir; class property CommonStartMenuPrograms: string index CSIDL_COMMON_PROGRAMS read GetCSIDLDir; class property StartUp: string index CSIDL_STARTUP read GetCSIDLDir; class property CommonStartUp: string index CSIDL_COMMON_STARTUP read GetCSIDLDir; class property Templates: string index CSIDL_TEMPLATES read GetCSIDLDir; class property CommonTemplates: string index CSIDL_COMMON_TEMPLATES read GetCSIDLDir; class property Cookies: string index CSIDL_COOKIES read GetCSIDLDir; class property DiscBurnArea: string index CSIDL_CDBURN_AREA read GetCSIDLDir; class property History: string index CSIDL_HISTORY read GetCSIDLDir; class property NetHood: string index CSIDL_NETHOOD read GetCSIDLDir; class property PrintHood: string index CSIDL_PRINTHOOD read GetCSIDLDir; class property Recent: string index CSIDL_RECENT read GetCSIDLDir; class property SendTo: string index CSIDL_SENDTO read GetCSIDLDir; class property ByCSIDL[const CSIDL: Integer]: string read GetCSIDLDir; end; //////////////////////////////////////////////////////////////////////////////////////////////////// implementation uses Windows, SysUtils, ComObj, Classes, IOUtils; var TempFolders: TStringList; type TStringAPICallback = reference to function(lpBuffer: PChar; nSize: Cardinal): Cardinal; { ------------------------------------------------------------------------------------------------ } function CallAPIStringFunction(const Callback: TStringAPICallback; const InitialSize: integer = MAX_PATH): string; var iSize, iResult, iError: integer; begin iSize := InitialSize; repeat SetLength(Result, iSize); iResult := Callback(PChar(Result), iSize); iError := GetLastError; if iResult = 0 then begin if iError = ERROR_SUCCESS then begin Result := ''; Exit; end else begin RaiseLastOSError; end; end else if iResult >= iSize then begin iSize := iResult + 1; end else begin SetLength(Result, iResult); Break; end; until iResult < iSize; end {GetStringFromAPI}; { ================================================================================================ } { TSpecialFolders } { ------------------------------------------------------------------------------------------------ } class procedure TSpecialFolders.AddTempFolder(const TempDir: string); begin if not DirectoryExists(TempDir) then begin if not Assigned(TempFolders) then TempFolders := TStringList.Create; TempFolders.Add(TempDir); end; end {TSpecialFolders.AddTempFolder}; { ------------------------------------------------------------------------------------------------ } class procedure TSpecialFolders.DeleteTempFolders; var i: Integer; begin if Assigned(TempFolders) then begin for i := TempFolders.Count - 1 downto 0 do begin // remove all files first TDirectory.Delete(TempFolders[i], True); RemoveDir(TempFolders[i]); end; FreeAndNil(TempFolders); end; end {TSpecialFolders.DeleteTempFolders}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetCSIDLDir(const CSIDL: Integer): string; var Buffer: array[0..MAX_PATH] of Char; PBuffer: PChar; begin PBuffer := PChar(@Buffer[0]); OleCheck(SHGetFolderPath(0, CSIDL or CSIDL_FLAG_CREATE, GetHToken, SHGFP_TYPE_CURRENT, PBuffer)); Result := IncludeTrailingPathDelimiter(string(PBuffer)); end {TSpecialFolders.GetCSIDLDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetDll: string; begin Result := GetModulePathName(HInstance); end {TSpecialFolders.GetDll}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetDllDir: string; begin Result := ExtractFilePath(GetDll); end {TSpecialFolders.GetDllDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetDllBaseName: string; begin Result := ChangeFileExt(ExtractFileName(GetDll), ''); end {TSpecialFolders.GetDllName}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetExe: string; begin Result := GetModulePathName(0); end {TSpecialFolders.GetExe}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetExeDir: string; begin Result := ExtractFilePath(GetExe); end {TSpecialFolders.GetExeDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetHToken: Cardinal; begin Result := 0; // use `High(Cardinal)` instead of `0` for default user's paths end {TSpecialFolders.GetHToken}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetExeBaseName: string; begin Result := ChangeFileExt(ExtractFileName(GetExe), ''); end {TSpecialFolders.GetExeName}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetModulePathName(const hInst: Cardinal): string; begin Result := CallAPIStringFunction( function(lpBuffer: PChar; nSize: Cardinal): Cardinal begin Result := GetModuleFileName(hInst, lpBuffer, nSize); end); if SameStr(Copy(Result, 1, 4), '\\?\') then Result := Copy(Result, 5); end {TSpecialFolders.GetModulePathName}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetTempDir(const Index: Integer): string; begin Result := CallAPIStringFunction( function(lpBuffer: PChar; nSize: Cardinal): Cardinal begin Result := GetTempPath(nSize, lpBuffer); end); if Index in [1, 3] then begin Result := Result + IncludeTrailingPathDelimiter(GetExeBaseName); AddTempFolder(Result); end; if (Index = 2) or ((Index = 3) and not SameFileName(GetExe, GetDll)) then begin Result := Result + IncludeTrailingPathDelimiter(GetDllBaseName); AddTempFolder(Result); end; ForceDirectories(Result); end {TSpecialFolders.GetTempDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetWindowsDir: string; begin Result := CallAPIStringFunction( function(lpBuffer: PChar; nSize: Cardinal): Cardinal begin Result := GetWindowsDirectory(lpBuffer, nSize); end); Result := IncludeTrailingPathDelimiter(Result); end {TSpecialFolders.GetWindowsDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.GetWindowsSysDir: string; begin Result := CallAPIStringFunction( function(lpBuffer: PChar; nSize: Cardinal): Cardinal begin Result := GetSystemDirectory(lpBuffer, nSize); end); Result := IncludeTrailingPathDelimiter(Result); end {TSpecialFolders.GetWindowSysDir}; { ------------------------------------------------------------------------------------------------ } class function TSpecialFolders.Settings(Flags: TSettingsFlags): string; var CSIDL: Integer; begin if not (sfUserSpecific in Flags) then CSIDL := CSIDL_COMMON_APPDATA else if sfMachineSpecific in Flags then CSIDL := CSIDL_LOCAL_APPDATA else CSIDL := CSIDL_APPDATA ; Result := GetCSIDLDir(CSIDL); if (sfExeSpecific in Flags) then begin Result := Result + IncludeTrailingPathDelimiter(GetExeBaseName); end; if (sfDllSpecific in Flags) and not ((sfExeSpecific in Flags) and SameFilename(GetExe, GetDll)) then begin Result := Result + IncludeTrailingPathDelimiter(GetDllBaseName); end; ForceDirectories(Result); end {TSpecialFolders.SettingsDir}; //////////////////////////////////////////////////////////////////////////////////////////////////// initialization finalization TSpecialFolders.DeleteTempFolders; end.
unit UnitOpenGLImage; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpu386} {$asmmode intel} {$endif} {$ifdef cpuamd64} {$asmmode intel} {$endif} {$ifdef fpc_little_endian} {$define little_endian} {$else} {$ifdef fpc_big_endian} {$define big_endian} {$endif} {$endif} {$ifdef fpc_has_internal_sar} {$define HasSAR} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$else} {$realcompatibility off} {$localsymbols on} {$define little_endian} {$ifndef cpu64} {$define cpu32} {$endif} {$define delphi} {$undef HasSAR} {$define UseDIV} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$define HAS_TYPE_SINGLE} {$endif} {$ifdef cpu386} {$define cpux86} {$endif} {$ifdef cpuamd64} {$define cpux86} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$ifdef windows} {$define win} {$endif} {$ifdef sdl20} {$define sdl} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} {$ifndef HAS_TYPE_DOUBLE} {$error No double floating point precision} {$endif} {$ifdef fpc} {$define caninline} {$else} {$undef caninline} {$ifdef ver180} {$define caninline} {$else} {$ifdef conditionalexpressions} {$if compilerversion>=18} {$define caninline} {$ifend} {$endif} {$endif} {$endif} interface uses {$ifdef fpcgl}gl,glext{$else}dglOpenGL{$endif}; function LoadImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean=false;MipMapLevel:longint=0;IsFloat:pboolean=nil):boolean; implementation uses Math,UnitOpenGLImagePNG,UnitOpenGLImageJPEG; function LoadImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean=false;MipMapLevel:longint=0;IsFloat:pboolean=nil):boolean; var IsFloatTemp:boolean; i:longint; pf:psingle; pb:pbyte; begin if assigned(IsFloat) then begin IsFloat^:=false; end; IsFloatTemp:=false; if (MipMapLevel=0) and LoadPNGImage(DataPointer,DataSize,ImageData,ImageWidth,ImageHeight,HeaderOnly) then begin result:=true; end else begin if assigned(IsFloat) then begin IsFloat^:=false; end; result:=LoadJPEGImage(DataPointer,DataSize,ImageData,ImageWidth,ImageHeight,HeaderOnly); end; if assigned(IsFloat) then begin IsFloat^:=IsFloatTemp; end else begin if IsFloatTemp then begin pf:=ImageData; pb:=ImageData; for i:=1 to (ImageWidth*ImageHeight)*4 do begin pb^:=Min(Max(round(pf^*255.0),0),255); inc(pf); inc(pb); end; end; end; end; initialization finalization end.
unit MyXMLParser; interface uses Classes, SysUtils; type TSetOfChar = Set of ANSIChar; TAttr = record Name: String; Value: String; Compare: Char; qtype: boolean; end; TAttrs = array of TAttr; TAttrList = class(TObject) private FAttrs: TAttrs; FTag: Integer; FNoParam: boolean; function GetCount: Integer; function GetNoParam: boolean; protected function GetAttr(AValue: Integer): TAttr; public procedure Assign(AAttrs: TAttrList); property Attribute[AValue: Integer]: TAttr read GetAttr; default; property Count: Integer read GetCount; procedure Add(AName: String; AValue: String; ACompVal: Char = #0; AQType: boolean = false); procedure Clear; function Value(AName: String): String; function IndexOf(AName: String): Integer; function AsString: String; constructor Create; destructor Destroy; override; property Tag: Integer read FTag write FTag; property NoParameters: boolean read GetNoParam write FNoParam; end; TTagList = class; TTagKind = (tkTag, tkInstruction, tkDeclaration, tkComment, tkText); TTextKind = (txkFullWithTags, txkFull, txkCurrent); TTagState = (tsNormal, tsOnlyText, tsClosable); TContentState = (csUnknown, csEmpty, csContent); TTag = class(TObject) private FParent: TTag; FName: String; FAttrList: TAttrList; // FText: String; FChilds: TTagList; FKind: TTagKind; FClosed: boolean; FTag: Integer; fState: TTagState; fCState: TContentState; protected procedure SetName(Value: String); procedure SetText(Value: String); function GetText: String; overload; public constructor Create(AName: String = ''; AKind: TTagKind = tkTag); destructor Destroy; override; function FindParent(TagString: String; ignoreState: boolean = false): TTag; function GetText(TextKind: TTextKind; AddOwnTag: boolean): string; overload; property Name: String read FName write SetName; property Attrs: TAttrList read FAttrList { write FAttrList }; property Text: String read GetText write SetText; property Childs: TTagList read FChilds; property Parent: TTag read FParent write FParent; property Kind: TTagKind read FKind write FKind; property Closed: boolean read FClosed write FClosed; property Tag: Integer read FTag write FTag; property State: TTagState read fState write fState; property ContentState: TContentState read fCState write fCState; end; tTagCommentStates = (tcsContent, tcsHelp); tTagCommentState = set of tTagCommentStates; TTagList = class(TList) protected function Get(ItemIndex: Integer): TTag; procedure Notify(Ptr: Pointer; Action: TListNotification); override; public procedure GetList(Tag: String; AAttrs: TAttrList; AList: TTagList); overload; procedure GetList(Tags: array of string; AAttrs: array of TAttrList; AList: TTagList); overload; procedure GetGroupList(Tags: array of string; AAttrs: array of TAttrList; AList: TTagList); procedure CopyList(AList: TTagList; Parent: TTag); procedure ExportToFile(FName: string; Comments: tTagCommentState = []); function FirstItemByName(tagname: string): TTag; function Text(Comments: tTagCommentState): String; overload; function Text: String; overload; destructor Destroy; override; property Items[ItemName: Integer]: TTag read Get; default; function CreateChild(Parent: TTag; AName: String = ''; TagKind: TTagKind = tkTag): TTag; function CopyTag(ATag: TTag; Parent: TTag = nil): TTag; end; TXMLOnTagEvent = procedure(ATag: TTag) of object; TXMLOnEndTagEvent = procedure(ATag: String) of object; TXMLOnContentEvent = procedure(ATag: TTag; AContent: String) of object; TMyXMLParser = class(TObject) // New realisation little beter then old private FOnStartTag, FOnEmptyTag, FOnEndTag: TXMLOnTagEvent; FOnContent: TXMLOnContentEvent; // : TXMLOnEndTagEvent; // : TXMLOnContentEvent; FTagList: TTagList; protected procedure CheckHTMLTag(Tag: TTag); function CheckHTMLStat(Tag: string): TContentState; public procedure JSON(starttag: string; const S: TStrings); overload; procedure JSON(starttag: string; S: String); overload; destructor Destroy; override; constructor Create; property OnStartTag: TXMLOnTagEvent read FOnStartTag write FOnStartTag; property OnEmptyTag: TXMLOnTagEvent read FOnEmptyTag write FOnEmptyTag; property OnEndTag: TXMLOnTagEvent read FOnEndTag write FOnEndTag; property OnContent: TXMLOnContentEvent read FOnContent write FOnContent; procedure Parse(S: String; html: boolean = false); overload; // need to make TStream parse procedure Parse(S: TStrings; html: boolean = false); overload; // can be useful to parse direct filestream without loading memory procedure LoadFromFile(FileName: String; html: boolean = false); property TagList: TTagList read FTagList; end; procedure JSONParseChilds(Parent: TTag; TagList: TTagList; tagname, S: string); procedure JSONParseValue(Tag: TTag; TagList: TTagList; S: string); procedure JSONParseTag(Tag: TTag; TagList: TTagList; S: String); implementation { COMMON } function TrimEx(S: String; ch: Char = ' '): String; overload; var i, l: Integer; begin l := length(S); i := 1; while (i <= l) and (S[i] = ch) do inc(i); if i > l then Result := '' else begin while S[l] = ch do dec(l); Result := copy(S, i, l - i + 1); end; end; function TrimEx(S: String; ch: TSetOfChar): String; overload; var i, l: Integer; begin l := length(S); i := 1; while (i <= l) and (CharInSet(S[i], ch)) do inc(i); if i > l then Result := '' else begin while CharInSet(S[l], ch) do dec(l); Result := copy(S, i, l - i + 1); end; end; function CharPos(str: string; ch: Char; Isolators, Brackets: array of string; From: Integer = 1): Integer; var i, j: Integer; // n: integer; { s1, } s2: Char; { b1, } b2: array of Char; st, br: TSetOfChar; begin st := []; for i := 0 to length(Isolators) - 1 do st := st + [Isolators[i][1]]; br := []; for i := 0 to length(Brackets) - 1 do br := br + [Brackets[i][1]]; // setlength(b1,0); setlength(b2, 0); // n := 0; // s1 := #0; s2 := #0; for i := From to length(str) do if s2 <> #0 then if str[i] = s2 then s2 := #0 else else if (length(b2) > 0) and (str[i] = b2[length(b2) - 1]) then setlength(b2, length(b2) - 1) // else // if CharInSet(str[i],br) then // begin // for j := 0 to length(Brackets) - 1 do // if (str[i] = Brackets[j][1]) then // begin // setlength(b2,length(b2)+1); // b2[length(b2)-1] := Brackets[j][2]; // break; // end; // end else else if (length(b2) = 0) and (str[i] = ch) then begin Result := i; Exit; end else if CharInSet(str[i], st) then begin for j := 0 to length(Isolators) - 1 do if (str[i] = Isolators[j][1]) then begin // s1 := Isolators[j][1]; s2 := Isolators[j][2]; break; end; // inc(n); end else if CharInSet(str[i], br) then begin for j := 0 to length(Brackets) - 1 do if (str[i] = Brackets[j][1]) then begin // setlength(b1,length(b1)+1); setlength(b2, length(b2) + 1); // b1[length(b1)-1] := Brackets[j][1]; b2[length(b2) - 1] := Brackets[j][2]; break; end; end; Result := 0; end; function CopyTo(var Source: String; ATo: Char; Isl, Brk: array of string; cut: boolean = false): string; var i: Integer; begin i := CharPos(Source, ATo, Isl, Brk); if i = 0 then Result := copy(Source, 1, length(Source)) else Result := copy(Source, 1, i - 1); if cut then if i = 0 then Delete(Source, 1, length(Source)) else Delete(Source, 1, i); end; function GetNextS(var S: string; del: String = ';'; ins: String = ''): string; var n: Integer; begin Result := ''; if ins <> #0 then while true do begin n := pos(ins, S); if (n > 0) and (pos(del, S) > n) then begin Result := Result + copy(S, 1, n - 1); Delete(S, 1, n + length(ins) - 1); n := pos(ins, S); case n of 0: raise Exception.Create('Can''t find 2nd insulator ''' + ins + ''':' + #13#10 + S); 1: Result := Result + copy(S, 1, n + length(ins) - 1); else Result := Result + copy(S, 1, n - 1); end; Delete(S, 1, n + length(ins) - 1); end else break; end; n := pos(del, S); if n > 0 then begin Result := Result + copy(S, 1, n - 1); Delete(S, 1, n + length(del) - 1); end else begin Result := Result + S; S := ''; end; end; { *********** JSON ******************** } const JSONISL: array [0 .. 0] of string = ('""'); JSONBRK: array [0 .. 1] of string = ('[]', '{}'); // parse childs procedure JSONParseChilds(Parent: TTag; TagList: TTagList; tagname, S: string); var n: string; Tag: TTag; begin while S <> '' do begin n := Trim(CopyTo(S, ',', JSONISL, JSONBRK, true)); Tag := TagList.CreateChild(Parent); Tag.Name := tagname; // tag.Attrs := TAttrList.Create; if n <> '' then case n[1] of '[': JSONParseChilds(Tag, TagList, '', copy(n, 2, length(n) - 2)); '{': JSONParseTag(Tag, TagList, copy(n, 2, length(n) - 2)); else if CharPos(n, ':', JSONISL, JSONBRK) = -1 then Tag.Childs.CreateChild(Tag, n, tkText) else JSONParseValue(Tag, TagList, n); end; // JSONParseValue(tag,TagList,trim(n)); end; end; // parsetag procedure JSONParseValue(Tag: TTag; TagList: TTagList; S: string); var tagname: string; Value: string; child: TTag; begin if S = '' then raise Exception.Create('JSON Parse: empty value'); // s := StringReplace(s,'\\','&#92;',[rfReplaceAll]); S := StringReplace(S, '\"', '&quot;', [rfReplaceAll]); tagname := TrimEx(CopyTo(S, ':', JSONISL, JSONBRK, true), [' ', '"']); S := TrimEx(S, [' ', '"']); if S = '' then begin Value := tagname; tagname := ''; end else Value := S; case Value[1] of '{': begin child := TagList.CreateChild(Tag, tagname); // child.Name := tagname; // child.Attrs := TAttrList.Create; JSONParseTag(child, TagList, copy(Value, 2, length(Value) - 2)); end; '[': JSONParseChilds(Tag, TagList, tagname, copy(Value, 2, length(Value) - 2)); else begin if Tag = nil then begin Tag := TagList.CreateChild(nil); // tag.Attrs := TAttrList.Create; end; if tagname = '' then Tag.Childs.CreateChild(Tag, TrimEx(Value, '"'), tkText) else Tag.Attrs.Add(tagname, Value); end; end; end; procedure JSONParseTag(Tag: TTag; TagList: TTagList; S: String); var n: string; begin while S <> '' do begin n := Trim(CopyTo(S, ',', JSONISL, JSONBRK, true)); JSONParseValue(Tag, TagList, n); end; end; { *********** JSON ******************** } procedure WriteList(List: TTagList; var S: String; Comments: tTagCommentState); const qbool: array [boolean] of String = ('"', ''''); var i, j: Integer; tmp: string; begin for i := 0 to List.Count - 1 do begin if List[i].Kind = tkText then S := S + List[i].Name else if (List[i].Kind = tkComment) then if tcsContent in Comments then S := S + '<!--' + List[i].Name + '-->' else else if List[i].Kind = tkDeclaration then S := S + '<!' + List[i].Name + '>' else if List[i].Kind = tkInstruction then begin tmp := List[i].Name; for j := 0 to List[i].Attrs.Count - 1 do tmp := tmp + ' ' + List[i].Attrs[j].Name + '=' + qbool[List[i].Attrs[j].qtype] + List[i].Attrs[j].Value + qbool[List[i].Attrs[j].qtype]; S := S + '<?' + tmp + '?>'; end else begin tmp := '<' + List[i].Name; for j := 0 to List[i].Attrs.Count - 1 do tmp := tmp + ' ' + List[i].Attrs[j].Name + '=' + qbool[List[i].Attrs[j].qtype] + List[i].Attrs[j].Value + qbool[List[i].Attrs[j].qtype]; if not List[i].Closed and (List[i].Childs.Count = 0) and not(List[i].ContentState in [csContent]) then S := S + tmp + ' />' else begin S := S + (tmp + '>'); WriteList(List[i].Childs, S, Comments); if (tcsHelp in Comments) and (List[i].Attrs.Count > 0) then begin S := S + '</' + List[i].Name + '><!--'; for j := 0 to List[i].Attrs.Count - 1 do S := S + ' ' + List[i].Attrs[j].Name + '=' + qbool[List[i].Attrs[j].qtype] + List[i].Attrs[j].Value + qbool[List[i].Attrs[j].qtype]; S := S + ' -->'; end else S := S + '</' + List[i].Name + '>'; end; end; end; end; procedure TTagList.Notify(Ptr: Pointer; Action: TListNotification); var p: TTag; begin case Action of lnDeleted: begin p := Ptr; // if p is TTag then p.Free; end; end; end; function TTagList.Text(Comments: tTagCommentState): String; begin Result := ''; WriteList(Self, Result, Comments); end; function TTagList.Text: String; begin Result := Text([tcsContent]); end; function TTagList.Get(ItemIndex: Integer): TTag; begin Result := inherited Get(ItemIndex); end; function CheckRule(v1, v2: string; r: Char): boolean; var tmp: string; begin if (v1 = '') then begin case r of '!': Result := v2 <> ''; '=': Result := v2 = ''; else raise Exception.Create('Check Rule: unknown operation "' + r + '"'); end; Exit; end; if pos(' ', v2) > 0 then // string with spaces begin Result := SameText(v1, v2); Exit; end; while v1 <> '' do begin tmp := GetNextS(v1, ' '); // tags case r of '!': if SameText(tmp, v2) then begin Result := false; Exit; end; else if SameText(tmp, v2) then begin Result := true; Exit; end; end; end; case r of '!': Result := true; '=': Result := false; else raise Exception.Create('Check Rule: unknown operation "' + r + '"'); end; end; procedure TTagList.GetList(Tag: String; AAttrs: TAttrList; AList: TTagList); var i, j: Integer; b: boolean; S: string; begin // if not Assigned(AAttrs) then // Exit; for i := 0 to Count - 1 do if (Items[i].Kind = tkTag) then if SameText(Items[i].Name, Tag) and not(Assigned(AAttrs) and AAttrs.NoParameters and (Items[i].Attrs.Count > 0)) then begin b := true; if Assigned(AAttrs) then for j := 0 to AAttrs.Count - 1 do begin S := Items[i].Attrs.Value(AAttrs[j].Name); if not CheckRule(S, AAttrs[j].Value, AAttrs[j].Compare) and not((AAttrs[j].Value = '') and (S <> '')) then begin b := false; break; end; end; if b then AList.CopyTag(Items[i]) else Items[i].Childs.GetList(Tag, AAttrs, AList); end else Items[i].Childs.GetList(Tag, AAttrs, AList); end; procedure TTagList.GetList(Tags: array of string; AAttrs: array of TAttrList; AList: TTagList); var i, j, l, lx: Integer; b: boolean; S: string; t: TTag; begin // Tag := lowercase(Tag); lx := 0; if length(Tags) <> length(AAttrs) then raise Exception.Create('Incorrect tags and parameters count'); for i := 0 to Count - 1 do if (Items[i].Kind = tkTag) then begin //b := false; if lx = length(Tags) then lx := 0; for l := 0 to length(Tags) - 1 do if SameText(Items[i].Name, Tags[l]) and not(Assigned(AAttrs[l]) and AAttrs[l].NoParameters { and (Items[i].Attrs.Count > 0) } ) then begin b := true; if Assigned(AAttrs[l]) then for j := 0 to AAttrs[l].Count - 1 do begin S := Items[i].Attrs.Value(AAttrs[l][j].Name); if not CheckRule(S, AAttrs[l][j].Value, AAttrs[l][j].Compare) and not((AAttrs[l][j].Value = '') and (S <> '')) then begin b := false; break; end; end; if b then begin //lx := l + 1; t := AList.CopyTag(Items[i]); if Assigned(AAttrs[l]) then t.Tag := AAttrs[l].Tag; break; end; end //else // break; // if not b then // Items[i].Childs.GetList(Tags,AAttrs,AList); end; end; procedure TTagList.GetGroupList(Tags: array of string; AAttrs: array of TAttrList; AList: TTagList); var i, j, l, lx: Integer; b: boolean; S: string; t: TTag; begin // Tag := lowercase(Tag); lx := 0; if length(Tags) <> length(AAttrs) then raise Exception.Create('Incorrect tags and parameters count'); for i := 0 to Count - 1 do if (Items[i].Kind = tkTag) then begin //b := false; if lx = length(Tags) then lx := 0; for l := lx to length(Tags) - 1 do if SameText(Items[i].Name, Tags[l]) and not(Assigned(AAttrs[l]) and AAttrs[l].NoParameters { and (Items[i].Attrs.Count > 0) } ) then begin b := true; if Assigned(AAttrs[l]) then for j := 0 to AAttrs[l].Count - 1 do begin S := Items[i].Attrs.Value(AAttrs[l][j].Name); if not CheckRule(S, AAttrs[l][j].Value, AAttrs[l][j].Compare) and not((AAttrs[l][j].Value = '') and (S <> '')) then begin b := false; break; end; end; if b then begin lx := l + 1; t := AList.CopyTag(Items[i]); if Assigned(AAttrs[l]) then t.Tag := AAttrs[l].Tag; break; end; end else break; // if not b then // Items[i].Childs.GetList(Tags,AAttrs,AList); end; end; function TTagList.CreateChild(Parent: TTag; AName: String = ''; TagKind: TTagKind = tkTag): TTag; begin if (TagKind in [tkText]) and (AName = '') then begin Result := nil; Exit; end; Result := TTag.Create(AName, TagKind); Result.Parent := Parent; if Parent <> nil then Parent.Childs.Add(Result) else Add(Result); end; destructor TTagList.Destroy; begin Clear; inherited; end; procedure TTagList.ExportToFile(FName: string; Comments: tTagCommentState); var S: tstringlist; st: string; begin st := ''; S := tstringlist.Create; try WriteList(Self, st, Comments); S.Text := st; S.SaveToFile(FName, TEncoding.UTF8); finally S.Free; end; end; function TTagList.FirstItemByName(tagname: string): TTag; var i: Integer; begin for i := 0 to Count - 1 do if SameText(Items[i].Name, tagname) then begin Result := Items[i]; Exit; end; Result := nil; end; procedure TTagList.CopyList(AList: TTagList; Parent: TTag); var i: Integer; begin for i := 0 to AList.Count - 1 do CopyTag(AList[i], Parent); end; function TTagList.CopyTag(ATag: TTag; Parent: TTag = nil): TTag; { var p: TTag; } begin Result := CreateChild(Parent); Result.Name := ATag.Name; Result.Kind := ATag.Kind; // p.Text := ATag.Text; // p.Attrs := TAttrList.Create; Result.Attrs.Assign(ATag.Attrs); Result.Childs.CopyList(ATag.Childs, Result); Result.Tag := ATag.Tag; // Add(p); end; constructor TTag.Create(AName: String = ''; AKind: TTagKind = tkTag); begin inherited Create; FChilds := TTagList.Create; FAttrList := TAttrList.Create; FParent := nil; Name := AName; FKind := AKind; FClosed := false; // FAttrList := TAttrList.Create; FTag := 0; fState := tsNormal; fCState := csUnknown; end; destructor TTag.Destroy; begin FChilds.Free; FAttrList.Free; inherited; end; function TTag.FindParent(TagString: String; ignoreState: boolean = false): TTag; var p: TTag; begin // TagString := lowercase(TagString); if SameText(Name, TagString) then begin Result := Self; Exit; end else begin p := Parent; while Assigned(p) and (ignoreState or (p.State = tsClosable)) do if SameText(p.Name, TagString) then begin Result := p; Exit; end else p := p.Parent end; Result := nil; end; procedure TTag.SetName(Value: String); begin FName := Value; end; function TTag.GetText(TextKind: TTextKind; AddOwnTag: boolean): string; var i: Integer; function AttrString: String; begin if FAttrList.Count = 0 then Result := '' else Result := ' ' + FAttrList.AsString; end; begin if FKind = tkText then Result := FName else begin Result := ''; case TextKind of txkFullWithTags, txkFull: for i := 0 to Childs.Count - 1 do Result := Result + Childs[i].GetText(TextKind, AddOwnTag); txkCurrent: for i := 0 to Childs.Count - 1 do if Childs[i].Kind = tkText then Result := Result + Childs[i].Text; end; if AddOwnTag and (FKind = tkTag) then if Result = '' then Result := '<' + FName + AttrString + ' />' else Result := '<' + FName + AttrString + '>' + Result + '</' + FName + '>'; end; end; function TTag.GetText: String; begin Result := GetText(txkFull, false); end; procedure TTag.SetText(Value: String); begin if FKind = tkText then FName := Value; { if Assigned(FParent) then FParent.Text := FParent.Text + Value; } end; function TAttrList.GetAttr(AValue: Integer): TAttr; begin Result := FAttrs[AValue]; end; function TAttrList.GetCount: Integer; begin Result := length(FAttrs); end; function TAttrList.GetNoParam: boolean; begin Result := FNoParam and not(Count > 0); end; procedure TAttrList.Add(AName: String; AValue: String; ACompVal: Char = #0; AQType: boolean = false); begin if AName = '' then Exit; setlength(FAttrs, length(FAttrs) + 1); with FAttrs[length(FAttrs) - 1] do begin Name := AName; Value := AValue; Compare := ACompVal; qtype := AQType; end; // FNoParam := false; end; procedure TAttrList.Assign(AAttrs: TAttrList); var i: Integer; begin setlength(FAttrs, AAttrs.Count); for i := 0 to AAttrs.Count - 1 do begin FAttrs[i].Name := AAttrs[i].Name; FAttrs[i].Value := AAttrs[i].Value; end; end; procedure TAttrList.Clear; begin FAttrs := nil; end; function TAttrList.Value(AName: String): String; var i: Integer; begin for i := 0 to length(FAttrs) - 1 do if SameText(FAttrs[i].Name, AName) then begin Result := FAttrs[i].Value; Exit; end; Result := ''; end; function TAttrList.IndexOf(AName: String): Integer; var i: Integer; begin Result := -1; for i := 0 to length(FAttrs) - 1 do if SameText(FAttrs[i].Name, AName) then begin Result := i; break; end; end; function TAttrList.AsString: String; var i: Integer; begin Result := ''; for i := 0 to Count - 1 do if Result = '' then Result := Attribute[i].Name + '="' + Attribute[i].Value + '"' else Result := Result + ' ' + Attribute[i].Name + '="' + Attribute[i] .Value + '"' end; constructor TAttrList.Create; begin inherited; FAttrs := nil; FNoParam := true; end; destructor TAttrList.Destroy; begin FAttrs := nil; inherited; end; procedure TMyXMLParser.Parse(S: String; html: boolean = false); var i: Integer; // counter l: Integer; // string length qt: byte; // 0 - no quotes, 1 - ", 2 - ' istag: byte; // 0 - not a tag, 1 - searching tag bounds, 2 - creating tag lbr, rbr: Integer; // < and > pos lstart: Integer; // start copy position, is first symbol after tag ends ps, pe: Integer; // param's start and end tps, tpe: Integer; // remembered start and end of parameter before equal sign, // little fix to avoid stupid // using of isolator symbols inside isolated strings vs, ve: Integer; // value's start and end qtp: Integer; // quote pos, need to know, which type used last time eq: Integer; // equal sign pos isparam: boolean; // true - param part, false - value part; comm: byte; // is comment instr: boolean; // is xml instructions closetag: boolean; // is tag closing FTag: TTag; // current tag tmpTag: TTag; // temporary tag procedure tag_separate; begin if (istag <> 0) and (comm = 0) then // if is tag creating mode begin if isparam then begin if (pe < lbr) and (istag = 2) and not closetag then // create tag if it is tag name (first param) if Assigned(FTag) then FTag := FTag.Childs.CreateChild(FTag, copy(S, ps, i - ps), tkTag) else FTag := FTagList.CreateChild(FTag, copy(S, ps, i - ps), tkTag); if Assigned(FTag) and closetag then // if is tag closing begin // find what we closing, and return to it's parent if (FTag.State in [tsOnlyText]) // if is text only mode and not SameText(FTag.Name, copy(S, ps, i - ps)) then // and close tag not the same as current tag istag := 0 // just leave tag without actions else begin tmpTag := FTag.FindParent(copy(S, ps, i - ps), true); if Assigned(tmpTag) then begin tmpTag.Closed := true; // mark as "we are closed it with our hand" // not all tags closes by us, some of them just thrown opened // using it we can handle it FTag := tmpTag.Parent; end; closetag := false; if istag = 1 then // if is searching mode then not need to go into create mode istag := 0; end; end; // else // closetag := false; if pe < ps then pe := i - 1; end else if (vs > eq) then begin if (ve < eq) then ve := i - 1; isparam := true; end; end; end; procedure attr_add; // create parameter procedure begin // usualy call after SECOND parameter called or in the end of tag if (istag = 2) and (vs > eq) and (tps > lbr) and (tpe < eq) then if (qtp > eq) and (S[qtp] = '''') then FTag.Attrs.Add(copy(S, tps, tpe - tps + 1), copy(S, vs, ve - vs + 1), #0, true) else FTag.Attrs.Add(copy(S, tps, tpe - tps + 1), copy(S, vs, ve - vs + 1), #0, false); end; begin // if not Assigned(FTagList) then // FTagList := TTagList.Create // else FTagList.Clear; i := 1; l := length(S); lstart := 1; qt := 0; eq := 0; istag := 0; lbr := 0; rbr := 0; ps := 0; pe := 0; qtp := 0; vs := 0; ve := 0; FTag := nil; comm := 0; instr := false; closetag := false; while i <= l do begin case S[i] of '<': // left bracket starts tag begin if qt = 0 then // ignore isolated brackets begin case istag of 0: begin if not Assigned(FTag) // if is "OnlyText" State (ex. javascript content) or not(FTag.State in [tsOnlyText]) or (i < l) and (S[i + 1] = '/') then begin istag := 1; // if is non-tag then going to "searching tag" mode lbr := i; ps := 0; pe := 0; tps := 0; tpe := 0; vs := 0; ve := 0; isparam := true; instr := false; end; end; 1: if comm = 0 then lbr := i; // if multiple '<' then all previous will be ignored (and going to the non-tag part) // it happens in bad xml and we're need to solve it somehow 2: begin isparam := true; // next text will be param ps := 0; pe := 0; tps := 0; tpe := 0; vs := 0; ve := 0; instr := false; // comm := false; end; end; end; end; '>': // right bracket ends tag begin if qt = 0 then // ignore isolated brackets begin // rbr := i; case istag of 1: begin if ps > lbr then begin rbr := i; if Assigned(FTag) then // add all non-tag text to the current tag FTag.Childs.CreateChild(FTag, copy(S, lstart, lbr - lstart), tkText) else FTagList.CreateChild(nil, copy(S, lstart, lbr - lstart), tkText); tag_separate; if istag = 1 then // can be changed in tag_separate if is tag closing begin istag := 2; // if is searching tag mode then going to creating tag mode i := lbr - 1; end else if not Assigned(FTag) or not(FTag.State in [tsOnlyText] ) or FTag.Closed then lstart := i + 1; end else if comm > 0 then begin if (comm = 3) and ((i - lbr) > 5) then if (S[i - 1] = '-') and (S[i - 2] = '-') then begin rbr := i; if Assigned(FTag) then // add all non-tag text to the current tag begin FTag.Childs.CreateChild(FTag, copy(S, lstart, lbr - lstart), tkText); FTag.Childs.CreateChild(FTag, copy(S, lbr + 4, i - lbr - 6), tkComment); end else begin FTagList.CreateChild(nil, copy(S, lstart, lbr - lstart), tkText); FTagList.CreateChild(nil, copy(S, lbr + 4, i - lbr - 6), tkComment); end; comm := 0; istag := 0; lstart := i + 1; end else else begin rbr := i; if Assigned(FTag) then // add declaration string begin FTag.Childs.CreateChild(FTag, copy(S, lstart, lbr - lstart), tkText); FTag.Childs.CreateChild(FTag, copy(S, lbr + 2, i - lbr - 2), tkDeclaration) end else begin FTagList.CreateChild(nil, copy(S, lstart, lbr - lstart), tkText); FTagList.CreateChild(nil, copy(S, lbr + 2, i - lbr - 2), tkDeclaration); end; comm := 0; istag := 0; lstart := i + 1; end; end else istag := 0; end; 2: begin tag_separate; if not closetag then begin attr_add; if html then CheckHTMLTag(FTag); if (ps > lbr) then if (S[ps] = '?') and instr then begin FTag.Kind := tkInstruction; FTag := FTag.Parent; end else if (S[ps] = '/') and not(FTag.ContentState in [csContent]) or (FTag.ContentState in [csEmpty]) then // if empty tag then FTag := FTag.Parent; // return to the parent end; istag := 0; // if is creating tag mode then exit to the non-tag mode lstart := i + 1; end; end; end; end; '/': // means end of tag,if in the start of tag, then "end of the tag's content" begin // if in the end, then "end of the tag without content" aka "empty tag" if istag <> 0 then if (qt = 0) and (comm = 0) then // not quoted if lbr + 1 = i then // if in the start begin closetag := true; // mark it as is tag closing ps := i + 1; // next text must be param end else begin // mark it as parameter to check it comming in the end tag_separate; ps := i; pe := i; end; end; ' ', #13, #10, #9: // separator symbol, separate parameters begin if (istag <> 0) and (comm = 0) then if (ps = 0) then if (istag = 1) then // if param start is separator, then is invalid tag istag := 0 else i := rbr else if (qt = 0) then // if is not quoted tag_separate; end; '=': // means next text will be value of previous parameter begin if (istag <> 0) then if (qt = 0) and (comm = 0) then if (ps = 0) or closetag then // if param start is separator, then is invalid tag if istag = 1 then istag := 0 else i := rbr else // if is not quoted begin tag_separate; attr_add; eq := i; if tps <> ps then begin tps := ps; tpe := pe; isparam := false; end; end; end; '?': // if is first symbol of the tag then is xml instructions begin if istag <> 0 then if (qt = 0) and (comm = 0) then // not quoted if lbr + 1 = i then // if in the start begin instr := true; // mark it as is xml instruction ps := i + 1; // next text must be param end else // if not in the start then begin // mark it as parameter to check it comming in the end tag_separate; ps := i; pe := i; end; end; '!': // if is first symbol of the tag then is can be comment begin if istag <> 0 then if qt = 0 then // not quoted if lbr + 1 = i then // if in the start begin // comm := 1; //mark it as is comment start if ((l - i) > 1) and (S[i + 1] = '-') and (S[i + 2] = '-') then comm := 3 else comm := 1; end // // else //if not in the start then // begin //mark it as parameter to check it comming in the end // tag_separate; // ps := i; pe := i; // end; end; // '-': //possible part of comment declaration // begin // if istag <> 0 then // if qt = 0 then //not quoted // if (comm = 1) and (s[i-1] = '!') // or (comm = 2) and (s[i-1] = '-') then // inc(comm); // end; '"': // bracket 1 begin if (istag <> 0) and (comm = 0) then case qt of 0: if (vs < eq) then begin // if value not assigned qtp := i; qt := 1; vs := i + 1; end else if (qtp > eq) and (S[qtp] = S[i]) then // else it is broken value assign (with isol symbols inside) ve := i - 1; 1: begin qt := 0; ve := i - 1; end; end; end; '''': // bracket 2 begin if (istag <> 0) and (comm = 0) then case qt of 0: if (vs < eq) then begin qtp := i; qt := 2; vs := i + 1; end else if (qtp > eq) and (S[qtp] = S[i]) then ve := i - 1; 2: begin qt := 0; ve := i - 1; end; end; end; else begin if (istag <> 0) and (qt = 0) and (comm = 0) then if isparam then if (ps < lbr) or (ps <= pe) then ps := i else else if (vs < eq) then vs := i; end; end; inc(i); end; if l > rbr then if Assigned(FTag) then FTag.Childs.CreateChild(FTag, copy(S, rbr + 1, l - rbr), tkText) else FTagList.CreateChild(nil, copy(S, rbr + 1, l - rbr), tkText) end; procedure TMyXMLParser.CheckHTMLTag(Tag: TTag); begin if Assigned(Tag) then if SameText(Tag.Name, 'script') then Tag.State := tsOnlyText else if SameText(Tag.Name, 'link') or SameText(Tag.Name, 'br') or SameText(Tag.Name, 'hr') or SameText(Tag.Name, 'meta') or SameText(Tag.Name, 'img') or SameText(Tag.Name, 'input') then Tag.ContentState := csEmpty else if SameText(Tag.Name, 'a') then Tag.ContentState := csContent; // else // Tag.ContentState := csUnknown; end; constructor TMyXMLParser.Create; begin inherited; FTagList := TTagList.Create; end; destructor TMyXMLParser.Destroy; begin // if Assigned(FTagList) then FTagList.Free; inherited; end; function TMyXMLParser.CheckHTMLStat(Tag: string): TContentState; begin if SameText(Tag, 'link') or SameText(Tag, 'br') or SameText(Tag, 'hr') or SameText(Tag, 'meta') or SameText(Tag, 'img') or SameText(Tag, 'input') then Result := csEmpty else if SameText(Tag, 'a') then Result := csContent else Result := csUnknown; end; procedure TMyXMLParser.JSON(starttag: string; S: String); var i: Integer; begin // if not Assigned(FTagList) then // FTagList := TTagList.Create // else FTagList.Clear; JSONParseTag(nil, FTagList, S); for i := 0 to FTagList.Count - 1 do if FTagList[i].Name = '' then FTagList[i].Name := starttag; end; procedure TMyXMLParser.JSON(starttag: string; const S: TStrings); begin JSON(starttag, S.Text); end; procedure TMyXMLParser.Parse(S: TStrings; html: boolean = false); begin Parse(S.Text, html); end; procedure TMyXMLParser.LoadFromFile(FileName: String; html: boolean = false); var S: tstringlist; begin S := tstringlist.Create; try S.LoadFromFile(FileName); Parse(S, html); finally S.Free; end; end; end.
// MRQZZZ 2003 // Simple fire/smoke effect class // (surely needs many improvements..) unit UFireFxBase; interface Uses Windows, Classes, SysUtils, JPeg, GLScene, GLVectorFileObjects, GLObjects, GLSound, GLTexture, GLVectorGeometry, GLVectorTypes, GLMaterial; Type TFireFxSprite = class(TGLSprite) { TFireFxDummyCubeBase } public FxtkStarted: integer; Fxspeed: TVector3f; FxMatRepeats: integer; FxtkMatRepeated: integer; end; // Base Fire/Smoke/Particle effect emitter class Type TFireFxDummyCubeBase = class(TGLDummyCube) private FFxSpritesCount: integer; FFxMatLib: TGLMaterialLibrary; FFxEnabled: boolean; mustDisable: boolean; procedure SetFxSpritesCount(const Value: integer); procedure SetFxMatLib(const Value: TGLMaterialLibrary); procedure destroyAllSprites; procedure SetFxEnabled(const Value: boolean); public FxMatIndexStart: integer; // start index of Material in the Material library FxMatIndexEnd: integer; // End index of Material in the Material library FxMatIndexIncCoeff: single; // animation increment (from FxMatIndexStart to FxMatIndexEnd). FxMatIndexIncCoeff * (GetTickCount-StartTk) := Deltaindex FxMatRepeatCount: integer; // how many times we must restart from FxMatIndexStart FxSpritesParentObject: TGLBaseSceneObject; // Parent of emitted sprites FxSpritesList: TList; FXStartSize: TVector3f; FXDeltaSize: TVector3f; FXStartRotation: single; FXDeltaRotation: single; FXStartSpeed: TVector3f; FXDeltaSpeed: TVector3f; FXAccel: TVector3f; FxtkStarted: integer; // TickCount when started FXLifeLength: integer; // in milliseconds FxTkEmissiondelay: integer; // in milliseconds : delay between each sprite emission FxTkUpdatedelay: integer; // in milliseconds : delay between each sprite update (animation,position) FXTKLastEmission: integer; // TickCount when emitted last sprite FXTKLastUpdate: integer; // TickCount when done last update to sprites FxCurrenTGLSpriteIndex: integer; constructor Create(ParentObject, SpritesParentObject: TGLBaseSceneObject; AOwner: TComponent); overload; destructor destroy; override; procedure FxAdvance; virtual; property FxSpritesCount: integer read FFxSpritesCount write SetFxSpritesCount; property FxMatLib: TGLMaterialLibrary read FFxMatLib write SetFxMatLib; property FxEnabled: boolean read FFxEnabled write SetFxEnabled; end; var IsClient: boolean = false; YHeadOffset: single; implementation constructor TFireFxDummyCubeBase.Create(ParentObject, SpritesParentObject : TGLBaseSceneObject; AOwner: TComponent); begin inherited Create(AOwner); ParentObject.AddChild(self); FxSpritesParentObject := SpritesParentObject; FxSpritesList := TList.Create; FFxSpritesCount := 0; FxTkEmissiondelay := 60; FxTkUpdatedelay := 20; FXLifeLength := 1000; MakeVector(FXAccel, 0, 0, 0); MakeVector(FXStartSpeed, 0, 0, 0); MakeVector(FXStartSize, 1, 1, 0); MakeVector(FXDeltaSize, 1, 1, 1); FxMatIndexIncCoeff := 0.01; FxMatRepeatCount := 1; FXStartRotation := -1; FXDeltaRotation := 0.1; FxCurrenTGLSpriteIndex := 0; FxEnabled := false; end; destructor TFireFxDummyCubeBase.destroy; begin destroyAllSprites; inherited; end; procedure TFireFxDummyCubeBase.destroyAllSprites; var t: integer; sp: TFireFxSprite; begin for t := FxSpritesList.Count - 1 downto 0 do begin sp := TFireFxSprite(FxSpritesList[t]); sp.Parent.Remove(sp, false); sp.Free; FxSpritesList.Delete(t); end; inherited; end; // ----------- // ADVANCE // ----------- procedure TFireFxDummyCubeBase.FxAdvance; var tk, dTk: integer; sp: TFireFxSprite; P: TVector4F; t: integer; MatIdx: integer; begin tk := GetTickCount; // EMIT NEW SPRITE ? if (tk - FXTKLastEmission >= FxTkEmissiondelay) and (not mustDisable) then begin inc(FxCurrenTGLSpriteIndex); if FxCurrenTGLSpriteIndex > FxSpritesList.Count - 1 then FxCurrenTGLSpriteIndex := 0; sp := TFireFxSprite(FxSpritesList[FxCurrenTGLSpriteIndex]); sp.BeginUpdate; P := self.AbsolutePosition; sp.Position.SetPoint(P.X, P.Y, P.Z); sp.FxtkStarted := tk; sp.FxtkMatRepeated := tk; sp.Fxspeed := FXStartSpeed; sp.FxMatRepeats := 1; sp.Width := FXStartSize.X; sp.Height := FXStartSize.Y; sp.Visible := true; if FXStartRotation = -1 then sp.Rotation := random * 360 else sp.Rotation := FXStartRotation; // sp.EndUpdate; FXTKLastEmission := tk; end; // Positions/Animations updates dTk := tk - FXTKLastUpdate; if dTk >= FxTkUpdatedelay then begin for t := 0 to FxSpritesList.Count - 1 do begin sp := TFireFxSprite(FxSpritesList[t]); if sp.Visible then begin // sp.BeginUpdate; // UPDATE SPEED VectorAdd(FXAccel, sp.Fxspeed, sp.Fxspeed); VectorScale(sp.Fxspeed, dTk * 0.001 * random, sp.Fxspeed); // UPDATE POS P := sp.Position.AsVector; sp.Position.SetPoint(P.X + sp.Fxspeed.X, P.Y + sp.Fxspeed.Y, P.Z + sp.Fxspeed.Z); // Update size sp.Width := sp.Width + (FXDeltaSize.X * dTk); sp.Height := sp.Height + (FXDeltaSize.Y * dTk); // Update Rotation sp.Rotation := sp.Rotation + (FXDeltaRotation * dTk * (random)); // UPDATE MATERIAL MatIdx := FxMatIndexStart + Round(FxMatIndexIncCoeff * (tk - sp.FxtkMatRepeated)); if MatIdx > FxMatIndexEnd then begin inc(sp.FxMatRepeats); if sp.FxMatRepeats > FxMatRepeatCount then begin sp.Visible := false; // Sprite dies end else MatIdx := FxMatIndexStart; MatIdx := FxMatIndexEnd; sp.FxtkMatRepeated := tk; end; sp.Material.LibMaterialName := sp.Material.MaterialLibrary.Name[MatIdx]; // sp.EndUpdate; end; end; FXTKLastUpdate := tk; end; end; procedure TFireFxDummyCubeBase.SetFxEnabled(const Value: boolean); var t: integer; sp: TFireFxSprite; P: TVector4F; begin if (not Value) then begin mustDisable := true; { for t := FxSpritesList.Count-1 downto 0 do begin sp := TFireFxSprite(FxSpritesList[t]); sp.Visible := false; end; } end else if (not FFxEnabled) and Value then begin mustDisable := false; FXTKLastUpdate := GetTickCount; end; FFxEnabled := Value; end; procedure TFireFxDummyCubeBase.SetFxMatLib(const Value: TGLMaterialLibrary); var t: integer; sp: TFireFxSprite; begin FFxMatLib := Value; for t := FxSpritesList.Count - 1 downto 0 do begin sp := TFireFxSprite(FxSpritesList[t]); sp.Material.MaterialLibrary := FFxMatLib; end; end; procedure TFireFxDummyCubeBase.SetFxSpritesCount(const Value: integer); var t: integer; sp: TFireFxSprite; begin destroyAllSprites; FFxSpritesCount := Value; for t := 0 to FFxSpritesCount - 1 do begin sp := TFireFxSprite(FxSpritesParentObject.AddNewChild(TFireFxSprite)); FxSpritesList.Add(sp); sp.MirrorU := true; sp.Visible := false; end; SetFxMatLib(FFxMatLib); end; end.
{*********************************************************} { } { WZDUmp Mysql Objects } { WZeos Backup component } { } { Originally written by Wellington Fonseca } { } {*********************************************************} {@********************************************************} { Copyright (c) 2018-2019 Cw2 Development Group } { } { License Agreement: } { } { This library 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 Lesser General } { Public License for more details. } { } { The source code of the ZEOS Libraries and packages are } { distributed under the Library GNU General Public } { License (see the file COPYING / COPYING.ZEOS) } { 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. } { } { } { } { } { Cw2 Development Group. } {*********************************************************} unit WDump; interface uses ZDataset, windows, ZConnection, System.Sysutils, Vcl.Dialogs, System.Classes, Vcl.Forms, Data.DB, Vcl.Samples.Gauges, Vcl.StdCtrls; type TWProgress = procedure(progress, countofobjects, actualnumberobject: Integer; typeofobject, nameobject: string) of object; TWError = procedure(sErro, NameObject: string) of object; TWDump = class(TComponent) private Fcaminho: string; Fconn: TZConnection; FProgress: TGauge; FOnError: TWError; FDatabase: string; FTableNames: string; FDumperTables: Boolean; FDumperFunctions: boolean; FDumperViews: boolean; FDumperTriggers: boolean; FDumperEvents: boolean; FDumperProcedures: Boolean; FValuesPerInsert: Integer; FControlCancel: Boolean; FOnProgress: TWprogress; procedure DumpFunctions; procedure DumpProcedures; procedure DumpTables; procedure DumpEspecificsTables; procedure DumpViews; procedure DumpTriggers; procedure DumpEvents; procedure Setcaminho(const Value: string); procedure Setconn(const Value: TZConnection); procedure Setprogress(const Value: TGauge); function GetFieldValueForDump(Field: TField): string; function StringReplaceExt(const S: string; OldPattern, NewPattern: array of string; Flags: TReplaceFlags): string; function mysql_real_escape_string(const unescaped_string: string): string; function removedefine(str: string): string; procedure InsertIntoFile(caminho, mensagem: string); procedure SetDatabase(const Value: string); procedure SetDumperEvents(const Value: boolean); procedure SetDumperFunctions(const Value: boolean); procedure SetDumperTriggers(const Value: boolean); procedure SetDumperViews(const Value: boolean); procedure SetDumperProcedures(const Value: Boolean); procedure SetTableNames(const Value: string); procedure SetDumperTables(const Value: boolean); function GetFDatabase: string; function GetValuesPerInsert: Integer; procedure SetValuesPerInsert(const Value: Integer); function statementPGCreateTable(table: string): string; public procedure Dumper; procedure CancelDumper; published property Caminho: string read Fcaminho write Setcaminho; property Conn: TZConnection read Fconn write Setconn; property Gauge: TGauge read Fprogress write Setprogress; property Database: string read GetFDatabase write SetDatabase; property TableNames: string read FTableNames write SetTableNames; property DumperViews: boolean read FDumperViews write SetDumperViews; property DumperTriggers: boolean read FDumperTriggers write SetDumperTriggers; property DumperTables: boolean read FDumperTables write SetDumperTables; property DumperFunctions: boolean read FDumperFunctions write SetDumperFunctions; property DumperEvents: boolean read FDumperEvents write SetDumperEvents; property DumperProcedures: Boolean read FDumperProcedures write SetDumperProcedures; property OnProgress: TWprogress read FOnProgress write FOnProgress; property OnError: TWError read FOnError write FOnError; property ValuesPerInsert: Integer read GetValuesPerInsert write SetValuesPerInsert; end; procedure Register; const EOL = #13 + #10; implementation procedure TrimAppMemorySize; var MainHandle: THandle; begin try MainHandle := OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessID); SetProcessWorkingSetSize(MainHandle, $FFFFFFFF, $FFFFFFFF); CloseHandle(MainHandle); except end; Application.ProcessMessages; end; procedure TWDump.InsertIntoFile(caminho, mensagem: string); var log: TextFile; begin AssignFile(log, caminho); if fileexists(caminho) then Append(log) else Rewrite(log); Writeln(log, mensagem); Closefile(log); end; function Explode(Texto, Separador: string): TStrings; var strItem: string; ListaAuxUTILS: TStrings; NumCaracteres, TamanhoSeparador, I: Integer; begin ListaAuxUTILS := TStringList.Create; strItem := ''; NumCaracteres := Length(Texto); TamanhoSeparador := Length(Separador); I := 1; while I <= NumCaracteres do begin if (Copy(Texto, I, TamanhoSeparador) = Separador) or (I = NumCaracteres) then begin if (I = NumCaracteres) then strItem := strItem + Texto[I]; ListaAuxUTILS.Add(trim(strItem)); strItem := ''; I := I + (TamanhoSeparador - 1); end else strItem := strItem + Texto[I]; I := I + 1; end; Explode := ListaAuxUTILS; end; function TWDump.removedefine(str: string): string; var mtipo, antesdefine, posdefine: string; begin try antesdefine := Explode(str, 'DEFINER')[0]; except Result := str; end; try posdefine := Explode(str, 'SQL SECURITY DEFINER')[1]; Result := antesdefine + ' SQL SECURITY DEFINER ' + posdefine; except try posdefine := Explode(str, 'FUNCTION')[1]; Result := antesdefine + ' FUNCTION ' + posdefine; except try posdefine := Explode(str, 'TRIGGER')[1]; Result := antesdefine + ' TRIGGER ' + posdefine; except try posdefine := Explode(str, 'EVENT')[1]; Result := antesdefine + ' EVENT ' + posdefine; except try posdefine := Explode(str, 'PROCEDURE')[1]; Result := antesdefine + ' PROCEDURE ' + posdefine; except Result := str; end; end; end; end; end; end; function TWDump.StringReplaceExt(const S: string; OldPattern, NewPattern: array of string; Flags: TReplaceFlags): string; var i: integer; begin Assert(Length(OldPattern) = (Length(NewPattern))); Result := S; for i := Low(OldPattern) to High(OldPattern) do begin Result := StringReplace(Result, OldPattern[i], NewPattern[i], Flags); end; end; function TWDump.mysql_real_escape_string(const unescaped_string: string): string; begin Result := StringReplaceExt(unescaped_string, ['\', #34, #0, #10, #13, #26, ';'], ['\\', '\'#34, '\0', '\n', '\r', '\Z', '\;'], [rfReplaceAll]); end; function TWDump.GetFDatabase: string; begin Result := FDatabase end; function TWDump.GetFieldValueForDump(Field: TField): string; var FmtSet: TFormatSettings; s: string; i: integer; i64: int64; d: double; cur: currency; dt: TDateTime; begin if Field.IsNull then if (Field.DataType = ftDate) and (Fconn.Protocol = 'mysql') then Result := '0000-00-00' else Result := 'NULL' else begin case Field.DataType of ftSmallint, ftWord, ftInteger: begin i := Field.AsInteger; Result := IntToStr(i); end; ftLargeint: begin i64 := TLargeintField(Field).AsLargeInt; Result := IntToStr(i64); end; ftFloat: begin d := Field.AsFloat; FmtSet.DecimalSeparator := '.'; Result := FloatToStr(d, FmtSet); end; ftBCD: begin cur := Field.AsCurrency; FmtSet.DecimalSeparator := '.'; Result := CurrToStr(cur, FmtSet); end; ftFMTBcd: begin Result := Field.AsString; if FormatSettings.DecimalSeparator <> '.' then Result := StringReplace(Result, FormatSettings.DecimalSeparator, '.', []); end; ftBoolean: begin Result := BoolToStr(Field.AsBoolean, False); end; ftDate: begin dt := Field.AsDateTime; FmtSet.DateSeparator := '-'; Result := '''' + FormatDateTime('yyyy-mm-dd', dt, FmtSet) + ''''; end; ftTime: begin dt := Field.AsDateTime; FmtSet.TimeSeparator := ':'; Result := '''' + FormatDateTime('hh:nn:ss', dt, FmtSet) + ''''; end; ftDateTime: begin dt := Field.AsDateTime; FmtSet.DateSeparator := '-'; FmtSet.TimeSeparator := ':'; Result := '''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', dt, FmtSet) + ''''; end; else Result := QuotedStr(mysql_real_escape_string(Field.Value)); end; end; end; function TWDump.GetValuesPerInsert: Integer; begin if FValuesPerInsert <> 0 then Result := FValuesPerInsert else Result := 18; end; procedure TWDump.DumpProcedures; var q2, q3, q4, q5: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; percent, count, numfields: integer; begin q2 := TZQuery.Create(nil); //function q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; Fconn.Connected := true; if assigned(Fprogress) then Fprogress.Progress := 0; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); linha := ''; with q2 do begin close; sql.Clear; sql.Text := 'SHOW PROCEDURE STATUS WHERE Db =' + QuotedStr(GetFDatabase); try Open; except on e: Exception do if Assigned(FOnError) then Fonerror(E.Message, ''); end; end; if q2.RecordCount > 0 then begin if Assigned(Fprogress) then Fprogress.MaxValue := q2.RecordCount; while not q2.eof do begin if Assigned(Fprogress) then Fprogress.Progress := q2.RecNo; application.ProcessMessages; if FControlCancel then Break; with q3 do begin close; sql.Clear; sql.Text := 'SHOW CREATE PROCEDURE ' + q2.FieldByName('Name').AsString; try Open; except on e: Exception do if Assigned(FOnError) then FonError(E.Message, q2.FieldByName('Name').AsString); end; end; if Assigned(FonProgress) then FOnProgress((q2.RecNo * 100 div q2.RecordCount), q2.RecordCount, q2.RecNo, 'PROCEDURE', q2.FieldByName('Name').AsString); if q3.FieldByName('Create Procedure').AsString <> '' then begin linha := 'DELIMITER //' + EOL; linha := linha + removedefine(q3.FieldByName('Create Procedure').AsString) + EOL; linha := linha + '//' + EOL; linha := linha + 'DELIMITER ;' + EOL; Writeln(arq, linha); end; q2.Next; end; end; Closefile(arq); end; procedure TWDump.DumpEvents; var q2, q3, q4, q5: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; count, numfields: integer; begin q2 := TZQuery.Create(nil); q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; Fconn.Connected := true; if Assigned(Fprogress) then Fprogress.Progress := 0; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); linha := ''; with q2 do begin close; sql.Clear; sql.Text := 'SELECT *, EVENT_SCHEMA AS `Db`, EVENT_NAME AS `Name` FROM information_schema.`EVENTS` WHERE `EVENT_SCHEMA` = ' + QuotedStr(GetFDatabase); try Open; except on E: Exception do if Assigned(FOnError) then Fonerror('Erro na obtenção da lista de Eventos ' + E.Message, GetFDatabase); end; end; if q2.RecordCount > 0 then begin if Assigned(Fprogress) then Fprogress.MaxValue := q2.RecordCount; while not q2.eof do begin if Assigned(Fprogress) then Fprogress.Progress := Fprogress.Progress + 1; if Assigned(FonProgress) then FOnProgress((q2.RecNo * 100 div q2.RecordCount), q2.RecordCount, q2.RecNo, 'EVENT', q2.FieldByName('EVENT_NAME').AsString); application.ProcessMessages; with q3 do begin close; sql.Clear; sql.Text := 'SHOW CREATE EVENT ' + q2.FieldByName('EVENT_NAME').AsString; try Open; except on E: exception do if Assigned(FOnError) then Fonerror(E.Message, q2.FieldByName('EVENT_NAME').AsString); end; end; if q3.FieldByName('Create Event').AsString <> '' then begin linha := 'DELIMITER //' + EOL; linha := linha + removedefine(q3.FieldByName('Create Event').AsString) + EOL; linha := 'DROP EVENT IF EXISTS ' + q2.FieldByName('Name').AsString + ';' + EOL + linha + EOL; linha := linha + '//' + EOL; linha := linha + 'DELIMITER ;' + EOL; Writeln(arq, linha); end; q2.Next; end; end; Closefile(arq); end; procedure TWDump.DumpFunctions; var q2, q3, q4, q5: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; count, numfields: integer; begin q2 := TZQuery.Create(nil); //function q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; Fconn.Connected := true; if Assigned(Fprogress) then Fprogress.Progress := 0; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); linha := ''; with q2 do begin close; sql.Clear; sql.Text := 'SHOW FUNCTION STATUS WHERE Db =' + QuotedStr(GetFDatabase); try Open; except on E: Exception do if Assigned(FOnError) then FonError(E.Message, GetFDatabase); end; end; if q2.RecordCount > 0 then begin if Assigned(Fprogress) then Fprogress.MaxValue := q2.RecordCount; while not q2.eof do begin if Assigned(Fprogress) then Fprogress.Progress := q2.RecNo; if Assigned(FonProgress) then FOnProgress((q2.RecNo * 100 div q2.RecordCount), q2.RecordCount, q2.RecNo, 'FUNCTION', q2.FieldByName('Name').AsString); application.ProcessMessages; with q3 do begin close; sql.Clear; sql.Text := 'SHOW CREATE FUNCTION ' + q2.FieldByName('Name').AsString; try Open; except on e: Exception do if Assigned(FOnError) then FOnError(e.Message, q2.FieldByName('Name').AsString); end; end; if q3.FieldByName('Create Function').AsString <> '' then begin linha := 'DELIMITER //' + EOL; linha := linha + q3.FieldByName('Create Function').AsString + EOL; linha := removedefine(linha); linha := 'DROP FUNCTION IF EXISTS ' + q2.FieldByName('Name').AsString + ';' + EOL + linha + EOL; linha := linha + '//' + EOL; linha := linha + 'DELIMITER ;' + EOL; Writeln(arq, linha); end; q2.Next; end; end; Closefile(arq); end; { tWDump } procedure TWDump.CancelDumper; begin FControlCancel := True; end; procedure TWDump.Dumper; var arq: TextFile; metadata: Boolean; begin if fileexists(Fcaminho) then DeleteFile(Fcaminho); metadata := Conn.UseMetadata; Conn.UseMetadata := false; if FDumperTables then begin if trim(FTablenames) = '' then DumpTables else DumpEspecificsTables; end; if FDumperFunctions then DumpFunctions; if FDumperViews then DumpViews; if FDumperProcedures then DumpProcedures; if FDumperTriggers then DumpTriggers; if FDumperEvents then DumpEvents; Conn.UseMetadata := metadata; end; function TWDump.statementPGCreateTable(table: string): string; begin Result := ' SELECT ' + QuotedStr(table) + ' as table, ''CREATE TABLE '' || relname || E''' + EOL + '(' + EOL + ''' || ' + ' array_to_string( array_agg( '' '' || column_name || ' + QuotedStr(' ') + ' || type || ' + QuotedStr(' ') + ' || not_null' + ' ), E'',' + EOL + ''' ) || E''' + EOL + ');' + EOL + ''' from ( SELECT c.relname, a.attname AS column_name, pg_catalog.format_type(a.atttypid, a.atttypmod) as type, case when a.attnotnull then ''NOT NULL'' ' + ' else ''NULL'' END as not_null FROM pg_class c, pg_attribute a, pg_type t WHERE c.relname = ' + QuotedStr(table) + ' AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid ORDER BY a.attnum ) as tabledefinition group by relname'; end; procedure TWDump.DumpTables; var q2, q3, q4, q5: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; count, percent, numfields: integer; begin try q2 := TZQuery.Create(nil); q2.Connection := Fconn; with q2 do begin close; sql.Clear; if Connection.Protocol = 'mysql' then sql.text := 'show table status where engine is not null' else if Connection.Protocol = 'postgresql' then sql.Text := 'SELECT table_name as show_tables FROM information_schema.tables WHERE table_type = ' + QuotedStr('BASE TABLE') + ' AND table_schema NOT IN (''pg_catalog'', ''information_schema'') order by show_tables;'; try Open; except on e: Exception do begin Closefile(arq); if Assigned(FOnError) then Fonerror(E.Message, GetFDatabase); end; end; end; if q2.RecordCount > 0 then begin while not q2.eof do begin application.ProcessMessages; FTableNames := FTableNames + q2.Fields[0].AsString + ','; application.ProcessMessages; q2.Next; end; delete(FTableNames, length(FTableNames), 1); DumpEspecificsTables; end else Fonerror('Tabelas Não encontradas', GetFDatabase); finally FreeAndNIl(q2); end; end; procedure TWDump.DumpEspecificsTables; var q2, q3, q4, q5, Qconsulta: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; numrows, row, rowsperselect, rowinit, rowend, i, counter, numfields: integer; Lista: TStrings; begin Lista := Tstrings.Create; q2 := TZQuery.Create(nil); q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; q4 := TZQuery.Create(nil); q4.Connection := Fconn; q5 := TZQuery.Create(nil); q5.Connection := Fconn; rowsperselect := 100000; if assigned(Fprogress) then Fprogress.Progress := 0; try Lista := explode(Ftablenames, ','); except on E: exception do if Assigned(FOnError) then Fonerror(E.Message, Ftablenames); end; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); if Fconn.Protocol = 'mysql' then Writeln(arq, 'SET FOREIGN_KEY_CHECKS=0;'); for i := 0 to Lista.count - 1 do begin application.ProcessMessages; with q3 do begin if active then close; sql.Clear; if connection.Protocol = 'mysql' then sql.Text := 'show create table ' + Lista[i] else if connection.Protocol = 'postgresql' then sql.Text := statementPGCreateTable(Lista[i]); try Open; except on E: exception do begin if Assigned(FOnError) then begin Fonerror(E.Message, Ftablenames); end; end; end; end; if q3.active and (q3.RecordCount > 0) then begin Writeln(arq, 'DROP TABLE IF EXISTS ' + Lista[i] + ';'); Writeln(arq, q3.fields[1].Asstring + ';'); campo := ''; with q4 do begin close; sql.clear; if Connection.Protocol = 'mysql' then sql.text := 'show columns from ' + Lista[i] else sql.Text := 'SELECT COLUMN_NAME as field FROM information_schema.COLUMNS WHERE TABLE_NAME =' + QuotedStr(Lista[i]); try open; except on e: Exception do begin if Assigned(FOnerror) then FOnError(E.Message, Lista[i]); CloseFile(arq); end; end; end; while not q4.eof do begin campo := campo + q4.fieldbyname('field').Asstring + ','; application.ProcessMessages; q4.Next; end; delete(campo, length(campo), 1); with q5 do begin Close; sql.clear; sql.text := 'select count(*) from ' + Lista[i]; try Open; except on e: exception do begin if Assigned(FOnerror) then FOnError('Erro obtendo total de ' + Lista[i] + ' query ' + sql.text + ' erro ' + e.message, Lista[i]); CloseFile(arq); end; end; numrows := fields[0].AsInteger; end; if assigned(Fprogress) then begin Fprogress.Progress := 0; Fprogress.MaxValue := numrows; Fprogress.Refresh; end; row := 0; if numrows > 0 then if Assigned(FonProgress) then FOnProgress((Fprogress.Progress * 100 div numrows), Lista.count, (i + 1), 'Table ', Lista[i]); while row < numrows do begin FreeAndnil(q5); q5 := TZQuery.Create(Self); q5.Connection := Fconn; TrimAppMemorySize; application.ProcessMessages; with q5 do begin Close; sql.clear; if connection.Protocol = 'mysql' then sql.text := 'select * from ' + Lista[i] + ' limit ' + IntToStr(row) + ',' + IntToStr(rowsperselect) else sql.text := 'select * from "' + Lista[i] + '" limit ' + IntToStr(rowsperselect) + ' OFFSET ' + IntToStr(row); Open; end; row := (row + rowsperselect); if q5.active then if q5.RecordCount > 0 then //se tiver dados begin q5.First; pvalues := EmptyStr; counter := 0; while not q5.eof do begin application.ProcessMessages; if assigned(Fprogress) then Fprogress.Progress := Fprogress.Progress + 1; if Assigned(FonProgress) then FOnProgress((Fprogress.Progress * 100 div numrows), Lista.count, (i + 1), 'Table', Lista[i]); values := emptystr; q4.first; while not q4.eof do begin if not q5.fieldbyname(q4.fieldbyname('field').Asstring).IsBlob then values := values + GetFieldValueForDump(q5.fieldbyname(q4.fieldbyname('field').Asstring)) + ',' else values := values + QuotedStr(mysql_real_escape_string(q5.fieldbyname(q4.fieldbyname('field').Asstring).AsString)) + ','; q4.Next; application.ProcessMessages; end; if (campo <> '') and (values <> '') then begin linha := EmptyStr; delete(values, length(values), 1); end; if (counter < GetValuesPerInsert) then begin pvalues := pvalues + '(' + values + ')' + ','; counter := counter + 1; IntToStr(counter); q5.Next; end else begin TrimAppMemorySize; delete(pvalues, length(pvalues), 1); linha := 'insert into ' + Lista[i] + ' values ' + pvalues + ';'; if trim(pvalues) <> '' then Writeln(arq, linha); pvalues := EmptyStr; counter := 0; end; application.ProcessMessages; end; delete(pvalues, length(pvalues), 1); linha := 'insert into ' + Lista[i] + ' values ' + pvalues + ';'; if trim(pvalues) <> '' then Writeln(arq, linha); pvalues := EmptyStr; end; end; end; application.ProcessMessages; end; q2.Free; q3.Free; q4.Free; q5.Free; FreeAndNIl(Lista); if Fconn.Protocol = 'mysql' then Writeln(arq, 'SET FOREIGN_KEY_CHECKS=1;'); Closefile(arq); end; procedure TWDump.DumpViews; var q2, q3, q4, q5: TZQuery; linha, campo, values, pvalues: string; arq: TextFile; count, numfields: integer; begin q2 := TZQuery.Create(nil); //view q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); try if assigned(Fprogress) then Fprogress.Progress := 0; with q2 do begin Close; sql.Clear; sql.Text := 'SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ' + QuotedStr(GetFDatabase); try Open; except on e: Exception do if Assigned(FOnError) then Fonerror('Erro na obtenção da lista de Views ' + E.Message, GetFDatabase); end; if assigned(Fprogress) then Fprogress.MaxValue := q2.RecordCount; while not q2.eof do begin Fprogress.Progress := Fprogress.Progress + 1; application.processmessages; if Assigned(FonProgress) then FOnProgress((q2.Recno * 100 div q2.RecordCount), q2.RecordCount, q2.RecNo, 'VIEW', q2.FieldByName('table_name').Asstring); with q3 do begin close; sql.Clear; sql.Text := 'SHOW CREATE VIEW ' + q2.FieldByName('table_name').Asstring; Open; end; application.ProcessMessages; linha := 'DROP VIEW IF EXISTS ' + q2.FieldByName('table_name').Asstring + ';' + EOL; linha := linha + 'DELIMITER //' + EOL; linha := linha + removedefine(q3.FieldByName('Create View').AsString) + ';' + EOL; linha := linha + '//' + EOL; linha := linha + 'DELIMITER ;' + EOL; Writeln(arq, linha); q2.Next; end; end; finally q2.Free; q3.Free; end; Closefile(arq); end; procedure TWDump.DumpTriggers; var q2, q3 : TZQuery; linha, campo, values, pvalues: string; arq: TextFile; count, numfields: integer; begin q2 := TZQuery.Create(nil); //view q2.Connection := Fconn; q3 := TZQuery.Create(nil); q3.Connection := Fconn; AssignFile(arq, Fcaminho); if fileexists(Fcaminho) then Append(arq) else Rewrite(arq); try if assigned(Fprogress) then Fprogress.Progress := 0; with q2 do begin Close; sql.Clear; sql.Text := 'SHOW TRIGGERS FROM ' + GetFDatabase; try Open; except on e: Exception do raise Exception.Create('Erro na obtenção da lista de TRIGGERS ' + E.message + ' ' + sql.Text); end; if assigned(Fprogress) then Fprogress.MaxValue := q2.RecordCount; while not q2.eof do begin Fprogress.Progress := Fprogress.Progress + 1; application.processmessages; if Assigned(FonProgress) then FOnProgress((q2.RecNo * 100 div q2.RecordCount), q2.RecordCount, q2.RecNo, 'TRIGGER', q2.FieldByName('Trigger').Asstring); with q3 do begin close; sql.Clear; sql.Text := 'SHOW CREATE TRIGGER ' + q2.FieldByName('Trigger').Asstring; Open; end; if q3.RecordCount > 0 then begin linha := 'DROP TRIGGER IF EXISTS ' + q2.FieldByName('Trigger').Asstring + ';' + EOL; linha := linha + 'DELIMITER //' + EOL; linha := linha + removedefine(q3.FieldByName('SQL Original Statement').AsString) + ';' + EOL; linha := linha + '//' + EOL; linha := linha + 'DELIMITER ;' + EOL; Writeln(arq, linha); end; q2.Next; end; end; finally q2.Free; q3.Free; end; Closefile(arq); end; procedure TWDump.Setcaminho(const Value: string); begin if Value <> '' then Fcaminho := Value else raise Exception.Create('Caminho não pode ser vazio.'); end; procedure TWDump.Setconn(const Value: TZConnection); begin if not Assigned(Value) then raise Exception.Create('Error Conexão não identificada'); Fconn := Value; end; procedure TWDump.SetDatabase(const Value: string); begin if Value <> '' then FDatabase := Value else raise Exception.Create('Informar Database'); end; procedure TWDump.SetDumperEvents(const Value: boolean); begin FDumperEvents := Value; end; procedure TWDump.SetDumperFunctions(const Value: boolean); begin FDumperFunctions := Value; end; procedure TWDump.SetDumperProcedures(const Value: Boolean); begin FDumperProcedures := Value; end; procedure TWDump.SetDumperTables(const Value: boolean); begin FDumperTables := Value; end; procedure TWDump.SetDumperTriggers(const Value: boolean); begin FDumperTriggers := Value; end; procedure TWDump.SetDumperViews(const Value: boolean); begin FDumperViews := Value; end; procedure TWDump.Setprogress(const Value: TGauge); begin Fprogress := Value; end; procedure TWDump.SetTableNames(const Value: string); begin FTablenames := Value; end; procedure TWDump.SetValuesPerInsert(const Value: Integer); begin FValuesPerInsert := Value; end; procedure Register; begin RegisterComponents('Zeos Access', [TWDump]); end; end.
unit SDL2_SimpleGUI; {:< The Library Unit} { Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski, get more infos here: https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI. It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal, get it here: https://sourceforge.net/projects/lkgui. Written permission to re-license the library has been granted to me by the original author. Copyright (c) 2016-2020 Matthias J. Molski 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. } interface uses SDL2, SDL2_SimpleGUI_Master, SDL2_SimpleGUI_Form, SDL2_SimpleGUI_StdWgts, SDL2_SimpleGUI_Base; { Base Types from Base Unit } type TRGBA = SDL2_SimpleGUI_Base.TRGBA; TTextAlign = SDL2_SimpleGUI_Base.TTextAlign; TVertAlign = SDL2_SimpleGUI_Base.TVertAlign; TDirection = SDL2_SimpleGUI_Base.TDirection; TBorderStyle = SDL2_SimpleGUI_Base.TBorderStyle; TFillStyle = SDL2_SimpleGUI_Base.TFillStyle; { Default Colors and Consts } const GUI_DefaultBackColor: TRGBA = (R: 48; G: 48; B: 48; A: 255); GUI_DefaultTextBackColor: TRGBA = (R: 24; G: 24; B: 24; A: 255); GUI_DefaultForeColor: TRGBA = (R: 190; G: 190; B: 190; A: 255); GUI_DefaultBorderColor: TRGBA = (R: 64; G: 64; B: 64; A: 255); GUI_DefaultFormBack: TRGBA = (R: 32; G: 32; B: 32; A: 255); GUI_DefaultTitleBarBack: TRGBA = (R: 24; G: 24; B: 64; A: 255); GUI_DefaultUnselectedTitleBarBack: TRGBA = (R: 24; G: 24; B: 24; A: 255); GUI_SelectedColor: TRGBA = (R: 24; G: 24; B: 64; A: 255); GUI_DefaultActiveColor: TRGBA = (R: 24; G: 24; B: 64; A: 255); GUI_TitleBarHeight = 25; GUI_FullTrans: TRGBA = (R: 0; G: 0; B: 0; A: 0); GUI_ScrollbarSize = 11; GUI_DebugColor: TRGBA = (R: 0; G: 255; B: 0; A: 255); //< for dbg purpose only {$ifdef ENDIAN_LITTLE} amask = $ff000000; {$else} amask = $000000ff; {$endif} { GUI Elements and Widgets from respective units } type TGUI_Master = SDL2_SimpleGUI_Master.TGUI_Master; TGUI_Form = SDL2_SimpleGUI_Form.TGUI_Form; TGUI_Button = SDL2_SimpleGUI_StdWgts.TGUI_Button; TGUI_CheckBox = SDL2_SimpleGUI_StdWgts.TGUI_CheckBox; TGUI_Label = SDL2_SimpleGUI_StdWgts.TGUI_Label; TGUI_ScrollBar = SDL2_SimpleGUI_StdWgts.TGUI_ScrollBar; TGUI_TextBox = SDL2_SimpleGUI_StdWgts.TGUI_TextBox; TGUI_Image = SDL2_SimpleGUI_StdWgts.TGUI_Image; TGUI_Listbox = SDL2_SimpleGUI_StdWgts.TGUI_Listbox; implementation begin end.
unit feli_user; {$mode objfpc} interface uses feli_collection, feli_document, feli_user_event, feli_event, fpjson; type FeliUserKeys = class public const username = 'username'; displayName = 'display_name'; salt = 'salt'; saltedPassword = 'salted_password'; password = 'password'; email = 'email'; firstName = 'first_name'; lastName = 'last_name'; accessLevel = 'access_level'; joinedEvents = 'joined_events'; createdEvents = 'created_events'; pendingEvents = 'pending_events'; end; FeliUser = class(FeliDocument) private salt, saltedPassword: ansiString; public username, password, displayName, email, firstName, lastName, accessLevel: ansiString; createdAt: int64; // joinedEvents, createdEvents, pendingEvents: TJsonArray; joinedEvents, createdEvents, pendingEvents: FeliUserEventCollection; constructor create(); function toTJsonObject(secure: boolean = false): TJsonObject; override; // function toJson(): ansiString; function verify(): boolean; function validate(): boolean; procedure generateSaltedPassword(); procedure joinEvent(eventId, ticketId: ansiString); procedure createEvent(event: FeliEvent); procedure leaveEvent(eventId: ansiString); procedure removeCreatedEvent(eventId: ansiString); function generateAnalysis(): TJsonObject; // Factory Methods class function fromTJsonObject(userObject: TJsonObject): FeliUser; static; end; FeliUserCollection = class(FeliCollection) private public // data: TJsonArray; // constructor create(); // function where(key: ansiString; operation: ansiString; value: ansiString): FeliUserCollection; // function toTJsonArray(): TJsonArray; // function toJson(): ansiString; procedure add(user: FeliUser); procedure join(newCollection: FeliUserCollection); function toSecureTJsonArray(): TJsonArray; function toSecureJson(): ansiString; // function length(): int64; // class function fromTJsonArray(usersArray: TJsonArray): FeliUserCollection; static; class function fromFeliCollection(collection: FeliCollection): FeliUserCollection; static; end; implementation uses feli_storage, feli_crypto, feli_validation, feli_operators, feli_access_level, feli_errors, feli_stack_tracer, feli_event_participant, feli_event_ticket, feli_logger, dateutils, sysutils; constructor FeliUser.create(); begin joinedEvents := FeliUserEventCollection.create(); createdEvents := FeliUserEventCollection.create(); pendingEvents := FeliUserEventCollection.create(); end; function FeliUser.toTJsonObject(secure: boolean = false): TJsonObject; var user, userData: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliUser.toTJsonObject(secure: boolean = false): TJsonObject;'); user := TJsonObject.create(); user.add(FeliUserKeys.username, username); user.add(FeliUserKeys.displayName, displayName); if not secure then user.add(FeliUserKeys.salt, salt); if not secure then user.add(FeliUserKeys.saltedPassword, saltedPassword); user.add(FeliUserKeys.email, email); user.add(FeliUserKeys.firstName, firstName); user.add(FeliUserKeys.lastName, lastName); user.add(FeliUserKeys.accessLevel, accessLevel); case accessLevel of FeliAccessLevel.admin: begin user.add(FeliUserKeys.joinedEvents, joinedEvents.toTJsonArray()); user.add(FeliUserKeys.createdEvents, createdEvents.toTJsonArray()); user.add(FeliUserKeys.pendingEvents, pendingEvents.toTJsonArray()); end; FeliAccessLevel.organiser: begin user.add(FeliUserKeys.createdEvents, createdEvents.toTJsonArray()); end; FeliAccessLevel.participator: begin user.add(FeliUserKeys.joinedEvents, joinedEvents.toTJsonArray()); user.add(FeliUserKeys.pendingEvents, pendingEvents.toTJsonArray()); end; FeliAccessLevel.anonymous: begin end; end; result := user; FeliStackTrace.trace('end', 'function FeliUser.toTJsonObject(secure: boolean = false): TJsonObject;'); end; // function FeliUser.toJson(): ansiString; // begin // result := self.toTJsonObject().formatJson; // end; function FeliUser.verify(): boolean; begin result := (saltedPassword = FeliCrypto.hashMD5(salt + password)); end; function FeliUser.validate(): boolean; begin FeliStackTrace.trace('begin', 'function FeliUser.validate(): boolean;'); if not FeliValidation.emailCheck(email) then raise Exception.Create(FeliErrors.invalidEmail); if not FeliValidation.lengthCheck(username, 4, 16) then raise Exception.Create(FeliErrors.invalidUsernameLength); if not FeliValidation.lengthCheck(password, 8, 32) then raise Exception.Create(FeliErrors.invalidPasswordLength); if not FeliValidation.lengthCheck(firstName, 1, 32) then raise Exception.Create(FeliErrors.emptyFirstName); if not FeliValidation.lengthCheck(lastName, 1, 32) then raise Exception.Create(FeliErrors.emptyLastName); if not FeliValidation.lengthCheck(displayName, 1, 32) then raise Exception.Create(FeliErrors.emptyDisplayName); if not FeliValidation.fixedValueCheck(accessLevel, [FeliAccessLevel.organiser, FeliAccessLevel.participator]) then raise Exception.Create(FeliErrors.accessLevelNotAllowed); FeliStackTrace.trace('end', 'function FeliUser.validate(): boolean;'); end; procedure FeliUser.generateSaltedPassword(); begin FeliStackTrace.trace('begin', 'procedure FeliUser.generateSaltedPassword();'); salt := FeliCrypto.generateSalt(32); saltedPassword := FeliCrypto.hashMD5(salt + password); FeliStackTrace.trace('end', 'procedure FeliUser.generateSaltedPassword();'); end; procedure FeliUser.joinEvent(eventId, ticketId: ansiString); var event: FeliEvent; participant: FeliEventParticipant; tempCollection: FeliCollection; eventFull: boolean; userEvent: FeliUserEvent; begin FeliStackTrace.trace('begin', 'procedure FeliUser.joinEvent(eventId: ansistring);'); event := FeliStorageAPI.getEvent(eventId); if (event <> nil) then begin eventFull := event.participants.length() >= event.participantLimit; tempCollection := event.participants.where(FeliEventParticipantKey.username, FeliOperators.equalsTo, username); if (not eventFull) then begin if (tempCollection.length() <= 0) then begin participant := FeliEventParticipant.create(); participant.username := username; participant.createdAt := DateTimeToUnix(Now()) * 1000 - 8 * 60 * 60 * 1000; participant.ticketId := ticketId; event.participants.add(participant); FeliStorageAPI.setEvent(event); userEvent := FeliUserEvent.create(); userEvent.eventId := eventId; userEvent.createdAt := participant.createdAt; joinedEvents.add(userEvent); FeliStorageAPI.setUser(self) end; end else begin if not (tempCollection.length() >= 1) then begin tempCollection := event.waitingList.where(FeliEventParticipantKey.username, FeliOperators.equalsTo, username); if (tempCollection.length() <= 0) then begin participant := FeliEventParticipant.create(); participant.username := username; participant.createdAt := DateTimeToUnix(Now()) * 1000 - 8 * 60 * 60 * 1000; participant.ticketId := ticketId; event.waitingList.add(participant); FeliStorageAPI.setEvent(event); userEvent := FeliUserEvent.create(); userEvent.eventId := eventId; userEvent.createdAt := participant.createdAt; pendingEvents.add(userEvent); FeliStorageAPI.setUser(self); end; end; end; end else begin end; FeliStackTrace.trace('end', 'procedure FeliUser.joinEvent(eventId: ansistring);'); end; procedure FeliUser.createEvent(event: FeliEvent); var userEvent: FeliUserEvent; begin event.id := FeliCrypto.generateSalt(32); event.createdAt := DateTimeToUnix(Now()) * 1000 - 8 * 60 * 60 * 1000; FeliStorageAPI.addEvent(event); userEvent := FeliUserEvent.create(); userEvent.createdAt := event.createdAt; userEvent.eventId := event.id; createdEvents.add(userEvent); FeliStorageAPI.setUser(self); end; procedure FeliUser.leaveEvent(eventId: ansiString); var event: FeliEvent; tempWaitingListCollection, tempParticipantCollection, tempPendingCollection, tempCollection: FeliCollection; lengthBefore, allowQueue: int64; tempData: TJsonObject; tempParticipant: FeliEventParticipant; tempUserEvent: FeliUserEvent; tempUser: FeliUser; begin FeliStackTrace.trace('begin', 'procedure FeliUser.leaveEvent(eventId: ansiString);'); event := FeliStorageAPI.getEvent(eventId); if (event <> nil) then begin tempWaitingListCollection := event.waitingList.where(FeliEventParticipantKey.username, FeliOperators.notEqualsTo, username); lengthBefore := event.participants.length(); tempParticipantCollection := event.participants.where(FeliEventParticipantKey.username, FeliOperators.notEqualsTo, username); allowQueue := lengthBefore - tempParticipantCollection.length(); tempCollection := joinedEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); joinedEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); tempCollection := pendingEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); pendingEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); while (not (allowQueue <= 0)) do begin tempData := tempWaitingListCollection.shift(); if (tempData <> nil) then begin tempParticipant := FeliEventParticipant.fromTJsonObject(tempData); tempParticipantCollection.data.add(tempData); tempUser := FeliStorageAPI.getUser(tempParticipant.username); tempPendingCollection := tempUser.pendingEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); tempUserEvent := FeliUserEvent.create(); tempUserEvent.eventId := eventId; tempUserEvent.createdAt := tempParticipant.createdAt; tempUser.joinedEvents.add(tempUserEvent); tempUser.pendingEvents := FeliUserEventCollection.fromFeliCollection(tempPendingCollection); FeliStorageAPI.setUser(tempUser); allowQueue := allowQueue - 1; end else begin allowQueue := 0; end; end; event.participants := FeliEventParticipantCollection.fromFeliCollection(tempParticipantCollection); event.waitingList := FeliEventWaitingCollection.fromFeliCollection(tempWaitingListCollection); FeliStorageAPI.setEvent(event); FeliStorageAPI.setUser(self); end else begin end; FeliStackTrace.trace('end', 'procedure FeliUser.leaveEvent(eventId: ansiString);'); end; procedure FeliUser.removeCreatedEvent(eventId: ansiString); var tempJoinedUser, tempWaitingUser: FeliUser; tempCollection: FeliCollection; targetEvent: FeliEvent; tempEventParticipantArray, tempEventWaitingArray: TJsonArray; tempEventParticipant, tempEventWaitingParticipant: FeliEventParticipant; i: integer; begin targetEvent := FeliStorageAPI.getEvent(eventId); if (targetEvent <> nil) then begin tempCollection := createdEvents.where(FeliUserEventKeys.eventId, FeliOperators.equalsTo, eventId); if (tempCollection.length > 0) then begin tempEventParticipantArray := targetEvent.participants.toTJsonArray(); for i := 0 to (tempEventParticipantArray.count - 1) do begin tempEventParticipant := FeliEventParticipant.fromTJsonObject(tempEventParticipantArray[i] as TJsonObject); tempJoinedUser := FeliStorageAPI.getUser(tempEventParticipant.username); tempCollection := tempJoinedUser.joinedEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); tempJoinedUser.joinedEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); FeliStorageAPI.setUser(tempJoinedUser); end; tempEventWaitingArray := targetEvent.waitingList.toTJsonArray(); for i := 0 to (tempEventWaitingArray.count - 1) do begin tempEventWaitingParticipant := FeliEventParticipant.fromTJsonObject(tempEventWaitingArray[i] as TJsonObject); tempWaitingUser := FeliStorageAPI.getUser(tempEventWaitingParticipant.username); tempCollection := tempWaitingUser.pendingEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); tempWaitingUser.pendingEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); FeliStorageAPI.setUser(tempWaitingUser); end; FeliStorageAPI.removeEvent(eventId); tempCollection := createdEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); createdEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); tempCollection := pendingEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); pendingEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); tempCollection := joinedEvents.where(FeliUserEventKeys.eventId, FeliOperators.notEqualsTo, eventId); joinedEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); FeliStorageAPI.setUser(self); end; end; end; function FeliUser.generateAnalysis(): TJsonObject; // const // createdEventsTableKeys: array[0..1] of ansiString = (FeliEventKeys.id, FeliEventKeys.name); var header, body, footer, analysis, headerUser: TJsonObject; totalFee: real; createdEventsTable, joinedEventsTable: TJsonArray; userEvent: FeliUserEvent; eventParticipant: FeliEventParticipant; tempArray, tempArray2: TJsonArray; i, j: integer; event: FeliEvent; eventFee, createdEventsTotalFee, joinedEventsTotalFee: real; key: ansiString; dataRow: TJsonArray; ticket: FeliEventTicket; tempCollection, tempCollection2: FeliCollection; begin FeliStackTrace.trace('begin', 'function FeliUser.generateAnalysis(): TJsonObject;'); totalFee := 0; createdEventsTotalFee := 0; joinedEventsTotalFee := 0; header := TJsonObject.create(); headerUser := TJsonObject.create(); body := TJsonObject.create(); footer := TJsonObject.create(); analysis := TJsonObject.create(); analysis['header'] := header; analysis['body'] := body; analysis['footer'] := footer; headerUser.add('name', format('%s %s', [firstName, lastName])); headerUser.add('email', format('%s', [email])); header.add('title', 'analysis_report'); header['user'] := headerUser; footer.add('barcode', username); // Created Events if (FeliValidation.fixedValueCheck(accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.organiser])) then begin createdEventsTable := TJsonArray.create(); createdEventsTotalFee := 0; dataRow := TJsonArray.create(); dataRow.add('event_id'); dataRow.add('event_name'); dataRow.add('participant_count'); dataRow.add('$'); createdEventsTable.add(dataRow); tempArray := createdEvents.toTJsonArray(); for i := 0 to (tempArray.count - 1) do begin dataRow := TJsonArray.create(); userEvent := FeliUserEvent.fromTJsonObject(tempArray[i] as TJsonObject); event := FeliStorageAPI.getEvent(userEvent.eventId); dataRow.add(event.id); dataRow.add(event.name); dataRow.add(event.participants.length); eventFee := 0; tempArray2 := event.participants.toTJsonArray(); for j := 0 to tempArray2.count - 1 do begin eventParticipant := FeliEventParticipant.fromTJsonObject(tempArray2[j] as TJsonObject); tempCollection := event.tickets.where(FeliEventTicketKeys.id, FeliOperators.equalsTo, eventParticipant.ticketId); ticket := FeliEventTicket.fromTJsonObject(tempCollection.toTJsonArray()[0] as TJsonObject); eventFee := eventFee + ticket.fee; end; createdEventsTotalFee := createdEventsTotalFee + eventFee; dataRow.add(eventFee); createdEventsTable.add(dataRow); end; body['created_events_table'] := createdEventsTable; body.add('created_events_fee', createdEventsTotalFee); end; // Joined Events if (FeliValidation.fixedValueCheck(accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.participator])) then begin joinedEventsTable := TJsonArray.create(); joinedEventsTotalFee := 0; dataRow := TJsonArray.create(); dataRow.add('event_id'); dataRow.add('event_name'); dataRow.add('ticket_id'); dataRow.add('ticket_name'); dataRow.add('$'); joinedEventsTable.add(dataRow); tempArray := joinedEvents.toTJsonArray(); for i := 0 to (tempArray.count - 1) do begin dataRow := TJsonArray.create(); userEvent := FeliUserEvent.fromTJsonObject(tempArray[i] as TJsonObject); event := FeliStorageAPI.getEvent(userEvent.eventId); dataRow.add(event.id); dataRow.add(event.name); eventFee := 0; // tempArray2 := event.participants.toTJsonArray(); // for j := 0 to tempArray2.count - 1 do // begin tempCollection := event.participants.where(FeliEventParticipantKey.username, FeliOperators.equalsTo, username); eventParticipant := FeliEventParticipant.fromTJsonObject(tempCollection.toTJsonArray()[0] as TJsonObject); tempCollection2 := event.tickets.where(FeliEventTicketKeys.id, FeliOperators.equalsTo, eventParticipant.ticketId); ticket := FeliEventTicket.fromTJsonObject(tempCollection2.toTJsonArray()[0] as TJsonObject); eventFee := eventFee + ticket.fee; // end; joinedEventsTotalFee := joinedEventsTotalFee + eventFee; dataRow.add(ticket.id); dataRow.add(ticket.tType); dataRow.add(eventFee); joinedEventsTable.add(dataRow); end; body['joined_events_table'] := joinedEventsTable; body.add('joined_events_fee', joinedEventsTotalFee); end; totalFee := createdEventsTotalFee - joinedEventsTotalFee; body.add('fee', totalFee); result := analysis; FeliStackTrace.trace('end', 'function FeliUser.generateAnalysis(): TJsonObject;'); end; class function FeliUser.fromTJsonObject(userObject: TJsonObject): FeliUser; static; var feliUserInstance: FeliUser; tempTJsonArray: TJsonArray; tempCollection: FeliCollection; begin FeliStackTrace.trace('begin', 'class function FeliUser.fromTJsonObject(userObject: TJsonObject): FeliUser; static;'); feliUserInstance := FeliUser.create(); with feliUserInstance do begin try username := userObject.getPath(FeliUserKeys.username).asString; except on e: exception do begin end; end; try displayName := userObject.getPath(FeliUserKeys.displayName).asString; except on e: exception do begin end; end; try salt := userObject.getPath(FeliUserKeys.salt).asString; except on e: exception do begin end; end; try saltedPassword := userObject.getPath(FeliUserKeys.saltedPassword).asString; except on e: exception do begin end; end; try password := userObject.getPath(FeliUserKeys.password).asString; except on e: exception do begin end; end; try email := userObject.getPath(FeliUserKeys.email).asString; except on e: exception do begin end; end; try firstName := userObject.getPath(FeliUserKeys.firstName).asString; except on e: exception do begin end; end; try lastName := userObject.getPath(FeliUserKeys.lastName).asString; except on e: exception do begin end; end; try accessLevel := userObject.getPath(FeliUserKeys.accessLevel).asString; except on e: exception do begin end; end; try tempTJsonArray := TJsonArray(userObject.findPath(FeliUserKeys.joinedEvents)); if not tempTJsonArray.isNull then begin tempCollection := FeliCollection.fromTJsonArray(tempTJsonArray); joinedEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); end; except end; try tempTJsonArray := TJsonArray(userObject.findPath(FeliUserKeys.createdEvents)); if not tempTJsonArray.isNull then begin tempCollection := FeliCollection.fromTJsonArray(tempTJsonArray); createdEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); end; except end; try tempTJsonArray := TJsonArray(userObject.findPath(FeliUserKeys.pendingEvents)); if not tempTJsonArray.isNull then begin tempCollection := FeliCollection.fromTJsonArray(tempTJsonArray); pendingEvents := FeliUserEventCollection.fromFeliCollection(tempCollection); end; except end; end; result := feliUserInstance; FeliStackTrace.trace('end', 'class function FeliUser.fromTJsonObject(userObject: TJsonObject): FeliUser; static;'); end; // constructor FeliUserCollection.create(); // begin // data := TJsonArray.Create; // end; // function FeliUserCollection.where(key: ansiString; operation: ansiString; value: ansiString): FeliUserCollection; // var // dataTemp: TJsonArray; // dataEnum: TJsonEnum; // dataSingle: TJsonObject; // begin // dataTemp := TJsonArray.create(); // for dataEnum in data do // begin // dataSingle := dataEnum.value as TJsonObject; // case operation of // FeliOperators.equalsTo: begin // if (dataSingle.getPath(key).asString = value) then // dataTemp.add(dataSingle); // end; // FeliOperators.notEqualsTo: begin // if (dataSingle.getPath(key).asString <> value) then // dataTemp.add(dataSingle); // end; // FeliOperators.largerThanOrEqualTo: begin // if (dataSingle.getPath(key).asString >= value) then // dataTemp.add(dataSingle); // end; // FeliOperators.largerThan: begin // if (dataSingle.getPath(key).asString > value) then // dataTemp.add(dataSingle); // end; // FeliOperators.smallerThanOrEqualTo: begin // if (dataSingle.getPath(key).asString <= value) then // dataTemp.add(dataSingle); // end; // FeliOperators.smallerThan: begin // if (dataSingle.getPath(key).asString < value) then // dataTemp.add(dataSingle); // end; // end; // end; // result := FeliUserCollection.fromTJsonArray(dataTemp); // end; procedure FeliUserCollection.add(user: FeliUser); begin FeliStackTrace.trace('begin', 'procedure FeliUserCollection.add(user: FeliUser);'); data.add(user.toTJsonObject()); FeliStackTrace.trace('end', 'procedure FeliUserCollection.add(user: FeliUser);'); end; procedure FeliUserCollection.join(newCollection: FeliUserCollection); var newArray: TJsonArray; newEnum: TJsonEnum; newDataSingle: TJsonObject; begin FeliStackTrace.trace('begin', 'procedure FeliUserCollection.join(newCollection: FeliUserCollection);'); newArray := newCollection.toTJsonArray(); for newEnum in newArray do begin newDataSingle := newEnum.value as TJsonObject; data.add(newDataSingle); end; FeliStackTrace.trace('end', 'procedure FeliUserCollection.join(newCollection: FeliUserCollection);'); end; function FeliUserCollection.toSecureTJsonArray(): TJsonArray; var user: FeliUser; i: integer; secureArray: TJsonArray; begin secureArray := TJsonArray.create(); for i := 0 to (data.count - 1) do begin user := FeliUser.fromTJsonObject(data[i] as TJsonObject); user.email := ''; user.firstName := ''; user.lastName := ''; secureArray.add(user.toTJsonObject(true)); end; result := secureArray; end; function FeliUserCollection.toSecureJson(): ansiString; begin result := toSecureTJsonArray().formatJson; end; // function FeliUserCollection.length(): int64; // begin // result := data.count; // end; // function FeliUserCollection.toTJsonArray(): TJsonArray; // begin // result := data; // end; // function FeliUserCollection.toJson(): ansiString; // begin // result := self.toTJsonArray().formatJson; // end; // class function FeliUserCollection.fromTJsonArray(usersArray: TJsonArray): FeliUserCollection; static; // var // feliUserCollectionInstance: FeliUserCollection; // begin // feliUserCollectionInstance := feliUserCollection.create(); // feliUserCollectionInstance.data := usersArray; // result := feliUserCollectionInstance; // end; class function FeliUserCollection.fromFeliCollection(collection: FeliCollection): FeliUserCollection; static; var feliUserCollectionInstance: FeliUserCollection; begin FeliStackTrace.trace('begin', 'class function FeliUserCollection.fromFeliCollection(collection: FeliCollection): FeliUserCollection; static;'); feliUserCollectionInstance := FeliUserCollection.create(); feliUserCollectionInstance.data := collection.data; result := feliUserCollectionInstance; FeliStackTrace.trace('end', 'class function FeliUserCollection.fromFeliCollection(collection: FeliCollection): FeliUserCollection; static;'); end; end.
unit SyntaxU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Add, Registry, ScktComp, RichEdit, DCPockets; type TStyle = record Color: TColor; Styles: TFontStyles; end; TSkobki = record First, Last: String; Comment: Boolean; Style: TStyle; Stat: Boolean; end; TRezerved = record S: String; Style: TStyle; end; procedure Syntax(RE: TRichEdit; Rez: array of TRezerved; Sko: array of TSkobki; TextColor: TColor; TextStyle: TFontStyles); procedure EaseSyntax(RE: TRichEdit; Sko: array of TSkobki; TextColor: TColor; TextStyle: TFontStyles; S: String); function Parse(S: String): String; implementation Const Rus: Array [1..32, 1..2] of Char = (('à', 'À'),('á', 'Á'),('â', 'Â'),('ã', 'Ã'),('ä', 'Ä'),('å', 'Å'),('¸', '¨'),('æ', 'Æ'),('ç', 'Ç'),('è', 'È'),('ê', 'Ê'),('ë', 'Ë'),('ì', 'Ì'),('í', 'Í'),('î', 'Î'),('ï', 'Ï'),('ð', 'Ð'), ('ñ', 'Ñ'),('ò', 'Ò'),('ó', 'Ó'),('ô', 'Ô'),('õ', 'Õ'),('ö', 'Ö'),('÷', '×'),('ø', 'Ø'),('ù', 'Ù'),('ü', 'Ü'),('ú', 'Ú'),('û', 'Û'),('ý', 'Ý'),('þ', 'Þ'),('ÿ', 'ß')); Function RUpCase(Ch: Char): Char; var I: Integer; Begin Result:=UpCase(Ch); if Ch=Result then for I := 1 to High(Rus) do if Ch=Rus[I, 1] then Begin Result:=Rus[I, 2]; Break; end; end; Function RLowCase(Ch: Char): Char; var I: Integer; T: String; Begin T:=LowerCase(Ch); Result:=T[1]; if Ch=Result then for I := 1 to High(Rus) do if Ch=Rus[I, 2] then Begin Result:=Rus[I, 1]; Break; end; end; Function RUpperCase(S: String): String; Var I: LongInt; T: String; Begin T:=''; For I:=1 To Length(S) Do T:=T+RUpCase(S[I]); RUpperCase:=T; End; Function RLowerCase(S: String): String; Var I: LongInt; T: String; Begin T:=''; For I:=1 To Length(S) Do T:=T+RLowCase(S[I]); RLowerCase:=T; End; Function Letter(Ch: Char): Boolean; Begin If (RUpCase(Ch)=Ch)And(RLowCase(Ch)=Ch) then Letter:=False Else Letter:=True; End; Function PosAfter(Sub, S: String; num: LongInt): LongInt; Begin delete(S, 1, num); if pos(Sub, S)<>0 then PosAfter:=num+Pos(Sub, S) Else PosAfter:=0; End; type TTextRange = record chrg: TCharRange; lpstrText: PAnsiChar; end; procedure Syntax(RE: TRichEdit; Rez: array of TRezerved; Sko: array of TSkobki; TextColor: TColor; TextStyle: TFontStyles); var Q, I, J, ST: LongInt; B: Boolean; Te: Array of Array [1..3] of LongInt; Sk: Array of Array of LongInt; S, T: String; Po: TPoint; TextRange: TTextRange; Function Find(Num: LongInt): LongInt; var I: LongInt; begin for I:=Num-1 DownTo 1 Do if Te[I, 2]<>0 then begin Find:=Te[I, 2]; Exit; end; Find:=1; end; Function InBrackets(Num: LongInt): Boolean; var I: LongInt; begin Result:=False; if Sko[Num].Comment then Num:=-1; for I:=0 to High(Sk) do begin if (Sk[I, 0]<>0)And(Num<>I) then begin Result:=True; Break; end; end; end; Function Comment: Boolean; var I: LongInt; begin Comment:=False; for I := 0 to High(Sko) do if (Sko[I].Comment)And(Sk[I, 0]>0) then begin Comment:=True; Break; end; end; procedure DelFromAll(Num: LongInt); var I, J: LongInt; begin I:=0; While I<=High(Sk) do begin J:=Sk[I, 0]; while J>= 1 do begin if Sk[I, J]>Num then begin Dec(Sk[I, 0]); SetLength(Sk[I], High(Sk[I])); end else Break; Dec(J); end; Inc(I); end; end; begin // Ti:=Time; Po:=Re.CaretPos; S:=Re.Text; SetLength(Sk, Length(Sko)); for I := 0 to High(Sk) do SetLength(Sk[I], 1); SetLength(Te, 0); Q:=-1; I:=1; S:=RUpperCase(S); while I<=Length(S) do begin B:=False; for J:=0 to High(Rez) do begin T:=Copy(S, I, length(Rez[J].S)); if (T=Rez[J].S) And(Not Letter(S[I-1]))And(Not Letter(S[I+Length(Rez[J].S)]))And(not InBrackets(-1)) then begin inc(Q); SetLength(Te, High(Te)+2); Te[Q, 1]:=I-1; inc(I, Length(Rez[J].S)-1); Te[Q, 2]:=I; Te[Q, 3]:=J; B:=True; Break; end; end; if not B then begin for J:=0 to High(Sko) do begin T:=Copy(S, I, length(Sko[J].Last)); if (T=Sko[J].Last)And(Sk[J, 0]>0)And((not Comment){And((not InBrackets(J))}Or(Sko[J].Comment)) then begin Dec(Sk[J, 0]); Te[Sk[J, Sk[J, 0]+1], 2]:=I-1; DelFromAll(Sk[J, Sk[J, 0]+1]); B:=True; SetLength(Sk[J], High(Sk[J])); inc(I, Length(Sko[J].Last)-1); Break; end; end; end; if Not B then begin for J:=0 to High(Sko) do begin T:=Copy(S, I, length(Sko[J].First)); if (T=Sko[J].First)And(Not Comment){And(Not InBrackets(J))} then begin Inc(Sk[J, 0]); inc(Q); SetLength(Sk[J], High(Sk[J])+2); SetLength(Te, High(Te)+2); Sk[J, Sk[J, 0]]:=Q; Te[Q, 1]:=I+Length(Sko[J].First)-1; Te[Q, 3]:=J+Length(Rez); Inc(I, Length(Sko[J].First)-1); Break; end; end; end; inc(I); end; RE.Lines.BeginUpdate; RE.Perform(EM_SETSEL, 0, Length(RE.Text)); RE.SelAttributes.Color:=TextColor; RE.SelAttributes.Style:=TextStyle; for I:=0 to Q do begin if Te[I, 2]<>0 then begin // St:=Find(I); RE.Perform(EM_SETSEL, Te[I, 1], Te[I, 2]); if Te[I, 3]>=Length(Rez) then begin RE.SelAttributes.Color:=Sko[Te[I, 3]-Length(Rez)].Style.Color; RE.SelAttributes.Style:=Sko[Te[I, 3]-Length(Rez)].Style.Styles; end else begin RE.SelAttributes.Color:=Rez[Te[I, 3]].Style.Color; RE.SelAttributes.Style:=Rez[Te[I, 3]].Style.Styles; end; end; end; RE.Lines.EndUpdate; Re.CaretPos:=Po; end; Function GetWord(RE: TRichEdit; var Be, Len: LongInt): String; var I, N: LongInt; begin N:=0; for I:=1 to RE.CaretPos.Y do Inc(N, Length(RE.Lines[I])+2); for I:=N downto 1 do begin if Not Letter(RE.Text[I]) then begin Be:=I; Break; end; end; for I:=N to Length(RE.Text) do begin if Not Letter(RE.Text[I]) then begin Len:=I-Be; Break; end; end; end; Function CheckWord(RE: TRichEdit; Rez: array of TRezerved): Boolean; var T: String; J: LongInt; begin T:=RUpperCase(RE.Text); for J:=0 to High(Rez) do begin if (T=Rez[J].S) then begin { RE.Perform(EM_SETSEL, 0, Length(RE.Text)); RE.SelAttributes.Color:=Rez[J].Style.Color; RE.SelAttributes.Style:=Rez[J].Style.Styles;} Break; end; end; end; procedure EaseSyntax(RE: TRichEdit; Sko: array of TSkobki; TextColor: TColor; TextStyle: TFontStyles; S: String); var I, J, C, Con: Longint; T: String; B: Boolean; Mark: array of record S, E: LongInt; Num: LongInt; end; function FindLast(N: LongInt): LongInt; var I, J: LongInt; begin FindLast:=-1; for I := High(Mark) downto 0 do begin if Mark[I].Num=N then begin FindLast:=I; Break; end; end; end; begin I:=1; while I<=Length(S) do begin for J:=0 to High(Sko) do begin B:=False; T:=Copy(S, I, length(Sko[J].First)); if (RUpperCase(T)=Sko[J].First) then begin SetLength(Mark, High(Mark)+2); Mark[High(Mark)].S:=I; Mark[High(Mark)].Num:=J; delete(S, I, length(Sko[J].First)); dec(I); B:=True; Break; end; end; if Not B then begin for J:=0 to High(Sko) do begin T:=Copy(S, I, length(Sko[J].Last)); if (RUpperCase(T)=Sko[J].Last) then begin C:=FindLast(J); if C<>-1 then begin Mark[C].E:=I; delete(S, I, length(Sko[J].Last)); dec(I); end; Break; end; end; end; inc(I); end; Con:=Length(S); { if High(Mark)>-1 then begin Con:=0; for I := 0 to RE.Lines.Count - 1 do begin inc(Con, Length(RE.Lines.Strings[I])); inc(Con, 2); end; end;} RE.Lines.Add(S); for I := 0 to High(Mark) do begin { if not Mark[I].Visit then begin Test(Mark[I].S, Mark[I].E, Sko[Mark[I].Num].Style); for J := 0 to High(Mas) do begin } RE.Perform(EM_SETSEL, Length(RE.Lines.Text)-Con+Mark[I].S-3, Length(RE.Lines.Text)-Con+Mark[I].E-3); if Sko[Mark[I].Num].Stat then RE.SelAttributes.Color:=Sko[Mark[I].Num].Style.Color else RE.SelAttributes.Style:=Sko[Mark[I].Num].Style.Styles; // end; // end; end; end; function Parse(S: String): String; var T: String; begin if S[1]='<' then begin T:=copy(S, 2, pos('>', S)-2); if IsOP(T)=-1 then begin Insert('[/blue][/b]', S, pos('>', S)); Insert('[b][blue]', S, 2); end else begin Insert('[/red][/b]', S, pos('>', S)); Insert('[b][red]', S, 2); end; end; Parse:=S; end; end.
unit uDadosBasicos; {********************************************************************** ** unit uDadosBasicos ** ** ** ** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE ** ** REFERENTE AS INFORMAÇÕES DENTRO DA ABA DE DADOS BÁSICOS ** ** ** ***********************************************************************} {$mode objfpc}{$H+} interface uses Classes, SysUtils, uCadPacientes, uClassPaciente, DateTimePicker, uClassControlePaciente, uFrmMensagem; type { DadosBasicos } DadosBasicos = class public class procedure InclusaoOuEdicaoDadosBasicos(frm: TfrmCadPaciente); class function CarregaObjDadosBasicos(objDados: TPaciente; frm: TfrmCadPaciente): TPaciente; class procedure ApagarDadosBasico(codigo: integer); end; implementation { DadosBasicos } class procedure DadosBasicos.InclusaoOuEdicaoDadosBasicos(frm: TfrmCadPaciente); var objDadosBasicos : TPaciente; objControlePaciente : TControlePaciente; codigo : integer; frmMensagem : TfrmMensagem; begin if Trim(frm.edtNomePaciente.Text) = '' then begin try frmMensagem := TfrmMensagem.Create(nil); frmMensagem.InfoFormMensagem('A T E N Ç Ã O', tiAviso, 'O nome do paciente deve ser preenchido!'); finally FreeAndNil(frmMensagem); end; frm.edtNomePaciente.SetFocus; exit; end; try objDadosBasicos := TPaciente.Create; objControlePaciente := TControlePaciente.Create; objDadosBasicos := CarregaObjDadosBasicos(objDadosBasicos, frm); codigo := objControlePaciente.InclusaoOuEdicaoDadosBasicos(objDadosBasicos); if codigo > 0 then begin try frmMensagem := TfrmMensagem.Create(nil); frmMensagem.InfoFormMensagem('Cadastro do paciente', tiInformacao, 'Paciente cadastrado com sucesso!'); finally FreeAndNil(frmMensagem); end; frm.lblCodPaciente.Caption := 'Código: ' + IntToStr(codigo); frm.lblNomePaciente.Caption := 'Nome do Paciente: ' + frm.edtNomePaciente.Text; if objDadosBasicos.dataNascimento <> StrToDate('30/12/1899')then frm.lblIdade.Caption := objDadosBasicos.RetornoIdadeCompleta; frm.edtCodPaciente.Text := IntToStr(codigo); //DesabilitaControles(pcCadPaciente.ActivePage); //estado := teNavegacao; //EstadoBotoes; end else frm.lblCodPaciente.Caption := 'Código: '; finally FreeAndNil(objControlePaciente); FreeAndNil(objDadosBasicos); end; end; class function DadosBasicos.CarregaObjDadosBasicos(objDados: TPaciente; frm: TfrmCadPaciente): TPaciente; begin with objDados do {** PREENCHER O OBJETO PACIENTE COM OS SEUS DADOS BASÍCOS QUE ESTÃO NO FORM **} begin if frm.chkboxAtivo.Checked then ativo := 'A' else ativo := 'I'; if frm.edtCodPaciente.Text = EmptyStr then // Caso vazio o ID recebe zero, senão preenche a instancia com o ID exisstente idPaciente := 0 else idPaciente := StrToInt(frm.edtCodPaciente.Text); nomePaciente := frm.edtNomePaciente.Text; nomePai := frm.edtNomePai.Text; nomeMae := frm.edtNomeMae.Text; estadoCivil := frm.cboxEstCivil.Text; nomeConjuge := frm.edtNomeConjuge.Text; case frm.rgexSexo.ItemIndex of 0 : sexo := 'F'; 1 : sexo := 'M'; end; if not(IsNullDate(frm.dtpkNascimento.Date)) then dataNascimento := frm.dtpkNascimento.Date; naturalidade := frm.edtNaturalidade.Text; ufNascimento := frm.cboxUFNascimento.Text; nacionalidade := frm.edtNacionalidade.Text; end; result := objDados; end; class procedure DadosBasicos.ApagarDadosBasico(codigo: integer); var frmMensagem : TfrmMensagem; objControlePaciente : TControlePaciente; begin objControlePaciente := TControlePaciente.Create; if objControlePaciente.ApagarCadastroBasico(codigo) then begin try frmMensagem := TfrmMensagem.Create(nil); frmMensagem.InfoFormMensagem('Remoção do cadastro do paciente', tiInformacao, 'Paciente removido com sucesso!'); finally FreeAndNil(frmMensagem); end; end; end; end.
{ just adds a pop up menu with a 'paste' item to TPasswordRichEdit} unit OTFEFreeOTFE_PasswordRichEdit; interface uses Classes, Menus, PasswordRichEdit; type TOTFEFreeOTFE_PasswordRichEdit = class (TPasswordRichEdit) private FInternalPopupMenu: TPopupMenu; protected procedure SetPopupMenu(newMenu: TPopupMenu); function GetPopupMenuFilterInternal(): TPopupMenu; procedure PasteClicked(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; published property PopupMenu: TPopupMenu Read GetPopupMenuFilterInternal;// write SetPopupMenu; end; procedure Register; implementation resourcestring RS_PASTE = 'Paste'; procedure Register; begin RegisterComponents('FreeOTFE', [TOTFEFreeOTFE_PasswordRichEdit]); end; constructor TOTFEFreeOTFE_PasswordRichEdit.Create(AOwner: TComponent); var pasteMenuItem: TMenuItem; begin inherited; FInternalPopupMenu := TPopupMenu.Create(nil); pasteMenuItem := TMenuItem.Create(FInternalPopupMenu); pasteMenuItem.OnClick := PasteClicked; pasteMenuItem.Caption := RS_PASTE; pasteMenuItem.ShortCut := TextToShortCut('CTRL+V'); FInternalPopupMenu.Items.Add(pasteMenuItem); SetPopupMenu(FInternalPopupMenu); end; destructor TOTFEFreeOTFE_PasswordRichEdit.Destroy(); begin if (GetPopupMenu = FInternalPopupMenu) then begin SetPopupMenu(nil); end; FInternalPopupMenu.Free(); inherited; end; procedure TOTFEFreeOTFE_PasswordRichEdit.SetPopupMenu(newMenu: TPopupMenu); begin // Don't set to FInternalPopupMenu; Destroy() calls this with nil, then free's // off FInternalPopupMenu! // if (newMenu = nil) then // begin // newMenu := FInternalPopupMenu; // end; inherited PopupMenu := newMenu; end; function TOTFEFreeOTFE_PasswordRichEdit.GetPopupMenuFilterInternal(): TPopupMenu; begin Result := inherited GetPopupMenu; if (Result = FInternalPopupMenu) then Result := nil; end; procedure TOTFEFreeOTFE_PasswordRichEdit.PasteClicked(Sender: TObject); begin self.PasteFromClipboard(); end; end.
{* FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn Cryptograpical code from OpenSSL Project *} unit sshmac; interface uses sshhash, sshsha; type TSSH2MAC = class protected function GetMacSize: integer; virtual; function GetName: string; virtual; procedure GenMAC(Source: Pointer; Len: integer; Dest: Pointer; Sequence: integer); virtual; public procedure SetKey(Data: Pointer); virtual; procedure MakeMAC(Source: Pointer; Len: integer; Sequence: integer); function VerifyMAC(Source: Pointer; Len: integer; Sequence: integer): boolean; property MacSize: integer read GetMacSize; property Name: string read GetName; end; TSSH2MACSHA1 = class(TSSH2MAC) protected s1, s2: TSSHSHA1; procedure SHA1Key(var s1, s2: TSSHSHA1; Key: Pointer; Len: integer); function GetMacSize: integer; override; function GetName: string; override; procedure GenMAC(Source: Pointer; Len: integer; Dest: Pointer; Sequence: integer); override; public constructor Create; procedure SetKey(Data: Pointer); override; end; TSSH2MACSHA1Buggy = class(TSSH2MACSHA1) public procedure SetKey(Data: Pointer); override; end; implementation uses Math, Sysutils, WinSock; { TSSH2MAC } procedure TSSH2MAC.GenMAC(Source: Pointer; Len: integer; Dest: Pointer; Sequence: integer); begin end; function TSSH2MAC.GetMacSize: integer; begin Result := 0; end; function TSSH2MAC.GetName: string; begin Result := ''; end; procedure TSSH2MAC.MakeMAC(Source: Pointer; Len, Sequence: integer); begin GenMAC(Source, Len, PChar(Source) + Len, Sequence); end; procedure TSSH2MAC.SetKey(Data: Pointer); begin end; function TSSH2MAC.VerifyMAC(Source: Pointer; Len, Sequence: integer): boolean; var correct: array[0..19] of char; begin GenMac(Source, Len, @correct, Sequence); Result := CompareMem(@correct, PChar(Source) + Len, 20); end; { TSSH2MACSHA1 } constructor TSSH2MACSHA1.Create; begin s1 := TSSHSHA1.Create; s2 := TSSHSHA1.Create; end; procedure TSSH2MACSHA1.GenMAC(Source: Pointer; Len: integer; Dest: Pointer; Sequence: integer); var s: TSSHSHA1; buf: array[0..19] of byte; i: integer; begin i := ntohl(Sequence); s := TSSHSHA1.Create; s.Assign(s1); s.Update(@i, 4); s.Update(Source, Len); s.Final(@buf); s.Assign(s2); s.Update(@buf, 20); s.Final(Dest); s.Free; end; function TSSH2MACSHA1.GetMacSize: integer; begin Result := 20; end; function TSSH2MACSHA1.GetName: string; begin Result := 'hmac-sha1'; end; procedure TSSH2MACSHA1.SetKey(Data: Pointer); begin SHA1Key(s1, S2, Data, 20); end; procedure TSSH2MACSHA1.SHA1Key(var s1, s2: TSSHSHA1; Key: Pointer; Len: integer); var foo: array[1..64] of byte; i: integer; keyptr: PChar; begin Fillchar(foo, 64, $36); KeyPtr := Key; for i := 1 to min(64, len) do foo[i] := foo[i] xor Ord((KeyPtr + i - 1)^); S1.Free; S1 := TSSHSHA1.Create; s1.Update(@foo, 64); Fillchar(foo, 64, $5C); for i := 1 to min(64, len) do foo[i] := foo[i] xor Ord((KeyPtr + i - 1)^); S2.Free; S2 := TSSHSHA1.Create; s2.Update(@foo, 64); Fillchar(foo, 64, 0); end; { TSSH2MACSHA1Buggy } procedure TSSH2MACSHA1Buggy.SetKey(Data: Pointer); begin SHA1Key(s1, S2, Data, 16); end; end.
unit UserScript; var i: Integer; sortedList, unsortedList: TStringList; // function ripped from mator's library function HexFormID(e: IInterface): String; var s: String; begin s := GetElementEditValues(e, 'Record Header\FormID'); if SameText(Signature(e), '') then Result := '00000000' else Result := Copy(s, Pos('[' + Signature(e) + ':', s) + Length(Signature(e)) + 2, 8); end; function Initialize: Integer; begin sortedList := TStringList.Create; sortedList.Sorted := True; unsortedList := TStringList.Create; unsortedList.Sorted := False; end; function Process(e: IInterface): Integer; var kParent, kChild, kReference: IInterface; s: String; begin if Signature(e) <> 'FLST' then exit; kParent := ElementByName(e, 'FormIDs'); // create a delimited list of ref counts and Form IDs by iterating through // lnams, counting refs, and sorting by number of refs. // the list is sorted automatically. for i := 0 to ElementCount(kParent) - 1 do begin kChild := ElementByIndex(kParent, i); kReference := LinksTo(kChild); // call to format() pads ref count with up to 5 leading zeroes // so we can sort numbers as strings correctly s := Format('%.*d', [5, ReferencedByCount(kReference)]) + ',' + HexFormID(kReference); sortedList.Add(s); end; // create a new explicitly unsorted list of Form IDs by removing padded ref // counts from all items in the previous list. for i := sortedList.Count - 1 downto 0 do begin s := sortedList[i]; // remove chars at indices 1 through 6 (padded number + comma) Delete(s, 1, 6); unsortedList.Add(s); end; // iterate through lnams again, from the bottom up, overwriting each lnam // with the values from the unsorted list. we go bottom up because the // original list is sorted in ascending order, but we want descending order // for the formlist, so that the most common item is first. kParent := ElementByName(e, 'FormIDs'); for i := ElementCount(kParent) - 1 downto 0 do begin kChild := ElementByIndex(kParent, i); SetEditValue(kChild, unsortedList[i]); end; sortedList.Clear; unsortedList.Clear; end; function Finalize: Integer; begin sortedList.Free; unsortedList.Free; end; end.
unit uSelectParams; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, uFControl, uLabeledFControl, uSpravControl, ActnList, Buttons, DB, FIBDataSet, pFIBDataSet, uCommonSp, uMemoControl, uInvisControl, uCharControl, qFTools; type TfmSelectParams = class(TForm) Department: TqFSpravControl; CheckPlan: TCheckListBox; Label1: TLabel; OkButton: TBitBtn; BitBtn1: TBitBtn; KeyList: TActionList; OkAction: TAction; CancelAction: TAction; SelectTypePost: TpFIBDataSet; SelectTypePostID_TYPE_POST: TFIBIntegerField; SelectTypePostNAME_TYPE_POST: TFIBStringField; SelectTypePostSHORT_NAME: TFIBStringField; IntroText: TqFMemoControl; PostTypeStr: TqFCharControl; DetQuery: TpFIBDataSet; DetQueryPOST_TYPE_STR: TFIBStringField; DetQueryID_DEPARTMENT: TFIBIntegerField; DetQueryINTRO: TFIBStringField; DetQueryDEPARTMETN_NAME: TFIBStringField; procedure OkActionExecute(Sender: TObject); procedure CancelActionExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); procedure CheckPlanClick(Sender: TObject); private { Private declarations } public ar: array [0..100] of integer; ResultPostStr : String; end; var fmSelectParams: TfmSelectParams; implementation uses uPlanHolidayOrder; {$R *.dfm} procedure TfmSelectParams.OkActionExecute(Sender: TObject); var i, k : Integer; Proverka: Boolean; len:Integer; begin if VarIsNull(Department.Value) then begin MessageDlg('Потрібно вибрати Підрозділ!',mtError,[mbYes],0); exit; end; Proverka :=False; ResultPostStr :=''; for k := 0 to CheckPlan.Items.Count - 1 do begin if CheckPlan.Checked[k] then begin Proverka :=True; break; end; end; if (proverka=True) then begin for i := 0 to CheckPlan.Items.Count - 1 do if CheckPlan.Checked[i] then ResultPostStr := ResultPostStr + IntToStr(ar[i]) + ','; ResultPostStr := Copy(ResultPostStr, 1, Length(ResultPostStr) - 1); end else begin MessageDlg('Потрібно вибрати тип персоналу!',mtError,[mbYes],0); exit; end; PostTypeStr.Value := ResultPostStr; qFtools.qFAutoSaveIntoRegistry(Self, nil); ModalResult := mrOk; end; procedure TfmSelectParams.CancelActionExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfmSelectParams.FormCreate(Sender: TObject); var i : Integer; s : String; begin try if uPlanHolidayOrder.fmPlanHolidayOrder.SelectQuery.IsEmpty then begin qFtools.qFAutoLoadFromRegistry(Self, nil); S := PostTypeStr.Value; end else begin DetQuery.Close; DetQuery.ParamByName('ID_ORDER').AsInteger := uPlanHolidayOrder.fmPlanHolidayOrder.IdOrder; DetQuery.Open; if not DetQuery.IsEmpty then begin Department.Value := DetQueryID_DEPARTMENT.Value; Department.DisplayText := DetQueryDEPARTMETN_NAME.Value; IntroText.Value := DetQueryINTRO.Value; S := DetQueryPOST_TYPE_STR.Value; end; end; except end; SelectTypePost.Open; SelectTypePost.First; i := 0; while not SelectTypePost.Eof do begin CheckPlan.Items.add(SelectTypePostNAME_TYPE_POST.Value); // запись в массив ar[i] := SelectTypePostID_TYPE_POST.Value; // если в предыдущий раз был выбран этот пункт, то устанавливаем флажок if (pos(IntToStr(SelectTypePostID_TYPE_POST.Value) + ',', s) <> 0) or (pos(',' + IntToStr(SelectTypePostID_TYPE_POST.Value), s) <> 0) or (IntToStr(SelectTypePostID_TYPE_POST.Value) = s) then CheckPlan.Checked[i] := True; SelectTypePost.Next; i := i + 1; end; end; procedure TfmSelectParams.DepartmentOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: String); var sp: TSprav; begin // создать справочник sp := GetSprav('SpDepartment'); if sp <> nil then begin // заполнить входные параметры with sp.Input do begin Append; FieldValues['DBHandle'] := Integer(fmPlanHolidayOrder.LocalDatabase.Handle); FieldValues['Actual_Date'] := Date; Post; end; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if ( sp.Output <> nil ) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Department']; DisplayText := sp.Output['Name_Full']; end; sp.Free; end; end; procedure TfmSelectParams.CheckPlanClick(Sender: TObject); var pPostType : String; y, m, d : Word; i : Integer; begin for i := 0 to CheckPlan.Items.Count - 1 do if CheckPlan.Checked[i] then pPostType := pPostType + CheckPlan.Items[i] + ', '; pPostType := Copy(pPostType, 1, Length(pPostType) - 2); DecodeDate(uPlanHolidayOrder.fmPlanHolidayOrder.DateOrder, y, m, d); IntroText.Value := ' Згідно графіку відпусток для типів персоналу: ' + pPostType + ' за ' + IntToStr(y) + ' рік, затвердженому ректором і узгодженому з профкомом ДонНУ,' + ' надати щорічну відпустку нижепереліченим працівникам у наступний термін:'; end; end.
// Wheberson Hudson Migueletti, em Brasília, 03 de abril de 1999. // Codificação/Descodificação de arquivos ".cur" e ".ico" (Windows CUR/ICO). // Captura a primeira (caso tenha mais de 1) imagem e a primeira máscara. unit DelphiCursorIcon; interface uses Windows, SysUtils, Classes, Graphics, DelphiImage; type PCursorDirectoryEntry= ^TCursorDirectoryEntry; TCursorDirectoryEntry= packed record bWidth : Byte; // Largura do cursor bHeight : Byte; // Altura do cursor bColorCount : Byte; // Deve ser 0 bReserved : Byte; // Deve ser 0 wXHotspot : Word; // Coordenada em X do Hotspot wYHotspot : Word; // Coordenada em Y do Hotspot lBytesInRes : Integer; // Tamanho do objeto em bytes dwImageOffset: Integer; // Onde começa a imagem (a partir da posição 0) end; PIconDirectoryEntry= ^TIconDirectoryEntry; TIconDirectoryEntry= packed record bWidth : Byte; // Largura do ícone bHeight : Byte; // Altura do ícone bColorCount : Byte; // Deve ser 0 bReserved : Byte; // Deve ser 0 wPlanes : Word; // Planos wBitCount : Word; // Bits por pixel lBytesInRes : Integer; // Tamanho objeto em bytes dwImageOffset: Integer; // Onde começa a imagem (a partir da posição 0) end; PCursorOrIcon= ^TCursorOrIcon; TCursorOrIcon= packed record cdReserved: Word; // Deve ser sempre 0 cdType : Word; // Deve ser sempre 2 cdCount : Word; // Número de cursores end; PCursorDirectory= ^TCursorDirectory; TCursorDirectory= packed record cdReserved: Word; // Deve ser sempre 0 cdType : Word; // Deve ser sempre 2 cdCount : Word; // Número de cursores cdEntries : TCursorDirectoryEntry; // Primeiro "CursorDirectoryEntry" end; PIconDirectory= ^TIconDirectory; TIconDirectory= packed record cdReserved: Word; // Deve ser sempre 0 cdType : Word; // Deve ser sempre 1 cdCount : Word; // Número de ícones cdEntries : TIconDirectoryEntry; // Primeiro "IconDirectoryEntry" end; TCursorIcon= class (TBitmap) protected Color : TRGBQuad; Stream: TStream; procedure Read (var Buffer; Count: Integer); procedure ReadStream (AStream: TStream); procedure DumpHeader; procedure DumpImage; public Cursor : Boolean; // Cursor -> True; Icon -> False Mask : TBitmap; Hotspot: TPoint; constructor Create (AColor: TColor); destructor Destroy; override; function IsValid (const FileName: String): Boolean; procedure LoadFromStream (Stream: TStream); override; end; function CriarCursor (XorBits, AndBits: HBitmap; XHotSpot, YHotSpot: LongInt): HCursor; procedure SaveBitmapsAsCursorToStream (Stream: TStream; Bitmap, Mask: TBitmap; Hotspot: TPoint); procedure SaveBitmapsAsCursorToFile (const FileName: String; Bitmap, Mask: TBitmap; Hotspot: TPoint); procedure SaveBitmapAsCursorToFile (const FileName: String; Bitmap: TBitmap; Hotspot: TPoint; CreateMask, Mono: Boolean); function CriarIcone (XorBits, AndBits: HBitmap): HIcon; procedure SaveBitmapsAsIconToStream (Stream: TStream; Bitmap, Mask: TBitmap); procedure SaveBitmapsAsIconToFile (const FileName: String; Bitmap, Mask: TBitmap); procedure SaveBitmapAsIconToFile (const FileName: String; Bitmap: TBitmap; CreateMask: Boolean); procedure MergeColorMask (Bitmap, BMColor, BMMask: TBitmap); implementation uses DelphiColorQuantization; // Borland function DupBits (Src: HBitmap; Size: TPoint; Mono: Boolean): HBitmap; var DC, Mem1, Mem2: HDC; Old1, Old2 : HBitmap; Bitmap : Windows.TBitmap; begin Result:= 0; Mem1 := CreateCompatibleDC (0); Mem2 := CreateCompatibleDC (0); try GetObject (Src, SizeOf (Bitmap), @Bitmap); if Mono then Result:= CreateBitmap (Size.X, Size.Y, 1, 1, nil) else begin DC:= GetDC (0); if DC <> 0 then begin try Result:= CreateCompatibleBitmap (DC, Size.X, Size.Y); finally ReleaseDC (0, DC); end; end; end; if Result <> 0 then begin Old1:= SelectObject (Mem1, Src); Old2:= SelectObject (Mem2, Result); StretchBlt (Mem2, 0, 0, Size.X, Size.Y, Mem1, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, SrcCopy); if Old1 <> 0 then SelectObject (Mem1, Old1); if Old2 <> 0 then SelectObject (Mem2, Old2); end; finally DeleteDC (Mem1); DeleteDC (Mem2); end; end; // Borland function CriarCursor (XorBits, AndBits: HBitmap; XHotSpot, YHotSpot: LongInt): HCursor; var Length : Integer; XorLen, AndLen : Integer; ResData : Pointer; XorMem, AndMem : Pointer; XorInfo, AndInfo: Windows.TBitmap; CursorSize : TPoint; begin CursorSize.X:= GetSystemMetrics (SM_CXCURSOR); CursorSize.Y:= GetSystemMetrics (SM_CYCURSOR); XorBits := DupBits (XorBits, CursorSize, True); AndBits := DupBits (AndBits, CursorSize, True); GetObject (AndBits, SizeOf (Windows.TBitmap), @AndInfo); GetObject (XorBits, SizeOf (Windows.TBitmap), @XorInfo); with AndInfo do AndLen:= bmWidthBytes * bmHeight * bmPlanes; with XorInfo do XorLen:= bmWidthBytes * bmHeight * bmPlanes; Length := AndLen + XorLen; ResData:= AllocMem (Length); try AndMem:= ResData; with AndInfo do XorMem:= Pointer (LongInt (ResData) + AndLen); GetBitmapBits (AndBits, AndLen, AndMem); GetBitmapBits (XorBits, XorLen, XorMem); Result:= CreateCursor (HInstance, XHotSpot, YHotSpot, CursorSize.X, CursorSize.Y, AndMem, XorMem); finally FreeMem (ResData, Length); end; end; // Borland function CriarIcone (XorBits, AndBits: HBitmap): HIcon; var Length : Integer; XorLen, AndLen : Integer; ResData : Pointer; XorMem, AndMem : Pointer; XorInfo, AndInfo: Windows.TBitmap; IconSize : TPoint; begin IconSize.X:= GetSystemMetrics (SM_CXICON); IconSize.Y:= GetSystemMetrics (SM_CYICON); XorBits := DupBits (XorBits, IconSize, False); AndBits := DupBits (AndBits, IconSize, True); GetObject (AndBits, SizeOf (Windows.TBitmap), @AndInfo); GetObject (XorBits, SizeOf (Windows.TBitmap), @XorInfo); with AndInfo do AndLen:= bmWidthBytes * bmHeight * bmPlanes; with XorInfo do XorLen:= bmWidthBytes * bmHeight * bmPlanes; Length := AndLen + XorLen; ResData:= AllocMem (Length); try AndMem:= ResData; with AndInfo do XorMem:= Pointer (LongInt (ResData) + AndLen); GetBitmapBits (AndBits, AndLen, AndMem); GetBitmapBits (XorBits, XorLen, XorMem); Result:= CreateIcon (HInstance, IconSize.X, IconSize.Y, XorInfo.bmPlanes, XorInfo.bmBitsPixel, AndMem, XorMem); finally FreeMem (ResData, Length); end; end; function ConverterIconeParaCursor (HotSpot: TPoint; Icon: Graphics.TIcon): HCursor; var Length : Integer; XorLen, AndLen : Integer; ResData : Pointer; XorMem, AndMem : Pointer; XorInfo, AndInfo: Windows.TBitmap; IconInfo : TIconInfo; CursorSize : TPoint; begin GetIconInfo (Icon.Handle, IconInfo); CursorSize.X := GetSystemMetrics (SM_CXCURSOR); CursorSize.Y := GetSystemMetrics (SM_CYCURSOR); IconInfo.hbmColor:= DupBits (IconInfo.hbmColor, CursorSize, True); IconInfo.hbmMask := DupBits (IconInfo.hbmMask, CursorSize, True); GetObject (IconInfo.hbmMask, SizeOf (Windows.TBitmap), @AndInfo); GetObject (IconInfo.hbmColor, SizeOf (Windows.TBitmap), @XorInfo); with AndInfo do AndLen:= bmWidthBytes * bmHeight * bmPlanes; with XorInfo do XorLen:= bmWidthBytes * bmHeight * bmPlanes; Length := AndLen + XorLen; ResData:= AllocMem (Length); try AndMem:= ResData; with AndInfo do XorMem:= Pointer (LongInt (ResData) + AndLen); GetBitmapBits (IconInfo.hbmMask, AndLen, AndMem); GetBitmapBits (IconInfo.hbmMask, XorLen, XorMem); Result:= CreateCursor (HInstance, HotSpot.X, HotSpot.Y, CursorSize.X, CursorSize.Y, AndMem, XorMem); finally FreeMem (ResData, Length); end; end; // O armazenamento é feito a partir da posição corrente da "Stream" procedure SaveBitmapsAsCursorToStream (Stream: TStream; Bitmap, Mask: TBitmap; Hotspot: TPoint); var StartPosition: Integer; BFH : TBitmapFileHeader; BIH, BIHMask : TBitmapInfoHeader; CursorDir : TCursorDirectory; DIBStream : TMemoryStream; begin if Assigned (Stream) then begin DIBStream:= TMemoryStream.Create; try // Carregando o DIB do "Bitmap" Bitmap.SaveToStream (DIBStream); DIBStream.Seek (SizeOf (TBitmapFileHeader), soFromBeginning); DIBStream.Read (BIH, SizeOf (TBitmapInfoHeader)); DIBStream.Seek (SizeOf (TBitmapFileHeader), soFromBeginning); // Inicializando FillChar (CursorDir, SizeOf (TCursorDirectory), #0); with CursorDir, cdEntries do begin cdType := 2; cdCount := 1; wXHotspot := Hotspot.X; wYHotspot := Hotspot.Y; dwImageOffset:= SizeOf (TCursorDirectory); if Bitmap.Width < 256 then bWidth:= Bitmap.Width; if Bitmap.Height < 256 then bHeight:= Bitmap.Height; end; StartPosition:= Stream.Position; Stream.Write (CursorDir, SizeOf (TCursorDirectory)); // Copiando o DIB do "Bitmap" Stream.CopyFrom (DIBStream, DIBStream.Size-DIBStream.Position); // Carregando/Copiando o DIB do "Mask" DIBStream.Clear; Mask.SaveToStream (DIBStream); DIBStream.Seek (0, soFromBeginning); DIBStream.Read (BFH, SizeOf (TBitmapFileHeader)); DIBStream.Read (BIHMask, SizeOf (TBitmapInfoHeader)); DIBStream.Seek (BFH.bfOffBits, soFromBeginning); Stream.CopyFrom (DIBStream, DIBStream.Size-DIBStream.Position); // Atualizando o "Header" try CursorDir.cdEntries.lBytesInRes:= Stream.Size - StartPosition - SizeOf (TCursorDirectory); Inc (BIH.biHeight, BIHMask.biHeight); Inc (BIH.biSizeImage, BIHMask.biSizeImage); Stream.Seek (StartPosition, soFromBeginning); Stream.Write (CursorDir, SizeOf (TCursorDirectory)); Stream.Write (BIH, SizeOf (TBitmapInfoHeader)); finally Stream.Seek (0, soFromEnd); end; finally DIBStream.Free; end; end; end; procedure SaveBitmapsAsCursorToFile (const FileName: String; Bitmap, Mask: TBitmap; Hotspot: TPoint); var Stream: TMemoryStream; begin if (FileName <> '') and Assigned (Bitmap) and Assigned (Mask) then begin Stream:= TMemoryStream.Create; try // Copia SaveBitmapsAsCursorToStream (Stream, Bitmap, Mask, Hotspot); // Grava Stream.Seek (0, soFromBeginning); Stream.SaveToFile (FileName); finally Stream.Free; end; end; end; procedure SaveBitmapAsCursorToFile (const FileName: String; Bitmap: TBitmap; Hotspot: TPoint; CreateMask, Mono: Boolean); const cTamanhoDefault= 32; var TamanhoExato: Boolean; Mask : TBitmap; procedure MontarMascara (Bmp: TBitmap); var R: TRect; begin Mask.Width := Bmp.Width; Mask.Height:= Bmp.Height; if CreateMask then begin Mask.Canvas.CopyMode:= cmSrcInvert; Mask.Canvas.CopyRect (Rect (0, 0, Bmp.Width, Bmp.Height), Bmp.Canvas, Rect (0, 0, Bmp.Width, Bmp.Height)); end else if TamanhoExato then begin Mask.Canvas.Brush.Color:= clBlack; Mask.Canvas.FillRect (Rect (0, 0, Mask.Width, Mask.Height)); end else begin Mask.Canvas.Brush.Color:= clWhite; Mask.Canvas.FillRect (Rect (0, 0, Mask.Width, Mask.Height)); Mask.Canvas.Brush.Color:= clBlack; R := Enquadrar (Bitmap.Width, Bitmap.Height, Mask.Width, Mask.Height, True); Inc (R.Right); Inc (R.Bottom); Mask.Canvas.FillRect (R); end; SetPixelFormat (Mask, pf1bit); end; var Bmp: TBitmap; begin if (FileName <> '') and Assigned (Bitmap) then begin Mask:= TBitmap.Create; try TamanhoExato:= (Bitmap.Width = cTamanhoDefault) and (Bitmap.Height = cTamanhoDefault); if (not Mono) and TamanhoExato and (Bitmap.PixelFormat in [pf1bit, pf4bit, pf8bit]) then begin MontarMascara (Bitmap); SaveBitmapsAsCursorToFile (FileName, Bitmap, Mask, Hotspot); end else begin Bmp:= TBitmap.Create; try if TamanhoExato then Bmp.Assign (Bitmap) else DimensionarBitmap (Bitmap, Bmp, cTamanhoDefault, cTamanhoDefault, cteQuandoNecessario, True, True, clBlack); if Mono then SetPixelFormat (Bmp, pf1bit) else SetPixelFormat (Bmp, pf8bit); MontarMascara (Bmp); SaveBitmapsAsCursorToFile (FileName, Bmp, Mask, Hotspot); finally Bmp.Free; end; end; finally Mask.Free; end; end; end; // O armazenamento é feito a partir da posição corrente da "Stream" procedure SaveBitmapsAsIconToStream (Stream: TStream; Bitmap, Mask: TBitmap); var StartPosition: Integer; BFH : TBitmapFileHeader; BIH, BIHMask : TBitmapInfoHeader; IconDir : TIconDirectory; DIBStream : TMemoryStream; begin if Assigned (Stream) then begin DIBStream:= TMemoryStream.Create; try // Carregando o DIB do "Bitmap" Bitmap.SaveToStream (DIBStream); DIBStream.Seek (SizeOf (TBitmapFileHeader), soFromBeginning); DIBStream.Read (BIH, SizeOf (TBitmapInfoHeader)); DIBStream.Seek (SizeOf (TBitmapFileHeader), soFromBeginning); // Inicializando FillChar (IconDir, SizeOf (TIconDirectory), #0); with IconDir, cdEntries do begin cdType := 1; cdCount := 1; wPlanes := BIH.biPlanes; wBitCount := BIH.biBitCount; dwImageOffset:= SizeOf (TIconDirectory); if Bitmap.Width < 256 then bWidth:= Bitmap.Width; if Bitmap.Height < 256 then bHeight:= Bitmap.Height; end; StartPosition:= Stream.Position; Stream.Write (IconDir, SizeOf (TIconDirectory)); // Copiando o DIB do "Bitmap" Stream.CopyFrom (DIBStream, DIBStream.Size-DIBStream.Position); // Carregando/Copiando o DIB do "Mask" DIBStream.Clear; Mask.SaveToStream (DIBStream); DIBStream.Seek (0, soFromBeginning); DIBStream.Read (BFH, SizeOf (TBitmapFileHeader)); DIBStream.Read (BIHMask, SizeOf (TBitmapInfoHeader)); DIBStream.Seek (BFH.bfOffBits, soFromBeginning); Stream.CopyFrom (DIBStream, DIBStream.Size-DIBStream.Position); // Atualizando o "Header" try IconDir.cdEntries.lBytesInRes:= Stream.Size - StartPosition - SizeOf (TIconDirectory); Inc (BIH.biHeight, BIHMask.biHeight); Inc (BIH.biSizeImage, BIHMask.biSizeImage); Stream.Seek (StartPosition, soFromBeginning); Stream.Write (IconDir, SizeOf (TIconDirectory)); Stream.Write (BIH, SizeOf (TBitmapInfoHeader)); finally Stream.Seek (0, soFromEnd); end; finally DIBStream.Free; end; end; end; procedure SaveBitmapsAsIconToFile (const FileName: String; Bitmap, Mask: TBitmap); var Stream: TMemoryStream; begin if (FileName <> '') and Assigned (Bitmap) and Assigned (Mask) then begin Stream:= TMemoryStream.Create; try // Copia SaveBitmapsAsIconToStream (Stream, Bitmap, Mask); // Grava Stream.Seek (0, soFromBeginning); Stream.SaveToFile (FileName); finally Stream.Free; end; end; end; procedure SaveBitmapAsIconToFile (const FileName: String; Bitmap: TBitmap; CreateMask: Boolean); const cTamanhoDefault= 32; var TamanhoExato: Boolean; Mask : TBitmap; procedure MontarMascara (Bmp: TBitmap); var R: TRect; begin Mask.Width := Bmp.Width; Mask.Height:= Bmp.Height; if CreateMask then begin Mask.Canvas.CopyMode:= cmSrcInvert; Mask.Canvas.CopyRect (Rect (0, 0, Bmp.Width, Bmp.Height), Bmp.Canvas, Rect (0, 0, Bmp.Width, Bmp.Height)); end else if TamanhoExato then begin Mask.Canvas.Brush.Color:= clBlack; Mask.Canvas.FillRect (Rect (0, 0, Mask.Width, Mask.Height)); end else begin Mask.Canvas.Brush.Color:= clWhite; Mask.Canvas.FillRect (Rect (0, 0, Mask.Width, Mask.Height)); Mask.Canvas.Brush.Color:= clBlack; R := Enquadrar (Bitmap.Width, Bitmap.Height, Mask.Width, Mask.Height, True); Inc (R.Right); Inc (R.Bottom); Mask.Canvas.FillRect (R); end; SetPixelFormat (Mask, pf1bit); end; var Bmp: TBitmap; begin if (FileName <> '') and Assigned (Bitmap) then begin Mask:= TBitmap.Create; try TamanhoExato:= (Bitmap.Width = cTamanhoDefault) and (Bitmap.Height = cTamanhoDefault); if TamanhoExato and (Bitmap.PixelFormat in [pf1bit, pf4bit, pf8bit]) then begin MontarMascara (Bitmap); SaveBitmapsAsIconToFile (FileName, Bitmap, Mask); end else begin Bmp:= TBitmap.Create; try if TamanhoExato then Bmp.Assign (Bitmap) else DimensionarBitmap (Bitmap, Bmp, cTamanhoDefault, cTamanhoDefault, cteQuandoNecessario, True, True, clBlack); SetPixelFormat (Bmp, pf8bit); MontarMascara (Bmp); SaveBitmapsAsIconToFile (FileName, Bmp, Mask); finally Bmp.Free; end; end; finally Mask.Free; end; end; end; procedure MergeColorMask (Bitmap, BMColor, BMMask: TBitmap); type PLine08= ^TLine08; PLine24= ^TLine24; TLine08= array[0..0] of Byte; TLine24= array[0..0] of TRGBTriple; var Entries: array[Byte] of TPaletteEntry; Black : Byte; X, Y : Integer; MLine : PLine08; BLine : PLine24; CLine : PLine24; Color : TRGBTriple; begin if Assigned (Bitmap) and Assigned (BMColor) and Assigned (BMMask) and (BMMask.PixelFormat = pf1bit) then begin GetPaletteEntries (BMMask.Palette, 0, 2, Entries); if (Entries[0].peRed = 0) and (Entries[0].peGreen = 0) and (Entries[0].peBlue = 0) then with Color do begin rgbtRed := Entries[1].peRed; rgbtGreen:= Entries[1].peGreen; rgbtBlue := Entries[1].peBlue; end else with Color do begin rgbtRed := Entries[0].peRed; rgbtGreen:= Entries[0].peGreen; rgbtBlue := Entries[0].peBlue; end; Bitmap.PixelFormat := pf24bit; BMColor.PixelFormat:= pf24bit; BMMask.PixelFormat := pf8bit; Black := GetNearestPaletteIndex (BMMask.Palette, 0); for Y:= 0 to Abs (Bitmap.Height)-1 do begin CLine:= BMColor.ScanLine[Y]; MLine:= BMMask.ScanLine[Y]; BLine:= Bitmap.ScanLine[Y]; for X:= 0 to Bitmap.Width-1 do if MLine[X] = Black then BLine[X]:= CLine[X] else BLine[X]:= Color; end; end; end; //---------------------------------------------------------------------------------------------- constructor TCursorIcon.Create (AColor: TColor); begin inherited Create; AColor:= Graphics.ColorToRGB (AColor); Mask := TBitmap.Create; with Color do begin rgbRed := GetRValue (AColor); rgbGreen := GetGValue (AColor); rgbBlue := GetBValue (AColor); rgbReserved:= 0; end; end; destructor TCursorIcon.Destroy; begin Mask.Free; inherited Destroy; end; procedure TCursorIcon.Read (var Buffer; Count: Integer); var Lidos: Integer; begin Lidos:= Stream.Read (Buffer, Count); if Lidos <> Count then raise EInvalidImage.Create (Format ('CURSOR/ICON read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos])); end; procedure TCursorIcon.ReadStream (AStream: TStream); begin Stream:= AStream; if Stream.Size > 0 then begin DumpHeader; DumpImage; end else begin Assign (nil); Mask.Assign (nil); end; end; procedure TCursorIcon.DumpHeader; var CursorOrIcon: TCursorOrIcon; Entry : TIconDirectoryEntry; begin Read (CursorOrIcon, Sizeof (TCursorOrIcon)); if (CursorOrIcon.cdReserved = 0) and (CursorOrIcon.cdType in [1, 2]) then begin Read (Entry, Sizeof (TIconDirectoryEntry)); {if CursorOrIcon.cdCount > 1 then Stream.Seek (CursorOrIcon.cdCount*Sizeof (TIconDirectoryEntry), soFromCurrent);} Stream.Seek (Entry.dwImageOffset, soFromBeginning); Cursor:= CursorOrIcon.cdType = 2; if Cursor then Hotspot:= Point (Entry.wPlanes, Entry.wBitCount); end else raise EUnsupportedImage.Create ('Unsupported file format !'); end; procedure TCursorIcon.DumpImage; const cBlack: Integer= $00000000; var Size : Integer; BMMaskSize : Integer; BitmapFileHeader: TBitmapFileHeader; BitmapInfoHeader: TBitmapInfoHeader; Local : TMemoryStream; begin Read (BitmapInfoHeader, SizeOf (TBitmapInfoHeader)); Local:= TMemoryStream.Create; try // BMColor with BitmapInfoHeader do begin Size := 0; biHeight := Abs (biHeight div 2); BMMaskSize:= BytesPerScanLine (biWidth, 1, 32)*biHeight; Dec (biSizeImage, BMMaskSize); if biBitCount <= 8 then begin if biClrUsed = 0 then Inc (Size, (1 shl biBitCount)*SizeOf (TRGBQuad)) else Inc (Size, biClrUsed*SizeOf (TRGBQuad)); end else if (biCompression and BI_BITFIELDS) <> 0 then Inc (Size, 12); end; with BitmapFileHeader do begin bfType := $4D42; bfOffBits := SizeOf (TBitmapFileHeader) + SizeOf (TBitmapInfoHeader) + Size; bfReserved1:= 0; bfReserved2:= 0; bfSize := bfOffBits + BitmapInfoHeader.biSizeImage; end; Local.Write (BitmapFileHeader, SizeOf (TBitmapFileHeader)); Local.Write (BitmapInfoHeader, SizeOf (TBitmapInfoHeader)); Local.CopyFrom (Stream, Size + BitmapInfoHeader.biSizeImage); Local.Seek (0, soFromBeginning); inherited LoadFromStream (Local); // BMMask Local.Clear; with BitmapFileHeader do begin bfType := $4D42; bfOffBits := SizeOf (TBitmapFileHeader) + SizeOf (TBitmapInfoHeader) + 8; bfReserved1:= 0; bfReserved2:= 0; bfSize := bfOffBits + BMMaskSize; end; with BitmapInfoHeader do begin biPlanes := 1; biBitCount := 1; biCompression := BI_RGB; biSizeImage := BMMaskSize; biClrUsed := 2; biClrImportant:= 2; end; Local.Write (BitmapFileHeader, SizeOf (TBitmapFileHeader)); Local.Write (BitmapInfoHeader, SizeOf (TBitmapInfoHeader)); Local.Write (cBlack, 4); Local.Write (Color, 4); Local.CopyFrom (Stream, BMMaskSize); Local.Seek (0, soFromBeginning); Mask.LoadFromStream (Local); finally Local.Free; end; end; function TCursorIcon.IsValid (const FileName: String): Boolean; var Local : TStream; Header: TIconDirectory; begin Result:= False; if FileExists (FileName) then begin Local:= TFileStream.Create (FileName, fmOpenRead); try Result:= (Local.Read (Header, SizeOf (TIconDirectory)) = SizeOf (TIconDirectory)) and (Header.cdReserved = 0) and (Header.cdType in [1, 2]); Cursor:= Header.cdType = 2; finally Local.Free; end; end; end; procedure TCursorIcon.LoadFromStream (Stream: TStream); begin if Assigned (Stream) then ReadStream (Stream); end; end.
unit TriangleFiller; interface uses BasicMathsTypes, BasicDataTypes, Vector3fSet, BasicFunctions, math3D, Windows, Graphics, Abstract2DImageData; type CTriangleFiller = class private // Pixel Utils function IsP1HigherThanP2(_P1, _P2 : TVector2f): boolean; procedure AssignPointColour(var _DestPoint: TVector2f; var _DestColour: TVector4f; const _SourcePoint: TVector2f; const _SourceColour: TVector4f); overload; procedure AssignPointColour(var _DestPoint: TVector2f; var _DestColour: TVector3f; const _SourcePoint: TVector2f; const _SourceColour: TVector3f); overload; function GetAverageColour(const _C1, _C2: TVector3f):TVector3f; overload; function GetAverageColour(const _C1, _C2: TVector4f):TVector4f; overload; function GetAverageColour(const _C1, _C2,_C3: TVector3f):TVector3f; overload; function GetAverageColour(const _C1, _C2,_C3: TVector4f):TVector4f; overload; procedure GetRGBFactorsFromPixel(const _r, _g, _b: real; var _i, _rX, _gX, _bX: real); function GetColourSimilarityFactor(_r1, _g1, _b1, _r2, _g2, _b2: real; var _cos: real): real; function AreColoursSimilar(_r1, _g1, _b1, _r2, _g2, _b2: real): real; // Paint single pixel procedure PaintPixel(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size, _PosX, _PosY : integer; _Colour: TVector4f; _Weight : single); overload; procedure PaintPixel(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size, _PosX, _PosY : integer; _Colour: TVector3f; _Weight : single); overload; procedure PaintPixel(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Size, _PosX, _PosY : integer; _Colour: TVector3f; _Weight : single); overload; procedure PaintPixel(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Size, _PosX, _PosY : integer; _Colour: TVector4f; _Weight : single); overload; // Paint bicubic pixel procedure PaintPixelAtFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Point: TVector2f; _Colour: TVector4f); overload; procedure PaintPixelAtFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Point: TVector2f; _Colour: TVector3f); overload; procedure PaintPixelAtFrameBuffer(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Point: TVector2f; _Colour: TVector3f); overload; procedure PaintPixelAtFrameBuffer(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Point: TVector2f; _Colour: TVector4f); overload; procedure PaintBumpValueAtFrameBuffer(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _X, _Y : single; _Size: integer); overload; // Paint line procedure PaintGouraudHorizontalLine(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector3f); overload; procedure PaintGouraudHorizontalLine(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector4f); overload; procedure PaintGouraudHorizontalLine(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector3f); overload; procedure PaintGouraudHorizontalLine(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector4f); overload; procedure PaintHorizontalLineNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector4f); overload; procedure PaintHorizontalLineNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector4f); overload; procedure PaintBumpHorizontalLine(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _X1, _X2, _Y : single; _Size: integer); overload; procedure PaintBumpHorizontalLine(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _X1, _X2, _Y : single; _Size: integer); overload; // Triangle Utils procedure GetGradient(const _P2, _P1: TVector2f; const _C2, _C1: TVector3f; var _dx, _dr, _dg, _db: single); overload; procedure GetGradient(const _P2, _P1: TVector2f; const _C2, _C1: TVector4f; var _dx, _dr, _dg, _db, _da: single); overload; procedure GetGradient(const _P2, _P1: TVector2f; var _dx: single); overload; procedure GetGradientNCM(const _P2, _P1: TVector2f; const _C2, _C1: TVector4f; var _dy, _dx, _dr, _dg, _db, _da: single; var _iStart, _iEnd: real); overload; procedure PaintTrianglePiece(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector3f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe: real); overload; procedure PaintTrianglePiece(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); overload; procedure PaintTrianglePiece(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector3f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe: real); overload; procedure PaintTrianglePiece(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); overload; procedure PaintTrianglePiece(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; var _S, _E: TVector2f; const _FinalPos: TVector2f; const _dxs, _dxe: single; _Size: integer); overload; procedure PaintTrianglePiece(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; var _S, _E: TVector2f; const _FinalPos: TVector2f; const _dxs, _dxe: single; _Size: integer); overload; procedure PaintTrianglePieceNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dys, _dye, _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae,_iStart1, _iEnd1,_iStart2,_iEnd2: real); overload; procedure PaintTrianglePieceNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dys, _dye, _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae,_iStart1, _iEnd1,_iStart2,_iEnd2: real); overload; procedure PaintTrianglePieceBorder(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); overload; procedure PaintTrianglePieceBorder(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); overload; // Paint triangle procedure PaintGouraudTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintGouraudTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector3f); overload; procedure PaintGouraudTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector3f); overload; procedure PaintGouraudTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintNCMTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintNCMTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintBumpMapTriangle(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _P1, _P2, _P3 : TVector2f); overload; procedure PaintBumpMapTriangle(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); overload; procedure PaintGouraudTriangleBorder(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintGouraudTriangleBorder(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; public // For bump mapping only procedure PaintBumpValueAtFrameBuffer(var _Bitmap: TBitmap; const _HeightMap: TByteMap; _X, _Y : single; _Size: integer); overload; procedure PaintBumpValueAtFrameBuffer(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _X, _Y : single; _Size: integer); overload; // Painting procedures procedure PaintTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _N1, _N2, _N3: TVector3f); overload; procedure PaintTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _N1, _N2, _N3: TVector3f); overload; procedure PaintTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintTriangleNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintTriangleNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); overload; procedure PaintFlatTriangleFromHeightMap(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _P1, _P2, _P3 : TVector2f); overload; procedure PaintFlatTriangleFromHeightMap(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); overload; procedure PaintDebugTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f); overload; procedure PaintDebugTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); overload; end; implementation uses Math, SysUtils; // Pixel Utils function CTriangleFiller.IsP1HigherThanP2(_P1, _P2 : TVector2f): boolean; begin if _P1.V > _P2.V then begin Result := true; end else if _P1.V = _P2.V then begin if _P1.U > _P2.U then begin Result := true; end else begin Result := false; end; end else begin Result := false; end; end; procedure CTriangleFiller.AssignPointColour(var _DestPoint: TVector2f; var _DestColour: TVector4f; const _SourcePoint: TVector2f; const _SourceColour: TVector4f); begin _DestPoint := SetVector(_SourcePoint); _DestColour := SetVector(_SourceColour); end; procedure CTriangleFiller.AssignPointColour(var _DestPoint: TVector2f; var _DestColour: TVector3f; const _SourcePoint: TVector2f; const _SourceColour: TVector3f); begin _DestPoint := SetVector(_SourcePoint); _DestColour := SetVector(_SourceColour); end; function CTriangleFiller.GetAverageColour(const _C1, _C2: TVector3f):TVector3f; begin Result.X := (_C1.X + _C2.X) / 2; Result.Y := (_C1.Y + _C2.Y) / 2; Result.Z := (_C1.Z + _C2.Z) / 2; end; function CTriangleFiller.GetAverageColour(const _C1, _C2: TVector4f):TVector4f; begin Result.X := (_C1.X + _C2.X) / 2; Result.Y := (_C1.Y + _C2.Y) / 2; Result.Z := (_C1.Z + _C2.Z) / 2; Result.W := (_C1.W + _C2.W) / 2; end; function CTriangleFiller.GetAverageColour(const _C1, _C2,_C3: TVector3f):TVector3f; begin Result.X := (_C1.X + _C2.X + _C3.X) / 3; Result.Y := (_C1.Y + _C2.Y + _C3.Y) / 3; Result.Z := (_C1.Z + _C2.Z + _C3.Z) / 3; end; function CTriangleFiller.GetAverageColour(const _C1, _C2,_C3: TVector4f):TVector4f; begin Result.X := (_C1.X + _C2.X + _C3.X) / 3; Result.Y := (_C1.Y + _C2.Y + _C3.Y) / 3; Result.Z := (_C1.Z + _C2.Z + _C3.Z) / 3; Result.W := (_C1.W + _C2.W + _C3.W) / 3; end; procedure CTriangleFiller.GetRGBFactorsFromPixel(const _r, _g, _b: real; var _i, _rX, _gX, _bX: real); var temp: real; begin _i := Max(_r, Max(_g, _b)); // Get the chrome. if _r + _g + _b > 0 then begin temp := sqrt((_r * _r) + (_g * _g) + (_b * _b)); _rX := _r / temp; _gX := _g / temp; _bX := _b / temp; end else begin _rX := sqrt(3)/3; _gX := _rX; _bX := _rX; end; end; function CTriangleFiller.GetColourSimilarityFactor(_r1, _g1, _b1, _r2, _g2, _b2: real; var _cos: real): real; var dot: real; begin // Get the inner product between the two normalized colours and calculate score. _cos := (_r1 * _r2) + (_g1 * _g2) + (_b1 * _b2); if _cos >= 1 then begin Result := 0; end else begin Result := sqrt(1 - (_cos * _cos)); // Result is the sin: sin = sqrt(1 - cosē) in the 1st quadrant end; end; function CTriangleFiller.AreColoursSimilar(_r1, _g1, _b1, _r2, _g2, _b2: real): real; const C_EPSILON = 6/255; var i1, r1, g1, b1, i2, r2, g2, b2, cos, sin: real; begin GetRGBFactorsFromPixel(_r1, _g1, _b1, i1, r1, g1, b1); GetRGBFactorsFromPixel(_r2, _g2, _b2, i2, r2, g2, b2); sin := GetColourSimilarityFactor(r1, g1, b1, r2, g2, b2, cos); //if ((i1 * sin) <= C_EPSILON) and ((i2 * sin) <= C_EPSILON) then if (sin <= (sqrt(12)/(255 * i1 * i1))) and (sin <= (sqrt(12)/(255 * i2 * i2))) then Result := cos else Result := 0; end; // Paint Pixel procedure CTriangleFiller.PaintPixel(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size, _PosX, _PosY : integer; _Colour: TVector3f; _Weight : single); begin if (_PosY < _Size) and (_PosX < _Size) and (_PosX >= 0) and (_PosY >= 0) then begin _Buffer[_PosX,_PosY].X := _Buffer[_PosX,_PosY].X + (_Colour.X * _Weight); _Buffer[_PosX,_PosY].Y := _Buffer[_PosX,_PosY].Y + (_Colour.Y * _Weight); _Buffer[_PosX,_PosY].Z := _Buffer[_PosX,_PosY].Z + (_Colour.Z * _Weight); _WeightBuffer[_PosX,_PosY] := _WeightBuffer[_PosX,_PosY] + _Weight; end; end; procedure CTriangleFiller.PaintPixel(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Size, _PosX, _PosY : integer; _Colour: TVector4f; _Weight : single); begin if (_PosY < _Size) and (_PosX < _Size) and (_PosX >= 0) and (_PosY >= 0) then begin _Buffer[_PosX,_PosY].X := _Buffer[_PosX,_PosY].X + (_Colour.X * _Weight); _Buffer[_PosX,_PosY].Y := _Buffer[_PosX,_PosY].Y + (_Colour.Y * _Weight); _Buffer[_PosX,_PosY].Z := _Buffer[_PosX,_PosY].Z + (_Colour.Z * _Weight); _Buffer[_PosX,_PosY].W := _Buffer[_PosX,_PosY].W + (_Colour.W * _Weight); _WeightBuffer[_PosX,_PosY] := _WeightBuffer[_PosX,_PosY] + _Weight; end; end; procedure CTriangleFiller.PaintPixel(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Size, _PosX, _PosY : integer; _Colour: TVector3f; _Weight : single); begin if (_PosY < _Size) and (_PosX < _Size) and (_PosX >= 0) and (_PosY >= 0) then begin _Buffer.Red[_PosX,_PosY] := _Buffer.Red[_PosX,_PosY] + (_Colour.X * _Weight); _Buffer.Green[_PosX,_PosY] := _Buffer.Green[_PosX,_PosY] + (_Colour.Y * _Weight); _Buffer.Blue[_PosX,_PosY] := _Buffer.Blue[_PosX,_PosY] + (_Colour.Z * _Weight); _WeightBuffer.Red[_PosX,_PosY] := _WeightBuffer.Red[_PosX,_PosY] + _Weight; end; end; procedure CTriangleFiller.PaintPixel(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Size, _PosX, _PosY : integer; _Colour: TVector4f; _Weight : single); begin if (_PosY < _Size) and (_PosX < _Size) and (_PosX >= 0) and (_PosY >= 0) then begin _Buffer.Red[_PosX,_PosY] := _Buffer.Red[_PosX,_PosY] + (_Colour.X * _Weight); _Buffer.Green[_PosX,_PosY] := _Buffer.Green[_PosX,_PosY] + (_Colour.Y * _Weight); _Buffer.Blue[_PosX,_PosY] := _Buffer.Blue[_PosX,_PosY] + (_Colour.Z * _Weight); _Buffer.Alpha[_PosX,_PosY] := _Buffer.Alpha[_PosX,_PosY] + (_Colour.W * _Weight); _WeightBuffer.Red[_PosX,_PosY] := _WeightBuffer.Red[_PosX,_PosY] + _Weight; end; end; // Painting procedures procedure CTriangleFiller.PaintPixelAtFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Point: TVector2f; _Colour: TVector4f); var Size : integer; PosX, PosY : integer; Point,FractionLow,FractionHigh : TVector2f; begin Size := High(_Buffer)+1; Point := SetVector(_Point); PosX := Trunc(Point.U); PosY := Trunc(Point.V); FractionHigh := SetVector(Point.U - PosX, Point.V - PosY); FractionLow := SetVector(1 - FractionHigh.U,1 - FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY, _Colour, FractionLow.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY, _Colour, FractionHigh.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY+1, _Colour, FractionLow.U * FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY+1, _Colour, FractionHigh.U * FractionHigh.V); end; procedure CTriangleFiller.PaintPixelAtFrameBuffer(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _Point: TVector2f; _Colour: TVector3f); var Size : integer; PosX, PosY : integer; Point,FractionLow,FractionHigh : TVector2f; begin Size := High(_Buffer)+1; Point := SetVector(_Point); PosX := Trunc(Point.U); PosY := Trunc(Point.V); FractionHigh := SetVector(Point.U - PosX, Point.V - PosY); FractionLow := SetVector(1 - FractionHigh.U,1 - FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY, _Colour, FractionLow.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY, _Colour, FractionHigh.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY+1, _Colour, FractionLow.U * FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY+1, _Colour, FractionHigh.U * FractionHigh.V); end; procedure CTriangleFiller.PaintPixelAtFrameBuffer(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Point: TVector2f; _Colour: TVector3f); var Size : integer; PosX, PosY : integer; Point,FractionLow,FractionHigh : TVector2f; begin Size := _Buffer.MaxX + 1; Point := SetVector(_Point); PosX := Trunc(Point.U); PosY := Trunc(Point.V); FractionHigh := SetVector(Point.U - PosX, Point.V - PosY); FractionLow := SetVector(1 - FractionHigh.U,1 - FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY, _Colour, FractionLow.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY, _Colour, FractionHigh.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY+1, _Colour, FractionLow.U * FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY+1, _Colour, FractionHigh.U * FractionHigh.V); end; procedure CTriangleFiller.PaintPixelAtFrameBuffer(var _Buffer,_WeightBuffer: TAbstract2DImageData; _Point: TVector2f; _Colour: TVector4f); var Size : integer; PosX, PosY : integer; Point,FractionLow,FractionHigh : TVector2f; begin Size := _Buffer.MaxX + 1; Point := SetVector(_Point); PosX := Trunc(Point.U); PosY := Trunc(Point.V); FractionHigh := SetVector(Point.U - PosX, Point.V - PosY); FractionLow := SetVector(1 - FractionHigh.U,1 - FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY, _Colour, FractionLow.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY, _Colour, FractionHigh.U * FractionLow.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX, PosY+1, _Colour, FractionLow.U * FractionHigh.V); PaintPixel(_Buffer, _WeightBuffer, Size, PosX+1, PosY+1, _Colour, FractionHigh.U * FractionHigh.V); end; procedure CTriangleFiller.PaintBumpValueAtFrameBuffer(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _X, _Y : single; _Size: integer); const FaceSequence : array [0..7,0..3] of integer = ((-1,-1,0,-1),(0,-1,1,-1),(1,-1,1,0),(1,0,1,1),(1,1,0,1),(0,1,-1,1),(-1,1,-1,0),(-1,0,-1,-1)); var DifferentNormalsList: CVector3fSet; i,x,y,P1x,P1y,P2x,P2y : integer; CurrentNormal : PVector3f; V1, V2, Normal: TVector3f; begin x := Round(_X); y := Round(_Y); if (X < 0) or (Y < 0) or (X >= _Size) or (Y >= _Size) then exit; DifferentNormalsList := CVector3fSet.Create; Normal := SetVector(0,0,0); for i := 0 to 7 do begin P1x := X + FaceSequence[i,0]; P1y := Y + FaceSequence[i,1]; P2x := X + FaceSequence[i,2]; P2y := Y + FaceSequence[i,3]; if (P1x >= 0) and (P1y >= 0) and (P1x < _Size) and (P1y < _Size) and (P2x >= 0) and (P2y >= 0) and (P2x < _Size) and (P2y < _Size) then begin CurrentNormal := new(PVector3f); V1 := SetVector(FaceSequence[i,0], FaceSequence[i,1], _HeightMap[X,Y] - _HeightMap[P1x,P1y]); V2 := SetVector(FaceSequence[i,2], FaceSequence[i,3], _HeightMap[X,Y] - _HeightMap[P2x,P2y]); Normalize(V1); Normalize(V2); CurrentNormal^ := CrossProduct(V1,V2); Normalize(CurrentNormal^); if DifferentNormalsList.Add(CurrentNormal) then begin Normal := AddVector(Normal,CurrentNormal^); end; end; end; if not DifferentNormalsList.isEmpty then begin Normalize(Normal); end; _Buffer[X,Y].X := Normal.X; _Buffer[X,Y].Y := Normal.Y; _Buffer[X,Y].Z := Normal.Z; DifferentNormalsList.Free; end; procedure CTriangleFiller.PaintBumpValueAtFrameBuffer(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _X, _Y : single; _Size: integer); const FaceSequence : array [0..7,0..3] of integer = ((-1,-1,0,-1),(0,-1,1,-1),(1,-1,1,0),(1,0,1,1),(1,1,0,1),(0,1,-1,1),(-1,1,-1,0),(-1,0,-1,-1)); var DifferentNormalsList: CVector3fSet; i,x,y,P1x,P1y,P2x,P2y : integer; CurrentNormal : PVector3f; V1, V2, Normal: TVector3f; begin x := Round(_X); y := Round(_Y); if (X < 0) or (Y < 0) or (X >= _Size) or (Y >= _Size) then exit; DifferentNormalsList := CVector3fSet.Create; Normal := SetVector(0,0,0); for i := 0 to 7 do begin P1x := X + FaceSequence[i,0]; P1y := Y + FaceSequence[i,1]; P2x := X + FaceSequence[i,2]; P2y := Y + FaceSequence[i,3]; if (P1x >= 0) and (P1y >= 0) and (P1x < _Size) and (P1y < _Size) and (P2x >= 0) and (P2y >= 0) and (P2x < _Size) and (P2y < _Size) then begin CurrentNormal := new(PVector3f); V1 := SetVector(FaceSequence[i,0], FaceSequence[i,1], _HeightMap.Red[X,Y] - _HeightMap.Red[P1x,P1y]); V2 := SetVector(FaceSequence[i,2], FaceSequence[i,3], _HeightMap.Red[X,Y] - _HeightMap.Red[P2x,P2y]); Normalize(V1); Normalize(V2); CurrentNormal^ := CrossProduct(V1,V2); Normalize(CurrentNormal^); if DifferentNormalsList.Add(CurrentNormal) then begin Normal := AddVector(Normal,CurrentNormal^); end; end; end; if not DifferentNormalsList.isEmpty then begin Normalize(Normal); end; _Buffer.Red[X,Y] := (1 + Normal.X) * 127.5; _Buffer.Green[X,Y] := (1 + Normal.Y) * 127.5; _Buffer.Blue[X,Y] := (1 + Normal.Z) * 127.5; DifferentNormalsList.Free; end; procedure CTriangleFiller.PaintBumpValueAtFrameBuffer(var _Bitmap: TBitmap; const _HeightMap: TByteMap; _X, _Y : single; _Size: integer); const FaceSequence : array [0..7,0..3] of integer = ((-1,-1,0,-1),(0,-1,1,-1),(1,-1,1,0),(1,0,1,1),(1,1,0,1),(0,1,-1,1),(-1,1,-1,0),(-1,0,-1,-1)); var DifferentNormalsList: CVector3fSet; i,x,y,P1x,P1y,P2x,P2y : integer; CurrentNormal : PVector3f; V1, V2, Normal: TVector3f; begin x := Round(_X); y := Round(_Y); if (X < 0) or (Y < 0) or (X >= _Size) or (Y >= _Size) then exit; DifferentNormalsList := CVector3fSet.Create; Normal := SetVector(0,0,0); for i := 0 to 7 do begin P1x := X + FaceSequence[i,0]; P1y := Y + FaceSequence[i,1]; P2x := X + FaceSequence[i,2]; P2y := Y + FaceSequence[i,3]; if (P1x >= 0) and (P1y >= 0) and (P1x < _Size) and (P1y < _Size) and (P2x >= 0) and (P2y >= 0) and (P2x < _Size) and (P2y < _Size) then begin CurrentNormal := new(PVector3f); V1 := SetVector(FaceSequence[i,0], FaceSequence[i,1], _HeightMap[X,Y] - _HeightMap[P1x,P1y]); V2 := SetVector(FaceSequence[i,2], FaceSequence[i,3], _HeightMap[X,Y] - _HeightMap[P2x,P2y]); Normalize(V1); Normalize(V2); CurrentNormal^ := CrossProduct(V1,V2); Normalize(CurrentNormal^); if DifferentNormalsList.Add(CurrentNormal) then begin Normal := AddVector(Normal,CurrentNormal^); end; end; end; if not DifferentNormalsList.isEmpty then begin Normalize(Normal); end; if (abs(Normal.X) + abs(Normal.Y) + abs(Normal.Z)) = 0 then Normal.Z := 1; _Bitmap.Canvas.Pixels[X,Y] := RGB(Round((1 + Normal.X) * 127.5), Round((1 + Normal.Y) * 127.5), Round((1 + Normal.Z) * 127.5)); DifferentNormalsList.Free; end; // Paint line procedure CTriangleFiller.PaintGouraudHorizontalLine(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector3f); var dx, dr, dg, db : real; x2, x1 : single; C1, C2, PC : TVector3f; PP : TVector2f; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; // get the gradients for each colour channel if (x2 - x1) > 1 then begin dx := (x2 - x1) / trunc(x2 - x1); dr := (C2.X - C1.X) / trunc(x2 - x1); dg := (C2.Y - C1.Y) / trunc(x2 - x1); db := (C2.Z - C1.Z) / trunc(x2 - x1); PC := SetVector(C1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PC.X := PC.X + dr; PC.Y := PC.Y + dg; PC.Z := PC.Z + db; PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintGouraudHorizontalLine(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector4f); var dx, dr, dg, db, da : real; x2, x1 : single; C1, C2, PC : TVector4f; PP : TVector2f; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; // get the gradients for each colour channel if (x2 - x1) > 1 then begin PC := SetVector(C1); dx := (x2 - x1) / trunc(x2 - x1); dr := (C2.X - C1.X) / trunc(x2 - x1); dg := (C2.Y - C1.Y) / trunc(x2 - x1); db := (C2.Z - C1.Z) / trunc(x2 - x1); da := (C2.W - C1.W) / trunc(x2 - x1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PC.X := PC.X + dr; PC.Y := PC.Y + dg; PC.Z := PC.Z + db; PC.W := PC.W + da; PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintGouraudHorizontalLine(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector3f); var dx, dr, dg, db : real; x2, x1 : single; C1, C2, PC : TVector3f; PP : TVector2f; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; // get the gradients for each colour channel if (x2 - x1) > 1 then begin dx := (x2 - x1) / trunc(x2 - x1); dr := (C2.X - C1.X) / trunc(x2 - x1); dg := (C2.Y - C1.Y) / trunc(x2 - x1); db := (C2.Z - C1.Z) / trunc(x2 - x1); PC := SetVector(C1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PC.X := PC.X + dr; PC.Y := PC.Y + dg; PC.Z := PC.Z + db; PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintGouraudHorizontalLine(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector4f); var dx, dr, dg, db, da : real; x2, x1 : single; C1, C2, PC : TVector4f; PP : TVector2f; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; // get the gradients for each colour channel if (x2 - x1) > 1 then begin dx := (x2 - x1) / trunc(x2 - x1); dr := (C2.X - C1.X) / trunc(x2 - x1); dg := (C2.Y - C1.Y) / trunc(x2 - x1); db := (C2.Z - C1.Z) / trunc(x2 - x1); da := (C2.W - C1.W) / trunc(x2 - x1); PC := SetVector(C1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PC.X := PC.X + dr; PC.Y := PC.Y + dg; PC.Z := PC.Z + db; PC.W := PC.W + da; PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintHorizontalLineNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _X1, _X2, _Y : single; _C1, _C2: TVector4f); const C_EPSILON = 0.000001; var dx, dr, dg, db, da : real; x2, x1 : single; C1, C2, PC, PN : TVector4f; PP : TVector2f; iStart, iEnd, iSize, iStep, iCurrent, iPrevious, iNext: real; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; iStart := x1 + (((1 - AreColoursSimilar(C1.X, C1.Y, C1.Z, C2.X, C2.Y, C2.Z)) / 2) * (x2 - x1)); iEnd := x2 - (iStart - x1); iSize := iEnd - iStart; // get the gradients for each colour channel if (x2 - x1) > 1 then begin dx := (x2 - x1) / trunc(x2 - x1); if iSize > C_EPSILON then begin dr := (C2.X - C1.X) / iSize; dg := (C2.Y - C1.Y) / iSize; db := (C2.Z - C1.Z) / iSize; da := (C2.W - C1.W) / iSize; end else begin if iSize < C_EPSILON then iSize := C_EPSILON; dr := (C2.X - C1.X); dg := (C2.Y - C1.Y); db := (C2.Z - C1.Z); da := (C2.W - C1.W); end; PC := SetVector(C1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); iCurrent := 0; PN := SetVector(PC); while PP.U < x2 do begin if (PP.U - iStart + dx) > 0 then begin if iCurrent < iSize then begin iStep := (PP.U - iStart + dx) - iCurrent; if iStart > PP.U then begin iPrevious := iStart - PP.U; end else begin iPrevious := 0; end; if ((iStep + iCurrent) > iSize) then begin if iSize > C_EPSILON then begin iStep := iSize - iCurrent; iNext := (PP.U + dx) - iEnd; end else begin iStep := 0; iNext := dx; end; end else begin iNext := 0; end; if iStep > 0 then begin PC := SetVector(PN); PN.X := PN.X + (iStep * dr); PN.Y := PN.Y + (iStep * dg); PN.Z := PN.Z + (iStep * db); PN.W := PN.W + (iStep * da); PC.X := ((PC.X * iPrevious) + (PC.X * iStep) + ((PN.X - PC.X) * iStep * 0.5) + (PN.X * iNext)) / dx; PC.Y := ((PC.Y * iPrevious) + (PC.Y * iStep) + ((PN.Y - PC.Y) * iStep * 0.5) + (PN.Y * iNext)) / dx; PC.Z := ((PC.Z * iPrevious) + (PC.Z * iStep) + ((PN.Z - PC.Z) * iStep * 0.5) + (PN.Z * iNext)) / dx; PC.W := ((PC.W * iPrevious) + (PC.W * iStep) + ((PN.W - PC.W) * iStep * 0.5) + (PN.W * iNext)) / dx; end else begin PC.X := PN.X + dr; PC.Y := PN.Y + dg; PC.Z := PN.Z + db; PC.W := PN.W + da; PN.X := PN.X + dr; PN.Y := PN.Y + dg; PN.Z := PN.Z + db; PN.W := PN.W + da; iStep := 1; end; iCurrent := iCurrent + iStep; end; end; PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintHorizontalLineNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; _X1, _X2, _Y : single; _C1, _C2: TVector4f); const C_EPSILON = 0.000001; var dx, dr, dg, db, da : real; x2, x1 : single; C1, C2, PC, PN : TVector4f; PP : TVector2f; iStart, iEnd, iSize, iStep, iCurrent, iPrevious, iNext: real; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; C1 := SetVector(_C2); C2 := SetVector(_C1); end else if _X1 = _X2 then begin PP := SetVector(_x1,_Y); PC := GetAverageColour(_C1,_C2); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); exit; end else begin x1 := _X1; x2 := _X2; C1 := SetVector(_C1); C2 := SetVector(_C2); end; iStart := x1 + (((1 - AreColoursSimilar(C1.X, C1.Y, C1.Z, C2.X, C2.Y, C2.Z)) / 2) * (x2 - x1)); iEnd := x2 - (iStart - x1); iSize := iEnd - iStart; // get the gradients for each colour channel if (x2 - x1) > 1 then begin dx := (x2 - x1) / trunc(x2 - x1); if iSize > C_EPSILON then begin dr := (C2.X - C1.X) / iSize; dg := (C2.Y - C1.Y) / iSize; db := (C2.Z - C1.Z) / iSize; da := (C2.W - C1.W) / iSize; end else begin if iSize < C_EPSILON then iSize := C_EPSILON; dr := (C2.X - C1.X); dg := (C2.Y - C1.Y); db := (C2.Z - C1.Z); da := (C2.W - C1.W); end; PC := SetVector(C1); end else begin dx := (x2 - x1); PC := GetAverageColour(_C1,_C2); end; // Now, let's start the painting procedure: PP := SetVector(x1,_Y); PN := SetVector(PC); iCurrent := 0; while PP.U < x2 do begin if (PP.U - iStart + dx) > 0 then begin if iCurrent < iSize then begin iStep := (PP.U - iStart + dx) - iCurrent; if iStart > PP.U then begin iPrevious := iStart - PP.U; end else begin iPrevious := 0; end; if ((iStep + iCurrent) > iSize) then begin if iSize > C_EPSILON then begin iStep := iSize - iCurrent; iNext := (PP.U + dx) - iEnd; end else begin iStep := 0; iNext := dx; end; end else begin iNext := 0; end; if iStep > 0 then begin PC := SetVector(PN); PN.X := PN.X + (iStep * dr); PN.Y := PN.Y + (iStep * dg); PN.Z := PN.Z + (iStep * db); PN.W := PN.W + (iStep * da); PC.X := ((PC.X * iPrevious) + (PC.X * iStep) + ((PN.X - PC.X) * iStep * 0.5) + (PN.X * iNext)) / dx; PC.Y := ((PC.Y * iPrevious) + (PC.Y * iStep) + ((PN.Y - PC.Y) * iStep * 0.5) + (PN.Y * iNext)) / dx; PC.Z := ((PC.Z * iPrevious) + (PC.Z * iStep) + ((PN.Z - PC.Z) * iStep * 0.5) + (PN.Z * iNext)) / dx; PC.W := ((PC.W * iPrevious) + (PC.W * iStep) + ((PN.W - PC.W) * iStep * 0.5) + (PN.W * iNext)) / dx; end else begin PC.X := PN.X + dr; PC.Y := PN.Y + dg; PC.Z := PN.Z + db; PC.W := PN.W + da; PN.X := PN.X + dr; PN.Y := PN.Y + dg; PN.Z := PN.Z + db; PN.W := PN.W + da; iStep := 1; end; iCurrent := iCurrent + iStep; end; end; PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PP, PC); PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintBumpHorizontalLine(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _X1, _X2, _Y : single; _Size: integer); var x2, x1 : single; PP : TVector2f; dx: real; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; end else if _X1 = _X2 then begin PaintBumpValueAtFrameBuffer(_Buffer, _HeightMap, _x1, _Y,_Size); exit; end else begin x1 := _X1; x2 := _X2; end; if (x2 - x1) > 1 then dx := (x2 - x1) / trunc(x2 - x1) else dx := (x2 - x1); // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintBumpValueAtFrameBuffer(_Buffer, _HeightMap, PP.U, PP.V,_Size); PP.U := PP.U + dx; end; end; procedure CTriangleFiller.PaintBumpHorizontalLine(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _X1, _X2, _Y : single; _Size: integer); var x2, x1 : single; PP : TVector2f; dx: real; begin // First we make sure x1 will be smaller than x2. if (_X1 > _X2) then begin x1 := _X2; x2 := _X1; end else if _X1 = _X2 then begin PaintBumpValueAtFrameBuffer(_Buffer, _HeightMap, _x1, _Y,_Size); exit; end else begin x1 := _X1; x2 := _X2; end; if (x2 - x1) > 1 then dx := (x2 - x1) / trunc(x2 - x1) else dx := (x2 - x1); // Now, let's start the painting procedure: PP := SetVector(x1,_Y); while PP.U < x2 do begin PaintBumpValueAtFrameBuffer(_Buffer, _HeightMap, PP.U, PP.V,_Size); PP.U := PP.U + dx; end; end; // Triangle Utils procedure CTriangleFiller.GetGradient(const _P2, _P1: TVector2f; const _C2, _C1: TVector3f; var _dx, _dr, _dg, _db: single); var VSize: real; begin VSize := trunc(abs(_P2.V - _P1.V)); if VSize > 1 then begin _dx := (_P2.U - _P1.U) / VSize; _dr := (_C2.X - _C1.X) / VSize; _dg := (_C2.Y - _C1.Y) / VSize; _db := (_C2.Z - _C1.Z) / VSize; end else begin _dx := (_P2.U - _P1.U); _dr := (_C2.X - _C1.X); _dg := (_C2.Y - _C1.Y); _db := (_C2.Z - _C1.Z); end; end; procedure CTriangleFiller.GetGradient(const _P2, _P1: TVector2f; const _C2, _C1: TVector4f; var _dx, _dr, _dg, _db, _da: single); var VSize: real; begin VSize := trunc(abs(_P2.V - _P1.V)); if VSize > 1 then begin _dx := (_P2.U - _P1.U) / VSize; _dr := (_C2.X - _C1.X) / VSize; _dg := (_C2.Y - _C1.Y) / VSize; _db := (_C2.Z - _C1.Z) / VSize; _da := (_C2.W - _C1.W) / VSize; end else begin _dx := (_P2.U - _P1.U); _dr := (_C2.X - _C1.X); _dg := (_C2.Y - _C1.Y); _db := (_C2.Z - _C1.Z); _da := (_C2.W - _C1.W); end; end; procedure CTriangleFiller.GetGradientNCM(const _P2, _P1: TVector2f; const _C2, _C1: TVector4f; var _dy, _dx, _dr, _dg, _db, _da: single; var _iStart, _iEnd: real); const C_EPSILON = 0.000001; var iStart, iEnd, iSize: real; begin _iStart := _P1.V + (((1 - AreColoursSimilar(_C1.X, _C1.Y, _C1.Z, _C2.X, _C2.Y, _C2.Z)) / 2) * (_P2.V - _P1.V)); _iEnd := _P2.V - (_iStart - _P1.V); iSize := _iEnd - _iStart; if abs(_P2.V - _P1.V) > 1 then begin _dy := (_P2.V - _P1.V) / trunc(abs(_P2.V - _P1.V)); _dx := (_P2.U - _P1.U) / abs(_P2.V - _P1.V); end else begin _dy := (_P2.V - _P1.V); _dx := (_P2.U - _P1.U); end; if iSize > C_EPSILON then begin _dr := (_C2.X - _C1.X) / iSize; _dg := (_C2.Y - _C1.Y) / iSize; _db := (_C2.Z - _C1.Z) / iSize; _da := (_C2.W - _C1.W) / iSize; end else begin _dr := (_C2.X - _C1.X); _dg := (_C2.Y - _C1.Y); _db := (_C2.Z - _C1.Z); _da := (_C2.W - _C1.W); end; end; procedure CTriangleFiller.GetGradient(const _P2, _P1: TVector2f; var _dx: single); begin _dx := trunc(abs(_P2.V - _P1.V)); if _dx > 1 then begin _dx := (_P2.U - _P1.U) / trunc(abs(_P2.V - _P1.V)); end else begin _dx := (_P2.U - _P1.U); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector3f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe: real); var dy: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dy := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dy); _EP := SetVector(_EP.U + _dxe, _EP.V + dy); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); var dy: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dy := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dy); _EP := SetVector(_EP.U + _dxe, _EP.V + dy); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs, _SC.W + _das); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe, _EC.W + _dae); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector3f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe: real); var dy: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dy := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dy); _EP := SetVector(_EP.U + _dxe, _EP.V + dy); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); var dy: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dy := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dy); _EP := SetVector(_EP.U + _dxe, _EP.V + dy); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs, _SC.W + _das); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe, _EC.W + _dae); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePieceNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dys, _dye, _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae, _iStart1, _iEnd1,_iStart2,_iEnd2: real); const C_EPSILON = 0.000001; var iSize1, iSize2, iCurrent1, iCurrent2, iStep1, iStep2, iPrevious1, iPrevious2, iNext1, iNext2: real; SN, EN: TVector4f; begin iSize1 := _iEnd1 - _iStart1; iSize2 := _iEnd2 - _iStart2; if iSize1 < C_EPSILON then iSize1 := C_EPSILON; if iSize2 < C_EPSILON then iSize2 := C_EPSILON; iCurrent1 := 0; iCurrent2 := 0; if (_FinalPos.V - _SP.V) > 1 then begin SN := SetVector(_SC); EN := SetVector(_EC); while (_SP.V < _FinalPos.V) do begin if (_SP.V - _iStart1 + _dys) > 0 then begin if iCurrent1 < iSize1 then begin iStep1 := (_SP.V - _iStart1 + _dys) - iCurrent1; if _iStart1 > _SP.V then begin iPrevious1 := _iStart1 - _SP.V; end else begin iPrevious1 := 0; end; if ((iStep1 + iCurrent1) > iSize1) then begin if iSize1 > C_EPSILON then begin iStep1 := iSize1 - iCurrent1; iNext1 := (_SP.V + _dys) - _iEnd1; end else begin iStep1 := 0; iNext1 := _dys; end; end else begin iNext1 := 0; end; if iStep1 > 0 then begin _SC := SetVector(SN); SN := SetVector(SN.X + (iStep1 * _drs), SN.Y + (iStep1 * _dgs), SN.Z + (iStep1 * _dbs), SN.W + (iStep1 * _das)); _SC := SetVector(((_SC.X * iPrevious1) + (_SC.X * iStep1) + ((SN.X - _SC.X) * iStep1 * 0.5) + (SN.X * iNext1)) / _dys, ((_SC.Y * iPrevious1) + (_SC.Y * iStep1) + ((SN.Y - _SC.Y) * iStep1 * 0.5) + (SN.Y * iNext1)) / _dys, ((_SC.Z * iPrevious1) + (_SC.Z * iStep1) + ((SN.Z - _SC.Z) * iStep1 * 0.5) + (SN.Z * iNext1)) / _dys, ((_SC.W * iPrevious1) + (_SC.W * iStep1) + ((SN.W - _SC.W) * iStep1 * 0.5) + (SN.W * iNext1)) / _dys); end else begin _SC := SetVector(SN.X + _drs, SN.Y + _dgs, SN.Z + _dbs, SN.W + _das); SN := SetVector(SN.X + _drs, SN.Y + _dgs, SN.Z + _dbs, SN.W + _das); end; iCurrent1 := iCurrent1 + iStep1; end; end; if (_EP.V - _iStart2 + _dye) > 0 then begin if iCurrent2 < iSize2 then begin iStep2 := (_EP.V - _iStart2 + _dye) - iCurrent2; if _iStart2 > _EP.V then begin iPrevious2 := _iStart2 - _EP.V; end else begin iPrevious2 := 0; end; if ((iStep2 + iCurrent2) > iSize2) then begin if iSize2 > C_EPSILON then begin iStep2 := iSize2 - iCurrent2; iNext2 := (_EP.V + _dye) - _iEnd2; end else begin iStep2 := 0; iNext2 := _dye; end; end else begin iNext2 := 0; end; if iStep2 > 0 then begin _EC := SetVector(EN); EN := SetVector(EN.X + (iStep2 * _dre), EN.Y + (iStep2 * _dge), EN.Z + (iStep2 * _dbe), EN.W + (iStep2 * _dae)); _EC := SetVector(((_EC.X * iPrevious2) + (_EC.X * iStep2) + ((EN.X - _EC.X) * iStep2 * 0.5) + (EN.X * iNext2)) / _dye, ((_EC.Y * iPrevious2) + (_EC.Y * iStep2) + ((EN.Y - _EC.Y) * iStep2 * 0.5) + (EN.Y * iNext2)) / _dye, ((_EC.Z * iPrevious2) + (_EC.Z * iStep2) + ((EN.Z - _EC.Z) * iStep2 * 0.5) + (EN.Z * iNext2)) / _dye, ((_EC.W * iPrevious2) + (_EC.W * iStep2) + ((EN.W - _EC.W) * iStep2 * 0.5) + (EN.W * iNext2)) / _dye); end else begin _EC := SetVector(EN.X + _dre, EN.Y + _dge, EN.Z + _dbe, EN.W + _dae); EN := SetVector(EN.X + _dre, EN.Y + _dge, EN.Z + _dbe, EN.W + _dae); end; iCurrent2 := iCurrent2 + iStep2; end; end; PaintHorizontalLineNCM(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + _dys); _EP := SetVector(_EP.U + _dxe, _EP.V + _dye); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintHorizontalLineNCM(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePieceNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dys, _dye, _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae,_iStart1, _iEnd1,_iStart2,_iEnd2: real); const C_EPSILON = 0.000001; var iSize1, iSize2, iCurrent1, iCurrent2, iStep1, iStep2, iPrevious1, iPrevious2, iNext1, iNext2: real; SN, EN: TVector4f; begin iSize1 := _iEnd1 - _iStart1; iSize2 := _iEnd2 - _iStart2; if iSize1 < 0.00001 then iSize1 := 0.00001; if iSize2 < 0.00001 then iSize2 := 0.00001; iCurrent1 := 0; iCurrent2 := 0; if (_FinalPos.V - _SP.V) > 1 then begin SN := SetVector(_SC); EN := SetVector(_EC); while (_SP.V < _FinalPos.V) do begin if (_SP.V - _iStart1 + _dys) > 0 then begin if iCurrent1 < iSize1 then begin iStep1 := (_SP.V - _iStart1 + _dys) - iCurrent1; if _iStart1 > _SP.V then begin iPrevious1 := _iStart1 - _SP.V; end else begin iPrevious1 := 0; end; if ((iStep1 + iCurrent1) > iSize1) then begin if iSize1 > C_EPSILON then begin iStep1 := iSize1 - iCurrent1; iNext1 := (_SP.V + _dys) - _iEnd1; end else begin iStep1 := 0; iNext1 := _dys; end; end else begin iNext1 := 0; end; if iStep1 > 0 then begin _SC := SetVector(SN); SN := SetVector(SN.X + (iStep1 * _drs), SN.Y + (iStep1 * _dgs), SN.Z + (iStep1 * _dbs), SN.W + (iStep1 * _das)); _SC := SetVector(((_SC.X * iPrevious1) + (_SC.X * iStep1) + ((SN.X - _SC.X) * iStep1 * 0.5) + (SN.X * iNext1)) / _dys, ((_SC.Y * iPrevious1) + (_SC.Y * iStep1) + ((SN.Y - _SC.Y) * iStep1 * 0.5) + (SN.Y * iNext1)) / _dys, ((_SC.Z * iPrevious1) + (_SC.Z * iStep1) + ((SN.Z - _SC.Z) * iStep1 * 0.5) + (SN.Z * iNext1)) / _dys, ((_SC.W * iPrevious1) + (_SC.W * iStep1) + ((SN.W - _SC.W) * iStep1 * 0.5) + (SN.W * iNext1)) / _dys); end else begin _SC := SetVector(SN.X + _drs, SN.Y + _dgs, SN.Z + _dbs, SN.W + _das); SN := SetVector(SN.X + _drs, SN.Y + _dgs, SN.Z + _dbs, SN.W + _das); end; iCurrent1 := iCurrent1 + iStep1; end; end; if (_EP.V - _iStart2 + _dye) > 0 then begin if iCurrent2 < iSize2 then begin iStep2 := (_EP.V - _iStart2 + _dye) - iCurrent2; if _iStart2 > _EP.V then begin iPrevious2 := _iStart2 - _EP.V; end else begin iPrevious2 := 0; end; if ((iStep2 + iCurrent2) > iSize2) then begin if iSize2 > C_EPSILON then begin iStep2 := iSize2 - iCurrent2; iNext2 := (_EP.V + _dye) - _iEnd2; end else begin iStep2 := 0; iNext2 := _dye; end; end else begin iNext2 := 0; end; if iStep2 > 0 then begin _EC := SetVector(EN); EN := SetVector(EN.X + (iStep2 * _dre), EN.Y + (iStep2 * _dge), EN.Z + (iStep2 * _dbe), EN.W + (iStep2 * _dae)); _EC := SetVector(((_EC.X * iPrevious2) + (_EC.X * iStep2) + ((EN.X - _EC.X) * iStep2 * 0.5) + (EN.X * iNext2)) / _dye, ((_EC.Y * iPrevious2) + (_EC.Y * iStep2) + ((EN.Y - _EC.Y) * iStep2 * 0.5) + (EN.Y * iNext2)) / _dye, ((_EC.Z * iPrevious2) + (_EC.Z * iStep2) + ((EN.Z - _EC.Z) * iStep2 * 0.5) + (EN.Z * iNext2)) / _dye, ((_EC.W * iPrevious2) + (_EC.W * iStep2) + ((EN.W - _EC.W) * iStep2 * 0.5) + (EN.W * iNext2)) / _dye); end else begin _EC := SetVector(EN.X + _dre, EN.Y + _dge, EN.Z + _dbe, EN.W + _dae); EN := SetVector(EN.X + _dre, EN.Y + _dge, EN.Z + _dbe, EN.W + _dae); end; iCurrent2 := iCurrent2 + iStep2; end; end; PaintHorizontalLineNCM(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + _dys); _EP := SetVector(_EP.U + _dxe, _EP.V + _dye); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintHorizontalLineNCM(_Buffer,_WeightBuffer,_SP.U,_EP.U,_SP.V,_SC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; var _S, _E: TVector2f; const _FinalPos: TVector2f; const _dxs, _dxe: single; _Size: integer); var dy: real; begin if (_FinalPos.V - _S.V) > 1 then begin dy := (_FinalPos.V - _S.V) / trunc(_FinalPos.V - _S.V); while _S.V < _FinalPos.V do begin PaintBumpHorizontalLine(_Buffer, _HeightMap,_S.U,_E.U,_S.V,_Size); _S := SetVector(_S.U + _dxs, _S.V + dy); _E := SetVector(_E.U + _dxe, _E.V + dy); end; end else begin PaintBumpHorizontalLine(_Buffer, _HeightMap,_S.U,_E.U,_S.V,_Size); _E := SetVector(_E.U + _dxe, _E.V + (_FinalPos.V - _S.V)); _S := SetVector(_S.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePiece(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; var _S, _E: TVector2f; const _FinalPos: TVector2f; const _dxs, _dxe: single; _Size: integer); var dy: real; begin if (_FinalPos.V - _S.V) > 1 then begin dy := (_FinalPos.V - _S.V) / trunc(_FinalPos.V - _S.V); while _S.V < _FinalPos.V do begin PaintBumpHorizontalLine(_Buffer, _HeightMap,_S.U,_E.U,_S.V,_Size); _S := SetVector(_S.U + _dxs, _S.V + dy); _E := SetVector(_E.U + _dxe, _E.V + dy); end; end else begin PaintBumpHorizontalLine(_Buffer, _HeightMap,_S.U,_E.U,_S.V,_Size); _E := SetVector(_E.U + _dxe, _E.V + (_FinalPos.V - _S.V)); _S := SetVector(_S.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePieceBorder(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); var dys,dye: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dys := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); dye := (_FinalPos.V - _EP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_SP.U + _dxs,_SP.V,_SC,_SC); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_EP.U,_EP.U + _dxe,_EP.V,_EC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dys); _EP := SetVector(_EP.U + _dxe, _EP.V + dye); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs, _SC.W + _das); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe, _EC.W + _dae); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_SP.U + _dxs,_SP.V,_SC,_SC); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_EP.U,_EP.U + _dxe,_EP.V,_EC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintTrianglePieceBorder(var _Buffer, _WeightBuffer: TAbstract2DImageData; var _SP, _EP: TVector2f; var _SC, _EC: TVector4f; const _FinalPos: TVector2f; const _dxs, _dxe, _drs, _dre, _dgs, _dge, _dbs, _dbe, _das, _dae: real); var dys,dye: real; begin if (_FinalPos.V - _SP.V) > 1 then begin dys := (_FinalPos.V - _SP.V) / trunc(_FinalPos.V - _SP.V); dye := (_FinalPos.V - _EP.V) / trunc(_FinalPos.V - _SP.V); while (_SP.V < _FinalPos.V) do begin PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_SP.U + _dxs,_SP.V,_SC,_SC); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_EP.U,_EP.U + _dxe,_EP.V,_EC,_EC); _SP := SetVector(_SP.U + _dxs, _SP.V + dys); _EP := SetVector(_EP.U + _dxe, _EP.V + dye); _SC := SetVector(_SC.X + _drs, _SC.Y + _dgs, _SC.Z + _dbs, _SC.W + _das); _EC := SetVector(_EC.X + _dre, _EC.Y + _dge, _EC.Z + _dbe, _EC.W + _dae); end; end else begin _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_SP.U,_SP.U + _dxs,_SP.V,_SC,_SC); PaintGouraudHorizontalLine(_Buffer,_WeightBuffer,_EP.U,_EP.U + _dxe,_EP.V,_EC,_EC); _SC := SetVector(_SC.X + (_drs / 2), _SC.Y + (_dgs / 2), _SC.Z + (_dbs / 2), _SC.W + (_das / 2)); _EC := SetVector(_EC.X + (_dre / 2), _EC.Y + (_dge / 2), _EC.Z + (_dbe / 2), _EC.W + (_dae / 2)); _EP := SetVector(_EP.U + _dxe, _EP.V + (_FinalPos.V - _SP.V)); _SP := SetVector(_SP.U + _dxs, _FinalPos.V); end; end; procedure CTriangleFiller.PaintGouraudTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector3f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3 : single; SP, EP : TVector2f; SC, EC : TVector3f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3); end else begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2); end; end; procedure CTriangleFiller.PaintGouraudTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1,da1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2,da2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3,da3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3); end else begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2); end; end; // Code adapted from http://www-users.mat.uni.torun.pl/~wrona/3d_tutor/tri_fillers.html procedure CTriangleFiller.PaintGouraudTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1,da1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2,da2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3,da3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3); end else begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2); end; end; procedure CTriangleFiller.PaintGouraudTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector3f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3 : single; SP, EP : TVector2f; SC, EC : TVector3f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3); end else begin PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePiece(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2); end; end; procedure CTriangleFiller.PaintNCMTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dy1, dy2, dy3, dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; iStart1, iEnd1, iStart2, iEnd2: real; begin GetGradient(_P2,_P1,dx1); GetGradient(_P3,_P1,dx2); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin GetGradientNCM(_P2,_P1,_C2,_C1,dy1,dx1,dr1,dg1,db1,da1,iStart1,iEnd1); GetGradientNCM(_P3,_P1,_C3,_C1,dy2,dx2,dr2,dg2,db2,da2,iStart2,iEnd2); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dy2,dy1,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1,iStart1,iEnd1,iStart2,iEnd2); AssignPointColour(EP,EC,_P2,_C2); GetGradientNCM(_P3,_P2,_C3,_C2,dy3,dx3,dr3,dg3,db3,da3,iStart1,iEnd1); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dy2,dy3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3,iStart1,iEnd1,iStart2,iEnd2); end else begin GetGradientNCM(_P2,_P1,_C2,_C1,dy1,dx1,dr1,dg1,db1,da1,iStart1,iEnd1); GetGradientNCM(_P3,_P1,_C3,_C1,dy2,dx2,dr2,dg2,db2,da2,iStart2,iEnd2); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dy1,dy2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2,iStart1,iEnd1,iStart2,iEnd2); AssignPointColour(SP,SC,_P2,_C2); GetGradientNCM(_P3,_P2,_C3,_C2,dy3,dx3,dr3,dg3,db3,da3,iStart1,iEnd1); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dy3,dy2,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2,iStart1,iEnd1,iStart2,iEnd2); end; end; procedure CTriangleFiller.PaintNCMTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dy1, dy2, dy3, dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; iStart1, iEnd1, iStart2, iEnd2: real; begin GetGradient(_P2,_P1,dx1); GetGradient(_P3,_P1,dx2); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin GetGradientNCM(_P2,_P1,_C2,_C1,dy1,dx1,dr1,dg1,db1,da1,iStart1,iEnd1); GetGradientNCM(_P3,_P1,_C3,_C1,dy2,dx2,dr2,dg2,db2,da2,iStart2,iEnd2); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dy2,dy1,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1,iStart1,iEnd1,iStart2,iEnd2); AssignPointColour(EP,EC,_P2,_C2); GetGradientNCM(_P3,_P2,_C3,_C2,dy3,dx3,dr3,dg3,db3,da3,iStart2,iEnd2); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dy2,dy3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3,iStart1,iEnd1,iStart2,iEnd2); end else begin GetGradientNCM(_P2,_P1,_C2,_C1,dy1,dx1,dr1,dg1,db1,da1,iStart1,iEnd1); GetGradientNCM(_P3,_P1,_C3,_C1,dy2,dx2,dr2,dg2,db2,da2,iStart2,iEnd2); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dy1,dy2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2,iStart1,iEnd1,iStart2,iEnd2); AssignPointColour(SP,SC,_P2,_C2); GetGradientNCM(_P3,_P2,_C3,_C2,dy3,dx3,dr3,dg3,db3,da3,iStart1,iEnd1); PaintTrianglePieceNCM(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dy3,dy2,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2,iStart1,iEnd1,iStart2,iEnd2); end; end; procedure CTriangleFiller.PaintBumpMapTriangle(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _P1, _P2, _P3 : TVector2f); var dx1, dx2, dx3 : single; Size : integer; S, E : TVector2f; begin Size := High(_Buffer[0])+1; GetGradient(_P2,_P1,dx1); GetGradient(_P3,_P1,dx2); GetGradient(_P3,_P2,dx3); E := SetVector(_P1); S := SetVector(_P1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P2,dx2,dx1,Size); E := SetVector(_P2); PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P3,dx2,dx3,Size); end else begin PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P2,dx1,dx2,Size); S := SetVector(_P2); PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P3,dx3,dx2,Size); end; end; procedure CTriangleFiller.PaintBumpMapTriangle(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); var dx1, dx2, dx3 : single; Size : integer; S, E : TVector2f; begin Size := _Buffer.MaxX +1; GetGradient(_P2,_P1,dx1); GetGradient(_P3,_P1,dx2); GetGradient(_P3,_P2,dx3); E := SetVector(_P1); S := SetVector(_P1); if (dx1 > dx2) then begin PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P2,dx2,dx1,Size); E := SetVector(_P2); PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P3,dx2,dx3,Size); end else begin PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P2,dx1,dx2,Size); S := SetVector(_P2); PaintTrianglePiece(_Buffer,_HeightMap,S,E,_P3,dx3,dx2,Size); end; end; procedure CTriangleFiller.PaintGouraudTriangleBorder(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1,da1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2,da2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3,da3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3); end else begin PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2); end; end; procedure CTriangleFiller.PaintGouraudTriangleBorder(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var dx1, dx2, dx3, dr1, dr2, dr3, dg1, dg2, dg3, db1, db2, db3, da1, da2, da3 : single; SP, EP : TVector2f; SC, EC : TVector4f; begin GetGradient(_P2,_P1,_C2,_C1,dx1,dr1,dg1,db1,da1); GetGradient(_P3,_P1,_C3,_C1,dx2,dr2,dg2,db2,da2); GetGradient(_P3,_P2,_C3,_C2,dx3,dr3,dg3,db3,da3); AssignPointColour(SP,SC,_P1,_C1); AssignPointColour(EP,EC,_P1,_C1); if (dx1 > dx2) then begin PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx2,dx1,dr2,dr1,dg2,dg1,db2,db1,da2,da1); AssignPointColour(EP,EC,_P2,_C2); PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx2,dx3,dr2,dr3,dg2,dg3,db2,db3,da2,da3); end else begin PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P2,dx1,dx2,dr1,dr2,dg1,dg2,db1,db2,da1,da2); AssignPointColour(SP,SC,_P2,_C2); PaintTrianglePieceBorder(_Buffer,_WeightBuffer,SP,EP,SC,EC,_P3,dx3,dx2,dr3,dr2,dg3,dg2,db3,db2,da3,da2); end; end; // Public methods starts here. procedure CTriangleFiller.PaintTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := High(_Buffer[0])+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_C3,_C2,_C1); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_C2,_C3,_C1); end else begin // P2 < P1 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_C2,_C1,_C3); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_C3,_C1,_C2); end else begin // P1 < P3 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_C1,_C3,_C2); end; end else begin // P1 < P2 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_C1,_C2,_C3); end; end; end; procedure CTriangleFiller.PaintTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _N1, _N2, _N3: TVector3f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := High(_Buffer[0])+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if P1.V > P2.V then begin if P2.V > P3.V then begin // P3 < P2 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_N3,_N2,_N1); end else begin if P1.V > P3.V then begin // P2 < P3 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_N2,_N3,_N1); end else begin // P2 < P1 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_N2,_N1,_N3); end; end; end else begin if P2.V > P3.V then begin if P1.V > P3.V then begin // P3 < P1 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_N3,_N1,_N2); end else begin // P1 < P3 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_N1,_N3,_N2); end; end else begin // P1 < P2 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_N1,_N2,_N3); end; end; end; procedure CTriangleFiller.PaintTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _N1, _N2, _N3: TVector3f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := _Buffer.MaxX+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if P1.V > P2.V then begin if P2.V > P3.V then begin // P3 < P2 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_N3,_N2,_N1); end else begin if P1.V > P3.V then begin // P2 < P3 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_N2,_N3,_N1); end else begin // P2 < P1 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_N2,_N1,_N3); end; end; end else begin if P2.V > P3.V then begin if P1.V > P3.V then begin // P3 < P1 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_N3,_N1,_N2); end else begin // P1 < P3 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_N1,_N3,_N2); end; end else begin // P1 < P2 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_N1,_N2,_N3); end; end; end; procedure CTriangleFiller.PaintTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := _Buffer.MaxX +1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_C3,_C2,_C1); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_C2,_C3,_C1); end else begin // P2 < P1 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_C2,_C1,_C3); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_C3,_C1,_C2); end else begin // P1 < P3 < P2 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_C1,_C3,_C2); end; end else begin // P1 < P2 < P3 PaintGouraudTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_C1,_C2,_C3); end; end; end; procedure CTriangleFiller.PaintTriangleNCM(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := High(_Buffer[0])+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintNCMTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_C3,_C2,_C1); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintNCMTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_C2,_C3,_C1); end else begin // P2 < P1 < P3 PaintNCMTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_C2,_C1,_C3); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintNCMTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_C3,_C1,_C2); end else begin // P1 < P3 < P2 PaintNCMTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_C1,_C3,_C2); end; end else begin // P1 < P2 < P3 PaintNCMTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_C1,_C2,_C3); end; end; end; procedure CTriangleFiller.PaintTriangleNCM(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f; _C1, _C2, _C3: TVector4f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := _Buffer.MaxX +1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintNCMTriangle(_Buffer,_WeightBuffer,P3,P2,P1,_C3,_C2,_C1); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintNCMTriangle(_Buffer,_WeightBuffer,P2,P3,P1,_C2,_C3,_C1); end else begin // P2 < P1 < P3 PaintNCMTriangle(_Buffer,_WeightBuffer,P2,P1,P3,_C2,_C1,_C3); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintNCMTriangle(_Buffer,_WeightBuffer,P3,P1,P2,_C3,_C1,_C2); end else begin // P1 < P3 < P2 PaintNCMTriangle(_Buffer,_WeightBuffer,P1,P3,P2,_C1,_C3,_C2); end; end else begin // P1 < P2 < P3 PaintNCMTriangle(_Buffer,_WeightBuffer,P1,P2,P3,_C1,_C2,_C3); end; end; end; procedure CTriangleFiller.PaintFlatTriangleFromHeightMap(var _Buffer: T2DFrameBuffer; const _HeightMap: TByteMap; _P1, _P2, _P3 : TVector2f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := High(_Buffer[0])+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if P1.V > P2.V then begin if P2.V > P3.V then begin // P3 < P2 < P1 PaintBumpMapTriangle(_Buffer,_HeightMap,P3,P2,P1); end else begin if P1.V > P3.V then begin // P2 < P3 < P1 PaintBumpMapTriangle(_Buffer,_HeightMap,P2,P3,P1); end else begin // P2 < P1 < P3 PaintBumpMapTriangle(_Buffer,_HeightMap,P2,P1,P3); end; end; end else begin if P2.V > P3.V then begin if P1.V > P3.V then begin // P3 < P1 < P2 PaintBumpMapTriangle(_Buffer,_HeightMap,P3,P1,P2); end else begin // P1 < P3 < P2 PaintBumpMapTriangle(_Buffer,_HeightMap,P1,P3,P2); end; end else begin // P1 < P2 < P3 PaintBumpMapTriangle(_Buffer,_HeightMap,P1,P2,P3); end; end; end; procedure CTriangleFiller.PaintFlatTriangleFromHeightMap(var _Buffer: TAbstract2DImageData; const _HeightMap: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); var P1, P2, P3 : TVector2f; Size : integer; begin Size := _Buffer.MaxX+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); if P1.V > P2.V then begin if P2.V > P3.V then begin // P3 < P2 < P1 PaintBumpMapTriangle(_Buffer,_HeightMap,P3,P2,P1); end else begin if P1.V > P3.V then begin // P2 < P3 < P1 PaintBumpMapTriangle(_Buffer,_HeightMap,P2,P3,P1); end else begin // P2 < P1 < P3 PaintBumpMapTriangle(_Buffer,_HeightMap,P2,P1,P3); end; end; end else begin if P2.V > P3.V then begin if P1.V > P3.V then begin // P3 < P1 < P2 PaintBumpMapTriangle(_Buffer,_HeightMap,P3,P1,P2); end else begin // P1 < P3 < P2 PaintBumpMapTriangle(_Buffer,_HeightMap,P1,P3,P2); end; end else begin // P1 < P2 < P3 PaintBumpMapTriangle(_Buffer,_HeightMap,P1,P2,P3); end; end; end; procedure CTriangleFiller.PaintDebugTriangle(var _Buffer: T2DFrameBuffer; var _WeightBuffer: TWeightBuffer; _P1, _P2, _P3 : TVector2f); var P1, P2, P3, PC : TVector2f; CX : TVector4f; Size : integer; Perimeterx2, D12, D23, D31 : single; begin Size := High(_Buffer[0])+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); // We'll do things in a different way here. // 1) paint center of triangle: // Detect Central position. D12 := VectorDistance(P1, P2); D23 := VectorDistance(P2, P3); D31 := VectorDistance(P3, P1); Perimeterx2 := (D12 + D23 + D31) * 2; PC.U := (P1.U * ((D12 + D31) / Perimeterx2)) + (P2.U * ((D12 + D23) / Perimeterx2)) + (P3.U * ((D23 + D31) / Perimeterx2)); PC.V := (P1.V * ((D12 + D31) / Perimeterx2)) + (P2.V * ((D12 + D23) / Perimeterx2)) + (P3.V * ((D23 + D31) / Perimeterx2)); // Set Center colour, should be a green. CX.X := 0; CX.Y := 1; CX.Z := 0; CX.W := 0; // Paint it. PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PC, CX); // 2) paint the edges. // Set edge colour, should be a blue. CX.X := 0; CX.Y := 0; CX.Z := 1; CX.W := 0; if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P3,P2,P1,CX,CX,CX); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P2,P3,P1,CX,CX,CX); end else begin // P2 < P1 < P3 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P2,P1,P3,CX,CX,CX); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P3,P1,P2,CX,CX,CX); end else begin // P1 < P3 < P2 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P1,P3,P2,CX,CX,CX); end; end else begin // P1 < P2 < P3 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P1,P2,P3,CX,CX,CX); end; end; // 3) Paint vertexes. // Set vertex colour, should be red. CX.X := 1; CX.Y := 0; CX.Z := 0; CX.W := 0; // Paint it. PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P1, CX); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P2, CX); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P3, CX); end; procedure CTriangleFiller.PaintDebugTriangle(var _Buffer, _WeightBuffer: TAbstract2DImageData; _P1, _P2, _P3 : TVector2f); var P1, P2, P3, P12, P23, P31, PC : TVector2f; CX : TVector4f; Size : integer; Perimeter, D12, D23, D31 : single; begin Size := _Buffer.MaxX+1; P1 := ScaleVector(_P1,Size); P2 := ScaleVector(_P2,Size); P3 := ScaleVector(_P3,Size); // We'll do things in a different way here. // 1) paint center of triangle: // Detect Central position. D12 := VectorDistance(P1, P2); D23 := VectorDistance(P2, P3); D31 := VectorDistance(P3, P1); P12.U := (P1.U + P2.U) / 2; P12.V := (P1.V + P2.V) / 2; P23.U := (P2.U + P3.U) / 2; P23.V := (P2.V + P3.V) / 2; P31.U := (P3.U + P1.U) / 2; P31.V := (P3.V + P1.V) / 2; Perimeter := (D12 + D23 + D31); PC.U := (P23.U * (D23 / Perimeter)) + (P31.U * (D31 / Perimeter)) + (P12.U * (D12 / Perimeter)); PC.V := (P23.V * (D23 / Perimeter)) + (P31.V * (D31 / Perimeter)) + (P12.V * (D12 / Perimeter)); // Set Center colour, should be a green. CX.X := 0; CX.Y := 1; CX.Z := 0; CX.W := 1; // Paint it. PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, PC, CX); // 2) paint the edges. // Set edge colour, should be a blue. CX.X := 0; CX.Y := 0; CX.Z := 1; CX.W := 1; if IsP1HigherThanP2(P1,P2) then begin if IsP1HigherThanP2(P2,P3) then begin // P3 < P2 < P1 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P3,P2,P1,CX,CX,CX); end else begin if IsP1HigherThanP2(P1,P3) then begin // P2 < P3 < P1 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P2,P3,P1,CX,CX,CX); end else begin // P2 < P1 < P3 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P2,P1,P3,CX,CX,CX); end; end; end else begin if IsP1HigherThanP2(P2,P3) then begin if IsP1HigherThanP2(P1,P3) then begin // P3 < P1 < P2 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P3,P1,P2,CX,CX,CX); end else begin // P1 < P3 < P2 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P1,P3,P2,CX,CX,CX); end; end else begin // P1 < P2 < P3 PaintGouraudTriangleBorder(_Buffer,_WeightBuffer,P1,P2,P3,CX,CX,CX); end; end; // 3) Paint vertexes. // Set vertex colour, should be white. CX.X := 1; CX.Y := 1; CX.Z := 0; CX.W := 1; // Paint it. PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P1, CX); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P2, CX); PaintPixelAtFrameBuffer(_Buffer, _WeightBuffer, P3, CX); end; end.
unit pSHConsts; interface const SCaptionButtonOK = 'OK'; SCaptionButtonCancel = 'Cancel'; SCaptionButtonHelp = 'Help'; SAskReplaceText = 'Replace this occurence of "%s"?'; SNoMoreStringFound = 'No more string ''%s'' found'; SLineNumberOutOfRange = 'Line number must be between 1 and %d'; // SInformation = 'Information'; implementation end.
unit StopWatch; interface // Adapted from // http://delphi.about.com/od/windowsshellapi/a/delphi-high-performance-timer-tstopwatch.htm uses Windows, SysUtils, DateUtils; type TStopWatch = class private fFrequency : TLargeInteger; fIsRunning: boolean; fIsHighResolution: boolean; fStartCount, fStopCount : TLargeInteger; procedure SetTickStamp(var lInt : TLargeInteger) ; function GetElapsedTicks: TLargeInteger; function GetElapsedMiliseconds: TLargeInteger; function GetElapsedNanoseconds: Extended; function GetElapsed: string; public constructor Create(const startOnCreate : boolean = false) ; procedure Start; procedure Stop; property IsHighResolution : boolean read fIsHighResolution; property ElapsedTicks : TLargeInteger read GetElapsedTicks; property ElapsedMiliseconds : TLargeInteger read GetElapsedMiliseconds; property ElapsedNanoseconds : Extended read GetElapsedNanoseconds; property Elapsed : string read GetElapsed; property IsRunning : boolean read fIsRunning; end; implementation constructor TStopWatch.Create(const startOnCreate : boolean = false); begin inherited Create; fIsRunning := false; fIsHighResolution := QueryPerformanceFrequency(fFrequency); if not fIsHighResolution then fFrequency := MSecsPerSec; if startOnCreate then Start; end; function TStopWatch.GetElapsedTicks: TLargeInteger; begin result := fStopCount - fStartCount; end; procedure TStopWatch.SetTickStamp(var lInt : TLargeInteger); begin if fIsHighResolution then QueryPerformanceCounter(lInt) else lInt := MilliSecondOf(Now) ; end; function TStopWatch.GetElapsed: string; var dt : TDateTime; begin dt := ElapsedMiliseconds / MSecsPerSec / SecsPerDay; result := Format('%d days, %s', [Trunc(dt), FormatDateTime('hh:nn:ss.z', Frac(dt))]) ; end; function TStopWatch.GetElapsedMiliseconds: TLargeInteger; begin result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency; end; function TStopWatch.GetElapsedNanoseconds: Extended; begin result := (1000000000 * (fStopCount - fStartCount)) / fFrequency; end; procedure TStopWatch.Start; begin SetTickStamp(fStartCount) ; fIsRunning := true; end; procedure TStopWatch.Stop; begin SetTickStamp(fStopCount) ; fIsRunning := false; end; end.
unit MyMsgBox; interface uses Windows; function MbIserIcon_Ok(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : BOOL; function MbIserIcon_YesNo(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : Integer; function MbIserIcon_Error(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : BOOL; implementation function MbIserIcon_Ok(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : BOOL; var MsgInfo : TMsgBoxParams; begin with MsgInfo do begin lpfnMsgBoxCallback := nil; cbSize := SizeOf(TMsgBoxParams); hwndOwner := hWnd; hInstance := GetWindowLong(hWnd, GWL_HINSTANCE); lpszText := @Text[1]; lpszCaption := @Caption[1]; dwStyle := MB_USERICON or MB_OK; lpszIcon := MAKEINTRESOURCE(IDICON); dwLanguageId := GetSystemDefaultLangID; MessageBeep(MB_ICONASTERISK); end; Result := MessageBoxIndirect(MsgInfo); end; function MbIserIcon_YesNo(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : Integer; var MsgInfo : TMsgBoxParams; begin with MsgInfo do begin lpfnMsgBoxCallback := nil; cbSize := SizeOf(TMsgBoxParams); hwndOwner := hWnd; hInstance := GetWindowLong(hWnd, GWL_HINSTANCE); lpszText := @Text[1]; lpszCaption := @Caption[1]; dwStyle := MB_USERICON or MB_YESNO; lpszIcon := MAKEINTRESOURCE(IDICON); dwLanguageId := GetSystemDefaultLangID; MessageBeep(MB_ICONEXCLAMATION); end; Result := Integer(MessageBoxIndirect(MsgInfo)); end; function MbIserIcon_Error(hWnd : HWND; Text, Caption : String; IDIcon : DWORD) : BOOL; var MsgInfo : TMsgBoxParams; begin with MsgInfo do begin lpfnMsgBoxCallback := nil; cbSize := SizeOf(TMsgBoxParams); hwndOwner := hWnd; hInstance := GetWindowLong(hWnd, GWL_HINSTANCE); lpszText := @Text[1]; lpszCaption := @Caption[1]; dwStyle := MB_USERICON or MB_OK; lpszIcon := MAKEINTRESOURCE(IDICON); dwLanguageId := GetSystemDefaultLangID; MessageBeep(MB_ICONHAND); end; Result := MessageBoxIndirect(MsgInfo); end; end.
unit ccnUtils; interface uses Windows, Classes, DB, SysUtils, DBCtrls, Uni, InterBaseUniProvider, IdHashMessageDigest, idHash, Registry, TLHelp32, IdSMTP, IdMessage, IdBaseComponent, IdComponent, IniFiles; function MD5(const text_str : string) : string; function GetRegistryValue(keyName, itemName: string): string; procedure SetRegistryValue(keyname, keyvalue : string); function GetFileVersion(szFullPath: pChar): String; implementation function MD5(const text_str : string) : string; var idmd5 : TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := idmd5.HashStringAsHex(text_str); finally idmd5.Free; end; end; function GetRegistryValue(keyName, itemName: string): string; var Registry: TRegistry; regVal : string; begin Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey(keyName, False) then regVal := Registry.ReadString(itemName) else regVal := ''; Result := regVal; finally Registry.Free; end; end; procedure SetRegistryValue(keyname, keyvalue : string); var Registry : TRegistry; begin Registry := TRegistry.Create(KEY_WRITE); Registry.RootKey := HKEY_CURRENT_USER; Registry.CreateKey(keyname); Registry.OpenKey(keyname,True); Registry.WriteString('', keyvalue); end; function GetFileVersion(szFullPath: pChar): String; var Size, Size2: DWord; Pt, Pt2: Pointer; begin Result := ''; Size := GetFileVersionInfoSize(szFullPath, Size2); if Size > 0 then begin GetMem(Pt, Size); try GetFileVersionInfo(szFullPath, 0, Size, Pt); VerQueryValue (Pt, '\', Pt2, Size2); with TVSFixedFileInfo(Pt2^) do begin Result := Format('%d.%d.%d.%d', [HiWord(dwFileVersionMS), LoWord(dwFileVersionMS), HiWord(dwFileVersionLS), LoWord(dwFileVersionLS)]); end; finally FreeMem(Pt); end; end; end; end.
unit uDDStex; interface uses System.Classes, System.SysUtils, GLCompositeImage, GLFileDDS, GLMaterial, GLTexture; function libmat(AMatLib: TGLMaterialLibrary; AMatName: string): TGLLibMaterial; function DDStex(AMatLib: TGLMaterialLibrary; ATexName, AFileName: string; ASecondTexName: string = ''; ADDSLevel: integer = 0): TGLLibMaterial; // ============================================================ implementation // ============================================================ function libmat(AMatLib: TGLMaterialLibrary; AMatName: string): TGLLibMaterial; begin if AMatLib = nil then exit; result := AMatLib.LibMaterialByName(AMatName); if result = nil then begin result := AMatLib.Materials.Add; result.Name := AMatName; end; end; function DDStex(AMatLib: TGLMaterialLibrary; ATexName, AFileName: string; ASecondTexName: string = ''; ADDSLevel: integer = 0): TGLLibMaterial; var d: TGLDDSDetailLevels; begin d := vDDSDetailLevel; case ADDSLevel of 1: vDDSDetailLevel := ddsMediumDet; 2: vDDSDetailLevel := ddsLowDet; else vDDSDetailLevel := ddsHighDet; end; result := libmat(AMatLib, ATexName); result.Texture2Name := ASecondTexName; with result.Material.Texture do begin ImageClassName := 'TGLCompositeImage'; Image.LoadFromFile(AFileName); disabled := false; end; vDDSDetailLevel := d; end; end.
unit ModelLib; interface uses Classes; type TService = class(TObject) sercieName:string; key:string; value:string; treeKey:string;//父类ID end; TServiceAdvance = class(TPersistent) private function GetItems(Key: string): TService; function GetCount: Integer; public Keys: TStrings; Values: array of TService; property Items[Key: string]: TService read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TService): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TStringArr = class(TPersistent) private function GetItems(Key: string): string; function GetCount: Integer; public Keys: TStrings; Values: array of string; property Items[Key: string]: string read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: string): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TStringArrAdvance = class(TPersistent) private function GetItems(Key: string): TStringArr; function GetCount: Integer; public Keys: TStrings; Values: array of TStringArr; property Items[Key: string]: TStringArr read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TStringArr): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TCheckRule = class(TObject) rules:TStringArr; needs:TStrings; events:TStrings; needCheck:Boolean; procedure clear; constructor Create; overload; end; //属性 TPrototype = class(TObject) public dataType:string;//数据类型 主键、manytoone、onetomany、普通属性 dataData:string;//数据类型 dataName:string; //字段名称 dataLength:Integer;//数据长度 comment:string;//中文描述 ClassName:string;//如果是外键属性,那么对应哪个实体类? autoInsert:Boolean; //主键时,是否自动插入还是手动生成 enable:Boolean; //是否不是外键属性 constructor Create; overload; end; //属性集合 TPrototypes = class(TPersistent) private function GetItems(Key: string): TPrototype; function GetCount: Integer; public Keys: TStrings; Values: array of TPrototype; procedure clear; property Items[Key: string]: TPrototype read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TPrototype): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TPrototypeUse = class(TObject) public dataName:string; //字段名称 comment:string;//中文描述 Prototype:TPrototype; //基本类型 StringArr:TStringArr; //静态取数集合 service:TService; //动态取数对象 diccode:string;//数据字典 dataGetType:Integer;//取数类型 3=无,0=静态 1=动态 2=数据字典; showType:string; //显示方式 timerCoder:string;//时间控件显示方式 no:Integer; constructor Create; overload; end; //列表 TListType = class(TPrototypeUse) public order:Boolean; DataLength:Integer; end; //列表s TListTypes = class(TPersistent) private function GetItems(Key: string): TListType; function GetCount: Integer; public Keys: TStrings; Values: array of TListType; procedure clear; property Items[Key: string]: TListType read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TListType): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; //查询条件 TConditionType = class(TPrototypeUse) public datanameex:string;//别名 eqs:string;//对比关系 // isAdv:Boolean; //是否是高级查询 end; //查询条件集合 TConditionTypes = class(TPersistent) private function GetItems(Key: string): TConditionType; function GetCount: Integer; public Keys: TStrings; Values: array of TConditionType; procedure clear; property Items[Key: string]: TConditionType read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TConditionType): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; //表单 TFormType = class(TPrototypeUse) public CheckRule:TCheckRule; constructor Create; overload; end; //表单集合 TFormTypes = class(TPersistent) private function GetItems(Key: string): TFormType; function GetCount: Integer; public Keys: TStrings; Values: array of TFormType; procedure clear; property Items[Key: string]: TFormType read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TFormType): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; //查看 TViewType = class(TPrototypeUse) end; TViewTypes = class(TPersistent) private function GetItems(Key: string): TViewType; function GetCount: Integer; public Keys: TStrings; Values: array of TViewType; procedure clear; property Items[Key: string]: TViewType read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TViewType): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; //附件 TFj = class(TObject) itemid:string; fileType:string; qz,hz:string; //前缀、后缀 showasimage:string; maxcount :Integer; path:string; comment:string; end; TFJS = array of TFj; //模块s TModel = class(TObject) className:string; serviceName:string; modelName:string; hibernatePath:string; springPath:string; pacName:string;//包名 prototypes:TPrototypes;//属性集合 constructor Create; overload; end; TModels = class(TPersistent) private function GetItems(Key: string): TModel; function GetCount: Integer; public Keys: TStrings; Values: array of TModel; procedure clear; property Items[Key: string]: TModel read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TModel): Integer; //添加元素 function Remove(Key: string): Integer; //移除 constructor Create; overload; end; //代码模块 TModelCode = class(TComponent) public mobile:Boolean; //生成移动模块 mobilePath:string; //移动目录路径 mobileTitle:string; //移动项目题目 propath:string; //项目目录 modelPath:string; //模块目录 pacname:string; //包名 modelLargeName:string;//大写名模块 className:string; //类名 modelName:string; //项目名称 hibernatePath:string; //hibernate目录 modelChname:string;//模块中文名 hibernate:string; //hibernate根目录 author:string; company:string; changeHibernate:Boolean; dynamicUpdate:Boolean; //智能插入 OneToMany:string; ManyToOne:string; prototypes:TPrototypes;//属性集合 ConditionTypes:TConditionTypes;//查询条件集合 ListTypes:TListTypes; //列表 // advanceList:TConditionTypes;//高级查询列表 tionTypes: TConditionTypes;//所有查询列表 FormTypes:TFormTypes; //表单 parentIds:TStrings; //many-to-one id集合 proList:TStrings; //字段名称集合 xmlList:TStrings; //已经级联读取的hibernatexml文件 otherModels:TModels; //其他模块集合 springList:TStrings; //spring文件合集 springPath:string; CheckRule:TCheckRule; //表单验证 viewList:TViewTypes; //查看页面 Prototype:TPrototype;//主键 showAsTree:Boolean;//是否显示为树 showExport:Boolean;// 是否导出 treeNode:string;//树节点id treeText:string;//树节点 services:TServiceAdvance; // 动态取数集合 showcheckbox:Boolean; showNum:Boolean; Fjs:TFJS; constructor Create; overload; procedure clear; end; implementation constructor TCheckRule.Create; begin rules:=TStringArr.Create; needs:=TStringList.Create; events:=TStringList.Create; needCheck := True; end; procedure TCheckRule.clear; begin rules.clear; needs.clear; events.clear; end; constructor TFormType.Create; begin CheckRule := TCheckRule.Create; inherited Create(); end; constructor TModel.Create; begin prototypes := TPrototypes.Create; end; procedure TModelCode.clear; begin prototypes.clear; ConditionTypes.clear; ListTypes.clear; FormTypes.clear; parentIds.Clear; proList.Clear; xmlList.Clear; otherModels.Clear; springList.Clear; CheckRule.clear; viewList.clear; services.clear; // advanceList.clear; tionTypes.clear; end; constructor TPrototype.Create; begin autoInsert := False; enable:=True; end; constructor TPrototypeUse.Create; begin StringArr:=TStringArr.Create; service := Tservice.Create; dataGetType := 3; end; constructor TModelCode.Create; begin prototypes:=Tprototypes.Create; ConditionTypes := TConditionTypes.Create; ListTypes:=TListTypes.Create; FormTypes:=TFormTypes.Create; proList := TStringList.Create; parentIds := TStringList.Create; xmlList :=TStringList.Create; otherModels:= TModels.Create; springList := TStringList.Create; CheckRule := TCheckRule.Create; viewList := TViewTypes.Create; services := TServiceAdvance.Create; // advanceList :=TConditionTypes.Create; tionTypes := TConditionTypes.Create; end; constructor TStringArr.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TStringArr.clear; begin SetLength(Values, 0); Keys.Clear; end; function TStringArr.GetItems(Key: string): string; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := ''; end; function TStringArr.Add(Key: string; Value: string): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TStringArr.GetCount: Integer; begin Result := Keys.Count; end; function TStringArr.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TPrototypes.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TPrototypes.clear; begin SetLength(Values, 0); Keys.Clear; end; function TPrototypes.GetItems(Key: string): TPrototype; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TPrototypes.Add(Key: string; Value: TPrototype): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TPrototypes.GetCount: Integer; begin Result := Keys.Count; end; function TPrototypes.Remove(Key: string): Integer; //移除 var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TListTypes.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TListTypes.clear; begin SetLength(Values, 0); Keys.Clear; end; function TListTypes.GetItems(Key: string): TListType; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TListTypes.Add(Key: string; Value: TListType): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TListTypes.GetCount: Integer; begin Result := Keys.Count; end; function TListTypes.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TConditionTypes.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TConditionTypes.clear; begin SetLength(Values, 0); Keys.Clear; end; function TConditionTypes.GetItems(Key: string): TConditionType; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TConditionTypes.Add(Key: string; Value: TConditionType): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TConditionTypes.GetCount: Integer; begin Result := Keys.Count; end; function TConditionTypes.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TFormTypes.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TFormTypes.clear; begin SetLength(Values, 0); Keys.Clear; end; function TFormTypes.GetItems(Key: string): TFormType; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TFormTypes.Add(Key: string; Value: TFormType): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TFormTypes.GetCount: Integer; begin Result := Keys.Count; end; function TFormTypes.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TModels.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TModels.clear; begin SetLength(Values, 0); Keys.Clear; end; function TModels.GetItems(Key: string): TModel; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TModels.Add(Key: string; Value: TModel): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TModels.GetCount: Integer; begin Result := Keys.Count; end; function TModels.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TStringArrAdvance.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TStringArrAdvance.clear; begin SetLength(Values, 0); Keys.Clear; end; function TStringArrAdvance.GetItems(Key: string): TStringArr; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TStringArrAdvance.Add(Key: string; Value: TStringArr): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TStringArrAdvance.GetCount: Integer; begin Result := Keys.Count; end; function TStringArrAdvance.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TViewTypes.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TViewTypes.clear; begin SetLength(Values, 0); Keys.Clear; end; function TViewTypes.GetItems(Key: string): TViewType; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TViewTypes.Add(Key: string; Value: TViewType): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TViewTypes.GetCount: Integer; begin Result := Keys.Count; end; function TViewTypes.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TServiceAdvance.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TServiceAdvance.clear; begin SetLength(Values, 0); Keys.Clear; end; function TServiceAdvance.GetItems(Key: string): TService; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TServiceAdvance.Add(Key: string; Value: TService): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TServiceAdvance.GetCount: Integer; begin Result := Keys.Count; end; function TServiceAdvance.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; end.
unit VirtualUnicodeControls; // Version 1.3.0 // // 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/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // 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 initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Much of this unit is based on Troy Wolbrinks Unicode Controls package // http://home.ccci.org/wolbrink/tntmpd/delphi_unicode_controls_project.htm // Thanks to Troy for making this possible. // ---------------------------------------------------------------------------- // 10-04 // Fixed Bug in TWideCaptionHolder.Notification // Added WideCaptionHolders.Remove(Self); interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ActiveX, ComCtrls, Commctrl, ImgList, VirtualWideStrings, VirtualShellUtilities, VirtualUtilities; type TSetAnsiStrEvent = procedure(const Value: AnsiString) of object; type TCustomWideEdit = class(TCustomEdit{TNT-ALLOW TCustomEdit}) private function GetSelText: WideString; reintroduce; procedure SetSelText(const Value: WideString); function GetText: WideString; procedure SetText(const Value: WideString); // function GetHint: WideString; // procedure SetHint(const Value: WideString); // function IsHintStored: Boolean; protected procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DefineProperties(Filer: TFiler); override; procedure SelectText(FirstChar, LastChar: integer); public property SelText: WideString read GetSelText write SetSelText; property Text: WideString read GetText write SetText; published // property Hint: WideString read GetHint write SetHint stored IsHintStored; end; TWideEdit = class(TCustomWideEdit) published property Anchors; property AutoSelect; property AutoSize; property BiDiMode; property BorderStyle; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; {$ifdef COMPILER_5_UP} property OnContextPopup; {$endif} property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; procedure TntCustomEdit_CreateWindowHandle(Edit: TCustomEdit; const Params: TCreateParams); function TntCustomEdit_GetSelText(Edit: TCustomEdit): WideString; procedure TntCustomEdit_SetSelText(Edit: TCustomEdit; const Value: WideString); // register/create window procedure SubClassUnicodeControl(Control: TWinControl; Params_Caption: PAnsiChar; IDEWindow: Boolean = False); procedure RegisterUnicodeClass(Params: TCreateParams; out WideWinClassName: WideString; IDEWindow: Boolean = False); procedure CreateUnicodeHandle(Control: TWinControl; const Params: TCreateParams; const SubClass: WideString; IDEWindow: Boolean = False); // caption/text management function TntControl_IsCaptionStored(Control: TControl): Boolean; function TntControl_GetStoredText(Control: TControl; const Default: WideString): WideString; function TntControl_GetText(Control: TControl): WideString; procedure TntControl_SetText(Control: TControl; const Text: WideString); function Tnt_SetWindowTextW(hWnd: HWND; lpString: PWideChar): BOOL; // "synced" wide string function GetSyncedWideString(var WideStr: WideString; const AnsiStr: AnsiString): WideString; procedure SetSyncedWideString(const Value: WideString; var WideStr: WideString; const AnsiStr: AnsiString; SetAnsiStr: TSetAnsiStrEvent); // text/char message function IsTextMessage(Msg: UINT): Boolean; procedure MakeWMCharMsgSafeForAnsi(var Message: TMessage); procedure RestoreWMCharMsg(var Message: TMessage); function GetWideCharFromWMCharMsg(Message: TWMChar): WideChar; procedure SetWideCharForWMCharMsg(var Message: TWMChar; Ch: WideChar); function Tnt_Is_IntResource(ResStr: LPCWSTR): Boolean; implementation uses Imm, VirtualShellContainers; type TAccessWinControl = class(TWinControl); TAccessControlActionLink = class(TControlActionLink); TAccessControl = class(TControl); TWndProc = function(HWindow: HWnd; Message, WParam, LParam: Longint): Longint; stdcall; {$IFNDEF T2H} type TWinControlTrap = class(TComponent) private WinControl_ObjectInstance: Pointer; ObjectInstance: Pointer; DefObjectInstance: Pointer; function IsInSubclassChain(Control: TWinControl): Boolean; procedure SubClassWindowProc; private FControl: TAccessWinControl; Handle: THandle; PrevWin32Proc: Pointer; PrevDefWin32Proc: Pointer; PrevWindowProc: TWndMethod; private LastWin32Msg: UINT; Win32ProcLevel: Integer; IDEWindow: Boolean; DestroyTrap: Boolean; TestForNull: Boolean; FoundNull: Boolean; {$IFDEF TNT_VERIFY_WINDOWPROC} LastVerifiedWindowProc: TWndMethod; {$ENDIF} procedure Win32Proc(var Message: TMessage); procedure DefWin32Proc(var Message: TMessage); procedure WindowProc(var Message: TMessage); private procedure SubClassControl(Params_Caption: PAnsiChar); procedure UnSubClassUnicodeControl; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; type TWideCaptionHolder = class(TComponent) private FControl: TControl; FWideCaption: WideString; FWideHint: WideString; procedure SetAnsiText(const Value: AnsiString); // procedure SetAnsiHint(const Value: AnsiString); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TControl); reintroduce; property WideCaption: WideString read FWideCaption; property WideHint: WideString read FWideHint; end; const ANSI_UNICODE_HOLDER = $FF; var PendingRecreateWndTrapList: TObjectList = nil; WindowAtom: TAtom; ControlAtom: TAtom; WindowAtomString: AnsiString; ControlAtomString: AnsiString; UnicodeCreationControl: TWinControl = nil; WideCaptionHolders: TObjectList = nil; Finalized: Boolean; { If any tnt controls are still around after finalization it must be due to a memory leak. Windows will still try to send a WM_DESTROY, but we will just ignore it if we're finalized. } _IsShellProgramming: Boolean = False; // Local Procedures // ----------------------------------------------------------------------------- function Win32PlatformIsUnicode: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT end; function Win32PlatformIsXP: Boolean; begin Result := ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1)) or (Win32MajorVersion > 5); end; procedure RaiseLastOperatingSystemError; begin {$IFDEF COMPILER_6_UP} RaiseLastOSError {$ELSE} RaiseLastWin32Error {$ENDIF} end; procedure RestoreWMCharMsg(var Message: TMessage); begin with TWMChar(Message) do begin Assert(Message.Msg = WM_CHAR); if (Unused > 0) and (CharCode = ANSI_UNICODE_HOLDER) then CharCode := Unused; Unused := 0; end; end; function SameWndMethod(A, B: TWndMethod): Boolean; begin Result := @A = @B; end; function WideCompareStr(const W1, W2: WideString): Integer; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := CompareStringW(LOCALE_USER_DEFAULT, 0, PWideChar(W1), Length(W1), PWideChar(W2), Length(W2)) - 2 else Result := AnsiCompareStr(W1, W2); end; function WideSameStr(const W1, W2: WideString): Boolean; begin Result := WideCompareStr(W1, W2) = 0; end; function FindWideCaptionHolder(Control: TControl; CreateIfNotFound: Boolean = True): TWideCaptionHolder; var i: integer; begin Result := nil; for i := 0 to WideCaptionHolders.Count - 1 do begin if (TWideCaptionHolder(WideCaptionHolders[i]).FControl = Control) then begin Result := TWideCaptionHolder(WideCaptionHolders[i]); exit; // found it! end; end; if (Result = nil) and CreateIfNotFound then begin Result := TWideCaptionHolder.Create(Control); end; end; procedure SetWideStoredText(Control: TControl; const Value: WideString); begin FindWideCaptionHolder(Control).FWideCaption := Value end; procedure InitControls; procedure InitAtomStrings_D5_D6_D7; begin WindowAtomString := Format('Delphi%.8X',[GetCurrentProcessID]); ControlAtomString := Format('ControlOfs%.8X%.8X', [HInstance, GetCurrentThreadID]); end; {$IFDEF VER120} procedure InitAtomStrings; // Delphi 4 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} {$IFDEF VER130} procedure InitAtomStrings; // Delphi 5 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} {$IFDEF VER140} procedure InitAtomStrings; // Delphi 6 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} {$IFDEF VER150} procedure InitAtomStrings; // Delphi 7 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} {$IFDEF VER170} procedure InitAtomStrings; // Delphi 2005 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} {$IFDEF VER180} procedure InitAtomStrings; // Delphi 2006 begin InitAtomStrings_D5_D6_D7; end; {$ENDIF} begin InitAtomStrings; WindowAtom := GlobalAddAtom(PAnsiChar(WindowAtomString)); ControlAtom := GlobalAddAtom(PAnsiChar(ControlAtomString)); end; procedure DoneControls; begin GlobalDeleteAtom(ControlAtom); ControlAtomString := ''; GlobalDeleteAtom(WindowAtom); WindowAtomString := ''; end; function FindOrCreateWinControlTrap(Control: TWinControl): TWinControlTrap; var i: integer; begin // find or create trap object Result := nil; for i := PendingRecreateWndTrapList.Count - 1 downto 0 do begin if TWinControlTrap(PendingRecreateWndTrapList[i]).FControl = Control then begin Result := TWinControlTrap(PendingRecreateWndTrapList[i]); PendingRecreateWndTrapList.Delete(i); break; { found it } end; end; if Result = nil then Result := TWinControlTrap.Create(Control); end; function InitWndProcW(HWindow: HWnd; Message, WParam, LParam: Longint): Longint; stdcall; function GetObjectInstance(Control: TWinControl): Pointer; var WinControlTrap: TWinControlTrap; begin WinControlTrap := FindOrCreateWinControlTrap(Control); PendingRecreateWndTrapList.Add(WinControlTrap); Result := WinControlTrap.WinControl_ObjectInstance; end; var ObjectInstance: Pointer; begin TAccessWinControl(CreationControl).WindowHandle := HWindow; ObjectInstance := GetObjectInstance(CreationControl); {Controls.InitWndProc converts control to ANSI here by calling SetWindowLongA()!} SetWindowLongW(HWindow, GWL_WNDPROC, Longint(ObjectInstance)); if (GetWindowLongW(HWindow, GWL_STYLE) and WS_CHILD <> 0) and (GetWindowLongW(HWindow, GWL_ID) = 0) then SetWindowLongW(HWindow, GWL_ID, HWindow); SetProp(HWindow, MakeIntAtom(ControlAtom), THandle(CreationControl)); SetProp(HWindow, MakeIntAtom(WindowAtom), THandle(CreationControl)); CreationControl := nil; Result := TWndProc(ObjectInstance)(HWindow, Message, WParam, lParam); end; function IsUnicodeCreationControl(Handle: HWND): Boolean; begin Result := (UnicodeCreationControl <> nil) and (UnicodeCreationControl.HandleAllocated) and (UnicodeCreationControl.Handle = Handle); end; function WMNotifyFormatResult(FromHandle: HWND): Integer; begin if (Win32Platform = VER_PLATFORM_WIN32_NT) and (IsWindowUnicode(FromHandle) or IsUnicodeCreationControl(FromHandle)) then Result := NFR_UNICODE else Result := NFR_ANSI; end; {$ENDIF T2H} // Exported Procedure // ----------------------------------------------------------------------------- procedure TntCustomEdit_CreateWindowHandle(Edit: TCustomEdit; const Params: TCreateParams); var P: TCreateParams; begin if SysLocale.FarEast and not(Win32Platform = VER_PLATFORM_WIN32_NT) and ((Params.Style and ES_READONLY) <> 0) then begin // Work around Far East Win95 API/IME bug. P := Params; P.Style := P.Style and (not ES_READONLY); CreateUnicodeHandle(Edit, P, 'EDIT'); if Edit.HandleAllocated then SendMessage(Edit.Handle, EM_SETREADONLY, Ord(True), 0); end else CreateUnicodeHandle(Edit, Params, 'EDIT'); end; function TntCustomEdit_GetSelText(Edit: TCustomEdit{TNT-ALLOW TCustomEdit}): WideString; begin if Win32PlatformIsUnicode then Result := Copy(TntControl_GetText(Edit), Edit.SelStart + 1, Edit.SelLength) else Result := Edit.SelText end; procedure TntCustomEdit_SetSelText(Edit: TCustomEdit{TNT-ALLOW TCustomEdit}; const Value: WideString); begin if Win32PlatformIsUnicode then SendMessageW(Edit.Handle, EM_REPLACESEL, 0, Longint(PWideChar(Value))) else Edit.SelText := Value; end; procedure SubClassUnicodeControl(Control: TWinControl; Params_Caption: PAnsiChar; IDEWindow: Boolean = False); var WinControlTrap: TWinControlTrap; begin if not IsWindowUnicode(Control.Handle) then raise Exception.Create('TNT Internal Error: SubClassUnicodeControl.Control is not Unicode.'); WinControlTrap := FindOrCreateWinControlTrap(Control); WinControlTrap.SubClassControl(Params_Caption); WinControlTrap.IDEWindow := IDEWindow; end; procedure RegisterUnicodeClass(Params: TCreateParams; out WideWinClassName: WideString; IDEWindow: Boolean = False); const UNICODE_CLASS_EXT = '.UnicodeClass'; var TempClass: TWndClassW; WideClass: TWndClassW; ClassRegistered: Boolean; InitialProc: TFNWndProc; begin if IDEWindow then InitialProc := @InitWndProc else InitialProc := @InitWndProcW; with Params do begin WideWinClassName := WinClassName + UNICODE_CLASS_EXT; ClassRegistered := GetClassInfoW(WindowClass.hInstance, PWideChar(WideWinClassName), TempClass); if (not ClassRegistered) or (TempClass.lpfnWndProc <> InitialProc) then begin if ClassRegistered then Windows.UnregisterClassW(PWideChar(WideWinClassName), WindowClass.hInstance); // Prepare a TWndClassW record WideClass := TWndClassW(WindowClass); WideClass.lpfnWndProc := InitialProc; if not Tnt_Is_IntResource(PWideChar(WindowClass.lpszMenuName)) then begin WideClass.lpszMenuName := PWideChar(WideString(WindowClass.lpszMenuName)); end; WideClass.lpszClassName := PWideChar(WideWinClassName); // Register the UNICODE class if RegisterClassW(WideClass) = 0 then RaiseLastOperatingSystemError; end; end; end; procedure CreateUnicodeHandle(Control: TWinControl; const Params: TCreateParams; const SubClass: WideString; IDEWindow: Boolean = False); var TempSubClass: TWndClassW; WideWinClassName: WideString; Handle: THandle; begin if not (Win32Platform = VER_PLATFORM_WIN32_NT) then begin with Params do TAccessWinControl(Control).WindowHandle := CreateWindowEx(ExStyle, WinClassName, Caption, Style, X, Y, Width, Height, WndParent, 0, WindowClass.hInstance, Param); end else begin // SubClass the unicode version of this control by getting the correct DefWndProc if (SubClass <> '') and GetClassInfoW(Params.WindowClass.hInstance, PWideChar(SubClass), TempSubClass) then TAccessWinControl(Control).DefWndProc := TempSubClass.lpfnWndProc else TAccessWinControl(Control).DefWndProc := @DefWindowProcW; // make sure Unicode window class is registered RegisterUnicodeClass(Params, WideWinClassName, IDEWindow); // Create UNICODE window handle UnicodeCreationControl := Control; try with Params do Handle := CreateWindowExW(ExStyle, PWideChar(WideWinClassName), nil, Style, X, Y, Width, Height, WndParent, 0, WindowClass.hInstance, Param); if Handle = 0 then RaiseLastOperatingSystemError; TAccessWinControl(Control).WindowHandle := Handle; if IDEWindow then SetWindowLongW(Handle, GWL_WNDPROC, GetWindowLong(Handle, GWL_WNDPROC)); finally UnicodeCreationControl := nil; end; SubClassUnicodeControl(Control, Params.Caption, IDEWindow); end; end; function TntControl_IsCaptionStored(Control: TControl): Boolean; begin with TAccessControl(Control) do Result := (ActionLink = nil) or not TAccessControlActionLink(ActionLink).IsCaptionLinked; end; function TntControl_GetStoredText(Control: TControl; const Default: WideString): WideString; var WideCaptionHolder: TWideCaptionHolder; begin WideCaptionHolder := FindWideCaptionHolder(Control, False); if WideCaptionHolder <> nil then Result := WideCaptionHolder.WideCaption else Result := Default; end; procedure TntControl_SetStoredText(Control: TControl; const Value: WideString); begin FindWideCaptionHolder(Control).FWideCaption := Value; TAccessControl(Control).Text := Value; end; function TntControl_GetText(Control: TControl): WideString; var WideCaptionHolder: TWideCaptionHolder; begin if (not Win32PlatformIsUnicode) or ((Control is TWinControl) and TWinControl(Control).HandleAllocated and (not IsWindowUnicode(TWinControl(Control).Handle))) then // Win9x / non-unicode handle Result := TAccessControl(Control).Text else if (not (Control is TWinControl)) then begin // non-windowed TControl WideCaptionHolder := FindWideCaptionHolder(Control, False); if WideCaptionHolder = nil then Result := TAccessControl(Control).Text else Result := GetSyncedWideString(WideCaptionHolder.FWideCaption, TAccessControl(Control).Text); end else if (not TWinControl(Control).HandleAllocated) then begin // NO HANDLE Result := TntControl_GetStoredText(Control, TAccessControl(Control).Text) end else begin // UNICODE & HANDLE SetLength(Result, GetWindowTextLengthW(TWinControl(Control).Handle) + 1); GetWindowTextW(TWinControl(Control).Handle, PWideChar(Result), Length(Result)); SetLength(Result, Length(Result) - 1); end; end; procedure TntControl_SetText(Control: TControl; const Text: WideString); begin if (not Win32PlatformIsUnicode) or ((Control is TWinControl) and TWinControl(Control).HandleAllocated and (not IsWindowUnicode(TWinControl(Control).Handle))) then // Win9x / non-unicode handle TAccessControl(Control).Text := Text else if (not (Control is TWinControl)) then begin // non-windowed TControl with FindWideCaptionHolder(Control) do SetSyncedWideString(Text, FWideCaption, TAccessControl(Control).Text, SetAnsiText) end else if (not TWinControl(Control).HandleAllocated) then begin // NO HANDLE TntControl_SetStoredText(Control, Text); end else if TntControl_GetText(Control) <> Text then begin // UNICODE & HANDLE Tnt_SetWindowTextW(TWinControl(Control).Handle, PWideChar(Text)); Control.Perform(CM_TEXTCHANGED, 0, 0); end; end; function Tnt_SetWindowTextW(hWnd: HWND; lpString: PWideChar): BOOL; begin if Win32PlatformIsUnicode then Result := SetWindowTextW{TNT-ALLOW SetWindowTextW}(hWnd, lpString) else Result := SetWindowTextA{TNT-ALLOW SetWindowTextA}(hWnd, PAnsiChar(AnsiString(lpString))); end; function GetSyncedWideString(var WideStr: WideString; const AnsiStr: AnsiString): WideString; begin if AnsiString(WideStr) <> (AnsiStr) then begin WideStr := AnsiStr; {AnsiStr changed. Keep WideStr in sync.} end; Result := WideStr; end; procedure SetSyncedWideString(const Value: WideString; var WideStr: WideString; const AnsiStr: AnsiString; SetAnsiStr: TSetAnsiStrEvent); begin if Value <> GetSyncedWideString(WideStr, AnsiStr) then begin if (not WideSameStr(Value, AnsiString(Value))) {unicode chars lost in conversion} and (AnsiStr = AnsiString(Value)) {AnsiStr is not going to change} then begin SetAnsiStr(''); {force the change} end; WideStr := Value; SetAnsiStr(Value); end; end; function IsTextMessage(Msg: UINT): Boolean; begin // WM_CHAR is omitted because of the special handling it receives Result := (Msg = WM_SETTEXT) or (Msg = WM_GETTEXT) or (Msg = WM_GETTEXTLENGTH); end; procedure MakeWMCharMsgSafeForAnsi(var Message: TMessage); begin with TWMChar(Message) do begin Assert(Msg = WM_CHAR); //Assert(Unused = 0); // JH: when a Unicode control is embedded under non-Delphi Unicode window // something strange happens if (Unused <> 0) then begin CharCode := (Unused SHL 8) OR CharCode; end; if (CharCode > Word(High(AnsiChar))) then begin Unused := CharCode; CharCode := ANSI_UNICODE_HOLDER; end; end; end; { procedure MakeWMCharMsgSafeForAnsi(var Message: TMessage); begin with TWMChar(Message) do begin Assert(Msg = WM_CHAR); Assert(Unused = 0); if (CharCode > Word(High(AnsiChar))) then begin Unused := CharCode; CharCode := ANSI_UNICODE_HOLDER; end; end; end; } function GetWideCharFromWMCharMsg(Message: TWMChar): WideChar; begin if (Message.CharCode = ANSI_UNICODE_HOLDER) and (Message.Unused <> 0) then Result := WideChar(Message.Unused) else Result := WideChar(Message.CharCode); end; procedure SetWideCharForWMCharMsg(var Message: TWMChar; Ch: WideChar); begin Message.CharCode := Word(Ch); Message.Unused := 0; MakeWMCharMsgSafeForAnsi(TMessage(Message)); end; function Tnt_Is_IntResource(ResStr: LPCWSTR): Boolean; begin Result := HiWord(Cardinal(ResStr)) = 0; end; { TWinControlTrap } constructor TWinControlTrap.Create(AOwner: TComponent); begin FControl := TAccessWinControl(AOwner as TWinControl); inherited Create(nil); FControl.FreeNotification(Self); {$IFNDEF DELPHI_6_UP} WinControl_ObjectInstance := Forms.MakeObjectInstance(FControl.MainWndProc); ObjectInstance := Forms.MakeObjectInstance(Win32Proc); DefObjectInstance := Forms.MakeObjectInstance(DefWin32Proc); {$ELSE} WinControl_ObjectInstance := Classes.MakeObjectInstance(FControl.MainWndProc); ObjectInstance := Classes.MakeObjectInstance(Win32Proc); DefObjectInstance := Classes.MakeObjectInstance(DefWin32Proc); {$ENDIF} end; destructor TWinControlTrap.Destroy; begin {$IFNDEF DELPHI_6_UP} Forms.FreeObjectInstance(ObjectInstance); Forms.FreeObjectInstance(DefObjectInstance); Forms.FreeObjectInstance(WinControl_ObjectInstance); {$ELSE} Classes.FreeObjectInstance(ObjectInstance); Classes.FreeObjectInstance(DefObjectInstance); Classes.FreeObjectInstance(WinControl_ObjectInstance); {$ENDIF} inherited; end; procedure TWinControlTrap.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FControl) and (Operation = opRemove) then begin FControl := nil; if Win32ProcLevel = 0 then Free else DestroyTrap := True; end; end; function TWinControlTrap.IsInSubclassChain(Control: TWinControl): Boolean; var Message: TMessage; begin if SameWndMethod(Control.WindowProc, TAccessWinControl(Control).WndProc) then Result := False { no subclassing } else if SameWndMethod(Control.WindowProc, Self.WindowProc) then Result := True { directly subclassed } else begin TestForNull := True; FoundNull := False; ZeroMemory(@Message, SizeOf(Message)); Message.Msg := WM_NULL; Control.WindowProc(Message); Result := FoundNull; { indirectly subclassed } end; end; procedure TWinControlTrap.SubClassWindowProc; begin if not IsInSubclassChain(FControl) then begin PrevWindowProc := FControl.WindowProc; FControl.WindowProc := Self.WindowProc; end; {$IFDEF TNT_VERIFY_WINDOWPROC} LastVerifiedWindowProc := FControl.WindowProc; {$ENDIF} end; procedure TWinControlTrap.SubClassControl(Params_Caption: PAnsiChar); begin // initialize trap object Handle := FControl.Handle; PrevWin32Proc := Pointer(GetWindowLongW(FControl.Handle, GWL_WNDPROC)); PrevDefWin32Proc := FControl.DefWndProc; // subclass Window Procedures SetWindowLongW(FControl.Handle, GWL_WNDPROC, Integer(ObjectInstance)); FControl.DefWndProc := DefObjectInstance; SubClassWindowProc; // For some reason, caption gets garbled after calling SetWindowLongW(.., GWL_WNDPROC). TntControl_SetText(FControl, TntControl_GetStoredText(FControl, Params_Caption)); end; procedure TWinControlTrap.Win32Proc(var Message: TMessage); begin if (not Finalized) then begin Inc(Win32ProcLevel); try with Message do begin {$IFDEF TNT_VERIFY_WINDOWPROC} if not SameWndMethod(FControl.WindowProc, LastVerifiedWindowProc) then begin SubClassWindowProc; LastVerifiedWindowProc := FControl.WindowProc; end; {$ENDIF} LastWin32Msg := Msg; Result := CallWindowProcW(PrevWin32Proc, Handle, Msg, wParam, lParam); end; finally Dec(Win32ProcLevel); end; if (Win32ProcLevel = 0) and (DestroyTrap) then Free; end else if (Message.Msg = WM_DESTROY) then FControl.WindowHandle := 0 end; procedure TWinControlTrap.DefWin32Proc(var Message: TMessage); function IsChildEdit(AHandle: HWND): Boolean; var AHandleClass: WideString; begin Result := False; if (FControl.Handle = GetParent(Handle)) then begin // child control SetLength(AHandleClass, 255); SetLength(AHandleClass, GetClassNameW(AHandle, PWideChar(AHandleClass), Length(AHandleClass))); Result := StrICompW(PWideChar(AHandleClass), 'EDIT') = 0; end; end; begin with Message do begin if Msg = WM_NOTIFYFORMAT then Result := WMNotifyFormatResult(Message.wParam) else begin if (Msg = WM_CHAR) then begin RestoreWMCharMsg(Message) end; if (Msg = WM_IME_CHAR) and (not _IsShellProgramming) and (not Win32PlatformIsXP) then begin { In Windows XP, DefWindowProc handles WM_IME_CHAR fine for VCL windows. } { Before XP, DefWindowProc will sometimes produce incorrect, non-Unicode WM_CHAR. } { Also, using PostMessageW on Windows 2000 didn't always produce the correct results. } Message.Result := SendMessageW(Handle, WM_CHAR, wParam, lParam) end else if (Msg = WM_IME_CHAR) and (_IsShellProgramming) then begin { When a Tnt control is hosted by a non-delphi control, DefWindowProc doesn't always work even on XP. } if IsChildEdit(Handle) then Message.Result := Integer(PostMessageW(Handle, WM_CHAR, wParam, lParam)) // native edit child control else Message.Result := SendMessageW(Handle, WM_CHAR, wParam, lParam); end else begin if (Msg = WM_DESTROY) then begin UnSubClassUnicodeControl; {The reason for doing this in DefWin32Proc is because in D9, TWinControl.WMDestroy() does a perform(WM_TEXT) operation. } end; { Normal DefWindowProc } Result := CallWindowProcW(PrevDefWin32Proc, Handle, Msg, wParam, lParam); end; end; end; end; procedure TWinControlTrap.WindowProc(var Message: TMessage); var CameFromWindows: Boolean; begin if TestForNull and (Message.Msg = WM_NULL) then FoundNull := True; if (not FControl.HandleAllocated) then FControl.WndProc(Message) else begin CameFromWindows := LastWin32Msg <> WM_NULL; LastWin32Msg := WM_NULL; with Message do begin { if Msg = CM_HINTSHOW then ProcessCMHintShowMsg(Message); } if (not CameFromWindows) and (IsTextMessage(Msg)) then Result := SendMessageA(Handle, Msg, wParam, lParam) else begin if (Msg = WM_CHAR) then begin MakeWMCharMsgSafeForAnsi(Message); end; PrevWindowProc(Message) end; end; end; end; procedure TWinControlTrap.UnSubClassUnicodeControl; begin // remember caption for future window creation if not (csDestroying in FControl.ComponentState) then TntControl_SetStoredText(FControl, TntControl_GetText(FControl)); // restore window procs (restore WindowProc only if we are still the direct subclass) if SameWndMethod(FControl.WindowProc, Self.WindowProc) then FControl.WindowProc := PrevWindowProc; TAccessWinControl(FControl).DefWndProc := PrevDefWin32Proc; SetWindowLongW(FControl.Handle, GWL_WNDPROC, Integer(PrevWin32Proc)); if IDEWindow then DestroyTrap := True else if not (csDestroying in FControl.ComponentState) then // control not being destroyed, probably recreating window PendingRecreateWndTrapList.Add(Self); end; { TWideCaptionHolder } type TListTargetCompare = function (Item, Target: Pointer): Integer; function FindSortedListByTarget(List: TList; TargetCompare: TListTargetCompare; Target: Pointer; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := List.Count - 1; while L <= H do begin I := (L + H) shr 1; C := TargetCompare(List[i], Target); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; function CompareCaptionHolderToTarget(Item, Target: Pointer): Integer; begin if Integer(TWideCaptionHolder(Item).FControl) < Integer(Target) then Result := -1 else if Integer(TWideCaptionHolder(Item).FControl) > Integer(Target) then Result := 1 else Result := 0; end; function FindWideCaptionHolderIndex(Control: TControl; var Index: Integer): Boolean; begin // find control in sorted wide caption list (list is sorted by TWideCaptionHolder.FControl) Result := FindSortedListByTarget(WideCaptionHolders, CompareCaptionHolderToTarget, Control, Index); end; constructor TWideCaptionHolder.Create(AOwner: TControl); var Index: Integer; begin inherited Create(nil); FControl := AOwner; FControl.FreeNotification(Self); // insert into list according sort FindWideCaptionHolderIndex(FControl, Index); WideCaptionHolders.Insert(Index, Self); end; procedure TWideCaptionHolder.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FControl) and (Operation = opRemove) then begin FControl := nil; // JIM 10/04 // BUG Added to fix problem with MDI Apps WideCaptionHolders.Remove(Self); Free; end; end; procedure TWideCaptionHolder.SetAnsiText(const Value: AnsiString); begin TAccessControl(FControl).Text := Value; end; //procedure TWideCaptionHolder.SetAnsiHint(const Value: AnsiString); //begin // FControl.Hint := Value; //end; { TCustomWideEdit } procedure TCustomWideEdit.CreateWindowHandle(const Params: TCreateParams); begin TntCustomEdit_CreateWindowHandle(Self, Params); end; procedure TCustomWideEdit.DefineProperties(Filer: TFiler); begin inherited; // Only need this if we want to have the IDE show wide string (Published) at design time // To include it we need Mikes Unicode package and that is too much overhead // DefineWideProperties(Filer, Self); end; function TCustomWideEdit.GetSelText: WideString; begin Result := TntCustomEdit_GetSelText(Self); end; function TCustomWideEdit.GetText: WideString; begin Result := TntControl_GetText(Self); end; procedure TCustomWideEdit.SelectText(FirstChar, LastChar: integer); begin if IsWindowUnicode(Handle) then PostMessageW(Handle, EM_SETSEL, FirstChar, LastChar) else PostMessage(Handle, EM_SETSEL, FirstChar, LastChar) end; procedure TCustomWideEdit.SetSelText(const Value: WideString); begin TntCustomEdit_SetSelText(Self, Value); end; procedure TCustomWideEdit.SetText(const Value: WideString); begin TntControl_SetText(Self, Value); end; initialization WideCaptionHolders := TObjectList.Create(True); PendingRecreateWndTrapList := TObjectList.Create(False); InitControls; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then DefFontData.Name := 'MS Shell Dlg 2' else DefFontData.Name := 'MS Shell Dlg'; finalization WideCaptionHolders.Free; PendingRecreateWndTrapList.Free; DoneControls; end.
unit E_UtilsGeo; //------------------------------------------------------------------------------ // Модуль гео-подпрограмм //------------------------------------------------------------------------------ // Содержит процедуры и функции для работы с гео-координатами (в широком смысле) // // *** аргументы указываются в градусах, если не указано иное *** //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, Math, T_Points, E_UtilsStr; //------------------------------------------------------------------------------ //! перевести строку WZ в массив координат //! формат строки <широта1>W<долгота1>Z...<широтаN>W<долготаN>Z //------------------------------------------------------------------------------ procedure ParseWZ( const AStr: string; var RArray: TGeoPointArray ); //------------------------------------------------------------------------------ //! рассчитать дистанцию (в километрах) по гео-координатам //------------------------------------------------------------------------------ function GeoLength( const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double ): Double; //------------------------------------------------------------------------------ //! рассчитать дистанцию по гео-координатам //! использует медленный, но точный метод //! результат будет в тех же единицах, что и указанный радиус //! *** принимает аргументы в радианах *** //------------------------------------------------------------------------------ function GeoLengthLongRad( const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double; const ARadius: Double ): Double; //------------------------------------------------------------------------------ //! получить пиксельные координаты по гео-координатам //------------------------------------------------------------------------------ procedure GeoConvToFixed( const AScale: Double; const AFromLat, AFromLong: Double; const ACenterLat, ACenterLong: Double; const ACenterX, ACenterY: Integer; var RToX, RToY: Integer ); //------------------------------------------------------------------------------ //! получить пиксельные координаты по гео-координатам для Graphics32 //! TFloat в Graphics32 = Single //------------------------------------------------------------------------------ procedure GeoConvToFixedSingle( const AScale: Double; const AFromLat, AFromLong: Double; const ACenterLat, ACenterLong: Double; const ACenterX, ACenterY: Integer; var RToX, RToY: Single ); //------------------------------------------------------------------------------ //! получить гео-координатам по пиксельным координатам //------------------------------------------------------------------------------ procedure GeoConvFromFixed( const AScale: Double; const AFromX, AFromY: Integer; const ACenterX, ACenterY: Integer; const ACenterLat, ACenterLong: Double; var RToLat, RToLong: Double ); //------------------------------------------------------------------------------ //! рассчитать угол направления по точкам //------------------------------------------------------------------------------ function DirectionAngle( const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double ): Double; //------------------------------------------------------------------------------ implementation procedure ParseWZ( const AStr: string; var RArray: TGeoPointArray ); var //! PozW, PozZ: integer; //! StrW, StrZ: string; //! WorkStr: string; //------------------------------------------------------------------------------ begin SetLength( RArray, 0 ); WorkStr := AStr; repeat PozW := PosFirstDelimiter( WorkStr, 'W' ); PozZ := PosFirstDelimiter( WorkStr, 'Z' ); if ( PozW = 0 ) or ( PozZ = 0 ) then Exit; StrW := Copy( WorkStr, 1, PozW - 1 ); StrZ := Copy( WorkStr, PozW + 1, PozZ - PozW - 1 ); SetLength( RArray, Length( RArray ) + 1 ); RArray[High( RArray )].Latitude := StrToFloat( StrW ); RArray[High( RArray )].Longitude := StrToFloat( StrZ ); WorkStr := Copy( WorkStr, PozZ + 1, MaxInt ); until False; end; function GeoLength( const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double ): Double; begin //*** 111.225 - это среднее значение ((меридиан + экватор) / 2), в реальности оно будет больше на экваторе //*** но для наших целей такого приближения достаточно Result := 111.225 * Hypot( ALatitudeFrom - ALatitudeTo, ( ALongitudeFrom - ALongitudeTo ) * Cos( DegToRad( ALatitudeFrom ) ) ); end; function GeoLengthLongRad( const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double; const ARadius: Double ): Double; begin Result := ArcCos( Sin( ALatitude1 ) * Sin( ALatitude2 ) + Cos( ALatitude1 ) * Cos( ALatitude2 ) * Cos( ALongitude1 - ALongitude2 ) ) * ARadius; end; procedure GeoConvToFixed( const AScale: Double; const AFromLat, AFromLong: Double; const ACenterLat, ACenterLong: Double; const ACenterX, ACenterY: Integer; var RToX, RToY: Integer ); begin RToX := Trunc( ( AFromLong - ACenterLong ) * AScale ) + ACenterX; RToY := Trunc( ( ACenterLat - AFromLat ) * AScale / Cos( DegToRad( ( AFromLat + ACenterLat ) * 0.5 ) ) ) + ACenterY; end; procedure GeoConvToFixedSingle( const AScale: Double; const AFromLat, AFromLong: Double; const ACenterLat, ACenterLong: Double; const ACenterX, ACenterY: Integer; var RToX, RToY: Single ); begin RToX := Int( ( AFromLong - ACenterLong ) * AScale + ACenterX + 1 ); RToY := Int( ( ACenterLat - AFromLat ) * AScale / Cos( DegToRad( ( AFromLat + ACenterLat ) * 0.5 ) ) + ACenterY + 1 ); end; procedure GeoConvFromFixed( const AScale: Double; const AFromX, AFromY: Integer; const ACenterX, ACenterY: Integer; const ACenterLat, ACenterLong: Double; var RToLat, RToLong: Double ); begin RToLat := Cos( DegToRad( ACenterLat ) ) * ( ACenterY - AFromY ) / AScale + ACenterLat; RToLong := ( AFromX - ACenterX ) / AScale + ACenterLong; end; function DirectionAngle( const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double ): Double; begin Result := ArcTan( ( ALatitudeTo - ALatitudeFrom ) / ( ( ALongitudeTo - ALongitudeFrom ) * Cos( DegToRad( ALatitudeTo ) ) ) ); if ( ALongitudeTo < ALongitudeFrom ) then begin if ( ALatitudeTo > ALatitudeFrom ) then Result := Result + Pi else Result := Result - Pi; end; end; end.
unit BasicMathsTypes; interface type TVector4f = record X, Y, Z, W : single; end; PVector4f = ^TVector4f; TAVector4f = array of TVector4f; PAVector4f = ^TAVector4f; TVector3f = record X, Y, Z : single; end; PVector3f = ^TVector3f; TAVector3f = array of TVector3f; PAVector3f = ^TAVector3f; TVector2f = record U, V : single; end; TAVector2f = array of TVector2f; PAVector2f = ^TAVector2f; TVector3i = record X, Y, Z : integer; end; TAVector3i = array of TVector3i; PAVector3i = ^TAVector3i; TVector3b = record R,G,B : Byte; end; TRectangle3f = record Min, Max : TVector3f; end; TGLMatrixf4 = array[0..3, 0..3] of Single; TVector3fMap = array of array of array of TVector3f; TDistanceFunc = function (_Distance: single): single; implementation end.
{..............................................................................} { Summary Clear Inside - Delete objects within an area defined by user. } { Confirm before deleting. Use on a schematic document. } { Copyright (c) 2003 by Altium Limited } {..............................................................................} {..............................................................................} Var Value : Integer; Begin ResetParameters; AddStringParameter('Action','All'); RunProcess('Sch:Deselect'); ResetParameters; AddStringParameter('Action','InsideArea'); RunProcess('Sch:Select'); ResetParameters; Value := ConfirmNoYes('Confirm Delete'); If Value = True Then Begin RunProcess('Sch:Clear'); End Else Begin AddStringParameter('Action','All'); RunProcess('Sch:Deselect'); End; End. {..............................................................................} {..............................................................................}
unit OilSlickControl; interface uses Math, TypeControl, CircularUnitControl; type TOilSlick = class(TCircularUnit) private FRemainingLifetime: LongInt; function GetRemainingLifetime: LongInt; public property RemainingLifetime: LongInt read GetRemainingLifetime; constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const ARadius: Double; const ARemainingLifetime: LongInt); destructor Destroy; override; end; TOilSlickArray = array of TOilSlick; implementation function TOilSlick.GetRemainingLifetime: LongInt; begin Result := FRemainingLifetime; end; constructor TOilSlick.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const ARadius: Double; const ARemainingLifetime: LongInt); begin inherited Create(AId, AMass, AX, AY, ASpeedX, ASpeedY, AAngle, AAngularSpeed, ARadius); FRemainingLifetime := ARemainingLifetime; end; destructor TOilSlick.Destroy; begin inherited; end; end.
program part; {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} {$H+} {$D-,O+,Q-,R-,S-} {$include isgui.inc} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, dialogsx, define_types,upart,nii_core; const kDefaultBins = 20; procedure WriteHelp; var E, B: string; begin {$IFDEF CPU64} B := '64-bit'; {$ELSE} B := '32-bit'; {$ENDIF} E := extractfilename(ParamStr(0)); writeln('Usage: ',E,'[options] input.nii'); writeln('Version: '+kVers+' by Chris Rorden '+B); writeln(' Uses Siemens PULS/RESP data to remove variance in NIfTI images.'); writeln(' For details, see Deckers et al (2006) www.pubmed.com/17011214.'); writeln('Options:'); writeln(' -1 name of first DICOM volume (else onset time should be stored in input.nii''s header)'); writeln(' -b number of bins (otherwise '+inttostr(kDefaultBins)+')'); writeln(' -d delete volumes'); writeln(' -o name of output file (otherwise ''p'' prefix added to input name)'); writeln(' -p name of physio file'); writeln(' -s slice order (ascending/descending,sequential/interleaved): AS='+inttostr(kAscending)+' AI='+inttostr(kAscendingInterleavedPhilGE)+' DS='+inttostr(kDescending)+' DI='+inttostr(kDescendingInterleavedPhilGE)+' AI[Siemens]='+inttostr(kAscendingInterleavedSiemens)+' DI[Siemens]='+inttostr(kDescendingInterleavedSiemens)); writeln(' -t TR in seconds (otherwise uses TR from input.nii''s header)'); // writeln(' -r create text regressor files instead of adjusted image)'); writeln(' -h show these help instructions)'); writeln('Examples:'); {$IFDEF UNIX} writeln(' '+E+' -p ~/f1/p1.resp -t 1.72 -b 30 -o ~/f1/fixedp1.nii ~/f1/i1.nii'); writeln(' Will automatically load ~/f1/p1.puls if file exists.'); writeln(' '+E+' -p ~/f1/p1.resp -p ~/f1/p1.puls ~/f1/i1.nii'); writeln(' Will create output ~/f1/pi1.nii'); writeln(' '+E+' -p ~/f1/p1.resp -r -p ~/f1/p1.puls ~/f1/i1.nii'); writeln(' Will create text file regressors instead of modified image'); writeln(' '+E+' ~/f1/i1.nii'); writeln(' Assumes a resp/puls file[s] exists with same name as input (~/f1/i1.resp)'); {$ELSE} writeln(' '+E+' -p c:\f1\p1.resp -t 1.72 -b 30 -o c:\f1\fixedp1.nii c:\f1\i1.nii'); writeln(' Will automatically load c:\f1\p1.puls if file exists.'); writeln(' '+E+' -p c:\f1\p1.resp -p c:\f1\p1.puls c:\f1\i1.nii'); writeln(' Will create output c:\f1\pi1.nii'); writeln(' '+E+' -p c:\f1\p1.resp -r -p c:\f1\p1.puls c:\f1\i1.nii'); writeln(' Will create text file regressors instead of modified image'); writeln(' '+E+' c:\f1\i1.nii'); writeln(' Assumes a resp/puls file[s] exists with same name as input (c:\f1\i1.resp)'); {$ENDIF} end; function StoInt(S: string; Default: integer): integer; begin try result := StrToInt(S); except on Exception : EConvertError do result := Default; end; end; function StoFloat(S: string; Default: single): single; begin try result := StrToFloat(S); except on Exception : EConvertError do result := Default; end; end; procedure StrToMemo(lStr: String); var lLen,lPos: integer; lOutStr: string; begin lLen := length(lStr); if lLen < 1 then exit; lOutStr := ''; for lPos := 1 to lLen do begin if lStr[lPos] = kCR then begin Writeln(lOutStr); lOutStr := ''; end else lOutStr := lOutStr + lStr[lPos]; end; if lOutStr <> '' then Writeln(lOutStr); end; procedure DisplayMessages; var i: integer; begin if DebugStrings.Count < 1 then exit; for i := 0 to (DebugStrings.Count-1) do Writeln(DebugStrings[i]); DebugStrings.Clear; end; procedure ProcessParamStr; var lPhysioNames : TStringlist; lImgFilename,lPhysioFilename2,lOutname,lComments,l1stDICOMname: string; lTRsec,lDeleteVols: single; bins,i,lSliceOrder: integer; s,s2: string; lCreateImg,lCreateText:boolean; c: char; begin ExitCode := 1;//assume error - set to zero on successful completion lImgFilename := ''; lOutname := ''; l1stDICOMname := ''; lSliceOrder := kAscending; lCreateImg := true; lCreateText := false; lPhysioNames := TStringlist.Create; i := 1; bins := 20; lTRsec := 0.0; lDeleteVols := 0.0; while i <= ParamCount do begin s := ParamStr(i); if length(s)> 1 then begin if s[1]='-' then begin c := upcase(s[2]); if c='H' then Writehelp else {if c='R' then begin lCreateImg := false; lCreateText := true; end else} if i < paramcount then begin inc(i); s2 := ParamStr(i); case c of '1': l1stDICOMname := s2; 'B': bins := StoInt(s2,bins); 'O': lOutname := s2; 'D': lDeleteVols := StoFloat(s2,lDeleteVols); 'P': lPhysionames.Add(s2); 'S': lSliceOrder := StoInt(s2,lSliceOrder); 'T': lTRsec := StoFloat(s2,lTRsec); end;//case end; end else// starts with '-' lImgFilename := s; end; //length > 1 char inc(i); end; //for each parameter if (lImgFilename='') or (not fileexists(lImgFilename)) then begin writeln('Please specify a valid input image '+lImgFilename); exit; end; if lOutname = '' then lOutname := ChangeFilePrefix(lImgFilename,'p'); if lPhysioNames.count = 0 then lPhysioNames.add(ChangeFileExtX(lImgFilename,'.resp')); if lPhysioNames.count = 1 then begin if UpCaseExt(lPhysioNames[0]) = '.PULS' then lPhysioFilename2 := (changefileext(lPhysioNames[0],'.resp')) else lPhysioFilename2 := (changefileext(lPhysioNames[0],'.puls')); if fileexists(lPhysioFilename2) then lPhysioNames.add(lPhysioFilename2); end; if not fileexists(lPhysioNames[0]) then begin writeln('Please specify a valid physio file '+lPhysioNames[0]); exit; end; lComments := ApplyPart( lImgFilename,lOutname,l1stDICOMname, lPhysioNames,bins,lSliceOrder,lTRsec,lDeleteVols,lCreateImg,lCreateText); //ApplyPart( lImg,Outname{opt},l1stDICOMname{optional}: string; lPhysionames: TStrings; lBins,lSliceOrder : integer; lTRsec,lDeleteVols: single; lImgOut,lTextOut:boolean): string; lPhysioNames.free; DisplayMessages; StrToMemo(lComments); ExitCode := 0; end; {$R *.res} begin // quick check parameters {$IFDEF GUI} showmsg('Compiler error: currently GUI is defined. Please edit isgui.inc');{$ENDIF} // parse parameters if (ParamCount = 0) then WriteHelp else ProcessParamStr; end.
{$I Directives.inc} unit UDirChangeNotifier; interface uses Windows, SysUtils, Classes; type TDirChangeNotifier = class; { Liste des notifications possibles } TDirChangeNotification = (dcnFileAdd, dcnFileRemove, dcnRenameFile, dcnRenameDir, dcnModified, dcnLastWrite, dcnLastAccess, dcnCreationTime); TDirChangeNotifications = set of TDirChangeNotification; { Evenement de notification de changement } TDirChangeEvent = procedure (Sender: TDirChangeNotifier; const FileName, OtherFileName: WideString; Action: TDirChangeNotification) of object; TDirChangeNotifier = class(TThread) private { Dossier à surveiller } FDir: WideString; { Handle du dossier } FDirHandle: THandle; { Liste dee notifications } FNotifList: TDirChangeNotifications; { Evenement de fin } FTermEvent: THandle; { Structure d'attente de notification } FOverlapped: TOverlapped; { Evenement } FOnChange: TDirChangeEvent; FFileName: WideString; FOtherFileName: WideString; FAction: TDirChangeNotification; protected function WhichAttrChanged(const AFileName: WideString): TDirChangeNotification; procedure Execute; override; procedure DoChange; public constructor Create(const ADirectory: WideString; WantedNotifications: TDirChangeNotifications); destructor Destroy; override; procedure Terminate; reintroduce; property OnChange: TDirChangeEvent read FOnChange write FOnChange; end; const { Constantes pour CreateFile() } FILE_LIST_DIRECTORY = $0001; FILE_READ_ATTRIBUTES = $0080; { Liste des notifications } CNotificationFilters: array[TDirChangeNotification] of Cardinal = (0, 0, FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_LAST_ACCESS, FILE_NOTIFY_CHANGE_CREATION); { Constante de toutes les notifications } CAllNotifications: TDirChangeNotifications = [dcnFileAdd, dcnFileRemove, dcnRenameFile, dcnRenameDir, dcnModified, dcnLastWrite, dcnLastAccess, dcnCreationTime]; implementation constructor TDirChangeNotifier.Create(const ADirectory: WideString; WantedNotifications: TDirChangeNotifications); begin inherited Create(False); FreeOnTerminate := True; FDir := ExcludeTrailingPathDelimiter(ADirectory); FNotifList := WantedNotifications; end; destructor TDirChangeNotifier.Destroy; begin // inherited Destroy; end; function FileTimeToDateTime(FileTime: TFileTime): TDateTime; var SysTime: TSystemTime; TimeZoneInfo: TTimeZoneInformation; Bias: Double; begin FileTimeToSystemTime(FileTime, SysTime); GetTimeZoneInformation(TimeZoneInfo); Bias := TimeZoneInfo.Bias / 1440; // = 60 * 24 Result := SystemTimeToDateTime(SysTime) - Bias; end; function TDirChangeNotifier.WhichAttrChanged(const AFileName: WideString): TDirChangeNotification; var hFile: THandle; FCreation, FModification, FAccess: TFileTime; Creation, Modification, Access: TDateTime; begin {>> Lecture des dates du fichier et conversion en TDateTime } hFile := CreateFileW(PWideChar(AFileName), FILE_READ_ATTRIBUTES, FILE_SHARE_READ or FILE_SHARE_DELETE or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); {>> Y'a des fichiers que Windows modifie mais qu'on ne peut pas lire ... } if hFile = 0 then begin Result := dcnModified; Exit; end; GetFileTime(hFile, @FCreation, @FAccess, @FModification); Creation := FileTimeToDateTime(FCreation); Access := FileTimeToDateTime(FAccess); Modification := FileTimeToDateTime(FModification); {>> Détermine l'heure la plus proche du temps actuel (moins de 20 secondes de décalage sinon on considère que ce n'est pas l'heure qui a déclenché l'évenement) } if Now - Access <= 20.0 then Result := dcnLastAccess else if Now - Modification <= 20.0 then Result := dcnLastWrite else if Now - Creation <= 20.0 then Result := dcnCreationTime {>> Sinon, on considère que c'est la taille du fichier, donc que celui-ci à été modifié } else Result := dcnModified; {>> Libère le fichier } CloseHandle(hFile); end; procedure TDirChangeNotifier.Execute; var Buffer: array[0..4095] of Byte; BytesReturned: Cardinal; WaitHandles: array[0..1] of THandle; NotifyFilter, I, Next, Action, FileNameLength: Cardinal; FileName: WideString; FmtSettings: TFormatSettings; N: TDirChangeNotification; begin {>> Création des évenements } FTermEvent := CreateEvent(nil, True, False, nil); FillChar(FOverlapped, SizeOf(TOverlapped), 0); FOverlapped.hEvent := CreateEvent(nil, True, False, nil); {>> Ouverture du dossier } FDirHandle := CreateFileW(PWideChar(FDir), FILE_LIST_DIRECTORY, FILE_SHARE_READ or FILE_SHARE_DELETE or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OVERLAPPED, 0); {>> Création du tableau de handles } WaitHandles[0] := FTermEvent; WaitHandles[1] := FOverlapped.hEvent; GetLocaleFormatSettings(LOCALE_USER_DEFAULT, FmtSettings); {>> Création du filtre } NotifyFilter := 0; for N := Low(TDirChangeNotification) to High(TDirChangeNotification) do if N in FNotifList then Inc(NotifyFilter, CNotificationFilters[N]); {>> Boucle du thread } while True do begin {>> Demande de lecture des évenements du dossier } ReadDirectoryChangesW(FDirHandle, @Buffer, SizeOf(Buffer), True, NotifyFilter, nil, @FOverlapped, nil); {>> Attente de qqch ou de la fin } if WaitForMultipleObjects(2, @WaitHandles, False, INFINITE) = WAIT_OBJECT_0 then Break; {>> Récupération du nombre d'octets reçus } GetOverlappedResult(FDirHandle, FOverlapped, BytesReturned, False); {>> Lecture du buffer } I := 0; repeat {>> Offset vers le suivant } Move(Buffer[I], Next, 4); {>> Action effectuée } Move(Buffer[I + 4], Action, 4); {>> Transcription de Action en FAction } case Action of FILE_ACTION_ADDED: FAction := dcnFileAdd; FILE_ACTION_REMOVED: FAction := dcnFileRemove; FILE_ACTION_MODIFIED: FAction := dcnModified; // Ici: on suppose qu'il s'agit d'un fichier FILE_ACTION_RENAMED_OLD_NAME, FILE_ACTION_RENAMED_NEW_NAME: FAction := dcnRenameFile; end; {>> Nom de fichier } Move(Buffer[I + 8], FileNameLength, 4); { "div 2" car Delphi et windows ne gèrent pas la taille des WideString de la même manière. Pour delphi, c'est le nombre de caractères, pour windows, c'est la taille en octets } SetLength(FileName, FileNameLength div 2); Move(Buffer[I + 12], FileName[1], FileNameLength); {>> Regarde si c'est vraiment la taille ou bien les dates du fichier car la notification générée est la même :-( } if (FAction = dcnModified) and FileExists(FDir + '\' + FileName) then FAction := WhichAttrChanged(FDir + '\' + FileName); {>> Choix du nom de fichier à remplir } if Action = FILE_ACTION_RENAMED_NEW_NAME then begin FOtherFileName := FDir + '\' + FileName; if DirectoryExists(FOtherFileName) then FAction := dcnRenameDir; end else begin FFileName := FDir + '\' + FileName; FOtherFileName := ''; end; {>> Notification si besoin } if (Action <> FILE_ACTION_RENAMED_OLD_NAME) and (FAction in FNotifList) then Synchronize(DoChange); {>> Passe au suivant } Inc(I, Next); until Next = 0; end; {>> Libération des évenements } CloseHandle(FTermEvent); FTermEvent := 0; CloseHandle(FOverlapped.hEvent); {>> Fermeture du dossier } CloseHandle(FDirHandle); end; procedure TDirChangeNotifier.Terminate; begin if FTermEvent <> 0 then SetEvent(FTermEvent); end; procedure TDirChangeNotifier.DoChange; begin if Assigned(FOnChange) then FOnChange(Self, FFileName, FOtherFileName, FAction); end; end.
unit Empresa; interface uses System.Classes, System.Generics.Collections, // Aurelius.Mapping.Attributes, Aurelius.Types.Blob, Aurelius.Types.Nullable, Aurelius.Types.Proxy, // Contador, EmpresaEndereco; type [Entity] [Table('EMPRESA')] [Id('Id', TIdGenerator.IdentityOrSequence)] TEmpresa = class private FID: Integer; FID_CONTADOR: Integer; FRAZAO_SOCIAL: string; FFANTASIA: string; FCNPJ: string; FContador: TContador; FEnderecoLista: TObjectList<TEmpresaEndereco>; public [Column('ID', [TColumnProp.Required, TColumnProp.NoInsert, TColumnProp.NoUpdate])] property Id: Integer read FID write FID; [Column('ID_CONTADOR', [])] property IdContador: Integer read FID_CONTADOR write FID_CONTADOR; [Column('RAZAO_SOCIAL', [], 100)] property RazaoSocial: string read FRAZAO_SOCIAL write FRAZAO_SOCIAL; [Column('FANTASIA', [], 100)] property Fantasia: string read FFANTASIA write FFANTASIA; [Column('CNPJ', [], 100)] property Cnpj: string read FCNPJ write FCNPJ; [Association([], CascadeTypeAllButRemove)] [JoinColumn('ID_CONTADOR', [], 'ID')] property Contador: TContador read FContador write FContador; [ManyValuedAssociation([], CascadeTypeAll)] [ForeignJoinColumn('ID', [], 'ID_EMPRESA')] property EnderecoLista: TObjectList<TEmpresaEndereco> read FEnderecoLista write FEnderecoLista; end; implementation initialization RegisterEntity(TEmpresa); end.
unit Objekt.DHLLabelDataList; interface uses System.SysUtils, System.Classes, Objekt.DHLLabelData, Objekt.DHLBaseList, System.Contnrs; type TDHLLabelDataList = class(TDHLBaseList) private function getDHLLabelData(Index: Integer): TDHLLabelData; public constructor Create; override; destructor Destroy; override; property Item[Index: Integer]: TDHLLabelData read getDHLLabelData; function Add: TDHLLabelData; end; implementation { TDHLLabelDataList } constructor TDHLLabelDataList.Create; begin inherited; end; destructor TDHLLabelDataList.Destroy; begin inherited; end; function TDHLLabelDataList.getDHLLabelData(Index: Integer): TDHLLabelData; begin Result := nil; if Index > fList.Count -1 then exit; Result := TDHLLabelData(fList[Index]); end; function TDHLLabelDataList.Add: TDHLLabelData; begin Result := TDHLLabelData.Create; fList.Add(Result); end; end.
unit BaseDAO; interface uses Classes, SqlExpr, DBXCommon; type {$MethodInfo ON} TBaseDAO = class(TPersistent) protected FComm: TDBXCommand; procedure PrepareCommand; end; implementation uses uSCPrincipal; { TBaseDAO } { TBaseDAO } procedure TBaseDAO.PrepareCommand; begin if not(Assigned(FComm)) then begin if not(SCPrincipal.ConnTopCommerce.Connected) then SCPrincipal.ConnTopCommerce.Open; FComm := SCPrincipal.ConnTopCommerce.DBXConnection.CreateCommand; FComm.CommandType := TDBXCommandTypes.DbxSQL; if not(FComm.IsPrepared) then FComm.Prepare; end; end; end.
unit Server.Repository; interface uses System.SysUtils, System.Classes, Data.DB, MemDS, DBAccess, Uni, RDQuery, RDSQLConnection, System.Generics.Collections, System.JSON, Spring.Container.Common, Spring.Collections, Spring.Logging, Common.Entities.Player, Common.Entities.Card, Common.Entities.Round, Common.Entities.Bet, Server.Entities.Game, Common.Entities.GameSituation, Server.WIRL.Response, Server.Controller.Game; type IRepository= interface ['{52DC4164-4347-4D49-9CB3-D19E910062D9}'] function GetPlayers:TPlayers<TPlayer>; function RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse; function DeletePlayer(const APlayerName:String):TBaseRESTResponse; function GetAllCards:TCards; function NewGame:TExtendedRESTResponse; function GetGame:TGame; function GetGameSituation: TGameSituation<TPlayer>; procedure NewGameInfo(const AMessage: String); function GiveUp: TBaseRESTResponse; function GetBets:TBets; function NewBet(const AParam: TBet): TBaseRESTResponse; function SetKing(ACard: TCardKey): TBaseRESTResponse; function ChangeCards(ACards: TCards): TBaseRESTResponse; function GetRound:TGameRound; function NewRound: TBaseRESTResponse; function Turn(AName:String; ACard:TCardKey): TBaseRESTResponse; end; TRepository = class(TInterfacedObject, IRepository) private FLastError: String; FPlayers:TPlayers<TPlayer>; FGames:TGames; FGameController:TGameController; FLogger: ILogger; function GetActGame: TGame; public constructor Create; destructor Destroy; override; function GetPlayers:TPlayers<TPlayer>; function RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse; function DeletePlayer(const APlayerName:String):TBaseRESTResponse; function GetAllCards:TCards; function NewGame:TExtendedRESTResponse; function GetGame:TGame; function GetGameSituation: TGameSituation<TPlayer>; procedure NewGameInfo(const AMessage: String); function GetBets:TBets; function NewBet(const ABet: TBet): TBaseRESTResponse; function SetKing(ACard: TCardKey): TBaseRESTResponse; function ChangeCards(ACards: TCards): TBaseRESTResponse; function GetRound:TGameRound; function NewRound: TBaseRESTResponse; function Turn(AName:String; ACard:TCardKey): TBaseRESTResponse; function GiveUp: TBaseRESTResponse; property ActGame:TGame read GetActGame; property GameController:TGameController read FGameController; property LastError: String read FLastError; property Logger: ILogger read FLogger write FLogger; end; implementation uses Math, Classes.Dataset.Helpers, Server.Configuration, Server.Register; { TRepository } {======================================================================================================================} function TRepository.ChangeCards(ACards: TCards): TBaseRESTResponse; begin try if not Assigned(FGameController) then raise Exception.Create('No active Game'); FGameController.ChangeCards(ACards); Result:=TBaseRESTResponse.BuildResponse(True); except on E:Exception do begin Result:=TBaseRESTResponse.BuildResponse(False,E.Message); Result.Message:=E.Message; end; end; end; constructor TRepository.Create; {======================================================================================================================} var configuration: TConfiguration; compNameSuffix: String; begin Logger := GetContainer.Resolve<ILogger>; Logger.Enter('TRepository.Create'); configuration := GetContainer.Resolve<TConfiguration>; compNameSuffix := IntToStr(Integer(Pointer(TThread.Current))) + '_' + IntToStr(TThread.GetTickCount); FPlayers:=TPlayers<TPlayer>.Create(True); (* FPlayers.Add(TPlayer.Create('HANNES')); FPlayers.Add(TPlayer.Create('WOLFGANG')); FPlayers.Add(TPlayer.Create('LUKI')); FPlayers.Add(TPlayer.Create('ANDI')); *) FGames:=TGames.Create(True); Logger.Leave('TRepository.Create'); end; {======================================================================================================================} destructor TRepository.Destroy; {======================================================================================================================} begin Logger.Enter('TRepository.Destroy'); FreeAndNil(FPlayers); FreeAndNil(FGames); FreeAndNil(FGameController); inherited; Logger.Leave('TRepository.Destroy'); end; function TRepository.GetActGame: TGame; begin Result:=FGames.PeekOrDefault; end; function TRepository.GetAllCards: TCards; begin Result:=ALLCards; end; function TRepository.GetBets: TBets; begin if Assigned(ActGame) then Result:=ActGame.Bets else Result:=Nil; end; function TRepository.GetGame: TGame; var g:TGame; begin g:=ActGame; if Assigned(g) then Result:=g else Result:=nil; end; function TRepository.GetGameSituation: TGameSituation<TPlayer>; begin if Assigned(ActGame) then begin Result:=ActGame.Situation.Clone; end else begin Result:=TGameSituation<TPlayer>.Create; Result.State:=gsNone; Result.Players:=FPlayers.Clone<TPlayer>; if Result.Players.Count<4 then Result.GameInfo.Add('Wir warten noch auf Spieler') else Result.GameInfo.Add('Starte das Spiel') end; end; function TRepository.GetPlayers: TPlayers<TPlayer>; begin Logger.Enter('TRepository.GetPlayers'); Result:=Nil; try Result:=FPlayers; except on E: Exception do Logger.Error('TRepository.GetPlayers :: Exception: ' + E.Message); end; Logger.Leave('TRepository.GetPlayers'); end; function TRepository.GetRound: TGameRound; var g:TGame; begin g:=ActGame; if Assigned(g) then Result:=g.ActRound else raise Exception.Create('No active game'); end; function TRepository.GiveUp: TBaseRESTResponse; begin try if not Assigned(FGameController) then Result:=TBaseRESTResponse.BuildResponse(False,'No active Game') else begin FGameController.GiveUp; Result:=TBaseRESTResponse.BuildResponse(True,ActGame.Situation.Gamer+' fold'); end; except on E:Exception do Result:=TBaseRESTResponse.BuildResponse(False,E.Message) end; end; function TRepository.NewBet(const ABet: TBet): TBaseRESTResponse; var s:String; begin try if not Assigned(FGameController) then Result:=TBaseRESTResponse.BuildResponse(False,'No active Game') else begin if ActGame.Situation.State=gsBidding then s:=FGameController.NewBet(ABet) else if ActGame.Situation.State=gsFinalBet then s:=FGameController.FinalBet(ABet) else raise Exception.Create('It is not time to bid'); Result:=TBaseRESTResponse.BuildResponse(True); Result.Message:='Turn is on '+s; end; except on E:Exception do begin Result:=TBaseRESTResponse.BuildResponse(False,E.Message); Result.Message:=E.Message; end; end; end; function TRepository.NewGame: TExtendedRESTResponse; var g:TGame; i: Integer; begin if FPlayers.Count=4 then begin if Assigned(ActGame) and ActGame.Active then Result:=TExtendedRESTResponse.BuildResponse(False,'A game is just active') else begin g:=TGame.Create(FPlayers); if Assigned(ActGame) then begin g.Situation.Beginner:=ActGame.Situation.TurnOn; for i:=0 to ActGame.Doubles.Count-1 do g.Doubles.Add(ActGame.Doubles[i]); end else g.Situation.Beginner:=FPlayers[0].Name; FGames.Push(g); g.Situation.GameNo:=FGames.Count; Result:=TExtendedRESTResponse.BuildResponse(True); Result.Message:=g.Situation.Beginner; Result.ID:=g.ID; FreeAndNil(FGameController); FGameController:=TGameController.Create(g); FGameController.Shuffle; g.Situation.State:=gsBidding; g.Situation.BestBet:=0; g.Situation.GameType:=''; g.Situation.Gamer:=''; g.Situation.TurnOn:=g.Situation.Beginner; end; end else Result:=TExtendedRESTResponse.BuildResponse(False,'Needs 4 registered players to create a game'); end; procedure TRepository.NewGameInfo(const AMessage: String); begin if Assigned(ActGame) then ActGame.Situation.GameInfo.Add(AMessage); end; function TRepository.NewRound: TBaseRESTResponse; begin try if not Assigned(FGameController) then Result:=TBaseRESTResponse.BuildResponse(False,'No active Game') else begin FGameController.NewRound; Result:=TBaseRESTResponse.BuildResponse(True,'Beginner is '+ActGame.ActRound.TurnOn); end; except on E:Exception do Result:=TBaseRESTResponse.BuildResponse(False,E.Message) end; end; function TRepository.RegisterPlayer(const APlayer:TPlayers<TPlayer>):TBaseRESTResponse; var p:TPlayer; begin Result:=nil; Logger.Enter('TRepository.RegisterPlayer'); try for p in APlayer do begin if Assigned(FPlayers.Find(p.Name)) then begin Logger.Error('TRepository.RegisterPlayer :: Exception: ' + p.Name +' is just a registered Player'); Result:=TBaseRESTResponse.BuildResponse(False,p.Name +' is just a registered Player') end else if FPlayers.Count>=4 then begin Logger.Error('TRepository.RegisterPlayer :: Exception: cannot accept more than 4 players'); Result:=TBaseRESTResponse.BuildResponse(False,'Cannot accept more than 4 players') end else begin FPlayers.Add(TPlayer.Create(p.Name)); Result:=TBaseRESTResponse.BuildResponse(True) end; end; finally // APlayer.Free; end; if Result=nil then Result:=TBaseRESTResponse.BuildResponse(True); Logger.Leave('TRepository.RegisterPlayer'); end; function TRepository.SetKing(ACard: TCardKey): TBaseRESTResponse; begin try if not Assigned(FGameController) then raise Exception.Create('No active Game'); FGameController.SetKing(ACard); Result:=TBaseRESTResponse.BuildResponse(True); except on E:Exception do begin Result:=TBaseRESTResponse.BuildResponse(False,E.Message); Result.Message:=E.Message; end; end; end; function TRepository.Turn(AName: String; ACard: TCardKey): TBaseRESTResponse; var nextTurnOn:String; i: Integer; begin if not Assigned(FGameController) then Result:=TBaseRESTResponse.BuildResponse(False,'No active Game') else begin nextTurnOn:=FGameController.Turn(AName,ACard); if not ActGame.Active then begin for i:=0 to FPlayers.Count-1 do FPlayers[i].Score:=ActGame.Players[i].Score; end; Result:=TBaseRESTResponse.BuildResponse(True); Result.Message:=nextTurnOn end; end; function TRepository.DeletePlayer(const APlayerName:String):TBaseRESTResponse; var p2:TPlayer; begin Result:=nil; Logger.Enter('TRepository.DeletePlayer'); p2:=FPlayers.Find(APlayerName); if Assigned(p2) then begin FPlayers.Remove(p2); NewGameInfo(p2.Name+' hat Spiel verlassen'); if Assigned(ActGame) and ActGame.Active then begin ActGame.Active:=False; NewGameInfo('Laufendes Spiel wurde abgebrochen'); end; Result:=TBaseRESTResponse.BuildResponse(True); end else Result:=TBaseRESTResponse.BuildResponse(False,APlayerName +' is not a registered Player'); if Result=nil then Result:=TBaseRESTResponse.BuildResponse(True); Logger.Leave('TRepository.DeletePlayer'); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ArchiveUtilsTests; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Classes, SysUtils, AbUtils, DB, DBXUtils, ArchiveUtils, SqlExpr; const cnTestFileName = 'DUnitTestFile'; type // Test methods for ArchiveUtils unit TestArchiveUtils = class(TTestCase) private procedure DoCreateFromStreamTest(const AFileName: string; const AItemCount: Integer); overload; procedure DoCreateFromStreamTest(const AStream: TStream; const AFileName: string; const AItemCount: Integer); overload; procedure DoCreateFromFieldTest(const AField: TField; const AFileName: string; const AItemCount: Integer); procedure DoCheckArchiveStreamTest(const AFileName: string); procedure DoCheckArchiveStringTest(const AFileName: string); procedure DoCompressAndEncodeStringTest(AType: TAbArchiveType); procedure VerifyCompressedEncodedString(const AString: string; const AExpected: string; AType: TAbArchiveType; AFileName: string = cnTestFileName); procedure DoCompressAndEncodeStreamTest(AType: TAbArchiveType); procedure DoCompressTest(AType: TAbArchiveType); procedure DoDecodeAndUnCompressStreamTest(AType: TAbArchiveType); procedure DoUnCompressStreamTest(AType: TAbArchiveType); procedure DoUnCompressBytesTest(AType: TAbArchiveType); procedure VerifyCompressedString(AArchive: TArchive; const AExpected: string); procedure DoCompressToStreamTest(AType: TAbArchiveType); public procedure SetUp; override; procedure TearDown; override; procedure TestArchive(const AArchive: TArchive; const AFileName: string; const AItemCount: integer); published procedure CreateFromStreamTest; procedure CompressAndEncodeStringTest; procedure CompressAndEncodeStreamTest; procedure CompressTest; procedure CompressToStreamTest; procedure EncodeTest; procedure DecodeAndUnCompressStreamTest; procedure DecodeTest; procedure UnCompressBytesTest; procedure UnCompressStreamTest; procedure CheckArchiveStreamTest; procedure CheckArchiveStringTest; procedure OpenArchiveTest; procedure FileExtFromArchiveTypeTest; procedure BZip2Test; // procedure QCAttachmentTest; // procedure BlobArchiveTest(AConnection: TSQLConnection; ASql, // AFieldName: string; AItemCount: integer); end; const cnTestRoot = 'D:\cdn\trunk\cdn\dev\qualitycentral\Delphi\test\'; cnTestZip = cnTestRoot + 'test.zip'; cnTestExe = cnTestRoot + 'test.exe'; cnTestTar = cnTestRoot + 'test.tar'; cnTestGZip = cnTestRoot + 'test.tar.gz'; cnTestBZip = cnTestRoot + 'test.tar.bz'; cnTestCab = cnTestRoot + 'test.cab'; implementation uses AbZipTyp, EncdDecd, Windows, AbCabTyp, AbZipKit, AbBrowse, Math, AbArcTyp, AbBzip2Typ; const cnTestString = 'DUnit Compress and encode test'; procedure TestArchiveUtils.DoCheckArchiveStringTest(const AFileName: string); var lString: string; lStream: TFileStream; lEncoded: TStringStream; begin lStream := TFileStream.Create(AFileName, fmOpenRead); try lEncoded := TStringStream.Create; try EncodeStream(lStream, lEncoded); lString := lEncoded.DataString; finally lEncoded.Free; end; finally lStream.Free; end; CheckArchive(lString); CheckArchive(lString, ExtractFileName(AFileName)); end; procedure TestArchiveUtils.DoCheckArchiveStreamTest(const AFileName: string); var lStream: TFileStream; begin lStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try CheckArchive(lStream); lStream.Position := 0; CheckArchive(lStream, ExtractFileName(AFileName)); finally lStream.Free; end; end; procedure TestArchiveUtils.BZip2Test; procedure DoTest(AType: TAbArchiveType); var lZipKit: TAbZipKit; lStream: TStringStream; lFileName: string; lMS: TMemoryStream; begin lFileName := 'd:\temp\test'; if AType = atBzip2 then lFileName := lFileName + '.bz2' else lFileName := lFileName + '.tbz'; lStream := TStringStream.Create('Test'); try lZipKit := TAbZipKit.Create(nil); try lZipKit.ArchiveType := AType; lZipKit.ForceType := True; lZipKit.TarAutoHandle := True; lZipKit.FileName := lFileName; lZipKit.AddFromStream('Test', lStream); lZipKit.Save; finally lZipKit.Free; end; lMS := TMemoryStream.Create; try lMS.LoadFromFile(lFileName); lMS.Position := 0; lZipKit := TAbZipKit.Create(nil); try lZipKit.TarAutoHandle := True; lZipKit.Stream := lMS; lStream.Clear; lZipKit.ExtractToStream(lZipKit.Items[0].FileName, lStream); CheckEqualsString('Test', lStream.DataString); finally lZipKit.Free; end; finally lMS.Free; end; finally lStream.Free; end; end; begin DoTest(atBzippedTar); //Stream Read Error on AbDetermineArcType call DoTest(atBzip2); end; procedure TestArchiveUtils.CheckArchiveStreamTest; begin DoCheckArchiveStreamTest(cnTestZip); DoCheckArchiveStreamTest(cnTestExe); DoCheckArchiveStreamTest(cnTestTar); DoCheckArchiveStreamTest(cnTestGzip); DoCheckArchiveStreamTest(cnTestBzip); DoCheckArchiveStreamTest(cnTestCab); end; procedure TestArchiveUtils.CheckArchiveStringTest; begin DoCheckArchiveStringTest(cnTestZip); DoCheckArchiveStringTest(cnTestExe); DoCheckArchiveStringTest(cnTestTar); DoCheckArchiveStringTest(cnTestGzip); DoCheckArchiveStringTest(cnTestBzip); DoCheckArchiveStringTest(cnTestCab); end; procedure TestArchiveUtils.VerifyCompressedString(AArchive: TArchive; const AExpected: string); var lStr: TStringStream; begin lStr := TStringStream.Create; try AArchive.ExtractToStream(AArchive.Items[0].FileName, lStr); CheckEqualsString(AExpected, lStr.DataString); finally lStr.Free; end; end; procedure TestArchiveUtils.VerifyCompressedEncodedString(const AString: string; const AExpected: string; AType: TAbArchiveType; AFileName: string = cnTestFileName); var lMemStream: TMemoryStream; lStringStream: TStringStream; lArc: TArchive; begin lStringStream := TStringStream.Create(AString); try lMemStream := TMemoryStream.Create; try DecodeStream(lStringStream, lMemStream); lMemStream.Position := 0; lArc := CreateFromStream(lMemStream, AFileName); try VerifyCompressedString(lArc, AExpected); finally lArc.Free; end; finally lMemStream.Free; end; finally lStringStream.Free; end; end; procedure TestArchiveUtils.DoCompressAndEncodeStringTest(AType: TAbArchiveType); var lCompressed: string; begin lCompressed := CompressAndEncode(cnTestString, cnTestFileName, AType); VerifyCompressedEncodedString(lCompressed, cnTestString, AType); end; procedure TestArchiveUtils.DoCompressTest(AType: TAbArchiveType); var lArc: TArchive; lStream: TStringStream; begin lStream := TStringStream.Create(cnTestString); try lArc := Compress(lStream, cnTestFileName, AType); try VerifyCompressedString(lArc, cnTestString); finally lArc.Free; end; finally lStream.Free; end; end; procedure TestArchiveUtils.DoCompressToStreamTest(AType: TAbArchiveType); var lArc: TArchive; lStringStream: TStringStream; lMemStream: TMemoryStream; begin lStringStream := TStringStream.Create(cnTestString); try lMemStream := TMemoryStream.Create; try CompressToStream(lStringStream, lMemStream, cnTestFileName, AType); lArc := CreateFromStream(lMemStream); try VerifyCompressedString(lArc, cnTestString); finally lArc.Free; end; finally lMemStream.Free; end; finally lStringStream.Free; end; end; procedure TestArchiveUtils.DoCompressAndEncodeStreamTest(AType: TAbArchiveType); var lCompressed: string; lStream: TStringStream; begin lStream := TStringStream.Create(cnTestString); try lCompressed := CompressAndEncode(lStream, cnTestFileName, AType); finally lStream.Free; end; VerifyCompressedEncodedString(lCompressed, cnTestString, AType); end; procedure TestArchiveUtils.CompressAndEncodeStringTest; begin DoCompressAndEncodeStringTest(atZip); DoCompressAndEncodeStringTest(atGzip); DoCompressAndEncodeStringTest(atTar); DoCompressAndEncodeStringTest(atBzip2); DoCompressAndEncodeStringTest(atGzippedTar); DoCompressAndEncodeStringTest(atBzippedTar); //DoCompressAndEncodeStringTest(atCab); end; procedure TestArchiveUtils.CompressTest; begin DoCompressTest(atZip); DoCompressTest(atGzip); DoCompressTest(atTar); DoCompressTest(atBzip2); DoCompressTest(atGzippedTar); DoCompressTest(atBzippedTar); end; procedure TestArchiveUtils.CompressToStreamTest; begin DoCompressToStreamTest(atZip); DoCompressToStreamTest(atGzip); DoCompressToStreamTest(atTar); DoCompressToStreamTest(atBzip2); DoCompressToStreamTest(atGzippedTar); DoCompressToStreamTest(atBzippedTar); end; procedure TestArchiveUtils.CompressAndEncodeStreamTest; begin DoCompressAndEncodeStreamTest(atZip); DoCompressAndEncodeStreamTest(atGzip); DoCompressAndEncodeStreamTest(atTar); DoCompressAndEncodeStreamTest(atGzippedTar); DoCompressAndEncodeStreamTest(atBzippedTar); DoCompressAndEncodeStreamTest(atBzip2); //DoCompressAndEncodeStreamTest(atCab); end; procedure TestArchiveUtils.FileExtFromArchiveTypeTest; const cnExpected: array[Low(TAbArchiveType)..High(TAbArchiveType)] of string = ('', '.zip', '.zip', '.exe', '.tar', '.gz', '.tgz', '.cab', '.bz2', '.tbz'); var i: TAbArchiveType; begin for i := Low(TAbArchiveType) to High(TAbArchiveType) do CheckEqualsString(cnExpected[i], FileExtFromArchiveType(i)); end; procedure TestArchiveUtils.DoCreateFromFieldTest(const AField: TField; const AFileName: string; const AItemCount: Integer); var input: TStream; buf: TArray<Byte>; begin input := TMemoryStream.Create; try buf := AField.AsBytes; input.Write(buf[0], Length(buf)); DoCreateFromStreamTest(input, AFileName, AItemCount); finally input.Free; end; end; procedure TestArchiveUtils.TestArchive(const AArchive: TArchive; const AFileName: string; const AItemCount: integer); var lContents: TStringStream; lItem: TAbArchiveItem; lSize: int64; begin CheckNotNull(AArchive, Format('%s->NotNull', [AFileName])); if (AArchive.ClassType = TEDNCabArchive) then CheckEqualsString(AFileName, ExtractFileName(AArchive.ArchiveName), Format('%s->ArchiveName', [AFileName])) else CheckEqualsString(AFileName, AArchive.ArchiveName, Format('%s->ArchiveName', [AFileName])); CheckEquals(AItemCount, AArchive.Count, Format('%s->Count', [AFileName])); if AItemCount > 0 then begin lItem := AArchive.Items[0]; lContents := TStringStream.Create; try AArchive.ExtractToStream(lItem.FileName, lContents); lSize := Length(lContents.DataString); CheckEquals(lSize, lItem.UncompressedSize, Format('%s extracted size %d=%d', [lItem.FileName, lSize, lItem.UncompressedSize])); finally lContents.Free; end; end; end; procedure TestArchiveUtils.UnCompressBytesTest; begin DoUnCompressBytesTest(atZip); DoUnCompressBytesTest(atGzip); DoUnCompressBytesTest(atTar); DoUnCompressBytesTest(atGzippedTar); DoUnCompressBytesTest(atBzippedTar); DoUnCompressBytesTest(atBzip2); end; procedure TestArchiveUtils.UnCompressStreamTest; begin DoUnCompressStreamTest(atZip); DoUnCompressStreamTest(atGzip); DoUnCompressStreamTest(atTar); DoUnCompressStreamTest(atGzippedTar); DoUnCompressStreamTest(atBzippedTar); DoUnCompressStreamTest(atBzip2); end; procedure TestArchiveUtils.DoCreateFromStreamTest(const AStream: TStream; const AFileName: string; const AItemCount: Integer); var lArchive: TArchive; lArcName: string; begin lArcName := ExtractFileName(AFileName); lArchive := CreateFromStream(AStream, lArcName); try TestArchive(lArchive, lArcName, AItemCount); finally lArchive.Free; end; end; procedure TestArchiveUtils.DoCreateFromStreamTest(const AFileName: string; const AItemCount: Integer); var lStream: TFileStream; begin lStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try DoCreateFromStreamTest(lStream, AFileName, AItemCount); finally lStream.Free; end; end; procedure TestArchiveUtils.CreateFromStreamTest; begin DoCreateFromStreamTest(cnTestZip, 4); DoCreateFromStreamTest(cnTestExe, 4); DoCreateFromStreamTest(cnTestTar, 3); DoCreateFromStreamTest(cnTestGzip, 3); DoCreateFromStreamTest(cnTestBzip, 3); DoCreateFromStreamTest(cnTestCab, 3); end; procedure TestArchiveUtils.DoDecodeAndUnCompressStreamTest(AType: TAbArchiveType); var lEncoded: string; lStream: TStringStream; lDecoded: string; begin lEncoded := CompressAndEncode(cnTestString, cnTestFileName, AType); VerifyCompressedEncodedString(lEncoded, cnTestString, AType); lStream := TStringStream.Create(lEncoded); try lDecoded := DecodeAndUnCompress(lStream); CheckEqualsString(cnTestString, lDecoded); lStream.Position := 0; lDecoded := DecodeAndUnCompress(lStream); CheckEqualsString(cnTestString, lDecoded); finally lStream.Free; end; end; procedure TestArchiveUtils.DoUnCompressStreamTest(AType: TAbArchiveType); var lEncoded: string; lStream: TBytesStream; lDecoded: TBytes; lUncompressed: string; begin lEncoded := CompressAndEncode(cnTestString, cnTestFileName, AType); lDecoded := DecodeBytes(lEncoded); lStream := TBytesStream.Create(lDecoded); try lStream.Position := 0; lUncompressed := UnCompress(lStream); CheckEqualsString(cnTestString, lUncompressed); finally lStream.Free; end; end; procedure TestArchiveUtils.DoUnCompressBytesTest(AType: TAbArchiveType); var lEncoded: string; lDecoded: TBytes; lUncompressed: string; begin lEncoded := CompressAndEncode(cnTestString, cnTestFileName, AType); lDecoded := DecodeBytes(lEncoded); lUncompressed := UnCompress(lDecoded); CheckEqualsString(cnTestString, lUncompressed); end; procedure TestArchiveUtils.DecodeAndUnCompressStreamTest; begin DoDecodeAndUnCompressStreamTest(atZip); DoDecodeAndUnCompressStreamTest(atGzip); DoDecodeAndUnCompressStreamTest(atTar); DoDecodeAndUnCompressStreamTest(atGzippedTar); DoDecodeAndUnCompressStreamTest(atBzippedTar); DoDecodeAndUnCompressStreamTest(atBzip2); //DoDecodeAndUnCompressStreamTest(atCab); end; procedure TestArchiveUtils.DecodeTest; begin end; procedure TestArchiveUtils.EncodeTest; begin end; procedure TestArchiveUtils.OpenArchiveTest; begin end; procedure TestArchiveUtils.SetUp; begin inherited; end; procedure TestArchiveUtils.TearDown; begin inherited; end; initialization // Register any test cases with the test runner RegisterTest(TestArchiveUtils.Suite); end.