text
stringlengths
14
6.51M
(** * Author: Nhat M. Nguyen * Date: 05-02-18 **) program merge_sort; uses crt; const MAXN = 100000; INF = 100000; var i, n: longint; a: array [0..MAXN] of longint; procedure merge(var a: array of longint; st: longint; mi: longint; en: longint); var i, j, k: longint; n_left, n_right: longint; left: array of longint; right: array of longint; begin n_left := mi - st + 1; n_right := en - (mi + 1) + 1; setlength(left, n_left + 1); setlength(right, n_right + 1); for i := st to mi do left[i - st] := a[i]; for j := mi + 1 to en do right[j - mi - 1] := a[j]; left[n_left] := INF; right[n_right] := INF; i := 0; j := 0; for k := st to en do if left[i] < right[j] then begin a[k] := left[i]; i := i + 1; end else begin a[k] := right[j]; j := j + 1; end; end; procedure merge_sort(var a: array of longint; st: longint; en: longint); var mi: longint; begin if st < en then begin mi := (st + en) div 2; merge_sort(a, st, mi); merge_sort(a, mi + 1, en); merge(a, st, mi, en); end; end; begin clrscr; readln(n); for i := 0 to n - 1 do readln(a[i]); merge_sort(a, 0, n - 1); for i := 0 to n - 1 do writeln(a[i]); end.
unit fFuncsSet; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TF_FuncsSet = class(TForm) Label1: TLabel; CB_Vyznam: TComboBox; RG_Stav: TRadioGroup; Label2: TLabel; B_Apply: TButton; L_Status: TLabel; procedure B_ApplyClick(Sender: TObject); procedure FormShow(Sender: TObject); private procedure FuncsSetOK(Sender:TObject; Data:Pointer); public procedure UpdateFuncsList(items:TStrings); end; var F_FuncsSet: TF_FuncsSet; implementation uses fMain, Trakce; {$R *.dfm} //////////////////////////////////////////////////////////////////////////////// // nastavit funkce: procedure TF_FuncsSet.B_ApplyClick(Sender: TObject); begin if (not TrkSystem.openned) then begin Application.MessageBox('Aplikace není připojena k centrále', 'Nelze pokračovat', MB_OK OR MB_ICONWARNING); Exit(); end; if (Self.CB_Vyznam.Text = '') then begin Application.MessageBox('Vyplňte význam funkce', 'Nelze pokračovat', MB_OK OR MB_ICONWARNING); Exit(); end; Self.B_Apply.Enabled := false; Self.RG_Stav.Enabled := false; Self.CB_Vyznam.Enabled := false; Self.L_Status.Font.Color := clGray; Self.L_Status.Caption := 'Nastavuji funkci...'; Application.ProcessMessages(); TrkSystem.callback_ok := TTrakce.GenerateCallback(Self.FuncsSetOK); TrkSystem.callback_err := TTrakce.GenerateCallback(Self.FuncsSetOK); TrkSystem.LoksSetFunc(Self.CB_Vyznam.Text, (Self.RG_Stav.ItemIndex = 1)); end; //////////////////////////////////////////////////////////////////////////////// // callback uspesneho nastaveni funkci: procedure TF_FuncsSet.FuncsSetOK(Sender:TObject; Data:Pointer); begin Self.B_Apply.Enabled := true; Self.RG_Stav.Enabled := true; Self.CB_Vyznam.Enabled := true; Self.L_Status.Font.Color := clGreen; Self.L_Status.Caption := 'Funkce nastaveny'; end; //////////////////////////////////////////////////////////////////////////////// procedure TF_FuncsSet.FormShow(Sender: TObject); begin if (Self.L_Status.Caption = 'Funkce nastaveny') then Self.L_Status.Caption := ''; end; //////////////////////////////////////////////////////////////////////////////// procedure TF_FuncsSet.UpdateFuncsList(items:TStrings); begin Self.CB_Vyznam.Clear(); Self.CB_Vyznam.Items.AddStrings(items); end; //////////////////////////////////////////////////////////////////////////////// end.//unit
{ Sobre o autor: Guinther Pauli Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura) Colaborador Editorial Revistas .net Magazine e ClubeDelphi MVP (Most Valuable Professional) - Embarcadero Technologies - US http://gpauli.com http://www.facebook.com/guintherpauli http://www.twitter.com/guintherpauli http://br.linkedin.com/in/guintherpauli } unit uFramework; interface uses Generics.Collections; type // forwards ConcreteElementA = class; ConcreteElementB = class; // "Visitor" Visitor = class abstract public procedure VisitConcreteElementA( concreteElementA: ConcreteElementA); virtual; abstract; public procedure VisitConcreteElementB( concreteElementB: ConcreteElementB); virtual; abstract; end; // "ConcreteVisitor1" ConcreteVisitor1 = class(Visitor) public procedure VisitConcreteElementA( concreteElementA: ConcreteElementA); override; public procedure VisitConcreteElementB( concreteElementB: ConcreteElementB); override; end; // "ConcreteVisitor2" ConcreteVisitor2 = class(Visitor) public procedure VisitConcreteElementA( concreteElementA: ConcreteElementA); override; public procedure VisitConcreteElementB( concreteElementB: ConcreteElementB); override; end; // "Element" Element = class abstract public procedure Accept(visitor: Visitor); virtual; abstract; end; // "ConcreteElementA" ConcreteElementA = class(Element) public procedure Accept(visitor: Visitor); override; public procedure OperationA(); end; // "ConcreteElementB" ConcreteElementB = class(Element) public procedure Accept(visitor: Visitor); override; public procedure OperationB(); end; // "ObjectStructure" ObjectStructure = class private elements: TList<Element>; public procedure Attach(element: Element); public procedure DeAttach(element: Element); public procedure Accept(visitor: Visitor); public constructor Create(); public destructor Destroy(); override; end; implementation uses System.SysUtils; { ConcreteVisitor1 } procedure ConcreteVisitor1.VisitConcreteElementA( concreteElementA: ConcreteElementA); begin Writeln(Format('%s visited by %s', [concreteElementA.ClassType.ClassName, self.ClassType.ClassName])); end; procedure ConcreteVisitor1.VisitConcreteElementB( concreteElementB: ConcreteElementB); begin Writeln(Format('%s visited by %s', [concreteElementB.ClassType.ClassName, self.ClassType.ClassName])); end; { ConcreteVisitor2 } procedure ConcreteVisitor2.VisitConcreteElementA( concreteElementA: ConcreteElementA); begin Writeln(Format('%s visited by %s', [concreteElementA.ClassType.ClassName, self.ClassType.ClassName])); end; procedure ConcreteVisitor2.VisitConcreteElementB( concreteElementB: ConcreteElementB); begin Writeln(Format('%s visited by %s', [concreteElementB.ClassType.ClassName, self.ClassType.ClassName])); end; { ConcreteElementA } procedure ConcreteElementA.Accept(visitor: Visitor); begin visitor.VisitConcreteElementA(self); end; procedure ConcreteElementA.OperationA(); begin Writeln('ConcreteElementA.OperationA()'); end; { ConcreteElementB } procedure ConcreteElementB.Accept(visitor: Visitor); begin visitor.VisitConcreteElementB(self); end; procedure ConcreteElementB.OperationB(); begin Writeln('ConcreteElementB.OperationB()'); end; { ObjectStructure } procedure ObjectStructure.Accept(visitor: Visitor); var e: Element; begin for e in self.elements do e.Accept(visitor); end; procedure ObjectStructure.Attach(element: Element); begin self.elements.Add(element); end; constructor ObjectStructure.Create(); begin self.elements := TList<Element>.Create(); end; procedure ObjectStructure.DeAttach(element: Element); begin self.elements.Remove(element); end; destructor ObjectStructure.Destroy(); begin self.elements.Free(); inherited; end; end.
unit frm_main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, FileUtil, Forms, Controls, Graphics, Dialogs, ActnList, Menus, ExtCtrls, StdCtrls, DBGrids ,dmgeneral; type { TfrmMain } TfrmMain = class(TForm) conImportPrefixes: TAction; conCalcScores: TAction; conAddFileLog: TAction; conAddFolderLogs: TAction; contLoad: TAction; MenuItem10: TMenuItem; MenuItem11: TMenuItem; MenuItem12: TMenuItem; MenuItem9: TMenuItem; selPrefixes: TOpenDialog; txLog: TMemo; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; selLog: TOpenDialog; Panel1: TPanel; prgExit: TAction; contNew: TAction; ActionList1: TActionList; MainMenu1: TMainMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; SelContest: TSelectDirectoryDialog; stYearContest: TStaticText; stNameContest: TStaticText; stPath: TStaticText; procedure conAddFileLogExecute(Sender: TObject); procedure conAddFolderLogsExecute(Sender: TObject); procedure conCalcScoresExecute(Sender: TObject); procedure conImportPrefixesExecute(Sender: TObject); procedure contLoadExecute(Sender: TObject); procedure contNewExecute(Sender: TObject); procedure prgExitExecute(Sender: TObject); private procedure ContestProperties (path: string); procedure LoadScreen; procedure RefreshLog; public { public declarations } end; var frmMain: TfrmMain; implementation {$R *.lfm} uses frm_contestam ,dmcontest ; { TfrmMain } procedure TfrmMain.prgExitExecute(Sender: TObject); begin application.Terminate; end; (******************************************************************************* *** CONTEST *******************************************************************************) procedure TfrmMain.ContestProperties(path: string); var scrContest: TfrmContestAM; begin scrContest:= TfrmContestAM.Create(self); try scrContest.path:= path; scrContest.ShowModal; finally scrContest.Free; end; LoadScreen; end; procedure TfrmMain.LoadScreen; begin stYearContest.Caption:= DM_Contest.contestYear; stNameContest.Caption:= DM_Contest.contestName; stPath.Caption:= DM_Contest.contestPath; RefreshLog; end; procedure TfrmMain.RefreshLog; begin txLog.Clear; DM_General.EventLog.Active:= false; txLog.Lines.LoadFromFile(DM_General.EventLog.FileName); DM_General.EventLog.Active:= true; end; procedure TfrmMain.contNewExecute(Sender: TObject); begin ContestProperties(EmptyStr); end; procedure TfrmMain.contLoadExecute(Sender: TObject); begin if SelContest.Execute then ContestProperties(SelContest.FileName); end; procedure TfrmMain.conAddFolderLogsExecute(Sender: TObject); begin DM_Contest.analizeLogDir; RefreshLog; ShowMessage('Process finished'); end; procedure TfrmMain.conAddFileLogExecute(Sender: TObject); begin if selLog.Execute then DM_Contest.analizeFile(selLog.FileName); RefreshLog; ShowMessage('Process finished'); end; procedure TfrmMain.conCalcScoresExecute(Sender: TObject); begin DM_Contest.CalculateScores; ShowMessage('The scores have been calculated'); end; procedure TfrmMain.conImportPrefixesExecute(Sender: TObject); begin if selPrefixes.Execute then DM_Contest.ImportPrefixes (selPrefixes.FileName); end; end.
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, System.Json, Datasnap.DSServer, Datasnap.DSAuth; type TMyObject = class(TObject) private FNumber: Integer; FTitle: string; public constructor Create(aTitle: string; aNumber: Integer); property Number: Integer read FNumber; property Title: string read FTitle; end; {$METHODINFO ON} TServerMethods1 = class(TDataModule) private public function EchoString(Value: string): string; function ReverseString(Value: string): string; function ObjectList: TJSONArray; end; {$METHODINFO OFF} implementation {$R *.dfm} uses System.StrUtils, REST.Json; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods1.ObjectList: TJSONArray; var i: Integer; lMyObject: TMyObject; begin Result := TJSONArray.Create; for i := 1 to 5 do begin lMyObject := TMyObject.Create('Title ' + i.ToString,i); Result.AddElement(TJson.ObjectToJsonObject(lMyObject)); lMyObject.Free; end; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; constructor TMyObject.Create(aTitle: string; aNumber: Integer); begin FTitle := aTitle; FNumber := aNumber; end; end.
unit uZFilterCombo; interface uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, CheckLst, uZClasses, IniFiles, IB, IBHeader, IBDataBase, IBSQL, Dialogs; type ZFilterCombo = class(TCheckListBox) private { Private declarations } list: ZContainerId; was_all_checked: boolean; protected { Protected declarations } procedure ClickCheck(Sender: TObject); public { Public declarations } procedure Clear; override; published { Published declarations } procedure InitFilter; procedure AddLine(txt: string; id: integer); procedure FillFromSQL(sql: string; db_handle: TISC_DB_HANDLE); procedure FillFromSQLChecked(sql: string; db_handle: TISC_DB_HANDLE); procedure SaveToIni(file_name: string; section: string); procedure LoadFromIni(file_name: string; section: string); function GenerateList: AnsiString; function GenerateSpaceList: AnsiString; function GetCheckedCount: integer; function PosToId(pos: integer): integer; constructor Create(AOwner:TComponent); override; destructor Destroy; override; end; procedure Register; implementation procedure Register; begin RegisterComponents('Freedom', [ZFilterCombo]); end; constructor ZFilterCombo.Create(AOwner:TComponent); begin inherited Create(AOwner); // Parent := TWinControl(AOwner); Visible := true; self.ParentColor := false; self.ParentCtl3D := false; self.ParentFont := false; self.ParentShowHint := false; BevelInner := bvNone; BevelKind := bkNone; BevelOuter := bvLowered; OnClickCheck := ClickCheck; list := ZContainerId.Create; was_all_checked := false; end; destructor ZFilterCombo.Destroy; begin inherited Destroy; list.Destroy; end; procedure ZFilterCombo.InitFilter; begin Clear; end; procedure ZFilterCombo.AddLine(txt: string; id: integer); begin list.Add(id); Self.Items.Add(txt); end; procedure ZFilterCombo.FillFromSQL(sql: string; db_handle: TISC_DB_HANDLE); var tr: TIBTransaction; q: TIBSQL; base: TIBDatabase; begin Clear; base := TIBDatabase.Create(nil); tr := TIBTransaction.Create(nil); q := TIBSQL.Create(nil); try base.SetHandle(db_handle); base.DefaultTransaction := tr; tr.DefaultDatabase := base; q.Transaction := tr; if tr.InTransaction then tr.Commit; tr.StartTransaction; q.SQL.Text := sql; q.ExecQuery; while not q.Eof do begin AddLine(q.FieldByName('name').AsString, q.FieldByName('id').AsInteger); q.Next; end; if tr.InTransaction then tr.Commit; finally if tr.InTransaction then tr.Rollback; q.Free; tr.Free; base.Free; end; end; procedure ZFilterCombo.FillFromSQLChecked(sql: string; db_handle: TISC_DB_HANDLE); var tr: TIBTransaction; q: TIBSQL; base: TIBDatabase; begin Clear; base := TIBDatabase.Create(nil); tr := TIBTransaction.Create(nil); q := TIBSQL.Create(nil); try base.SetHandle(db_handle); base.DefaultTransaction := tr; tr.DefaultDatabase := base; q.Transaction := tr; if tr.InTransaction then tr.Commit; tr.StartTransaction; q.SQL.Text := sql; q.ExecQuery; while not q.Eof do begin AddLine(q.FieldByName('name').AsString, q.FieldByName('id').AsInteger); Self.Checked[Self.Count - 1] := (q.FieldByName('is_checked').AsInteger > 0); q.Next; end; if tr.InTransaction then tr.Commit; finally if tr.InTransaction then tr.Rollback; q.Free; tr.Free; base.Free; end; end; procedure ZFilterCombo.SaveToIni(file_name: string; section: string); var f: TIniFile; i: integer; rec_name: string; begin f := TIniFile.Create(file_name); for i := 1 to Items.Count - 1 do begin rec_name := section + IntToStr(list.FindId(i - 1)); f.WriteBool(section, rec_name, Self.Checked[i]); end; f.Destroy; end; procedure ZFilterCombo.LoadFromIni(file_name: string; section: string); var f: TIniFile; i: integer; rec_name: string; begin f := TIniFile.Create(file_name); for i := 1 to Items.Count - 1 do begin rec_name := section + IntToStr(list.FindId(i - 1)); Self.Checked[i] := f.ReadBool(section, rec_name, true); end; f.Destroy; end; function ZFilterCombo.GenerateList: AnsiString; var check_list: ZContainerId; i: integer; begin check_list := ZContainerId.Create; for i := 1 to Items.Count - 1 do begin if Checked[i] then check_list.Add(list.FindId(i - 1)); end; GenerateList := check_list.GenerateList; check_list.Destroy; end; function ZFilterCombo.GenerateSpaceList: AnsiString; var check_list: ZContainerId; i: integer; begin check_list := ZContainerId.Create; for i := 1 to Items.Count - 1 do begin if Checked[i] then check_list.Add(list.FindId(i - 1)); end; GenerateSpaceList := check_list.GenerateSpaceList; check_list.Destroy; end; function ZFilterCombo.GetCheckedCount: integer; var checked_count: integer; i: integer; begin checked_count := 0; for i := 1 to Items.Count - 1 do begin if Checked[i] then checked_count := checked_count + 1; end; GetCheckedCount := checked_count; end; procedure ZFilterCombo.Clear; begin inherited Clear; Items.Add('Мыт'); list.Clear; end; function ZFilterCombo.PosToId(pos: integer): integer; begin PosToId := list.FindId(pos - 1); end; procedure ZFilterCombo.ClickCheck(Sender: TObject); var i: integer; begin if (was_all_checked <> Self.Checked[0]) then begin for i := 1 to Items.Count - 1 do begin Checked[i] := Checked[0]; end; was_all_checked := Checked[0]; end; for i := 1 to Items.Count - 1 do begin if not Checked[i] then begin Checked[0] := false; was_all_checked := false; end end; end; end.
program HelloWorld2; {$mode objfpc}{$H+} uses MUIClass.Base, //needed for MUIApp MUIClass.Window, //needed for TMUIWindow MUIClass.Area; //needed for TMUIButton and TMUIText type // My Window (mainly because we need the Event attached to an Object) TMyWindow = class(TMUIWindow) procedure ButtonClick(Sender: TObject); end; var Win: TMyWindow; // Window Text: TMUIText; // Text field Button: TMUIButton; // Button // Event called, when Button is pressed procedure TMyWindow.ButtonClick(Sender: TObject); begin Text.Contents := 'Clicked'; // Change string in Text Object end; begin // Create a Window, with a title bar text Win := TMyWindow.Create; Win.Title := 'Test Window'; // Create a Text field with text Text := TMUIText.Create; Text.Contents := 'not Clicked'; Text.Parent := Win; // Insert text field in the Window // Create a Button with some text Button := TMUIButton.Create; Button.Contents := 'Click Me'; Button.OnClick := @Win.ButtonClick; // Connect the Click Event Button.Parent := Win; // Insert Button in the Window // will actually start everything, // Create MUI object, connect them together // from the Parent relation we builded with Pascal Classes // Open the Window and run the Message Loop // destroy everything after the Window is closed again. MUIApp.Run; end.
unit UUADPropLineAddr; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } //Used for entering the property address correctly on the comp address lines interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, Dialogs, StrUtils, UCell, UUADUtils, UContainer, UEditor, UGlobals, UStatus, UForms, uListComps3,UGridMgr, ComCtrls; type TdlgUADPropLineAddr = class(TAdvancedForm) bbtnCancel: TBitBtn; lblState: TLabel; cbState: TComboBox; lblZipCode: TLabel; edtZipCode: TEdit; edtZipPlus4: TEdit; lblZipSep: TLabel; lblUnitNum: TLabel; edtUnitNum: TEdit; lblStreetAddr: TLabel; edtStreetAddr: TEdit; lblCity: TLabel; edtCity: TEdit; bbtnHelp: TBitBtn; bbtnClear: TBitBtn; cbSubjAddr2ToComp: TCheckBox; chkCheckComp: TCheckBox; bbtnOK: TBitBtn; ResultText: TLabel; procedure FormShow(Sender: TObject); procedure SetAddrFromText(Addr1Cell, Addr2Cell: TBaseCell; IsUnitReqd: Boolean=False); procedure bbtnHelpClick(Sender: TObject); procedure bbtnOKClick(Sender: TObject); procedure edtZipCodeKeyPress(Sender: TObject; var Key: Char); procedure edtZipPlus4KeyPress(Sender: TObject; var Key: Char); procedure bbtnClearClick(Sender: TObject); procedure cbStateKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure chkCheckCompClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure bbtnCancelClick(Sender: TObject); procedure editOnChange(Sender: TObject); private { Private declarations } FAddr1Cell, FAddr2Cell: TBaseCell; FClearData: Boolean; IsUnitAddr, IsSubj: Boolean; CompDB : TCompsDBList2; SalesGrid,ListingGrid: TCompMgr2; CompID, CompType: Integer; CompColumn: TCompColumn; FResetText: Boolean; tmpAddress, tmpCityStZip: String; appPref_AutoDetectComp: Boolean; //Ticket #1231: Preference to show on UAD Comp address pop function CellInSalesTable(CurCell:TBaseCell; SalesGrid:TCompMgr2; var CompID: Integer; var CompType:Integer):Boolean; function CellInListingTable(CurCell:TBaseCell; ListingGrid:TCompMgr2; var CompID: Integer; var CompType:Integer):Boolean; procedure DoSaveAddress; procedure DoCheckComp; procedure DoLoadComp; procedure SavePrefs; procedure LoadPrefs; function ValidateEntries: Boolean; function IsNonPropAddressXID:Boolean; //Ticket #1272 public { Public declarations } FDoc: TContainer; FCell: TBaseCell; AutoPopSubjCityStateZip: Boolean; procedure Clear; procedure SetSubjCityStZip; procedure SaveToCell; end; const MaxAddrType = 12; MaxSubjAddr = 5; MaxNonPropAddr = 3; PropAddr1XID = 925; SubjAuxAddr1XID = 46; MaxNonComp = 15; var dlgUADPropLineAddr: TdlgUADPropLineAddr; AddrTypeName: array[0..MaxAddrType] of String = ('Subject','Comparable','Subject','Appraiser', 'Supervisor','Appraiser','Supervisor','Listing','Rental','Subject','Comparable','Comparable','Comparable'); // XID 46, 41, 9, 10, 24 & 42 are on the FNMA certification forms // XID 1660 & 1737 are on the 1004MC form // XID 3981 & 3982 are on the Supplemental REO 2008 form // XID 932 & 933 are on the FNMA1025 XRentals form Addr1XID: array[0..MaxAddrType] of Integer = (925,925,46,9,24,1660,1737,3981,932,1801,1819,1838,1857); SubjAddr1XIDStr: array[0..MaxSubjAddr] of String = ('46','925','932','1801','2758','3981'); NonPropAddr1XIDStr: array[0..MaxNonPropAddr] of String = ('9','24','1660','1737'); Addr2XID: array[0..MaxAddrType] of Integer = (926,926,41,10,42,1660,1737,3982,933,1802,1820,1839,1858); //Ticket #1272: XML ID not on the grid: //46-49: Subject 41: property appriaser addr 37,31:company address //9,10: Appraiser company address //24,42: Supervisor company address //2758,2760, 2761:FNMA 1004MC //Set up this array for IsNonPropAddressXID function. This will always set the caption save button as Save. NonCompAddrStr: array[0..MaxNonComp] of String = ('46','47','48','49','9','10','24','42','41','37','31', '2758','2760','2761','1660', '1737'); implementation {$R *.dfm} uses UPage, UAppraisalIDs, UStrings,uBase, UUtil2, UMain,IniFiles; function TdlgUADPropLineAddr.IsNonPropAddressXID:Boolean; var i:Integer; begin result := False; for i:= low(NonCompAddrStr) to high(NonCompAddrStr) do begin if FCell.FCellXID = StrToIntDef(NonCompAddrStr[i], 0) then begin result := True; bbtnOK.Caption := 'Save'; break; end; end; end; procedure TdlgUADPropLineAddr.FormShow(Sender: TObject); var Page: TDocPage; AddrIdx, Cntr: Integer; IsAddr1, IsAddr2: Boolean; begin if FDoc = nil then FDoc := Main.ActiveContainer; //if nil, use active container FResetText := True; Clear; FClearData := False; Page := FCell.ParentPage as TDocPage; IsAddr1 := False; IsAddr2 := False; IsUnitAddr := False; AddrIdx := -1; Cntr := -1; repeat Cntr := Succ(Cntr); if FCell.FCellXID = Addr1XID[Cntr] then if (Cntr = 0) then begin if (FCell.FContextID > 0) then begin IsAddr1 := True; AddrIdx := Cntr; end; end else begin IsAddr1 := True; AddrIdx := Cntr; end; until IsAddr1 or (Cntr = MaxAddrType); if not IsAddr1 then begin Cntr := -1; repeat Cntr := Succ(Cntr); if FCell.FCellXID = Addr2XID[Cntr] then if (Cntr = 0) then begin if (FCell.FContextID > 0) then begin IsAddr2 := True; AddrIdx := Cntr; end; end else begin IsAddr2 := True; AddrIdx := Cntr; end; until IsAddr2 or (Cntr = MaxAddrType); end; if (not IsAddr1) and (not IsAddr2) then Close else begin if IsAddr1 then begin FAddr1Cell := FCell; if Addr1XID[AddrIdx] <> Addr2XID[AddrIdx] then FAddr2Cell := Page.pgData.DataCell[FCell.GetCellIndex + 1] else FAddr2Cell := nil; end else begin if Addr1XID[AddrIdx] = Addr2XID[AddrIdx] then begin FAddr1Cell := FCell; FAddr2Cell := nil; end else begin FAddr1Cell := Page.pgData.DataCell[FCell.GetCellIndex - 1]; FAddr2Cell := FCell; end; end; Caption := 'UAD: ' + AddrTypeName[AddrIdx] + ' Address'; cbSubjAddr2ToComp.Checked := appPref_UADSubjAddr2ToComp; IsSubj := ((FAddr1Cell.FContextID > 0) and ((AnsiIndexStr(IntToStr(FAddr1Cell.FCellXID), SubjAddr1XIDStr) >= 0))); cbSubjAddr2ToComp.Visible := (not IsSubj) and ((AnsiIndexStr(IntToStr(FAddr1Cell.FCellXID), NonPropAddr1XIDStr) < 0)); // Appraiser and supervisor addresses do not include a separate unit number if (AddrIdx < 3) or (AddrIdx > 6) then IsUnitAddr := not IsResidReport(FCell.ParentPage.ParentForm.ParentDocument as TContainer); lblUnitNum.Visible := IsUnitAddr; edtUnitNum.Visible := IsUnitAddr; if (not IsSubj) and cbSubjAddr2ToComp.Checked and (Trim(FAddr1Cell.Text) = '') and ((FAddr2Cell <> nil) and (FAddr2Cell.Text = ''))then SetSubjCityStZip else SetAddrFromText(FAddr1Cell, FAddr2Cell, edtUnitNum.Visible); edtStreetAddr.SetFocus; end; //Ticket #1231: setup auto detect Comps if assigned(FAddr1Cell) then //Ticket #1272: check if not nil before set the text tmpAddress := FAddr1Cell.Text; if assigned(FAddr2Cell) then tmpCityStZip := FAddr2Cell.Text; SalesGrid := TCompMgr2.Create; ListingGrid := TCompMgr2.Create; SalesGrid.BuildGrid(FDoc, gtSales); //create and build the grid for sales ListingGrid.BuildGrid(FDoc, gtListing); //if no sales then create listings chkCheckComp.Visible := not isSubj and not IsNonPropAddressXID; //Ticket #1272 only visible for comp address cell id LoadPrefs; ResultText.Caption := ''; ResultText.Visible := chkCheckComp.Checked; end; procedure TdlgUADPropLineAddr.SetAddrFromText(Addr1Cell, Addr2Cell: TBaseCell; IsUnitReqd: Boolean=False); var PosItem: Integer; CityStZip, sStreet, sCity, sState, sUnit, sZip, FullAddr: String; begin sStreet := ''; if Addr2Cell = nil then begin FullAddr := Addr1Cell.Text; PosItem := Pos(',',FullAddr); if PosItem > 0 then begin sStreet := Copy(FullAddr, 1, Pred(PosItem)); CityStZip := Copy(FullAddr, Succ(PosItem), Length(FullAddr)); end; end else begin sStreet := Addr1Cell.Text; CityStZip := Addr2Cell.Text; end; if IsUnitReqd then begin PosItem := Pos(',',CityStZip); if PosItem > 0 then // If there is a unit number (2 commas in the address) then // retrieve the unit and capture only the city, state and zip // for further processing if Pos(',', Copy(CityStZip, Succ(PosItem), Length(CityStZip))) > 0 then begin sUnit := Copy(cityStZip, 1, Pred(PosItem)); CityStZip := Copy(CityStZip, Succ(PosItem), Length(CityStZip)); end; end; sCity := ParseCityStateZip2(CityStZip, cmdGetCity); sState := ParseCityStateZip2(CityStZip, cmdGetState); sZip := ParseCityStateZip2(CityStZip, cmdGetZip); edtStreetAddr.Text := sStreet; edtUnitNum.Text := sUnit; edtCity.Text := sCity; cbState.ItemIndex := cbState.Items.IndexOf(sState); edtZipCode.Text := Copy(sZip, 1, 5); edtZipPlus4.Text := Copy(sZip, 7, 4); end; procedure TdlgUADPropLineAddr.bbtnHelpClick(Sender: TObject); begin ShowUADHelp('FILE_HELP_UAD_PROPERTY_ADDRESS', Caption); end; procedure TdlgUADPropLineAddr.bbtnOKClick(Sender: TObject); begin if CompareText(bbtnOK.Caption, 'Check') = 0 then //Ticket #1231: do check comps logic if is check else do normal stuff DoCheckComp else if CompareText(bbtnOK.Caption, 'Load Comp') = 0 then DoLoadComp else DoSaveAddress; end; procedure TdlgUADPropLineAddr.DoLoadComp; var aOK: Boolean; begin if assigned(CompDB) then begin CompDB.OnRecChanged; //load comps photo query aOK := CompDB.ExportComparable(CompID, CompType); //export both data and images if aOK then begin FResetText := False; bbtnCancel.Click; end; end; end; function TdlgUADPropLineAddr.ValidateEntries: Boolean; begin result := False; if length(edtStreetAddr.Text) = 0 then begin ShowAlert(atWarnAlert, msgUADValidStreet); edtStreetAddr.SetFocus; end else if length(edtCity.Text) = 0 then begin ShowAlert(atWarnAlert, msgUADValidCity); edtCity.SetFocus; end else if length(cbState.Text) = 0 then begin ShowAlert(atWarnAlert, msgValidState); cbState.SetFocus; end else if length(edtZipCode.Text) = 0 then begin ShowAlert(atWarnAlert, msgValidZipCode); edtZipCode.SetFocus; end else result := True; end; procedure TdlgUADPropLineAddr.DoCheckComp; //Ticket #1231 var i: Integer; CurCell, aCell: TBaseCell; aCityStateZip: String; aOK: Boolean; gridCell: TGridCell; lo, hi: Integer; aZipCode: String; begin CompType := -1; if not ValidateEntries then exit; ResultText.Caption := ''; aOK := False; try if (SalesGrid.Count = 0) and (ListingGrid.Count = 0) then //No sales nor listings exit; CurCell := FDoc.docActiveCell; //get the current active cell if not assigned(CurCell) then exit; if CellInListingTable(CurCell, ListingGrid, CompID, CompType) then CompColumn := ListingGrid.Comp[CompID]; if CompType = -1 then begin if CellInSalesTable(CurCell, SalesGrid,CompID, CompType) then CompColumn := SalesGrid.Comp[CompID]; end; if CompType = -1 then Exit; aCell := curcell; if CompID > 0 then //we have comp # begin CompDB := TCompsDBList2.Create(nil); //Ticket #1379: since the form now is set to poOwnderFormCenter, it always pop up to the top of the active window //In this case, we just want to borrow the form to set the search value to hit find button in the background only CompDB.position := poDefault; TContainer(CompDB.FDoc) := FDoc; CompDB.FAutoDetectComp := True; //Tell Comps DB to run in background not to show dialog CompDB.LoadFieldToCellIDMap; CompDB.edtSubjectAddr.Text := trim(edtStreetAddr.Text); //load address to the search tab CompDB.cmbSubjectCity.Text := trim(edtCity.Text); CompDB.cmbSubjectState.Text := trim(cbState.Text); CompDB.edtUnitNum.Text := trim(edtUnitNum.Text); //Ticket #1231: handle original zip code +4 digit code if length(edtZipPlus4.Text) > 0 then aZipCode := Format('%s-%s',[trim(edtZipCode.Text), trim(edtZipPlus4.text)]) else aZipCode := trim(edtZipCode.Text); CompDB.cmbSubjectZip.Text := aZipCode; aCityStateZip := Format('%s, %s %s',[trim(edtCity.Text), trim(cbState.Text), trim(aZipCode)]); if edtUnitNum.Text <> '' then //Ticket #1315: Include Unit # aCityStateZip := Format('%s, %s',[trim(edtUnitNum.text), aCityStateZip]); if assigned(CompColumn) then begin //Save current one to a temp CompColumn.SetCellTextByID(925, edtStreetAddr.Text); //write the both address cells for comps db to pick up CompColumn.SetCellTextByID(926, aCityStateZip); CompColumn.SetCellTextByID(2141, edtUnitNum.Text); end; CompDB.btnFind.Click; //search for the address try if not CompDB.FNoMatch then //we found it begin CompDB.Show; CompDB.LoadReportCompTables; if CompDB.CompsInDB(CompID, CompType) then //found sales begin ResultText.Font.Color := clBlue; ResultText.Caption := 'Search Result: Address is in Comps Database,do you want to load it?'; bbtnOK.Caption := 'Load Comp'; bbtnOK.Refresh; aOK := True; end else aOK := False; end else //not found in Comps db begin aOK := False; end; if not aOK then begin ResultText.Font.Color := clRed; ResultText.Caption := 'Search Result: Address is not in Comps Database.'; bbtnOK.Caption := 'Save'; bbtnOK.Refresh; FDoc.MakeCurCell(aCell); CompColumn.SetCellTextByID(925, tmpAddress); //write the both address cells for comps db to pick up CompColumn.SetCellTextByID(926, tmpCityStZip); end; finally end; end; finally ResultText.Visible := True; end; end; procedure TdlgUADPropLineAddr.DoSaveAddress; begin if Trim(edtStreetAddr.Text) = '' then begin ShowAlert(atWarnAlert, msgUADValidStreet); edtStreetAddr.SetFocus; Exit; end; if IsUnitAddr and (Trim(edtUnitNum.Text) = '') then begin ShowAlert(atWarnAlert, msgUADValidUnitNo); edtUnitNum.SetFocus; Exit; end; if Trim(edtCity.Text) = '' then begin ShowAlert(atWarnAlert, msgUADValidCity); edtCity.SetFocus; Exit; end; //user needs to be able to type in state. easier than clicking list if (cbState.text = '') or (length(cbState.text) = 1) or (POS(cbState.text, cbState.Items.Text)= 0) then begin ShowAlert(atWarnAlert, msgValidState); cbState.SetFocus; Exit; end; if (Trim(edtZipCode.Text) = '') or (Length(edtZipCode.Text) < 5) or (StrToInt(edtZipCode.Text) <= 0) then begin ShowAlert(atWarnAlert, msgValidZipCode); edtZipCode.SetFocus; Exit; end; if Length(Trim(edtZipPlus4.Text)) > 0 then if (Length(edtZipPlus4.Text) < 4) or (StrToInt(edtZipPlus4.Text) = 0) then begin ShowAlert(atWarnAlert, msgValidZipPlus); edtZipPlus4.SetFocus; Exit; end; SaveToCell; ModalResult := mrOK; end; procedure TdlgUADPropLineAddr.edtZipCodeKeyPress(Sender: TObject; var Key: Char); begin Key := PositiveNumKey(Key); end; procedure TdlgUADPropLineAddr.edtZipPlus4KeyPress(Sender: TObject; var Key: Char); begin Key := PositiveNumKey(Key); end; procedure TdlgUADPropLineAddr.cbStateKeyPress(Sender: TObject; var Key: Char); begin Key := GetAlphaKey(Key); end; procedure TdlgUADPropLineAddr.Clear; begin IsUnitAddr := False; edtStreetAddr.Text := ''; edtUnitNum.Text := ''; edtCity.Text := ''; cbState.ItemIndex := -1; edtZipCode.Text := ''; edtZipPlus4.Text := ''; end; procedure TdlgUADPropLineAddr.SetSubjCityStZip; var Document: TContainer; FAddrCell: TBaseCell; begin if cbSubjAddr2ToComp.Checked then begin Document := FCell.ParentPage.ParentForm.ParentDocument as TContainer; FAddrCell := Document.GetCellByXID(47); // General city XID if FAddrCell = nil then FAddrCell := Document.GetCellByXID(3971); // REO2008 Addendum city XID if FAddrCell <> nil then edtCity.Text := FAddrCell.Text; FAddrCell := Document.GetCellByXID(48); // General state XID if FAddrCell = nil then FAddrCell := Document.GetCellByXID(3972); // REO2008 Addendum city XID if FAddrCell <> nil then cbState.ItemIndex := cbState.Items.IndexOf(FAddrCell.Text); FAddrCell := Document.GetCellByXID(49); // General zip XID if FAddrCell = nil then FAddrCell := Document.GetCellByXID(3973); // REO2008 Addendum zip XID if FAddrCell <> nil then begin edtZipCode.Text := Copy(FAddrCell.Text, 1, 5); edtZipPlus4.Text := Copy(FAddrCell.Text, 7, 4); end; end; end; procedure TdlgUADPropLineAddr.SaveToCell; const cCom = ', '; var FirstLn, SecondLn: String; Document: TContainer; begin FirstLn := edtStreetAddr.Text; SecondLn := ''; if not FClearData then begin if IsUnitAddr then SecondLn := edtUnitNum.Text + cCom; SecondLn := SecondLn + edtCity.Text + cCom + cbState.Text + ' ' + edtZipCode.Text; if Trim(edtZipPlus4.Text) <> '' then SecondLn := SecondLn + '-' + edtZipPlus4.Text; end; // Remove any legacy data - no longer used FAddr1Cell.GSEData := ''; // Save the cleared or valid address if FAddr2Cell = nil then begin if not FClearData then SetDisplayUADText(FAddr1Cell, (FirstLn + cCom + SecondLn)) else SetDisplayUADText(FAddr1Cell, ''); end else begin SetDisplayUADText(FAddr1Cell, FirstLn); SetDisplayUADText(FAddr2Cell, SecondLn); end; // If entering the subject address munge so the page 1 fields are populated if IsSubj then begin Document := FAddr1Cell.ParentPage.ParentForm.ParentDocument as TContainer; Document.BroadcastCellContext(kAddress, edtStreetAddr.Text); Document.BroadcastCellContext(kUnitNo, edtUnitNum.Text); Document.BroadcastCellContext(kCity, edtCity.Text); Document.BroadcastCellContext(kState, cbState.Text); Document.BroadcastCellContext(kZip, edtZipCode.Text); end; end; procedure TdlgUADPropLineAddr.bbtnClearClick(Sender: TObject); begin if WarnOK2Continue(msgUAGClearDialog) then begin Clear; FClearData := True; // save subject address to the munger SaveToCell; appPref_UADSubjAddr2ToComp := cbSubjAddr2ToComp.Checked; ModalResult := mrOK; end; end; procedure TdlgUADPropLineAddr.FormClose(Sender: TObject; var Action: TCloseAction); begin appPref_UADSubjAddr2ToComp := cbSubjAddr2ToComp.Checked; end; function TdlgUADPropLineAddr.CellInSalesTable(CurCell:TBaseCell; SalesGrid:TCompMgr2; var CompID: Integer; var CompType: Integer):Boolean; var i: Integer; aCell: TBaseCell; aCompCol: TCompColumn; aCoord: TPoint; begin //Ticket # 1265: Use grid manager to pass the current cell uid to get the compid out. CompID := TGridMgr(SalesGrid).GetCellCompID(CurCell.UID, aCoord); if CompID <> -1 then CompType := TGridMgr(SalesGrid).Kind; result := (CompID >= 0) and (CompType <> -1); (* CompType := gtSales; for i:= 0 to SalesGrid.Count - 1 do //walk through the grid begin aCell := SalesGrid.Comp[i].GetCellByID(CurCell.FCellID); //get the active cell from the grid if not assigned(aCell) then continue; if (CurCell.UID.Num = aCell.UID.Num) and //if active cell matches with the cell on the grid (CurCell.UID.Pg = aCell.UID.Pg) and (CurCell.UID.FormID = aCell.UID.FormID) and (CurCell.FCellID = aCell.FCellID) and ((CurCell.FCellID=925) or (CurCell.FCellID=926)) then begin //CompID := i; compType := gtSales; Break; end; end; result := (CompType <> -1); *) end; function TdlgUADPropLineAddr.CellInListingTable(CurCell:TBaseCell; ListingGrid:TCompMgr2; var CompID: Integer; var CompType:Integer):Boolean; var i: Integer; aCell: TBaseCell; aCoord: TPoint; begin //Ticket # 1265: Use grid manager to pass the current cell uid to get the compid out. CompID := TGridMgr(ListingGrid).GetCellCompID(CurCell.UID, aCoord); if CompID <> -1 then CompType := TGridMgr(ListingGrid).Kind; result := (CompID >= 0) and (CompType <> -1); (* CompType := -1; for i:= 0 to ListingGrid.Count - 1 do //walk through the grid begin aCell := ListingGrid.Comp[i].GetCellByID(CurCell.FCellID); //get the active cell from the grid if not assigned(aCell) then continue; if (CurCell.UID.Num = aCell.UID.Num) and //if active cell matches with the cell on the grid (CurCell.UID.Pg = aCell.UID.Pg) and (CurCell.UID.FormID = aCell.UID.FormID) and (CurCell.FCellID = aCell.FCellID) and ((CurCell.FCellID=925) or (CurCell.FCellID=926)) then begin compType := gtListing; CompID := i; break; //we are done. end; end; result := (CompType <> -1); *) end; procedure TdlgUADPropLineAddr.chkCheckCompClick(Sender: TObject); begin ResultText.Visible := False; if isSubj or IsNonPropAddressXID then //if it's subject we need the button say "Save" begin bbtnOK.Caption := 'Save'; exit; end; if chkCheckComp.Checked then //Ticket #1231: if checked show check else show save begin bbtnOK.Caption := 'Check'; // Height := 190; //#1519: use the original height that set in design end else begin bbtnOK.Caption := 'Save'; // Height := 165; //#1519: use the original height that set in design end; end; procedure TdlgUADPropLineAddr.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if CanClose then begin SavePrefs; if assigned(CompDB) then CompDB.Free; if assigned(SalesGrid) then SalesGrid.Free; if assigned(ListingGrid) then ListingGrid.Free; end; end; procedure TdlgUADPropLineAddr.bbtnCancelClick(Sender: TObject); begin if FResetText then begin if not assigned(CompColumn) then exit; CompColumn.SetCellTextByID(925, tmpAddress); //write the both address cells for comps db to pick up CompColumn.SetCellTextByID(926, tmpCityStZip); end; end; procedure TdlgUADPropLineAddr.LoadPrefs; var IniFilePath: String; PrefFile : TMemIniFile; begin IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI; PrefFile := TMemIniFile.Create(IniFilePath); //create the INI reader try With PrefFile do begin appPref_AutoDetectComp := ReadBool('CompsDB', 'AutoDetectComp',True); chkCheckComp.Checked := appPref_AutoDetectComp; end; finally PrefFile.Free; end; end; procedure TdlgUADPropLineAddr.SavePrefs; var IniFilePath: String; PrefFile: TMemIniFile; begin IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI; PrefFile := TMemIniFile.Create(IniFilePath); //create the INI writer try appPref_AutoDetectComp := chkCheckComp.Checked; with PrefFile do begin //Saving Comps DB WriteBool('CompsDB', 'AutoDetectComp', appPref_AutoDetectComp); UpdateFile; // do it now end; finally PrefFile.Free; end; end; procedure TdlgUADPropLineAddr.editOnChange(Sender: TObject); begin if isSubj or IsNonPropAddressXID then exit; if chkCheckComp.Checked then bbtnOK.Caption := 'Check' else bbtnOK.Caption := 'Save'; end; end.
unit IpiTrib; interface uses TributacaoItemNotaFiscal; type TIpiTrib = class private FAliquota :Real; FValor :Real; FBaseCalculo: Real; FCodigoItem: integer; procedure SetAliquota(const Value: Real); procedure SetValor(const Value: Real); private function GetCST :String; function GetValor :Real; public constructor Create(Aliquota :Real);overload; constructor Create(Aliquota, pBaseCalculo :Real; pCodigoItem :integer);overload; public property codigoItem :integer read FCodigoItem write FCodigoItem; property CST :String read GetCST; property Aliquota :Real read FAliquota write SetAliquota; property Valor :Real read GetValor write SetValor; property BaseCalculo :Real read FBaseCalculo write FBaseCalculo; end; implementation uses Funcoes; { TIpiTrib } constructor TIpiTrib.Create(Aliquota, pBaseCalculo :Real; pCodigoItem :integer); begin self.Create(Aliquota); self.FCodigoItem := pCodigoItem; self.FBaseCalculo := pBaseCalculo; end; constructor TIpiTrib.Create(Aliquota: Real); begin self.FAliquota := Aliquota; end; function TIpiTrib.GetCST: String; begin result := '50'; end; function TIpiTrib.GetValor: Real; begin result := arredonda(((self.BaseCalculo * self.FAliquota) / 100),3); end; procedure TIpiTrib.SetAliquota(const Value: Real); begin FAliquota := Value; end; procedure TIpiTrib.SetValor(const Value: Real); begin FValor := value; end; end.
unit BombaBO; interface uses Data.SqlExpr, SysUtils, Forms, Windows, Util, BombaDAO, Bomba; type TBombaBO = class private { private declarations } public function ObterListaBombas(Descricao: String = ''):TSQLQuery; function ObterBombaPorId(Id :Integer):TBomba; function UltimaBomba:TBomba; procedure Salvar(Bomba: TBomba); procedure Excluir(Bomba: TBomba); end; implementation { TBombaBO } procedure TBombaBO.Excluir(Bomba: TBomba); var BombaDAO: TBombaDAO; begin try BombaDAO := TBombaDAO.Create; BombaDAO.Excluir(Bomba); FreeAndNil(BombaDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; function TBombaBO.ObterBombaPorId(Id :Integer): TBomba; var BombaDAO: TBombaDAO; begin try BombaDAO := TBombaDAO.Create; Result := BombaDAO.ObterBombaPorId(Id); FreeAndNil(BombaDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; function TBombaBO.ObterListaBombas(Descricao: String = ''): TSQLQuery; var BombaDAO: TBombaDAO; begin try BombaDAO := TBombaDAO.Create; Result := BombaDAO.ObterListaBombas(Descricao); FreeAndNil(BombaDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; procedure TBombaBO.Salvar(Bomba: TBomba); var BombaDAO: TBombaDAO; begin try BombaDAO := TBombaDAO.Create; BombaDAO.Salvar(Bomba); FreeAndNil(BombaDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; function TBombaBO.UltimaBomba: TBomba; var BombaDAO: TBombaDAO; begin try BombaDAO := TBombaDAO.Create; Result := BombaDAO.UltimaBomba(); FreeAndNil(BombaDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; end.
unit uCadastroUsuario; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Mask, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Datasnap.DBClient, Datasnap.Provider, Generics.Collections, uDmCadastro, UCrudUsuario, uUsuario; type TfCadastroUsuario = class(TfBaseCadastro) edtCodigo: TMaskEdit; edtLogin: TMaskEdit; edtSenha: TMaskEdit; lblCodigo: TLabel; lblLogin: TLabel; edtNome: TMaskEdit; lblNome: TLabel; lblSenha: TLabel; edtSenhaConfirma: TMaskEdit; lblConfirmarSenha: TLabel; cbxAdm: TCheckBox; procedure btnSalvarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbgCadastroDblClick(Sender: TObject); procedure dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnExcluirClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private UsuarioCrud : ICrudUsuario; Usuario : IUsuario; function ValidaCampos: Boolean; procedure AtualizaGrid; procedure PreencheCampos; procedure PreencheUsuarioComEdits; procedure LimpaObjetoUsuario; public { Public declarations } end; var fCadastroUsuario: TfCadastroUsuario; implementation {$R *.dfm} uses uUtilidades, uConstantes; { TfCadastroUsuario } procedure TfCadastroUsuario.AtualizaGrid; begin UsuarioCrud.AtualizaGridUsuario; end; procedure TfCadastroUsuario.dbgCadastroDblClick(Sender: TObject); begin inherited; PreencheCampos; PreencheUsuarioComEdits; end; procedure TfCadastroUsuario.dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then begin PreencheCampos; PreencheUsuarioComEdits; end; end; procedure TfCadastroUsuario.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(dmCadastro); end; procedure TfCadastroUsuario.FormCreate(Sender: TObject); begin inherited; UsuarioCrud := TCrudUsuario.Create; Usuario := TUsuario.Create; Application.CreateForm(TdmCadastro, dmCadastro); end; procedure TfCadastroUsuario.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F5 then AtualizaGrid; end; procedure TfCadastroUsuario.FormShow(Sender: TObject); begin inherited; AtualizaGrid; end; procedure TfCadastroUsuario.LimpaObjetoUsuario; begin Usuario.Codigo := 0; Usuario.Login := Empty; Usuario.Senha := Empty; Usuario.Nome := Empty; Usuario.Administrador := 0; end; procedure TfCadastroUsuario.PreencheCampos; begin edtCodigo.Text := IntToStr(dmCadastro.cdsUsuarioCODIGO.AsInteger); edtLogin.Text := dmCadastro.cdsUsuarioLOGIN.AsString; edtNome.Text := dmCadastro.cdsUsuarioNOME.AsString; cbxAdm.Checked := dmCadastro.cdsUsuarioADMINISTRADOR.AsInteger = Administrador; end; procedure TfCadastroUsuario.PreencheUsuarioComEdits; begin Usuario.Codigo := StrToInt(edtCodigo.Text); Usuario.Login := edtLogin.Text; Usuario.Nome := edtNome.Text; if not TUtilidades.IsEmpty(edtSenha.Text) then Usuario.Senha := TUtilidadesSeguranca.EncriptarSenha(edtSenha.Text); if cbxAdm.Checked then Usuario.Administrador := Administrador else Usuario.Administrador := NaoAdministrador; end; procedure TfCadastroUsuario.btnAlterarClick(Sender: TObject); begin inherited; PreencheUsuarioComEdits; UsuarioCrud.Alterar(Usuario); AtualizaGrid; LimparCampos; LimpaObjetoUsuario; end; procedure TfCadastroUsuario.btnExcluirClick(Sender: TObject); begin inherited; UsuarioCrud.Excluir(Usuario); AtualizaGrid; LimparCampos; LimpaObjetoUsuario; end; procedure TfCadastroUsuario.btnSalvarClick(Sender: TObject); const ehAdmin = 1; begin inherited; Usuario.Login := Trim(edtLogin.Text); Usuario.Nome := edtNome.Text; Usuario.Senha := TUtilidadesSeguranca.EncriptarSenha(edtSenha.Text); if cbxAdm.Checked then Usuario.Administrador := ehAdmin; if not ValidaCampos then Exit; if not TUtilidades.IsEmpty(UsuarioCrud.ConsultaPeloLogin(Usuario.Login).Login) then ShowMessage('Login já existe') else UsuarioCrud.Incluir(Usuario); AtualizaGrid; LimparCampos; LimpaObjetoUsuario; edtLogin.SetFocus; end; function TfCadastroUsuario.ValidaCampos: Boolean; begin Result := true; if TUtilidades.IsEmpty(edtLogin.Text) then begin Result := false; ShowMessage('Informe o Login.'); edtLogin.SetFocus; end else if TUtilidades.IsEmpty(edtSenha.Text) then begin Result := false; ShowMessage('Informe a Senha.'); edtSenha.SetFocus; end else if TUtilidades.IsEmpty(edtSenhaConfirma.Text) then begin Result := false; ShowMessage('Confirme a Senha.'); edtSenhaConfirma.SetFocus; end else if (edtSenha.Text <> edtSenhaConfirma.Text) and (not TUtilidades.IsEmpty(edtSenha.Text)) and (not TUtilidades.IsEmpty(edtSenhaConfirma.Text)) then begin Result := false; ShowMessage('As senhas estão diferentes.'); end; end; end.
unit Prototype.Classes.IdInfo; interface type TIdInfo = class private FIdNumber: Integer; procedure SetIdNumber(const Value: Integer); public constructor Create(AIdNumber: Integer); property IdNumber: Integer read FIdNumber write SetIdNumber; end; implementation { TIdInfo } constructor TIdInfo.Create(AIdNumber: Integer); begin FIdNumber := AIdNumber; end; procedure TIdInfo.SetIdNumber(const Value: Integer); begin FIdNumber := Value; end; end.
unit ALAndroidAppsFlyerApi; interface uses Androidapi.JNIBridge, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes; type {***************************************} JAppsFlyerConversionListener = interface; JALAppsFlyerLib = interface; {*******************************************************} JAppsFlyerConversionListenerClass = interface(IJavaClass) ['{E7C1E146-2E55-478F-9218-C1DAA89DA964}'] end; [JavaSignature('com/appsflyer/AppsFlyerConversionListener')] JAppsFlyerConversionListener = interface(IJavaInstance) ['{ACE202A5-AD33-4D2D-876B-296874928AA4}'] procedure onAppOpenAttribution(conversionData: JMap); cdecl; procedure onAttributionFailure(errorMessage: JString); cdecl; procedure onInstallConversionDataLoaded(conversionData: JMap); cdecl; procedure onInstallConversionFailure(errorMessage: JString); cdecl; end; TJAppsFlyerConversionListener = class(TJavaGenericImport<JAppsFlyerConversionListenerClass, JAppsFlyerConversionListener>) end; {*******************************} //this class because of this bug: //https://stackoverflow.com/questions/53141813/delphi-android-java-class-init-function JALAppsFlyerLibClass = interface(JObjectClass) ['{48A22162-044E-48B1-BBA0-C8D02162A522}'] {class} procedure initialize(key: JString; conversionListener: JAppsFlyerConversionListener; context: JContext); cdecl; {class} procedure sendDeepLinkData(activity: JActivity); cdecl; {class} procedure startTracking(application: JApplication); cdecl; {class} procedure trackEvent(context: JContext; eventName: JString; eventValues: JHashMap); cdecl; overload; {class} procedure trackEvent(context: JContext; eventName: JString); cdecl; overload; {class} procedure unregisterConversionListener; cdecl; {class} procedure setAndroidIdData(androidIdData: JString); cdecl; {class} procedure enableUninstallTracking(senderId: JString); cdecl; {class} procedure updateServerUninstallToken(context: JContext; refreshedToken: JString); cdecl; {class} procedure setCustomerUserId(id: JString); cdecl; end; [JavaSignature('com/alcinoe/appsflyer/ALAppsFlyer')] JALAppsFlyerLib = interface(JObject) ['{6145C2CE-433B-4F69-B996-614EA0C015A5}'] end; TJALAppsFlyerLib = class(TJavaGenericImport<JALAppsFlyerLibClass, JALAppsFlyerLib>) end; implementation {**********************} procedure RegisterTypes; begin TRegTypes.RegisterType('ALAndroidAppsFlyerApi.JAppsFlyerConversionListener', TypeInfo(ALAndroidAppsFlyerApi.JAppsFlyerConversionListener)); TRegTypes.RegisterType('ALAndroidAppsFlyerApi.JALAppsFlyerLib', TypeInfo(ALAndroidAppsFlyerApi.JALAppsFlyerLib)); end; initialization RegisterTypes; end.
unit USelfHelpConst; interface uses SysUtils, UDataModule; const {*Frame ID*} cFI_FrameMain = $0000; //主显示 cFI_FrameQueryCard = $0001; //磁卡查询 cFI_FrameMakeCard = $0002; //制卡 cFI_FramePrint = $0003; //打印 cFI_FramePrintBill = $0009; //打印小票 cFI_FrameSafeInfo = $0008; //安全须知 cFI_FrameInputCertificate = $0004; //输入取卡凭证 cFI_FrameReadCardID = $0005; //身份证号查询 cFI_FramePurERPMakeCard = $0006; //ERP采购单制卡 cFI_FrameSaleMakeCard = $0007; //ERP销售制卡 {*Form ID*} cFI_FormReadCardID = $0050; //读取身份证 {*CMD ID*} cCmd_QueryCard = $0001; //查询卡片 cCmd_FrameQuit = $0002; //退出窗口 cCmd_MakeCard = $0003; //制卡 cCmd_SelectZhiKa = $0004; //选择商城订单 cCmd_MakeNCSaleCard = $0010; //NC订单制卡 cSendWeChatMsgType_AddBill = 1; //开提货单 cSendWeChatMsgType_OutFactory = 2; //车辆出厂 cSendWeChatMsgType_Report = 3; //报表 cSendWeChatMsgType_DelBill = 4; //删提货单 c_WeChatStatusCreateCard = 1; //订单已办卡 c_WeChatStatusFinished = 3; //订单已完成 c_WeChatStatusIn = 2; //订单已进厂 c_WeChatStatusDeleted = 100; type TSysParam = record FProgID : string; //程序标识 FLocalIP : string; //本机IP FLocalMAC : string; //本机MAC FLocalName : string; //本机名称 FMITServURL : string; //业务服务 FHYDanPrinter:string; //指定化验单打印的打印机 FCardPrinter: string; //指定小票打印机 FTTCEK720ID : string; //指定发卡机 FAICMPDCount: Integer; //自助拼单个数 FSafeInfoFoot : string; //安全提醒页脚 end; //系统参数 PMallPurchaseItem = ^stMallPurchaseItem; stMallPurchaseItem = record FOrder_Id : string; //商城ID FProvID : string; //供应商ID FProvName : string; //供应商名称 FGoodsID : string; //物料编号 FGoodsname: string; //物料名称 FData : string; //数量 FMaxMum : string; //最大供应量 FZhiKaNo : string; //合同编号 FTrackNo : string; //车牌号 FArea : string; end; // 采购单 TOrderInfoItem = record FZhiKaNo: string; FCusID: string; //客户号 FCusName: string; //客户名 FSaleMan: string; //业务员 FStockID: string; //物料号 FStockName: string; //物料名 FStockBrand: string; //物料品牌 FStockArea : string; //产地,矿点 FTruck: string; //车牌号 FBatchCode: string; //批次号 FOrders: string; //订单号(可多张) FValue: Double; //可用量 FBm: string; //喷码发送的中文编码 FPd: string; FWxZhuId: string; FWxZiId: string; FPhy: string; FTransType: string; FSelect: Boolean; end; TOrderInfoItems = array of TOrderInfoItem; resourcestring sImages = 'Images\'; sConfig = 'Config.Ini'; sConfigSec = 'Config'; //主配置小节 sForm = 'FormInfo.Ini'; sDB = 'DBConn.Ini'; sReportDir = 'Report\'; //报表目录 sHint = '提示'; //对话框标题 sWarn = '警告'; //== sAsk = '询问'; //询问对话框 sError = '未知错误'; //错误对话框 sUnCheck = '□'; sCheck = '[√]'; var gPath: string; //系统路径 gSysParam:TSysParam; //程序环境参数 gTimeCounter: Int64; //计时器 gNeedSearchPurOrder : Boolean; gNeedSearchSaleOrder : Boolean; gNeedClear : Boolean; gAgree : Boolean; function GetIDCardNumCheckCode(nIDCardNum: string): string; //身份证号校验算法 implementation //Date: 2017/6/14 //Parm: 身份证号的前17位 //Desc: 获取身份证号校验码 function GetIDCardNumCheckCode(nIDCardNum: string): string; const cWIArray: Array[0..16] of Integer = (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2); cModCode: array [0..10] of string = ('1','0','X','9','8','7','6','5','4','3','2'); var nIdx, nSum, nModResult: Integer; begin Result := ''; if Length(nIDCardNum) < 17 then Exit; nSum := 0; for nIdx := 0 to Length(cWIArray) - 1 do begin nSum := nSum + StrToInt(nIDCardNum[nIdx + 1]) * cWIArray[nIdx]; end; nModResult := nSum mod 11; Result := cModCode[nModResult]; end; end.
unit USettings; interface uses System.IniFiles; type TSettings = class strict private class var FIni: TIniFile; FIniFolder: string; strict private class function GetBoolValue(const AParam: string; const ADefVal: Boolean): Boolean; class function GetIntValue(const AParam: string; const ADefVal: Integer): Integer; class function GetStrValue(const AParam, ADefVal: string): string; class procedure SetBoolValue(const AParam: string; const AVal: Boolean); class procedure SetIntValue(const AParam: string; const AVal: Integer); class procedure SetStrValue(const AParam, AVal: string); strict private class function GetWMSDatabase: string; static; class procedure SetWMSDatabase(const AValue: string); static; class function GetAlanServer: string; static; class procedure SetAlanServer(const AValue: string); static; class function GetGatewayIntervalMinute: Cardinal; static; class procedure SetGatewayIntervalMinute(const AValue: Cardinal); static; class function GetTimerInterval: Cardinal; static; class procedure SetTimerInterval(const AValue: Cardinal); static; class function GetUseLog: Boolean; static; class procedure SetUseLog(const AValue: Boolean); static; public class constructor Create; class destructor Destroy; class function GetLogFolder: string; class procedure ApplyDefault; class property WMSDatabase: string read GetWMSDatabase write SetWMSDatabase; class property AlanServer: string read GetAlanServer write SetAlanServer; class property TimerInterval: Cardinal read GetTimerInterval write SetTimerInterval; class property GatewayIntervalMinute: Cardinal read GetGatewayIntervalMinute write SetGatewayIntervalMinute; class property UseLog: Boolean read GetUseLog write SetUseLog; end; function IsService: Boolean; implementation uses System.IOUtils , System.Classes , System.SysUtils , System.SyncObjs , Winapi.SHFolder , Winapi.Windows , UConstants ; var mCS: TCriticalSection; const // INI params cINI_Section = 'Settings'; cUseLogParam = 'UseLog'; cAlanServerParam = 'AlanServer'; cWMSDatabaseParam = 'WMSDatabase'; cTimerIntervalParam = 'TimerInterval'; cGatewayIntervalParam = 'GatewayIntervalMinute'; // Default values cTimerIntervalDef = 10000; cGatewayIntervalMinuteDef = 3; // интервал 3 минуты cAlanServerDef = 'integer-srv.alan.dp.ua'; cWMSDatabaseDef = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=wms-db-1.alan.dp.ua)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=wmsdb)))'; function IsService: Boolean; var C: Cardinal; Data: USEROBJECTFLAGS; begin GetUserObjectInformation(GetProcessWindowStation, UOI_FLAGS, @Data, SizeOf(Data), C); Result := (Data.dwFlags and WSF_VISIBLE <> WSF_VISIBLE) or FindCmdLineSwitch('INSTALL', ['-', '/'], True) or FindCmdLineSwitch('UNINSTALL', ['-', '/'], True); end; function GetPublicDocuments: string; var LStr: array[0 .. MAX_PATH] of Char; const CSIDL_COMMON_DOCUMENTS = $002E; begin SetLastError(ERROR_SUCCESS); if SHGetFolderPath(0, CSIDL_COMMON_DOCUMENTS, 0, 0, @LStr) = S_OK then Result := LStr; end; function GetAppName: string; begin Result := ExtractFileName(ParamStr(0)); Result := ChangeFileExt(Result, ''); end; function GetAppDataFolder: string; begin if IsService then Result := IncludeTrailingPathDelimiter(GetPublicDocuments) + GetAppName else {$IFDEF DEBUG} Result := ExtractFilePath(ParamStr(0)); {$ELSE} Result := IncludeTrailingPathDelimiter(TPath.GetDocumentsPath) + GetAppName; {$ENDIF} end; function GetINIFolder: string; begin Result := GetAppDataFolder; end; { TSettings } class procedure TSettings.ApplyDefault; begin WMSDatabase := cWMSDatabaseDef; AlanServer := cAlanServerDef; TimerInterval := cTimerIntervalDef; UseLog := True; end; class constructor TSettings.Create; var sIniFile: string; tmpFS: TFileStream; begin FIniFolder := GetINIFolder; if not TDirectory.Exists(FIniFolder) then TDirectory.CreateDirectory(FIniFolder); FIniFolder := IncludeTrailingPathDelimiter(FIniFolder); sIniFile := FIniFolder + ChangeFileExt(ExtractFileName(ParamStr(0)), '.ini'); if not TFile.Exists(sIniFile) then begin tmpFS := TFile.Create(sIniFile); tmpFS.Free; end; Assert(TFile.Exists(sIniFile)); try FIni := TIniFile.Create(sIniFile); except FIni := nil; end; end; class destructor TSettings.Destroy; begin FreeAndNil(FIni); end; class function TSettings.GetAlanServer: string; begin mCS.Enter; try Result := GetStrValue(cAlanServerParam, cAlanServerDef); finally mCS.Leave; end; end; class function TSettings.GetBoolValue(const AParam: string; const ADefVal: Boolean): Boolean; var ValueExist: Boolean; begin Result := ADefVal; if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try begin ValueExist := FIni.SectionExists(cINI_Section); ValueExist := ValueExist and FIni.ValueExists(cINI_Section, AParam); if ValueExist then Result := FIni.ReadBool(cINI_Section, AParam, ADefVal) else FIni.WriteBool(cINI_Section, AParam, ADefVal); end; finally System.TMonitor.Exit(FIni); end; end; end; class function TSettings.GetGatewayIntervalMinute: Cardinal; begin mCS.Enter; try Result := GetIntValue(cGatewayIntervalParam, cGatewayIntervalMinuteDef); finally mCS.Leave; end; end; class function TSettings.GetIntValue(const AParam: string; const ADefVal: Integer): Integer; var ValueExist: Boolean; begin Result := ADefVal; if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try ValueExist := FIni.SectionExists(cINI_Section); ValueExist := ValueExist and FIni.ValueExists(cINI_Section, AParam); if ValueExist then Result := FIni.ReadInteger(cINI_Section, AParam, ADefVal) else FIni.WriteInteger(cINI_Section, AParam, ADefVal); finally System.TMonitor.Exit(FIni); end; end; end; class function TSettings.GetLogFolder: string; begin mCS.Enter; try Result := GetAppDataFolder + '\Log' ; finally mCS.Leave; end; end; class function TSettings.GetStrValue(const AParam, ADefVal: string): string; var ValueExist: Boolean; begin Result := ADefVal; if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try ValueExist := FIni.SectionExists(cINI_Section); ValueExist := ValueExist and FIni.ValueExists(cINI_Section, AParam); if ValueExist then Result := FIni.ReadString(cINI_Section, AParam, ADefVal) else FIni.WriteString(cINI_Section, AParam, ADefVal); finally System.TMonitor.Exit(FIni); end; end; end; class function TSettings.GetTimerInterval: Cardinal; begin mCS.Enter; try Result := GetIntValue(cTimerIntervalParam, cTimerIntervalDef); finally mCS.Leave; end; end; class function TSettings.GetUseLog: Boolean; begin mCS.Enter; try Result := GetBoolValue(cUseLogParam, False); finally mCS.Leave; end; end; class function TSettings.GetWMSDatabase: string; begin mCS.Enter; try Result := GetStrValue(cWMSDatabaseParam, cWMSDatabaseDef); finally mCS.Leave; end; end; class procedure TSettings.SetAlanServer(const AValue: string); begin mCS.Enter; try SetStrValue(cAlanServerParam, AValue); finally mCS.Leave; end; end; class procedure TSettings.SetBoolValue(const AParam: string; const AVal: Boolean); begin if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try FIni.WriteBool(cINI_Section, AParam, AVal); finally System.TMonitor.Exit(FIni); end; end; end; class procedure TSettings.SetGatewayIntervalMinute(const AValue: Cardinal); begin mCS.Enter; try SetIntValue(cGatewayIntervalParam, AValue); finally mCS.Leave; end; end; class procedure TSettings.SetIntValue(const AParam: string; const AVal: Integer); begin if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try FIni.WriteInteger(cINI_Section, AParam, AVal); finally System.TMonitor.Exit(FIni); end; end; end; class procedure TSettings.SetStrValue(const AParam, AVal: string); begin if Assigned(FIni) then begin System.TMonitor.Enter(FIni); try FIni.WriteString(cINI_Section, AParam, AVal); finally System.TMonitor.Exit(FIni); end; end; end; class procedure TSettings.SetTimerInterval(const AValue: Cardinal); begin mCS.Enter; try SetIntValue(cTimerIntervalParam, AValue); finally mCS.Leave; end; end; class procedure TSettings.SetUseLog(const AValue: Boolean); begin mCS.Enter; try SetBoolValue(cUseLogParam, AValue); finally mCS.Leave; end; end; class procedure TSettings.SetWMSDatabase(const AValue: string); begin mCS.Enter; try SetStrValue(cWMSDatabaseParam, AValue); finally mCS.Leave; end; end; initialization mCS := TCriticalSection.Create; finalization FreeAndNil(mCS); end.
unit uVendasDAO; interface uses uProdutosModel, uVendaModel,uDMConexaoDAO,DB,ZAbstractRODataset, ZAbstractDataset, ZDataset, generics.Collections,StrUtils, SysUtils; type TVendasDAO = class public function Gravar(VendaModel:TVendasModel):Boolean; function RecuperaIdVenda(Qry:TZQuery):Integer; end; implementation { TVendasDAO } function TVendasDAO.RecuperaIdVenda(Qry:TZQuery):Integer; begin Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('Select Last_Insert_Id() as CODVENDA'); Qry.Open; result := Qry.FieldByName('CODVENDA').AsInteger; end; function TVendasDAO.Gravar(VendaModel: TVendasModel): Boolean; function InsereVenda(Qry:TZQuery):Boolean; var Sucesso:Boolean; begin Sucesso := true; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('insert into venda_cab(id_cliente, data_venda, faturado, data_faturado )'+ ' values(:id_cliente, :data_venda, :faturado, :data_faturado )'); Qry.ParamByName('id_cliente').AsInteger := VendaModel.Cliente.Id; Qry.ParamByName('data_venda').AsDate := VendaModel.DataVenda; Qry.ParamByName('faturado').AsInteger := StrToInt(IfThen(VendaModel.Faturado = True, '1','0')); Qry.ParamByName('data_faturado').AsDate := VendaModel.DataFaturado; try Qry.ExecSQL; except Sucesso := False; end; Result := Sucesso; end; function InsereItensVenda(Qry:TZQuery;IdVenda:Integer; ListaProdutos:TObjectList<TProdutosModel>):Boolean; var ProdutosModel:TProdutosModel; Sucesso:Boolean; begin Sucesso := True; for ProdutosModel in ListaProdutos do begin Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('insert into venda_item(Qtd, valor_unitario, '+ ' desconto, id_venda_cab, id_produto ) '+ ' values(:Qtd, :valor_unitario, :desconto, :id_venda_cab, :id_produto )'); Qry.ParamByName('Qtd').AsFloat := ProdutosModel.Qtd; Qry.ParamByName('valor_unitario').AsFloat := ProdutosModel.Custo; Qry.ParamByName('desconto').AsFloat := ProdutosModel.Desconto; Qry.ParamByName('id_venda_cab').AsInteger := IdVenda; Qry.ParamByName('id_produto').AsInteger := ProdutosModel.Id; try Qry.ExecSQL; except Sucesso := False; end; end; Result := Sucesso; end; var Qry:TZQuery; IdVenda:Integer; SucessoVenda,SucessoItemVenda:Boolean; begin Qry := DMConexao.CriaQuery; try SucessoVenda:=InsereVenda(Qry); IdVenda := RecuperaIdVenda(Qry); SucessoItemVenda:=InsereItensVenda(Qry, IdVenda, VendaModel.ListaDeProdutos); finally Qry.Free; end; Result:=(SucessoVenda and SucessoItemVenda); end; end.
unit broadcastreceiver; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TIntentActionFiter = (afTimeTick, //Intent.ACTION_TIME_TICK afTimeChanged, //Intent.ACTION_TIME_CHANGED afTimeZoneChanged, //Intent.ACTION_TIMEZONE_CHANGED afBootCompleted, //Intent.ACTION_BOOT_COMPLETED afBatteryChanged, //Intent.ACTION_BATTERY_CHANGED afPowerConnected, //Intent.ACTION_POWER_CONNECTED afPowerDisconnected, //Intent.ACTION_POWER_DISCONNECTED afShutDown, //Intent.ACTION_SHUTDOWN afSMSReceived, //android.provider.Telephony.SMS_RECEIVED afDownloadComplete, //android.intent.action.DOWNLOAD_COMPLETE or DownloadManager.ACTION_DOWNLOAD_COMPLETE afPhoneState, //android.intent.action.PHONE_STATE afNewOutgoingCall, //android.intent.action.NEW_OUTGOING_CALL afScreenOn, //Intent.ACTION_SCREEN_ON afScreenOff, //Intent.ACTION_SCREEN_OFF afNone); TOnReceiver = procedure(Sender: TObject; intent: jObject) of Object; {Draft Component code by "Lazarus Android Module Wizard" [1/18/2015 2:13:27]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jBroadcastReceiver = class(jControl) private FIntentActionFilter: TIntentActionFiter; FOnReceiver: TOnReceiver; FRegistered: boolean; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure RegisterIntentActionFilter(_intentActionFilter: string); overload; procedure RegisterIntentActionFilter(_intentActionFilter: TIntentActionFiter); overload; procedure SetIntentActionFilter(_intentActionFilter: TIntentActionFiter); procedure Unregister(); function GetResultCode(): TAndroidResult; function GetResultData(): string; function GetResultExtras(): jObject; procedure GenEvent_OnBroadcastReceiver(Obj: TObject; intent: jObject); property Registered: boolean read FRegistered write FRegistered; published property IntentActionFilter: TIntentActionFiter read FIntentActionFilter write SetIntentActionFilter; property OnReceiver: TOnReceiver read FOnReceiver write FOnReceiver; end; function jBroadcastReceiver_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jBroadcastReceiver_RegisterIntentActionFilter(env: PJNIEnv; _jbroadcastreceiver: JObject; _intentAction: integer); function jBroadcastReceiver_GetResultExtras(env: PJNIEnv; _jbroadcastreceiver: JObject): jObject; implementation {--------- jBroadcastReceiver --------------} constructor jBroadcastReceiver.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... FRegistered:= False; FIntentActionFilter:= afNone; end; destructor jBroadcastReceiver.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jni_free(gApp.jni.jEnv, FjObject); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jBroadcastReceiver.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jBroadcastReceiver_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); if FjObject = nil then exit; FInitialized:= True; if FIntentActionFilter <> afNone then begin jBroadcastReceiver_RegisterIntentActionFilter(gApp.jni.jEnv, FjObject, Ord(FIntentActionFilter)); FRegistered:= True; end; end; procedure jBroadcastReceiver.RegisterIntentActionFilter(_intentActionFilter: string); begin //in designing component state: set value here... if FInitialized then begin FRegistered:= True; jni_proc_t(gApp.jni.jEnv, FjObject, 'RegisterIntentActionFilter', _intentActionFilter); end; end; procedure jBroadcastReceiver.RegisterIntentActionFilter(_intentActionFilter: TIntentActionFiter); begin //in designing component state: set value here... if FInitialized then begin FRegistered:= True; jBroadcastReceiver_RegisterIntentActionFilter(gApp.jni.jEnv, FjObject, Ord(_intentActionFilter)); end; end; procedure jBroadcastReceiver.SetIntentActionFilter(_intentActionFilter: TIntentActionFiter); begin //in designing component state: set value here... FIntentActionFilter:= _intentActionFilter; if FInitialized then begin FRegistered:= True; jBroadcastReceiver_RegisterIntentActionFilter(gApp.jni.jEnv, FjObject, Ord(_intentActionFilter)); end; end; procedure jBroadcastReceiver.Unregister(); begin //in designing component state: set value here... if FInitialized then begin if FRegistered then begin jni_proc(gApp.jni.jEnv, FjObject, 'Unregister'); FRegistered:= False; end; end; end; procedure jBroadcastReceiver.GenEvent_OnBroadcastReceiver(Obj: TObject; intent: jObject); begin if Assigned(FOnReceiver) then FOnReceiver(Obj, intent); end; function jBroadcastReceiver.GetResultCode(): TAndroidResult; begin //in designing component state: result value here... Result:= RESULT_CANCELED; if FInitialized then begin Result:= TAndroidResult(jni_func_out_i(gApp.jni.jEnv, FjObject, 'GetResultCode')); end; end; function jBroadcastReceiver.GetResultData(): string; begin //in designing component state: result value here... if FInitialized then Result:= jni_func_out_t(gApp.jni.jEnv, FjObject, 'GetResultData'); end; function jBroadcastReceiver.GetResultExtras(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jBroadcastReceiver_GetResultExtras(gApp.jni.jEnv, FjObject); end; {-------- jBroadcastReceiver_JNI_Bridge ----------} function jBroadcastReceiver_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin result := nil; if (env = nil) or (this = nil) then exit; jCls:= Get_gjClass(env); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'jBroadcastReceiver_jCreate', '(J)Ljava/lang/Object;'); if jMethod = nil then goto _exceptionOcurred; jParams[0].j:= _Self; Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); _exceptionOcurred: if jni_ExceptionOccurred(env) then result := nil; end; procedure jBroadcastReceiver_RegisterIntentActionFilter(env: PJNIEnv; _jbroadcastreceiver: JObject; _intentAction: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin if (env = nil) or (_jbroadcastreceiver = nil) then exit; jCls:= env^.GetObjectClass(env, _jbroadcastreceiver); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'RegisterIntentActionFilter', '(I)V'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; jParams[0].i:= _intentAction; env^.CallVoidMethodA(env, _jbroadcastreceiver, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; function jBroadcastReceiver_GetResultExtras(env: PJNIEnv; _jbroadcastreceiver: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; label _exceptionOcurred; begin Result := nil; if (env = nil) or (_jbroadcastreceiver = nil) then exit; jCls:= env^.GetObjectClass(env, _jbroadcastreceiver); if jCls = nil then goto _exceptionOcurred; jMethod:= env^.GetMethodID(env, jCls, 'GetResultExtras', '()Landroid/os/Bundle;'); if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end; Result:= env^.CallObjectMethod(env, _jbroadcastreceiver, jMethod); env^.DeleteLocalRef(env, jCls); _exceptionOcurred: jni_ExceptionOccurred(env); end; end.
unit SectionSetHolder; interface uses AbstractDataSetHolder, SysUtils, Classes; type TSectionSetFieldDefs = class (TAbstractDataSetFieldDefs) private function GetSectionIdFieldName: String; procedure SetSectionIdFieldName(const Value: String); public ParentIdSectionFieldName: String; SectionNameFieldName: String; property SectionIdFieldName: String read GetSectionIdFieldName write SetSectionIdFieldName; end; TSectionSetFieldDefsClass = class of TSectionSetFieldDefs; TSectionSetHolder = class (TAbstractDataSetHolder) private function GetParentIdSectionFieldName: String; function GetSectionIdFieldName: String; function GetSectionNameFieldName: String; function GetSectionSetFieldDefs: TSectionSetFieldDefs; procedure SetParentIdSectionFieldName(const Value: String); procedure SetSectionIdFieldName(const Value: String); procedure SetSectionNameFieldName(const Value: String); procedure SetSectionSetFieldDefs(const Value: TSectionSetFieldDefs); function GetParentIdSectionFieldValue: Variant; function GetSectionIdFieldValue: Variant; function GetSectionNameFieldValue: String; procedure SetParentIdSectionFieldValue(const Value: Variant); procedure SetSectionIdFieldValue(const Value: Variant); procedure SetSectionNameFieldValue(const Value: String); protected public property SectionIdFieldName: String read GetSectionIdFieldName write SetSectionIdFieldName; property ParentIdSectionFieldName: String read GetParentIdSectionFieldName write SetParentIdSectionFieldName; property SectionNameFieldName: String read GetSectionNameFieldName write SetSectionNameFieldName; public property SectionIdFieldValue: Variant read GetSectionIdFieldValue write SetSectionIdFieldValue; property ParentIdSectionFieldValue: Variant read GetParentIdSectionFieldValue write SetParentIdSectionFieldValue; property SectionNameFieldValue: String read GetSectionNameFieldValue write SetSectionNameFieldValue; public property FieldDefs: TSectionSetFieldDefs read GetSectionSetFieldDefs write SetSectionSetFieldDefs; end; TSectionSetHolderClass = class of TSectionSetHolder; implementation uses Variants; { TSectionSetHolder } function TSectionSetHolder.GetParentIdSectionFieldName: String; begin Result := FieldDefs.ParentIdSectionFieldName; end; function TSectionSetHolder.GetParentIdSectionFieldValue: Variant; begin Result := GetDataSetFieldValue(ParentIdSectionFieldName, Null); end; function TSectionSetHolder.GetSectionIdFieldName: String; begin Result := FieldDefs.SectionIdFieldName; end; function TSectionSetHolder.GetSectionIdFieldValue: Variant; begin Result := GetDataSetFieldValue(SectionIdFieldName, Null); end; function TSectionSetHolder.GetSectionNameFieldName: String; begin Result := FieldDefs.SectionNameFieldName; end; function TSectionSetHolder.GetSectionNameFieldValue: String; begin Result := GetDataSetFieldValue(SectionNameFieldName, ''); end; function TSectionSetHolder.GetSectionSetFieldDefs: TSectionSetFieldDefs; begin Result := TSectionSetFieldDefs(FFieldDefs); end; procedure TSectionSetHolder.SetParentIdSectionFieldName(const Value: String); begin FieldDefs.ParentIdSectionFieldName := Value; end; procedure TSectionSetHolder.SetParentIdSectionFieldValue(const Value: Variant); begin SetDataSetFieldValue(ParentIdSectionFieldName, Value); end; procedure TSectionSetHolder.SetSectionIdFieldName(const Value: String); begin FieldDefs.SectionIdFieldName := Value; end; procedure TSectionSetHolder.SetSectionIdFieldValue(const Value: Variant); begin SetDataSetFieldValue(SectionIdFieldName, Value); end; procedure TSectionSetHolder.SetSectionNameFieldName(const Value: String); begin FieldDefs.SectionNameFieldName := Value; end; procedure TSectionSetHolder.SetSectionNameFieldValue(const Value: String); begin SetDataSetFieldValue(SectionNameFieldName, Value); end; procedure TSectionSetHolder.SetSectionSetFieldDefs( const Value: TSectionSetFieldDefs); begin SetFieldDefs(Value); end; { TSectionSetFieldDefs } function TSectionSetFieldDefs.GetSectionIdFieldName: String; begin Result := RecordIdFieldName; end; procedure TSectionSetFieldDefs.SetSectionIdFieldName(const Value: String); begin RecordIdFieldName := Value; end; end.
unit UConexao; interface Uses Classes, FireDAC.Comp.Client, SysUtils, Data.DB, DMGeral, ULogSistema; type TCConexao = class private { private declarations } Procedure GeraLogCampo(DataSet : TDataSet); Procedure BeforeInsert(DataSet : TDataSet); Procedure BeforeDelete(DataSet : TDataSet); Procedure BeforeEdit(DataSet : TDataSet); Procedure BeforePost(DataSet : TDataSet); Procedure AfterInsert(DataSet : TDataSet); Procedure AfterDelete(DataSet : TDataSet); Procedure AfterEdit(DataSet : TDataSet); Procedure AfterPost(DataSet : TDataSet); protected { protected declarations } public VcSqlConexao : TFDQuery; Function ExecuteSql(PpSQL:String):String; Function ExecuteRetornoValor(Campo, PpSQL:String):String; Function ExecuteComando(PpComando:String):String; published { published declarations } Constructor Create; // declaração do metodo construtor Destructor Destroy; Override; // declaração do metodo destrutor end; Var VcConexao : TCConexao; implementation { TCConexao } constructor TCConexao.Create; begin inherited; VcSqlConexao := TFDQuery.Create(nil); VcSqlConexao.Connection := FDmGeral.FdConexao; VcSqlConexao.BeforeInsert := BeforeInsert; VcSqlConexao.BeforeDelete := BeforeDelete; VcSqlConexao.BeforeEdit := BeforeEdit; VcSqlConexao.BeforePost := BeforePost; VcSqlConexao.AfterInsert := AfterInsert; VcSqlConexao.AfterDelete := AfterDelete; VcSqlConexao.AfterEdit := AfterEdit; VcSqlConexao.AfterPost := AfterPost; end; function TCConexao.ExecuteComando(PpComando: String): String; begin try VcSqlConexao.Close; VcSqlConexao.SQL.Text := PpComando; VcSqlConexao.ExecSQL(True); VcLogSistema.GravarLog('SQL: ' + PpComando); Except VcLogSistema.GravarLog('Erro ao executar : ' + PpComando); end; end; function TCConexao.ExecuteRetornoValor(Campo, PpSQL: String): String; begin try VcSqlConexao.Close; VcSqlConexao.SQL.Text := PpSQL; VcSqlConexao.Open; if (VcSqlConexao.RecordCount = 0) then Result := '' else Result := VcSqlConexao.FieldByName(Campo).AsString; VcLogSistema.GravarLog('SQL: ' + PpSQL); Except VcLogSistema.GravarLog('Erro ao executar : ' + PpSQL); Result := 'Problema ao consultar tabela!'; end; end; function TCConexao.ExecuteSql(PpSQL: String): String; begin try VcSqlConexao.Close; VcSqlConexao.SQL.Text := PpSQL; VcSqlConexao.Open; if (VcSqlConexao.RecordCount = 0) then Result := 'Registro não encontrado!'; VcLogSistema.GravarLog('SQL: ' + PpSQL); Except Result := 'Problema ao consultar tabela!'; VcLogSistema.GravarLog('SQL erro: ' + PpSQL); end; end; procedure TCConexao.GeraLogCampo(DataSet : TDataSet); var VpLaco : Integer; VpDadoLog: String; begin VpDadoLog := ''; for VpLaco := 0 to DataSet.FieldCount-1 do VpDadoLog := VpDadoLog + DataSet.Fields[VpLaco].FieldName + ': ' + DataSet.Fields[VpLaco].AsString + ','; VcLogSistema.GravarLog(VpDadoLog); end; procedure TCConexao.BeforeEdit(DataSet: TDataSet); begin // end; procedure TCConexao.BeforeInsert(DataSet: TDataSet); begin // end; procedure TCConexao.BeforePost(DataSet: TDataSet); begin VcLogSistema.GravarLog('Salvando registro da tabela:' + VcSqlConexao.Table.Name); GeraLogCampo(DataSet); end; procedure TCConexao.BeforeDelete(DataSet: TDataSet); begin VcLogSistema.GravarLog('Deletando registro da tabela:' + VcSqlConexao.Table.Name); GeraLogCampo(DataSet); end; procedure TCConexao.AfterPost(DataSet : TDataSet); begin VcLogSistema.GravarLog('Registro salvo na tabela:' + VcSqlConexao.Table.Name); end; procedure TCConexao.AfterDelete(DataSet : TDataSet); begin VcLogSistema.GravarLog('Registro deletado da tabela:' + VcSqlConexao.Table.Name); end; procedure TCConexao.AfterEdit(DataSet : TDataSet); begin // end; procedure TCConexao.AfterInsert(DataSet : TDataSet); begin // end; destructor TCConexao.Destroy; begin VcSqlConexao.Free; inherited; end; end.
unit bcm_mailbox; interface function ReadMailbox(var AChannel: byte): longword; function WaitMailbox(AChannel: byte): longword; procedure WriteMailbox(AChannel: byte; AData: longword); implementation uses bcm_mem; const MAILBOX_OFFSET = $2000B880; var MAIL0_READ: longword absolute MAILBOX_OFFSET+$00; MAIL0_PEEK: longword absolute MAILBOX_OFFSET+$10; MAIL0_SENDER: longword absolute MAILBOX_OFFSET+$14; MAIL0_STATUS: longword absolute MAILBOX_OFFSET+$18; MAIL0_CONFIG: longword absolute MAILBOX_OFFSET+$1C; MAIL0_WRITE: longword absolute MAILBOX_OFFSET+$20; const MAIL_EMPTY = $40000000; MAIL_FULL = $80000000; function ReadMailbox(var AChannel: byte): longword; var res: LongWord; begin repeat MemBarrier; until (MAIL0_STATUS and MAIL_EMPTY)=0; MemBarrier; res:=MAIL0_READ; AChannel:=res and $F; ReadMailbox:=(res and $FFFFFFF0); end; function WaitMailbox(AChannel: byte): longword; var ch: byte; begin repeat WaitMailbox:=ReadMailbox(ch); until ch=AChannel; end; procedure WriteMailbox(AChannel: byte; AData: longword); begin repeat MemBarrier; until (MAIL0_STATUS and MAIL_FULL)=0; MAIL0_WRITE:=longword(AChannel and $F) or longword(AData and $FFFFFFF0); MemBarrier; end; end.
{ Gerador de classes para SIMPLEORM Desenvolvido por Alan Petry - APNET INFORMATICA LTDA Fone: (54)98415-0888 Email: alanpetry@alnet.eti.br ou alanpetry@outlook.com } unit HSORM.Entidades.PEDIDO; interface uses System.Generics.Collections, System.Classes, Rest.Json, System.JSON, SimpleAttributes; type [Tabela('PEDIDO')] TPEDIDO = class private FID: integer; FNOME: string; FVALOR: real; FDATA: TDate; procedure SetDATA(const Value: TDate); procedure SetID(const Value: integer); procedure SetNOME(const Value: string); procedure SetVALOR(const Value: real); public constructor Create; destructor Destroy; override; published {verificar os atributos do campo de chave primária} {Exemplo: [Campo('NOME_CAMPO'), PK, AutoInc] } [Campo('ID'), PK] property ID: integer read FID write SetID; [Campo('NOME')] property NOME: string read FNOME write SetNome; [Campo('DATA')] property DATA: TDate read FDATA write SetDATA; [Campo('VALOR')] property VALOR: real read FVALOR write SetVALOR; function ToJSONObject: TJsonObject; function ToJsonString: string; end; implementation constructor TPEDIDO.Create; begin end; destructor TPEDIDO.Destroy; begin inherited; end; procedure TPEDIDO.SetDATA(const Value: TDate); begin FDATA := Value; end; procedure TPEDIDO.SetID(const Value: integer); begin FID := Value; end; procedure TPEDIDO.SetNOME(const Value: string); begin FNOME := Value; end; procedure TPEDIDO.SetVALOR(const Value: real); begin FValor := Value; end; function TPEDIDO.ToJSONObject: TJsonObject; begin Result := TJson.ObjectToJsonObject(Self); end; function TPEDIDO.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; end.
{----------------------------------------------------------------------------- Author: Alexander Roth Date: 04-Nov-2006 Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, gemäß Version 2 der Lizenz. Description: alpha is the horizontal angle of the laser light alpha= 0° (or 0) means that the laser light has 90° to the screen, where you can see the laser point alpha=90° (or pi/2) means that this will never hit a wall. It is parralel to the screen BUT: Alpha is not the angle which you see at the screen. Alpha ist the angle that is inside of the Grid. Alpha is that transformed with Refraction (is wanted) and with the x-Deflection (when theta<>0) beta is the horizontal angle of the slit beta=0° (or 0) means that the horizontal axis of the slit('s) are parralel to the screen (or wall) beta =90° (or pi/2) means that the laser light doesn't go though the slit, beacause the horizontal axis of the slit('s) are identical (parallel and same koordinates) gamma is the vertical angle of the laser light gamma= 0° (or 0) means that the laser light has 90° to the screen, where you can see the laser point gamma=90° (or pi/2) means that this will never hit a wall. It is parralel to the screen theta is the vertical angle of the slit theta=0° (or 0) means that the vertical axis of the slit('s) are parralel to the screen (or wall) theta =90° (or pi/2) means that the laser light doesn't go though the slit, beacause the vertical axis of the slit('s) are identical (parallel and same koordinates) -----------------------------------------------------------------------------} //{$DEFINE ExtraInfos} //{$DEFINE CalcTimes} unit Uapparatus; interface uses Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,Math,unit1,comCtrls,uanderes, UChart, LResources, spin, UMathe, UVector; type TLSAxisType=(LSAmplitude,LSIntensity); TxAxisType=(xAngle,xMeter,xlambda); TImageAxisType=(ImageAngle,ImageMeter); TMySlitType=(MySingle,MyN,MyCombi,MyImage); TMinMaxStaus=(mmsMin, mmsMainMax, mmsMinorMax, mmsNoMinMax, mmsEnd); TInterestingFunctionType= function(n:integer):extended of object ; TMinMaxFunctionType= function (z:integer; var Value:extended):TMinMaxStaus of object; {----------------------------------------------------------------------------- Class: TSingleSlit Description: Dies ist die klasse mit der alles beginnt Hier sind die wichtigen Methoden, Felder für den einfach/n-fach Spalt integriert Ich hätte auch eine TSlit klasse schreiben können, die die abstrakten Methoden deklarationen enthält und damit das Interface schafft, aber es ist absolut gleichertig, ob ich eine Vorfahrklasse mit abstrakten Methoden deklariere und dann TSingleSlit=class(TSlit) mache, oder gleich alles hier -----------------------------------------------------------------------------} { TSingleSlit } TSingleSlit=class(TComponent) private SlitType:TMySlitType; UseMaxMin, CalcMaxima, CalcMinima:boolean; Fnumber:byte; Factive:boolean; dialog:TColorDialog; ChartMinMax:TPointChart; box:TOGlBox; FForm:TForm; CheckSTRGOnMouseDown, CheckSTRGMaxMinOnMouseDown, WasRealKlick, FVisible:boolean; ShowMaxLabels, ShowMinLabels:boolean; function MaximaWidth:extended; virtual; procedure WriteFForm(Form:TForm); procedure setactive(value:boolean); virtual; procedure setVisible(value:boolean); procedure OnColorChange(Sender: TObject); procedure ColorOnClick(Sender: TObject); procedure CheckChange(Sender: TObject); procedure CheckOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure CheckMaxMinClick(Sender: TObject); procedure CheckMaxMinOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure writeCaption(var checkbox:TCheckbox); virtual; function AngleOfVec(s:TVec; angleKind:TAngleKind):extended; function KoorStrechtedOfVec(s:TVec; XYZKind:TXYZKind):extended; function XAngleOfVec(s:TVec):extended; function PathDifferenceOfVec(s:TVec):extended; virtual; function YAngleOfVec(s:TVec):extended; function XKoorStrechtedOfVec(s:TVec):extended; function YKoorStrechtedOfVec(s:TVec):extended; function CalcAngleDeflectionVec(alpha:extended):TVec; overload; function MaxFunc(z:integer; var s:TVec):TMinMaxStaus; //nicht belegt! // geteilt, damit ich die leerstellen mitzählen kann function MinFunc(z:integer; var s:TVec):TMinMaxStaus; // geteilt, damit ich die leerstellen mitzählen kann function MaxFunc(z:integer; var alpha:Extended):TMinMaxStaus; virtual; //nicht belegt! // geteilt, damit ich die leerstellen mitzählen kann function MinFunc(z:integer; var alpha:Extended):TMinMaxStaus; virtual; // geteilt, damit ich die leerstellen mitzählen kann // function getInterestingPointInfo(var CountPoints:word):TInterestingFunctionType; virtual; function getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; virtual; function getXFunc(xAxisType:TxAxisType):TFunctionVecType; // function getAntiXFunc(xAxisType:TxAxisType):TFunctionVecType; function getImageFunc(ImageAxisType:TImageAxisType):TFunctionVecType; procedure DelUnVisibleValues; procedure CalcMinMax(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; percision:word=0); virtual; public Values, ValuesMaxMin:TChartValueArray; Chart:TChart; NewCalculatedPoints:integer; check:TCheckbox; checkMaxMin:TCheckbox; LED:TALED; CalcGamma:boolean; //alle alphas im bogenmaß; alpha ist der winkel zur optischen achse function OneSlitAmplitude(s:TVec):extended; // Formel die Für 1 Spalte Stimmt function OneSlitIntensity(s:TVec):extended; // Formel die Für 1 Spalte Stimmt //alle alphas im bogenmaß; alpha ist der winkel zur optischen achse function CalcGyVec:TVec; function CalcGzVec:TVec; function CalcMinMaxAlpha(TheSign:shortint):extended; function CalcMinAlpha:extended; function CalcMaxAlpha:extended; function GammaAngleBog(s:TVec):extended; function GammaAngleDeg(s:TVec):extended; function GammaMeter(s:TVec):extended; procedure getspecifications; procedure Calc(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; Quality:real=20); virtual; procedure DrawOGL; virtual; procedure RefreshChecked; virtual; procedure MakeRightColor; property active:boolean read Factive write setactive; //das greift im hintergrund eigentlich nur auf lambda zu property Visible:boolean read FVisible write setVisible; property number:byte read Fnumber; property Form:TForm read FForm write WriteFForm; constructor create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); virtual; destructor Destroy; override; end; {----------------------------------------------------------------------------- Class: TRSNSlit Description: Abgleitete Klasse von TSingleSlit Hat nur wenige erweiterungen, doch die sind absolut nötig. Oft werden die Methoden von TSingleSlit benutzt -----------------------------------------------------------------------------} { TRSNSlit } TRSNSlit=class(TSingleSlit) private //alle alphas im bogenmaß; alpha ist der winkel zur optischen achse function MaximaWidth:extended; override; procedure writeCaption(var checkbox:TCheckbox); override; //function alpha2lambda(alpha:extended):extended; override; //function lambda2alpha(lambda:extended):extended; override; function PathDifferenceOfVec(s: TVec): extended; override; function MaxFunc(z:integer; var alpha:Extended):TMinMaxStaus; override; function MinFunc(z:integer; var alpha:Extended):TMinMaxStaus; override; //nicht belegt! //function getInterestingPointInfo(var CountPoints:word):TInterestingFunctionType; override; function getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; override; public function NSlitAmplitude(s:TVec):extended; function NSlitIntensity(s:TVec):extended; constructor create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); override; end; {----------------------------------------------------------------------------- Class: TCombiSlit Description: Hier wäre es pratisch wenn man die Methoden von 2 Klassen ableiten könnte, doch da das nicht geht muss ich irgendwie auf die Methoden von TRSNSlit zugreifen das mache ich so: Die Methodennamen so wählen, dass ich auf TSingleSlit Methoden und auf TRSNSlit Methoden zugreifen kann. -----------------------------------------------------------------------------} TCombiSlit=class(TRSNSlit) private //alle alphas im bogenmaß; alpha ist der winkel zur optischen achse procedure writeCaption(var checkbox:TCheckbox); override; function getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; override; function ApproxCombiSlitAmplitude(s:TVec):extended; function HuygensCombiSlitAmplitude(s:TVec):extended; public function CombiSlitAmplitude(s:TVec):extended; function CombiSlitIntensity(s:TVec):extended; constructor create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); override; end; {----------------------------------------------------------------------------- Class: TImageIntensity Description: Nutzt TCombiSlit und die hauptsache, ist das hier kein Graph dargestellt wird, sondern ein bmp und dies als Hintergrund des Diagramms genommen wird deshalb ist die Hauptsache hier die ersetzte Calc Methode -----------------------------------------------------------------------------} { TImageIntensity } TImageIntensity=class(TCombiSlit) private //procedure Draw2ColorLine(xPos1,xPos2:word; Col1,Col2:TColor; Intensity1,Intensity2:real); //procedure DrawColorLine(xPos1,xPos2:word; Col:TColor; Intensity:real); //procedure DrawPixel(xPos:word; Col:TColor; Intensity:real); procedure writeCaption(var checkbox:TCheckbox); override; public procedure DrawOGL; override; constructor create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); override; destructor Destroy; override; end; {----------------------------------------------------------------------------- Class: TArrayItem Description: Die Klasse kapselt ein paar Sachen, die wichtig sind für ein Array Item später. Also z.B. ob es jetzt aktiv ist, oder welche Nummer bzw. Index es hat. -----------------------------------------------------------------------------} { TArrayItem } TArrayItem=class(TComponent) private FForm:TForm1; Factive:boolean; Fnumber:byte; procedure WriteFForm(Form:TForm1); procedure setactive(value:boolean); virtual; public property active:boolean read Factive write setactive; //das greift im hintergrund eigentlich nur auf lambda zu property number:byte read Fnumber; property Form:TForm1 read FForm write WriteFForm; constructor create(AOwner: TComponent; aForm:TForm1; anumber:byte); virtual; end; TUsedFormula=(UFApprox, UFHuygens); {----------------------------------------------------------------------------- Class: TScreem Description: Kapselt den gesamten Bildschirm und was dazu gehört: SingleSlit, NSlit, CombiSlit, ImageIntensity So ist TScreem der Bildschirm und zeichnet auch selbstständig die Kurven auf Gleichrangig zu Tsource und Taperture -----------------------------------------------------------------------------} { TScreem } TScreem=class(TArrayItem) private FColor:TColor; FBox:TOGlBox; procedure LabelChart(xAxis:TxAxisType; LSaxis:TLSAxisType; ImageAxis:TImageAxisType); overload; procedure LabelChart; overload; procedure Calc(bSingleSlit,bNSlit,bCombiSlit,bImage:boolean; Quality:real=20); procedure DrawOGL(bSingleSlit,bNSlit,bCombiSlit,bImage:boolean); procedure setactive(value:boolean); override; public CalcReflection:boolean; SingleSlit:TSingleSlit; NSlit:TRSNSlit; CombiSlit:TCombiSlit; ImageIntensity:TImageIntensity; xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; ColorNumber, CheckNumber :byte; property Color:Tcolor read FColor write FColor; property Box:TOGlBox read FBox; procedure CalcAll(Quality:real=20); procedure CalcOnlyVisible(Quality:real=20); procedure DrawOGLOnlyVisible; procedure deleteAllValues; procedure getspecifications; procedure MakeAllRightColor; constructor create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte); destructor Destroy; override; end; {----------------------------------------------------------------------------- Class: Taperture = öffnung Description: Gibt die Spezifikationen des Spaltes (der zwischen Schirm und Laser steht) an Ist nicht sehr umfachngreich, trotzdem aber gleichrangig wie Tsource und TScreem -----------------------------------------------------------------------------} { Taperture } Taperture=class(TComponent) private FScreenDistance:real; //screen-aperture Form:TForm1; procedure writeScreenDistance(value:real); public slit:record count:integer; distance:extended; //=g=Gitterkonstante width:extended; beta, theta:real; end; LaserHeight:real; // 1 ist standart property ScreenDistance:real read FScreenDistance write writeScreenDistance; { procedure reset;} constructor create(AOwner: TComponent; aForm:TForm1); end; {----------------------------------------------------------------------------- Class: Tsource Description: Hier ist drin: Was für Licht/Teilchen kommen aus dem Laser? Umrechnung zwischen lambda, frequency, energy der Photonen Gleichrangig zu Taperture und TScreem -----------------------------------------------------------------------------} { Tsource } Tsource=class(TArrayItem) private Flambda:real; function getfrequency:Double ; procedure setfrequency(value:Double); function getenergy:Double ; procedure setenergy(value:Double); procedure setlambda(value:Double); procedure setactive(value:boolean); override; function getactive:boolean; virtual; procedure OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TrackBarChange(Sender: TObject); procedure WriteEdits; procedure WriteEditsAndTrackbar; procedure getspecifications; public TrackBar:TTrackBar; lambdaMin, lambdaMax:integer; EditLambda, EditFrequency:TEdit; GroupBox:TGroupBox; procedure CalcOtherEdits(Source:TCustomEdit); property lambda:Double read Flambda write setlambda; //das greift im hintergrund eigentlich nur auf lambda zu property frequency:Double read getfrequency write setfrequency; //das greift im hintergrund eigentlich nur auf lambda zu property energy:Double read getenergy write setenergy; //das greift im hintergrund eigentlich nur auf lambda zu property active:boolean read getactive write setactive; //das greift im hintergrund eigentlich nur auf lambda zu constructor create(AOwner: TComponent; aForm:TForm1; anumber:byte); override; destructor Destroy; override; end; {----------------------------------------------------------------------------- Class: TSaSArray //SaS=Source and Screen Description: Kapselt die Mehreren Schirme und Quellen in einer Klasse Es ist fast eine Art erweitertes Array -----------------------------------------------------------------------------} { TSaSArray } TSaSArray=class private FOnDrawingEnabledChange:TNotifyEvent; FOnQualityChange:TNotifyEvent; FOnIntensityColorFactorChange:TNotifyEvent; Form:TForm1; FQuality:real; FIntensityColorFactor:real; FActiveNumber:byte; FDrawingEnabled:boolean; procedure setActiveNumber(value:byte); procedure OnResize(sender:TObject); procedure writeDrawingEnabled(value:boolean); procedure writeQuality(value:real); procedure writeIntensityColorFactor(value:real); procedure BeginCalc; procedure EndCalc; procedure Calc(OneSlit,NSlit,CombiSlit,Image:boolean); procedure DrawOGL(OneSlit,NSlit,CombiSlit,Image:boolean); public box:TOGlBox; OldChart:record ZoomMin, ZoomMax, OldQuality:real; end; UsedFormula:TUsedFormula; gradient:TGradientBackgroundChart; //Masterbmp:Tbitmap; Source:array of TSource; Screen:array of TScreem; starttime:longword; CalculationTime:integer; function count:word; // procedure delete(idx:word); procedure deleteLastItem; procedure add(AOwner: TComponent); procedure addActive(AOwner: TComponent); procedure SetAllCalcReflection(value:boolean); procedure ShowCorScreen; procedure ChangeAllColor(acolor,agridcolor:Tcolor); procedure ChangeAllChecked(SlitType:TMySlitType; IsMaxMin,bool:boolean); function MinOneChecked(SlitType:TMySlitType):boolean; procedure RefreshAllChecked; procedure deleteAllValues; procedure getAllspecifications; procedure CalcAll; procedure CalcImageIntensity; procedure CalcOnlyVisible; procedure DrawOGLOnlyVisible; procedure CalcAndDrawBox; property ActiveNumber:byte read FActiveNumber write setActiveNumber; procedure ExportAllValues(FileName:string); constructor Create(aForm:TForm1); virtual; destructor Destroy; override; published property OnDrawingEnabledChange:TNotifyEvent read FOnDrawingEnabledChange write FOnDrawingEnabledChange; property OnQualityChange:TNotifyEvent read FOnQualityChange write FOnQualityChange; property OnIntensityColorFactorChange:TNotifyEvent read FOnIntensityColorFactorChange write FOnIntensityColorFactorChange; property DrawingEnabled:boolean read FDrawingEnabled write writeDrawingEnabled; property Quality:real read FQuality write writeQuality; property IntensityColorFactor:real read FIntensityColorFactor write writeIntensityColorFactor; end; procedure getAllspecifications; //ruft von jedem die getspecifications auf const c=299792458; //m/s h=4.13566743E-15; //eVs var SaS:TSaSArray; aperture:Taperture; implementation uses utxt,LCLIntf; {----------------------------------------------------------------------------- Description: ruft von jedem die getspecifications auf Procedure: getAllspecifications Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure getAllspecifications; begin SaS.getAllspecifications; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray TSaSArray //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: deleteLastItem Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.deleteLastItem; var len:byte; begin if SaS.count<=1 then exit; self.ActiveNumber:=SaS.count-2; len:=high(source); source[len].Free; screen[len].Free; setlength(source,len); setlength(screen,len); end; {----------------------------------------------------------------------------- Description: Procedure: add Arguments: (AOwner: TComponent; thisparent:Twincontrol) Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.add(AOwner: TComponent); var len:byte; begin len:=count; if source=nil then begin setlength(source,1); setlength(screen,1); end else begin setlength(source,len+1); setlength(screen,len+1); end; source[len]:=Tsource.create(AOwner,Form,len); screen[len]:=TScreem.create(AOwner,Form,box,len); end; {----------------------------------------------------------------------------- Description: Procedure: addActive Arguments: AOwner: TComponent Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.addActive(AOwner: TComponent); begin self.add(AOwner); SaS.ActiveNumber:=SaS.count-1; end; procedure TSaSArray.SetAllCalcReflection(value: boolean); begin for i:=0 to count-1 do self.Screen[i].CalcReflection:=value; end; {----------------------------------------------------------------------------- Description: Procedure: count Arguments: None Result: word Detailed description: -----------------------------------------------------------------------------} function TSaSArray.count:word; begin result:=length(Source); if length(Source)<>length(Screen) then showmessage('Fehler!!! Bitte schreibe an roth-a@gmx.de dass Arrays unterschiedlich lang sind'+#13+ 'length(Source)= '+IntToStr(length(Source))+#13+ 'length(Screen)= '+IntToStr(length(Screen))); end; {----------------------------------------------------------------------------- Description: Procedure: getAllspecifications Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.getAllspecifications; var i:integer; begin for i:=0 to count-1 do begin source[i].getspecifications; // Screen[i].MakeAllRightColor; screen[i].getspecifications; end; end; {============================================================================== Procedure: Create Belongs to: TSaSArray Result: None Parameters: CForm : TForm1 = Description: ==============================================================================} constructor TSaSArray.Create(AForm:TForm1); begin inherited create; self.Form:=aForm; self.box:=OGLBox; FQuality:=20; FDrawingEnabled:=true; FIntensityColorFactor:=1; CalculationTime:=100; gradient:=TGradientBackgroundChart.Create(box); //box.OnResize:=@self.Onresize; OldChart.ZoomMin:=self.box.LSAxis.Koor.Min; OldChart.ZoomMax:=self.box.LSaxis.Koor.Max; end; {----------------------------------------------------------------------------- Description: Procedure: destroy Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} destructor TSaSArray.destroy; var i:integer; begin for i:=0 to count-1 do begin source[i].Free; screen[i].Free; end; source:=nil; screen:=nil; gradient.Free; inherited destroy; end; {----------------------------------------------------------------------------- Description: Procedure: BeginDraw Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.BeginCalc; begin stop:=false; starttime:=GetTickCount; //self.Masterbmp.Canvas.FillRect(self.Masterbmp.Canvas.ClipRect); Form1.AddLog(''); Form1.AddLog(''); Form1.AddLog('|==================|'); Form1.AddLog('| Neue Zeichnung |'); Form1.AddLog('|==================|'); {$IFDEF CalcTimes} writeln('--------------------------------------'); writeln('Begin Calc All Values'); {$ENDIF} {$IFDEF ExtraInfos} writeln('--------------------------------------'); writeln('Begin Calc All Values'); {$ENDIF} form1.ProgressDraw.Position:=0; form1.ProgressDraw.Visible:=true; end; {----------------------------------------------------------------------------- Description: Procedure: EndCalc Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.EndCalc; var i:integer; begin // box.BackGround.Image.Bitmap:=SaS.Masterbmp; //damit überhaupt das neue Bild angezeigt wird OldChart.ZoomMin:=self.box.xAxis.Koor.Min; OldChart.ZoomMax:=self.box.xAxis.Koor.Max; OldChart.OldQuality:=Quality; //SaS.box.Update; if Form1.ProgrammerInfo then begin with Form1.ListCountPoints do begin Clear; for I := 0 to self.Count - 1 do begin Items.Add('Screen '+inttostr(i)+' SingleSlit = '+inttostr(self.Screen[i].SingleSlit.Values.Count)+' Neu Berechnet = '+inttostr(self.Screen[i].SingleSlit.NewCalculatedPoints)); Items.Add('Screen '+inttostr(i)+' NSlit = '+inttostr(self.Screen[i].NSlit.Values.Count)+' Neu Berechnet = '+inttostr(self.Screen[i].NSlit.NewCalculatedPoints)); Items.Add('Screen '+inttostr(i)+' CombiSlit = '+inttostr(self.Screen[i].CombiSlit.Values.Count)+' Neu Berechnet = '+inttostr(self.Screen[i].CombiSlit.NewCalculatedPoints)); Items.Add('Screen '+inttostr(i)+' Image Intensity = '+inttostr(self.Screen[i].ImageIntensity.Values.Count)+' Neu Berechnet = '+inttostr(self.Screen[i].ImageIntensity.NewCalculatedPoints)); //Items.Add(HTMLColorString('Screen '+inttostr(i)+' OneSlit = '+inttostr(screen[i].SingleSlit.Values.Count)+' Neu Berechnet = '+inttostr(screen[i].SingleSlit.NewCalculatedPoints),screen[i].Color)); //Items.Add(HTMLColorString('Screen '+inttostr(i)+' NSlit = '+inttostr(screen[i].NSlit.Values.Count)+' Neu Berechnet = '+inttostr(screen[i].NSlit.NewCalculatedPoints),screen[i].Color)); //Items.Add(HTMLColorString('Screen '+inttostr(i)+' CombiSlit = '+inttostr(screen[i].CombiSlit.Values.Count)+' Neu Berechnet = '+inttostr(screen[i].CombiSlit.NewCalculatedPoints),screen[i].Color)); //Items.Add(HTMLColorString('Screen '+inttostr(i)+' Image Intensity = '+inttostr(screen[i].ImageIntensity.Values.Count)+' Neu Berechnet = '+inttostr(screen[i].ImageIntensity.NewCalculatedPoints),screen[i].Color)); Items.Add(''); end; end; CalculationTime:=GetTickCount-starttime; Form1.AddLog('Gesamte Zeichenoperation hat '+IntToStr(CalculationTime)+' ms gedauert'); Form1.AddLog(''); end; Form1.AddLog('|=======================|'); Form1.AddLog('| Ende Zeichnung |'); Form1.AddLog('|=======================|'); Form1.AddLog(''); {$IFDEF CalcTimes} writeln('Sas.EndCalc Time= '+IntToStr(CalculationTime)+' ms'); writeln('--------------------------------------'); {$ENDIF} {$IFDEF ExtraInfos} writeln('Sas.EndCalc'); writeln('--------------------------------------'); {$ENDIF} // form1.ProgressDraw.Visible:=false; form1.ProgressDraw.Position:=0; end; {----------------------------------------------------------------------------- Description: Procedure: drawAll Arguments: none Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.CalcAll; var i:integer; begin if not DrawingEnabled then exit; BeginCalc; for i:=0 to count-1 do begin self.Screen[i].CalcAll(Quality); form1.ProgressDraw.Position:=round(i/count*100); if stop then exit; end; EndCalc; end; {----------------------------------------------------------------------------- Description: Procedure: CalcImageIntensity Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.CalcImageIntensity; var i:integer; begin if not DrawingEnabled then exit; BeginCalc; for i:=0 to count-1 do begin self.Screen[i].Calc(false,false,false,self.Screen[i].ImageIntensity.Visible,Quality); if stop then exit; end; EndCalc; end; {----------------------------------------------------------------------------- Description: Procedure: CalcOnlyVisible Arguments: UpdatingType:TUpdatingType Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.CalcOnlyVisible; var i:integer; begin if not DrawingEnabled then exit; BeginCalc; for i:=0 to count-1 do begin self.Screen[i].CalcOnlyVisible(Quality); form1.ProgressDraw.Position:=round(i/count*100); //Application.ProcessMessages; if stop then exit; end; EndCalc; // self.Masterbmp.SaveToFile('C:\'+self.ClassName+'.bmp'); end; procedure TSaSArray.DrawOGLOnlyVisible; var i:integer; begin if not DrawingEnabled then exit; for i:=0 to count-1 do begin self.Screen[i].DrawOGLOnlyVisible; if stop then exit; end; gradient.DrawOGL; end; procedure TSaSArray.CalcAndDrawBox; begin CalcOnlyVisible; box.DrawOGL; end; {----------------------------------------------------------------------------- Description: Procedure: Calc Arguments: OneSlit,NSlit,CombiSlit,Image:boolean; UpdatingType:TUpdatingType Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.Calc(OneSlit,NSlit,CombiSlit,Image:boolean); var i:integer; begin if not DrawingEnabled then exit; BeginCalc; for i:=0 to count-1 do begin self.Screen[i].Calc(OneSlit,NSlit,CombiSlit,Image,Quality); if stop then exit; end; EndCalc; end; procedure TSaSArray.DrawOGL(OneSlit, NSlit, CombiSlit, Image: boolean); var i:integer; begin if not DrawingEnabled then exit; for i:=0 to count-1 do begin self.Screen[i].DrawOGL(OneSlit,NSlit,CombiSlit,Image); if stop then exit; end; end; {----------------------------------------------------------------------------- Description: Procedure: setActiveNumber Arguments: value:byte Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.setActiveNumber(value:byte); //var s:string; begin if (value>=self.count)or (ActiveNumber>=self.count) then exit; source[ActiveNumber].active:=false; self.Screen[ActiveNumber].active:=false; self.Screen[value].active:=true; Source[value].active:=true; FActiveNumber:=value; { s:=''; for I := 0 to Count - 1 do begin s:=s+#13+inttostr(i); if source[i].active then s:=s+' sichtbar'; end; showmessage(s);} end; {----------------------------------------------------------------------------- Description: Procedure: OnResize Arguments: sender:TObject Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.OnResize(sender:TObject); begin //SaS.Masterbmp.width:=box.Width; //for i:=0 to count-1 do //self.Screen[i].ImageIntensity.Resize; // Self.CalcOnlyVisible; end; procedure TSaSArray.writeDrawingEnabled(value: boolean); begin if FDrawingEnabled=value then exit; FDrawingEnabled:=value; if DrawingEnabled then CalcOnlyVisible; if Assigned(FOnDrawingEnabledChange) then FOnDrawingEnabledChange(self); end; procedure TSaSArray.writeQuality(value: real); begin if FQuality=value then exit; FQuality:=value; if Assigned(FOnQualityChange) then FOnQualityChange(self); end; procedure TSaSArray.writeIntensityColorFactor(value: real); begin FIntensityColorFactor:=value; for i := 0 to SaS.count-1 do SaS.Screen[i].ImageIntensity.Chart.IntensityColorFactor:=IntensityColorFactor; if Assigned(FOnIntensityColorFactorChange) then FOnIntensityColorFactorChange(self); end; {----------------------------------------------------------------------------- Description: Procedure: ShowCorScreen Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.ShowCorScreen; var i:integer; countactiveImage,CountActiveOther:integer; begin {$IFDEF ExtraInfos} writeln('ShowCorScreen'); {$ENDIF} countactiveImage:=0; CountActiveOther:=0; for i:=0 to count-1 do begin if Screen[i].ImageIntensity.Visible then inc(countactiveImage); if self.Screen[i].SingleSlit.Visible or self.Screen[i].NSlit.Visible or self.Screen[i].CombiSlit.Visible then inc(CountActiveOther); end; //if (countactiveImage>0) then ChangeAllColor(clwhite,IntensityColor(clWhite, 0.5)); //else //ChangeAllColor(clblack,IntensityColor(clWhite, 0.5)); box.LSaxis.Visible:=(CountActiveOther>0); box.LSaxis.ShowMainGrid:=(CountActiveOther>0) and Form.CheckShowLSGitternetz.Checked; box.ImageAxis.Visible:=(countactiveImage>0); box.ImageAxis.ShowMainGrid:=(countactiveImage>0) and (CountActiveOther=0) and Form.CheckShowLSGitternetz.Checked; // gradient.Visible:=(countactiveImage=0); gradient.Visible:=false; box.DrawOGL; end; {----------------------------------------------------------------------------- Description: Procedure: ChangeAllColor Arguments: color,gridcolor:Tcolor Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.ChangeAllColor(acolor,agridcolor:Tcolor); begin //box.Color:=acolor; with box do begin header.Color:=acolor; Header.BackgroundColor:=GegenFarbe(aColor); with xAxis do begin ColorAxis:=acolor; ColorBigTicks:=acolor; ColorMainGrid:=agridcolor; ColorTicks:=agridcolor; Title.Color:=aColor; Title.BackgroundColor:=GegenFarbe(aColor); end; with LSAxis do begin ColorAxis:=acolor; ColorBigTicks:=acolor; ColorMainGrid:=agridcolor; ColorTicks:=agridcolor; Title.Color:=aColor; Title.BackgroundColor:=GegenFarbe(aColor); end; with ImageAxis do begin ColorAxis:=acolor; ColorBigTicks:=acolor; ColorMainGrid:=agridcolor; ColorTicks:=agridcolor; Title.Color:=aColor; Title.BackgroundColor:=GegenFarbe(aColor); end; end; end; {============================================================================== Procedure: ChangeAllChecked Belongs to: TSaSArray Result: None Parameters: SlitType : TMySlitType = IsMaxMin : boolean = bool : boolean = Description: ==============================================================================} procedure TSaSArray.ChangeAllChecked(SlitType:TMySlitType; IsMaxMin,bool:boolean); var i:integer; begin {$IFDEF ExtraInfos} writeln('ChangeAllChecked'); {$ENDIF} if not IsMaxMin then case SlitType of MySingle: for i:=0 to count-1 do self.Screen[i].SingleSlit.Visible:=bool; MyN: for i:=0 to count-1 do self.Screen[i].NSlit.Visible:=bool; MyCombi: for i:=0 to count-1 do self.Screen[i].CombiSlit.Visible:=bool; MyImage: for i:=0 to count-1 do self.Screen[i].ImageIntensity.Visible:=bool; end; // für maxmin if IsMaxMin then case SlitType of MySingle: for i:=0 to count-1 do with self.Screen[i].SingleSlit do if UseMaxMin then begin checkMaxMin.Checked:=bool; RefreshChecked; end; MyN: for i:=0 to count-1 do with self.Screen[i].NSlit do if UseMaxMin then begin checkMaxMin.Checked:=bool; RefreshChecked; end; MyCombi: for i:=0 to count-1 do with self.Screen[i].CombiSlit do if UseMaxMin then begin checkMaxMin.Checked:=bool; RefreshChecked; end; MyImage: for i:=0 to count-1 do with self.Screen[i].ImageIntensity do if UseMaxMin then begin checkMaxMin.Checked:=bool; RefreshChecked; end; end; ShowCorScreen; end; {============================================================================== Procedure: MinOneChecked Belongs to: TSaSArray Result: boolean Parameters: SlitType : TMySlitType = Description: ==============================================================================} function TSaSArray.MinOneChecked(SlitType:TMySlitType):boolean; var i:integer; begin result:=false; case SlitType of MySingle: for i := 0 to count-1 do if self.Screen[i].SingleSlit.Visible then begin Result:=true; break; end; MyN: for i := 0 to count-1 do if self.Screen[i].NSlit.Visible then begin Result:=true; break; end; MyCombi: for i := 0 to count-1 do if self.Screen[i].CombiSlit.Visible then begin Result:=true; break; end; MyImage: for i := 0 to count-1 do if self.Screen[i].ImageIntensity.Visible then begin Result:=true; break; end; end; end; {============================================================================== Procedure: RefreshAllChecked Belongs to: TSaSArray Result: None Parameters: Description: ==============================================================================} procedure TSaSArray.RefreshAllChecked; var i:integer; begin for i:=0 to count-1 do begin with self.Screen[i].SingleSlit do RefreshChecked; with self.Screen[i].NSlit do RefreshChecked; with self.Screen[i].CombiSlit do RefreshChecked; with self.Screen[i].ImageIntensity do RefreshChecked; end; end; {----------------------------------------------------------------------------- Description: Procedure: deleteAllValues Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSaSArray.deleteAllValues; var i:integer; begin for i:=0 to count-1 do self.Screen[i].deleteAllValues; end; {============================================================================== Procedure: ExportAllValues Belongs to: TSaSArray Result: None Parameters: FileName : string = Description: ==============================================================================} procedure TSaSArray.ExportAllValues(FileName:string); procedure AddIf(add:boolean; substring:string; var s:string); overload; begin if add then s:=s+substring+';' else s:=s+';'; end; procedure AddIf(add:boolean; value:extended; var s:string); overload; begin AddIf(add, FloatToStr(value), s); end; procedure AddIf(add:boolean; arPointer:TChartValueArray; idx:integer; WhatValue:TXYZKind; var s:string); overload; begin if add then begin case WhatValue of xyzkX: s:=s+FloatToStr(arPointer[idx].pos.x.v)+';'; xyzkY: s:=s+FloatToStr(arPointer[idx].pos.y.v)+';'; xyzkZ: s:=s+FloatToStr(arPointer[idx].pos.z.v)+';'; end end else s:=s+';'; end; function XTitle:string; begin result:=OGLBox.xAxis.Title.Text; end; function LSTitle:string; begin result:=OGLBox.LSAxis.Title.Text; end; function ImageTitle:string; begin result:=OGLBox.ImageAxis.Title.Text; end; const CountColPerSlit=2; CountColPerMinMax=3; var i,j,Scr, maxi,countCol:integer; s:string; begin s:='Export aller Werte aus dem Programm Interferenz '+version+' am '+datetostr(now)+' '+timetostr(now)+#13+#13; s:=s+'Wenn Sie dieses Programm oft benutzen, wäre es sehr freundlich wenn Sie mir eine Spende zukommen lassen würden. Ich würde mich schon über eine bescheidene Spende freuen.'+#13; s:=s+'Schließlich muss das Programm gewartet, überprüft und verbessert werden, ebenso die Homepage und der Webspace...'+#13; s:=s+'Wie gesagt, es muss nicht viel sein. - Einfach mir eine Mail schreiben an: roth-a@gmx.de'+#13; s:=s+'Mit freundlichen Grüßen vom Programmierer: Alexander Roth'+#13+#13; case UsedFormula of // UFApprox: s:=s+'Brechnet mit der Näherungsformel (Fraunhofer''schen Beugungsmuster)'; UFHuygens: s:=s+'Brechnet u.a. mit der genauen Formel (Fresnel''sches Beugungsmuster). Nun gilt nicht mehr e>>g'; end; s:=s+#13+#13; // Kopf Schreiben for i := 0 to self.count - 1 do begin // Spalten Zählen countcol:=0; with self.Screen[i] do begin if SingleSlit.Visible then inc(countcol, CountColPerSlit+CountColPerMinMax); if NSlit.Visible then inc(countcol, CountColPerSlit+CountColPerMinMax); if CombiSlit.Visible then inc(countcol, CountColPerSlit+CountColPerMinMax); if ImageIntensity.Visible then inc(countcol, CountColPerMinMax+CountColPerMinMax); end; s:=s+ReplikeString('Wellenlänge '+inttostr(i)+' (lambda='+inttostr(round(self.Source[i].lambda*1E9))+'nm);', CountCol); end; s:=s+#13; // Kopf Schreiben for i := 0 to self.count - 1 do with self.Screen[i] do begin if SingleSlit.Visible then s:=s+ReplikeString('Einfachspalt;',CountColPerSlit)+ReplikeString('Minima des Einfachspalts;',CountColPerMinMax); if NSlit.Visible then s:=s+ReplikeString('N-fach Spalt;',CountColPerSlit)+ReplikeString('Minima und Maxima des N-fach Spalt;',CountColPerMinMax); if CombiSlit.Visible then s:=s+ReplikeString('Wirklicher N-fach Spalt;',CountColPerSlit)+ReplikeString('Maxima des Wirklichen N-fach Spalts;',CountColPerMinMax); if ImageIntensity.Visible then s:=s+ReplikeString('Farbbild;',CountColPerMinMax)+ReplikeString('Minima und Maxima des Farbbilds;',CountColPerMinMax); end; s:=s+#13; // Kopf Schreiben for i := 0 to self.count - 1 do with self.Screen[i] do begin if SingleSlit.Visible then s:=s+XTitle+';'+LSTitle+';' + XTitle+';'+LSTitle+';'+ImageTitle+';'; if NSlit.Visible then s:=s+XTitle+';'+LSTitle+';' + XTitle+';'+LSTitle+';'+ImageTitle+';'; if CombiSlit.Visible then s:=s+XTitle+';'+LSTitle+';' + XTitle+';'+LSTitle+';'+ImageTitle+';'; if ImageIntensity.Visible then s:=s+XTitle+';'+LSTitle+';'+ImageTitle+';' + XTitle+';'+LSTitle+';'+ImageTitle+';'; end; s:=s+#13; //max Count feststellen maxi:=0; for i := 0 to self.count - 1 do with self.Screen[i] do begin maxi:=max(SingleSlit.Values.Count, NSlit.Values.Count); maxi:=max(maxi, CombiSlit.Values.Count); maxi:=max(maxi, ImageIntensity.Values.Count); SingleSlit.CalcMinMax(xAxisType,LSAxisType, ImageAxisType); NSlit.CalcMinMax(xAxisType,LSAxisType, ImageAxisType); CombiSlit.CalcMinMax(xAxisType,LSAxisType, ImageAxisType); ImageIntensity.CalcMinMax(xAxisType,LSAxisType, ImageAxisType); end; for i := 0 to maxi - 1 do begin for Scr := 0 to self.count - 1 do with self.Screen[Scr] do begin with SingleSlit do if Visible then begin AddIf(i<Values.Count, Values, i , xyzkX, s); AddIf(i<Values.Count, Values, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkX, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkY, s); end; with NSlit do if Visible then begin AddIf(i<Values.Count, Values, i , xyzkX, s); AddIf(i<Values.Count, Values, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkX, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkY, s); end; with CombiSlit do if Visible then begin AddIf(i<Values.Count, Values, i , xyzkX, s); AddIf(i<Values.Count, Values, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkX, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkY, s); end; with ImageIntensity do if Visible then begin AddIf(i<Values.Count, Values, i , xyzkX, s); AddIf(i<Values.Count, Values, i , xyzkZ, s); AddIf(i<Values.Count, Values, i , xyzkY, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkX, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkZ, s); AddIf(i<ValuesMaxMin.Count, ValuesMaxMin, i , xyzkY, s); end; end; s:=s+#13; end; //schriebe in csv datei utxt.intxtschreiben(s,FileName,'.csv',true); end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit TSingleSlit //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: create Arguments: AOwner: TComponent; box:TOGlBox; number:byte Result: None Detailed description: -----------------------------------------------------------------------------} constructor TSingleSlit.create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); begin inherited create(AOwner); box:=abox; SlitType:=MySingle; FForm:=aForm; Fnumber:=anumber; UseMaxMin:=aCreateMaxMin; CalcMaxima:=true; CalcMinima:=true; CheckSTRGOnMouseDown:=false; CheckSTRGMaxMinOnMouseDown:=false; WasRealKlick:=false; CalcGamma:=false; FVisible:=true; ShowMaxLabels:=true; ShowMinLabels:=true; Values:=TChartValueArray.Create; Values.Clear; Chart:=TLineChart.Create(abox, Values); Chart.Depth:=Koor1(number+1, kkz); Chart.WhatIsYValue:=xyzkZ; // parent.LeftAxis.Options := [axAutomaticMinimum, axShowLabels, axShowGrid, axShowTitle, axAutomaticMaximum]; if UseMaxMin then begin ValuesMaxMin:=TChartValueArray.Create; ValuesMaxMin.clear; ChartMinMax:=TPointChart.Create(abox, ValuesMaxMin); with ChartMinMax do begin Depth:=Koor1(self.Chart.Depth.v+0.1,kkz); Visible:=false; UseIntensityColor:=false; WhatIsYValue:=xyzkZ; end; end; //Options := [coLabelEachPoint]; Chart.pen.Width:=0; dialog:=TColorDialog.Create(self); inc(TScreem(AOwner).ColorNumber); //Komonenten Createn with Form1 do begin inc(TScreem(AOwner).CheckNumber); // hauptcheckbox check:=TCheckbox.Create(FForm); with check do begin parent:=GroupShowChart; name:=self.ClassName+'_Check_'+inttostr(number); left:=16; width:=180; top:=24*TScreem(AOwner).CheckNumber; writeCaption(TCheckbox(check)); Hint:='Press STRG or CTRL and click for changing all wavelengths at the same time.'; end; check.OnMouseDown:=@self.CheckOnMouseDown;//muss am schluss ausgeführt werden damit er nicht vorher zeichnet check.OnChange:=@self.CheckChange;//muss am schluss ausgeführt werden damit er nicht vorher zeichnet // für farbeinstellungen LED:=TALED.Create(FForm); with LED do begin parent:=GroupColors; name:=self.ClassName+'_LED_'+inttostr(number); left:=16; top:=24*TScreem(AOwner).ColorNumber; Status:=true; colorON:=self.Chart.Color; onclick:=@self.ColorOnClick; OnColorChange:=@self.OnColorChange; end; // für farbeinstellungen with TLabel.Create(self) do begin parent:=GroupColors; name:=self.ClassName+'_TLabel_'+inttostr(number); left:=42; top:=24*TScreem(AOwner).ColorNumber; Caption:=check.Caption; onclick:=@self.ColorOnClick; end; if UseMaxMin then begin checkMaxMin:=TCheckbox.Create(FForm); with checkMaxMin do begin parent:=GroupShowMaxMin; name:=self.ClassName+'_CheckMaxMin_'+inttostr(number); left:=16; width:=160; top:=24*TScreem(AOwner).CheckNumber-22; checked:=false; writeCaption(checkMaxMin); end; checkMaxMin.OnMouseDown:=@CheckMaxMinOnMouseDown;//muss am schluss ausgeführt werden damit er nicht vorher zeichnet checkMaxMin.OnClick:=@CheckMaxMinClick;//muss am schluss ausgeführt werden damit er nicht vorher zeichnet end; end; self.active:=false; self.MakeRightColor; end; {----------------------------------------------------------------------------- Description: Procedure: destroy Arguments: None Result: None Detailed description: brauche ich nicht, da led,check,checkmaxmin zu self.Owner.Owner.groupbox gehören, und deswegen anscheinend von Tform1 zerstört werden -----------------------------------------------------------------------------} destructor TSingleSlit.Destroy; begin if assigned(Chart) then Chart.Free; if assigned(LED) then LED.Free; if assigned(check) then check.Free; if UseMaxMin and assigned(checkMaxMin) then checkMaxMin.Free; if assigned(Values) then Values.free; if UseMaxMin and assigned(ValuesMaxMin) then ValuesMaxMin.Free; inherited destroy; end; {----------------------------------------------------------------------------- Description: Procedure: writeCaption Arguments: (var checkbox:TCheckbox) Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.writeCaption(var checkbox:TCheckbox); begin checkbox.Caption:='Einfachspalt';//+inttostr(number); CalcMaxima:=true; CalcMinima:=true; Visible:=true; end; procedure TSingleSlit.WriteFForm(Form: TForm); begin FForm:=Form; end; {----------------------------------------------------------------------------- Description: Procedure: setactive Arguments: value:boolean Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.setactive(value:boolean); begin Factive:=value; self.check.Visible:=value; if UseMaxMin then self.checkMaxMin.Visible:=value; if UseMaxMin then self.ChartMinMax.Visible:=self.checkMaxMin.Checked and self.Visible; self.LED.Visible:=value; { showmessage( inttostr(number)+#13+ self.ClassName+'.check.Visible= '+booltostr(self.check.Visible,true)+#13+ self.ClassName+'.ChartMinMax.Visible= '+booltostr(self.ChartMinMax.Visible,true)+#13+ self.ClassName+'.LED.Visible= '+booltostr(self.LED.Visible,true) );} end; procedure TSingleSlit.setVisible(value: boolean); begin FVisible:=value; check.Checked:=value; end; procedure TSingleSlit.OnColorChange(Sender: TObject); begin self.Chart.Color:=LED.ColorOn; end; {============================================================================== Procedure: RefreshChecked Belongs to: TSingleSlit Result: None Parameters: Description: ==============================================================================} procedure TSingleSlit.RefreshChecked; begin Chart.Visible:=Visible; if UseMaxMin then ChartMinMax.Visible:=self.checkMaxMin.Checked and Visible; end; {----------------------------------------------------------------------------- Description: Procedure: ColorOnClick Arguments: Sender: TObject Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.ColorOnClick(Sender: TObject); begin if dialog.Execute then LED.ColorOn:=dialog.Color; box.DrawOGL; // das muss hier rein, denn wenn es in oncolorchange ist dann versucht es auch n und multislit zuzugreifen, die noch garnicht created sind end; procedure TSingleSlit.CheckChange(Sender: TObject); begin {$IFDEF ExtraInfos} writeln(ClassName+'.CheckChange'); {$ENDIF} Visible:=check.Checked; self.RefreshChecked; if CheckSTRGOnMouseDown then SaS.ChangeAllChecked(SlitType,false, self.Visible) // es muss hier überall not visible, weil visible ja noch nicht abnders gesetzt wurde else begin if Visible then Calc(TScreem(Owner).xAxisType,TScreem(Owner).LSAxisType, TScreem(Owner).ImageAxisType); if WasRealKlick then SaS.ShowCorScreen else box.DrawOGL; end; WasRealKlick:=false; CheckSTRGOnMouseDown:=false; end; procedure TSingleSlit.CheckOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin {$IFDEF ExtraInfos} writeln(ClassName+'.CheckOnMouseDown'); {$ENDIF} CheckSTRGOnMouseDown:= Shift=[ssCtrl, ssLeft]; WasRealKlick:=true; end; procedure TSingleSlit.CheckMaxMinClick(Sender: TObject); begin if CheckSTRGMaxMinOnMouseDown then begin SaS.ChangeAllChecked(SlitType,true,checkMaxMin.Checked); exit; end else self.RefreshChecked; CheckSTRGMaxMinOnMouseDown:=false; if self.checkMaxMin.Checked then self.CalcMinMax(TScreem(owner).xAxisType,TScreem(owner).LSAxisType, TScreem(Owner).ImageAxisType); box.DrawOGL; end; {----------------------------------------------------------------------------- Description: Procedure: CheckcheckMaxMinOnClick Arguments: Sender: TObject Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.CheckMaxMinOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin CheckSTRGMaxMinOnMouseDown:=shift=[ssCtrl, ssLeft]; end; {----------------------------------------------------------------------------- Description: Procedure: getspecifications Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.getspecifications; begin end; {----------------------------------------------------------------------------- Description: Procedure: OneSlitAmplitude Arguments: alpha:extended Result: extended Detailed description: Herleitung durch vereifachjung der N-fach Spalt Intensitätsformel Da delta phi -->0 und N --> unendlich qhi = N* delta phi sin(delta phi /2) = delta phi /2 Einsetzen und man bekomnt es heraus Dreh-Gitter: Die Erweiterung ist nun dass wenn man das Gitter dreht es leider nicht schön delta s = g*sin(alpha) sondern das recht kompliziert sich mal Wege addieren bzw. subtrahieren. Das wird allerdings wunderschön durch die Vorzeichen kompensiert delta s = g*abs(sin(beta)+sin(alpha-beta)) Wenn alpha=0 dann delta s = 0 Aufpassen mit Vorzeichen von Winkeln!!! Nur so klappt es -----------------------------------------------------------------------------} function TSingleSlit.OneSlitAmplitude(s:TVec):extended; // Formel die Für 2 Spalten Stimmt const delta=0.000001; var phi,cosalpha1,cosalpha2, Gangunterschied, beta:extended; l0:Tvec; begin beta:=aperture.slit.beta; l0:=Vec(-1,0,0); cosalpha1:= -l0 * CalcGyVec ; cosalpha2:=s * CalcGyVec ; Gangunterschied:=aperture.slit.width * ( cosalpha1 + cosalpha2 ); phi:= 2*pi*Gangunterschied / SaS.Source[number].lambda; if abs(phi)>delta then //sonst dividiert er durch 0 //Hauptmaximum result:=1* 2*sin(phi/2)/phi else result:=1 * cos(phi/2); end; {----------------------------------------------------------------------------- Description: Procedure: OneSlitIntensity Arguments: alpha:extended Result: extended Detailed description: -----------------------------------------------------------------------------} function TSingleSlit.OneSlitIntensity(s:TVec):extended; // Formel die Für 1 Spalte Stimmt begin result:=sqr(self.OneSlitAmplitude(s)); end; function TSingleSlit.GammaAngleBog(s:TVec): extended; var x:extended; begin // Result:=0; //ablenkung durch gitterverdrehung wenn sowohl beta, als auch theta gekippt sind // dadurch wird das Gitter i bezug auf den Laser leicht gedreht, wodurch die Interferensachse // nicht mehr horizontal ist sondern schief //Gitterachsenvektor ist: vec Gittervektor = left ( stack{sin %THETA cos %beta # sin %THETA sin %beta # cos %THETA } right ) //relevanter Gitterachsenvektor ist: vec Gittervektor = left ( stack{0 # sin %THETA sin %beta # cos %THETA } right ) //senkrecht dazu ist die Interferenzachse: vec Interferenzvektor = left ( stack{0 # -cos %THETA # sin %THETA sin %beta } right ) //senkrecht dazu ist die Interferenzachse mit länge 1: vec Interferenzvektor = left ( stack{0 # -cos %THETA # sin %THETA sin %beta } right ) over left lline left ( stack{0 # -cos %THETA # sin %THETA sin %beta } right ) right rline //Vereinfacht: senkrecht dazu ist die Interferenzachse mit länge 1: vec Interferenzvektor = left ( stack{0 # -cos %THETA # sin %THETA sin %beta } right ) over sqrt{(cos %THETA)^2 + (sin %THETA)^2 (sin %beta)^2 } // ohne vektoren sondern nur mit koordinaten: y(x) = {cos(%THETA)} over {sin(%THETA) cdot sin(%beta)}cdot x //mit alpha einberechnung: //x:=aperture.ScreenDistance*tan(alpha); //if (aperture.slit.theta<2*pi) then //Result:=-sin(aperture.slit.theta)*sin(aperture.slit.beta)/cos(aperture.slit.theta) *x; // hier die krümmung durch verticales kippen des gitters (drehen um horizontale achse) // Gebe in Openoffice Formel: c_{neu 3} = tan(%beta) cdot e cdot left (1-sqrt{tan^2(%alpha_1)+1} right ) // Result:=Result+tan(aperture.slit.theta)*aperture.ScreenDistance * (1-sqrt( sqr(tan(alpha))+1 )); // in winkel umrechnen // Result:=arctan(Result/aperture.ScreenDistance); // Result:=alpha+CalcX2RotationDeflection(alpha, xyzkY); //brechung miteinberechnen // Result:=alpha; Result:=AngleOfVec(s, akgamma); end; function TSingleSlit.GammaAngleDeg(s:TVec): extended; begin result:=BogtoRad( GammaAngleBog(s)); end; function TSingleSlit.GammaMeter(s:TVec): extended; begin Result:=aperture.ScreenDistance*tan(GammaAngleBog(s)); end; {----------------------------------------------------------------------------- Description: Procedure: alpha2X Arguments: alpha:extended Result: extended Detailed description: -----------------------------------------------------------------------------} //function TSingleSlit.alpha2X(alpha:extended):extended; //begin //result:=aperture.ScreenDistance*tan(alpha); //end; //{----------------------------------------------------------------------------- //Description: //Procedure: X2alpha //Arguments: x:extended //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.X2alpha(x:extended):extended; //begin //result:=arctan(x/aperture.ScreenDistance); //end; //{----------------------------------------------------------------------------- //Description: //Procedure: alpha2lambda //Arguments: alpha:extended //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.alpha2lambda(alpha:extended):extended; //begin //result:=aperture.slit.width * sin(alpha) / SaS.Source[number].lambda; //end; //{----------------------------------------------------------------------------- //Description: lambda bedeutet hier Gangunterschied, da lambda die einheit ist //Procedure: lambda2alpha //Arguments: lambda:extended //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.lambda2alpha(lambda:extended):extended; //var temp:extended; //begin //temp:=lambda*SaS.Source[number].lambda/aperture.slit.width; //korrigiere(temp,-1,1); //result:=arcsin(temp); //end; //{----------------------------------------------------------------------------- //Description: //Procedure: AlphaBog2AlphaDeg //Arguments: alpha:extended //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.AlphaBog2AlphaDeg(alpha:extended):extended; //begin //result:=RadtoDeg(alpha); //end; //{----------------------------------------------------------------------------- //Description: //Procedure: AlphaDeg2AlphaBog //Arguments: alpha:extended //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.AlphaDeg2AlphaBog(alpha:extended):extended; //begin //result:=DegtoRad(alpha); //end; //{============================================================================== //Procedure: returnValue //Belongs to: TSingleSlit //Result: extended //Parameters: //Value : extended = //Description: //==============================================================================} //function TSingleSlit.returnValue(Value:extended):extended; //begin //result:=Value; //end; function TSingleSlit.CalcGyVec: TVec; var beta:extended; begin beta:=aperture.slit.beta; Result.x1:=sin(beta); Result.x2:=-cos(beta); Result.x3:=0; end; function TSingleSlit.CalcGzVec: TVec; var beta,theta:extended; begin theta:=aperture.slit.theta; beta:=aperture.slit.beta; Result.x1:=sin(theta)*cos(beta); Result.x2:=sin(beta)*sin(theta); Result.x3:=cos(theta); end; { alte berechnung mit s brutal ausrechnen var k1,k2,k3,a,b,c,s3,s1:extended; beta,theta,cosalphax,cosalphay0,sinalpha:extended; gx,gy,l0:TVec; begin theta:=aperture.slit.theta; beta:=aperture.slit.beta; gx:=CalcGyVec; gy:=CalcGzVec; l0:=vec(-1,0,0); cosalphay0:=gy*l0; k3:=tan(beta); k1:=tan(theta)*sin(beta)*tan(beta) + cos(beta) * tan(theta); k2:=1/cos(beta); s3:=1/(-k1-k2); a:=1+1/sqr(k3); b:=-2*k1*s3 /sqr(k3); c:=sqr(k1*s3/k3)-1+sqr(s3); s1:=ABC(a,b,c,+1); cosalphax:=1/gy.x2*( cosalphay0*gx.x2 - s3*(gy.x3*gx.x2-gx.x3*gy.x2) - s1*(gy.x1*gx.x2-gx.x1*gy.x2) ) ; sinalpha:=ABC(1, 2*cosalphax*cos(beta), -sqr(sin(beta)) + sqr(cosalphax), +1); Result:=arcsin(sinalpha); } // mit kreisberechnung function TSingleSlit.CalcMinMaxAlpha(TheSign: shortint): extended; function secureArccos(value:extended):extended; begin korrigiere(value,-1,1); Result:=arccos(value); end; var alphaz:extended; gz,gy,l0,s:TVec; temp:extended; begin gy:=CalcGyVec; gz:=CalcGzVec; l0:=vec(-1,0,0); alphaz:=arccos(l0*gz); s:=TheSign* sin(alphaz) *gy + cos(alphaz)* gz; result:=secureArccos(gy*l0)-secureArccos(gy*s); //ohne secure gibt er hier einen fehler aus korrigiere(Result, -pi/2,pi/2); end; function TSingleSlit.CalcMinAlpha: extended; begin result:=CalcMinMaxAlpha(-1)+0.001; end; function TSingleSlit.CalcMaxAlpha: extended; begin result:=CalcMinMaxAlpha(+1)-0.001; end; function TSingleSlit.MaximaWidth: extended; begin result := 1/5* 1/(aperture.slit.distance/200e-6); end; // du musst de losptalk anwenden ansonten entstehen polstellen function TSingleSlit.CalcAngleDeflectionVec(alpha: extended): TVec; var cosalphaz0, cosalphay, s3WothoutSinBy, davor, davor2:extended; s,gz,gy,l1,l0:TVec; reflectionsign:shortint; begin gy:=CalcGyVec; gz:=CalcGzVec; l0:=vec(-1, 0,0); l1:=vec(-cos(alpha), -sin(alpha),0); cosalphay:=l1*gy; cosalphaz0:=l0*gz; if TScreem(Owner).CalcReflection then reflectionsign:=1 else reflectionsign:=-1; s.x1:=ABC( sqr(gz.x3*gy.x2)+sqr(gz.x3 *gy.x1) + sqr( gz.x1*gy.x2-gz.x2*gy.x1 ), -2*( cosalphay*sqr(gz.x3)*gy.x1 + ( cosalphaz0*gy.x2 - cosalphay*gz.x2 )*( gz.x1*gy.x2-gz.x2*gy.x1 ) ), sqr(cosalphay * gz.x3) + sqr( cosalphaz0*gy.x2 - cosalphay*gz.x2 ) - sqr(gz.x3 * gy.x2 ) , reflectionsign); s.x2:=(cosalphay - s.x1*gy.x1)/gy.x2; s.x3:=( gy.x2* cosalphaz0 - gz.x2*cosalphay - s.x1*( gz.x1*gy.x2-gy.x1*gz.x2 ) ) / (gy.x2*gz.x3); //intxtschreiben('-----------------------------', ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); //intxtschreiben('alpha '+ FloatToStr(alpha) , ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); //intxtschreiben('a '+ FloatToStr(sqr(gz.x3*gy.x2)+sqr(gz.x3 *gy.x1) + sqr( gz.x1*gy.x2-gz.x2*gy.x1 )) , ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); //intxtschreiben('b '+ FloatToStr(-2*( cosalphay*sqr(gz.x3)*gy.x1 + ( cosalphaz0*gy.x2 - cosalphay*gz.x2 )*( gz.x1*gy.x2-gz.x2*gy.x1 ) )) , ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); //intxtschreiben('c '+ FloatToStr(sqr(cosalphay * gz.x3) + sqr( cosalphaz0*gy.x2 - cosalphay*gz.x2 ) -1) , ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); //intxtschreiben('s1 '+ FloatToStr(s.x1) , ExtractFilePath(ParamStr(0))+'s1.txt', '.txt', false); result:=s; end; function TSingleSlit.AngleOfVec(s:TVec; angleKind: TAngleKind): extended; begin //now we calculate the angle we need case angleKind of akalpha: Result:=pi-RecreateRealAngle(s.x1, s.x2) ; //pi- da ich nicht von der positiven y-Achse den Winkel messe, sondern von der negativen x-Achse (im Koordinatensystem von meiner Arbeit) akgamma: Result:=pi-RecreateRealAngle(s.x1, s.x3) ; end; end; function TSingleSlit.KoorStrechtedOfVec(s: TVec; XYZKind: TXYZKind): extended; begin if s.x1=0 then case XYZKind of xyzkX: Result:=s.x2*aperture.ScreenDistance * 1E10; xyzkY: Result:=s.x3*aperture.ScreenDistance * 1E10; end; case XYZKind of xyzkX: Result:=s.x2/s.x1*aperture.ScreenDistance; xyzkY: Result:=s.x3/s.x1*aperture.ScreenDistance; xyzkZ: Result:=s.x1; end; end; function TSingleSlit.XAngleOfVec(s: TVec): extended; begin result:=BogtoRad(AngleOfVec(s, akalpha)); end; function TSingleSlit.PathDifferenceOfVec(s: TVec): extended; var cosalpha1,cosalpha2,beta:extended; l0:Tvec; begin beta:=aperture.slit.beta; l0:=Vec(-1,0,0); cosalpha1:= -l0 * CalcGyVec ; cosalpha2:=s * CalcGyVec ; result:=aperture.slit.width * ( cosalpha1 + cosalpha2 ) / SaS.Source[number].lambda; end; function TSingleSlit.YAngleOfVec(s: TVec): extended; begin result:=BogtoRad(AngleOfVec(s, akgamma)); end; function TSingleSlit.XKoorStrechtedOfVec(s: TVec): extended; begin result:=KoorStrechtedOfVec(s, xyzkX); end; function TSingleSlit.YKoorStrechtedOfVec(s: TVec): extended; begin result:=KoorStrechtedOfVec(s, xyzkY); end; function TSingleSlit.MaxFunc(z: integer; var alpha: Extended): TMinMaxStaus; begin alpha:=0; if z=0 then begin alpha:=0; Result:=mmsMainMax; if not IsInRange(alpha, CalcMinAlpha, CalcMaxAlpha) then Result:=mmsEnd; end else Result:=mmsEnd; end; function TSingleSlit.MinFunc(z: integer; var alpha: Extended): TMinMaxStaus; var l0MalGx:extended; begin alpha:=0; l0MalGx:=Vec(-1,0,0) * CalcGyVec; alpha:=z*SaS.Source[number].lambda/aperture.slit.width +l0MalGx; if IsInRange(alpha, -1,1) then begin Result:=mmsMin; alpha:=aperture.slit.beta + arcsin(alpha); if not IsInRange(alpha, CalcMinAlpha, CalcMaxAlpha) then Result:=mmsEnd; end else Result:=mmsEnd; end; function TSingleSlit.MaxFunc(z:integer; var s:TVec):TMinMaxStaus; var alpha:extended; str:string; begin Result:=MaxFunc(z, alpha); if not (Result in [mmsEnd, mmsNoMinMax]) then s:=CalcAngleDeflectionVec(alpha); end; function TSingleSlit.MinFunc(z:integer; var s:TVec):TMinMaxStaus; var alpha:extended; begin Result:=MinFunc(z, alpha); if not (Result in [mmsEnd, mmsNoMinMax]) then s:=CalcAngleDeflectionVec(alpha); end; {----------------------------------------------------------------------------- Description: Procedure: getImageFunc Arguments: LSAxisType:TLSAxisType Result: TFunctionVecType Detailed description: // TLSAxisType=(Amplitude,Intensity,BrigthDark); -----------------------------------------------------------------------------} function TSingleSlit.getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; begin case LSAxisType of LSAmplitude: result:=@OneSlitAmplitude; LSIntensity: result:=@OneSlitIntensity; end; end; {----------------------------------------------------------------------------- Description: Procedure: getXFunc Arguments: xAxisType:TxAxisType Result: TFunctionVecType Detailed description: -----------------------------------------------------------------------------} function TSingleSlit.getXFunc(xAxisType:TxAxisType):TFunctionVecType; begin case xAxisType of xangle: result:=@self.XAngleOfVec; xmeter: result:=@self.XKoorStrechtedOfVec; xlambda: result:=@self.PathDifferenceOfVec; end; end; //{----------------------------------------------------------------------------- //Description: Umkehrfunktion!!! //Procedure: getAntiXFunc //Arguments: xAxisType:TxAxisType //Result: TFunctionVecType //Detailed description: //-----------------------------------------------------------------------------} //function TSingleSlit.getAntiXFunc(xAxisType:TxAxisType):TFunctionVecType; //begin //case xAxisType of //xangle: result:=@self.AlphaDeg2AlphaBog; //xmeter: result:=@self.X2alpha; //xlambda: result:=@self.lambda2alpha; //end; //end; function TSingleSlit.getImageFunc(ImageAxisType: TImageAxisType): TFunctionVecType; begin case ImageAxisType of ImageAngle: result:=@self.GammaAngleDeg; ImageMeter: result:=@self.GammaMeter; end; end; {----------------------------------------------------------------------------- Description: Procedure: DelUnVisibleValues Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.DelUnVisibleValues; var i: Integer; min,max:real; begin i:=0; min:=self.Chart.Box.xAxis.Koor.Min; max:=self.Chart.Box.xAxis.Koor.Max; while i< Values.Count do if not IsInRange(Values[i].Pos.X.v, min, max) then Values.Delete(i) else inc(i); end; {----------------------------------------------------------------------------- Description: Wer zeichnet da die blauen Punkte? Procedure: CalcMinMax Arguments: xAxisType:TxAxisType; LSAxisType:TLSAxisType; percision:word=0 Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.CalcMinMax(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; percision:word=0); const IntensityColor_Minimum=0.3; var funcLS,funcx, FuncImage:TFunctionVecType; i, j, leerstellen:integer; alpha:extended; stopped:boolean; s:TVec; str,postlabel:string; begin if not UseMaxMin then exit; funcLS:=getLSFunc(LSAxisType); funcx:=getXFunc(xAxisType); FuncImage:=getImageFunc(ImageAxisType); ValuesMaxMin.Clear; //ChartMinMax.Font.Color:= self.Chart.Color; if CalcMaxima then begin //max+ i:=0; leerstellen:=0; stopped:=false; repeat case MaxFunc(i +leerstellen, s) of mmsMainMax: begin if abs(i+leerstellen)>500 then begin inc(i); Continue; end; //if abs(i+leerstellen)<=10 then postlabel :='.Max'; //else // postlabel :=''; ValuesMaxMin.Add(ChartValue(Koor3(funcx(s), FuncImage(s) , funcLS(s), kkx, kkImage, kkLS), inttostr(i+leerstellen)+postlabel, ShowMaxLabels, ChartMinMax.Color, ord(mmsMainMax), i +leerstellen)); end; mmsNoMinMax, mmsMin: begin dec(i); inc(leerstellen); end; mmsEnd: begin stopped:=true; break; end; end; inc(i); until stopped; //max- i:=-1; leerstellen:=0; stopped:=false; repeat case MaxFunc(i -leerstellen, s) of mmsMainMax: begin if abs(i+leerstellen)>500 then begin dec(i); Continue; end; postlabel :='.Max' ; //else // postlabel :=''; ValuesMaxMin.Add(ChartValue(Koor3(funcx(s), FuncImage(s) , funcLS(s), kkx, kkImage, kkLS), inttostr(i-leerstellen)+postlabel, ShowMaxLabels, ChartMinMax.Color, ord(mmsMainMax), i -leerstellen)); end; mmsNoMinMax, mmsMin: begin inc(i); inc(leerstellen); end; mmsEnd: begin stopped:=true; break; end; end; dec(i); until stopped; end; if CalcMinima then begin //min+ i:=1; leerstellen:=0; stopped:=false; repeat case MinFunc(i +leerstellen, s) of mmsMin: begin if abs(i)>500 then begin inc(i); Continue; end; ValuesMaxMin.Add(ChartValue(Koor3(funcx(s), FuncImage(s) , funcLS(s), kkx, kkImage, kkLS), inttostr(i)+'.Min', ShowMinLabels, IntensityColor(ChartMinMax.Color, IntensityColor_Minimum), ord(mmsMin), i +leerstellen)); end; mmsNoMinMax, mmsMainMax, mmsMinorMax: begin dec(i); inc(leerstellen); end; mmsEnd: begin stopped:=true; break; end; end; inc(i); until stopped; //min- i:=-1; leerstellen:=0; stopped:=false; repeat case MinFunc(i -leerstellen, s) of mmsMin: begin if abs(i)>500 then begin dec(i); Continue; end; ValuesMaxMin.Add(ChartValue(Koor3(funcx(s), FuncImage(s) , funcLS(s), kkx, kkImage, kkLS), inttostr(i)+'.Min', ShowMinLabels, IntensityColor(ChartMinMax.Color, IntensityColor_Minimum), ord(mmsMainMax), i -leerstellen)); end; mmsNoMinMax, mmsMainMax, mmsMinorMax: begin inc(i); inc(leerstellen); end; mmsEnd: begin stopped:=true; break; end; end; dec(i); until stopped; end; ValuesMaxMin.sort(xyzkX); end; {============================================================================== Procedure: Calc Belongs to: TSingleSlit ==============================================================================} procedure TSingleSlit.Calc(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; Quality:real=20); var funcLS,funcx,{funcAntiX,}funcImage:TFunctionVecType; mini,maxi:real; //grenzen fürs zeichnen Verhaeltnis: Real;// neur Ausschnitt / altem ausschnitt MaxStep,MinStep:real; {============================================================================== Procedure: DelUnVisibleValues ==============================================================================} //procedure DelUnVisibleValues; //var //i: Integer; //MyfuncX:TFunctionType; //min,max:real; //begin //i:=0; //if StretchX then //MyfuncX:=returnValue //else //MyfuncX:=getXFunc(xAxisType); //min:=box.xAxis.Minimum; //max:=box.xAxis.Maximum; //while i< Values.Count do //if not IsInRange(MyfuncX(Values.Items[i].X), min,max) then //Values.Delete(i) //else //inc(i); //end; {============================================================================== Procedure: CalcPointsNearMax Parameters: xMax : real = ==============================================================================} procedure CalcPointsNearMax(xMax,MinRange,MaxRange:real); var r,area:real; count,countPoints:integer; s:TVec; begin area:=MaximaWidth; s:=CalcAngleDeflectionVec(xMax); r:=funcLS(s); if xMax<-0.4 then r:=funcLS(s); countPoints:=abs(round(500*r*Quality)); // bestimme Anzahl der Punkte nach der Helligkeit korrigiere(countPoints,0,round(50*Quality)); if countPoints>0 then values.Add(Koor3(funcx(s),funcImage(s),r, kkx,kkImage, kkLS), Chart.Color); r:=Max(xMax-area/2,mini); for i := 0 to countPoints-1 do begin r:=r+area/countPoints; if not IsInRange(r, MinRange, MaxRange) then continue; s:=CalcAngleDeflectionVec(r); Values.Add(Koor3(funcx(s),funcImage(s),funcLS(s), kkx, kkImage, kkLS), Chart.Color); inc(NewCalculatedPoints); end; //log if Form1.CheckExMaximaDraw.Checked and (countPoints>0) then begin form1.AddLog('CalcPointsNearMax bei x= '+FormatFloat('0.0000',funcX(CalcAngleDeflectionVec(xMax)))+' mit count= '+inttostr(countPoints)); form1.AddLog('Von xMin= '+FormatFloat('0.0000',funcX(CalcAngleDeflectionVec(xMax-area/2)))+' bis xMax= '+FormatFloat('0.0000',funcX(CalcAngleDeflectionVec(xMax+area/2)))); form1.AddLog(''); Form1.CheckLog; end; end; {============================================================================== Procedure: CalcInterestingPoints ==============================================================================} procedure CalcInterestingPoints(MinRange,MaxRange:real); var i:Integer; count:word; alpha:extended; begin if not UseMaxMin then exit; if MinRange>=MaxRange then exit; for I := 0 to ValuesMaxMin.count-1 do begin if TMinMaxStaus(ValuesMaxMin.arr[i].Tag) in [mmsMainMax, mmsMinorMax] then begin if MaxFunc(ValuesMaxMin.arr[i].Tag2, alpha) in [mmsNoMinMax, mmsEnd] then continue; end else if TMinMaxStaus(ValuesMaxMin.arr[i].Tag) in [mmsMin] then if MinFunc(ValuesMaxMin.arr[i].Tag2, alpha) in [mmsNoMinMax, mmsEnd] then continue; if IsInRange( alpha ,MinRange,MaxRange) then CalcPointsNearMax(alpha,MinRange,MaxRange); end; end; {============================================================================== Function: GetStep ==============================================================================} function GetStep(oldx,oldy,newx,newy:real):real; const MaxSteigungThenMinStep=5; var Steigung:real; begin if newx-oldx=0 then begin result:=(MaxStep+MinStep)/2; exit; end; Steigung:=abs((newy-oldy)/(newx-oldx)); result:=MinStep+(MaxStep-MinStep)*(1-Steigung/MaxSteigungThenMinStep); korrigiere(result,MinStep,MaxStep); end; {============================================================================== Procedure: DelRange ==============================================================================} procedure DelRange(Minidx,Maxidx:integer); var r,abstand:real; begin //zu viele Werte löschen r:=0; abstand:=Verhaeltnis/(Verhaeltnis-1)*3; // abstand von den Indexen der einzelnen Werten while round(r)<=Values.Count-1 do begin if True then Values.Delete(round(r)); r:=r+abstand-1; // minus 1 da die Werte 1 vorrücken end; end; {============================================================================== Procedure: CalcImportant ==============================================================================} procedure CalcRange(MinRange,MaxRange:real); var oldx,oldLS,newx,newLS,newImage,Step, r:real; s:TVec; begin if MinRange>=MaxRange then exit; CalcInterestingPoints(MinRange, MaxRange); r:=MinRange; s:=CalcAngleDeflectionVec(r); oldx:=funcx(s); oldLS:=funcLS(s); repeat s:=CalcAngleDeflectionVec(r); newx:=funcx(s); newLS:=funcLS(s); if CalcGamma then newImage:=funcImage(s) else newImage:=0; Values.Add(Koor3(newx,newImage,newLS, kkx, kkImage, kkLS), Chart.Color); Step:=GetStep(oldx,oldLS,newx,newLS); r:=r+Step; inc(NewCalculatedPoints); oldx:=newx; oldLS:=newLS; until r>=MaxRange; Values.sort(xyzkX); end; {============================================================================== Procedure: ReCalc ==============================================================================} //procedure ReCalc; //begin //end; //{============================================================================== //Procedure: CalcMove //==============================================================================} //procedure CalcMove; //begin //DelUnVisibleValues; ////links //CalcRange(mini,funcAntiX(SaS.OldChart.ZoomMin)); ////rechts //CalcRange(funcAntiX(SaS.OldChart.ZoomMax),maxi); //end; {============================================================================== Procedure: CalcZoom ==============================================================================} //procedure CalcZoom; //begin //Values.Clear; //CalcRange(Mini,maxi); //DelUnVisibleValues; //with Parent.BottomAxis do //if anzpixel<>0 then //abstand:=(maxi-r)/anzpixel/(1-Verhaeltnis) //else //abstand:=(maxi-r)/2000; // zeichnet die restlichen punkte //repeat //Values.Add(funcx(r),funcLS(r)); //inc(NewCalculatedPoints); //r:=r+abstand; //until r>=maxi; //end; //{============================================================================== //Procedure: CalcUnZoom //==============================================================================} //procedure CalcUnZoom; //begin //// wenn (nix passiert, bzw er zoomt) dann nix machen //if Verhaeltnis<=1 then //begin //ReCalc; //exit; //end; ////zu viele Werte löschen //DelRange(0,Values.Count-1); ////drum herum zeichnen ////links //CalcRange(mini,funcAntiX(SaS.OldChart.ZoomMin)); ////rechts //CalcRange(funcAntiX(SaS.OldChart.ZoomMax),maxi); //end; {============================================================================== Procedure: CalcImportant ==============================================================================} procedure CalcImportant; begin Values.Clear; CalcRange(mini,maxi); end; begin DeleteFile(ExtractFilePath(ParamStr(0))+'s1.txt'); {$IFDEF CalcTimes} tick:=GetTickCount; {$ENDIF} // if UseMaxMin then //always calciulate the min max for plotting // if (checkMaxMin.Checked) then CalcMinMax(xAxisType,LSAxisType,ImageAxisType); // getAllspecifications; //BeginUpdate; NewCalculatedPoints:=0; funcx:=getXFunc(xAxisType); funcLS:=getLSFunc(LSAxisType); // funcAntiX:=getAntiXFunc(xAxisType); funcImage:=getImageFunc(ImageAxisType); //maxi:=Min(funcAntiX(Chart.Box.VisibleRect.Right),pi/2+aperture.slit.beta); // nichts zeichnen was beim gedrehten über 90° wäre //Mini:=Max(funcAntiX(Chart.Box.VisibleRect.Left),-pi/2+aperture.slit.beta); // nichts zeichnen was beim gedrehten über 90° wäre maxi:=CalcMaxAlpha; // nichts zeichnen was beim gedrehten über 90° wäre Mini:=CalcMinAlpha; // nichts zeichnen was beim gedrehten über 90° wäre //maxi:=2e-4; // nichts zeichnen was beim gedrehten über 90° wäre //Mini:=-maxi; // nichts zeichnen was beim gedrehten über 90° wäre if Quality=0 then Quality:=1; MaxStep:=(maxi-Mini)/1200/Quality*20; MinStep:=(maxi-Mini)/3000/Quality*20; { with self.Parent.BottomAxis do anzpixel:=(AxisToPixel(funcx(maxi))-AxisToPixel(funcx(r)))/Quality;} Verhaeltnis:=1; //if (funcAntiX(SaS.OldChart.ZoomMax)-funcAntiX(SaS.OldChart.ZoomMin))=0 then //Verhaeltnis:=1 //else //Verhaeltnis:=(maxi-mini)/(funcAntiX(SaS.OldChart.ZoomMax)-funcAntiX(SaS.OldChart.ZoomMin)); //if (Verhaeltnis=1)and(UpdatingType<>UCalcAndDraw)and(UpdatingType<>UDraw) then //d.h. wenn der ausschnitt nicht verändert wird sondern nur neu gezeichnet werden soll //begin //ReCalc; // dann verlasst er diese procedure ////EndUpdate; //exit; //end; /////////////////////////////////////////////////////////////////// /// wichtig //// /////////////////////////////////////////////////////////////////// //case UpdatingType of ////UMove: CalcMove; ////UZoom: CalcZoom; ////UUnZoom: CalcUnZoom; ////Uimportant: CalcImportant; //end; CalcImportant; // Values.Sort; //log form1.AddLog(self.ClassName+inttostr(number)+' wurde berechnet',self.Chart.Color); {$IFDEF CalcTimes} WriteLn(ClassName+' Nr.'+IntToStr(number)+' Time per Value ='+floattostr((GetTickCount-tick)/Values.count*1000)+' microseconds'); {$ENDIF} end; procedure TSingleSlit.DrawOGL; begin TLineChart(Chart).DrawOGL; if UseMaxMin then ChartMinMax.DrawOGL; end; {----------------------------------------------------------------------------- Description: Procedure: MakeRightColor Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TSingleSlit.MakeRightColor; begin self.LED.ColorOn:=WavelengthToRGB(SaS.Source[number].lambda{*1E9}); //das ruft nämlich die property auf und ich kann mir pen.color sparen dialog.Color:=self.LED.ColorOn; Chart.Color:=self.LED.ColorOn; if UseMaxMin then ChartMinMax.Color:=self.LED.ColorOn; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit TRSNSlit //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {============================================================================== Procedure: create Belongs to: TRSNSlit Result: None Parameters: AOwner : TComponent = thisparent : TRSCustomChartPanel = anumber : byte = Description: ==============================================================================} constructor TRSNSlit.create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); begin inherited; SlitType:=MyN; ShowMinLabels:=false; end; function TRSNSlit.MaximaWidth: extended; begin result := 1/aperture.slit.count/(aperture.slit.distance/200e-6); end; {----------------------------------------------------------------------------- Description: Procedure: writeCaption Arguments: (var checkbox:TCheckbox) Result: None Detailed description: -----------------------------------------------------------------------------} procedure TRSNSlit.writeCaption(var checkbox:TCheckbox); begin checkbox.Caption:='(Gitter ohne Einzelspaltüberlagerung)'; checkbox.Font.Size:=8; CalcMaxima:=true; CalcMinima:=false; Visible:=false; end; function TRSNSlit.PathDifferenceOfVec(s: TVec): extended; var cosalpha1,cosalpha2,beta:extended; l0:Tvec; begin beta:=aperture.slit.beta; l0:=Vec(-1,0,0); cosalpha1:= -l0 * CalcGyVec ; cosalpha2:=s * CalcGyVec ; result:=aperture.slit.distance * ( cosalpha1 + cosalpha2 ) / SaS.Source[number].lambda; end; //{----------------------------------------------------------------------------- //Description: //Procedure: CalcMinMax //Arguments: xAxisType:TxAxisType; LSAxisType:TLSAxisType; percision:word=0 //Result: None //Detailed description: //-----------------------------------------------------------------------------} //procedure TRSNSlit.CalcMinMax(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; percision:word=0); //var funcLS,funcx, funcImage:TFunctionVecType; //i:integer; //arMin,arMax:TRealArray; //begin //if not UseMaxMin then //exit; //funcLS:=getLSFunc(LSAxisType); //funcx:=getXFunc(xAxisType); //FuncImage:=getImageFunc(ImageAxisType); //arMin:=TRealArray.Create; //arMax:=TRealArray.Create; //try ////ins array schreiben //for i:=0 to NSlitCountMax do //arMax.insert(i,NSlitMaxtoAlpha(i)); //for i:=0 to NSlitCountMin do //arMin.insert(i,NSlitMintoAlpha(i)); //arMin.delete(0); ////überschneidungen rauswerfen //arMin.DelDubbleValues(arMax,[0]); ////ins diagramm zeichnen //with self.ChartMinMax do //begin //ValuesMaxMin.Clear; //Font.Color:=self.Chart.Color; //for i:=0 to arMin.count-1 do //begin //ValuesMaxMin.Add(Koor3(funcx(arMin[i]), funcImage(arMin[i]), funcLS(arMin[i]), kkx, kkImage, kkLS),inttostr(i)+'. Min'); //ValuesMaxMin.Add(Koor3(funcx(-arMin[i]), funcImage(-arMin[i]), funcLS(-arMin[i]), kkx, kkImage, kkLS),inttostr(i)+'. Min'); //end; //for i:=0 to arMax.count-1 do //begin //arMax[i]:=findnextMaxMin(funcLS,arMax[i],-pi/2,pi/2,true); //ValuesMaxMin.Add(Koor3(funcx(arMax[i]),funcImage(arMin[i]), funcLS(arMax[i]), kkx, kkImage, kkLS),inttostr(i)+'. Max'); //ValuesMaxMin.Add(Koor3(funcx(-arMax[i]), funcImage(-arMin[i]), funcLS(-arMax[i]), kkx, kkImage, kkLS),inttostr(i)+'. Max'); //end; //end; //finally //arMin.Free; //arMax.Free; //end; //end; //{============================================================================== //Procedure: alpha2lambda //Belongs to: TRSNSlit //Result: extended //Parameters: //alpha : extended = //Description: //==============================================================================} //function TRSNSlit.alpha2lambda(alpha:extended):extended; //begin //result:=aperture.slit.distance * sin(alpha) / SaS.Source[number].lambda; //end; //{============================================================================== //Procedure: lambda2alpha //Belongs to: TRSNSlit //Result: extended //Parameters: //lambda : extended = //Description: //==============================================================================} //function TRSNSlit.lambda2alpha(lambda:extended):extended; //var temp:extended; //begin //temp:=lambda*SaS.Source[number].lambda/aperture.slit.distance; //korrigiere(temp,-1,1); //result:=arcsin(temp); //end; function TRSNSlit.MaxFunc(z:integer; var alpha:Extended):TMinMaxStaus; var l0MalGx:extended; begin l0MalGx:=Vec(-1,0,0) * CalcGyVec; alpha:=z*SaS.Source[number].lambda/aperture.slit.distance +l0MalGx; if IsInRange(alpha, -1,1) then begin Result:=mmsMainMax; alpha:=aperture.slit.beta + arcsin(alpha ); if not IsInRange(alpha, CalcMinAlpha, CalcMaxAlpha) then Result:=mmsEnd; end else Result:=mmsEnd; end; function TRSNSlit.MinFunc(z:integer; var alpha:Extended):TMinMaxStaus; begin Result:=mmsEnd; alpha:=0; //if not IsInRange(alpha, CalcMinAlpha, CalcMaxAlpha) then //Result:=mmsEnd; end; //{----------------------------------------------------------------------------- //Description: //Procedure: NSlitCountMax //Arguments: None //Result: word //Detailed description: //-----------------------------------------------------------------------------} //function TRSNSlit.NSlitCountMax:word; //begin //result:=trunc(aperture.slit.distance/SaS.Source[number].lambda); //end; //{----------------------------------------------------------------------------- //Description: //Procedure: NSlitCountMin //Arguments: None //Result: word //Detailed description: //-----------------------------------------------------------------------------} //function TRSNSlit.NSlitCountMin:word; //begin //result:= trunc(aperture.slit.count*aperture.slit.width/SaS.Source[number].lambda); //end; //{----------------------------------------------------------------------------- //Description: gibt den winkel der Maxima nter ordnung an //Procedure: NSlitMaxtoAlpha //Arguments: N:integer //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TRSNSlit.NSlitMaxtoAlpha(N:integer):extended; //var pre:real; //begin //// Open Formel Maximum: %alpha = arcsin left (n cdot %lambda over g - sin(%beta)right )+%beta newline newline %alpha = arcsin left (- n cdot %lambda over g - sin(%beta)right )+%beta //result:=0; //pre:=abs(n)*SaS.Source[number].lambda/aperture.slit.distance; //{ if pre>1 then //showmessage('hilfw');} //if (abs(n)<=NSlitCountMax)and(pre<=1) then //result:=arcsin( pre ); //result:=sign(n)*result; //end; //{----------------------------------------------------------------------------- //Description: gibt den winkel der Minima nter ordnung an //Procedure: NSlitMintoAlpha //Arguments: N:integer //Result: extended //Detailed description: //-----------------------------------------------------------------------------} //function TRSNSlit.NSlitMintoAlpha(N:integer):extended; //begin //// Open Formel Minimum: %alpha = arcsin left (n cdot %lambda over {N cdot g} - sin(%beta)right )+%beta newline newline %alpha = arcsin left (- n cdot %lambda over {N cdot g} - sin(%beta)right )+%beta //result:=0; //if (abs(n)>0)and(abs(n)<=NSlitCountMin-1) then //result:=arcsin( abs(n)*SaS.Source[number].lambda/aperture.slit.distance/aperture.slit.count ); //result:=sign(n)*result; //end; {----------------------------------------------------------------------------- Description: Procedure: NSlitAmplitude Arguments: alpha:extended Result: extended Detailed description: Formel über Zeigerdarstellung herleiten Zwei Sinus Beziehungen suchen und durcheinanderer Dividiren und nach A(alpha) auflösen -----------------------------------------------------------------------------} function TRSNSlit.NSlitAmplitude(s:TVec):extended; // Formel die Für 2 Spalten Stimmt const delta=0.000001; var phi,cosalpha1,cosalpha2, Gangunterschied, beta:extended; l0:Tvec; begin beta:=aperture.slit.beta; l0:=Vec(-1,0,0); cosalpha1:= -l0 * CalcGyVec ; cosalpha2:= s * CalcGyVec ; Gangunterschied:=aperture.slit.distance * ( cosalpha1 + cosalpha2 ); phi:= 2*pi*Gangunterschied / SaS.Source[number].lambda; if abs(sin(phi/2))>delta then result:=1* sin(aperture.slit.count*phi/2)/(aperture.slit.count*sin(phi/2)) else result:=1* cos(aperture.slit.count*phi/2)/(cos(phi/2)); end; {----------------------------------------------------------------------------- Description: Procedure: NSlitIntensity Arguments: alpha:extended Result: extended Detailed description: -----------------------------------------------------------------------------} function TRSNSlit.NSlitIntensity(s:TVec):extended; begin result:=sqr(self.NSlitAmplitude(s)); end; //{============================================================================== //Procedure: getInterestingPointInfo //Belongs to: TSingleSlit //Result: TInterestingFunctionType //Parameters: //CountPoints : word = //Description: //==============================================================================} //function TRSNSlit.getInterestingPointInfo(var CountPoints:word):TInterestingFunctionType; //begin //CountPoints:=NSlitCountMax; //result:=@NSlitMaxtoAlpha; //end; {----------------------------------------------------------------------------- Description: Procedure: getImageFunc Arguments: LSAxisType:TLSAxisType Result: TFunctionVecType Detailed description: // TLSAxisType=(Amplitude,Intensity,BrigthDark); -----------------------------------------------------------------------------} function TRSNSlit.getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; begin case LSAxisType of LSAmplitude: result:=@NSlitAmplitude; LSIntensity: result:=@NSlitIntensity; end; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit TCombiSlit //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {============================================================================== Procedure: create Belongs to: TCombiSlit Result: None Parameters: AOwner : TComponent = thisparent : TRSCustomChartPanel = anumber : byte = Description: ==============================================================================} constructor TCombiSlit.create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); begin inherited; SlitType:=MyCombi; end; {----------------------------------------------------------------------------- Description: Procedure: writeCaption Arguments: (var checkbox:TCheckbox) Result: None Detailed description: -----------------------------------------------------------------------------} procedure TCombiSlit.writeCaption(var checkbox:TCheckbox); begin checkbox.Caption:='reales Gitter'; CalcMaxima:=true; CalcMinima:=false; Visible:=true; end; {----------------------------------------------------------------------------- Description: Procedure: CombiSlitAmplitude Arguments: alpha:extended Result: extended Detailed description: -----------------------------------------------------------------------------} function TCombiSlit.ApproxCombiSlitAmplitude(s:TVec):extended; // Formel die Für 2 Spalten Stimmt begin result:=self.NSlitAmplitude(s) * self.OneSlitAmplitude(s); end; {============================================================================== Procedure: HuygensCombiSlitAmplitude Belongs to: TCombiSlit Result: extended Parameters: alpha : extended = Description: ==============================================================================} function TCombiSlit.HuygensCombiSlitAmplitude(s:TVec):extended; // Formel die Für 2 Spalten Stimmt var i:integer; temp:real; const1,e2,a,g, x,y:real; begin const1:=2*pi/SaS.source[number].lambda; e2:=sqr(aperture.ScreenDistance); a:=XKoorStrechtedOfVec(s); // a:=aperture.ScreenDistance*tan(alpha); g:=aperture.slit.distance; x:=0; y:=0; a:=a- aperture.slit.count/2 *g; for I := 0 to aperture.slit.count-1 do begin temp:=const1* sqrt( e2 + sqr(a + i*g) ); x:=x+cos(temp); y:=y+sin(temp); end; x:=x* OneSlitAmplitude(s)/aperture.slit.count; y:=y* OneSlitAmplitude(s)/aperture.slit.count; result:=sqrt(sqr(x)+sqr(y)); end; {============================================================================== Procedure: CombiSlitAmplitude Belongs to: TCombiSlit Result: extended Parameters: alpha : extended = Description: ==============================================================================} function TCombiSlit.CombiSlitAmplitude(s:TVec):extended; // Formel die Für 2 Spalten Stimmt begin case SaS.UsedFormula of UFApprox: Result:=ApproxCombiSlitAmplitude(s); UFHuygens: Result:=HuygensCombiSlitAmplitude(s); end; end; {----------------------------------------------------------------------------- Description: Procedure: CombiSlitIntensity Arguments: alpha:extended Result: extended Detailed description: -----------------------------------------------------------------------------} function TCombiSlit.CombiSlitIntensity(s:TVec):extended; begin result:=sqr(CombiSlitAmplitude(s)); end; {----------------------------------------------------------------------------- Description: Procedure: getImageFunc Arguments: LSAxisType:TLSAxisType Result: TFunctionVecType Detailed description: // TLSAxisType=(Amplitude,Intensity,BrigthDark); ich muss trotz gleichem Inhalt in TCombiSlit.getImageFunc und TRSNSlit.getImageFunc aufführen damit TCombiSlit.NSlitIntensity ausgeführt wird und nicht die geerbte Funktion die inherited getImageFunc Auch result:=inheritet getImageFunc(LSAxisType) kann ich nicht schreiben, da es das selbe ist Auch override von der getImageFunc kann ich nicht machen da sonst ich das result:=OneSlitIntensity(alpha) * inherited NSlitIntensity(alpha); nicht ausführen künnte -----------------------------------------------------------------------------} function TCombiSlit.getLSFunc(LSAxisType:TLSAxisType):TFunctionVecType; begin case LSAxisType of LSAmplitude: result:=@CombiSlitAmplitude; LSIntensity: result:=@CombiSlitIntensity; end; end; //{----------------------------------------------------------------------------- //Description: //Procedure: CalcMinMax //Arguments: xAxisType:TxAxisType; LSAxisType:TLSAxisType; percision:word=0 //Result: None //Detailed description: //-----------------------------------------------------------------------------} //procedure TCombiSlit.CalcMinMax(xAxisType:TxAxisType; LSAxisType:TLSAxisType; ImageAxisType:TImageAxisType; percision:word=0); //var funcLS,funcx, funcImage:TFunctionVecType; //i:integer; //arMin,arSingleMin,arMax:TRealArray; //begin //if not UseMaxMin then //exit; //funcLS:=getLSFunc(LSAxisType); //funcx:=getXFunc(xAxisType); //FuncImage:=getImageFunc(ImageAxisType); //arMin:=TRealArray.Create; //arMax:=TRealArray.Create; //arSingleMin:=TRealArray.Create; //try ////ins array schreiben //for i:=0 to NSlitCountMax do //arMax.insert(i,NSlitMaxtoAlpha(i)); //for i:=0 to NSlitCountMin do //arMin.insert(i,NSlitMintoAlpha(i)); //for i:=0 to SingleSlitCountMin do //arSingleMin.insert(i,SingleSlitMintoAlpha(i)); //arMin.delete(0); //arSingleMin.delete(0); ////überschneidungen rauswerfen //arMax.DelDubbleValues(arSingleMin,[0]); //arMin.DelDubbleValues(arMax,[0]); ////ins diagramm zeichnen //with self.ChartMinMax do //begin //ValuesMaxMin.Clear; //Font.Color:=self.Chart.Color; //for i:=0 to arMin.count-1 do //begin //{ Values.Add(funcx(arMin[i]),funcLS(arMin[i]),inttostr(i)+'. Minimum',self.Color); //Values.Add(funcx(-arMin[i]),funcLS(-arMin[i]),inttostr(i)+'. Minimum',self.Color);} //end; //for i:=0 to arMax.count-1 do //begin //arMax[i]:=findnextMaxMin(funcLS,arMax[i],-pi/2,pi/2,true); //ValuesMaxMin.Add(Koor3(funcx(arMax[i]), funcImage(arMin[i]), funcLS(arMax[i]), kkx, kkImage, kkLS),inttostr(i)+'. Max',self.Chart.Color); //ValuesMaxMin.Add(Koor3(funcx(-arMax[i]), funcImage(-arMin[i]), funcLS(-arMax[i]), kkx, kkImage, kkLS),inttostr(i)+'. Max',self.Chart.Color); //end; //end; //finally //arMin.Free; //arMax.Free; //arSingleMin.Free; //end; //end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity TImageIntensity //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: create Arguments: AOwner: TComponent; thisparent:TRSCustomChartPanel; number:byte Result: None Detailed description: -----------------------------------------------------------------------------} constructor TImageIntensity.create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte; aCreateMaxMin:boolean); begin inherited; Chart.Free; Chart:=TBorderdBackgroundChart.Create(abox, Values); Chart.Depth:=Koor1(-255+number,kkz); Chart.IntensityColorFactor:=SaS.IntensityColorFactor; Chart.WhatIsYValue:=xyzkY; if UseMaxMin then ChartMinMax.WhatIsYValue:=xyzkY; SlitType:=MyImage; CalcGamma:=true; end; {----------------------------------------------------------------------------- Description: Procedure: destroy Arguments: None Result: None Detailed description: wichtig, da bmp zu garnix gehört und unbedingt hier weider zerstört werden muss -----------------------------------------------------------------------------} destructor TImageIntensity.destroy; begin inherited; end; {============================================================================== Procedure: Draw2ColorLine Belongs to: TImageIntensity Result: None Parameters: xPos1 : word = xPos2 : word = Col1 : TColor = Col2 : TColor = Intensity1 : real = Intensity2 : real = Description: ==============================================================================} //procedure TImageIntensity.Draw2ColorLine(xPos1,xPos2:word; Col1,Col2:TColor; Intensity1,Intensity2:real); //var I:integer; //col:Tcolor; //perc:real; //begin //for I := xPos1 to xPos2 do //begin //if xPos1=xPos2 then //perc:=0.5 //else //perc:=(i-xPos1)/(xPos2-xPos1); //col:=AddColors(col1,col2,(1-perc)*Intensity1,perc*Intensity2); //self.bmp.Canvas.Pixels[i,0]:=col; //end; //end; {============================================================================== Procedure: DrawColorLine Belongs to: TImageIntensity Result: None Parameters: xPos1 : word = xPos2 : word = Col : TColor = Intensity : real = Description: ==============================================================================} //procedure TImageIntensity.DrawColorLine(xPos1,xPos2:word; Col:TColor; Intensity:real); //begin //with bmp.Canvas do //begin //Pen.Color:= IntensityColor(col,Intensity); //MoveTo(xPos1,0); //LineTo(xPos2,0); //end; //end; {============================================================================== Procedure: DrawPixel Belongs to: TImageIntensity Result: None Parameters: xPos : word = Col : TColor = Intensity : real = Description: ==============================================================================} //procedure TImageIntensity.DrawPixel(xPos:word; Col:TColor; Intensity:real); //begin //with bmp.Canvas do //Pixels[xPos,0]:=IntensityColor(col,Intensity); //end; {----------------------------------------------------------------------------- Description: Procedure: writeCaption Arguments: (var checkbox:TCheckbox) Result: None Detailed description: -----------------------------------------------------------------------------} procedure TImageIntensity.writeCaption(var checkbox:TCheckbox); begin checkbox.Caption:='Schirmbild'; if assigned(self.checkMaxMin) then self.checkMaxMin.Checked:=true; CalcMaxima:=true; CalcMinima:=false; Visible:=true; end; procedure TImageIntensity.DrawOGL; begin TBackgroundChart(Chart).DrawOGL; if UseMaxMin then ChartMinMax.DrawOGL; end; {============================================================================== Procedure: Calc Belongs to: TImageIntensity Result: None Parameters: xAxisType : TxAxisType = LSAxisType : TLSAxisType = UpdatingType : TUpdatingType = Quality : real = 2 Description: Hier wird die Zusammenfassende Arebit gemacht, nämlich das zeichnen ==============================================================================} //procedure TImageIntensity.Calc(xAxisType:TxAxisType; LSAxisType:TLSAxisType; UpdatingType:TUpdatingType; Quality:real=20); //var funcx,funcAntiX:TFunctionVecType; //lcut,rcut:integer; //ZMin,constFak:real; //{============================================================================== //Procedure: XtoPixel //Parameters: //r : real = //==============================================================================} ////function XtoPixel(r:real):integer; ////begin ////result:=trunc( ( funcx(r) - Zmin )/constFak +lcut ); ////end; //{============================================================================== //Procedure: XtoPixel //Parameters: //r : real = //==============================================================================} ////function DistanceInPixel(r1,r2:real):integer; overload; ////begin ////result:=abs(XtoPixel(r2)-XtoPixel(r1)); ////end; ////function DistanceInPixel(Pixel1:integer; r1:real):integer; overload; ////begin ////result:=abs(Pixel1-XtoPixel(r1)); ////end; ////function DistanceInPixel(Pixel1,Pixel2:integer):integer; overload; ////begin ////result:=abs(Pixel1-Pixel2); ////end; //{============================================================================== //Procedure: MaxValue //Belongs to: None //Result: real //Parameters: //OnPointI : integer = //SearchFirstIdx : boolean = //FirstIdx : integer = //slitobject : TRSChart = //funcAntiX : TFunctionVecType = //NextFirstIdx : integer = //Description: Sucht den Maximalwert auf einem Bildpunkt (=OnPointI) und gibt den Wert zurück //Damit man wenn, was der nächste Index außerhalb dieses Bildpunktes ist, gibt er //auch NextFirstIdx zurück //==============================================================================} ////function MaxValue(OnPointI:integer; SearchFirstIdx:boolean; FirstIdx:integer; slitobject:TChart; funcAntiX:TFunctionVecType; var NextFirstIdx:integer):real; ////var i:word; ////temp:real; ////begin ////if SearchFirstIdx or ////(FirstIdx<slitobject.Values.Count)and(XtoPixel(funcAntiX(slitobject.Values[FirstIdx].X))<>OnPointI) then // suche ersten idx der auf den Bildpunkt OnPointI füllt ////for I := 0 to slitobject.Values.Count - 1 do // wenn es gefordert wird, oder wenn die angegebenen Werte nicht stimmen ////if XtoPixel(funcAntiX(slitobject.Values[i].Pos.X))=OnPointI then ////begin ////FirstIdx:=i; ////break; ////end; ////result:=0; ////for I := FirstIdx to slitobject.Values.Count-1 do // laufe die idx weiter durch bis es den bildpunkt verlässt ////begin ////if XtoPixel(funcAntiX(slitobject.Values[i].Pos.x))<>OnPointI then ////begin ////NextFirstIdx:=i; ////break; ////end; ////temp:=slitobject.Values[i].Pos.LS; ////if abs(Result)<abs(temp) then ////Result:=abs(temp); ////end; ////end; //{============================================================================== //Procedure: SumValue //Belongs to: None //Result: real //Parameters: //OnPointI : integer = //SearchFirstIdx : boolean = //FirstIdx : integer = //slitobject : TRSChart = //funcAntiX : TFunctionVecType = //NextFirstIdx : integer = //Description: Schlechter Versucht!!! Wird nicht benutzt!!! //==============================================================================} //{ function SumValue(OnPointI:integer; SearchFirstIdx:boolean; FirstIdx:integer; slitobject:TRSChart; funcAntiX:TFunctionVecType; var NextFirstIdx:integer):real; //var i:word; //temp:real; //begin //if SearchFirstIdx or //(FirstIdx<slitobject.Values.Count)and(XtoPixel(funcAntiX(slitobject.Values.Items[FirstIdx].X))<>OnPointI) then // suche ersten idx der auf den Bildpunkt OnPointI füllt //for I := 0 to slitobject.Values.Count - 1 do // wenn es gefordert wird, oder wenn die angegebenen Werte nicht stimmen //if XtoPixel(funcAntiX(slitobject.Values.Items[i].X))=OnPointI then //begin //FirstIdx:=i; //break; //end; //result:=0; //for I := FirstIdx to slitobject.Values.Count-1 do // laufe die idx weiter durch bis es den bildpunkt verlässt //begin //if XtoPixel(funcAntiX(slitobject.Values.Items[i].x))<>OnPointI then //begin //NextFirstIdx:=i; //break; //end; //temp:=slitobject.Values.Items[i].LS; //Result:=Result+temp; //end; //korrigiere(Result,0,1); //end;} //{============================================================================== //Procedure: CalcAllCases //Description: Hier zeichnet er es, egal ob neue Werte berechnet werden müssen, oder ob sie aus dem //CombiArray genommen werden. //Falls noch keine Werte da sind und kein CombiArray da ist, dann berechnet er die //Werte erst in das eigene ValueArray und zeichnet dann //Da die Werte nicht regelmäßig verteilt sind, sind manchmal mehrere Werte //auf einem Bildpunkt, und manchmal weniger. Damit aber alle Punkte gezeichnet werden //aber auch nicht mehrfach, ist es nötig zu unterschieden, ob die Punkte mehr oder weniger als //einen Bildpunkt auseinanderliegen. //==============================================================================} ////procedure CalcAllCases(WithCombiValues:boolean); ////var i,j{,FirstIdx},NextFirstIdx:integer; ////slitobject:TChart; ////funcAntiX:TFunctionVecType; ////oldy,newy:real; ////oldx,newx:integer; ////LastDrawedWithSpecialSum, ////ExtendedLog:boolean; ////begin ////ExtendedLog:=form1.CheckPixelExtendedImageIntesity.Checked; ////// Dieser Abschnitt regelt, ob Werte übernommen, oder neu berechnet werden ////// und in welchem array diese dann landen ////if WithCombiValues then //selbst berechnen oder auslesen aus combivalues? ////begin ////slitobject:=TScreem(self.Owner).CombiSlit; ////funcAntiX:=getAntiXFunc(xAxisType); ////end ////else ////begin ////slitobject:=self; ////funcAntiX:=@returnValue; ////Calc(xAxisType, LSAxisType, UpdatingType, false,true, Quality); ////if (slitobject.Values.Count<=0)and(UpdatingType<>UCalcAndDraw) then // falls er keine Ergebnisse hat, weil flaser Update Typ ////Calc(xAxisType, LSAxisType, UCalcAndDraw, false,true, Quality); ////if (slitobject.Values.Count<=0) then // falls er immer noch keine Ergebnisse hat, dann muss er raus gehen ////exit; ////end; ////with slitobject do ////begin ////{ FirstIdx:=0; } ////NextFirstIdx:=0; ////LastDrawedWithSpecialSum:=false; ////oldx:=XtoPixel(funcAntiX(Values[0].X)); ////oldy:=abs(Values[0].LS); ////for I := 1 to Values.Count-1 do // er zählt die werte im Array durch ////begin ////newx:=XtoPixel(funcAntiX(Values[i].Pos.X)); // den x wert berechnen ////if (oldx=newx){and(i<=Values.Count-2)and(DistanceInPixel(newx,funcAntiX(Values.Items[i+1].X))<1)} then // wenn der neue x-Wert = dem nächsten, bedeutet das sie liegen auf dem selben Bildpunkt, ////// was zur folge hat, dass er das Maximum suchen muss ////begin ////if LastDrawedWithSpecialSum then // er darf nicht immer wieder das Maxiumum suchen und zeichnen ////begin // er muss hier sobald er es einmal gezeichnet hat weiter bis zum nächsten Punkt ////if ExtendedLog then form1.AddLog('Continue bei '+inttostr(newx)); ////continue; ////end; ////newy:=MaxValue(newx,false,i,slitobject,funcAntiX,NextFirstIdx); // das Maximum suchen und zeichnen ////CalcPixel(newx,self.Pen.Color,newy); // Jetzt zeichnet er den einen Pixel ////LastDrawedWithSpecialSum:=true; ////if ExtendedLog then form1.AddLog('Pixel '+inttostr(newx)+ HTMLColorString(' Farbe',IntensityColor(self.Color,newy))); ////end ////else ////begin ////newy:=abs(Values[i].Pos.LS); ////Draw2ColorLine(oldx+1,newx,self.Pen.Color,self.Pen.Color,oldy,newy); // Linie zwischen den "weit" entfernten Wertepaaren zeichnen ////LastDrawedWithSpecialSum:=false; ////if ExtendedLog then form1.AddLog('Line '+inttostr(oldx+1)+' bis '+inttostr(newx)+ HTMLColorString(' Farbe',IntensityColor(self.Color,newy))); ////end; ////if ExtendedLog and (newx-(oldx+1)>1)and LastDrawedWithSpecialSum then ////for j := oldx+1 to newx do ////form1.AddLog('Pixel Ausgelssen !!! i= '+inttostr(j)+ ColorString(' Farbe',IntensityColor(self.Color,newy))); ////oldy:=newy; ////oldx:=newx; ////end; ////end; //{ oldx:=lcut; //oldy:=MaxValue(oldx,true,0,slitobject,funcAntiX,NextFirstIdx); //FirstIdx:=NextFirstIdx; //for i := lcut+1 to bmp.Width-rcut do //begin //newy:=MaxValue(i,false,FirstIdx,slitobject,funcAntiX,NextFirstIdx); //Draw2ColorLine(oldx, i, //Self.Color, Self.Color, //oldy, newy); //FirstIdx:=NextFirstIdx; //oldx:=i; //oldy:=newy; //end;} ////end; //{============================================================================== //Procedure: CalcNormal //==============================================================================} //{ procedure CalcNormal; //var i,xold,xnew:integer; //ynew:real; //begiTR3Vecn //Calc(Values,xAxisType, LSAxisType, UpdatingType, false,true, Quality); //xold:=XtoPixel(Values.Items[0].X); //for I := 1 to Values.Count-1 do //begin //xnew:=XtoPixel(Values.Items[i].X); //ynew:=abs(Values.Items[i].LS); //// DrawColorLine(trunc(i-step+lcut),trunc(i+lcut),self.Pen.Color,ynew); //DrawColorLine(xold, //xnew, //self.Pen.Color, //YNew //); //xold:=xnew; //end; //end;} //{============================================================================== //Procedure: drawWithCombiValues //==============================================================================} //{ procedure drawWithCombiValues; //var ynew:real; //i,xold,xnew:integer; //begin //with TScreem(self.Owner).CombiSlit do //begin //xold:=XtoPixel(funcAntiX(Values.Items[0].X)); //for i:= 1 to Values.Count-1 do //begin //xnew:=XtoPixel(funcAntiX(Values.Items[i].X)); //ynew:=abs(Values.Items[i].LS); //DrawColorLine(xold,xNew,self.Pen.Color,ynew); //xOld:=xNew; //end; //end; //end;} //begin ////Self.BeginUpdate; //// getAllspecifications; ////self.bmp.Canvas.FillRect(self.bmp.Canvas.ClipRect); ////lcut:=self.Parent.xAxis.AxisToPixel(self.Parent.xAxis.Minimum)-0; ////rcut:=self.Parent.Width- self.Parent.xAxis.AxisToPixel(self.Parent.xAxis.Maximum)-11 ; //funcx:=getXFunc(xAxisType); //funcAntiX:=getAntiXFunc(xAxisType); //if Quality=0 then //Quality:=1; //BackgroundChart.DrawOGL; ////Zmin:=self.Parent.xAxis.Minimum; ////constFak:=(self.Parent.xAxis.Maximum-self.Parent.xAxis.Minimum) / (self.bmp.Width-(lcut+rcut)); ////welches zeichnen soll ermachen ////with TScreem(self.Owner).CombiSlit do ////if Visible and (Values.Count>=20) then ////DrawAllCases(true) ////else ////CalcAllCases(false); //{ with TScreem(self.Owner).CombiSlit do //if Visible and (Values.Count>=1) then //CalcWithCombiValues //else //CalcNormal;} ////mitte markieren //// self.bmp.Canvas.Pixels[self.Parent.BottomAxis.AxisToPixel(0),0]:=cllime; ////MergeBmp(SaS.Masterbmp,bmp,SaS.Masterbmp); //// self.bmp.SaveToFile('C:\'+self.ClassName+inttostr(number)+'.bmp'); //if Form1.CheckExImageIntensity.Checked then //begin //form1.AddLog(self.ClassName+inttostr(number)+':',self.Color); //{ form1.AddLog(' anzpixel '+FormatFloat('#.00',anzpixel),self.Color); //form1.AddLog(' step '+floattostr(step),self.Color);} ////form1.AddLog(' lcut '+floattostr(lcut),self.Color); ////form1.AddLog(' rcut '+inttostr(rcut),self.Color); ////form1.AddLog(' max '+inttostr(self.Parent.xAxis.AxisToPixel(self.Parent.BottomAxis.ZoomMaximum)),self.Color); //form1.AddLog(''); //end //else //form1.AddLog(self.ClassName+inttostr(number)+' wurde gezeichnet',self.Color); ////self.EndUpdate; //end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem TArrayItem //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: create Arguments: AOwner: TComponent;aForm:TForm1; number:byte Result: None Detailed description: -----------------------------------------------------------------------------} constructor TArrayItem.create(AOwner: TComponent; aForm:TForm1; anumber:byte); begin inherited create(AOwner); FForm:=aForm; Fnumber:=anumber; end; procedure TArrayItem.WriteFForm(Form: TForm1); begin FForm:=Form; end; {----------------------------------------------------------------------------- Description: für property active Procedure: setactive Arguments: value:boolean Result: None Detailed description: -----------------------------------------------------------------------------} procedure TArrayItem.setactive(value:boolean); begin Factive:=value; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem TScreem //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: create Arguments: AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte Result: None Detailed description: -----------------------------------------------------------------------------} constructor TScreem.create(AOwner: TComponent; aForm:TForm1; abox:TOGlBox; anumber:byte); begin inherited create(AOwner, aForm, anumber); FBox:=abox; CalcReflection:=false; ColorNumber:=0; CheckNumber:=0; //diagramme SingleSlit:=TSingleSlit.Create(self,aForm, abox,number, true); NSlit:=TRSNSlit.Create(self,aForm, abox,number, true); CombiSlit:=TCombiSlit.Create(self,aForm, abox,number, true); //image ImageIntensity:=TImageIntensity.Create(self,aForm, abox,number, true); self.active:=false; self.Color:= WavelengthToRGB(SaS.Source[number].lambda{*1E9}); //das ruft nämlich die property auf und ich kann mir pen.color sparen end; {----------------------------------------------------------------------------- Description: Procedure: Destroy Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} destructor TScreem.Destroy; begin SingleSlit.Free; NSlit.Free; CombiSlit.Free; ImageIntensity.Free; inherited destroy; end; {----------------------------------------------------------------------------- Description: für property active Procedure: setactive Arguments: value:boolean Result: None Detailed description: -----------------------------------------------------------------------------} procedure TScreem.setactive(value:boolean); begin inherited setactive(value); self.SingleSlit.active:=value; self.NSlit.active:=value; self.CombiSlit.active:=value; self.ImageIntensity.active:=value; end; {----------------------------------------------------------------------------- Description: Procedure: getspecifications Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TScreem.getspecifications; begin self.SingleSlit.getspecifications; self.NSlit.getspecifications; self.CombiSlit.getspecifications; self.ImageIntensity.getspecifications; case form.RadioXAxis.ItemIndex of 0: xAxisType:= xmeter; 1: xAxisType:= xangle; 2: xAxisType:= xlambda; end; case form.RadioLSAxis.ItemIndex of 0: if LSAxisType<>LSAmplitude then LSAxisType:= LSAmplitude; 1: if LSAxisType<>LSIntensity then LSAxisType:= LSIntensity; end; case form.RadioImageAxis.ItemIndex of 0: ImageAxisType:= ImageMeter; 1: ImageAxisType:= ImageAngle; end; end; {============================================================================== Procedure: CalcAll Belongs to: TScreem Result: None Parameters: Quality : real = 20 Description: ==============================================================================} procedure TScreem.CalcAll(Quality:real=20); begin Calc(true,true,true,true,Quality); end; {============================================================================== Procedure: CalcOnlyVisible Belongs to: TScreem Result: None Parameters: UpdatingType : TUpdatingType = Quality : real = 20 Description: ==============================================================================} procedure TScreem.CalcOnlyVisible(Quality:real=20); begin Calc(self.SingleSlit.Visible,self.NSlit.Visible,self.CombiSlit.Visible,self.ImageIntensity.Visible, Quality); end; {============================================================================== Procedure: Calc Belongs to: TScreem Result: None Parameters: OneSlit : boolean = NSlit : boolean = CombiSlit : boolean = Image : boolean = UpdatingType : TUpdatingType = Quality : real = 20 Description: ==============================================================================} procedure TScreem.Calc(bSingleSlit,bNSlit,bCombiSlit,bImage:boolean; Quality:real=20); begin getAllspecifications; // mrs; LabelChart; if bSingleSlit then SingleSlit.Calc(self.xAxisType,LSAxisType,ImageAxisType, Quality); if bNSlit then NSlit.Calc(self.xAxisType,LSAxisType,ImageAxisType, Quality); if bCombiSlit then CombiSlit.Calc(self.xAxisType,LSAxisType,ImageAxisType, Quality); if bImage then ImageIntensity.Calc(self.xAxisType,self.LSAxisType,ImageAxisType, Quality); end; procedure TScreem.DrawOGL(bSingleSlit, bNSlit, bCombiSlit, bImage: boolean); begin getAllspecifications; // mrs; LabelChart; if bSingleSlit then SingleSlit.DrawOGL; if bNSlit then NSlit.DrawOGL; if bCombiSlit then CombiSlit.DrawOGL; if bImage then ImageIntensity.DrawOGL; end; {----------------------------------------------------------------------------- Description: Procedure: deleteAllValues Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TScreem.deleteAllValues; begin SingleSlit.Values.Clear; NSlit.Values.Clear; CombiSlit.Values.Clear; ImageIntensity.Values.Clear; end; procedure TScreem.DrawOGLOnlyVisible; begin DrawOGL(self.SingleSlit.Visible,self.NSlit.Visible,self.CombiSlit.Visible,self.ImageIntensity.Visible); end; {----------------------------------------------------------------------------- Description: Procedure: LabelChart Arguments: xAxis:TxAxisType; LSaxis:TLSAxisType; ImageAxis:TImageAxisType Result: None Detailed description: -----------------------------------------------------------------------------} procedure TScreem.LabelChart(xAxis:TxAxisType; LSaxis:TLSAxisType; ImageAxis:TImageAxisType); var s:string; begin Box.xAxis.MainDescription:='Horizontale Ablenkung'; Box.LSAxis.MainDescription:='Licht-Intensität/Amplitude'; Box.ImageAxis.MainDescription:='Vertikale Ablenkung'; with Box.xAxis do case xAxis of xangle: begin Dimension:=(*KorrectUmlaut*)('°'); DimensionDescription:='Horizontaler Winkel'; end; xmeter: begin Dimension:='m'; DimensionDescription:='Horizontale Koordinaten'; end; xlambda: begin Dimension:='lambda'; DimensionDescription:='Gangunterschied'; end; end; with Box.xAxis do if Dimension<>'' then Title.Text:=DimensionDescription+' in '+Dimension else Title.Text:=DimensionDescription; with Box.LSAxis do case LSaxis of LSAmplitude: begin Dimension:=''; DimensionDescription:='Amplitude'; end; LSIntensity: begin Dimension:=''; DimensionDescription:='Intensit'+(*KorrectUmlaut*)('ä')+'t'; end; end; with Box.LSAxis do if Dimension<>'' then Title.Text:=DimensionDescription+' in '+Dimension else Title.Text:=DimensionDescription; with Box.ImageAxis do case ImageAxis of ImageAngle: begin Dimension:=(*(*KorrectUmlaut*)*)('°'); DimensionDescription:='Vertikaler Winkel'; end; ImageMeter: begin Dimension:='m'; DimensionDescription:='Vertikale Koordinaten'; end; end; with Box.ImageAxis do if Dimension<>'' then Title.Text:=DimensionDescription+' in '+Dimension else Title.Text:=DimensionDescription; s:=Box.LSAxis.DimensionDescription; case xAxis of xangle: s:=s+' '+(*(*KorrectUmlaut*)*)('ü')+'ber dem Winkel'; xmeter: s:=s+' '+(*(*KorrectUmlaut*)*)('ü')+'ber der x-Koordinate'; xlambda: s:=s+' '+(*(*KorrectUmlaut*)*)('ü')+'ber dem Gangunterschied'; end; box.Header.Text:=s; end; {----------------------------------------------------------------------------- Description: mache automatisch was gesucht ist Arguments: -----------------------------------------------------------------------------} procedure TScreem.LabelChart; begin LabelChart(self.xAxisType,self.LSAxisType, self.ImageAxisType); end; {----------------------------------------------------------------------------- Description: Procedure: MakeAllRightColor Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure TScreem.MakeAllRightColor; begin self.Color:= WavelengthToRGB(SaS.Source[number].lambda); //das ruft nämlich die property auf und ich kann mir pen.color sparen self.SingleSlit.MakeRightColor; self.NSlit.MakeRightColor; self.CombiSlit.MakeRightColor; self.ImageIntensity.MakeRightColor; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture Taperture //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} constructor Taperture.create(AOwner: TComponent; aForm:TForm1); begin inherited create(AOwner); Form:=aForm; LaserHeight:=90; ScreenDistance:=100; with self.slit do begin beta:=0; theta:=0; count:=1; distance:=6E-6; width:=1E-5; end; end; procedure Taperture.writeScreenDistance(value: real); begin if value<1E-10 then value:=1E-10; FScreenDistance:=value; end; {////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource Tsource //////////////////////////////////////////////////////////////////////////////////////////////////////////////////} {----------------------------------------------------------------------------- Description: Procedure: create Arguments: AOwner: TComponent; thisparent:Twincontrol; number:byte Result: None Detailed description: -----------------------------------------------------------------------------} constructor Tsource.create(AOwner: TComponent; aForm:TForm1; anumber:byte); const lamNM=633; var n:byte; procedure SetSettings(ed:TEdit; title,Einheit:string); begin //was ist es with Tlabel.Create(self) do begin Parent:=GroupBox; Left := 14; Top := n*24+4; Width := 77; caption:=title; end; //edit feld with ed do begin Parent:=GroupBox; //DisplayFormat := dfScientific; //DecimalPlaces := 3; //value := '0'; Text:='0'; Left := 96; Top := n*24+4; Width := 77; OnKeyDown:=@self.OnKeyDown; ShowHint:=true; end; //Einheit with Tlabel.Create(FForm) do begin Parent:=GroupBox; Left := ed.Left+ed.Width+1; Top := n*24+8; caption:=Einheit; end; inc(n); end; begin inherited; n:=1; lambdaMin:=380; lambdaMax:=779; Fnumber:=anumber; //groupbox GroupBox := TGroupBox.Create(FForm); with GroupBox do begin Parent := Form.PanelLambda; name:='GroupBoxSource_'+inttostr(anumber); Width := 276; Height := Form.GroupShowChart.Height; Left := 292; Top := Form.GroupShowChart.Top ; Anchors := [akLeft, akBottom]; Caption := 'Wellenlänge verändern'; end; EditLambda:=TEdit.Create(AOwner); SetSettings(EditLambda,'Wellenlänge','nm'); //EditLambda.DisplayFormat:=dfInteger; EditLambda.Hint:='Die Wellenlänge des Lichts'; EditLambda.Text:='630'; EditLambda.Name:='EditLambda_'+inttostr(anumber); EditLambda.OnChange:=@form.AllEditChange; EditFrequency:=TEdit.Create(AOwner); SetSettings(EditFrequency,'Frequenz','Hz'); EditFrequency.Hint:='Die Frequenz des Lichts'; EditFrequency.Text:='1E-14'; EditFrequency.Name:='EditFrequency_'+inttostr(anumber); EditFrequency.OnChange:=@form.AllEditChange; //Trackbar TrackBar := TTrackBar.Create(AOwner); with TrackBar do begin Name := self.ClassName+'TrackBar_'+inttostr(anumber); Parent := GroupBox; Left := 6; Top := 91; Width := GroupBox.Width-12; Height := 28; Max := lambdaMax; Min := lambdaMin; Frequency := 20; TickStyle:=tsNone; ScalePos:=trRight; position:=lamNM; OnChange := @TrackBarChange; end; with TLabel.Create(Self) do begin Parent := GroupBox; Left := 6; Top := 79; Width := 111; Height := 20; Caption := 'Wellenlänge'; end; Flambda:=lamNM *1E-9; //startwert property schreibt die anderen werte self.active:=false; end; {----------------------------------------------------------------------------- Description: Procedure: destroy Arguments: None Result: None Detailed description: brauche ich nicht, da EditLambda,EditFrequency,EditEnergy zu thisparent gehören, und deswegen anscheinend von Tform1 zerstört werden -----------------------------------------------------------------------------} destructor Tsource.destroy; begin GroupBox.Free; EditLambda.free; EditFrequency.free; TrackBar.Free; // EditEnergy.free; inherited destroy; end; {----------------------------------------------------------------------------- Description: Procedure: getactive Arguments: None Result: boolean Detailed description: -----------------------------------------------------------------------------} function Tsource.getactive:boolean; begin result:=Factive; // result:= self.GroupBox.Visible; if uanderes.boolUngleich(Factive,self.GroupBox.Visible) then ShowMessage('ungleich'); end; {----------------------------------------------------------------------------- Description: für property active Procedure: setactive Arguments: value:boolean Result: None Detailed description: -----------------------------------------------------------------------------} procedure Tsource.setactive(value:boolean); begin inherited setactive(value); self.GroupBox.Visible:=value; // self.GroupBox.BringToFront; end; {----------------------------------------------------------------------------- Procedure: OnKeyDown Arguments: Sender: TObject; var Key: Word; Shift: TShiftState Result: None Detailed description: -----------------------------------------------------------------------------} procedure Tsource.OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Self.EditLambda = sender then Form.OnChangeMakeAll(EditLambda, Key) else if Self.EditFrequency = sender then Form.OnChangeMakeAll(EditFrequency, Key); //if BeginEditKeyDown(TCustomEdit(sender), Key) then //exit; //if key = 13 then //begin //if BeginInputChange then //exit; //CalcOtherEdits(TEdit(sender)); //self.TrackBar.Position:=round(lambdaMax+lambdaMin-strtofloat(self.EditLambda.Text)); //EndInputChange; //end; end; {----------------------------------------------------------------------------- Description: Procedure: TrackBarChange Arguments: Sender: TObject Result: None Detailed description: -----------------------------------------------------------------------------} procedure Tsource.TrackBarChange(Sender: TObject); begin Form.OnChangeMakeAll(TrackBar); //Flambda:=self.TrackBar.position*1E-9; //WriteEdits; //with SaS.Screen[number] do //begin //MakeAllRightColor; //Form1.RelistSources; //with SaS.Screen[self.number] do //begin //Calc(SingleSlit.Visible, NSlit.Visible, CombiSlit.Visible, false); //if ImageIntensity.Visible then //SaS.CalcImageIntensity; //SaS.box.Update; //end; //// if ImageIntensity.Visible then //// SaS.Calc(false,false,false,true,Uimportant); //// Calc(SingleSlit.Visible,NSlit.Visible,CombiSlit.Visible,false,Uimportant); //end; end; {----------------------------------------------------------------------------- Description: Procedure: CalcOtherEdits Arguments: Source:TJvValidateEdit Result: None Detailed description: -----------------------------------------------------------------------------} procedure Tsource.CalcOtherEdits(Source:TCustomEdit); begin if Source= self.EditLambda then Flambda:=strtofloat(source.Text)*1E-9 else if Source= self.EditFrequency then frequency:=strtofloat(Source.Text)*1E-9; WriteEdits; end; {============================================================================== Procedure: WriteEdits Belongs to: Tsource Result: None Parameters: Description: ==============================================================================} procedure Tsource.WriteEdits; begin EditLambda.Text:= Formatfloat('###',lambda*1E9); EditFrequency.Text:= Formatfloat('###E-0',frequency); end; procedure Tsource.WriteEditsAndTrackbar; var bvorher:boolean; begin bvorher:=IsChangingInput; IsChangingInput:=true; // damit er nicht in onchynge make all geht WriteEdits; self.TrackBar.Position:=round(lambda*1E9); IsChangingInput:=bvorher; // damit er nicht in onchange make all geht end; {----------------------------------------------------------------------------- Description: Procedure: getspecifications Arguments: None Result: None Detailed description: -----------------------------------------------------------------------------} procedure Tsource.getspecifications; begin { frequency:=strtofloat(form1.EditFrequency.text); energy:=strtofloat(form1.Editenergy.text);} Flambda:=strtofloat(self.EditLambda.Text)*1E-9; end; {----------------------------------------------------------------------------- Description: Hier das wird ausgeführt wenn irgendeine set-Property aufgerufen wird, wegen bezug Procedure: setlambda Arguments: value:Double Result: None Detailed description: Hier aktualisiert er auch die sichtabren edits -----------------------------------------------------------------------------} procedure Tsource.setlambda(value:Double); begin Flambda:=value; WriteEditsAndTrackbar; with SaS.Screen[number] do begin MakeAllRightColor; Form1.RelistSources; //with SaS.Screen[self.number] do //// if SaS.DrawingEnabled then //Calc(SingleSlit.Visible, NSlit.Visible, CombiSlit.Visible, ImageIntensity.Visible); end; end; {----------------------------------------------------------------------------- Description: Procedure: getfrequency Arguments: None Result: Double Detailed description: lambda=c/f http://de.wikipedia.org/wiki/Wellenl%C3%A4nge also f=c/lambda -----------------------------------------------------------------------------} function Tsource.getfrequency:Double; begin result:=c/lambda; end; {----------------------------------------------------------------------------- Description: Procedure: setfrequency Arguments: value:Double Result: None Detailed description: lambda=c/f http://de.wikipedia.org/wiki/Wellenl%C3%A4nge -----------------------------------------------------------------------------} procedure Tsource.setfrequency(value:Double); begin lambda:=c/value; end; {----------------------------------------------------------------------------- Description: Procedure: getenergy Arguments: None Result: Double Detailed description: Da E=hf http://de.wikipedia.org/wiki/Plancksches_Wirkungsquantum -----------------------------------------------------------------------------} function Tsource.getenergy:Double; begin result:=h*frequency; end; {----------------------------------------------------------------------------- Description: Procedure: setenergy Arguments: value:Double Result: None Detailed description: Da E=hf http://de.wikipedia.org/wiki/Plancksches_Wirkungsquantum also f=E/h -----------------------------------------------------------------------------} procedure Tsource.setenergy(value:Double); begin frequency:=value/h; end; end.
unit tcpsocketclient; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TOnMessageReceived = procedure(Sender: TObject; messageReceived: string) of object; TOnBytesReceived = procedure(Sender: TObject; var jbytesReceived: TDynArrayOfJByte) of object; TOnSendFileProgress = procedure(Sender: TObject; fileName: string; sendFileSize: integer; fileSize: integer) of object; TOnSendFileFinished = procedure(Sender: TObject; fileName: string; fileSize: integer) of object; TOnGetFileProgress = procedure(Sender: TObject; fileName: string; remainingFileSize: integer; fileSize: integer) of object; TOnGetFileFinished = procedure(Sender: TObject; fileName: string; fileSize: integer) of object; TOnDisConnected=procedure(Sender:TObject) of object; TDataTransferMode = (dtmText, dtmByte, dtmFileGet, dtmFileSend); {Draft Component code by "Lazarus Android Module Wizard" [5/19/2015 18:49:35]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jTCPSocketClient = class(jControl) private FOnMessageReceived: TOnMessageReceived; FOnBytesReceived: TOnBytesReceived; FOnConnected: TOnNotify; FOnSendFileProgress: TOnSendFileProgress; FOnSendFileFinished: TOnSendFileFinished; FOnGetFileProgress: TOnGetFileProgress; FOnGetFileFinished: TOnGetFileFinished; FOnDisconnected: TOnDisConnected; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); function SendMessage(message: string): boolean; function SendFile(fullPath: string) : boolean; procedure SetSendFileProgressStep(_bytes: integer); function SetGetFile(fullPath: string; fileSize: integer) : boolean; function ConnectAsyncTimeOut(_serverIP: string; _serverPort: integer; _timeOut: integer): boolean; function ConnectAsync(_serverIP: string; _serverPort: integer): boolean; overload; function IsConnected(): boolean; procedure CloseConnection(); procedure SetTimeOut(_millisecondsTimeOut: integer); function SendBytes(var _jbyteArray: TDynArrayOfJByte; _writeLength: boolean): boolean; function SetDataTransferMode(_dataTransferMode: TDataTransferMode) : boolean; procedure GenEvent_OnTCPSocketClientMessagesReceived(Sender: TObject; messageReceived: string); procedure GenEvent_OnTCPSocketClientBytesReceived(Sender: TObject; var jbytesReceived: TDynArrayOfJByte); procedure GenEvent_OnTCPSocketClientConnected(Sender: TObject); procedure GenEvent_OnTCPSocketClientFileSendProgress(Sender: TObject; filename: string; sendFileSize: integer; filesize: integer); procedure GenEvent_pOnTCPSocketClientFileSendFinished(Sender: TObject; filename: string; filesize: integer); procedure GenEvent_OnTCPSocketClientFileGetProgress(Sender: TObject; filename: string; remainingFileSize: integer; filesize: integer); procedure GenEvent_pOnTCPSocketClientFileGetFinished(Sender: TObject; filename: string; filesize: integer); procedure GenEvent_OnTCPSocketClientDisConnected(Sender:TObject); published property OnMessagesReceived: TOnMessageReceived read FOnMessageReceived write FOnMessageReceived; property OnBytesReceived: TOnBytesReceived read FOnBytesReceived write FOnBytesReceived; property OnConnected: TOnNotify read FOnConnected write FOnConnected; property OnSendFileProgress: TOnSendFileProgress read FOnSendFileProgress write FOnSendFileProgress; property OnSendFileFinished: TOnSendFileFinished read FOnSendFileFinished write FOnSendFileFinished; property OnGetFileProgress: TOnGetFileProgress read FOnGetFileProgress write FOnGetFileProgress; property OnGetFileFinished: TOnGetFileFinished read FOnGetFileFinished write FOnGetFileFinished; property OnDisconnected: TOnDisconnected read FOnDisconnected write FOnDisconnected; end; function jTCPSocketClient_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; implementation {--------- jTCPSocketClient --------------} constructor jTCPSocketClient.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jTCPSocketClient.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jTCPSocketClient.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; FInitialized:= True; end; function jTCPSocketClient.jCreate(): jObject; begin Result:= jTCPSocketClient_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jTCPSocketClient.jFree(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'jFree'); end; function jTCPSocketClient.SendMessage(message: string) : boolean; begin //in designing component state: set value here... if FInitialized then Result:= jni_func_t_out_z(gApp.jni.jEnv, FjObject, 'SendMessage', message); end; function jTCPSocketClient.SendFile(fullPath: string) : boolean; begin //in designing component state: set value here... if FInitialized then Result := jni_func_t_out_z(gApp.jni.jEnv, FjObject, 'SendFile', fullPath); end; function jTCPSocketClient.SetGetFile(fullPath: string; fileSize: integer) : boolean; begin //in designing component state: set value here... if FInitialized then Result := jni_func_ti_out_z(gApp.jni.jEnv, FjObject, 'SetGetFile', fullPath, fileSize); end; procedure jTCPSocketClient.CloseConnection(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'CloseConnection'); end; function jTCPSocketClient.ConnectAsync(_serverIP: string; _serverPort: integer): boolean; overload; begin //in designing component state: result value here... if FInitialized then Result:= jni_func_ti_out_z(gApp.jni.jEnv, FjObject, 'Connect', _serverIP ,_serverPort); end; function jTCPSocketClient.ConnectAsyncTimeOut(_serverIP: string; _serverPort: integer; _timeOut: integer): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jni_func_tii_out_z(gApp.jni.jEnv, FjObject, 'Connect', _serverIP ,_serverPort ,_timeOut); end; function jTCPSocketClient.IsConnected(): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jni_func_out_z(gApp.jni.jEnv, FjObject, 'isConnected'); end; procedure jTCPSocketClient.SetSendFileProgressStep(_bytes: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'SetSendFileProgressStep', _bytes); end; procedure jTCPSocketClient.SetTimeOut(_millisecondsTimeOut: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_i(gApp.jni.jEnv, FjObject, 'SetTimeOut', _millisecondsTimeOut); end; function jTCPSocketClient.SendBytes(var _jbyteArray: TDynArrayOfJByte; _writeLength: boolean): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jni_func_dab_z_out_z(gApp.jni.jEnv, FjObject, 'SendBytes', _jbyteArray ,_writeLength); end; function jTCPSocketClient.SetDataTransferMode(_dataTransferMode: TDataTransferMode) : boolean; begin //in designing component state: set value here... if FInitialized then Result := jni_func_i_out_z(gApp.jni.jEnv, FjObject, 'SetDataTransferMode', Ord(_dataTransferMode)); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientMessagesReceived(Sender: TObject; messageReceived: string); begin if Assigned(FOnMessageReceived) then FOnMessageReceived(Sender, messageReceived); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientBytesReceived(Sender: TObject; var jbytesReceived: TDynArrayOfJByte); begin if Assigned(FOnBytesReceived) then FOnBytesReceived(Sender, jbytesReceived); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientConnected(Sender: TObject); begin if Assigned(FOnConnected) then FOnConnected(Sender); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientFileSendProgress(Sender: TObject; filename: string; sendFileSize: integer; filesize: integer); begin if Assigned(FOnSendFileProgress) then FOnSendFileProgress(Sender, filename, sendFileSize, filesize); end; procedure jTCPSocketClient.GenEvent_pOnTCPSocketClientFileSendFinished(Sender: TObject; filename: string; filesize: integer); begin if Assigned(FOnSendFileFinished) then FOnSendFileFinished(Sender, filename, filesize); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientFileGetProgress(Sender: TObject; filename: string; remainingFileSize: integer; filesize: integer); begin if Assigned(FOnGetFileProgress) then FOnGetFileProgress(Sender, filename, remainingFileSize, filesize); end; procedure jTCPSocketClient.GenEvent_pOnTCPSocketClientFileGetFinished(Sender: TObject; filename: string; filesize: integer); begin if Assigned(FOnGetFileFinished) then FOnGetFileFinished(Sender, filename, filesize); end; procedure jTCPSocketClient.GenEvent_OnTCPSocketClientDisConnected(Sender:TObject); begin if Assigned(FOnDisconnected) then FOnDisconnected(Sender); end; {-------- jTCPSocketClient_JNI_Bridge ----------} function jTCPSocketClient_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jTCPSocketClient_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; end.
unit unit_CadCurso; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ListBox, FMX.Controls.Presentation, FMX.Edit, Curso, System.Rtti, FMX.Grid.Style, FMX.ScrollBox, FMX.Grid, Utilitario; type TForm_CadCurso = class(TForm) edNome: TEdit; cbStatus: TComboBox; lbNome: TLabel; lbStatus: TLabel; sbtnNovo: TSpeedButton; sbtnSalvar: TSpeedButton; sbtnExcluir: TSpeedButton; sbtnBusca: TSpeedButton; Panel1: TPanel; gridMaterias: TStringGrid; Panel2: TPanel; sbtnAdcExclMateria: TSpeedButton; procedure sbtnBuscaClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure sbtnNovoClick(Sender: TObject); procedure sbtnSalvarClick(Sender: TObject); procedure sbtnExcluirClick(Sender: TObject); procedure sbtnAdcExclMateriaClick(Sender: TObject); private { Private declarations } procedure CaregaStringGrid(vCodCurso: Integer); public { Public declarations } end; var Form_CadCurso: TForm_CadCurso; vCurso: TCurso; vUtilitario : TUtilitario; implementation Uses Consulta, Unit_CadMateria; {$R *.fmx} procedure TForm_CadCurso.CaregaStringGrid(vCodCurso: Integer); var vConsulta : TConsulta; begin vConsulta := TConsulta.create; try gridMaterias.ClearColumns; vConsulta.setTextosql('select a.id_materia ''codigo'','#13+ ' b.nome ''nome'', '#13+ ' c.periodo ''periodo'' '#13+ 'from curso_materia a, materia b,'#13+ ' periodo c '#13+ 'where a.id_materia = b.id_materia '#13+ 'and b.id_periodo = c.id_periodo '#13+ 'and a.id_curso = ' + Format('%s', [vCurso.getCampoFromListaValores(0)])); vConsulta.getConsultaToSg(gridMaterias); vUtilitario.ajustaTamnhosg(gridMaterias); finally FreeAndNil(vConsulta); end; end; procedure TForm_CadCurso.FormCreate(Sender: TObject); begin vCurso := TCurso.Create('curso'); vCurso.estado := 0; end; procedure TForm_CadCurso.FormDestroy(Sender: TObject); begin FreeAndNil(vCurso); end; procedure TForm_CadCurso.sbtnAdcExclMateriaClick(Sender: TObject); var vForm_CadMateria : TForm_CadMateria; begin if (StrToInt(vCurso.getCampoFromListaValores(0)) <> 0) then begin vForm_CadMateria := TForm_CadMateria.Create(Self); try vForm_CadMateria.PID_Curso := StrToInt(vCurso.getCampoFromListaValores(0)); vForm_CadMateria.ShowModal; finally FreeAndNil(vForm_CadMateria); end; end else begin ShowMessage('Antes de inserir ou alterar alguma materia voce deve cadastrar ou'+ 'selecionar algum curso'); end; CaregaStringGrid(StrToInt(vCurso.getCampoFromListaValores(0))); end; procedure TForm_CadCurso.sbtnBuscaClick(Sender: TObject); var vConsulta : TConsulta; begin vConsulta := TConsulta.create; try vConsulta.setTitulo('Consulta Cursos'); vConsulta.setTextosql('Select id_curso ''C�digo'',' + 'Nome Nome, c.c.Ativo ''Cod Status'', IF(c.Ativo = 1, ''Ativo'', ''Inativo'')as ''Status'' '+ 'from curso c, periodo p '+ ' order by nome'); vConsulta.getConsulta; if (vConsulta.getRetorno <> '') then begin vCurso.select(0,vConsulta.getRetorno); if (vCurso.isExiteSlvalores) then begin edNome.Text := vCurso.getCampoFromListaValores(1); cbStatus.ItemIndex := StrToInt(vCurso.getCampoFromListaValores(2)) + 1; vCurso.estado := 1; end else begin vCurso.estado := 0; edNome.Text := ''; cbStatus.ItemIndex := -1; end; end; CaregaStringGrid(StrToInt(vCurso.getCampoFromListaValores(0))); finally FreeAndNil(vConsulta); end; end; procedure TForm_CadCurso.sbtnExcluirClick(Sender: TObject); var vConsulta : TConsulta; fExisteMateriaCadastrada : Boolean; begin if (vCurso.getEstado = 0) then exit else begin vConsulta := TConsulta.create; try vConsulta.setTextosql('select *'+ ' from curso_materia a'+ ' where a.ID_CURSO = '+ Format('%s', [vCurso.getCampoFromListaValores(0)]) ); vCadCurso_Materia.slCampos.Add('ID_CURSO_MATERIA'); vCadCurso_Materia.slCampos.Add('ID_CURSO'); vCadCurso_Materia.slCampos.Add('ID_MATERIA'); vConsulta.getConsultaDados(vCadCurso_Materia.slCampos); fExisteMateriaCadastrada := vConsulta.getfTemRegistroConsulta; if (not fExisteMateriaCadastrada) then begin vCurso.delete; vCurso.utilitario.LimpaTela(self); edNome.SetFocus; end else ShowMessage('Ante de excluir o curso, devese excluir todas as'+ ' Mat�rias deste curso'); finally FreeAndNil(vConsulta); end; end; end; procedure TForm_CadCurso.sbtnNovoClick(Sender: TObject); begin vCurso.utilitario.LimpaTela(self); edNome.SetFocus; vCurso.estado := 0; end; procedure TForm_CadCurso.sbtnSalvarClick(Sender: TObject); begin if (vCurso.getEstado = 1) then begin vCurso.slValores.Strings[1] := edNome.Text; vCurso.slValores.Strings[2] := IntToStr(cbStatus.ItemIndex - 1); end else begin vCurso.slValores.Clear; vCurso.slValores.Add('0'); vCurso.slValores.Add(edNome.Text); vCurso.slValores.Add(IntToStr(cbStatus.ItemIndex - 1)); end; vCurso.insert(vCurso.slValores); CaregaStringGrid(StrToInt(vCurso.getCampoFromListaValores(0))); vCurso.utilitario.LimpaTela(self); edNome.SetFocus; end; end.
// // Made from com.vk:android-sdk-core:3.5.1 // unit Alcinoe.AndroidApi.VKontakte; interface {$I Alcinoe.inc} {$IFNDEF ALCompilerVersionSupported} //Please run <Alcinoe>\Tools\NativeBridgeFileGenerator\NativeBridgeFileGeneratorAndroid.bat //with the library identifiers com.vk:android-sdk-core:xx.xx.xx where xx.xx.xx //is the last version of the VKontakte and gave also the path to //<Alcinoe>\Source\Alcinoe.AndroidApi.VKontakte.pas to build the compare source file. Then make a diff //compare between the new generated Alcinoe.AndroidApi.VKontakte.pas and this one to see if the api //signature is still the same {$MESSAGE WARN 'Check if the api signature of the last version of VKontakte sdk (android) is still the same'} {$ENDIF} uses Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.App, Androidapi.JNI.Os; type {******************} JUserId = interface; JVKAuthException = interface; JVKScope = interface; JVKAccessToken = interface; JVKAuthCallback = interface; JVK = interface; {****************************************} JUserIdClass = interface(JParcelableClass) ['{3F4AC4F7-0225-4A77-8EC7-7957BBAEB98E}'] end; [JavaSignature('com/vk/dto/common/id/UserId')] JUserId = interface(JParcelable) ['{CCE90A13-2538-4413-BD73-B27E5BAA4628}'] function toString: JString; cdecl; end; TJUserId = class(TJavaGenericImport<JUserIdClass, JUserId>) end; {************************************************} JVKAuthExceptionClass = interface(JExceptionClass) ['{D3099883-E9CD-4B17-BF67-931280B3C2D3}'] end; [JavaSignature('com/vk/api/sdk/exceptions/VKAuthException')] JVKAuthException = interface(JException) ['{356CB57F-3E2F-4F84-9767-CC7DA9E4CCB0}'] function getAuthError: JString; cdecl; function isCanceled: Boolean; cdecl; end; TJVKAuthException = class(TJavaGenericImport<JVKAuthExceptionClass, JVKAuthException>) end; {***********************************} JVKScopeClass = interface(JEnumClass) ['{6D299E22-9E66-4DD9-8556-17C7830134F6}'] {class} function _GetADS: JVKScope; cdecl; {class} function _GetAUDIO: JVKScope; cdecl; {class} function _GetDOCS: JVKScope; cdecl; {class} function _GetEMAIL: JVKScope; cdecl; {class} function _GetFRIENDS: JVKScope; cdecl; {class} function _GetGROUPS: JVKScope; cdecl; {class} function _GetMARKET: JVKScope; cdecl; {class} function _GetMESSAGES: JVKScope; cdecl; {class} function _GetNOTES: JVKScope; cdecl; {class} function _GetNOTIFICATIONS: JVKScope; cdecl; {class} function _GetNOTIFY: JVKScope; cdecl; {class} function _GetOFFLINE: JVKScope; cdecl; {class} function _GetPAGES: JVKScope; cdecl; {class} function _GetPHONE: JVKScope; cdecl; {class} function _GetPHOTOS: JVKScope; cdecl; {class} function _GetSTATS: JVKScope; cdecl; {class} function _GetSTATUS: JVKScope; cdecl; {class} function _GetSTORIES: JVKScope; cdecl; {class} function _GetVIDEO: JVKScope; cdecl; {class} function _GetWALL: JVKScope; cdecl; {class} function valueOf(name: JString): JVKScope; cdecl; {class} function values: TJavaObjectArray<JVKScope>; cdecl; {class} property ADS: JVKScope read _GetADS; {class} property AUDIO: JVKScope read _GetAUDIO; {class} property DOCS: JVKScope read _GetDOCS; {class} property EMAIL: JVKScope read _GetEMAIL; {class} property FRIENDS: JVKScope read _GetFRIENDS; {class} property GROUPS: JVKScope read _GetGROUPS; {class} property MARKET: JVKScope read _GetMARKET; {class} property MESSAGES: JVKScope read _GetMESSAGES; {class} property NOTES: JVKScope read _GetNOTES; {class} property NOTIFICATIONS: JVKScope read _GetNOTIFICATIONS; {class} property NOTIFY: JVKScope read _GetNOTIFY; {class} property OFFLINE: JVKScope read _GetOFFLINE; {class} property PAGES: JVKScope read _GetPAGES; {class} property PHONE: JVKScope read _GetPHONE; {class} property PHOTOS: JVKScope read _GetPHOTOS; {class} property STATS: JVKScope read _GetSTATS; {class} property STATUS: JVKScope read _GetSTATUS; {class} property STORIES: JVKScope read _GetSTORIES; {class} property VIDEO: JVKScope read _GetVIDEO; {class} property WALL: JVKScope read _GetWALL; end; [JavaSignature('com/vk/api/sdk/auth/VKScope')] JVKScope = interface(JEnum) ['{2596E59E-D2E5-457F-B3EE-CA7ADD5FD1C2}'] end; TJVKScope = class(TJavaGenericImport<JVKScopeClass, JVKScope>) end; {*******************************************} JVKAccessTokenClass = interface(JObjectClass) ['{4AA5D139-70EF-4BED-AFCE-6AD11B109F57}'] end; [JavaSignature('com/vk/api/sdk/auth/VKAccessToken')] JVKAccessToken = interface(JObject) ['{B7E0A898-D133-4A4B-A74E-F192D64E28DA}'] function getAccessToken: JString; cdecl; function getCreated: Int64; cdecl; function getEmail: JString; cdecl; function getPhone: JString; cdecl; function getPhoneAccessKey: JString; cdecl; function getSecret: JString; cdecl; function getUserId: JUserId; cdecl; function isValid: Boolean; cdecl; end; TJVKAccessToken = class(TJavaGenericImport<JVKAccessTokenClass, JVKAccessToken>) end; {******************************************} JVKAuthCallbackClass = interface(IJavaClass) ['{85991DF5-2CD9-46BD-B3BC-41373EA0850F}'] end; [JavaSignature('com/vk/api/sdk/auth/VKAuthCallback')] JVKAuthCallback = interface(IJavaInstance) ['{682834EF-3C5A-40DA-AD7D-30DE4015C2B5}'] procedure onLogin(token: JVKAccessToken); cdecl; procedure onLoginFailed(authException: JVKAuthException); cdecl; end; TJVKAuthCallback = class(TJavaGenericImport<JVKAuthCallbackClass, JVKAuthCallback>) end; {********************************} JVKClass = interface(JObjectClass) ['{0450DCD7-E946-43D6-801E-9DAC255B6052}'] {class} function getUserId: JUserId; cdecl; {class} procedure initialize(context: JContext); cdecl; {class} procedure login(activity: JActivity); cdecl; overload; {class} procedure login(activity: JActivity; scopes: JCollection); cdecl; overload; {class} procedure logout; cdecl; {class} function onActivityResult(requestCode: Integer; resultCode: Integer; data: JIntent; callback: JVKAuthCallback): Boolean; cdecl; end; [JavaSignature('com/vk/api/sdk/VK')] JVK = interface(JObject) ['{CBA5C3FA-9F3B-467C-A3D5-0F21093F2CFB}'] end; TJVK = class(TJavaGenericImport<JVKClass, JVK>) end; implementation {**********************} procedure RegisterTypes; begin TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JUserId', TypeInfo(Alcinoe.AndroidApi.VKontakte.JUserId)); TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JVKAuthException', TypeInfo(Alcinoe.AndroidApi.VKontakte.JVKAuthException)); TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JVKScope', TypeInfo(Alcinoe.AndroidApi.VKontakte.JVKScope)); TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JVKAccessToken', TypeInfo(Alcinoe.AndroidApi.VKontakte.JVKAccessToken)); TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JVKAuthCallback', TypeInfo(Alcinoe.AndroidApi.VKontakte.JVKAuthCallback)); TRegTypes.RegisterType('Alcinoe.AndroidApi.VKontakte.JVK', TypeInfo(Alcinoe.AndroidApi.VKontakte.JVK)); end; initialization RegisterTypes; end.
unit fmain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, IdHL7, IdTCPConnection; type { TForm1 } TForm1 = class(TForm) btnStart: TButton; btnListen: TButton; edtServerPort: TEdit; edtServer: TEdit; edtPort: TEdit; idHl7Client: TIdHL7; idHl7Server: TIdHL7; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; memClient: TMemo; memClientReplyText: TMemo; memGeneral: TMemo; memServerReply: TMemo; memServer: TMemo; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; procedure btnListenClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormCreate(Sender: TObject); procedure idHl7ClientConnCountChange(ASender: TIdHL7; AConnCount: integer); procedure idHl7ClientConnect(Sender: TObject); procedure idHl7ClientDisconnect(Sender: TObject); procedure idHl7ClientReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean); procedure idHl7ServerConnCountChange(ASender: TIdHL7; AConnCount: integer); procedure idHl7ServerConnect(Sender: TObject); procedure idHl7ServerDisconnect(Sender: TObject); procedure idHl7ServerReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean); procedure Panel3Click(Sender: TObject); protected procedure hl7ServerReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string); procedure hl7ServerMsgArrive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string); procedure hl7clientReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string); private procedure clientSend(); public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btnStartClick(Sender: TObject); begin if idHl7Client.Status = isConnected then begin idHl7Client.Stop; end; idHl7Client.Port := StrToInt(edtPort.Text); idHl7Client.Address := edtServer.Text; clientSend; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin if idHl7Client.Status = isConnected then begin idHl7Client.Stop; end; end; procedure TForm1.FormCreate(Sender: TObject); begin idHl7Server.OnReceiveMessage := @hl7ServerReceive; idHl7Server.OnMessageArrive := @hl7ServerMsgArrive; idHl7Client.OnReceiveMessage:= @hl7clientReceive; end; procedure TForm1.idHl7ClientConnCountChange(ASender: TIdHL7; AConnCount: integer); begin memGeneral.Lines.add('clientcon_count change : '); end; procedure TForm1.idHl7ClientConnect(Sender: TObject); begin memGeneral.Lines.add('clientconnect : '); end; procedure TForm1.idHl7ClientDisconnect(Sender: TObject); begin memGeneral.Lines.add('clientdisconenct : '); end; procedure TForm1.idHl7ClientReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean); begin memGeneral.Lines.add('clientrcverr : ' + AException.Message); VDropConnection := True; end; procedure TForm1.idHl7ServerConnCountChange(ASender: TIdHL7; AConnCount: integer); begin memGeneral.Lines.add('servercon_count change : '); end; procedure TForm1.idHl7ServerConnect(Sender: TObject); begin memGeneral.Lines.add('serverconnect : '); end; procedure TForm1.idHl7ServerDisconnect(Sender: TObject); begin memGeneral.Lines.add('serverdisconenct : '); end; procedure TForm1.idHl7ServerReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean); begin memGeneral.Lines.add('servrcverr : ' + AException.Message); VDropConnection := True; end; procedure TForm1.Panel3Click(Sender: TObject); begin end; procedure TForm1.hl7ServerReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string); begin vReply := memServerReply.Lines.Text; memServer.lines.text := Amsg; vhandled := True; memGeneral.Lines.add('servreceived '+AMsg+ '- reply provided '+vReply); end; procedure TForm1.hl7ServerMsgArrive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string); begin memGeneral.Lines.add('servmsgarrive : ' + AMsg); memServer.lines.add(amsg); idHl7Server.AsynchronousSend(memServerReply.Lines.text,AConnection); end; procedure TForm1.hl7clientReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string); begin memClientReplyText.lines.text := Amsg; vhandled := True; memGeneral.Lines.add('clreceived '+AMsg); end; procedure TForm1.clientSend; var iX: integer; sAnt: string; // vR : TSendResponse; vMsg : IInterface; begin if idHl7Client.Status <> isConnected then begin idHl7Client.Start; idHl7Client.WaitForConnection(10000); end; idHl7Client.SendMessage(memClient.Lines.Text); iX := 0; while (iX < 10) do begin Inc(iX); sleep(10); Application.ProcessMessages; (*vR*)vMsg := idHl7Client.GetMessage(sAnt); if vMsg <> nil (*vR = srOK*) then begin memClientReplyText.Lines.text := 'success : '+sAnt; break (* end else if vR = srError then begin memClientReplyText.Lines.text := 'error : '+sAnt; break; end else if vR = srTimeout then begin memClientReplyText.Lines.text := 'timeout waiting for reply '; break;*) end; end; // memClientReplyText.Lines.Text := sAnt; end; procedure TForm1.btnListenClick(Sender: TObject); begin if btnListen.Tag = 0 then begin idHl7Server.Port := StrToInt(edtServerPort.Text); idHl7Server.Start; btnListen.Tag := 1; btnListen.Caption := 'Stop'; end else begin if idHl7Server.Status = isConnected then begin idHl7Server.Stop; end; btnListen.Caption := 'Start'; btnListen.Tag := 0; end; end; end.
unit TestUnsedUses; interface uses TestFramework, FindUnit.UnusedUses, FindUnit.Utils, Interf.EnvironmentController, System.Classes, System.SysUtils; type TTestEnv = class(TInterfacedObject, IRFUEnvironmentController) function GetFullMatch(const SearchString: string): TStringList; function AreDependenciasReady: Boolean; procedure ForceRunDependencies; function PasExists(PasName: string): Boolean; end; TestTUnsedUsesProcessor = class(TTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure TestProcess; procedure TestRegularBase; end; implementation procedure TestTUnsedUsesProcessor.SetUp; begin end; procedure TestTUnsedUsesProcessor.TearDown; begin end; procedure TestTUnsedUsesProcessor.TestProcess; var EnvControl: IRFUEnvironmentController; ReturnValue: string; UsesUnit: string; ReturnInfo: TUsesUnit; IsResultOk: Boolean; Path: string; UnsedUsesProcessor: TUnsedUsesProcessor; begin Path := ExtractFilePath(ParamStr(0)); Path := Fetch(Path, '\Test\'); UnsedUsesProcessor := TUnsedUsesProcessor.Create(Path + '\Test\TestUnusedUses\FindUnit.FileCache.pas'); try EnvControl := TTestEnv.Create; UnsedUsesProcessor.SetEnvControl(EnvControl); UnsedUsesProcessor.Process; UsesUnit := 'Winapi.UI.Xaml'; UsesUnit := UsesUnit.ToUpper; if not UnsedUsesProcessor.UnusedUses.TryGetValue(UsesUnit, ReturnInfo) then Assert(false, 'Result not found'); IsResultOk := (ReturnInfo.Line = 12) and (ReturnInfo.Collumn = 3) and (ReturnInfo.Name.Equals('Winapi.UI.Xaml')); Assert(IsResultOk, 'Result is not correct'); finally UnsedUsesProcessor.Free; UnsedUsesProcessor := nil; end; end; procedure TestTUnsedUsesProcessor.TestRegularBase; var EnvControl: IRFUEnvironmentController; Path: string; UnsedUsesProcessor: TUnsedUsesProcessor; begin Path := ExtractFilePath(ParamStr(0)); Path := Fetch(Path, '\Test\'); UnsedUsesProcessor := TUnsedUsesProcessor.Create(Path + '\Test\TestUnusedUses\BaseUnusedUnitsSetAllUse.pas'); try EnvControl := TTestEnv.Create; UnsedUsesProcessor.SetEnvControl(EnvControl); UnsedUsesProcessor.Process; Assert(UnsedUsesProcessor.UsesStartLine = 5, 'Wrong start uses line'); Assert(UnsedUsesProcessor.UnusedUses.Count = 0, 'All the units must be marked as found'); finally UnsedUsesProcessor.Free; UnsedUsesProcessor := nil; end; end; { TTestEnv } function TTestEnv.AreDependenciasReady: Boolean; begin Result := True; end; procedure TTestEnv.ForceRunDependencies; begin end; function TTestEnv.GetFullMatch(const SearchString: string): TStringList; begin Result := TStringList.Create; if SearchString = '' then Exit else if SearchString.ToUpper = 'REVERSESTRING' then begin Result.Add('OWideSupp.OReverseString - Function'); Result.Add('System.AnsiStrings.AnsiReverseString - Function'); Result.Add('System.AnsiStrings.ReverseString - Function'); Result.Add('System.StrUtils.AnsiReverseString - Function'); Result.Add('System.StrUtils.ReverseString - Function'); end else if SearchString.ToUpper = 'TLIST' then begin Result.Add('Spring.Collections.Lists.TList.* - Class'); Result.Add('System.Classes.TList.* - Class'); Result.Add('System.Classes.TList.* - Interface'); Result.Add('System.Classes.TList.Error - Class produre - Class Procedure'); Result.Add('System.Generics.Collections.TList.* - Class'); Result.Add('System.Generics.Collections.TList.Error - Class produre - Class Procedure'); end else if SearchString.ToUpper = 'TDICTIONARY' then begin Result.Add('EClasses.TDictionary.* - Class'); Result.Add('OXmlRTTISerialize.TSerializableObjectDictionary.* - Class'); Result.Add('Spring.Collections.Dictionaries.TDictionary.* - Class'); Result.Add('System.Generics.Collections.TDictionary.* - Class'); Result.Add('System.Generics.Collections.TObjectDictionary.* - Class'); Result.Add('Winapi.AspTlb.IRequestDictionary.* - Interface'); Result.Add('Winapi.AspTlb.IVariantDictionary.* - Interface'); end else if SearchString.ToUpper = 'FORMAT' then begin Result.Add('System.AnsiStrings.FormatBuf - Function'); Result.Add('System.JSON.Types.TJsonDateFormatHandling.FormatSettings - Enum item'); Result.Add('System.MaskUtils.FormatMaskText - Function'); Result.Add('System.SysUtils.Format - Function'); Result.Add('System.SysUtils.FormatBuf - Function'); Result.Add('System.SysUtils.FormatCurr - Function'); Result.Add('System.SysUtils.FormatDateTime - Function'); Result.Add('System.SysUtils.FormatFloat - Function'); Result.Add('System.SysUtils.FormatSettings - Variable'); Result.Add('Winapi.DirectShow9.FORMAT_AnalogVideo - Constant'); Result.Add('Winapi.DirectShow9.FORMAT_DolbyAC3 - Constant'); end else if SearchString.ToUpper = 'TRECT' then begin Result.Add('FMX.Ani.TRectAnimation.* - Class'); Result.Add('FMX.InertialMovement.TRectD - Record'); Result.Add('FMX.Objects.TRectangle.* - Class'); Result.Add('FMX.Objects3D.TRectangle3D.* - Class'); Result.Add('FmxAnimationEditors.TRectAnimationProperty.* - Class'); Result.Add('FmxAnimationEditors.TRectAnimationPropertyName.* - Class'); Result.Add('System.Types.TRect - Record'); Result.Add('System.Types.TRectF - Record'); end else begin Result.Add('FindUnit.FileCache.TUnitsController - Class'); Result.Add('FindUnit.PasParser.TPasFile - Class'); Result.Add('System.Classes.TStringList - Class'); Result.Add('System.SyncObjs.TCriticalSection - Class'); Result.Add('System.TObject - Class'); Result.Add('EClasses.TDictionary - Class'); Result.Add('Spring.Collections.Dictionaries.TDictionary - Class'); Result.Add('System.Generics.Collections.TDictionary - Class'); end; end; function TTestEnv.PasExists(PasName: string): Boolean; begin end; initialization // Register any test cases with the test runner RegisterTest(TestTUnsedUsesProcessor.Suite); end.
unit formMergeMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.ToolWin, Vcl.ComCtrls, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.StdActns, Vcl.Menus; type TfrmMergeMain = class(TForm) Panel1: TPanel; Panel2: TPanel; GroupBox2: TGroupBox; Splitter1: TSplitter; FileOpenDialog1: TFileOpenDialog; edtMSSQLDatabase: TEdit; Panel3: TPanel; btnMerge: TButton; ProgressBar1: TProgressBar; ProgressBar2: TProgressBar; ProgressBar3: TProgressBar; ProgressBar4: TProgressBar; ProgressBar5: TProgressBar; ProgressBar6: TProgressBar; Panel4: TPanel; GroupBox1: TGroupBox; sbInterBase: TSpeedButton; edtIBDatabase: TEdit; MainMenu1: TMainMenu; ActionList1: TActionList; FileExit1: TFileExit; Exit1: TMenuItem; File1: TMenuItem; edtMSSQLServer: TEdit; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } Controller : TComponent; public { Public declarations } end; var frmMergeMain: TfrmMergeMain; implementation {$R *.dfm} uses formMergeMainController; procedure TfrmMergeMain.FormCreate(Sender: TObject); begin inherited; Controller := TMergeMainController.Create(Self, Self); end; procedure TfrmMergeMain.FormDestroy(Sender: TObject); begin Controller.Free; end; end.
unit dtdbcoordedit; {$MODE Delphi} interface uses LCLIntf, LCLType, LMessages, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MaskEdit, DB, DBCtrls; type TCoordKind = (ckLatitude, ckLongitude); { TDtDBCoordEdit } TDtDBCoordEdit = class(TDBEdit) private FCoordKind: TCoordKind; FDataLink: TFieldDataLink; procedure DataChange(Sender: TObject); procedure SetCoordKind(AValue: TCoordKind); procedure UpdateControlState(ValueState: boolean); procedure UpdateData(Sender: TObject); procedure UpdateDisplayText(const NewText: string); protected procedure KeyDown(var Key: word; Shift: TShiftState); override; procedure KeyPress(var Key: char); override; property CustomEditMask; property EditMask; //events public constructor Create(AOwner: TComponent); override; published property CoordKind: TCoordKind read FCoordKind write SetCoordKind; end; procedure Register; implementation procedure Register; begin RegisterComponents('Mis Componentes', [TDtDBCoordEdit]); end; procedure TDtDBCoordEdit.DataChange(Sender: TObject); begin inherited; end; procedure TDtDBCoordEdit.SetCoordKind(AValue: TCoordKind); begin if FCoordKind=AValue then Exit; FCoordKind:=AValue; end; procedure TDtDBCoordEdit.UpdateControlState(ValueState: boolean); begin end; procedure TDtDBCoordEdit.UpdateData(Sender: TObject); var s: string; begin if (Trim(Text) = '') then FDataLink.Field.Value := Null else begin //Completo con ceros si por si lo dejó en blanco Text := StringReplace(Text, ' ', '0', [rfReplaceAll]); ValidateEdit; FDataLink.Field.AsFloat := StrToFloat(Text); end; end; procedure TDtDBCoordEdit.UpdateDisplayText(const NewText: string); begin inherited; end; procedure TDtDBCoordEdit.KeyDown(var Key: word; Shift: TShiftState); begin if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) then begin FDataLink.Edit; if Key = VK_DELETE then begin FDatalink.Field.Value := Null; Key := VK_UNKNOWN; end; end; inherited KeyDown(Key, Shift); end; procedure TDtDBCoordEdit.KeyPress(var Key: char); var ss: integer; begin // inherited KeyPress(Key); if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin Beep; Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; //#27: //begin // FDataLink.Reset; // SelectAll; // Key := #0; //end; end; ss := selstart; if ss <= 7 then sellength := 1; if ss = 0 then begin if not (key in ['0'..'9']) then key := #0; end else if ss = 1 then begin if not ((EditText[1] in ['0'..'8']) and (key in ['0'..'9'])) and not ((EditText[1] = '9') and (key in ['0'])) then key := #0; end else if ss = 2 then begin if not (key in ['0'..'5']) then key := #0; end else if ss = 3 then begin if not (key in ['0'..'9']) then key := #0; end else if ss = 4 then begin if not (key in [',','.']) then key := '.'; end else if ss = 5 then begin if not (key in ['0'..'9']) then key := #0; end else if ss = 6 then begin if not (key in ['0'..'9']) then key := #0; end else if ss >= 8 then begin key := #0; end; if key <> #0 then inherited else Beep; end; constructor TDtDBCoordEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink := TFieldDataLink(Perform(CM_GETDATALINK, 0, 0)); FDataLink.OnUpdateData := UpdateData; CustomEditMask := True; FCoordKind:=ckLatitude; EditMask := '####.##;1;_'; end; end.
unit XPipePrp; interface uses Classes, DsgnIntf, XLnkPipe, XDBTFC; type { TXControlPipeLinkProperty } TXControlPipeLinkProperty = class(TComponentProperty) public function GetXPipeLinks: TXPipeLinks; procedure GetValues(Proc: TGetStrProc); override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TPipeControlEditor } TPipeControlEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; { TXPipeSourcesProperty } TXPipeSourcesProperty = class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure Edit; override; end; { TXPipeLinksProperty } TXPipeLinksProperty = class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure Edit; override; end; procedure SwapPipeLinks(AComponent: TDBFormControl; ADesigner: TFormDesigner); implementation uses TypInfo, SysUtils, Controls, LnkSet, DiDual, Forms, XMisc, ColnEdit, Consts, XReports; function EditPipeSources(AComponent: TPipeControl; AList: TStringList; ADesigner: TFormDesigner): Boolean; var Form: TEtvDualListDlg; i, j: Integer; L1: TXPipeSources; Priz: Boolean; Src: TXPipeSourceItem; Comp: TPipeControl; S: String; begin Result := False; Form := TEtvDualListDlg.Create(Application); try with Form do begin Form.Caption := 'LinkSources selector'; SrcLabel.Caption := 'Selected LinkSources'; DstLabel.Caption := 'All LinkSources'; L1:= AComponent.Sources; { SrcList.Items.Assign(L1);} SrcList.Clear; DstList.Clear; for i:=0 to L1.Count-1 do if Assigned(L1[i].Source) then SrcList.Items.Add(L1[i].Source.Name); for i:=0 to AList.Count-1 do begin Priz:=True; for j:=0 to L1.Count-1 do if AnsiCompareText(AList[i], L1[j].Source.Name)=0 then begin Priz:=False; Break; end; if Priz then begin DstList.Items.Add(AList[i]); end; end; end; Result := (Form.ShowModal = mrOk); if Result then begin Comp:=AComponent; i:=0; While i<Comp.Sources.Count do begin Priz:=True; for j:=0 to Form.SrcList.Items.Count-1 do if AnsiCompareText(Comp.Sources[i].Source.Name, Form.SrcList.Items[j])=0 then begin Priz:=False; Break; end; if Priz then begin Comp.Sources[i].Free end else Inc(i); end; for i:=0 to Form.SrcList.Items.Count-1 do begin if Comp.Sources.IndexOfLinkName(Form.SrcList.Items[i])=-1 then begin Src:= Comp.Sources.Add; Src.Source:=TLinkSource(ADesigner.GetComponent(Form.SrcList.Items[i])); end; end; end; finally Form.Free; end; end; function EditPipeLinks(AComponent: TDBFormControl; AList: TStringList; ADesigner: TFormDesigner): Boolean; var Form: TEtvDualListDlg; i, j: Integer; L1: TXPipeLinks; Priz: Boolean; Src: TXPipeLinkItem; Comp: TDBFormControl; S: String; begin Result := False; Form := TEtvDualListDlg.Create(Application); try with Form do begin Form.Caption := 'PipeControls selector'; SrcLabel.Caption := 'Selected PipeControls'; DstLabel.Caption := 'All PipeControls'; L1:= AComponent.PipeLinks; { SrcList.Items.Assign(L1);} SrcList.Clear; DstList.Clear; for i:=0 to L1.Count-1 do if Assigned(L1[i].PipeLink) then SrcList.Items.Add(L1[i].PipeLink.Name); for i:=0 to AList.Count-1 do begin Priz:=True; for j:=0 to L1.Count-1 do if AnsiCompareText(AList[i], L1[j].PipeLink.Name)=0 then begin Priz:=False; Break; end; if Priz then begin DstList.Items.Add(AList[i]); end; end; end; Result := (Form.ShowModal = mrOk); if Result then begin Comp:=AComponent; i:=0; While i<Comp.PipeLinks.Count do begin Priz:=True; for j:=0 to Form.SrcList.Items.Count-1 do if AnsiCompareText(Comp.PipeLinks[i].PipeLink.Name, Form.SrcList.Items[j])=0 then begin Priz:=False; Break; end; if Priz then begin Comp.PipeLinks[i].Free end else Inc(i); end; for i:=0 to Form.SrcList.Items.Count-1 do begin if Comp.PipeLinks.IndexOfLinkName(Form.SrcList.Items[i])=-1 then begin Src:= Comp.PipeLinks.Add; Src.PipeLink:=TPipeControl(ADesigner.GetComponent(Form.SrcList.Items[i])); end; end; end; finally Form.Free; end; end; procedure GetClassLinks(ADesigner: TFormDesigner; Proc: TGetStrProc; AClass: TClass); var P: PTypeData; begin New(P); P^.ClassType:= AClass; ADesigner.GetComponentNames(P, Proc); Dispose(P); end; procedure SwapPipeSources(AComponent: TPipeControl; ADesigner: TFormDesigner); type TGetStrFunc = function(const Value: string): Integer of object; var Values: TStringList; AddValue: TGetStrFunc; begin Values := TStringList.Create; Values.Sorted := True; try AddValue := Values.Add; GetClassLinks(ADesigner, TGetStrProc(AddValue), TLinkSource); if EditPipeSources(AComponent, Values, ADesigner) then ADesigner.Modified; finally Values.Free; end; end; procedure SwapPipeLinks(AComponent: TDBFormControl; ADesigner: TFormDesigner); type TGetStrFunc = function(const Value: string): Integer of object; var Values: TStringList; AddValue: TGetStrFunc; begin Values := TStringList.Create; Values.Sorted := True; try AddValue := Values.Add; GetClassLinks(ADesigner, TGetStrProc(AddValue), TPipeControl); if EditPipeLinks(AComponent, Values, ADesigner) then ADesigner.Modified; finally Values.Free; end; end; { TPipeControlEditor } procedure TPipeControlEditor.ExecuteVerb(Index: Integer); begin Case Index of 0: ShowCollectionEditorClass(Designer, TCollectionEditor, Component, TPipeControl(Component).FieldMaps, 'FieldMaps'); 1: ShowCollectionEditorClass(Designer, TCollectionEditor, Component, TPipeControl(Component).DataMaps, 'DataMaps'); 2: ShowCollectionEditorClass(Designer, TCollectionEditor, Component, TPipeControl(Component).Pipes, 'Pipes'); 3: SwapPipeSources(TPipeControl(Component), Designer); end; end; function TPipeControlEditor.GetVerb(Index: Integer): string; begin Case Index of 0: Result:= 'FieldMaps editor'; 1: Result:= 'DataMaps editor'; 2: Result:= 'Pipes editor'; 3: Result:= 'Add/Del Sources'; end; end; function TPipeControlEditor.GetVerbCount: Integer; begin Result := 4 end; { TXPipeSourcesProperty } function TXPipeSourcesProperty.GetAttributes: TPropertyAttributes; begin Result:= [paReadOnly, paDialog]; end; function TXPipeSourcesProperty.GetValue: string; begin if TCollection(GetOrdValue).Count>0 then if TCollection(GetOrdValue).Count=1 then FmtStr(Result, '(%s)', ['One source']) else FmtStr(Result, '(%s)', ['Some sources']) else FmtStr(Result, '(%s)', ['Not sources']); end; procedure TXPipeSourcesProperty.Edit; begin SwapPipeSources(TPipeControl(GetComponent(0)), Designer); end; { TXPipeLinksProperty } function TXPipeLinksProperty.GetAttributes: TPropertyAttributes; begin Result:= [paReadOnly, paDialog]; end; function TXPipeLinksProperty.GetValue: string; begin if TCollection(GetOrdValue).Count>0 then if TCollection(GetOrdValue).Count=1 then FmtStr(Result, '(%s)', ['One link']) else FmtStr(Result, '(%s)', ['Some links']) else FmtStr(Result, '(%s)', ['Not links']); end; procedure TXPipeLinksProperty.Edit; begin SwapPipeLinks(TDBFormControl(GetComponent(0)), Designer); end; { TXControlPipeLinkProperty } function TXControlpipeLinkProperty.GetXPipeLinks: TXPipeLinks; var Comp: TPersistent; begin Comp:= GetComponent(0); Result:=TXReportItem(Comp).DBControl.PipeLinks; end; function TXControlPipeLinkProperty.GetValue: string; begin if TComponent(GetOrdValue)<>Nil then Result:= TComponent(GetOrdValue).Name else Result:= Inherited GetValue; end; procedure TXControlPipeLinkProperty.SetValue(const Value: string); var ALinks: TXPipeLinks; i: Integer; begin if Value<>'' then begin ALinks:= GetXPipeLinks; for i:=0 to ALinks.Count-1 do if ALinks[i].PipeLink is TPipeControl then if ALinks[i].PipeLink.Name = Value then begin Inherited SetValue(Value); exit; end; raise EPropertyError.Create(SInvalidPropertyValue); end; Inherited SetValue(Value); end; procedure TXControlPipeLinkProperty.GetValues(Proc: TGetStrProc); var ALinks: TXPipeLinks; i: Integer; begin ALinks:= GetXPipeLinks; for i:=0 to ALinks.Count-1 do if ALinks[i].PipeLink is TPipeControl then Proc(ALinks[i].PipeLink.Name); end; end.
unit SalePromoGoodsDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDialog, Vcl.ActnList, dsdAction, System.DateUtils, cxClasses, cxPropertiesStore, dsdAddOn, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxTextEdit, Vcl.ExtCtrls, dsdGuides, dsdDB, cxMaskEdit, cxButtonEdit, AncestorBase, dxSkinsCore, dxSkinsDefaultPainters, Data.DB, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, Datasnap.DBClient, cxGridLevel, cxGridCustomView, cxGrid, cxCurrencyEdit, dxSkinsdxBarPainter, dxBar, cxSpinEdit, dxBarExtItems, cxBarEditItem, cxBlobEdit, cxCheckBox, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, System.Actions, dxDateRanges; type TSalePromoGoodsDialogForm = class(TAncestorBaseForm) BankPOSTerminalGrid: TcxGrid; BankPOSTerminalGridDBTableView: TcxGridDBTableView; BankPOSTerminalGridLevel: TcxGridLevel; SalePromoGoodsDialoglDS: TDataSource; GoodsPresentName: TcxGridDBColumn; Panel1: TPanel; bbCancel: TcxButton; bbOk: TcxButton; GoodsPresentCode: TcxGridDBColumn; PriceSale: TcxGridDBColumn; AmountSale: TcxGridDBColumn; Remains: TcxGridDBColumn; procedure BankPOSTerminalGridDBTableViewDblClick(Sender: TObject); private { Private declarations } public end; function SalePromoGoodsDialogExecute(ADS : TClientDataSet) : boolean; implementation {$R *.dfm} uses LocalWorkUnit, CommonData; function SalePromoGoodsDialogExecute(ADS : TClientDataSet) : boolean; var SalePromoGoodsDialogForm : TSalePromoGoodsDialogForm; begin Result := False; if ADS.IsEmpty then Exit; SalePromoGoodsDialogForm := TSalePromoGoodsDialogForm.Create(Application); With SalePromoGoodsDialogForm do try try SalePromoGoodsDialoglDS.DataSet := ADS; while True do if ShowModal = mrOK then begin Result := True; Break; end else if ADS.FieldByName('isDiscountInformation').AsBoolean then Break else ShowMessage('Акционный товар надо выбрать.');; Except ON E: Exception DO MessageDlg(E.Message,mtError,[mbOk],0); end; finally SalePromoGoodsDialogForm.Free; end; end; procedure TSalePromoGoodsDialogForm.BankPOSTerminalGridDBTableViewDblClick( Sender: TObject); begin inherited; ModalResult := mrOk; end; End.
unit deleteProduct; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, DB, pngimage, ExtCtrls; type TfrmDeleteProduct = class(TForm) Label1: TLabel; Label5: TLabel; Label2: TLabel; Button1: TButton; Label7: TLabel; Label6: TLabel; Label4: TLabel; lblCost: TLabel; lblSell: TLabel; lblStock: TLabel; Label3: TLabel; Label8: TLabel; btnDelete: TButton; BitBtn1: TBitBtn; DataSource1: TDataSource; edtName: TComboBox; Image1: TImage; procedure btnDeleteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } function findName: Boolean; procedure fill(); procedure display(); end; var frmDeleteProduct: TfrmDeleteProduct; implementation uses data, confirmDeleteProduct; {$R *.dfm} function TfrmDeleteProduct.findName; var name : String; found : Boolean; SearchOptions : TLocateOptions; number: Integer; begin number := edtName.ItemIndex; name := edtName.Items[number]; SearchOptions := [loCaseInsensitive]; found := DataModule2.tbProduct.Locate('Names', name, SearchOptions); findName := found; end; procedure TfrmDeleteProduct.FormCreate(Sender: TObject); begin fill(); end; procedure TfrmDeleteProduct.fill; begin DataModule2.tbProduct.First; while not(DataModule2.tbProduct.Eof) and (DataModule2.tbProductActive.Value = true) do begin edtName.Items.Add(DataModule2.tbProductNames.Value); DataModule2.tbProduct.Next; end; end; procedure TfrmDeleteProduct.btnDeleteClick(Sender: TObject); begin if MessageDlg('Are you sure you want to delete this product?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin DataModule2.tbProduct.Delete; DataModule2.connect; MessageDlg('The product has successfully been deleted.', mtInformation, [mbOk], 0); edtName.Clear; fill; end; end; procedure TfrmDeleteProduct.Button1Click(Sender: TObject); begin if findName then display(); end; procedure TfrmDeleteProduct.display; begin lblCost.Caption := FloatToStr(DataModule2.tbProductCost.Value); lblSell.Caption := FloatToStr(DataModule2.tbProductPrice.Value); lblStock.Caption := IntToStr(DataModule2.tbProductStock.Value); btnDelete.Enabled := true; ShowMessage('Press the Delete Product button to delete this product.'); end; end.
unit WorldGenBigTree_u; interface uses WorldGenerator_u, generation, RandomMCT; type WorldGenBigTree=class(WorldGenerator) private otherCoordPairs:array[0..5] of byte; rand1:rnd; basePos:array[0..2] of byte; heightLimit,height,trunkSize,heightLimitLimit,leafDistanceLimit:integer; leafNodes:array of ar_int; heightAttenuation,field_875_h,field_874_i,field_873_j, field_872_k:double; public constructor Create; destructor Destroy; procedure generateLeafNodeList(xreg,yreg:integer; map:region); procedure func_523_a(xreg,yreg:integer; map:region; i,j,k:integer; f:double; byte0,l:integer); function func_528_a(i:integer):double; function func_526_b(i:integer):double; procedure generateLeafNode(xreg,yreg:integer; map:region; i,j,k:integer); procedure placeBlockLine(xreg,yreg:integer; map:region; ai,ai1:array of integer; i:integer); procedure generateLeaves(xreg,yreg:integer; map:region); function leafNodeNeedsBase(i:integer):boolean; procedure generateTrunk(xreg,yreg:integer; map:region); procedure generateLeafNodeBases(xreg,yreg:integer; map:region); function checkBlockLine(xreg,yreg:integer; map:region; ai,ai1:array of integer):integer; function validTreeLocation(xreg,yreg:integer; map:region):boolean; procedure func_517_a(d,d1,d2:double); override; function generate(xreg,yreg:integer; map:region; rand:rnd; i,j,k:integer):boolean; override; end; implementation uses Math, MathHelper_u; constructor WorldGenBigTree.Create; begin rand1:=rnd.create; heightLimit:=0; heightAttenuation:=0.61799999999999999; field_875_h:=1; field_874_i:=0.38100000000000001; field_873_j:=1; field_872_k:=1; trunkSize:=1; heightLimitLimit:=12; leafDistanceLimit:=4; otherCoordPairs[0]:=2; otherCoordPairs[1]:=0; otherCoordPairs[2]:=0; otherCoordPairs[3]:=1; otherCoordPairs[4]:=2; otherCoordPairs[5]:=1; basePos[0]:=0; basePos[1]:=0; basePos[2]:=0; end; destructor WorldGenBigTree.Destroy; var i:integer; begin for i:=0 to length(leafNodes)-1 do setlength(leafNodes[i],0); setlength(leafNodes,0); rand1.Free; inherited; end; procedure WorldGenBigTree.generateLeafNodeList(xreg,yreg:integer; map:region); var i,t,t1,j,k,l,i1,j1,k1,l1:integer; f,d,d1,d2,d3,d4:double; ai:array of ar_int; ai1,ai2,ai3:array[0..2] of integer; begin height:=trunc(heightLimit * heightAttenuation); if (height >= heightLimit)then height:=heightLimit - 1; i:=trunc(1.3819999999999999 + power((field_872_k * heightLimit) / 13, 2)); if (i < 1) then i:=1; setlength(ai,i * heightLimit); for t:=0 to length(ai)-1 do setlength(ai[t],4); j:=(basePos[1] + heightLimit) - leafDistanceLimit; k:=1; l:=basePos[1] + height; i1:=j - basePos[1]; ai[0][0]:=basePos[0]; ai[0][1]:=j; ai[0][2]:=basePos[2]; ai[0][3]:=l; dec(j); while (i1 >= 0) do begin j1:=0; f:=func_528_a(i1); if (f < 0) then begin dec(j); dec(i1); end else begin d:=0.5; while j1<i do begin d1:=field_873_j * (f * (rand1.nextFloat() + 0.32800000000000001)); d2:=rand1.nextFloat() * 2 * 3.1415899999999999; k1:=MathHelper_u.floor_double(d1 * sin(d2) + basePos[0] + d); l1:=MathHelper_u.floor_double(d1 * cos(d2) + basePos[2] + d); ai1[0]:=k1; ai1[1]:=j; ai1[2]:=l1; ai2[0]:=k1; ai2[1]:=j + leafDistanceLimit; ai2[2]:=l1; if (checkBlockLine(xreg,yreg,map,ai1, ai2) <> -1) then begin inc(j1); continue; end; for t:=0 to 2 do ai3[t]:=basePos[t]; d3:=sqrt(power(abs(basePos[0] - ai1[0]), 2) + power(abs(basePos[2] - ai1[2]), 2)); d4:=d3 * field_874_i; if (ai1[1] - d4 > l)then ai3[1]:=l else ai3[1]:=trunc(ai1[1] - d4); if (checkBlockLine(xreg,yreg,map,ai3, ai1) = -1)then begin ai[k][0]:=k1; ai[k][1]:=j; ai[k][2]:=l1; ai[k][3]:=ai3[1]; inc(k); end; inc(j1); end; dec(j); dec(i1); end; end; setlength(leafNodes,k); for t:=0 to length(leafNodes)-1 do setlength(leafNodes[t],4); for t:=0 to k-1 do for t1:=0 to 3 do leafNodes[t][t1]:=ai[t][t1]; for t:=0 to length(ai)-1 do setlength(ai[t],0); setlength(ai,0); end; procedure WorldGenBigTree.func_523_a(xreg,yreg:integer; map:region; i,j,k:integer; f:double; byte0,l:integer); var i1,byte1,byte2,j1,k1,l1,i2:integer; d:double; ai,ai1:array[0..2] of integer; begin i1:=trunc(f + 0.61799999999999999); byte1:=otherCoordPairs[byte0]; byte2:=otherCoordPairs[byte0 + 3]; ai[0]:=i; ai[1]:=j; ai[2]:=k; ai1[0]:=0; ai1[1]:=0; ai1[2]:=0; j1:=-i1; k1:=-i1; ai1[byte0]:=ai[byte0]; while j1<=i1 do begin ai1[byte1]:=ai[byte1] + j1; l1:=-i1; while l1<=i1 do begin d:=sqrt(power(abs(j1) + 0.5, 2) + power(abs(l1) + 0.5, 2)); if (d > f) then inc(l1) else begin ai1[byte2]:=ai[byte2] + l1; i2:=get_block_id(map,xreg,yreg,ai1[0], ai1[1], ai1[2]); if (i2 <> 0)and(i2 <> 18)then inc(l1) else begin set_block_id_data(map,xreg,yreg,ai1[0], ai1[1], ai1[2], l, 0); inc(l1); end; end; end; inc(j1); end; end; function WorldGenBigTree.func_528_a(i:integer):double; var f,f1,f2:double; begin if (i < heightLimit * 0.29999999999999999)then begin result:=-1.618; exit; end; f:=heightLimit / 2; f1:=heightLimit / 2 - i; if (f1 = 0)then f2:=f else if (abs(f1) >= f)then f2:=0 else f2:=sqrt(power(abs(f), 2) - power(abs(f1), 2)); f2:=f2*0.5; result:=f2; end; function WorldGenBigTree.func_526_b(i:integer):double; begin if (i < 0)or(i >= leafDistanceLimit)then begin result:=-1; exit; end; if (i <> 0)and(i <> leafDistanceLimit - 1)then result:=3 else result:=2; end; procedure WorldGenBigTree.generateLeafNode(xreg,yreg:integer; map:region; i,j,k:integer); var l,i1:integer; f:double; begin //l:=j; //for i1:=j+leafDistanceLimit to i1-1 do i1:=j + leafDistanceLimit; for l:=j to i1-1 do begin f:=func_526_b(l - j); func_523_a(xreg,yreg,map,i, l, k, f, 1, 18); end; end; procedure WorldGenBigTree.placeBlockLine(xreg,yreg:integer; map:region; ai,ai1:array of integer; i:integer); var ai2,ai3:array[0..2] of integer; byte0,j,byte1,byte2,byte3,k,l:integer; d,d1:double; begin ai2[0]:=0; ai2[1]:=0; ai2[2]:=0; byte0:=0; j:=0; while byte0<3 do begin ai2[byte0]:=ai1[byte0] - ai[byte0]; if (abs(ai2[byte0]) > abs(ai2[j]))then j:=byte0; inc(byte0); end; if (ai2[j] = 0) then exit; byte1:=otherCoordPairs[j]; byte2:=otherCoordPairs[j + 3]; if (ai2[j] > 0) then byte3:=1 else byte3:=-1; d:=ai2[byte1] / ai2[j]; d1:=ai2[byte2] / ai2[j]; ai3[0]:=0; ai3[1]:=0; ai3[2]:=0; k:=0; l:=ai2[j] + byte3; while k<>l do begin ai3[j]:=MathHelper_u.floor_double((ai[j] + k) + 0.5); ai3[byte1]:=MathHelper_u.floor_double(ai[byte1] + k * d + 0.5); ai3[byte2]:=MathHelper_u.floor_double(ai[byte2] + k * d1 + 0.5); set_block_id_data(map,xreg,yreg,ai3[0], ai3[1], ai3[2], i, 0); inc(k,byte3); end; end; procedure WorldGenBigTree.generateLeaves(xreg,yreg:integer; map:region); var i,j,k,l,i1:integer; begin i:=0; j:=length(leafNodes); while i<j do begin k:=leafNodes[i][0]; l:=leafNodes[i][1]; i1:=leafNodes[i][2]; generateLeafNode(xreg,yreg,map,k, l, i1); inc(i); end; end; function WorldGenBigTree.leafNodeNeedsBase(i:integer):boolean; begin //return (double)i >= (double)heightLimit * 0.20000000000000001D; result:=i >= heightLimit * 0.20000000000000001; end; procedure WorldGenBigTree.generateTrunk(xreg,yreg:integer; map:region); var i,j,k,l:integer; ai,ai1:array[0..2]of integer; begin i:=basePos[0]; j:=basePos[1]; k:=basePos[1] + height; l:=basePos[2]; ai[0]:=i; ai[1]:=j; ai[2]:=l; ai1[0]:=i; ai1[1]:=k; ai1[2]:=l; placeBlockLine(xreg,yreg,map,ai, ai1, 17); if (trunkSize = 2)then begin inc(ai[0]); inc(ai1[0]); placeBlockLine(xreg,yreg,map,ai, ai1, 17); inc(ai[2]); inc(ai1[2]); placeBlockLine(xreg,yreg,map,ai, ai1, 17); dec(ai[0]); dec(ai1[0]); placeBlockLine(xreg,yreg,map,ai, ai1, 17); end; end; procedure WorldGenBigTree.generateLeafNodeBases(xreg,yreg:integer; map:region); var i,j,k:integer; ai,ai2:array[0..2]of integer; ai1:array[0..3]of integer; begin i:=0; j:=length(leafNodes); ai[0]:=basePos[0]; ai[1]:=basePos[1]; ai[2]:=basePos[2]; while i<j do begin ai1[0]:=leafNodes[i][0]; ai1[1]:=leafNodes[i][1]; ai1[2]:=leafNodes[i][2]; ai1[3]:=leafNodes[i][3]; ai2[0]:=ai1[0]; ai2[1]:=ai1[1]; ai2[2]:=ai1[2]; ai[1]:=ai1[3]; k:=ai[1] - basePos[1]; if (leafNodeNeedsBase(k))then placeBlockLine(xreg,yreg,map,ai, ai2, 17); inc(i); end; end; function WorldGenBigTree.checkBlockLine(xreg,yreg:integer; map:region; ai,ai1:array of integer):integer; var ai2,ai3:array[0..2]of integer; byte0,i,byte1,byte2,byte3,j,k,l:integer; d,d1:double; begin ai2[0]:=0; ai2[1]:=0; ai2[2]:=0; byte0:=0; i:=0; while byte0<3 do begin ai2[byte0]:=ai1[byte0] - ai[byte0]; if (abs(ai2[byte0]) > abs(ai2[i]))then i:=byte0; inc(byte0); end; if (ai2[i] = 0)then begin result:=-1; exit; end; byte1:=otherCoordPairs[i]; byte2:=otherCoordPairs[i + 3]; if (ai2[i] > 0) then byte3:=1 else byte3:=-1; d:=ai2[byte1] / ai2[i]; d1:=ai2[byte2] / ai2[i]; ai3[0]:=0; ai3[1]:=0; ai3[2]:=0; j:=0; k:=ai2[i] + byte3; repeat if (j = k) then break; ai3[i]:=ai[i] + j; ai3[byte1]:=MathHelper_u.floor_double(ai[byte1] + j * d); ai3[byte2]:=MathHelper_u.floor_double(ai[byte2] + j * d1); l:=get_block_id(map,xreg,yreg,ai3[0], ai3[1], ai3[2]); if (l <> 0)and(l <> 18)then break; inc(j,byte3); until false; if (j = k)then result:=-1 else result:=abs(j); end; function WorldGenBigTree.validTreeLocation(xreg,yreg:integer; map:region):boolean; var ai,ai1:array[0..2]of integer; i,j:integer; begin ai[0]:=basePos[0]; ai[1]:=basePos[1]; ai[2]:=basePos[2]; ai1[0]:=basePos[0]; ai1[1]:=(basePos[1] + heightLimit) - 1; ai1[2]:=basePos[2]; i:=get_block_id(map,xreg,yreg,basePos[0], basePos[1] - 1, basePos[2]); if (i <> 2)and(i <> 3) then begin result:=false; exit; end; j:=checkBlockLine(xreg,yreg,map,ai, ai1); if (j = -1)then begin result:=true; exit; end; if (j < 6) then result:=false else begin heightLimit:=j; result:=true; end; end; procedure WorldGenBigTree.func_517_a(d,d1,d2:double); begin heightLimitLimit:=trunc(d * 12); if (d > 0.5)then leafDistanceLimit:=5; field_873_j:=d1; field_872_k:=d2; end; function WorldGenBigTree.generate(xreg,yreg:integer; map:region; rand:rnd; i,j,k:integer):boolean; var l:int64; begin l:=rand.nextLong(); rand1.setSeed(l); basePos[0]:=i; basePos[1]:=j; basePos[2]:=k; if (heightLimit = 0) then heightLimit:=5 + rand1.nextInt(heightLimitLimit); if (not(validTreeLocation(xreg,yreg,map)))then result:=false else begin generateLeafNodeList(xreg,yreg,map); generateLeaves(xreg,yreg,map); generateTrunk(xreg,yreg,map); generateLeafNodeBases(xreg,yreg,map); result:=true; end; end; end.
unit ClassForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public procedure Show(const msg: string); end; var Form1: TForm1; implementation {$R *.fmx} uses DateUtils; { Public = fields/methods can be accessed from anywhere else in program Protected = limited visibility so that they can only be accessed from current or derived classes Private = cannot be accessed from any class in another unit (but can from other classe within the same unit) Use 'strict private' to protect from other classes in the same unit } type TDate = class private FDate: TDateTime; public procedure SetValue(M, D, Y: Integer); function LeapYear: Boolean; function GetText: string; procedure Increase; end; { TDate } function TDate.GetText: string; begin Result := DateToStr(FDate); end; procedure TDate.Increase; var OldDate: TDateTime; begin OldDate := FDate; FDate := FDate + 1; Form1.Show('Date increased from ' + DateToStr(OldDate) + ' to ' + GetText); end; function TDate.LeapYear: Boolean; begin Result := IsLeapYear(YearOf(FDate)); end; procedure TDate.SetValue(M, D, Y: Integer); begin FDate := EncodeDate(Y, M, D); end; procedure TForm1.Button1Click(Sender: TObject); var ADay: TDate; begin // Create ADay := TDate.Create; // Use ADay.SetValue(1, 1, 2020); ADay.Increase; if ADay.LeapYear then Show('Leap year: ' + ADay.GetText); // Free the memory (for non ARC platforms) ADay.Free; end; procedure TForm1.Show(const Msg: string); begin Memo1.Lines.Add(Msg); end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_cast; interface // Headers for OpenSSL 1.1.1 // cast.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts; const CAST_ENCRYPT_CONST = 1; CAST_DECRYPT_CONST = 0; CAST_BLOCK = 8; CAST_KEY_LENGTH = 16; type CAST_LONG = type TIdC_UINT; PCAST_LONG = ^CAST_LONG; cast_key_st = record data: array of CAST_LONG; short_key: TIdC_INT; //* Use reduced rounds for short key */ end; CAST_KEY = cast_key_st; PCAST_KEY = ^CAST_KEY; var procedure CAST_set_key(key: PCast_Key; len: TIdC_INT; const data: PByte); procedure CAST_ecb_encrypt(const in_: PByte; out_: PByte; const key: PCast_Key; enc: TIdC_INT); procedure CAST_encrypt(data: PCAST_LONG; const key: PCast_Key); procedure CAST_decrypt(data: PCAST_LONG; const key: PCast_Key); procedure CAST_cbc_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; const ks: PCast_Key; iv: PByte; enc: TIdC_INT); procedure CAST_cfb64_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; const schedule: PCast_Key; ivec: PByte; num: PIdC_INT; enc: TIdC_INT); procedure CAST_ofb64_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; const schedule: PCast_Key; ivec: PByte; num: PIdC_INT); implementation end.
{==============================================================================} { } { OpenGL Video Renderer Helpful Functions } { Version 1.0 } { Date : 2010-07-10 } { } {==============================================================================} { } { Copyright (C) 2010 Torsten Spaete } { All Rights Reserved } { } { Uses DSPack (MPL 1.1) from } { http://progdigy.com } { } {==============================================================================} { The contents of this file are used with permission, 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/MPL-1.1.html } { } { 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. } {==============================================================================} { History : } { Version 1.0 Initial Release } {==============================================================================} unit OVRUtils; interface uses Windows; {$include OpenGLVideoRenderer_compilerflags.inc} procedure WriteTrace(_Line : WideString); function SubTypeToString(AGuid : TGUID) : String; function MGuidToString(_GUID : TGUID) : String; function FGuidToString(_GUID : TGUID) : String; function SGuidToString(_GUID : TGUID) : String; function NonPowerOfTwo(AWidth, AHeight, AMax : Integer) : TRect; implementation uses // Delphi Messages, SysUtils, // 3rd party DirectShow9; function SubTypeToString(AGuid : TGUID) : String; begin if IsEqualGuid(AGuid, MEDIASUBTYPE_RGB24) then Result := 'RGB24' else if IsEqualGuid(AGuid, MEDIASUBTYPE_RGB32) then Result := 'RGB32' else if IsEqualGuid(AGuid, MEDIASUBTYPE_RGB555) then Result := 'RGB555' else if IsEqualGuid(AGuid, MEDIASUBTYPE_RGB565) then Result := 'RGB565' else if IsEqualGuid(AGuid, MEDIASUBTYPE_YUYV) then Result := 'YUYV' else if IsEqualGuid(AGuid, MEDIASUBTYPE_UYVY) then Result := 'UYVY' else if IsEqualGuid(AGuid, MEDIASUBTYPE_YUY2) then Result := 'YUY2' else if IsEqualGuid(AGuid, MEDIASUBTYPE_YV12) then Result := 'YV12' else if IsEqualGuid(AGuid, MEDIASUBTYPE_YVYU) then Result := 'YVYU' else Result := 'UNKNOWN'; end; function SGuidToString(_GUID : TGUID) : String; begin if IsEqualGuid(_GUID, MEDIASUBTYPE_CLPL) then Result := 'MEDIASUBTYPE_CLPL' else if IsEqualGuid(_GUID, MEDIASUBTYPE_YUYV) then Result := 'MEDIASUBTYPE_YUYV' else if IsEqualGuid(_GUID, MEDIASUBTYPE_IYUV) then Result := 'MEDIASUBTYPE_IYUV' else if IsEqualGuid(_GUID, MEDIASUBTYPE_YVU9) then Result := 'MEDIASUBTYPE_YVU9' else if IsEqualGuid(_GUID, MEDIASUBTYPE_Y411) then Result := 'MEDIASUBTYPE_Y411' else if IsEqualGuid(_GUID, MEDIASUBTYPE_Y41P) then Result := 'MEDIASUBTYPE_Y41P' else if IsEqualGuid(_GUID, MEDIASUBTYPE_YUY2) then Result := 'MEDIASUBTYPE_YUY2' else if IsEqualGuid(_GUID, MEDIASUBTYPE_YVYU) then Result := 'MEDIASUBTYPE_YVYU' else if IsEqualGuid(_GUID, MEDIASUBTYPE_UYVY) then Result := 'MEDIASUBTYPE_UYVY' else if IsEqualGuid(_GUID, MEDIASUBTYPE_Y211) then Result := 'MEDIASUBTYPE_Y211' else if IsEqualGuid(_GUID, MEDIASUBTYPE_CLJR) then Result := 'MEDIASUBTYPE_CLJR' else if IsEqualGuid(_GUID, MEDIASUBTYPE_IF09) then Result := 'MEDIASUBTYPE_IF09' else if IsEqualGuid(_GUID, MEDIASUBTYPE_CPLA) then Result := 'MEDIASUBTYPE_CPLA' else if IsEqualGuid(_GUID, MEDIASUBTYPE_MJPG) then Result := 'MEDIASUBTYPE_MJPG' else if IsEqualGuid(_GUID, MEDIASUBTYPE_TVMJ) then Result := 'MEDIASUBTYPE_TVMJ' else if IsEqualGuid(_GUID, MEDIASUBTYPE_WAKE) then Result := 'MEDIASUBTYPE_WAKE' else if IsEqualGuid(_GUID, MEDIASUBTYPE_CFCC) then Result := 'MEDIASUBTYPE_CFCC' else if IsEqualGuid(_GUID, MEDIASUBTYPE_IJPG) then Result := 'MEDIASUBTYPE_IJPG' else if IsEqualGuid(_GUID, MEDIASUBTYPE_Plum) then Result := 'MEDIASUBTYPE_Plum' else if IsEqualGuid(_GUID, MEDIASUBTYPE_DVCS) then Result := 'MEDIASUBTYPE_DVCS' else if IsEqualGuid(_GUID, MEDIASUBTYPE_DVSD) then Result := 'MEDIASUBTYPE_DVSD' else if IsEqualGuid(_GUID, MEDIASUBTYPE_MDVF) then Result := 'MEDIASUBTYPE_MDVF' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB1) then Result := 'MEDIASUBTYPE_RGB1' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB4) then Result := 'MEDIASUBTYPE_RGB4' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB8) then Result := 'MEDIASUBTYPE_RGB8' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB565) then Result := 'MEDIASUBTYPE_RGB565' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB555) then Result := 'MEDIASUBTYPE_RGB555' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB24) then Result := 'MEDIASUBTYPE_RGB24' else if IsEqualGuid(_GUID, MEDIASUBTYPE_RGB32) then Result := 'MEDIASUBTYPE_RGB32' else if IsEqualGuid(_GUID, MEDIASUBTYPE_ARGB1555) then Result := 'MEDIASUBTYPE_ARGB1555' else if IsEqualGuid(_GUID, MEDIASUBTYPE_ARGB4444) then Result := 'MEDIASUBTYPE_ARGB4444' else if IsEqualGuid(_GUID, MEDIASUBTYPE_ARGB32) then Result := 'MEDIASUBTYPE_ARGB32' else if IsEqualGuid(_GUID, MEDIASUBTYPE_A2R10G10B10) then Result := 'MEDIASUBTYPE_A2R10G10B10' else if IsEqualGuid(_GUID, MEDIASUBTYPE_A2B10G10R10) then Result := 'MEDIASUBTYPE_A2B10G10R10' else if IsEqualGuid(_GUID, MEDIASUBTYPE_AYUV) then Result := 'MEDIASUBTYPE_AYUV' else if IsEqualGuid(_GUID, MEDIASUBTYPE_AI44) then Result := 'MEDIASUBTYPE_AI44' else if IsEqualGuid(_GUID, MEDIASUBTYPE_IA44) then Result := 'MEDIASUBTYPE_IA44' else if IsEqualGuid(_GUID, MEDIASUBTYPE_YV12) then Result := 'MEDIASUBTYPE_YV12' else Result := GUIDToString(_GUID); end; function FGuidToString(_GUID : TGUID) : String; begin if IsEqualGuid(_GUID, FORMAT_VideoInfo) then Result := 'FORMAT_VideoInfo' else if IsEqualGuid(_GUID, FORMAT_VideoInfo2) then Result := 'FORMAT_VideoInfo2' else if IsEqualGuid(_GUID, FORMAT_MPEGVideo) then Result := 'FORMAT_MPEGVideo' else if IsEqualGuid(_GUID, FORMAT_MPEG2VIDEO) then Result := 'FORMAT_MPEG2VIDEO' else if IsEqualGuid(_GUID, FORMAT_MPEGStreams) then Result := 'FORMAT_MPEGStreams' else if IsEqualGuid(_GUID, FORMAT_DvInfo) then Result := 'FORMAT_DvInfo' else if IsEqualGuid(_GUID, FORMAT_AnalogVideo) then Result := 'FORMAT_AnalogVideo' else if IsEqualGuid(_GUID, FORMAT_DolbyAC3) then Result := 'FORMAT_DolbyAC3' else if IsEqualGuid(_GUID, FORMAT_MPEG2Audio) then Result := 'FORMAT_MPEG2Audio' else if IsEqualGuid(_GUID, FORMAT_DVD_LPCMAudio) then Result := 'FORMAT_DVD_LPCMAudio' else if IsEqualGuid(_GUID, FORMAT_WaveFormatEx) then Result := 'FORMAT_WaveFormatEx' else if IsEqualGuid(_GUID, FORMAT_None) then Result := 'FORMAT_None' else Result := GUIDToString(_GUID); end; function MGuidToString(_GUID : TGUID) : String; begin if IsEqualGuid(_GUID, MEDIATYPE_NULL) then Result := 'MEDIATYPE_NULL' else if IsEqualGuid(_GUID, MEDIATYPE_Video) then Result := 'MEDIATYPE_Video' else if IsEqualGuid(_GUID, MEDIATYPE_Audio) then Result := 'MEDIATYPE_Audio' else if IsEqualGuid(_GUID, MEDIATYPE_Text) then Result := 'MEDIATYPE_Text' else if IsEqualGuid(_GUID, MEDIATYPE_Midi) then Result := 'MEDIATYPE_Midi' else if IsEqualGuid(_GUID, MEDIATYPE_Stream) then Result := 'MEDIATYPE_Stream' else if IsEqualGuid(_GUID, MEDIATYPE_Interleaved) then Result := 'MEDIATYPE_Interleaved' else if IsEqualGuid(_GUID, MEDIATYPE_File) then Result := 'MEDIATYPE_File' else if IsEqualGuid(_GUID, MEDIATYPE_ScriptCommand) then Result := 'MEDIATYPE_ScriptCommand' else if IsEqualGuid(_GUID, MEDIATYPE_AUXLine21Data) then Result := 'MEDIATYPE_AUXLine21Data' else if IsEqualGuid(_GUID, MEDIATYPE_VBI) then Result := 'MEDIATYPE_VBI' else if IsEqualGuid(_GUID, MEDIATYPE_Timecode) then Result := 'MEDIATYPE_Timecode' else if IsEqualGuid(_GUID, MEDIATYPE_LMRT) then Result := 'MEDIATYPE_LMRT' else if IsEqualGuid(_GUID, MEDIATYPE_URL_STREAM) then Result := 'MEDIATYPE_URL_STREAM' else if IsEqualGuid(_GUID, MEDIATYPE_MPEG1SystemStream) then Result := 'MEDIATYPE_MPEG1SystemStream' else if IsEqualGuid(_GUID, MEDIATYPE_AnalogAudio) then Result := 'MEDIATYPE_AnalogAudio' else if IsEqualGuid(_GUID, MEDIATYPE_AnalogVideo) then Result := 'MEDIATYPE_AnalogVideo' else if IsEqualGuid(_GUID, MEDIATYPE_MPEG2_PACK) then Result := 'MEDIATYPE_MPEG2_PACK' else if IsEqualGuid(_GUID, MEDIATYPE_MPEG2_PES) then Result := 'MEDIATYPE_MPEG2_PES' else if IsEqualGuid(_GUID, MEDIATYPE_CONTROL) then Result := 'MEDIATYPE_CONTROL' else if IsEqualGuid(_GUID, MEDIATYPE_MPEG2_SECTIONS) then Result := 'MEDIATYPE_MPEG2_SECTIONS' else if IsEqualGuid(_GUID, MEDIATYPE_DVD_ENCRYPTED_PACK) then Result := 'MEDIATYPE_DVD_ENCRYPTED_PACK' else if IsEqualGuid(_GUID, MEDIATYPE_DVD_NAVIGATION) then Result := 'MEDIATYPE_DVD_NAVIGATION' else Result := GUIDToString(_GUID); end; // returns number of characters in a string excluding the null terminator function StrLenW(Str: PWideChar): Cardinal; asm MOV EDX, EDI MOV EDI, EAX MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW MOV EAX, 0FFFFFFFEH SUB EAX, ECX MOV EDI, EDX end; {$ifdef EnableXenorateTrace} procedure WriteTrace(_Line : WideString); const TrennZeichen: WideString = '<[XTR]>'; var Parameter: WideString; MyCopyDataStruct: TCopyDataStruct; tracewnd: HWND; begin tracewnd := FindWindowW(nil, 'Xenorate Trace'); if tracewnd <> 0 then begin Parameter := FormatDateTime('yyyy-mm-dd hh:mm:ss:zzz',Now) + TrennZeichen + '5' + TrennZeichen + 'OpenGLVideoRenderer - ' + _Line + #0; // fill the TCopyDataStruct structure with data to send // TCopyDataStruct mit den Sende-Daten Infos ausfüllen with MyCopyDataStruct do begin dwData := 0; // may use a value do identify content of message cbData := (StrLenW(PWideChar(Parameter))*2)+2; //Need to transfer terminating #0 as well lpData := Pointer(PWideChar(Parameter)); end; SendMessageW(tracewnd, WM_COPYDATA, Longint(tracewnd), Longint(@MyCopyDataStruct)); end; end; {$else} procedure WriteTrace(_Line : WideString); begin end; {$endif} function GetNonPowerOfTwo(AValue, AMax : Integer) : Integer; begin Result := 2; while (Result < AValue) and (Result < AMax) do Result := Result * 2; end; function NonPowerOfTwo(AWidth, AHeight, AMax : Integer) : TRect; begin Result.Left := 0; Result.Top := 0; Result.Right := GetNonPowerOfTwo(AWidth, AMax); Result.Bottom := GetNonPowerOfTwo(AHeight, AMax); end; end.
unit log; interface uses System.SysUtils, System.SyncObjs; procedure ConsoleWrite(value: String); procedure ConsoleWriteLn(value: String = ''); var logcliticalsection: TCriticalSection; implementation procedure ConsoleWrite(value: String); begin logcliticalsection.Enter; Write(value); logcliticalsection.Leave; end; procedure ConsoleWriteLn(value: String); begin logcliticalsection.Enter; WriteLn(value); logcliticalsection.Leave; end; initialization logcliticalsection := TCriticalSection.Create; finalization FreeAndNil(logcliticalsection); end.
unit PLabelCombox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel, LookupControls; type TPLabelCombox = class(TCustomControl) private FComboBox: TComboBox; FLabel: TRxLabel; FLabelStyle: TLabelStyle; FParentFont: Boolean; protected function GetCaption:TCaption; function GetComboBoxWidth:integer; function GetComboClick:TNotifyEvent; function GetComboCtl3D:Boolean; function GetComboDblClick:TNotifyEvent; function GetComboDrawItem: TDrawItemEvent; function GetComboDropDown: TNotifyEvent; function GetComboDropDownCount:Integer; function GetComboDroppedDown: Boolean; function GetComboExit:TNotifyEvent; function GetComboEnter:TNotifyEvent; function GetComboItemHeight:Integer; function GetComboItemIndex: Integer; function GetComboItems:TStrings; function GetComboKeyDown:TKeyEvent ; function GetComboKeyPress:TKeyPressEvent; function GetComboKeyUp:TKeyEvent; function GetComboMaxLength:Integer; function GetComboMeasureItem: TMeasureItemEvent; function GetComboOnChange:TNotifyEvent; function GetComboSelLength: Integer; function GetComboSelStart: Integer; function GetComboSelText: string; function GetComboShowHint:Boolean; function GetComboSorted:Boolean; function GetComboStyle:TComboBoxStyle; function GetComboTabOrder:TTabOrder; function GetComboTabStop:Boolean; function GetComboText:TCaption; function GetFont:TFont; function GetLabelFont: TFont; procedure Paint;override; procedure SetCaption(Value: TCaption); procedure SetComboBoxWidth(Value: integer); procedure SetComboClick(Value:TNotifyEvent); procedure SetComboCtl3D(Value:Boolean); procedure SetComboDblClick(Value:TNotifyEvent); procedure SetComboDrawItem(Value:TDrawItemEvent); procedure SetComboDropDownCount(Value:Integer); procedure SetComboDroppedDown(Value:Boolean); procedure SetComboEnter(Value:TNotifyEvent); procedure SetComboExit(Value:TNotifyEvent); procedure SetComboItemHeight(Value:Integer); procedure SetComboItemIndex(Value:Integer); procedure SetComboItems(Value:TStrings); procedure SetComboKeyDown(Value:TKeyEvent); procedure SetComboKeyPress(Value:TKeyPressEvent); procedure SetComboKeyUp(Value:TKeyEvent); procedure SetComboMaxLength(Value:Integer); procedure SetComboMeasureItem(Value:TMeasureItemEvent); procedure SetComboOnChange(Value:TNotifyEvent); procedure SetComboOnDropDown(Value:TNotifyEvent); procedure SetComboSelLength(Value:Integer); procedure SetComboSelStart(Value:Integer); procedure SetComboSelText(Value:string); procedure SetComboShowHint(Value:Boolean); procedure SetComboSorted(Value:Boolean); procedure SetComboStyle(Value:TComboBoxStyle); procedure SetComboTabOrder(Value:TTabOrder); procedure SetComboTabStop(Value:Boolean); procedure SetComboText(Value:TCaption); procedure SetLabelFont(Value: TFont); procedure SetLabelStyle(Value: TLabelStyle); procedure SetParentFont(Value: Boolean); procedure SetFont(Value: TFont); public constructor Create(AOwner: TComponent); override; destructor Destroy;override; function ComboCanFocus: Boolean; function ComboFocused: Boolean; procedure ComboClear; procedure ComboSelectAll; procedure ComboSetFocus; property ComboDroppedDown: Boolean read GetComboDroppedDown write SetComboDroppedDown; property ComboItemIndex: Integer read GetComboItemIndex write SetComboItemIndex; property ComboSelLength: Integer read GetComboSelLength write SetComboSelLength; property ComboSelStart: Integer read GetComboSelStart write SetComboSelStart; property ComboSelText: string read GetComboSelText write SetComboSelText; published property Caption:TCaption read GetCaption write SetCaption; property ComboBoxWidth:integer read GetComboBoxWidth write SetComboBoxWidth; property ComboCtl3D:Boolean read GetComboCtl3D write SetComboCtl3D; property ComboDropDownCount:Integer read GetComboDropDownCount write SetComboDropDownCount; property ComboItems:TStrings read GetComboItems write SetComboItems; property ComboItemHeight:Integer read GetComboItemHeight write SetComboItemHeight; property ComboMaxLength:Integer read GetComboMaxLength write SetComboMaxLength; property ComboShowHint:Boolean read GetComboShowHint write SetComboShowHint; property ComboSorted:Boolean read GetComboSorted write SetComboSorted; property ComboStyle:TComboBoxStyle read GetComboStyle write SetComboStyle; property LabelStyle: TLabelStyle read FLabelStyle write SetLabelStyle default Normal; property ComboTabOrder:TTabOrder read GetComboTabOrder write SetComboTabOrder; property ComboTabStop:Boolean read GetComboTabStop write SetComboTabStop; property ComboText:TCaption read GetComboText write SetComboText; property Enabled; property Font:TFont read GetFont write SetFont; property LabelFont: TFont read GetLabelFont write SetLabelFont; property ParentColor; property ParentCtl3D; property ParentFont : Boolean read FParentFont write SetParentFont; property ParentShowHint; property TabOrder; property Visible; property OnComboChange: TNotifyEvent read GetComboOnChange write SetComboOnChange; property OnComboClick:TNotifyEvent read GetComboClick write SetComboClick; property OnComboDblClick:TNotifyEvent read GetComboDblClick write SetComboDblClick; property OnComboEnter:TNotifyEvent read GetComboEnter write SetComboEnter; property OnComboExit:TNotifyEvent read GetComboExit write SetComboExit; property OnComboKeyDown:TKeyEvent read GetComboKeyDown write SetComboKeyDown; property OnComboKeyPress:TKeyPressEvent read GetComboKeyPress write SetComboKeyPress; property OnComboKeyUp:TKeyEvent read GetComboKeyUp write SetComboKeyUp; property OnComboDropDown: TNotifyEvent read GetComboDropDown write SetComboOnDropDown; property OnComboDrawItem: TDrawItemEvent read GetComboDrawItem write SetComboDrawItem; property OnComboMeasureItem: TMeasureItemEvent read GetComboMeasureItem write SetComboMeasureItem; end; procedure Register; implementation constructor TPLabelCombox.Create(AOwner: TComponent); begin inherited Create(AOwner); FLabel := TRxLabel.Create(Self); FLabel.Parent := Self; FLabel.ShadowSize := 0; FLabel.Layout := tlCenter; FLabel.AutoSize := False; FLabel.Visible := True; FLabel.Font.Size := 11; FLabel.Font.Name := 'ËÎÌå'; FLabel.ParentFont := False; LabelStyle := Normal; FComboBox := TComboBox.Create(Self); FComboBox.Parent := Self; FComboBox.Visible := True; FComboBox.Font.Size := 9; FComboBox.Font.Name := 'ËÎÌå'; FComboBox.ParentFont := False; FLabel.FocusControl := FComboBox; FLabel.Height := FComboBox.Height; Height := FComboBox.Height; FLabel.Width := 60; FComboBox.Width :=120; FComboBox.Left:=60; Width := FLabel.Width+FComboBox.Width; ParentFont := False; end; function TPLabelCombox.GetLabelFont: TFont; begin Result := FLabel.Font; end; procedure TPLabelCombox.SetLabelFont(Value: TFont); begin FLabel.Font := Value; end; procedure TPLabelCombox.SetParentFont(Value: Boolean); begin inherited; FComboBox.ParentFont := Value; Flabel.ParentFont := Value; FParentFont := Value; end; destructor TPLabelCombox.Destroy ; begin FComboBox.Free; FLabel.Free; inherited Destroy; end; function TPLabelCombox.GetComboBoxWidth:integer; begin Result := FComboBox.Width; end; procedure TPLabelCombox.SetComboBoxWidth(Value: integer); begin FComboBox.Width := Value; FComboBox.Left := Width-Value; FLabel.Width := FComboBox.Left; end; function TPLabelCombox.GetFont:TFont; begin Result := FComboBox.Font; end; procedure TPLabelCombox.SetFont(Value: TFont); begin FComboBox.Font.Assign(Value); FLabel.Font.Assign(Value); FLabel.Height := FComboBox.Height; Height := FComboBox.Height; SetLabelStyle(LabelStyle); end; function TPLabelCombox.GetCaption:TCaption; begin Result := FLabel.Caption; end; procedure TPLabelCombox.SetCaption(Value: TCaption); begin FLabel.Caption := Value; end; procedure TPLabelCombox.SetLabelStyle (Value: TLabelStyle); begin FLabelStyle := Value; case Value of Normal: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := []; end; Notnil: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := []; end; Conditional: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := [fsUnderline]; end; NotnilAndConditional: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := [fsUnderline]; end; end; end; procedure TPLabelCombox.Paint; begin inherited Paint; FLabel.Height := FComboBox.Height; Height := FComboBox.Height; FComboBox.Left := Width-FComboBox.Width; FLabel.Width := FComboBox.Left; end; function TPLabelCombox.GetComboDroppedDown: Boolean; begin Result := FCombobox.DroppedDown ; end; procedure TPLabelCombox.SetComboDroppedDown(Value:Boolean); begin FCombobox.DroppedDown := Value; end; function TPLabelCombox.GetComboItemIndex: Integer; begin Result := FComboBox.ItemIndex ; end; procedure TPLabelCombox.SetComboItemIndex(Value:Integer); begin FComboBox.ItemIndex := Value; end; function TPLabelCombox.GetComboSelLength: Integer; begin Result := FComboBox.SelLength ; end; procedure TPLabelCombox.SetComboSelLength(Value:Integer); begin FComboBox.SelLength := Value; end; function TPLabelCombox.GetComboSelStart: Integer; begin Result := FComboBox.SelStart ; end; procedure TPLabelCombox.SetComboSelStart(Value:Integer); begin FComboBox.SelStart := Value; end; function TPLabelCombox.GetComboSelText: string; begin Result := FComboBox.SelText ; end; procedure TPLabelCombox.SetComboSelText(Value:string); begin FComboBox.SelText := Value; end; function TPLabelCombox.GetComboStyle:TComboBoxStyle; begin Result := FComboBox.Style end; procedure TPLabelCombox.SetComboStyle(Value:TComboBoxStyle); begin FComboBox.Style := Value; end; function TPLabelCombox.GetComboCtl3D:Boolean; begin Result := FComboBox.Ctl3D end; procedure TPLabelCombox.SetComboCtl3D(Value:Boolean); begin FComboBox.Ctl3D := Value; end; function TPLabelCombox.GetComboDropDownCount:Integer; begin Result := FComboBox.DropDownCount end; procedure TPLabelCombox.SetComboDropDownCount(Value:Integer); begin FComboBox.DropDownCount := Value; end; function TPLabelCombox.GetComboItemHeight:Integer; begin Result := FComboBox.ItemHeight end; procedure TPLabelCombox.SetComboItemHeight(Value:Integer); begin FComboBox.ItemHeight := Value; end; function TPLabelCombox.GetComboItems:TStrings; begin Result := FComboBox.Items end; procedure TPLabelCombox.SetComboItems(Value:TStrings); begin FComboBox.Items := Value; end; function TPLabelCombox.GetComboMaxLength:Integer; begin Result := FComboBox.MaxLength end; procedure TPLabelCombox.SetComboMaxLength(Value:Integer); begin FComboBox.MaxLength := Value; end; function TPLabelCombox.GetComboShowHint:Boolean; begin Result := FComboBox.ShowHint end; procedure TPLabelCombox.SetComboShowHint(Value:Boolean); begin FComboBox.ShowHint := Value; end; function TPLabelCombox.GetComboSorted:Boolean; begin Result := FComboBox.Sorted end; procedure TPLabelCombox.SetComboSorted(Value:Boolean); begin FComboBox.Sorted := Value; end; function TPLabelCombox.GetComboTabOrder:TTabOrder; begin Result := FComboBox.TabOrder end; procedure TPLabelCombox.SetComboTabOrder(Value:TTabOrder); begin FComboBox.TabOrder := Value; end; function TPLabelCombox.GetComboTabStop:Boolean; begin Result := FComboBox.TabStop end; procedure TPLabelCombox.SetComboTabStop(Value:Boolean); begin FComboBox.TabStop := Value; end; function TPLabelCombox.GetComboText:TCaption; begin Result := FComboBox.Text end; procedure TPLabelCombox.SetComboText(Value:TCaption); begin FComboBox.Text := Value; end; function TPLabelCombox.GetComboOnChange:TNotifyEvent; begin Result := FComboBox.OnChange; end; procedure TPLabelCombox.SetComboOnChange(Value:TNotifyEvent); begin FComboBox.OnChange:= Value; end; function TPLabelCombox.GetComboClick:TNotifyEvent; begin Result := FComboBox.OnClick; end; procedure TPLabelCombox.SetComboClick(Value:TNotifyEvent); begin FComboBox.OnClick:= Value; end; function TPLabelCombox.GetComboDblClick:TNotifyEvent; begin Result := FComboBox.OnDblClick; end; procedure TPLabelCombox.SetComboDblClick(Value:TNotifyEvent); begin FComboBox.OnDblClick:= Value; end; function TPLabelCombox.GetComboEnter:TNotifyEvent; begin Result := FComboBox.OnEnter; end; procedure TPLabelCombox.SetComboEnter(Value:TNotifyEvent); begin FComboBox.OnEnter:= Value; end; function TPLabelCombox.GetComboExit:TNotifyEvent; begin Result := FComboBox.OnExit; end; procedure TPLabelCombox.SetComboExit(Value:TNotifyEvent); begin FComboBox.OnExit:= Value; end; function TPLabelCombox.GetComboKeyDown:TKeyEvent ; begin Result := FComboBox.OnKeyDown; end; procedure TPLabelCombox.SetComboKeyDown(Value:TKeyEvent); begin FComboBox.OnKeyDown:= Value; end; function TPLabelCombox.GetComboKeyPress:TKeyPressEvent; begin Result := FComboBox.OnKeyPress; end; procedure TPLabelCombox.SetComboKeyPress(Value:TKeyPressEvent); begin FComboBox.OnKeyPress:= Value; end; function TPLabelCombox.GetComboKeyUp:TKeyEvent; begin Result := FComboBox.OnKeyUp; end; procedure TPLabelCombox.SetComboKeyUp(Value:TKeyEvent); begin FComboBox.OnKeyUp:= Value; end; function TPLabelCombox.GetComboDropDown: TNotifyEvent; begin Result := FComboBox.OnDropDown; end; procedure TPLabelCombox.SetComboOnDropDown(Value:TNotifyEvent); begin FComboBox.OnDropDown := Value; end; function TPLabelCombox.GetComboDrawItem: TDrawItemEvent; begin Result := FComboBox.OnDrawItem; end; procedure TPLabelCombox.SetComboDrawItem(Value:TDrawItemEvent); begin FComboBox.OnDrawItem := Value; end; function TPLabelCombox.GetComboMeasureItem: TMeasureItemEvent; begin Result := FComboBox.OnMeasureItem; end; procedure TPLabelCombox.SetComboMeasureItem(Value:TMeasureItemEvent); begin FComboBox.OnMeasureItem := Value; end; procedure TPLabelCombox.ComboClear; begin FComboBox.Clear; end; procedure TPLabelCombox.ComboSelectAll; begin FComboBox.SelectAll; end; function TPLabelCombox.ComboCanFocus: Boolean; begin Result := FComboBox.CanFocus; end; function TPLabelCombox.ComboFocused: Boolean; begin Result := FComboBox.Focused; end; procedure TPLabelCombox.ComboSetFocus; begin FComboBox.SetFocus; end; procedure Register; begin RegisterComponents('PosControl', [TPLabelCombox]); end; end.
{* ***************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambú Code SA de CV - Ing. Luis Carrasco Esta clase se encarga de convertir las excepciones por falla de internet de Delphi a excepciones propias para que sea mas claro el error ante el usuario Este archivo pertenece al proyecto de codigo abierto de Bambú Code: http://bambucode.com/codigoabierto La licencia de este código fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ***************************************************************************** *} unit ManejadorDeErroresComunes; interface uses SysUtils, {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} FacturaTipos; type TManejadorErroresComunes = class class procedure LanzarExcepcionSiDetectaFallaInternet(const aExcepcion: Exception); private class procedure DetectarErroresConocidos(const aExcepcion: Exception); end; implementation uses SOAPHTTPTrans; class procedure TManejadorErroresComunes.LanzarExcepcionSiDetectaFallaInternet(const aExcepcion: Exception); begin if aExcepcion <> nil then begin {$IFDEF CODESITE} CodeSite.SendException(aExcepcion); {$ENDIF} if aExcepcion Is ESOAPHttpException then begin // Lista de codigos de error estandares: // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error case ESOAPHttpException(aExcepcion).StatusCode of 502, 503, 504, 522: raise EPACProblemaConInternetException.Create('No se pudo realizar una conexion con el PAC: ' + aExcepcion.Message, 0, 0, True); 505: raise EPACErrorGenericoException.Create('Hubo un error al procesar tu factura: ' + aExcepcion.Message, 0, ESOAPHttpException(aExcepcion).StatusCode, False); else DetectarErroresConocidos(aExcepcion); end; end else DetectarErroresConocidos(aExcepcion); end; end; class procedure TManejadorErroresComunes.DetectarErroresConocidos(const aExcepcion: Exception); const _SIN_INTERNET = 'No se pudo establecer una conexi'; _SIN_INTERNET_INGLES = 'A connection with the server could not be established '; _CADENA_ERROR_DNS_ESPANOL = 'resolver el nombre de servidor'; _CADENA_ERROR_DNS_INGLES = 'address could not be resolved'; _CADENA_TIMEOUT_GENERICO_ESPANOL = 'el tiempo de espera para la operaci'; _CADENA_TIMEOUT_GENERICO_INGLES = 'timed out'; begin if (AnsiPos(_SIN_INTERNET, aExcepcion.Message) > 0) or (AnsiPos(_SIN_INTERNET_INGLES, aExcepcion.Message) > 0) then raise EPACProblemaConInternetException.Create('No se pudo realizar una conexion con el PAC: ' + aExcepcion.Message, 0, 0, True) else if (AnsiPos(_CADENA_ERROR_DNS_ESPANOL, aExcepcion.Message) > 0) or (AnsiPos(_CADENA_ERROR_DNS_INGLES, aExcepcion.Message) > 0) then raise EPACProblemaConInternetException.Create('No se pudo realizar una conexion con el PAC: ' + aExcepcion.Message, 0, 0, True) else if (AnsiPos(AnsiUpperCase(_CADENA_TIMEOUT_GENERICO_ESPANOL), AnsiUpperCase(aExcepcion.Message)) > 0) or (AnsiPos(AnsiUpperCase(_CADENA_TIMEOUT_GENERICO_INGLES), AnsiUpperCase(aExcepcion.Message)) > 0) then raise EPACProblemaTimeoutException.Create('No se pudo realizar una conexion con el PAC: ' + aExcepcion.Message, 0, 0, True) else raise EPACProblemaConInternetException.Create('No se pudo realizar una conexion con el PAC: ' + aExcepcion.Message, 0, 0, True); end; end.
namespace Beta; interface uses Foundation, UIKit; type [IBObject] DetailViewController = public class (UIViewController) private fDetailItem: id; fWebViewController: WebViewController; method setDetailItem(newDetailItem: id); method configureView; protected public property detailItem: id read fDetailItem write setDetailItem; [IBOutlet] property detailDescriptionLabel: weak UILabel; [IBOutlet] property masterPopoverController: UIPopoverController; method viewDidLoad; override; method didReceiveMemoryWarning; override; method showChangeLog(aHtml: String); method hideChangeLog; end; implementation method DetailViewController.viewDidLoad; begin inherited.viewDidLoad; // Do any additional setup after loading the view, typically from a nib. configureView(); end; method DetailViewController.setDetailItem(newDetailItem: id); begin if fDetailItem ≠ newDetailItem then begin fDetailItem := newDetailItem; configureView(); end; if assigned(masterPopoverController) then masterPopoverController.dismissPopoverAnimated(true); end; method DetailViewController.configureView; begin // Update the user interface for the detail item. if assigned(detailItem) then //detailDescriptionLabel.text := detailItem.description; //bug: why isn't detailDescriptionLabel getting connected from storyboard? end; method DetailViewController.didReceiveMemoryWarning; begin inherited.didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; method DetailViewController.showChangeLog(aHtml: String); begin if not assigned(fWebViewController) then begin var f := view.bounds; f.size.height := f.size.height - 64; f.origin.y := 64; fWebViewController := new WebViewController withFrame(f) andHtml(aHtml); fWebViewController.view.frame := f; fWebViewController.view.autoresizingMask := UIViewAutoresizing.UIViewAutoresizingFlexibleHeight or UIViewAutoresizing.UIViewAutoresizingFlexibleWidth; view.autoresizingMask := UIViewAutoresizing.UIViewAutoresizingFlexibleHeight or UIViewAutoresizing.UIViewAutoresizingFlexibleWidth; view.autoresizesSubviews := true; view.addSubview(fWebViewController.view); end else begin fWebViewController.loadHtml(aHtml); end; end; method DetailViewController.hideChangeLog; begin if assigned(fWebViewController) then begin fWebViewController.view.removeFromSuperview(); fWebViewController := nil; end; end; end.
unit UAMC_UserID_ISGN; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is the unit that takes the userID and password and queries the ISGN } { GatorNet system to verify the login credentials. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MSXML6_TLB, WinHTTP_TLB, ComCtrls, comObj, UBase64, Grids, HTTPApp, Grids_ts, TSGrid, osAdvDbGrid, UWindowsInfo, UContainer, UAMC_Globals, UAMC_Base, UAMC_Login, UAMC_ODP, UAMC_Port, UAMC_WorkflowBaseFrame, UGlobals; type TAMC_UserID_ISGN = class(TWorkflowBaseFrame) edtUserID: TEdit; edtUserPsw: TEdit; sTxTitle: TStaticText; stxUserID: TStaticText; sTxPswd: TStaticText; btnLogin: TButton; StaticText2: TStaticText; stxAddress: TStaticText; stxOrderID: TStaticText; edtOrderID: TEdit; stLogin: TStaticText; procedure btnLoginClick(Sender: TObject); procedure LoginEntered(Sender: TObject); private FAppraiserHash: String; //Base64 encoded login & password for the appraiser FOrderID: String; FAMCOrder: AMCOrderInfo; FOrderSelected: Boolean; public procedure InitPackageData; override; procedure DoProcessData; override; procedure Login; procedure LoadTestFiles; procedure SetPackageContents; //sets the package contents end; implementation {$R *.dfm} Uses UWebConfig, UStatus, UAMC_Utils, UAMC_Util_ISGN, UFileUtils; const cOrderInvalid = 'The order has not been validated. Click the Login button to validate this order.'; cValidateOrder = 'Click the Login button to validate this order.'; cOrderValid = 'Order is valid - click the Next button to proceed.'; { TAMC_PackageDef } procedure TAMC_UserID_ISGN.InitPackageData; var UserInfo: AMCUserUID; Cntr: Integer; begin inherited; //init vars FAMCOrder := FDoc.ReadAMCOrderInfoFromReport; //has all info about order/user LoginEntered(nil); //set state of Login button FOrderSelected := False; FAppraiserHash := ''; //session ID for appraiser FOrderID := ''; //orderID if Length(FAMCOrder.ProviderID) = 0 then for Cntr := 0 to AMCClientCnt do if AMCStdInfo[Cntr].ID = AMC_ISGN then FAMCOrder.ProviderIdx := Cntr; edtOrderID.Text := FAMCOrder.OrderID; if Trim(edtOrderID.Text) <> '' then edtOrderID.Enabled := False else edtOrderID.Enabled := True; stxAddress.Caption := PackageData.SubjectAddress; //display the subject address to user //defaults for ISGN PackageData.FForceContents := True; //user cannot change package contents PackageData.FNeedPDF := True; //ISGN always needs PDF as a separate file PackageData.FEmbbedPDF := True; //PDF is embedded only in the 2.6GSE XML if length(trim(edtOrderID.Text)) > 0 then begin if AMCStdInfo[FAMCOrder.ProviderIdx].SessionPW then begin if UserInfo.UserId = AMCUserID then UserInfo.UserPSW := AMCUserPassword else UserInfo.UserPSW := ''; edtUserID.Text := UserInfo.UserId; edtUserPSW.Text := UserInfo.UserPSW; end else begin if GetAMCUserRegistryInfo(FAMCOrder.ProviderID, UserInfo) then begin edtUserID.Text := UserInfo.UserId; edtUserPSW.Text := UserInfo.UserPSW; end else begin edtUserID.Text := ''; edtUserPSW.Text := ''; end; end; end; end; procedure TAMC_UserID_ISGN.btnLoginClick(Sender: TObject); begin Login; end; procedure TAMC_UserID_ISGN.LoginEntered(Sender: TObject); begin btnLogin.Enabled := (length(edtOrderID.text)> 0) and (length(edtUserPSW.text)> 0) and (Length(edtUserID.Text) > 0); end; procedure TAMC_UserID_ISGN.Login; var id, psw: String; OrdResp: String; ODPInfo: IXMLREQUEST_GROUP; UserInfo: AMCUserUID; ErrMsg: String; //detailed error message for user errCode: Integer; Cntr: Integer; begin //initialize id := edtUserID.Text; psw := edtUserPSW.Text; // If an order was not retrieved then find the provider in AMC.INI if FAMCOrder.ProviderIdx < 0 then begin for Cntr := 0 to AMCClientCnt do if FAMCOrder.ProviderID = IntToStr(AMCStdInfo[Cntr].ID) then FAMCOrder.ProviderIdx := Cntr; end; // If no order and no provider in AMC.INI then get the defaults if FAMCOrder.ProviderIdx < 0 then FAMCOrder.SvcGetDataEndPointUrl := GetURLForISGNServer(ISGN_GetData, FAMCOrder.SvcGetDataEndPointVer) else begin FAMCOrder.SvcGetDataEndPointUrl := AMCStdInfo[FAMCOrder.ProviderIdx].SvcGetDataUrl; FAMCOrder.SvcGetDataEndPointVer := AMCStdInfo[FAMCOrder.ProviderIdx].SvcGetDataVer; end; // Now try and retrieve the order information errCode := AMCGetISGNOrderDetails(edtUserId.Text, edtUserPSW.Text, edtOrderID.Text, FAMCOrder.SvcGetDataEndPointURL, FAMCOrder.SvcGetDataEndPointVer, OrdResp, ErrMsg); case errCode of cseOK: begin ODPInfo := ISGNConvertRespToOrd(OrdResp); if AMCStdInfo[FAMCOrder.ProviderIdx].SessionPW then begin AMCUserID := edtUserId.Text; AMCUserPassword := edtUserPSW.Text; end else begin UserInfo.VendorID := FAMCOrder.ProviderID; UserInfo.UserId := edtUserID.Text; UserInfo.UserPSW := edtUserPSW.Text; SetAMCUserRegistryInfo(FAMCOrder.ProviderID, UserInfo); AMCUserID := UserInfo.UserId; AMCUserPassword := UserInfo.UserPSW; end; FOrderSelected := True; FOrderID := edtOrderID.Text; FAppraiserHash := Base64Encode(edtUserID.Text + ':' + edtUserPSW.Text); PackageData.NeedENV := (Uppercase(AMCENV_Req) = 'Y'); SetPackageContents; stLogin.Caption := cOrderValid; stLogin.Font.Color := clGreen; stLogin.Refresh; end; cseInvalidLogin, cseInvalidProvider: begin ShowAlert(atWarnAlert,errMsg); stLogin.Caption := cValidateOrder; stLogin.Font.Color := clRed; stLogin.Refresh; btnLogin.SetFocus; end; else //cseNotConnected, cseOrderNotFound, cseOther, ... begin if FAMCOrder.ProviderIdx < 0 then SaveAMCSvcErr('AMCGetOrderDetails', 'Order:' + FAMCOrder.OrderID + ' ' + errMsg, -1, ErrCode, 1) else SaveAMCSvcErr('AMCGetOrderDetails', 'Order:' + FAMCOrder.OrderID + ' ' + errMsg, AMCStdInfo[FAMCOrder.ProviderIdx].ID, ErrCode, AMCStdInfo[FAMCOrder.ProviderIdx].SvcLogCount); ShowAlert(atWarnAlert,errMsg); stLogin.Caption := cValidateOrder; stLogin.Font.Color := clRed; stLogin.Refresh; btnLogin.SetFocus; end; end; end; procedure TAMC_UserID_ISGN.SetPackageContents; var dataFile: TDataFile; AMCData: TAMCData_ISGN; begin PackageData.FDataFiles.Clear; //delete all previous DataObjs if PackageData.IsUAD and (PackageData.FXMLVersion = cMISMO26GSE) then begin dataFile := TDataFile.Create(fTypXML26GSE); PackageData.FDataFiles.add(dataFile); end; if PackageData.FNeedXML26 then begin dataFile := TDataFile.Create(fTypXML26); PackageData.FDataFiles.add(dataFile); end; if PackageData.FNeedENV then begin dataFile := TDataFile.Create(fTypENV); PackageData.FDataFiles.add(dataFile); end; //we always require the PDF dataFile := TDataFile.Create(fTypPDF); PackageData.FDataFiles.add(dataFile); if Assigned(PackageData.FAMCData) then //Init the AMC Specific data object PackageData.FAMCData.free; AMCData := TAMCData_ISGN.Create; //Create a new StreetLinks Data Object AMCData.FAppraiserHash := FAppraiserHash; //set the appraiser Hash (session identifier) AMCData.FOrderID := FOrderID; //set the order identifier PackageData.FAMCData := AMCData; end; procedure TAMC_UserID_ISGN.DoProcessData; begin inherited; PackageData.FGoToNextOk := FOrderSelected; PackageData.FHardStop := not FOrderSelected; PackageData.FAlertMsg := ''; if not FOrderSelected then begin if Length(FOrderID) = 0 then PackageData.FAlertMsg := cOrderInvalid else PackageData.FAlertMsg := 'Your user name and/or password was not validated by GatorNet.'; btnLogin.SetFocus; end; end; //just for testing procedure TAMC_UserID_ISGN.LoadTestFiles; const envFilePath = 'C:\\workflowSampleUploadFiles\UAD_1004_TEST.ENV'; pdfFilePath = 'C:\\workflowSampleUploadFiles\UAD_1004_TEST.PDF'; xmlFilePath = 'C:\\workflowSampleUploadFiles\UAD_1004_TEST.XML'; var // PDFStream: TFileStream; // ENVStream: TFileStream; // XMLStream: TFileStream; // streamLen: LongInt; dataFile: TDataFile; begin If PackageData.DataFiles.NeedsDataFile(fTypXML26GSE) then begin dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26GSE, False); dataFile.LoadFromFile(xmlFilePath); (* XMLStream := TFileStream.Create(xmlFilePath, fmOpenRead); try XMLStream.Seek(0,soFromBeginning); streamLen := XMLStream.size; SetLength(dataFile.FData, streamLen); XMLStream.Read(Pchar(dataFile.FData)^, streamLen); finally XMLStream.Free; end; *) end; if PackageData.DataFiles.NeedsDataFile(fTypXML26) then begin dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26, False); dataFile.LoadFromFile(xmlFilePath); (* XMLStream := TFileStream.Create(xmlFilePath, fmOpenRead); try XMLStream.Seek(0,soFromBeginning); streamLen := XMLStream.size; SetLength(dataFile.FData, streamLen); XMLStream.Read(Pchar(dataFile.FData)^, streamLen); finally XMLStream.Free; end; *) end; if PackageData.DataFiles.NeedsDataFile(fTypENV) then begin dataFile := PackageData.DataFiles.GetDataFileObj(fTypENV, False); dataFile.LoadFromFile(envFilePath); (* ENVStream := TFileStream.Create(envFilePath, fmOpenRead); try ENVStream.Seek(0,soFromBeginning); streamLen := ENVStream.size; SetLength(dataFile.FData, streamLen); ENVStream.Read(Pchar(dataFile.FData)^, streamLen); // dataFile.FData := Base64Encode(dataFile.FData); finally ENVStream.Free; end; *) end; if PackageData.DataFiles.NeedsDataFile(fTypPDF) then begin dataFile := PackageData.DataFiles.GetDataFileObj(fTypPDF, False); //get ref to object dataFile.LoadFromFile(pdfFilePath); (* PDFStream := TFileStream.Create(pdfFilePath, fmOpenRead); try PDFStream.Seek(0,soFromBeginning); streamLen := PDFStream.size; SetLength(dataFile.FData, streamLen); PDFStream.Read(Pchar(dataFile.FData)^, streamLen); // dataFile.FData := Base64Encode(dataFile.FData); finally PDFStream.Free; end; *) end; end; end.
unit ScripterEditorFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IDEMain, LMDDckSite, SpTBXItem, ComCtrls, ScriptCtrls, atScript, atScripter, AdvMemo, StdCtrls, AdvCodeList, ToolWin, ExtCtrls, dIDEActions; type TFrmScripterEditor = class(TForm) ScripterEngine: TIDEEngine; LMDDockManager1: TLMDDockManager; LMDDockSite1: TLMDDockSite; SpTBXStatusBar1: TSpTBXStatusBar; PanMemo: TLMDDockPanel; PanExplorer: TLMDDockPanel; PanCodeList: TLMDDockPanel; ScripterMain: TIDEScripter; SourceExplorer: TSourceExplorer; MemoSource: TIDEMemo; Watches: TLMDDockPanel; WatchList: TIDEWatchListView; CodeList: TAdvCodeList; ControlBar1: TControlBar; ToolBar2: TToolBar; tbNewProject: TToolButton; tbOpenProject: TToolButton; tbSaveAll: TToolButton; ToolBar4: TToolBar; tbNewUnit: TToolButton; tbNewForm: TToolButton; tbOpenFile: TToolButton; tbSaveFile: TToolButton; tbEdit: TToolBar; tbCut: TToolButton; tbCopy: TToolButton; tbPaste: TToolButton; ToolBar1: TToolBar; tbRun: TToolButton; tbPause: TToolButton; tbReset: TToolButton; ToolButton9: TToolButton; tbTraceInto: TToolButton; tbStepOver: TToolButton; ToolButton12: TToolButton; tbToggleBreakPoint: TToolButton; tbAddWatch: TToolButton; private public end; implementation {$R *.dfm} end.
unit Menus.Controller.Entity.Clientes; interface uses Menus.Controller.Entity.Interfaces, Menu.Model.Conexoes.Interfaces, Menus.Controller.Conexoes.Factory.Conexao, Menus.Controller.Conexoes.Factory.DataSet, Menus.Model.Entity.Interfaces, Menus.Model.Entity.Factory, Data.DB, Menus.Controller.Conexoes.Interfaces, Menus.Controller.Conexoes.Facade; type TControllerEntityClientes = class(TInterfacedObject, iControllerEntity) private FFacadeConexao: iControllerConexoesFacade; FEntity: iModelEntity; public constructor Create; destructor Destroy; override; class function New: iControllerEntity; function Lista(aDataSource : TDataSource) : iControllerEntity; end; implementation { TControllerEntityClientes } constructor TControllerEntityClientes.Create; begin FFacadeConexao := TControllerConexoesFacade.New; FEntity := TModelEntityFactory.New.Clientes(FFacadeConexao.iDataSet); end; destructor TControllerEntityClientes.Destroy; begin inherited; end; function TControllerEntityClientes.Lista( aDataSource: TDataSource): iControllerEntity; begin Result := Self; aDataSource.DataSet := TDataSet(FEntity.Listar); end; class function TControllerEntityClientes.New: iControllerEntity; begin Result := Self.Create; end; end.
program fib(input,output); var x:integer; r,exp:real; {--------------------------FIB} function fib(N:integer):integer; {pre: N is a positive integer} {post: Fib is the Nth term of the Fibonacci sequence} begin if n<=2 then fib:=1 {if n<=2 then it returns 1} else {it does this if n is not <=2} fib:=fib(N-2)+Fib(N-1); end; {----------------------------MAIN} {This is the main program} begin x:=1; writeln('TERM R (2R-1)squared'); writeln('--------------------------------------'); repeat writeln(fib(x),' ',r:1:6,' ',exp:1:6); x:=x+1; r:=fib(x)/fib(x-1); exp:=sqr(2*r-1); until (fib(x)>1000); end. 
unit Alcinoe.HTTP.Client.Net; interface uses System.Net.HttpClient, System.net.URLClient; Function ALCreateNetHTTPClient(Const aAllowcookies: Boolean = False): THttpClient; function ALAcquireKeepAliveNetHttpClient(const aURI: TUri): THTTPClient; procedure ALReleaseKeepAliveNetHttpClient(const aURI: TUri; var aHTTPClient: THTTPClient); procedure ALReleaseAllKeepAliveNetHttpClients; implementation uses System.NetConsts, System.SysUtils, System.Types, System.Generics.Collections, Alcinoe.Common, Alcinoe.HTTP.Client, Alcinoe.StringUtils; {*} var _ALNetHttpClientKeepAlives: TObjectDictionary<String, TobjectList<THTTPClient>>; {********************************************************************************} Function ALCreateNetHTTPClient(Const aAllowcookies: Boolean = False): THttpClient; Begin Result := THttpClient.Create; Result.AllowCookies := aAllowcookies; Result.Accept := 'text/html, */*'; {$IF not Defined(ALHttpGzipAuto)} //http://developer.android.com/reference/java/net/HttpURLConnection.html //By default, this implementation of HttpURLConnection requests that servers use gzip compression and //it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and //Content-Length response headers are cleared in this case. Gzip compression can be disabled by //setting the acceptable encodings in the request header //it's the same for IOS and OSX Result.AcceptEncoding := 'gzip'; {$ENDIF} Result.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'; Result.ConnectionTimeout := ALCreateHttpClientConnectTimeout; Result.ResponseTimeout := ALCreateHttpClientReceiveTimeout; Result.SendTimeout := ALCreateHttpClientSendTimeout; end; {**********************************************************************} function ALAcquireKeepAliveNetHttpClient(const aURI: TUri): THTTPClient; var LList: TobjectList<THTTPClient>; begin TMonitor.Enter(_ALNetHttpClientKeepAlives); try if _ALNetHttpClientKeepAlives.TryGetValue(AlLowerCase(aURI.Scheme) + '://' + AlLowerCase(aURI.Host) + ':' + ALIntToStrW(aURI.port), LList) then begin if LList.Count > 0 then result := LList.ExtractItem(LList.Last, TDirection.FromEnd) else result := ALCreateNetHTTPClient; end else result := ALCreateNetHTTPClient; finally TMonitor.exit(_ALNetHttpClientKeepAlives); end; end; {****************************************************************************************} procedure ALReleaseKeepAliveNetHttpClient(const aURI: TUri; var aHTTPClient: THTTPClient); var LList: TobjectList<THTTPClient>; begin TMonitor.Enter(_ALNetHttpClientKeepAlives); try if _ALNetHttpClientKeepAlives.TryGetValue(AlLowerCase(aURI.Scheme) + '://' + AlLowerCase(aURI.Host) + ':' + ALIntToStrW(aURI.port), LList) then begin while LList.Count >= ALMaxKeepAliveHttpClientPerHost do LList.Delete(0); LList.Add(aHTTPClient); aHTTPClient := nil; end else begin LList := TobjectList<THTTPClient>.create(true{aOwnObject}); try LList.Add(aHTTPClient); aHTTPClient := nil; if not _ALNetHttpClientKeepAlives.TryAdd(AlLowerCase(aURI.Scheme) + '://' + AlLowerCase(aURI.Host) + ':' + ALIntToStrW(aURI.port), LList) then ALFreeAndNil(LList); except ALFreeAndNil(LList); raise; end; end; finally TMonitor.exit(_ALNetHttpClientKeepAlives); end; end; {********************************************} procedure ALReleaseAllKeepAliveNetHttpClients; begin TMonitor.Enter(_ALNetHttpClientKeepAlives); try _ALNetHttpClientKeepAlives.Clear; finally TMonitor.exit(_ALNetHttpClientKeepAlives); end; end; initialization _ALNetHttpClientKeepAlives := TObjectDictionary<String, TobjectList<THTTPClient>>.create([doOwnsValues]); finalization ALFreeAndNil(_ALNetHttpClientKeepAlives); end.
unit Patient; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Day; type TPatient = class private FDayArray: array of TDay; public constructor Create(NrOfDays: integer); function GetDay(Index: integer): TDay; end; implementation constructor TPatient.Create(NrOfDays: integer); var DayIdx: integer; NewDay: TDay; begin SetLength(FDayArray, NrOfDays); for DayIdx := 0 to NrOfDays do begin NewDay := TDay.Create(); FDayArray[DayIdx] := NewDay; end; end; function TPatient.GetDay(Index: integer) : TDay; begin GetDay := FDayArray[Index]; end; end.
unit fmCambioMoneda; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmBase, ExtCtrls, StdCtrls, Buttons, frCambioMoneda; type TfCambioMoneda2 = class(TfBase) fCambioMoneda: TfCambioMoneda; bAceptar: TBitBtn; bCancelar: TBitBtn; Bevel2: TBevel; procedure fCambioMonedaeMonedaValorChange(Sender: TObject); procedure FormShow(Sender: TObject); private function GetMonedaFrom: string; function GetMonedaTo: string; function GetMonedaValor: currency; procedure SetMonedaFrom(const Value: string); procedure SetMonedaTo(const Value: string); procedure SetMonedaValor(const Value: currency); { Private declarations } public property MonedaValor: currency read GetMonedaValor write SetMonedaValor; property MonedaFrom: string read GetMonedaFrom write SetMonedaFrom; property MonedaTo: string read GetMonedaTo write SetMonedaTo; end; implementation {$R *.dfm} resourcestring CAPTION_MONEDA = 'Cambio moneda'; { TfCambioMoneda2 } procedure TfCambioMoneda2.fCambioMonedaeMonedaValorChange(Sender: TObject); begin inherited; bAceptar.Enabled := MonedaValor > 0; end; procedure TfCambioMoneda2.FormShow(Sender: TObject); begin inherited; fCambioMoneda.BuscarBD; end; function TfCambioMoneda2.GetMonedaFrom: string; begin result := fCambioMoneda.MonedaFrom; end; function TfCambioMoneda2.GetMonedaTo: string; begin result := fCambioMoneda.MonedaTo; end; function TfCambioMoneda2.GetMonedaValor: currency; begin result := fCambioMoneda.MonedaValor; end; procedure TfCambioMoneda2.SetMonedaFrom(const Value: string); begin fCambioMoneda.MonedaFrom := Value; end; procedure TfCambioMoneda2.SetMonedaTo(const Value: string); begin fCambioMoneda.MonedaTo := Value; Caption := CAPTION_MONEDA + ' ' + Value; end; procedure TfCambioMoneda2.SetMonedaValor(const Value: currency); begin fCambioMoneda.MonedaValor := Value; end; end.
unit TimeFrame; interface uses DomainObjectValueUnit, DateTimeRange, SysUtils, Classes; type TTimeFrame = class (TDomainObjectValue) protected FDateTimeRange: TDateTimeRange; function GetDeadline: TDateTime; function GetStart: TDateTime; procedure CreateDateTimeRange; overload; procedure CreateDateTimeRange( const StartDateTime: TDateTime; const EndDateTime: TDateTime ); overload; procedure EnsureThatStartAndDeadlineSpecifyCorrectInterval( const Start, Deadline: TDateTime ); procedure SetDeadline(const Value: TDateTime); procedure SetStart(const Value: TDateTime); public destructor Destroy; override; constructor Create; overload; virtual; constructor Create( const Start: TDateTime; const Deadline: TDateTime ); overload; function IsExpired: Boolean; function IsExpiring: Boolean; procedure SetStartAndDeadline(const Start, Deadline: TDateTime); published property Start: TDateTime read GetStart write SetStart; property Deadline: TDateTime read GetDeadline write SetDeadline; end; implementation uses AuxDebugFunctionsUnit; { TTimeFrame } constructor TTimeFrame.Create(const Start, Deadline: TDateTime); begin inherited Create; CreateDateTimeRange; SetStartAndDeadline(Start, Deadline); end; procedure TTimeFrame.CreateDateTimeRange(const StartDateTime, EndDateTime: TDateTime); begin FDateTimeRange := TDateTimeRange.Create(StartDateTime, EndDateTime); end; destructor TTimeFrame.Destroy; begin FreeAndNil(FDateTimeRange); inherited; end; procedure TTimeFrame.EnsureThatStartAndDeadlineSpecifyCorrectInterval( const Start, Deadline: TDateTime); begin if not InvariantsComplianceRequested then Exit; if Start > Deadline then raise Exception.CreateFmt( 'Дата начала %s и конца %s определяют ' + 'истекший промежуток времени', [ Start, Deadline ] ); end; procedure TTimeFrame.CreateDateTimeRange; begin CreateDateTimeRange(Now, Now); end; constructor TTimeFrame.Create; begin inherited; CreateDateTimeRange; end; function TTimeFrame.GetDeadline: TDateTime; begin Result := FDateTimeRange.EndDateTime; end; function TTimeFrame.GetStart: TDateTime; begin Result := FDateTimeRange.StartDateTime; end; function TTimeFrame.IsExpired: Boolean; begin Result := Now > Deadline; end; function TTimeFrame.IsExpiring: Boolean; begin Result := FDateTimeRange.HasIncludes(Now); end; procedure TTimeFrame.SetDeadline(const Value: TDateTime); begin SetStartAndDeadline(Start, Value); end; procedure TTimeFrame.SetStart(const Value: TDateTime); begin SetStartAndDeadline(Value, Deadline); end; procedure TTimeFrame.SetStartAndDeadline(const Start, Deadline: TDateTime); begin EnsureThatStartAndDeadlineSpecifyCorrectInterval(Start, Deadline); FDateTimeRange.StartDateTime := Start; FDateTimeRange.EndDateTime := Deadline; end; end.
unit MsgBoardUnit; interface uses Classes, SysUtils, DbUnit; type { TMsgBoardItem } TMsgBoardItem = class(TDbItem) public Desc: string; Text: string; Priority: integer; Author: string; BeginDate: TDateTime; EndDate: TDateTime; class procedure FillDbTableInfo(ADbTableInfo: TDbTableInfo); override; function GetValue(const AName: string): string; override; procedure SetValue(const AName: string; AValue: string); override; end; { TMsgBoardList } TMsgBoardList = class(TDbItemList) private //LastID: integer; //function CompareFunc(Item1, Item2: Pointer): Integer; public BeginDate: TDateTime; EndDate: TDateTime; FileName: string; constructor Create(ADbDriver: TDbDriver); reintroduce; class function GetDbItemClass(): TDbItemClass; override; procedure Sort(); end; implementation //uses MainFunc; class procedure TMsgBoardItem.FillDbTableInfo(ADbTableInfo: TDbTableInfo); begin inherited FillDbTableInfo(ADbTableInfo); with ADbTableInfo do begin TableName := 'msg_board'; AddField('desc', 'S'); AddField('text', 'S'); AddField('priority', 'I'); AddField('author', 'S'); AddField('begin_date', 'D'); AddField('end_date', 'D'); end; end; // === TMsgBoardItem === function TMsgBoardItem.GetValue(const AName: string): string; begin if AName = 'id' then Result := IntToStr(self.FID) else if AName = 'desc' then Result := self.Desc else if AName = 'text' then Result := self.Text else if AName = 'priority' then Result := IntToStr(self.Priority) else if AName = 'author' then Result := self.Author else if AName = 'begin_date' then Result := DateTimeToStr(self.BeginDate) else if AName = 'end_date' then Result := DateTimeToStr(self.EndDate) else Result := inherited GetValue(AName); end; procedure TMsgBoardItem.SetValue(const AName: string; AValue: string); begin if AName = 'id' then self.FID := StrToInt64Def(AValue, 0) else if AName = 'desc' then self.Desc := AValue else if AName = 'text' then self.Text := AValue else if AName = 'priority' then self.Priority := StrToIntDef(AValue, 0) else if AName = 'author' then self.Author := AValue else if AName = 'begin_date' then self.BeginDate := StrToDateTime(AValue) else if AName = 'end_date' then self.EndDate := StrToDateTime(AValue) else inherited SetValue(AName, AValue); end; // === TMsgBoardList === constructor TMsgBoardList.Create(ADbDriver: TDbDriver); var ti: TDbTableInfo; begin if not Assigned(ADbDriver) then ADbDriver := GlobalDbDriver; ti := ADbDriver.GetDbTableInfo('msg_board'); if not Assigned(ti) then begin ti := TDbTableInfo.Create(); with ti do begin TableName := 'msg_board'; AddField('id', 'I'); AddField('desc', 'S'); AddField('text', 'S'); AddField('priority', 'I'); AddField('author', 'S'); AddField('begin_date', 'D'); AddField('end_date', 'D'); end; ADbDriver.TablesList.Add(ti); end; inherited Create(ti, ADbDriver); end; class function TMsgBoardList.GetDbItemClass(): TDbItemClass; begin Result := TMsgBoardItem; end; function CompareFunc(Item1, Item2: Pointer): integer; begin Result := TMsgBoardItem(Item2).Priority - TMsgBoardItem(Item1).Priority; end; procedure TMsgBoardList.Sort(); begin inherited Sort(@CompareFunc); end; end.
unit UntMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.Layouts, System.Bluetooth, System.Bluetooth.Components, FMX.Objects, FGX.ProgressDialog; //Passo 1 - Constante relacionada ao GUID para impressoras Bluetooth const UUID = '{00001101-0000-1000-8000-00805F9B34FB}'; type TfrmPrincipal = class(TForm) bthDispositivos: TBluetooth; cbxDevices: TComboBox; Button1: TButton; Button2: TButton; lblConectado: TLabel; Button3: TButton; ListBox1: TListBox; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; ListBoxItem4: TListBoxItem; ToolBar1: TToolBar; Label2: TLabel; Label3: TLabel; fgActivityDialog1: TfgActivityDialog; crlConectado: TCircle; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private //Passo 3 - Listar os dispositivos JÁ pareados procedure CarregarDispositivos; function CarregarImpressoraPorNome(ANomeImpressora: String): TBluetoothDevice; function ConectarImpressora(ANomeImpressora: String): boolean; { Private declarations } public { Public declarations } //Passo 2 - Criar variável. Esta será usada para enviar comandos para a impressora FSocket : TBluetoothSocket; procedure ShowAguarde(const AMessage: String); procedure HideAguarde; end; var frmPrincipal: TfrmPrincipal; implementation {$R *.fmx} procedure TfrmPrincipal.Button1Click(Sender: TObject); begin CarregarDispositivos; end; procedure TfrmPrincipal.CarregarDispositivos; var Dispositivo: TBluetoothDevice; begin ShowAguarde('Listando...'); cbxDevices.Clear; for Dispositivo in bthDispositivos.PairedDevices do cbxDevices.Items.Add(Dispositivo.DeviceName); (* if cbxDevices.Items.Count > 0 then cbxDevices.ItemIndex := 0; *) HideAguarde; end; function TfrmPrincipal.CarregarImpressoraPorNome(ANomeImpressora: String): TBluetoothDevice; var Dispositivo: TBluetoothDevice; begin Result := nil; for Dispositivo in bthDispositivos.PairedDevices do if Dispositivo.DeviceName = ANomeImpressora then Result := Dispositivo; end; procedure TfrmPrincipal.Button2Click(Sender: TObject); begin ShowAguarde('Conectando...'); if (cbxDevices.Selected <> nil) and (cbxDevices.Selected.Text <> '') then begin //Testa se conegue conectar à impressora if ConectarImpressora(cbxDevices.Selected.Text) then begin lblConectado.Text := ' Conectado a Impressora'; crlConectado.Fill.Color := TAlphaColorRec.Lime; end else begin lblConectado.Text := ' Não conectado'; crlConectado.Fill.Color := TAlphaColorRec.Red; end; end else ShowMessage('Selecione um dispositivo'); HideAguarde; end; procedure TfrmPrincipal.Button3Click(Sender: TObject); procedure Centralizar; begin FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(1))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(8))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(16))); end; procedure Titulo; begin FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(32))); end; procedure Normal; begin FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); end; begin if (FSocket <> nil) and (FSocket.Connected) then begin FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(64))); Centralizar; Titulo; FSocket.SendData(TEncoding.UTF8.GetBytes('EC 2016' + chr(13))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); FSocket.SendData(TEncoding.UTF8.GetBytes('----------------' + chr(13))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); Centralizar; Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('MASTERCARD')); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); Centralizar; Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('DEBITO A VISTA')); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('Via Cliente> CPF: 266.452.608-15')); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(0))); Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('SAO PAULO - SP')); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(0))); Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('DOC-705890 - ' + FormatDateTime('DD/MM/YY',Date) + ' - ' + FormatDateTime('HH:MM',Time))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(0))); Normal; FSocket.SendData(TEncoding.UTF8.GetBytes('Valor: 12,50')); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); Centralizar; FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(0))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(5))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(29) + chr(107) + chr(2) + '8920183749284' + chr(0))); FSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(5))); end; end; function TfrmPrincipal.ConectarImpressora(ANomeImpressora: String): Boolean; var Dispositivo: TBluetoothDevice; begin Result := False; Dispositivo := CarregarImpressoraPorNome(ANomeImpressora); if Dispositivo <> nil then begin FSocket := Dispositivo.CreateClientSocket(StringToGUID(UUID), False); if FSocket <> nil then begin FSocket.Connect; Result := FSocket.Connected; end; end; end; procedure TfrmPrincipal.HideAguarde; begin fgActivityDialog1.Hide; end; procedure TfrmPrincipal.ShowAguarde(const AMessage: String); begin fgActivityDialog1.Title := 'Aguarde'; fgActivityDialog1.Message := AMessage; fgActivityDialog1.Cancellable := False; fgActivityDialog1.Show; end; end.
{ Description: ADXL345 library. Copyright (C) 2019 Melchiorre Caruso <melchiorrecaruso@gmail.com> This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit adxl345; {$mode objfpc} interface uses wiringPi; const adxl345_addr = $53; type adxl345_rec = packed record x: double; y: double; z: double; end; function adxl345setup: longint; function adxl345_read(fd: longint): adxl345_rec; implementation procedure adxl345_init(fd: longint); begin //Register 0x31—DATA_FORMAT (Read/Write) // (31dec -> 0000 1011 binary) Bit FULL-RANGE, D0 and D1 wiringpii2cwritereg8(fd, $31, $0b); // Register 0x2D—POWER_CTL (Read/Write) // (8dec -> 0000 1000 binary) Bit D3 High for measuring enable wiringpii2cwritereg8(fd, $2d, $08); //wiringpii2cwritereg8(fd, $2e, $00); wiringpii2cwritereg8(fd, $1e, $00); wiringpii2cwritereg8(fd, $1f, $00); wiringpii2cwritereg8(fd, $20, $00); wiringpii2cwritereg8(fd, $21, $00); wiringpii2cwritereg8(fd, $22, $00); wiringpii2cwritereg8(fd, $23, $00); wiringpii2cwritereg8(fd, $24, $01); wiringpii2cwritereg8(fd, $25, $0f); wiringpii2cwritereg8(fd, $26, $2b); wiringpii2cwritereg8(fd, $27, $00); wiringpii2cwritereg8(fd, $28, $09); wiringpii2cwritereg8(fd, $29, $ff); wiringpii2cwritereg8(fd, $2a, $80); wiringpii2cwritereg8(fd, $2c, $0a); wiringpii2cwritereg8(fd, $2f, $00); wiringpii2cwritereg8(fd, $38, $9f); end; function adxl345_read(fd: longint): adxl345_rec; var x0, y0, z0: longint; x1, y1, z1: longint; begin // Start with register 0x32 (ACCEL_XOUT_H) // Read 6 registers total, each axis value is stored in 2 registers x0 := wiringpii2creadreg8(fd, $32); x1 := wiringpii2creadreg8(fd, $33); y0 := wiringpii2creadreg8(fd, $34); y1 := wiringpii2creadreg8(fd, $35); z0 := wiringpii2creadreg8(fd, $36); z1 := wiringpii2creadreg8(fd, $37); result.x := ((x1 shl 8) or x0)/32; // X-axis value result.y := ((y1 shl 8) or y0)/32; // Y-axis value result.z := ((z1 shl 8) or z0)/32; // Z-axis value end; function adxl345setup: longint; var fd: longint; begin result := -1; fd := wiringpii2csetup(adxl345_addr); if fd <> -1 then begin adxl345_init(fd); result := fd; end; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://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 DUnitX.Expert.ProjectWizard; interface {$I DUnitX.inc} uses ToolsApi, {$IFDEF USE_NS} VCL.Graphics; {$ELSE} Graphics; {$ENDIF} type TDUnitXNewProjectWizard = class(TNotifierObject,IOTAWizard,IOTARepositoryWizard, IOTARepositoryWizard80, IOTAProjectWizard) protected FIcon : TIcon; public // IOTARepositoryWizard80 function GetGalleryCategory: IOTAGalleryCategory; function GetPersonality: string; // IOTARepositoryWizard60 function GetDesigner: string; // IOTARepositoryWizard function GetAuthor: string; function GetComment: string; function GetPage: string; function GetGlyph: Cardinal; // IOTAWizard function GetIDString: string; function GetName: string; function GetState: TWizardState; { Launch the AddIn } procedure Execute; constructor Create; destructor Destroy; override; end; implementation uses DUnitX.Expert.Forms.NewProjectWizard, DUnitX.Expert.CodeGen.NewTestProject, DUnitX.Expert.CodeGen.NewTestUnit, DccStrs, Controls, Forms, Windows; { TNewBatchJobWizard } constructor TDUnitXNewProjectWizard.Create; begin FIcon := TIcon.create; FIcon.LoadFromResourceName(HInstance,'DUnitXNewProjectIcon'); end; destructor TDUnitXNewProjectWizard.Destroy; begin FIcon.Free; inherited; end; procedure TDUnitXNewProjectWizard.Execute; var WizardForm : TfrmDunitXNewProject; ModuleServices : IOTAModuleServices; Project : IOTAProject; Config : IOTABuildConfiguration; TestUnit : IOTAModule; begin WizardForm := TfrmDunitXNewProject.Create(Application); try if WizardForm.ShowModal = mrOk then begin if not WizardForm.AddToProjectGroup then begin (BorlandIDEServices as IOTAModuleServices).CloseAll; end; ModuleServices := (BorlandIDEServices as IOTAModuleServices); // Create Project Source ModuleServices.CreateModule(TTestProjectFile.Create(WizardForm.ReportLeakOption)); Project := GetActiveProject; Config := (Project.ProjectOptions as IOTAProjectOptionsConfigurations).BaseConfiguration; Config.SetValue(sUnitSearchPath,'$(DUnitX)'); // Create Test Unit if WizardForm.CreateTestUnit then begin TestUnit := ModuleServices.CreateModule( TNewTestUnit.Create(WizardForm.CreateSetupTearDownMethods, WizardForm.CreateSampleMethods, WizardForm.TestFixtureClasaName )); Project.AddFile(TestUnit.FileName,true); end; end; finally WizardForm.Free; end; end; function TDUnitXNewProjectWizard.GetAuthor: string; begin result := 'DUnitX Team - https://github.com/VSoftTechnologies/DUnitX'; end; function TDUnitXNewProjectWizard.GetComment: string; begin result := 'Create New DUnitX Test Project'; end; function TDUnitXNewProjectWizard.GetDesigner: string; begin result := dAny; end; function TDUnitXNewProjectWizard.GetGalleryCategory: IOTAGalleryCategory; begin result := (BorlandIDEServices as IOTAGalleryCategoryManager).FindCategory(sCategoryDelphiNew); end; function TDUnitXNewProjectWizard.GetGlyph: Cardinal; begin result := CopyIcon(FIcon.Handle); end; function TDUnitXNewProjectWizard.GetIDString: string; begin result := 'DunitX.Wizard.NewProjectWizard'; end; function TDUnitXNewProjectWizard.GetName: string; begin result := 'DUnitX Project'; end; function TDUnitXNewProjectWizard.GetPage: string; begin // Results not used if IOTARepositoryWizard80.GetGalleryCategory implemented result := 'Delphi Project'; end; function TDUnitXNewProjectWizard.GetPersonality: string; begin result := sDelphiPersonality; end; function TDUnitXNewProjectWizard.GetState: TWizardState; begin result := [wsEnabled]; end; end.
{******************************************************************************* This file is part of the Open Chemera Library. This work is public domain (see README.TXT). ******************************************************************************** Author: Ludwig Krippahl Date: 20.3.2011 Purpose: Geometric hashing class Requirements: Revisions: To do: *******************************************************************************} unit geomhash; {$mode objfpc} interface uses Classes, SysUtils, basetypes, geomutils; type { TGeomHasher } TGeomHasher=class //Only stores indexes in the grid //The size of the grid cell must be > 1e-6 and the points array must not //be empty private FHashGrid:array of array of array of TIntegers; //indexes of hashed points FShiftToGrid:TCoord; FInvGridStep:TFloat; //1/gridstep FHighX,FHighY,FHighZ:Integer; //max grid cells FPoints:TCoords; FRads:TFloats; procedure GridBounds(out B1,B2:Integer; const Val:TFloat; const Hi:Integer); //Computes bounds of neighboring cells in one dimension, with max of Hi public constructor Create(Points:TCoords;GridStep:TFloat;maxX:Integer;maxY:Integer;maxZ:Integer;Rads:TFloats=nil;dummyCreate:Boolean = false); function ListNeighours(C:TCoord):TIntegers; procedure SumAtomIndexes(currentIndex:Integer); function getLoopCount():Integer; procedure ResetAtomCounter(); //Returns all indexes in the 27 grid cells belonging to the neighbourhood //of the cell corresponding to C function IsInnerPoint(C:TCoord):Boolean; //Use only if Rads supplied in create; otherwise points are not kept end; implementation { TGeomHasher } var iix:Integer; procedure TGeomHasher.GridBounds(out B1, B2: Integer; const Val: TFloat; const Hi: Integer); begin B1:=Trunc(Val)-1; B2:=Trunc(Val)+1; if B1>Hi then B1:=Hi; if B1<0 then B1:=0; if B2>Hi then B2:=Hi; if B2<0 then B2:=0; end; {procedure TGeomHasher.PrintTCoords(C:TCoord); begin WriteLn('TCOORDS: '); WriteLn('C[0]',C[0]); WriteLn('C[1]',C[1]); WriteLn('C[2]',C[2]); end;} function TGeomHasher.getLoopCount():Integer; begin Result:= iix; end; procedure TGeomHasher.SumAtomIndexes(currentIndex:Integer); begin iix := iix + currentIndex; end; constructor TGeomHasher.Create(Points:TCoords;GridStep:TFloat;maxX:Integer;maxY:Integer;maxZ:Integer;Rads:TFloats=nil;dummyCreate:Boolean=false); procedure Setup; var minc,maxc:TCoord; begin maxc:=Max(Points); minc:=Min(Points); FShiftToGrid:=Simmetric(minc); // calcular o indice máximo das células em cada eixo do referencial if not dummyCreate then begin FHighX:=Trunc((maxc[0]-minc[0])/GridStep); FHighY:=Trunc((maxc[1]-minc[1])/GridStep); FHighZ:=Trunc((maxc[2]-minc[2])/GridStep); SetLength(FHashGrid,FHighX+1,FHighY+1,FHighZ+1); end else begin FHighX:=maxX; FHighY:=maxY; FHighZ:=maxZ; SetLength(FHashGrid,FHighX+1,FHighY+1,FHighZ+1); end; { WriteLn('FHX',FHighX+1); WriteLn('FHY',FHighY+1); WriteLn('FHZ',FHighZ+1); WriteLn('maxX',maxc[0]); WriteLn('maxY',maxc[1]); WriteLn('maxZ',maxc[2]); WriteLn('minX',minc[0]); WriteLn('minY',minc[1]); WriteLn('minZ',minc[2]); } WriteLn('GridStep',GridStep); // WriteLn('FHGLENGTH',Length(FHashGrid)); if Rads=nil then begin // geomhasher used only for indexing regions FPoints:=nil; FRads:=nil; end else // used to detect collisions, inner points, etc begin Assert(Length(Points)=Length(Rads),'Different number of radii and points'); FPoints:=Copy(Points,0,Length(Points)); FRads:=Copy(Rads,0,Length(Rads)); end; end; var f,x,y,z,i:Integer; c:TCoord; begin inherited Create; //Inicialização do HashGrid Assert(Points<>nil,'Empty points array for hashing'); Assert(GridStep>1e-6,'GridStep too small'); FInvGridStep:=1/GridStep; // Após o setup conhecemos os valores de highx, highy e highz Setup; i:=0; for x:=0 to FHighX do for y:=0 to FHighY do for z:=0 to FHighZ do FHashGrid[x,y,z]:=nil; // número de átomos -1 // Length(Points) adds ao hashgrid // WriteLn('ABCD'); for f:=0 to High(Points) do begin c:=Add(Points[f],FShiftToGrid); x:=Trunc(c[0]*FInvGridStep); y:=Trunc(c[1]*FInvGridStep); z:=Trunc(c[2]*FInvGridStep); AddToArray(f, FHashGrid[x,y,z]); end; end; procedure TGeomHasher.ResetAtomCounter(); begin iix := 0; end; function TGeomHasher.ListNeighours(C:TCoord):TIntegers; var count,x,y,z,x1,x2,y1,y2,z1,z2,f:Integer; begin C:=Multiply(Add(C,FShiftToGrid),FInvGridStep); Result:=nil; GridBounds(x1,x2,C[0],FHighX); GridBounds(y1,y2,C[1],FHighY); GridBounds(z1,z2,C[2],FHighZ); count:=0; for x:=x1 to x2 do for y:=y1 to y2 do for z:=z1 to z2 do count:=count+Length(FHashGrid[x,y,z]); SetLength(Result,count); count:=0; for x:=x1 to x2 do for y:=y1 to y2 do for z:=z1 to z2 do for f:=0 to High(FHashGrid[x,y,z]) do begin Result[count]:=FHashGrid[x,y,z,f]; Inc(count); end; end; function TGeomHasher.IsInnerPoint(C: TCoord): Boolean; var x,y,z,x1,x2,y1,y2,z1,z2,f,ix:Integer; tmpc:TCoord; tmpIndex:Integer; dist:TFloat; begin //{$DEFINE ISPM} tmpc:=Multiply(Add(C,FShiftToGrid),FInvGridStep); Result:=False; GridBounds(x1,x2,tmpc[0],FHighX); GridBounds(y1,y2,tmpc[1],FHighY); GridBounds(z1,z2,tmpc[2],FHighZ); //Substituir os loops por uma chamada do isInnerPoint do marrow {$IFDEF ISPM} //=========Solução Marrow isInnerPoint========================/ // Result:=isInnerPointM(C,FPoints,FRads,length(FPoints)); //=========Solução Original========================/ {$ELSE} tmpIndex := 0; //WriteLn('ABCD'); for x:=0 to FHighX do begin for y:=0 to FHighY do begin for z:=0 to FHighZ do begin for f:=0 to High(FHashGrid[x,y,z]) do begin ix:=FHashGrid[x,y,z,f]; // dist := Distance(C,FPoints[ix]); tmpIndex:= tmpIndex + 1; if dist < FRads[ix] then begin Result:=True; Break; end; end; SumAtomIndexes(tmpIndex); if Result then Break; end; if Result then Break; end; if Result then Break; end; // WriteLn('iix ', getLoopCount()); // ResetAtomCounter(); {$ENDIF} end; end.
unit About; interface uses Windows, SHELLAPI, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, SysUtils; type TWinVersion = ( wvUnknown, wv95, wv98, wv98SE, wvNT, wvME, wv2000, wvXP, wvVista, wv2003, wv7 ); TMemoryStatusEx = record dwLength: DWORD; dwMemoryLoad: DWORD; ullTotalPhys: Int64; ullAvailPhys: Int64; ullTotalPageFile: Int64; ullAvailPageFile: Int64; ullTotalVirtual: Int64; ullAvailVirtual: Int64; ullAvailExtendedVirtual: Int64; end; TAboutBox = class( TForm ) Panel1: TPanel; OKButton: TButton; Panel2: TPanel; ProgramIcon: TImage; PhysMem: TLabel; FreeRes: TLabel; Label1: TLabel; Label2: TLabel; Panel3: TPanel; ProductName: TLabel; Panel4: TPanel; Label6: TLabel; Label3: TLabel; Label4: TLabel; l_site: TLabel; l_mail1: TLabel; l_mail2: TLabel; l_fileVersion: TLabel; procedure ProductNameDblClick( Sender: TObject ); procedure FormClose( Sender: TObject; var Action: TCloseAction ); procedure FormCreate( Sender: TObject ); procedure l_siteClick( Sender: TObject ); procedure l_mail1Click( Sender: TObject ); procedure l_mail2Click( Sender: TObject ); private progName: string; mailTheme: string; function GetTotalRAM: Int64; function GetFreeRAM: Int64; function GetWinVersion: TWinVersion; function GetGlobalMemoryRecord: TMemoryStatusEx; public end; var AboutBox: TAboutBox; implementation uses VerInfo, Config, Procs, RegistryUtil; {$R *.DFM} procedure TAboutBox.FormClose( Sender: TObject; var Action: TCloseAction ); begin Action := caFree; end; procedure TAboutBox.FormCreate( Sender: TObject ); var vInfo: TVerInfoRes; freeRam: byte; version: string; begin PhysMem.Caption := FormatFloat( '#,###" KB"', GetTotalRAM( ) / 1024 ); freeRam := Round( GetFreeRAM( ) / GetTotalRAM( ) * 100 ); FreeRes.Caption := Format( '%d %%', [freeRam] ); vInfo := TVerInfoRes.Create( Application.ExeName ); version := vInfo.ProductVersion; progName := gConfig.fApplicationName; FreeAndNil( vInfo ); l_fileVersion.Caption := 'Версия: ' + version; ProductName.Caption := progName; mailTheme := URLEncodeUTF8( 'Вопрос по программе DSCTool, вариант "' + gConfig.fApplicationName + '", версия ' + version ); end; procedure TAboutBox.l_mail1Click( Sender: TObject ); begin ShellExecute( Handle, 'open', PChar( 'mailto://s-fedotov@yandex.ru?subject=' + mailTheme ), nil, nil, SW_SHOW ); end; procedure TAboutBox.l_mail2Click( Sender: TObject ); begin ShellExecute( Handle, 'open', PChar( 'mailto://yvmos@yandex.ru?subject=' + mailTheme ), nil, nil, SW_SHOW ); end; procedure TAboutBox.l_siteClick( Sender: TObject ); begin ShellExecute( Handle, 'open', PChar( 'http://www.calorimeter.ru' ), nil, nil, SW_SHOW ); end; procedure TAboutBox.ProductNameDblClick( Sender: TObject ); begin MsgBox( gConfig.fProgramDataPath ); end; function TAboutBox.GetWinVersion: TWinVersion; var osVerInfo: TOSVersionInfo; majorVersion, minorVersion: Integer; begin Result := wvUnknown; osVerInfo.dwOSVersionInfoSize := SizeOf( TOSVersionInfo ); if GetVersionEx( osVerInfo ) then begin minorVersion := osVerInfo.dwMinorVersion; majorVersion := osVerInfo.dwMajorVersion; case osVerInfo.dwPlatformId of VER_PLATFORM_WIN32_NT: begin if majorVersion <= 4 then Result := wvNT else if ( majorVersion = 5 ) and ( minorVersion = 0 ) then Result := wv2000 else if ( majorVersion = 5 ) and ( minorVersion = 1 ) then Result := wvXP else if ( majorVersion = 5 ) and ( minorVersion = 2 ) then Result := wv2003 else if ( majorVersion = 6 ) then Result := wvVista else if ( majorVersion = 7 ) then Result := wv7; end; VER_PLATFORM_WIN32_WINDOWS: begin if ( majorVersion = 4 ) and ( minorVersion = 0 ) then Result := wv95 else if ( majorVersion = 4 ) and ( minorVersion = 10 ) then begin if osVerInfo.szCSDVersion[1] = 'A' then Result := wv98SE else Result := wv98; end else if ( majorVersion = 4 ) and ( minorVersion = 90 ) then Result := wvME else Result := wvUnknown; end; end; end; end; function TAboutBox.GetGlobalMemoryRecord: TMemoryStatusEx; type TGlobalMemoryStatusEx = procedure( var lpBuffer: TMemoryStatusEx ); stdcall; var ms: TMemoryStatus; h: THandle; gms: TGlobalMemoryStatusEx; begin Result.dwLength := SizeOf( Result ); if GetWinVersion in [wvUnknown, wv95, wv98, wv98SE, wvNT, wvME] then begin ms.dwLength := SizeOf( ms ); GlobalMemoryStatus( ms ); Result.dwMemoryLoad := ms.dwMemoryLoad; Result.ullTotalPhys := ms.dwTotalPhys; Result.ullAvailPhys := ms.dwAvailPhys; Result.ullTotalPageFile := ms.dwTotalPageFile; Result.ullAvailPageFile := ms.dwAvailPageFile; Result.ullTotalVirtual := ms.dwTotalVirtual; Result.ullAvailVirtual := ms.dwAvailVirtual; end else begin h := LoadLibrary( kernel32 ); try if h <> 0 then begin @gms := GetProcAddress( h, 'GlobalMemoryStatusEx' ); if @gms <> nil then gms( Result ); end; finally FreeLibrary( h ); end; end; end; function TAboutBox.GetTotalRAM: Int64; begin Result := GetGlobalMemoryRecord.ullTotalPhys; end; function TAboutBox.GetFreeRAM: Int64; begin Result := GetGlobalMemoryRecord.ullAvailPhys; end; end.
unit Classe.Cotacao; interface uses System.Generics.Collections; type (* { "status": "ok", "name": "Market Price (USD)", "unit": "USD", "period": "day", "description": "Average USD market price across major bitcoin exchanges.", "values": [{ "x": 1499990400, "y": 2190.947833333333 } ]} } *) TValor = class private Fx: Int64; Fy: Double; public property x: Int64 read Fx write Fx; property y: Double read Fy write Fy; end; TCotacao = class private FStatus: string; Fname: string; FUnit: string; Fperiod: string; Fdescription: string; Fvalues: TArray<TValor>; public property status: string read Fstatus write Fstatus; property name: string read Fname write Fname; property &unit: string read FUnit write FUnit; property period: string read Fperiod write Fperiod; property description: string read Fdescription write Fdescription; property values: TArray<TValor> read Fvalues write Fvalues; end; implementation end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost:8888/wsdl/ILoginWS // Encoding : utf-8 // Version : 1.0 // (3/30/2012 11:44:36 AM - 1.33.2.5) // ************************************************************************ // unit ILoginProxy; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" // !:boolean - "http://www.w3.org/2001/XMLSchema" TUserInfo = class; { "urn:LoginWSIntf" } TAuthHeader = class; { "urn:CommunicationObj"[H] } // ************************************************************************ // // Namespace : urn:LoginWSIntf // ************************************************************************ // TUserInfo = class(TRemotable) private FName: WideString; FLevel: Integer; published property Name: WideString read FName write FName; property Level: Integer read FLevel write FLevel; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TAuthHeader = class(TSOAPHeader) private FUserName: WideString; FToken: WideString; FLevel: Integer; published property UserName: WideString read FUserName write FUserName; property Token: WideString read FToken write FToken; property Level: Integer read FLevel write FLevel; end; // ************************************************************************ // // Namespace : urn:LoginWSIntf-ILoginWS // soapAction: |urn:LoginWSIntf-ILoginWS#Borrar_Usuario|urn:LoginWSIntf-ILoginWS#Get_ControllerLevel|urn:LoginWSIntf-ILoginWS#Get_ControllerName|urn:LoginWSIntf-ILoginWS#Get_InControl|urn:LoginWSIntf-ILoginWS#Get_Usuarios|urn:LoginWSIntf-ILoginWS#Login|urn:LoginWSIntf-ILoginWS#Logout|urn:LoginWSIntf-ILoginWS#Modificar|urn:LoginWSIntf-ILoginWS#Nuevo_Usuario|urn:LoginWSIntf-ILoginWS#ReleaseControl|urn:LoginWSIntf-ILoginWS#TakeControl|urn:LoginWSIntf-ILoginWS#Usuario // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : ILoginWSbinding // service : ILoginWSservice // port : ILoginWSPort // URL : http://localhost:8888/soap/ILoginWS // ************************************************************************ // ILoginWS = interface(IInvokable) ['{C0A84F6E-0F00-7E2F-073F-5071C9041728}'] function Borrar_Usuario(const Name: WideString): Boolean; stdcall; function Get_ControllerLevel: Integer; stdcall; function Get_ControllerName: WideString; stdcall; function Get_InControl: Boolean; stdcall; function Get_Usuarios: Integer; stdcall; function Login(const UserName: WideString; const Password: WideString): Boolean; stdcall; function Logout: Boolean; stdcall; function Modificar(const Name: WideString; const Password: WideString; const Level: Integer): Boolean; stdcall; function Nuevo_Usuario(const Name: WideString; const Password: WideString; const Level: Integer): Boolean; stdcall; function ReleaseControl: Boolean; stdcall; function TakeControl: Boolean; stdcall; function Usuario(const Index: Integer): TUserInfo; stdcall; end; function GetILoginWS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ILoginWS; implementation function GetILoginWS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ILoginWS; const defWSDL = 'http://localhost:8888/wsdl/ILoginWS'; defURL = 'http://localhost:8888/soap/ILoginWS'; defSvc = 'ILoginWSservice'; defPrt = 'ILoginWSPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as ILoginWS); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(ILoginWS), 'urn:LoginWSIntf-ILoginWS', 'utf-8'); InvRegistry.RegisterAllSOAPActions(TypeInfo(ILoginWS), '|urn:LoginWSIntf-ILoginWS#Borrar_Usuario' +'|urn:LoginWSIntf-ILoginWS#Get_ControllerLevel' +'|urn:LoginWSIntf-ILoginWS#Get_ControllerName' +'|urn:LoginWSIntf-ILoginWS#Get_InControl' +'|urn:LoginWSIntf-ILoginWS#Get_Usuarios' +'|urn:LoginWSIntf-ILoginWS#Login' +'|urn:LoginWSIntf-ILoginWS#Logout' +'|urn:LoginWSIntf-ILoginWS#Modificar' +'|urn:LoginWSIntf-ILoginWS#Nuevo_Usuario' +'|urn:LoginWSIntf-ILoginWS#ReleaseControl' +'|urn:LoginWSIntf-ILoginWS#TakeControl' +'|urn:LoginWSIntf-ILoginWS#Usuario' ); InvRegistry.RegisterHeaderClass(TypeInfo(ILoginWS), TAuthHeader, 'TAuthHeader', 'urn:CommunicationObj'); RemClassRegistry.RegisterXSClass(TUserInfo, 'urn:LoginWSIntf', 'TUserInfo'); RemClassRegistry.RegisterXSClass(TAuthHeader, 'urn:CommunicationObj', 'TAuthHeader'); end.
/////////////////////////////////////////////////////////////////////////////// // // // Function to draw color slanted stripes in cell on canvas // // and place text over them with default canvas settings // // Returns SVG presentation of the cell // // // // Simple to see and interesting to get it working and test // // // // Free for commercial and non-commercial use // // // // Designed by Oleg Mitin, 1998 - 2017 // // https://github.com/omitindelphi // // // /////////////////////////////////////////////////////////////////////////////// unit ClrBand; interface uses Classes,Windows,Graphics ,Variants ,Types ,SysUtils ,StrUtils ,Spring ,Spring.Collections ,Xml.VerySimple ; function ColorBandsOfListMovable( Canvas:TCanvas; Rect:TRect; ColorList: IList<TColor> ; BandWidth, BandShift:integer; Text:string): string; implementation uses UITypes; type GraphicStorage = record PenStyle: TPenStyle; PenColor: TColor; PenWidth: integer; PenMode: TPenMode; BrushColor: TColor; BrushStyle: TBrushStyle; end; TLocalCellDescriptor = record Text:string; Rect: TRect; RectNoBorders: TRect; Colors: IList<TColor>; BandWidth: integer; Bandshift: integer; Canvas: TCanvas; R: TRect; end; TParallelogram = record public function BandWidth: integer; // function Edges: TQuattroEdges; case Integer of 0: (Vertexes: array[0..3] of TPoint); 1: ( // A point of top left , clockwise A: TPoint; B: TPoint; C: TPoint; D: Tpoint; ); 2: ( xa: integer; ya: integer; xb: integer; yb: integer; xc: integer; yc: integer; xd: integer; yd: integer ); end; TpointArray = TArray<Tpoint>; TVertexesCase = record Vertexes: TpointArray; PolygonCase: integer; end; SerializablePolygon = interface ['{BF18BFBB-53D5-431B-94F6-A40C6EF4132E}'] function SerializeAsSVGFragment: string; procedure Draw( Canvas: TCanvas); end; TCrossGeneratorFunction = function( Cell: TRect; Band: TParallelogram):TVertexesCase of object; TCanvasPolygon = class( TInterfacedObject, SerializablePolygon) private VertexesCase: TVertexesCase; ColorFill: Tcolor; FVertexPopulatorHolder: TCrossGeneratorFunction; function PolygonCase: integer; // we have 16 different configurations; and we must be sure that no configuration went untested, or ever unused class function SelectorOfIntersectionCase(Cell:TRect; Band: TParallelogram): TCrossGeneratorFunction; class function GenerateVertexCase01(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase02(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase03(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase04(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase05(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase06(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase07(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase08(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase09(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase10(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase11(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase12(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase13(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase14(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase15(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase16(Cell:TRect; Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase17(Cell: TRect;Band: Tparallelogram): TVertexesCase; class function GenerateVertexCase18(Cell: TRect;Band: Tparallelogram): TVertexesCase; class function NoVertexCase(Cell: TRect;Band: Tparallelogram): TVertexesCase; public constructor CreateAsCellToCrossParallelogram(Cell:TRect; Band: TParallelogram; ColorFill: TColor); constructor CreateAsSingleColorRect(Cell: TRect; ColorToFill: Tcolor); function SerializeAsSVGFragment: string; procedure Draw(Canvas : TCanvas); end; TCanvasPolygonInsider = class helper for TCanvasPolygon function SerializeVortexes: string; function SerializeFillStyle: string; function SerializePolygonKind: string; end; TCellInsider = class private class function ColorToRGBString( Color: TColor): string; static; class function SVGTagWrap( SVGFragment: string; Rect: TRect): string; static; class function PolygonFragmentToSVG( TextRectCanvas: TLocalCellDescriptor; PolygonFragmentSVG: string): string; static; class function StoreCanvasPenBrush( Canvas: TCanvas): GraphicStorage; static; class procedure RestoreCanvasPenBrush( Storage: GraphicStorage; Canvas: TCanvas); class function TextToSVGFragment( TextRectCanvas: TLocalCellDescriptor): string; static; class function GetDefaultFontName: string; static; class function NormalizeBandWidth( BandWidth: integer): integer; static; class function NormalizeBandshift( CellDescriptor: TLocalCellDescriptor): integer; static; class function DrawSingleCellForSingleColor( CellDescriptor: TLocalCellDescriptor): string; static; class procedure ClearCellCanvas( CellDescriptor: TLocalCellDescriptor); static; class function InitializeXIterator( CellDescriptor: TlocalCelldescriptor): integer; static; class function PopulateWorkingRectWithClippedBorder( OriginalCell: TRect): TRect; static; class function PopulateParallelogram( XIterator: integer; R: TRect; CellDescriptor: TLocalCellDescriptor): TParallelogram; static; class function PopulateCellDescriptor( Canvas: TCanvas; Rect: TRect; ColorList: IList<TColor>; BandWidth, BandShift: integer; Text: string): TLocalCellDescriptor; static; class procedure PlaceTextToCellCanvas( CellDescriptor: TLocalCellDescriptor); static; end; IStripGenerator = interface ['{3667D8D4-B437-4699-BFAB-7817E8CF86C0}'] function DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; end; IStripGeneratorFactory = interface ['{00C49844-7218-46A1-A882-ED58E919F2B3}'] function CreateStripGenerator( CellDescriptor: TLocalCellDescriptor): IStripGenerator; end; TStripGenerator = class(TInterfacedObject, IStripGenerator) protected function DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; virtual; abstract; end; TSingleColorStripGenerator = class( TStripGenerator) protected function DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; override; end; TMultiColorStripGenerator = class(TStripGenerator) protected function DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; override; end; TStripGeneratorFactory = class(TinterfacedObject, IStripGeneratorFactory) private function CreateStripGenerator( CellDescriptor: TLocalCellDescriptor): IStripGenerator; end; {TStripGeneratorFactory } function TStripGeneratorFactory.CreateStripGenerator( CellDescriptor: TLocalCellDescriptor): IStripGenerator; begin if CellDescriptor.Colors.Count <= 1 then begin Result := TSingleColorStripGenerator.Create; end else begin Result := TMultiColorStripGenerator.Create; end; end; { TSingleColorStripGenerator } function TSingleColorStripGenerator.DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; var LocalDesc: TLocalCellDescriptor; begin LocalDesc := CellDescriptor; if LocalDesc.Colors.Count = 0 then LocalDesc.Colors.Add(clWindow); Result := TCellInsider.DrawSingleCellForSingleColor(LocalDesc); end; { TMultiColorStripGenerator } function TMultiColorStripGenerator.DrawStripsAndReturnSVG( CellDescriptor: TLocalCellDescriptor): string; var ColorIterator: integer; XIterator: integer; Band: TParallelogram; Polygon: SerializablePolygon; begin Result := ''; ColorIterator := -1; XIterator := TCellInsider.InitializeXIterator( CellDescriptor ); begin while xIterator < CellDescriptor.RectNoBorders.Width + CellDescriptor.RectNoBorders.Height do begin XIterator := XIterator + CellDescriptor.BandWidth; ColorIterator := ColorIterator + 1; Band := TCellInsider.PopulateParallelogram( XIterator, CellDescriptor.RectNoBorders, CellDescriptor); Polygon := TCanvasPolygon.CreateAsCellToCrossParallelogram( CellDescriptor.RectNoBorders, Band, CellDescriptor.Colors[ColorIterator mod CellDescriptor.Colors.Count] ); Polygon.Draw(CellDescriptor.Canvas); Result := Result + Polygon.SerializeAsSVGFragment(); Polygon := nil; end; end; TCellInsider.PlaceTextToCellCanvas( CellDescriptor); Result := TCellInsider.PolygonFragmentToSVG( CellDescriptor, Result); end; { TCanvasPolygon } function TCanvasPolygon.PolygonCase: integer; begin Result := VertexesCase.PolygonCase; end; class function TCanvasPolygon.SelectorOfIntersectionCase( Cell:TRect; Band: TParallelogram): TCrossGeneratorFunction; var R: Trect; begin R := Cell; Result := NoVertexCase; // no cross between Cell and parallelogram with Band do begin if (band.xa <= Cell.Left) and (Band.xb <= Cell.Left) and (Band.xc <= Cell.Right) and (Band.xd <= Cell.Left) and (Band.xc > Cell.Left) then // Triangle :1 bottom left begin Result := GenerateVertexCase01; Exit; end; if (xa <= R.Left) and (xb <= R.Left) and (xc > R.Left) and (xc <= R.Right) and (xd> R.Left) then // 4-angle :2 begin Result := GenerateVertexCase02; Exit; end; if (xa <= R.Left)and(xb <= R.Left)and(xc > R.Right)and(xd <= R.Left) then // 4-angle :3 begin Result := GenerateVertexCase03; Exit; end; if (xa <= R.Left) and (xb<= R.Left) and (xc> R.Right) and (xd> R.Left) and (xd<= R.Right) then // Right Bottom 5-angle; :4 begin Result := GenerateVertexCase04; Exit; end; if (xb <= R.left) and ( xd > R.right) then // 4-angle :5 begin Result := GenerateVertexCase05; Exit; end; if (xa <= R.Left) and ( xb > R.Left) and (xb <= R.Right )and (xd > R.Right) then // 5-angle :6 begin Result := GenerateVertexCase06; Exit; end; if (xa > R.left) and (xc <= R.Right) then // 4-angle : 7 begin Result := GenerateVertexCase07; Exit; end; if (xa > R.Left) and (xb <= R.Right) and(xd <= R.Right) and (xc > R.Right) then // 5-angle :8 begin Result := GenerateVertexCase08; Exit; end; if (xa > R.Left) and (xb <= R.Right) and (xd > R.Right) then // 4-angle :9 begin Result := GenerateVertexCase09; Exit; end; if (xa > R.Left) and (xa <= R.Right) and (xb > R.Right) and (xd > R.Right) and (xc > R.Right) then // 3-angle :10 top right begin Result := GenerateVertexCase10; Exit; end; if (xa <= R.Left) and (xb > R.Left) and ( xd > R.Left) and (xd <= R.Right) and (xc > R.Left) and (xc<=R.right) then // 5-angle : 11 begin Result := GenerateVertexCase11; Exit; end; if (xa <= R.Left) and (xb > R.Left) and (xd <= R.Left) and (xc <= R.Right) then // 4-angle :12 begin Result := GenerateVertexCase12; Exit; end; if (xa <= R.Right) and (xa > R.Left) and (Xb > R.Right) and (xd <= R.Right) then // 4-angle :13 begin Result := GenerateVertexCase13; Exit; end; if (xa <= R.Left) and (xb > R.Left) and (Xb <= R.Right) and (xd <= R.Right) and (xc > R.Right) and (xd > R.Left)then // 6-angle :14 begin Result := GenerateVertexCase14; Exit; end; if (xd <= R.Left) and (xb > R.Right) then // 4-angle Rect :15 begin Result := GenerateVertexCase15; Exit; end; if (xa <= R.Left) and (xb >= R.Right) and (xd > R.Right) then // 4-angle : 16 begin Result := GenerateVertexCase16; Exit; end; if (xa <= R.Left) and (xb > R.Left) and (Xb <= R.Right) and (xd <= R.Right) and (xc > R.Right) and (xd <= R.Left) then // 5-angle :17 begin Result := GenerateVertexCase17; Exit; end; if (xa <= R.left)and( xb >= R.right) and (xd <= R.Right) then // 5-angle : 18 begin Result := GenerateVertexCase18; Exit; end; end; end; constructor TCanvasPolygon.CreateAsSingleColorRect( Cell:TRect; ColorToFill:TColor); begin // if only one color to fill then we draw full cell box in single color inherited Create; Self.VertexesCase.PolygonCase := 0; SetLength(Self.VertexesCase.Vertexes, 4); Self.VertexesCase.Vertexes[0].X:= Cell.Left; Self.VertexesCase.Vertexes[0].Y:= Cell.Bottom; Self.VertexesCase.Vertexes[1].X:= Cell.Left; Self.VertexesCase.Vertexes[1].Y:= Cell.Top; Self.VertexesCase.Vertexes[2].X:= Cell.Right; Self.VertexesCase.Vertexes[2].Y:= Cell.Top; Self.VertexesCase.Vertexes[3].X:= Cell.Right; Self.VertexesCase.Vertexes[3].Y:= Cell.Bottom; Self.ColorFill := ColorToFill; end; class function TCanvasPolygon.GenerateVertexCase01( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; begin // |\ Result.PolygonCase := 1; // | | iterator := Band.xd - Cell.Left; // | \ SetLength(Result.Vertexes, 3); // | \ Result.Vertexes[0].X:= Cell.Left; Result.Vertexes[0].Y:= Cell.Bottom; // |____\ Result.Vertexes[1].X:= Cell.Left; Result.Vertexes[1].Y:= Cell.Bottom - iterator - Band.BandWidth; Result.Vertexes[2].X:= Cell.Left + iterator + band.BandWidth; Result.Vertexes[2].Y:= Cell.Bottom; end; class function TCanvasPolygon.GenerateVertexCase02( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; // | begin // |\ Result.PolygonCase := 2; // | \ iterator := Band.xd - Cell.Left; // | \ R := Cell; // \ \ with Band do // \ \ begin // \___\ SetLength(Result.Vertexes, 4); // Result.Vertexes[0].X:=xd; Result.Vertexes[0].Y:=R.Bottom; Result.Vertexes[1].X:=R.Left; Result.Vertexes[1].Y:=R.Bottom-iterator; Result.Vertexes[2].X:=R.Left; Result.Vertexes[2].Y:=R.Bottom-iterator-BandWidth; Result.Vertexes[3].X:=xc; Result.Vertexes[3].Y:=R.Bottom; end; end; class function TCanvasPolygon.GenerateVertexCase03( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; // R: TRect; // . begin // |\ Result.PolygonCase := 3; // | \ iterator := Band.xd - Cell.Left; // | \ R := Cell; // | \ with Band do // | \ begin // |____| SetLength(Result.Vertexes, 4); Result.Vertexes[0].X:= R.Left; Result.Vertexes[0].Y:= R.Bottom; Result.Vertexes[1].X:= R.Left; Result.Vertexes[1].Y:= R.Bottom - iterator - BandWidth; Result.Vertexes[2].X:= R.Right; Result.Vertexes[2].Y:= R.Bottom - iterator - BandWidth + Cell.Width; Result.Vertexes[3].X:= R.Right; Result.Vertexes[3].Y:= R.Bottom; end end; class function TCanvasPolygon.GenerateVertexCase04( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; begin Result.PolygonCase := 4; // | iterator := Band.xd - Cell.Left; // |\ R := Cell; // | \ with Band do // \ \ begin // \__| Setlength(Result.Vertexes,5); Result.Vertexes[0].X:=xd; Result.Vertexes[0].Y:= R.Bottom; Result.Vertexes[1].X:= R.Left; Result.Vertexes[1].Y:= R.Bottom - iterator; Result.Vertexes[2].X:= R.Left; Result.Vertexes[2].Y:= R.Bottom - iterator - BandWidth; Result.Vertexes[3].X:= R.Right; Result.Vertexes[3].Y := R.Bottom - (xc - R.Right); Result.Vertexes[4]:=Point(R.Right, R.Bottom); end end; class function TCanvasPolygon.GenerateVertexCase05( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; begin // | Result.PolygonCase := 5; // |\ iterator := Band.xd - Cell.Left; // | \ R := Cell; // \ | with Band do // \ | begin // \| Setlength(Result.Vertexes,4); // | Result.Vertexes[0].x:=R.left; Result.Vertexes[0].y:=R.bottom - iterator; Result.Vertexes[1].x:=R.left; Result.Vertexes[1].y:=R.bottom - iterator - BandWidth; Result.Vertexes[2].x:=R.right; Result.Vertexes[2].y:=R.bottom - iterator + Cell.Width - BandWidth; Result.Vertexes[3].x:=R.right; Result.Vertexes[3].y:=R.bottom - iterator + Cell.Width; end; end; class function TCanvasPolygon.GenerateVertexCase06( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; // _ begin // | \ Result.PolygonCase := 6; // | | R := Cell; // \ | with Band do // \| begin // | SetLength(Result.Vertexes,5); Result.Vertexes[0].X:=R.Right; Result.Vertexes[0].Y:= R.Bottom - (xd - R.Right); Result.Vertexes[1].X:= R.Left; Result.Vertexes[1].Y:=R.Top + (R.Left - xa); Result.Vertexes[2]:=Point(R.Left,R.Top); Result.Vertexes[3].X:=xb; Result.Vertexes[3].Y:= R.Top; Result.Vertexes[4].X:=R.Right; Result.Vertexes[4].Y:=R.Top + (R.Right - xb); end; end; class function TCanvasPolygon.GenerateVertexCase07( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; // ____ begin // \ \ Result.PolygonCase := 7; // \ \ R := Cell; // \ \ with Band do // \ \ begin // \___\ SetLength(Result.Vertexes,4); Result.Vertexes[0].x := xd; Result.Vertexes[0].y := R.bottom; Result.Vertexes[1].x := xa; Result.Vertexes[1].y := R.top; Result.Vertexes[2].x := xb; Result.Vertexes[2].y := R.Top; Result.Vertexes[3].x := xc; Result.Vertexes[3].y := R.Bottom; end; end; class function TCanvasPolygon.GenerateVertexCase08( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; // R: TRect; // begin // _____ Result.PolygonCase := 8; // \ \ iterator := Band.xd - Cell.Left; // \ \ R := Cell; // \ | with Band do // \___| begin SetLength(Result.Vertexes,5); Result.Vertexes[0].X := xd; Result.Vertexes[0].Y := R.Bottom; Result.Vertexes[1].X := xa; Result.Vertexes[1].Y := R.Top; Result.Vertexes[2].X := xb; Result.Vertexes[2].Y := R.Top; Result.Vertexes[3].X := R.Right; Result.Vertexes[3].Y := R.Bottom-(iterator-Cell.Width)-BandWidth; Result.Vertexes[4]:=Point(R.Right,R.Bottom); end; end; class function TCanvasPolygon.GenerateVertexCase09( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; // ____ R: TRect; // \ \ begin // \ \ Result.PolygonCase := 9; // \ | iterator := Band.xd - Cell.Left; // \ | R := Cell; // \ | with Band do // \| begin // | SetLength(Result.Vertexes,4); Result.Vertexes[0].X := R.Right; Result.Vertexes[0].Y := R.Bottom - iterator + Cell.Width; Result.Vertexes[1].X := xa; Result.Vertexes[1].Y := R.Top; Result.Vertexes[2].X := xb; Result.Vertexes[2].Y := R.Top; Result.Vertexes[3].X := R.Right; Result.Vertexes[3].Y := R.Bottom - (iterator - Cell.Width) - BandWidth; end; end; class function TCanvasPolygon.GenerateVertexCase10( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; begin Result.PolygonCase := 10; // ____ iterator := Band.xd - Cell.Left; // \ | R := Cell; // \ | with Band do // \ | begin // \| SetLength(Result.Vertexes,3); // | Result.Vertexes[0].X := R.Right; Result.Vertexes[0].Y := R.Bottom - iterator + Cell.Width; Result.Vertexes[1].X :=xa; Result.Vertexes[1].Y := R.Top; Result.Vertexes[2] := Point(R.Right,R.Top); end; end; class function TCanvasPolygon.GenerateVertexCase11( Cell:TRect; Band: Tparallelogram): TVertexesCase; var // ____ R: TRect; // | \ begin // | \ Result.PolygonCase := 11; // \ \ R := Cell; // \_____\ with Band do // begin // SetLength(Result.Vertexes,5); Result.Vertexes[0].x :=xd; Result.Vertexes[0].y := R.bottom; Result.Vertexes[1].x :=R.Left; Result.Vertexes[1].y := R.top + (R.Left - xa); Result.Vertexes[2].x :=R.Left; Result.Vertexes[2].y := R.Top; Result.Vertexes[3].x :=xb; Result.Vertexes[3].y := R.Top; Result.Vertexes[4].x :=xc; Result.Vertexes[4].y := R.Bottom; end; end; class function TCanvasPolygon.GenerateVertexCase12( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; // ____ begin // | \ Result.PolygonCase := 12; // | \ R := Cell; // |______\ with Band do begin Setlength(Result.Vertexes,4); Result.Vertexes[0] := Point(R.Left,R.Bottom); Result.Vertexes[1] := Point(R.Left,R.Top); Result.Vertexes[2] := Point(Xb,R.Top); Result.Vertexes[3] := Point(Xc,R.Bottom); end; end; class function TCanvasPolygon.GenerateVertexCase13( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; // ________ begin // \ | Result.PolygonCase := 13; // \ | R := Cell; // \ | with Band do // \____| begin // SetLength(Result.Vertexes,4); Result.Vertexes[0] := Point(Xd,R.Bottom); Result.Vertexes[1] := Point(Xa,R.Top); Result.Vertexes[2] := Point(R.Right,R.Top); Result.Vertexes[3] := Point(R.Right,R.Bottom); end; end; class function TCanvasPolygon.GenerateVertexCase14( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; begin Result.PolygonCase := 14; R := Cell; with Band do begin // __ Setlength(Result.Vertexes,6); // | \ Result.Vertexes[0] := Point(R.Left, R.Top + (R.Left - xa) ); // | \ Result.Vertexes[1] := Point(R.Left,R.Top); // \ \ Result.Vertexes[2] := Point(Xb,R.Top); // \ | Result.Vertexes[3] := Point(R.Right, R.Top + (R.Right - xb) );// \__| Result.Vertexes[4] := Point(R.Right,R.Bottom); Result.Vertexes[5] := Point(xd, R.Bottom); end; end; class function TCanvasPolygon.GenerateVertexCase15( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; begin Result.PolygonCase := 15; R := Cell; with Band do begin SetLength(Result.Vertexes,4); Result.Vertexes[0]:=Point(R.Left,R.Bottom); // ______ Result.Vertexes[1]:=Point(R.Left,R.Top); // | | Result.Vertexes[2]:=Point(R.Right,R.Top); // | | Result.Vertexes[3]:=Point(R.Right,R.Bottom); // |______| end; end; class function TCanvasPolygon.GenerateVertexCase16( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; // ___ begin // | | Result.PolygonCase := 16; // | | iterator := Band.xd - Cell.Left; // \ | R := Cell; // \ | with Band do // \| begin // | SetLength(Result.Vertexes,4); Result.Vertexes[0].x:=R.left; Result.Vertexes[0].y:=R.bottom - iterator; Result.Vertexes[1].x:=R.left; Result.Vertexes[1].y:=R.top; Result.Vertexes[2].x:=R.right; Result.Vertexes[2].y:=R.top; Result.Vertexes[3].x:=R.right; Result.Vertexes[3].y:=R.bottom - iterator + Cell.Width; end; end; class function TCanvasPolygon.GenerateVertexCase17( Cell:TRect; Band: Tparallelogram): TVertexesCase; var R: TRect; begin Result.PolygonCase := 17; R := Cell; with Band do begin // __ Setlength(Result.Vertexes,5); // | \ Result.Vertexes[0] := Point(R.Left,R.Bottom); // | \ Result.Vertexes[1] := Point(R.Left,R.Top); // | \ Result.Vertexes[2] := Point(Xb,R.Top); // | | Result.Vertexes[3] := Point(R.Right, R.Top + (R.Right - xb) );// |_____| Result.Vertexes[4] := Point(R.Right,R.Bottom); end; end; class function TCanvasPolygon.GenerateVertexCase18( Cell:TRect; Band: Tparallelogram): TVertexesCase; var iterator: integer; R: TRect; // ___ begin // | | Result.PolygonCase := 18; // | | iterator := Band.xd - Cell.Left; // \ | R := Cell; // \_| with Band do begin SetLength(Result.Vertexes,5); Result.Vertexes[0].x := R.left; Result.Vertexes[0].y :=R.bottom - iterator; Result.Vertexes[1].x := R.left; Result.Vertexes[1].y :=R.top; Result.Vertexes[2].x := R.right; Result.Vertexes[2].y :=R.top; Result.Vertexes[3].x := R.right; Result.Vertexes[3].y :=R.bottom; Result.Vertexes[4].x := Band.xd; Result.Vertexes[4].y := R.bottom; end; end; class function TCanvasPolygon.NoVertexCase(Cell: TRect; Band: Tparallelogram): TVertexesCase; begin Result.PolygonCase := -1; Setlength(Result.Vertexes, 0); end; constructor TCanvasPolygon.CreateAsCellToCrossParallelogram( Cell:TRect; Band: TParallelogram; ColorFill: TColor); begin inherited Create; FVertexPopulatorHolder := SelectorOfIntersectionCase( Cell, Band); if Assigned(FVertexPopulatorHolder) then begin Self.VertexesCase := FVertexPopulatorHolder( Cell,Band); Self.ColorFill := ColorFill; end; end; procedure TCanvasPolygon.Draw( Canvas: TCanvas); begin if Assigned(Canvas) then Canvas.Brush.Color := clWindow; if Length(VertexesCase.Vertexes) > 0 then begin Canvas.Pen.Mode := pmCopy; Canvas.Pen.Style := psSolid; Canvas.Pen.Color := Self.ColorFill; Canvas.Pen.Width := 1; Canvas.Brush.Color := Self.ColorFill; Canvas.Brush.Style := bsSolid; Canvas.Polygon(VertexesCase.Vertexes); end; end; function TCanvasPolygon.SerializeAsSVGFragment: string; begin // Example: <polygon points="200,10 250,190 160,210" style="stroke:none;fill:rgb(0,255,0)" /> Result := ''; if Length(VertexesCase.Vertexes) > 0 then begin Result := '<polygon points=' + SerializeVortexes(); Result := Result + ' ' + SerializeFillStyle(); Result := Result + ' />'; Result := Result + SerializePolygonKind(); end; end; { TCanvasPolygonInsider } function TCanvasPolygonInsider.SerializeVortexes: string; var kVortex: TPoint; begin //Example as comma-pair, separated by space: "200,10 250,190 160,210" for kVortex in VertexesCase.Vertexes do Result := Result + Format('%d,%d ', [kVortex.X, kVortex.Y]); Result := AnsiLeftStr(Result, Length(Result) - 1); Result := AnsiQuotedStr(Result, '"'); end; function TCanvasPolygonInsider.SerializeFillStyle: string; begin Result := ' ' + Format('style="fill: %s;"', [ TCellInsider.ColorToRGBString(Self.ColorFill) ]); end; function TCanvasPolygonInsider.SerializePolygonKind: string; begin Result := Char(13) + char(10) + Format('<!-- Polygon variation Case %d -->'+#13+#10,[PolygonCase()]); end; { TCellInsider } class function TCellInsider.TextToSVGFragment(TextRectCanvas: TLocalCellDescriptor): string; // Example: <text x="10" y="40" // style="font-family: Times New Roman; // font-size: 44px; stroke: #00ff00; fill: #0000ff;"> // SVG text styling // </text> var FontName: string; FontSize: integer; FontColor: TColor; begin if Assigned(TextRectCanvas.Canvas) then begin FontName := TextRectCanvas.Canvas.Font.Name; FontSize := TextRectCanvas.Canvas.Font.Size; FontColor := TextRectCanvas.Canvas.Font.Color; end else begin FontName := TCellInsider.GetDefaultFontName; FontSize := 10; FontColor := clBlack; end; Result := Format('<text x="%d" y="%d" style="font-family: %s; font-size: %dpx; fill: %s;">', [ TextRectCanvas.Rect.Left + 1, TextRectCanvas.Rect.Top + 1 + FontSize, FontName, FontSize, ColorToRGBString(FontColor) ]) + TXmlVerySimple.Escape(TextRectCanvas.Text) +'</text>'; end; class function TCellInsider.SVGTagWrap( SVGFragment: string; Rect: TRect): string; begin //Example: <svg height="30" width="200"> ... </svg> Result := Format('<svg version="1.1" baseProfile="full" ' + 'height="%d" width="%d" xmlns="http://www.w3.org/2000/svg">' , [Rect.Height,Rect.Width]) + #13#10 + SVGFragment + #13#10 +'</svg>'+ #13#10; end; class procedure TCellInsider.ClearCellCanvas( CellDescriptor: TLocalCellDescriptor); begin if Assigned(CellDescriptor.Canvas) then begin CellDescriptor.Canvas.Brush.Color:=clwindow; CellDescriptor.Canvas.Brush.Style := bsSolid; CellDescriptor.Canvas.FillRect(CellDescriptor.Rect); end; end; class function TCellInsider.ColorToRGBString( Color: TColor): string; begin Result := Format('rgb(%d ,%d, %d)', [getRValue(Color), getGValue(Color), getBValue(Color) ]); end; class function TCellInsider.StoreCanvasPenBrush( Canvas: TCanvas): GraphicStorage; begin Result.PenStyle := Canvas.Pen.Style; Result.PenColor := Canvas.Pen.Color; Result.PenWidth := Canvas.Pen.Width; Result.BrushColor := canvas.Brush.Color; Result.BrushStyle := Canvas.Brush.Style; end; class procedure TCellInsider.RestoreCanvasPenBrush( Storage: GraphicStorage; Canvas: TCanvas); begin Canvas.Pen.Style := Storage.PenStyle; Canvas.Pen.Color := Storage.PenColor; Canvas.Pen.Width := Storage.PenWidth; Canvas.Brush.Color := Storage.BrushColor; Canvas.Brush.Style := Storage.BrushStyle ; end; class function TCellInsider.DrawSingleCellForSingleColor( CellDescriptor: TLocalCellDescriptor): string; var Polygon: SerializablePolygon; begin Polygon := TCanvasPolygon.CreateAsSingleColorRect( CellDescriptor.Rect,CellDescriptor.Colors.Items[0]); Polygon.Draw(CellDescriptor.Canvas); CellDescriptor.Canvas.TextRect(CellDescriptor.Rect, CellDescriptor.Rect.Left+1, CellDescriptor.Rect.Top+1, CellDescriptor.Text); Result := Polygon.SerializeAsSVGFragment(); Result := TCellInsider.PolygonFragmentToSVG( CellDescriptor, Result); end; class function TCellInsider.GetDefaultFontName: string; var B: TBitmap; begin B := TBitmap.Create; try B.Height := 10; B.Width := 10; Result := B.Canvas.Font.Name; finally B.Free; end; end; class function TCellInsider.NormalizeBandshift( CellDescriptor: TLocalCellDescriptor): integer; begin if CellDescriptor.Colors.Count = 0 then Result := 0 else Result := CellDescriptor.BandShift mod ( CellDescriptor.Colors.Count * Abs(CellDescriptor.BandWidth)); end; class function TCellInsider.NormalizeBandWidth( BandWidth: integer): integer; begin Result := Abs(BandWidth); if Result <= 2 then Result := 2; end; class function TCellInsider.PopulateWorkingRectWithClippedBorder( OriginalCell:TRect): TRect; begin Result := OriginalCell; Result.Left := Result.Left+1; Result.Right := Result.Right-1; Result.Bottom:=Result.Bottom-1; end; class function TCellInsider.InitializeXIterator( CellDescriptor: TlocalCelldescriptor): integer; begin Result:= -(CellDescriptor.Bandwidth * CellDescriptor.Colors.Count) - CellDescriptor.BandShift ; while Result > -(CellDescriptor.Bandwidth * CellDescriptor.Colors.Count) do Result:= Result - (CellDescriptor.Bandwidth * CellDescriptor.Colors.Count); end; class function TCellInsider.PopulateCellDescriptor( Canvas:TCanvas; Rect:TRect; ColorList: IList<TColor> ; BandWidth, BandShift:integer; Text:string): TLocalCellDescriptor; begin Result.Canvas := Canvas; Result.Text := Text; Result.Rect := Rect; Result.RectNoBorders := TCellInsider.PopulateWorkingRectWithClippedBorder(Rect); Result.Colors := ColorList; Result.BandWidth := TCellInsider.NormalizeBandWidth( BandWidth); Result.BandShift := BandShift; Result.BandShift := TCellInsider.NormalizeBandshift( Result); end; class function TCellInsider.PopulateParallelogram( XIterator: integer; R:TRect; CellDescriptor: TLocalCellDescriptor): TParallelogram; var xa,xb,xc,xd: integer; begin xa:= R.Left + XIterator - R.Height; xb:=xa + CellDescriptor.BandWidth; xc:= R.Left + xIterator + cellDescriptor.Bandwidth; xd:= R.Left + xIterator; Result.A := Point(xa, R.Top); Result.B := Point(xb, R.Top); Result.C := Point(xc,R.Bottom); Result.D := Point(xd, R.Bottom); end; class procedure TCellInsider.PlaceTextToCellCanvas( CellDescriptor: TLocalCellDescriptor); begin if Assigned (CellDescriptor.Canvas) then begin CellDescriptor.Canvas.Brush.Style:=bsClear; CellDescriptor.Canvas.TextRect( CellDescriptor.Rect, CellDescriptor.Rect.Left+1, CellDescriptor.Rect.Top+1, CellDescriptor.Text); end; end; class function TCellInsider.PolygonFragmentToSVG( TextRectCanvas: TLocalCellDescriptor; PolygonFragmentSVG: string): string; var TempString: string; begin TempString := PolygonFragmentSVG; TempString := TempString + TCellInsider.TextToSVGFragment( TextRectCanvas); Result := TempString; Result := TCellInsider.SVGTagWrap( TempString, TextRectCanvas.Rect); end; function ColorBandsOfListMovable( Canvas:TCanvas; Rect:TRect; ColorList: IList<TColor> ; BandWidth, BandShift:integer; Text:string): string; var OriginalCanvasSettings: GraphicStorage; CellDescriptor: TLocalCellDescriptor; StripGeneratorFactory: IStripGeneratorFactory; StripGenerator: IStripGenerator; begin Result := ''; OriginalCanvasSettings := TCellInsider.StoreCanvasPenBrush(Canvas); try CellDescriptor := TCellInsider.PopulateCellDescriptor(Canvas, Rect, ColorList, BandWidth, BandShift, Text); TCellInsider.ClearCellCanvas(CellDescriptor); StripGeneratorFactory := TStripGeneratorFactory.Create; StripGenerator := StripGeneratorFactory.CreateStripGenerator(CellDescriptor); Result := StripGenerator.DrawStripsAndReturnSVG(CellDescriptor); finally if Assigned(Canvas) then TCellInsider.RestoreCanvasPenBrush(OriginalCanvasSettings, Canvas); end; end; { Tparallelogram } function Tparallelogram.BandWidth: integer; begin Result := Self.B.X - Self.A.X; if Result <> self.C.X - self.D.X then raise Exception.Create( Format('Attempt to use malformed parallelogram: ' + '(%d %d) (%d %d) (%d %d) (%d %d)', [xa,ya,xb,yb,xc,yc,xd,yd]) ); end; end.
unit UPrefFToolSketcher; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is the Frame that contains the Tools > Sketcher Preferences} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, RzPanel, RzRadGrp, RzLabel, UContainer, UToolUtils; type TPrefToolSketcher = class(TFrame) SketchToolDefault: TRzRadioGroup; Panel1: TPanel; StaticText1: TStaticText; private FDoc: TContainer; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer); procedure LoadPrefs; //loads in the prefs from the app procedure SavePrefs; //saves the changes end; implementation uses UGlobals, UInit; {$R *.dfm} constructor TPrefToolSketcher.CreateFrame(AOwner: TComponent; ADoc: TContainer); begin inherited Create(AOwner); FDoc := ADoc; SketchToolDefault.Items.Clear; SketchToolDefault.Items.add('AreaSketch'); SketchToolDefault.Items.add('WinSketch'); SketchToolDefault.Items.add('Apex'); SketchToolDefault.Items.add('RapidSketch'); if HasAreaSketchSE then SketchToolDefault.Items.add('AreaSketch Special Edition'); {if fileExists(GetPhoenixSketchPath) then SketchToolDefault.Items.add('PhoenixSketch'); } LoadPrefs; end; procedure TPrefToolSketcher.LoadPrefs; begin SketchToolDefault.ItemIndex := appPref_DefaultSketcher; end; procedure TPrefToolSketcher.SavePrefs; begin appPref_DefaultSketcher := SketchToolDefault.ItemIndex; end; end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} unit cwThreading.Internal.TaskRecord.Standard; {$ifdef fpc}{$mode delphiunicode}{$endif} interface uses cwThreading , cwThreading.Internal ; type pNativeuint = ^nativeuint; TTaskRecord = class( TInterfacedObject, ITaskRecord ) private fTask: ITask; fTaskThread: TThreadID; fComplete: boolean; strict private //- ITaskRecord -// procedure Execute; function IsComplete: boolean; function IsLocked: boolean; function Lock: boolean; public constructor Create( const Task: ITask ); reintroduce; destructor Destroy; override; end; implementation {$ifdef MSWINDOWS} uses cwWin32.Kernel32 ; {$endif} procedure TTaskRecord.Execute; begin if assigned(fTask) then begin fTask.Execute; fComplete := True; end; end; function TTaskRecord.IsComplete: boolean; begin Result := fComplete; end; function TTaskRecord.IsLocked: boolean; begin Result := fTaskThread<>0; end; function TTaskRecord.Lock: boolean; var CurrentThreadID: TThreadID; begin Result := False; if fTaskThread<>0 then exit; CurrentThreadID := getCurrentThreadID; fTaskThread := CurrentThreadID; Result := fTaskThread = CurrentThreadID; end; constructor TTaskRecord.Create(const Task: ITask); begin inherited Create; fComplete := False; fTaskThread := 0; fTask := Task; end; destructor TTaskRecord.Destroy; begin fTask := nil; inherited Destroy; end; end.
// Author: Wayne Buchner // Student ID: 6643140 // Date: 20 04 2011 // Program: Calculate Change Assignment 6 Program // Description: This program initialises a set of coins, accepts a value for a purchase // and tests whether enough change is present and if is able to return the change given // in the correct demonination. {$MODE objfpc} program ChangeCalculator; uses SysUtils, math; // Type Declarations. type CoinData = record value : Integer; count : Integer; description : String; end; // Declare the CoinSet array here... CoinSet = array [0..5] of CoinData; // Delcare the CombineCoinsOp enumeration here... CombineCoinsOp = (AddCoins, RemoveCoins); // Zero all of the counts in a set of coins procedure ZeroCounts(var aSet: CoinSet); var i : Integer; begin for i := Low(aSet) to High(aSet) do begin aSet[i].count := 0; end; end; // Setup the coin data, initialise value, description, and count (set to 0) procedure InitialiseCoins(out aSet: CoinSet); begin aSet[0].value := 5; aSet[0].description := '5c'; aSet[1].value := 10; aSet[1].description := '10c'; aSet[2].value := 20; aSet[2].description := '20c'; aSet[3].value := 50; aSet[3].description := '50c'; aSet[4].value := 100; aSet[4].description := '$1'; aSet[5].value := 200; aSet[5].description := '$2'; ZeroCounts(aSet); end; // Draws a horizontal line on the Console procedure DrawLine(); var i: Integer; begin for i := 0 to 70 do begin Write('-'); end; WriteLn(); end; // Prints a message followed by the coin data from a set of coins. procedure PrintCoins(message: String; const aSet: CoinSet); var i : Integer; begin Write(message,' '); for i := Low(aSet) to High(aSet) do begin Write(aSet[i].count, ' x ', aSet[i].description); if i < High(aSet) then begin Write(', '); end; end; WriteLn(); end; // Displays the coins in the machine between two horizontal lines. procedure PrintMachineStatus(const machineCoins: CoinSet); begin DrawLine(); PrintCoins('In Machine - ', machineCoins); DrawLine(); WriteLn(); end; // Reads in an integer, using the message as the prompt for the value function ReadInteger(message: String): Integer; var temp: String; begin Write(message); ReadLn(temp); while not TryStrToInt(temp, result) do begin WriteLn('Please enter a whole number.'); Write(message); ReadLn(temp); end; end; // Reads coin data from the user into a set of coins. procedure ReadCoinCounts(message: String; var intoSet: CoinSet); begin Write(message, ' (5, 10, 20, 50, 100, 200): '); ReadLn(intoSet[0].count, intoSet[1].count, intoSet[2].count, intoSet[3].count, intoSet[4].count, intoSet[5].count ); WriteLn(); end; // Calculates the total value of a set of coins. function TotalValue(const aSet: CoinSet): Integer; var i : Integer; begin result :=0; for i := Low(aSet) to High(aSet) do begin result += (aSet[i].value * aSet[i].count); end; end; // The function returns true if it was about to distribute the correct // change, otherwise it returns false. function CalculateChange(amount: Integer; const machineCoins: CoinSet; const fromCoins: CoinSet; var intoCoins: CoinSet): Boolean; var i, val : Integer; begin result := False; for i := High(machineCoins) downto Low(machineCoins) do begin if machineCoins[i].count > 0 then begin val := amount DIV machineCoins[i].value; if machineCoins[i].count <= val then begin intoCoins[i].count := machineCoins[i].count; amount := amount - (machineCoins[i].count * machineCoins[i].value); end else begin intoCoins[i].count := val; amount := amount - (val * machineCoins[i].value); end; end; end; if amount = 0 then begin result := True; end end; // Adds or removes the coins in coinsDiff from the fromCoins. procedure CombineCoins(const coinDiff: CoinSet; var alterCoins: CoinSet; operation: CombineCoinsOp); var i : Integer; begin for i:= low(coinDiff) to High(CoinDiff) do if operation = AddCoins then begin alterCoins[i].count := alterCoins[i].count + coinDiff[i].count; end else if operation = RemoveCoins then begin alterCoins[i].count := alterCoins[i].count - coinDiff[i].count; end; end; // Performs a purchase involving determining cost, procedure PerformPurchase(var machineCoins: CoinSet; var purchaseCoins: CoinSet); var cost, diff: Integer; payment, change: CoinSet; begin // Incoming coins InitialiseCoins(payment); InitialiseCoins(change); cost := ReadInteger('PP Cost in cents: '); ReadCoinCounts('PP Coins used', payment); diff := TotalValue(payment) - cost; WriteLn('Change Required ', diff,' cents' ); // put coins paid into machine CombineCoins(payment, machineCoins, AddCoins); // CALLING CALCULATE CHANGE HERE TRUE or FALSE if CalculateChange(diff, machineCoins, purchaseCoins, change) then begin // if calculatechange is true do this.....check this function with remove coins! CombineCoins(change, machineCoins, RemoveCoins); PrintCoins('Change required :', change); end else begin WriteLn('Not Enough Change Sorry'); CombineCoins(payment, machineCoins, RemoveCoins); WriteLn(TotalValue(payment),' refunded'); end; WriteLn(); end; // Main procedure Main(); var machineCoins, customerCoins: CoinSet; i : Boolean; begin i := True; InitialiseCoins(machineCoins); InitialiseCoins(customerCoins); while i = True do begin ReadCoinCounts('Coins to add to machine: ',machineCoins); CombineCoins(customerCoins, machineCoins, AddCoins); PrintMachineStatus(machineCoins); WriteLn('Total value of machine coins is: ', TotalValue(machineCoins)); PerformPurchase(machineCoins, customerCoins); CombineCoins(customerCoins, machineCoins, RemoveCoins); // test remove coins PrintMachineStatus(machineCoins); WriteLn('Total value of machine coins is: ', TotalValue(machineCoins)); end; end; begin Main(); end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 2007, Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit descriptivestatistics; interface uses Math, Sysutils, Ap; procedure CalculateMoments(const X : TReal1DArray; N : AlglibInteger; var Mean : Double; var Variance : Double; var Skewness : Double; var Kurtosis : Double); procedure CalculateADev(const X : TReal1DArray; N : AlglibInteger; var ADev : Double); procedure CalculateMedian(X : TReal1DArray; N : AlglibInteger; var Median : Double); procedure CalculatePercentile(X : TReal1DArray; N : AlglibInteger; P : Double; var V : Double); implementation procedure InternalStatHeapSort(var Arr : TReal1DArray; N : AlglibInteger);forward; (************************************************************************* Calculation of the distribution moments: mean, variance, slewness, kurtosis. Input parameters: X - sample. Array with whose indexes range within [0..N-1] N - sample size. Output parameters: Mean - mean. Variance- variance. Skewness- skewness (if variance<>0; zero otherwise). Kurtosis- kurtosis (if variance<>0; zero otherwise). -- ALGLIB -- Copyright 06.09.2006 by Bochkanov Sergey *************************************************************************) procedure CalculateMoments(const X : TReal1DArray; N : AlglibInteger; var Mean : Double; var Variance : Double; var Skewness : Double; var Kurtosis : Double); var I : AlglibInteger; V : Double; V1 : Double; V2 : Double; StdDev : Double; begin Mean := 0; Variance := 0; Skewness := 0; Kurtosis := 0; StdDev := 0; if N<=0 then begin Exit; end; // // Mean // I:=0; while I<=N-1 do begin Mean := Mean+X[I]; Inc(I); end; Mean := Mean/N; // // Variance (using corrected two-pass algorithm) // if N<>1 then begin V1 := 0; I:=0; while I<=N-1 do begin V1 := V1+AP_Sqr(X[I]-Mean); Inc(I); end; V2 := 0; I:=0; while I<=N-1 do begin V2 := V2+(X[I]-Mean); Inc(I); end; V2 := AP_Sqr(V2)/N; Variance := (V1-V2)/(N-1); if AP_FP_Less(Variance,0) then begin Variance := 0; end; StdDev := Sqrt(Variance); end; // // Skewness and kurtosis // if AP_FP_Neq(StdDev,0) then begin I:=0; while I<=N-1 do begin V := (X[I]-Mean)/StdDev; V2 := AP_Sqr(V); Skewness := Skewness+V2*V; Kurtosis := Kurtosis+AP_Sqr(V2); Inc(I); end; Skewness := Skewness/N; Kurtosis := Kurtosis/N-3; end; end; (************************************************************************* ADev Input parameters: X - sample (array indexes: [0..N-1]) N - sample size Output parameters: ADev- ADev -- ALGLIB -- Copyright 06.09.2006 by Bochkanov Sergey *************************************************************************) procedure CalculateADev(const X : TReal1DArray; N : AlglibInteger; var ADev : Double); var I : AlglibInteger; Mean : Double; begin Mean := 0; ADev := 0; if N<=0 then begin Exit; end; // // Mean // I:=0; while I<=N-1 do begin Mean := Mean+X[I]; Inc(I); end; Mean := Mean/N; // // ADev // I:=0; while I<=N-1 do begin ADev := ADev+AbsReal(X[I]-Mean); Inc(I); end; ADev := ADev/N; end; (************************************************************************* Median calculation. Input parameters: X - sample (array indexes: [0..N-1]) N - sample size Output parameters: Median -- ALGLIB -- Copyright 06.09.2006 by Bochkanov Sergey *************************************************************************) procedure CalculateMedian(X : TReal1DArray; N : AlglibInteger; var Median : Double); var i : AlglibInteger; ir : AlglibInteger; j : AlglibInteger; l : AlglibInteger; midp : AlglibInteger; K : AlglibInteger; a : Double; tval : Double; begin X := DynamicArrayCopy(X); // // Some degenerate cases // Median := 0; if N<=0 then begin Exit; end; if N=1 then begin Median := X[0]; Exit; end; if N=2 then begin Median := Double(0.5)*(X[0]+X[1]); Exit; end; // // Common case, N>=3. // Choose X[(N-1)/2] // l := 0; ir := n-1; k := (N-1) div 2; while True do begin if ir<=l+1 then begin // // 1 or 2 elements in partition // if (ir=l+1) and AP_FP_Less(x[ir],x[l]) then begin tval := x[l]; x[l] := x[ir]; x[ir] := tval; end; Break; end else begin midp := (l+ir) div 2; tval := x[midp]; x[midp] := x[l+1]; x[l+1] := tval; if AP_FP_Greater(x[l],x[ir]) then begin tval := x[l]; x[l] := x[ir]; x[ir] := tval; end; if AP_FP_Greater(x[l+1],x[ir]) then begin tval := x[l+1]; x[l+1] := x[ir]; x[ir] := tval; end; if AP_FP_Greater(x[l],x[l+1]) then begin tval := x[l]; x[l] := x[l+1]; x[l+1] := tval; end; i := l+1; j := ir; a := x[l+1]; while True do begin repeat i := i+1; until AP_FP_Greater_Eq(x[i],a); repeat j := j-1; until AP_FP_Less_Eq(x[j],a); if j<i then begin Break; end; tval := x[i]; x[i] := x[j]; x[j] := tval; end; x[l+1] := x[j]; x[j] := a; if j>=k then begin ir := j-1; end; if j<=k then begin l := i; end; end; end; // // If N is odd, return result // if N mod 2=1 then begin Median := X[k]; Exit; end; a := x[n-1]; i:=k+1; while i<=n-1 do begin if AP_FP_Less(x[i],a) then begin a := x[i]; end; Inc(i); end; Median := Double(0.5)*(x[k]+a); end; (************************************************************************* Percentile calculation. Input parameters: X - sample (array indexes: [0..N-1]) N - sample size, N>1 P - percentile (0<=P<=1) Output parameters: V - percentile -- ALGLIB -- Copyright 01.03.2008 by Bochkanov Sergey *************************************************************************) procedure CalculatePercentile(X : TReal1DArray; N : AlglibInteger; P : Double; var V : Double); var I1 : AlglibInteger; T : Double; begin X := DynamicArrayCopy(X); Assert(N>1, 'CalculatePercentile: N<=1!'); Assert(AP_FP_Greater_Eq(P,0) and AP_FP_Less_Eq(P,1), 'CalculatePercentile: incorrect P!'); InternalStatHeapSort(X, N); if AP_FP_Eq(P,0) then begin V := X[0]; Exit; end; if AP_FP_Eq(P,1) then begin V := X[N-1]; Exit; end; T := P*(N-1); I1 := Floor(T); T := T-Floor(T); V := X[I1]*(1-T)+X[I1+1]*T; end; procedure InternalStatHeapSort(var Arr : TReal1DArray; N : AlglibInteger); var I : AlglibInteger; K : AlglibInteger; T : AlglibInteger; Tmp : Double; begin if N=1 then begin Exit; end; i := 2; repeat t := i; while t<>1 do begin k := t div 2; if AP_FP_Greater_Eq(Arr[k-1],Arr[t-1]) then begin t := 1; end else begin Tmp := Arr[k-1]; Arr[k-1] := Arr[t-1]; Arr[t-1] := Tmp; t := k; end; end; i := i+1; until not (i<=n); i := n-1; repeat Tmp := Arr[i]; Arr[i] := Arr[0]; Arr[0] := Tmp; t := 1; while t<>0 do begin k := 2*t; if k>i then begin t := 0; end else begin if k<i then begin if AP_FP_Greater(Arr[k],Arr[k-1]) then begin k := k+1; end; end; if AP_FP_Greater_Eq(Arr[t-1],Arr[k-1]) then begin t := 0; end else begin Tmp := Arr[k-1]; Arr[k-1] := Arr[t-1]; Arr[t-1] := Tmp; t := k; end; end; end; i := i-1; until not (i>=1); end; end.
unit UPostResponse; interface type TPostResponse = class(TObject) private fResponse: String; fOk: Boolean; procedure SetResponse(const Value: String); procedure SetOk(const Value: Boolean); public property Response : String read fResponse write SetResponse; property Ok : Boolean read fOk write SetOk; end; implementation { TPostResponse } procedure TPostResponse.SetOk(const Value: Boolean); begin fOk := Value; end; procedure TPostResponse.SetResponse(const Value: String); begin fResponse := Value; end; end.
unit ValidateCheckListBoxUnit; interface uses Windows, SysUtils, Classes, CheckLst, Graphics; const DEFAULT_INVALID_COLOR = $00A087FF; DEFAULT_INVALID_HINT = ''; type TOnCheckListBoxValidateEvent = procedure(Sender: TObject; var IsValid: Boolean) of object; TValidateCheckListBox = class(TCheckListBox) strict protected FInvalidColor: TColor; FInvalidHint: String; procedure Init( const AInvalidHint: String = DEFAULT_INVALID_HINT; const AInvalidColor: TColor = DEFAULT_INVALID_COLOR ); function AreSelectedItemsExists: Boolean; procedure OnClickCheckHandle(Sender: TObject); procedure UpdateInvalidProperties(const AIsValid: Boolean); public constructor Create(AOwner: TComponent); overload; override; constructor Create( const AInvalidColor: TColor; AOwner: TComponent ); overload; constructor Create( const AInvalidHint: String; const AInvalidColor: TColor; AOwner: TComponent ); overload; function IsValid: Boolean; procedure ResetInvalid; published property InvalidColor: TColor read FInvalidColor write FInvalidColor; property InvalidHint: String read FInvalidHint write FInvalidHint; end; procedure Register; implementation { TValidateCheckListBox } constructor TValidateCheckListBox.Create(AOwner: TComponent); begin inherited; Init; end; constructor TValidateCheckListBox.Create(const AInvalidColor: TColor; AOwner: TComponent); begin inherited Create(AOwner); Init(DEFAULT_INVALID_HINT); end; function TValidateCheckListBox.AreSelectedItemsExists: Boolean; var I: Integer; begin for I := 0 to Count - 1 do if Checked[I] then begin Result := True; Exit; end; Result := False; end; constructor TValidateCheckListBox.Create(const AInvalidHint: String; const AInvalidColor: TColor; AOwner: TComponent); begin inherited Create(AOwner); Init(DEFAULT_INVALID_HINT); end; procedure TValidateCheckListBox.Init(const AInvalidHint: String; const AInvalidColor: TColor); begin FInvalidColor := AInvalidColor; FInvalidHint := AInvalidHint; OnClickCheck := OnClickCheckHandle; end; function TValidateCheckListBox.IsValid: Boolean; begin Result := AreSelectedItemsExists; UpdateInvalidProperties(Result); end; procedure TValidateCheckListBox.OnClickCheckHandle(Sender: TObject); begin IsValid; end; procedure TValidateCheckListBox.ResetInvalid; begin UpdateInvalidProperties(True); end; procedure TValidateCheckListBox.UpdateInvalidProperties( const AIsValid: Boolean); begin if AIsValid then begin Color := clWindow; Hint := ''; ShowHint := False; end else begin Color := FInvalidColor; Hint := FInvalidHint; ShowHint := True; end; end; procedure Register; begin RegisterComponents('Additional', [TValidateCheckListBox]); end; end.
unit UMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Design, ExtCtrls, RPCtrls, Design2, ComCtrls, ToolWin, Menus, FORecord, ActnList, ImgList, RTObjInspector, UReportInspector, RPDesignInfo, UToolForm; resourcestring AppTitle = 'Report Designer'; const StartTop = 20; BottomMargin = 20; RightMargin = 20; type TReportDesigner = class(TForm) sbDesignArea: TScrollBox; DesignerPane: TDesigner2; MainMenu: TMainMenu; miFile: TMenuItem; N1: TMenuItem; miExit: TMenuItem; ToolBar: TToolBar; miSave: TMenuItem; miOpen: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; alFile: TActionList; ImageList1: TImageList; FileClose1: TKSFileClose; FileNew1: TKSFileNew; FileOpen1: TKSFileOpen; FileSave1: TKSFileSave; FileSaveAs1: TKSFileSaveAs; FileOpenRecord: TFileOpenRecord; alNewBand: TActionList; acNewSimpleBand: TAction; miNew: TMenuItem; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; btnSelect: TToolButton; btnLabel: TToolButton; btnShape: TToolButton; btnPicture: TToolButton; acNewGroupBand: TAction; acNewRepeatBand: TAction; miSaveAs: TMenuItem; ToolButton5: TToolButton; ReportInspector: TReportInspector; Splitter1: TSplitter; StatusBar: TStatusBar; ImageList2: TImageList; miView: TMenuItem; miFullDesignArea: TMenuItem; N2: TMenuItem; miOldMethod: TMenuItem; procedure DesignerPaneCanMoveCtrl(Designer: TCustomDesigner; Ctrl: TControl; var CanMoved: Boolean); procedure FormCreate(Sender: TObject); procedure FileOpenRecordFileClose(Sender: TObject); procedure acNewSimpleBandExecute(Sender: TObject); procedure alNewBandUpdate(Action: TBasicAction; var Handled: Boolean); procedure FileOpenRecordFileSave(FORecord: TFileOpenRecord; const FileName: String); procedure FileOpenRecordFileOpen(FORecord: TFileOpenRecord; const FileName: String); procedure FileOpenRecordFileNew(Sender: TObject); procedure DesignerPaneDesignCtrlChanged(DesignCtrl: TControl); procedure FormDestroy(Sender: TObject); procedure DesignerPaneCtrlSizeMove(Sender: TObject); procedure SelectedTool(Sender: TObject); procedure DesignerPanePlaceNewCtrl(PlaceOn: TWinControl; x, y: Integer); procedure acNewGroupBandExecute(Sender: TObject); procedure acNewRepeatBandExecute(Sender: TObject); procedure FileOpenRecordStatusChanged(Sender: TObject); procedure DesignerPaneDelete(DeleteCtrl: TControl); procedure FileOpenRecordAfterFileOperate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure miFullDesignAreaClick(Sender: TObject); procedure miOldMethodClick(Sender: TObject); procedure DesignerPaneCanSizeCtrl(Designer: TCustomDesigner; Ctrl: TControl; var CanSized: Boolean); private { Private declarations } FReportInfo : TReportInfo; FToolForms : TList; FStartY : Integer; function GetDesignning: Boolean; procedure SetDesignning(const Value: Boolean); procedure Init; function GetSelected: TControl; procedure SetSelected(const Value: TControl); function CanNewBand : Boolean; function GetGroupBand : TRDCustomGroupBand; procedure AddCtrl(Ctrl : TControl); procedure UpdateToolStatus; function GetModified: Boolean; procedure SetModified(const Value: Boolean); procedure ShowToolForm(Sender : TObject); procedure BeforeLoad; procedure AfterLoad; procedure AfterFileOperation; {procedure BuildHistoryMenu; procedure DoLoadState(Sender : TObject);} protected procedure ValidateRename(AComponent: TComponent; const CurName, NewName: string); override; public { Public declarations } procedure StartDesignning; procedure StopDesignning(ChangeRoot : Boolean=True); procedure InstallToolForm(ToolForm : TToolForm); procedure Changed(Obj : TObject); procedure AddObject(Obj : TObject); procedure UpdateDesignArea; procedure RefreshTools; property ReportInfo : TReportInfo read FReportInfo; property Designning : Boolean read GetDesignning write SetDesignning; property Selected : TControl read GetSelected write SetSelected; property Modified : Boolean read GetModified write SetModified; end; var ReportDesigner: TReportDesigner; implementation uses JPEG, CompUtils, RPDefines; {$R *.DFM} procedure TReportDesigner.FormCreate(Sender: TObject); begin Init; end; procedure TReportDesigner.Init; var FileFilters, DefaultExt: string; begin Application.Title := AppTitle; FileOpenRecord.UpdateFormCaption; FToolForms := TList.Create; FReportInfo := TReportInfo.Create(Self); ReportFileStores.GetFileInfo(FileFilters, DefaultExt); OpenDialog.Filter := FileFilters; OpenDialog.DefaultExt := DefaultExt; SaveDialog.Filter := FileFilters; SaveDialog.DefaultExt := DefaultExt; OnCloseQuery := FileOpenRecord.FormCloseQuery; UReportInspector.ReportInspector := ReportInspector; DesignerPane.PopupMenu := ReportInspector.StructView.PopupMenu; //ReportInspector.StructView.TreeView.RightClickSelect := True; StartDesignning; FStartY := StartTop; end; procedure TReportDesigner.FormDestroy(Sender: TObject); begin FToolForms.Free; StopDesignning; end; procedure TReportDesigner.DesignerPaneCanMoveCtrl( Designer: TCustomDesigner; Ctrl: TControl; var CanMoved: Boolean); begin CanMoved := not (Ctrl is TRDReport); end; function TReportDesigner.GetDesignning: Boolean; begin Result := DesignerPane.Designed; end; procedure TReportDesigner.SetDesignning(const Value: Boolean); begin DesignerPane.Designed := Value; end; procedure TReportDesigner.StartDesignning; begin if ReportInfo.Report<>nil then begin with ReportInfo.Report do begin SetBounds(0,0,Width,Height); DesignerPane.SetBounds(0,0,Width,Height); Parent := DesignerPane; end; //ReportInspector.Root := ReportInfo.Report; ReportInspector.Root := ReportInfo; ReportInspector.Report := ReportInfo.Report; Designning := true; end else Designning := false; end; procedure TReportDesigner.StopDesignning(ChangeRoot : Boolean=True); begin Designning := false; ReportInspector.Selected := nil; if ChangeRoot then ReportInspector.Root := nil; if ReportInfo.Report<>nil then begin //ReportInfo.Report.Parent := ReportInfo; ReportInfo.Report.Parent := nil; end end; procedure TReportDesigner.FileOpenRecordFileClose(Sender: TObject); begin Close; end; function TReportDesigner.GetSelected: TControl; begin Result := DesignerPane.DesignCtrl; end; procedure TReportDesigner.SetSelected(const Value: TControl); begin DesignerPane.DesignCtrl := Value; if Value<>nil then sbDesignArea.ScrollInView(Value); end; function TReportDesigner.CanNewBand: Boolean; begin Result := ReportInspector.Selected is TRDCustomGroupBand; end; function TReportDesigner.GetGroupBand: TRDCustomGroupBand; begin Assert(Selected is TRDCustomGroupBand); Result := TRDCustomGroupBand(Selected); end; procedure TReportDesigner.alNewBandUpdate(Action: TBasicAction; var Handled: Boolean); var B : Boolean; begin Handled := true; B := CanNewBand; acNewSimpleBand.Enabled := B; acNewGroupBand.Enabled := B; acNewRepeatBand.Enabled := B; end; procedure TReportDesigner.FileOpenRecordFileSave(FORecord: TFileOpenRecord; const FileName: String); begin StopDesignning(False); ReportInfo.SaveToFile(FileName); StartDesignning; end; procedure TReportDesigner.FileOpenRecordFileOpen(FORecord: TFileOpenRecord; const FileName: String); begin StopDesignning; BeforeLoad; ReportInfo.LoadFromFile(FileName); AfterLoad; StartDesignning; end; procedure TReportDesigner.FileOpenRecordFileNew(Sender: TObject); begin StopDesignning; BeforeLoad; ReportInfo.New; AfterLoad; StartDesignning; end; procedure TReportDesigner.DesignerPaneDesignCtrlChanged( DesignCtrl: TControl); begin ReportInspector.Selected := DesignCtrl; end; procedure TReportDesigner.DesignerPaneCtrlSizeMove(Sender: TObject); begin if DesignerPane.DesignCtrl is TRDReport then UpdateDesignArea; Modified := true; end; procedure TReportDesigner.AddCtrl(Ctrl: TControl); begin Modified := True; ReportInspector.AddObject(Ctrl); Selected := Ctrl; AddObject(Ctrl); end; procedure TReportDesigner.SelectedTool(Sender: TObject); begin UpdateToolStatus; end; procedure TReportDesigner.DesignerPanePlaceNewCtrl(PlaceOn: TWinControl; x, y: Integer); var SimpleBand : TRDSimpleBand; Ctrl : TControl; begin if PlaceOn is TRDSimpleBand then begin SimpleBand := TRDSimpleBand(PlaceOn); if btnLabel.Down then Ctrl := ReportInfo.NewLabel else if btnShape.Down then Ctrl := ReportInfo.NewShape else if btnPicture.Down then Ctrl := ReportInfo.NewPicture else Ctrl := nil; if Ctrl<>nil then begin Ctrl.SetBounds(x,y,Ctrl.Width,Ctrl.Height); Ctrl.Parent := SimpleBand; AddCtrl(Ctrl); end; btnSelect.Down := True; end; UpdateToolStatus; end; procedure TReportDesigner.UpdateToolStatus; begin DesignerPane.PlaceNewCtrl := not btnSelect.Down; end; procedure TReportDesigner.acNewSimpleBandExecute(Sender: TObject); var Ctrl : TControl; begin if CanNewBand then begin Ctrl := ReportInfo.NewSimpleBand; Ctrl.Parent := GetGroupBand; AddCtrl(Ctrl); end; end; procedure TReportDesigner.acNewGroupBandExecute(Sender: TObject); var Ctrl : TControl; begin if CanNewBand then begin Ctrl := ReportInfo.NewGroupBand; Ctrl.Parent := GetGroupBand; AddCtrl(Ctrl); end; end; procedure TReportDesigner.acNewRepeatBandExecute(Sender: TObject); var Ctrl : TControl; begin if CanNewBand then begin Ctrl := ReportInfo.NewRepeatBand; Ctrl.Parent := GetGroupBand; AddCtrl(Ctrl); end; end; procedure TReportDesigner.FileOpenRecordStatusChanged(Sender: TObject); begin if FileOpenRecord.Modified then StatusBar.Panels[0].Text := 'Modified' else begin StatusBar.Panels[0].Text := ''; ReportInspector.Properties.ClearModified; end; end; function TReportDesigner.GetModified: Boolean; begin Result := FileOpenRecord.Modified; end; procedure TReportDesigner.SetModified(const Value: Boolean); begin FileOpenRecord.Modified := Value; end; procedure TReportDesigner.DesignerPaneDelete(DeleteCtrl: TControl); begin Selected := DeleteCtrl; ReportInspector.StructView.DeleteAction.Execute; end; procedure TReportDesigner.UpdateDesignArea; var PaperWidth, PaperHeight, LeftMargin, TopMargin: Integer; Temp : Integer; begin Assert(ReportInfo.Report<>nil); PaperWidth := ScreenTransform.Physics2DeviceX(ReportInfo.Report.PaperWidth); PaperHeight := ScreenTransform.Physics2DeviceY(ReportInfo.Report.PaperHeight); LeftMargin := ScreenTransform.Physics2DeviceX(ReportInfo.Report.Margin.Left); TopMargin := ScreenTransform.Physics2DeviceY(ReportInfo.Report.Margin.Top); sbDesignArea.HorzScrollBar.Position:=0; sbDesignArea.VertScrollBar.Position:=0; if ReportInfo.Report.Orientation=poLandscape then begin Temp := PaperWidth; PaperWidth := PaperHeight; PaperHeight := Temp; end; DesignerPane.SetBounds(0,0,PaperWidth,PaperHeight); ReportInfo.Report.SetBounds(LeftMargin,TopMargin,ReportInfo.Report.Width,ReportInfo.Report.Height); end; procedure TReportDesigner.FileOpenRecordAfterFileOperate(Sender: TObject); begin UpdateDesignArea; AfterFileOperation; end; procedure TReportDesigner.FormActivate(Sender: TObject); begin UpdateDesignArea; end; procedure TReportDesigner.miFullDesignAreaClick(Sender: TObject); var B : Boolean; begin B := not miFullDesignArea.Checked; miFullDesignArea.Checked := B; //ToolBar.Visible := not B; StatusBar.Visible := not B; ReportInspector.Visible := not B; end; { procedure TReportDesigner.BuildHistoryMenu; var i : integer; MenuItem : TMenuItem; begin FStateMenus.Clear; for i:=0 to FStateData.Count-1 do begin MenuItem := TMenuItem.Create(Self); FStateMenus.Add(MenuItem); MenuItem.Caption := FStates[i]; MenuItem.Tag := I; MenuItem.OnClick := DoLoadState; miHistory.Add(MenuItem); end; end; } procedure TReportDesigner.InstallToolForm(ToolForm: TToolForm); var MenuItem : TMenuItem; X , Y : Integer; begin ToolForm.ReportInfo := ReportInfo; FToolForms.Add(ToolForm); Y := FStartY; Inc(FStartY,ToolForm.Height); if FStartY+BottomMargin>Screen.Height then FStartY := StartTop; X := Screen.Width - RightMargin - ToolForm.Width; ToolForm.SetBounds(X,Y,ToolForm.Width,ToolForm.Height); MenuItem := TMenuItem.Create(Self); MenuItem.Caption := ToolForm.Caption; MenuItem.ShortCut := TextToShortCut(ToolForm.Hint); MenuItem.Tag := FToolForms.Count-1; MenuItem.OnClick := ShowToolForm; miView.Add(MenuItem); end; procedure TReportDesigner.ShowToolForm(Sender: TObject); begin Assert(Sender is TMenuItem); TForm(FToolForms[TMenuItem(Sender).Tag]).Show; end; procedure TReportDesigner.AfterLoad; var i : integer; begin ReportInfo.Name := ''; for i:=0 to FToolForms.Count-1 do TToolForm(FToolForms[i]).AfterLoad; end; procedure TReportDesigner.BeforeLoad; var i : integer; begin for i:=0 to FToolForms.Count-1 do TToolForm(FToolForms[i]).BeforeLoad; end; procedure TReportDesigner.AfterFileOperation; var i : integer; begin for i:=0 to FToolForms.Count-1 do TToolForm(FToolForms[i]).AfterFileOperation; end; procedure TReportDesigner.Changed(Obj: TObject); var i : integer; begin for i:=0 to FToolForms.Count-1 do TToolForm(FToolForms[i]).Changed(Obj); end; procedure TReportDesigner.AddObject(Obj: TObject); var i : integer; begin if FToolForms<>nil then for i:=0 to FToolForms.Count-1 do TToolForm(FToolForms[i]).Add(Obj); end; procedure TReportDesigner.ValidateRename(AComponent: TComponent; const CurName, NewName: string); begin inherited; { if (AComponent is TReportInfo) and (CurName<>NewName) and (NewName<>'') then Abort; } end; procedure TReportDesigner.RefreshTools; var I : integer; begin if FToolForms<>nil then for I:=0 to FToolForms.Count-1 do TToolForm(FToolForms[I]).RefreshObjects; end; procedure TReportDesigner.miOldMethodClick(Sender: TObject); begin miOldMethod.Checked := not miOldMethod.Checked; ScreenTransform.InitFromScreen(miOldMethod.Checked); ReportInfo.Report.PaperSizeChanged; UpdateDesignArea; end; procedure TReportDesigner.DesignerPaneCanSizeCtrl( Designer: TCustomDesigner; Ctrl: TControl; var CanSized: Boolean); begin CanSized := not (Ctrl is TRDReport); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC DataSnap driver } { } { Copyright(c) 2004-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} {$I FireDAC.inc} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Phys.DataSnap.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Phys.DataSnap.o"'} {$ENDIF} unit FireDAC.Phys.DataSnap; interface uses System.Classes, FireDAC.Phys.TDBXBase; type TFDPhysDataSnapDriverLink = class; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] TFDPhysDataSnapDriverLink = class(TFDPhysTDBXBaseDriverLink) protected function GetBaseDriverID: String; override; end; {-------------------------------------------------------------------------------} implementation uses System.SysUtils, System.IniFiles, System.Variants, Data.DBXCommon, Data.DbxDatasnap, Data.DbxJSON, Datasnap.DSProxy, Datasnap.DSCommon, FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.SQLGenerator, FireDAC.Phys.Meta, FireDAC.Phys.DataSnapMeta; type TFDPhysDataSnapDriver = class; TFDPhysDataSnapConnection = class; TFDPhysDataSnapEventAlerter = class; TFDPhysDataSnapCommand = class; TFDPhysDataSnapDriver = class(TFDPhysTDBXDriverBase) protected class function GetBaseDriverID: String; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; function GetConnParamCount(AKeys: TStrings): Integer; override; procedure GetConnParams(AKeys: TStrings; Index: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); override; end; TFDPhysDataSnapConnection = class(TFDPhysTDBXConnectionBase) private FProductVersion: TFDVersion; function CheckNetworkError(AExc: Exception; AObj: TObject): Boolean; protected function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override; function InternalCreateCommand: TFDPhysCommand; override; function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override; function InternalCreateMetadata: TObject; override; procedure InternalConnect; override; procedure InternalPing; override; procedure CheckDBXDriver; override; procedure BuildDBXConnParams(const AConnectionDef: IFDStanConnectionDef; AConnProps: TDBXProperties); override; end; TFDPhysDataSnapEventAlerter = class(TFDPhysEventAlerter) private FManagers: TFDObjList; FCallbacks: TFDStringList; function GetDSConn: TFDPhysDataSnapConnection; protected procedure InternalAllocHandle; override; procedure InternalReleaseHandle; override; procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override; procedure InternalRegister; override; procedure InternalUnregister; override; procedure InternalSignal(const AEvent: String; const AArgument: Variant); override; public constructor Create(AConnection: TFDPhysConnection; const AKind: String); override; destructor Destroy; override; property DSConn: TFDPhysDataSnapConnection read GetDSConn; end; TFDPhysDataSnapCommand = class(TFDPhysTDBXCommand) private function GetDSConn: TFDPhysDataSnapConnection; protected procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override; function InternalOpen: Boolean; override; function InternalNextRecordSet: Boolean; override; procedure InternalPrepare; override; public property DSConn: TFDPhysDataSnapConnection read GetDSConn; end; const S_FD_TCPIP = 'TCP/IP'; S_FD_HTTP = 'HTTP'; {-------------------------------------------------------------------------------} { TFDPhysDataSnapDriverLink } {-------------------------------------------------------------------------------} function TFDPhysDataSnapDriverLink.GetBaseDriverID: String; begin Result := S_FD_DataSnapId; end; {-------------------------------------------------------------------------------} { TFDPhysDataSnapDriver } {-------------------------------------------------------------------------------} class function TFDPhysDataSnapDriver.GetBaseDriverID: String; begin Result := S_FD_DataSnapId; end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysDataSnapConnection.Create(Self, AConnHost); end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapDriver.GetConnParamCount(AKeys: TStrings): Integer; begin Result := inherited GetConnParamCount(AKeys) + 5; if (AKeys <> nil) and (CompareText(AKeys.Values[S_FD_ConnParam_DataSnap_Protocol], S_FD_HTTP) = 0) then Result := Result + 9; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapDriver.GetConnParams(AKeys: TStrings; Index: Integer; var AName, AType, ADefVal, ACaption: String; var ALoginIndex: Integer); begin ALoginIndex := -1; ADefVal := ''; if Index < inherited GetConnParamCount(AKeys) then begin inherited GetConnParams(AKeys, Index, AName, AType, ADefVal, ACaption, ALoginIndex); if AName = S_FD_ConnParam_Common_Database then ALoginIndex := -1; end else begin Index := Index - inherited GetConnParamCount(AKeys); case Index of 0: begin AName := S_FD_ConnParam_DataSnap_Protocol; AType := S_FD_TCPIP + ';' + S_FD_HTTP; ADefVal := S_FD_TCPIP; end; 1: begin AName := S_FD_ConnParam_Common_Server; AType := '@S'; ADefVal := '127.0.0.1'; ALoginIndex := 2; end; 2: begin AName := TDBXPropertyNames.Port; AType := '@I'; if (AKeys <> nil) and (CompareText(AKeys.Values[S_FD_ConnParam_DataSnap_Protocol], S_FD_HTTP) = 0) then ADefVal := '8080' else ADefVal := '211'; ALoginIndex := 3; end; 3: begin AName := TDBXPropertyNames.BufferKBSize; AType := '@I'; ADefVal := '32'; end; 4: begin AName := TDBXPropertyNames.Filters; AType := '@S'; end; else if (AKeys <> nil) and (CompareText(AKeys.Values[S_FD_ConnParam_DataSnap_Protocol], S_FD_HTTP) = 0) then case Index of 5: begin AName := TDBXPropertyNames.URLPath; AType := '@S'; end; 6: begin AName := TDBXPropertyNames.DatasnapContext; AType := '@S'; ADefVal := DS_CONTEXT; end; 7: begin AName := TDBXPropertyNames.DSProxyHost; AType := '@S'; end; 8: begin AName := TDBXPropertyNames.DSProxyPort; AType := '@I'; end; 9: begin AName := TDBXPropertyNames.DSProxyUsername; AType := '@S'; end; 10: begin AName := TDBXPropertyNames.DSProxyPassword; AType := '@S'; end; 11: begin AName := TDBXPropertyNames.DSAuthenticationScheme; AType := ';basic'; end; 12: begin AName := S_FD_ConnParam_Common_LoginTimeout; AType := '@I'; end; 13: begin AName := TDBXPropertyNames.CommunicationTimeout; AType := '@I'; end; end; end; ACaption := AName; end; end; {-------------------------------------------------------------------------------} { TFDPhysDataSnapConnection } {-------------------------------------------------------------------------------} function TFDPhysDataSnapConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; begin if CompareText(AEventKind, S_FD_EventKind_DataSnap_Events) = 0 then Result := TFDPhysDataSnapEventAlerter.Create(Self, AEventKind) else Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapConnection.InternalCreateCommand: TFDPhysCommand; begin Result := TFDPhysDataSnapCommand.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapConnection.InternalCreateCommandGenerator( const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; begin Result := TFDPhysCommandGenerator.Create(ACommand); end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapConnection.InternalCreateMetadata: TObject; begin Result := TFDPhysDataSnapMetadata.Create(Self, 0, FProductVersion, True); end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapConnection.CheckDBXDriver; begin FDriverName := 'DataSnap'; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapConnection.BuildDBXConnParams( const AConnectionDef: IFDStanConnectionDef; AConnProps: TDBXProperties); procedure SetParam(const ADbxPar, AADPar, ADef: String); var s: String; begin s := AADPar; if s = '' then s := ADbxPar; s := AConnectionDef.AsString[s]; if s = '' then s := ADef; if s <> '' then AConnProps.Values[ADbxPar] := s; end; begin AConnProps.Values[TDBXPropertyNames.DriverName] := FDriverName; AConnProps.Values[TDBXPropertyNames.DriverUnit] := 'Data.DbxDatasnap'; SetParam(TDBXPropertyNames.CommunicationProtocol, S_FD_ConnParam_DataSnap_Protocol, S_FD_TCPIP); SetParam(TDBXPropertyNames.HostName, S_FD_ConnParam_Common_Server, '127.0.0.1'); if CompareText(AConnectionDef.AsString[S_FD_ConnParam_DataSnap_Protocol], S_FD_TCPIP) = 0 then SetParam(TDBXPropertyNames.Port, '', '211') else SetParam(TDBXPropertyNames.Port, '', '8080'); SetParam(TDBXPropertyNames.BufferKBSize, '', '32'); SetParam(TDBXPropertyNames.Filters, '', ''); SetParam(TDBXPropertyNames.URLPath, '', ''); SetParam(TDBXPropertyNames.DatasnapContext, '', DS_CONTEXT); SetParam(TDBXPropertyNames.DSProxyHost, '', ''); SetParam(TDBXPropertyNames.DSProxyPort, '', ''); SetParam(TDBXPropertyNames.DSProxyUsername, '', ''); SetParam(TDBXPropertyNames.DSProxyPassword, '', ''); SetParam(TDBXPropertyNames.DSAuthenticationUser, S_FD_ConnParam_Common_UserName, ''); SetParam(TDBXPropertyNames.DSAuthenticationPassword, S_FD_ConnParam_Common_Password, ''); SetParam(TDBXPropertyNames.DSAuthenticationScheme, '', ''); SetParam(TDBXPropertyNames.ConnectTimeout, S_FD_ConnParam_Common_LoginTimeout, ''); SetParam(TDBXPropertyNames.CommunicationTimeout, '', ''); end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapConnection.CheckNetworkError(AExc: Exception; AObj: TObject): Boolean; var oExc: ETDBXNativeException; oExcClass: TClass; begin oExcClass := AExc.ClassType; while (oExcClass <> nil) and (CompareText(oExcClass.ClassName, 'EIdException') <> 0) do oExcClass := oExcClass.ClassParent; if oExcClass <> nil then begin oExc := ETDBXNativeException.Create(er_FD_DBXGeneral, FDExceptionLayers([S_FD_LPhys, S_FD_TDBXId, S_FD_DataSnapId]) + ' ' + AExc.Message); oExc.AppendError(1, TDBXErrorCodes.ConnectionFailed, AExc.Message, '', ekServerGone, -1, -1); FDException(AObj, oExc {$IFDEF FireDAC_Monitor}, False {$ENDIF}); Result := True; end else Result := False; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapConnection.InternalConnect; begin try inherited InternalConnect; FProductVersion := FDVerStr2Int(DbxConnection.ProductVersion); except on E: Exception do if not CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapConnection.InternalPing; begin try // simplest DataSnap command DbxConnection.GetVendorProperty(TDBXPropertyNames.ProductVersion); except on E: Exception do if not CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} { TFDPhysDataSnapEventMessage } {-------------------------------------------------------------------------------} type TFDPhysDataSnapEventMessage = class(TFDPhysEventMessage) private FCBName: String; FArgs: Variant; public constructor Create(const ACBName: String; const AArgs: Variant); end; {-------------------------------------------------------------------------------} constructor TFDPhysDataSnapEventMessage.Create(const ACBName: String; const AArgs: Variant); begin inherited Create; FCBName := ACBName; FArgs := AArgs; end; {-------------------------------------------------------------------------------} { TFDDataSnapCallback } {-------------------------------------------------------------------------------} type TFDDataSnapCallback = class(TDBXCallback) private FAlerter: TFDPhysDataSnapEventAlerter; FName: String; public constructor Crate(AAlerter: TFDPhysDataSnapEventAlerter; const AName: String); function Execute(const AArg: TJSONValue): TJSONValue; overload; override; function Execute(AArg: TObject): TObject; overload; override; end; {-------------------------------------------------------------------------------} constructor TFDDataSnapCallback.Crate(AAlerter: TFDPhysDataSnapEventAlerter; const AName: String); begin inherited Create; FAlerter := AAlerter; FName := AName; end; {-------------------------------------------------------------------------------} function TFDDataSnapCallback.Execute(const AArg: TJSONValue): TJSONValue; var V: Variant; i: Integer; begin if AArg is TJSONArray then begin V := VarArrayCreate([0, TJSONArray(AArg).Size - 1], varADWString); for i := 0 to TJSONArray(AArg).Size - 1 do V[i] := TJSONArray(AArg).Get(i).Value; end else V := AArg.Value; if FAlerter.IsRunning then FAlerter.FMsgThread.EnqueueMsg(TFDPhysDataSnapEventMessage.Create(FName, V)); Result := TJSONTrue.Create; end; {-------------------------------------------------------------------------------} function TFDDataSnapCallback.Execute(AArg: TObject): TObject; begin Result := Execute(TDSClientCallbackChannelManager(FAlerter.FManagers[0]). MarshalData(AArg)); end; {-------------------------------------------------------------------------------} { TFDPhysDataSnapEventAlerter } {-------------------------------------------------------------------------------} constructor TFDPhysDataSnapEventAlerter.Create(AConnection: TFDPhysConnection; const AKind: String); begin inherited Create(AConnection, AKind); FManagers := TFDObjList.Create; FCallbacks := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDPhysDataSnapEventAlerter.Destroy; begin inherited Destroy; FDFreeAndNil(FManagers); FDFreeAndNil(FCallbacks); end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapEventAlerter.GetDSConn: TFDPhysDataSnapConnection; begin Result := TFDPhysDataSnapConnection(ConnectionObj); end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalAllocHandle; var oDef: IFDStanConnectionDef; oNames: TStrings; i: Integer; oMan: TDSClientCallbackChannelManager; sCBName: String; sChnlName: String; function Def(const AValue, ADef: String): String; begin if AValue = '' then Result := ADef else Result := AValue; end; function GenSessionId: String; begin Result := TDSSessionHelper.GenerateSessionId; end; begin oDef := DSConn.ConnectionDef; oNames := GetNames; for i := 0 to oNames.Count - 1 do begin oMan := TDSClientCallbackChannelManager.Create(nil); FManagers.Add(oMan); oMan.CommunicationProtocol := Def(oDef.AsString[S_FD_ConnParam_DataSnap_Protocol], S_FD_TCPIP); oMan.DSHostname := Def(oDef.Server, '127.0.0.1'); if CompareText(oMan.CommunicationProtocol, S_FD_TCPIP) = 0 then oMan.DSPort := Def(oDef.AsString[S_FD_ConnParam_Common_Port], '211') else oMan.DSPort := Def(oDef.AsString[S_FD_ConnParam_Common_Port], '8080'); oMan.DSPath := oDef.AsString[TDBXPropertyNames.URLPath]; oMan.UserName := oDef.UserName; oMan.Password := oDef.Password; oMan.ProxyHost := oDef.AsString[TDBXPropertyNames.DSProxyHost]; oMan.ProxyPort := oDef.AsInteger[TDBXPropertyNames.DSProxyPort]; oMan.ProxyUsername := oDef.AsString[TDBXPropertyNames.DSProxyUsername]; oMan.ProxyPassword := oDef.AsString[TDBXPropertyNames.DSProxyPassword]; oMan.ConnectionTimeout := oDef.AsString[S_FD_ConnParam_Common_LoginTimeout]; oMan.CommunicationTimeout := oDef.AsString[TDBXPropertyNames.CommunicationTimeout]; oMan.ManagerId := GenSessionId; sChnlName := FDNameFromIndex(oNames, i); if sChnlName = '' then sChnlName := GenSessionId; oMan.ChannelName := sChnlName; sCBName := FDValueFromIndex(oNames, i); if sCBName = '' then sCBName := GenSessionId; FCallbacks.Add(sCBName); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalHandle( AEventMessage: TFDPhysEventMessage); begin if GetHandler = nil then Exit; GetHandler.HandleEvent(TFDPhysDataSnapEventMessage(AEventMessage).FCBName, TFDPhysDataSnapEventMessage(AEventMessage).FArgs); end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalRegister; var i: Integer; oCB: TFDDataSnapCallback; begin for i := 0 to FManagers.Count - 1 do begin oCB := TFDDataSnapCallback.Crate(Self, FCallbacks[i]); TDSClientCallbackChannelManager(FManagers[i]).RegisterCallback(oCB.FName, oCB); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalUnregister; var i: Integer; begin for i := 0 to FManagers.Count - 1 do TDSClientCallbackChannelManager(FManagers[i]).UnregisterCallback(FCallbacks[i]); end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalReleaseHandle; var i: Integer; begin for i := 0 to FManagers.Count - 1 do FDFree(TDSClientCallbackChannelManager(FManagers[i])); FManagers.Clear; FCallbacks.Clear; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapEventAlerter.InternalSignal(const AEvent: String; const AArgument: Variant); var iChnl, i: Integer; oClnt: TDSAdminClient; oArr: TJSONArray; oMsg: TJSONValue; oRsp: TJSONValue; begin iChnl := GetNames.IndexOfName(AEvent); if iChnl = -1 then iChnl := GetNames.IndexOf(AEvent); if VarIsArray(AArgument) then begin oArr := TJSONArray.Create; for i := VarArrayLowBound(AArgument, 1) to VarArrayHighBound(AArgument, 1) do oArr.Add(VarToStrDef(AArgument[i], '')); oMsg := oArr; end else oMsg := TJSONString.Create(VarToStrDef(AArgument, '')); oClnt := TDSAdminClient.Create(DSConn.DbxConnection); try if iChnl <> -1 then oClnt.BroadcastToChannel(AEvent, oMsg) else oClnt.NotifyCallback(AArgument[0], AEvent, oMsg, oRsp); finally FDFree(oClnt); end; end; {-------------------------------------------------------------------------------} { TFDPhysDataSnapCommand } {-------------------------------------------------------------------------------} function TFDPhysDataSnapCommand.GetDSConn: TFDPhysDataSnapConnection; begin Result := TFDPhysDataSnapConnection(TDBXConn); end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapCommand.InternalPrepare; begin try inherited InternalPrepare; except on E: Exception do if not DSConn.CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysDataSnapCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); begin try inherited InternalExecute(ATimes, AOffset, ACount); except on E: Exception do if not DSConn.CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapCommand.InternalOpen: Boolean; begin Result := False; try Result := inherited InternalOpen; except on E: Exception do if not DSConn.CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} function TFDPhysDataSnapCommand.InternalNextRecordSet: Boolean; begin Result := False; try Result := inherited InternalNextRecordSet; except on E: Exception do if not DSConn.CheckNetworkError(E, Self) then raise; end; end; {-------------------------------------------------------------------------------} initialization FDPhysManager(); FDPhysManagerObj.RegisterDriverClass(TFDPhysDataSnapDriver); finalization // FDPhysManagerObj.UnRegisterDriverClass(TFDPhysDataSnapDriver); end.
// ****************************************************************** // // Program Name : AT Software_DNA Library // Program Version: 1.00 // Platform(s) : OS X, Win32, Win64 // Framework : FireMonkey // // Filenames : AT.DNA.FMX.Dlg.Reactivation.pas/.fmx // File Version : 1.30 // Date Created : 04-MAY-2016 // Author : Matthew S. Vesperman // // Description: // // Re-activation dialog for Software_DNA - FireMonkey version for // cross-platform. // // Revision History: // // v1.00 : Initial version // v1.10 : 01-JUN-2016 // + text field trimming // v1.20 : 28-JUN-2016 // * Refactored code // v1.30 : 02-JUL-2016 // * Implemented resource strings // // ****************************************************************** // // COPYRIGHT © 2015 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** unit AT.DNA.FMX.Dlg.Reactivation; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, AT.DNA.FMX.Dlg.Base, System.ImageList, FMX.ImgList, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit, AT.SoftwareDNA.Types; type /// <summary> /// Reactivation dialog for Software_DNA. /// </summary> TDNAReactivationDlg = class(TDNABaseDlg) btnClearConfNewPwd: TClearEditButton; btnClearCurrPwd: TClearEditButton; btnClearNewPwd: TClearEditButton; btnForgotPwd: TButton; btnShowConfNewPwd: TPasswordEditButton; btnShowCurrPwd: TPasswordEditButton; btnShowNewPwd: TPasswordEditButton; lblConfirmNewPwd: TLabel; lblCurrentPwd: TLabel; lblNewPassword: TLabel; shpInfoDivider: TLine; txtConfirmPassword: TEdit; txtCurrentPwd: TEdit; txtNewPassword: TEdit; procedure ForgotPwdButtonClicked(Sender: TObject); strict private /// <summary> /// Stores the value of the ActivationCode property. /// </summary> FActivationCode: String; /// <summary> /// Stores a reference to the forgot password handler. /// </summary> FForgotPwdHandler: TDNAForgotPwdHandler; /// <summary> /// Stores a reference to the OnForgotPassword event handler. /// </summary> FOnForgotPassword: TNotifyEvent; /// <summary> /// CurrentPassword property getter. /// </summary> function GetCurrentPassword: String; /// <summary> /// NewPassword property getter. /// </summary> function GetNewPassword: String; /// <summary> /// ActivationCode property setter. /// </summary> procedure SetActivationCode(const Value: String); /// <summary> /// CurrentPassword property setter. /// </summary> procedure SetCurrentPassword(const Value: String); /// <summary> /// NewPassword property setter. /// </summary> procedure SetNewPassword(const Value: String); strict protected procedure InitControls; override; procedure InitFields; override; function ValidateFields: Boolean; override; public /// <summary> /// Called to attach a handler to the dialog to be called when /// the forgot password button is clicked. /// </summary> /// <param name="AHandler"> /// Pass a reference to a procedure to set the handler, pass /// NIL to clear it. /// </param> /// <remarks> /// AHandler MUST match the signature of TDNAForgotPwdHandler. /// </remarks> /// <seealso cref="TDNAForgotPwdHandler" /> procedure AttachForgotPwdHandler(AHandler: TDNAForgotPwdHandler); published /// <summary> /// Sets/Gets the activation code for the dialog box. /// </summary> property ActivationCode: String read FActivationCode write SetActivationCode; /// <summary> /// Sets/Gets the current password field of the dialog box. /// </summary> property CurrentPassword: String read GetCurrentPassword write SetCurrentPassword; /// <summary> /// Sets/Gets the new password field of the dialog box. /// </summary> property NewPassword: String read GetNewPassword write SetNewPassword; /// <summary> /// Sets/Gets the reference to the OnForgotPassword event /// handler. /// </summary> property OnForgotPassword: TNotifyEvent read FOnForgotPassword write FOnForgotPassword; end; var DNAReactivationDlg: TDNAReactivationDlg; implementation {$R *.fmx} uses AT.DNA.ResourceStrings; procedure TDNAReactivationDlg.AttachForgotPwdHandler (AHandler: TDNAForgotPwdHandler); begin FForgotPwdHandler := AHandler; //Set forgot password handler... end; procedure TDNAReactivationDlg.ForgotPwdButtonClicked(Sender: TObject); begin //Check for OnForgotPassword handler... if (Assigned(FOnForgotPassword)) then FOnForgotPassword(Self); //We have one, so call it... //Check for forgot password handler... if (Assigned(FForgotPwdHandler)) then FForgotPwdHandler(Self); //We have one, so call it... end; function TDNAReactivationDlg.GetCurrentPassword: String; begin Result := txtCurrentPwd.Text.Trim; //Get current password... end; function TDNAReactivationDlg.GetNewPassword: String; begin Result := txtNewPassword.Text.Trim; //Get new password... end; procedure TDNAReactivationDlg.InitControls; begin inherited InitControls; //Call inherited... //Change OK button caption TO Re-Activate... btnOK.Text := rstrReactivate; txtCurrentPwd.SetFocus; //Set focus to current password field...... end; procedure TDNAReactivationDlg.InitFields; begin inherited InitFields; //call inherited... //Set all fields to empty string... ActivationCode := EmptyStr; CurrentPassword := EmptyStr; NewPassword := EmptyStr; end; procedure TDNAReactivationDlg.SetActivationCode(const Value: String); begin //Store activation code... FActivationCode := Value.Trim; //Set dialog caption to include activation code... Self.Caption := Format(rstrRActivateCapFmt, [FActivationCode]); end; procedure TDNAReactivationDlg.SetCurrentPassword(const Value: String); begin //Set current password field... txtCurrentPwd.Text := Value.Trim; end; procedure TDNAReactivationDlg.SetNewPassword(const Value: String); begin //Set new password and confirm new password fields... txtNewPassword.Text := Value.Trim; txtConfirmPassword.Text := Value.Trim; end; function TDNAReactivationDlg.ValidateFields: Boolean; var ACurrPwd, ANewPwd, AConfirmPwd: String; begin //Check for empty current password... ACurrPwd := txtCurrentPwd.Text.Trim; if (ACurrPwd.IsEmpty) then begin //Current password is blank, inform user... MessageDlg(rstrValCPwdEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtCurrentPwd.SetFocus; //set focus to current pwd control... Exit(False); //Validation failure... end; //Check for empty new password field... ANewPwd := txtNewPassword.Text.Trim; if (ANewPwd.IsEmpty) then begin //New password is blank, inform user... MessageDlg(rstrValNPwdEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtNewPassword.SetFocus; //Set focus to new pwd control... Exit(False); //Validation failure... end; //Ensure new password is different than current pwd... if (ANewPwd.CompareTo(ACurrPwd) = 0) then begin //New and current passwords match, inform user... MessageDlg(rstrValCPwdNPwdMatch, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtNewPassword.SetFocus; //Set focus to new pwd control... Exit(False); //Validation failure... end; //Check if confirm password is blank... AConfirmPwd := txtConfirmPassword.Text.Trim; if (AConfirmPwd.IsEmpty) then begin //Confirm pwd is blank, inform user... MessageDlg(rstrValNPwdConfirmEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmPassword.SetFocus; //Set focus to confirm pwd... Exit(False); //Validation failure... end; //Make sure confirm password does not match current pwd... if (AConfirmPwd.CompareTo(ACurrPwd) = 0) then begin //Confirm matches current pwd, inform user... MessageDlg(rstrValPwdConfirmWrong, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmPassword.SetFocus; //Set focus to confirm pwd... Exit(False); //Validation failure... end; //Ensure new password and confirm passwords match... if (ANewPwd.CompareTo(AConfirmPwd) <> 0) then begin //new and confirm pwds do not match, inform user... MessageDlg(rstrValNPwdMismatch, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmPassword.SetFocus; //Set focus to confirm pwd... Exit(False); //Validation failure... end; Result := inherited ValidateFields; //call inherited... end; end.
unit TipoMoeda; interface type TTipoMoeda = (tmDinheiro = 1, tmCheque = 2, tmCartaoCredito=3, tmCartaoDebito=4, tmDeposito=5); type TTipoMoedaUtilitario = class public class function DeEnumeradoParaInteiro(TipoMoeda :TTipoMoeda) :Integer; class function DeInteiroParaEnumerado(TipoMoeda :Integer) :TTipoMoeda; end; implementation uses ExcecaoParametroInvalido; { TTipoMoedaUtilitario } class function TTipoMoedaUtilitario.DeEnumeradoParaInteiro(TipoMoeda: TTipoMoeda): Integer; begin if (TipoMoeda = tmDinheiro) then result := 1 else if (TipoMoeda = tmCheque) then result := 2 else if (TipoMoeda = tmCartaoCredito) then result := 3 else if (TipoMoeda = tmCartaoDebito) then result := 4 else if (TipoMoeda = tmDeposito) then result := 5 else raise TExcecaoParametroInvalido.Create('TTipoMoedaUtilitario', 'DeEnumeradoParaInteiro', 'TipoMoeda :TTipoMoeda'); end; class function TTipoMoedaUtilitario.DeInteiroParaEnumerado(TipoMoeda: Integer): TTipoMoeda; begin case TipoMoeda of 1: result := tmDinheiro; 2: result := tmCheque; 3: result := tmCartaoCredito; 4: result := tmCartaoDebito; 5: result := tmDeposito; else raise TExcecaoParametroInvalido.Create('TTipoFreteUtilitario', 'DeInteiroParaEnumerado', 'TipoFrete :TTipoFrete'); end; end; end.
unit UFolderSelect; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted 2002-2011 by Bradford Technologies, Inc. } { } { This unit is used to display a dialog to show folders and images} {$WARN SYMBOL_PLATFORM OFF} {$WARN UNIT_PLATFORM OFF} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, RzTreeVw, RzShellCtrls, RzListVw, UForms; type TSelectFiles = class(TAdvancedForm) StatusBar1: TStatusBar; RzShellList: TRzShellList; RzShellTree: TRzShellTree; Panel1: TPanel; btnOK: TButton; btnCancel: TButton; cbxShowList: TCheckBox; rdoLoadAll: TRadioButton; rdoManualSelect: TRadioButton; procedure cbxShowListClick(Sender: TObject); procedure rdoLoadAllClick(Sender: TObject); procedure rdoManualSelectClick(Sender: TObject); private { Private declarations } public constructor Create(AOwner: TComponent); Override; end; function GetSelectedFiles(var startDir: String): TStringList; function SelectOneFolder(wTitle, startDir: String): String; var SelectFiles: TSelectFiles; implementation {$R *.dfm} Uses UStrings; function GetSelectedFiles(var startDir: String): TStringList; var selFiles: TSelectFiles; pathStr: String; i: integer; fileList: TStringList; begin fileList := nil; selFiles := TSelectFiles.Create(nil); selFiles.RzShellTree.HideSelection := False; selFiles.RzShellList.HideSelection := False; selFiles.RzShellTree.SelectedFolder.PathName := startDir; try if selFiles.showmodal = mrOK then with selFiles.RzShellList do begin fileList := TStringList.create; if MultiSelect and (SelCount > 0) then begin for i := 0 to Items.count-1 do if Items.Item[i].Selected then if (not ShellListData[i].IsFolder) and (not ShellListData[i].IsLnkShortcut) and ShellListData[i].IsFileSystem then begin pathStr := ShellListData[i].PathName; if length(pathStr) > 0 then fileList.add(pathStr); end; end else begin for i := 0 to Items.count-1 do if (not ShellListData[i].IsFolder) and (not ShellListData[i].IsLnkShortcut) and ShellListData[i].IsFileSystem then begin pathStr := ShellListData[i].PathName; if length(pathStr) > 0 then fileList.add(pathStr); end; end; //do we have anything to return if fileList.Count = 0 then FreeAndNil(fileList); end; finally startDir := selFiles.RzShellTree.SelectedFolder.PathName; selFiles.free; result := fileList; end; end; function SelectOneFolder(wTitle, startDir: String): String; var selFiles: TSelectFiles; begin result := startDir; selFiles := TSelectFiles.Create(nil); selFiles.Caption := wTitle; selFiles.rdoLoadAll.Visible := False; selFiles.rdoManualSelect.Visible := False; selFiles.RzShellTree.HideSelection := False; selFiles.RzShellList.HideSelection := False; selFiles.RzShellTree.SelectedFolder.PathName := startDir; try if selFiles.showmodal = mrOK then result := selFiles.RzShellTree.SelectedFolder.PathName; finally selFiles.free; end; end; { TSelectFiles } constructor TSelectFiles.Create(AOwner: TComponent); begin inherited; rdoLoadAll.checked := True; cbxShowList.checked := True; RzShellList.MultiSelect := False; RzShellList.FileFilter := SupportedImageFormats; // 061711 JWyatt Override any automatic settings to ensure that these buttons // appear and move properly at 120DPI. // btnOK.Left := Panel1.Left + 287; btnOK.Left := 315; btnOK.Width := 75; // btnCancel.Left := Panel1.Left + 383; btnCancel.Left := 403; btnCancel.Width := 75; end; procedure TSelectFiles.cbxShowListClick(Sender: TObject); begin if cbxShowList.checked then RzShellList.ViewStyle := vsReport else RzShellList.ViewStyle := vsIcon; end; procedure TSelectFiles.rdoLoadAllClick(Sender: TObject); begin RzShellList.MultiSelect := False; end; procedure TSelectFiles.rdoManualSelectClick(Sender: TObject); begin RzShellList.MultiSelect := True; end; end.
unit RepositorioParametrosNFCe; interface uses DB, Auditoria, Repositorio; type TRepositorioParametrosNFCe = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses SysUtils, ParametrosNFCe, StrUtils; { TRepositorioParametrosNFCe } function TRepositorioParametrosNFCe.Get(Dataset: TDataSet): TObject; var ParametrosNFCe :TParametrosNFCe; begin ParametrosNFCe:= TParametrosNFCe.Create; ParametrosNFCe.Codigo := self.FQuery.FieldByName('codigo').AsInteger; ParametrosNFCe.FormaEmissao := self.FQuery.FieldByName('forma_emissao').AsInteger; ParametrosNFCe.IntervaloTentativas := self.FQuery.FieldByName('intervalo_tentativas').AsInteger; ParametrosNFCe.Tentativas := self.FQuery.FieldByName('tentativas').AsInteger; ParametrosNFCe.VersaoDF := self.FQuery.FieldByName('versao_df').AsInteger; ParametrosNFCe.ID_TOKEN := self.FQuery.FieldByName('id_token').AsString; ParametrosNFCe.TOKEN := self.FQuery.FieldByName('token').AsString; ParametrosNFCe.Certificado := self.FQuery.FieldByName('certificado').AsString; ParametrosNFCe.senha := self.FQuery.FieldByName('senha').AsString; ParametrosNFCe.DANFE.VisualizarImpressao := (self.FQuery.FieldByName('visualiza_impressao').AsString = 'S'); ParametrosNFCe.DANFE.ViaConsumidor := (self.FQuery.FieldByName('via_consumidor').AsString = 'S'); ParametrosNFCe.DANFE.ImprimirItens := (self.FQuery.FieldByName('imprime_itens').AsString = 'S'); ParametrosNFCe.Ambiente := IfThen(self.FQuery.FieldByName('ambiente').AsString = 'P', 'Produção','Homologação'); result := ParametrosNFCe; end; function TRepositorioParametrosNFCe.GetIdentificador(Objeto: TObject): Variant; begin result := TParametrosNFCe(Objeto).Codigo; end; function TRepositorioParametrosNFCe.GetNomeDaTabela: String; begin result := 'PARAMETROS_NFCE'; end; function TRepositorioParametrosNFCe.GetRepositorio: TRepositorio; begin result := TRepositorioParametrosNFCe.Create; end; function TRepositorioParametrosNFCe.IsInsercao(Objeto: TObject): Boolean; begin result := (TParametrosNFCe(Objeto).Codigo <= 0); end; procedure TRepositorioParametrosNFCe.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var ParametrosNFCeAntigo :TParametrosNFCe; ParametrosNFCeNovo :TParametrosNFCe; begin ParametrosNFCeAntigo := (AntigoObjeto as TParametrosNFCe); ParametrosNFCeNovo := (Objeto as TParametrosNFCe); if (ParametrosNFCeAntigo.FormaEmissao <> ParametrosNFCeNovo.FormaEmissao) then Auditoria.AdicionaCampoAlterado('forma_emissao', IntToStr(ParametrosNFCeAntigo.FormaEmissao), IntToStr(ParametrosNFCeNovo.FormaEmissao)); if (ParametrosNFCeAntigo.IntervaloTentativas <> ParametrosNFCeNovo.IntervaloTentativas) then Auditoria.AdicionaCampoAlterado('intervalo_tentativas', IntToStr(ParametrosNFCeAntigo.IntervaloTentativas), IntToStr(ParametrosNFCeNovo.IntervaloTentativas)); if (ParametrosNFCeAntigo.tentativas <> ParametrosNFCeNovo.tentativas) then Auditoria.AdicionaCampoAlterado('tentativas', IntToStr(ParametrosNFCeAntigo.tentativas), IntToStr(ParametrosNFCeNovo.tentativas)); if (ParametrosNFCeAntigo.VersaoDF <> ParametrosNFCeNovo.VersaoDF) then Auditoria.AdicionaCampoAlterado('versao_df', IntToStr(ParametrosNFCeAntigo.VersaoDF), IntToStr(ParametrosNFCeNovo.VersaoDF)); if (ParametrosNFCeAntigo.ID_TOKEN <> ParametrosNFCeNovo.id_token) then Auditoria.AdicionaCampoAlterado('id_token', ParametrosNFCeAntigo.id_token, ParametrosNFCeNovo.id_token); if (ParametrosNFCeAntigo.token <> ParametrosNFCeNovo.TOKEN) then Auditoria.AdicionaCampoAlterado('token', ParametrosNFCeAntigo.token, ParametrosNFCeNovo.token); if (ParametrosNFCeAntigo.certificado <> ParametrosNFCeNovo.certificado) then Auditoria.AdicionaCampoAlterado('certificado', ParametrosNFCeAntigo.certificado, ParametrosNFCeNovo.certificado); if (ParametrosNFCeAntigo.senha <> ParametrosNFCeNovo.senha) then Auditoria.AdicionaCampoAlterado('senha', ParametrosNFCeAntigo.senha, ParametrosNFCeNovo.senha); if (ParametrosNFCeAntigo.Ambiente <> ParametrosNFCeNovo.Ambiente) then Auditoria.AdicionaCampoAlterado('ambiente', ParametrosNFCeAntigo.Ambiente, ParametrosNFCeNovo.Ambiente); end; procedure TRepositorioParametrosNFCe.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var ParametrosNFCe :TParametrosNFCe; begin ParametrosNFCe := (Objeto as TParametrosNFCe); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(ParametrosNFCe.codigo)); Auditoria.AdicionaCampoExcluido('forma_emissao' , IntToStr(ParametrosNFCe.FormaEmissao)); Auditoria.AdicionaCampoExcluido('intervalo_tentativas', IntToStr(ParametrosNFCe.IntervaloTentativas)); Auditoria.AdicionaCampoExcluido('tentativas' , IntToStr(ParametrosNFCe.tentativas)); Auditoria.AdicionaCampoExcluido('versao_df' , IntToStr(ParametrosNFCe.VersaoDF)); Auditoria.AdicionaCampoExcluido('id_token' , ParametrosNFCe.id_token); Auditoria.AdicionaCampoExcluido('token' , ParametrosNFCe.token); Auditoria.AdicionaCampoExcluido('certificado' , ParametrosNFCe.certificado); Auditoria.AdicionaCampoExcluido('senha' , ParametrosNFCe.senha); Auditoria.AdicionaCampoExcluido('ambiente' , ParametrosNFCe.Ambiente); end; procedure TRepositorioParametrosNFCe.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var ParametrosNFCe :TParametrosNFCe; begin ParametrosNFCe := (Objeto as TParametrosNFCe); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(ParametrosNFCe.codigo)); Auditoria.AdicionaCampoIncluido('forma_emissao' , IntToStr(ParametrosNFCe.FormaEmissao)); Auditoria.AdicionaCampoIncluido('intervalo_tentativas', IntToStr(ParametrosNFCe.IntervaloTentativas)); Auditoria.AdicionaCampoIncluido('tentativas' , IntToStr(ParametrosNFCe.tentativas)); Auditoria.AdicionaCampoIncluido('versao_df' , IntToStr(ParametrosNFCe.VersaoDF)); Auditoria.AdicionaCampoIncluido('id_token' , ParametrosNFCe.id_token); Auditoria.AdicionaCampoIncluido('token' , ParametrosNFCe.token); Auditoria.AdicionaCampoIncluido('certificado' , ParametrosNFCe.certificado); Auditoria.AdicionaCampoIncluido('senha' , ParametrosNFCe.senha); Auditoria.AdicionaCampoIncluido('Ambiente' , ParametrosNFCe.Ambiente); end; procedure TRepositorioParametrosNFCe.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TParametrosNFCe(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioParametrosNFCe.SetParametros(Objeto: TObject); var ParametrosNFCe :TParametrosNFCe; begin ParametrosNFCe := (Objeto as TParametrosNFCe); self.FQuery.ParamByName('codigo').AsInteger := ParametrosNFCe.codigo; self.FQuery.ParamByName('forma_emissao').AsInteger := ParametrosNFCe.FormaEmissao; self.FQuery.ParamByName('intervalo_tentativas').AsInteger := ParametrosNFCe.IntervaloTentativas; self.FQuery.ParamByName('tentativas').AsInteger := ParametrosNFCe.tentativas; self.FQuery.ParamByName('versao_df').AsInteger := ParametrosNFCe.VersaoDF; self.FQuery.ParamByName('id_token').AsString := ParametrosNFCe.id_token; self.FQuery.ParamByName('token').AsString := ParametrosNFCe.token; self.FQuery.ParamByName('certificado').AsString := ParametrosNFCe.certificado; self.FQuery.ParamByName('senha').AsString := ParametrosNFCe.senha; self.FQuery.ParamByName('visualiza_impressao').AsString := IfThen( ParametrosNFCe.DANFE.VisualizarImpressao, 'S', 'N'); self.FQuery.ParamByName('via_consumidor').AsString := IfThen( ParametrosNFCe.DANFE.ViaConsumidor, 'S', 'N'); self.FQuery.ParamByName('imprime_itens').AsString := IfThen( ParametrosNFCe.DANFE.ImprimirItens, 'S', 'N'); self.FQuery.ParamByName('ambiente').AsString := Copy(ParametrosNFCe.ambiente,1,1); end; function TRepositorioParametrosNFCe.SQLGet: String; begin result := 'select * from PARAMETROS_NFCE where codigo = :ncod'; end; function TRepositorioParametrosNFCe.SQLGetAll: String; begin result := 'select * from PARAMETROS_NFCE'; end; function TRepositorioParametrosNFCe.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from PARAMETROS_NFCE where '+ campo +' = :ncampo'; end; function TRepositorioParametrosNFCe.SQLRemover: String; begin result := ' delete from PARAMETROS_NFCE where codigo = :codigo '; end; function TRepositorioParametrosNFCe.SQLSalvar: String; begin result := 'update or insert into PARAMETROS_NFCE (CODIGO ,FORMA_EMISSAO ,INTERVALO_TENTATIVAS ,TENTATIVAS ,VERSAO_DF ,ID_TOKEN ,TOKEN '+ ' ,CERTIFICADO ,SENHA, VISUALIZA_IMPRESSAO, VIA_CONSUMIDOR, IMPRIME_ITENS) '+ ' values ( :CODIGO , :FORMA_EMISSAO , :INTERVALO_TENTATIVAS , :TENTATIVAS , :VERSAO_DF , :ID_TOKEN , '+ ' :TOKEN , :CERTIFICADO , :SENHA, :VISUALIZA_IMPRESSAO, :VIA_CONSUMIDOR, :IMPRIME_ITENS) '; end; end.
unit uAccionesConsultas; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uAcciones, ActnList, ImgList, TB2Item, SpTBXItem, TB2Dock, TB2Toolbar, dmConsultasMenu; const WM_MENU_COUNT = WM_USER + 1; type TAccionesConsultas = class(TAcciones) Administrar: TAction; MenuConsultas: TSpTBXSubmenuItem; SpTBXItem1: TSpTBXItem; SpTBXSeparatorItem1: TSpTBXSeparatorItem; procedure AdministrarExecute(Sender: TObject); procedure MenuConsultasPopup(Sender: TTBCustomItem; FromLink: Boolean); private MustCalculateValores: boolean; MenuCreated: boolean; ConsultasMenu: TConsultasMenu; UltimaOIDSesion: integer; OIDValores: TArrayInteger; OIDConsultaMenus: TArrayInteger; procedure MenuCount(var Msg: TMessage); message WM_MENU_COUNT; procedure OnMercadoGrupoCambiado; procedure OnTipoCotizacionCambiada; procedure InicializarMenuCount; procedure CalculateValores; procedure UpdateMenuCount(const menu: TSpTBXItem; const num: Integer); procedure BuscarOIDConsultaMenus; procedure CreateMenus; procedure OnClikMenuConsulta(Sender: TObject); procedure CrearConsulta(const OID: integer; const nombre: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetBarras: TBarras; override; end; implementation uses uAccionesGrafico, UtilForms, fmConsultas, VirtualTrees, frFS, dmConsultas, fmConsulta, dmData, BusCommunication, dmAccionesValor, UtilDB, dmFS, UtilFS, StrUtils; {$R *.dfm} type TMenuCountItem = class(TMenuFSItem) end; const NUM_DESCONOCIDO: integer = -1; function CrearMenuItem(const AOwner: TComponent; const FS: TFS; const data: TBasicNodeData): TSpTBXItem; begin if TConsultas(FS).HasCodigoCompiled(data.OID) then begin if TConsultas(FS).DebeContar(data.OID) then begin result := TMenuCountItem.Create(AOwner); result.Caption := data.Caption + ' (?)'; end else begin result := TMenuFSItem.Create(AOwner); result.Caption := data.Caption; end; end else result := nil; end; procedure TAccionesConsultas.AdministrarExecute(Sender: TObject); begin inherited; ShowFormModal(TfConsultas); while MenuConsultas.Count > 2 do MenuConsultas.Delete(2); MenuCreated := false; end; procedure TAccionesConsultas.CalculateValores; var inspect: TInspectDataSet; i: integer; begin SetLength(OIDValores, Data.Valores.RecordCount); inspect := StartInspectDataSet(Data.Valores); try i := 0; Data.Valores.First; while not Data.Valores.Eof do begin OIDValores[i] := Data.ValoresOID_VALOR.Value; Data.Valores.Next; inc(i); end; MustCalculateValores := false; finally EndInspectDataSet(inspect); end; end; procedure TAccionesConsultas.CrearConsulta(const OID: integer; const nombre: string); var fConsulta: TfConsulta; nameConsulta: string; begin if OID < 0 then nameConsulta := '_CONSULTA_' + IntToStr(-OID) else nameConsulta := '_CONSULTA' + IntToStr(OID); fConsulta := TfConsulta(FindForm(Self, nameConsulta)); if fConsulta = nil then begin fConsulta := TfConsulta.Create(Self, OID, @OIDValores); fConsulta.Name := nameConsulta; fConsulta.Caption := nombre; fConsulta.Show; fConsulta.Buscar; end else fConsulta.Show; end; constructor TAccionesConsultas.Create(AOwner: TComponent); begin inherited Create(AOwner); ConsultasMenu := TConsultasMenu.Create(Handle); UltimaOIDSesion := -1; MustCalculateValores := true; Bus.RegisterEvent(MessageMercadoGrupoCambiado, OnMercadoGrupoCambiado); Bus.RegisterEvent(MessageTipoCotizacionCambiada, OnTipoCotizacionCambiada); end; procedure TAccionesConsultas.CreateMenus; begin Screen.Cursor := crHourGlass; try CreateMenuFormFS(Self, MenuConsultas, TConsultas, OnClikMenuConsulta, CrearMenuItem); BuscarOIDConsultaMenus; finally Screen.Cursor := crDefault; end; MenuCreated := true; end; destructor TAccionesConsultas.Destroy; begin Bus.UnregisterEvent(MessageMercadoGrupoCambiado, OnMercadoGrupoCambiado); Bus.UnregisterEvent(MessageTipoCotizacionCambiada, OnTipoCotizacionCambiada); ConsultasMenu.Free; inherited; end; function TAccionesConsultas.GetBarras: TBarras; begin result := nil; end; procedure TAccionesConsultas.InicializarMenuCount; var i, num: integer; subItem: TSpTBXItem; procedure IniSubMenuCount(const item: TSpTBXItem); var i, num: integer; subItem: TSpTBXItem; begin num := item.Count - 1; for i := 0 to num do begin subItem := TSpTBXItem(item.Items[i]); if subItem is TMenuCountItem then UpdateMenuCount(subItem, NUM_DESCONOCIDO) else IniSubMenuCount(subItem); end; end; begin num := MenuConsultas.Count - 1; for i := 2 to num do begin subItem := TSpTBXItem(MenuConsultas.Items[i]); if subItem is TMenuCountItem then UpdateMenuCount(subItem, NUM_DESCONOCIDO) else IniSubMenuCount(subItem); end; end; procedure TAccionesConsultas.MenuConsultasPopup(Sender: TTBCustomItem; FromLink: Boolean); var OIDSesion: Integer; begin inherited; if not MenuCreated then begin CreateMenus; // Si se recrean los menus, se debe volver a calcular los posibles counts. // Lo más rápido es simular que ha habido un cambio de sesión. UltimaOIDSesion := -1; end; OIDSesion := Data.OIDSesion; if (UltimaOIDSesion <> OIDSesion) or (MustCalculateValores) then begin InicializarMenuCount; if MustCalculateValores then CalculateValores; ConsultasMenu.Find(@OIDValores, @OIDConsultaMenus); UltimaOIDSesion := OIDSesion; end; end; procedure TAccionesConsultas.MenuCount(var Msg: TMessage); var OIDConsulta: integer; item: TSpTBXItem; function FindSubMenu(const item: TSpTBXItem): TSpTBXItem; var i, num: integer; subItem: TSpTBXItem; begin num := item.Count - 1; for i := 0 to num do begin subItem := TSpTBXItem(item.Items[i]); if subItem.Count = 0 then begin if (subItem is TMenuCountItem) and (TMenuCountItem(subItem).OID = OIDConsulta) then begin result := subItem; exit; end; end else begin result := FindSubMenu(subItem); if result <> nil then exit; end; end; result := nil; end; function FindItem: TSpTBXItem; var i, num: integer; subItem: TSpTBXItem; begin num := MenuConsultas.Count - 1; for i := 2 to num do begin subItem := TSpTBXItem(MenuConsultas.Items[i]); if subItem.Count = 0 then begin if (subItem is TMenuCountItem) and (TMenuCountItem(subItem).OID = OIDConsulta) then begin result := subItem; exit; end; end else begin result := FindSubMenu(subItem); if result <> nil then exit; end; end; result := nil; end; begin OIDConsulta := Msg.WParam; item := FindItem; if item <> nil then UpdateMenuCount(item, Msg.LParam); end; procedure TAccionesConsultas.OnClikMenuConsulta(Sender: TObject); begin if not (Sender is TSpTBXSubmenuItem) then with TMenuCountItem(Sender) do CrearConsulta(OID, Caption); end; procedure TAccionesConsultas.OnMercadoGrupoCambiado; begin MustCalculateValores := true; end; procedure TAccionesConsultas.OnTipoCotizacionCambiada; begin UltimaOIDSesion := -1; end; procedure TAccionesConsultas.BuscarOIDConsultaMenus; var iList, i, num: integer; subItem: TSpTBXItem; procedure AddItem(const item: TMenuCountItem); begin Inc(iList); SetLength(OIDConsultaMenus, iList); OIDConsultaMenus[iList - 1] := item.OID; end; procedure RefrescarSubMenu(const item: TSpTBXItem); var i, num: integer; subItem: TSpTBXItem; begin // primer nivel num := item.Count - 1; for i := 0 to num do begin subItem := TSpTBXItem(item.Items[i]); if subItem is TMenuCountItem then AddItem(TMenuCountItem(subItem)); end; // subniveles for i := 0 to num do begin subItem := TSpTBXItem(item.Items[i]); if subItem.Count > 0 then RefrescarSubMenu(subItem); end; end; begin SetLength(OIDConsultaMenus, 0); iList := 0; num := MenuConsultas.Count - 1; for i := 2 to num do begin subItem := TSpTBXItem(MenuConsultas.Items[i]); if subItem is TMenuCountItem then begin AddItem(TMenuCountItem(subItem)); end; end; // subniveles for i := 2 to num do begin subItem := TSpTBXItem(MenuConsultas.Items[i]); if subItem.Count > 0 then RefrescarSubMenu(subItem); end; end; procedure TAccionesConsultas.UpdateMenuCount(const menu: TSpTBXItem; const num: Integer); var i: integer; sNum, caption: string; begin caption := menu.Caption; i := length(caption); while (i > 0) and (caption[i] <> '(') do Dec(i); if i <> 0 then begin if num = NUM_DESCONOCIDO then sNum := '?' else sNum := IntToStr(num); menu.Caption := Copy(caption, 1, i) + sNum + ')'; menu.Invalidate; end; end; initialization RegisterAccionesAfter(TAccionesConsultas, TAccionesGrafico); end.
{ *************************************************************************** } { } { Audio Tools Library } { Class TWAVPackFile - for manipulating with WAVPack Files } { } { http://mac.sourceforge.net/atl/ } { e-mail: macteam@users.sourceforge.net } { } { Copyright (c) 2003-2005 by Mattias Dahlberg } { } { Version 1.3 (February 2015) by 3delite } { - Added support for the NextGen compiler } { - Added LoadFromStream() function } { } { Version 1.2 (09 August 2004) by jtclipper } { - updated to support WavPack version 4 files } { - added encoder detection } { } { Version 1.1 (April 2004) by Gambit } { - Added Ratio and Samples property } { } { Version 1.0 (August 2003) } { } { This library is free software; you can redistribute it 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. } { } { 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. } { } { You should have received a copy of the GNU Lesser General Public } { License along with this library; if not, write to the Free Software } { Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } { } { *************************************************************************** } unit WAVPackFile; interface uses Classes, SysUtils; type TWAVPackfile = class(TObject) private FFileSize: int64; FValid: boolean; FFormatTag: integer; FVersion: integer; FChannels: integer; FSampleRate: integer; FBits: integer; FBitrate: double; FDuration: double; FEncoder: string; FTagSize: integer; FSamples: Int64; FBSamples: Int64; procedure FResetData; function FGetRatio: Double; function FGetChannelMode: string; public constructor Create; destructor Destroy; override; function LoadFromFile(const FileName: String; TagSize: Integer): Boolean; function LoadFromStream(Stream: TStream; TagSize: Integer): Boolean; function _ReadV3( f: TStream ): boolean; function _ReadV4( f: TStream ): boolean; property FileSize: int64 read FFileSize; property Valid: boolean read FValid; property FormatTag: integer read FFormatTag; property Version: integer read FVersion; property Channels: integer read FChannels; property ChannelMode: string read FGetChannelMode; property SampleRate: integer read FSamplerate; property Bits: integer read FBits; property Bitrate: double read FBitrate; property Duration: double read FDuration; property Samples: Int64 read FSamples; property BSamples: Int64 read FBSamples; property Ratio: Double read FGetRatio; property Encoder: string read FEncoder; end; implementation type wavpack_header3 = record ckID: array[0..3] of Byte; ckSize: longword; version: word; bits: word ; flags: word; shift: word; total_samples: longword; crc: longword; crc2: longword; extension: array[0..3] of Byte; extra_bc: byte; extras: array[0..2] of Byte; end; wavpack_header4 = record ckID: array[0..3] of Byte; ckSize: longword; version: word; track_no: byte; index_no: byte; total_samples: longword; block_index: longword; block_samples: longword; flags: longword; crc: longword; end; fmt_chunk = record wformattag: word; wchannels: word; dwsamplespersec: longword; dwavgbytespersec: longword; wblockalign: word; wbitspersample: word; end; riff_chunk = record id: array[0..3] of Byte; size: longword; end; const //version 3 flags MONO_FLAG_v3 = 1; // not stereo FAST_FLAG_v3 = 2; // non-adaptive predictor and stereo mode // RAW_FLAG_v3 = 4; // raw mode (no .wav header) // CALC_NOISE_v3 = 8; // calc noise in lossy mode (no longer stored) HIGH_FLAG_v3 = $10; // high quality mode (all modes) // BYTES_3_v3 = $20; // files have 3-byte samples // OVER_20_v3 = $40; // samples are over 20 bits WVC_FLAG_v3 = $80; // create/use .wvc (no longer stored) // LOSSY_SHAPE_v3 = $100; // noise shape (lossy mode only) // VERY_FAST_FLAG_v3 = $200; // double fast (no longer stored) NEW_HIGH_FLAG_v3 = $400; // new high quality mode (lossless only) // CANCEL_EXTREME_v3 = $800; // cancel EXTREME_DECORR // CROSS_DECORR_v3 = $1000; // decorrelate chans (with EXTREME_DECORR flag) // NEW_DECORR_FLAG_v3 = $2000; // new high-mode decorrelator // JOINT_STEREO_v3 = $4000; // joint stereo (lossy and high lossless) EXTREME_DECORR_v3 = $8000; // extra decorrelation (+ enables other flags) sample_rates: array[0..14] of integer = ( 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 ); { --------------------------------------------------------------------------- } procedure TWAVPackfile.FResetData; begin FFileSize := 0; FTagSize := 0; FValid := false; FFormatTag := 0; FChannels := 0; FSampleRate := 0; FBits := 0; FBitrate := 0; FDuration := 0; FVersion := 0; FEncoder := ''; FSamples := 0; FBSamples := 0; //FAPEtag.Clear; end; { --------------------------------------------------------------------------- } constructor TWAVPackfile.Create; begin inherited; //FAPEtag := TAPEv2Tag.Create; FResetData; end; destructor TWAVPackfile.Destroy; begin //FAPEtag.Free; inherited; end; { --------------------------------------------------------------------------- } function TWAVPackfile.FGetChannelMode: string; begin case FChannels of 1: result := 'Mono'; 2: result := 'Stereo'; else result := 'Surround'; end; end; { --------------------------------------------------------------------------- } function TWAVPackfile.LoadFromFile(const FileName: String; TagSize: Integer): Boolean; var f: TStream; begin FResetData; try f := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); Result := LoadFromStream(f, TagSize); finally FreeAndNil(f); end; end; function TWAVPackfile.LoadFromStream(Stream: TStream; TagSize: Integer): Boolean; var marker: array[0..3] of Byte; begin FResetData; FTagSize := TagSize; FFileSize := Stream.Size; //read first bytes FillChar( marker, SizeOf(marker), 0); Stream.Read(marker, SizeOf(marker)); Stream.Seek(0, soBeginning); if (marker[0] = Ord('R')) AND (marker[1] = Ord('I')) AND (marker[2] = Ord('F')) AND (marker[3] = Ord('F')) then begin result := _ReadV3(Stream); end else if (marker[0] = Ord('w')) AND (marker[1] = Ord('v')) AND (marker[2] = Ord('p')) AND (marker[3] = Ord('k')) then begin Result := _ReadV4(Stream); end else begin Result := False; end; end; { --------------------------------------------------------------------------- } function TWAVPackfile._ReadV4(f: TStream): boolean; var wvh4: wavpack_header4; EncBuf : array[1..4096] of Byte; tempo : Integer; encoderbyte: Byte; begin Result := False; FillChar( wvh4, SizeOf(wvh4) ,0); f.Read(wvh4, SizeOf(wvh4)); if (wvh4.ckID[0] = Ord('w')) AND (wvh4.ckID[1] = Ord('v')) AND (wvh4.ckID[2] = Ord('p')) AND (wvh4.ckID[3] = Ord('k')) then // wavpack header found begin Result := true; FValid := true; FVersion := wvh4.version shr 8; FChannels := 2 - (wvh4.flags and 4); // mono flag FBits := ((wvh4.flags and 3) * 16); // bytes stored flag FSamples := wvh4.total_samples; FBSamples := wvh4.block_samples; FSampleRate := (wvh4.flags and ($1F shl 23)) shr 23; if (FSampleRate > 14) or (FSampleRate < 0) then begin FSampleRate := 44100; end else begin FSampleRate := sample_rates[FSampleRate]; end; if ((wvh4.flags and 8) = 8) then // hybrid flag begin FEncoder := 'hybrid lossy'; end else begin //if ((wvh4.flags and 2) = 2) then begin // lossless flag FEncoder := 'lossless'; end; { if ((wvh4.flags and $20) > 0) then // MODE_HIGH begin FEncoder := FEncoder + ' (high)'; end else if ((wvh4.flags and $40) > 0) then // MODE_FAST begin FEncoder := FEncoder + ' (fast)'; end; } FDuration := wvh4.total_samples / FSampleRate; if FDuration > 0 then begin FBitrate := (FFileSize - int64( FTagSize ) ) * 8 / (FSamples / FSampleRate) / 1000; end; FillChar(EncBuf, SizeOf(EncBuf), 0); f.Read(EncBuf, SizeOf(EncBuf)); for tempo := 1 to 4094 do begin If EncBuf[tempo] = $65 then if EncBuf[tempo + 1] = $02 then begin encoderbyte := EncBuf[tempo + 2]; if encoderbyte = 8 then FEncoder := FEncoder + ' (high)' else if encoderbyte = 0 then FEncoder := FEncoder + ' (normal)' else if encoderbyte = 2 then FEncoder := FEncoder + ' (fast)' else if encoderbyte = 6 then FEncoder := FEncoder + ' (very fast)'; Break; end; end; end; end; { --------------------------------------------------------------------------- } function TWAVPackfile._ReadV3(f: TStream): boolean; var chunk: riff_chunk; wavchunk: array[0..3] of Byte; fmt: fmt_chunk; hasfmt: boolean; fpos: int64; wvh3: wavpack_header3; begin Result := False; hasfmt := False; // read and evaluate header FillChar( chunk, sizeof(chunk), 0 ); if (f.Read(chunk, sizeof(chunk)) <> SizeOf( chunk )) or (f.Read(wavchunk, sizeof(wavchunk)) <> SizeOf(wavchunk)) or (wavchunk[0] <> Ord('W')) or (wavchunk[1] <> Ord('A')) or (wavchunk[2] <> Ord('V')) or (wavchunk[3] <> Ord('E')) then exit; // start looking for chunks FillChar( chunk, SizeOf(chunk), 0 ); while (f.Position < f.Size) do begin if (f.read(chunk, sizeof(chunk)) < sizeof(chunk)) or (chunk.size <= 0) then break; fpos := f.Position; if (chunk.id[0] = Ord('f')) AND (chunk.id[1] = Ord('m')) AND (chunk.id[2] = Ord('t')) AND (chunk.id[3] = Ord(' ')) then begin // Format chunk found read it if (chunk.size >= sizeof(fmt)) and (f.Read(fmt, sizeof(fmt)) = sizeof(fmt)) then begin hasfmt := true; result := True; FValid := true; FFormatTag := fmt.wformattag; FChannels := fmt.wchannels; FSampleRate := fmt.dwsamplespersec; FBits := fmt.wbitspersample; FBitrate := fmt.dwavgbytespersec / 125.0; // 125 = 1/8*1000 end else begin Break; end; end else if (chunk.id[0] = Ord('d')) AND (chunk.id[1] = Ord('a')) AND (chunk.id[2] = Ord('t')) AND (chunk.id[3] = Ord('a')) and hasfmt then begin FillChar( wvh3, SizeOf(wvh3) ,0); f.Read( wvh3, SizeOf(wvh3) ); if (wvh3.ckID[0] = Ord('w')) AND (wvh3.ckID[1] = Ord('v')) AND (wvh3.ckID[2] = Ord('p')) AND (wvh3.ckID[3] = Ord('k')) then begin // wavpack header found result := true; FValid := true; FVersion := wvh3.version; FChannels := 2 - (wvh3.flags and 1); // mono flag FSamples := wvh3.total_samples; // Encoder guess if wvh3.bits > 0 then begin if (wvh3.flags and NEW_HIGH_FLAG_v3) > 0 then begin FEncoder := 'hybrid'; if (wvh3.flags and WVC_FLAG_v3) > 0 then begin FEncoder := FEncoder + ' lossless'; end else begin FEncoder := FEncoder + ' lossy'; end; if (wvh3.flags and EXTREME_DECORR_v3) > 0 then FEncoder := FEncoder + ' (high)'; end else if (wvh3.flags and (HIGH_FLAG_v3 or FAST_FLAG_v3)) = 0 then begin FEncoder := IntToStr( wvh3.bits + 3 ) + '-bit lossy'; end else begin FEncoder := IntToStr( wvh3.bits + 3 ) + '-bit lossy'; if (wvh3.flags and HIGH_FLAG_v3) > 0 then begin FEncoder := FEncoder + ' high'; end else begin FEncoder := FEncoder + ' fast'; end end; end else begin if (wvh3.flags and HIGH_FLAG_v3) = 0 then begin FEncoder := 'lossless (fast mode)'; end else if (wvh3.flags and EXTREME_DECORR_v3) > 0 then begin FEncoder := 'lossless (high mode)'; end else begin FEncoder := 'lossless'; end; end; if FSampleRate <= 0 then FSampleRate := 44100; FDuration := wvh3.total_samples / FSampleRate; if FDuration > 0 then FBitrate := 8.0*(FFileSize - int64( FTagSize ) - int64(wvh3.ckSize))/(FDuration*1000.0); end; Break; end else begin // not a wv file Break; end; f.seek(fpos + chunk.size, soBeginning); end; // while end; { --------------------------------------------------------------------------- } function TWAVPackfile.FGetRatio: Double; begin { Get compression ratio } if FValid then Result := FFileSize / (FSamples * (FChannels * FBits / 8) + 44) * 100 else Result := 0; end; { --------------------------------------------------------------------------- } end.
{* SDEVICE.PAS * * Sound Device definitions * * Copyright 1995 Petteri Kangaslampi and Jarno Paananen * * This file is part of the MIDAS Sound System, and may only be * used, modified and distributed under the terms of the MIDAS * Sound System license, LICENSE.TXT. By continuing to use, * modify or distribute this file you indicate that you have * read the license and understand and accept it fully. *} unit SDevice; {$define NOLOADERS} {$define CUTDOWN} interface const SMPMAX = 65519; { max sample length (65536-16 - 1) } MAXINSTS = 256; { maximum number of instruments } {****************************************************************************\ * enum smpTypes * ------------- * Description: Sample types \****************************************************************************} const smpNone = 0; { no sample } smp8bit = 1; { 8-bit unsigned sample } {****************************************************************************\ * enum sdPanning * -------------- * Description: Sound Device panning values. Legal values range from * panLeft to panRight, in steps of 1, plus panSurround. * Surround sound is played from middle if surround is not * enabled. \****************************************************************************} const panLeft = -64; { left speaker } panMiddle = 0; { middle (both speakers) } panRight = 64; { right speaker } panSurround = $80; { surround sound } {****************************************************************************\ * enum sdSmpPos * ------------- * Description: Sample positions in memory \****************************************************************************} const sdSmpNone = 0; { no sample } sdSmpConv = 1; { conventional memory } sdSmpEMS = 2; { EMS } {****************************************************************************\ * enum sdStatus * ------------- * Description: SoundDevice status \****************************************************************************} const sdUnInitialized = 0; sdOK = 1; {****************************************************************************\ * enum sdMode * ----------- * Description: Possible SoundDevice output modes \****************************************************************************} const sdMono = 1; { mono } sdStereo = 2; { stereo } sd8bit = 4; { 8-bit output } sd16bit = 8; { 16-bit output } {****************************************************************************\ * enum sdConfigBits * ----------------- * Description: Sound Device configuration information bits \****************************************************************************} const sdUsePort = 1; { SD uses an I/O port } sdUseIRQ = 2; { SD uses an IRQ } sdUseDMA = 4; { SD uses a DMA channel } sdUseMixRate = 8; { SD uses the set mixing rate } sdUseOutputMode = 16; { SD uses the set output mode } sdUseDSM = 32; { SD uses software mixing (DSM) } {****************************************************************************\ * struct SoundDevice * ------------------ * Description: SoundDevice structure. See SDEVICE.TXT for documentation \****************************************************************************} { Sound Device function pointer types: } type Pinteger = ^integer; Pbyte = ^byte; Pword = ^word; Plongint = ^longint; sdDetect = function(result : Pinteger) : integer; sdInit = function(mixRate, mode : word) : integer; sdClose = function : integer; sdGetMixRate = function(mixRate : Pword) : integer; sdGetMode = function(mode : Pword) : integer; sdOpenChannels = function(channels : word) : integer; sdCloseChannels = function : integer; sdClearChannels = function : integer; sdMute = function(mute : integer) : integer; sdPause = function(pause : integer) : integer; sdSetMasterVolume = function(masterVolume : byte) : integer; sdGetMasterVolume = function(masterVolume : Pbyte) : integer; sdSetAmplification = function(amplification : word) : integer; sdGetAmplification = function(amplification : Pword) : integer; sdPlaySound = function(channel : word; rate : longint) : integer; sdStopSound = function(channel : word) : integer; sdSetRate = function(channel : word; rate : longint) : integer; sdGetRate = function(channel : word; rate : Plongint) : integer; sdSetVolume = function(channel : word; volume : byte) : integer; sdGetVolume = function(channel : word; volume : Pbyte) : integer; sdSetInstrument = function(channel : word; inst : word) : integer; sdGetInstrument = function(channel : word; inst : Pword) : integer; sdSetPosition = function(channel : word; pos : word) : integer; sdGetPosition = function(channel : word; pos : Pword) : integer; sdSetPanning = function(channel : word; panning : integer) : integer; sdGetPanning = function(channel : word; panning : Pinteger) : integer; sdMuteChannel = function(channel : word; mute : integer) : integer; sdAddInstrument = function(sample : pointer; smpType : integer; length, loopStart, loopEnd : word; volume : byte; loop : integer; copySample : integer; instHandle : Pword) : integer; sdRemInstrument = function(inst : word) : integer; sdSetUpdRate = function(updRate : word) : integer; sdStartPlay = function : integer; sdPlay = function(callMP : Pinteger) : integer; PcharArray = array[0..1023] of Pchar; PPcharArray = ^PcharArray; { actual Sound Device structure: } SoundDevice = Record tempoPoll : word; configBits : word; { Configuration info bits. See enum sdConfigBits. } port : word; { Sound Device I/O port address } IRQ : byte; { Sound Device IRQ number } DMA : byte; { Sound Device DMA channel number } cardType : word; { Sound Device sound card type. Starting from 1, 0 means autodetect } numCardTypes : word; { number of different sound card types for this Sound Device } status : word; { Sound Device status } modes : word; { Possible modes for this SD, see enum sdMode } ID : Pchar; { pointer Sound Device ID string } cardNames : PPcharArray; { pointer to an array of pointers to sound card name strings } numPortAddresses : word; { number of possible port addresses in table } portAddresses : Pword; { pointer to an array of possible I/O port addresses } Detect : sdDetect; Init : sdInit; Close : sdClose; GetMixRate : sdGetMixRate; GetMode : sdGetMode; OpenChannels : sdOpenChannels; CloseChannels : sdCloseChannels; ClearChannels : sdClearChannels; Mute : sdMute; Pause : sdPause; SetMasterVolume : sdSetMasterVolume; GetMasterVolume : sdGetMasterVolume; SetAmplification : sdSetAmplification; GetAmplification : sdGetAmplification; PlaySound : sdPlaySound; StopSound : sdStopSound; SetRate : sdSetRate; GetRate : sdGetRate; SetVolume : sdSetVolume; GetVolume : sdGetVolume; SetInstrument : sdSetInstrument; GetInstrument : sdGetInstrument; SetPosition : sdSetPosition; GetPosition : sdGetPosition; SetPanning : sdSetPanning; GetPanning : sdGetPanning; MuteChannel : sdMuteChannel; AddInstrument : sdAddInstrument; RemInstrument : sdRemInstrument; SetUpdRate : sdSetUpdRate; StartPlay : sdStartPlay; Play : sdPlay; end; PSoundDevice = ^SoundDevice; {****************************************************************************\ * SoundDevice structures for all Sound Devices: \****************************************************************************} {* Note! This SHOULD NOT be here, but Borland Pascal does not allow * external variables in data segment. Sheesh. Can a language really * be this stupid? *} var GUS : SoundDevice; SB : SoundDevice; NSND : SoundDevice; implementation USES Errors, mMem, mUtils, mGlobals, DMA, DSM {$IFDEF __BPPROT__} ,DPMI {$ENDIF} ; procedure gusSD; external; {$L GUS.OBJ} procedure sbSD; external; {$L SB.OBJ} procedure nsndSD; external; {$L NSND.OBJ} BEGIN mMemCopy(@GUS, @gusSD, SizeOf(SoundDevice)); mMemCopy(@SB, @sbSD, SizeOf(SoundDevice)); mMemCopy(@NSND, @nsndSD, SizeOf(SoundDevice)) END.
{$IFDEF FREEPASCAL} {$MODE DELPHI} {$ENDIF} unit dll_gdiplus_graphic; interface uses atmcmbaseconst, winconst, wintype, dll_gdiplus; type TGPCompositingMode = ( CompositingModeSourceOver, // 0 CompositingModeSourceCopy // 1 ); TGPQualityMode = ( QualityModeInvalid = -1, QualityModeDefault = 0, QualityModeLow = 1, // Best performance QualityModeHigh = 2 // Best rendering quality ); TGPCompositingQuality = ( CompositingQualityInvalid = Ord(QualityModeInvalid), CompositingQualityDefault = Ord(QualityModeDefault), CompositingQualityHighSpeed = Ord(QualityModeLow), CompositingQualityHighQuality = Ord(QualityModeHigh), CompositingQualityGammaCorrected, CompositingQualityAssumeLinear ); (* SmoothingModeInvalid = -1; {指定一个无效模式} SmoothingModeDefault = 0; {指定不消除锯齿} SmoothingModeHighSpeed = 1; {指定高速度、低质量呈现} SmoothingModeHighQuality = 2; {指定高质量、低速度呈现} SmoothingModeNone = 3; {指定不消除锯齿} SmoothingModeAntiAlias = 4; {指定消除锯齿的呈现} *) TGPSmoothingMode = ( SmoothingModeInvalid = Ord(QualityModeInvalid), // 指定不消除锯齿 SmoothingModeDefault = Ord(QualityModeDefault), SmoothingModeHighSpeed = Ord(QualityModeLow), // 指定高速度、低质量呈现 SmoothingModeHighQuality = Ord(QualityModeHigh), SmoothingModeNone, // 指定不消除锯齿 SmoothingModeAntiAlias, // 指定消除锯齿的呈现 SmoothingModeAntiAlias8x4 = SmoothingModeAntiAlias, SmoothingModeAntiAlias8x8 = 5 ); TGPPixelOffsetMode = ( PixelOffsetModeInvalid = Ord(QualityModeInvalid), PixelOffsetModeDefault = Ord(QualityModeDefault), PixelOffsetModeHighSpeed = Ord(QualityModeLow), PixelOffsetModeHighQuality = Ord(QualityModeHigh), PixelOffsetModeNone, // No pixel offset PixelOffsetModeHalf // Offset by -0.5, -0.5 for fast anti-alias perf ); TGPInterpolationMode = ( InterpolationModeInvalid = Ord(QualityModeInvalid), InterpolationModeDefault = Ord(QualityModeDefault), InterpolationModeLowQuality = Ord(QualityModeLow), InterpolationModeHighQuality = Ord(QualityModeHigh), InterpolationModeBilinear, InterpolationModeBicubic, InterpolationModeNearestNeighbor, InterpolationModeHighQualityBilinear, InterpolationModeHighQualityBicubic ); TGPTextRenderingHint = ( TextRenderingHintSystemDefault, // Glyph with system default rendering hint TextRenderingHintSingleBitPerPixelGridFit, // Glyph bitmap with hinting TextRenderingHintSingleBitPerPixel, // Glyph bitmap without hinting TextRenderingHintAntiAliasGridFit, // Glyph anti-alias bitmap with hinting TextRenderingHintAntiAlias, // Glyph anti-alias bitmap without hinting TextRenderingHintClearTypeGridFit // Glyph CT bitmap with hinting ); TGPCoordinateSpace = ( CoordinateSpaceWorld, // 0 CoordinateSpacePage, // 1 CoordinateSpaceDevice // 2 ); GpCoordinateSpace = TGPCoordinateSpace; { GpGraphics } function GdipCreateFromHDC(ADC: HDC; out AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipCreateFromHDC2(ADC: HDC; hDevice: THandle; out AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipCreateFromHWND(AWnd: HWND; out AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipCreateFromHWNDICM(AWnd: HWND; out AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipFlush(AGraphics: TGpGraphics; intention: TGPFlushIntention): TGpStatus; stdcall; external gdiplus; function GdipDeleteGraphics(AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipGetDC(AGraphics: TGpGraphics; var ADC: HDC): TGpStatus; stdcall; external gdiplus; function GdipReleaseDC(AGraphics: TGpGraphics; ADC: HDC): TGpStatus; stdcall; external gdiplus; function GdipSetCompositingMode(AGraphics: TGpGraphics; compositingMode: TGPCompositingMode): TGpStatus; stdcall; external gdiplus; function GdipGetCompositingMode(AGraphics: TGpGraphics; var compositingMode: TGPCompositingMode): TGpStatus; stdcall; external gdiplus; function GdipSetRenderingOrigin(AGraphics: TGpGraphics; x: Integer; y: Integer): TGpStatus; stdcall; external gdiplus; function GdipGetRenderingOrigin(AGraphics: TGpGraphics; var x: Integer; var y: Integer): TGpStatus; stdcall; external gdiplus; function GdipSetCompositingQuality(AGraphics: TGpGraphics; compositingQuality: TGPCompositingQuality): TGpStatus; stdcall; external gdiplus; function GdipGetCompositingQuality(AGraphics: TGpGraphics; var compositingQuality: TGPCompositingQuality): TGpStatus; stdcall; external gdiplus; function GdipSetSmoothingMode(AGraphics: TGpGraphics; smoothingMode: TGPSmoothingMode): TGpStatus; stdcall; external gdiplus; function GdipGetSmoothingMode(AGraphics: TGpGraphics; var smoothingMode: TGPSmoothingMode): TGpStatus; stdcall; external gdiplus; function GdipSetPixelOffsetMode(AGraphics: TGpGraphics; pixelOffsetMode: TGPPixelOffsetMode): TGpStatus; stdcall; external gdiplus; function GdipGetPixelOffsetMode(AGraphics: TGpGraphics; var pixelOffsetMode: TGPPixelOffsetMode): TGpStatus; stdcall; external gdiplus; function GdipSetTextRenderingHint(AGraphics: TGpGraphics; mode: TGPTextRenderingHint): TGpStatus; stdcall; external gdiplus; function GdipGetTextRenderingHint(AGraphics: TGpGraphics; var mode: TGPTextRenderingHint): TGpStatus; stdcall; external gdiplus; function GdipSetTextContrast(AGraphics: TGpGraphics; contrast: Integer): TGpStatus; stdcall; external gdiplus; function GdipGetTextContrast(AGraphics: TGpGraphics; var contrast: UINT): TGpStatus; stdcall; external gdiplus; function GdipSetInterpolationMode(AGraphics: TGpGraphics; interpolationMode: TGPInterpolationMode): TGpStatus; stdcall; external gdiplus; function GdipGetInterpolationMode(AGraphics: TGpGraphics; var interpolationMode: TGPInterpolationMode): TGpStatus; stdcall; external gdiplus; function GdipSetWorldTransform(AGraphics: TGpGraphics; matrix: TGPMATRIX): TGpStatus; stdcall; external gdiplus; function GdipResetWorldTransform(AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipMultiplyWorldTransform(AGraphics: TGpGraphics; matrix: TGPMATRIX; order: TGPMatrixOrder): TGpStatus; stdcall; external gdiplus; function GdipTranslateWorldTransform(AGraphics: TGpGraphics; dx: Single; dy: Single; order: TGPMatrixOrder): TGpStatus; stdcall; external gdiplus; function GdipScaleWorldTransform(AGraphics: TGpGraphics; sx: Single; sy: Single; order: TGPMatrixOrder): TGpStatus; stdcall; external gdiplus; function GdipRotateWorldTransform(AGraphics: TGpGraphics; angle: Single; order: TGPMatrixOrder): TGpStatus; stdcall; external gdiplus; function GdipGetWorldTransform(AGraphics: TGpGraphics; matrix: TGPMATRIX): TGpStatus; stdcall; external gdiplus; function GdipResetPageTransform(AGraphics: TGpGraphics): TGpStatus; stdcall; external gdiplus; function GdipGetPageUnit(AGraphics: TGpGraphics; var unit_: TGPUNIT): TGpStatus; stdcall; external gdiplus; function GdipGetPageScale(AGraphics: TGpGraphics; var scale: Single): TGpStatus; stdcall; external gdiplus; function GdipSetPageUnit(AGraphics: TGpGraphics; unit_: TGPUNIT): TGpStatus; stdcall; external gdiplus; function GdipSetPageScale(AGraphics: TGpGraphics; scale: Single): TGpStatus; stdcall; external gdiplus; function GdipGetDpiX(AGraphics: TGpGraphics; var dpi: Single): TGpStatus; stdcall; external gdiplus; function GdipGetDpiY(AGraphics: TGpGraphics; var dpi: Single): TGpStatus; stdcall; external gdiplus; function GdipTransformPoints(AGraphics: TGpGraphics; destSpace: GPCOORDINATESPACE; srcSpace: GPCOORDINATESPACE; points: PGPPOINTF; count: Integer): TGpStatus; stdcall; external gdiplus; function GdipTransformPointsI(AGraphics: TGpGraphics; destSpace: GPCOORDINATESPACE; srcSpace: GPCOORDINATESPACE; points: PGPPOINT; count: Integer): TGpStatus; stdcall; external gdiplus; function GdipGetNearestColor(AGraphics: TGpGraphics; argb: PGPColor): TGpStatus; stdcall; external gdiplus; // Creates the Win9x Halftone Palette (even on NT) with correct Desktop colors function GdipCreateHalftonePalette: HPALETTE; stdcall; external gdiplus; implementation end.
unit UFileThread; interface uses UThreadUtil, IOUtils, classes, SysUtils, Math, shellapi, SyncObjs; type {$Region ' 文件 Job 信息 ' } // 父类 TFileJobBase = class( TThreadJob ) public ActionID : string; ControlPath : string; IsLocal : Boolean; public constructor Create( _ActionID : string ); procedure SetControlPath( _ControlPath : string; _IsLocal : Boolean ); procedure Update;override; protected procedure BeforeAction; procedure ActionHandle;virtual;abstract; procedure AfterAction; private procedure RemoveToFace; end; // 文件父类 TFileJob = class( TFileJobBase ) public FilePath : string; public procedure SetFilePath( _FilePath : string ); end; // 有目标的 Job TFileDesJob = class( TFileJob ) public DesFilePath : string; public procedure SetDesFilePath( _DesFilePath : string ); end; // 复制 TFileCopyJob = class( TFileDesJob ) protected procedure ActionHandle;override; private procedure AddToFace; end; // 删除 TFileDeleteJob = class( TFileJob ) protected procedure ActionHandle;override; private procedure AddToFace; end; // 压缩 TFileZipJob = class( TFileJobBase ) public FileList : TStringList; ZipPath : string; public procedure SetFileList( _FileList : TStringList ); procedure SetZipPath( _ZipPath : string ); destructor Destroy; override; protected procedure ActionHandle;override; private procedure ShowForm; procedure HideForm; private procedure AddToFace; end; {$EndRegion} // 添加参数 TJobAddParams = record public FilePath, DesFilePath : string; ControlPath, ActionID : string; IsLocal : Boolean; end; // 删除参数 TJobDeleteParams = record public FilePath : string; ControlPath, ActionID : string; IsLocal : Boolean; end; // 压缩参数 TJobZipParams = record public FileList : TStringList; ZipPath : string; ControlPath, ActionID : string; IsLocal : Boolean; end; // 文件任务处理器 TMyFileJobHandler = class( TMyJobHandler ) private RunningLock : TCriticalSection; RunningCount : Integer; private IsUserStop : Boolean; public constructor Create; destructor Destroy; override; public procedure AddFleCopy( Params : TJobAddParams ); procedure AddFleDelete( Params : TJobDeleteParams ); procedure AddFileZip( Params : TJobZipParams ); public procedure AddRuningCount; procedure RemoveRuningCount; function ReadIsRunning : Boolean; end; var MyFileJobHandler : TMyFileJobHandler; implementation uses UMyUtils, UFrameDriver, UFormZip; { TFileMoveInfo } procedure TFileJobBase.AfterAction; begin // 正在运行 MyFileJobHandler.RemoveRuningCount; end; procedure TFileJobBase.BeforeAction; begin // 结束 Waiting FaceUpdate( RemoveToFace ); end; constructor TFileJobBase.Create(_ActionID: string); begin ActionID := _ActionID; end; procedure TFileJobBase.RemoveToFace; begin FaceFileJobApi.RemoveFileJob( ActionID ); end; procedure TFileJobBase.SetControlPath(_ControlPath: string; _IsLocal : Boolean); begin ControlPath := _ControlPath; IsLocal := _IsLocal; end; { TFileDesJob } procedure TFileDesJob.SetDesFilePath(_DesFilePath: string); begin DesFilePath := _DesFilePath; end; { TFileCopyJob } procedure TFileCopyJob.ActionHandle; var fo: TSHFILEOPSTRUCT; begin FillChar(fo, SizeOf(fo), 0); with fo do begin Wnd := 0; wFunc := FO_COPY; pFrom := PChar(FilePath + #0); pTo := PChar(DesFilePath + #0); fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR; end; if SHFileOperation(fo)=0 then FaceUpdate( AddToFace ) else MyFileJobHandler.IsUserStop := True; end; procedure TFileCopyJob.AddToFace; begin if IsLocal then UserNetworkDriverApi.AddFile( ControlPath, DesFilePath ) else UserLocalDriverApi.AddFile( ControlPath, DesFilePath ); end; { TMyFileJobHandler } procedure TMyFileJobHandler.AddFileZip(Params : TJobZipParams); var FileZipJob : TFileZipJob; begin AddRuningCount; FileZipJob := TFileZipJob.Create( Params.ActionID ); FileZipJob.SetControlPath( Params.ControlPath, Params.IsLocal ); FileZipJob.SetFileList( Params.FileList ); FileZipJob.SetZipPath( Params.ZipPath ); AddJob( FileZipJob ); end; procedure TMyFileJobHandler.AddFleCopy( Params : TJobAddParams ); var FileCopyJob : TFileCopyJob; begin AddRuningCount; FileCopyJob := TFileCopyJob.Create( Params.ActionID ); FileCopyJob.SetControlPath( Params.ControlPath, Params.IsLocal ); FileCopyJob.SetFilePath( Params.FilePath ); FileCopyJob.SetDesFilePath( Params.DesFilePath ); AddJob( FileCopyJob ); end; procedure TMyFileJobHandler.AddFleDelete(Params : TJobDeleteParams); var FileDeleteJob : TFileDeleteJob; begin AddRuningCount; FileDeleteJob := TFileDeleteJob.Create( Params.ActionID ); FileDeleteJob.SetControlPath( Params.ControlPath, Params.IsLocal ); FileDeleteJob.SetFilePath( Params.FilePath ); AddJob( FileDeleteJob ); end; procedure TMyFileJobHandler.AddRuningCount; begin RunningLock.Enter; Inc( RunningCount ); RunningLock.Leave; end; constructor TMyFileJobHandler.Create; begin inherited; RunningLock := TCriticalSection.Create; RunningCount := 0; IsUserStop := False; end; destructor TMyFileJobHandler.Destroy; begin RunningLock.Free; inherited; end; function TMyFileJobHandler.ReadIsRunning: Boolean; begin RunningLock.Enter; Result := RunningCount > 0; RunningLock.Leave; end; procedure TMyFileJobHandler.RemoveRuningCount; begin RunningLock.Enter; Dec( RunningCount ); RunningLock.Leave; // Reset if RunningCount <= 0 then IsUserStop := False; end; procedure TFileJobBase.Update; begin // 操作前 BeforeAction; try // 实际操作 if not MyFileJobHandler.IsUserStop then ActionHandle; except end; // 操作后 AfterAction; end; { TFileDeleteJob } procedure TFileDeleteJob.ActionHandle; begin if MyShellFile.DeleteFile( FilePath ) then FaceUpdate( AddToFace ) else MyFileJobHandler.IsUserStop := True; end; procedure TFileDeleteJob.AddToFace; begin if IsLocal then UserLocalDriverApi.RemoveFile( ControlPath, FilePath ) else UserNetworkDriverApi.RemoveFile( ControlPath, FilePath ); end; { TFileJob } procedure TFileJob.SetFilePath(_FilePath: string); begin FilePath := _FilePath; end; { TFileZipBaseJob } procedure TFileZipJob.ActionHandle; begin FaceUpdate( ShowForm ); frmZip.SetFileList( FileList ); frmZip.SetZipPath( ZipPath ); if frmZip.FileZip then FaceUpdate( AddToFace ) else // 压缩失败,删除压缩文件 MyShellFile.DeleteFile( ZipPath ); FaceUpdate( HideForm ); end; procedure TFileZipJob.AddToFace; begin if IsLocal then begin UserLocalDriverApi.CancelSelect( ControlPath ); UserLocalDriverApi.AddFile( ControlPath, ZipPath ); end else begin UserNetworkDriverApi.CancelSelect( ControlPath ); UserNetworkDriverApi.AddFile( ControlPath, ZipPath ); end; end; destructor TFileZipJob.Destroy; begin FileList.Free; inherited; end; procedure TFileZipJob.HideForm; begin frmZip.Close; end; procedure TFileZipJob.SetFileList(_FileList: TStringList); begin FileList := _FileList; end; procedure TFileZipJob.SetZipPath(_ZipPath: string); begin ZipPath := _ZipPath; end; procedure TFileZipJob.ShowForm; begin frmZip.Show; end; end.
unit DatabaseUtils; interface uses Aurelius.Criteria.Base, Aurelius.Drivers.Interfaces, Aurelius.Engine.DatabaseManager, Aurelius.Engine.ObjectManager, MusicEntities; procedure UpdateDatabase(Conn: IDBConnection); implementation uses System.IOUtils, System.StrUtils, System.Types, System.Classes, System.SysUtils; function DataFileName(const FileName: string): string; var BaseDir: string; begin BaseDir := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), '..\..\data'); if not TDirectory.Exists(BaseDir) then BaseDir := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), '..\data'); if not TDirectory.Exists(BaseDir) then BaseDir := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'data'); Result := TPath.Combine(BaseDir, FileName); end; function CreateDataFromFiles(Manager: TObjectManager): Boolean; var ArtistFile, GenreFile, AlbumFile, TrackFile: string; Artist: TArtist; Album: TAlbum; Genre: TGenre; Track: TTrack; Row: string; Cols: TStrings; begin ArtistFile := DataFileName('artist.csv'); AlbumFile := DataFileName('album.csv'); GenreFile := DataFileName('genre.csv'); TrackFile := DataFileName('track.csv'); Result := TFile.Exists(ArtistFile) and TFile.Exists(AlbumFile) and TFile.Exists(GenreFile) and TFile.Exists(TrackFile); if not Result then Exit; Cols := TStringList.Create; try // process artists for Row in TFile.ReadAllLines(ArtistFile) do begin Cols.Clear; if ExtractStrings([','], [], PChar(Row), Cols) <> 2 then raise Exception.Create('Artist data file should have 2 columns'); if Cols[0] = 'ArtistId' then Continue; // skip first line Artist := TArtist.Create; try Artist.Id := StrToInt(Cols[0]); Artist.Name := AnsiDequotedStr(Cols[1], '"'); Manager.Replicate<TArtist>(Artist); finally Artist.Free; end; end; // process albuns for Row in TFile.ReadAllLines(AlbumFile) do begin Cols.Clear; if ExtractStrings([','], [], PChar(Row), Cols) <> 3 then raise Exception.Create('Album data file should have 3 columns'); if Cols[0] = 'AlbumId' then Continue; // skip first line Artist := Manager.Find<TArtist>(StrToInt(Cols[2])); Album := TAlbum.Create; try Album.Id := StrToInt(Cols[0]); Album.Name := AnsiDequotedStr(Cols[1], '"'); Album.Artist := Artist; Manager.Replicate<TAlbum>(Album); finally Album.Free; end; end; // process genres for Row in TFile.ReadAllLines(GenreFile) do begin Cols.Clear; if ExtractStrings([','], [], PChar(Row), Cols) <> 2 then raise Exception.Create('Genre data file should have 2 columns'); if Cols[0] = 'GenreId' then Continue; // skip first line Genre := TGenre.Create; try Genre.Id := StrToInt(Cols[0]); Genre.Name := AnsiDequotedStr(Cols[1], '"'); Manager.Replicate<TGenre>(Genre); finally Genre.Free; end; end; // process tracks for Row in TFile.ReadAllLines(TrackFile) do begin Cols.Clear; if ExtractStrings([','], [], PChar(Row), Cols) <> 6 then raise Exception.Create('Track data file should have 6 columns'); if Cols[0] = 'TrackId' then Continue; // skip first line Track := TTrack.Create; try Track.Id := StrToInt(Cols[0]); Track.Name := AnsiDequotedStr(Cols[1], '"'); Track.Genre := Manager.Find<TGenre>(StrToInt(Cols[3])); Track.Composer := AnsiDequotedStr(Cols[4], '"'); Track.Milliseconds := StrToInt(Cols[5]); Album := Manager.Find<TAlbum>(StrToInt(Cols[2])); Album.Tracks.Add(Manager.Replicate<TTrack>(Track)); finally Track.Free; end; end; Manager.Flush; finally Cols.Free; end; end; procedure CreateDataManually(M: TObjectManager); var Rock, Alternative: TGenre; Led, Nirvana, REM: TArtist; LedIV, Presence, Nevermind, OutOfTime: TAlbum; begin Rock := TGenre.Create('Rock'); Alternative := TGenre.Create('Alternative'); Led := TArtist.Create('Led Zeppelin'); Nirvana := TArtist.Create('Nirvana'); REM := TArtist.Create('R.E.M.'); LedIV := TAlbum.Create('Led Zeppelin IV', Led); LedIV.Tracks.Add(TTrack.Create('Black Dog', Rock, 'Jimmy Page, Robert Plant, John Paul Jones', 296672)); LedIV.Tracks.Add(TTrack.Create('Rock & Roll', Rock, 'Jimmy Page, Robert Plant, John Paul Jones, John Bonam', 220917)); LedIV.Tracks.Add(TTrack.Create('The Battle of Evermore', Rock, 'Jimmy Page, Robert Plant', 351555)); LedIV.Tracks.Add(TTrack.Create('Stairway to Heaven', Rock, 'Jimmy Page, Robert Plant', 481619)); LedIV.Tracks.Add(TTrack.Create('Misty Mountain Hop', Rock, 'Jimmy Page, Robert Plant, John Paul Jones', 278857)); LedIV.Tracks.Add(TTrack.Create('Four Sticks', Rock, 'Jimmy Page, Robert Plant', 284447)); LedIV.Tracks.Add(TTrack.Create('Going to California', Rock, 'Jimmy Page, Robert Plant', 215693)); LedIV.Tracks.Add(TTrack.Create('When the Levee Breaks', Rock, 'Jimmy Page, Robert Plant, John Paul Jones, John Bonhan, Memphis Minnie', 427702)); M.Save(LedIV); Presence := TAlbum.Create('Presence', Led); Presence.Tracks.Add(TTrack.Create('Achilles Last Stand', Rock, 'Jimmy Page, Robert Plant', 625502)); Presence.Tracks.Add(TTrack.Create('For Your Life', Rock, 'Jimmy Page, Robert Plant', 384391)); Presence.Tracks.Add(TTrack.Create('Royal Orleans', Rock, 'John Bonham, John Paul Jones', 179591)); Presence.Tracks.Add(TTrack.Create('Nobody''s Fault But Mine', Rock, 'Jimmy Page, Robert Plant', 376215)); Presence.Tracks.Add(TTrack.Create('Candy Store Rock', Rock, 'Jimmy Page, Robert Plant', 252055)); Presence.Tracks.Add(TTrack.Create('Hots On For Nowhere', Rock, 'Jimmy Page, Robert Plant', 284107)); Presence.Tracks.Add(TTrack.Create('Tea For One', Rock, 'Jimmy Page, Robert Plant', 566752)); M.Save(Presence); Nevermind := TAlbum.Create('Nevermind', Nirvana); Nevermind.Tracks.Add(TTrack.Create('Smells Like Teen Spirit', Rock, 'Kurt Cobain', 301296)); Nevermind.Tracks.Add(TTrack.Create('In Bloom', Rock, 'Kurt Cobain', 254928)); Nevermind.Tracks.Add(TTrack.Create('Come As You Are', Rock, 'Kurt Cobain', 219219)); Nevermind.Tracks.Add(TTrack.Create('Breed', Rock, 'Kurt Cobain', 183928)); Nevermind.Tracks.Add(TTrack.Create('Lithium', Rock, 'Kurt Cobain', 256992)); Nevermind.Tracks.Add(TTrack.Create('Polly', Rock, 'Kurt Cobain', 177031)); Nevermind.Tracks.Add(TTrack.Create('Territorial Pissings', Rock, 'Kurt Cobain', 143281)); Nevermind.Tracks.Add(TTrack.Create('Drain You', Rock, 'Kurt Cobain', 223973)); Nevermind.Tracks.Add(TTrack.Create('Lounge Act', Rock, 'Kurt Cobain', 156786)); Nevermind.Tracks.Add(TTrack.Create('Stay Away', Rock, 'Kurt Cobain', 212636)); Nevermind.Tracks.Add(TTrack.Create('On a Plain', Rock, 'Kurt Cobain', 196440)); Nevermind.Tracks.Add(TTrack.Create('Something In The Way', Rock, 'Kurt Cobain', 230556)); M.Save(Nevermind); OutOfTime := TAlbum.Create('Out of Time', REM); OutOfTime.Tracks.Add(TTrack.Create('Shiny Happy People', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 226298)); OutOfTime.Tracks.Add(TTrack.Create('Me In Honey', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 246674)); OutOfTime.Tracks.Add(TTrack.Create('Radio Song', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 255477)); OutOfTime.Tracks.Add(TTrack.Create('Losing My Religion', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 269035)); OutOfTime.Tracks.Add(TTrack.Create('Low', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 296777)); OutOfTime.Tracks.Add(TTrack.Create('Near Wild Heaven', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 199862)); OutOfTime.Tracks.Add(TTrack.Create('Endgame', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 230687)); OutOfTime.Tracks.Add(TTrack.Create('Belong', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 247013)); OutOfTime.Tracks.Add(TTrack.Create('Half A World Away', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 208431)); OutOfTime.Tracks.Add(TTrack.Create('Texarkana', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 220081)); OutOfTime.Tracks.Add(TTrack.Create('Country Feedback', Alternative, 'Bill Berry/Michael Stipe/Mike Mills/Peter Buck', 249782)); M.Save(OutOfTime); end; procedure UpdateDatabase(Conn: IDBConnection); var DB: TDatabaseManager; Manager: TObjectManager; Trans: IDBTransaction; begin DB := TDatabaseManager.Create(Conn); try DB.UpdateDatabase; finally DB.Free; end; Manager := TObjectManager.Create(Conn); try // Simple test that works for this demo (might fail in production environments): // try to find an artist from database, if no artist, then add all objects if Manager.Find<TArtist>.Take(1).UniqueResult = nil then begin Trans := conn.BeginTransaction; try if not CreateDataFromFiles(Manager) then CreateDataManually(Manager); Trans.Commit; except Trans.Rollback; raise; end; end; finally Manager.Free; end; end; end.
unit uConfigForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, uLibraryData, uregisterseditor, uConfigEditor; type { TConfigForm } TConfigForm = class(TEditingForm) ConfigImageList: TImageList; Splitter: TSplitter; RegistersPanel: TPanel; ConfigPanel: TPanel; procedure FormCreate(Sender: TObject); private fRegistersEditor: TRegistersEditor; fConfigEditor: TConfigEditor; public procedure Load(const aLibraryData: TLibraryData); override; procedure Unload; override; end; implementation {$R *.lfm} { TConfigForm } procedure TConfigForm.FormCreate(Sender: TObject); begin fRegistersEditor := TRegistersEditor.Create(Self); fRegistersEditor.Parent := RegistersPanel; fRegistersEditor.Align := alClient; fConfigEditor := TConfigEditor.Create(Self, ConfigImageList); fConfigEditor.Parent := ConfigPanel; fConfigEditor.Align := alClient; fConfigEditor.Images := ConfigImageList; end; procedure TConfigForm.Load(const aLibraryData: TLibraryData); begin if aLibraryData is TConfigurationData then begin fRegistersEditor.LoadRegisters(TConfigurationData(aLibraryData).Registers); fConfigEditor.LoadConfig(TConfigurationData(aLibraryData).Configuration); end; end; procedure TConfigForm.Unload; begin fRegistersEditor.Clear; fConfigEditor.Clear; end; end.
unit RDialogs; interface function CustomMsgBox(const Caption, Text: string; Flags: Integer): Integer; function ErrorBox(const Text: string): Integer; function InfoBox(const Text: string): Integer; function CautionBox(const Text: string): Integer; function WarningBox(const Text: string): Integer; function WarningBoxYN(const Text: string): Integer; function WarningBoxNY(const Text: string): Integer; function ErrorBoxYN(const Text: string): Integer; function ErrorBoxNY(const Text: string): Integer; function QueryBoxYN(const Caption, Text: string): Integer; function QueryBoxNY(const Caption, Text: string): Integer; function QueryBoxYNC(const Caption, Text: string): Integer; function QueryBoxNYC(const Caption, Text: string): Integer; function QueryBoxCYN(const Caption, Text: string): Integer; function QueryBoxStdYN(const Text: string): Integer; function QueryBoxStdNY(const Text: string): Integer; function QueryBoxStdYNC(const Text: string): Integer; function QueryBoxStdNYC(const Text: string): Integer; function QueryBoxStdCYN(const Text: string): Integer; function DeleteQueryStd: Boolean; function DeleteQueryName(const Name: string): Boolean; function DeleteQueryText(const Text: string): Boolean; function DeleteQueryMulti(const RecCount: Integer): Boolean; function CloseAppQuery: Boolean; procedure StrNotFoundBox(const Text: string); resourcestring SDlgError = 'Ошибка'; SDlgInfo = 'Информация'; SDlgCaution = 'Внимание!'; SDlgWarning = 'Предупреждение'; SDlgQuery = 'Подтверждение'; SMsgStrNotFound = 'Строка "%s" не найдена!'; SMsgProcessCounts = 'Из %d записей успешно обработано - %d, пропущено - %d.'; SQueryDeleteSelected = 'Удалить выделенную запись?'; SQueryDeleteCount = 'Удалить все выделенные записи (всего будет удалено %d записи(ей))?'; SQueryDeleteText = 'Удалить запись "%s"?'; SQueryCloseApp = 'Завершить работу с программой?'; SQueryBreakOperation = 'Во время обработки данных произошла ошибка. Прервать выполнение операции?'; (* SQueryProcAllRecords = 'Обработать все показанные записи (всего %d записи(ей)) - "Да" / "Yes",'#13 + 'либо только выделенные записи (выбрано %d записи(ей)) - "Нет" / "No"?'#13#13 + 'Для отмены операции и выхода без обработки нажмите "Отмена" / "Cancel".'; *) implementation uses SysUtils, Themes, Forms, Controls, Windows; function CustomMsgBox(const Caption, Text: string; Flags: Integer): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), Flags); end; function ErrorBox(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgError), MB_ICONERROR + MB_OK); end; function InfoBox(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgInfo), MB_ICONINFORMATION + MB_OK); end; function CautionBox(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgCaution), MB_ICONWARNING + MB_OK); end; function WarningBox(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgWarning), MB_ICONWARNING + MB_OK); end; function WarningBoxYN(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgWarning), MB_ICONWARNING + MB_YESNO + MB_DEFBUTTON1); end; function WarningBoxNY(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgWarning), MB_ICONWARNING + MB_YESNO + MB_DEFBUTTON2); end; function ErrorBoxYN(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgWarning), MB_ICONERROR + MB_YESNO + MB_DEFBUTTON1); end; function ErrorBoxNY(const Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(SDlgWarning), MB_ICONERROR + MB_YESNO + MB_DEFBUTTON2); end; function QueryBoxYN(const Caption, Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON1); end; function QueryBoxNY(const Caption, Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON2); end; function QueryBoxYNC(const Caption, Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_ICONQUESTION + MB_YESNOCANCEL + MB_DEFBUTTON1); end; function QueryBoxNYC(const Caption, Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_ICONQUESTION + MB_YESNOCANCEL + MB_DEFBUTTON2); end; function QueryBoxCYN(const Caption, Text: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_ICONQUESTION + MB_YESNOCANCEL + MB_DEFBUTTON3); end; function QueryBoxStdYN(const Text: string): Integer; begin Result := QueryBoxYN(SDlgQuery, Text); end; function QueryBoxStdNY(const Text: string): Integer; begin Result := QueryBoxNY(SDlgQuery, Text); end; function QueryBoxStdYNC(const Text: string): Integer; begin Result := QueryBoxYNC(SDlgQuery, Text); end; function QueryBoxStdNYC(const Text: string): Integer; begin Result := QueryBoxNYC(SDlgQuery, Text); end; function QueryBoxStdCYN(const Text: string): Integer; begin Result := QueryBoxCYN(SDlgQuery, Text); end; function DeleteQueryStd: Boolean; begin Result := QueryBoxNY(SDlgWarning, SQueryDeleteSelected)= IDYES; end; function DeleteQueryName(const Name: string): Boolean; begin Result := QueryBoxNY(SDlgWarning, Format(SQueryDeleteText, [Name]))= IDYES; end; function DeleteQueryText(const Text: string): Boolean; begin Result := QueryBoxNY(SDlgWarning, Text)= IDYES; end; function DeleteQueryMulti(const RecCount: Integer): Boolean; begin if RecCount = 1 then Result := QueryBoxNY(SDlgWarning, SQueryDeleteSelected)= IDYES else Result := QueryBoxNY(SDlgWarning, Format(SQueryDeleteCount, [RecCount]))= IDYES; end; function CloseAppQuery: Boolean; begin Result := QueryBoxNY(Application.Title, SQueryCloseApp)= IDYES; end; procedure StrNotFoundBox(const Text: string); begin InfoBox(Format(SMsgStrNotFound, [Text])); end; end.
unit win.cpu; interface {$DEFINE TARGET_x86} {$DEFINE Windows} type TCPUInstructionSet = ( ciMMX, ciEMMX, ciSSE, ciSSE2, ci3DNow, ci3DNowExt, ciSSE3 ); TCPUInstructionSets = set of TCPUInstructionSet; TCPUIDRegs = record rEAX : Cardinal; rEBX : Cardinal; rECX : Cardinal; rEDX : Cardinal; end; PCPUData = ^TCPUData; TCPUData = record Features: TCPUInstructionSets; end; const CPUISChecks: array [TCPUInstructionSet] of Cardinal = ($800000, $400000, $2000000, $4000000, $80000000, $40000000, 0); {ciMMX , ciEMMX, ciSSE , ciSSE2 , ci3DNow , ci3DNowExt} function CPUID(const FuncId : Cardinal) : TCPUIDRegs; procedure InitializeCPUData(ACPUData: PCPUData); { Returns the number of processors configured by the operating system. } function GetProcessorCount: Cardinal; function HasInstructionSet(const ACpuInstructionSet: TCPUInstructionSet): Boolean; function GetSupportedSimdInstructionSets : TCPUInstructionSets; function GetL2CacheSize : Integer; implementation uses Windows; function CPUID(const FuncId : Cardinal) : TCPUIDRegs; var Regs : TCPUIDRegs; begin { Request the opcode support } asm { Save registers } PUSH EAX PUSH EBX PUSH ECX PUSH EDX { Set the function 1 and clear others } MOV EAX, [FuncId] XOR EBX, EBX XOR ECX, ECX XOR EDX, EDX { Call CPUID } CPUID { Store the registers we need } MOV [Regs.rEAX], EAX MOV [Regs.rEBX], EBX MOV [Regs.rECX], ECX MOV [Regs.rEDX], EDX { Restore registers } POP EDX POP ECX POP EBX POP EAX end; Result := Regs; end; function CPUIIDSupports(const FuncId : Cardinal; const Extended : Boolean = false) : Boolean; begin if Extended then Result := CPUID($80000000).rEAX >= FuncId else Result := CPUID($00000000).rEAX >= FuncId; end; function GetSupportedSimdInstructionSets : TCPUInstructionSets; var Regs : TCPUIDRegs; begin Result := []; { Check for iset support } if not CPUIIDSupports($00000001) then Exit; { Request SIMD support } Regs := CPUID($00000001); if ((Regs.rECX and 1) <> 0) then Result := Result + [ciSSE3]; if ((Regs.rEDX and (1 shl 23)) <> 0) then Result := Result + [ciMMX]; if ((Regs.rEDX and (1 shl 25)) <> 0) then Result := Result + [ciSSE]; if ((Regs.rEDX and (1 shl 26)) <> 0) then Result := Result + [ciSSE2]; { Check if Windows supports XMM registers - run an instruction and check for exceptions. } try asm ORPS XMM0, XMM0 end except begin { Exclude SSE instructions! } Result := Result - [ciSSE, ciSSE2, ciSSE3]; end; end; end; function GetL2CacheSize : Integer; var { Variables used for config description } Regs: TCPUIDRegs; CfgD: packed array[0..15] of Byte absolute Regs; I, J: Integer; QueryCount: Byte; begin { Unknown cache size } Result := 0; { Check for cache support } if not CPUIIDSupports($00000002) then Exit; { Request cache support } Regs := CPUID($00000002); { Query count } QueryCount := Regs.rEAX and $FF; for I := 1 to QueryCount do begin for J := 1 to 15 do begin case CfgD[J] of $39: Result := 128; $3B: Result := 128; $3C: Result := 256; $41: Result := 128; $42: Result := 256; $43: Result := 512; $44: Result := 1024; $45: Result := 2048; $78: Result := 1024; $79: Result := 128; $7A: Result := 256; $7B: Result := 512; $7C: Result := 1024; $7D: Result := 2048; $7F: Result := 512; $82: Result := 256; $83: Result := 512; $84: Result := 1024; $85: Result := 2048; $86: Result := 512; $87: Result := 1024; end; end; { Re-Request cache support } if I < QueryCount then Regs := CPUID($00000002); end; end; function GetExtendedL2CacheSize : Integer; var Regs: TCPUIDRegs; begin Result := 0; { Check for cache support } if not CPUIIDSupports($80000006, true) then Exit; { CPUID: $80000005 } Regs := CPUID($80000006); { L2 Cache size } Result := Regs.rECX shr 16; end; {$IFDEF UNIX} {$IFDEF FPC} function GetProcessorCount: Cardinal; begin Result := 1; end; {$ENDIF} {$ENDIF} {$IFDEF Windows} function GetProcessorCount: Cardinal; var lpSysInfo: TSystemInfo; begin GetSystemInfo(lpSysInfo); Result := lpSysInfo.dwNumberOfProcessors; end; {$ENDIF} function CPUID_Available: Boolean; asm {$IFDEF TARGET_x86} MOV EDX,False PUSHFD POP EAX MOV ECX,EAX XOR EAX,$00200000 PUSH EAX POPFD PUSHFD POP EAX XOR ECX,EAX JZ @1 MOV EDX,True @1: PUSH EAX POPFD MOV EAX,EDX {$ENDIF} {$IFDEF TARGET_x64} MOV EDX,False PUSHFQ POP RAX MOV ECX,EAX XOR EAX,$00200000 PUSH RAX POPFQ PUSHFQ POP RAX XOR ECX,EAX JZ @1 MOV EDX,True @1: PUSH RAX POPFQ MOV EAX,EDX {$ENDIF} end; function CPU_Signature: Integer; asm {$IFDEF TARGET_x86} PUSH EBX MOV EAX,1 {$IFDEF FPC} CPUID {$ELSE} DW $A20F // CPUID {$ENDIF} POP EBX {$ENDIF} {$IFDEF TARGET_x64} PUSH RBX MOV EAX,1 CPUID POP RBX {$ENDIF} end; function CPU_Features: Integer; asm {$IFDEF TARGET_x86} PUSH EBX MOV EAX,1 {$IFDEF FPC} CPUID {$ELSE} DW $A20F // CPUID {$ENDIF} POP EBX MOV EAX,EDX {$ENDIF} {$IFDEF TARGET_x64} PUSH RBX MOV EAX,1 CPUID POP RBX MOV EAX,EDX {$ENDIF} end; function CPU_ExtensionsAvailable: Boolean; asm {$IFDEF TARGET_x86} PUSH EBX MOV @Result, True MOV EAX, $80000000 {$IFDEF FPC} CPUID {$ELSE} DW $A20F // CPUID {$ENDIF} CMP EAX, $80000000 JBE @NOEXTENSION JMP @EXIT @NOEXTENSION: MOV @Result, False @EXIT: POP EBX {$ENDIF} {$IFDEF TARGET_x64} PUSH RBX MOV @Result, True MOV EAX, $80000000 CPUID CMP EAX, $80000000 JBE @NOEXTENSION JMP @EXIT @NOEXTENSION: MOV @Result, False @EXIT: POP RBX {$ENDIF} end; function CPU_ExtFeatures: Integer; asm {$IFDEF TARGET_x86} PUSH EBX MOV EAX, $80000001 {$IFDEF FPC} CPUID {$ELSE} DW $A20F // CPUID {$ENDIF} POP EBX MOV EAX,EDX {$ENDIF} {$IFDEF TARGET_x64} PUSH RBX MOV EAX, $80000001 CPUID POP RBX MOV EAX,EDX {$ENDIF} end; function HasInstructionSet(const ACpuInstructionSet: TCPUInstructionSet): Boolean; // Must be implemented for each target CPU on which specific functions rely begin Result := False; if not CPUID_Available then begin Exit; // no CPUID available end; if CPU_Signature shr 8 and $0F < 5 then begin Exit; // not a Pentium class end; case ACpuInstructionSet of ci3DNow, ci3DNowExt: {$IFNDEF FPC} if not CPU_ExtensionsAvailable or (CPU_ExtFeatures and CPUISChecks[ACpuInstructionSet] = 0) then {$ENDIF} Exit; ciEMMX: begin // check for SSE, necessary for Intel CPUs because they don't implement the // extended info if (CPU_Features and CPUISChecks[ciSSE] = 0) and (not CPU_ExtensionsAvailable or (CPU_ExtFeatures and CPUISChecks[ciEMMX] = 0)) then Exit; end; else if CPU_Features and CPUISChecks[ACpuInstructionSet] = 0 then Exit; // return -> instruction set not supported end; Result := True; end; procedure InitializeCPUData(ACPUData: PCPUData); var I: TCPUInstructionSet; begin ACPUData.Features := []; for I := Low(TCPUInstructionSet) to High(TCPUInstructionSet) do begin if HasInstructionSet(I) then begin ACPUData.Features := ACPUData.Features + [I]; end; end; end; end.
unit BankAccountMovement; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorEditDialog, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dsdDB, dsdAction, Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, dsdGuides, cxButtonEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxCurrencyEdit, cxLabel, dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue; type TBankAccountMovementForm = class(TAncestorEditDialogForm) Код: TcxLabel; cxLabel1: TcxLabel; ceOperDate: TcxDateEdit; cxLabel2: TcxLabel; ceBankAccount: TcxButtonEdit; GuidesBankAccount: TdsdGuides; ceAmountIn: TcxCurrencyEdit; cxLabel7: TcxLabel; ceAmountOut: TcxCurrencyEdit; cxLabel3: TcxLabel; cxLabel6: TcxLabel; ceObject: TcxButtonEdit; GuidesObject: TdsdGuides; cxLabel10: TcxLabel; ceComment: TcxTextEdit; edInvNumber: TcxTextEdit; ceBank: TcxButtonEdit; cxLabel13: TcxLabel; GuidesBank: TdsdGuides; cxLabel15: TcxLabel; ceInvoice: TcxButtonEdit; GuidesInvoice: TdsdGuides; cxLabel18: TcxLabel; edInvNumberPartner: TcxTextEdit; GuidesFiller: TGuidesFiller; cxLabel4: TcxLabel; GuidesParent: TdsdGuides; edParent: TcxButtonEdit; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TBankAccountMovementForm); end.
unit Unt_ThreadComEvent; interface uses System.Classes, System.SyncObjs, Vcl.StdCtrls; type /// <summary> /// Exemplo de utilização do TEvent /// </summary> TExemploThread = class(TThread) private FSinalizador: TEvent; FMemo : TMemo; FMensagem : string; procedure EscreverNoMemo; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure Execute; override; procedure SinalizarThread; property Memo: TMemo read FMemo write FMemo; end; implementation uses System.SysUtils; { TExemploThread } procedure TExemploThread.AfterConstruction; begin inherited; Self.FSinalizador := TEvent.Create(nil, False, True, '_delphiconference'); end; procedure TExemploThread.BeforeDestruction; begin inherited; Self.FSinalizador.Free; end; procedure TExemploThread.EscreverNoMemo; begin Self.FMemo.Lines.Insert(0, TimeToStr(Time) + ' - ' + Self.FMensagem); end; procedure TExemploThread.Execute; var eEvent: TWaitResult; begin inherited; while not(Self.Terminated) do begin eEvent := Self.FSinalizador.WaitFor(5000); //Pode-se usar a constante INFINITE case eEvent of wrSignaled: begin Self.FMensagem := 'Thread sinalizada!'; end; wrTimeout: begin Self.FMensagem := 'Time-out na espera da sinalização!'; end; wrAbandoned: begin Self.FMensagem := 'Sinalizador encerrado!'; end; wrError: begin Self.FMensagem := 'Erro! ' + IntToStr(Self.FSinalizador.LastError); end; wrIOCompletion: begin Self.FMensagem := 'wrIOCompletion'; end; end; Self.Synchronize(Self.EscreverNoMemo); end; end; procedure TExemploThread.SinalizarThread; begin Self.FSinalizador.SetEvent; end; end.
unit UnitTraslados; interface uses DateUtils, IniFiles, SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, IdBaseComponent, IdComponent, IdTCPServer, FMTBcd, DB,IBQuery, IBSql, IBDatabase,IdCoder, JvSimpleXml, DBXpress, SqlExpr, IdCoder3To4, sdXmlDocuments; type PTCuenta = ^TCuenta; TCuenta = Record Id_Agencia :Integer; Id_Tipo_Captacion :Integer; Numero_Cuenta:Integer; Digito_Cuenta:Integer; CodContable:string; end; type PTPersona = ^TPersona; TPersona = record id:Integer; persona:string; end; type TfrmServerTraslados = class(TForm) EdLog: TMemo; Label1: TLabel; Label2: TLabel; lblDatabase: TLabel; Label3: TLabel; lblPuerto: TLabel; IdTCPServer1: TIdTCPServer; SQLConnection1: TSQLConnection; SQLQuery1: TSQLQuery; Label4: TLabel; lblTimeOut: TLabel; procedure FormCreate(Sender: TObject); procedure IdTCPServer1Execute(AThread: TIdPeerThread); private { Private declarations } IDpuerto :Integer; IDtiempo: Integer; DBserver: String; DBpath: String; DBname: String; DBRole :string; DBUser :string; DBpassword :string; archivo :TextFile; MiIni :string; host_remoto: string; host_ocana: string; host_abrego: string; host_convencion: string; host_aguachica:string; Hay_Conexion: Boolean; procedure Ejecutar(AThread: TIdPeerThread); function BuscoTasaAnt(Ag: Integer;Colocacion: string;FechaIntereses:TDateTime): Single; public { Public declarations } procedure procesar(tipo: integer; id: string); procedure Contabilizar; end; var frmServerTraslados: TfrmServerTraslados; implementation {$R *.xfm} uses UnitGlobales; procedure TfrmServerTraslados.FormCreate(Sender: TObject); var Archivo_respaldo :string; i :integer; begin MiIni := ChangeFileExt(Application.ExeName,'.ini'); shortdateformat := 'yyyy/mm/dd'; decimalseparator := '.'; AssignFile(archivo,ChangeFileExt(Application.ExeName,'.log')); Archivo_respaldo := ChangeFileExt(Application.ExeName,'.log'); if not(FileExists(Archivo_respaldo)) then Rewrite(archivo); with TIniFile.Create(MiIni) do begin DBServer := ReadString('SERVER','servidor','0.0.0.0'); DBPath := ReadString('SERVER','ruta','/var/db/fbird/'); DBName := ReadString('SERVER','nombre','database.fdb'); IDtiempo := StrToInt(ReadString('SERVER','tiempo','0')); IDpuerto := StrToInt(ReadString('SERVER','puerto','0')); DBrole := ReadString('SERVER','rolename','0'); DBpassword := ReadString('SERVER','password','0'); DBuser := ReadString('SERVER','username','0'); host_ocana := ReadString('SERVER','hostocana',''); host_abrego := ReadString('SERVER','hostabrego',''); host_convencion := ReadString('SERVER','hostconvencion',''); host_aguachica := ReadString('SERVER','hostaguachica',''); end; IdTCPServer1.TerminateWaitTime := IDtiempo; IdTCPServer1.DefaultPort := IDpuerto; IdTCPServer1.Active := True; lblDataBase.Caption := DBServer + ':' + DBPath + DBName; lblPuerto.Caption := IntToStr(IDpuerto); lblTimeOut.Caption := IntToStr(IDtiempo) + ' Milisegundos Puerto ' + IntToStr(IDpuerto); end; procedure TfrmServerTraslados.IdTCPServer1Execute(AThread: TIdPeerThread); begin if Athread.Connection.RecvBufferSize > 0 then begin Ejecutar(AThread); end; end; procedure TfrmServerTraslados.Ejecutar(AThread: TIdPeerThread); var i,Size:Integer; AStream:TStringStream; XMLDoc,XMLDocRet :TsdXmlDocument; XMLRet:Boolean; SQLConn:TSQLConnection; ANode: TXmlNode; Id:Integer; Nm:string; begin XmlDocRet := TsdXmlDocument.Create; XmlDocRet.EncodingString := 'ISO8859-1'; XmlDocRet.XmlFormat := xfReadable; XmlDoc := TsdXmlDocument.Create; Athread.Connection.WriteLn('Esperando...'); AStream := TStringStream.Create(''); Size := AThread.Connection.ReadInteger; Athread.Connection.ReadStream(AStream,Size,False); System.WriteLn('Stream recibido'); try XMLDoc.LoadFromStream(AStream); XMLDoc.SaveToFile('xmlrecibido1.xml'); EdLog.Lines.LoadFromStream(AStream); System.WriteLn('Xml Cargado'); finally end; AStream := TStringStream.Create(''); System.WriteLn('Guardando AStream Retorno'); XMLDocRet.SaveToStream(AStream); XMLDocRet.SaveToFile('XmlServer.xml'); AStream.Seek(0,0); Athread.Connection.WriteInteger(AStream.Size); Athread.Connection.OpenWriteBuffer; Athread.Connection.WriteStream(AStream); Athread.Connection.CloseWriteBuffer; end; procedure TfrmServerTraslados.procesar(tipo: integer; id: string); var i,j,k,l:Integer; Id_Agencia,Id_Tipo_Captacion,Numero_Cuenta,Digito_Cuenta:Integer; yaExiste :Boolean; vTabla :Boolean; vContador :Integer; OldTimeFormat,OldDateFormat,OldDateTimeFormat:string; CodContable:string; Nombre:string; Fecha1,Fecha2:TDateTime; Cuentas :TList; Personas :TList; IBSql1: TIBQuery; IBDataBase1 : TIBDatabase; xml :TJvSimpleXml; Nodo1 : TJvSimpleElemenClass; begin Cuentas := TList.Create; Personas := TList.Create; IBDataBase1 := TIBDatabase.Create(nil); IBSql1 := TIBQuery.Create(nil); OldDateFormat := ShortDateFormat; ShortDateFormat := 'yyyy/MM/dd'; OldTimeFormat := LongTimeFormat; LongTimeFormat := 'HH:mm:ss'; Fecha1 := EncodeDate(YearOf(fFechaActual(IBDatabase1)),01,01); Fecha2 := EncodeDate(YearOf(fFechaActual(IBDatabase1)),12,31); with IBSQl1 do begin SQL.Clear; SQL.Add('SELECT '); SQL.Add(' "cap$maestrotitular".ID_AGENCIA,'); SQL.Add(' "cap$maestrotitular".ID_TIPO_CAPTACION,'); SQL.Add(' "cap$maestrotitular".NUMERO_CUENTA,'); SQL.Add(' "cap$maestrotitular".DIGITO_CUENTA,'); SQL.Add(' "cap$maestrotitular".ID_IDENTIFICACION,'); SQL.Add(' "cap$maestrotitular".ID_PERSONA,'); SQL.Add(' "cap$maestrotitular".NUMERO_TITULAR,'); SQL.Add(' "cap$maestrotitular".TIPO_TITULAR,'); SQL.Add(' "gen$persona".NOMBRE || '' '' ||'); SQL.Add(' "gen$persona".PRIMER_APELLIDO || '' '' ||'); SQL.Add(' "gen$persona".SEGUNDO_APELLIDO AS ASOCIADO'); SQL.Add('FROM'); SQL.Add(' "cap$maestrotitular"'); SQL.Add('INNER JOIN "gen$persona" ON ("cap$maestrotitular".ID_IDENTIFICACION="gen$persona".ID_IDENTIFICACION)'); SQL.Add('AND ("cap$maestrotitular".ID_PERSONA="gen$persona".ID_PERSONA)'); SQL.Add('WHERE'); SQL.Add('"cap$maestrotitular".ID_IDENTIFICACION = :ID_IDENTIFICACION'); SQL.Add('AND'); SQL.Add('"cap$maestrotitular".ID_PERSONA = :ID_PERSONA'); SQL.Add('AND'); SQL.Add('"cap$maestrotitular".NUMERO_TITULAR = 1'); SQL.Add('ORDER BY'); SQL.Add('"cap$maestrotitular".ID_TIPO_CAPTACION, "cap$maestrotitular".NUMERO_CUENTA'); ParamByName('ID_IDENTIFICACION').AsInteger := tipo; ParamByName('ID_PERSONA').AsString := id; try Open; except Transaction.Rollback; raise; Exit; end; end; // fin del with cap$maestrotitular busqueda inicial de cuenta Nombre := IBSql1.FieldByName('ASOCIADO').AsString; xml.Root.Properties.Add('tipo',IntToStr(tipo)); xml.Root.Properties.Add('numero',id); xml.Root.Properties.Add('asociado',Nombre); Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$maestro'); while not IBSql1.Eof do begin Id_Agencia := IBSql1.FieldByName('ID_AGENCIA').AsInteger; Id_Tipo_Captacion := IBSql1.FieldByName('ID_TIPO_CAPTACION').AsInteger; Numero_Cuenta := IBSql1.FieldByName('NUMERO_CUENTA').AsInteger; Digito_Cuenta := IBSql1.FieldByName('DIGITO_CUENTA').AsInteger; // Realizar proceso general para esta cuenta IBSql2.Close; IBSql2.SQL.Clear; IBSql2.SQL.Add('SELECT '); IBSql2.SQL.Add(' "cap$maestro".ID_AGENCIA,'); IBSql2.SQL.Add(' "cap$maestro".ID_TIPO_CAPTACION,'); IBSql2.SQL.Add(' "cap$maestro".NUMERO_CUENTA,'); IBSql2.SQL.Add(' "cap$maestro".DIGITO_CUENTA,'); IBSql2.SQL.Add(' "cap$maestro".VALOR_INICIAL,'); IBSql2.SQL.Add(' "cap$maestro".ID_FORMA,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_APERTURA,'); IBSql2.SQL.Add(' "cap$maestro".PLAZO_CUENTA,'); IBSql2.SQL.Add(' "cap$maestro".TIPO_INTERES,'); IBSql2.SQL.Add(' "cap$maestro".ID_INTERES,'); IBSql2.SQL.Add(' "cap$maestro".TASA_EFECTIVA,'); IBSql2.SQL.Add(' "cap$maestro".PUNTOS_ADICIONALES,'); IBSql2.SQL.Add(' "cap$maestro".MODALIDAD,'); IBSql2.SQL.Add(' "cap$maestro".AMORTIZACION,'); IBSql2.SQL.Add(' "cap$maestro".CUOTA,'); IBSql2.SQL.Add(' "cap$maestro".CUOTA_CADA,'); IBSql2.SQL.Add(' "cap$maestro".ID_PLAN,'); IBSql2.SQL.Add(' "cap$maestro".ID_ESTADO,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_VENCIMIENTO,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_ULTIMO_PAGO,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_PROXIMO_PAGO,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_PRORROGA,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_VENCIMIENTO_PRORROGA,'); IBSql2.SQL.Add(' "cap$maestro".FECHA_SALDADA,'); IBSql2.SQL.Add(' "cap$maestro".FIRMAS,'); IBSql2.SQL.Add(' "cap$maestro".SELLOS,'); IBSql2.SQL.Add(' "cap$maestro".PROTECTOGRAFOS,'); IBSql2.SQL.Add(' "cap$maestro".ID_TIPO_CAPTACION_ABONO,'); IBSql2.SQL.Add(' "cap$maestro".NUMERO_CUENTA_ABONO'); IBSql2.SQL.Add('FROM'); IBSql2.SQL.Add(' "cap$maestro"'); IBSql2.SQL.Add('WHERE'); IBSql2.SQL.Add(' "cap$maestro".ID_AGENCIA = :ID_AGENCIA'); IBSql2.SQL.Add('AND'); IBSql2.SQL.Add(' "cap$maestro".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql2.SQL.Add('AND'); IBSql2.SQL.Add(' "cap$maestro".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql2.SQL.Add('AND'); IBSql2.SQL.Add(' "cap$maestro".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql2.SQL.Add('AND'); IBSql2.SQL.Add(' "cap$maestro".ID_ESTADO IN (1,3,4,6,13,14)'); IBSql2.ParamByName('ID_AGENCIA').AsInteger := Id_Agencia; IBSql2.ParamByName('ID_TIPO_CAPTACION').AsInteger := Id_Tipo_Captacion; IBSql2.ParamByName('NUMERO_CUENTA').AsInteger := Numero_Cuenta; IBSql2.ParamByName('DIGITO_CUENTA').AsInteger := Digito_Cuenta; try IBSql2.Open; if IBSql2.RecordCount > 0 then begin Nodo2 := Nodo1.Items.Add('registro'); IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO_CONTABLE from "cap$contable" where ID_CAPTACION = :ID_CAP AND ID_CONTABLE = :ID_CONTABLE'); if ((IBSql2.FieldByName('ID_TIPO_CAPTACION').AsInteger = 1) or (IBSql2.FieldByName('ID_TIPO_CAPTACION').AsInteger = 2) or (IBSql2.FieldByName('ID_TIPO_CAPTACION').AsInteger = 4) or (IBSql2.FieldByName('ID_TIPO_CAPTACION').AsInteger = 5)) then begin IBSql3.ParamByName('ID_CAP').AsInteger := id_Tipo_Captacion; IBSql3.ParamByName('ID_CONTABLE').AsInteger := 20; end else begin IBSql3.ParamByName('ID_CAP').AsInteger := id_Tipo_Captacion; if ((IBSql2.FieldByName('PLAZO_CUENTA').AsInteger > 0) and (IBSql2.FieldByName('PLAZO_CUENTA').AsInteger <= 179)) then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 21 else if ((IBSql2.FieldByName('PLAZO_CUENTA').AsInteger >= 180) and (IBSql2.FieldByName('PLAZO_CUENTA').AsInteger <= 360)) then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 22 else if ((IBSql2.FieldByName('PLAZO_CUENTA').AsInteger >= 361) and (IBSql2.FieldByName('PLAZO_CUENTA').AsInteger <= 539)) then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 23 else if ((IBSql2.FieldByName('PLAZO_CUENTA').AsInteger >= 180) and (IBSql2.FieldByName('PLAZO_CUENTA').AsInteger <= 360)) then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 24; end; IBSql3.Open; CodContable := IBSql3.FieldByName('CODIGO_CONTABLE').AsString; IBSql3.Close; New(dCuenta); dCuenta.Id_Agencia := IBSql2.FieldByName('ID_AGENCIA').AsInteger; dCuenta.Id_Tipo_Captacion := IBSql2.FieldByName('ID_TIPO_CAPTACION').AsInteger; dCuenta.Numero_Cuenta := IBSql2.FieldByName('NUMERO_CUENTA').AsInteger; dCuenta.Digito_Cuenta := IBSql2.FieldByName('DIGITO_CUENTA').AsInteger; dCuenta.CodContable := CodContable; Cuentas.Add(dCuenta); for i := 0 to IBSql2.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql2.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql2.Fields[i].DataSize)); Nodo3.Value := IBSql2.Fields[i].AsString; end; IBSql2.Close; end; except IBSql2.Transaction.Rollback; raise; Exit; end; IBSql1.Next; end; // fin del while de ciclo de cuentas encontradas para ese asociado CheckBox1.Checked := True; // Procesar cap$maestrotitular por cada una de las cuentas a trasladar Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$maestrotitular'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$maestrotitular".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$maestrotitular".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$maestrotitular".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrotitular".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrotitular".ID_IDENTIFICACION,'); IBSql1.SQL.Add(' "cap$maestrotitular".ID_PERSONA,'); IBSql1.SQL.Add(' "cap$maestrotitular".NUMERO_TITULAR,'); IBSql1.SQL.Add(' "cap$maestrotitular".TIPO_TITULAR'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$maestrotitular"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$maestrotitular".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrotitular".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrotitular".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrotitular".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; yaExiste := False; for k := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[k]; if (dPersona.id = IBSql1.Fields[4].AsInteger) and (dPersona.persona = IBSql1.Fields[5].AsString) then yaExiste := True; end; if not yaExiste then begin New(dPersona); dPersona.id := IBSql1.Fields[4].AsInteger; dPersona.persona := IBSql1.Fields[5].AsString; Personas.Add(dPersona); end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox2.Checked := True; // Fin lectura Maestro titular // Lectura Maestro Saldo Inicial Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$maestrosaldoinicial'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ANO,'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".SALDO_INICIAL'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldoinicial".ANO = :ANO'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; IBSql1.ParamByName('ANO').AsString := IntToStr(yearof(now)); try IBSql1.Open; if IBSql1.RecordCount > 0 then begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; end; except IBTransaction1.Rollback; raise; Exit; end; end; CheckBox3.Checked := True; // Fin lectura maestro saldo inicial // Lectura Maestro Saldos Mes Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$maestrosaldosmes'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$maestrosaldosmes".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".MES,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".DEBITO,'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".CREDITO'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$maestrosaldosmes"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosaldosmes".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; try IBSql1.Open; if IBSql1.RecordCount > 0 then begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; end; except IBTransaction1.Rollback; raise; Exit; end; end; CheckBox4.Checked := True; // Fin Lectura mestro saldos mes // Lectura Maestro Apertura Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$maestrosapertura'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$maestrosapertura".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$maestrosapertura".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$maestrosapertura".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosapertura".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$maestrosapertura".FECHA,'); IBSql1.SQL.Add(' "cap$maestrosapertura".HORA,'); IBSql1.SQL.Add(' "cap$maestrosapertura".EFECTIVO,'); IBSql1.SQL.Add(' "cap$maestrosapertura".CHEQUE'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$maestrosapertura"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$maestrosapertura".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosapertura".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosapertura".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$maestrosapertura".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; try IBSql1.Open; if IBSql1.RecordCount > 0 then begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; end; except IBTransaction1.Rollback; raise; Exit; end; end; CheckBox5.Checked := True; // Fin Lectura Maestro Apertura // Lectura Extractos Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$extracto'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$extracto".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$extracto".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$extracto".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$extracto".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$extracto".FECHA_MOVIMIENTO,'); IBSql1.SQL.Add(' "cap$extracto".HORA_MOVIMIENTO,'); IBSql1.SQL.Add(' "cap$extracto".ID_TIPO_MOVIMIENTO,'); IBSql1.SQL.Add(' "cap$extracto".DOCUMENTO_MOVIMIENTO,'); IBSql1.SQL.Add(' "cap$extracto".DESCRIPCION_MOVIMIENTO,'); IBSql1.SQL.Add(' "cap$extracto".VALOR_DEBITO,'); IBSql1.SQL.Add(' "cap$extracto".VALOR_CREDITO'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$extracto"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$extracto".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$extracto".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$extracto".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$extracto".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$extracto".FECHA_MOVIMIENTO BETWEEN :FECHA1 and :FECHA2'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; IBSql1.ParamByName('FECHA1').AsDate := Fecha1; IBSql1.ParamByName('FECHA2').AsDate := Fecha2; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin if IBSql1.FieldDefs.Items[j].DataType = fttime then begin Nodo3 := Nodo2.Items.Add('campo',FormatDateTime('hh:mm:ss',IBSql1.Fields.Fields[j].AsDateTime)); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end else begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox6.Checked := True; // Fin Lectura Extractos // Lectura Tabla Liquidacion Cdats Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$tablaliquidacion'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$tablaliquidacion".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".FECHA_PAGO,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".VALOR,'); IBSql1.SQL.Add(' "cap$tablaliquidacion".PAGADO'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$tablaliquidacion"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$tablaliquidacion".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacion".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacion".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacion".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox7.Checked := True; // Fin Lectura Tabla Liquidacion Cdats // Lectura Tabla Liquidacion Contractural Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$tablaliquidacioncon'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".FECHA_DESCUENTO,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".VALOR,'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".DESCONTADO'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$tablaliquidacioncon".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox8.Checked := True; // Fin Lectura Tabla Liquidacion Contractual // Lectura tabla saldos iniciales mes Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','cap$saldosmes'); // Procesar datos adicionales de cada cuenta. for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "cap$saldosmes".ID_AGENCIA,'); IBSql1.SQL.Add(' "cap$saldosmes".ID_TIPO_CAPTACION,'); IBSql1.SQL.Add(' "cap$saldosmes".NUMERO_CUENTA,'); IBSql1.SQL.Add(' "cap$saldosmes".DIGITO_CUENTA,'); IBSql1.SQL.Add(' "cap$saldosmes".ANO,'); IBSql1.SQL.Add(' "cap$saldosmes".MES,'); IBSql1.SQL.Add(' "cap$saldosmes".SALDOINICIAL'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "cap$saldosmes"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "cap$saldosmes".ID_AGENCIA = :ID_AGENCIA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$saldosmes".ID_TIPO_CAPTACION = :ID_TIPO_CAPTACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$saldosmes".NUMERO_CUENTA = :NUMERO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$saldosmes".DIGITO_CUENTA = :DIGITO_CUENTA'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "cap$saldosmes".ANO = :ANO'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := dCuenta.Id_Agencia; IBSql1.ParamByName('ID_TIPO_CAPTACION').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql1.ParamByName('NUMERO_CUENTA').AsInteger := dCuenta.Numero_Cuenta; IBSql1.ParamByName('DIGITO_CUENTA').AsInteger := dCuenta.Digito_Cuenta; IBSql1.ParamByName('ANO').AsInteger := yearof(Now); try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); Nodo3.Value := IBSql1.Fields[j].AsString; end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox9.Checked := True; // Fin Lectura Tabla Liquidacion Contractual // Inicio Traslado de Solicitudes vAnalista := 'WURIBE'; vContador := 1; vTabla := False; vId_Persona := EdDocumento.Text; vId_Identificacion := EdTipo.Value; with IBSql1 do begin SQL.Clear; SQL.Add('select * from "col$solicitud" where ID_PERSONA = :ID_PERSONA and ID_IDENTIFICACION = :ID_IDENTIFICACION'); ParamByName('ID_PERSONA').AsString := vId_Persona; ParamByName('ID_IDENTIFICACION').AsInteger := vId_Identificacion; Open; if RecordCount > 0 then //registro de solicitudes begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$solicitud'); while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; CdSolicitud.Append; CdSolicitud.FieldValues['ID_SOLICITUD'] := FieldByName('ID_SOLICITUD').AsString; CdSolicitud.Post; Next; end; yaExiste := False; for k := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[k]; if (dPersona.id = IBSql1.Fields[2].AsInteger) and (dPersona.persona = IBSql1.Fields[1].AsString) then yaExiste := True; end; if not yaExiste then begin New(dPersona); dPersona.id := IBSql1.Fields[2].AsInteger; dPersona.persona := IBSql1.Fields[1].AsString; Personas.Add(dPersona); end; end; //fin registro de solicitudes // busqueda de codeudores vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$codeudor" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$codeudor'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; yaExiste := False; for k := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[k]; if (dPersona.id = IBSql1.Fields[2].AsInteger) and (dPersona.persona = IBSql1.Fields[1].AsString) then yaExiste := True; end; if not yaExiste then begin New(dPersona); dPersona.id := IBSql1.Fields[2].AsInteger; dPersona.persona := IBSql1.Fields[1].AsString; Personas.Add(dPersona); end; Next; end; end; CdSolicitud.Next; end; //fin del registra codeudor // busqueda de conyuges vTabla := False; vContador := 0; SQL.Clear; SQL.Add('select * from "col$infconyuge" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$infconyuge'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin del registra conyuges // busqueda de referencias Close; SQL.Clear; SQL.Add('select * from "col$referencias" where ID_PERSONA = :ID_PERSONA and ID_IDENTIFICACION = :ID_IDENTIFICACION'); ParamByName('ID_PERSONA').AsString := vId_Persona; ParamByName('ID_IDENTIFICACION').AsInteger := vId_Identificacion; Open; if RecordCount > 0 then //registro de solicitudes begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$referencias'); while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; //fin registro de referencias solicitud // busqueda entardas de las solicitudes vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$referenciasolicitud" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$referenciasolicitud'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin entradas de las solicitudes // busqueda registros de sesion vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$registrosesion" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$registrosesion'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin if FieldDefs.Items[i].DataType = fttime then begin Nodo3 := Nodo2.Items.Add('campo',FormatDateTime('hh:mm:ss',Fields.Fields[i].AsDateTime)); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end end; Next; end; end; CdSolicitud.Next; end; //fin consulta de registro de sesion // registro de la entrada de los analistas vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$solicitudanalista" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$solicitudanalista'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin if i = 2 then begin Nodo3 := Nodo2.Items.Add('campo',vAnalista); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin if FieldDefs.Items[i].DataType = ftdatetime then begin Nodo3 := Nodo2.Items.Add('campo',FormatDateTime('yyyy/mm/dd hh:mm:ss',Fields.Fields[i].AsDateTime)); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; end; end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin consulta de los analista // consulta de los requisisitos vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$solicitudrequisito" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$solicitudrequisito'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin consulta de los requisistos // consulta de los requisisitos vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$observacion" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$observacion'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin consulta de la observaciones del analista // consulta bien raiz vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "gen$bienesraices" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$bienesraices'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //consulta infromacion crediticia // consulta bien raiz vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "gen$infcrediticia" where ID_SOLICITUD = :ID_SOLICITUD'); CdSolicitud.First; while not CdSolicitud.Eof do begin Close; ParamByName('ID_SOLICITUD').AsString := CdSolicitud.FieldByName('ID_SOLICITUD').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$infcrediticia'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; vContador := vContador + 1; Next; end; end; CdSolicitud.Next; end; //fin consulta bien raiz Close; // consulta de informacion de persona infpersona SQL.Clear; SQL.Add('select * from "gen$infpersona" where ID_PERSONA = :ID_PERSONA and ID_IDENTIFICACION = :ID_IDENTIFICACION'); ParamByName('ID_PERSONA').AsString := vId_Persona; ParamByName('ID_IDENTIFICACION').AsInteger := vId_Identificacion; Open; if RecordCount > 0 then //registro de solicitudes begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$infpersona'); while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; //fin consulat de informacion adicional de la persona Close;// consulta de vehiculos SQL.Clear; SQL.Add('select * from "gen$vehiculo" where ID_PERSONA = :ID_PERSONA and ID_IDENTIFICACION = :ID_IDENTIFICACION'); ParamByName('ID_PERSONA').AsString := vId_Persona; ParamByName('ID_IDENTIFICACION').AsInteger := vId_Identificacion; Open; if RecordCount > 0 then //registro de solicitudes begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$vehiculo'); while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; //fin consulta de vehiculos // end; // Fin Traslado de Solicitudes // Inicio Traslado de Cartera vTabla := False; SQL.Clear; SQL.Add('select * from "col$colocacion" where ID_PERSONA = :ID_PERSONA and ID_IDENTIFICACION = :ID_IDENTIFICACION and ID_ESTADO_COLOCACION IN (0,2,3,8,9)'); ParamByName('ID_PERSONA').AsString := EdDocumento.Text; ParamByName('ID_IDENTIFICACION').AsInteger := EdTipo.Value; Open; if RecordCount > 0 then //registro de Colocaciones begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$colocacion'); while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; CDcartera.Append; CDcartera.FieldValues['ID_COLOCACION'] := FieldByName('ID_COLOCACION').AsString; CDcartera.FieldValues['CLASIFICACION'] := FieldByName('ID_CLASIFICACION').AsInteger; CDcartera.FieldValues['GARANTIA'] := FieldByName('ID_GARANTIA').AsInteger; CDcartera.FieldValues['CATEGORIA'] := FieldByName('ID_EVALUACION').AsString; CDcartera.Post; yaExiste := False; for k := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[k]; if (dPersona.id = IBSql1.Fields[2].AsInteger) and (dPersona.persona = Trim(IBSql1.Fields[3].AsString)) then yaExiste := True; end; if not yaExiste then begin New(dPersona); dPersona.id := IBSql1.Fields[2].AsInteger; dPersona.persona := Trim(IBSql1.Fields[3].AsString); Personas.Add(dPersona); end; Next; end; end; //fin registro de Colocaciones // Busqueda de extracto vTabla := False; SQL.Clear; SQL.Add('select * from "col$extracto" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$extracto'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do if FieldDefs.Items[i].DataType = fttime then begin Nodo3 := Nodo2.Items.Add('campo',FormatDateTime('hh:mm:ss',Fields.Fields[i].AsDateTime)); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //fin del registra extracto // Busqueda de Extracto Detallado vTabla := False; SQL.Clear; SQL.Add('select * from "col$extractodet" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$extractodet'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin if FieldDefs.Items[i].DataType = fttime then begin Nodo3 := Nodo2.Items.Add('campo',FormatDateTime('hh:mm:ss',Fields.Fields[i].AsDateTime)); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; end; Next; end; end; CDcartera.Next; end; //fin del registra Extracto Detallado // Busqueda de Garantias Personales vTabla := False; SQL.Clear; SQL.Add('select * from "col$colgarantias" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$colgarantias'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; yaExiste := False; for k := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[k]; if (dPersona.id = IBSql1.Fields[2].AsInteger) and (dPersona.persona = Trim(IBSql1.Fields[3].AsString)) then yaExiste := True; end; if not yaExiste then begin New(dPersona); dPersona.id := IBSql1.Fields[2].AsInteger; dPersona.persona := Trim(IBSql1.Fields[3].AsString); Personas.Add(dPersona); end; Next; end; end; CDcartera.Next; end; //Fin registro de Garantias Personales // Busqueda de Garantias Reales vTabla := False; SQL.Clear; SQL.Add('select * from "col$colgarantiasreal" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$colgarantiasreal'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin registro de Garantias Reales // Busqueda de Tabla de Liquidacion vTabla := False; vContador := 1; SQL.Clear; SQL.Add('select * from "col$tablaliquidacion" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$tablaliquidacion'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do if i = 2 then begin Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Tabla de Liquidacion // Busqueda Registros de Costas vTabla := False; SQL.Clear; SQL.Add('select * from "col$costas" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$costas'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Registro de Costas // Registro de Pagos Consignacion Nal vTabla := False; SQL.Clear; SQL.Add('select * from "col$pagoconnal" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$pagoconnal'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Pagos Consignacion Nal // Registro Control de Cobro vTabla := False; SQL.Clear; SQL.Add('select * from "col$controlcobro" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$controlcobro'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Control de Cobro // Registro Colocaciones en Abogados vTabla := False; SQL.Clear; SQL.Add('select * from "col$colocacionabogado" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$colocacionabogado'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Colocaciones en Abogados // Registro Cambios de Estado vTabla := False; SQL.Clear; SQL.Add('select * from "col$cambioestado" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$cambioestado'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 0 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Cambios de Estado // Registro Marcas vTabla := False; SQL.Clear; SQL.Add('select * from "col$marcas" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$marcas'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); for i := 0 to FieldDefs.Count -1 do if i = 1 then begin Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end else begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Registro de Marcas //Inicio Provisiones de años anteriores vTabla := False; SQL.Clear; SQL.Add('select * from "col$causaciondiariamov" where ID_COLOCACION = :ID_COLOCACION'); CDcartera.First; while not CDcartera.Eof do begin Close; ParamByName('ID_COLOCACION').AsString := CDcartera.FieldByName('ID_COLOCACION').AsString; Open; if RecordCount > 0 then begin if vTabla = False then // valida si fue creado el nodo begin vTabla := True; Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','col$causaciondiariamov'); end; while not Eof do begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo3 := Nodo2.Items.Add('campo',AgenciaT); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[0].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[0].DataSize)); for i := 1 to FieldDefs.Count -1 do begin Nodo3 := Nodo2.Items.Add('campo',Fields.Fields[i].AsString); Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[i].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[i].DataSize)); end; Next; end; end; CDcartera.Next; end; //Fin Registro de Provisiones Anteriores end; // Fin Traslado de Cartera // Guardar información de Persona Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$persona'); // Procesar datos adicionales de cada cuenta. for i := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "gen$persona".ID_IDENTIFICACION,'); IBSql1.SQL.Add(' "gen$persona".ID_PERSONA,'); IBSql1.SQL.Add(' "gen$persona".LUGAR_EXPEDICION,'); IBSql1.SQL.Add(' "gen$persona".FECHA_EXPEDICION,'); IBSql1.SQL.Add(' "gen$persona".NOMBRE,'); IBSql1.SQL.Add(' "gen$persona".PRIMER_APELLIDO,'); IBSql1.SQL.Add(' "gen$persona".SEGUNDO_APELLIDO,'); IBSql1.SQL.Add(' "gen$persona".ID_TIPO_PERSONA,'); IBSql1.SQL.Add(' "gen$persona".SEXO,'); IBSql1.SQL.Add(' "gen$persona".FECHA_NACIMIENTO,'); IBSql1.SQL.Add(' "gen$persona".LUGAR_NACIMIENTO,'); IBSql1.SQL.Add(' "gen$persona".PROVINCIA_NACIMIENTO,'); IBSql1.SQL.Add(' "gen$persona".DEPTO_NACIMIENTO,'); IBSql1.SQL.Add(' "gen$persona".PAIS_NACIMIENTO,'); IBSql1.SQL.Add(' "gen$persona".ID_TIPO_ESTADO_CIVIL,'); IBSql1.SQL.Add(' "gen$persona".ID_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".ID_IDENTIFICACION_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".NOMBRE_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".PRIMER_APELLIDO_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".SEGUNDO_APELLIDO_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".ID_APODERADO,'); IBSql1.SQL.Add(' "gen$persona".ID_IDENTIFICACION_APODERADO,'); IBSql1.SQL.Add(' "gen$persona".NOMBRE_APODERADO,'); IBSql1.SQL.Add(' "gen$persona".PRIMER_APELLIDO_APODERADO,'); IBSql1.SQL.Add(' "gen$persona".SEGUNDO_APELLIDO_APODERADO,'); IBSql1.SQL.Add(' "gen$persona".PROFESION,'); IBSql1.SQL.Add(' "gen$persona".ID_ESTADO,'); IBSql1.SQL.Add(' "gen$persona".ID_TIPO_RELACION,'); IBSql1.SQL.Add(' "gen$persona".ID_CIIU,'); IBSql1.SQL.Add(' "gen$persona".EMPRESA_LABORA,'); IBSql1.SQL.Add(' "gen$persona".FECHA_INGRESO_EMPRESA,'); IBSql1.SQL.Add(' "gen$persona".CARGO_ACTUAL,'); IBSql1.SQL.Add(' "gen$persona".DECLARACION,'); IBSql1.SQL.Add(' "gen$persona".INGRESOS_A_PRINCIPAL,'); IBSql1.SQL.Add(' "gen$persona".INGRESOS_OTROS,'); IBSql1.SQL.Add(' "gen$persona".INGRESOS_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".INGRESOS_CONYUGE_OTROS,'); IBSql1.SQL.Add(' "gen$persona".DESC_INGR_OTROS,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_ALQUILER,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_SERVICIOS,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_TRANSPORTE,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_ALIMENTACION,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_DEUDAS,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_OTROS,'); IBSql1.SQL.Add(' "gen$persona".DESC_EGRE_OTROS,'); IBSql1.SQL.Add(' "gen$persona".EGRESOS_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".OTROS_EGRESOS_CONYUGE,'); IBSql1.SQL.Add(' "gen$persona".TOTAL_ACTIVOS,'); IBSql1.SQL.Add(' "gen$persona".TOTAL_PASIVOS,'); IBSql1.SQL.Add(' "gen$persona".EDUCACION,'); IBSql1.SQL.Add(' "gen$persona".RETEFUENTE,'); IBSql1.SQL.Add(' "gen$persona".ACTA,'); IBSql1.SQL.Add(' "gen$persona".FECHA_REGISTRO,'); IBSql1.SQL.Add(' "gen$persona".FOTO,'); IBSql1.SQL.Add(' "gen$persona".FIRMA,'); IBSql1.SQL.Add(' "gen$persona".ESCRITURA_CONSTITUCION,'); IBSql1.SQL.Add(' "gen$persona".DURACION_SOCIEDAD,'); IBSql1.SQL.Add(' "gen$persona".CAPITAL_SOCIAL,'); IBSql1.SQL.Add(' "gen$persona".MATRICULA_MERCANTIL,'); IBSql1.SQL.Add(' "gen$persona".FOTO_HUELLA,'); IBSql1.SQL.Add(' "gen$persona".DATOS_HUELLA,'); IBSql1.SQL.Add(' "gen$persona".EMAIL,'); IBSql1.SQL.Add(' "gen$persona".ID_EMPLEADO,'); IBSql1.SQL.Add(' "gen$persona".FECHA_ACTUALIZACION'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "gen$persona"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "gen$persona".ID_IDENTIFICACION = :ID_IDENTIFICACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "gen$persona".ID_PERSONA = :ID_PERSONA'); IBSql1.ParamByName('ID_IDENTIFICACION').AsInteger := dPersona.id; IBSql1.ParamByName('ID_PERSONA').AsString := dPersona.persona; try IBSql1.Open; if IBSql1.RecordCount > 0 then begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); if IBSql1.Fields[j].DataType in [ ftBlob, ftGraphic ] then begin fO := SZFullEncodeOnlyBase64(IBSql1.Fields[j].AsString); Nodo3.Value := fO; Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); end else begin Nodo3.Value := IBSql1.Fields[j].AsString; Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); end; end; end; except IBTransaction1.Rollback; raise; Exit; end; end; CheckBox10.Checked := True; // Fin Información de Personas // Lectura Información Direcciones Persona Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$direccion'); // Procesar datos adicionales de cada cuenta. for i := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "gen$direccion".ID_IDENTIFICACION,'); IBSql1.SQL.Add(' "gen$direccion".ID_PERSONA,'); IBSql1.SQL.Add(' "gen$direccion".CONSECUTIVO,'); IBSql1.SQL.Add(' "gen$direccion".ID_DIRECCION,'); IBSql1.SQL.Add(' "gen$direccion".DIRECCION,'); IBSql1.SQL.Add(' "gen$direccion".BARRIO,'); IBSql1.SQL.Add(' "gen$direccion".COD_MUNICIPIO,'); IBSql1.SQL.Add(' "gen$direccion".MUNICIPIO,'); IBSql1.SQL.Add(' "gen$direccion".TELEFONO1,'); IBSql1.SQL.Add(' "gen$direccion".TELEFONO2,'); IBSql1.SQL.Add(' "gen$direccion".TELEFONO3,'); IBSql1.SQL.Add(' "gen$direccion".TELEFONO4'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "gen$direccion"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "gen$direccion".ID_IDENTIFICACION = :ID_IDENTIFICACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "gen$direccion".ID_PERSONA = :ID_PERSONA'); IBSql1.ParamByName('ID_IDENTIFICACION').AsInteger := dPersona.id; IBSql1.ParamByName('ID_PERSONA').AsString := dPersona.persona; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Value := IBSql1.Fields[j].AsString; Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox11.Checked := True; // Fin Lectura Direcciones // Lectura Información Referencias Persona Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$referencias'); // Procesar datos adicionales de cada cuenta. for i := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "gen$referencias".TIPO_ID_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".ID_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".CONSECUTIVO_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".PRIMER_APELLIDO_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".SEGUNDO_APELLIDO_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".NOMBRE_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".DIRECCION_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".TELEFONO_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".TIPO_REFERENCIA,'); IBSql1.SQL.Add(' "gen$referencias".PARENTESCO_REFERENCIA'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "gen$referencias"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "gen$referencias".TIPO_ID_REFERENCIA = :ID_IDENTIFICACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "gen$referencias".ID_REFERENCIA = :ID_PERSONA'); IBSql1.ParamByName('ID_IDENTIFICACION').AsInteger := dPersona.id; IBSql1.ParamByName('ID_PERSONA').AsString := dPersona.persona; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Value := IBSql1.Fields[j].AsString; Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox12.Checked := True; // Fin Lectura Referencia // Lectura Información Beneficiarios de la Persona Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','gen$beneficiario'); // Procesar datos adicionales de cada cuenta. for i := 0 to Personas.Count - 1 do begin dPersona := Personas.Items[i]; IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT '); IBSql1.SQL.Add(' "gen$beneficiario".ID_AGENCIA,'); IBSql1.SQL.Add(' "gen$beneficiario".ID_PERSONA,'); IBSql1.SQL.Add(' "gen$beneficiario".ID_IDENTIFICACION,'); IBSql1.SQL.Add(' "gen$beneficiario".CONSECUTIVO,'); IBSql1.SQL.Add(' "gen$beneficiario".PRIMER_APELLIDO,'); IBSql1.SQL.Add(' "gen$beneficiario".SEGUNDO_APELLIDO,'); IBSql1.SQL.Add(' "gen$beneficiario".NOMBRE,'); IBSql1.SQL.Add(' "gen$beneficiario".ID_PARENTESCO,'); IBSql1.SQL.Add(' "gen$beneficiario".PORCENTAJE,'); IBSql1.SQL.Add(' "gen$beneficiario".AUXILIO'); IBSql1.SQL.Add('FROM'); IBSql1.SQL.Add(' "gen$beneficiario"'); IBSql1.SQL.Add('WHERE'); IBSql1.SQL.Add(' "gen$beneficiario".ID_IDENTIFICACION = :ID_IDENTIFICACION'); IBSql1.SQL.Add('AND'); IBSql1.SQL.Add(' "gen$beneficiario".ID_PERSONA = :ID_PERSONA'); IBSql1.ParamByName('ID_IDENTIFICACION').AsInteger := dPersona.id; IBSql1.ParamByName('ID_PERSONA').AsString := dPersona.persona; try IBSql1.Open; if IBSql1.RecordCount > 0 then while not IBSql1.Eof do begin Nodo2 := Nodo1.Items.Add('registro'); for j := 0 to IBSql1.FieldCount - 1 do begin Nodo3 := Nodo2.Items.Add('campo'); Nodo3.Value := IBSql1.Fields[j].AsString; Nodo3.Properties.Add('tipo',fldtostr(IBSql1.Fields[j].DataType)); Nodo3.Properties.Add('Size',IntToStr(IBSql1.Fields[j].DataSize)); end; IBSql1.Next; end; except IBSql1.Transaction.Rollback; raise; Exit; end; end; // fin del for de cuentas CheckBox13.Checked := True; // Fin Lectura Referencia end; procedure TfrmServerTraslados.Contabilizar; var i:Integer; Saldo:Currency; SaldoK,ProvK,Costas,ProvI,ProvC,Causados,Anticipados,Contingentes:Currency; CodAportes,CodAhorros,CodCausaCdat,CodCausaContractual:string; CodDControl,CodCont,CodAcCont,CodOHip,CodOCdat,CredAprob:string; SucK,SucCxC,SucProv,SucOPas:string; SucAportes,SucAhorros:string; TotalAportes,TotalAhorros:Currency; Dias,DiasCxC,DiasContingencia,DiasCalc,DiasCorrientes,DiasANT,DiasCON:Integer; FechaFinal,FechaInicial,FechaCorte,FechaDesembolso:TDate; Tasa,Tasa1,TasaViv,TasaAnt:Double; Bisiesto:Boolean; ListaFechas:TList; AFechas:PFechasLiq; begin Nodo1 := xml.Root.Items.Add('tabla'); Nodo1.Properties.Add('nombre','con$auxiliar'); //INICIO DEPOSITOS TotalAportes := 0; TotalAhorros := 0; for i := 0 to Cuentas.Count - 1 do begin dCuenta := Cuentas.Items[i]; Saldo := 0; if dCuenta.Id_Tipo_Captacion = 1 then begin //Es aportes IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO_CONTABLE from "cap$contable" where ID_CAPTACION = :ID_CAP AND ID_CONTABLE = :ID_CONTABLE'); IBSql3.ParamByName('ID_CAP').AsInteger := DCUENTA.Id_Tipo_Captacion; if AgenciaT = 1 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 16 else if AgenciaT = 2 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 17 else if AgenciaT = 3 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 18 else if AgenciaT = 4 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 19; IBSql3.Open; SucAportes := IBSql3.FieldByName('CODIGO_CONTABLE').AsString; IBSql3.Close; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT SALDO_ACTUAL FROM SALDO_ACTUAL(:AG,:TP,:CTA,:DGT,:ANO,:FECHA1,:FECHA2)'); IBSql3.ParamByName('AG').AsInteger := dCuenta.Id_Agencia; IBSql3.ParamByName('TP').AsInteger := dCuenta.Id_Tipo_Captacion; IBSql3.ParamByName('CTA').AsInteger := dCuenta.Numero_Cuenta; IBSql3.ParamByName('DGT').AsInteger := dCuenta.Digito_Cuenta; IBSql3.ParamByName('ANO').AsInteger := YearOf(Date); IBSql3.ParamByName('FECHA1').AsDate := EncodeDate(YearOf(Date),01,01); IBSql3.ParamByName('FECHA2').AsDate := Date; IBSql3.Open; Saldo := IBSql3.FieldByName('SALDO_ACTUAL').AsCurrency; TotalAportes := TotalAportes + Saldo; IBSql3.Close; if Saldo > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',dCuenta.CodContable); Nodo2.Items.Add('campo',CurrToStr(Saldo)); end; end // FIN APORTES else begin //ES DEPOSITOS IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO_CONTABLE from "cap$contable" where ID_CAPTACION = :ID_CAP AND ID_CONTABLE = :ID_CONTABLE'); IBSql3.ParamByName('ID_CAP').AsInteger := 2; if AgenciaT = 1 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 16 else if AgenciaT = 2 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 17 else if AgenciaT = 3 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 18 else if AgenciaT = 4 then IBSql3.ParamByName('ID_CONTABLE').AsInteger := 19; IBSql3.Open; SucAhorros := IBSql3.FieldByName('CODIGO_CONTABLE').AsString; IBSql3.Close; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT SALDO_ACTUAL FROM SALDO_ACTUAL(:AG,:TP,:CTA,:DGT,:ANO,:FECHA1,:FECHA2)'); IBSql3.ParamByName('AG').AsInteger := DCUENTA.Id_Agencia; IBSql3.ParamByName('TP').AsInteger := DCUENTA.Id_Tipo_Captacion; IBSql3.ParamByName('CTA').AsInteger := DCUENTA.Numero_Cuenta; IBSql3.ParamByName('DGT').AsInteger := DCUENTA.Digito_Cuenta; IBSql3.ParamByName('ANO').AsInteger := YearOf(Date); IBSql3.ParamByName('FECHA1').AsDate := EncodeDate(YearOf(Date),01,01); IBSql3.ParamByName('FECHA2').AsDate := Date; IBSql3.Open; Saldo := IBSql3.FieldByName('SALDO_ACTUAL').AsCurrency; TotalAhorros := TotalAhorros + Saldo; IBSql3.Close; if Saldo > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',dCuenta.CodContable); Nodo2.Items.Add('campo',CurrToStr(Saldo)); end; //Busca Causacion de Cdat y Contractual if (dCuenta.Id_Tipo_Captacion = 6) then begin IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO_PUC FROM "cap$codigoscausacion" WHERE ES_INTERESES = 1'); IBSql3.Open; CodCausaCdat := IBSql3.FieldByName('CODIGO_PUC').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT NETO_TOTAL from "cap$causacioncdat" where ID_AGENCIA = :AG AND NUMERO_CUENTA = :NUMERO'); IBSql3.SQL.Add('AND DIGITO_CUENTA = :DIGITO AND ANO = :ANO AND MES = :MES'); IBSql3.ParamByName('AG').AsInteger := DCUENTA.Id_Agencia; IBSql3.ParamByName('NUMERO').AsInteger := DCUENTA.Numero_Cuenta; IBSql3.ParamByName('DIGITO').AsInteger := DCUENTA.Digito_Cuenta; IBSql3.ParamByName('ANO').AsString := IntToStr(YearOf(Date)); IBSql3.ParamByName('MES').AsInteger := (MonthOf(Date) - 1); IBSql3.Open; if IBSql3.FieldByName('NETO_TOTAL').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodCausaCdat); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('NETO_TOTAL').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucAhorros); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('NETO_TOTAL').AsCurrency)); end; IBSql3.Close; end; if (dCuenta.Id_Tipo_Captacion = 5) then begin IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "cap$codigoscontractual" WHERE ID_CODIGO = 2'); IBSql3.Open; CodCausaContractual := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CAUSACION_ACUMULADA from "cap$causacioncon" where ID_AGENCIA = :AG AND NUMERO_CUENTA = :NUMERO'); IBSql3.SQL.Add('AND DIGITO_CUENTA = :DIGITO AND ANO = :ANO AND MES = :MES'); IBSql3.ParamByName('AG').AsInteger := DCUENTA.Id_Agencia; IBSql3.ParamByName('NUMERO').AsInteger := DCUENTA.Numero_Cuenta; IBSql3.ParamByName('DIGITO').AsInteger := DCUENTA.Digito_Cuenta; IBSql3.ParamByName('ANO').AsString := IntToStr(YearOf(Date)); IBSql3.ParamByName('MES').AsInteger := (MonthOf(Date) - 1); IBSql3.Open; if IBSql3.FieldByName('CAUSACION_ACUMULADA').AsCurrency > 0then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodCausaContractual); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('CAUSACION_ACUMULADA').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucAhorros); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('CAUSACION_ACUMULADA').AsCurrency)); end; IBSql3.Close; end; end; end; // Fin del For //Totaliza Depositos if TotalAportes > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucAportes); Nodo2.Items.Add('campo','-' + CurrToStr(TotalAportes)); end; if TotalAhorros > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucAhorros); Nodo2.Items.Add('campo','-' + CurrToStr(TotalAhorros)); end; // FIN DEPOSITOS // INICIO CARTERA with CDcartera do begin CDcartera.First; while not CDcartera.Eof do begin IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if AgenciaT = 1 then IBSql3.ParamByName('ID').AsInteger := 30 else if AgenciaT = 2 then IBSql3.ParamByName('ID').AsInteger := 31 else if AgenciaT = 3 then IBSql3.ParamByName('ID').AsInteger := 32 else if AgenciaT = 4 then IBSql3.ParamByName('ID').AsInteger := 33; IBSql3.Open; SucK := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if AgenciaT = 1 then IBSql3.ParamByName('ID').AsInteger := 34 else if AgenciaT = 2 then IBSql3.ParamByName('ID').AsInteger := 35 else if AgenciaT = 3 then IBSql3.ParamByName('ID').AsInteger := 36 else if AgenciaT = 4 then IBSql3.ParamByName('ID').AsInteger := 37; IBSql3.Open; SucCxC := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if AgenciaT = 1 then IBSql3.ParamByName('ID').AsInteger := 38 else if AgenciaT = 2 then IBSql3.ParamByName('ID').AsInteger := 39 else if AgenciaT = 3 then IBSql3.ParamByName('ID').AsInteger := 40 else if AgenciaT = 4 then IBSql3.ParamByName('ID').AsInteger := 41; IBSql3.Open; SucProv := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if AgenciaT = 1 then IBSql3.ParamByName('ID').AsInteger := 54 else if AgenciaT = 2 then IBSql3.ParamByName('ID').AsInteger := 55 else if AgenciaT = 3 then IBSql3.ParamByName('ID').AsInteger := 56 else if AgenciaT = 4 then IBSql3.ParamByName('ID').AsInteger := 57; IBSql3.Open; SucOPas := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); IBSql3.ParamByName('ID').AsInteger := 42; IBSql3.Open; CodCont := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); IBSql3.ParamByName('ID').AsInteger := 43; IBSql3.Open; CodDControl := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); IBSql3.ParamByName('ID').AsInteger := 52; IBSql3.Open; CodAcCont := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql4.Close; IBSql4.SQL.Clear; IBSql4.SQL.Add('select * from "col$codigospuc" where ID_CLASIFICACION = :"ID_CLASIFICACION" and '); IBSql4.SQL.Add('ID_GARANTIA = :"ID_GARANTIA" and ID_CATEGORIA = :"ID_CATEGORIA" '); IBSql4.ParamByName('ID_CLASIFICACION').AsInteger := CDcartera.FieldValues['CLASIFICACION']; IBSql4.ParamByName('ID_GARANTIA').AsInteger := CDcartera.FieldValues['GARANTIA']; IBSql4.ParamByName('ID_CATEGORIA').AsString := CDcartera.FieldValues['CATEGORIA']; IBSql4.Open; FechaCorte := EncodeDate(YearOf(Date),MonthOf(Date) - 1,30); IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT ("col$colocacion".VALOR_DESEMBOLSO - "col$colocacion".ABONOS_CAPITAL) AS SALDO,"col$colocacion".ID_EVALUACION,"col$colocacion".FECHA_INTERES,'); IBSql3.SQL.Add('"col$colocacion".ID_ESTADO_COLOCACION,"col$colocacion".ID_LINEA,"col$colocacion".ID_CLASIFICACION,'); IBSql3.SQL.Add('"col$colocacion".AMORTIZA_INTERES,"col$colocacion".ID_TIPO_CUOTA,"col$colocacion".FECHA_DESEMBOLSO,'); IBSql3.SQL.Add('"col$colocacion".ID_INTERES,"col$colocacion".TASA_INTERES_CORRIENTE,"col$colocacion".PUNTOS_INTERES,'); IBSql3.SQL.Add('"col$causaciondiaria".ANTICIPADOS, "col$causaciondiaria".CAUSADOS,"col$causaciondiaria".CONTINGENCIAS,'); IBSql3.SQL.Add('"col$causaciondiaria".PCAPITAL,"col$causaciondiaria".PINTERES, "col$causaciondiaria".PCOSTAS,"col$tiposcuota".INTERES'); IBSql3.SQL.Add('FROM "col$colocacion" INNER JOIN "col$causaciondiaria" ON ("col$colocacion".ID_AGENCIA="col$causaciondiaria".ID_AGENCIA)'); IBSql3.SQL.Add('AND ("col$colocacion".ID_COLOCACION="col$causaciondiaria".ID_COLOCACION)'); IBSql3.SQL.Add('LEFT JOIN "col$tiposcuota" ON ("col$colocacion".ID_TIPO_CUOTA = "col$tiposcuota".ID_TIPOS_CUOTA)'); IBSql3.SQL.Add('WHERE ("col$colocacion".ID_COLOCACION = :ID_COLOCACION and FECHA_CORTE = :FECHA_CORTE)'); IBSql3.ParamByName('ID_COLOCACION').AsString := CDcartera.FieldValues['ID_COLOCACION']; IBSql3.ParamByName('FECHA_CORTE').AsDate := FechaCorte; IBSql3.Open; if IBSql3.RecordCount > 0 then begin //Cartera Castigada if IBSql3.FieldByName('ID_ESTADO_COLOCACION').AsInteger = 3 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_CAPITAL_CAS').AsString); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodDControl); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); end else begin //fin Cartera Castigada //contabilizar Capital Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_CAPITAL_CP').AsString); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucK); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); //Fin Capital //Contabilizar Provision a Capital if IBSql3.FieldByName('PCAPITAL').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_PROV_CAPITAL').AsString); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('PCAPITAL').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucProv); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('PCAPITAL').AsCurrency)); end; //Fin Provision a Capital //Contabilizar Provision a Interes if IBSql3.FieldByName('PINTERES').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_PROV_INTERES').AsString); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('PINTERES').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucProv); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('PINTERES').AsCurrency)); end; //Fin Provision a Interes //Contabilizar Provision a Costas if IBSql3.FieldByName('PCOSTAS').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_PROV_COSTAS').AsString); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('PCOSTAS').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucProv); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('PCOSTAS').AsCurrency)); end; //Fin Provision a Costas //Contabilizar Intereses Dias := DiasEntre(IBSql3.FieldByName('FECHA_INTERES').AsDateTime,Date); Tasa1 := BuscoTasaEfectivaMaximaNueva(IBQVarios,Date); IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('select DIAS_INICIALES from "col$codigospuc" where'); IBSql1.SQL.Add('ID_CLASIFICACION = :CLASIFICACION and '); IBSql1.SQL.Add('ID_GARANTIA = :GARANTIA and '); IBSql1.SQL.Add('ID_CATEGORIA = :CATEGORIA'); IBSql1.ParamByName('CLASIFICACION').AsInteger := CDcartera.FieldValues['CLASIFICACION']; IBSql1.ParamByName('GARANTIA').AsInteger := CDcartera.FieldValues['GARANTIA']; IBSql1.ParamByName('CATEGORIA').AsString := 'C'; IBSql1.Open; DiasContingencia := IBSql1.FieldByName('DIAS_INICIALES').AsInteger; IBSql1.Close; DiasCorrientes := Dias; if IBSql3.FieldByName('INTERES').AsString = 'V' then DiasContingencia := DiasContingencia + IBSql3.FieldByName('AMORTIZA_INTERES').AsInteger; if Dias > 0 then if (Dias >= DiasContingencia) then begin DiasANT := 0; DiasCON := Dias - (DiasContingencia - 1); DiasCXC := DiasContingencia - 1; end else begin DiasANT := 0; DiasCON := 0; DiasCXC := Dias; end// if else begin DiasANT := dias; DiasCON := 0; DiasCXC := 0; end; // if // Evaluar Fechas if DiasCXC > 0 then begin FechaInicial := IBSql3.FieldByName('FECHA_INTERES').AsDateTime; FechaFinal := Date; ListaFechas := TList.Create; if IBSql3.FieldByName('ID_TIPO_CUOTA').AsInteger = 1 then CalcularFechasLiquidarFija(FechaInicial,FechaFinal,FechaFinal,ListaFechas) else if IBSql3.FieldByName('ID_TIPO_CUOTA').AsInteger = 2 then CalcularFechasLiquidarVarAnticipada(FechaInicial,FechaFinal,FechaFinal,ListaFechas) else CalcularFechasLiquidarVarVencida(FechaInicial,FechaFinal,FechaFinal,ListaFechas); Causados := 0; Contingentes := 0; DiasCXC := 0; DiasCON := 0; for i := 0 to ListaFechas.Count - 1 do begin AFechas := ListaFechas.Items[i]; if IBSql3.FieldByName('ID_INTERES').AsInteger = 0 then begin Tasa := BuscoTasaEfectivaMaximaNueva(IBQVarios,AFechas.FechaFinal); if IBSql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat < Tasa then Tasa :=IBsql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat; if IBSql3.FieldByName('ID_EVALUACION').AsString = 'E' then Tasa := TasaNominalVencida(Tasa,30) else begin if IBSql3.FieldByName('INTERES').AsString = 'A' then begin Tasa := TasaNominalAnticipada(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger); end else begin Tasa := TasaNominalVencida(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger); end; end; end else if IBSql3.FieldByName('ID_INTERES').AsInteger = 1 then begin Tasa := BuscoTasaEfectivaMaximaDtfNueva(IBQVarios,AFechas.FechaFinal); if IBSql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat < Tasa then Tasa :=IBsql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat; if IBSql3.FieldByName('ID_EVALUACION').AsString = 'E' then Tasa := TasaNominalVencida(Tasa,30) else begin if IBSql3.FieldByName('INTERES').AsString = 'A' then begin Tasa := TasaNominalAnticipada(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBsql3.FieldByName('PUNTOS_INTERES').AsFloat; end else begin Tasa := TasaNominalVencida(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBsql3.FieldByName('PUNTOS_INTERES').AsFloat; end; end; end else if IBSql3.FieldByName('ID_INTERES').AsInteger = 2 then begin Tasa := BuscoTasaEfectivaMaximaIPCNueva(IBQVarios); if IBSql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat < Tasa then Tasa :=IBsql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat; if IBSql3.FieldByName('ID_EVALUACION').AsString = 'E' then Tasa := TasaNominalVencida(Tasa,30) else begin if IBSql3.FieldByName('INTERES').AsString = 'A' then begin Tasa := TasaNominalAnticipada(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBSql3.FieldByName('PUNTOS_INTERES').AsFloat; end else begin Tasa := TasaNominalVencida(Tasa,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBsql3.FieldByName('PUNTOS_INTERES').AsFloat; end; end; end; //*****Tasa de vivienda***//// if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 3 then begin TasaViv := BuscoTasaEfectivaUvrNueva(IBQVarios,AFechas.FechaFinal); if IBSql3.FieldByName('ID_EVALUACION').AsString = 'E' then TasaViv := TasaNominalVencida(Tasa,30) else begin if IBSql3.FieldByName('INTERES').AsString = 'A' then begin TasaViv := TasaNominalAnticipada(TasaViv,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBsql3.FieldByName('PUNTOS_INTERES').AsFloat; end else begin TasaViv := TasaNominalVencida(TasaViv,IBsql3.FieldByName('AMORTIZA_INTERES').AsInteger) + IBsql3.FieldByName('PUNTOS_INTERES').AsFloat; end; end; if Tasa > TasaViv then Tasa := TasaViv; end; if IBSql3.FieldByName('ID_EVALUACION').AsString = 'E' then Tasa := Tasa1; Bisiesto := False; FechaDesembolso := IBsql3.FieldByName('FECHA_DESEMBOLSO').AsDateTime; if AFechas^.FechaInicial = FechaInicial then AFechas^.FechaInicial := CalculoFecha(FechaInicial,1); DiasCalc := DiasEntreFechas(AFechas^.FechaInicial,AFechas^.FechaFinal,FechaDesembolso,bisiesto); if DiasCalc < 0 then DiasCalc := 0; Dispose(AFechas); if DiasCXC < (DiasContingencia - 1) then begin DiasCXC := DiasCXC + DiasCalc; if DiasCXC > (DiasContingencia - 1) then begin DiasCON := DiasCXC - (DiasContingencia-1); DiasCXC := (DiasContingencia-1); Contingentes := Contingentes + SimpleRoundTo(((IBsql3.FieldByName('SALDO').AsCurrency * (Tasa/100)) / 360 ) * DiasCON,0); DiasCalc := DiasCalc - DiasCON; end; Causados := Causados + SimpleRoundTo(((IBsql3.FieldByName('SALDO').AsCurrency * (Tasa/100)) / 360 ) * DiasCalc,0); end else begin Contingentes := Contingentes + SimpleRoundTo(((IBsql3.FieldByName('SALDO').AsCurrency * (Tasa/100)) / 360 ) * DiasCalc,0); DiasCON := DiasCON + DiasCalc; end; end; ListaFechas.Free; end else begin Contingentes := 0; Causados := 0; DiasCON := 0; DiasCXC := 0; end; // Buscar Tasa Anticipada if DiasANT < 0 then begin TasaAnt := BuscoTasaAnt(AgenciaL,CDcartera.FieldValues['ID_COLOCACION'],IBsql3.FieldByName('FECHA_INTERES').AsDateTime); if TasaAnt = 0 then begin case IBSql3.FieldByName('ID_INTERES').AsInteger of 0 : begin TasaAnt := BuscoTasaEfectivaMaximaNueva(IBQVarios,FechaCorte); if IBSql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat < TasaAnt then TasaAnt := IBsql3.FieldByName('TASA_INTERES_CORRIENTE').AsFloat; end; 1 : TasaAnt := BuscoTasaEfectivaMaximaDtfNueva(IBQVarios,Date); 2 : TasaAnt := BuscoTasaEfectivaMaximaIPCNueva(IBQVarios); end; if IBsql3.FieldByName('INTERES').AsString = 'A' then TasaAnt := TasaNominalAnticipada(TasaAnt,IBSQL3.fieldbyname('AMORTIZA_INTERES').AsInteger) else TasaAnt := TasaNominalVencida(TasaAnt,IBSQL3.FieldByName('AMORTIZA_INTERES').AsInteger); end; end; // Fin Buqueda de Tasa Anticipada // Calculo Intereses Anticipados := SimpleRoundTo(((IBSQL3.FieldByName('SALDO').AsCurrency * (TasaAnt/100)) / 360 ) * -DiasANT,0); // Fin Calculo Intereses //Contabilizar Anticipados if Anticipados > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_INT_ANT').AsString); Nodo2.Items.Add('campo',CurrToStr(Anticipados)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucOPas); Nodo2.Items.Add('campo','-' + CurrToStr(Anticipados)); end; //Fin Anticipados //Contabilizar Causados if Causados > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_CXC').AsString); Nodo2.Items.Add('campo','-' + CurrToStr(Causados)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucCxC); Nodo2.Items.Add('campo',CurrToStr(Causados)); end; //Fin Causados //Contabilizar Costas IBSql1.Close; IBSql1.SQL.Clear; IBSql1.SQL.Add('SELECT SUM(VALOR_COSTAS) AS COSTAS from "col$costas" where ID_AGENCIA = :ID_AGENCIA AND ID_COLOCACION = :ID_COLOCACION'); IBSql1.ParamByName('ID_AGENCIA').AsInteger := AgenciaL; IBSql1.ParamByName('ID_COLOCACION').AsString := CDcartera.FieldValues['ID_COLOCACION']; IBSql1.Open; if IBSql1.FieldByName('COSTAS').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_COSTAS').AsString); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql1.FieldByName('COSTAS').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',SucCxC); Nodo2.Items.Add('campo',CurrToStr(IBSql1.FieldByName('COSTAS').AsCurrency)); end; IBSql1.Close; //Fin Costas //Contabilizar Contingencias if IBSql3.FieldByName('CONTINGENCIAS').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',IBSql4.FieldByName('COD_CONTINGENCIA').AsString); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('CONTINGENCIAS').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodCont); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('CONTINGENCIAS').AsCurrency)); end; //Fin Contingencias // Contabilizar Cuentas de Orden Garantia Cdat if ((IBSql3.FieldByName('ID_LINEA').AsInteger = 6) or (IBSql3.FieldByName('ID_LINEA').AsInteger = 12)) then begin IBSql4.Close; IBSql4.SQL.Clear; IBSql4.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 1 then IBSql4.ParamByName('ID').AsInteger := 48 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 2 then IBSql4.ParamByName('ID').AsInteger := 49 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 3 then IBSql4.ParamByName('ID').AsInteger := 50 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 4 then IBSql4.ParamByName('ID').AsInteger := 51; IBSql4.Open; CodOCdat := IBSql3.FieldByName('CODIGO').AsString; IBSql4.Close; Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodOCdat); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodAcCont); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('SALDO').AsCurrency)); end; //Fin cuentas de Orden Garantia Cdat //Contabilizar Cuentas de Orden Garantia Real Hipoteca IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT ID_CLASIFICACION, SUM(CUENTAS_DE_ORDEN) AS ORDEN FROM "col$colgarantiasreal"'); IBSql3.SQL.Add('INNER JOIN "col$colocacion" on ("col$colgarantiasreal".ID_COLOCACION = "col$colocacion".ID_COLOCACION)'); IBSql3.SQL.Add('WHERE "col$colgarantiasreal".ID_COLOCACION = :ID_COLOCACION group by ID_CLASIFICACION'); IBSql3.ParamByName('ID_COLOCACION').AsString := CDcartera.FieldValues['ID_COLOCACION']; IBSql3.Open; while not IBSql3.Eof do begin IBSql4.Close; IBSql4.SQL.Clear; IBSql4.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 1 then IBSql4.ParamByName('ID').AsInteger := 44 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 2 then IBSql4.ParamByName('ID').AsInteger := 45 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 3 then IBSql4.ParamByName('ID').AsInteger := 46 else if IBSql3.FieldByName('ID_CLASIFICACION').AsInteger = 4 then IBSql4.ParamByName('ID').AsInteger := 47; IBSql4.Open; CodOHip := IBSql4.FieldByName('CODIGO').AsString; IBSql4.Close; if IBSql3.FieldByName('ORDEN').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodOHip); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('ORDEN').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodAcCont); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('ORDEN').AsCurrency)); end; IBSql3.Next; end; //Fin While Garantia Real Hipotecaria end; // Fin de if Cartera Castigada end; // fin de if RecordCount Cartera Next; end; // Fin de While end; //Fin de With // FIN CARTERA //INICIO SOLICITUDES with CDSolicitud do begin CDSolicitud.First; while not CDSolicitud.Eof do begin IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT CODIGO FROM "col$codigospucbasicos" WHERE ID_CODIGOPUCBASICO = :ID'); IBSql3.ParamByName('ID').AsInteger := 53; IBSql3.Open; CredAprob := IBSql3.FieldByName('CODIGO').AsString; IBSql3.Close; IBSql3.SQL.Clear; IBSql3.SQL.Add('SELECT VALOR_APROBADO from "col$solicitud" where ID_SOLICITUD = :ID_SOLICITUD AND ESTADO = 4'); IBSql3.ParamByName('ID_SOLICITUD').AsString := CDSolicitud.FieldValues['ID_SOLICITUD']; IBSql3.Open; if IBSql3.FieldByName('VALOR_APROBADO').AsCurrency > 0 then begin Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CredAprob); Nodo2.Items.Add('campo',CurrToStr(IBSql3.FieldByName('VALOR_APROBADO').AsCurrency)); Nodo2 := Nodo1.Items.Add('Registro'); Nodo2.Items.Add('campo',CodAcCont); Nodo2.Items.Add('campo','-' + CurrToStr(IBSql3.FieldByName('VALOR_APROBADO').AsCurrency)); end; Next; end; //fin de while solicitudes end; // fin de with solicitudes //FIN SOLICITUDES CDcartera.Destroy; CDSolicitud.Destroy; end; function TfrmServerTraslados.BuscoTasaAnt(Ag: Integer;Colocacion: string;FechaIntereses:TDate): Single; begin with IBQVarios do begin Close; SQL.Clear; SQL.Add('select * from "col$extracto" where ID_AGENCIA = :ID_AGENCIA and ID_COLOCACION = :ID_COLOCACION'); SQL.Add('ORDER BY FECHA_EXTRACTO DESC, HORA_EXTRACTO DESC'); ParamByName('ID_AGENCIA').AsInteger := Ag; ParamByName('ID_COLOCACION').AsString := Colocacion; try Open; if RecordCount > 0 then while not Eof do begin if FieldByName('INTERES_PAGO_HASTA').AsDateTime = FechaIntereses then begin Result := SimpleRoundTo(FieldByName('TASA_INTERES_LIQUIDACION').AsFloat); Exit; end; Next; end; Close; Result := 0; except Result := 0; end; end; end; end.
unit NetReaderZenit; interface uses NetReader; // Low level access to Protel Netlist files. type TZenitNetReader = class( TveNetReader ) protected CurrentNet : string; HaveNet : boolean; HaveLine : boolean; LinePos : integer; function GetNetlistDescriptor : string; override; public function CheckCompatibility : boolean; override; procedure ToFirstComponent; override; function GetNextComponent( var Designator, Value, Outline : string ) : boolean; override; procedure ToFirstConnection; override; function GetNextConnection( var NetName, Designator, PinName : string ) : boolean; override; end; implementation uses SysUtils, ParseCSV, ExceptSafe; type ESafeZenitReader = class( ESafe ); // ********************************************** // TProtelNetReader // ********************************************** // safe to scan each code unit (16 bit char) because both bytes of a surrogate // are guaranteed never to match any single unit char. function DeComma( const S : string ) : string; var i : integer; begin result := S; for i := 1 to Length(S) do begin if result[i] = ',' then begin result[i] := '_'; end; end; end; function TZenitNetReader.GetNetlistDescriptor : string; begin result := 'ZenitPCB'; end; function TZenitNetReader.CheckCompatibility : boolean; begin result := True; end; procedure TZenitNetReader.ToFirstComponent; begin LineIndex := 0; while LineIndex < LineLimit do begin // find opening *Parts* of component section of lines, then move // to next line Line := Lines[LineIndex]; Inc( LineIndex ); if Line = '*Parts*' then begin exit; end; end; // *Parts* section not found raise ESafeZenitReader.Create( '*Parts* heading not found.' ); end; function TZenitNetReader.GetNextComponent( var Designator, Value, Outline : string ) : boolean; procedure LoadComponent; var Index : integer; begin // read line of form // Designator;Package;Value;??;???;Datasheet filename. // R1;RES-CR 1/4W S[10.16MM 400MIL];220K;;0.000;C:\PROGRAM FILES\ZENITSUITE\DATASHEET\RESISTOR.PDF Index := 0; ParseCsvValue( Line, Designator, Index, ';' ); ParseCsvValue( Line, Outline, Index, ';' ); ParseCsvValue( Line, Value, Index, ';' ); Designator := Trim( Designator ); Outline := Trim( Outline ); Value := Trim( Value ); // must have designator (eg 'C1', 'Q2') - other fields can be blank // OR could give a dummy designator or no designator ?? // OR raise an exception. if (Designator = '') then begin raise ESafeZenitReader.CreateFmt( 'Component on line %d has blank Designator', [LineIndex + 1] ); end; end; begin // search for next component while LineIndex < LineLimit do begin Line := Trim(Lines[LineIndex]); // parts section ends when *Nets* heading encountered if Line = '*Nets*' then begin result := False; exit; end else if Line <> '' then begin LoadComponent; FCurrentLine := LineIndex + 1; Inc( LineIndex ); result := True; exit; end; Inc( LineIndex ); end; // no component loaded - at end of file raise ESafeZenitReader.Create( 'End of file before *Nets* statement encountered' ); end; procedure TZenitNetReader.ToFirstConnection; begin LineIndex := 0; while LineIndex < LineLimit do begin // find opening *Parts* of component section of lines, then move to // next line Line := Lines[LineIndex]; Inc( LineIndex ); if Line = '*Nets*' then begin HaveNet := False; exit; end; end; // *Parts* section not found raise ESafeZenitReader.Create( '*Nets* heading not found.' ); end; function TZenitNetReader.GetNextConnection( var NetName, Designator, PinName : string ) : boolean; procedure ToNextNet; var ColonPos : integer; SemiColonPos : integer; begin while LineIndex < LineLimit do begin // find opening 'Signal:' of net definition group of lines Line := Trim(Lines[LineIndex]); if Line = '*end*' then begin exit; end else if Pos( 'Signal:', Line ) = 1 then begin ColonPos := Pos( ':', Line ); SemiColonPos := Pos( ';', Line ); if SemiColonPos = 0 then begin end; CurrentNet := Trim( Copy( Line, ColonPos + 1, SemiColonPos - ColonPos -1 )); // successfully entered new net HaveNet := True; HaveLine := False; exit; end; inc( LineIndex ); end; // fell through loop and did not find net : leave HaveNet = False; // HaveNet := False; end; procedure ToNextLine; begin inc( LineIndex ); LinePos := 1; HaveLine := LineIndex < LineLimit; end; // read next pin from current line of form "C2.2 CN1.1 R1.2 IC2.3 IC1.4" function ParseNextPin : boolean; var FirstCharPos : integer; PeriodPos : integer; begin // scan past white space to first char // ..prevent "uninitialised variable" compiler warning FirstCharPos := 0; while LinePos <= Length(Line) do begin if Line[LinePos] <> '' then begin FirstCharPos := LinePos; break; end; inc( LinePos ); end; // possibly no more pin assignment on this line if LinePos > Length(Line) then begin result := False; exit; end; // scan until '.' character // ..prevent "uninitialised variable" compiler warning PeriodPos := 0; while LinePos <= Length(Line) do begin if Line[LinePos] = '.' then begin PeriodPos := LinePos; break; end; inc( LinePos ); end; // scan until next white space (probably digits) while LinePos <= Length(Line) do begin if Line[LinePos] = ' ' then begin break; end; inc( LinePos ); end; if FirstCharPos = PeriodPos then begin raise ESafeZenitReader.CreateFmt( 'Blank designator on net line %d', [LineIndex +1] ); end; NetName := CurrentNet; Designator := Copy( Line, FirstCharPos, PeriodPos - FirstCharPos ); PinName := Copy( Line, PeriodPos +1, LinePos - PeriodPos -1 ); Inc( LinePos ); result := True; end; begin while LineIndex < LineLimit do begin // must be inside a net definition if not HaveNet then begin ToNextNet; // no net definition found if not HaveNet then begin result := False; exit; end; end; // must have a line to digest if not HaveLine then begin ToNextLine; if not HaveLine then begin HaveNet := False; continue; end; end; // read line Line := Trim(Lines[ LineIndex ]); // find end of net definition if Pos( 'Signal:', Line ) = 1 then begin HaveNet := False; continue; end else if Line = '*end*' then begin result := False; exit; end // Parse next designator, pin no from line, of form 'R1.2' else if ParseNextPin then begin FCurrentLine := LineIndex + 1; result := True; exit; end // couldn't parse - end of line else begin HaveLine := False; end; end; // fell through loop - end of netlist file result := False; end; end.
unit Do03; { ULDI03.DPR ================================================================ File: DO03.PAS Library Call Demonstrated: cbDOutScan() Purpose: Multiple writes to a digital output port. Demonstration: Writes to a digital output port and displays the data. Other Library Calls: cbDConfigPort() cbErrHandling() Special Requirements: Board 0 must support paced digital output (for example, CIO-PDMA16). (c) Copyright 1995 - 2002, Measurement Computing Corp. All rights reserved. =========================================================================== } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, cbw; type TfrmDIO = class(TForm) cmdStart: TButton; cmdQuit: TButton; MemoData: TMemo; procedure cmdStartClick(Sender: TObject); procedure cmdQuitClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmDIO: TfrmDIO; implementation {$R *.DFM} var ULStat: Integer; Options: Integer; PortNum: Integer; Direction: Integer; Rate: Longint; DataBuffer: array [0..9] of Word; MemHandle: Integer; ErrReporting: Integer; ErrHandling: Integer; ValString: string; RevLevel: Single; const BoardNum: Integer = 0; Count: Longint = 10; FirstPoint: Longint = 0; TargetRate: Longint = 3; procedure TfrmDIO.FormCreate(Sender: TObject); var index: Integer; data: Integer; begin {declare Revision Level} RevLevel := CURRENTREVNUM; ULStat := cbDeclareRevision(RevLevel); { set up internal error handling for the Universal Library } ErrReporting := PRINTALL; {set Universal Library to print all errors} ErrHandling := STOPALL; {set Universal Library to stop on errors} ULStat := cbErrHandling(ErrReporting, ErrHandling); MemHandle := cbWinBufAlloc (Count); { configure FIRSTPORTA and FIRSTPORTB for digital input Parameters: BoardNum :the number used by CB.CFG to describe this board. PortNum :the input port Direction :sets the port for input or output } PortNum := FIRSTPORTB; Direction := DIGITALOUT; ULStat := cbDConfigPort (BoardNum, PortNum, Direction); If ULStat <> 0 then exit; PortNum := FIRSTPORTA; ULStat := cbDConfigPort (BoardNum, PortNum, Direction); If ULStat <> 0 then exit; Rate := TargetRate; MemoData.Text := Format ('Click Start to write the following array to digital outputs at %dHz...', [Rate]); MemoData.Lines.Add (' '); { place values into the output array } data := 1; for index := 0 to Count - 1 do begin DataBuffer[index] := data; ValString := ValString + Format( ' %d', [DataBuffer[index]]); data := data * 2 end; MemoData.Lines.Add (ValString); { Transfer the array to the buffer set up using cbWinBufAlloc() } ULStat := cbWinArrayToBuf (DataBuffer[0], MemHandle, FirstPoint, Count); If ULStat <> 0 then exit; end; procedure TfrmDIO.cmdStartClick(Sender: TObject); begin MemoData.Text := 'Writing array to digital outputs....'; Application.ProcessMessages; Rate := TargetRate; Options := WORDXFER; ULStat := cbDOutScan (BoardNum, PortNum, Count, Rate, MemHandle, Options); If ULStat <> 0 then exit; MemoData.Text := 'Array has been written to digital outputs.' end; procedure TfrmDIO.cmdQuitClick(Sender: TObject); begin ULStat := cbWinBufFree (MemHandle); Close; end; end.
program exer4; const max = 100; type mat = array [1 .. max,1 .. max] of integer; procedure imprimir(var matriz:mat; tam: integer); var i,j:integer; begin for i:=1 to tam do begin for j:=1 to tam do write(matriz[i,j],' '); writeln(' '); end; end; procedure ler(var matriz:mat; var tam:integer); var i,j:integer; begin read(tam); for i:=1 to tam do for j:=1 to tam do read(matriz[i,j]); end; var matriz:mat; temp,i,j,tam:integer; begin ler(matriz,tam); for i:=1 to tam do for j:=1 to i do begin temp:=matriz[i,j]; matriz[i,j]:=matriz[j,i]; matriz[j,i]:=temp; end; imprimir(matriz,tam); end. //Ex. //- escrever um procedimento que "flipa" uma matriz quadrada sobre a diagonal //principal (matriz transposta) // 1 5 10 // 7 3 11 // 8 2 13 //para // 1 7 8 // 5 3 2 // 10 11 13
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit uMRUList; interface uses System.SysUtils, System.Classes, Data.DBXJSON, uRESTObjects; const MRUDBFILE = 'mru.dat'; // do not localize MRUCAPACITY = 40; type TMRUList = class(TObject) private FItems : TRESTRequestParamsObjectList; FAutoSave : boolean; FFilename : string; public constructor Create( const AFilename : string = '' ); overload; destructor Destroy; override; procedure Clear; procedure AddItem( AItem : TRESTRequestParams ); function ContainsItem( const AURL : string ) : boolean; function RemoveItem( const AURL : string ) : boolean; procedure SaveToFile( const AFilename : string = '' ); procedure LoadFromFile( const AFilename : string = '' ); property AutoSave : boolean read FAutoSave write FAutoSave; property Items : TRESTRequestParamsObjectList read FItems; end; implementation { TMRUList } procedure TMRUList.AddItem( AItem : TRESTRequestParams ); var LItem : TRESTRequestParams; begin Assert( Assigned(AItem) ); /// we do not want duplicates in the mru-list if ContainsItem( AItem.ToString ) then RemoveItem( AItem.ToString ); /// ensure that we do not exceed the desired capacity if (FItems.Count > MRUCAPACITY) then FItems.Delete( FItems.Count-1 ); LItem:= TRESTRequestParams.Create; LItem.Assign( AItem ); /// as this is a MRU-list, we want the most recent item on top FItems.Insert( 0, LItem ); if FAutoSave then SaveToFile; end; procedure TMRUList.Clear; begin FItems.Clear; end; function TMRUList.ContainsItem( const AURL : string ) : boolean; var LItem : TRESTRequestParams; begin result:= FALSE; for LItem IN FItems do begin if SameText(LItem.ToString, AURL) then begin result:= TRUE; BREAK; end; end; end; constructor TMRUList.Create( const AFilename : string = '' ); begin inherited Create; FFilename:= AFilename; FAutoSave:= (FFilename <> ''); FItems:= TRESTRequestParamsObjectList.Create; FItems.OwnsObjects:= TRUE; if (FFilename <> '') AND FileExists(FFilename) then LoadFromFile( FFilename ); end; destructor TMRUList.Destroy; begin Clear; FreeAndNIL( FItems ); inherited; end; procedure TMRUList.LoadFromFile( const AFilename : string = '' ); var LStream : TStringStream; LRoot : TJSONArray; LItem : TRESTRequestParams; LFilename : string; i : integer; begin Clear; if (AFilename <> '') then LFilename:= AFilename else LFilename:= FFilename; if (LFilename = '') OR (NOT FileExists(LFilename)) then EXIT; LStream:= TStringStream.Create; TRY LStream.LoadFromFile( LFilename ); LRoot:= TJSONObject.ParseJSONValue( LStream.DataString ) AS TJSONArray; for i:= 0 to LRoot.Size-1 do begin LItem:= TRESTRequestParams.Create; LItem.FromJSONObject( LRoot.Get( i ) AS TJSONObject ); FItems.Add( LItem ); end; FINALLY FreeAndNIL( LStream ); END; LRoot:= TJSONArray.Create; TRY for LItem IN FItems do LRoot.Add( LItem.AsJSONObject ); FINALLY FreeAndNIL( LRoot ); END; end; function TMRUList.RemoveItem( const AURL : string ) : boolean; var LItem : TRESTRequestParams; begin result:= FALSE; for LItem IN FItems do begin if SameText(LItem.ToString, AURL) then begin FItems.Remove( LItem ); result:= TRUE; BREAK; end; end; if FAutoSave then SaveToFile; end; procedure TMRUList.SaveToFile( const AFilename : string = '' ); var LStream : TStringStream; LRoot : TJSONArray; LItem : TRESTRequestParams; LFilename : string; begin if (AFilename <> '') then LFilename:= AFilename else LFilename:= FFilename; if (LFilename = '') then EXIT; LRoot:= TJSONArray.Create; TRY for LItem IN FItems do LRoot.Add( LItem.AsJSONObject ); LStream:= TStringStream.Create( LRoot.ToString ); TRY LStream.SaveToFile( LFilename ); FINALLY FreeAndNIL( LStream ); END; FINALLY FreeAndNIL( LRoot ); END; end; end.
unit ZPI_Z01MsgUnit; interface uses bsHL7Object, ZINSegUnit, ZAUSegUnit, BSHL7DT251; type TBSZPI_Z01_251 = class(TBSHL7Message) private function GetIN1: TbsIN1_251; function GetMSH: TbsMSH_251; function GetPID: TbsPID_251; function GetPRD: TbsPRD_251; function GetZAU: TbsZAU_251; function GetZIN: TbsZIN_251; procedure SetIN1(const Value: TbsIN1_251); procedure SetMSH(const Value: TbsMSH_251); procedure SetPID(const Value: TbsPID_251); procedure SetPRD(const Value: TbsPRD_251); procedure SetZAU(const Value: TbsZAU_251); procedure SetZIN(const Value: TbsZIN_251); public procedure Init; override; property MSH : TbsMSH_251 read GetMSH write SetMSH; property ZAU : TbsZAU_251 read GetZAU write SetZAU; property PRD : TbsPRD_251 read GetPRD write SetPRD; property PID : TbsPID_251 read GetPID write SetPID; property IN1 : TbsIN1_251 read GetIN1 write SetIN1; property ZIN : TbsZIN_251 read GetZIN write SetZIN; end; implementation { TBSZPI_Z01_251 } function TBSZPI_Z01_251.GetIN1: TbsIN1_251; begin Result:=TbsIN1_251(GetOrCreateObject('IN1')); end; function TBSZPI_Z01_251.GetMSH: TbsMSH_251; begin Result:=TbsMSH_251(GetOrCreateObject('MSH')); end; function TBSZPI_Z01_251.GetPID: TbsPID_251; begin Result:=TbsPID_251(GetOrCreateObject('PID')); end; function TBSZPI_Z01_251.GetPRD: TbsPRD_251; begin Result:=TbsPRD_251(GetOrCreateObject('PRD')); end; function TBSZPI_Z01_251.GetZAU: TbsZAU_251; begin Result:=TbsZAU_251(GetOrCreateObject('ZAU')); end; function TBSZPI_Z01_251.GetZIN: TbsZIN_251; begin Result:=TbsZIN_251(GetOrCreateObject('ZIN')); end; procedure TBSZPI_Z01_251.Init; begin FTypeName:='ZPI_Z01'; FTypeVersion:='251'; FTypeVendor:='BESA'; inherited; end; procedure TBSZPI_Z01_251.SetIN1(const Value: TbsIN1_251); begin SetObject('IN1',Value); end; procedure TBSZPI_Z01_251.SetMSH(const Value: TbsMSH_251); begin SetObject('MSH',Value); end; procedure TBSZPI_Z01_251.SetPID(const Value: TbsPID_251); begin SetObject('PID',Value); end; procedure TBSZPI_Z01_251.SetPRD(const Value: TbsPRD_251); begin SetObject('PRD',Value); end; procedure TBSZPI_Z01_251.SetZAU(const Value: TbsZAU_251); begin SetObject('ZAU',Value); end; procedure TBSZPI_Z01_251.SetZIN(const Value: TbsZIN_251); begin SetObject('ZIN',Value); end; procedure InitZPI_Z01Message; var LDefinition : TBSHL7Definition; begin LDefinition := TBSHL7Definition.Create('ZPI_Z01','2.5.1','BESA','M'); BSHL7Library.AddType(LDefinition); LDefinition.Add('MSH','MSH',1,1); LDefinition.Add('MSA','MSA',0,1); LDefinition.Add('ZAU','ZAU',0,1,'BESA'); LDefinition.Add('PRD','PRD',0,1); LDefinition.Add('PID','PID',0,1); LDefinition.Add('IN1','IN1',0,1); LDefinition.Add('ZIN','ZIN',0,1,'BESA'); end; initialization InitZPI_Z01Message; end.
unit UIWhist; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,ExtCtrls,Generics.Collections, UGame, Ucard, UDeck, UPlayer; type TBoard = class(TForm) NextDeal: TButton; type TCardList = TObjectList<TCard>; const NORTHX = 100; NORTHY = 200; EASTX = 200; EASTY = 100; SOUTHX = 100; SOUTHY = 10; WESTX = 10; WESTY = 100; SPACING = 20; //increment bewtween cards on screen - controls overlap procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FGame: TGame; North, South, East, West: TPlayer; CardImages:TList<TImage>; procedure DrawCard(Card: TCard; x,y: integer); procedure NextDealClick(Sender: TObject); public procedure UpdateUI; end; var CardGameForm: TBoard; implementation {$R *.dfm} {$R CardImages.res} //resource file containing card images procedure TBoard.UpdateUI(); begin end; procedure TBoard.NextDealClick(Sender: TObject); var player, cardIndex, xPos, yPos: integer; begin FGame:= TGame.Create(4,13); for player := 0 to 3 do case player of //get appropriate xy co-ordinates 0: begin // for each player's hand xPos:= NORTHX; yPos:= NORTHY; end; 1: begin xPos:= EASTX ; yPos:= EASTY ; end; 2: begin xPos:= SOUTHX; yPos:= SOUTHY; end; 3: begin xPos:= WESTX; yPos:= WESTY; end; end; //show all players cards on screen for cardIndex := 0 to FGame.getPlayerCardsInHand(player)-1 do begin Drawcard (FGame.getPlayerCard(player, cardIndex),xPos+cardindex*SPACING, yPos); //show card on screen end; end; procedure TBoard.DrawCard(Card: TCard; x,y: integer); //draws Card at (x,y) var ResName: string; NewImage:TImage; begin NewImage:=TImage.Create(Self); //create image with form as owner CardImages.Add(NewImage); //add to list with NewImage do begin visible := false; //make it invisible until we have positioned it and loaded the bitmap parent := self; //set form as parent, responsible for displaying it top := y; //set y co-ordinate, relative to origin of parent left := x; //set x co-ordinate ResName := Card.TSuitToStr[1] + Card.RankToStr; //assign resource name based on suit and rank picture.Bitmap.LoadFromResourceName(HInstance, ResName); //load bitmap from resource visible := true; end; end; procedure TBoard.FormCreate(Sender: TObject); //create list of images begin CardImages:=TList<TImage>.Create; end; procedure TBoard.FormClose(Sender: TObject; var Action: TCloseAction); var i:integer; begin if CardImages.Count > 0 then for i := 0 to CardImages.Count-1 do CardImages.Free; end; end.
unit uCadastroTipoJuros; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, PngImageList, Vcl.ToolWin, Vcl.ExtCtrls, TipoJuros, TipoJurosRN; type TfrmCadastroTipoJuros = class(TForm) Panel1: TPanel; ToolBar1: TToolBar; PngImageList1: TPngImageList; btnVoltar: TToolButton; btnNovo: TToolButton; btnEditar: TToolButton; btnExcluir: TToolButton; btnGravar: TToolButton; btnCancelar: TToolButton; btnPesquisar: TToolButton; lblDescricao: TLabel; edtDescricao: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); procedure btnNovoClick(Sender: TObject); private bNovo, bAtualizar: boolean; public { Public declarations } idTipoJuros: Integer; procedure controleSHOW; procedure controleNOVOALTERAR; procedure controleGRAVAR; procedure controleCANCELAR; procedure controlePESQUISAR; procedure controleEXCLUIR; procedure setNovo; procedure setTipoJuros(var PTipoJuros: TTipoJuros); procedure setFonteNegrito(bNegrito: boolean); procedure excluir; procedure gravar; end; var frmCadastroTipoJuros: TfrmCadastroTipoJuros; TipojurosRn : TTipoJurosRn; tipoJuros : TTipoJuros; implementation {$R *.dfm} uses uPesquisaTipoJuros; procedure TfrmCadastroTipoJuros.btnCancelarClick(Sender: TObject); begin controleCANCELAR; end; procedure TfrmCadastroTipoJuros.btnEditarClick(Sender: TObject); begin bNovo := false; bAtualizar := true; controleNOVOALTERAR; end; procedure TfrmCadastroTipoJuros.btnExcluirClick(Sender: TObject); begin excluir; end; procedure TfrmCadastroTipoJuros.btnGravarClick(Sender: TObject); begin gravar; end; procedure TfrmCadastroTipoJuros.btnNovoClick(Sender: TObject); begin bNovo := true; bAtualizar := false; edtDescricao.Clear; controleNOVOALTERAR; end; procedure TfrmCadastroTipoJuros.btnPesquisarClick(Sender: TObject); begin if frmPesquisaTipoJuros = nil then begin frmPesquisaTipoJuros := TfrmPesquisaTipoJuros.Create(frmPesquisaTipoJuros); frmPesquisaTipoJuros.ShowModal; end; end; procedure TfrmCadastroTipoJuros.btnVoltarClick(Sender: TObject); begin close; end; procedure TfrmCadastroTipoJuros.controleCANCELAR; begin controleSHOW; bNovo := false; bAtualizar := false; setFonteNegrito(false); end; procedure TfrmCadastroTipoJuros.controleEXCLUIR; begin btnVoltar.Enabled := true; btnNovo.Enabled := true; btnEditar.Enabled := false; btnExcluir.Enabled := false; btnGravar.Enabled := false; btnCancelar.Enabled := false; btnPesquisar.Enabled := true; Panel1.Enabled := false; bNovo := false; bAtualizar := false; setFonteNegrito(false); end; procedure TfrmCadastroTipoJuros.controleGRAVAR; begin btnVoltar.Enabled := true; btnNovo.Enabled := true; btnEditar.Enabled := true; btnExcluir.Enabled := true; btnGravar.Enabled := false; btnCancelar.Enabled := true; btnPesquisar.Enabled := true; Panel1.Enabled := false; bNovo := false; bAtualizar := false; setFonteNegrito(true); end; procedure TfrmCadastroTipoJuros.controleNOVOALTERAR; begin btnVoltar.Enabled := false; btnNovo.Enabled := false; btnEditar.Enabled := false; btnExcluir.Enabled := false; btnGravar.Enabled := true; btnCancelar.Enabled := true; btnPesquisar.Enabled := false; Panel1.Enabled := true; if edtDescricao.CanFocus then edtDescricao.SetFocus; setFonteNegrito(false); end; procedure TfrmCadastroTipoJuros.controlePESQUISAR; begin btnVoltar.Enabled := true; btnNovo.Enabled := true; btnEditar.Enabled := true; btnExcluir.Enabled := true; btnGravar.Enabled := false; btnCancelar.Enabled := true; btnPesquisar.Enabled := true; Panel1.Enabled := false; if edtDescricao.CanFocus then edtDescricao.SetFocus; setFonteNegrito(false); end; procedure TfrmCadastroTipoJuros.controleSHOW; begin btnVoltar.Enabled := true; btnNovo.Enabled := true; btnPesquisar.Enabled := true; btnCancelar.Enabled := false; btnGravar.Enabled := false; btnExcluir.Enabled := false; btnEditar.Enabled := false; Panel1.Enabled := false; edtDescricao.Clear; end; procedure TfrmCadastroTipoJuros.excluir; begin try if TipoJurosRn.verificaExclusao(TipoJuros) then raise exception.Create('Não é possível excluir este ...um ou mais Tipo Juros(s) já estão sendo utilizados!!!'); if Application.MessageBox(PChar('Deseja realmente excluir?'), 'Confirmação', MB_ICONQUESTION+MB_YESNO) = mrYes then begin TipoJurosRn.excluir(TipoJuros); setNovo; controleEXCLUIR; end; except on E: Exception do begin Application.MessageBox(PChar(E.Message), 'Atenção', MB_ICONINFORMATION + MB_OK); end; end; end; procedure TfrmCadastroTipoJuros.FormClose(Sender: TObject; var Action: TCloseAction); begin try TipoJurosRn.Free; TipoJuros.Free; finally Action := caFree; frmCadastroTipoJuros := nil; end; end; procedure TfrmCadastroTipoJuros.FormCreate(Sender: TObject); begin TipojurosRn := TTipoJurosRn.Create; tipoJuros := TTipoJuros.Create; end; procedure TfrmCadastroTipoJuros.FormShow(Sender: TObject); begin controleSHOW(); end; procedure TfrmCadastroTipoJuros.gravar; begin try if edtDescricao.Text = '' then raise exception.Create('O campo Descricão é Obrigatório!'); Tipojuros.setDescricao(edtDescricao.Text); if bNovo then begin TipoJurosRn.incluir(TipoJuros); end; if bAtualizar then begin TipoJurosRn.editar(Tipojuros); end; controleGRAVAR; except on E: Exception do begin Application.MessageBox(PChar(E.Message), 'Atenção', MB_ICONINFORMATION + MB_OK); end; end; end; procedure TfrmCadastroTipoJuros.setFonteNegrito(bNegrito: boolean); begin if bNegrito then edtDescricao.Font.Style := [fsBold]; if not bNegrito then edtDescricao.Font.Style := []; end; procedure TfrmCadastroTipoJuros.setNovo; begin edtDescricao.Clear; end; procedure TfrmCadastroTipoJuros.setTipoJuros(var PTipoJuros: TTipoJuros); begin TipoJuros.setCodigo(PTipoJuros.getCodigo); TipoJuros.setDescricao(PTipoJuros.getDescricao); idTipoJuros := TipoJuros.getCodigo; edtDescricao.Text := TipoJuros.getDescricao; controlePESQUISAR; end; end.
{ Mystix Copyright (C) 2005 Piotr Jura This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You can contact with me by e-mail: pjura@o2.pl } unit uConfirmReplace; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TConfirmReplaceDialog = class(TForm) imgIcon: TImage; lblQuestion: TLabel; btnCancel: TButton; btnSkip: TButton; btnReplace: TButton; btnAll: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } function Execute(X, Y: Integer; ASearch, AReplace: String): TModalResult; end; var ConfirmReplaceDialog: TConfirmReplaceDialog; implementation uses uUtils, uMyIniFiles, uMain; {$R *.dfm} function TConfirmReplaceDialog.Execute(X, Y: Integer; ASearch, AReplace: String): TModalResult; begin Left := X; Top := Y; lblQuestion.Caption := Format(sStrings[siConfirmReplace], [ASearch, AReplace]); Result := ShowModal; end; procedure TConfirmReplaceDialog.FormCreate(Sender: TObject); begin imgIcon.Picture.Icon.Handle := LoadIcon(0, IDI_ASTERISK); end; procedure TConfirmReplaceDialog.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit SSLDemo.RandFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.NetEncoding, System.IOUtils; type TRandomFrame = class(TFrame) EditSize: TEdit; EditResult: TEdit; ButtonRandom: TButton; LabelSize: TLabel; procedure ButtonRandomClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses OpenSSL.RandUtils; {$R *.dfm} procedure TRandomFrame.ButtonRandomClick(Sender: TObject); var Buffer: TBytes; begin Buffer := TRandUtil.GetRandomBytes(StrToInt(EditSize.Text)); EditResult.Text := TNetEncoding.Base64.EncodeBytesToString(Buffer); end; end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit BoundSocketSvrImpl; interface {$MODE OBJFPC} {$H+} uses RunnableIntf, Sockets, SocketSvrImpl; type (*!----------------------------------------------- * bound socket server implementation which support graceful * shutdown when receive SIGTERM/SIGINT signal and also * allow for keeping client connection open if required * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TBoundSocketSvr = class(TSocketSvr) protected procedure bind(); override; procedure shutdown(); override; (*!----------------------------------------------- * begin listen socket *-----------------------------------------------*) procedure listen(); override; (*!----------------------------------------------- * accept connection *------------------------------------------------- * @param listenSocket, socket handle created with fpSocket() * @return client socket which data can be read *-----------------------------------------------*) function accept(listenSocket : longint) : longint; override; public function run() : IRunnable; override; end; implementation procedure TBoundSocketSvr.bind(); begin //socket already bound and listen //do nothing end; procedure TBoundSocketSvr.listen(); begin //socket already bound and listen //do nothing end; procedure TBoundSocketSvr.shutdown(); begin //do nothing end; (*!----------------------------------------------- * accept connection *------------------------------------------------- * @param listenSocket, socket handle created with fpSocket() * @return client socket which data can be read *-----------------------------------------------*) function TBoundSocketSvr.accept(listenSocket : longint) : longint; begin result := fpAccept(listenSocket, nil, nil); end; function TBoundSocketSvr.run() : IRunnable; begin //skip running bind() and listen() as our socket already bound and listened handleConnection(); result := self; end; end.
unit Common.Consts; interface const CONF_FILE_EXT = '.ini'; CONF_FILE_DB_SECTION = 'Database'; DB_USR = 'SYSDBA'; DB_PWD = 'masterkey'; DB_CHARSET = 'UTF8'; implementation end.
{ X/Y Scaling example... } TYPE Virtual = Array [1..64000] of byte; VirtPtr = ^Virtual; {$I ..\fdat.dat} { Font Data } CubeOBJ : array [0..3,0..1] of integer = ( (-1,-1), ( 1,-1), ( 1, 1), (-1, 1)); LineArr : array [0..3,0..1] of byte = ( (0,1),(1,2),(2,3),(3,0)); NumPoints : byte = 3; { -1 because of zero indexes } XWinMax = 320; XWinMin : word = 0; YWinMax = 180; YWinMin : word = 0; XMid : word = XWinMax div 2; YMid : word = YWinMax div 2; var Virscr : VirtPtr; bseg : word; zind : byte; d_Flag : boolean; de : real; Procedure _Malloc; BEGIN GetMem (VirScr,64000); bseg := seg (virscr^); {The segment for page 1} END; Procedure _MDealloc; BEGIN FreeMem (VirScr,64000); END; procedure PokeString(X, Y : word; InString : string; Size, Colour : byte; where : word); var i,offset,Index,XOrigin : word; YOrigin,index2,XIndex : word; oldcol : byte; begin XOrigin := X; XIndex := Xorigin; YOrigin := y; offset := 1; OldCol := Colour; for Index2 := 1 to length(InString) do begin { Is the character a lowercase letter??? } if (word(InString[Index2]) > 96) and (word(InString[Index2]) < 123) then { Lowercase - Uppercase } offset:=((word(InString[Index2])-65)*(FontWidth*FontHeight))+1 else { Otherwise leave them alone } offset:=((word(InString[Index2])-33)*(FontWidth*FontHeight))+1; { Poke 1 Character } if word(InString[Index2]) > 0 then begin for Index := offset to (offset+((FontWidth*FontHeight)-1)) do begin inc(x); if Fontdata[Index] <> 0 then for i:=1 to size do mem [where:x+((y+i)*320)]:=Fontdata[Index]+(Colour-1); if x > (Xorigin + (FontWidth-1)) then begin x:=XOrigin; inc(y,size); end; end; end; XIndex := Xorigin+(FontWidth+(2*size)); { Space between characters } Xorigin := XIndex; { Set the new X origin } x := XOrigin; { Reset new X for next character } y:= Yorigin; { And align the Y co-ord to keep them in line } colour:= oldcol; end; end; Procedure Putpixel (Where, x, y :word; Col : Byte); function between(num,hi,lo : word): boolean; begin if (num < hi) and (num > lo) then Between:=True else between:=False; end; BEGIN if (between(x,XWinMax,XWinMin) and between(y,YWinMax,YWinMin)) then Mem [Where:X+(Y*320)]:=Col; END; Procedure line(buff : word; x1, y1, x2, y2 : integer; col : byte); { Bresenham's Line Method } function sgn( a : real) : integer; begin if a>0 then sgn:=+1; if a<0 then sgn:=-1; if a=0 then sgn:=0; end; var u, s, v, d1x, d1y, d2x, d2y, m, n : real; i : integer; begin u:= x2 - x1; v:= y2 - y1; d1x:= SGN(u); d1y:= SGN(v); d2x:= SGN(u); d2y:= 0; m:= ABS(u); n := ABS(v); IF NOT (M>N) then BEGIN d2x := 0 ; d2y := SGN(v); m := ABS(v); n := ABS(u); END; s := INT(m / 2); FOR i := 0 TO round(m) DO BEGIN putpixel(buff,x1,y1,col); s := s + n; IF not (s<m) THEN BEGIN s := s - m; x1:= x1 + round(d1x); y1 := y1 + round(d1y); END ELSE BEGIN x1 := x1 + round(d2x); y1 := y1 + round(d2y); END; end; END; procedure VM(Mode : Word); Assembler; asm mov ax,Mode int 10h end; procedure DrawOBJ( ZoomIndex, col : byte; Buffer : word; deg : real); var lindex : word; ax, ay, bx, by : word; begin putpixel(Buffer,XMid,YMid,col); for lindex := 0 to NumPoints do begin ax := round(word((CubeOBJ[Linearr[Lindex,0],0]*zoomindex)+XMid)*cos(deg)); ay := round(word((CubeOBJ[linearr[Lindex,1],1]*zoomindex)+YMid)*sin(deg)); bx := round(word((CubeOBJ[Linearr[Lindex,0],1]*zoomindex)+XMid)*cos(deg)); by := round(word((CubeOBJ[linearr[Lindex,1],0]*zoomindex)+YMid)*sin(deg)); Line(buffer,ax,ay,bx,by,col); Line(buffer,XMid,YMid,bx,by,col); Line(buffer,bx,ay,XMid,YMid,col); end; end; function ESC : Byte; Assembler; asm in al,60h xor ah,ah end; procedure VidSync; Assembler; asm mov dx,3dah @@1000: in al,dx and al,8 jnz @@1000 @@2000: in al,dx and al,8 jz @@2000 end; procedure FLip16(source, dest : word); Assembler; asm push ds mov cx,32000 mov es,dest xor si,si mov di,si mov ds,source rep movsw pop ds end; function IntToStr(I: Longint): String; var S: string[11]; begin Str(I, S); IntToStr := S; end; Procedure CLRBuff( buf : word); Assembler; asm push es mov es, buf xor ax,ax mov cx,32000 xor di,di mov si,di rep stosw pop es end; begin d_Flag := false; zind := 165; de := 0; _Malloc; VM($13); asm mov ax,101bh { Set palette 256 greyscale } xor bx,bx mov cx,0ffh int 10h end; repeat CLRBuff(bseg); if D_Flag then begin inc(zind,3); if zind > 165 then D_Flag := False; end else begin dec(zind,3); if zind < 1 then D_Flag:=True; end; de:=de+0.01; DrawOBJ(Zind, 30, bseg,de); PokeString(0,185,'C',2,100,bseg); PokeString(6,188,'urrent zoom : '+inttostr(zind),1,100,bseg); Flip16(bseg,$0a000); VidSync; until ESC = 1 ; VM(3); _MDealloc; end.
unit InvoiceXML; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLINVOICEType = interface; IXMLHEADType = interface; IXMLPOSITIONType = interface; IXMLPOSITIONTypeList = interface; IXMLTAXType = interface; { IXMLINVOICEType } IXMLINVOICEType = interface(IXMLNode) ['{19D5DFF0-6CB5-4D37-A9A8-771EA5B441BD}'] { Property Accessors } function Get_DOCUMENTNAME: UnicodeString; function Get_NUMBER: UnicodeString; function Get_DATE: UnicodeString; function Get_DELIVERYDATE: UnicodeString; function Get_CURRENCY: UnicodeString; function Get_ORDERNUMBER: UnicodeString; function Get_ORDERDATE: UnicodeString; function Get_DELIVERYNOTENUMBER: UnicodeString; function Get_DELIVERYNOTEDATE: UnicodeString; function Get_GOODSTOTALAMOUNT: UnicodeString; function Get_POSITIONSAMOUNT: UnicodeString; function Get_VATSUM: UnicodeString; function Get_INVOICETOTALAMOUNT: UnicodeString; function Get_TAXABLEAMOUNT: UnicodeString; function Get_PAYMENTORDERNUMBER: UnicodeString; function Get_CAMPAIGNNUMBER: UnicodeString; function Get_MANAGER: UnicodeString; function Get_VAT: UnicodeString; function Get_HEAD: IXMLHEADType; procedure Set_DOCUMENTNAME(Value: UnicodeString); procedure Set_NUMBER(Value: UnicodeString); procedure Set_DATE(Value: UnicodeString); procedure Set_DELIVERYDATE(Value: UnicodeString); procedure Set_CURRENCY(Value: UnicodeString); procedure Set_ORDERNUMBER(Value: UnicodeString); procedure Set_ORDERDATE(Value: UnicodeString); procedure Set_DELIVERYNOTENUMBER(Value: UnicodeString); procedure Set_DELIVERYNOTEDATE(Value: UnicodeString); procedure Set_GOODSTOTALAMOUNT(Value: UnicodeString); procedure Set_POSITIONSAMOUNT(Value: UnicodeString); procedure Set_VATSUM(Value: UnicodeString); procedure Set_INVOICETOTALAMOUNT(Value: UnicodeString); procedure Set_TAXABLEAMOUNT(Value: UnicodeString); procedure Set_PAYMENTORDERNUMBER(Value: UnicodeString); procedure Set_CAMPAIGNNUMBER(Value: UnicodeString); procedure Set_MANAGER(Value: UnicodeString); procedure Set_VAT(Value: UnicodeString); { Methods & Properties } property DOCUMENTNAME: UnicodeString read Get_DOCUMENTNAME write Set_DOCUMENTNAME; property NUMBER: UnicodeString read Get_NUMBER write Set_NUMBER; property DATE: UnicodeString read Get_DATE write Set_DATE; property DELIVERYDATE: UnicodeString read Get_DELIVERYDATE write Set_DELIVERYDATE; property CURRENCY: UnicodeString read Get_CURRENCY write Set_CURRENCY; property ORDERNUMBER: UnicodeString read Get_ORDERNUMBER write Set_ORDERNUMBER; property ORDERDATE: UnicodeString read Get_ORDERDATE write Set_ORDERDATE; property DELIVERYNOTENUMBER: UnicodeString read Get_DELIVERYNOTENUMBER write Set_DELIVERYNOTENUMBER; property DELIVERYNOTEDATE: UnicodeString read Get_DELIVERYNOTEDATE write Set_DELIVERYNOTEDATE; property GOODSTOTALAMOUNT: UnicodeString read Get_GOODSTOTALAMOUNT write Set_GOODSTOTALAMOUNT; property POSITIONSAMOUNT: UnicodeString read Get_POSITIONSAMOUNT write Set_POSITIONSAMOUNT; property VATSUM: UnicodeString read Get_VATSUM write Set_VATSUM; property INVOICETOTALAMOUNT: UnicodeString read Get_INVOICETOTALAMOUNT write Set_INVOICETOTALAMOUNT; property TAXABLEAMOUNT: UnicodeString read Get_TAXABLEAMOUNT write Set_TAXABLEAMOUNT; property PAYMENTORDERNUMBER: UnicodeString read Get_PAYMENTORDERNUMBER write Set_PAYMENTORDERNUMBER; property CAMPAIGNNUMBER: UnicodeString read Get_CAMPAIGNNUMBER write Set_CAMPAIGNNUMBER; property MANAGER: UnicodeString read Get_MANAGER write Set_MANAGER; property VAT: UnicodeString read Get_VAT write Set_VAT; property HEAD: IXMLHEADType read Get_HEAD; end; { IXMLHEADType } IXMLHEADType = interface(IXMLNode) ['{C22ACC36-895D-4E99-B1B5-31430F893447}'] { Property Accessors } function Get_SUPPLIER: UnicodeString; function Get_BUYER: UnicodeString; function Get_DELIVERYPLACE: UnicodeString; function Get_SENDER: UnicodeString; function Get_RECIPIENT: UnicodeString; function Get_POSITION: IXMLPOSITIONTypeList; procedure Set_SUPPLIER(Value: UnicodeString); procedure Set_BUYER(Value: UnicodeString); procedure Set_DELIVERYPLACE(Value: UnicodeString); procedure Set_SENDER(Value: UnicodeString); procedure Set_RECIPIENT(Value: UnicodeString); { Methods & Properties } property SUPPLIER: UnicodeString read Get_SUPPLIER write Set_SUPPLIER; property BUYER: UnicodeString read Get_BUYER write Set_BUYER; property DELIVERYPLACE: UnicodeString read Get_DELIVERYPLACE write Set_DELIVERYPLACE; property SENDER: UnicodeString read Get_SENDER write Set_SENDER; property RECIPIENT: UnicodeString read Get_RECIPIENT write Set_RECIPIENT; property POSITION: IXMLPOSITIONTypeList read Get_POSITION; end; { IXMLPOSITIONType } IXMLPOSITIONType = interface(IXMLNode) ['{6D6E2A35-5997-4800-A197-245C12526045}'] { Property Accessors } function Get_POSITIONNUMBER: UnicodeString; function Get_PRODUCT: UnicodeString; function Get_PRODUCTIDBUYER: UnicodeString; function Get_INVOICEUNIT: UnicodeString; function Get_INVOICEDQUANTITY: UnicodeString; function Get_UNITPRICE: UnicodeString; function Get_PRICEWITHVAT: UnicodeString; function Get_GROSSPRICE: UnicodeString; function Get_AMOUNT: UnicodeString; function Get_DESCRIPTION: UnicodeString; function Get_AMOUNTTYPE: UnicodeString; function Get_TAX: IXMLTAXType; procedure Set_POSITIONNUMBER(Value: UnicodeString); procedure Set_PRODUCT(Value: UnicodeString); procedure Set_PRODUCTIDBUYER(Value: UnicodeString); procedure Set_INVOICEUNIT(Value: UnicodeString); procedure Set_INVOICEDQUANTITY(Value: UnicodeString); procedure Set_PRICEWITHVAT(Value: UnicodeString); procedure Set_GROSSPRICE(Value: UnicodeString); procedure Set_UNITPRICE(Value: UnicodeString); procedure Set_AMOUNT(Value: UnicodeString); procedure Set_DESCRIPTION(Value: UnicodeString); procedure Set_AMOUNTTYPE(Value: UnicodeString); { Methods & Properties } property POSITIONNUMBER: UnicodeString read Get_POSITIONNUMBER write Set_POSITIONNUMBER; property PRODUCT: UnicodeString read Get_PRODUCT write Set_PRODUCT; property PRODUCTIDBUYER: UnicodeString read Get_PRODUCTIDBUYER write Set_PRODUCTIDBUYER; property INVOICEUNIT: UnicodeString read Get_INVOICEUNIT write Set_INVOICEUNIT; property INVOICEDQUANTITY: UnicodeString read Get_INVOICEDQUANTITY write Set_INVOICEDQUANTITY; property UNITPRICE: UnicodeString read Get_UNITPRICE write Set_UNITPRICE; property PRICEWITHVAT: UnicodeString read Get_PRICEWITHVAT write Set_PRICEWITHVAT; property GROSSPRICE: UnicodeString read Get_GROSSPRICE write Set_GROSSPRICE; property AMOUNT: UnicodeString read Get_AMOUNT write Set_AMOUNT; property DESCRIPTION: UnicodeString read Get_DESCRIPTION write Set_DESCRIPTION; property AMOUNTTYPE: UnicodeString read Get_AMOUNTTYPE write Set_AMOUNTTYPE; property TAX: IXMLTAXType read Get_TAX; end; { IXMLPOSITIONTypeList } IXMLPOSITIONTypeList = interface(IXMLNodeCollection) ['{817C04E2-DFE2-4A4E-9200-31A7FB442247}'] { Methods & Properties } function Add: IXMLPOSITIONType; function Insert(const Index: Integer): IXMLPOSITIONType; function Get_Item(Index: Integer): IXMLPOSITIONType; property Items[Index: Integer]: IXMLPOSITIONType read Get_Item; default; end; { IXMLTAXType } IXMLTAXType = interface(IXMLNode) ['{5D7C545A-7320-48B1-A59F-1E55F18DA7B6}'] { Property Accessors } function Get_FUNCTION_: UnicodeString; function Get_TAXTYPECODE: UnicodeString; function Get_TAXRATE: UnicodeString; function Get_TAXAMOUNT: UnicodeString; function Get_CATEGORY: UnicodeString; procedure Set_FUNCTION_(Value: UnicodeString); procedure Set_TAXTYPECODE(Value: UnicodeString); procedure Set_TAXRATE(Value: UnicodeString); procedure Set_TAXAMOUNT(Value: UnicodeString); procedure Set_CATEGORY(Value: UnicodeString); { Methods & Properties } property FUNCTION_: UnicodeString read Get_FUNCTION_ write Set_FUNCTION_; property TAXTYPECODE: UnicodeString read Get_TAXTYPECODE write Set_TAXTYPECODE; property TAXRATE: UnicodeString read Get_TAXRATE write Set_TAXRATE; property TAXAMOUNT: UnicodeString read Get_TAXAMOUNT write Set_TAXAMOUNT; property CATEGORY: UnicodeString read Get_CATEGORY write Set_CATEGORY; end; { Forward Decls } TXMLINVOICEType = class; TXMLHEADType = class; TXMLPOSITIONType = class; TXMLPOSITIONTypeList = class; TXMLTAXType = class; { TXMLINVOICEType } TXMLINVOICEType = class(TXMLNode, IXMLINVOICEType) protected { IXMLINVOICEType } function Get_DOCUMENTNAME: UnicodeString; function Get_NUMBER: UnicodeString; function Get_DATE: UnicodeString; function Get_DELIVERYDATE: UnicodeString; function Get_CURRENCY: UnicodeString; function Get_ORDERNUMBER: UnicodeString; function Get_ORDERDATE: UnicodeString; function Get_DELIVERYNOTENUMBER: UnicodeString; function Get_DELIVERYNOTEDATE: UnicodeString; function Get_GOODSTOTALAMOUNT: UnicodeString; function Get_POSITIONSAMOUNT: UnicodeString; function Get_VATSUM: UnicodeString; function Get_INVOICETOTALAMOUNT: UnicodeString; function Get_TAXABLEAMOUNT: UnicodeString; function Get_PAYMENTORDERNUMBER: UnicodeString; function Get_CAMPAIGNNUMBER: UnicodeString; function Get_MANAGER: UnicodeString; function Get_VAT: UnicodeString; function Get_HEAD: IXMLHEADType; procedure Set_DOCUMENTNAME(Value: UnicodeString); procedure Set_NUMBER(Value: UnicodeString); procedure Set_DATE(Value: UnicodeString); procedure Set_DELIVERYDATE(Value: UnicodeString); procedure Set_CURRENCY(Value: UnicodeString); procedure Set_ORDERNUMBER(Value: UnicodeString); procedure Set_ORDERDATE(Value: UnicodeString); procedure Set_DELIVERYNOTENUMBER(Value: UnicodeString); procedure Set_DELIVERYNOTEDATE(Value: UnicodeString); procedure Set_GOODSTOTALAMOUNT(Value: UnicodeString); procedure Set_POSITIONSAMOUNT(Value: UnicodeString); procedure Set_VATSUM(Value: UnicodeString); procedure Set_INVOICETOTALAMOUNT(Value: UnicodeString); procedure Set_TAXABLEAMOUNT(Value: UnicodeString); procedure Set_PAYMENTORDERNUMBER(Value: UnicodeString); procedure Set_CAMPAIGNNUMBER(Value: UnicodeString); procedure Set_MANAGER(Value: UnicodeString); procedure Set_VAT(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLHEADType } TXMLHEADType = class(TXMLNode, IXMLHEADType) private FPOSITION: IXMLPOSITIONTypeList; protected { IXMLHEADType } function Get_SUPPLIER: UnicodeString; function Get_BUYER: UnicodeString; function Get_DELIVERYPLACE: UnicodeString; function Get_SENDER: UnicodeString; function Get_RECIPIENT: UnicodeString; function Get_POSITION: IXMLPOSITIONTypeList; procedure Set_SUPPLIER(Value: UnicodeString); procedure Set_BUYER(Value: UnicodeString); procedure Set_DELIVERYPLACE(Value: UnicodeString); procedure Set_SENDER(Value: UnicodeString); procedure Set_RECIPIENT(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLPOSITIONType } TXMLPOSITIONType = class(TXMLNode, IXMLPOSITIONType) protected { IXMLPOSITIONType } function Get_POSITIONNUMBER: UnicodeString; function Get_PRODUCT: UnicodeString; function Get_PRODUCTIDBUYER: UnicodeString; function Get_INVOICEUNIT: UnicodeString; function Get_INVOICEDQUANTITY: UnicodeString; function Get_UNITPRICE: UnicodeString; function Get_PRICEWITHVAT: UnicodeString; function Get_GROSSPRICE: UnicodeString; function Get_AMOUNT: UnicodeString; function Get_DESCRIPTION: UnicodeString; function Get_AMOUNTTYPE: UnicodeString; function Get_TAX: IXMLTAXType; procedure Set_POSITIONNUMBER(Value: UnicodeString); procedure Set_PRODUCT(Value: UnicodeString); procedure Set_PRODUCTIDBUYER(Value: UnicodeString); procedure Set_INVOICEUNIT(Value: UnicodeString); procedure Set_INVOICEDQUANTITY(Value: UnicodeString); procedure Set_UNITPRICE(Value: UnicodeString); procedure Set_PRICEWITHVAT(Value: UnicodeString); procedure Set_GROSSPRICE(Value: UnicodeString); procedure Set_AMOUNT(Value: UnicodeString); procedure Set_DESCRIPTION(Value: UnicodeString); procedure Set_AMOUNTTYPE(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLPOSITIONTypeList } TXMLPOSITIONTypeList = class(TXMLNodeCollection, IXMLPOSITIONTypeList) protected { IXMLPOSITIONTypeList } function Add: IXMLPOSITIONType; function Insert(const Index: Integer): IXMLPOSITIONType; function Get_Item(Index: Integer): IXMLPOSITIONType; end; { TXMLTAXType } TXMLTAXType = class(TXMLNode, IXMLTAXType) protected { IXMLTAXType } function Get_FUNCTION_: UnicodeString; function Get_TAXTYPECODE: UnicodeString; function Get_TAXRATE: UnicodeString; function Get_TAXAMOUNT: UnicodeString; function Get_CATEGORY: UnicodeString; procedure Set_FUNCTION_(Value: UnicodeString); procedure Set_TAXTYPECODE(Value: UnicodeString); procedure Set_TAXRATE(Value: UnicodeString); procedure Set_TAXAMOUNT(Value: UnicodeString); procedure Set_CATEGORY(Value: UnicodeString); end; { Global Functions } function GetINVOICE(Doc: IXMLDocument): IXMLINVOICEType; function LoadINVOICE(XMLString: string): IXMLINVOICEType; function NewINVOICE: IXMLINVOICEType; const TargetNamespace = ''; implementation { Global Functions } function GetINVOICE(Doc: IXMLDocument): IXMLINVOICEType; begin Result := Doc.GetDocBinding('INVOICE', TXMLINVOICEType, TargetNamespace) as IXMLINVOICEType; end; function LoadINVOICE(XMLString: string): IXMLINVOICEType; begin with NewXMLDocument do begin LoadFromXML(XMLString); Result := GetDocBinding('INVOICE', TXMLINVOICEType, TargetNamespace) as IXMLINVOICEType; end; end; function NewINVOICE: IXMLINVOICEType; begin Result := NewXMLDocument.GetDocBinding('INVOICE', TXMLINVOICEType, TargetNamespace) as IXMLINVOICEType; end; { TXMLINVOICEType } procedure TXMLINVOICEType.AfterConstruction; begin RegisterChildNode('HEAD', TXMLHEADType); inherited; end; function TXMLINVOICEType.Get_DOCUMENTNAME: UnicodeString; begin Result := ChildNodes['DOCUMENTNAME'].Text; end; procedure TXMLINVOICEType.Set_DOCUMENTNAME(Value: UnicodeString); begin ChildNodes['DOCUMENTNAME'].NodeValue := Value; end; function TXMLINVOICEType.Get_NUMBER: UnicodeString; begin Result := ChildNodes['NUMBER'].Text; end; procedure TXMLINVOICEType.Set_NUMBER(Value: UnicodeString); begin ChildNodes['NUMBER'].NodeValue := Value; end; function TXMLINVOICEType.Get_DATE: UnicodeString; begin Result := ChildNodes['DATE'].Text; end; procedure TXMLINVOICEType.Set_DATE(Value: UnicodeString); begin ChildNodes['DATE'].NodeValue := Value; end; function TXMLINVOICEType.Get_DELIVERYDATE: UnicodeString; begin Result := ChildNodes['DELIVERYDATE'].Text; end; procedure TXMLINVOICEType.Set_DELIVERYDATE(Value: UnicodeString); begin ChildNodes['DELIVERYDATE'].NodeValue := Value; end; function TXMLINVOICEType.Get_CURRENCY: UnicodeString; begin Result := ChildNodes['CURRENCY'].Text; end; procedure TXMLINVOICEType.Set_CURRENCY(Value: UnicodeString); begin ChildNodes['CURRENCY'].NodeValue := Value; end; function TXMLINVOICEType.Get_ORDERNUMBER: UnicodeString; begin Result := ChildNodes['ORDERNUMBER'].Text; end; procedure TXMLINVOICEType.Set_ORDERNUMBER(Value: UnicodeString); begin ChildNodes['ORDERNUMBER'].NodeValue := Value; end; function TXMLINVOICEType.Get_ORDERDATE: UnicodeString; begin Result := ChildNodes['ORDERDATE'].Text; end; procedure TXMLINVOICEType.Set_ORDERDATE(Value: UnicodeString); begin ChildNodes['ORDERDATE'].NodeValue := Value; end; function TXMLINVOICEType.Get_DELIVERYNOTENUMBER: UnicodeString; begin Result := ChildNodes['DELIVERYNOTENUMBER'].Text; end; procedure TXMLINVOICEType.Set_DELIVERYNOTENUMBER(Value: UnicodeString); begin ChildNodes['DELIVERYNOTENUMBER'].NodeValue := Value; end; function TXMLINVOICEType.Get_DELIVERYNOTEDATE: UnicodeString; begin Result := ChildNodes['DELIVERYNOTEDATE'].Text; end; procedure TXMLINVOICEType.Set_DELIVERYNOTEDATE(Value: UnicodeString); begin ChildNodes['DELIVERYNOTEDATE'].NodeValue := Value; end; function TXMLINVOICEType.Get_GOODSTOTALAMOUNT: UnicodeString; begin Result := ChildNodes['GOODSTOTALAMOUNT'].Text; end; procedure TXMLINVOICEType.Set_GOODSTOTALAMOUNT(Value: UnicodeString); begin ChildNodes['GOODSTOTALAMOUNT'].NodeValue := Value; end; function TXMLINVOICEType.Get_POSITIONSAMOUNT: UnicodeString; begin Result := ChildNodes['POSITIONSAMOUNT'].Text; end; procedure TXMLINVOICEType.Set_POSITIONSAMOUNT(Value: UnicodeString); begin ChildNodes['POSITIONSAMOUNT'].NodeValue := Value; end; function TXMLINVOICEType.Get_VATSUM: UnicodeString; begin Result := ChildNodes['VATSUM'].Text; end; procedure TXMLINVOICEType.Set_VATSUM(Value: UnicodeString); begin ChildNodes['VATSUM'].NodeValue := Value; end; function TXMLINVOICEType.Get_INVOICETOTALAMOUNT: UnicodeString; begin Result := ChildNodes['INVOICETOTALAMOUNT'].Text; end; procedure TXMLINVOICEType.Set_INVOICETOTALAMOUNT(Value: UnicodeString); begin ChildNodes['INVOICETOTALAMOUNT'].NodeValue := Value; end; function TXMLINVOICEType.Get_TAXABLEAMOUNT: UnicodeString; begin Result := ChildNodes['TAXABLEAMOUNT'].Text; end; procedure TXMLINVOICEType.Set_TAXABLEAMOUNT(Value: UnicodeString); begin ChildNodes['TAXABLEAMOUNT'].NodeValue := Value; end; function TXMLINVOICEType.Get_PAYMENTORDERNUMBER: UnicodeString; begin Result := ChildNodes['PAYMENTORDERNUMBER'].Text; end; procedure TXMLINVOICEType.Set_PAYMENTORDERNUMBER(Value: UnicodeString); begin ChildNodes['PAYMENTORDERNUMBER'].NodeValue := Value; end; function TXMLINVOICEType.Get_CAMPAIGNNUMBER: UnicodeString; begin Result := ChildNodes['CAMPAIGNNUMBER'].Text; end; procedure TXMLINVOICEType.Set_CAMPAIGNNUMBER(Value: UnicodeString); begin ChildNodes['CAMPAIGNNUMBER'].NodeValue := Value; end; function TXMLINVOICEType.Get_MANAGER: UnicodeString; begin Result := ChildNodes['MANAGER'].Text; end; procedure TXMLINVOICEType.Set_MANAGER(Value: UnicodeString); begin ChildNodes['MANAGER'].NodeValue := Value; end; function TXMLINVOICEType.Get_VAT: UnicodeString; begin Result := ChildNodes['VAT'].Text; end; procedure TXMLINVOICEType.Set_VAT(Value: UnicodeString); begin ChildNodes['VAT'].NodeValue := Value; end; function TXMLINVOICEType.Get_HEAD: IXMLHEADType; begin Result := ChildNodes['HEAD'] as IXMLHEADType; end; { TXMLHEADType } procedure TXMLHEADType.AfterConstruction; begin RegisterChildNode('POSITION', TXMLPOSITIONType); FPOSITION := CreateCollection(TXMLPOSITIONTypeList, IXMLPOSITIONType, 'POSITION') as IXMLPOSITIONTypeList; inherited; end; function TXMLHEADType.Get_SUPPLIER: UnicodeString; begin Result := ChildNodes['SUPPLIER'].Text; end; procedure TXMLHEADType.Set_SUPPLIER(Value: UnicodeString); begin ChildNodes['SUPPLIER'].NodeValue := Value; end; function TXMLHEADType.Get_BUYER: UnicodeString; begin Result := ChildNodes['BUYER'].Text; end; procedure TXMLHEADType.Set_BUYER(Value: UnicodeString); begin ChildNodes['BUYER'].NodeValue := Value; end; function TXMLHEADType.Get_DELIVERYPLACE: UnicodeString; begin Result := ChildNodes['DELIVERYPLACE'].Text; end; procedure TXMLHEADType.Set_DELIVERYPLACE(Value: UnicodeString); begin ChildNodes['DELIVERYPLACE'].NodeValue := Value; end; function TXMLHEADType.Get_SENDER: UnicodeString; begin Result := ChildNodes['SENDER'].Text; end; procedure TXMLHEADType.Set_SENDER(Value: UnicodeString); begin ChildNodes['SENDER'].NodeValue := Value; end; function TXMLHEADType.Get_RECIPIENT: UnicodeString; begin Result := ChildNodes['RECIPIENT'].Text; end; procedure TXMLHEADType.Set_RECIPIENT(Value: UnicodeString); begin ChildNodes['RECIPIENT'].NodeValue := Value; end; function TXMLHEADType.Get_POSITION: IXMLPOSITIONTypeList; begin Result := FPOSITION; end; { TXMLPOSITIONType } procedure TXMLPOSITIONType.AfterConstruction; begin RegisterChildNode('TAX', TXMLTAXType); inherited; end; function TXMLPOSITIONType.Get_POSITIONNUMBER: UnicodeString; begin Result := ChildNodes['POSITIONNUMBER'].Text; end; procedure TXMLPOSITIONType.Set_POSITIONNUMBER(Value: UnicodeString); begin ChildNodes['POSITIONNUMBER'].NodeValue := Value; end; function TXMLPOSITIONType.Get_PRODUCT: UnicodeString; begin Result := ChildNodes['PRODUCT'].Text; end; procedure TXMLPOSITIONType.Set_PRODUCT(Value: UnicodeString); begin ChildNodes['PRODUCT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_INVOICEUNIT: UnicodeString; begin Result := ChildNodes['INVOICEUNIT'].Text; end; procedure TXMLPOSITIONType.Set_INVOICEUNIT(Value: UnicodeString); begin ChildNodes['INVOICEUNIT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_PRODUCTIDBUYER: UnicodeString; begin Result := ChildNodes['PRODUCTIDBUYER'].Text; end; procedure TXMLPOSITIONType.Set_PRODUCTIDBUYER(Value: UnicodeString); begin ChildNodes['PRODUCTIDBUYER'].NodeValue := Value; end; function TXMLPOSITIONType.Get_INVOICEDQUANTITY: UnicodeString; begin Result := ChildNodes['INVOICEDQUANTITY'].Text; end; procedure TXMLPOSITIONType.Set_INVOICEDQUANTITY(Value: UnicodeString); begin ChildNodes['INVOICEDQUANTITY'].NodeValue := Value; end; function TXMLPOSITIONType.Get_UNITPRICE: UnicodeString; begin Result := ChildNodes['UNITPRICE'].Text; end; procedure TXMLPOSITIONType.Set_UNITPRICE(Value: UnicodeString); begin ChildNodes['UNITPRICE'].NodeValue := Value; end; function TXMLPOSITIONType.Get_PRICEWITHVAT: UnicodeString; begin Result := ChildNodes['PRICEWITHVAT'].Text; end; procedure TXMLPOSITIONType.Set_PRICEWITHVAT(Value: UnicodeString); begin ChildNodes['PRICEWITHVAT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_GROSSPRICE: UnicodeString; begin Result := ChildNodes['GROSSPRICE'].Text; end; procedure TXMLPOSITIONType.Set_GROSSPRICE(Value: UnicodeString); begin ChildNodes['GROSSPRICE'].NodeValue := Value; end; function TXMLPOSITIONType.Get_AMOUNT: UnicodeString; begin Result := ChildNodes['AMOUNT'].Text; end; procedure TXMLPOSITIONType.Set_AMOUNT(Value: UnicodeString); begin ChildNodes['AMOUNT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_DESCRIPTION: UnicodeString; begin Result := ChildNodes['DESCRIPTION'].Text; end; procedure TXMLPOSITIONType.Set_DESCRIPTION(Value: UnicodeString); begin ChildNodes['DESCRIPTION'].NodeValue := Value; end; function TXMLPOSITIONType.Get_AMOUNTTYPE: UnicodeString; begin Result := ChildNodes['AMOUNTTYPE'].Text; end; procedure TXMLPOSITIONType.Set_AMOUNTTYPE(Value: UnicodeString); begin ChildNodes['AMOUNTTYPE'].NodeValue := Value; end; function TXMLPOSITIONType.Get_TAX: IXMLTAXType; begin Result := ChildNodes['TAX'] as IXMLTAXType; end; { TXMLPOSITIONTypeList } function TXMLPOSITIONTypeList.Add: IXMLPOSITIONType; begin Result := AddItem(-1) as IXMLPOSITIONType; end; function TXMLPOSITIONTypeList.Insert(const Index: Integer): IXMLPOSITIONType; begin Result := AddItem(Index) as IXMLPOSITIONType; end; function TXMLPOSITIONTypeList.Get_Item(Index: Integer): IXMLPOSITIONType; begin Result := List[Index] as IXMLPOSITIONType; end; { TXMLTAXType } function TXMLTAXType.Get_FUNCTION_: UnicodeString; begin Result := ChildNodes['FUNCTION'].Text; end; procedure TXMLTAXType.Set_FUNCTION_(Value: UnicodeString); begin ChildNodes['FUNCTION'].NodeValue := Value; end; function TXMLTAXType.Get_TAXTYPECODE: UnicodeString; begin Result := ChildNodes['TAXTYPECODE'].Text; end; procedure TXMLTAXType.Set_TAXTYPECODE(Value: UnicodeString); begin ChildNodes['TAXTYPECODE'].NodeValue := Value; end; function TXMLTAXType.Get_TAXRATE: UnicodeString; begin Result := ChildNodes['TAXRATE'].Text; end; procedure TXMLTAXType.Set_TAXRATE(Value: UnicodeString); begin ChildNodes['TAXRATE'].NodeValue := Value; end; function TXMLTAXType.Get_TAXAMOUNT: UnicodeString; begin Result := ChildNodes['TAXAMOUNT'].Text; end; procedure TXMLTAXType.Set_TAXAMOUNT(Value: UnicodeString); begin ChildNodes['TAXAMOUNT'].NodeValue := Value; end; function TXMLTAXType.Get_CATEGORY: UnicodeString; begin Result := ChildNodes['CATEGORY'].Text; end; procedure TXMLTAXType.Set_CATEGORY(Value: UnicodeString); begin ChildNodes['CATEGORY'].NodeValue := Value; end; end.
unit PerformanceDiagnostics.VirtualMethodInterceptor; interface uses PerformanceDiagnostics.Interfaces, System.Rtti, System.Diagnostics, System.TimeSpan, System.SysUtils; type TMethodProxy = class(TVirtualMethodInterceptor, IMethodProxy) strict private private [Volatile] FRefCount: Integer; protected public class function New(_AObject: TObject): IMethodProxy; {Interface Implementation} function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; TMethodInterceptor = class(TInterfacedObject, IMethodInterceptor) strict private FProxy: IMethodProxy; private protected public constructor Create(_AObject: TObject; _ABefore: TInterceptBeforeNotify; _AAfter: TInterceptAfterNotify); class function New(_AObject: TObject; _ABefore: TInterceptBeforeNotify; _AAfter: TInterceptAfterNotify): IMethodInterceptor; end; implementation { TMethodInterceptor } constructor TMethodInterceptor.Create(_AObject: TObject; _ABefore: TInterceptBeforeNotify; _AAfter: TInterceptAfterNotify); begin FProxy := TMethodProxy.New(_AObject); TVirtualMethodInterceptor(FProxy).OnBefore := _ABefore; TVirtualMethodInterceptor(FProxy).OnAfter := _AAfter; TVirtualMethodInterceptor(FProxy).Proxify(_AObject); end; class function TMethodInterceptor.New(_AObject: TObject; _ABefore: TInterceptBeforeNotify; _AAfter: TInterceptAfterNotify): IMethodInterceptor; begin Result := TMethodInterceptor.Create(_AObject, _ABefore, _AAfter); end; { TMethodProxy } class function TMethodProxy.New(_AObject: TObject): IMethodProxy; begin Result := TMethodProxy.Create(_AObject.ClassType); end; function TMethodProxy.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TMethodProxy._AddRef: Integer; begin {$IFNDEF AUTOREFCOUNT} Result := AtomicIncrement(FRefCount); {$ELSE} Result := __ObjAddRef; {$ENDIF} end; function TMethodProxy._Release: Integer; begin {$IFNDEF AUTOREFCOUNT} Result := AtomicDecrement(FRefCount); if Result = 0 then Destroy; {$ELSE} Result := __ObjRelease; {$ENDIF} end; end.
unit Tools.Encryption; interface type Encryption = class public class function Encrypt(const Value: String): String; class function Decrypt(const Value: String): String; class function Md5(const Filename: String): String; end; implementation uses //IdHash, //IdHashMessageDigest, //System.Classes, System.SysUtils; const ENCRYPTION_KEY = 'BLASTWER'; { Encryption } class function Encryption.Decrypt(const Value: String): String; var Dest, Key: String; KeyLen, KeyPos, OffSet, SrcPos, SrcAsc, TmpSrcAsc: Integer; begin if (Value = EmptyStr) Then begin Result:= EmptyStr; Exit; end; Key := ENCRYPTION_KEY; Dest := ''; KeyLen := Length(Key); KeyPos := 0; OffSet := StrToInt('$' + copy(Value,1,2)); SrcPos := 3; repeat SrcAsc := StrToInt('$' + copy(Value,SrcPos,2)); if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1; TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]); if TmpSrcAsc <= OffSet then TmpSrcAsc := 255 + TmpSrcAsc - OffSet else TmpSrcAsc := TmpSrcAsc - OffSet; Dest := Dest + Chr(TmpSrcAsc); OffSet := SrcAsc; SrcPos := SrcPos + 2; until (SrcPos >= Length(Value)); Result:= Dest; end; class function Encryption.Encrypt(const Value: String): String; var Dest, Key: String; KeyLen, KeyPos, OffSet, Range, SrcPos, SrcAsc: Integer; begin if (Value = EmptyStr) Then begin Result:= EmptyStr; Exit; end; Key := ENCRYPTION_KEY; Dest := ''; KeyLen := Length(Key); KeyPos := 0; Range := 256; Randomize; OffSet := Random(Range); Dest := Format('%1.2x',[OffSet]); for SrcPos := 1 to Length(Value) do begin SrcAsc := (Ord(Value[SrcPos]) + OffSet) Mod 255; if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1; SrcAsc := SrcAsc Xor Ord(Key[KeyPos]); Dest := Dest + Format('%1.2x',[SrcAsc]); OffSet := SrcAsc; end; Result:= Dest; end; class function Encryption.Md5(const Filename: String): String; {var IdMD5: TIdHashMessageDigest5; Stream: TFileStream;} begin { IdMD5 := TIdHashMessageDigest5.Create; try Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); Result := IdMD5.HashStreamAsHex(Stream) finally FreeAndNil(Stream); FreeAndNil(IdMD5); end; } end; end.
unit Board; interface uses Simulation, Queen; const QueensCount = 5; type TBoard = class private class var Rows : array [0 .. QueensCount - 1] of Boolean; class var DiagsUp : array [0 .. 2 * QueensCount - 1] of Boolean; class var DiagsDown : array [0 .. 2 * QueensCount - 1] of Boolean; public class var Queens : array [0 .. QueensCount - 1] of TQueen; class function IsFree(Col, Row : Byte) : Boolean; class procedure MakeOccupied(Col, Row : Byte); class procedure MakeFree(Col, Row : Byte); class procedure Remember; end; implementation { TBoard } class function TBoard.IsFree(Col, Row: Byte): Boolean; begin Result := not Rows[Row] and not DiagsUp[Col + QueensCount - Row - 1] and not DiagsDown[Col + Row]; end; class procedure TBoard.MakeOccupied(Col, Row: Byte); begin Rows[Row] := True; DiagsUp[Col + QueensCount - Row - 1] := True; DiagsDown[Col + Row] := True; end; class procedure TBoard.MakeFree(Col, Row: Byte); begin Rows[Row] := False; DiagsUp[Col + QueensCount - Row - 1] := False; DiagsDown[Col + Row] := False; end; class procedure TBoard.Remember; var i : Integer; begin for i := 0 to QueensCount - 1 do Console.Write('{0} ', [Queens[i].Row]); Console.WriteLine; end; end.
{$I ..\Definition.Inc} unit WrapVclExtCtrls; interface uses Classes, SysUtils, PythonEngine, WrapDelphi, WrapDelphiClasses, WrapVclControls, Windows, ExtCtrls; type TPyDelphiShape = class (TPyDelphiGraphicControl) private function GetDelphiObject: TShape; procedure SetDelphiObject(const Value: TShape); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TShape read GetDelphiObject write SetDelphiObject; end; TPyDelphiPaintBox = class (TPyDelphiGraphicControl) private function GetDelphiObject: TPaintBox; procedure SetDelphiObject(const Value: TPaintBox); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TPaintBox read GetDelphiObject write SetDelphiObject; end; TPyDelphiImage = class (TPyDelphiGraphicControl) private function GetDelphiObject: TImage; procedure SetDelphiObject(const Value: TImage); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TImage read GetDelphiObject write SetDelphiObject; end; TPyDelphiBevel = class (TPyDelphiGraphicControl) private function GetDelphiObject: TBevel; procedure SetDelphiObject(const Value: TBevel); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TBevel read GetDelphiObject write SetDelphiObject; end; TPyDelphiTimer = class (TPyDelphiComponent) private function GetDelphiObject: TTimer; procedure SetDelphiObject(const Value: TTimer); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TTimer read GetDelphiObject write SetDelphiObject; end; TPyDelphiPanel = class (TPyDelphiWinControl) private function GetDelphiObject: TPanel; procedure SetDelphiObject(const Value: TPanel); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TPanel read GetDelphiObject write SetDelphiObject; end; TPyDelphiPage = class (TPyDelphiWinControl) private function GetDelphiObject: TPage; procedure SetDelphiObject(const Value: TPage); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TPage read GetDelphiObject write SetDelphiObject; end; TPyDelphiNotebook = class (TPyDelphiWinControl) private function GetDelphiObject: TNotebook; procedure SetDelphiObject(const Value: TNotebook); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TNotebook read GetDelphiObject write SetDelphiObject; end; {$IFNDEF FPC} TPyDelphiHeader = class (TPyDelphiWinControl) private function GetDelphiObject: THeader; procedure SetDelphiObject(const Value: THeader); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: THeader read GetDelphiObject write SetDelphiObject; end; {$ENDIF FPC} TPyDelphiRadioGroup = class (TPyDelphiWinControl) private function GetDelphiObject: TRadioGroup; procedure SetDelphiObject(const Value: TRadioGroup); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TRadioGroup read GetDelphiObject write SetDelphiObject; end; {$IFDEF FPC} TPyDelphiSplitter = class (TPyDelphiWinControl) {$ELSE FPC} TPyDelphiSplitter = class (TPyDelphiGraphicControl) {$ENDIF FPC} private function GetDelphiObject: TSplitter; procedure SetDelphiObject(const Value: TSplitter); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TSplitter read GetDelphiObject write SetDelphiObject; end; {$IFNDEF FPC} TPyDelphiControlBar = class (TPyDelphiWinControl) private function GetDelphiObject: TControlBar; procedure SetDelphiObject(const Value: TControlBar); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TControlBar read GetDelphiObject write SetDelphiObject; end; {$ENDIF FPC} TPyDelphiBoundLabel = class (TPyDelphiControl) private function GetDelphiObject: TBoundLabel; procedure SetDelphiObject(const Value: TBoundLabel); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TBoundLabel read GetDelphiObject write SetDelphiObject; end; TPyDelphiLabeledEdit = class (TPyDelphiWinControl) private function GetDelphiObject: TLabeledEdit; procedure SetDelphiObject(const Value: TLabeledEdit); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TLabeledEdit read GetDelphiObject write SetDelphiObject; end; {$IFNDEF FPC} TPyDelphiColorBox = class (TPyDelphiWinControl) private function GetDelphiObject: TColorBox; procedure SetDelphiObject(const Value: TColorBox); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TColorBox read GetDelphiObject write SetDelphiObject; end; {$ENDIF FPC} implementation { Register the wrappers, the globals and the constants } type TExtCtrlsRegistration = class(TRegisteredUnit) public function Name : string; override; procedure RegisterWrappers(APyDelphiWrapper : TPyDelphiWrapper); override; procedure DefineVars(APyDelphiWrapper : TPyDelphiWrapper); override; end; { TExtCtrlsRegistration } procedure TExtCtrlsRegistration.DefineVars(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; end; function TExtCtrlsRegistration.Name: string; begin Result := 'ExtCtrls'; end; procedure TExtCtrlsRegistration.RegisterWrappers(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiShape); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiPaintBox); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiImage); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiBevel); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiTimer); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiPanel); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiPage); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiNotebook); {$IFNDEF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiHeader); {$ENDIF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiRadioGroup); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiSplitter); {$IFNDEF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiControlBar); {$ENDIF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiBoundLabel); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiLabeledEdit); {$IFNDEF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiColorBox); {$ENDIF FPC} end; { TPyDelphiShape } class function TPyDelphiShape.DelphiObjectClass: TClass; begin Result := TShape; end; function TPyDelphiShape.GetDelphiObject: TShape; begin Result := TShape(inherited DelphiObject); end; procedure TPyDelphiShape.SetDelphiObject(const Value: TShape); begin inherited DelphiObject := Value; end; { TPyDelphiPaintBox } class function TPyDelphiPaintBox.DelphiObjectClass: TClass; begin Result := TPaintBox; end; function TPyDelphiPaintBox.GetDelphiObject: TPaintBox; begin Result := TPaintBox(inherited DelphiObject); end; procedure TPyDelphiPaintBox.SetDelphiObject(const Value: TPaintBox); begin inherited DelphiObject := Value; end; { TPyDelphiImage } class function TPyDelphiImage.DelphiObjectClass: TClass; begin Result := TImage; end; function TPyDelphiImage.GetDelphiObject: TImage; begin Result := TImage(inherited DelphiObject); end; procedure TPyDelphiImage.SetDelphiObject(const Value: TImage); begin inherited DelphiObject := Value; end; { TPyDelphiBevel } class function TPyDelphiBevel.DelphiObjectClass: TClass; begin Result := TBevel; end; function TPyDelphiBevel.GetDelphiObject: TBevel; begin Result := TBevel(inherited DelphiObject); end; procedure TPyDelphiBevel.SetDelphiObject(const Value: TBevel); begin inherited DelphiObject := Value; end; { TPyDelphiTimer } class function TPyDelphiTimer.DelphiObjectClass: TClass; begin Result := TTimer; end; function TPyDelphiTimer.GetDelphiObject: TTimer; begin Result := TTimer(inherited DelphiObject); end; procedure TPyDelphiTimer.SetDelphiObject(const Value: TTimer); begin inherited DelphiObject := Value; end; { TPyDelphiPanel } class function TPyDelphiPanel.DelphiObjectClass: TClass; begin Result := TPanel; end; function TPyDelphiPanel.GetDelphiObject: TPanel; begin Result := TPanel(inherited DelphiObject); end; procedure TPyDelphiPanel.SetDelphiObject(const Value: TPanel); begin inherited DelphiObject := Value; end; { TPyDelphiPage } class function TPyDelphiPage.DelphiObjectClass: TClass; begin Result := TPage; end; function TPyDelphiPage.GetDelphiObject: TPage; begin Result := TPage(inherited DelphiObject); end; procedure TPyDelphiPage.SetDelphiObject(const Value: TPage); begin inherited DelphiObject := Value; end; { TPyDelphiNotebook } class function TPyDelphiNotebook.DelphiObjectClass: TClass; begin Result := TNotebook; end; function TPyDelphiNotebook.GetDelphiObject: TNotebook; begin Result := TNotebook(inherited DelphiObject); end; procedure TPyDelphiNotebook.SetDelphiObject(const Value: TNotebook); begin inherited DelphiObject := Value; end; {$IFNDEF FPC} { TPyDelphiHeader } class function TPyDelphiHeader.DelphiObjectClass: TClass; begin Result := THeader; end; function TPyDelphiHeader.GetDelphiObject: THeader; begin Result := THeader(inherited DelphiObject); end; procedure TPyDelphiHeader.SetDelphiObject(const Value: THeader); begin inherited DelphiObject := Value; end; {$ENDIF FPC} { TPyDelphiRadioGroup } class function TPyDelphiRadioGroup.DelphiObjectClass: TClass; begin Result := TRadioGroup; end; function TPyDelphiRadioGroup.GetDelphiObject: TRadioGroup; begin Result := TRadioGroup(inherited DelphiObject); end; procedure TPyDelphiRadioGroup.SetDelphiObject(const Value: TRadioGroup); begin inherited DelphiObject := Value; end; { TPyDelphiSplitter } class function TPyDelphiSplitter.DelphiObjectClass: TClass; begin Result := TSplitter; end; function TPyDelphiSplitter.GetDelphiObject: TSplitter; begin Result := TSplitter(inherited DelphiObject); end; procedure TPyDelphiSplitter.SetDelphiObject(const Value: TSplitter); begin inherited DelphiObject := Value; end; {$IFNDEF FPC} { TPyDelphiControlBar } class function TPyDelphiControlBar.DelphiObjectClass: TClass; begin Result := TControlBar; end; function TPyDelphiControlBar.GetDelphiObject: TControlBar; begin Result := TControlBar(inherited DelphiObject); end; procedure TPyDelphiControlBar.SetDelphiObject(const Value: TControlBar); begin inherited DelphiObject := Value; end; {$ENDIF FPC} { TPyDelphiBoundLabel } class function TPyDelphiBoundLabel.DelphiObjectClass: TClass; begin Result := TBoundLabel; end; function TPyDelphiBoundLabel.GetDelphiObject: TBoundLabel; begin Result := TBoundLabel(inherited DelphiObject); end; procedure TPyDelphiBoundLabel.SetDelphiObject(const Value: TBoundLabel); begin inherited DelphiObject := Value; end; { TPyDelphiLabeledEdit } class function TPyDelphiLabeledEdit.DelphiObjectClass: TClass; begin Result := TLabeledEdit; end; function TPyDelphiLabeledEdit.GetDelphiObject: TLabeledEdit; begin Result := TLabeledEdit(inherited DelphiObject); end; procedure TPyDelphiLabeledEdit.SetDelphiObject(const Value: TLabeledEdit); begin inherited DelphiObject := Value; end; {$IFNDEF FPC} { TPyDelphiColorBox } class function TPyDelphiColorBox.DelphiObjectClass: TClass; begin Result := TColorBox; end; function TPyDelphiColorBox.GetDelphiObject: TColorBox; begin Result := TColorBox(inherited DelphiObject); end; procedure TPyDelphiColorBox.SetDelphiObject(const Value: TColorBox); begin inherited DelphiObject := Value; end; {$ENDIF FPC} initialization RegisteredUnits.Add( TExtCtrlsRegistration.Create ); {$IFDEF FPC} Classes.RegisterClasses([TShape, TPaintBox, TImage, TBevel, TTimer, TPanel, TPage, TNotebook, TRadioGroup, TSplitter, TBoundLabel, TLabeledEdit]); {$ELSE FPC} Classes.RegisterClasses([TShape, TPaintBox, TImage, TBevel, TTimer, TPanel, TPage, TNotebook, THeader, TRadioGroup, TSplitter, TControlBar, TBoundLabel, TLabeledEdit, TColorBox]); {$ENDIF FPC} end.
unit DIOTA.Dto.Request.CheckConsistencyRequest; interface uses System.Classes, REST.Client, System.JSON.Builders, DIOTA.IotaAPIClasses; type TCheckConsistencyRequest = class(TIotaAPIRequest) private FTails: TStrings; protected function GetCommand: String; override; function BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; override; public constructor Create(ARESTClient: TCustomRESTClient; ATimeout: Integer; ATails: TStrings); reintroduce; virtual; end; implementation { TCheckConsistencyRequest } constructor TCheckConsistencyRequest.Create(ARESTClient: TCustomRESTClient; ATimeout: Integer; ATails: TStrings); begin inherited Create(ARESTClient, ATimeout); FTails := ATails; end; function TCheckConsistencyRequest.GetCommand: String; begin Result := 'checkConsistency'; end; function TCheckConsistencyRequest.BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; var AElements: TJSONCollectionBuilder.TElements; ATail: String; begin if Assigned(FTails) then begin AElements := JsonBuilder.BeginArray('tails'); for ATail in FTails do AElements := AElements.Add(ATail); AElements.EndArray; end; Result := JsonBuilder; end; end.
{ ZIPDLL.PAS - Delphi v2 translation of file "wizzip.h" by Eric W. Engler } { Import Unit for ZIPDLL - put this into the "uses" clause of any other unit that wants to access the DLL. } { I changed this to use dynamic loading of the DLL in order to allow the user program to control when to load and unload the DLLs. Thanks to these people for sending me dynamic loading code: Ewart Nijburg, Nijsoft@Compuserve.com P.A. Gillioz, pag.aria@rhone.ch } unit ZIPDLL; interface uses Windows, Dialogs, ZCallBck; { This record is very critical. Any changes in the order of items, the size of items, or modifying the number of items, may have disasterous results. You have been warned! } Type ZipParms = packed record Handle: THandle; Caller: Pointer; { "self" referance of the Delphi form } { This is passed back to us in the callback function so we can direct the info to the proper form instance - thanks to Dennis Passmore for this idea. } Version: LongInt; { version of DLL we expect to see } ZCallbackFunc: ZFunctionPtrType; { type def in ZCallBck.PAS } fTraceEnabled: LongBool; {============== Begin Zip Flag section ============== } PZipPassword: PChar; { password pointer } fSuffix: LongBool; { not used yet } fEncrypt: LongBool; { Encrypt files to be added? } { include system and hidden files } fSystem: LongBool; { Include volume label } fVolume: LongBool; { Include extra file attributes (read-only, unix timestamps, etc) } fExtra: LongBool; { Do not add directory names to .ZIP archive } { see also: fJunkDir } fNoDirEntries: LongBool; { Only add files newer a specified date } { See the "Date" array below if you set this to TRUE } fDate: LongBool; { Give a little more information to the user via message boxes } fVerboseEnabled: LongBool; { Quiet operation - the DLL won't issue any messages at all. } { Delphi program MUST handle ALL errors via it's callback function. } fQuiet: LongBool; { Compression level (0 - 9; 9=max, 0=none) } { All of these levels are variations of deflate. } { I strongly recommend you use one of 3 values here: 0 = no compression, just store file 3 = "fast" compression 9 = "best" compression } fLevel: longint; { Try to compress files that appear to be already compressed based on their extension: .zip, .arc, .gif, ... } fComprSpecial: LongBool; { translate text file end-of-lines } fCRLF_LF: LongBool; { junk the directory names } { If true, this says not to save dirnames as separate entries, in addition to being save with filenames. } { see also: fNoDirEntries } fJunkDir: LongBool; { Recurse into subdirectories } fRecurse: LongBool; { Allow appending to a zip file } fGrow: LongBool; { Convert filenames to DOS 8x3 names - for compatibility with PKUNZIP v2.04g, which doesn't understand long filenames } fForce: LongBool; { Delete orig files that were added or updated in zip file } { This is a variation of Add } fMove: LongBool; { Delete specified files from zip file } fDeleteEntries: LongBool; { Update zip -- if true, rezip changed, and add new files in fspec } { This is a variation of Add } fUpdate: LongBool; { Freshen zip -- if true, rezip all changed files in fspec } { This is a variation of Add } fFreshen: LongBool; { junk the SFX prefix on the self-extracing .EXE archives } fJunkSFX: LongBool; { Set zip file time to time of newest file in it } fLatestTime: LongBool; {============== End Zip Flag section ============== } { Cutoff Date for Add-by-date; add files newer than this day } { This is only used if the "fDate" option is TRUE } { format = MMDDYY plus 2 trailing nulls } Date: Array[0..7] of Char; { Count of files to add or delete - don't forget to set this! } argc: LongInt; { ptr to name of zip file } PZipFN: PChar; seven: LongInt; { pass a 7 here to validate struct size } { Array of filenames contained in the ZIP archive } PFileNames: array[0..FilesMax] of PChar; end; type PZipParms = ^ZipParms; PWord = ^Word; ZipOpt = (ZipAdd, ZipDelete); { NOTE: Freshen, Update, and Move are only variations of Add } { Main call to execute a ZIP add or Delete. This call returns the number of files that were sucessfully operated on. } var ZipDllExec: function(ZipRec: PZipParms): DWORD; stdcall; var GetZipDllVersion: function : DWORD; stdcall; var ZipDllHandle: THandle; implementation end.